mockbroker.go 9.3 KB

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