client.go 30 KB

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