client.go 25 KB

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