consumer.go 28 KB

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