client.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. ConcurrencyPerBroker int // How many outstanding requests each broker is allowed to have.
  12. }
  13. // Client is a generic Kafka client. It manages connections to one or more Kafka brokers.
  14. // You MUST call Close() on a client to avoid leaks, it will not be garbage-collected
  15. // automatically when it passes out of scope. A single client can be safely shared by
  16. // multiple concurrent Producers and Consumers.
  17. type Client struct {
  18. id string
  19. config ClientConfig
  20. // the broker addresses given to us through the constructor are not guaranteed to be returned in
  21. // the cluster metadata (I *think* it only returns brokers who are currently leading partitions?)
  22. // so we store them separately
  23. extraBrokerAddrs []string
  24. extraBroker *Broker
  25. brokers map[int32]*Broker // maps broker ids to brokers
  26. leaders map[string]map[int32]int32 // maps topics to partition ids to broker ids
  27. lock sync.RWMutex // protects access to the maps, only one since they're always written together
  28. }
  29. // NewClient creates a new Client with the given client ID. It connects to one of the given broker addresses
  30. // and uses that broker to automatically fetch metadata on the rest of the kafka cluster. If metadata cannot
  31. // be retrieved from any of the given broker addresses, the client is not created.
  32. func NewClient(id string, addrs []string, config *ClientConfig) (*Client, error) {
  33. if config == nil {
  34. config = new(ClientConfig)
  35. }
  36. if config.MetadataRetries < 0 {
  37. return nil, ConfigurationError("Invalid MetadataRetries")
  38. }
  39. if config.ConcurrencyPerBroker < 0 {
  40. return nil, ConfigurationError("Invalid ConcurrencyPerBroker")
  41. }
  42. if len(addrs) < 1 {
  43. return nil, ConfigurationError("You must provide at least one broker address")
  44. }
  45. client := &Client{
  46. id: id,
  47. config: *config,
  48. extraBrokerAddrs: addrs,
  49. extraBroker: NewBroker(addrs[0]),
  50. brokers: make(map[int32]*Broker),
  51. leaders: make(map[string]map[int32]int32),
  52. }
  53. client.extraBroker.Open(config.ConcurrencyPerBroker)
  54. // do an initial fetch of all cluster metadata by specifing an empty list of topics
  55. err := client.RefreshAllMetadata()
  56. if err != nil {
  57. client.Close() // this closes tmp, since it's still in the brokers hash
  58. return nil, err
  59. }
  60. return client, nil
  61. }
  62. // Close shuts down all broker connections managed by this client. It is required to call this function before
  63. // a client object passes out of scope, as it will otherwise leak memory. You must close any Producers or Consumers
  64. // using a client before you close the client.
  65. func (client *Client) Close() error {
  66. client.lock.Lock()
  67. defer client.lock.Unlock()
  68. for _, broker := range client.brokers {
  69. myBroker := broker // NB: block-local prevents clobbering
  70. go withRecover(func() { myBroker.Close() })
  71. }
  72. client.brokers = nil
  73. client.leaders = nil
  74. if client.extraBroker != nil {
  75. go withRecover(func() { client.extraBroker.Close() })
  76. }
  77. return nil
  78. }
  79. // Partitions returns the sorted list of available partition IDs for the given topic.
  80. func (client *Client) Partitions(topic string) ([]int32, error) {
  81. partitions := client.cachedPartitions(topic)
  82. if partitions == nil {
  83. err := client.RefreshTopicMetadata(topic)
  84. if err != nil {
  85. return nil, err
  86. }
  87. partitions = client.cachedPartitions(topic)
  88. }
  89. if partitions == nil {
  90. return nil, NoSuchTopic
  91. }
  92. return partitions, nil
  93. }
  94. // Topics returns the set of available topics as retrieved from the cluster metadata.
  95. func (client *Client) Topics() ([]string, error) {
  96. client.lock.RLock()
  97. defer client.lock.RUnlock()
  98. ret := make([]string, 0, len(client.leaders))
  99. for topic := range client.leaders {
  100. ret = append(ret, topic)
  101. }
  102. return ret, nil
  103. }
  104. // Leader returns the broker object that is the leader of the current topic/partition, as
  105. // determined by querying the cluster metadata.
  106. func (client *Client) Leader(topic string, partitionID int32) (*Broker, error) {
  107. leader := client.cachedLeader(topic, partitionID)
  108. if leader == nil {
  109. err := client.RefreshTopicMetadata(topic)
  110. if err != nil {
  111. return nil, err
  112. }
  113. leader = client.cachedLeader(topic, partitionID)
  114. }
  115. if leader == nil {
  116. return nil, UnknownTopicOrPartition
  117. }
  118. return leader, nil
  119. }
  120. // RefreshTopicMetadata takes a list of topics and queries the cluster to refresh the
  121. // available metadata for those topics.
  122. func (client *Client) RefreshTopicMetadata(topics ...string) error {
  123. return client.refreshMetadata(topics, client.config.MetadataRetries)
  124. }
  125. // RefreshAllMetadata queries the cluster to refresh the available metadata for all topics.
  126. func (client *Client) RefreshAllMetadata() error {
  127. // Kafka refreshes all when you encode it an empty array...
  128. return client.refreshMetadata(make([]string, 0), client.config.MetadataRetries)
  129. }
  130. // misc private helper functions
  131. // XXX: see https://github.com/Shopify/sarama/issues/15
  132. // and https://github.com/Shopify/sarama/issues/23
  133. // disconnectBroker is a bad hacky way to accomplish broker management. It should be replaced with
  134. // something sane and the replacement should be made part of the public Client API
  135. func (client *Client) disconnectBroker(broker *Broker) {
  136. client.lock.Lock()
  137. defer client.lock.Unlock()
  138. if broker == client.extraBroker {
  139. client.extraBrokerAddrs = client.extraBrokerAddrs[1:]
  140. if len(client.extraBrokerAddrs) > 0 {
  141. client.extraBroker = NewBroker(client.extraBrokerAddrs[0])
  142. client.extraBroker.Open(client.config.ConcurrencyPerBroker)
  143. } else {
  144. client.extraBroker = nil
  145. }
  146. } else {
  147. // we don't need to update the leaders hash, it will automatically get refreshed next time because
  148. // the broker lookup will return nil
  149. delete(client.brokers, broker.ID())
  150. }
  151. myBroker := broker // NB: block-local prevents clobbering
  152. go withRecover(func() { myBroker.Close() })
  153. }
  154. func (client *Client) refreshMetadata(topics []string, retries int) error {
  155. // Kafka will throw exceptions on an empty topic and not return a proper
  156. // error. This handles the case by returning an error instead of sending it
  157. // off to Kafka. See: https://github.com/Shopify/sarama/pull/38#issuecomment-26362310
  158. for _, topic := range topics {
  159. if len(topic) == 0 {
  160. return NoSuchTopic
  161. }
  162. }
  163. for broker := client.any(); broker != nil; broker = client.any() {
  164. response, err := broker.GetMetadata(client.id, &MetadataRequest{Topics: topics})
  165. switch err {
  166. case nil:
  167. // valid response, use it
  168. retry, err := client.update(response)
  169. switch {
  170. case err != nil:
  171. return err
  172. case len(retry) == 0:
  173. return nil
  174. default:
  175. if retries <= 0 {
  176. return LeaderNotAvailable
  177. }
  178. time.Sleep(client.config.WaitForElection) // wait for leader election
  179. return client.refreshMetadata(retry, retries-1)
  180. }
  181. case EncodingError:
  182. // didn't even send, return the error
  183. return err
  184. }
  185. // some other error, remove that broker and try again
  186. client.disconnectBroker(broker)
  187. }
  188. return OutOfBrokers
  189. }
  190. func (client *Client) any() *Broker {
  191. client.lock.RLock()
  192. defer client.lock.RUnlock()
  193. for _, broker := range client.brokers {
  194. return broker
  195. }
  196. return client.extraBroker
  197. }
  198. func (client *Client) cachedLeader(topic string, partitionID int32) *Broker {
  199. client.lock.RLock()
  200. defer client.lock.RUnlock()
  201. partitions := client.leaders[topic]
  202. if partitions != nil {
  203. leader, ok := partitions[partitionID]
  204. if ok {
  205. return client.brokers[leader]
  206. }
  207. }
  208. return nil
  209. }
  210. func (client *Client) cachedPartitions(topic string) []int32 {
  211. client.lock.RLock()
  212. defer client.lock.RUnlock()
  213. partitions := client.leaders[topic]
  214. if partitions == nil {
  215. return nil
  216. }
  217. ret := make([]int32, 0, len(partitions))
  218. for id := range partitions {
  219. ret = append(ret, id)
  220. }
  221. sort.Sort(int32Slice(ret))
  222. return ret
  223. }
  224. // if no fatal error, returns a list of topics that need retrying due to LeaderNotAvailable
  225. func (client *Client) update(data *MetadataResponse) ([]string, error) {
  226. client.lock.Lock()
  227. defer client.lock.Unlock()
  228. // For all the brokers we received:
  229. // - if it is a new ID, save it
  230. // - if it is an existing ID, but the address we have is stale, discard the old one and save it
  231. // - otherwise ignore it, replacing our existing one would just bounce the connection
  232. // We asynchronously try to open connections to the new brokers. We don't care if they
  233. // fail, since maybe that broker is unreachable but doesn't have a topic we care about.
  234. // If it fails and we do care, whoever tries to use it will get the connection error.
  235. for _, broker := range data.Brokers {
  236. if client.brokers[broker.ID()] == nil {
  237. broker.Open(client.config.ConcurrencyPerBroker)
  238. client.brokers[broker.ID()] = broker
  239. Logger.Printf("Registered new broker #%d at %s", broker.ID(), broker.Addr())
  240. } else if broker.Addr() != client.brokers[broker.ID()].Addr() {
  241. myBroker := client.brokers[broker.ID()] // use block-local to prevent clobbering `broker` for Gs
  242. go withRecover(func() { myBroker.Close() })
  243. broker.Open(client.config.ConcurrencyPerBroker)
  244. client.brokers[broker.ID()] = broker
  245. Logger.Printf("Replaced registered broker #%d with %s", broker.ID(), broker.Addr())
  246. }
  247. }
  248. toRetry := make(map[string]bool)
  249. for _, topic := range data.Topics {
  250. switch topic.Err {
  251. case NoError:
  252. break
  253. case LeaderNotAvailable:
  254. toRetry[topic.Name] = true
  255. default:
  256. return nil, topic.Err
  257. }
  258. client.leaders[topic.Name] = make(map[int32]int32, len(topic.Partitions))
  259. for _, partition := range topic.Partitions {
  260. switch partition.Err {
  261. case LeaderNotAvailable:
  262. toRetry[topic.Name] = true
  263. delete(client.leaders[topic.Name], partition.ID)
  264. case NoError:
  265. client.leaders[topic.Name][partition.ID] = partition.Leader
  266. default:
  267. return nil, partition.Err
  268. }
  269. }
  270. }
  271. ret := make([]string, 0, len(toRetry))
  272. for topic := range toRetry {
  273. ret = append(ret, topic)
  274. }
  275. return ret, nil
  276. }