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.

254 lines
6.5 KiB

7 years ago
7 years ago
8 years ago
8 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
  1. package server
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "net"
  7. "os"
  8. "runtime"
  9. "github.com/tendermint/tendermint/abci/types"
  10. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  11. tmlog "github.com/tendermint/tendermint/libs/log"
  12. tmnet "github.com/tendermint/tendermint/libs/net"
  13. "github.com/tendermint/tendermint/libs/service"
  14. )
  15. // var maxNumberConnections = 2
  16. type SocketServer struct {
  17. service.BaseService
  18. isLoggerSet bool
  19. proto string
  20. addr string
  21. listener net.Listener
  22. connsMtx tmsync.Mutex
  23. conns map[int]net.Conn
  24. nextConnID int
  25. appMtx tmsync.Mutex
  26. app types.Application
  27. }
  28. func NewSocketServer(protoAddr string, app types.Application) service.Service {
  29. proto, addr := tmnet.ProtocolAndAddress(protoAddr)
  30. s := &SocketServer{
  31. proto: proto,
  32. addr: addr,
  33. listener: nil,
  34. app: app,
  35. conns: make(map[int]net.Conn),
  36. }
  37. s.BaseService = *service.NewBaseService(nil, "ABCIServer", s)
  38. return s
  39. }
  40. func (s *SocketServer) SetLogger(l tmlog.Logger) {
  41. s.BaseService.SetLogger(l)
  42. s.isLoggerSet = true
  43. }
  44. func (s *SocketServer) OnStart() error {
  45. ln, err := net.Listen(s.proto, s.addr)
  46. if err != nil {
  47. return err
  48. }
  49. s.listener = ln
  50. go s.acceptConnectionsRoutine()
  51. return nil
  52. }
  53. func (s *SocketServer) OnStop() {
  54. if err := s.listener.Close(); err != nil {
  55. s.Logger.Error("Error closing listener", "err", err)
  56. }
  57. s.connsMtx.Lock()
  58. defer s.connsMtx.Unlock()
  59. for id, conn := range s.conns {
  60. delete(s.conns, id)
  61. if err := conn.Close(); err != nil {
  62. s.Logger.Error("Error closing connection", "id", id, "conn", conn, "err", err)
  63. }
  64. }
  65. }
  66. func (s *SocketServer) addConn(conn net.Conn) int {
  67. s.connsMtx.Lock()
  68. defer s.connsMtx.Unlock()
  69. connID := s.nextConnID
  70. s.nextConnID++
  71. s.conns[connID] = conn
  72. return connID
  73. }
  74. // deletes conn even if close errs
  75. func (s *SocketServer) rmConn(connID int) error {
  76. s.connsMtx.Lock()
  77. defer s.connsMtx.Unlock()
  78. conn, ok := s.conns[connID]
  79. if !ok {
  80. return fmt.Errorf("connection %d does not exist", connID)
  81. }
  82. delete(s.conns, connID)
  83. return conn.Close()
  84. }
  85. func (s *SocketServer) acceptConnectionsRoutine() {
  86. for {
  87. // Accept a connection
  88. s.Logger.Info("Waiting for new connection...")
  89. conn, err := s.listener.Accept()
  90. if err != nil {
  91. if !s.IsRunning() {
  92. return // Ignore error from listener closing.
  93. }
  94. s.Logger.Error("Failed to accept connection", "err", err)
  95. continue
  96. }
  97. s.Logger.Info("Accepted a new connection")
  98. connID := s.addConn(conn)
  99. closeConn := make(chan error, 2) // Push to signal connection closed
  100. responses := make(chan *types.Response, 1000) // A channel to buffer responses
  101. // Read requests from conn and deal with them
  102. go s.handleRequests(closeConn, conn, responses)
  103. // Pull responses from 'responses' and write them to conn.
  104. go s.handleResponses(closeConn, conn, responses)
  105. // Wait until signal to close connection
  106. go s.waitForClose(closeConn, connID)
  107. }
  108. }
  109. func (s *SocketServer) waitForClose(closeConn chan error, connID int) {
  110. err := <-closeConn
  111. switch {
  112. case err == io.EOF:
  113. s.Logger.Error("Connection was closed by client")
  114. case err != nil:
  115. s.Logger.Error("Connection error", "err", err)
  116. default:
  117. // never happens
  118. s.Logger.Error("Connection was closed")
  119. }
  120. // Close the connection
  121. if err := s.rmConn(connID); err != nil {
  122. s.Logger.Error("Error closing connection", "err", err)
  123. }
  124. }
  125. // Read requests from conn and deal with them
  126. func (s *SocketServer) handleRequests(closeConn chan error, conn io.Reader, responses chan<- *types.Response) {
  127. var count int
  128. var bufReader = bufio.NewReader(conn)
  129. defer func() {
  130. // make sure to recover from any app-related panics to allow proper socket cleanup
  131. r := recover()
  132. if r != nil {
  133. const size = 64 << 10
  134. buf := make([]byte, size)
  135. buf = buf[:runtime.Stack(buf, false)]
  136. err := fmt.Errorf("recovered from panic: %v\n%s", r, buf)
  137. if !s.isLoggerSet {
  138. fmt.Fprintln(os.Stderr, err)
  139. }
  140. closeConn <- err
  141. s.appMtx.Unlock()
  142. }
  143. }()
  144. for {
  145. var req = &types.Request{}
  146. err := types.ReadMessage(bufReader, req)
  147. if err != nil {
  148. if err == io.EOF {
  149. closeConn <- err
  150. } else {
  151. closeConn <- fmt.Errorf("error reading message: %w", err)
  152. }
  153. return
  154. }
  155. s.appMtx.Lock()
  156. count++
  157. s.handleRequest(req, responses)
  158. s.appMtx.Unlock()
  159. }
  160. }
  161. func (s *SocketServer) handleRequest(req *types.Request, responses chan<- *types.Response) {
  162. switch r := req.Value.(type) {
  163. case *types.Request_Echo:
  164. responses <- types.ToResponseEcho(r.Echo.Message)
  165. case *types.Request_Flush:
  166. responses <- types.ToResponseFlush()
  167. case *types.Request_Info:
  168. res := s.app.Info(*r.Info)
  169. responses <- types.ToResponseInfo(res)
  170. case *types.Request_DeliverTx:
  171. res := s.app.DeliverTx(*r.DeliverTx)
  172. responses <- types.ToResponseDeliverTx(res)
  173. case *types.Request_CheckTx:
  174. res := s.app.CheckTx(*r.CheckTx)
  175. responses <- types.ToResponseCheckTx(res)
  176. case *types.Request_Commit:
  177. res := s.app.Commit()
  178. responses <- types.ToResponseCommit(res)
  179. case *types.Request_Query:
  180. res := s.app.Query(*r.Query)
  181. responses <- types.ToResponseQuery(res)
  182. case *types.Request_InitChain:
  183. res := s.app.InitChain(*r.InitChain)
  184. responses <- types.ToResponseInitChain(res)
  185. case *types.Request_BeginBlock:
  186. res := s.app.BeginBlock(*r.BeginBlock)
  187. responses <- types.ToResponseBeginBlock(res)
  188. case *types.Request_EndBlock:
  189. res := s.app.EndBlock(*r.EndBlock)
  190. responses <- types.ToResponseEndBlock(res)
  191. case *types.Request_ListSnapshots:
  192. res := s.app.ListSnapshots(*r.ListSnapshots)
  193. responses <- types.ToResponseListSnapshots(res)
  194. case *types.Request_OfferSnapshot:
  195. res := s.app.OfferSnapshot(*r.OfferSnapshot)
  196. responses <- types.ToResponseOfferSnapshot(res)
  197. case *types.Request_LoadSnapshotChunk:
  198. res := s.app.LoadSnapshotChunk(*r.LoadSnapshotChunk)
  199. responses <- types.ToResponseLoadSnapshotChunk(res)
  200. case *types.Request_ApplySnapshotChunk:
  201. res := s.app.ApplySnapshotChunk(*r.ApplySnapshotChunk)
  202. responses <- types.ToResponseApplySnapshotChunk(res)
  203. default:
  204. responses <- types.ToResponseException("Unknown request")
  205. }
  206. }
  207. // Pull responses from 'responses' and write them to conn.
  208. func (s *SocketServer) handleResponses(closeConn chan error, conn io.Writer, responses <-chan *types.Response) {
  209. bw := bufio.NewWriter(conn)
  210. for res := range responses {
  211. if err := types.WriteMessage(res, bw); err != nil {
  212. closeConn <- fmt.Errorf("error writing message: %w", err)
  213. return
  214. }
  215. if err := bw.Flush(); err != nil {
  216. closeConn <- fmt.Errorf("error flushing write buffer: %w", err)
  217. return
  218. }
  219. }
  220. }