consumer.go 28 KB

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