client.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. brokers map[int32]*Broker // maps broker ids to brokers
  20. leaders map[string]map[int32]int32 // maps topics to partition ids to broker ids
  21. lock sync.RWMutex // protects access to the maps, only one since they're always written together
  22. }
  23. // NewClient creates a new Client with the given client ID. It connects to the broker at the given
  24. // host:port address, and uses that broker to automatically fetch metadata on the rest of the kafka cluster.
  25. // If metadata cannot be retrieved (even if the connection otherwise succeeds) then the client is not created.
  26. func NewClient(id string, host string, port int32, config ClientConfig) (client *Client, err error) {
  27. if config.MetadataRetries < 0 {
  28. return nil, ConfigurationError("Invalid MetadataRetries")
  29. }
  30. tmp := NewBroker(host, port)
  31. err = tmp.Connect()
  32. if err != nil {
  33. return nil, err
  34. }
  35. client = new(Client)
  36. client.id = id
  37. client.config = config
  38. client.brokers = make(map[int32]*Broker)
  39. client.leaders = make(map[string]map[int32]int32)
  40. // add it to the set so that refreshTopics can find it
  41. // brokers created through NewBroker() have an ID of -1, which won't conflict with
  42. // whatever the metadata request returns
  43. client.brokers[tmp.ID()] = tmp
  44. // do an initial fetch of all cluster metadata by specifing an empty list of topics
  45. err = client.refreshTopics(make([]string, 0), client.config.MetadataRetries)
  46. if err != nil {
  47. client.Close() // this closes tmp, since it's still in the brokers hash
  48. return nil, err
  49. }
  50. // So apparently a kafka broker is not required to return its own address in response
  51. // to a 'give me *all* the metadata request'... I'm not sure if that's because you're
  52. // assumed to have it already or what. Regardless, this means that we can't assume we can
  53. // disconnect our tmp broker here, since if it didn't return itself to us we want to keep
  54. // it around anyways. The worst that happens is we end up with two connections to the same
  55. // broker, one with ID -1 and one with the real ID.
  56. return client, nil
  57. }
  58. // Close shuts down all broker connections managed by this client. It is required to call this function before
  59. // a client object passes out of scope, as it will otherwise leak memory. You must close any Producers or Consumers
  60. // using a client before you close the client.
  61. func (client *Client) Close() {
  62. client.lock.Lock()
  63. defer client.lock.Unlock()
  64. for _, broker := range client.brokers {
  65. go broker.Close()
  66. }
  67. client.brokers = nil
  68. client.leaders = nil
  69. }
  70. // functions for use by producers and consumers
  71. // if Go had the concept they would be marked 'protected'
  72. func (client *Client) leader(topic string, partition_id int32) (*Broker, error) {
  73. leader := client.cachedLeader(topic, partition_id)
  74. if leader == nil {
  75. err := client.refreshTopic(topic)
  76. if err != nil {
  77. return nil, err
  78. }
  79. leader = client.cachedLeader(topic, partition_id)
  80. }
  81. if leader == nil {
  82. return nil, UNKNOWN_TOPIC_OR_PARTITION
  83. }
  84. return leader, nil
  85. }
  86. func (client *Client) partitions(topic string) ([]int32, error) {
  87. partitions := client.cachedPartitions(topic)
  88. if partitions == nil {
  89. err := client.refreshTopic(topic)
  90. if err != nil {
  91. return nil, err
  92. }
  93. partitions = client.cachedPartitions(topic)
  94. }
  95. if partitions == nil {
  96. return nil, NoSuchTopic
  97. }
  98. return partitions, nil
  99. }
  100. func (client *Client) disconnectBroker(broker *Broker) {
  101. client.lock.Lock()
  102. defer client.lock.Unlock()
  103. // we don't need to update the leaders hash, it will automatically get refreshed next time because
  104. // the broker lookup will return nil
  105. delete(client.brokers, broker.ID())
  106. go broker.Close()
  107. }
  108. func (client *Client) refreshTopic(topic string) error {
  109. tmp := make([]string, 1)
  110. tmp[0] = topic
  111. // we permit three retries by default, 'cause that seemed like a nice number
  112. return client.refreshTopics(tmp, client.config.MetadataRetries)
  113. }
  114. // truly private helper functions
  115. func (client *Client) refreshTopics(topics []string, retries int) error {
  116. for broker := client.any(); broker != nil; broker = client.any() {
  117. response, err := broker.GetMetadata(client.id, &MetadataRequest{Topics: topics})
  118. switch err {
  119. case nil:
  120. // valid response, use it
  121. retry, err := client.update(response)
  122. switch {
  123. case err != nil:
  124. return err
  125. case len(retry) == 0:
  126. return nil
  127. default:
  128. if retries <= 0 {
  129. return LEADER_NOT_AVAILABLE
  130. }
  131. time.Sleep(client.config.WaitForElection) // wait for leader election
  132. return client.refreshTopics(retry, retries-1)
  133. }
  134. case EncodingError:
  135. // didn't even send, return the error
  136. return err
  137. }
  138. // some other error, remove that broker and try again
  139. client.disconnectBroker(broker)
  140. }
  141. return OutOfBrokers
  142. }
  143. func (client *Client) any() *Broker {
  144. client.lock.RLock()
  145. defer client.lock.RUnlock()
  146. for _, broker := range client.brokers {
  147. return broker
  148. }
  149. return nil
  150. }
  151. func (client *Client) cachedLeader(topic string, partition_id int32) *Broker {
  152. client.lock.RLock()
  153. defer client.lock.RUnlock()
  154. partitions := client.leaders[topic]
  155. if partitions != nil {
  156. leader, ok := partitions[partition_id]
  157. if ok && leader != -1 {
  158. return client.brokers[leader]
  159. }
  160. }
  161. return nil
  162. }
  163. func (client *Client) cachedPartitions(topic string) []int32 {
  164. client.lock.RLock()
  165. defer client.lock.RUnlock()
  166. partitions := client.leaders[topic]
  167. if partitions == nil {
  168. return nil
  169. }
  170. ret := make([]int32, 0, len(partitions))
  171. for id, _ := range partitions {
  172. ret = append(ret, id)
  173. }
  174. sort.Sort(int32Slice(ret))
  175. return ret
  176. }
  177. // if no fatal error, returns a list of topics that need retrying due to LEADER_NOT_AVAILABLE
  178. func (client *Client) update(data *MetadataResponse) ([]string, error) {
  179. // First discard brokers that we already know about. This avoids bouncing TCP connections,
  180. // and especially avoids closing valid connections out from under other code which may be trying
  181. // to use them. We only need a read-lock for this.
  182. var newBrokers []*Broker
  183. client.lock.RLock()
  184. for _, broker := range data.Brokers {
  185. if !broker.Equals(client.brokers[broker.ID()]) {
  186. newBrokers = append(newBrokers, broker)
  187. }
  188. }
  189. client.lock.RUnlock()
  190. // connect to the brokers before taking the write lock, as this can take a while
  191. // to timeout if one of them isn't reachable
  192. for _, broker := range newBrokers {
  193. err := broker.Connect()
  194. if err != nil {
  195. return nil, err
  196. }
  197. }
  198. client.lock.Lock()
  199. defer client.lock.Unlock()
  200. for _, broker := range newBrokers {
  201. if client.brokers[broker.ID()] != nil {
  202. go client.brokers[broker.ID()].Close()
  203. }
  204. client.brokers[broker.ID()] = broker
  205. }
  206. toRetry := make(map[string]bool)
  207. for _, topic := range data.Topics {
  208. switch topic.Err {
  209. case NO_ERROR:
  210. break
  211. case LEADER_NOT_AVAILABLE:
  212. toRetry[topic.Name] = true
  213. default:
  214. return nil, topic.Err
  215. }
  216. client.leaders[topic.Name] = make(map[int32]int32, len(topic.Partitions))
  217. for _, partition := range topic.Partitions {
  218. switch partition.Err {
  219. case LEADER_NOT_AVAILABLE:
  220. // in the LEADER_NOT_AVAILABLE case partition.Leader will be -1 because the
  221. // partition is in the middle of leader election, so we fallthrough to save it
  222. // anyways in order to avoid returning the stale leader (since -1 isn't a valid broker ID)
  223. toRetry[topic.Name] = true
  224. fallthrough
  225. case NO_ERROR:
  226. client.leaders[topic.Name][partition.Id] = partition.Leader
  227. default:
  228. return nil, partition.Err
  229. }
  230. }
  231. }
  232. ret := make([]string, 0, len(toRetry))
  233. for topic, _ := range toRetry {
  234. ret = append(ret, topic)
  235. }
  236. return ret, nil
  237. }