client.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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. Requires Kafka 0.10 or higher.
  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. if !client.conf.Version.IsAtLeast(V0_10_0_0) {
  314. return nil, ErrUnsupportedVersion
  315. }
  316. controller := client.cachedController()
  317. if controller == nil {
  318. if err := client.refreshMetadata(); err != nil {
  319. return nil, err
  320. }
  321. controller = client.cachedController()
  322. }
  323. if controller == nil {
  324. return nil, ErrControllerNotAvailable
  325. }
  326. _ = controller.Open(client.conf)
  327. return controller, nil
  328. }
  329. func (client *client) Coordinator(consumerGroup string) (*Broker, error) {
  330. if client.Closed() {
  331. return nil, ErrClosedClient
  332. }
  333. coordinator := client.cachedCoordinator(consumerGroup)
  334. if coordinator == nil {
  335. if err := client.RefreshCoordinator(consumerGroup); err != nil {
  336. return nil, err
  337. }
  338. coordinator = client.cachedCoordinator(consumerGroup)
  339. }
  340. if coordinator == nil {
  341. return nil, ErrConsumerCoordinatorNotAvailable
  342. }
  343. _ = coordinator.Open(client.conf)
  344. return coordinator, nil
  345. }
  346. func (client *client) RefreshCoordinator(consumerGroup string) error {
  347. if client.Closed() {
  348. return ErrClosedClient
  349. }
  350. response, err := client.getConsumerMetadata(consumerGroup, client.conf.Metadata.Retry.Max)
  351. if err != nil {
  352. return err
  353. }
  354. client.lock.Lock()
  355. defer client.lock.Unlock()
  356. client.registerBroker(response.Coordinator)
  357. client.coordinators[consumerGroup] = response.Coordinator.ID()
  358. return nil
  359. }
  360. // private broker management helpers
  361. // registerBroker makes sure a broker received by a Metadata or Coordinator request is registered
  362. // in the brokers map. It returns the broker that is registered, which may be the provided broker,
  363. // or a previously registered Broker instance. You must hold the write lock before calling this function.
  364. func (client *client) registerBroker(broker *Broker) {
  365. if client.brokers[broker.ID()] == nil {
  366. client.brokers[broker.ID()] = broker
  367. Logger.Printf("client/brokers registered new broker #%d at %s", broker.ID(), broker.Addr())
  368. } else if broker.Addr() != client.brokers[broker.ID()].Addr() {
  369. safeAsyncClose(client.brokers[broker.ID()])
  370. client.brokers[broker.ID()] = broker
  371. Logger.Printf("client/brokers replaced registered broker #%d with %s", broker.ID(), broker.Addr())
  372. }
  373. }
  374. // deregisterBroker removes a broker from the seedsBroker list, and if it's
  375. // not the seedbroker, removes it from brokers map completely.
  376. func (client *client) deregisterBroker(broker *Broker) {
  377. client.lock.Lock()
  378. defer client.lock.Unlock()
  379. if len(client.seedBrokers) > 0 && broker == client.seedBrokers[0] {
  380. client.deadSeeds = append(client.deadSeeds, broker)
  381. client.seedBrokers = client.seedBrokers[1:]
  382. } else {
  383. // we do this so that our loop in `tryRefreshMetadata` doesn't go on forever,
  384. // but we really shouldn't have to; once that loop is made better this case can be
  385. // removed, and the function generally can be renamed from `deregisterBroker` to
  386. // `nextSeedBroker` or something
  387. Logger.Printf("client/brokers deregistered broker #%d at %s", broker.ID(), broker.Addr())
  388. delete(client.brokers, broker.ID())
  389. }
  390. }
  391. func (client *client) resurrectDeadBrokers() {
  392. client.lock.Lock()
  393. defer client.lock.Unlock()
  394. Logger.Printf("client/brokers resurrecting %d dead seed brokers", len(client.deadSeeds))
  395. client.seedBrokers = append(client.seedBrokers, client.deadSeeds...)
  396. client.deadSeeds = nil
  397. }
  398. func (client *client) any() *Broker {
  399. client.lock.RLock()
  400. defer client.lock.RUnlock()
  401. if len(client.seedBrokers) > 0 {
  402. _ = client.seedBrokers[0].Open(client.conf)
  403. return client.seedBrokers[0]
  404. }
  405. // not guaranteed to be random *or* deterministic
  406. for _, broker := range client.brokers {
  407. _ = broker.Open(client.conf)
  408. return broker
  409. }
  410. return nil
  411. }
  412. // private caching/lazy metadata helpers
  413. type partitionType int
  414. const (
  415. allPartitions partitionType = iota
  416. writablePartitions
  417. // If you add any more types, update the partition cache in update()
  418. // Ensure this is the last partition type value
  419. maxPartitionIndex
  420. )
  421. func (client *client) cachedMetadata(topic string, partitionID int32) *PartitionMetadata {
  422. client.lock.RLock()
  423. defer client.lock.RUnlock()
  424. partitions := client.metadata[topic]
  425. if partitions != nil {
  426. return partitions[partitionID]
  427. }
  428. return nil
  429. }
  430. func (client *client) cachedPartitions(topic string, partitionSet partitionType) []int32 {
  431. client.lock.RLock()
  432. defer client.lock.RUnlock()
  433. partitions, exists := client.cachedPartitionsResults[topic]
  434. if !exists {
  435. return nil
  436. }
  437. return partitions[partitionSet]
  438. }
  439. func (client *client) setPartitionCache(topic string, partitionSet partitionType) []int32 {
  440. partitions := client.metadata[topic]
  441. if partitions == nil {
  442. return nil
  443. }
  444. ret := make([]int32, 0, len(partitions))
  445. for _, partition := range partitions {
  446. if partitionSet == writablePartitions && partition.Err == ErrLeaderNotAvailable {
  447. continue
  448. }
  449. ret = append(ret, partition.ID)
  450. }
  451. sort.Sort(int32Slice(ret))
  452. return ret
  453. }
  454. func (client *client) cachedLeader(topic string, partitionID int32) (*Broker, error) {
  455. client.lock.RLock()
  456. defer client.lock.RUnlock()
  457. partitions := client.metadata[topic]
  458. if partitions != nil {
  459. metadata, ok := partitions[partitionID]
  460. if ok {
  461. if metadata.Err == ErrLeaderNotAvailable {
  462. return nil, ErrLeaderNotAvailable
  463. }
  464. b := client.brokers[metadata.Leader]
  465. if b == nil {
  466. return nil, ErrLeaderNotAvailable
  467. }
  468. _ = b.Open(client.conf)
  469. return b, nil
  470. }
  471. }
  472. return nil, ErrUnknownTopicOrPartition
  473. }
  474. func (client *client) getOffset(topic string, partitionID int32, time int64) (int64, error) {
  475. broker, err := client.Leader(topic, partitionID)
  476. if err != nil {
  477. return -1, err
  478. }
  479. request := &OffsetRequest{}
  480. if client.conf.Version.IsAtLeast(V0_10_1_0) {
  481. request.Version = 1
  482. }
  483. request.AddBlock(topic, partitionID, time, 1)
  484. response, err := broker.GetAvailableOffsets(request)
  485. if err != nil {
  486. _ = broker.Close()
  487. return -1, err
  488. }
  489. block := response.GetBlock(topic, partitionID)
  490. if block == nil {
  491. _ = broker.Close()
  492. return -1, ErrIncompleteResponse
  493. }
  494. if block.Err != ErrNoError {
  495. return -1, block.Err
  496. }
  497. if len(block.Offsets) != 1 {
  498. return -1, ErrOffsetOutOfRange
  499. }
  500. return block.Offsets[0], nil
  501. }
  502. // core metadata update logic
  503. func (client *client) backgroundMetadataUpdater() {
  504. defer close(client.closed)
  505. if client.conf.Metadata.RefreshFrequency == time.Duration(0) {
  506. return
  507. }
  508. ticker := time.NewTicker(client.conf.Metadata.RefreshFrequency)
  509. defer ticker.Stop()
  510. for {
  511. select {
  512. case <-ticker.C:
  513. if err := client.refreshMetadata(); err != nil {
  514. Logger.Println("Client background metadata update:", err)
  515. }
  516. case <-client.closer:
  517. return
  518. }
  519. }
  520. }
  521. func (client *client) refreshMetadata() error {
  522. topics := []string{}
  523. if !client.conf.Metadata.Full {
  524. if specificTopics, err := client.Topics(); err != nil {
  525. return err
  526. } else if len(specificTopics) == 0 {
  527. return ErrNoTopicsToUpdateMetadata
  528. } else {
  529. topics = specificTopics
  530. }
  531. }
  532. if err := client.RefreshMetadata(topics...); err != nil {
  533. return err
  534. }
  535. return nil
  536. }
  537. func (client *client) tryRefreshMetadata(topics []string, attemptsRemaining int) error {
  538. retry := func(err error) error {
  539. if attemptsRemaining > 0 {
  540. Logger.Printf("client/metadata retrying after %dms... (%d attempts remaining)\n", client.conf.Metadata.Retry.Backoff/time.Millisecond, attemptsRemaining)
  541. time.Sleep(client.conf.Metadata.Retry.Backoff)
  542. return client.tryRefreshMetadata(topics, attemptsRemaining-1)
  543. }
  544. return err
  545. }
  546. for broker := client.any(); broker != nil; broker = client.any() {
  547. if len(topics) > 0 {
  548. Logger.Printf("client/metadata fetching metadata for %v from broker %s\n", topics, broker.addr)
  549. } else {
  550. Logger.Printf("client/metadata fetching metadata for all topics from broker %s\n", broker.addr)
  551. }
  552. req := &MetadataRequest{Topics: topics}
  553. if client.conf.Version.IsAtLeast(V0_10_0_0) {
  554. req.Version = 1
  555. }
  556. response, err := broker.GetMetadata(req)
  557. switch err.(type) {
  558. case nil:
  559. allKnownMetaData := len(topics) == 0
  560. // valid response, use it
  561. shouldRetry, err := client.updateMetadata(response, allKnownMetaData)
  562. if shouldRetry {
  563. Logger.Println("client/metadata found some partitions to be leaderless")
  564. return retry(err) // note: err can be nil
  565. }
  566. return err
  567. case PacketEncodingError:
  568. // didn't even send, return the error
  569. return err
  570. default:
  571. // some other error, remove that broker and try again
  572. Logger.Println("client/metadata got error from broker while fetching metadata:", err)
  573. _ = broker.Close()
  574. client.deregisterBroker(broker)
  575. }
  576. }
  577. Logger.Println("client/metadata no available broker to send metadata request to")
  578. client.resurrectDeadBrokers()
  579. return retry(ErrOutOfBrokers)
  580. }
  581. // if no fatal error, returns a list of topics that need retrying due to ErrLeaderNotAvailable
  582. func (client *client) updateMetadata(data *MetadataResponse, allKnownMetaData bool) (retry bool, err error) {
  583. client.lock.Lock()
  584. defer client.lock.Unlock()
  585. // For all the brokers we received:
  586. // - if it is a new ID, save it
  587. // - if it is an existing ID, but the address we have is stale, discard the old one and save it
  588. // - otherwise ignore it, replacing our existing one would just bounce the connection
  589. for _, broker := range data.Brokers {
  590. client.registerBroker(broker)
  591. }
  592. client.controllerID = data.ControllerID
  593. if allKnownMetaData {
  594. client.metadata = make(map[string]map[int32]*PartitionMetadata)
  595. client.cachedPartitionsResults = make(map[string][maxPartitionIndex][]int32)
  596. }
  597. for _, topic := range data.Topics {
  598. delete(client.metadata, topic.Name)
  599. delete(client.cachedPartitionsResults, topic.Name)
  600. switch topic.Err {
  601. case ErrNoError:
  602. break
  603. case ErrInvalidTopic, ErrTopicAuthorizationFailed: // don't retry, don't store partial results
  604. err = topic.Err
  605. continue
  606. case ErrUnknownTopicOrPartition: // retry, do not store partial partition results
  607. err = topic.Err
  608. retry = true
  609. continue
  610. case ErrLeaderNotAvailable: // retry, but store partial partition results
  611. retry = true
  612. break
  613. default: // don't retry, don't store partial results
  614. Logger.Printf("Unexpected topic-level metadata error: %s", topic.Err)
  615. err = topic.Err
  616. continue
  617. }
  618. client.metadata[topic.Name] = make(map[int32]*PartitionMetadata, len(topic.Partitions))
  619. for _, partition := range topic.Partitions {
  620. client.metadata[topic.Name][partition.ID] = partition
  621. if partition.Err == ErrLeaderNotAvailable {
  622. retry = true
  623. }
  624. }
  625. var partitionCache [maxPartitionIndex][]int32
  626. partitionCache[allPartitions] = client.setPartitionCache(topic.Name, allPartitions)
  627. partitionCache[writablePartitions] = client.setPartitionCache(topic.Name, writablePartitions)
  628. client.cachedPartitionsResults[topic.Name] = partitionCache
  629. }
  630. return
  631. }
  632. func (client *client) cachedCoordinator(consumerGroup string) *Broker {
  633. client.lock.RLock()
  634. defer client.lock.RUnlock()
  635. if coordinatorID, ok := client.coordinators[consumerGroup]; ok {
  636. return client.brokers[coordinatorID]
  637. }
  638. return nil
  639. }
  640. func (client *client) cachedController() *Broker {
  641. client.lock.RLock()
  642. defer client.lock.RUnlock()
  643. return client.brokers[client.controllerID]
  644. }
  645. func (client *client) getConsumerMetadata(consumerGroup string, attemptsRemaining int) (*FindCoordinatorResponse, error) {
  646. retry := func(err error) (*FindCoordinatorResponse, error) {
  647. if attemptsRemaining > 0 {
  648. Logger.Printf("client/coordinator retrying after %dms... (%d attempts remaining)\n", client.conf.Metadata.Retry.Backoff/time.Millisecond, attemptsRemaining)
  649. time.Sleep(client.conf.Metadata.Retry.Backoff)
  650. return client.getConsumerMetadata(consumerGroup, attemptsRemaining-1)
  651. }
  652. return nil, err
  653. }
  654. for broker := client.any(); broker != nil; broker = client.any() {
  655. Logger.Printf("client/coordinator requesting coordinator for consumergroup %s from %s\n", consumerGroup, broker.Addr())
  656. request := new(FindCoordinatorRequest)
  657. request.CoordinatorKey = consumerGroup
  658. request.CoordinatorType = CoordinatorGroup
  659. response, err := broker.FindCoordinator(request)
  660. if err != nil {
  661. Logger.Printf("client/coordinator request to broker %s failed: %s\n", broker.Addr(), err)
  662. switch err.(type) {
  663. case PacketEncodingError:
  664. return nil, err
  665. default:
  666. _ = broker.Close()
  667. client.deregisterBroker(broker)
  668. continue
  669. }
  670. }
  671. switch response.Err {
  672. case ErrNoError:
  673. Logger.Printf("client/coordinator coordinator for consumergroup %s is #%d (%s)\n", consumerGroup, response.Coordinator.ID(), response.Coordinator.Addr())
  674. return response, nil
  675. case ErrConsumerCoordinatorNotAvailable:
  676. Logger.Printf("client/coordinator coordinator for consumer group %s is not available\n", consumerGroup)
  677. // This is very ugly, but this scenario will only happen once per cluster.
  678. // The __consumer_offsets topic only has to be created one time.
  679. // The number of partitions not configurable, but partition 0 should always exist.
  680. if _, err := client.Leader("__consumer_offsets", 0); err != nil {
  681. Logger.Printf("client/coordinator the __consumer_offsets topic is not initialized completely yet. Waiting 2 seconds...\n")
  682. time.Sleep(2 * time.Second)
  683. }
  684. return retry(ErrConsumerCoordinatorNotAvailable)
  685. default:
  686. return nil, response.Err
  687. }
  688. }
  689. Logger.Println("client/coordinator no available broker to send consumer metadata request to")
  690. client.resurrectDeadBrokers()
  691. return retry(ErrOutOfBrokers)
  692. }