consumer.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. package sarama
  2. import (
  3. "fmt"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. )
  8. // ConsumerMessage encapsulates a Kafka message returned by the consumer.
  9. type ConsumerMessage struct {
  10. Key, Value []byte
  11. Topic string
  12. Partition int32
  13. Offset int64
  14. }
  15. // ConsumerError is what is provided to the user when an error occurs.
  16. // It wraps an error and includes the topic and partition.
  17. type ConsumerError struct {
  18. Topic string
  19. Partition int32
  20. Err error
  21. }
  22. func (ce ConsumerError) Error() string {
  23. return fmt.Sprintf("kafka: error while consuming %s/%d: %s", ce.Topic, ce.Partition, ce.Err)
  24. }
  25. // ConsumerErrors is a type that wraps a batch of errors and implements the Error interface.
  26. // It can be returned from the PartitionConsumer's Close methods to avoid the need to manually drain errors
  27. // when stopping.
  28. type ConsumerErrors []*ConsumerError
  29. func (ce ConsumerErrors) Error() string {
  30. return fmt.Sprintf("kafka: %d errors while consuming", len(ce))
  31. }
  32. // Consumer manages PartitionConsumers which process Kafka messages from brokers. You MUST call Close()
  33. // on a consumer to avoid leaks, it will not be garbage-collected automatically when it passes out of
  34. // scope.
  35. type Consumer interface {
  36. // Topics returns the set of available topics as retrieved from the cluster metadata.
  37. // This method is the same as Client.Topics(), and is provided for convenience.
  38. Topics() ([]string, error)
  39. // Partitions returns the sorted list of all partition IDs for the given topic.
  40. // This method is the same as Client.Pertitions(), and is provided for convenience.
  41. Partitions(topic string) ([]int32, error)
  42. // ConsumePartition creates a PartitionConsumer on the given topic/partition with the given offset. It will
  43. // return an error if this Consumer is already consuming on the given topic/partition. Offset can be a
  44. // literal offset, or OffsetNewest or OffsetOldest
  45. ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error)
  46. // Close shuts down the consumer. It must be called after all child PartitionConsumers have already been closed.
  47. Close() error
  48. }
  49. type consumer struct {
  50. client Client
  51. conf *Config
  52. ownClient bool
  53. lock sync.Mutex
  54. children map[string]map[int32]*partitionConsumer
  55. brokerConsumers map[*Broker]*brokerConsumer
  56. }
  57. // NewConsumer creates a new consumer using the given broker addresses and configuration.
  58. func NewConsumer(addrs []string, config *Config) (Consumer, error) {
  59. client, err := NewClient(addrs, config)
  60. if err != nil {
  61. return nil, err
  62. }
  63. c, err := NewConsumerFromClient(client)
  64. if err != nil {
  65. return nil, err
  66. }
  67. c.(*consumer).ownClient = true
  68. return c, nil
  69. }
  70. // NewConsumerFromClient creates a new consumer using the given client. It is still
  71. // necessary to call Close() on the underlying client when shutting down this consumer.
  72. func NewConsumerFromClient(client Client) (Consumer, error) {
  73. // Check that we are not dealing with a closed Client before processing any other arguments
  74. if client.Closed() {
  75. return nil, ErrClosedClient
  76. }
  77. c := &consumer{
  78. client: client,
  79. conf: client.Config(),
  80. children: make(map[string]map[int32]*partitionConsumer),
  81. brokerConsumers: make(map[*Broker]*brokerConsumer),
  82. }
  83. return c, nil
  84. }
  85. func (c *consumer) Close() error {
  86. if c.ownClient {
  87. return c.client.Close()
  88. }
  89. return nil
  90. }
  91. func (c *consumer) Topics() ([]string, error) {
  92. return c.client.Topics()
  93. }
  94. func (c *consumer) Partitions(topic string) ([]int32, error) {
  95. return c.client.Partitions(topic)
  96. }
  97. func (c *consumer) ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error) {
  98. child := &partitionConsumer{
  99. consumer: c,
  100. conf: c.conf,
  101. topic: topic,
  102. partition: partition,
  103. messages: make(chan *ConsumerMessage, c.conf.ChannelBufferSize),
  104. errors: make(chan *ConsumerError, c.conf.ChannelBufferSize),
  105. trigger: make(chan none, 1),
  106. dying: make(chan none),
  107. fetchSize: c.conf.Consumer.Fetch.Default,
  108. }
  109. if err := child.chooseStartingOffset(offset); err != nil {
  110. return nil, err
  111. }
  112. var leader *Broker
  113. var err error
  114. if leader, err = c.client.Leader(child.topic, child.partition); err != nil {
  115. return nil, err
  116. }
  117. if err := c.addChild(child); err != nil {
  118. return nil, err
  119. }
  120. go withRecover(child.dispatcher)
  121. child.broker = c.refBrokerConsumer(leader)
  122. child.broker.input <- child
  123. return child, nil
  124. }
  125. func (c *consumer) addChild(child *partitionConsumer) error {
  126. c.lock.Lock()
  127. defer c.lock.Unlock()
  128. topicChildren := c.children[child.topic]
  129. if topicChildren == nil {
  130. topicChildren = make(map[int32]*partitionConsumer)
  131. c.children[child.topic] = topicChildren
  132. }
  133. if topicChildren[child.partition] != nil {
  134. return ConfigurationError("That topic/partition is already being consumed")
  135. }
  136. topicChildren[child.partition] = child
  137. return nil
  138. }
  139. func (c *consumer) removeChild(child *partitionConsumer) {
  140. c.lock.Lock()
  141. defer c.lock.Unlock()
  142. delete(c.children[child.topic], child.partition)
  143. }
  144. func (c *consumer) refBrokerConsumer(broker *Broker) *brokerConsumer {
  145. c.lock.Lock()
  146. defer c.lock.Unlock()
  147. bc := c.brokerConsumers[broker]
  148. if bc == nil {
  149. bc = c.newBrokerConsumer(broker)
  150. c.brokerConsumers[broker] = bc
  151. }
  152. bc.refs++
  153. return bc
  154. }
  155. func (c *consumer) unrefBrokerConsumer(brokerWorker *brokerConsumer) {
  156. c.lock.Lock()
  157. defer c.lock.Unlock()
  158. brokerWorker.refs--
  159. if brokerWorker.refs == 0 {
  160. close(brokerWorker.input)
  161. if c.brokerConsumers[brokerWorker.broker] == brokerWorker {
  162. delete(c.brokerConsumers, brokerWorker.broker)
  163. }
  164. }
  165. }
  166. func (c *consumer) abandonBrokerConsumer(brokerWorker *brokerConsumer) {
  167. c.lock.Lock()
  168. defer c.lock.Unlock()
  169. delete(c.brokerConsumers, brokerWorker.broker)
  170. }
  171. // PartitionConsumer
  172. // PartitionConsumer processes Kafka messages from a given topic and partition. You MUST call Close()
  173. // or AsyncClose() on a PartitionConsumer to avoid leaks, it will not be garbage-collected automatically
  174. // when it passes out of scope.
  175. //
  176. // The simplest way of using a PartitionConsumer is to loop over its Messages channel using a for/range
  177. // loop. The PartitionConsumer will only stop itself in one case: when the offset being consumed is reported
  178. // as out of range by the brokers. In this case you should decide what you want to do (try a different offset,
  179. // notify a human, etc) and handle it appropriately. For all other error cases, it will just keep retrying.
  180. // By default, it logs these errors to sarama.Logger; if you want to be notified directly of all errors, set
  181. // your config's Consumer.Return.Errors to true and read from the Errors channel, using a select statement
  182. // or a separate goroutine. Check out the Consumer examples to see implementations of these different approaches.
  183. type PartitionConsumer interface {
  184. // AsyncClose initiates a shutdown of the PartitionConsumer. This method will return immediately,
  185. // after which you should wait until the 'messages' and 'errors' channel are drained.
  186. // It is required to call this function, or Close before a consumer object passes out of scope,
  187. // as it will otherwise leak memory. You must call this before calling Close on the underlying
  188. // client.
  189. AsyncClose()
  190. // Close stops the PartitionConsumer from fetching messages. It is required to call this function
  191. // (or AsyncClose) before a consumer object passes out of scope, as it will otherwise leak memory. You must
  192. // call this before calling Close on the underlying client.
  193. Close() error
  194. // Messages returns the read channel for the messages that are returned by the broker.
  195. Messages() <-chan *ConsumerMessage
  196. // Errors returns a read channel of errors that occured during consuming, if enabled. By default,
  197. // errors are logged and not returned over this channel. If you want to implement any custom errpr
  198. // handling, set your config's Consumer.Return.Errors setting to true, and read from this channel.
  199. Errors() <-chan *ConsumerError
  200. // HighWaterMarkOffset returns the high water mark offset of the partition, i.e. the offset that will
  201. // be used for the next message that will be produced. You can use this to determine how far behind
  202. // the processing is.
  203. HighWaterMarkOffset() int64
  204. }
  205. type partitionConsumer struct {
  206. consumer *consumer
  207. conf *Config
  208. topic string
  209. partition int32
  210. broker *brokerConsumer
  211. messages chan *ConsumerMessage
  212. errors chan *ConsumerError
  213. trigger, dying chan none
  214. fetchSize int32
  215. offset int64
  216. highWaterMarkOffset int64
  217. }
  218. func (child *partitionConsumer) sendError(err error) {
  219. cErr := &ConsumerError{
  220. Topic: child.topic,
  221. Partition: child.partition,
  222. Err: err,
  223. }
  224. if child.conf.Consumer.Return.Errors {
  225. child.errors <- cErr
  226. } else {
  227. Logger.Println(cErr)
  228. }
  229. }
  230. func (child *partitionConsumer) dispatcher() {
  231. for _ = range child.trigger {
  232. select {
  233. case <-child.dying:
  234. close(child.trigger)
  235. case <-time.After(child.conf.Consumer.Retry.Backoff):
  236. if child.broker != nil {
  237. child.consumer.unrefBrokerConsumer(child.broker)
  238. child.broker = nil
  239. }
  240. Logger.Printf("consumer/%s/%d finding new broker\n", child.topic, child.partition)
  241. if err := child.dispatch(); err != nil {
  242. child.sendError(err)
  243. child.trigger <- none{}
  244. }
  245. }
  246. }
  247. if child.broker != nil {
  248. child.consumer.unrefBrokerConsumer(child.broker)
  249. }
  250. child.consumer.removeChild(child)
  251. close(child.messages)
  252. close(child.errors)
  253. }
  254. func (child *partitionConsumer) dispatch() error {
  255. if err := child.consumer.client.RefreshMetadata(child.topic); err != nil {
  256. return err
  257. }
  258. var leader *Broker
  259. var err error
  260. if leader, err = child.consumer.client.Leader(child.topic, child.partition); err != nil {
  261. return err
  262. }
  263. child.broker = child.consumer.refBrokerConsumer(leader)
  264. child.broker.input <- child
  265. return nil
  266. }
  267. func (child *partitionConsumer) chooseStartingOffset(offset int64) error {
  268. newestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetNewest)
  269. if err != nil {
  270. return err
  271. }
  272. oldestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetOldest)
  273. if err != nil {
  274. return err
  275. }
  276. switch {
  277. case offset == OffsetNewest:
  278. child.offset = newestOffset
  279. case offset == OffsetOldest:
  280. child.offset = oldestOffset
  281. case offset >= oldestOffset && offset <= newestOffset:
  282. child.offset = offset
  283. default:
  284. return ErrOffsetOutOfRange
  285. }
  286. return nil
  287. }
  288. func (child *partitionConsumer) Messages() <-chan *ConsumerMessage {
  289. return child.messages
  290. }
  291. func (child *partitionConsumer) Errors() <-chan *ConsumerError {
  292. return child.errors
  293. }
  294. func (child *partitionConsumer) AsyncClose() {
  295. // this triggers whatever worker owns this child to abandon it and close its trigger channel, which causes
  296. // the dispatcher to exit its loop, which removes it from the consumer then closes its 'messages' and
  297. // 'errors' channel (alternatively, if the child is already at the dispatcher for some reason, that will
  298. // also just close itself)
  299. close(child.dying)
  300. }
  301. func (child *partitionConsumer) Close() error {
  302. child.AsyncClose()
  303. go withRecover(func() {
  304. for _ = range child.messages {
  305. // drain
  306. }
  307. })
  308. var errors ConsumerErrors
  309. for err := range child.errors {
  310. errors = append(errors, err)
  311. }
  312. if len(errors) > 0 {
  313. return errors
  314. }
  315. return nil
  316. }
  317. func (child *partitionConsumer) HighWaterMarkOffset() int64 {
  318. return atomic.LoadInt64(&child.highWaterMarkOffset)
  319. }
  320. func (child *partitionConsumer) handleResponse(response *FetchResponse) error {
  321. block := response.GetBlock(child.topic, child.partition)
  322. if block == nil {
  323. return ErrIncompleteResponse
  324. }
  325. if block.Err != ErrNoError {
  326. return block.Err
  327. }
  328. if len(block.MsgSet.Messages) == 0 {
  329. // We got no messages. If we got a trailing one then we need to ask for more data.
  330. // Otherwise we just poll again and wait for one to be produced...
  331. if block.MsgSet.PartialTrailingMessage {
  332. if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize == child.conf.Consumer.Fetch.Max {
  333. // we can't ask for more data, we've hit the configured limit
  334. child.sendError(ErrMessageTooLarge)
  335. child.offset++ // skip this one so we can keep processing future messages
  336. } else {
  337. child.fetchSize *= 2
  338. if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize > child.conf.Consumer.Fetch.Max {
  339. child.fetchSize = child.conf.Consumer.Fetch.Max
  340. }
  341. }
  342. }
  343. return nil
  344. }
  345. // we got messages, reset our fetch size in case it was increased for a previous request
  346. child.fetchSize = child.conf.Consumer.Fetch.Default
  347. atomic.StoreInt64(&child.highWaterMarkOffset, block.HighWaterMarkOffset)
  348. incomplete := false
  349. atLeastOne := false
  350. prelude := true
  351. for _, msgBlock := range block.MsgSet.Messages {
  352. for _, msg := range msgBlock.Messages() {
  353. if prelude && msg.Offset < child.offset {
  354. continue
  355. }
  356. prelude = false
  357. if msg.Offset >= child.offset {
  358. atLeastOne = true
  359. child.messages <- &ConsumerMessage{
  360. Topic: child.topic,
  361. Partition: child.partition,
  362. Key: msg.Msg.Key,
  363. Value: msg.Msg.Value,
  364. Offset: msg.Offset,
  365. }
  366. child.offset = msg.Offset + 1
  367. } else {
  368. incomplete = true
  369. }
  370. }
  371. }
  372. if incomplete || !atLeastOne {
  373. return ErrIncompleteResponse
  374. }
  375. return nil
  376. }
  377. // brokerConsumer
  378. type brokerConsumer struct {
  379. consumer *consumer
  380. broker *Broker
  381. input chan *partitionConsumer
  382. newSubscriptions chan []*partitionConsumer
  383. wait chan none
  384. subscriptions map[*partitionConsumer]none
  385. refs int
  386. }
  387. func (c *consumer) newBrokerConsumer(broker *Broker) *brokerConsumer {
  388. bc := &brokerConsumer{
  389. consumer: c,
  390. broker: broker,
  391. input: make(chan *partitionConsumer),
  392. newSubscriptions: make(chan []*partitionConsumer),
  393. wait: make(chan none),
  394. subscriptions: make(map[*partitionConsumer]none),
  395. refs: 0,
  396. }
  397. go withRecover(bc.subscriptionManager)
  398. go withRecover(bc.subscriptionConsumer)
  399. return bc
  400. }
  401. func (bc *brokerConsumer) subscriptionManager() {
  402. var buffer []*partitionConsumer
  403. // The subscriptionManager constantly accepts new subscriptions on `input` (even when the main subscriptionConsumer
  404. // goroutine is in the middle of a network request) and batches it up. The main worker goroutine picks
  405. // up a batch of new subscriptions between every network request by reading from `newSubscriptions`, so we give
  406. // it nil if no new subscriptions are available. We also write to `wait` only when new subscriptions is available,
  407. // so the main goroutine can block waiting for work if it has none.
  408. for {
  409. if len(buffer) > 0 {
  410. select {
  411. case event, ok := <-bc.input:
  412. if !ok {
  413. goto done
  414. }
  415. buffer = append(buffer, event)
  416. case bc.newSubscriptions <- buffer:
  417. buffer = nil
  418. case bc.wait <- none{}:
  419. }
  420. } else {
  421. select {
  422. case event, ok := <-bc.input:
  423. if !ok {
  424. goto done
  425. }
  426. buffer = append(buffer, event)
  427. case bc.newSubscriptions <- nil:
  428. }
  429. }
  430. }
  431. done:
  432. close(bc.wait)
  433. if len(buffer) > 0 {
  434. bc.newSubscriptions <- buffer
  435. }
  436. close(bc.newSubscriptions)
  437. }
  438. func (bc *brokerConsumer) subscriptionConsumer() {
  439. <-bc.wait // wait for our first piece of work
  440. // the subscriptionConsumer ensures we will get nil right away if no new subscriptions is available
  441. for newSubscriptions := range bc.newSubscriptions {
  442. bc.updateSubscriptionCache(newSubscriptions)
  443. if len(bc.subscriptions) == 0 {
  444. // We're about to be shut down or we're about to receive more subscriptions.
  445. // Either way, the signal just hasn't propagated to our goroutine yet.
  446. <-bc.wait
  447. continue
  448. }
  449. response, err := bc.fetchNewMessages()
  450. if err != nil {
  451. Logger.Printf("consumer/broker/%d disconnecting due to error processing FetchRequest: %s\n", bc.broker.ID(), err)
  452. bc.abort(err)
  453. return
  454. }
  455. for child := range bc.subscriptions {
  456. if err := child.handleResponse(response); err != nil {
  457. switch err {
  458. case ErrOffsetOutOfRange:
  459. // there's no point in retrying this it will just fail the same way again
  460. // so shut it down and force the user to choose what to do
  461. child.AsyncClose()
  462. fallthrough
  463. default:
  464. child.sendError(err)
  465. fallthrough
  466. case ErrUnknownTopicOrPartition, ErrNotLeaderForPartition, ErrLeaderNotAvailable:
  467. // these three are not fatal errors, but do require redispatching
  468. child.trigger <- none{}
  469. delete(bc.subscriptions, child)
  470. Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n", bc.broker.ID(), child.topic, child.partition, err)
  471. }
  472. }
  473. }
  474. }
  475. }
  476. func (bc *brokerConsumer) updateSubscriptionCache(newSubscriptions []*partitionConsumer) {
  477. // take new subscriptions, and abandon subscriptions that have been closed
  478. for _, child := range newSubscriptions {
  479. bc.subscriptions[child] = none{}
  480. Logger.Printf("consumer/broker/%d added subscription to %s/%d\n", bc.broker.ID(), child.topic, child.partition)
  481. }
  482. for child := range bc.subscriptions {
  483. select {
  484. case <-child.dying:
  485. close(child.trigger)
  486. delete(bc.subscriptions, child)
  487. Logger.Printf("consumer/broker/%d closed dead subscription to %s/%d\n", bc.broker.ID(), child.topic, child.partition)
  488. default:
  489. }
  490. }
  491. }
  492. func (bc *brokerConsumer) abort(err error) {
  493. bc.consumer.abandonBrokerConsumer(bc)
  494. _ = bc.broker.Close() // we don't care about the error this might return, we already have one
  495. for child := range bc.subscriptions {
  496. child.sendError(err)
  497. child.trigger <- none{}
  498. }
  499. for newSubscription := range bc.newSubscriptions {
  500. for _, child := range newSubscription {
  501. child.sendError(err)
  502. child.trigger <- none{}
  503. }
  504. }
  505. }
  506. func (bc *brokerConsumer) fetchNewMessages() (*FetchResponse, error) {
  507. request := &FetchRequest{
  508. MinBytes: bc.consumer.conf.Consumer.Fetch.Min,
  509. MaxWaitTime: int32(bc.consumer.conf.Consumer.MaxWaitTime / time.Millisecond),
  510. }
  511. for child := range bc.subscriptions {
  512. request.AddBlock(child.topic, child.partition, child.offset, child.fetchSize)
  513. }
  514. return bc.broker.Fetch(request)
  515. }