client.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. package sarama
  2. import (
  3. "sort"
  4. "sync"
  5. "time"
  6. )
  7. // Client is a generic Kafka client. It manages connections to one or more Kafka brokers.
  8. // You MUST call Close() on a client to avoid leaks, it will not be garbage-collected
  9. // automatically when it passes out of scope. A single client can be safely shared by
  10. // multiple concurrent Producers and Consumers.
  11. type Client interface {
  12. // Config returns the Config struct of the client. This struct should not be altered after it
  13. // has been created.
  14. Config() *Config
  15. // Topics returns the set of available topics as retrieved from the cluster metadata.
  16. Topics() ([]string, error)
  17. // Partitions returns the sorted list of all partition IDs for the given topic.
  18. Partitions(topic string) ([]int32, error)
  19. // WritablePartitions returns the sorted list of all writable partition IDs for the given topic,
  20. // where "writable" means "having a valid leader accepting writes".
  21. WritablePartitions(topic string) ([]int32, error)
  22. // Leader returns the broker object that is the leader of the current topic/partition, as
  23. // determined by querying the cluster metadata.
  24. Leader(topic string, partitionID int32) (*Broker, error)
  25. // Replicas returns the set of all replica IDs for the given partition.
  26. Replicas(topic string, partitionID int32) ([]int32, error)
  27. // ReplicasInSync returns the set of all in-sync replica IDs for the given partition.
  28. // Note: kafka's metadata here is known to be stale in many cases, and should not generally be trusted.
  29. // This method should be considered effectively deprecated.
  30. ReplicasInSync(topic string, partitionID int32) ([]int32, error)
  31. // RefreshTopicMetadata takes a list of topics and queries the cluster to refresh the
  32. // available metadata for those topics.
  33. RefreshTopicMetadata(topics ...string) error
  34. // RefreshAllMetadata queries the cluster to refresh the available metadata for all topics.
  35. RefreshAllMetadata() error
  36. // GetOffset queries the cluster to get the most recent available offset at the given
  37. // time on the topic/partition combination.
  38. GetOffset(topic string, partitionID int32, where OffsetTime) (int64, error)
  39. // Close shuts down all broker connections managed by this client. It is required to call this function before
  40. // a client object passes out of scope, as it will otherwise leak memory. You must close any Producers or Consumers
  41. // using a client before you close the client.
  42. Close() error
  43. // Closed returns true if the client has already had Close called on it
  44. Closed() bool
  45. }
  46. type client struct {
  47. conf *Config
  48. closer chan none
  49. // the broker addresses given to us through the constructor are not guaranteed to be returned in
  50. // the cluster metadata (I *think* it only returns brokers who are currently leading partitions?)
  51. // so we store them separately
  52. seedBrokerAddrs []string
  53. seedBroker *Broker
  54. deadBrokerAddrs map[string]none
  55. brokers map[int32]*Broker // maps broker ids to brokers
  56. metadata map[string]map[int32]*PartitionMetadata // maps topics to partition ids to metadata
  57. // If the number of partitions is large, we can get some churn calling cachedPartitions,
  58. // so the result is cached. It is important to update this value whenever metadata is changed
  59. cachedPartitionsResults map[string][maxPartitionIndex][]int32
  60. lock sync.RWMutex // protects access to the maps, only one since they're always written together
  61. }
  62. // NewClient creates a new Client. It connects to one of the given broker addresses
  63. // and uses that broker to automatically fetch metadata on the rest of the kafka cluster. If metadata cannot
  64. // be retrieved from any of the given broker addresses, the client is not created.
  65. func NewClient(addrs []string, conf *Config) (Client, error) {
  66. Logger.Println("Initializing new client")
  67. if conf == nil {
  68. conf = NewConfig()
  69. }
  70. if err := conf.Validate(); err != nil {
  71. return nil, err
  72. }
  73. if len(addrs) < 1 {
  74. return nil, ConfigurationError("You must provide at least one broker address")
  75. }
  76. client := &client{
  77. conf: conf,
  78. closer: make(chan none),
  79. seedBrokerAddrs: addrs,
  80. seedBroker: NewBroker(addrs[0]),
  81. deadBrokerAddrs: make(map[string]none),
  82. brokers: make(map[int32]*Broker),
  83. metadata: make(map[string]map[int32]*PartitionMetadata),
  84. cachedPartitionsResults: make(map[string][maxPartitionIndex][]int32),
  85. }
  86. _ = client.seedBroker.Open(conf)
  87. // do an initial fetch of all cluster metadata by specifing an empty list of topics
  88. err := client.RefreshAllMetadata()
  89. switch err {
  90. case nil:
  91. break
  92. case ErrLeaderNotAvailable, ErrReplicaNotAvailable:
  93. // indicates that maybe part of the cluster is down, but is not fatal to creating the client
  94. Logger.Println(err)
  95. default:
  96. _ = client.Close()
  97. return nil, err
  98. }
  99. go withRecover(client.backgroundMetadataUpdater)
  100. Logger.Println("Successfully initialized new client")
  101. return client, nil
  102. }
  103. func (client *client) Config() *Config {
  104. return client.conf
  105. }
  106. func (client *client) Close() error {
  107. // Check to see whether the client is closed
  108. if client.Closed() {
  109. // Chances are this is being called from a defer() and the error will go unobserved
  110. // so we go ahead and log the event in this case.
  111. Logger.Printf("Close() called on already closed client")
  112. return ErrClosedClient
  113. }
  114. client.lock.Lock()
  115. defer client.lock.Unlock()
  116. Logger.Println("Closing Client")
  117. for _, broker := range client.brokers {
  118. safeAsyncClose(broker)
  119. }
  120. client.brokers = nil
  121. client.metadata = nil
  122. if client.seedBroker != nil {
  123. safeAsyncClose(client.seedBroker)
  124. }
  125. close(client.closer)
  126. return nil
  127. }
  128. func (client *client) Closed() bool {
  129. return client.brokers == nil
  130. }
  131. func (client *client) Topics() ([]string, error) {
  132. // Check to see whether the client is closed
  133. if client.Closed() {
  134. return nil, ErrClosedClient
  135. }
  136. client.lock.RLock()
  137. defer client.lock.RUnlock()
  138. ret := make([]string, 0, len(client.metadata))
  139. for topic := range client.metadata {
  140. ret = append(ret, topic)
  141. }
  142. return ret, nil
  143. }
  144. func (client *client) Partitions(topic string) ([]int32, error) {
  145. // Check to see whether the client is closed
  146. if client.Closed() {
  147. return nil, ErrClosedClient
  148. }
  149. partitions := client.cachedPartitions(topic, allPartitions)
  150. if len(partitions) == 0 {
  151. err := client.RefreshTopicMetadata(topic)
  152. if err != nil {
  153. return nil, err
  154. }
  155. partitions = client.cachedPartitions(topic, allPartitions)
  156. }
  157. if partitions == nil {
  158. return nil, ErrUnknownTopicOrPartition
  159. }
  160. return partitions, nil
  161. }
  162. func (client *client) WritablePartitions(topic string) ([]int32, error) {
  163. // Check to see whether the client is closed
  164. if client.Closed() {
  165. return nil, ErrClosedClient
  166. }
  167. partitions := client.cachedPartitions(topic, writablePartitions)
  168. // len==0 catches when it's nil (no such topic) and the odd case when every single
  169. // partition is undergoing leader election simultaneously. Callers have to be able to handle
  170. // this function returning an empty slice (which is a valid return value) but catching it
  171. // here the first time (note we *don't* catch it below where we return ErrUnknownTopicOrPartition) triggers
  172. // a metadata refresh as a nicety so callers can just try again and don't have to manually
  173. // trigger a refresh (otherwise they'd just keep getting a stale cached copy).
  174. if len(partitions) == 0 {
  175. err := client.RefreshTopicMetadata(topic)
  176. if err != nil {
  177. return nil, err
  178. }
  179. partitions = client.cachedPartitions(topic, writablePartitions)
  180. }
  181. if partitions == nil {
  182. return nil, ErrUnknownTopicOrPartition
  183. }
  184. return partitions, nil
  185. }
  186. func (client *client) Replicas(topic string, partitionID int32) ([]int32, error) {
  187. if client.Closed() {
  188. return nil, ErrClosedClient
  189. }
  190. metadata, err := client.getMetadata(topic, partitionID)
  191. if err != nil {
  192. return nil, err
  193. }
  194. if metadata.Err == ErrReplicaNotAvailable {
  195. return nil, metadata.Err
  196. }
  197. return dupeAndSort(metadata.Replicas), nil
  198. }
  199. func (client *client) ReplicasInSync(topic string, partitionID int32) ([]int32, error) {
  200. if client.Closed() {
  201. return nil, ErrClosedClient
  202. }
  203. metadata, err := client.getMetadata(topic, partitionID)
  204. if err != nil {
  205. return nil, err
  206. }
  207. if metadata.Err == ErrReplicaNotAvailable {
  208. return nil, metadata.Err
  209. }
  210. return dupeAndSort(metadata.Isr), nil
  211. }
  212. func (client *client) Leader(topic string, partitionID int32) (*Broker, error) {
  213. leader, err := client.cachedLeader(topic, partitionID)
  214. if leader == nil {
  215. err := client.RefreshTopicMetadata(topic)
  216. if err != nil {
  217. return nil, err
  218. }
  219. leader, err = client.cachedLeader(topic, partitionID)
  220. }
  221. return leader, err
  222. }
  223. func (client *client) RefreshTopicMetadata(topics ...string) error {
  224. return client.refreshMetadata(topics, client.conf.Metadata.Retry.Max)
  225. }
  226. func (client *client) RefreshAllMetadata() error {
  227. // Kafka refreshes all when you encode it an empty array...
  228. return client.refreshMetadata(make([]string, 0), client.conf.Metadata.Retry.Max)
  229. }
  230. func (client *client) GetOffset(topic string, partitionID int32, where OffsetTime) (int64, error) {
  231. broker, err := client.Leader(topic, partitionID)
  232. if err != nil {
  233. return -1, err
  234. }
  235. request := &OffsetRequest{}
  236. request.AddBlock(topic, partitionID, where, 1)
  237. response, err := broker.GetAvailableOffsets(request)
  238. if err != nil {
  239. return -1, err
  240. }
  241. block := response.GetBlock(topic, partitionID)
  242. if block == nil {
  243. return -1, ErrIncompleteResponse
  244. }
  245. if block.Err != ErrNoError {
  246. return -1, block.Err
  247. }
  248. if len(block.Offsets) != 1 {
  249. return -1, ErrOffsetOutOfRange
  250. }
  251. return block.Offsets[0], nil
  252. }
  253. // private broker management helpers
  254. // XXX: see https://github.com/Shopify/sarama/issues/15
  255. // and https://github.com/Shopify/sarama/issues/23
  256. // disconnectBroker is a bad hacky way to accomplish broker management. It should be replaced with
  257. // something sane and the replacement should be made part of the public Client API
  258. func (client *client) disconnectBroker(broker *Broker) {
  259. client.lock.Lock()
  260. defer client.lock.Unlock()
  261. Logger.Printf("Disconnecting Broker %d\n", broker.ID())
  262. client.deadBrokerAddrs[broker.addr] = none{}
  263. if broker == client.seedBroker {
  264. client.seedBrokerAddrs = client.seedBrokerAddrs[1:]
  265. if len(client.seedBrokerAddrs) > 0 {
  266. client.seedBroker = NewBroker(client.seedBrokerAddrs[0])
  267. _ = client.seedBroker.Open(client.conf)
  268. } else {
  269. client.seedBroker = nil
  270. }
  271. } else {
  272. // we don't need to update the leaders hash, it will automatically get refreshed next time because
  273. // the broker lookup will return nil
  274. delete(client.brokers, broker.ID())
  275. }
  276. safeAsyncClose(broker)
  277. }
  278. func (client *client) resurrectDeadBrokers() {
  279. client.lock.Lock()
  280. defer client.lock.Unlock()
  281. for _, addr := range client.seedBrokerAddrs {
  282. client.deadBrokerAddrs[addr] = none{}
  283. }
  284. client.seedBrokerAddrs = []string{}
  285. for addr := range client.deadBrokerAddrs {
  286. client.seedBrokerAddrs = append(client.seedBrokerAddrs, addr)
  287. }
  288. client.deadBrokerAddrs = make(map[string]none)
  289. client.seedBroker = NewBroker(client.seedBrokerAddrs[0])
  290. _ = client.seedBroker.Open(client.conf)
  291. }
  292. func (client *client) any() *Broker {
  293. client.lock.RLock()
  294. defer client.lock.RUnlock()
  295. if client.seedBroker != nil {
  296. _ = client.seedBroker.Open(client.conf)
  297. return client.seedBroker
  298. }
  299. for _, broker := range client.brokers {
  300. _ = broker.Open(client.conf)
  301. return broker
  302. }
  303. return nil
  304. }
  305. // private caching/lazy metadata helpers
  306. type partitionType int
  307. const (
  308. allPartitions partitionType = iota
  309. writablePartitions
  310. // If you add any more types, update the partition cache in update()
  311. // Ensure this is the last partition type value
  312. maxPartitionIndex
  313. )
  314. func (client *client) getMetadata(topic string, partitionID int32) (*PartitionMetadata, error) {
  315. metadata := client.cachedMetadata(topic, partitionID)
  316. if metadata == nil {
  317. err := client.RefreshTopicMetadata(topic)
  318. if err != nil {
  319. return nil, err
  320. }
  321. metadata = client.cachedMetadata(topic, partitionID)
  322. }
  323. if metadata == nil {
  324. return nil, ErrUnknownTopicOrPartition
  325. }
  326. return metadata, nil
  327. }
  328. func (client *client) cachedMetadata(topic string, partitionID int32) *PartitionMetadata {
  329. client.lock.RLock()
  330. defer client.lock.RUnlock()
  331. partitions := client.metadata[topic]
  332. if partitions != nil {
  333. return partitions[partitionID]
  334. }
  335. return nil
  336. }
  337. func (client *client) cachedPartitions(topic string, partitionSet partitionType) []int32 {
  338. client.lock.RLock()
  339. defer client.lock.RUnlock()
  340. partitions, exists := client.cachedPartitionsResults[topic]
  341. if !exists {
  342. return nil
  343. }
  344. return partitions[partitionSet]
  345. }
  346. func (client *client) setPartitionCache(topic string, partitionSet partitionType) []int32 {
  347. partitions := client.metadata[topic]
  348. if partitions == nil {
  349. return nil
  350. }
  351. ret := make([]int32, 0, len(partitions))
  352. for _, partition := range partitions {
  353. if partitionSet == writablePartitions && partition.Err == ErrLeaderNotAvailable {
  354. continue
  355. }
  356. ret = append(ret, partition.ID)
  357. }
  358. sort.Sort(int32Slice(ret))
  359. return ret
  360. }
  361. func (client *client) cachedLeader(topic string, partitionID int32) (*Broker, error) {
  362. client.lock.RLock()
  363. defer client.lock.RUnlock()
  364. partitions := client.metadata[topic]
  365. if partitions != nil {
  366. metadata, ok := partitions[partitionID]
  367. if ok {
  368. if metadata.Err == ErrLeaderNotAvailable {
  369. return nil, ErrLeaderNotAvailable
  370. }
  371. b := client.brokers[metadata.Leader]
  372. if b == nil {
  373. return nil, ErrLeaderNotAvailable
  374. }
  375. _ = b.Open(client.conf)
  376. return b, nil
  377. }
  378. }
  379. return nil, ErrUnknownTopicOrPartition
  380. }
  381. // core metadata update logic
  382. func (client *client) backgroundMetadataUpdater() {
  383. if client.conf.Metadata.RefreshFrequency == time.Duration(0) {
  384. return
  385. }
  386. ticker := time.NewTicker(client.conf.Metadata.RefreshFrequency)
  387. for {
  388. select {
  389. case <-ticker.C:
  390. if err := client.RefreshAllMetadata(); err != nil {
  391. Logger.Println("Client background metadata update:", err)
  392. }
  393. case <-client.closer:
  394. ticker.Stop()
  395. return
  396. }
  397. }
  398. }
  399. func (client *client) refreshMetadata(topics []string, retriesRemaining int) error {
  400. // This function is a sort of central point for most functions that create new
  401. // resources. Check to see if we're dealing with a closed Client and error
  402. // out immediately if so.
  403. if client.Closed() {
  404. return ErrClosedClient
  405. }
  406. // Prior to 0.8.2, Kafka will throw exceptions on an empty topic and not return a proper
  407. // error. This handles the case by returning an error instead of sending it
  408. // off to Kafka. See: https://github.com/Shopify/sarama/pull/38#issuecomment-26362310
  409. for _, topic := range topics {
  410. if len(topic) == 0 {
  411. return ErrInvalidTopic // this is the error that 0.8.2 and later correctly return
  412. }
  413. }
  414. for broker := client.any(); broker != nil; broker = client.any() {
  415. if len(topics) > 0 {
  416. Logger.Printf("Fetching metadata for %v from broker %s\n", topics, broker.addr)
  417. } else {
  418. Logger.Printf("Fetching metadata for all topics from broker %s\n", broker.addr)
  419. }
  420. response, err := broker.GetMetadata(&MetadataRequest{Topics: topics})
  421. switch err.(type) {
  422. case nil:
  423. // valid response, use it
  424. retry, err := client.update(response)
  425. if len(retry) > 0 {
  426. if retriesRemaining <= 0 {
  427. Logger.Println("Some partitions are leaderless, but we're out of retries")
  428. return nil
  429. }
  430. Logger.Printf("Some partitions are leaderless, waiting %dms for election... (%d retries remaining)\n",
  431. client.conf.Metadata.Retry.Backoff/time.Millisecond, retriesRemaining)
  432. time.Sleep(client.conf.Metadata.Retry.Backoff) // wait for leader election
  433. return client.refreshMetadata(retry, retriesRemaining-1)
  434. }
  435. return err
  436. case PacketEncodingError:
  437. // didn't even send, return the error
  438. return err
  439. default:
  440. // some other error, remove that broker and try again
  441. Logger.Println("Error from broker while fetching metadata:", err)
  442. client.disconnectBroker(broker)
  443. }
  444. }
  445. Logger.Println("Out of available brokers.")
  446. if retriesRemaining > 0 {
  447. Logger.Printf("Resurrecting dead brokers after %dms... (%d retries remaining)\n",
  448. client.conf.Metadata.Retry.Backoff/time.Millisecond, retriesRemaining)
  449. time.Sleep(client.conf.Metadata.Retry.Backoff)
  450. client.resurrectDeadBrokers()
  451. return client.refreshMetadata(topics, retriesRemaining-1)
  452. }
  453. return ErrOutOfBrokers
  454. }
  455. // if no fatal error, returns a list of topics that need retrying due to ErrLeaderNotAvailable
  456. func (client *client) update(data *MetadataResponse) ([]string, error) {
  457. client.lock.Lock()
  458. defer client.lock.Unlock()
  459. // For all the brokers we received:
  460. // - if it is a new ID, save it
  461. // - if it is an existing ID, but the address we have is stale, discard the old one and save it
  462. // - otherwise ignore it, replacing our existing one would just bounce the connection
  463. for _, broker := range data.Brokers {
  464. if client.brokers[broker.ID()] == nil {
  465. client.brokers[broker.ID()] = broker
  466. Logger.Printf("Registered new broker #%d at %s", broker.ID(), broker.Addr())
  467. } else if broker.Addr() != client.brokers[broker.ID()].Addr() {
  468. safeAsyncClose(client.brokers[broker.ID()])
  469. client.brokers[broker.ID()] = broker
  470. Logger.Printf("Replaced registered broker #%d with %s", broker.ID(), broker.Addr())
  471. }
  472. }
  473. toRetry := make(map[string]bool)
  474. var err error
  475. for _, topic := range data.Topics {
  476. switch topic.Err {
  477. case ErrNoError:
  478. break
  479. case ErrLeaderNotAvailable, ErrUnknownTopicOrPartition:
  480. toRetry[topic.Name] = true
  481. default:
  482. err = topic.Err
  483. }
  484. client.metadata[topic.Name] = make(map[int32]*PartitionMetadata, len(topic.Partitions))
  485. delete(client.cachedPartitionsResults, topic.Name)
  486. for _, partition := range topic.Partitions {
  487. client.metadata[topic.Name][partition.ID] = partition
  488. if partition.Err == ErrLeaderNotAvailable {
  489. toRetry[topic.Name] = true
  490. }
  491. }
  492. var partitionCache [maxPartitionIndex][]int32
  493. partitionCache[allPartitions] = client.setPartitionCache(topic.Name, allPartitions)
  494. partitionCache[writablePartitions] = client.setPartitionCache(topic.Name, writablePartitions)
  495. client.cachedPartitionsResults[topic.Name] = partitionCache
  496. }
  497. if err != nil {
  498. return nil, err
  499. }
  500. ret := make([]string, 0, len(toRetry))
  501. for topic := range toRetry {
  502. ret = append(ret, topic)
  503. }
  504. return ret, nil
  505. }