consumer.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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. Timestamp time.Time // only set if kafka is version 0.10+, inner message timestamp
  16. BlockTimestamp time.Time // only set if kafka is version 0.10+, outer (compressed) block timestamp
  17. Headers []*RecordHeader // only set if kafka is version 0.11+
  18. }
  19. // ConsumerError is what is provided to the user when an error occurs.
  20. // It wraps an error and includes the topic and partition.
  21. type ConsumerError struct {
  22. Topic string
  23. Partition int32
  24. Err error
  25. }
  26. func (ce ConsumerError) Error() string {
  27. return fmt.Sprintf("kafka: error while consuming %s/%d: %s", ce.Topic, ce.Partition, ce.Err)
  28. }
  29. // ConsumerErrors is a type that wraps a batch of errors and implements the Error interface.
  30. // It can be returned from the PartitionConsumer's Close methods to avoid the need to manually drain errors
  31. // when stopping.
  32. type ConsumerErrors []*ConsumerError
  33. func (ce ConsumerErrors) Error() string {
  34. return fmt.Sprintf("kafka: %d errors while consuming", len(ce))
  35. }
  36. // Consumer manages PartitionConsumers which process Kafka messages from brokers. You MUST call Close()
  37. // on a consumer to avoid leaks, it will not be garbage-collected automatically when it passes out of
  38. // scope.
  39. //
  40. // Sarama's Consumer type does not currently support automatic consumer-group rebalancing and offset tracking.
  41. // For Zookeeper-based tracking (Kafka 0.8.2 and earlier), the https://github.com/wvanbergen/kafka library
  42. // builds on Sarama to add this support. For Kafka-based tracking (Kafka 0.9 and later), the
  43. // https://github.com/bsm/sarama-cluster library builds on Sarama to add this support.
  44. type Consumer interface {
  45. // Topics returns the set of available topics as retrieved from the cluster
  46. // metadata. This method is the same as Client.Topics(), and is provided for
  47. // convenience.
  48. Topics() ([]string, error)
  49. // Partitions returns the sorted list of all partition IDs for the given topic.
  50. // This method is the same as Client.Partitions(), and is provided for convenience.
  51. Partitions(topic string) ([]int32, error)
  52. // ConsumePartition creates a PartitionConsumer on the given topic/partition with
  53. // the given offset. It will return an error if this Consumer is already consuming
  54. // on the given topic/partition. Offset can be a literal offset, or OffsetNewest
  55. // or OffsetOldest
  56. ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error)
  57. // HighWaterMarks returns the current high water marks for each topic and partition.
  58. // Consistency between partitions is not guaranteed since high water marks are updated separately.
  59. HighWaterMarks() map[string]map[int32]int64
  60. // Close shuts down the consumer. It must be called after all child
  61. // PartitionConsumers have already been closed.
  62. Close() error
  63. }
  64. type consumer struct {
  65. client Client
  66. conf *Config
  67. ownClient bool
  68. lock sync.Mutex
  69. children map[string]map[int32]*partitionConsumer
  70. brokerConsumers map[*Broker]*brokerConsumer
  71. }
  72. // NewConsumer creates a new consumer using the given broker addresses and configuration.
  73. func NewConsumer(addrs []string, config *Config) (Consumer, error) {
  74. client, err := NewClient(addrs, config)
  75. if err != nil {
  76. return nil, err
  77. }
  78. c, err := NewConsumerFromClient(client)
  79. if err != nil {
  80. return nil, err
  81. }
  82. c.(*consumer).ownClient = true
  83. return c, nil
  84. }
  85. // NewConsumerFromClient creates a new consumer using the given client. It is still
  86. // necessary to call Close() on the underlying client when shutting down this consumer.
  87. func NewConsumerFromClient(client Client) (Consumer, error) {
  88. // Check that we are not dealing with a closed Client before processing any other arguments
  89. if client.Closed() {
  90. return nil, ErrClosedClient
  91. }
  92. c := &consumer{
  93. client: client,
  94. conf: client.Config(),
  95. children: make(map[string]map[int32]*partitionConsumer),
  96. brokerConsumers: make(map[*Broker]*brokerConsumer),
  97. }
  98. return c, nil
  99. }
  100. func (c *consumer) Close() error {
  101. if c.ownClient {
  102. return c.client.Close()
  103. }
  104. return nil
  105. }
  106. func (c *consumer) Topics() ([]string, error) {
  107. return c.client.Topics()
  108. }
  109. func (c *consumer) Partitions(topic string) ([]int32, error) {
  110. return c.client.Partitions(topic)
  111. }
  112. func (c *consumer) ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error) {
  113. child := &partitionConsumer{
  114. consumer: c,
  115. conf: c.conf,
  116. topic: topic,
  117. partition: partition,
  118. messages: make(chan *ConsumerMessage, c.conf.ChannelBufferSize),
  119. errors: make(chan *ConsumerError, c.conf.ChannelBufferSize),
  120. feeder: make(chan *FetchResponse, 1),
  121. trigger: make(chan none, 1),
  122. dying: make(chan none),
  123. fetchSize: c.conf.Consumer.Fetch.Default,
  124. }
  125. if err := child.chooseStartingOffset(offset); err != nil {
  126. return nil, err
  127. }
  128. var leader *Broker
  129. var err error
  130. if leader, err = c.client.Leader(child.topic, child.partition); err != nil {
  131. return nil, err
  132. }
  133. if err := c.addChild(child); err != nil {
  134. return nil, err
  135. }
  136. go withRecover(child.dispatcher)
  137. go withRecover(child.responseFeeder)
  138. child.broker = c.refBrokerConsumer(leader)
  139. child.broker.input <- child
  140. return child, nil
  141. }
  142. func (c *consumer) HighWaterMarks() map[string]map[int32]int64 {
  143. c.lock.Lock()
  144. defer c.lock.Unlock()
  145. hwms := make(map[string]map[int32]int64)
  146. for topic, p := range c.children {
  147. hwm := make(map[int32]int64, len(p))
  148. for partition, pc := range p {
  149. hwm[partition] = pc.HighWaterMarkOffset()
  150. }
  151. hwms[topic] = hwm
  152. }
  153. return hwms
  154. }
  155. func (c *consumer) addChild(child *partitionConsumer) error {
  156. c.lock.Lock()
  157. defer c.lock.Unlock()
  158. topicChildren := c.children[child.topic]
  159. if topicChildren == nil {
  160. topicChildren = make(map[int32]*partitionConsumer)
  161. c.children[child.topic] = topicChildren
  162. }
  163. if topicChildren[child.partition] != nil {
  164. return ConfigurationError("That topic/partition is already being consumed")
  165. }
  166. topicChildren[child.partition] = child
  167. return nil
  168. }
  169. func (c *consumer) removeChild(child *partitionConsumer) {
  170. c.lock.Lock()
  171. defer c.lock.Unlock()
  172. delete(c.children[child.topic], child.partition)
  173. }
  174. func (c *consumer) refBrokerConsumer(broker *Broker) *brokerConsumer {
  175. c.lock.Lock()
  176. defer c.lock.Unlock()
  177. bc := c.brokerConsumers[broker]
  178. if bc == nil {
  179. bc = c.newBrokerConsumer(broker)
  180. c.brokerConsumers[broker] = bc
  181. }
  182. bc.refs++
  183. return bc
  184. }
  185. func (c *consumer) unrefBrokerConsumer(brokerWorker *brokerConsumer) {
  186. c.lock.Lock()
  187. defer c.lock.Unlock()
  188. brokerWorker.refs--
  189. if brokerWorker.refs == 0 {
  190. close(brokerWorker.input)
  191. if c.brokerConsumers[brokerWorker.broker] == brokerWorker {
  192. delete(c.brokerConsumers, brokerWorker.broker)
  193. }
  194. }
  195. }
  196. func (c *consumer) abandonBrokerConsumer(brokerWorker *brokerConsumer) {
  197. c.lock.Lock()
  198. defer c.lock.Unlock()
  199. delete(c.brokerConsumers, brokerWorker.broker)
  200. }
  201. // PartitionConsumer
  202. // PartitionConsumer processes Kafka messages from a given topic and partition. You MUST call one of Close() or
  203. // AsyncClose() on a PartitionConsumer to avoid leaks; it will not be garbage-collected automatically when it passes out
  204. // of scope.
  205. //
  206. // The simplest way of using a PartitionConsumer is to loop over its Messages channel using a for/range
  207. // loop. The PartitionConsumer will only stop itself in one case: when the offset being consumed is reported
  208. // as out of range by the brokers. In this case you should decide what you want to do (try a different offset,
  209. // notify a human, etc) and handle it appropriately. For all other error cases, it will just keep retrying.
  210. // By default, it logs these errors to sarama.Logger; if you want to be notified directly of all errors, set
  211. // your config's Consumer.Return.Errors to true and read from the Errors channel, using a select statement
  212. // or a separate goroutine. Check out the Consumer examples to see implementations of these different approaches.
  213. //
  214. // To terminate such a for/range loop while the loop is executing, call AsyncClose. This will kick off the process of
  215. // consumer tear-down & return imediately. Continue to loop, servicing the Messages channel until the teardown process
  216. // AsyncClose initiated closes it (thus terminating the for/range loop). If you've already ceased reading Messages, call
  217. // Close; this will signal the PartitionConsumer's goroutines to begin shutting down (just like AsyncClose), but will
  218. // also drain the Messages channel, harvest all errors & return them once cleanup has completed.
  219. type PartitionConsumer interface {
  220. // AsyncClose initiates a shutdown of the PartitionConsumer. This method will return immediately, after which you
  221. // should continue to service the 'Messages' and 'Errors' channels until they are empty. It is required to call this
  222. // function, or Close before a consumer object passes out of scope, as it will otherwise leak memory. You must call
  223. // this before calling Close on the underlying client.
  224. AsyncClose()
  225. // Close stops the PartitionConsumer from fetching messages. It will initiate a shutdown just like AsyncClose, drain
  226. // the Messages channel, harvest any errors & return them to the caller. Note that if you are continuing to service
  227. // the Messages channel when this function is called, you will be competing with Close for messages; consider
  228. // calling AsyncClose, instead. It is required to call this function (or AsyncClose) before a consumer object passes
  229. // out of scope, as it will otherwise leak memory. You must call this before calling Close on the underlying client.
  230. Close() error
  231. // Messages returns the read channel for the messages that are returned by
  232. // the broker.
  233. Messages() <-chan *ConsumerMessage
  234. // Errors returns a read channel of errors that occurred during consuming, if
  235. // enabled. By default, errors are logged and not returned over this channel.
  236. // If you want to implement any custom error handling, set your config's
  237. // Consumer.Return.Errors setting to true, and read from this channel.
  238. Errors() <-chan *ConsumerError
  239. // HighWaterMarkOffset returns the high water mark offset of the partition,
  240. // i.e. the offset that will be used for the next message that will be produced.
  241. // You can use this to determine how far behind the processing is.
  242. HighWaterMarkOffset() int64
  243. }
  244. type partitionConsumer struct {
  245. highWaterMarkOffset int64 // must be at the top of the struct because https://golang.org/pkg/sync/atomic/#pkg-note-BUG
  246. consumer *consumer
  247. conf *Config
  248. topic string
  249. partition int32
  250. broker *brokerConsumer
  251. messages chan *ConsumerMessage
  252. errors chan *ConsumerError
  253. feeder chan *FetchResponse
  254. trigger, dying chan none
  255. responseResult error
  256. closeOnce sync.Once
  257. fetchSize int32
  258. offset int64
  259. retries int32
  260. }
  261. var errTimedOut = errors.New("timed out feeding messages to the user") // not user-facing
  262. func (child *partitionConsumer) sendError(err error) {
  263. cErr := &ConsumerError{
  264. Topic: child.topic,
  265. Partition: child.partition,
  266. Err: err,
  267. }
  268. if child.conf.Consumer.Return.Errors {
  269. child.errors <- cErr
  270. } else {
  271. Logger.Println(cErr)
  272. }
  273. }
  274. func (child *partitionConsumer) computeBackoff() time.Duration {
  275. if child.conf.Consumer.Retry.BackoffFunc != nil {
  276. retries := atomic.AddInt32(&child.retries, 1)
  277. return child.conf.Consumer.Retry.BackoffFunc(int(retries))
  278. } else {
  279. return child.conf.Consumer.Retry.Backoff
  280. }
  281. }
  282. func (child *partitionConsumer) dispatcher() {
  283. for range child.trigger {
  284. select {
  285. case <-child.dying:
  286. close(child.trigger)
  287. case <-time.After(child.computeBackoff()):
  288. if child.broker != nil {
  289. child.consumer.unrefBrokerConsumer(child.broker)
  290. child.broker = nil
  291. }
  292. Logger.Printf("consumer/%s/%d finding new broker\n", child.topic, child.partition)
  293. if err := child.dispatch(); err != nil {
  294. child.sendError(err)
  295. child.trigger <- none{}
  296. }
  297. }
  298. }
  299. if child.broker != nil {
  300. child.consumer.unrefBrokerConsumer(child.broker)
  301. }
  302. child.consumer.removeChild(child)
  303. close(child.feeder)
  304. }
  305. func (child *partitionConsumer) dispatch() error {
  306. if err := child.consumer.client.RefreshMetadata(child.topic); err != nil {
  307. return err
  308. }
  309. var leader *Broker
  310. var err error
  311. if leader, err = child.consumer.client.Leader(child.topic, child.partition); err != nil {
  312. return err
  313. }
  314. child.broker = child.consumer.refBrokerConsumer(leader)
  315. child.broker.input <- child
  316. return nil
  317. }
  318. func (child *partitionConsumer) chooseStartingOffset(offset int64) error {
  319. newestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetNewest)
  320. if err != nil {
  321. return err
  322. }
  323. oldestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetOldest)
  324. if err != nil {
  325. return err
  326. }
  327. switch {
  328. case offset == OffsetNewest:
  329. child.offset = newestOffset
  330. case offset == OffsetOldest:
  331. child.offset = oldestOffset
  332. case offset >= oldestOffset && offset <= newestOffset:
  333. child.offset = offset
  334. default:
  335. return ErrOffsetOutOfRange
  336. }
  337. return nil
  338. }
  339. func (child *partitionConsumer) Messages() <-chan *ConsumerMessage {
  340. return child.messages
  341. }
  342. func (child *partitionConsumer) Errors() <-chan *ConsumerError {
  343. return child.errors
  344. }
  345. func (child *partitionConsumer) AsyncClose() {
  346. // this triggers whatever broker owns this child to abandon it and close its trigger channel, which causes
  347. // the dispatcher to exit its loop, which removes it from the consumer then closes its 'messages' and
  348. // 'errors' channel (alternatively, if the child is already at the dispatcher for some reason, that will
  349. // also just close itself)
  350. child.closeOnce.Do(func() {
  351. close(child.dying)
  352. })
  353. }
  354. func (child *partitionConsumer) Close() error {
  355. child.AsyncClose()
  356. go withRecover(func() {
  357. for range child.messages {
  358. // drain
  359. }
  360. })
  361. var errors ConsumerErrors
  362. for err := range child.errors {
  363. errors = append(errors, err)
  364. }
  365. if len(errors) > 0 {
  366. return errors
  367. }
  368. return nil
  369. }
  370. func (child *partitionConsumer) HighWaterMarkOffset() int64 {
  371. return atomic.LoadInt64(&child.highWaterMarkOffset)
  372. }
  373. func (child *partitionConsumer) responseFeeder() {
  374. var msgs []*ConsumerMessage
  375. expiryTicker := time.NewTicker(child.conf.Consumer.MaxProcessingTime)
  376. firstAttempt := true
  377. feederLoop:
  378. for response := range child.feeder {
  379. msgs, child.responseResult = child.parseResponse(response)
  380. if child.responseResult == nil {
  381. atomic.StoreInt32(&child.retries, 0)
  382. }
  383. for i, msg := range msgs {
  384. messageSelect:
  385. select {
  386. case child.messages <- msg:
  387. firstAttempt = true
  388. case <-expiryTicker.C:
  389. if !firstAttempt {
  390. child.responseResult = errTimedOut
  391. child.broker.acks.Done()
  392. for _, msg = range msgs[i:] {
  393. child.messages <- msg
  394. }
  395. child.broker.input <- child
  396. continue feederLoop
  397. } else {
  398. // current message has not been sent, return to select
  399. // statement
  400. firstAttempt = false
  401. goto messageSelect
  402. }
  403. }
  404. }
  405. child.broker.acks.Done()
  406. }
  407. expiryTicker.Stop()
  408. close(child.messages)
  409. close(child.errors)
  410. }
  411. func (child *partitionConsumer) parseMessages(msgSet *MessageSet) ([]*ConsumerMessage, error) {
  412. var messages []*ConsumerMessage
  413. for _, msgBlock := range msgSet.Messages {
  414. for _, msg := range msgBlock.Messages() {
  415. offset := msg.Offset
  416. timestamp := msg.Msg.Timestamp
  417. if msg.Msg.Version >= 1 {
  418. baseOffset := msgBlock.Offset - msgBlock.Messages()[len(msgBlock.Messages())-1].Offset
  419. offset += baseOffset
  420. if msg.Msg.LogAppendTime {
  421. timestamp = msgBlock.Msg.Timestamp
  422. }
  423. }
  424. if offset < child.offset {
  425. continue
  426. }
  427. messages = append(messages, &ConsumerMessage{
  428. Topic: child.topic,
  429. Partition: child.partition,
  430. Key: msg.Msg.Key,
  431. Value: msg.Msg.Value,
  432. Offset: offset,
  433. Timestamp: timestamp,
  434. BlockTimestamp: msgBlock.Msg.Timestamp,
  435. })
  436. child.offset = offset + 1
  437. }
  438. }
  439. if len(messages) == 0 {
  440. child.offset++
  441. }
  442. return messages, nil
  443. }
  444. func (child *partitionConsumer) parseRecords(batch *RecordBatch) ([]*ConsumerMessage, error) {
  445. var messages []*ConsumerMessage
  446. for _, rec := range batch.Records {
  447. offset := batch.FirstOffset + rec.OffsetDelta
  448. if offset < child.offset {
  449. continue
  450. }
  451. timestamp := batch.FirstTimestamp.Add(rec.TimestampDelta)
  452. if batch.LogAppendTime {
  453. timestamp = batch.MaxTimestamp
  454. }
  455. messages = append(messages, &ConsumerMessage{
  456. Topic: child.topic,
  457. Partition: child.partition,
  458. Key: rec.Key,
  459. Value: rec.Value,
  460. Offset: offset,
  461. Timestamp: timestamp,
  462. Headers: rec.Headers,
  463. })
  464. child.offset = offset + 1
  465. }
  466. if len(messages) == 0 {
  467. child.offset++
  468. }
  469. return messages, nil
  470. }
  471. func (child *partitionConsumer) parseResponse(response *FetchResponse) ([]*ConsumerMessage, error) {
  472. block := response.GetBlock(child.topic, child.partition)
  473. if block == nil {
  474. return nil, ErrIncompleteResponse
  475. }
  476. if block.Err != ErrNoError {
  477. return nil, block.Err
  478. }
  479. nRecs, err := block.numRecords()
  480. if err != nil {
  481. return nil, err
  482. }
  483. if nRecs == 0 {
  484. partialTrailingMessage, err := block.isPartial()
  485. if err != nil {
  486. return nil, err
  487. }
  488. // We got no messages. If we got a trailing one then we need to ask for more data.
  489. // Otherwise we just poll again and wait for one to be produced...
  490. if partialTrailingMessage {
  491. if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize == child.conf.Consumer.Fetch.Max {
  492. // we can't ask for more data, we've hit the configured limit
  493. child.sendError(ErrMessageTooLarge)
  494. child.offset++ // skip this one so we can keep processing future messages
  495. } else {
  496. child.fetchSize *= 2
  497. if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize > child.conf.Consumer.Fetch.Max {
  498. child.fetchSize = child.conf.Consumer.Fetch.Max
  499. }
  500. }
  501. }
  502. return nil, nil
  503. }
  504. // we got messages, reset our fetch size in case it was increased for a previous request
  505. child.fetchSize = child.conf.Consumer.Fetch.Default
  506. atomic.StoreInt64(&child.highWaterMarkOffset, block.HighWaterMarkOffset)
  507. messages := []*ConsumerMessage{}
  508. for _, records := range block.RecordsSet {
  509. switch records.recordsType {
  510. case legacyRecords:
  511. messageSetMessages, err := child.parseMessages(records.MsgSet)
  512. if err != nil {
  513. return nil, err
  514. }
  515. messages = append(messages, messageSetMessages...)
  516. case defaultRecords:
  517. recordBatchMessages, err := child.parseRecords(records.RecordBatch)
  518. if err != nil {
  519. return nil, err
  520. }
  521. if control, err := records.isControl(); err != nil || control {
  522. continue
  523. }
  524. messages = append(messages, recordBatchMessages...)
  525. default:
  526. return nil, fmt.Errorf("unknown records type: %v", records.recordsType)
  527. }
  528. }
  529. return messages, nil
  530. }
  531. // brokerConsumer
  532. type brokerConsumer struct {
  533. consumer *consumer
  534. broker *Broker
  535. input chan *partitionConsumer
  536. newSubscriptions chan []*partitionConsumer
  537. wait chan none
  538. subscriptions map[*partitionConsumer]none
  539. acks sync.WaitGroup
  540. refs int
  541. }
  542. func (c *consumer) newBrokerConsumer(broker *Broker) *brokerConsumer {
  543. bc := &brokerConsumer{
  544. consumer: c,
  545. broker: broker,
  546. input: make(chan *partitionConsumer),
  547. newSubscriptions: make(chan []*partitionConsumer),
  548. wait: make(chan none),
  549. subscriptions: make(map[*partitionConsumer]none),
  550. refs: 0,
  551. }
  552. go withRecover(bc.subscriptionManager)
  553. go withRecover(bc.subscriptionConsumer)
  554. return bc
  555. }
  556. func (bc *brokerConsumer) subscriptionManager() {
  557. var buffer []*partitionConsumer
  558. // The subscriptionManager constantly accepts new subscriptions on `input` (even when the main subscriptionConsumer
  559. // goroutine is in the middle of a network request) and batches it up. The main worker goroutine picks
  560. // up a batch of new subscriptions between every network request by reading from `newSubscriptions`, so we give
  561. // it nil if no new subscriptions are available. We also write to `wait` only when new subscriptions is available,
  562. // so the main goroutine can block waiting for work if it has none.
  563. for {
  564. if len(buffer) > 0 {
  565. select {
  566. case event, ok := <-bc.input:
  567. if !ok {
  568. goto done
  569. }
  570. buffer = append(buffer, event)
  571. case bc.newSubscriptions <- buffer:
  572. buffer = nil
  573. case bc.wait <- none{}:
  574. }
  575. } else {
  576. select {
  577. case event, ok := <-bc.input:
  578. if !ok {
  579. goto done
  580. }
  581. buffer = append(buffer, event)
  582. case bc.newSubscriptions <- nil:
  583. }
  584. }
  585. }
  586. done:
  587. close(bc.wait)
  588. if len(buffer) > 0 {
  589. bc.newSubscriptions <- buffer
  590. }
  591. close(bc.newSubscriptions)
  592. }
  593. func (bc *brokerConsumer) subscriptionConsumer() {
  594. <-bc.wait // wait for our first piece of work
  595. // the subscriptionConsumer ensures we will get nil right away if no new subscriptions is available
  596. for newSubscriptions := range bc.newSubscriptions {
  597. bc.updateSubscriptions(newSubscriptions)
  598. if len(bc.subscriptions) == 0 {
  599. // We're about to be shut down or we're about to receive more subscriptions.
  600. // Either way, the signal just hasn't propagated to our goroutine yet.
  601. <-bc.wait
  602. continue
  603. }
  604. response, err := bc.fetchNewMessages()
  605. if err != nil {
  606. Logger.Printf("consumer/broker/%d disconnecting due to error processing FetchRequest: %s\n", bc.broker.ID(), err)
  607. bc.abort(err)
  608. return
  609. }
  610. bc.acks.Add(len(bc.subscriptions))
  611. for child := range bc.subscriptions {
  612. child.feeder <- response
  613. }
  614. bc.acks.Wait()
  615. bc.handleResponses()
  616. }
  617. }
  618. func (bc *brokerConsumer) updateSubscriptions(newSubscriptions []*partitionConsumer) {
  619. for _, child := range newSubscriptions {
  620. bc.subscriptions[child] = none{}
  621. Logger.Printf("consumer/broker/%d added subscription to %s/%d\n", bc.broker.ID(), child.topic, child.partition)
  622. }
  623. for child := range bc.subscriptions {
  624. select {
  625. case <-child.dying:
  626. Logger.Printf("consumer/broker/%d closed dead subscription to %s/%d\n", bc.broker.ID(), child.topic, child.partition)
  627. close(child.trigger)
  628. delete(bc.subscriptions, child)
  629. default:
  630. break
  631. }
  632. }
  633. }
  634. func (bc *brokerConsumer) handleResponses() {
  635. // handles the response codes left for us by our subscriptions, and abandons ones that have been closed
  636. for child := range bc.subscriptions {
  637. result := child.responseResult
  638. child.responseResult = nil
  639. switch result {
  640. case nil:
  641. break
  642. case errTimedOut:
  643. Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because consuming was taking too long\n",
  644. bc.broker.ID(), child.topic, child.partition)
  645. delete(bc.subscriptions, child)
  646. case ErrOffsetOutOfRange:
  647. // there's no point in retrying this it will just fail the same way again
  648. // shut it down and force the user to choose what to do
  649. child.sendError(result)
  650. Logger.Printf("consumer/%s/%d shutting down because %s\n", child.topic, child.partition, result)
  651. close(child.trigger)
  652. delete(bc.subscriptions, child)
  653. case ErrUnknownTopicOrPartition, ErrNotLeaderForPartition, ErrLeaderNotAvailable, ErrReplicaNotAvailable:
  654. // not an error, but does need redispatching
  655. Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n",
  656. bc.broker.ID(), child.topic, child.partition, result)
  657. child.trigger <- none{}
  658. delete(bc.subscriptions, child)
  659. default:
  660. // dunno, tell the user and try redispatching
  661. child.sendError(result)
  662. Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n",
  663. bc.broker.ID(), child.topic, child.partition, result)
  664. child.trigger <- none{}
  665. delete(bc.subscriptions, child)
  666. }
  667. }
  668. }
  669. func (bc *brokerConsumer) abort(err error) {
  670. bc.consumer.abandonBrokerConsumer(bc)
  671. _ = bc.broker.Close() // we don't care about the error this might return, we already have one
  672. for child := range bc.subscriptions {
  673. child.sendError(err)
  674. child.trigger <- none{}
  675. }
  676. for newSubscriptions := range bc.newSubscriptions {
  677. if len(newSubscriptions) == 0 {
  678. <-bc.wait
  679. continue
  680. }
  681. for _, child := range newSubscriptions {
  682. child.sendError(err)
  683. child.trigger <- none{}
  684. }
  685. }
  686. }
  687. func (bc *brokerConsumer) fetchNewMessages() (*FetchResponse, error) {
  688. request := &FetchRequest{
  689. MinBytes: bc.consumer.conf.Consumer.Fetch.Min,
  690. MaxWaitTime: int32(bc.consumer.conf.Consumer.MaxWaitTime / time.Millisecond),
  691. }
  692. if bc.consumer.conf.Version.IsAtLeast(V0_9_0_0) {
  693. request.Version = 1
  694. }
  695. if bc.consumer.conf.Version.IsAtLeast(V0_10_0_0) {
  696. request.Version = 2
  697. }
  698. if bc.consumer.conf.Version.IsAtLeast(V0_10_1_0) {
  699. request.Version = 3
  700. request.MaxBytes = MaxResponseSize
  701. }
  702. if bc.consumer.conf.Version.IsAtLeast(V0_11_0_0) {
  703. request.Version = 4
  704. request.Isolation = ReadUncommitted // We don't support yet transactions.
  705. }
  706. for child := range bc.subscriptions {
  707. request.AddBlock(child.topic, child.partition, child.offset, child.fetchSize)
  708. }
  709. return bc.broker.Fetch(request)
  710. }