consumer.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. package sarama
  2. import (
  3. "errors"
  4. "fmt"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "github.com/rcrowley/go-metrics"
  9. )
  10. // ConsumerMessage encapsulates a Kafka message returned by the consumer.
  11. type ConsumerMessage struct {
  12. Key, Value []byte
  13. Topic string
  14. Partition int32
  15. Offset int64
  16. Timestamp time.Time // only set if kafka is version 0.10+, inner message timestamp
  17. BlockTimestamp time.Time // only set if kafka is version 0.10+, outer (compressed) block timestamp
  18. Headers []*RecordHeader // only set if kafka is version 0.11+
  19. }
  20. // ConsumerError is what is provided to the user when an error occurs.
  21. // It wraps an error and includes the topic and partition.
  22. type ConsumerError struct {
  23. Topic string
  24. Partition int32
  25. Err error
  26. }
  27. func (ce ConsumerError) Error() string {
  28. return fmt.Sprintf("kafka: error while consuming %s/%d: %s", ce.Topic, ce.Partition, ce.Err)
  29. }
  30. // ConsumerErrors is a type that wraps a batch of errors and implements the Error interface.
  31. // It can be returned from the PartitionConsumer's Close methods to avoid the need to manually drain errors
  32. // when stopping.
  33. type ConsumerErrors []*ConsumerError
  34. func (ce ConsumerErrors) Error() string {
  35. return fmt.Sprintf("kafka: %d errors while consuming", len(ce))
  36. }
  37. // Consumer manages PartitionConsumers which process Kafka messages from brokers. You MUST call Close()
  38. // on a consumer to avoid leaks, it will not be garbage-collected automatically when it passes out of
  39. // scope.
  40. //
  41. // Sarama's Consumer type does not currently support automatic consumer-group rebalancing and offset tracking.
  42. // For Zookeeper-based tracking (Kafka 0.8.2 and earlier), the https://github.com/wvanbergen/kafka library
  43. // builds on Sarama to add this support. For Kafka-based tracking (Kafka 0.9 and later), the
  44. // https://github.com/bsm/sarama-cluster library builds on Sarama to add this support.
  45. type Consumer interface {
  46. // Topics returns the set of available topics as retrieved from the cluster
  47. // metadata. This method is the same as Client.Topics(), and is provided for
  48. // convenience.
  49. Topics() ([]string, error)
  50. // Partitions returns the sorted list of all partition IDs for the given topic.
  51. // This method is the same as Client.Partitions(), and is provided for convenience.
  52. Partitions(topic string) ([]int32, error)
  53. // ConsumePartition creates a PartitionConsumer on the given topic/partition with
  54. // the given offset. It will return an error if this Consumer is already consuming
  55. // on the given topic/partition. Offset can be a literal offset, or OffsetNewest
  56. // or OffsetOldest
  57. ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error)
  58. // HighWaterMarks returns the current high water marks for each topic and partition.
  59. // Consistency between partitions is not guaranteed since high water marks are updated separately.
  60. HighWaterMarks() map[string]map[int32]int64
  61. // Close shuts down the consumer. It must be called after all child
  62. // PartitionConsumers have already been closed.
  63. Close() error
  64. }
  65. type consumer struct {
  66. client Client
  67. conf *Config
  68. ownClient bool
  69. lock sync.Mutex
  70. children map[string]map[int32]*partitionConsumer
  71. brokerConsumers map[*Broker]*brokerConsumer
  72. }
  73. // NewConsumer creates a new consumer using the given broker addresses and configuration.
  74. func NewConsumer(addrs []string, config *Config) (Consumer, error) {
  75. client, err := NewClient(addrs, config)
  76. if err != nil {
  77. return nil, err
  78. }
  79. c, err := NewConsumerFromClient(client)
  80. if err != nil {
  81. return nil, err
  82. }
  83. c.(*consumer).ownClient = true
  84. return c, nil
  85. }
  86. // NewConsumerFromClient creates a new consumer using the given client. It is still
  87. // necessary to call Close() on the underlying client when shutting down this consumer.
  88. func NewConsumerFromClient(client Client) (Consumer, error) {
  89. // Check that we are not dealing with a closed Client before processing any other arguments
  90. if client.Closed() {
  91. return nil, ErrClosedClient
  92. }
  93. c := &consumer{
  94. client: client,
  95. conf: client.Config(),
  96. children: make(map[string]map[int32]*partitionConsumer),
  97. brokerConsumers: make(map[*Broker]*brokerConsumer),
  98. }
  99. return c, nil
  100. }
  101. func (c *consumer) Close() error {
  102. if c.ownClient {
  103. return c.client.Close()
  104. }
  105. return nil
  106. }
  107. func (c *consumer) Topics() ([]string, error) {
  108. return c.client.Topics()
  109. }
  110. func (c *consumer) Partitions(topic string) ([]int32, error) {
  111. return c.client.Partitions(topic)
  112. }
  113. func (c *consumer) ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error) {
  114. child := &partitionConsumer{
  115. consumer: c,
  116. conf: c.conf,
  117. topic: topic,
  118. partition: partition,
  119. messages: make(chan *ConsumerMessage, c.conf.ChannelBufferSize),
  120. errors: make(chan *ConsumerError, c.conf.ChannelBufferSize),
  121. feeder: make(chan *FetchResponse, 1),
  122. trigger: make(chan none, 1),
  123. dying: make(chan none),
  124. fetchSize: c.conf.Consumer.Fetch.Default,
  125. }
  126. if err := child.chooseStartingOffset(offset); err != nil {
  127. return nil, err
  128. }
  129. var leader *Broker
  130. var err error
  131. if leader, err = c.client.Leader(child.topic, child.partition); err != nil {
  132. return nil, err
  133. }
  134. if err := c.addChild(child); err != nil {
  135. return nil, err
  136. }
  137. go withRecover(child.dispatcher)
  138. go withRecover(child.responseFeeder)
  139. child.broker = c.refBrokerConsumer(leader)
  140. child.broker.input <- child
  141. return child, nil
  142. }
  143. func (c *consumer) HighWaterMarks() map[string]map[int32]int64 {
  144. c.lock.Lock()
  145. defer c.lock.Unlock()
  146. hwms := make(map[string]map[int32]int64)
  147. for topic, p := range c.children {
  148. hwm := make(map[int32]int64, len(p))
  149. for partition, pc := range p {
  150. hwm[partition] = pc.HighWaterMarkOffset()
  151. }
  152. hwms[topic] = hwm
  153. }
  154. return hwms
  155. }
  156. func (c *consumer) addChild(child *partitionConsumer) error {
  157. c.lock.Lock()
  158. defer c.lock.Unlock()
  159. topicChildren := c.children[child.topic]
  160. if topicChildren == nil {
  161. topicChildren = make(map[int32]*partitionConsumer)
  162. c.children[child.topic] = topicChildren
  163. }
  164. if topicChildren[child.partition] != nil {
  165. return ConfigurationError("That topic/partition is already being consumed")
  166. }
  167. topicChildren[child.partition] = child
  168. return nil
  169. }
  170. func (c *consumer) removeChild(child *partitionConsumer) {
  171. c.lock.Lock()
  172. defer c.lock.Unlock()
  173. delete(c.children[child.topic], child.partition)
  174. }
  175. func (c *consumer) refBrokerConsumer(broker *Broker) *brokerConsumer {
  176. c.lock.Lock()
  177. defer c.lock.Unlock()
  178. bc := c.brokerConsumers[broker]
  179. if bc == nil {
  180. bc = c.newBrokerConsumer(broker)
  181. c.brokerConsumers[broker] = bc
  182. }
  183. bc.refs++
  184. return bc
  185. }
  186. func (c *consumer) unrefBrokerConsumer(brokerWorker *brokerConsumer) {
  187. c.lock.Lock()
  188. defer c.lock.Unlock()
  189. brokerWorker.refs--
  190. if brokerWorker.refs == 0 {
  191. close(brokerWorker.input)
  192. if c.brokerConsumers[brokerWorker.broker] == brokerWorker {
  193. delete(c.brokerConsumers, brokerWorker.broker)
  194. }
  195. }
  196. }
  197. func (c *consumer) abandonBrokerConsumer(brokerWorker *brokerConsumer) {
  198. c.lock.Lock()
  199. defer c.lock.Unlock()
  200. delete(c.brokerConsumers, brokerWorker.broker)
  201. }
  202. // PartitionConsumer
  203. // PartitionConsumer processes Kafka messages from a given topic and partition. You MUST call one of Close() or
  204. // AsyncClose() on a PartitionConsumer to avoid leaks; it will not be garbage-collected automatically when it passes out
  205. // of scope.
  206. //
  207. // The simplest way of using a PartitionConsumer is to loop over its Messages channel using a for/range
  208. // loop. The PartitionConsumer will only stop itself in one case: when the offset being consumed is reported
  209. // as out of range by the brokers. In this case you should decide what you want to do (try a different offset,
  210. // notify a human, etc) and handle it appropriately. For all other error cases, it will just keep retrying.
  211. // By default, it logs these errors to sarama.Logger; if you want to be notified directly of all errors, set
  212. // your config's Consumer.Return.Errors to true and read from the Errors channel, using a select statement
  213. // or a separate goroutine. Check out the Consumer examples to see implementations of these different approaches.
  214. //
  215. // To terminate such a for/range loop while the loop is executing, call AsyncClose. This will kick off the process of
  216. // consumer tear-down & return imediately. Continue to loop, servicing the Messages channel until the teardown process
  217. // AsyncClose initiated closes it (thus terminating the for/range loop). If you've already ceased reading Messages, call
  218. // Close; this will signal the PartitionConsumer's goroutines to begin shutting down (just like AsyncClose), but will
  219. // also drain the Messages channel, harvest all errors & return them once cleanup has completed.
  220. type PartitionConsumer interface {
  221. // AsyncClose initiates a shutdown of the PartitionConsumer. This method will return immediately, after which you
  222. // should continue to service the 'Messages' and 'Errors' channels until they are empty. It is required to call this
  223. // function, or Close before a consumer object passes out of scope, as it will otherwise leak memory. You must call
  224. // this before calling Close on the underlying client.
  225. AsyncClose()
  226. // Close stops the PartitionConsumer from fetching messages. It will initiate a shutdown just like AsyncClose, drain
  227. // the Messages channel, harvest any errors & return them to the caller. Note that if you are continuing to service
  228. // the Messages channel when this function is called, you will be competing with Close for messages; consider
  229. // calling AsyncClose, instead. It is required to call this function (or AsyncClose) before a consumer object passes
  230. // out of scope, as it will otherwise leak memory. You must call this before calling Close on the underlying client.
  231. Close() error
  232. // Messages returns the read channel for the messages that are returned by
  233. // the broker.
  234. Messages() <-chan *ConsumerMessage
  235. // Errors returns a read channel of errors that occurred during consuming, if
  236. // enabled. By default, errors are logged and not returned over this channel.
  237. // If you want to implement any custom error handling, set your config's
  238. // Consumer.Return.Errors setting to true, and read from this channel.
  239. Errors() <-chan *ConsumerError
  240. // HighWaterMarkOffset returns the high water mark offset of the partition,
  241. // i.e. the offset that will be used for the next message that will be produced.
  242. // You can use this to determine how far behind the processing is.
  243. HighWaterMarkOffset() int64
  244. }
  245. type partitionConsumer struct {
  246. highWaterMarkOffset int64 // must be at the top of the struct because https://golang.org/pkg/sync/atomic/#pkg-note-BUG
  247. consumer *consumer
  248. conf *Config
  249. topic string
  250. partition int32
  251. broker *brokerConsumer
  252. messages chan *ConsumerMessage
  253. errors chan *ConsumerError
  254. feeder chan *FetchResponse
  255. trigger, dying chan none
  256. responseResult error
  257. closeOnce sync.Once
  258. fetchSize int32
  259. offset int64
  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) dispatcher() {
  275. for range child.trigger {
  276. select {
  277. case <-child.dying:
  278. close(child.trigger)
  279. case <-time.After(child.conf.Consumer.Retry.Backoff):
  280. if child.broker != nil {
  281. child.consumer.unrefBrokerConsumer(child.broker)
  282. child.broker = nil
  283. }
  284. Logger.Printf("consumer/%s/%d finding new broker\n", child.topic, child.partition)
  285. if err := child.dispatch(); err != nil {
  286. child.sendError(err)
  287. child.trigger <- none{}
  288. }
  289. }
  290. }
  291. if child.broker != nil {
  292. child.consumer.unrefBrokerConsumer(child.broker)
  293. }
  294. child.consumer.removeChild(child)
  295. close(child.feeder)
  296. }
  297. func (child *partitionConsumer) dispatch() error {
  298. if err := child.consumer.client.RefreshMetadata(child.topic); err != nil {
  299. return err
  300. }
  301. var leader *Broker
  302. var err error
  303. if leader, err = child.consumer.client.Leader(child.topic, child.partition); err != nil {
  304. return err
  305. }
  306. child.broker = child.consumer.refBrokerConsumer(leader)
  307. child.broker.input <- child
  308. return nil
  309. }
  310. func (child *partitionConsumer) chooseStartingOffset(offset int64) error {
  311. newestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetNewest)
  312. if err != nil {
  313. return err
  314. }
  315. oldestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetOldest)
  316. if err != nil {
  317. return err
  318. }
  319. switch {
  320. case offset == OffsetNewest:
  321. child.offset = newestOffset
  322. case offset == OffsetOldest:
  323. child.offset = oldestOffset
  324. case offset >= oldestOffset && offset <= newestOffset:
  325. child.offset = offset
  326. default:
  327. return ErrOffsetOutOfRange
  328. }
  329. return nil
  330. }
  331. func (child *partitionConsumer) Messages() <-chan *ConsumerMessage {
  332. return child.messages
  333. }
  334. func (child *partitionConsumer) Errors() <-chan *ConsumerError {
  335. return child.errors
  336. }
  337. func (child *partitionConsumer) AsyncClose() {
  338. // this triggers whatever broker owns this child to abandon it and close its trigger channel, which causes
  339. // the dispatcher to exit its loop, which removes it from the consumer then closes its 'messages' and
  340. // 'errors' channel (alternatively, if the child is already at the dispatcher for some reason, that will
  341. // also just close itself)
  342. child.closeOnce.Do(func() {
  343. close(child.dying)
  344. })
  345. }
  346. func (child *partitionConsumer) Close() error {
  347. child.AsyncClose()
  348. go withRecover(func() {
  349. for range child.messages {
  350. // drain
  351. }
  352. })
  353. var errors ConsumerErrors
  354. for err := range child.errors {
  355. errors = append(errors, err)
  356. }
  357. if len(errors) > 0 {
  358. return errors
  359. }
  360. return nil
  361. }
  362. func (child *partitionConsumer) HighWaterMarkOffset() int64 {
  363. return atomic.LoadInt64(&child.highWaterMarkOffset)
  364. }
  365. func (child *partitionConsumer) responseFeeder() {
  366. var msgs []*ConsumerMessage
  367. expiryTicker := time.NewTicker(child.conf.Consumer.MaxProcessingTime)
  368. firstAttempt := true
  369. feederLoop:
  370. for response := range child.feeder {
  371. msgs, child.responseResult = child.parseResponse(response)
  372. for i, msg := range msgs {
  373. messageSelect:
  374. select {
  375. case child.messages <- msg:
  376. firstAttempt = true
  377. case <-expiryTicker.C:
  378. if !firstAttempt {
  379. child.responseResult = errTimedOut
  380. child.broker.acks.Done()
  381. for _, msg = range msgs[i:] {
  382. child.messages <- msg
  383. }
  384. child.broker.input <- child
  385. continue feederLoop
  386. } else {
  387. // current message has not been sent, return to select
  388. // statement
  389. firstAttempt = false
  390. goto messageSelect
  391. }
  392. }
  393. }
  394. child.broker.acks.Done()
  395. }
  396. expiryTicker.Stop()
  397. close(child.messages)
  398. close(child.errors)
  399. }
  400. func (child *partitionConsumer) parseMessages(msgSet *MessageSet) ([]*ConsumerMessage, error) {
  401. var messages []*ConsumerMessage
  402. for _, msgBlock := range msgSet.Messages {
  403. for _, msg := range msgBlock.Messages() {
  404. offset := msg.Offset
  405. timestamp := msg.Msg.Timestamp
  406. if msg.Msg.Version >= 1 {
  407. baseOffset := msgBlock.Offset - msgBlock.Messages()[len(msgBlock.Messages())-1].Offset
  408. offset += baseOffset
  409. if msg.Msg.LogAppendTime {
  410. timestamp = msgBlock.Msg.Timestamp
  411. }
  412. }
  413. if offset < child.offset {
  414. continue
  415. }
  416. messages = append(messages, &ConsumerMessage{
  417. Topic: child.topic,
  418. Partition: child.partition,
  419. Key: msg.Msg.Key,
  420. Value: msg.Msg.Value,
  421. Offset: offset,
  422. Timestamp: timestamp,
  423. BlockTimestamp: msgBlock.Msg.Timestamp,
  424. })
  425. child.offset = offset + 1
  426. }
  427. }
  428. if len(messages) == 0 {
  429. return nil, ErrIncompleteResponse
  430. }
  431. return messages, nil
  432. }
  433. func (child *partitionConsumer) parseRecords(batch *RecordBatch) ([]*ConsumerMessage, error) {
  434. var messages []*ConsumerMessage
  435. for _, rec := range batch.Records {
  436. offset := batch.FirstOffset + rec.OffsetDelta
  437. if offset < child.offset {
  438. continue
  439. }
  440. timestamp := batch.FirstTimestamp.Add(rec.TimestampDelta)
  441. if batch.LogAppendTime {
  442. timestamp = batch.MaxTimestamp
  443. }
  444. messages = append(messages, &ConsumerMessage{
  445. Topic: child.topic,
  446. Partition: child.partition,
  447. Key: rec.Key,
  448. Value: rec.Value,
  449. Offset: offset,
  450. Timestamp: timestamp,
  451. Headers: rec.Headers,
  452. })
  453. child.offset = offset + 1
  454. }
  455. if len(messages) == 0 {
  456. child.offset += 1
  457. }
  458. return messages, nil
  459. }
  460. func (child *partitionConsumer) parseResponse(response *FetchResponse) ([]*ConsumerMessage, error) {
  461. var (
  462. metricRegistry = child.conf.MetricRegistry
  463. consumerBatchSizeMetric metrics.Histogram
  464. )
  465. if metricRegistry != nil {
  466. consumerBatchSizeMetric = getOrRegisterHistogram("consumer-batch-size", metricRegistry)
  467. }
  468. block := response.GetBlock(child.topic, child.partition)
  469. if block == nil {
  470. return nil, ErrIncompleteResponse
  471. }
  472. if block.Err != ErrNoError {
  473. return nil, block.Err
  474. }
  475. nRecs, err := block.numRecords()
  476. if err != nil {
  477. return nil, err
  478. }
  479. consumerBatchSizeMetric.Update(int64(nRecs))
  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. }