123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394 |
- package sarama
- import (
- "sort"
- "sync"
- "time"
- )
- type ClientConfig struct {
- MetadataRetries int
- WaitForElection time.Duration
- ConcurrencyPerBroker int
- }
- type Client struct {
- id string
- config ClientConfig
-
-
-
- extraBrokerAddrs []string
- extraBroker *Broker
- deadBrokerAddrs []string
- brokers map[int32]*Broker
- leaders map[string]map[int32]int32
- lock sync.RWMutex
- }
- func NewClient(id string, addrs []string, config *ClientConfig) (*Client, error) {
- Logger.Println("Initializing new client")
- if config == nil {
- config = NewClientConfig()
- }
- if err := config.Validate(); err != nil {
- return nil, err
- }
- if len(addrs) < 1 {
- return nil, ConfigurationError("You must provide at least one broker address")
- }
- client := &Client{
- id: id,
- config: *config,
- extraBrokerAddrs: addrs,
- extraBroker: NewBroker(addrs[0]),
- brokers: make(map[int32]*Broker),
- leaders: make(map[string]map[int32]int32),
- }
- client.extraBroker.Open(config.ConcurrencyPerBroker)
-
- err := client.RefreshAllMetadata()
- if err != nil {
- client.Close()
- return nil, err
- }
- Logger.Println("Successfully initialized new client")
- return client, nil
- }
- func (client *Client) Close() error {
- client.lock.Lock()
- defer client.lock.Unlock()
- Logger.Println("Closing Client")
- for _, broker := range client.brokers {
- myBroker := broker
- go withRecover(func() { myBroker.Close() })
- }
- client.brokers = nil
- client.leaders = nil
- if client.extraBroker != nil {
- go withRecover(func() { client.extraBroker.Close() })
- }
- return nil
- }
- func (client *Client) Partitions(topic string) ([]int32, error) {
- partitions := client.cachedPartitions(topic)
- if partitions == nil {
- err := client.RefreshTopicMetadata(topic)
- if err != nil {
- return nil, err
- }
- partitions = client.cachedPartitions(topic)
- }
- if partitions == nil {
- return nil, NoSuchTopic
- }
- return partitions, nil
- }
- func (client *Client) Topics() ([]string, error) {
- client.lock.RLock()
- defer client.lock.RUnlock()
- ret := make([]string, 0, len(client.leaders))
- for topic := range client.leaders {
- ret = append(ret, topic)
- }
- return ret, nil
- }
- func (client *Client) Leader(topic string, partitionID int32) (*Broker, error) {
- leader := client.cachedLeader(topic, partitionID)
- if leader == nil {
- err := client.RefreshTopicMetadata(topic)
- if err != nil {
- return nil, err
- }
- leader = client.cachedLeader(topic, partitionID)
- }
- if leader == nil {
- return nil, UnknownTopicOrPartition
- }
- return leader, nil
- }
- func (client *Client) RefreshTopicMetadata(topics ...string) error {
- return client.refreshMetadata(topics, client.config.MetadataRetries)
- }
- func (client *Client) RefreshAllMetadata() error {
-
- return client.refreshMetadata(make([]string, 0), client.config.MetadataRetries)
- }
- func (client *Client) disconnectBroker(broker *Broker) {
- client.lock.Lock()
- defer client.lock.Unlock()
- Logger.Printf("Disconnecting Broker %d\n", broker.ID())
- client.deadBrokerAddrs = append(client.deadBrokerAddrs, broker.addr)
- if broker == client.extraBroker {
- client.extraBrokerAddrs = client.extraBrokerAddrs[1:]
- if len(client.extraBrokerAddrs) > 0 {
- client.extraBroker = NewBroker(client.extraBrokerAddrs[0])
- client.extraBroker.Open(client.config.ConcurrencyPerBroker)
- } else {
- client.extraBroker = nil
- }
- } else {
-
-
- delete(client.brokers, broker.ID())
- }
- myBroker := broker
- go withRecover(func() { myBroker.Close() })
- }
- func (client *Client) refreshMetadata(topics []string, retries int) error {
-
-
-
- for _, topic := range topics {
- if len(topic) == 0 {
- return NoSuchTopic
- }
- }
- for broker := client.any(); broker != nil; broker = client.any() {
- Logger.Printf("Fetching metadata from broker %s\n", broker.addr)
- response, err := broker.GetMetadata(client.id, &MetadataRequest{Topics: topics})
- switch err {
- case nil:
-
- retry, err := client.update(response)
- switch {
- case err != nil:
- return err
- case len(retry) == 0:
- return nil
- default:
- if retries <= 0 {
- return LeaderNotAvailable
- }
- Logger.Printf("Failed to fetch metadata from broker %s, waiting %dms... (%d retries remaining)\n", broker.addr, client.config.WaitForElection/time.Millisecond, retries)
- time.Sleep(client.config.WaitForElection)
- return client.refreshMetadata(retry, retries-1)
- }
- case EncodingError:
-
- return err
- }
-
- Logger.Println("Unexpected error from GetMetadata, closing broker:", err)
- client.disconnectBroker(broker)
- }
- if retries > 0 {
- Logger.Printf("Out of available brokers. Resurrecting dead brokers after %dms... (%d retries remaining)\n", client.config.WaitForElection/time.Millisecond, retries)
- time.Sleep(client.config.WaitForElection)
- client.resurrectDeadBrokers()
- return client.refreshMetadata(topics, retries-1)
- } else {
- Logger.Printf("Out of available brokers.\n")
- }
- return OutOfBrokers
- }
- func (client *Client) resurrectDeadBrokers() {
- client.lock.Lock()
- defer client.lock.Unlock()
- brokers := make(map[string]struct{})
- for _, addr := range client.deadBrokerAddrs {
- brokers[addr] = struct{}{}
- }
- for _, addr := range client.extraBrokerAddrs {
- brokers[addr] = struct{}{}
- }
- client.deadBrokerAddrs = []string{}
- client.extraBrokerAddrs = []string{}
- for addr := range brokers {
- client.extraBrokerAddrs = append(client.extraBrokerAddrs, addr)
- }
- client.extraBroker = NewBroker(client.extraBrokerAddrs[0])
- client.extraBroker.Open(client.config.ConcurrencyPerBroker)
- }
- func (client *Client) any() *Broker {
- client.lock.RLock()
- defer client.lock.RUnlock()
- for _, broker := range client.brokers {
- return broker
- }
- return client.extraBroker
- }
- func (client *Client) cachedLeader(topic string, partitionID int32) *Broker {
- client.lock.RLock()
- defer client.lock.RUnlock()
- partitions := client.leaders[topic]
- if partitions != nil {
- leader, ok := partitions[partitionID]
- if ok {
- return client.brokers[leader]
- }
- }
- return nil
- }
- func (client *Client) cachedPartitions(topic string) []int32 {
- client.lock.RLock()
- defer client.lock.RUnlock()
- partitions := client.leaders[topic]
- if partitions == nil {
- return nil
- }
- ret := make([]int32, 0, len(partitions))
- for id := range partitions {
- ret = append(ret, id)
- }
- sort.Sort(int32Slice(ret))
- return ret
- }
- func (client *Client) update(data *MetadataResponse) ([]string, error) {
- client.lock.Lock()
- defer client.lock.Unlock()
-
-
-
-
-
-
-
- for _, broker := range data.Brokers {
- if client.brokers[broker.ID()] == nil {
- broker.Open(client.config.ConcurrencyPerBroker)
- client.brokers[broker.ID()] = broker
- Logger.Printf("Registered new broker #%d at %s", broker.ID(), broker.Addr())
- } else if broker.Addr() != client.brokers[broker.ID()].Addr() {
- myBroker := client.brokers[broker.ID()]
- go withRecover(func() { myBroker.Close() })
- broker.Open(client.config.ConcurrencyPerBroker)
- client.brokers[broker.ID()] = broker
- Logger.Printf("Replaced registered broker #%d with %s", broker.ID(), broker.Addr())
- }
- }
- toRetry := make(map[string]bool)
- for _, topic := range data.Topics {
- switch topic.Err {
- case NoError:
- break
- case LeaderNotAvailable:
- toRetry[topic.Name] = true
- default:
- return nil, topic.Err
- }
- client.leaders[topic.Name] = make(map[int32]int32, len(topic.Partitions))
- for _, partition := range topic.Partitions {
- switch partition.Err {
- case LeaderNotAvailable:
- toRetry[topic.Name] = true
- delete(client.leaders[topic.Name], partition.ID)
- case NoError:
- client.leaders[topic.Name][partition.ID] = partition.Leader
- default:
- return nil, partition.Err
- }
- }
- }
- ret := make([]string, 0, len(toRetry))
- for topic := range toRetry {
- ret = append(ret, topic)
- }
- return ret, nil
- }
- func NewClientConfig() *ClientConfig {
- return &ClientConfig{
- MetadataRetries: 3,
- WaitForElection: 250 * time.Millisecond,
- ConcurrencyPerBroker: 0,
- }
- }
- func (config *ClientConfig) Validate() error {
- if config.MetadataRetries <= 0 {
- return ConfigurationError("Invalid MetadataRetries. Try 10")
- }
- if config.WaitForElection <= time.Duration(0) {
- return ConfigurationError("Invalid WaitForElection. Try 250*time.Millisecond")
- }
- if config.ConcurrencyPerBroker < 0 {
- return ConfigurationError("Invalid ConcurrencyPerBroker")
- }
- return nil
- }
|