consumer.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. package sarama
  2. import (
  3. "fmt"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. )
  8. // ConsumerMessage encapsulates a Kafka message returned by the consumer.
  9. type ConsumerMessage struct {
  10. Key, Value []byte
  11. Topic string
  12. Partition int32
  13. Offset int64
  14. }
  15. // ConsumerError is what is provided to the user when an error occurs.
  16. // It wraps an error and includes the topic and partition.
  17. type ConsumerError struct {
  18. Topic string
  19. Partition int32
  20. Err error
  21. }
  22. func (ce ConsumerError) Error() string {
  23. return fmt.Sprintf("kafka: error while consuming %s/%d: %s", ce.Topic, ce.Partition, ce.Err)
  24. }
  25. // ConsumerErrors is a type that wraps a batch of errors and implements the Error interface.
  26. // It can be returned from the PartitionConsumer's Close methods to avoid the need to manually drain errors
  27. // when stopping.
  28. type ConsumerErrors []*ConsumerError
  29. func (ce ConsumerErrors) Error() string {
  30. return fmt.Sprintf("kafka: %d errors while consuming", len(ce))
  31. }
  32. // Consumer manages PartitionConsumers which process Kafka messages from brokers. You MUST call Close()
  33. // on a consumer to avoid leaks, it will not be garbage-collected automatically when it passes out of
  34. // scope.
  35. type Consumer interface {
  36. // Topics returns the set of available topics as retrieved from the cluster metadata.
  37. // This method is the same as Client.Topics(), and is provided for convenience.
  38. Topics() ([]string, error)
  39. // Partitions returns the sorted list of all partition IDs for the given topic.
  40. // This method is the same as Client.Pertitions(), and is provided for convenience.
  41. Partitions(topic string) ([]int32, error)
  42. // ConsumePartition creates a PartitionConsumer on the given topic/partition with the given offset. It will
  43. // return an error if this Consumer is already consuming on the given topic/partition. Offset can be a
  44. // literal offset, or OffsetNewest or OffsetOldest
  45. ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error)
  46. // Close shuts down the consumer. It must be called after all child PartitionConsumers have already been closed.
  47. Close() error
  48. }
  49. type consumer struct {
  50. client Client
  51. conf *Config
  52. ownClient bool
  53. lock sync.Mutex
  54. children map[string]map[int32]*partitionConsumer
  55. brokerConsumers map[*Broker]*brokerConsumer
  56. }
  57. // NewConsumer creates a new consumer using the given broker addresses and configuration.
  58. func NewConsumer(addrs []string, config *Config) (Consumer, error) {
  59. client, err := NewClient(addrs, config)
  60. if err != nil {
  61. return nil, err
  62. }
  63. c, err := NewConsumerFromClient(client)
  64. if err != nil {
  65. return nil, err
  66. }
  67. c.(*consumer).ownClient = true
  68. return c, nil
  69. }
  70. // NewConsumerFromClient creates a new consumer using the given client. It is still
  71. // necessary to call Close() on the underlying client when shutting down this consumer.
  72. func NewConsumerFromClient(client Client) (Consumer, error) {
  73. // Check that we are not dealing with a closed Client before processing any other arguments
  74. if client.Closed() {
  75. return nil, ErrClosedClient
  76. }
  77. c := &consumer{
  78. client: client,
  79. conf: client.Config(),
  80. children: make(map[string]map[int32]*partitionConsumer),
  81. brokerConsumers: make(map[*Broker]*brokerConsumer),
  82. }
  83. return c, nil
  84. }
  85. func (c *consumer) Close() error {
  86. if c.ownClient {
  87. return c.client.Close()
  88. }
  89. return nil
  90. }
  91. func (c *consumer) Topics() ([]string, error) {
  92. return c.client.Topics()
  93. }
  94. func (c *consumer) Partitions(topic string) ([]int32, error) {
  95. return c.client.Partitions(topic)
  96. }
  97. func (c *consumer) ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error) {
  98. child := &partitionConsumer{
  99. consumer: c,
  100. conf: c.conf,
  101. topic: topic,
  102. partition: partition,
  103. messages: make(chan *ConsumerMessage, c.conf.ChannelBufferSize),
  104. errors: make(chan *ConsumerError, c.conf.ChannelBufferSize),
  105. trigger: make(chan none, 1),
  106. dying: make(chan none),
  107. fetchSize: c.conf.Consumer.Fetch.Default,
  108. }
  109. if err := child.chooseStartingOffset(offset); err != nil {
  110. return nil, err
  111. }
  112. var leader *Broker
  113. var err error
  114. if leader, err = c.client.Leader(child.topic, child.partition); err != nil {
  115. return nil, err
  116. }
  117. if err := c.addChild(child); err != nil {
  118. return nil, err
  119. }
  120. go withRecover(child.dispatcher)
  121. child.broker = c.refBrokerConsumer(leader)
  122. child.broker.input <- child
  123. return child, nil
  124. }
  125. func (c *consumer) addChild(child *partitionConsumer) error {
  126. c.lock.Lock()
  127. defer c.lock.Unlock()
  128. topicChildren := c.children[child.topic]
  129. if topicChildren == nil {
  130. topicChildren = make(map[int32]*partitionConsumer)
  131. c.children[child.topic] = topicChildren
  132. }
  133. if topicChildren[child.partition] != nil {
  134. return ConfigurationError("That topic/partition is already being consumed")
  135. }
  136. topicChildren[child.partition] = child
  137. return nil
  138. }
  139. func (c *consumer) removeChild(child *partitionConsumer) {
  140. c.lock.Lock()
  141. defer c.lock.Unlock()
  142. delete(c.children[child.topic], child.partition)
  143. }
  144. func (c *consumer) refBrokerConsumer(broker *Broker) *brokerConsumer {
  145. c.lock.Lock()
  146. defer c.lock.Unlock()
  147. brokerWorker := c.brokerConsumers[broker]
  148. if brokerWorker == nil {
  149. brokerWorker = &brokerConsumer{
  150. consumer: c,
  151. broker: broker,
  152. input: make(chan *partitionConsumer),
  153. newSubscriptions: make(chan []*partitionConsumer),
  154. wait: make(chan none),
  155. subscriptions: make(map[*partitionConsumer]none),
  156. refs: 0,
  157. }
  158. go withRecover(brokerWorker.subscriptionManager)
  159. go withRecover(brokerWorker.subscriptionConsumer)
  160. c.brokerConsumers[broker] = brokerWorker
  161. }
  162. brokerWorker.refs++
  163. return brokerWorker
  164. }
  165. func (c *consumer) unrefBrokerConsumer(brokerWorker *brokerConsumer) {
  166. c.lock.Lock()
  167. defer c.lock.Unlock()
  168. brokerWorker.refs--
  169. if brokerWorker.refs == 0 {
  170. close(brokerWorker.input)
  171. if c.brokerConsumers[brokerWorker.broker] == brokerWorker {
  172. delete(c.brokerConsumers, brokerWorker.broker)
  173. }
  174. }
  175. }
  176. func (c *consumer) abandonBrokerConsumer(brokerWorker *brokerConsumer) {
  177. c.lock.Lock()
  178. defer c.lock.Unlock()
  179. delete(c.brokerConsumers, brokerWorker.broker)
  180. }
  181. // PartitionConsumer
  182. // PartitionConsumer processes Kafka messages from a given topic and partition. You MUST call Close()
  183. // or AsyncClose() on a PartitionConsumer to avoid leaks, it will not be garbage-collected automatically
  184. // when it passes out of scope.
  185. //
  186. // The simplest way of using a PartitionConsumer is to loop over its Messages channel using a for/range
  187. // loop. The PartitionConsumer will only stop itself in one case: when the offset being consumed is reported
  188. // as out of range by the brokers. In this case you should decide what you want to do (try a different offset,
  189. // notify a human, etc) and handle it appropriately. For all other error cases, it will just keep retrying.
  190. // By default, it logs these errors to sarama.Logger; if you want to be notified directly of all errors, set
  191. // your config's Consumer.Return.Errors to true and read from the Errors channel, using a select statement
  192. // or a separate goroutine. Check out the Consumer examples to see implementations of these different approaches.
  193. type PartitionConsumer interface {
  194. // AsyncClose initiates a shutdown of the PartitionConsumer. This method will return immediately,
  195. // after which you should wait until the 'messages' and 'errors' channel are drained.
  196. // It is required to call this function, or Close before a consumer object passes out of scope,
  197. // as it will otherwise leak memory. You must call this before calling Close on the underlying
  198. // client.
  199. AsyncClose()
  200. // Close stops the PartitionConsumer from fetching messages. It is required to call this function
  201. // (or AsyncClose) before a consumer object passes out of scope, as it will otherwise leak memory. You must
  202. // call this before calling Close on the underlying client.
  203. Close() error
  204. // Messages returns the read channel for the messages that are returned by the broker.
  205. Messages() <-chan *ConsumerMessage
  206. // Errors returns a read channel of errors that occured during consuming, if enabled. By default,
  207. // errors are logged and not returned over this channel. If you want to implement any custom errpr
  208. // handling, set your config's Consumer.Return.Errors setting to true, and read from this channel.
  209. Errors() <-chan *ConsumerError
  210. // HighWaterMarkOffset returns the high water mark offset of the partition, i.e. the offset that will
  211. // be used for the next message that will be produced. You can use this to determine how far behind
  212. // the processing is.
  213. HighWaterMarkOffset() int64
  214. }
  215. type partitionConsumer struct {
  216. consumer *consumer
  217. conf *Config
  218. topic string
  219. partition int32
  220. broker *brokerConsumer
  221. messages chan *ConsumerMessage
  222. errors chan *ConsumerError
  223. trigger, dying chan none
  224. fetchSize int32
  225. offset int64
  226. highWaterMarkOffset int64
  227. }
  228. func (child *partitionConsumer) sendError(err error) {
  229. cErr := &ConsumerError{
  230. Topic: child.topic,
  231. Partition: child.partition,
  232. Err: err,
  233. }
  234. if child.conf.Consumer.Return.Errors {
  235. child.errors <- cErr
  236. } else {
  237. Logger.Println(cErr)
  238. }
  239. }
  240. func (child *partitionConsumer) dispatcher() {
  241. for _ = range child.trigger {
  242. select {
  243. case <-child.dying:
  244. close(child.trigger)
  245. case <-time.After(child.conf.Consumer.Retry.Backoff):
  246. if child.broker != nil {
  247. child.consumer.unrefBrokerConsumer(child.broker)
  248. child.broker = nil
  249. }
  250. Logger.Printf("consumer/%s/%d finding new broker\n", child.topic, child.partition)
  251. if err := child.dispatch(); err != nil {
  252. child.sendError(err)
  253. child.trigger <- none{}
  254. }
  255. }
  256. }
  257. if child.broker != nil {
  258. child.consumer.unrefBrokerConsumer(child.broker)
  259. }
  260. child.consumer.removeChild(child)
  261. close(child.messages)
  262. close(child.errors)
  263. }
  264. func (child *partitionConsumer) dispatch() error {
  265. if err := child.consumer.client.RefreshMetadata(child.topic); err != nil {
  266. return err
  267. }
  268. var leader *Broker
  269. var err error
  270. if leader, err = child.consumer.client.Leader(child.topic, child.partition); err != nil {
  271. return err
  272. }
  273. child.broker = child.consumer.refBrokerConsumer(leader)
  274. child.broker.input <- child
  275. return nil
  276. }
  277. func (child *partitionConsumer) chooseStartingOffset(offset int64) error {
  278. newestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetNewest)
  279. if err != nil {
  280. return err
  281. }
  282. oldestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetOldest)
  283. if err != nil {
  284. return err
  285. }
  286. switch {
  287. case offset == OffsetNewest:
  288. child.offset = newestOffset
  289. case offset == OffsetOldest:
  290. child.offset = oldestOffset
  291. case offset >= oldestOffset && offset <= newestOffset:
  292. child.offset = offset
  293. default:
  294. return ErrOffsetOutOfRange
  295. }
  296. return nil
  297. }
  298. func (child *partitionConsumer) Messages() <-chan *ConsumerMessage {
  299. return child.messages
  300. }
  301. func (child *partitionConsumer) Errors() <-chan *ConsumerError {
  302. return child.errors
  303. }
  304. func (child *partitionConsumer) AsyncClose() {
  305. // this triggers whatever worker owns this child to abandon it and close its trigger channel, which causes
  306. // the dispatcher to exit its loop, which removes it from the consumer then closes its 'messages' and
  307. // 'errors' channel (alternatively, if the child is already at the dispatcher for some reason, that will
  308. // also just close itself)
  309. close(child.dying)
  310. }
  311. func (child *partitionConsumer) Close() error {
  312. child.AsyncClose()
  313. go withRecover(func() {
  314. for _ = range child.messages {
  315. // drain
  316. }
  317. })
  318. var errors ConsumerErrors
  319. for err := range child.errors {
  320. errors = append(errors, err)
  321. }
  322. if len(errors) > 0 {
  323. return errors
  324. }
  325. return nil
  326. }
  327. func (child *partitionConsumer) HighWaterMarkOffset() int64 {
  328. return atomic.LoadInt64(&child.highWaterMarkOffset)
  329. }
  330. func (child *partitionConsumer) handleResponse(response *FetchResponse) error {
  331. block := response.GetBlock(child.topic, child.partition)
  332. if block == nil {
  333. return ErrIncompleteResponse
  334. }
  335. if block.Err != ErrNoError {
  336. return block.Err
  337. }
  338. if len(block.MsgSet.Messages) == 0 {
  339. // We got no messages. If we got a trailing one then we need to ask for more data.
  340. // Otherwise we just poll again and wait for one to be produced...
  341. if block.MsgSet.PartialTrailingMessage {
  342. if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize == child.conf.Consumer.Fetch.Max {
  343. // we can't ask for more data, we've hit the configured limit
  344. child.sendError(ErrMessageTooLarge)
  345. child.offset++ // skip this one so we can keep processing future messages
  346. } else {
  347. child.fetchSize *= 2
  348. if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize > child.conf.Consumer.Fetch.Max {
  349. child.fetchSize = child.conf.Consumer.Fetch.Max
  350. }
  351. }
  352. }
  353. return nil
  354. }
  355. // we got messages, reset our fetch size in case it was increased for a previous request
  356. child.fetchSize = child.conf.Consumer.Fetch.Default
  357. atomic.StoreInt64(&child.highWaterMarkOffset, block.HighWaterMarkOffset)
  358. incomplete := false
  359. atLeastOne := false
  360. prelude := true
  361. for _, msgBlock := range block.MsgSet.Messages {
  362. for _, msg := range msgBlock.Messages() {
  363. if prelude && msg.Offset < child.offset {
  364. continue
  365. }
  366. prelude = false
  367. if msg.Offset >= child.offset {
  368. atLeastOne = true
  369. child.messages <- &ConsumerMessage{
  370. Topic: child.topic,
  371. Partition: child.partition,
  372. Key: msg.Msg.Key,
  373. Value: msg.Msg.Value,
  374. Offset: msg.Offset,
  375. }
  376. child.offset = msg.Offset + 1
  377. } else {
  378. incomplete = true
  379. }
  380. }
  381. }
  382. if incomplete || !atLeastOne {
  383. return ErrIncompleteResponse
  384. }
  385. return nil
  386. }
  387. // brokerConsumer
  388. type brokerConsumer struct {
  389. consumer *consumer
  390. broker *Broker
  391. input chan *partitionConsumer
  392. newSubscriptions chan []*partitionConsumer
  393. wait chan none
  394. subscriptions map[*partitionConsumer]none
  395. refs int
  396. }
  397. func (w *brokerConsumer) subscriptionManager() {
  398. var buffer []*partitionConsumer
  399. // The subscriptionManager constantly accepts new subscriptions on `input` (even when the main subscriptionConsumer
  400. // goroutine is in the middle of a network request) and batches it up. The main worker goroutine picks
  401. // up a batch of new subscriptions between every network request by reading from `newSubscriptions`, so we give
  402. // it nil if no new subscriptions are available. We also write to `wait` only when new subscriptions is available,
  403. // so the main goroutine can block waiting for work if it has none.
  404. for {
  405. if len(buffer) > 0 {
  406. select {
  407. case event, ok := <-w.input:
  408. if !ok {
  409. goto done
  410. }
  411. buffer = append(buffer, event)
  412. case w.newSubscriptions <- buffer:
  413. buffer = nil
  414. case w.wait <- none{}:
  415. }
  416. } else {
  417. select {
  418. case event, ok := <-w.input:
  419. if !ok {
  420. goto done
  421. }
  422. buffer = append(buffer, event)
  423. case w.newSubscriptions <- nil:
  424. }
  425. }
  426. }
  427. done:
  428. close(w.wait)
  429. if len(buffer) > 0 {
  430. w.newSubscriptions <- buffer
  431. }
  432. close(w.newSubscriptions)
  433. }
  434. func (w *brokerConsumer) subscriptionConsumer() {
  435. <-w.wait // wait for our first piece of work
  436. // the subscriptionConsumer ensures we will get nil right away if no new subscriptions is available
  437. for newSubscriptions := range w.newSubscriptions {
  438. w.updateSubscriptionCache(newSubscriptions)
  439. if len(w.subscriptions) == 0 {
  440. // We're about to be shut down or we're about to receive more subscriptions.
  441. // Either way, the signal just hasn't propagated to our goroutine yet.
  442. <-w.wait
  443. continue
  444. }
  445. response, err := w.fetchNewMessages()
  446. if err != nil {
  447. Logger.Printf("consumer/broker/%d disconnecting due to error processing FetchRequest: %s\n", w.broker.ID(), err)
  448. w.abort(err)
  449. return
  450. }
  451. for child := range w.subscriptions {
  452. if err := child.handleResponse(response); err != nil {
  453. switch err {
  454. case ErrOffsetOutOfRange:
  455. // there's no point in retrying this it will just fail the same way again
  456. // so shut it down and force the user to choose what to do
  457. child.AsyncClose()
  458. fallthrough
  459. default:
  460. child.sendError(err)
  461. fallthrough
  462. case ErrUnknownTopicOrPartition, ErrNotLeaderForPartition, ErrLeaderNotAvailable:
  463. // these three are not fatal errors, but do require redispatching
  464. child.trigger <- none{}
  465. delete(w.subscriptions, child)
  466. Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n", w.broker.ID(), child.topic, child.partition, err)
  467. }
  468. }
  469. }
  470. }
  471. }
  472. func (w *brokerConsumer) updateSubscriptionCache(newSubscriptions []*partitionConsumer) {
  473. // take new subscriptions, and abandon subscriptions that have been closed
  474. for _, child := range newSubscriptions {
  475. w.subscriptions[child] = none{}
  476. Logger.Printf("consumer/broker/%d added subscription to %s/%d\n", w.broker.ID(), child.topic, child.partition)
  477. }
  478. for child := range w.subscriptions {
  479. select {
  480. case <-child.dying:
  481. close(child.trigger)
  482. delete(w.subscriptions, child)
  483. Logger.Printf("consumer/broker/%d closed dead subscription to %s/%d\n", w.broker.ID(), child.topic, child.partition)
  484. default:
  485. }
  486. }
  487. }
  488. func (w *brokerConsumer) abort(err error) {
  489. w.consumer.abandonBrokerConsumer(w)
  490. _ = w.broker.Close() // we don't care about the error this might return, we already have one
  491. for child := range w.subscriptions {
  492. child.sendError(err)
  493. child.trigger <- none{}
  494. }
  495. for newSubscription := range w.newSubscriptions {
  496. for _, child := range newSubscription {
  497. child.sendError(err)
  498. child.trigger <- none{}
  499. }
  500. }
  501. }
  502. func (w *brokerConsumer) fetchNewMessages() (*FetchResponse, error) {
  503. request := &FetchRequest{
  504. MinBytes: w.consumer.conf.Consumer.Fetch.Min,
  505. MaxWaitTime: int32(w.consumer.conf.Consumer.MaxWaitTime / time.Millisecond),
  506. }
  507. for child := range w.subscriptions {
  508. request.AddBlock(child.topic, child.partition, child.offset, child.fetchSize)
  509. }
  510. return w.broker.Fetch(request)
  511. }