client.go 8.7 KB

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