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.

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