2013-12-19 20:18:06 +00:00
|
|
|
package agent
|
|
|
|
|
|
|
|
import (
|
2016-12-05 08:07:53 +00:00
|
|
|
"context"
|
2013-12-21 00:39:32 +00:00
|
|
|
"flag"
|
2013-12-20 01:14:46 +00:00
|
|
|
"fmt"
|
2013-12-21 00:39:32 +00:00
|
|
|
"io"
|
2016-12-05 08:07:53 +00:00
|
|
|
"io/ioutil"
|
2016-11-02 18:35:37 +00:00
|
|
|
"log"
|
2013-12-30 23:27:41 +00:00
|
|
|
"net"
|
2016-12-05 08:07:53 +00:00
|
|
|
"net/http"
|
2013-12-21 00:39:32 +00:00
|
|
|
"os"
|
|
|
|
"os/signal"
|
2014-09-02 21:23:43 +00:00
|
|
|
"path/filepath"
|
2014-06-09 18:57:15 +00:00
|
|
|
"regexp"
|
2016-06-01 20:35:34 +00:00
|
|
|
"strconv"
|
2013-12-19 20:18:06 +00:00
|
|
|
"strings"
|
2013-12-21 00:39:32 +00:00
|
|
|
"syscall"
|
|
|
|
"time"
|
2014-06-16 21:36:12 +00:00
|
|
|
|
2016-12-05 08:07:53 +00:00
|
|
|
"golang.org/x/oauth2"
|
|
|
|
"golang.org/x/oauth2/google"
|
|
|
|
compute "google.golang.org/api/compute/v1"
|
|
|
|
|
2014-06-16 21:36:12 +00:00
|
|
|
"github.com/armon/go-metrics"
|
2016-07-18 13:34:43 +00:00
|
|
|
"github.com/armon/go-metrics/circonus"
|
2015-06-16 22:05:55 +00:00
|
|
|
"github.com/armon/go-metrics/datadog"
|
2016-05-12 01:41:41 +00:00
|
|
|
"github.com/aws/aws-sdk-go/aws"
|
|
|
|
"github.com/aws/aws-sdk-go/aws/credentials"
|
2016-11-02 22:48:15 +00:00
|
|
|
"github.com/aws/aws-sdk-go/aws/defaults"
|
2016-11-02 01:20:08 +00:00
|
|
|
"github.com/aws/aws-sdk-go/aws/ec2metadata"
|
2016-05-12 01:41:41 +00:00
|
|
|
"github.com/aws/aws-sdk-go/aws/session"
|
|
|
|
"github.com/aws/aws-sdk-go/service/ec2"
|
2016-01-29 19:42:34 +00:00
|
|
|
"github.com/hashicorp/consul/lib"
|
2016-11-04 04:14:56 +00:00
|
|
|
"github.com/hashicorp/consul/logger"
|
2014-08-21 20:09:13 +00:00
|
|
|
"github.com/hashicorp/consul/watch"
|
2014-09-02 21:23:43 +00:00
|
|
|
"github.com/hashicorp/go-checkpoint"
|
2016-11-30 18:29:42 +00:00
|
|
|
multierror "github.com/hashicorp/go-multierror"
|
2014-06-16 21:36:12 +00:00
|
|
|
"github.com/hashicorp/logutils"
|
2016-06-01 20:35:34 +00:00
|
|
|
scada "github.com/hashicorp/scada-client/scada"
|
2014-06-16 21:36:12 +00:00
|
|
|
"github.com/mitchellh/cli"
|
2013-12-19 20:18:06 +00:00
|
|
|
)
|
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
// gracefulTimeout controls how long we wait before forcefully terminating
|
|
|
|
var gracefulTimeout = 5 * time.Second
|
|
|
|
|
2014-06-09 18:57:15 +00:00
|
|
|
// validDatacenter is used to validate a datacenter
|
|
|
|
var validDatacenter = regexp.MustCompile("^[a-zA-Z0-9_-]+$")
|
|
|
|
|
2014-01-02 23:10:13 +00:00
|
|
|
// Command is a Command implementation that runs a Consul agent.
|
2013-12-19 20:18:06 +00:00
|
|
|
// The command will not end unless a shutdown message is sent on the
|
|
|
|
// ShutdownCh. If two messages are sent on the ShutdownCh it will forcibly
|
|
|
|
// exit.
|
|
|
|
type Command struct {
|
2016-07-20 01:38:15 +00:00
|
|
|
Revision string
|
|
|
|
Version string
|
|
|
|
VersionPrerelease string
|
|
|
|
HumanVersion string
|
|
|
|
Ui cli.Ui
|
|
|
|
ShutdownCh <-chan struct{}
|
2016-11-30 18:29:42 +00:00
|
|
|
configReloadCh chan chan error
|
2016-07-20 01:38:15 +00:00
|
|
|
args []string
|
|
|
|
logFilter *logutils.LevelFilter
|
|
|
|
logOutput io.Writer
|
|
|
|
agent *Agent
|
|
|
|
rpcServer *AgentRPC
|
|
|
|
httpServers []*HTTPServer
|
|
|
|
dnsServer *DNSServer
|
|
|
|
scadaProvider *scada.Provider
|
|
|
|
scadaHttp *HTTPServer
|
2013-12-21 00:39:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// readConfig is responsible for setup of our configuration using
|
|
|
|
// the command line and any file configs
|
|
|
|
func (c *Command) readConfig() *Config {
|
|
|
|
var cmdConfig Config
|
|
|
|
var configFiles []string
|
2014-10-12 17:50:15 +00:00
|
|
|
var retryInterval string
|
2014-11-17 22:14:59 +00:00
|
|
|
var retryIntervalWan string
|
2015-02-21 06:45:52 +00:00
|
|
|
var dnsRecursors []string
|
2015-11-29 04:40:05 +00:00
|
|
|
var dev bool
|
2016-03-18 14:44:35 +00:00
|
|
|
var dcDeprecated string
|
2013-12-21 00:39:32 +00:00
|
|
|
cmdFlags := flag.NewFlagSet("agent", flag.ContinueOnError)
|
|
|
|
cmdFlags.Usage = func() { c.Ui.Output(c.Help()) }
|
2014-04-11 22:22:35 +00:00
|
|
|
|
|
|
|
cmdFlags.Var((*AppendSliceValue)(&configFiles), "config-file", "json file to read config from")
|
|
|
|
cmdFlags.Var((*AppendSliceValue)(&configFiles), "config-dir", "directory of json files to read")
|
2015-02-21 06:45:52 +00:00
|
|
|
cmdFlags.Var((*AppendSliceValue)(&dnsRecursors), "recursor", "address of an upstream DNS server")
|
2015-11-29 04:40:05 +00:00
|
|
|
cmdFlags.BoolVar(&dev, "dev", false, "development server mode")
|
2014-04-11 22:22:35 +00:00
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.LogLevel, "log-level", "", "log level")
|
|
|
|
cmdFlags.StringVar(&cmdConfig.NodeName, "node", "", "node name")
|
2016-03-18 14:44:35 +00:00
|
|
|
cmdFlags.StringVar(&dcDeprecated, "dc", "", "node datacenter (deprecated: use 'datacenter' instead)")
|
|
|
|
cmdFlags.StringVar(&cmdConfig.Datacenter, "datacenter", "", "node datacenter")
|
2014-04-11 22:22:35 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.DataDir, "data-dir", "", "path to the data directory")
|
2015-12-22 17:30:19 +00:00
|
|
|
cmdFlags.BoolVar(&cmdConfig.EnableUi, "ui", false, "enable the built-in web UI")
|
2014-04-23 19:37:53 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.UiDir, "ui-dir", "", "path to the web UI directory")
|
2014-05-06 03:29:50 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.PidFile, "pid-file", "", "path to file to store PID")
|
2014-08-22 22:08:15 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.EncryptKey, "encrypt", "", "gossip encryption key")
|
2014-09-15 00:31:44 +00:00
|
|
|
|
2013-12-25 00:48:07 +00:00
|
|
|
cmdFlags.BoolVar(&cmdConfig.Server, "server", false, "run agent as server")
|
|
|
|
cmdFlags.BoolVar(&cmdConfig.Bootstrap, "bootstrap", false, "enable server bootstrap mode")
|
2014-06-20 00:08:48 +00:00
|
|
|
cmdFlags.IntVar(&cmdConfig.BootstrapExpect, "bootstrap-expect", 0, "enable automatic bootstrap via expect mode")
|
2015-03-20 14:22:13 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.Domain, "domain", "", "domain to use for DNS interface")
|
2014-04-11 22:22:35 +00:00
|
|
|
|
2014-11-14 19:39:19 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.ClientAddr, "client", "", "address to bind client listeners to (DNS, HTTP, HTTPS, RPC)")
|
2014-04-11 22:22:35 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.BindAddr, "bind", "", "address to bind server listeners to")
|
2016-11-03 19:58:58 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.SerfWanBindAddr, "serf-wan-bind", "", "address to bind Serf WAN listeners to")
|
|
|
|
cmdFlags.StringVar(&cmdConfig.SerfLanBindAddr, "serf-lan-bind", "", "address to bind Serf LAN listeners to")
|
2015-08-20 18:27:20 +00:00
|
|
|
cmdFlags.IntVar(&cmdConfig.Ports.HTTP, "http-port", 0, "http port to use")
|
2016-08-05 19:36:01 +00:00
|
|
|
cmdFlags.IntVar(&cmdConfig.Ports.DNS, "dns-port", 0, "DNS port to use")
|
2014-05-16 17:49:36 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.AdvertiseAddr, "advertise", "", "address to advertise instead of bind addr")
|
2015-03-28 14:48:06 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.AdvertiseAddrWan, "advertise-wan", "", "address to advertise on wan instead of bind or advertise addr")
|
2014-04-11 22:22:35 +00:00
|
|
|
|
2015-02-06 20:44:55 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.AtlasInfrastructure, "atlas", "", "infrastructure name in Atlas")
|
2015-02-05 01:23:42 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.AtlasToken, "atlas-token", "", "authentication token for Atlas")
|
2015-02-05 02:45:08 +00:00
|
|
|
cmdFlags.BoolVar(&cmdConfig.AtlasJoin, "atlas-join", false, "auto-join with Atlas")
|
2015-08-27 18:11:05 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.AtlasEndpoint, "atlas-endpoint", "", "endpoint for Atlas integration")
|
2015-02-05 01:23:42 +00:00
|
|
|
|
2014-03-09 22:57:03 +00:00
|
|
|
cmdFlags.IntVar(&cmdConfig.Protocol, "protocol", -1, "protocol version")
|
2014-04-11 22:22:35 +00:00
|
|
|
|
2014-05-21 19:06:03 +00:00
|
|
|
cmdFlags.BoolVar(&cmdConfig.EnableSyslog, "syslog", false,
|
|
|
|
"enable logging to syslog facility")
|
2014-05-21 19:32:24 +00:00
|
|
|
cmdFlags.BoolVar(&cmdConfig.RejoinAfterLeave, "rejoin", false,
|
|
|
|
"enable re-joining after a previous leave")
|
2014-04-11 23:59:16 +00:00
|
|
|
cmdFlags.Var((*AppendSliceValue)(&cmdConfig.StartJoin), "join",
|
|
|
|
"address of agent to join on startup")
|
2014-11-17 22:14:59 +00:00
|
|
|
cmdFlags.Var((*AppendSliceValue)(&cmdConfig.StartJoinWan), "join-wan",
|
2014-11-14 15:02:42 +00:00
|
|
|
"address of agent to join -wan on startup")
|
2014-10-12 17:50:15 +00:00
|
|
|
cmdFlags.Var((*AppendSliceValue)(&cmdConfig.RetryJoin), "retry-join",
|
|
|
|
"address of agent to join on startup with retry")
|
|
|
|
cmdFlags.IntVar(&cmdConfig.RetryMaxAttempts, "retry-max", 0,
|
|
|
|
"number of retries for joining")
|
|
|
|
cmdFlags.StringVar(&retryInterval, "retry-interval", "",
|
|
|
|
"interval between join attempts")
|
2016-11-02 18:35:37 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.RetryJoinEC2.Region, "retry-join-ec2-region", "",
|
|
|
|
"EC2 Region to discover servers in")
|
|
|
|
cmdFlags.StringVar(&cmdConfig.RetryJoinEC2.TagKey, "retry-join-ec2-tag-key", "",
|
|
|
|
"EC2 tag key to filter on for server discovery")
|
|
|
|
cmdFlags.StringVar(&cmdConfig.RetryJoinEC2.TagValue, "retry-join-ec2-tag-value", "",
|
|
|
|
"EC2 tag value to filter on for server discovery")
|
2016-12-05 08:07:53 +00:00
|
|
|
cmdFlags.StringVar(&cmdConfig.RetryJoinGCE.ProjectName, "retry-join-gce-project-name", "",
|
|
|
|
"Google Compute Engine project to discover servers in")
|
|
|
|
cmdFlags.StringVar(&cmdConfig.RetryJoinGCE.ZonePattern, "retry-join-gce-zone-pattern", "",
|
|
|
|
"Google Compute Engine region or zone to discover servers in (regex pattern)")
|
|
|
|
cmdFlags.StringVar(&cmdConfig.RetryJoinGCE.TagValue, "retry-join-gce-tag-value", "",
|
|
|
|
"Google Compute Engine tag value to filter on for server discovery")
|
|
|
|
cmdFlags.StringVar(&cmdConfig.RetryJoinGCE.CredentialsFile, "retry-join-gce-credentials-file", "",
|
|
|
|
"Path to credentials JSON file to use with Google Compute Engine")
|
2014-11-17 22:14:59 +00:00
|
|
|
cmdFlags.Var((*AppendSliceValue)(&cmdConfig.RetryJoinWan), "retry-join-wan",
|
2014-11-14 15:02:42 +00:00
|
|
|
"address of agent to join -wan on startup with retry")
|
2014-11-17 22:14:59 +00:00
|
|
|
cmdFlags.IntVar(&cmdConfig.RetryMaxAttemptsWan, "retry-max-wan", 0,
|
2014-11-14 15:02:42 +00:00
|
|
|
"number of retries for joining -wan")
|
2014-11-17 22:14:59 +00:00
|
|
|
cmdFlags.StringVar(&retryIntervalWan, "retry-interval-wan", "",
|
2014-11-14 15:02:42 +00:00
|
|
|
"interval between join -wan attempts")
|
2014-04-11 23:59:16 +00:00
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
if err := cmdFlags.Parse(c.args); err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-10-12 17:50:15 +00:00
|
|
|
if retryInterval != "" {
|
|
|
|
dur, err := time.ParseDuration(retryInterval)
|
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Error: %s", err))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
cmdConfig.RetryInterval = dur
|
|
|
|
}
|
|
|
|
|
2014-11-17 22:14:59 +00:00
|
|
|
if retryIntervalWan != "" {
|
|
|
|
dur, err := time.ParseDuration(retryIntervalWan)
|
2014-11-14 15:02:42 +00:00
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Error: %s", err))
|
|
|
|
return nil
|
|
|
|
}
|
2014-11-17 22:14:59 +00:00
|
|
|
cmdConfig.RetryIntervalWan = dur
|
2014-11-14 15:02:42 +00:00
|
|
|
}
|
|
|
|
|
2015-11-29 04:40:05 +00:00
|
|
|
var config *Config
|
|
|
|
if dev {
|
|
|
|
config = DevConfig()
|
|
|
|
} else {
|
|
|
|
config = DefaultConfig()
|
|
|
|
}
|
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
if len(configFiles) > 0 {
|
|
|
|
fileConfig, err := ReadConfigPaths(configFiles)
|
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(err.Error())
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
config = MergeConfig(config, fileConfig)
|
|
|
|
}
|
|
|
|
|
2015-02-21 06:45:52 +00:00
|
|
|
cmdConfig.DNSRecursors = append(cmdConfig.DNSRecursors, dnsRecursors...)
|
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
config = MergeConfig(config, &cmdConfig)
|
|
|
|
|
|
|
|
if config.NodeName == "" {
|
|
|
|
hostname, err := os.Hostname()
|
|
|
|
if err != nil {
|
2016-03-31 21:47:55 +00:00
|
|
|
c.Ui.Error(fmt.Sprintf("Error determining node name: %s", err))
|
|
|
|
return nil
|
|
|
|
}
|
2013-12-21 00:39:32 +00:00
|
|
|
config.NodeName = hostname
|
|
|
|
}
|
2016-03-31 22:10:19 +00:00
|
|
|
config.NodeName = strings.TrimSpace(config.NodeName)
|
|
|
|
if config.NodeName == "" {
|
2016-03-31 22:02:58 +00:00
|
|
|
c.Ui.Error("Node name can not be empty")
|
|
|
|
return nil
|
|
|
|
}
|
2013-12-21 00:39:32 +00:00
|
|
|
|
2016-09-01 06:39:11 +00:00
|
|
|
// Make sure LeaveOnTerm and SkipLeaveOnInt are set to the right
|
|
|
|
// defaults based on the agent's mode (client or server).
|
|
|
|
if config.LeaveOnTerm == nil {
|
|
|
|
config.LeaveOnTerm = Bool(!config.Server)
|
|
|
|
}
|
2016-04-01 00:45:14 +00:00
|
|
|
if config.SkipLeaveOnInt == nil {
|
2016-09-01 06:39:11 +00:00
|
|
|
config.SkipLeaveOnInt = Bool(config.Server)
|
2016-04-01 00:45:14 +00:00
|
|
|
}
|
|
|
|
|
2014-10-03 05:05:00 +00:00
|
|
|
// Ensure we have a data directory
|
2015-11-29 04:40:05 +00:00
|
|
|
if config.DataDir == "" && !dev {
|
2014-10-03 05:05:00 +00:00
|
|
|
c.Ui.Error("Must specify data directory using -data-dir")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-04-01 17:20:45 +00:00
|
|
|
// Ensure all endpoints are unique
|
2016-04-01 17:34:45 +00:00
|
|
|
if err := config.verifyUniqueListeners(); err != nil {
|
2016-04-01 17:20:45 +00:00
|
|
|
c.Ui.Error(fmt.Sprintf("All listening endpoints must be unique: %s", err))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-10-15 21:14:56 +00:00
|
|
|
// Check the data dir for signs of an un-migrated Consul 0.5.x or older
|
|
|
|
// server. Consul refuses to start if this is present to protect a server
|
|
|
|
// with existing data from starting on a fresh data set.
|
|
|
|
if config.Server {
|
2015-10-15 21:21:35 +00:00
|
|
|
mdbPath := filepath.Join(config.DataDir, "mdb")
|
|
|
|
if _, err := os.Stat(mdbPath); !os.IsNotExist(err) {
|
2016-03-28 16:56:24 +00:00
|
|
|
if os.IsPermission(err) {
|
|
|
|
c.Ui.Error(fmt.Sprintf("CRITICAL: Permission denied for data folder at %q!", mdbPath))
|
|
|
|
c.Ui.Error("Consul will refuse to boot without access to this directory.")
|
|
|
|
c.Ui.Error("Please correct permissions and try starting again.")
|
|
|
|
return nil
|
|
|
|
}
|
2015-10-15 21:21:35 +00:00
|
|
|
c.Ui.Error(fmt.Sprintf("CRITICAL: Deprecated data folder found at %q!", mdbPath))
|
2015-10-15 21:14:56 +00:00
|
|
|
c.Ui.Error("Consul will refuse to boot with this directory present.")
|
2016-01-13 22:44:01 +00:00
|
|
|
c.Ui.Error("See https://www.consul.io/docs/upgrade-specific.html for more information.")
|
2015-10-15 21:14:56 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-12 07:58:48 +00:00
|
|
|
// Verify DNS settings
|
|
|
|
if config.DNSConfig.UDPAnswerLimit < 1 {
|
|
|
|
c.Ui.Error(fmt.Sprintf("dns_config.udp_answer_limit %d too low, must always be greater than zero", config.DNSConfig.UDPAnswerLimit))
|
|
|
|
}
|
|
|
|
|
2014-09-15 00:31:44 +00:00
|
|
|
if config.EncryptKey != "" {
|
|
|
|
if _, err := config.EncryptBytes(); err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Invalid encryption key: %s", err))
|
|
|
|
return nil
|
|
|
|
}
|
2014-10-10 18:13:30 +00:00
|
|
|
keyfileLAN := filepath.Join(config.DataDir, serfLANKeyring)
|
|
|
|
if _, err := os.Stat(keyfileLAN); err == nil {
|
2015-02-20 02:51:32 +00:00
|
|
|
c.Ui.Error("WARNING: LAN keyring exists but -encrypt given, using keyring")
|
2014-10-03 05:05:00 +00:00
|
|
|
}
|
|
|
|
if config.Server {
|
2014-10-10 18:13:30 +00:00
|
|
|
keyfileWAN := filepath.Join(config.DataDir, serfWANKeyring)
|
|
|
|
if _, err := os.Stat(keyfileWAN); err == nil {
|
2015-02-20 02:51:32 +00:00
|
|
|
c.Ui.Error("WARNING: WAN keyring exists but -encrypt given, using keyring")
|
2014-10-09 22:28:38 +00:00
|
|
|
}
|
2014-10-03 05:05:00 +00:00
|
|
|
}
|
2014-02-23 01:34:57 +00:00
|
|
|
}
|
|
|
|
|
2016-03-18 14:44:35 +00:00
|
|
|
// Output a warning if the 'dc' flag has been used.
|
|
|
|
if dcDeprecated != "" {
|
|
|
|
c.Ui.Error("WARNING: the 'dc' flag has been deprecated. Use 'datacenter' instead")
|
|
|
|
|
|
|
|
// Making sure that we don't break previous versions.
|
|
|
|
config.Datacenter = dcDeprecated
|
|
|
|
}
|
|
|
|
|
2015-05-05 20:56:37 +00:00
|
|
|
// Ensure the datacenter is always lowercased. The DNS endpoints automatically
|
|
|
|
// lowercase all queries, and internally we expect DC1 and dc1 to be the same.
|
|
|
|
config.Datacenter = strings.ToLower(config.Datacenter)
|
|
|
|
|
2015-02-19 22:45:47 +00:00
|
|
|
// Verify datacenter is valid
|
2014-06-09 18:57:15 +00:00
|
|
|
if !validDatacenter.MatchString(config.Datacenter) {
|
|
|
|
c.Ui.Error("Datacenter must be alpha-numeric with underscores and hypens only")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-11-08 02:41:23 +00:00
|
|
|
// If 'acl_datacenter' is set, ensure it is lowercased.
|
|
|
|
if config.ACLDatacenter != "" {
|
|
|
|
config.ACLDatacenter = strings.ToLower(config.ACLDatacenter)
|
|
|
|
|
|
|
|
// Verify 'acl_datacenter' is valid
|
|
|
|
if !validDatacenter.MatchString(config.ACLDatacenter) {
|
|
|
|
c.Ui.Error("ACL datacenter must be alpha-numeric with underscores and hypens only")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-23 02:58:15 +00:00
|
|
|
// Only allow bootstrap mode when acting as a server
|
|
|
|
if config.Bootstrap && !config.Server {
|
|
|
|
c.Ui.Error("Bootstrap mode cannot be enabled when server mode is not enabled")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-06-16 21:36:12 +00:00
|
|
|
// Expect can only work when acting as a server
|
2014-06-20 00:08:48 +00:00
|
|
|
if config.BootstrapExpect != 0 && !config.Server {
|
2014-06-16 21:36:12 +00:00
|
|
|
c.Ui.Error("Expect mode cannot be enabled when server mode is not enabled")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-11-03 05:54:43 +00:00
|
|
|
// Expect can only work when dev mode is off
|
|
|
|
if config.BootstrapExpect > 0 && config.DevMode {
|
|
|
|
c.Ui.Error("Expect mode cannot be enabled when dev mode is enabled")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-06-16 21:36:12 +00:00
|
|
|
// Expect & Bootstrap are mutually exclusive
|
2014-06-20 00:08:48 +00:00
|
|
|
if config.BootstrapExpect != 0 && config.Bootstrap {
|
2014-06-18 16:03:30 +00:00
|
|
|
c.Ui.Error("Bootstrap cannot be provided with an expected server count")
|
2014-06-16 21:36:12 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-08-21 20:09:13 +00:00
|
|
|
// Compile all the watches
|
|
|
|
for _, params := range config.Watches {
|
|
|
|
// Parse the watches, excluding the handler
|
|
|
|
wp, err := watch.ParseExempt(params, []string{"handler"})
|
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Failed to parse watch (%#v): %v", params, err))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the handler
|
|
|
|
if err := verifyWatchHandler(wp.Exempt["handler"]); err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Failed to setup watch handler (%#v): %v", params, err))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Store the watch plan
|
|
|
|
config.WatchPlans = append(config.WatchPlans, wp)
|
|
|
|
}
|
|
|
|
|
2014-06-16 21:36:12 +00:00
|
|
|
// Warn if we are in expect mode
|
2014-06-20 00:08:48 +00:00
|
|
|
if config.BootstrapExpect == 1 {
|
|
|
|
c.Ui.Error("WARNING: BootstrapExpect Mode is specified as 1; this is the same as Bootstrap mode.")
|
|
|
|
config.BootstrapExpect = 0
|
|
|
|
config.Bootstrap = true
|
|
|
|
} else if config.BootstrapExpect > 0 {
|
|
|
|
c.Ui.Error(fmt.Sprintf("WARNING: Expect Mode enabled, expecting %d servers", config.BootstrapExpect))
|
2014-06-16 21:36:12 +00:00
|
|
|
}
|
|
|
|
|
2014-02-23 02:58:15 +00:00
|
|
|
// Warn if we are in bootstrap mode
|
|
|
|
if config.Bootstrap {
|
|
|
|
c.Ui.Error("WARNING: Bootstrap mode enabled! Do not enable unless necessary")
|
|
|
|
}
|
|
|
|
|
2016-11-02 18:35:37 +00:00
|
|
|
// Need both tag key and value for EC2 discovery
|
|
|
|
if config.RetryJoinEC2.TagKey != "" || config.RetryJoinEC2.TagValue != "" {
|
|
|
|
if config.RetryJoinEC2.TagKey == "" || config.RetryJoinEC2.TagValue == "" {
|
|
|
|
c.Ui.Error("tag key and value are both required for EC2 retry-join")
|
2016-05-12 01:41:41 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-05 08:07:53 +00:00
|
|
|
// EC2 and GCE discovery are mutually exclusive
|
|
|
|
if config.RetryJoinEC2.TagKey != "" && config.RetryJoinEC2.TagValue != "" && config.RetryJoinGCE.TagValue != "" {
|
|
|
|
c.Ui.Error("EC2 and GCE discovery are mutually exclusive. Please provide one or the other.")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-07-20 01:38:15 +00:00
|
|
|
// Set the version info
|
|
|
|
config.Revision = c.Revision
|
|
|
|
config.Version = c.Version
|
|
|
|
config.VersionPrerelease = c.VersionPrerelease
|
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
return config
|
|
|
|
}
|
|
|
|
|
2016-04-01 17:20:45 +00:00
|
|
|
// verifyUniqueListeners checks to see if an address was used more than once in
|
|
|
|
// the config
|
2016-04-01 17:34:45 +00:00
|
|
|
func (config *Config) verifyUniqueListeners() error {
|
2016-04-04 18:03:49 +00:00
|
|
|
listeners := []struct {
|
|
|
|
host string
|
|
|
|
port int
|
|
|
|
descr string
|
|
|
|
}{
|
|
|
|
{config.Addresses.RPC, config.Ports.RPC, "RPC"},
|
|
|
|
{config.Addresses.DNS, config.Ports.DNS, "DNS"},
|
|
|
|
{config.Addresses.HTTP, config.Ports.HTTP, "HTTP"},
|
|
|
|
{config.Addresses.HTTPS, config.Ports.HTTPS, "HTTPS"},
|
|
|
|
{config.AdvertiseAddr, config.Ports.Server, "Server RPC"},
|
|
|
|
{config.AdvertiseAddr, config.Ports.SerfLan, "Serf LAN"},
|
|
|
|
{config.AdvertiseAddr, config.Ports.SerfWan, "Serf WAN"},
|
|
|
|
}
|
|
|
|
|
2016-04-01 17:20:45 +00:00
|
|
|
type key struct {
|
|
|
|
host string
|
|
|
|
port int
|
|
|
|
}
|
2016-04-04 18:03:49 +00:00
|
|
|
m := make(map[key]string, len(listeners))
|
2016-04-01 17:20:45 +00:00
|
|
|
|
2016-04-04 18:03:49 +00:00
|
|
|
for _, l := range listeners {
|
|
|
|
if l.host == "" {
|
|
|
|
l.host = "0.0.0.0"
|
|
|
|
} else if strings.HasPrefix(l.host, "unix") {
|
2016-04-01 17:20:45 +00:00
|
|
|
// Don't compare ports on unix sockets
|
2016-04-04 18:03:49 +00:00
|
|
|
l.port = 0
|
2016-04-01 17:20:45 +00:00
|
|
|
}
|
2016-04-04 18:03:49 +00:00
|
|
|
if l.host == "0.0.0.0" && l.port <= 0 {
|
|
|
|
continue
|
2016-04-01 17:20:45 +00:00
|
|
|
}
|
|
|
|
|
2016-04-04 18:03:49 +00:00
|
|
|
k := key{l.host, l.port}
|
2016-04-01 17:20:45 +00:00
|
|
|
v, ok := m[k]
|
|
|
|
if ok {
|
2016-04-04 18:03:49 +00:00
|
|
|
return fmt.Errorf("%s address already configured for %s", l.descr, v)
|
2016-04-01 17:20:45 +00:00
|
|
|
}
|
2016-04-04 18:03:49 +00:00
|
|
|
m[k] = l.descr
|
2016-04-01 17:20:45 +00:00
|
|
|
}
|
2016-04-01 17:34:45 +00:00
|
|
|
return nil
|
2016-04-01 17:20:45 +00:00
|
|
|
}
|
|
|
|
|
2016-11-02 18:35:37 +00:00
|
|
|
// discoverEc2Hosts searches an AWS region, returning a list of instance ips
|
|
|
|
// where EC2TagKey = EC2TagValue
|
|
|
|
func (c *Config) discoverEc2Hosts(logger *log.Logger) ([]string, error) {
|
|
|
|
config := c.RetryJoinEC2
|
|
|
|
|
|
|
|
ec2meta := ec2metadata.New(session.New())
|
|
|
|
if config.Region == "" {
|
|
|
|
logger.Printf("[INFO] agent: No EC2 region provided, querying instance metadata endpoint...")
|
|
|
|
identity, err := ec2meta.GetInstanceIdentityDocument()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
config.Region = identity.Region
|
|
|
|
}
|
|
|
|
|
2016-05-12 01:41:41 +00:00
|
|
|
awsConfig := &aws.Config{
|
2016-11-02 18:35:37 +00:00
|
|
|
Region: &config.Region,
|
2016-11-02 01:20:08 +00:00
|
|
|
Credentials: credentials.NewChainCredentials(
|
|
|
|
[]credentials.Provider{
|
|
|
|
&credentials.StaticProvider{
|
|
|
|
Value: credentials.Value{
|
|
|
|
AccessKeyID: config.AccessKeyID,
|
|
|
|
SecretAccessKey: config.SecretAccessKey,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
&credentials.EnvProvider{},
|
|
|
|
&credentials.SharedCredentialsProvider{},
|
2016-11-02 22:48:15 +00:00
|
|
|
defaults.RemoteCredProvider(*(defaults.Config()), defaults.Handlers()),
|
2016-11-02 01:20:08 +00:00
|
|
|
}),
|
2016-05-12 01:41:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
svc := ec2.New(session.New(), awsConfig)
|
|
|
|
|
|
|
|
resp, err := svc.DescribeInstances(&ec2.DescribeInstancesInput{
|
|
|
|
Filters: []*ec2.Filter{
|
|
|
|
{
|
2016-11-01 18:45:42 +00:00
|
|
|
Name: aws.String("tag:" + config.TagKey),
|
2016-05-12 01:41:41 +00:00
|
|
|
Values: []*string{
|
2016-11-01 18:45:42 +00:00
|
|
|
aws.String(config.TagValue),
|
2016-05-12 01:41:41 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
2016-11-01 18:45:42 +00:00
|
|
|
return nil, err
|
2016-05-12 01:41:41 +00:00
|
|
|
}
|
|
|
|
|
2016-11-03 17:04:42 +00:00
|
|
|
var servers []string
|
2016-05-12 01:41:41 +00:00
|
|
|
for i := range resp.Reservations {
|
2016-11-01 18:45:42 +00:00
|
|
|
for _, instance := range resp.Reservations[i].Instances {
|
2016-11-02 01:20:08 +00:00
|
|
|
// Terminated instances don't have the PrivateIpAddress field
|
|
|
|
if instance.PrivateIpAddress != nil {
|
|
|
|
servers = append(servers, *instance.PrivateIpAddress)
|
|
|
|
}
|
2016-05-12 01:41:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return servers, nil
|
|
|
|
}
|
|
|
|
|
2016-12-05 08:07:53 +00:00
|
|
|
// discoverGCEHosts searches a Google Compute Engine region, returning a list
|
|
|
|
// of instance ips that match the tags given in GCETags.
|
|
|
|
func (c *Config) discoverGCEHosts(logger *log.Logger) ([]string, error) {
|
|
|
|
config := c.RetryJoinGCE
|
|
|
|
ctx := oauth2.NoContext
|
|
|
|
var client *http.Client
|
|
|
|
var err error
|
|
|
|
|
|
|
|
logger.Printf("[INFO] agent: Initializing GCE client")
|
|
|
|
if config.CredentialsFile != "" {
|
|
|
|
logger.Printf("[INFO] agent: Loading credentials from %s", config.CredentialsFile)
|
|
|
|
key, err := ioutil.ReadFile(config.CredentialsFile)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
jwtConfig, err := google.JWTConfigFromJSON(key, compute.ComputeScope)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
client = jwtConfig.Client(ctx)
|
|
|
|
} else {
|
|
|
|
logger.Printf("[INFO] agent: Using default credential chain")
|
|
|
|
client, err = google.DefaultClient(ctx, compute.ComputeScope)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
computeService, err := compute.New(client)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if config.ProjectName == "" {
|
|
|
|
logger.Printf("[INFO] agent: No GCE project provided, will discover from metadata.")
|
|
|
|
config.ProjectName, err = gceProjectIDFromMetadata(logger)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
logger.Printf("[INFO] agent: Using pre-defined GCE project name: %s", config.ProjectName)
|
|
|
|
}
|
|
|
|
|
|
|
|
zones, err := gceDiscoverZones(logger, ctx, computeService, config.ProjectName, config.ZonePattern)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.Printf("[INFO] agent: Discovering GCE hosts with tag %s in zones: %s", config.TagValue, strings.Join(zones, ", "))
|
|
|
|
|
|
|
|
servers := []string{}
|
|
|
|
for _, zone := range zones {
|
|
|
|
addresses, err := gceInstancesAddressesForZone(logger, ctx, computeService, config.ProjectName, zone, config.TagValue)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-01-12 03:37:22 +00:00
|
|
|
if len(addresses) > 0 {
|
|
|
|
logger.Printf("[INFO] agent: Discovered %d instances in %s/%s: %v", len(addresses), config.ProjectName, zone, addresses)
|
|
|
|
}
|
2016-12-05 08:07:53 +00:00
|
|
|
servers = append(servers, addresses...)
|
|
|
|
}
|
|
|
|
|
|
|
|
return servers, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// gceProjectIDFromMetadata queries the metadata service on GCE to get the
|
|
|
|
// project ID (name) of an instance.
|
|
|
|
func gceProjectIDFromMetadata(logger *log.Logger) (string, error) {
|
|
|
|
logger.Printf("[INFO] agent: Attempting to discover GCE project from metadata.")
|
|
|
|
client := &http.Client{}
|
|
|
|
|
|
|
|
req, err := http.NewRequest("GET", "http://metadata.google.internal/computeMetadata/v1/project/project-id", nil)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
req.Header.Add("Metadata-Flavor", "Google")
|
|
|
|
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
project, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.Printf("[INFO] agent: GCE project discovered as: %s", project)
|
|
|
|
return string(project), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// gceDiscoverZones discovers a list of zones from a supplied zone pattern, or
|
|
|
|
// all of the zones available to a project.
|
|
|
|
func gceDiscoverZones(logger *log.Logger, ctx context.Context, computeService *compute.Service, project, pattern string) ([]string, error) {
|
|
|
|
zones := []string{}
|
|
|
|
|
|
|
|
if pattern != "" {
|
|
|
|
logger.Printf("[INFO] agent: Discovering zones for project %s matching pattern: %s", project, pattern)
|
|
|
|
} else {
|
|
|
|
logger.Printf("[INFO] agent: Discovering all zones available to project: %s", project)
|
|
|
|
}
|
|
|
|
|
|
|
|
call := computeService.Zones.List(project)
|
|
|
|
if pattern != "" {
|
|
|
|
call = call.Filter(fmt.Sprintf("name eq %s", pattern))
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := call.Pages(ctx, func(page *compute.ZoneList) error {
|
|
|
|
for _, v := range page.Items {
|
|
|
|
zones = append(zones, v.Name)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}); err != nil {
|
|
|
|
return zones, err
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.Printf("[INFO] agent: Discovered GCE zones: %s", strings.Join(zones, ", "))
|
|
|
|
return zones, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// gceInstancesAddressesForZone locates all instances within a specific project
|
|
|
|
// and zone, matching the supplied tag. Only the private IP addresses are
|
|
|
|
// returned, but ID is also logged.
|
|
|
|
func gceInstancesAddressesForZone(logger *log.Logger, ctx context.Context, computeService *compute.Service, project, zone, tag string) ([]string, error) {
|
|
|
|
addresses := []string{}
|
|
|
|
call := computeService.Instances.List(project, zone)
|
|
|
|
if err := call.Pages(ctx, func(page *compute.InstanceList) error {
|
|
|
|
for _, v := range page.Items {
|
|
|
|
for _, t := range v.Tags.Items {
|
|
|
|
if t == tag && len(v.NetworkInterfaces) > 0 && v.NetworkInterfaces[0].NetworkIP != "" {
|
|
|
|
addresses = append(addresses, v.NetworkInterfaces[0].NetworkIP)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}); err != nil {
|
|
|
|
return addresses, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return addresses, nil
|
|
|
|
}
|
|
|
|
|
2013-12-23 19:38:51 +00:00
|
|
|
// setupAgent is used to start the agent and various interfaces
|
2016-11-04 04:14:56 +00:00
|
|
|
func (c *Command) setupAgent(config *Config, logOutput io.Writer, logWriter *logger.LogWriter) error {
|
2016-07-19 22:06:32 +00:00
|
|
|
c.Ui.Output("Starting Consul agent...")
|
2016-11-30 18:29:42 +00:00
|
|
|
agent, err := Create(config, logOutput, logWriter, c.configReloadCh)
|
2013-12-23 19:38:51 +00:00
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Error starting agent: %s", err))
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.agent = agent
|
|
|
|
|
2013-12-30 23:27:41 +00:00
|
|
|
// Setup the RPC listener
|
2014-09-02 19:47:40 +00:00
|
|
|
rpcAddr, err := config.ClientListener(config.Addresses.RPC, config.Ports.RPC)
|
2014-04-11 22:22:35 +00:00
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Invalid RPC bind address: %s", err))
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-01-20 21:44:27 +00:00
|
|
|
// Clear the domain socket file if it exists
|
|
|
|
socketPath, isSocket := unixSocketAddr(config.Addresses.RPC)
|
|
|
|
if isSocket {
|
|
|
|
if _, err := os.Stat(socketPath); !os.IsNotExist(err) {
|
|
|
|
agent.logger.Printf("[WARN] agent: Replacing socket %q", socketPath)
|
|
|
|
}
|
|
|
|
if err := os.Remove(socketPath); err != nil && !os.IsNotExist(err) {
|
|
|
|
c.Ui.Output(fmt.Sprintf("Error removing socket file: %s", err))
|
|
|
|
return err
|
2015-01-16 01:24:15 +00:00
|
|
|
}
|
2015-01-08 16:38:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
rpcListener, err := net.Listen(rpcAddr.Network(), rpcAddr.String())
|
2013-12-30 23:27:41 +00:00
|
|
|
if err != nil {
|
|
|
|
agent.Shutdown()
|
|
|
|
c.Ui.Error(fmt.Sprintf("Error starting RPC listener: %s", err))
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-01-20 21:44:27 +00:00
|
|
|
// Set up ownership/permission bits on the socket file
|
|
|
|
if isSocket {
|
|
|
|
if err := setFilePermissions(socketPath, config.UnixSockets); err != nil {
|
|
|
|
agent.Shutdown()
|
|
|
|
c.Ui.Error(fmt.Sprintf("Error setting up socket: %s", err))
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-12-30 23:27:41 +00:00
|
|
|
// Start the IPC layer
|
2014-01-02 23:10:13 +00:00
|
|
|
c.Ui.Output("Starting Consul agent RPC...")
|
2013-12-30 23:27:41 +00:00
|
|
|
c.rpcServer = NewAgentRPC(agent, rpcListener, logOutput, logWriter)
|
|
|
|
|
2015-02-05 02:17:45 +00:00
|
|
|
// Enable the SCADA integration
|
2015-08-26 01:27:07 +00:00
|
|
|
if err := c.setupScadaConn(config); err != nil {
|
|
|
|
agent.Shutdown()
|
|
|
|
c.Ui.Error(fmt.Sprintf("Error starting SCADA connection: %s", err))
|
|
|
|
return err
|
2015-02-05 02:17:45 +00:00
|
|
|
}
|
|
|
|
|
2015-08-25 23:40:55 +00:00
|
|
|
if config.Ports.HTTP > 0 || config.Ports.HTTPS > 0 {
|
|
|
|
servers, err := NewHTTPServers(agent, config, logOutput)
|
2013-12-23 19:38:51 +00:00
|
|
|
if err != nil {
|
|
|
|
agent.Shutdown()
|
2014-11-25 19:06:33 +00:00
|
|
|
c.Ui.Error(fmt.Sprintf("Error starting http servers: %s", err))
|
2013-12-23 19:38:51 +00:00
|
|
|
return err
|
|
|
|
}
|
2014-11-14 19:39:19 +00:00
|
|
|
c.httpServers = servers
|
2013-12-23 19:38:51 +00:00
|
|
|
}
|
2014-01-02 23:10:13 +00:00
|
|
|
|
2014-04-11 22:22:35 +00:00
|
|
|
if config.Ports.DNS > 0 {
|
2014-09-02 19:47:40 +00:00
|
|
|
dnsAddr, err := config.ClientListener(config.Addresses.DNS, config.Ports.DNS)
|
2014-04-11 22:22:35 +00:00
|
|
|
if err != nil {
|
2015-01-08 16:38:09 +00:00
|
|
|
agent.Shutdown()
|
2014-04-11 22:22:35 +00:00
|
|
|
c.Ui.Error(fmt.Sprintf("Invalid DNS bind address: %s", err))
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2014-06-08 22:49:24 +00:00
|
|
|
server, err := NewDNSServer(agent, &config.DNSConfig, logOutput,
|
2014-10-31 19:19:41 +00:00
|
|
|
config.Domain, dnsAddr.String(), config.DNSRecursors)
|
2014-01-02 23:10:13 +00:00
|
|
|
if err != nil {
|
|
|
|
agent.Shutdown()
|
|
|
|
c.Ui.Error(fmt.Sprintf("Error starting dns server: %s", err))
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.dnsServer = server
|
|
|
|
}
|
|
|
|
|
2014-09-02 21:23:43 +00:00
|
|
|
// Setup update checking
|
|
|
|
if !config.DisableUpdateCheck {
|
2015-02-08 06:30:31 +00:00
|
|
|
version := config.Version
|
|
|
|
if config.VersionPrerelease != "" {
|
|
|
|
version += fmt.Sprintf("-%s", config.VersionPrerelease)
|
|
|
|
}
|
2014-09-02 21:23:43 +00:00
|
|
|
updateParams := &checkpoint.CheckParams{
|
|
|
|
Product: "consul",
|
2015-02-08 06:30:31 +00:00
|
|
|
Version: version,
|
2014-09-02 21:23:43 +00:00
|
|
|
}
|
|
|
|
if !config.DisableAnonymousSignature {
|
|
|
|
updateParams.SignatureFile = filepath.Join(config.DataDir, "checkpoint-signature")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Schedule a periodic check with expected interval of 24 hours
|
|
|
|
checkpoint.CheckInterval(updateParams, 24*time.Hour, c.checkpointResults)
|
|
|
|
|
|
|
|
// Do an immediate check within the next 30 seconds
|
|
|
|
go func() {
|
2016-01-29 19:42:34 +00:00
|
|
|
time.Sleep(lib.RandomStagger(30 * time.Second))
|
2014-09-02 21:23:43 +00:00
|
|
|
c.checkpointResults(checkpoint.Check(updateParams))
|
|
|
|
}()
|
|
|
|
}
|
2013-12-23 19:38:51 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-09-02 21:23:43 +00:00
|
|
|
// checkpointResults is used to handler periodic results from our update checker
|
|
|
|
func (c *Command) checkpointResults(results *checkpoint.CheckResponse, err error) {
|
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Failed to check for updates: %v", err))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if results.Outdated {
|
2016-07-19 22:06:32 +00:00
|
|
|
c.Ui.Error(fmt.Sprintf("Newer Consul version available: %s (currently running: %s)", results.CurrentVersion, c.Version))
|
2014-09-02 21:23:43 +00:00
|
|
|
}
|
|
|
|
for _, alert := range results.Alerts {
|
|
|
|
switch alert.Level {
|
|
|
|
case "info":
|
|
|
|
c.Ui.Info(fmt.Sprintf("Bulletin [%s]: %s (%s)", alert.Level, alert.Message, alert.URL))
|
|
|
|
default:
|
|
|
|
c.Ui.Error(fmt.Sprintf("Bulletin [%s]: %s (%s)", alert.Level, alert.Message, alert.URL))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-04-11 23:59:16 +00:00
|
|
|
// startupJoin is invoked to handle any joins specified to take place at start time
|
|
|
|
func (c *Command) startupJoin(config *Config) error {
|
|
|
|
if len(config.StartJoin) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Ui.Output("Joining cluster...")
|
|
|
|
n, err := c.agent.JoinLAN(config.StartJoin)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Ui.Info(fmt.Sprintf("Join completed. Synced with %d initial agents", n))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-11-17 22:14:59 +00:00
|
|
|
// startupJoinWan is invoked to handle any joins -wan specified to take place at start time
|
|
|
|
func (c *Command) startupJoinWan(config *Config) error {
|
|
|
|
if len(config.StartJoinWan) == 0 {
|
2014-11-14 15:02:42 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Ui.Output("Joining -wan cluster...")
|
2014-11-17 22:14:59 +00:00
|
|
|
n, err := c.agent.JoinWAN(config.StartJoinWan)
|
2014-11-14 15:02:42 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Ui.Info(fmt.Sprintf("Join -wan completed. Synced with %d initial agents", n))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-10-12 19:45:40 +00:00
|
|
|
// retryJoin is used to handle retrying a join until it succeeds or all
|
|
|
|
// retries are exhausted.
|
2014-10-12 17:50:15 +00:00
|
|
|
func (c *Command) retryJoin(config *Config, errCh chan<- struct{}) {
|
2016-11-02 18:35:37 +00:00
|
|
|
ec2Enabled := config.RetryJoinEC2.TagKey != "" && config.RetryJoinEC2.TagValue != ""
|
|
|
|
|
2016-12-05 08:07:53 +00:00
|
|
|
if len(config.RetryJoin) == 0 && !ec2Enabled && config.RetryJoinGCE.TagValue == "" {
|
2014-10-12 17:50:15 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
logger := c.agent.logger
|
|
|
|
logger.Printf("[INFO] agent: Joining cluster...")
|
|
|
|
|
|
|
|
attempt := 0
|
|
|
|
for {
|
2016-11-02 18:35:37 +00:00
|
|
|
var servers []string
|
|
|
|
var err error
|
2016-12-05 08:07:53 +00:00
|
|
|
switch {
|
|
|
|
case ec2Enabled:
|
2016-11-02 18:35:37 +00:00
|
|
|
servers, err = config.discoverEc2Hosts(logger)
|
|
|
|
if err != nil {
|
|
|
|
logger.Printf("[ERROR] agent: Unable to query EC2 insances: %s", err)
|
|
|
|
}
|
|
|
|
logger.Printf("[INFO] agent: Discovered %d servers from EC2...", len(servers))
|
2016-12-05 08:07:53 +00:00
|
|
|
case config.RetryJoinGCE.TagValue != "":
|
|
|
|
servers, err = config.discoverGCEHosts(logger)
|
|
|
|
if err != nil {
|
|
|
|
logger.Printf("[ERROR] agent: Unable to query GCE insances: %s", err)
|
|
|
|
}
|
|
|
|
logger.Printf("[INFO] agent: Discovered %d servers from GCE.", len(servers))
|
2016-11-02 18:35:37 +00:00
|
|
|
}
|
|
|
|
|
2016-11-03 17:04:42 +00:00
|
|
|
servers = append(servers, config.RetryJoin...)
|
2016-11-02 18:35:37 +00:00
|
|
|
if len(servers) == 0 {
|
|
|
|
err = fmt.Errorf("No servers to join")
|
|
|
|
} else {
|
|
|
|
n, err := c.agent.JoinLAN(servers)
|
|
|
|
if err == nil {
|
|
|
|
logger.Printf("[INFO] agent: Join completed. Synced with %d initial agents", n)
|
|
|
|
return
|
|
|
|
}
|
2014-10-12 17:50:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
attempt++
|
|
|
|
if config.RetryMaxAttempts > 0 && attempt > config.RetryMaxAttempts {
|
|
|
|
logger.Printf("[ERROR] agent: max join retry exhausted, exiting")
|
|
|
|
close(errCh)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.Printf("[WARN] agent: Join failed: %v, retrying in %v", err,
|
|
|
|
config.RetryInterval)
|
|
|
|
time.Sleep(config.RetryInterval)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-11-17 22:14:59 +00:00
|
|
|
// retryJoinWan is used to handle retrying a join -wan until it succeeds or all
|
2014-11-14 15:02:42 +00:00
|
|
|
// retries are exhausted.
|
2014-11-17 22:14:59 +00:00
|
|
|
func (c *Command) retryJoinWan(config *Config, errCh chan<- struct{}) {
|
|
|
|
if len(config.RetryJoinWan) == 0 {
|
2014-11-14 15:02:42 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
logger := c.agent.logger
|
|
|
|
logger.Printf("[INFO] agent: Joining WAN cluster...")
|
|
|
|
|
|
|
|
attempt := 0
|
|
|
|
for {
|
2014-11-17 22:14:59 +00:00
|
|
|
n, err := c.agent.JoinWAN(config.RetryJoinWan)
|
2014-11-14 15:02:42 +00:00
|
|
|
if err == nil {
|
|
|
|
logger.Printf("[INFO] agent: Join -wan completed. Synced with %d initial agents", n)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
attempt++
|
2014-11-17 22:14:59 +00:00
|
|
|
if config.RetryMaxAttemptsWan > 0 && attempt > config.RetryMaxAttemptsWan {
|
2014-11-14 15:02:42 +00:00
|
|
|
logger.Printf("[ERROR] agent: max join -wan retry exhausted, exiting")
|
|
|
|
close(errCh)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.Printf("[WARN] agent: Join -wan failed: %v, retrying in %v", err,
|
2014-11-17 22:14:59 +00:00
|
|
|
config.RetryIntervalWan)
|
|
|
|
time.Sleep(config.RetryIntervalWan)
|
2014-11-14 15:02:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-10-03 05:05:00 +00:00
|
|
|
// gossipEncrypted determines if the consul instance is using symmetric
|
|
|
|
// encryption keys to protect gossip protocol messages.
|
|
|
|
func (c *Command) gossipEncrypted() bool {
|
|
|
|
if c.agent.config.EncryptKey != "" {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
server := c.agent.server
|
|
|
|
if server != nil {
|
|
|
|
return server.KeyManagerLAN() != nil || server.KeyManagerWAN() != nil
|
|
|
|
}
|
|
|
|
|
|
|
|
client := c.agent.client
|
|
|
|
return client != nil && client.KeyManagerLAN() != nil
|
|
|
|
}
|
|
|
|
|
2013-12-19 20:18:06 +00:00
|
|
|
func (c *Command) Run(args []string) int {
|
2013-12-20 01:14:46 +00:00
|
|
|
c.Ui = &cli.PrefixedUi{
|
|
|
|
OutputPrefix: "==> ",
|
|
|
|
InfoPrefix: " ",
|
|
|
|
ErrorPrefix: "==> ",
|
|
|
|
Ui: c.Ui,
|
|
|
|
}
|
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
// Parse our configs
|
|
|
|
c.args = args
|
|
|
|
config := c.readConfig()
|
|
|
|
if config == nil {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
|
|
|
// Setup the log outputs
|
2016-11-04 04:14:56 +00:00
|
|
|
logConfig := &logger.Config{
|
|
|
|
LogLevel: config.LogLevel,
|
|
|
|
EnableSyslog: config.EnableSyslog,
|
|
|
|
SyslogFacility: config.SyslogFacility,
|
|
|
|
}
|
|
|
|
logFilter, logGate, logWriter, logOutput, ok := logger.Setup(logConfig, c.Ui)
|
|
|
|
if !ok {
|
2013-12-21 00:39:32 +00:00
|
|
|
return 1
|
|
|
|
}
|
2016-11-04 04:14:56 +00:00
|
|
|
c.logFilter = logFilter
|
|
|
|
c.logOutput = logOutput
|
2013-12-21 00:39:32 +00:00
|
|
|
|
2016-11-30 18:29:42 +00:00
|
|
|
// Setup the channel for triggering config reloads
|
|
|
|
c.configReloadCh = make(chan chan error)
|
|
|
|
|
2014-02-20 21:51:51 +00:00
|
|
|
/* Setup telemetry
|
|
|
|
Aggregate on 10 second intervals for 1 minute. Expose the
|
|
|
|
metrics over stderr when there is a SIGUSR1 received.
|
|
|
|
*/
|
|
|
|
inm := metrics.NewInmemSink(10*time.Second, time.Minute)
|
|
|
|
metrics.DefaultInmemSignal(inm)
|
2015-10-08 19:45:45 +00:00
|
|
|
metricsConf := metrics.DefaultConfig(config.Telemetry.StatsitePrefix)
|
|
|
|
metricsConf.EnableHostname = !config.Telemetry.DisableHostname
|
2014-02-20 22:59:54 +00:00
|
|
|
|
2014-09-02 18:26:08 +00:00
|
|
|
// Configure the statsite sink
|
|
|
|
var fanout metrics.FanoutSink
|
2015-10-08 19:45:45 +00:00
|
|
|
if config.Telemetry.StatsiteAddr != "" {
|
|
|
|
sink, err := metrics.NewStatsiteSink(config.Telemetry.StatsiteAddr)
|
2014-02-20 22:59:54 +00:00
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Failed to start statsite sink. Got: %s", err))
|
|
|
|
return 1
|
|
|
|
}
|
2014-09-02 18:26:08 +00:00
|
|
|
fanout = append(fanout, sink)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Configure the statsd sink
|
2015-10-08 19:45:45 +00:00
|
|
|
if config.Telemetry.StatsdAddr != "" {
|
|
|
|
sink, err := metrics.NewStatsdSink(config.Telemetry.StatsdAddr)
|
2014-09-02 18:26:08 +00:00
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Failed to start statsd sink. Got: %s", err))
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
fanout = append(fanout, sink)
|
2015-06-16 22:05:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Configure the DogStatsd sink
|
2015-10-08 19:45:45 +00:00
|
|
|
if config.Telemetry.DogStatsdAddr != "" {
|
2015-06-16 22:05:55 +00:00
|
|
|
var tags []string
|
|
|
|
|
2015-10-08 19:45:45 +00:00
|
|
|
if config.Telemetry.DogStatsdTags != nil {
|
|
|
|
tags = config.Telemetry.DogStatsdTags
|
2015-06-16 22:05:55 +00:00
|
|
|
}
|
|
|
|
|
2015-10-08 19:45:45 +00:00
|
|
|
sink, err := datadog.NewDogStatsdSink(config.Telemetry.DogStatsdAddr, metricsConf.HostName)
|
2015-06-16 22:05:55 +00:00
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Failed to start DogStatsd sink. Got: %s", err))
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
sink.SetTags(tags)
|
|
|
|
fanout = append(fanout, sink)
|
2014-09-02 18:26:08 +00:00
|
|
|
}
|
2014-02-20 22:59:54 +00:00
|
|
|
|
2016-07-18 13:34:43 +00:00
|
|
|
if config.Telemetry.CirconusAPIToken != "" || config.Telemetry.CirconusCheckSubmissionURL != "" {
|
|
|
|
cfg := &circonus.Config{}
|
2016-07-18 19:46:11 +00:00
|
|
|
cfg.Interval = config.Telemetry.CirconusSubmissionInterval
|
2016-07-18 13:34:43 +00:00
|
|
|
cfg.CheckManager.API.TokenKey = config.Telemetry.CirconusAPIToken
|
|
|
|
cfg.CheckManager.API.TokenApp = config.Telemetry.CirconusAPIApp
|
|
|
|
cfg.CheckManager.API.URL = config.Telemetry.CirconusAPIURL
|
|
|
|
cfg.CheckManager.Check.SubmissionURL = config.Telemetry.CirconusCheckSubmissionURL
|
|
|
|
cfg.CheckManager.Check.ID = config.Telemetry.CirconusCheckID
|
|
|
|
cfg.CheckManager.Check.ForceMetricActivation = config.Telemetry.CirconusCheckForceMetricActivation
|
|
|
|
cfg.CheckManager.Check.InstanceID = config.Telemetry.CirconusCheckInstanceID
|
|
|
|
cfg.CheckManager.Check.SearchTag = config.Telemetry.CirconusCheckSearchTag
|
2016-11-09 20:33:37 +00:00
|
|
|
cfg.CheckManager.Check.DisplayName = config.Telemetry.CirconusCheckDisplayName
|
|
|
|
cfg.CheckManager.Check.Tags = config.Telemetry.CirconusCheckTags
|
2016-07-18 13:34:43 +00:00
|
|
|
cfg.CheckManager.Broker.ID = config.Telemetry.CirconusBrokerID
|
|
|
|
cfg.CheckManager.Broker.SelectTag = config.Telemetry.CirconusBrokerSelectTag
|
|
|
|
|
2016-07-18 19:46:11 +00:00
|
|
|
if cfg.CheckManager.API.TokenApp == "" {
|
|
|
|
cfg.CheckManager.API.TokenApp = "consul"
|
|
|
|
}
|
|
|
|
|
2016-07-18 13:34:43 +00:00
|
|
|
if cfg.CheckManager.Check.SearchTag == "" {
|
|
|
|
cfg.CheckManager.Check.SearchTag = "service:consul"
|
|
|
|
}
|
|
|
|
|
|
|
|
sink, err := circonus.NewCirconusSink(cfg)
|
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Failed to start Circonus sink. Got: %s", err))
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
sink.Start()
|
|
|
|
fanout = append(fanout, sink)
|
|
|
|
}
|
|
|
|
|
2014-09-02 18:26:08 +00:00
|
|
|
// Initialize the global sink
|
|
|
|
if len(fanout) > 0 {
|
|
|
|
fanout = append(fanout, inm)
|
|
|
|
metrics.NewGlobal(metricsConf, fanout)
|
2014-02-20 22:59:54 +00:00
|
|
|
} else {
|
|
|
|
metricsConf.EnableHostname = false
|
|
|
|
metrics.NewGlobal(metricsConf, inm)
|
|
|
|
}
|
2014-02-20 21:51:51 +00:00
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
// Create the agent
|
2013-12-30 23:27:41 +00:00
|
|
|
if err := c.setupAgent(config, logOutput, logWriter); err != nil {
|
2013-12-20 01:14:46 +00:00
|
|
|
return 1
|
|
|
|
}
|
2013-12-23 19:38:51 +00:00
|
|
|
defer c.agent.Shutdown()
|
2013-12-30 23:27:41 +00:00
|
|
|
if c.rpcServer != nil {
|
|
|
|
defer c.rpcServer.Shutdown()
|
|
|
|
}
|
2015-01-16 12:11:34 +00:00
|
|
|
if c.dnsServer != nil {
|
|
|
|
defer c.dnsServer.Shutdown()
|
|
|
|
}
|
2014-11-18 22:56:48 +00:00
|
|
|
for _, server := range c.httpServers {
|
|
|
|
defer server.Shutdown()
|
2013-12-23 19:38:51 +00:00
|
|
|
}
|
2015-08-25 23:40:55 +00:00
|
|
|
|
|
|
|
// Check and shut down the SCADA listeners at the end
|
|
|
|
defer func() {
|
|
|
|
if c.scadaHttp != nil {
|
|
|
|
c.scadaHttp.Shutdown()
|
|
|
|
}
|
|
|
|
if c.scadaProvider != nil {
|
|
|
|
c.scadaProvider.Shutdown()
|
|
|
|
}
|
|
|
|
}()
|
2013-12-20 01:14:46 +00:00
|
|
|
|
2014-04-11 23:59:16 +00:00
|
|
|
// Join startup nodes if specified
|
|
|
|
if err := c.startupJoin(config); err != nil {
|
|
|
|
c.Ui.Error(err.Error())
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
2014-11-14 15:02:42 +00:00
|
|
|
// Join startup nodes if specified
|
2014-11-17 22:14:59 +00:00
|
|
|
if err := c.startupJoinWan(config); err != nil {
|
2014-11-14 15:02:42 +00:00
|
|
|
c.Ui.Error(err.Error())
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
2014-11-14 19:39:19 +00:00
|
|
|
// Get the new client http listener addr
|
2015-01-13 17:50:17 +00:00
|
|
|
httpAddr, err := config.ClientListener(config.Addresses.HTTP, config.Ports.HTTP)
|
2014-08-21 20:09:13 +00:00
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Failed to determine HTTP address: %v", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Register the watches
|
|
|
|
for _, wp := range config.WatchPlans {
|
2014-09-15 17:55:57 +00:00
|
|
|
go func(wp *watch.WatchPlan) {
|
2016-10-04 15:36:41 +00:00
|
|
|
wp.Handler = makeWatchHandler(logOutput, wp.Exempt["handler"])
|
2014-08-21 20:09:13 +00:00
|
|
|
wp.LogOutput = c.logOutput
|
2015-01-13 17:50:17 +00:00
|
|
|
if err := wp.Run(httpAddr.String()); err != nil {
|
2014-08-21 20:09:13 +00:00
|
|
|
c.Ui.Error(fmt.Sprintf("Error running watch: %v", err))
|
|
|
|
}
|
2014-09-15 17:55:57 +00:00
|
|
|
}(wp)
|
2014-08-21 20:09:13 +00:00
|
|
|
}
|
|
|
|
|
2014-10-04 02:20:58 +00:00
|
|
|
// Figure out if gossip is encrypted
|
2014-10-12 00:29:24 +00:00
|
|
|
var gossipEncrypted bool
|
|
|
|
if config.Server {
|
|
|
|
gossipEncrypted = c.agent.server.Encrypted()
|
|
|
|
} else {
|
|
|
|
gossipEncrypted = c.agent.client.Encrypted()
|
|
|
|
}
|
2014-10-04 02:20:58 +00:00
|
|
|
|
2015-02-05 02:06:36 +00:00
|
|
|
// Determine the Atlas cluster
|
2015-02-06 20:44:55 +00:00
|
|
|
atlas := "<disabled>"
|
|
|
|
if config.AtlasInfrastructure != "" {
|
|
|
|
atlas = fmt.Sprintf("(Infrastructure: '%s' Join: %v)", config.AtlasInfrastructure, config.AtlasJoin)
|
2015-02-05 02:06:36 +00:00
|
|
|
}
|
|
|
|
|
2014-01-16 01:14:50 +00:00
|
|
|
// Let the agent know we've finished registration
|
2014-01-21 19:52:25 +00:00
|
|
|
c.agent.StartSync()
|
2014-01-16 01:14:50 +00:00
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
c.Ui.Output("Consul agent running!")
|
2016-07-20 15:09:05 +00:00
|
|
|
c.Ui.Info(fmt.Sprintf(" Version: '%s'", c.HumanVersion))
|
2014-05-21 00:00:04 +00:00
|
|
|
c.Ui.Info(fmt.Sprintf(" Node name: '%s'", config.NodeName))
|
|
|
|
c.Ui.Info(fmt.Sprintf(" Datacenter: '%s'", config.Datacenter))
|
|
|
|
c.Ui.Info(fmt.Sprintf(" Server: %v (bootstrap: %v)", config.Server, config.Bootstrap))
|
2014-11-14 19:39:19 +00:00
|
|
|
c.Ui.Info(fmt.Sprintf(" Client Addr: %v (HTTP: %d, HTTPS: %d, DNS: %d, RPC: %d)", config.ClientAddr,
|
|
|
|
config.Ports.HTTP, config.Ports.HTTPS, config.Ports.DNS, config.Ports.RPC))
|
2014-05-21 00:00:04 +00:00
|
|
|
c.Ui.Info(fmt.Sprintf(" Cluster Addr: %v (LAN: %d, WAN: %d)", config.AdvertiseAddr,
|
2014-04-11 22:54:03 +00:00
|
|
|
config.Ports.SerfLan, config.Ports.SerfWan))
|
2014-05-21 00:00:04 +00:00
|
|
|
c.Ui.Info(fmt.Sprintf("Gossip encrypt: %v, RPC-TLS: %v, TLS-Incoming: %v",
|
2014-10-04 02:20:58 +00:00
|
|
|
gossipEncrypted, config.VerifyOutgoing, config.VerifyIncoming))
|
2015-02-06 20:44:55 +00:00
|
|
|
c.Ui.Info(fmt.Sprintf(" Atlas: %s", atlas))
|
2013-12-21 00:39:32 +00:00
|
|
|
|
|
|
|
// Enable log streaming
|
|
|
|
c.Ui.Info("")
|
|
|
|
c.Ui.Output("Log data will now stream in as it occurs:\n")
|
|
|
|
logGate.Flush()
|
|
|
|
|
2014-10-12 17:50:15 +00:00
|
|
|
// Start retry join process
|
|
|
|
errCh := make(chan struct{})
|
|
|
|
go c.retryJoin(config, errCh)
|
|
|
|
|
2014-11-14 15:02:42 +00:00
|
|
|
// Start retry -wan join process
|
|
|
|
errWanCh := make(chan struct{})
|
2014-11-17 22:14:59 +00:00
|
|
|
go c.retryJoinWan(config, errWanCh)
|
2014-11-14 15:02:42 +00:00
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
// Wait for exit
|
2014-11-14 15:02:42 +00:00
|
|
|
return c.handleSignals(config, errCh, errWanCh)
|
2013-12-21 00:39:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// handleSignals blocks until we get an exit-causing signal
|
2014-11-17 22:14:59 +00:00
|
|
|
func (c *Command) handleSignals(config *Config, retryJoin <-chan struct{}, retryJoinWan <-chan struct{}) int {
|
2013-12-21 00:39:32 +00:00
|
|
|
signalCh := make(chan os.Signal, 4)
|
|
|
|
signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
|
|
|
|
|
|
|
|
// Wait for a signal
|
|
|
|
WAIT:
|
|
|
|
var sig os.Signal
|
2016-11-30 18:29:42 +00:00
|
|
|
var reloadErrCh chan error
|
2013-12-20 01:14:46 +00:00
|
|
|
select {
|
2013-12-21 00:39:32 +00:00
|
|
|
case s := <-signalCh:
|
|
|
|
sig = s
|
2014-06-11 17:53:28 +00:00
|
|
|
case <-c.rpcServer.ReloadCh():
|
|
|
|
sig = syscall.SIGHUP
|
2016-11-30 18:29:42 +00:00
|
|
|
case ch := <-c.configReloadCh:
|
|
|
|
sig = syscall.SIGHUP
|
|
|
|
reloadErrCh = ch
|
2013-12-20 01:14:46 +00:00
|
|
|
case <-c.ShutdownCh:
|
2013-12-21 00:39:32 +00:00
|
|
|
sig = os.Interrupt
|
2014-10-12 17:50:15 +00:00
|
|
|
case <-retryJoin:
|
|
|
|
return 1
|
2014-11-17 22:14:59 +00:00
|
|
|
case <-retryJoinWan:
|
2014-11-14 15:02:42 +00:00
|
|
|
return 1
|
2013-12-23 19:38:51 +00:00
|
|
|
case <-c.agent.ShutdownCh():
|
2013-12-21 00:39:32 +00:00
|
|
|
// Agent is already shutdown!
|
2013-12-20 01:14:46 +00:00
|
|
|
return 0
|
|
|
|
}
|
2013-12-21 00:39:32 +00:00
|
|
|
c.Ui.Output(fmt.Sprintf("Caught signal: %v", sig))
|
|
|
|
|
|
|
|
// Check if this is a SIGHUP
|
|
|
|
if sig == syscall.SIGHUP {
|
2016-11-30 18:29:42 +00:00
|
|
|
conf, err := c.handleReload(config)
|
|
|
|
if conf != nil {
|
2015-05-31 05:50:08 +00:00
|
|
|
config = conf
|
|
|
|
}
|
2016-11-30 18:29:42 +00:00
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(err.Error())
|
|
|
|
}
|
|
|
|
// Send result back if reload was called via HTTP
|
|
|
|
if reloadErrCh != nil {
|
|
|
|
reloadErrCh <- err
|
|
|
|
}
|
2013-12-21 00:39:32 +00:00
|
|
|
goto WAIT
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if we should do a graceful leave
|
|
|
|
graceful := false
|
2016-04-01 00:45:14 +00:00
|
|
|
if sig == os.Interrupt && !(*config.SkipLeaveOnInt) {
|
2013-12-21 00:39:32 +00:00
|
|
|
graceful = true
|
2016-09-01 06:39:11 +00:00
|
|
|
} else if sig == syscall.SIGTERM && (*config.LeaveOnTerm) {
|
2013-12-21 00:39:32 +00:00
|
|
|
graceful = true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Bail fast if not doing a graceful leave
|
|
|
|
if !graceful {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
|
|
|
// Attempt a graceful leave
|
|
|
|
gracefulCh := make(chan struct{})
|
|
|
|
c.Ui.Output("Gracefully shutting down agent...")
|
|
|
|
go func() {
|
2013-12-23 19:38:51 +00:00
|
|
|
if err := c.agent.Leave(); err != nil {
|
2013-12-21 00:39:32 +00:00
|
|
|
c.Ui.Error(fmt.Sprintf("Error: %s", err))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
close(gracefulCh)
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Wait for leave or another signal
|
|
|
|
select {
|
|
|
|
case <-signalCh:
|
|
|
|
return 1
|
|
|
|
case <-time.After(gracefulTimeout):
|
|
|
|
return 1
|
|
|
|
case <-gracefulCh:
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleReload is invoked when we should reload our configs, e.g. SIGHUP
|
2016-11-30 18:29:42 +00:00
|
|
|
func (c *Command) handleReload(config *Config) (*Config, error) {
|
2013-12-21 00:39:32 +00:00
|
|
|
c.Ui.Output("Reloading configuration...")
|
2016-11-30 18:29:42 +00:00
|
|
|
var errs error
|
2014-02-07 20:03:14 +00:00
|
|
|
newConf := c.readConfig()
|
|
|
|
if newConf == nil {
|
2016-11-30 18:29:42 +00:00
|
|
|
errs = multierror.Append(errs, fmt.Errorf("Failed to reload configs"))
|
|
|
|
return config, errs
|
2014-02-07 20:03:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Change the log level
|
|
|
|
minLevel := logutils.LogLevel(strings.ToUpper(newConf.LogLevel))
|
2016-11-04 04:14:56 +00:00
|
|
|
if logger.ValidateLevelFilter(minLevel, c.logFilter) {
|
2014-02-07 20:03:14 +00:00
|
|
|
c.logFilter.SetMinLevel(minLevel)
|
|
|
|
} else {
|
2016-11-30 18:29:42 +00:00
|
|
|
errs = multierror.Append(fmt.Errorf(
|
2014-02-07 20:03:14 +00:00
|
|
|
"Invalid log level: %s. Valid log levels are: %v",
|
|
|
|
minLevel, c.logFilter.Levels))
|
|
|
|
|
|
|
|
// Keep the current log level
|
|
|
|
newConf.LogLevel = config.LogLevel
|
|
|
|
}
|
|
|
|
|
2014-02-07 20:19:56 +00:00
|
|
|
// Bulk update the services and checks
|
|
|
|
c.agent.PauseSync()
|
|
|
|
defer c.agent.ResumeSync()
|
|
|
|
|
2015-02-17 20:00:04 +00:00
|
|
|
// Snapshot the current state, and restore it afterwards
|
|
|
|
snap := c.agent.snapshotCheckState()
|
|
|
|
defer c.agent.restoreCheckState(snap)
|
|
|
|
|
2015-01-08 02:05:46 +00:00
|
|
|
// First unload all checks and services. This lets us begin the reload
|
|
|
|
// with a clean slate.
|
|
|
|
if err := c.agent.unloadServices(); err != nil {
|
2016-11-30 18:29:42 +00:00
|
|
|
errs = multierror.Append(errs, fmt.Errorf("Failed unloading services: %s", err))
|
|
|
|
return nil, errs
|
2015-01-08 02:05:46 +00:00
|
|
|
}
|
|
|
|
if err := c.agent.unloadChecks(); err != nil {
|
2016-11-30 18:29:42 +00:00
|
|
|
errs = multierror.Append(errs, fmt.Errorf("Failed unloading checks: %s", err))
|
|
|
|
return nil, errs
|
2015-01-08 02:05:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Reload services and check definitions.
|
|
|
|
if err := c.agent.loadServices(newConf); err != nil {
|
2016-11-30 18:29:42 +00:00
|
|
|
errs = multierror.Append(errs, fmt.Errorf("Failed reloading services: %s", err))
|
|
|
|
return nil, errs
|
2014-02-07 20:19:56 +00:00
|
|
|
}
|
2015-01-08 02:05:46 +00:00
|
|
|
if err := c.agent.loadChecks(newConf); err != nil {
|
2016-11-30 18:29:42 +00:00
|
|
|
errs = multierror.Append(errs, fmt.Errorf("Failed reloading checks: %s", err))
|
|
|
|
return nil, errs
|
2014-02-07 20:19:56 +00:00
|
|
|
}
|
2014-02-07 20:03:14 +00:00
|
|
|
|
2014-08-21 20:09:13 +00:00
|
|
|
// Get the new client listener addr
|
2015-01-13 17:50:17 +00:00
|
|
|
httpAddr, err := newConf.ClientListener(config.Addresses.HTTP, config.Ports.HTTP)
|
2014-08-21 20:09:13 +00:00
|
|
|
if err != nil {
|
2016-11-30 18:29:42 +00:00
|
|
|
errs = multierror.Append(errs, fmt.Errorf("Failed to determine HTTP address: %v", err))
|
2014-08-21 20:09:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Deregister the old watches
|
|
|
|
for _, wp := range config.WatchPlans {
|
|
|
|
wp.Stop()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Register the new watches
|
|
|
|
for _, wp := range newConf.WatchPlans {
|
2014-09-15 17:55:57 +00:00
|
|
|
go func(wp *watch.WatchPlan) {
|
2016-10-04 15:36:41 +00:00
|
|
|
wp.Handler = makeWatchHandler(c.logOutput, wp.Exempt["handler"])
|
2014-08-21 20:09:13 +00:00
|
|
|
wp.LogOutput = c.logOutput
|
2015-01-13 17:50:17 +00:00
|
|
|
if err := wp.Run(httpAddr.String()); err != nil {
|
2016-11-30 18:29:42 +00:00
|
|
|
errs = multierror.Append(errs, fmt.Errorf("Error running watch: %v", err))
|
2014-08-21 20:09:13 +00:00
|
|
|
}
|
2014-09-15 17:55:57 +00:00
|
|
|
}(wp)
|
2014-08-21 20:09:13 +00:00
|
|
|
}
|
|
|
|
|
2015-08-26 03:43:57 +00:00
|
|
|
// Reload SCADA client if we have a change
|
|
|
|
if newConf.AtlasInfrastructure != config.AtlasInfrastructure ||
|
2015-08-27 20:29:07 +00:00
|
|
|
newConf.AtlasToken != config.AtlasToken ||
|
|
|
|
newConf.AtlasEndpoint != config.AtlasEndpoint {
|
2015-08-26 03:43:57 +00:00
|
|
|
if err := c.setupScadaConn(newConf); err != nil {
|
2016-11-30 18:29:42 +00:00
|
|
|
errs = multierror.Append(errs, fmt.Errorf("Failed reloading SCADA client: %s", err))
|
|
|
|
return nil, errs
|
2015-08-26 03:43:57 +00:00
|
|
|
}
|
2015-08-26 01:27:07 +00:00
|
|
|
}
|
|
|
|
|
2016-11-30 18:29:42 +00:00
|
|
|
return newConf, errs
|
2015-08-26 01:27:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// startScadaClient is used to start a new SCADA provider and listener,
|
|
|
|
// replacing any existing listeners.
|
|
|
|
func (c *Command) setupScadaConn(config *Config) error {
|
|
|
|
// Shut down existing SCADA listeners
|
2015-08-25 23:40:55 +00:00
|
|
|
if c.scadaProvider != nil {
|
|
|
|
c.scadaProvider.Shutdown()
|
2015-08-26 01:27:07 +00:00
|
|
|
}
|
|
|
|
if c.scadaHttp != nil {
|
|
|
|
c.scadaHttp.Shutdown()
|
|
|
|
}
|
2015-08-25 23:40:55 +00:00
|
|
|
|
2015-08-26 01:27:07 +00:00
|
|
|
// No-op if we don't have an infrastructure
|
|
|
|
if config.AtlasInfrastructure == "" {
|
|
|
|
return nil
|
2015-08-25 23:40:55 +00:00
|
|
|
}
|
|
|
|
|
2016-06-01 20:35:34 +00:00
|
|
|
scadaConfig := &scada.Config{
|
|
|
|
Service: "consul",
|
|
|
|
Version: fmt.Sprintf("%s%s", config.Version, config.VersionPrerelease),
|
|
|
|
ResourceType: "infrastructures",
|
|
|
|
Meta: map[string]string{
|
|
|
|
"auto-join": strconv.FormatBool(config.AtlasJoin),
|
|
|
|
"datacenter": config.Datacenter,
|
|
|
|
"server": strconv.FormatBool(config.Server),
|
|
|
|
},
|
|
|
|
Atlas: scada.AtlasConfig{
|
|
|
|
Endpoint: config.AtlasEndpoint,
|
|
|
|
Infrastructure: config.AtlasInfrastructure,
|
|
|
|
Token: config.AtlasToken,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2015-08-26 01:27:07 +00:00
|
|
|
// Create the new provider and listener
|
2015-08-26 04:03:16 +00:00
|
|
|
c.Ui.Output("Connecting to Atlas: " + config.AtlasInfrastructure)
|
2016-06-01 20:35:34 +00:00
|
|
|
provider, list, err := scada.NewHTTPProvider(scadaConfig, c.logOutput)
|
2015-08-26 01:27:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.scadaProvider = provider
|
|
|
|
c.scadaHttp = newScadaHttp(c.agent, list)
|
|
|
|
return nil
|
2013-12-19 20:18:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Command) Synopsis() string {
|
|
|
|
return "Runs a Consul agent"
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Command) Help() string {
|
|
|
|
helpText := `
|
|
|
|
Usage: consul agent [options]
|
|
|
|
|
|
|
|
Starts the Consul agent and runs until an interrupt is received. The
|
2014-04-11 22:22:35 +00:00
|
|
|
agent represents a single node in a cluster.
|
2013-12-19 20:18:06 +00:00
|
|
|
|
|
|
|
Options:
|
|
|
|
|
2016-12-05 08:07:53 +00:00
|
|
|
-advertise=addr Sets the advertise address to use
|
|
|
|
-advertise-wan=addr Sets address to advertise on wan instead of
|
|
|
|
advertise addr
|
|
|
|
-atlas=org/name Sets the Atlas infrastructure name, enables
|
|
|
|
SCADA.
|
|
|
|
-atlas-join Enables auto-joining the Atlas cluster
|
|
|
|
-atlas-token=token Provides the Atlas API token
|
|
|
|
-atlas-endpoint=1.2.3.4 The address of the endpoint for Atlas
|
|
|
|
integration.
|
|
|
|
-bootstrap Sets server to bootstrap mode
|
|
|
|
-bind=0.0.0.0 Sets the bind address for cluster
|
|
|
|
communication
|
|
|
|
-http-port=8500 Sets the HTTP API port to listen on
|
|
|
|
-bootstrap-expect=0 Sets server to expect bootstrap mode.
|
|
|
|
-client=127.0.0.1 Sets the address to bind for client access.
|
|
|
|
This includes RPC, DNS, HTTP and HTTPS (if
|
|
|
|
configured)
|
|
|
|
-config-file=foo Path to a JSON file to read configuration
|
|
|
|
from. This can be specified multiple times.
|
|
|
|
-config-dir=foo Path to a directory to read configuration
|
|
|
|
files from. This will read every file ending
|
|
|
|
in ".json" as configuration in this
|
|
|
|
directory in alphabetical order. This can be
|
|
|
|
specified multiple times.
|
|
|
|
-data-dir=path Path to a data directory to store agent
|
|
|
|
state
|
|
|
|
-dev Starts the agent in development mode.
|
|
|
|
-recursor=1.2.3.4 Address of an upstream DNS server.
|
|
|
|
Can be specified multiple times.
|
|
|
|
-dc=east-aws Datacenter of the agent (deprecated: use
|
|
|
|
'datacenter' instead).
|
|
|
|
-datacenter=east-aws Datacenter of the agent.
|
|
|
|
-encrypt=key Provides the gossip encryption key
|
|
|
|
-join=1.2.3.4 Address of an agent to join at start time.
|
|
|
|
Can be specified multiple times.
|
|
|
|
-join-wan=1.2.3.4 Address of an agent to join -wan at start
|
|
|
|
time. Can be specified multiple times.
|
|
|
|
-retry-join=1.2.3.4 Address of an agent to join at start time
|
|
|
|
with retries enabled. Can be specified
|
|
|
|
multiple times.
|
|
|
|
-retry-interval=30s Time to wait between join attempts.
|
|
|
|
-retry-max=0 Maximum number of join attempts. Defaults to
|
|
|
|
0, which will retry indefinitely.
|
|
|
|
-retry-join-ec2-region EC2 Region to use for discovering servers to
|
|
|
|
join.
|
|
|
|
-retry-join-ec2-tag-key EC2 tag key to filter on for server
|
|
|
|
discovery
|
|
|
|
-retry-join-ec2-tag-value EC2 tag value to filter on for server
|
|
|
|
discovery
|
|
|
|
-retry-join-gce-project-name Google Compute Engine project to discover
|
|
|
|
servers in
|
|
|
|
-retry-join-gce-zone-pattern Google Compute Engine region or zone to
|
|
|
|
discover servers in (regex pattern)
|
|
|
|
-retry-join-gce-tag-value Google Compute Engine tag value to filter
|
|
|
|
for server discovery
|
|
|
|
-retry-join-gce-credentials-file Path to credentials JSON file to use with
|
|
|
|
Google Compute Engine
|
|
|
|
-retry-join-wan=1.2.3.4 Address of an agent to join -wan at start
|
|
|
|
time with retries enabled. Can be specified
|
|
|
|
multiple times.
|
|
|
|
-retry-interval-wan=30s Time to wait between join -wan attempts.
|
|
|
|
-retry-max-wan=0 Maximum number of join -wan attempts.
|
|
|
|
Defaults to 0, which will retry
|
|
|
|
indefinitely.
|
|
|
|
-log-level=info Log level of the agent.
|
|
|
|
-node=hostname Name of this node. Must be unique in the
|
|
|
|
cluster
|
|
|
|
-protocol=N Sets the protocol version. Defaults to
|
|
|
|
latest.
|
|
|
|
-rejoin Ignores a previous leave and attempts to
|
|
|
|
rejoin the cluster.
|
|
|
|
-server Switches agent to server mode.
|
|
|
|
-syslog Enables logging to syslog
|
|
|
|
-ui Enables the built-in static web UI server
|
|
|
|
-ui-dir=path Path to directory containing the Web UI
|
|
|
|
resources
|
|
|
|
-pid-file=path Path to file to store agent PID
|
2014-04-11 22:22:35 +00:00
|
|
|
|
|
|
|
`
|
2013-12-19 20:18:06 +00:00
|
|
|
return strings.TrimSpace(helpText)
|
|
|
|
}
|