consumer.go 25 KB

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