You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

222 lines
5.5 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package server
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "net"
  7. "strings"
  8. "sync"
  9. "github.com/tendermint/abci/types"
  10. cmn "github.com/tendermint/tmlibs/common"
  11. )
  12. // var maxNumberConnections = 2
  13. type SocketServer struct {
  14. cmn.BaseService
  15. proto string
  16. addr string
  17. listener net.Listener
  18. connsMtx sync.Mutex
  19. conns map[int]net.Conn
  20. nextConnID int
  21. appMtx sync.Mutex
  22. app types.Application
  23. }
  24. func NewSocketServer(protoAddr string, app types.Application) cmn.Service {
  25. parts := strings.SplitN(protoAddr, "://", 2)
  26. proto, addr := parts[0], parts[1]
  27. s := &SocketServer{
  28. proto: proto,
  29. addr: addr,
  30. listener: nil,
  31. app: app,
  32. conns: make(map[int]net.Conn),
  33. }
  34. s.BaseService = *cmn.NewBaseService(nil, "ABCIServer", s)
  35. return s
  36. }
  37. func (s *SocketServer) OnStart() error {
  38. s.BaseService.OnStart()
  39. ln, err := net.Listen(s.proto, s.addr)
  40. if err != nil {
  41. return err
  42. }
  43. s.listener = ln
  44. go s.acceptConnectionsRoutine()
  45. return nil
  46. }
  47. func (s *SocketServer) OnStop() {
  48. s.BaseService.OnStop()
  49. s.listener.Close()
  50. s.connsMtx.Lock()
  51. for id, conn := range s.conns {
  52. delete(s.conns, id)
  53. conn.Close()
  54. }
  55. s.connsMtx.Unlock()
  56. }
  57. func (s *SocketServer) addConn(conn net.Conn) int {
  58. s.connsMtx.Lock()
  59. defer s.connsMtx.Unlock()
  60. connID := s.nextConnID
  61. s.nextConnID++
  62. s.conns[connID] = conn
  63. return connID
  64. }
  65. // deletes conn even if close errs
  66. func (s *SocketServer) rmConn(connID int, conn net.Conn) error {
  67. s.connsMtx.Lock()
  68. defer s.connsMtx.Unlock()
  69. delete(s.conns, connID)
  70. return conn.Close()
  71. }
  72. func (s *SocketServer) acceptConnectionsRoutine() {
  73. // semaphore := make(chan struct{}, maxNumberConnections)
  74. for {
  75. // semaphore <- struct{}{}
  76. // Accept a connection
  77. s.Logger.Info("Waiting for new connection...")
  78. conn, err := s.listener.Accept()
  79. if err != nil {
  80. if !s.IsRunning() {
  81. return // Ignore error from listener closing.
  82. }
  83. s.Logger.Error("Failed to accept connection: " + err.Error())
  84. } else {
  85. s.Logger.Info("Accepted a new connection")
  86. }
  87. connID := s.addConn(conn)
  88. closeConn := make(chan error, 2) // Push to signal connection closed
  89. responses := make(chan *types.Response, 1000) // A channel to buffer responses
  90. // Read requests from conn and deal with them
  91. go s.handleRequests(closeConn, conn, responses)
  92. // Pull responses from 'responses' and write them to conn.
  93. go s.handleResponses(closeConn, responses, conn)
  94. go func() {
  95. // Wait until signal to close connection
  96. errClose := <-closeConn
  97. if err == io.EOF {
  98. s.Logger.Error("Connection was closed by client")
  99. } else if errClose != nil {
  100. s.Logger.Error("Connection error", "error", errClose)
  101. } else {
  102. // never happens
  103. s.Logger.Error("Connection was closed.")
  104. }
  105. // Close the connection
  106. err := s.rmConn(connID, conn)
  107. if err != nil {
  108. s.Logger.Error("Error in closing connection", "error", err)
  109. }
  110. // <-semaphore
  111. }()
  112. }
  113. }
  114. // Read requests from conn and deal with them
  115. func (s *SocketServer) handleRequests(closeConn chan error, conn net.Conn, responses chan<- *types.Response) {
  116. var count int
  117. var bufReader = bufio.NewReader(conn)
  118. for {
  119. var req = &types.Request{}
  120. err := types.ReadMessage(bufReader, req)
  121. if err != nil {
  122. if err == io.EOF {
  123. closeConn <- err
  124. } else {
  125. closeConn <- fmt.Errorf("Error reading message: %v", err.Error())
  126. }
  127. return
  128. }
  129. s.appMtx.Lock()
  130. count++
  131. s.handleRequest(req, responses)
  132. s.appMtx.Unlock()
  133. }
  134. }
  135. func (s *SocketServer) handleRequest(req *types.Request, responses chan<- *types.Response) {
  136. switch r := req.Value.(type) {
  137. case *types.Request_Echo:
  138. responses <- types.ToResponseEcho(r.Echo.Message)
  139. case *types.Request_Flush:
  140. responses <- types.ToResponseFlush()
  141. case *types.Request_Info:
  142. resInfo := s.app.Info()
  143. responses <- types.ToResponseInfo(resInfo)
  144. case *types.Request_SetOption:
  145. so := r.SetOption
  146. logStr := s.app.SetOption(so.Key, so.Value)
  147. responses <- types.ToResponseSetOption(logStr)
  148. case *types.Request_DeliverTx:
  149. res := s.app.DeliverTx(r.DeliverTx.Tx)
  150. responses <- types.ToResponseDeliverTx(res.Code, res.Data, res.Log)
  151. case *types.Request_CheckTx:
  152. res := s.app.CheckTx(r.CheckTx.Tx)
  153. responses <- types.ToResponseCheckTx(res.Code, res.Data, res.Log)
  154. case *types.Request_Commit:
  155. res := s.app.Commit()
  156. responses <- types.ToResponseCommit(res.Code, res.Data, res.Log)
  157. case *types.Request_Query:
  158. resQuery := s.app.Query(*r.Query)
  159. responses <- types.ToResponseQuery(resQuery)
  160. case *types.Request_InitChain:
  161. s.app.InitChain(r.InitChain.Validators)
  162. responses <- types.ToResponseInitChain()
  163. case *types.Request_BeginBlock:
  164. s.app.BeginBlock(r.BeginBlock.Hash, r.BeginBlock.Header)
  165. responses <- types.ToResponseBeginBlock()
  166. case *types.Request_EndBlock:
  167. resEndBlock := s.app.EndBlock(r.EndBlock.Height)
  168. responses <- types.ToResponseEndBlock(resEndBlock)
  169. default:
  170. responses <- types.ToResponseException("Unknown request")
  171. }
  172. }
  173. // Pull responses from 'responses' and write them to conn.
  174. func (s *SocketServer) handleResponses(closeConn chan error, responses <-chan *types.Response, conn net.Conn) {
  175. var count int
  176. var bufWriter = bufio.NewWriter(conn)
  177. for {
  178. var res = <-responses
  179. err := types.WriteMessage(res, bufWriter)
  180. if err != nil {
  181. closeConn <- fmt.Errorf("Error writing message: %v", err.Error())
  182. return
  183. }
  184. if _, ok := res.Value.(*types.Response_Flush); ok {
  185. err = bufWriter.Flush()
  186. if err != nil {
  187. closeConn <- fmt.Errorf("Error flushing write buffer: %v", err.Error())
  188. return
  189. }
  190. }
  191. count++
  192. }
  193. }