client.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. package sarama
  2. import (
  3. "math/rand"
  4. "sort"
  5. "sync"
  6. "time"
  7. )
  8. // Client is a generic Kafka client. It manages connections to one or more Kafka brokers.
  9. // You MUST call Close() on a client to avoid leaks, it will not be garbage-collected
  10. // automatically when it passes out of scope. It is safe to share a client amongst many
  11. // users, however Kafka will process requests from a single client strictly in serial,
  12. // so it is generally more efficient to use the default one client per producer/consumer.
  13. type Client interface {
  14. // Config returns the Config struct of the client. This struct should not be
  15. // altered after it has been created.
  16. Config() *Config
  17. // Topics returns the set of available topics as retrieved from cluster metadata.
  18. Topics() ([]string, error)
  19. // Partitions returns the sorted list of all partition IDs for the given topic.
  20. Partitions(topic string) ([]int32, error)
  21. // WritablePartitions returns the sorted list of all writable partition IDs for
  22. // the given topic, where "writable" means "having a valid leader accepting
  23. // writes".
  24. WritablePartitions(topic string) ([]int32, error)
  25. // Leader returns the broker object that is the leader of the current
  26. // topic/partition, as determined by querying the cluster metadata.
  27. Leader(topic string, partitionID int32) (*Broker, error)
  28. // Replicas returns the set of all replica IDs for the given partition.
  29. Replicas(topic string, partitionID int32) ([]int32, error)
  30. // RefreshMetadata takes a list of topics and queries the cluster to refresh the
  31. // available metadata for those topics. If no topics are provided, it will refresh
  32. // metadata for all topics.
  33. RefreshMetadata(topics ...string) error
  34. // GetOffset queries the cluster to get the most recent available offset at the
  35. // given time on the topic/partition combination. Time should be OffsetOldest for
  36. // the earliest available offset, OffsetNewest for the offset of the message that
  37. // will be produced next, or a time.
  38. GetOffset(topic string, partitionID int32, time int64) (int64, error)
  39. // Coordinator returns the coordinating broker for a consumer group. It will
  40. // return a locally cached value if it's available. You can call
  41. // RefreshCoordinator to update the cached value. This function only works on
  42. // Kafka 0.8.2 and higher.
  43. Coordinator(consumerGroup string) (*Broker, error)
  44. // RefreshCoordinator retrieves the coordinator for a consumer group and stores it
  45. // in local cache. This function only works on Kafka 0.8.2 and higher.
  46. RefreshCoordinator(consumerGroup string) error
  47. // Close shuts down all broker connections managed by this client. It is required
  48. // to call this function before a client object passes out of scope, as it will
  49. // otherwise leak memory. You must close any Producers or Consumers using a client
  50. // before you close the client.
  51. Close() error
  52. // Closed returns true if the client has already had Close called on it
  53. Closed() bool
  54. }
  55. const (
  56. // OffsetNewest stands for the log head offset, i.e. the offset that will be
  57. // assigned to the next message that will be produced to the partition. You
  58. // can send this to a client's GetOffset method to get this offset, or when
  59. // calling ConsumePartition to start consuming new messages.
  60. OffsetNewest int64 = -1
  61. // OffsetOldest stands for the oldest offset available on the broker for a
  62. // partition. You can send this to a client's GetOffset method to get this
  63. // offset, or when calling ConsumePartition to start consuming from the
  64. // oldest offset that is still available on the broker.
  65. OffsetOldest int64 = -2
  66. )
  67. type client struct {
  68. conf *Config
  69. closer, closed chan none // for shutting down background metadata updater
  70. // the broker addresses given to us through the constructor are not guaranteed to be returned in
  71. // the cluster metadata (I *think* it only returns brokers who are currently leading partitions?)
  72. // so we store them separately
  73. seedBrokers []*Broker
  74. deadSeeds []*Broker
  75. brokers map[int32]*Broker // maps broker ids to brokers
  76. metadata map[string]map[int32]*PartitionMetadata // maps topics to partition ids to metadata
  77. coordinators map[string]int32 // Maps consumer group names to coordinating broker IDs
  78. // If the number of partitions is large, we can get some churn calling cachedPartitions,
  79. // so the result is cached. It is important to update this value whenever metadata is changed
  80. cachedPartitionsResults map[string][maxPartitionIndex][]int32
  81. lock sync.RWMutex // protects access to the maps that hold cluster state.
  82. }
  83. // NewClient creates a new Client. It connects to one of the given broker addresses
  84. // and uses that broker to automatically fetch metadata on the rest of the kafka cluster. If metadata cannot
  85. // be retrieved from any of the given broker addresses, the client is not created.
  86. func NewClient(addrs []string, conf *Config) (Client, error) {
  87. Logger.Println("Initializing new client")
  88. if conf == nil {
  89. conf = NewConfig()
  90. }
  91. if err := conf.Validate(); err != nil {
  92. return nil, err
  93. }
  94. if len(addrs) < 1 {
  95. return nil, ConfigurationError("You must provide at least one broker address")
  96. }
  97. client := &client{
  98. conf: conf,
  99. closer: make(chan none),
  100. closed: make(chan none),
  101. brokers: make(map[int32]*Broker),
  102. metadata: make(map[string]map[int32]*PartitionMetadata),
  103. cachedPartitionsResults: make(map[string][maxPartitionIndex][]int32),
  104. coordinators: make(map[string]int32),
  105. }
  106. random := rand.New(rand.NewSource(time.Now().UnixNano()))
  107. for _, index := range random.Perm(len(addrs)) {
  108. client.seedBrokers = append(client.seedBrokers, NewBroker(addrs[index]))
  109. }
  110. // do an initial fetch of all cluster metadata by specifing an empty list of topics
  111. err := client.RefreshMetadata()
  112. switch err {
  113. case nil:
  114. break
  115. case ErrLeaderNotAvailable, ErrReplicaNotAvailable, ErrTopicAuthorizationFailed, ErrClusterAuthorizationFailed:
  116. // indicates that maybe part of the cluster is down, but is not fatal to creating the client
  117. Logger.Println(err)
  118. default:
  119. close(client.closed) // we haven't started the background updater yet, so we have to do this manually
  120. _ = client.Close()
  121. return nil, err
  122. }
  123. go withRecover(client.backgroundMetadataUpdater)
  124. Logger.Println("Successfully initialized new client")
  125. return client, nil
  126. }
  127. func (client *client) Config() *Config {
  128. return client.conf
  129. }
  130. func (client *client) Close() error {
  131. if client.Closed() {
  132. // Chances are this is being called from a defer() and the error will go unobserved
  133. // so we go ahead and log the event in this case.
  134. Logger.Printf("Close() called on already closed client")
  135. return ErrClosedClient
  136. }
  137. // shutdown and wait for the background thread before we take the lock, to avoid races
  138. close(client.closer)
  139. <-client.closed
  140. client.lock.Lock()
  141. defer client.lock.Unlock()
  142. Logger.Println("Closing Client")
  143. for _, broker := range client.brokers {
  144. safeAsyncClose(broker)
  145. }
  146. for _, broker := range client.seedBrokers {
  147. safeAsyncClose(broker)
  148. }
  149. client.brokers = nil
  150. client.metadata = nil
  151. return nil
  152. }
  153. func (client *client) Closed() bool {
  154. return client.brokers == nil
  155. }
  156. func (client *client) Topics() ([]string, error) {
  157. if client.Closed() {
  158. return nil, ErrClosedClient
  159. }
  160. client.lock.RLock()
  161. defer client.lock.RUnlock()
  162. ret := make([]string, 0, len(client.metadata))
  163. for topic := range client.metadata {
  164. ret = append(ret, topic)
  165. }
  166. return ret, nil
  167. }
  168. func (client *client) Partitions(topic string) ([]int32, error) {
  169. if client.Closed() {
  170. return nil, ErrClosedClient
  171. }
  172. partitions := client.cachedPartitions(topic, allPartitions)
  173. if len(partitions) == 0 {
  174. err := client.RefreshMetadata(topic)
  175. if err != nil {
  176. return nil, err
  177. }
  178. partitions = client.cachedPartitions(topic, allPartitions)
  179. }
  180. if partitions == nil {
  181. return nil, ErrUnknownTopicOrPartition
  182. }
  183. return partitions, nil
  184. }
  185. func (client *client) WritablePartitions(topic string) ([]int32, error) {
  186. if client.Closed() {
  187. return nil, ErrClosedClient
  188. }
  189. partitions := client.cachedPartitions(topic, writablePartitions)
  190. // len==0 catches when it's nil (no such topic) and the odd case when every single
  191. // partition is undergoing leader election simultaneously. Callers have to be able to handle
  192. // this function returning an empty slice (which is a valid return value) but catching it
  193. // here the first time (note we *don't* catch it below where we return ErrUnknownTopicOrPartition) triggers
  194. // a metadata refresh as a nicety so callers can just try again and don't have to manually
  195. // trigger a refresh (otherwise they'd just keep getting a stale cached copy).
  196. if len(partitions) == 0 {
  197. err := client.RefreshMetadata(topic)
  198. if err != nil {
  199. return nil, err
  200. }
  201. partitions = client.cachedPartitions(topic, writablePartitions)
  202. }
  203. if partitions == nil {
  204. return nil, ErrUnknownTopicOrPartition
  205. }
  206. return partitions, nil
  207. }
  208. func (client *client) Replicas(topic string, partitionID int32) ([]int32, error) {
  209. if client.Closed() {
  210. return nil, ErrClosedClient
  211. }
  212. metadata := client.cachedMetadata(topic, partitionID)
  213. if metadata == nil {
  214. err := client.RefreshMetadata(topic)
  215. if err != nil {
  216. return nil, err
  217. }
  218. metadata = client.cachedMetadata(topic, partitionID)
  219. }
  220. if metadata == nil {
  221. return nil, ErrUnknownTopicOrPartition
  222. }
  223. if metadata.Err == ErrReplicaNotAvailable {
  224. return nil, metadata.Err
  225. }
  226. return dupeAndSort(metadata.Replicas), nil
  227. }
  228. func (client *client) Leader(topic string, partitionID int32) (*Broker, error) {
  229. if client.Closed() {
  230. return nil, ErrClosedClient
  231. }
  232. leader, err := client.cachedLeader(topic, partitionID)
  233. if leader == nil {
  234. err = client.RefreshMetadata(topic)
  235. if err != nil {
  236. return nil, err
  237. }
  238. leader, err = client.cachedLeader(topic, partitionID)
  239. }
  240. return leader, err
  241. }
  242. func (client *client) RefreshMetadata(topics ...string) error {
  243. if client.Closed() {
  244. return ErrClosedClient
  245. }
  246. // Prior to 0.8.2, Kafka will throw exceptions on an empty topic and not return a proper
  247. // error. This handles the case by returning an error instead of sending it
  248. // off to Kafka. See: https://github.com/Shopify/sarama/pull/38#issuecomment-26362310
  249. for _, topic := range topics {
  250. if len(topic) == 0 {
  251. return ErrInvalidTopic // this is the error that 0.8.2 and later correctly return
  252. }
  253. }
  254. return client.tryRefreshMetadata(topics, client.conf.Metadata.Retry.Max)
  255. }
  256. func (client *client) GetOffset(topic string, partitionID int32, time int64) (int64, error) {
  257. if client.Closed() {
  258. return -1, ErrClosedClient
  259. }
  260. offset, err := client.getOffset(topic, partitionID, time)
  261. if err != nil {
  262. if err := client.RefreshMetadata(topic); err != nil {
  263. return -1, err
  264. }
  265. return client.getOffset(topic, partitionID, time)
  266. }
  267. return offset, err
  268. }
  269. func (client *client) Coordinator(consumerGroup string) (*Broker, error) {
  270. if client.Closed() {
  271. return nil, ErrClosedClient
  272. }
  273. coordinator := client.cachedCoordinator(consumerGroup)
  274. if coordinator == nil {
  275. if err := client.RefreshCoordinator(consumerGroup); err != nil {
  276. return nil, err
  277. }
  278. coordinator = client.cachedCoordinator(consumerGroup)
  279. }
  280. if coordinator == nil {
  281. return nil, ErrConsumerCoordinatorNotAvailable
  282. }
  283. _ = coordinator.Open(client.conf)
  284. return coordinator, nil
  285. }
  286. func (client *client) RefreshCoordinator(consumerGroup string) error {
  287. if client.Closed() {
  288. return ErrClosedClient
  289. }
  290. response, err := client.getConsumerMetadata(consumerGroup, client.conf.Metadata.Retry.Max)
  291. if err != nil {
  292. return err
  293. }
  294. client.lock.Lock()
  295. defer client.lock.Unlock()
  296. client.registerBroker(response.Coordinator)
  297. client.coordinators[consumerGroup] = response.Coordinator.ID()
  298. return nil
  299. }
  300. // private broker management helpers
  301. // registerBroker makes sure a broker received by a Metadata or Coordinator request is registered
  302. // in the brokers map. It returns the broker that is registered, which may be the provided broker,
  303. // or a previously registered Broker instance. You must hold the write lock before calling this function.
  304. func (client *client) registerBroker(broker *Broker) {
  305. if client.brokers[broker.ID()] == nil {
  306. client.brokers[broker.ID()] = broker
  307. Logger.Printf("client/brokers registered new broker #%d at %s", broker.ID(), broker.Addr())
  308. } else if broker.Addr() != client.brokers[broker.ID()].Addr() {
  309. safeAsyncClose(client.brokers[broker.ID()])
  310. client.brokers[broker.ID()] = broker
  311. Logger.Printf("client/brokers replaced registered broker #%d with %s", broker.ID(), broker.Addr())
  312. }
  313. }
  314. // deregisterBroker removes a broker from the seedsBroker list, and if it's
  315. // not the seedbroker, removes it from brokers map completely.
  316. func (client *client) deregisterBroker(broker *Broker) {
  317. client.lock.Lock()
  318. defer client.lock.Unlock()
  319. if len(client.seedBrokers) > 0 && broker == client.seedBrokers[0] {
  320. client.deadSeeds = append(client.deadSeeds, broker)
  321. client.seedBrokers = client.seedBrokers[1:]
  322. } else {
  323. // we do this so that our loop in `tryRefreshMetadata` doesn't go on forever,
  324. // but we really shouldn't have to; once that loop is made better this case can be
  325. // removed, and the function generally can be renamed from `deregisterBroker` to
  326. // `nextSeedBroker` or something
  327. Logger.Printf("client/brokers deregistered broker #%d at %s", broker.ID(), broker.Addr())
  328. delete(client.brokers, broker.ID())
  329. }
  330. }
  331. func (client *client) resurrectDeadBrokers() {
  332. client.lock.Lock()
  333. defer client.lock.Unlock()
  334. Logger.Printf("client/brokers resurrecting %d dead seed brokers", len(client.deadSeeds))
  335. client.seedBrokers = append(client.seedBrokers, client.deadSeeds...)
  336. client.deadSeeds = nil
  337. }
  338. func (client *client) any() *Broker {
  339. client.lock.RLock()
  340. defer client.lock.RUnlock()
  341. if len(client.seedBrokers) > 0 {
  342. _ = client.seedBrokers[0].Open(client.conf)
  343. return client.seedBrokers[0]
  344. }
  345. // not guaranteed to be random *or* deterministic
  346. for _, broker := range client.brokers {
  347. _ = broker.Open(client.conf)
  348. return broker
  349. }
  350. return nil
  351. }
  352. // private caching/lazy metadata helpers
  353. type partitionType int
  354. const (
  355. allPartitions partitionType = iota
  356. writablePartitions
  357. // If you add any more types, update the partition cache in update()
  358. // Ensure this is the last partition type value
  359. maxPartitionIndex
  360. )
  361. func (client *client) cachedMetadata(topic string, partitionID int32) *PartitionMetadata {
  362. client.lock.RLock()
  363. defer client.lock.RUnlock()
  364. partitions := client.metadata[topic]
  365. if partitions != nil {
  366. return partitions[partitionID]
  367. }
  368. return nil
  369. }
  370. func (client *client) cachedPartitions(topic string, partitionSet partitionType) []int32 {
  371. client.lock.RLock()
  372. defer client.lock.RUnlock()
  373. partitions, exists := client.cachedPartitionsResults[topic]
  374. if !exists {
  375. return nil
  376. }
  377. return partitions[partitionSet]
  378. }
  379. func (client *client) setPartitionCache(topic string, partitionSet partitionType) []int32 {
  380. partitions := client.metadata[topic]
  381. if partitions == nil {
  382. return nil
  383. }
  384. ret := make([]int32, 0, len(partitions))
  385. for _, partition := range partitions {
  386. if partitionSet == writablePartitions && partition.Err == ErrLeaderNotAvailable {
  387. continue
  388. }
  389. ret = append(ret, partition.ID)
  390. }
  391. sort.Sort(int32Slice(ret))
  392. return ret
  393. }
  394. func (client *client) cachedLeader(topic string, partitionID int32) (*Broker, error) {
  395. client.lock.RLock()
  396. defer client.lock.RUnlock()
  397. partitions := client.metadata[topic]
  398. if partitions != nil {
  399. metadata, ok := partitions[partitionID]
  400. if ok {
  401. if metadata.Err == ErrLeaderNotAvailable {
  402. return nil, ErrLeaderNotAvailable
  403. }
  404. b := client.brokers[metadata.Leader]
  405. if b == nil {
  406. return nil, ErrLeaderNotAvailable
  407. }
  408. _ = b.Open(client.conf)
  409. return b, nil
  410. }
  411. }
  412. return nil, ErrUnknownTopicOrPartition
  413. }
  414. func (client *client) getOffset(topic string, partitionID int32, time int64) (int64, error) {
  415. broker, err := client.Leader(topic, partitionID)
  416. if err != nil {
  417. return -1, err
  418. }
  419. request := &OffsetRequest{}
  420. if client.conf.Version.IsAtLeast(V0_10_1_0) {
  421. request.Version = 1
  422. }
  423. request.AddBlock(topic, partitionID, time, 1)
  424. response, err := broker.GetAvailableOffsets(request)
  425. if err != nil {
  426. _ = broker.Close()
  427. return -1, err
  428. }
  429. block := response.GetBlock(topic, partitionID)
  430. if block == nil {
  431. _ = broker.Close()
  432. return -1, ErrIncompleteResponse
  433. }
  434. if block.Err != ErrNoError {
  435. return -1, block.Err
  436. }
  437. if len(block.Offsets) != 1 {
  438. return -1, ErrOffsetOutOfRange
  439. }
  440. return block.Offsets[0], nil
  441. }
  442. // core metadata update logic
  443. func (client *client) backgroundMetadataUpdater() {
  444. defer close(client.closed)
  445. if client.conf.Metadata.RefreshFrequency == time.Duration(0) {
  446. return
  447. }
  448. ticker := time.NewTicker(client.conf.Metadata.RefreshFrequency)
  449. defer ticker.Stop()
  450. for {
  451. select {
  452. case <-ticker.C:
  453. if err := client.RefreshMetadata(); err != nil {
  454. Logger.Println("Client background metadata update:", err)
  455. }
  456. case <-client.closer:
  457. return
  458. }
  459. }
  460. }
  461. func (client *client) tryRefreshMetadata(topics []string, attemptsRemaining int) error {
  462. retry := func(err error) error {
  463. if attemptsRemaining > 0 {
  464. Logger.Printf("client/metadata retrying after %dms... (%d attempts remaining)\n", client.conf.Metadata.Retry.Backoff/time.Millisecond, attemptsRemaining)
  465. time.Sleep(client.conf.Metadata.Retry.Backoff)
  466. return client.tryRefreshMetadata(topics, attemptsRemaining-1)
  467. }
  468. return err
  469. }
  470. for broker := client.any(); broker != nil; broker = client.any() {
  471. if len(topics) > 0 {
  472. Logger.Printf("client/metadata fetching metadata for %v from broker %s\n", topics, broker.addr)
  473. } else {
  474. Logger.Printf("client/metadata fetching metadata for all topics from broker %s\n", broker.addr)
  475. }
  476. response, err := broker.GetMetadata(&MetadataRequest{Topics: topics})
  477. switch err.(type) {
  478. case nil:
  479. // valid response, use it
  480. if shouldRetry, err := client.updateMetadata(response); shouldRetry {
  481. Logger.Println("client/metadata found some partitions to be leaderless")
  482. return retry(err) // note: err can be nil
  483. } else {
  484. return err
  485. }
  486. case PacketEncodingError:
  487. // didn't even send, return the error
  488. return err
  489. default:
  490. // some other error, remove that broker and try again
  491. Logger.Println("client/metadata got error from broker while fetching metadata:", err)
  492. _ = broker.Close()
  493. client.deregisterBroker(broker)
  494. }
  495. }
  496. Logger.Println("client/metadata no available broker to send metadata request to")
  497. client.resurrectDeadBrokers()
  498. return retry(ErrOutOfBrokers)
  499. }
  500. // if no fatal error, returns a list of topics that need retrying due to ErrLeaderNotAvailable
  501. func (client *client) updateMetadata(data *MetadataResponse) (retry bool, err error) {
  502. client.lock.Lock()
  503. defer client.lock.Unlock()
  504. // For all the brokers we received:
  505. // - if it is a new ID, save it
  506. // - if it is an existing ID, but the address we have is stale, discard the old one and save it
  507. // - otherwise ignore it, replacing our existing one would just bounce the connection
  508. for _, broker := range data.Brokers {
  509. client.registerBroker(broker)
  510. }
  511. for _, topic := range data.Topics {
  512. delete(client.metadata, topic.Name)
  513. delete(client.cachedPartitionsResults, topic.Name)
  514. switch topic.Err {
  515. case ErrNoError:
  516. break
  517. case ErrInvalidTopic, ErrTopicAuthorizationFailed: // don't retry, don't store partial results
  518. err = topic.Err
  519. continue
  520. case ErrUnknownTopicOrPartition: // retry, do not store partial partition results
  521. err = topic.Err
  522. retry = true
  523. continue
  524. case ErrLeaderNotAvailable: // retry, but store partial partition results
  525. retry = true
  526. break
  527. default: // don't retry, don't store partial results
  528. Logger.Printf("Unexpected topic-level metadata error: %s", topic.Err)
  529. err = topic.Err
  530. continue
  531. }
  532. client.metadata[topic.Name] = make(map[int32]*PartitionMetadata, len(topic.Partitions))
  533. for _, partition := range topic.Partitions {
  534. client.metadata[topic.Name][partition.ID] = partition
  535. if partition.Err == ErrLeaderNotAvailable {
  536. retry = true
  537. }
  538. }
  539. var partitionCache [maxPartitionIndex][]int32
  540. partitionCache[allPartitions] = client.setPartitionCache(topic.Name, allPartitions)
  541. partitionCache[writablePartitions] = client.setPartitionCache(topic.Name, writablePartitions)
  542. client.cachedPartitionsResults[topic.Name] = partitionCache
  543. }
  544. return
  545. }
  546. func (client *client) cachedCoordinator(consumerGroup string) *Broker {
  547. client.lock.RLock()
  548. defer client.lock.RUnlock()
  549. if coordinatorID, ok := client.coordinators[consumerGroup]; ok {
  550. return client.brokers[coordinatorID]
  551. }
  552. return nil
  553. }
  554. func (client *client) getConsumerMetadata(consumerGroup string, attemptsRemaining int) (*ConsumerMetadataResponse, error) {
  555. retry := func(err error) (*ConsumerMetadataResponse, error) {
  556. if attemptsRemaining > 0 {
  557. Logger.Printf("client/coordinator retrying after %dms... (%d attempts remaining)\n", client.conf.Metadata.Retry.Backoff/time.Millisecond, attemptsRemaining)
  558. time.Sleep(client.conf.Metadata.Retry.Backoff)
  559. return client.getConsumerMetadata(consumerGroup, attemptsRemaining-1)
  560. }
  561. return nil, err
  562. }
  563. for broker := client.any(); broker != nil; broker = client.any() {
  564. Logger.Printf("client/coordinator requesting coordinator for consumergroup %s from %s\n", consumerGroup, broker.Addr())
  565. request := new(ConsumerMetadataRequest)
  566. request.ConsumerGroup = consumerGroup
  567. response, err := broker.GetConsumerMetadata(request)
  568. if err != nil {
  569. Logger.Printf("client/coordinator request to broker %s failed: %s\n", broker.Addr(), err)
  570. switch err.(type) {
  571. case PacketEncodingError:
  572. return nil, err
  573. default:
  574. _ = broker.Close()
  575. client.deregisterBroker(broker)
  576. continue
  577. }
  578. }
  579. switch response.Err {
  580. case ErrNoError:
  581. Logger.Printf("client/coordinator coordinator for consumergroup %s is #%d (%s)\n", consumerGroup, response.Coordinator.ID(), response.Coordinator.Addr())
  582. return response, nil
  583. case ErrConsumerCoordinatorNotAvailable:
  584. Logger.Printf("client/coordinator coordinator for consumer group %s is not available\n", consumerGroup)
  585. // This is very ugly, but this scenario will only happen once per cluster.
  586. // The __consumer_offsets topic only has to be created one time.
  587. // The number of partitions not configurable, but partition 0 should always exist.
  588. if _, err := client.Leader("__consumer_offsets", 0); err != nil {
  589. Logger.Printf("client/coordinator the __consumer_offsets topic is not initialized completely yet. Waiting 2 seconds...\n")
  590. time.Sleep(2 * time.Second)
  591. }
  592. return retry(ErrConsumerCoordinatorNotAvailable)
  593. default:
  594. return nil, response.Err
  595. }
  596. }
  597. Logger.Println("client/coordinator no available broker to send consumer metadata request to")
  598. client.resurrectDeadBrokers()
  599. return retry(ErrOutOfBrokers)
  600. }