consumer.go 22 KB

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