Ejemplo n.º 1
0
func (f *ConsulFingerprint) Fingerprint(config *client.Config, node *structs.Node) (bool, error) {
	// Guard against uninitialized Links
	if node.Links == nil {
		node.Links = map[string]string{}
	}

	// 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

		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 := f.client.Agent().Self()
	if err != nil {
		// Clear any attributes set by a previous fingerprint.
		f.clearConsulAttributes(node)

		// Print a message indicating that the Consul Agent is not available
		// anymore
		if f.lastState == consulAvailable {
			f.logger.Printf("[INFO] fingerprint.consul: consul agent is unavailable")
		}
		f.lastState = consulUnavailable
		return false, nil
	}

	node.Attributes["consul.server"] = strconv.FormatBool(info["Config"]["Server"].(bool))
	node.Attributes["consul.version"] = info["Config"]["Version"].(string)
	node.Attributes["consul.revision"] = info["Config"]["Revision"].(string)
	node.Attributes["consul.name"] = info["Config"]["NodeName"].(string)
	node.Attributes["consul.datacenter"] = info["Config"]["Datacenter"].(string)

	node.Links["consul"] = fmt.Sprintf("%s.%s",
		node.Attributes["consul.datacenter"],
		node.Attributes["consul.name"])

	// If the Consul Agent was previously unavailable print a message to
	// indicate the Agent is available now
	if f.lastState == consulUnavailable {
		f.logger.Printf("[INFO] fingerprint.consul: consul agent is available")
	}
	f.lastState = consulAvailable
	return true, nil
}
Ejemplo n.º 2
0
// NewClient is used to create a new client from the given configuration
func NewClient(cfg *config.Config) (*Client, error) {
	// Create a logger
	logger := log.New(cfg.LogOutput, "", log.LstdFlags)

	// Create the consul client
	consulAddr := cfg.ReadDefault("consul.address", "127.0.0.1:8500")
	consulClient, err := NewConsulClient(logger, consulAddr)
	if err != nil {
		return nil, fmt.Errorf("failed to create the consul client: %v", err)
	}

	// Create the client
	c := &Client{
		config:       cfg,
		start:        time.Now(),
		consulClient: consulClient,
		connPool:     nomad.NewPool(cfg.LogOutput, clientRPCCache, clientMaxStreams, nil),
		logger:       logger,
		allocs:       make(map[string]*AllocRunner),
		shutdownCh:   make(chan struct{}),
	}

	// Initialize the client
	if err := c.init(); err != nil {
		return nil, fmt.Errorf("failed intializing client: %v", err)
	}

	// Setup the node
	if err := c.setupNode(); err != nil {
		return nil, fmt.Errorf("node setup failed: %v", err)
	}

	// Fingerprint the node
	if err := c.fingerprint(); err != nil {
		return nil, fmt.Errorf("fingerprinting failed: %v", err)
	}

	// Scan for drivers
	if err := c.setupDrivers(); err != nil {
		return nil, fmt.Errorf("driver setup failed: %v", err)
	}

	// Set up the known servers list
	c.SetServers(c.config.Servers)

	// Restore the state
	if err := c.restoreState(); err != nil {
		return nil, fmt.Errorf("failed to restore state: %v", err)
	}

	// Start the client!
	go c.run()

	// Start the consul client
	go c.consulClient.SyncWithConsul()
	return c, nil
}
Ejemplo n.º 3
0
func (d *RawExecDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
	// Check that the user has explicitly enabled this executor.
	enabled := cfg.ReadBoolDefault(rawExecConfigOption, false)

	if enabled {
		d.logger.Printf("[WARN] driver.raw_exec: raw exec is enabled. Only enable if needed")
		node.Attributes["driver.raw_exec"] = "1"
		return true, nil
	}

	return false, nil
}
Ejemplo n.º 4
0
Archivo: lxc.go Proyecto: zanella/nomad
// Fingerprint fingerprints the lxc driver configuration
func (d *LxcDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
	enabled := cfg.ReadBoolDefault(lxcConfigOption, true)
	if !enabled && !cfg.DevMode {
		return false, nil
	}
	version := lxc.Version()
	if version == "" {
		return false, nil
	}
	node.Attributes["driver.lxc.version"] = version
	node.Attributes["driver.lxc"] = "1"
	return true, nil
}
Ejemplo n.º 5
0
func (d *RawExecDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
	// Check that the user has explicitly enabled this executor.
	enabled, err := strconv.ParseBool(cfg.ReadDefault(rawExecConfigOption, "false"))
	if err != nil {
		return false, fmt.Errorf("Failed to parse %v option: %v", rawExecConfigOption, err)
	}

	if enabled {
		d.logger.Printf("[WARN] driver.raw_exec: raw exec is enabled. Only enable if needed")
		node.Attributes["driver.raw_exec"] = "1"
		return true, nil
	}

	return false, nil
}
Ejemplo n.º 6
0
func consulContext(clientConfig *config.Config, containerID string) *executor.ConsulContext {
	return &executor.ConsulContext{
		ConsulConfig:   clientConfig.ConsulConfig,
		ContainerID:    containerID,
		DockerEndpoint: clientConfig.Read("docker.endpoint"),
		TLSCa:          clientConfig.Read("docker.tls.ca"),
		TLSCert:        clientConfig.Read("docker.tls.cert"),
		TLSKey:         clientConfig.Read("docker.tls.key"),
	}
}
Ejemplo n.º 7
0
func (d *RawExecDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
	// Get the current status so that we can log any debug messages only if the
	// state changes
	_, currentlyEnabled := node.Attributes[rawExecDriverAttr]

	// Check that the user has explicitly enabled this executor.
	enabled := cfg.ReadBoolDefault(rawExecConfigOption, false)

	if enabled {
		if currentlyEnabled {
			d.logger.Printf("[WARN] driver.raw_exec: raw exec is enabled. Only enable if needed")
		}
		node.Attributes[rawExecDriverAttr] = "1"
		return true, nil
	}

	delete(node.Attributes, rawExecDriverAttr)
	return false, nil
}
Ejemplo n.º 8
0
func (f *ConsulFingerprint) Fingerprint(config *client.Config, node *structs.Node) (bool, error) {
	// Guard against uninitialized Links
	if node.Links == nil {
		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)
	}

	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)
	}

	// 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()
	if err != nil {
		return false, fmt.Errorf("Failed to query consul for agent status: %s", err)
	}

	node.Attributes["consul.server"] = strconv.FormatBool(info["Config"]["Server"].(bool))
	node.Attributes["consul.version"] = info["Config"]["Version"].(string)
	node.Attributes["consul.revision"] = info["Config"]["Revision"].(string)
	node.Attributes["consul.name"] = info["Config"]["NodeName"].(string)
	node.Attributes["consul.datacenter"] = info["Config"]["Datacenter"].(string)

	node.Links["consul"] = fmt.Sprintf("%s.%s",
		node.Attributes["consul.datacenter"],
		node.Attributes["consul.name"])

	return true, nil
}
Ejemplo n.º 9
0
// templateRunner returns a consul-template runner for the given templates and a
// lookup by destination to the template. If no templates are given, a nil
// template runner and lookup is returned.
func templateRunner(tmpls []*structs.Template, config *config.Config,
	vaultToken, taskDir string, taskEnv *env.TaskEnvironment) (
	*manager.Runner, map[string][]*structs.Template, error) {

	if len(tmpls) == 0 {
		return nil, nil, nil
	}

	runnerConfig, err := runnerConfig(config, vaultToken)
	if err != nil {
		return nil, nil, err
	}

	// Parse the templates
	allowAbs := config.ReadBoolDefault(hostSrcOption, true)
	ctmplMapping, err := parseTemplateConfigs(tmpls, taskDir, taskEnv, allowAbs)
	if err != nil {
		return nil, nil, err
	}

	// Set the config
	flat := make([]*ctconf.ConfigTemplate, 0, len(ctmplMapping))
	for ctmpl := range ctmplMapping {
		local := ctmpl
		flat = append(flat, &local)
	}
	runnerConfig.ConfigTemplates = flat

	runner, err := manager.NewRunner(runnerConfig, false, false)
	if err != nil {
		return nil, nil, err
	}

	// Build the lookup
	idMap := runner.ConfigTemplateMapping()
	lookup := make(map[string][]*structs.Template, len(idMap))
	for id, ctmpls := range idMap {
		for _, ctmpl := range ctmpls {
			templates := lookup[id]
			templates = append(templates, ctmplMapping[ctmpl])
			lookup[id] = templates
		}
	}

	return runner, lookup, nil
}
Ejemplo n.º 10
0
func consulContext(clientConfig *config.Config, containerID string) *executor.ConsulContext {
	cfg := consul.ConsulConfig{
		Addr:      clientConfig.ReadDefault("consul.address", "127.0.0.1:8500"),
		Token:     clientConfig.Read("consul.token"),
		Auth:      clientConfig.Read("consul.auth"),
		EnableSSL: clientConfig.ReadBoolDefault("consul.ssl", false),
		VerifySSL: clientConfig.ReadBoolDefault("consul.verifyssl", true),
		CAFile:    clientConfig.Read("consul.tls_ca_file"),
		CertFile:  clientConfig.Read("consul.tls_cert_file"),
		KeyFile:   clientConfig.Read("consul.tls_key_file"),
	}
	return &executor.ConsulContext{
		ConsulConfig:   &cfg,
		ContainerID:    containerID,
		DockerEndpoint: clientConfig.Read("docker.endpoint"),
		TLSCa:          clientConfig.Read("docker.tls.ca"),
		TLSCert:        clientConfig.Read("docker.tls.cert"),
		TLSKey:         clientConfig.Read("docker.tls.key"),
	}
}