client.go 27 KB

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