consumer.go 20 KB

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