client.go 18 KB

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