Skip to content

Commit

Permalink
deduplicate fallback dc list and remove the local DC
Browse files Browse the repository at this point in the history
  • Loading branch information
dmarkhas committed May 4, 2023
1 parent 6965645 commit 52a7ba4
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion consul.go
Expand Up @@ -3,6 +3,7 @@ package consulresolver
import (
"context"
"fmt"
"github.com/mitchellh/mapstructure"
"log"
"math"
"reflect"
Expand All @@ -17,6 +18,14 @@ import (
"go.uber.org/ratelimit"
)

type agentConfig struct {
DC string `mapstructure:"Datacenter"`
}

type agentSelf struct {
Config agentConfig `mapstructure:"Config"`
}

// Balancer interface provides methods for selecting a target and updating its state
type Balancer interface {
// Select returns a *api.ServiceEntry describing the selected target.
Expand Down Expand Up @@ -73,7 +82,23 @@ func NewConsulResolver(ctx context.Context, conf ResolverConfig) (*ServiceResolv
conf.Log = log.Printf
}

datacenters := append([]string{""}, conf.FallbackDatacenters...)
datacenters := []string{""}
if len(conf.FallbackDatacenters) > 0 {
seen := map[string]struct{}{}
// Exclude the local datacenter from the list of fallback datacenters
localDC, err := getLocalDatacenter(conf.Client.Agent())
if err != nil {
return nil, errors.Wrap(err, "failed determining local consul datacenter")
}

for _, dc := range conf.FallbackDatacenters {
if _, ok := seen[dc]; ok || dc == localDC {
continue
}
seen[dc] = struct{}{}
datacenters = append(datacenters, dc)
}
}

resolver := &ServiceResolver{
log: conf.Log,
Expand Down Expand Up @@ -223,3 +248,17 @@ func (r *ServiceResolver) getTargetsForUpdate(se []*api.ServiceEntry, priority i

return se, false
}

func getLocalDatacenter(c *api.Agent) (string, error) {
res, err := c.Self()
if err != nil {
return "", errors.Wrap(err, "failed querying agent")
}

var self agentSelf
if err := mapstructure.Decode(res, &self); err != nil {
return "", errors.Wrap(err, "failed decoding agent configuration")
}

return self.Config.DC, nil
}

0 comments on commit 52a7ba4

Please sign in to comment.