mockbroker.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package sarama
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. "io"
  7. "net"
  8. "reflect"
  9. "strconv"
  10. "sync"
  11. "time"
  12. "github.com/davecgh/go-spew/spew"
  13. )
  14. const (
  15. expectationTimeout = 500 * time.Millisecond
  16. )
  17. type requestHandlerFunc func(req *request) (res encoder)
  18. // MockBroker is a mock Kafka broker that is used in unit tests. It is exposed
  19. // to facilitate testing of higher level or specialized consumers and producers
  20. // built on top of Sarama. Note that it does not 'mimic' the Kafka API protocol,
  21. // but rather provides a facility to do that. It takes care of the TCP
  22. // transport, request unmarshaling, response marshaling, and makes it the test
  23. // writer responsibility to program correct according to the Kafka API protocol
  24. // MockBroker behaviour.
  25. //
  26. // MockBroker is implemented as a TCP server listening on a kernel-selected
  27. // localhost port that can accept many connections. It reads Kafka requests
  28. // from that connection and returns responses programmed by the SetHandlerByMap
  29. // function. If a MockBroker receives a request that it has no programmed
  30. // response for, then it returns nothing and the request times out.
  31. //
  32. // A set of MockRequest builders to define mappings used by MockBroker is
  33. // provided by Sarama. But users can develop MockRequests of their own and use
  34. // them along with or instead of the standard ones.
  35. //
  36. // When running tests with MockBroker it is strongly recommended to specify
  37. // a timeout to `go test` so that if the broker hangs waiting for a response,
  38. // the test panics.
  39. //
  40. // It is not necessary to prefix message length or correlation ID to your
  41. // response bytes, the server does that automatically as a convenience.
  42. type MockBroker struct {
  43. brokerID int32
  44. port int32
  45. closing chan none
  46. stopper chan none
  47. expectations chan encoder
  48. listener net.Listener
  49. t TestReporter
  50. latency time.Duration
  51. handler requestHandlerFunc
  52. history []RequestResponse
  53. lock sync.Mutex
  54. }
  55. // RequestResponse represents a Request/Response pair processed by MockBroker.
  56. type RequestResponse struct {
  57. Request protocolBody
  58. Response encoder
  59. }
  60. // SetLatency makes broker pause for the specified period every time before
  61. // replying.
  62. func (b *MockBroker) SetLatency(latency time.Duration) {
  63. b.latency = latency
  64. }
  65. // SetHandlerByMap defines mapping of Request types to MockResponses. When a
  66. // request is received by the broker, it looks up the request type in the map
  67. // and uses the found MockResponse instance to generate an appropriate reply.
  68. // If the request type is not found in the map then nothing is sent.
  69. func (b *MockBroker) SetHandlerByMap(handlerMap map[string]MockResponse) {
  70. b.setHandler(func(req *request) (res encoder) {
  71. reqTypeName := reflect.TypeOf(req.body).Elem().Name()
  72. mockResponse := handlerMap[reqTypeName]
  73. if mockResponse == nil {
  74. return nil
  75. }
  76. return mockResponse.For(req.body)
  77. })
  78. }
  79. // BrokerID returns broker ID assigned to the broker.
  80. func (b *MockBroker) BrokerID() int32 {
  81. return b.brokerID
  82. }
  83. // History returns a slice of RequestResponse pairs in the order they were
  84. // processed by the broker. Note that in case of multiple connections to the
  85. // broker the order expected by a test can be different from the order recorded
  86. // in the history, unless some synchronization is implemented in the test.
  87. func (b *MockBroker) History() []RequestResponse {
  88. b.lock.Lock()
  89. history := make([]RequestResponse, len(b.history))
  90. copy(history, b.history)
  91. b.lock.Unlock()
  92. return history
  93. }
  94. // Port returns the TCP port number the broker is listening for requests on.
  95. func (b *MockBroker) Port() int32 {
  96. return b.port
  97. }
  98. // Addr returns the broker connection string in the form "<address>:<port>".
  99. func (b *MockBroker) Addr() string {
  100. return b.listener.Addr().String()
  101. }
  102. // Close terminates the broker blocking until it stops internal goroutines and
  103. // releases all resources.
  104. func (b *MockBroker) Close() {
  105. close(b.expectations)
  106. if len(b.expectations) > 0 {
  107. buf := bytes.NewBufferString(fmt.Sprintf("mockbroker/%d: not all expectations were satisfied! Still waiting on:\n", b.BrokerID()))
  108. for e := range b.expectations {
  109. _, _ = buf.WriteString(spew.Sdump(e))
  110. }
  111. b.t.Error(buf.String())
  112. }
  113. close(b.closing)
  114. <-b.stopper
  115. }
  116. // setHandler sets the specified function as the request handler. Whenever
  117. // a mock broker reads a request from the wire it passes the request to the
  118. // function and sends back whatever the handler function returns.
  119. func (b *MockBroker) setHandler(handler requestHandlerFunc) {
  120. b.lock.Lock()
  121. b.handler = handler
  122. b.lock.Unlock()
  123. }
  124. func (b *MockBroker) serverLoop() {
  125. defer close(b.stopper)
  126. var err error
  127. var conn net.Conn
  128. go func() {
  129. <-b.closing
  130. err := b.listener.Close()
  131. if err != nil {
  132. b.t.Error(err)
  133. }
  134. }()
  135. wg := &sync.WaitGroup{}
  136. i := 0
  137. for conn, err = b.listener.Accept(); err == nil; conn, err = b.listener.Accept() {
  138. wg.Add(1)
  139. go b.handleRequests(conn, i, wg)
  140. i++
  141. }
  142. wg.Wait()
  143. Logger.Printf("*** mockbroker/%d: listener closed, err=%v", b.BrokerID(), err)
  144. }
  145. func (b *MockBroker) handleRequests(conn net.Conn, idx int, wg *sync.WaitGroup) {
  146. defer wg.Done()
  147. defer func() {
  148. _ = conn.Close()
  149. }()
  150. Logger.Printf("*** mockbroker/%d/%d: connection opened", b.BrokerID(), idx)
  151. var err error
  152. abort := make(chan none)
  153. defer close(abort)
  154. go func() {
  155. select {
  156. case <-b.closing:
  157. _ = conn.Close()
  158. case <-abort:
  159. }
  160. }()
  161. resHeader := make([]byte, 8)
  162. for {
  163. req, err := decodeRequest(conn)
  164. if err != nil {
  165. Logger.Printf("*** mockbroker/%d/%d: invalid request: err=%+v, %+v", b.brokerID, idx, err, spew.Sdump(req))
  166. b.serverError(err)
  167. break
  168. }
  169. if b.latency > 0 {
  170. time.Sleep(b.latency)
  171. }
  172. b.lock.Lock()
  173. res := b.handler(req)
  174. b.history = append(b.history, RequestResponse{req.body, res})
  175. b.lock.Unlock()
  176. if res == nil {
  177. Logger.Printf("*** mockbroker/%d/%d: ignored %v", b.brokerID, idx, spew.Sdump(req))
  178. continue
  179. }
  180. Logger.Printf("*** mockbroker/%d/%d: served %v -> %v", b.brokerID, idx, req, res)
  181. encodedRes, err := encode(res)
  182. if err != nil {
  183. b.serverError(err)
  184. break
  185. }
  186. if len(encodedRes) == 0 {
  187. continue
  188. }
  189. binary.BigEndian.PutUint32(resHeader, uint32(len(encodedRes)+4))
  190. binary.BigEndian.PutUint32(resHeader[4:], uint32(req.correlationID))
  191. if _, err = conn.Write(resHeader); err != nil {
  192. b.serverError(err)
  193. break
  194. }
  195. if _, err = conn.Write(encodedRes); err != nil {
  196. b.serverError(err)
  197. break
  198. }
  199. }
  200. Logger.Printf("*** mockbroker/%d/%d: connection closed, err=%v", b.BrokerID(), idx, err)
  201. }
  202. func (b *MockBroker) defaultRequestHandler(req *request) (res encoder) {
  203. select {
  204. case res, ok := <-b.expectations:
  205. if !ok {
  206. return nil
  207. }
  208. return res
  209. case <-time.After(expectationTimeout):
  210. return nil
  211. }
  212. }
  213. func (b *MockBroker) serverError(err error) {
  214. isConnectionClosedError := false
  215. if _, ok := err.(*net.OpError); ok {
  216. isConnectionClosedError = true
  217. } else if err == io.EOF {
  218. isConnectionClosedError = true
  219. } else if err.Error() == "use of closed network connection" {
  220. isConnectionClosedError = true
  221. }
  222. if isConnectionClosedError {
  223. return
  224. }
  225. b.t.Errorf(err.Error())
  226. }
  227. // NewMockBroker launches a fake Kafka broker. It takes a TestReporter as provided by the
  228. // test framework and a channel of responses to use. If an error occurs it is
  229. // simply logged to the TestReporter and the broker exits.
  230. func NewMockBroker(t TestReporter, brokerID int32) *MockBroker {
  231. return NewMockBrokerAddr(t, brokerID, "localhost:0")
  232. }
  233. // NewMockBrokerAddr behaves like newMockBroker but listens on the address you give
  234. // it rather than just some ephemeral port.
  235. func NewMockBrokerAddr(t TestReporter, brokerID int32, addr string) *MockBroker {
  236. var err error
  237. broker := &MockBroker{
  238. closing: make(chan none),
  239. stopper: make(chan none),
  240. t: t,
  241. brokerID: brokerID,
  242. expectations: make(chan encoder, 512),
  243. }
  244. broker.handler = broker.defaultRequestHandler
  245. broker.listener, err = net.Listen("tcp", addr)
  246. if err != nil {
  247. t.Fatal(err)
  248. }
  249. Logger.Printf("*** mockbroker/%d listening on %s\n", brokerID, broker.listener.Addr().String())
  250. _, portStr, err := net.SplitHostPort(broker.listener.Addr().String())
  251. if err != nil {
  252. t.Fatal(err)
  253. }
  254. tmp, err := strconv.ParseInt(portStr, 10, 32)
  255. if err != nil {
  256. t.Fatal(err)
  257. }
  258. broker.port = int32(tmp)
  259. go broker.serverLoop()
  260. return broker
  261. }
  262. func (b *MockBroker) Returns(e encoder) {
  263. b.expectations <- e
  264. }