consumer.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. package sarama
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. )
  7. // OffsetMethod is passed in ConsumerConfig to tell the consumer how to determine the starting offset.
  8. type OffsetMethod int
  9. const (
  10. // OffsetMethodNewest causes the consumer to start at the most recent available offset, as
  11. // determined by querying the broker.
  12. OffsetMethodNewest OffsetMethod = iota
  13. // OffsetMethodOldest causes the consumer to start at the oldest available offset, as
  14. // determined by querying the broker.
  15. OffsetMethodOldest
  16. // OffsetMethodManual causes the consumer to interpret the OffsetValue in the ConsumerConfig as the
  17. // offset at which to start, allowing the user to manually specify their desired starting offset.
  18. OffsetMethodManual
  19. )
  20. // ConsumerConfig is used to pass multiple configuration options to NewConsumer.
  21. type ConsumerConfig struct {
  22. // The minimum amount of data to fetch in a request - the broker will wait until at least this many bytes are available.
  23. // The default is 1, as 0 causes the consumer to spin when no messages are available.
  24. MinFetchSize int32
  25. // The maximum amount of time the broker will wait for MinFetchSize bytes to become available before it
  26. // returns fewer than that anyways. The default is 250ms, since 0 causes the consumer to spin when no events are available.
  27. // 100-500ms is a reasonable range for most cases. Kafka only supports precision up to milliseconds; nanoseconds will be truncated.
  28. MaxWaitTime time.Duration
  29. }
  30. // NewConsumerConfig creates a ConsumerConfig instance with sane defaults.
  31. func NewConsumerConfig() *ConsumerConfig {
  32. return &ConsumerConfig{
  33. MinFetchSize: 1,
  34. MaxWaitTime: 250 * time.Millisecond,
  35. }
  36. }
  37. // Validate checks a ConsumerConfig instance. It will return a
  38. // ConfigurationError if the specified value doesn't make sense.
  39. func (config *ConsumerConfig) Validate() error {
  40. if config.MinFetchSize <= 0 {
  41. return ConfigurationError("Invalid MinFetchSize")
  42. }
  43. if config.MaxWaitTime < 1*time.Millisecond {
  44. return ConfigurationError("Invalid MaxWaitTime, it needs to be at least 1ms")
  45. } else if config.MaxWaitTime < 100*time.Millisecond {
  46. Logger.Println("ConsumerConfig.MaxWaitTime is very low, which can cause high CPU and network usage. See documentation for details.")
  47. } else if config.MaxWaitTime%time.Millisecond != 0 {
  48. Logger.Println("ConsumerConfig.MaxWaitTime only supports millisecond precision; nanoseconds will be truncated.")
  49. }
  50. return nil
  51. }
  52. // PartitionConsumerConfig is used to pass multiple configuration options to AddPartition
  53. type PartitionConsumerConfig struct {
  54. // The default (maximum) amount of data to fetch from the broker in each request. The default is 32768 bytes.
  55. DefaultFetchSize int32
  56. // The maximum permittable message size - messages larger than this will return MessageTooLarge. The default of 0 is
  57. // treated as no limit.
  58. MaxMessageSize int32
  59. // The method used to determine at which offset to begin consuming messages. The default is to start at the most recent message.
  60. OffsetMethod OffsetMethod
  61. // Interpreted differently according to the value of OffsetMethod.
  62. OffsetValue int64
  63. // The number of events to buffer in the Events channel. Having this non-zero permits the
  64. // consumer to continue fetching messages in the background while client code consumes events,
  65. // greatly improving throughput. The default is 64.
  66. EventBufferSize int
  67. }
  68. // NewPartitionConsumerConfig creates a PartitionConsumerConfig with sane defaults.
  69. func NewPartitionConsumerConfig() *PartitionConsumerConfig {
  70. return &PartitionConsumerConfig{
  71. DefaultFetchSize: 32768,
  72. EventBufferSize: 64,
  73. }
  74. }
  75. // Validate checks a PartitionConsumerConfig instance. It will return a
  76. // ConfigurationError if the specified value doesn't make sense.
  77. func (config *PartitionConsumerConfig) Validate() error {
  78. if config.DefaultFetchSize <= 0 {
  79. return ConfigurationError("Invalid DefaultFetchSize")
  80. }
  81. if config.MaxMessageSize < 0 {
  82. return ConfigurationError("Invalid MaxMessageSize")
  83. }
  84. if config.EventBufferSize < 0 {
  85. return ConfigurationError("Invalid EventBufferSize")
  86. }
  87. return nil
  88. }
  89. // ConsumerEvent is what is provided to the user when an event occurs. It is either an error (in which case Err is non-nil) or
  90. // a message (in which case Err is nil and Offset, Key, and Value are set). Topic and Partition are always set.
  91. type ConsumerEvent struct {
  92. Key, Value []byte
  93. Topic string
  94. Partition int32
  95. Offset int64
  96. Err error
  97. }
  98. // ConsumeErrors is a type that wraps a batch of "ConsumerEvent"s and implements the Error interface.
  99. // It can be returned from the PartitionConsumer's Close methods to avoid the need to manually drain errors
  100. // when stopping.
  101. type ConsumeErrors []*ConsumerEvent
  102. func (ce ConsumeErrors) Error() string {
  103. return fmt.Sprintf("kafka: %d errors when consuming", len(ce))
  104. }
  105. // Consumer manages PartitionConsumers which process Kafka messages from brokers.
  106. type Consumer struct {
  107. client *Client
  108. config ConsumerConfig
  109. lock sync.Mutex
  110. children map[string]map[int32]*PartitionConsumer
  111. brokerConsumers map[*Broker]*brokerConsumer
  112. }
  113. // NewConsumer creates a new consumer attached to the given client.
  114. func NewConsumer(client *Client, config *ConsumerConfig) (*Consumer, error) {
  115. // Check that we are not dealing with a closed Client before processing any other arguments
  116. if client.Closed() {
  117. return nil, ClosedClient
  118. }
  119. if config == nil {
  120. config = NewConsumerConfig()
  121. }
  122. if err := config.Validate(); err != nil {
  123. return nil, err
  124. }
  125. c := &Consumer{
  126. client: client,
  127. config: *config,
  128. children: make(map[string]map[int32]*PartitionConsumer),
  129. brokerConsumers: make(map[*Broker]*brokerConsumer),
  130. }
  131. return c, nil
  132. }
  133. // ConsumePartition creates a PartitionConsumer on the given topic/partition with the given configuration. It will
  134. // return an error if this Consumer is already consuming on the given topic/partition.
  135. func (c *Consumer) ConsumePartition(topic string, partition int32, config *PartitionConsumerConfig) (*PartitionConsumer, error) {
  136. if config == nil {
  137. config = NewPartitionConsumerConfig()
  138. }
  139. if err := config.Validate(); err != nil {
  140. return nil, err
  141. }
  142. child := &PartitionConsumer{
  143. consumer: c,
  144. config: *config,
  145. topic: topic,
  146. partition: partition,
  147. events: make(chan *ConsumerEvent, config.EventBufferSize),
  148. trigger: make(chan none, 1),
  149. dying: make(chan none),
  150. fetchSize: config.DefaultFetchSize,
  151. }
  152. if err := child.chooseStartingOffset(); err != nil {
  153. return nil, err
  154. }
  155. if leader, err := c.client.Leader(child.topic, child.partition); err != nil {
  156. return nil, err
  157. } else {
  158. child.broker = leader
  159. }
  160. if err := c.addChild(child); err != nil {
  161. return nil, err
  162. }
  163. go withRecover(child.dispatcher)
  164. brokerWorker := c.refBrokerConsumer(child.broker)
  165. brokerWorker.input <- child
  166. return child, nil
  167. }
  168. func (c *Consumer) addChild(child *PartitionConsumer) error {
  169. c.lock.Lock()
  170. defer c.lock.Unlock()
  171. topicChildren := c.children[child.topic]
  172. if topicChildren == nil {
  173. topicChildren = make(map[int32]*PartitionConsumer)
  174. c.children[child.topic] = topicChildren
  175. }
  176. if topicChildren[child.partition] != nil {
  177. return ConfigurationError("That topic/partition is already being consumed")
  178. }
  179. topicChildren[child.partition] = child
  180. return nil
  181. }
  182. func (c *Consumer) removeChild(child *PartitionConsumer) {
  183. c.lock.Lock()
  184. defer c.lock.Unlock()
  185. delete(c.children[child.topic], child.partition)
  186. }
  187. func (c *Consumer) refBrokerConsumer(broker *Broker) *brokerConsumer {
  188. c.lock.Lock()
  189. defer c.lock.Unlock()
  190. brokerWorker := c.brokerConsumers[broker]
  191. if brokerWorker == nil {
  192. brokerWorker = &brokerConsumer{
  193. consumer: c,
  194. broker: broker,
  195. input: make(chan *PartitionConsumer),
  196. newSubscriptions: make(chan []*PartitionConsumer),
  197. wait: make(chan none),
  198. subscriptions: make(map[*PartitionConsumer]none),
  199. refs: 1,
  200. }
  201. go withRecover(brokerWorker.subscriptionManager)
  202. go withRecover(brokerWorker.subscriptionConsumer)
  203. c.brokerConsumers[broker] = brokerWorker
  204. } else {
  205. brokerWorker.refs++
  206. }
  207. return brokerWorker
  208. }
  209. func (c *Consumer) unrefBrokerConsumer(broker *Broker) {
  210. c.lock.Lock()
  211. defer c.lock.Unlock()
  212. brokerWorker := c.brokerConsumers[broker]
  213. brokerWorker.refs--
  214. if brokerWorker.refs == 0 {
  215. close(brokerWorker.input)
  216. delete(c.brokerConsumers, broker)
  217. }
  218. }
  219. // PartitionConsumer
  220. // PartitionConsumer processes Kafka messages from a given topic and partition. You MUST call Close()
  221. // on a consumer to avoid leaks, it will not be garbage-collected automatically when it passes out of
  222. // scope (this is in addition to calling Close on the underlying consumer's client, which is still necessary).
  223. type PartitionConsumer struct {
  224. consumer *Consumer
  225. config PartitionConsumerConfig
  226. topic string
  227. partition int32
  228. broker *Broker
  229. events chan *ConsumerEvent
  230. trigger, dying chan none
  231. fetchSize int32
  232. offset int64
  233. }
  234. func (child *PartitionConsumer) sendError(err error) {
  235. child.events <- &ConsumerEvent{
  236. Topic: child.topic,
  237. Partition: child.partition,
  238. Err: err,
  239. }
  240. }
  241. func (child *PartitionConsumer) dispatcher() {
  242. for _ = range child.trigger {
  243. select {
  244. case <-child.dying:
  245. close(child.trigger)
  246. default:
  247. if child.broker != nil {
  248. child.consumer.unrefBrokerConsumer(child.broker)
  249. child.broker = nil
  250. }
  251. if err := child.dispatch(); err != nil {
  252. child.sendError(err)
  253. child.trigger <- none{}
  254. // there's no point in trying again *right* away
  255. select {
  256. case <-child.dying:
  257. close(child.trigger)
  258. case <-time.After(10 * time.Second):
  259. }
  260. }
  261. }
  262. }
  263. if child.broker != nil {
  264. child.consumer.unrefBrokerConsumer(child.broker)
  265. }
  266. child.consumer.removeChild(child)
  267. close(child.events)
  268. }
  269. func (child *PartitionConsumer) dispatch() error {
  270. if err := child.consumer.client.RefreshTopicMetadata(child.topic); err != nil {
  271. return err
  272. }
  273. if leader, err := child.consumer.client.Leader(child.topic, child.partition); err != nil {
  274. return err
  275. } else {
  276. child.broker = leader
  277. }
  278. brokerWorker := child.consumer.refBrokerConsumer(child.broker)
  279. brokerWorker.input <- child
  280. return nil
  281. }
  282. func (child *PartitionConsumer) chooseStartingOffset() (err error) {
  283. var where OffsetTime
  284. switch child.config.OffsetMethod {
  285. case OffsetMethodManual:
  286. if child.config.OffsetValue < 0 {
  287. return ConfigurationError("OffsetValue cannot be < 0 when OffsetMethod is MANUAL")
  288. }
  289. child.offset = child.config.OffsetValue
  290. return nil
  291. case OffsetMethodNewest:
  292. where = LatestOffsets
  293. case OffsetMethodOldest:
  294. where = EarliestOffset
  295. default:
  296. return ConfigurationError("Invalid OffsetMethod")
  297. }
  298. child.offset, err = child.consumer.client.GetOffset(child.topic, child.partition, where)
  299. return err
  300. }
  301. // Events returns the read channel for any events (messages or errors) that might be returned by the broker.
  302. func (child *PartitionConsumer) Events() <-chan *ConsumerEvent {
  303. return child.events
  304. }
  305. // Close stops the PartitionConsumer from fetching messages. It is required to call this function before a
  306. // consumer object passes out of scope, as it will otherwise leak memory. You must call this before
  307. // calling Close on the underlying client.
  308. func (child *PartitionConsumer) Close() error {
  309. // this triggers whatever worker owns this child to abandon it and close its trigger channel, which causes
  310. // the dispatcher to exit its loop, which removes it from the consumer then closes its 'events' channel
  311. // (alternatively, if the child is already at the dispatcher for some reason, that will also just
  312. // close itself)
  313. close(child.dying)
  314. var errors ConsumeErrors
  315. for event := range child.events {
  316. if event.Err != nil {
  317. errors = append(errors, event)
  318. }
  319. }
  320. if len(errors) > 0 {
  321. return errors
  322. }
  323. return nil
  324. }
  325. // brokerConsumer
  326. type brokerConsumer struct {
  327. consumer *Consumer
  328. broker *Broker
  329. input chan *PartitionConsumer
  330. newSubscriptions chan []*PartitionConsumer
  331. wait chan none
  332. subscriptions map[*PartitionConsumer]none
  333. refs int
  334. }
  335. func (w *brokerConsumer) subscriptionManager() {
  336. var buffer []*PartitionConsumer
  337. // The subscriptionManager constantly accepts new subscriptions on `input` (even when the main subscriptionConsumer
  338. // goroutine is in the middle of a network request) and batches it up. The main worker goroutine picks
  339. // up a batch of new subscriptions between every network request by reading from `newSubscriptions`, so we give
  340. // it nil if no new subscriptions are available. We also write to `wait` only when new subscriptions is available,
  341. // so the main goroutine can block waiting for work if it has none.
  342. for {
  343. if len(buffer) > 0 {
  344. select {
  345. case event, ok := <-w.input:
  346. if !ok {
  347. goto done
  348. }
  349. buffer = append(buffer, event)
  350. case w.newSubscriptions <- buffer:
  351. buffer = nil
  352. case w.wait <- none{}:
  353. }
  354. } else {
  355. select {
  356. case event, ok := <-w.input:
  357. if !ok {
  358. goto done
  359. }
  360. buffer = append(buffer, event)
  361. case w.newSubscriptions <- nil:
  362. }
  363. }
  364. }
  365. done:
  366. close(w.wait)
  367. if len(buffer) > 0 {
  368. w.newSubscriptions <- buffer
  369. }
  370. close(w.newSubscriptions)
  371. }
  372. func (w *brokerConsumer) subscriptionConsumer() {
  373. <-w.wait // wait for our first piece of work
  374. // the subscriptionConsumer ensures we will get nil right away if no new subscriptions is available
  375. for newSubscriptions := range w.newSubscriptions {
  376. w.updateSubscriptionCache(newSubscriptions)
  377. if len(w.subscriptions) == 0 {
  378. // We're about to be shut down or we're about to receive more subscriptions.
  379. // Either way, the signal just hasn't propagated to our goroutine yet.
  380. <-w.wait
  381. continue
  382. }
  383. response, err := w.fetchNewMessages()
  384. if err != nil {
  385. Logger.Printf("Unexpected error processing FetchRequest; disconnecting broker %s: %s\n", w.broker.addr, err)
  386. w.abort(err)
  387. return
  388. }
  389. for child := range w.subscriptions {
  390. block := response.GetBlock(child.topic, child.partition)
  391. if block == nil {
  392. child.sendError(IncompleteResponse)
  393. child.trigger <- none{}
  394. delete(w.subscriptions, child)
  395. continue
  396. }
  397. w.handleResponse(child, block)
  398. }
  399. }
  400. }
  401. func (w *brokerConsumer) updateSubscriptionCache(newSubscriptions []*PartitionConsumer) {
  402. // take new subscriptions, and abandon subscriptions that have been closed
  403. for _, child := range newSubscriptions {
  404. w.subscriptions[child] = none{}
  405. }
  406. for child := range w.subscriptions {
  407. select {
  408. case <-child.dying:
  409. close(child.trigger)
  410. delete(w.subscriptions, child)
  411. default:
  412. }
  413. }
  414. }
  415. func (w *brokerConsumer) abort(err error) {
  416. _ = w.broker.Close() // we don't care about the error this might return, we already have one
  417. w.consumer.client.disconnectBroker(w.broker)
  418. for child := range w.subscriptions {
  419. child.sendError(err)
  420. child.trigger <- none{}
  421. }
  422. for newSubscription := range w.newSubscriptions {
  423. for _, child := range newSubscription {
  424. child.sendError(err)
  425. child.trigger <- none{}
  426. }
  427. }
  428. }
  429. func (w *brokerConsumer) fetchNewMessages() (*FetchResponse, error) {
  430. request := &FetchRequest{
  431. MinBytes: w.consumer.config.MinFetchSize,
  432. MaxWaitTime: int32(w.consumer.config.MaxWaitTime / time.Millisecond),
  433. }
  434. for child := range w.subscriptions {
  435. request.AddBlock(child.topic, child.partition, child.offset, child.fetchSize)
  436. }
  437. return w.broker.Fetch(w.consumer.client.id, request)
  438. }
  439. func (w *brokerConsumer) handleResponse(child *PartitionConsumer, block *FetchResponseBlock) {
  440. switch block.Err {
  441. case NoError:
  442. break
  443. default:
  444. child.sendError(block.Err)
  445. fallthrough
  446. case UnknownTopicOrPartition, NotLeaderForPartition, LeaderNotAvailable:
  447. // doesn't belong to us, redispatch it
  448. child.trigger <- none{}
  449. delete(w.subscriptions, child)
  450. return
  451. }
  452. if len(block.MsgSet.Messages) == 0 {
  453. // We got no messages. If we got a trailing one then we need to ask for more data.
  454. // Otherwise we just poll again and wait for one to be produced...
  455. if block.MsgSet.PartialTrailingMessage {
  456. if child.config.MaxMessageSize > 0 && child.fetchSize == child.config.MaxMessageSize {
  457. // we can't ask for more data, we've hit the configured limit
  458. child.sendError(MessageTooLarge)
  459. child.offset++ // skip this one so we can keep processing future messages
  460. } else {
  461. child.fetchSize *= 2
  462. if child.config.MaxMessageSize > 0 && child.fetchSize > child.config.MaxMessageSize {
  463. child.fetchSize = child.config.MaxMessageSize
  464. }
  465. }
  466. }
  467. return
  468. }
  469. // we got messages, reset our fetch size in case it was increased for a previous request
  470. child.fetchSize = child.config.DefaultFetchSize
  471. incomplete := false
  472. atLeastOne := false
  473. prelude := true
  474. for _, msgBlock := range block.MsgSet.Messages {
  475. for _, msg := range msgBlock.Messages() {
  476. if prelude && msg.Offset < child.offset {
  477. continue
  478. }
  479. prelude = false
  480. if msg.Offset >= child.offset {
  481. atLeastOne = true
  482. child.events <- &ConsumerEvent{
  483. Topic: child.topic,
  484. Partition: child.partition,
  485. Key: msg.Msg.Key,
  486. Value: msg.Msg.Value,
  487. Offset: msg.Offset,
  488. }
  489. child.offset = msg.Offset + 1
  490. } else {
  491. incomplete = true
  492. }
  493. }
  494. }
  495. if incomplete || !atLeastOne {
  496. child.sendError(IncompleteResponse)
  497. child.trigger <- none{}
  498. delete(w.subscriptions, child)
  499. }
  500. }