client.go 18 KB

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