github.com/kardianos/nomad@v0.1.3-0.20151022182107-b13df73ee850/client/fingerprint/consul.go (about)

     1  package fingerprint
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"strconv"
     7  	"time"
     8  
     9  	consul "github.com/hashicorp/consul/api"
    10  
    11  	client "github.com/hashicorp/nomad/client/config"
    12  	"github.com/hashicorp/nomad/nomad/structs"
    13  )
    14  
    15  // ConsulFingerprint is used to fingerprint the architecture
    16  type ConsulFingerprint struct {
    17  	logger *log.Logger
    18  }
    19  
    20  // NewConsulFingerprint is used to create an OS fingerprint
    21  func NewConsulFingerprint(logger *log.Logger) Fingerprint {
    22  	f := &ConsulFingerprint{logger: logger}
    23  	return f
    24  }
    25  
    26  func (f *ConsulFingerprint) Fingerprint(config *client.Config, node *structs.Node) (bool, error) {
    27  	// Guard against uninitialized Links
    28  	if node.Links == nil {
    29  		node.Links = map[string]string{}
    30  	}
    31  
    32  	address := config.ReadDefault("consul.address", "127.0.0.1:8500")
    33  	timeout, err := time.ParseDuration(config.ReadDefault("consul.timeout", "10ms"))
    34  	if err != nil {
    35  		return false, fmt.Errorf("Unable to parse consul.timeout: %s", err)
    36  	}
    37  
    38  	consulConfig := consul.DefaultConfig()
    39  	consulConfig.Address = address
    40  	consulConfig.HttpClient.Timeout = timeout
    41  
    42  	consulClient, err := consul.NewClient(consulConfig)
    43  	if err != nil {
    44  		return false, fmt.Errorf("Failed to initialize consul client: %s", err)
    45  	}
    46  
    47  	// We'll try to detect consul by making a query to to the agent's self API.
    48  	// If we can't hit this URL consul is probably not running on this machine.
    49  	info, err := consulClient.Agent().Self()
    50  	if err != nil {
    51  		return false, fmt.Errorf("Failed to query consul for agent status: %s", err)
    52  	}
    53  
    54  	node.Attributes["consul.server"] = strconv.FormatBool(info["Config"]["Server"].(bool))
    55  	node.Attributes["consul.version"] = info["Config"]["Version"].(string)
    56  	node.Attributes["consul.revision"] = info["Config"]["Revision"].(string)
    57  	node.Attributes["consul.name"] = info["Config"]["NodeName"].(string)
    58  	node.Attributes["consul.datacenter"] = info["Config"]["Datacenter"].(string)
    59  
    60  	node.Links["consul"] = fmt.Sprintf("%s.%s",
    61  		node.Attributes["consul.datacenter"],
    62  		node.Attributes["consul.name"])
    63  
    64  	return true, nil
    65  }