client.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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. broker, err := client.Leader(topic, partitionID)
  237. if err != nil {
  238. return -1, err
  239. }
  240. request := &OffsetRequest{}
  241. request.AddBlock(topic, partitionID, time, 1)
  242. response, err := broker.GetAvailableOffsets(request)
  243. if err != nil {
  244. return -1, err
  245. }
  246. block := response.GetBlock(topic, partitionID)
  247. if block == nil {
  248. return -1, ErrIncompleteResponse
  249. }
  250. if block.Err != ErrNoError {
  251. return -1, block.Err
  252. }
  253. if len(block.Offsets) != 1 {
  254. return -1, ErrOffsetOutOfRange
  255. }
  256. return block.Offsets[0], nil
  257. }
  258. // private broker management helpers
  259. func (client *client) disconnectBroker(broker *Broker) {
  260. client.lock.Lock()
  261. defer client.lock.Unlock()
  262. if len(client.seedBrokers) > 0 && broker == client.seedBrokers[0] {
  263. client.deadSeeds = append(client.deadSeeds, broker)
  264. client.seedBrokers = client.seedBrokers[1:]
  265. } else {
  266. // we do this so that our loop in `tryRefreshMetadata` doesn't go on forever,
  267. // but we really shouldn't have to; once that loop is made better this case can be
  268. // removed, and the function generally can be renamed from `disconnectBroker` to
  269. // `nextSeedBroker` or something
  270. delete(client.brokers, broker.ID())
  271. }
  272. }
  273. func (client *client) resurrectDeadBrokers() {
  274. client.lock.Lock()
  275. defer client.lock.Unlock()
  276. client.seedBrokers = append(client.seedBrokers, client.deadSeeds...)
  277. client.deadSeeds = nil
  278. }
  279. func (client *client) any() *Broker {
  280. client.lock.RLock()
  281. defer client.lock.RUnlock()
  282. if len(client.seedBrokers) > 0 {
  283. _ = client.seedBrokers[0].Open(client.conf)
  284. return client.seedBrokers[0]
  285. }
  286. // not guaranteed to be random *or* deterministic
  287. for _, broker := range client.brokers {
  288. _ = broker.Open(client.conf)
  289. return broker
  290. }
  291. return nil
  292. }
  293. // private caching/lazy metadata helpers
  294. type partitionType int
  295. const (
  296. allPartitions partitionType = iota
  297. writablePartitions
  298. // If you add any more types, update the partition cache in update()
  299. // Ensure this is the last partition type value
  300. maxPartitionIndex
  301. )
  302. func (client *client) cachedMetadata(topic string, partitionID int32) *PartitionMetadata {
  303. client.lock.RLock()
  304. defer client.lock.RUnlock()
  305. partitions := client.metadata[topic]
  306. if partitions != nil {
  307. return partitions[partitionID]
  308. }
  309. return nil
  310. }
  311. func (client *client) cachedPartitions(topic string, partitionSet partitionType) []int32 {
  312. client.lock.RLock()
  313. defer client.lock.RUnlock()
  314. partitions, exists := client.cachedPartitionsResults[topic]
  315. if !exists {
  316. return nil
  317. }
  318. return partitions[partitionSet]
  319. }
  320. func (client *client) setPartitionCache(topic string, partitionSet partitionType) []int32 {
  321. partitions := client.metadata[topic]
  322. if partitions == nil {
  323. return nil
  324. }
  325. ret := make([]int32, 0, len(partitions))
  326. for _, partition := range partitions {
  327. if partitionSet == writablePartitions && partition.Err == ErrLeaderNotAvailable {
  328. continue
  329. }
  330. ret = append(ret, partition.ID)
  331. }
  332. sort.Sort(int32Slice(ret))
  333. return ret
  334. }
  335. func (client *client) cachedLeader(topic string, partitionID int32) (*Broker, error) {
  336. client.lock.RLock()
  337. defer client.lock.RUnlock()
  338. partitions := client.metadata[topic]
  339. if partitions != nil {
  340. metadata, ok := partitions[partitionID]
  341. if ok {
  342. if metadata.Err == ErrLeaderNotAvailable {
  343. return nil, ErrLeaderNotAvailable
  344. }
  345. b := client.brokers[metadata.Leader]
  346. if b == nil {
  347. return nil, ErrLeaderNotAvailable
  348. }
  349. _ = b.Open(client.conf)
  350. return b, nil
  351. }
  352. }
  353. return nil, ErrUnknownTopicOrPartition
  354. }
  355. // core metadata update logic
  356. func (client *client) backgroundMetadataUpdater() {
  357. if client.conf.Metadata.RefreshFrequency == time.Duration(0) {
  358. return
  359. }
  360. ticker := time.NewTicker(client.conf.Metadata.RefreshFrequency)
  361. for {
  362. select {
  363. case <-ticker.C:
  364. if err := client.RefreshMetadata(); err != nil {
  365. Logger.Println("Client background metadata update:", err)
  366. }
  367. case <-client.closer:
  368. ticker.Stop()
  369. return
  370. }
  371. }
  372. }
  373. func (client *client) tryRefreshMetadata(topics []string, retriesRemaining int) error {
  374. for broker := client.any(); broker != nil; broker = client.any() {
  375. if len(topics) > 0 {
  376. Logger.Printf("Fetching metadata for %v from broker %s\n", topics, broker.addr)
  377. } else {
  378. Logger.Printf("Fetching metadata for all topics from broker %s\n", broker.addr)
  379. }
  380. response, err := broker.GetMetadata(&MetadataRequest{Topics: topics})
  381. switch err.(type) {
  382. case nil:
  383. // valid response, use it
  384. retry, err := client.updateMetadata(response)
  385. if len(retry) > 0 {
  386. if retriesRemaining <= 0 {
  387. Logger.Println("Some partitions are leaderless, but we're out of retries")
  388. return err
  389. }
  390. Logger.Printf("Some partitions are leaderless, waiting %dms for election... (%d retries remaining)\n",
  391. client.conf.Metadata.Retry.Backoff/time.Millisecond, retriesRemaining)
  392. time.Sleep(client.conf.Metadata.Retry.Backoff) // wait for leader election
  393. return client.tryRefreshMetadata(retry, retriesRemaining-1)
  394. }
  395. return err
  396. case PacketEncodingError:
  397. // didn't even send, return the error
  398. return err
  399. default:
  400. // some other error, remove that broker and try again
  401. Logger.Println("Error from broker while fetching metadata:", err)
  402. _ = broker.Close()
  403. client.disconnectBroker(broker)
  404. }
  405. }
  406. Logger.Println("Out of available brokers.")
  407. if retriesRemaining > 0 {
  408. Logger.Printf("Resurrecting dead brokers after %dms... (%d retries remaining)\n",
  409. client.conf.Metadata.Retry.Backoff/time.Millisecond, retriesRemaining)
  410. time.Sleep(client.conf.Metadata.Retry.Backoff)
  411. client.resurrectDeadBrokers()
  412. return client.tryRefreshMetadata(topics, retriesRemaining-1)
  413. }
  414. return ErrOutOfBrokers
  415. }
  416. // if no fatal error, returns a list of topics that need retrying due to ErrLeaderNotAvailable
  417. func (client *client) updateMetadata(data *MetadataResponse) ([]string, error) {
  418. client.lock.Lock()
  419. defer client.lock.Unlock()
  420. // For all the brokers we received:
  421. // - if it is a new ID, save it
  422. // - if it is an existing ID, but the address we have is stale, discard the old one and save it
  423. // - otherwise ignore it, replacing our existing one would just bounce the connection
  424. for _, broker := range data.Brokers {
  425. if client.brokers[broker.ID()] == nil {
  426. client.brokers[broker.ID()] = broker
  427. Logger.Printf("Registered new broker #%d at %s", broker.ID(), broker.Addr())
  428. } else if broker.Addr() != client.brokers[broker.ID()].Addr() {
  429. safeAsyncClose(client.brokers[broker.ID()])
  430. client.brokers[broker.ID()] = broker
  431. Logger.Printf("Replaced registered broker #%d with %s", broker.ID(), broker.Addr())
  432. }
  433. }
  434. toRetry := make(map[string]bool)
  435. var err error
  436. for _, topic := range data.Topics {
  437. delete(client.metadata, topic.Name)
  438. delete(client.cachedPartitionsResults, topic.Name)
  439. switch topic.Err {
  440. case ErrNoError:
  441. break
  442. case ErrInvalidTopic: // don't retry, don't store partial results
  443. err = topic.Err
  444. continue
  445. case ErrUnknownTopicOrPartition: // retry, do not store partial partition results
  446. err = topic.Err
  447. toRetry[topic.Name] = true
  448. continue
  449. case ErrLeaderNotAvailable: // retry, but store partiial partition results
  450. toRetry[topic.Name] = true
  451. break
  452. default: // don't retry, don't store partial results
  453. Logger.Printf("Unexpected topic-level metadata error: %s", topic.Err)
  454. err = topic.Err
  455. continue
  456. }
  457. client.metadata[topic.Name] = make(map[int32]*PartitionMetadata, len(topic.Partitions))
  458. for _, partition := range topic.Partitions {
  459. client.metadata[topic.Name][partition.ID] = partition
  460. if partition.Err == ErrLeaderNotAvailable {
  461. toRetry[topic.Name] = true
  462. }
  463. }
  464. var partitionCache [maxPartitionIndex][]int32
  465. partitionCache[allPartitions] = client.setPartitionCache(topic.Name, allPartitions)
  466. partitionCache[writablePartitions] = client.setPartitionCache(topic.Name, writablePartitions)
  467. client.cachedPartitionsResults[topic.Name] = partitionCache
  468. }
  469. ret := make([]string, 0, len(toRetry))
  470. for topic := range toRetry {
  471. ret = append(ret, topic)
  472. }
  473. return ret, err
  474. }