Skip to content

Commit

Permalink
Merge pull request #487 from hashicorp/b-single-consul-client
Browse files Browse the repository at this point in the history
Consul fingerprinter only creates one consul client
  • Loading branch information
dadgar committed Nov 22, 2015
2 parents 441687e + 220f79c commit acc4c55
Showing 1 changed file with 30 additions and 12 deletions.
42 changes: 30 additions & 12 deletions client/fingerprint/consul.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
// ConsulFingerprint is used to fingerprint the architecture
type ConsulFingerprint struct {
logger *log.Logger
client *consul.Client
}

// NewConsulFingerprint is used to create an OS fingerprint
Expand All @@ -29,25 +30,31 @@ func (f *ConsulFingerprint) Fingerprint(config *client.Config, node *structs.Nod
node.Links = map[string]string{}
}

address := config.ReadDefault("consul.address", "127.0.0.1:8500")
timeout, err := time.ParseDuration(config.ReadDefault("consul.timeout", "10ms"))
if err != nil {
return false, fmt.Errorf("Unable to parse consul.timeout: %s", err)
}
// Only create the client once to avoid creating too many connections to
// Consul.
if f.client == nil {
address := config.ReadDefault("consul.address", "127.0.0.1:8500")
timeout, err := time.ParseDuration(config.ReadDefault("consul.timeout", "10ms"))
if err != nil {
return false, fmt.Errorf("Unable to parse consul.timeout: %s", err)
}

consulConfig := consul.DefaultConfig()
consulConfig.Address = address
consulConfig.HttpClient.Timeout = timeout
consulConfig := consul.DefaultConfig()
consulConfig.Address = address
consulConfig.HttpClient.Timeout = timeout

consulClient, err := consul.NewClient(consulConfig)
if err != nil {
return false, fmt.Errorf("Failed to initialize consul client: %s", err)
f.client, err = consul.NewClient(consulConfig)
if err != nil {
return false, fmt.Errorf("Failed to initialize consul client: %s", err)
}
}

// We'll try to detect consul by making a query to to the agent's self API.
// If we can't hit this URL consul is probably not running on this machine.
info, err := consulClient.Agent().Self()
info, err := f.client.Agent().Self()
if err != nil {
// Clear any attributes set by a previous fingerprint.
f.clearConsulAttributes(node)
return false, nil
}

Expand All @@ -64,6 +71,17 @@ func (f *ConsulFingerprint) Fingerprint(config *client.Config, node *structs.Nod
return true, nil
}

// clearConsulAttributes removes consul attributes and links from the passed
// Node.
func (f *ConsulFingerprint) clearConsulAttributes(n *structs.Node) {
delete(n.Attributes, "consul.server")
delete(n.Attributes, "consul.version")
delete(n.Attributes, "consul.revision")
delete(n.Attributes, "consul.name")
delete(n.Attributes, "consul.datacenter")
delete(n.Links, "consul")
}

func (f *ConsulFingerprint) Periodic() (bool, time.Duration) {
return true, 15 * time.Second
}

0 comments on commit acc4c55

Please sign in to comment.