123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634 |
- package sarama
- import (
- "sort"
- "sync"
- "time"
- )
- type ClientConfig struct {
- MetadataRetries int
- WaitForElection time.Duration
- DefaultBrokerConf *BrokerConfig
- BackgroundRefreshFrequency time.Duration
- }
- func NewClientConfig() *ClientConfig {
- return &ClientConfig{
- MetadataRetries: 3,
- WaitForElection: 250 * time.Millisecond,
- BackgroundRefreshFrequency: 10 * time.Minute,
- }
- }
- func (config *ClientConfig) Validate() error {
- if config.MetadataRetries < 0 {
- return ConfigurationError("Invalid MetadataRetries, must be >= 0")
- }
- if config.WaitForElection <= time.Duration(0) {
- return ConfigurationError("Invalid WaitForElection, must be > 0")
- }
- if config.DefaultBrokerConf != nil {
- if err := config.DefaultBrokerConf.Validate(); err != nil {
- return err
- }
- }
- if config.BackgroundRefreshFrequency < time.Duration(0) {
- return ConfigurationError("Invalid BackgroundRefreshFrequency, must be >= 0")
- }
- return nil
- }
- type Client struct {
- id string
- config ClientConfig
- closer chan none
-
-
-
- seedBrokerAddrs []string
- seedBroker *Broker
- deadBrokerAddrs map[string]none
- brokers map[int32]*Broker
- metadata map[string]map[int32]*PartitionMetadata
-
-
- cachedPartitionsResults map[string][maxPartitionIndex][]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,
- closer: make(chan none),
- seedBrokerAddrs: addrs,
- seedBroker: NewBroker(addrs[0]),
- deadBrokerAddrs: make(map[string]none),
- brokers: make(map[int32]*Broker),
- metadata: make(map[string]map[int32]*PartitionMetadata),
- cachedPartitionsResults: make(map[string][maxPartitionIndex][]int32),
- }
- _ = client.seedBroker.Open(config.DefaultBrokerConf)
-
- err := client.RefreshAllMetadata()
- switch err {
- case nil:
- break
- case ErrLeaderNotAvailable, ErrReplicaNotAvailable:
-
- Logger.Println(err)
- default:
- _ = client.Close()
- return nil, err
- }
- go withRecover(client.backgroundMetadataUpdater)
- Logger.Println("Successfully initialized new client")
- return client, nil
- }
- func (client *Client) Close() error {
-
- if client.Closed() {
-
-
- Logger.Printf("Close() called on already closed client")
- return ErrClosedClient
- }
- client.lock.Lock()
- defer client.lock.Unlock()
- Logger.Println("Closing Client")
- for _, broker := range client.brokers {
- safeAsyncClose(broker)
- }
- client.brokers = nil
- client.metadata = nil
- if client.seedBroker != nil {
- safeAsyncClose(client.seedBroker)
- }
- close(client.closer)
- return nil
- }
- func (client *Client) Closed() bool {
- return client.brokers == nil
- }
- func (client *Client) Topics() ([]string, error) {
-
- if client.Closed() {
- return nil, ErrClosedClient
- }
- client.lock.RLock()
- defer client.lock.RUnlock()
- ret := make([]string, 0, len(client.metadata))
- for topic := range client.metadata {
- ret = append(ret, topic)
- }
- return ret, nil
- }
- func (client *Client) Partitions(topic string) ([]int32, error) {
-
- if client.Closed() {
- return nil, ErrClosedClient
- }
- partitions := client.cachedPartitions(topic, allPartitions)
- if len(partitions) == 0 {
- err := client.RefreshTopicMetadata(topic)
- if err != nil {
- return nil, err
- }
- partitions = client.cachedPartitions(topic, allPartitions)
- }
- if partitions == nil {
- return nil, ErrUnknownTopicOrPartition
- }
- return partitions, nil
- }
- func (client *Client) WritablePartitions(topic string) ([]int32, error) {
-
- if client.Closed() {
- return nil, ErrClosedClient
- }
- partitions := client.cachedPartitions(topic, writablePartitions)
-
-
-
-
-
-
- if len(partitions) == 0 {
- err := client.RefreshTopicMetadata(topic)
- if err != nil {
- return nil, err
- }
- partitions = client.cachedPartitions(topic, writablePartitions)
- }
- if partitions == nil {
- return nil, ErrUnknownTopicOrPartition
- }
- return partitions, nil
- }
- func (client *Client) Replicas(topic string, partitionID int32) ([]int32, error) {
- if client.Closed() {
- return nil, ErrClosedClient
- }
- metadata, err := client.getMetadata(topic, partitionID)
- if err != nil {
- return nil, err
- }
- if metadata.Err == ErrReplicaNotAvailable {
- return nil, metadata.Err
- }
- return dupeAndSort(metadata.Replicas), nil
- }
- func (client *Client) ReplicasInSync(topic string, partitionID int32) ([]int32, error) {
- if client.Closed() {
- return nil, ErrClosedClient
- }
- metadata, err := client.getMetadata(topic, partitionID)
- if err != nil {
- return nil, err
- }
- if metadata.Err == ErrReplicaNotAvailable {
- return nil, metadata.Err
- }
- return dupeAndSort(metadata.Isr), nil
- }
- func (client *Client) Leader(topic string, partitionID int32) (*Broker, error) {
- leader, err := client.cachedLeader(topic, partitionID)
- if leader == nil {
- err := client.RefreshTopicMetadata(topic)
- if err != nil {
- return nil, err
- }
- leader, err = client.cachedLeader(topic, partitionID)
- }
- return leader, err
- }
- 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) GetOffset(topic string, partitionID int32, where OffsetTime) (int64, error) {
- broker, err := client.Leader(topic, partitionID)
- if err != nil {
- return -1, err
- }
- request := &OffsetRequest{}
- request.AddBlock(topic, partitionID, where, 1)
- response, err := broker.GetAvailableOffsets(client.id, request)
- if err != nil {
- return -1, err
- }
- block := response.GetBlock(topic, partitionID)
- if block == nil {
- return -1, ErrIncompleteResponse
- }
- if block.Err != ErrNoError {
- return -1, block.Err
- }
- if len(block.Offsets) != 1 {
- return -1, ErrOffsetOutOfRange
- }
- return block.Offsets[0], nil
- }
- func (client *Client) disconnectBroker(broker *Broker) {
- client.lock.Lock()
- defer client.lock.Unlock()
- Logger.Printf("Disconnecting Broker %d\n", broker.ID())
- client.deadBrokerAddrs[broker.addr] = none{}
- if broker == client.seedBroker {
- client.seedBrokerAddrs = client.seedBrokerAddrs[1:]
- if len(client.seedBrokerAddrs) > 0 {
- client.seedBroker = NewBroker(client.seedBrokerAddrs[0])
- _ = client.seedBroker.Open(client.config.DefaultBrokerConf)
- } else {
- client.seedBroker = nil
- }
- } else {
-
-
- delete(client.brokers, broker.ID())
- }
- safeAsyncClose(broker)
- }
- func (client *Client) resurrectDeadBrokers() {
- client.lock.Lock()
- defer client.lock.Unlock()
- for _, addr := range client.seedBrokerAddrs {
- client.deadBrokerAddrs[addr] = none{}
- }
- client.seedBrokerAddrs = []string{}
- for addr := range client.deadBrokerAddrs {
- client.seedBrokerAddrs = append(client.seedBrokerAddrs, addr)
- }
- client.deadBrokerAddrs = make(map[string]none)
- client.seedBroker = NewBroker(client.seedBrokerAddrs[0])
- _ = client.seedBroker.Open(client.config.DefaultBrokerConf)
- }
- func (client *Client) any() *Broker {
- client.lock.RLock()
- defer client.lock.RUnlock()
- if client.seedBroker != nil {
- return client.seedBroker
- }
- for _, broker := range client.brokers {
- return broker
- }
- return nil
- }
- type partitionType int
- const (
- allPartitions partitionType = iota
- writablePartitions
-
-
- maxPartitionIndex
- )
- func (client *Client) getMetadata(topic string, partitionID int32) (*PartitionMetadata, error) {
- metadata := client.cachedMetadata(topic, partitionID)
- if metadata == nil {
- err := client.RefreshTopicMetadata(topic)
- if err != nil {
- return nil, err
- }
- metadata = client.cachedMetadata(topic, partitionID)
- }
- if metadata == nil {
- return nil, ErrUnknownTopicOrPartition
- }
- return metadata, nil
- }
- func (client *Client) cachedMetadata(topic string, partitionID int32) *PartitionMetadata {
- client.lock.RLock()
- defer client.lock.RUnlock()
- partitions := client.metadata[topic]
- if partitions != nil {
- return partitions[partitionID]
- }
- return nil
- }
- func (client *Client) cachedPartitions(topic string, partitionSet partitionType) []int32 {
- client.lock.RLock()
- defer client.lock.RUnlock()
- partitions, exists := client.cachedPartitionsResults[topic]
- if !exists {
- return nil
- }
- return partitions[partitionSet]
- }
- func (client *Client) setPartitionCache(topic string, partitionSet partitionType) []int32 {
- partitions := client.metadata[topic]
- if partitions == nil {
- return nil
- }
- ret := make([]int32, 0, len(partitions))
- for _, partition := range partitions {
- if partitionSet == writablePartitions && partition.Err == ErrLeaderNotAvailable {
- continue
- }
- ret = append(ret, partition.ID)
- }
- sort.Sort(int32Slice(ret))
- return ret
- }
- func (client *Client) cachedLeader(topic string, partitionID int32) (*Broker, error) {
- client.lock.RLock()
- defer client.lock.RUnlock()
- partitions := client.metadata[topic]
- if partitions != nil {
- metadata, ok := partitions[partitionID]
- if ok {
- if metadata.Err == ErrLeaderNotAvailable {
- return nil, ErrLeaderNotAvailable
- }
- b := client.brokers[metadata.Leader]
- if b == nil {
- return nil, ErrLeaderNotAvailable
- }
- return b, nil
- }
- }
- return nil, ErrUnknownTopicOrPartition
- }
- func (client *Client) backgroundMetadataUpdater() {
- if client.config.BackgroundRefreshFrequency == time.Duration(0) {
- return
- }
- ticker := time.NewTicker(client.config.BackgroundRefreshFrequency)
- for {
- select {
- case <-ticker.C:
- if err := client.RefreshAllMetadata(); err != nil {
- Logger.Println("Client background metadata update:", err)
- }
- case <-client.closer:
- ticker.Stop()
- return
- }
- }
- }
- func (client *Client) refreshMetadata(topics []string, retriesRemaining int) error {
-
-
-
- if client.Closed() {
- return ErrClosedClient
- }
-
-
-
- for _, topic := range topics {
- if len(topic) == 0 {
- return ErrUnknownTopicOrPartition
- }
- }
- for broker := client.any(); broker != nil; broker = client.any() {
- if len(topics) > 0 {
- Logger.Printf("Fetching metadata for %v from broker %s\n", topics, broker.addr)
- } else {
- Logger.Printf("Fetching metadata for all topics from broker %s\n", broker.addr)
- }
- response, err := broker.GetMetadata(client.id, &MetadataRequest{Topics: topics})
- switch err.(type) {
- case nil:
-
- retry, err := client.update(response)
- if len(retry) > 0 {
- if retriesRemaining <= 0 {
- Logger.Println("Some partitions are leaderless, but we're out of retries")
- return nil
- }
- Logger.Printf("Some partitions are leaderless, waiting %dms for election... (%d retries remaining)\n", client.config.WaitForElection/time.Millisecond, retriesRemaining)
- time.Sleep(client.config.WaitForElection)
- return client.refreshMetadata(retry, retriesRemaining-1)
- }
- return err
- case PacketEncodingError:
-
- return err
- default:
-
- Logger.Println("Error from broker while fetching metadata:", err)
- client.disconnectBroker(broker)
- }
- }
- Logger.Println("Out of available brokers.")
- if retriesRemaining > 0 {
- Logger.Printf("Resurrecting dead brokers after %dms... (%d retries remaining)\n", client.config.WaitForElection/time.Millisecond, retriesRemaining)
- time.Sleep(client.config.WaitForElection)
- client.resurrectDeadBrokers()
- return client.refreshMetadata(topics, retriesRemaining-1)
- }
- return ErrOutOfBrokers
- }
- 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.DefaultBrokerConf)
- 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() {
- safeAsyncClose(client.brokers[broker.ID()])
- _ = broker.Open(client.config.DefaultBrokerConf)
- client.brokers[broker.ID()] = broker
- Logger.Printf("Replaced registered broker #%d with %s", broker.ID(), broker.Addr())
- }
- }
- toRetry := make(map[string]bool)
- var err error
- for _, topic := range data.Topics {
- switch topic.Err {
- case ErrNoError:
- break
- case ErrLeaderNotAvailable:
- toRetry[topic.Name] = true
- default:
- err = topic.Err
- }
- client.metadata[topic.Name] = make(map[int32]*PartitionMetadata, len(topic.Partitions))
- delete(client.cachedPartitionsResults, topic.Name)
- for _, partition := range topic.Partitions {
- client.metadata[topic.Name][partition.ID] = partition
- if partition.Err == ErrLeaderNotAvailable {
- toRetry[topic.Name] = true
- }
- }
- var partitionCache [maxPartitionIndex][]int32
- partitionCache[allPartitions] = client.setPartitionCache(topic.Name, allPartitions)
- partitionCache[writablePartitions] = client.setPartitionCache(topic.Name, writablePartitions)
- client.cachedPartitionsResults[topic.Name] = partitionCache
- }
- if err != nil {
- return nil, err
- }
- ret := make([]string, 0, len(toRetry))
- for topic := range toRetry {
- ret = append(ret, topic)
- }
- return ret, nil
- }
|