consumer.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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. }
  260. var errTimedOut = errors.New("timed out feeding messages to the user") // not user-facing
  261. func (child *partitionConsumer) sendError(err error) {
  262. cErr := &ConsumerError{
  263. Topic: child.topic,
  264. Partition: child.partition,
  265. Err: err,
  266. }
  267. if child.conf.Consumer.Return.Errors {
  268. child.errors <- cErr
  269. } else {
  270. Logger.Println(cErr)
  271. }
  272. }
  273. func (child *partitionConsumer) dispatcher() {
  274. for range child.trigger {
  275. select {
  276. case <-child.dying:
  277. close(child.trigger)
  278. case <-time.After(child.conf.Consumer.Retry.Backoff):
  279. if child.broker != nil {
  280. child.consumer.unrefBrokerConsumer(child.broker)
  281. child.broker = nil
  282. }
  283. Logger.Printf("consumer/%s/%d finding new broker\n", child.topic, child.partition)
  284. if err := child.dispatch(); err != nil {
  285. child.sendError(err)
  286. child.trigger <- none{}
  287. }
  288. }
  289. }
  290. if child.broker != nil {
  291. child.consumer.unrefBrokerConsumer(child.broker)
  292. }
  293. child.consumer.removeChild(child)
  294. close(child.feeder)
  295. }
  296. func (child *partitionConsumer) dispatch() error {
  297. if err := child.consumer.client.RefreshMetadata(child.topic); err != nil {
  298. return err
  299. }
  300. var leader *Broker
  301. var err error
  302. if leader, err = child.consumer.client.Leader(child.topic, child.partition); err != nil {
  303. return err
  304. }
  305. child.broker = child.consumer.refBrokerConsumer(leader)
  306. child.broker.input <- child
  307. return nil
  308. }
  309. func (child *partitionConsumer) chooseStartingOffset(offset int64) error {
  310. newestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetNewest)
  311. if err != nil {
  312. return err
  313. }
  314. oldestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetOldest)
  315. if err != nil {
  316. return err
  317. }
  318. switch {
  319. case offset == OffsetNewest:
  320. child.offset = newestOffset
  321. case offset == OffsetOldest:
  322. child.offset = oldestOffset
  323. case offset >= oldestOffset && offset <= newestOffset:
  324. child.offset = offset
  325. default:
  326. return ErrOffsetOutOfRange
  327. }
  328. return nil
  329. }
  330. func (child *partitionConsumer) Messages() <-chan *ConsumerMessage {
  331. return child.messages
  332. }
  333. func (child *partitionConsumer) Errors() <-chan *ConsumerError {
  334. return child.errors
  335. }
  336. func (child *partitionConsumer) AsyncClose() {
  337. // this triggers whatever broker owns this child to abandon it and close its trigger channel, which causes
  338. // the dispatcher to exit its loop, which removes it from the consumer then closes its 'messages' and
  339. // 'errors' channel (alternatively, if the child is already at the dispatcher for some reason, that will
  340. // also just close itself)
  341. child.closeOnce.Do(func() {
  342. close(child.dying)
  343. })
  344. }
  345. func (child *partitionConsumer) Close() error {
  346. child.AsyncClose()
  347. go withRecover(func() {
  348. for range child.messages {
  349. // drain
  350. }
  351. })
  352. var errors ConsumerErrors
  353. for err := range child.errors {
  354. errors = append(errors, err)
  355. }
  356. if len(errors) > 0 {
  357. return errors
  358. }
  359. return nil
  360. }
  361. func (child *partitionConsumer) HighWaterMarkOffset() int64 {
  362. return atomic.LoadInt64(&child.highWaterMarkOffset)
  363. }
  364. func (child *partitionConsumer) responseFeeder() {
  365. var msgs []*ConsumerMessage
  366. expiryTicker := time.NewTicker(child.conf.Consumer.MaxProcessingTime)
  367. firstAttempt := true
  368. feederLoop:
  369. for response := range child.feeder {
  370. msgs, child.responseResult = child.parseResponse(response)
  371. for i, msg := range msgs {
  372. messageSelect:
  373. select {
  374. case child.messages <- msg:
  375. firstAttempt = true
  376. case <-expiryTicker.C:
  377. if !firstAttempt {
  378. child.responseResult = errTimedOut
  379. child.broker.acks.Done()
  380. for _, msg = range msgs[i:] {
  381. child.messages <- msg
  382. }
  383. child.broker.input <- child
  384. continue feederLoop
  385. } else {
  386. // current message has not been sent, return to select
  387. // statement
  388. firstAttempt = false
  389. goto messageSelect
  390. }
  391. }
  392. }
  393. child.broker.acks.Done()
  394. }
  395. expiryTicker.Stop()
  396. close(child.messages)
  397. close(child.errors)
  398. }
  399. func (child *partitionConsumer) parseMessages(msgSet *MessageSet) ([]*ConsumerMessage, error) {
  400. var messages []*ConsumerMessage
  401. for _, msgBlock := range msgSet.Messages {
  402. for _, msg := range msgBlock.Messages() {
  403. offset := msg.Offset
  404. timestamp := msg.Msg.Timestamp
  405. if msg.Msg.Version >= 1 {
  406. baseOffset := msgBlock.Offset - msgBlock.Messages()[len(msgBlock.Messages())-1].Offset
  407. offset += baseOffset
  408. if msg.Msg.LogAppendTime {
  409. timestamp = msgBlock.Msg.Timestamp
  410. }
  411. }
  412. if offset < child.offset {
  413. continue
  414. }
  415. messages = append(messages, &ConsumerMessage{
  416. Topic: child.topic,
  417. Partition: child.partition,
  418. Key: msg.Msg.Key,
  419. Value: msg.Msg.Value,
  420. Offset: offset,
  421. Timestamp: timestamp,
  422. BlockTimestamp: msgBlock.Msg.Timestamp,
  423. })
  424. child.offset = offset + 1
  425. }
  426. }
  427. if len(messages) == 0 {
  428. child.offset++
  429. }
  430. return messages, nil
  431. }
  432. func (child *partitionConsumer) parseRecords(batch *RecordBatch) ([]*ConsumerMessage, error) {
  433. var messages []*ConsumerMessage
  434. for _, rec := range batch.Records {
  435. offset := batch.FirstOffset + rec.OffsetDelta
  436. if offset < child.offset {
  437. continue
  438. }
  439. timestamp := batch.FirstTimestamp.Add(rec.TimestampDelta)
  440. if batch.LogAppendTime {
  441. timestamp = batch.MaxTimestamp
  442. }
  443. messages = append(messages, &ConsumerMessage{
  444. Topic: child.topic,
  445. Partition: child.partition,
  446. Key: rec.Key,
  447. Value: rec.Value,
  448. Offset: offset,
  449. Timestamp: timestamp,
  450. Headers: rec.Headers,
  451. })
  452. child.offset = offset + 1
  453. }
  454. if len(messages) == 0 {
  455. child.offset++
  456. }
  457. return messages, nil
  458. }
  459. func (child *partitionConsumer) parseResponse(response *FetchResponse) ([]*ConsumerMessage, error) {
  460. block := response.GetBlock(child.topic, child.partition)
  461. if block == nil {
  462. return nil, ErrIncompleteResponse
  463. }
  464. if block.Err != ErrNoError {
  465. return nil, block.Err
  466. }
  467. nRecs, err := block.numRecords()
  468. if err != nil {
  469. return nil, err
  470. }
  471. if nRecs == 0 {
  472. partialTrailingMessage, err := block.isPartial()
  473. if err != nil {
  474. return nil, err
  475. }
  476. // We got no messages. If we got a trailing one then we need to ask for more data.
  477. // Otherwise we just poll again and wait for one to be produced...
  478. if partialTrailingMessage {
  479. if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize == child.conf.Consumer.Fetch.Max {
  480. // we can't ask for more data, we've hit the configured limit
  481. child.sendError(ErrMessageTooLarge)
  482. child.offset++ // skip this one so we can keep processing future messages
  483. } else {
  484. child.fetchSize *= 2
  485. if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize > child.conf.Consumer.Fetch.Max {
  486. child.fetchSize = child.conf.Consumer.Fetch.Max
  487. }
  488. }
  489. }
  490. return nil, nil
  491. }
  492. // we got messages, reset our fetch size in case it was increased for a previous request
  493. child.fetchSize = child.conf.Consumer.Fetch.Default
  494. atomic.StoreInt64(&child.highWaterMarkOffset, block.HighWaterMarkOffset)
  495. messages := []*ConsumerMessage{}
  496. for _, records := range block.RecordsSet {
  497. switch records.recordsType {
  498. case legacyRecords:
  499. messageSetMessages, err := child.parseMessages(records.MsgSet)
  500. if err != nil {
  501. return nil, err
  502. }
  503. messages = append(messages, messageSetMessages...)
  504. case defaultRecords:
  505. recordBatchMessages, err := child.parseRecords(records.RecordBatch)
  506. if err != nil {
  507. return nil, err
  508. }
  509. if control, err := records.isControl(); err != nil || control {
  510. continue
  511. }
  512. messages = append(messages, recordBatchMessages...)
  513. default:
  514. return nil, fmt.Errorf("unknown records type: %v", records.recordsType)
  515. }
  516. }
  517. return messages, nil
  518. }
  519. // brokerConsumer
  520. type brokerConsumer struct {
  521. consumer *consumer
  522. broker *Broker
  523. input chan *partitionConsumer
  524. newSubscriptions chan []*partitionConsumer
  525. wait chan none
  526. subscriptions map[*partitionConsumer]none
  527. acks sync.WaitGroup
  528. refs int
  529. }
  530. func (c *consumer) newBrokerConsumer(broker *Broker) *brokerConsumer {
  531. bc := &brokerConsumer{
  532. consumer: c,
  533. broker: broker,
  534. input: make(chan *partitionConsumer),
  535. newSubscriptions: make(chan []*partitionConsumer),
  536. wait: make(chan none),
  537. subscriptions: make(map[*partitionConsumer]none),
  538. refs: 0,
  539. }
  540. go withRecover(bc.subscriptionManager)
  541. go withRecover(bc.subscriptionConsumer)
  542. return bc
  543. }
  544. func (bc *brokerConsumer) subscriptionManager() {
  545. var buffer []*partitionConsumer
  546. // The subscriptionManager constantly accepts new subscriptions on `input` (even when the main subscriptionConsumer
  547. // goroutine is in the middle of a network request) and batches it up. The main worker goroutine picks
  548. // up a batch of new subscriptions between every network request by reading from `newSubscriptions`, so we give
  549. // it nil if no new subscriptions are available. We also write to `wait` only when new subscriptions is available,
  550. // so the main goroutine can block waiting for work if it has none.
  551. for {
  552. if len(buffer) > 0 {
  553. select {
  554. case event, ok := <-bc.input:
  555. if !ok {
  556. goto done
  557. }
  558. buffer = append(buffer, event)
  559. case bc.newSubscriptions <- buffer:
  560. buffer = nil
  561. case bc.wait <- none{}:
  562. }
  563. } else {
  564. select {
  565. case event, ok := <-bc.input:
  566. if !ok {
  567. goto done
  568. }
  569. buffer = append(buffer, event)
  570. case bc.newSubscriptions <- nil:
  571. }
  572. }
  573. }
  574. done:
  575. close(bc.wait)
  576. if len(buffer) > 0 {
  577. bc.newSubscriptions <- buffer
  578. }
  579. close(bc.newSubscriptions)
  580. }
  581. func (bc *brokerConsumer) subscriptionConsumer() {
  582. <-bc.wait // wait for our first piece of work
  583. // the subscriptionConsumer ensures we will get nil right away if no new subscriptions is available
  584. for newSubscriptions := range bc.newSubscriptions {
  585. bc.updateSubscriptions(newSubscriptions)
  586. if len(bc.subscriptions) == 0 {
  587. // We're about to be shut down or we're about to receive more subscriptions.
  588. // Either way, the signal just hasn't propagated to our goroutine yet.
  589. <-bc.wait
  590. continue
  591. }
  592. response, err := bc.fetchNewMessages()
  593. if err != nil {
  594. Logger.Printf("consumer/broker/%d disconnecting due to error processing FetchRequest: %s\n", bc.broker.ID(), err)
  595. bc.abort(err)
  596. return
  597. }
  598. bc.acks.Add(len(bc.subscriptions))
  599. for child := range bc.subscriptions {
  600. child.feeder <- response
  601. }
  602. bc.acks.Wait()
  603. bc.handleResponses()
  604. }
  605. }
  606. func (bc *brokerConsumer) updateSubscriptions(newSubscriptions []*partitionConsumer) {
  607. for _, child := range newSubscriptions {
  608. bc.subscriptions[child] = none{}
  609. Logger.Printf("consumer/broker/%d added subscription to %s/%d\n", bc.broker.ID(), child.topic, child.partition)
  610. }
  611. for child := range bc.subscriptions {
  612. select {
  613. case <-child.dying:
  614. Logger.Printf("consumer/broker/%d closed dead subscription to %s/%d\n", bc.broker.ID(), child.topic, child.partition)
  615. close(child.trigger)
  616. delete(bc.subscriptions, child)
  617. default:
  618. break
  619. }
  620. }
  621. }
  622. func (bc *brokerConsumer) handleResponses() {
  623. // handles the response codes left for us by our subscriptions, and abandons ones that have been closed
  624. for child := range bc.subscriptions {
  625. result := child.responseResult
  626. child.responseResult = nil
  627. switch result {
  628. case nil:
  629. break
  630. case errTimedOut:
  631. Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because consuming was taking too long\n",
  632. bc.broker.ID(), child.topic, child.partition)
  633. delete(bc.subscriptions, child)
  634. case ErrOffsetOutOfRange:
  635. // there's no point in retrying this it will just fail the same way again
  636. // shut it down and force the user to choose what to do
  637. child.sendError(result)
  638. Logger.Printf("consumer/%s/%d shutting down because %s\n", child.topic, child.partition, result)
  639. close(child.trigger)
  640. delete(bc.subscriptions, child)
  641. case ErrUnknownTopicOrPartition, ErrNotLeaderForPartition, ErrLeaderNotAvailable, ErrReplicaNotAvailable:
  642. // not an error, but does need redispatching
  643. Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n",
  644. bc.broker.ID(), child.topic, child.partition, result)
  645. child.trigger <- none{}
  646. delete(bc.subscriptions, child)
  647. default:
  648. // dunno, tell the user and try redispatching
  649. child.sendError(result)
  650. Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n",
  651. bc.broker.ID(), child.topic, child.partition, result)
  652. child.trigger <- none{}
  653. delete(bc.subscriptions, child)
  654. }
  655. }
  656. }
  657. func (bc *brokerConsumer) abort(err error) {
  658. bc.consumer.abandonBrokerConsumer(bc)
  659. _ = bc.broker.Close() // we don't care about the error this might return, we already have one
  660. for child := range bc.subscriptions {
  661. child.sendError(err)
  662. child.trigger <- none{}
  663. }
  664. for newSubscriptions := range bc.newSubscriptions {
  665. if len(newSubscriptions) == 0 {
  666. <-bc.wait
  667. continue
  668. }
  669. for _, child := range newSubscriptions {
  670. child.sendError(err)
  671. child.trigger <- none{}
  672. }
  673. }
  674. }
  675. func (bc *brokerConsumer) fetchNewMessages() (*FetchResponse, error) {
  676. request := &FetchRequest{
  677. MinBytes: bc.consumer.conf.Consumer.Fetch.Min,
  678. MaxWaitTime: int32(bc.consumer.conf.Consumer.MaxWaitTime / time.Millisecond),
  679. }
  680. if bc.consumer.conf.Version.IsAtLeast(V0_9_0_0) {
  681. request.Version = 1
  682. }
  683. if bc.consumer.conf.Version.IsAtLeast(V0_10_0_0) {
  684. request.Version = 2
  685. }
  686. if bc.consumer.conf.Version.IsAtLeast(V0_10_1_0) {
  687. request.Version = 3
  688. request.MaxBytes = MaxResponseSize
  689. }
  690. if bc.consumer.conf.Version.IsAtLeast(V0_11_0_0) {
  691. request.Version = 4
  692. request.Isolation = ReadUncommitted // We don't support yet transactions.
  693. }
  694. for child := range bc.subscriptions {
  695. request.AddBlock(child.topic, child.partition, child.offset, child.fetchSize)
  696. }
  697. return bc.broker.Fetch(request)
  698. }