2013-12-20 01:14:46 +00:00
|
|
|
package agent
|
|
|
|
|
2013-12-20 23:33:13 +00:00
|
|
|
import (
|
2017-05-19 09:53:41 +00:00
|
|
|
"context"
|
2017-04-10 18:57:24 +00:00
|
|
|
"crypto/sha512"
|
2017-05-24 13:22:56 +00:00
|
|
|
"crypto/tls"
|
2014-11-24 08:36:03 +00:00
|
|
|
"encoding/json"
|
2013-12-20 23:33:13 +00:00
|
|
|
"fmt"
|
2013-12-21 00:39:32 +00:00
|
|
|
"io"
|
2015-06-04 21:33:30 +00:00
|
|
|
"io/ioutil"
|
2013-12-21 00:39:32 +00:00
|
|
|
"log"
|
2014-01-01 00:45:13 +00:00
|
|
|
"net"
|
2017-05-19 09:53:41 +00:00
|
|
|
"net/http"
|
2013-12-21 00:39:32 +00:00
|
|
|
"os"
|
2014-09-06 00:22:33 +00:00
|
|
|
"path/filepath"
|
2014-02-24 00:42:39 +00:00
|
|
|
"strconv"
|
2016-12-02 05:35:38 +00:00
|
|
|
"strings"
|
2013-12-21 00:39:32 +00:00
|
|
|
"sync"
|
2015-06-05 23:17:07 +00:00
|
|
|
"time"
|
2014-06-16 21:36:12 +00:00
|
|
|
|
2017-08-08 08:31:38 +00:00
|
|
|
"github.com/armon/go-metrics"
|
2017-08-23 14:52:48 +00:00
|
|
|
"github.com/hashicorp/consul/acl"
|
2017-08-28 12:17:09 +00:00
|
|
|
"github.com/hashicorp/consul/agent/ae"
|
2017-09-25 18:40:42 +00:00
|
|
|
"github.com/hashicorp/consul/agent/config"
|
pkg refactor
command/agent/* -> agent/*
command/consul/* -> agent/consul/*
command/agent/command{,_test}.go -> command/agent{,_test}.go
command/base/command.go -> command/base.go
command/base/* -> command/*
commands.go -> command/commands.go
The script which did the refactor is:
(
cd $GOPATH/src/github.com/hashicorp/consul
git mv command/agent/command.go command/agent.go
git mv command/agent/command_test.go command/agent_test.go
git mv command/agent/flag_slice_value{,_test}.go command/
git mv command/agent .
git mv command/base/command.go command/base.go
git mv command/base/config_util{,_test}.go command/
git mv commands.go command/
git mv consul agent
rmdir command/base/
gsed -i -e 's|package agent|package command|' command/agent{,_test}.go
gsed -i -e 's|package agent|package command|' command/flag_slice_value{,_test}.go
gsed -i -e 's|package base|package command|' command/base.go command/config_util{,_test}.go
gsed -i -e 's|package main|package command|' command/commands.go
gsed -i -e 's|base.Command|BaseCommand|' command/commands.go
gsed -i -e 's|agent.Command|AgentCommand|' command/commands.go
gsed -i -e 's|\tCommand:|\tBaseCommand:|' command/commands.go
gsed -i -e 's|base\.||' command/commands.go
gsed -i -e 's|command\.||' command/commands.go
gsed -i -e 's|command|c|' main.go
gsed -i -e 's|range Commands|range command.Commands|' main.go
gsed -i -e 's|Commands: Commands|Commands: command.Commands|' main.go
gsed -i -e 's|base\.BoolValue|BoolValue|' command/operator_autopilot_set.go
gsed -i -e 's|base\.DurationValue|DurationValue|' command/operator_autopilot_set.go
gsed -i -e 's|base\.StringValue|StringValue|' command/operator_autopilot_set.go
gsed -i -e 's|base\.UintValue|UintValue|' command/operator_autopilot_set.go
gsed -i -e 's|\bCommand\b|BaseCommand|' command/base.go
gsed -i -e 's|BaseCommand Options|Command Options|' command/base.go
gsed -i -e 's|base.Command|BaseCommand|' command/*.go
gsed -i -e 's|c\.Command|c.BaseCommand|g' command/*.go
gsed -i -e 's|\tCommand:|\tBaseCommand:|' command/*_test.go
gsed -i -e 's|base\.||' command/*_test.go
gsed -i -e 's|\bCommand\b|AgentCommand|' command/agent{,_test}.go
gsed -i -e 's|cmd.AgentCommand|cmd.BaseCommand|' command/agent.go
gsed -i -e 's|cli.AgentCommand = new(Command)|cli.Command = new(AgentCommand)|' command/agent_test.go
gsed -i -e 's|exec.AgentCommand|exec.Command|' command/agent_test.go
gsed -i -e 's|exec.BaseCommand|exec.Command|' command/agent_test.go
gsed -i -e 's|NewTestAgent|agent.NewTestAgent|' command/agent_test.go
gsed -i -e 's|= TestConfig|= agent.TestConfig|' command/agent_test.go
gsed -i -e 's|: RetryJoin|: agent.RetryJoin|' command/agent_test.go
gsed -i -e 's|\.\./\.\./|../|' command/config_util_test.go
gsed -i -e 's|\bverifyUniqueListeners|VerifyUniqueListeners|' agent/config{,_test}.go command/agent.go
gsed -i -e 's|\bserfLANKeyring\b|SerfLANKeyring|g' agent/{agent,keyring,testagent}.go command/agent.go
gsed -i -e 's|\bserfWANKeyring\b|SerfWANKeyring|g' agent/{agent,keyring,testagent}.go command/agent.go
gsed -i -e 's|\bNewAgent\b|agent.New|g' command/agent{,_test}.go
gsed -i -e 's|\bNewAgent|New|' agent/{acl_test,agent,testagent}.go
gsed -i -e 's|\bAgent\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bBool\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bConfig\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bDefaultConfig\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bDevConfig\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bMergeConfig\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bReadConfigPaths\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bParseMetaPair\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bSerfLANKeyring\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bSerfWANKeyring\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|circonus\.agent|circonus|g' command/agent{,_test}.go
gsed -i -e 's|logger\.agent|logger|g' command/agent{,_test}.go
gsed -i -e 's|metrics\.agent|metrics|g' command/agent{,_test}.go
gsed -i -e 's|// agent.Agent|// agent|' command/agent{,_test}.go
gsed -i -e 's|a\.agent\.Config|a.Config|' command/agent{,_test}.go
gsed -i -e 's|agent\.AppendSliceValue|AppendSliceValue|' command/{configtest,validate}.go
gsed -i -e 's|consul/consul|agent/consul|' GNUmakefile
gsed -i -e 's|\.\./test|../../test|' agent/consul/server_test.go
# fix imports
f=$(grep -rl 'github.com/hashicorp/consul/command/agent' * | grep '\.go')
gsed -i -e 's|github.com/hashicorp/consul/command/agent|github.com/hashicorp/consul/agent|' $f
goimports -w $f
f=$(grep -rl 'github.com/hashicorp/consul/consul' * | grep '\.go')
gsed -i -e 's|github.com/hashicorp/consul/consul|github.com/hashicorp/consul/agent/consul|' $f
goimports -w $f
goimports -w command/*.go main.go
)
2017-06-09 22:28:28 +00:00
|
|
|
"github.com/hashicorp/consul/agent/consul"
|
2017-08-28 12:17:12 +00:00
|
|
|
"github.com/hashicorp/consul/agent/local"
|
2017-07-06 10:34:00 +00:00
|
|
|
"github.com/hashicorp/consul/agent/structs"
|
2017-06-21 04:43:55 +00:00
|
|
|
"github.com/hashicorp/consul/agent/systemd"
|
2017-07-26 18:03:43 +00:00
|
|
|
"github.com/hashicorp/consul/agent/token"
|
2017-04-19 23:00:11 +00:00
|
|
|
"github.com/hashicorp/consul/api"
|
2017-05-15 20:10:36 +00:00
|
|
|
"github.com/hashicorp/consul/ipaddr"
|
2016-01-29 19:42:34 +00:00
|
|
|
"github.com/hashicorp/consul/lib"
|
2016-11-16 21:45:26 +00:00
|
|
|
"github.com/hashicorp/consul/logger"
|
2016-06-06 20:19:31 +00:00
|
|
|
"github.com/hashicorp/consul/types"
|
2017-06-02 12:56:49 +00:00
|
|
|
"github.com/hashicorp/consul/watch"
|
2016-11-09 23:22:53 +00:00
|
|
|
"github.com/hashicorp/go-uuid"
|
2017-09-07 19:17:20 +00:00
|
|
|
"github.com/hashicorp/memberlist"
|
2017-02-24 04:32:13 +00:00
|
|
|
"github.com/hashicorp/raft"
|
2014-06-16 21:36:12 +00:00
|
|
|
"github.com/hashicorp/serf/serf"
|
2017-02-01 18:27:04 +00:00
|
|
|
"github.com/shirou/gopsutil/host"
|
2013-12-20 23:33:13 +00:00
|
|
|
)
|
|
|
|
|
2014-11-24 08:36:03 +00:00
|
|
|
const (
|
|
|
|
// Path to save agent service definitions
|
|
|
|
servicesDir = "services"
|
|
|
|
|
|
|
|
// Path to save local agent checks
|
2015-06-05 23:17:07 +00:00
|
|
|
checksDir = "checks"
|
|
|
|
checkStateDir = "checks/state"
|
2015-01-16 20:39:15 +00:00
|
|
|
|
2015-01-21 22:45:09 +00:00
|
|
|
// Default reasons for node/service maintenance mode
|
|
|
|
defaultNodeMaintReason = "Maintenance mode is enabled for this node, " +
|
|
|
|
"but no reason was provided. This is a default message."
|
|
|
|
defaultServiceMaintReason = "Maintenance mode is enabled for this " +
|
|
|
|
"service, but no reason was provided. This is a default message."
|
2014-11-24 08:36:03 +00:00
|
|
|
)
|
|
|
|
|
2017-06-15 09:42:07 +00:00
|
|
|
// delegate defines the interface shared by both
|
2017-05-15 14:05:17 +00:00
|
|
|
// consul.Client and consul.Server.
|
2017-06-15 09:42:07 +00:00
|
|
|
type delegate interface {
|
2017-05-15 14:05:17 +00:00
|
|
|
Encrypted() bool
|
2017-08-14 14:36:07 +00:00
|
|
|
GetLANCoordinate() (lib.CoordinateSet, error)
|
2017-05-15 14:05:17 +00:00
|
|
|
Leave() error
|
|
|
|
LANMembers() []serf.Member
|
2017-09-05 19:22:20 +00:00
|
|
|
LANMembersAllSegments() ([]serf.Member, error)
|
2017-08-30 23:44:04 +00:00
|
|
|
LANSegmentMembers(segment string) ([]serf.Member, error)
|
2017-05-15 14:05:17 +00:00
|
|
|
LocalMember() serf.Member
|
|
|
|
JoinLAN(addrs []string) (n int, err error)
|
|
|
|
RemoveFailedNode(node string) error
|
|
|
|
RPC(method string, args interface{}, reply interface{}) error
|
2017-06-15 09:50:28 +00:00
|
|
|
SnapshotRPC(args *structs.SnapshotRequest, in io.Reader, out io.Writer, replyFn structs.SnapshotReplyFn) error
|
2017-05-15 14:05:17 +00:00
|
|
|
Shutdown() error
|
|
|
|
Stats() map[string]map[string]string
|
|
|
|
}
|
2015-02-09 17:22:51 +00:00
|
|
|
|
2017-06-21 04:43:55 +00:00
|
|
|
// notifier is called after a successful JoinLAN.
|
|
|
|
type notifier interface {
|
|
|
|
Notify(string) error
|
|
|
|
}
|
|
|
|
|
2017-05-15 14:05:17 +00:00
|
|
|
// The agent is the long running process that is run on every machine.
|
|
|
|
// It exposes an RPC interface that is used by the CLI to control the
|
|
|
|
// agent. The agent runs the query interfaces like HTTP, DNS, and RPC.
|
|
|
|
// However, it can run in either a client, or server mode. In server
|
|
|
|
// mode, it runs a full Consul server. In client-only mode, it only forwards
|
|
|
|
// requests to other Consul servers.
|
2013-12-20 01:14:46 +00:00
|
|
|
type Agent struct {
|
2017-05-23 17:04:06 +00:00
|
|
|
// config is the agent configuration.
|
2017-09-25 18:40:42 +00:00
|
|
|
config *config.RuntimeConfig
|
2013-12-20 23:33:13 +00:00
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
// Used for writing our logs
|
|
|
|
logger *log.Logger
|
|
|
|
|
|
|
|
// Output sink for logs
|
2017-05-19 15:51:39 +00:00
|
|
|
LogOutput io.Writer
|
2013-12-21 00:39:32 +00:00
|
|
|
|
2016-11-16 21:45:26 +00:00
|
|
|
// Used for streaming logs to
|
2017-05-19 15:51:39 +00:00
|
|
|
LogWriter *logger.LogWriter
|
2016-11-16 21:45:26 +00:00
|
|
|
|
2017-08-08 08:31:38 +00:00
|
|
|
// In-memory sink used for collecting metrics
|
|
|
|
MemSink *metrics.InmemSink
|
|
|
|
|
2017-05-15 14:05:17 +00:00
|
|
|
// delegate is either a *consul.Server or *consul.Client
|
|
|
|
// depending on the configuration
|
2017-06-15 09:42:07 +00:00
|
|
|
delegate delegate
|
2013-12-21 00:39:32 +00:00
|
|
|
|
2016-12-14 07:21:14 +00:00
|
|
|
// acls is an object that helps manage local ACL enforcement.
|
|
|
|
acls *aclManager
|
|
|
|
|
2014-01-16 01:14:50 +00:00
|
|
|
// state stores a local representation of the node,
|
|
|
|
// services and checks. Used for anti-entropy.
|
2017-08-28 12:17:13 +00:00
|
|
|
State *local.State
|
2014-01-21 20:05:56 +00:00
|
|
|
|
2017-08-28 12:17:09 +00:00
|
|
|
// sync manages the synchronization of the local
|
|
|
|
// and the remote state.
|
|
|
|
sync *ae.StateSyncer
|
|
|
|
|
2016-08-16 07:05:55 +00:00
|
|
|
// checkReapAfter maps the check ID to a timeout after which we should
|
|
|
|
// reap its associated service
|
|
|
|
checkReapAfter map[types.CheckID]time.Duration
|
|
|
|
|
2014-01-21 20:05:56 +00:00
|
|
|
// checkMonitors maps the check ID to an associated monitor
|
2016-06-06 20:19:31 +00:00
|
|
|
checkMonitors map[types.CheckID]*CheckMonitor
|
2015-01-09 22:43:24 +00:00
|
|
|
|
|
|
|
// checkHTTPs maps the check ID to an associated HTTP check
|
2016-06-06 20:19:31 +00:00
|
|
|
checkHTTPs map[types.CheckID]*CheckHTTP
|
2015-01-09 22:43:24 +00:00
|
|
|
|
2015-07-23 11:45:08 +00:00
|
|
|
// checkTCPs maps the check ID to an associated TCP check
|
2016-06-06 20:19:31 +00:00
|
|
|
checkTCPs map[types.CheckID]*CheckTCP
|
2015-07-23 11:45:08 +00:00
|
|
|
|
2015-01-09 22:43:24 +00:00
|
|
|
// checkTTLs maps the check ID to an associated check TTL
|
2016-06-06 20:19:31 +00:00
|
|
|
checkTTLs map[types.CheckID]*CheckTTL
|
2015-01-09 22:43:24 +00:00
|
|
|
|
2015-10-22 22:29:13 +00:00
|
|
|
// checkDockers maps the check ID to an associated Docker Exec based check
|
2016-06-06 20:19:31 +00:00
|
|
|
checkDockers map[types.CheckID]*CheckDocker
|
2015-10-22 22:29:13 +00:00
|
|
|
|
2015-01-09 22:43:24 +00:00
|
|
|
// checkLock protects updates to the check* maps
|
|
|
|
checkLock sync.Mutex
|
2014-01-21 20:05:56 +00:00
|
|
|
|
2017-07-12 14:01:42 +00:00
|
|
|
// dockerClient is the client for performing docker health checks.
|
|
|
|
dockerClient *DockerClient
|
|
|
|
|
2014-08-27 23:49:12 +00:00
|
|
|
// eventCh is used to receive user events
|
|
|
|
eventCh chan serf.UserEvent
|
|
|
|
|
2014-08-28 00:01:10 +00:00
|
|
|
// eventBuf stores the most recent events in a ring buffer
|
|
|
|
// using eventIndex as the next index to insert into. This
|
|
|
|
// is guarded by eventLock. When an insert happens, the
|
|
|
|
// eventNotify group is notified.
|
2014-08-28 17:56:30 +00:00
|
|
|
eventBuf []*UserEvent
|
2014-08-28 00:01:10 +00:00
|
|
|
eventIndex int
|
|
|
|
eventLock sync.RWMutex
|
2017-06-15 16:45:30 +00:00
|
|
|
eventNotify NotifyGroup
|
2014-08-28 00:01:10 +00:00
|
|
|
|
2016-11-30 18:29:42 +00:00
|
|
|
reloadCh chan chan error
|
|
|
|
|
2014-01-21 20:05:56 +00:00
|
|
|
shutdown bool
|
|
|
|
shutdownCh chan struct{}
|
|
|
|
shutdownLock sync.Mutex
|
2015-11-12 17:19:33 +00:00
|
|
|
|
2017-06-21 04:43:55 +00:00
|
|
|
// joinLANNotifier is called after a successful JoinLAN.
|
|
|
|
joinLANNotifier notifier
|
|
|
|
|
2017-06-02 09:55:29 +00:00
|
|
|
// retryJoinCh transports errors from the retry join
|
|
|
|
// attempts.
|
|
|
|
retryJoinCh chan error
|
|
|
|
|
2017-06-16 07:54:09 +00:00
|
|
|
// endpoints maps unique RPC endpoint names to common ones
|
|
|
|
// to allow overriding of RPC handlers since the golang
|
|
|
|
// net/rpc server does not allow this.
|
2017-05-22 22:00:14 +00:00
|
|
|
endpoints map[string]string
|
|
|
|
endpointsLock sync.RWMutex
|
2017-05-19 09:53:41 +00:00
|
|
|
|
|
|
|
// dnsServer provides the DNS API
|
|
|
|
dnsServers []*DNSServer
|
|
|
|
|
|
|
|
// httpServers provides the HTTP API on various endpoints
|
|
|
|
httpServers []*HTTPServer
|
|
|
|
|
|
|
|
// wgServers is the wait group for all HTTP and DNS servers
|
|
|
|
wgServers sync.WaitGroup
|
2017-06-24 19:52:41 +00:00
|
|
|
|
|
|
|
// watchPlans tracks all the currently-running watch plans for the
|
|
|
|
// agent.
|
|
|
|
watchPlans []*watch.Plan
|
2017-07-26 18:03:43 +00:00
|
|
|
|
|
|
|
// tokens holds ACL tokens initially from the configuration, but can
|
|
|
|
// be updated at runtime, so should always be used instead of going to
|
|
|
|
// the configuration directly.
|
|
|
|
tokens *token.Store
|
2013-12-20 01:14:46 +00:00
|
|
|
}
|
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
func New(c *config.RuntimeConfig) (*Agent, error) {
|
2017-05-19 09:53:41 +00:00
|
|
|
if c.Datacenter == "" {
|
2013-12-24 00:20:51 +00:00
|
|
|
return nil, fmt.Errorf("Must configure a Datacenter")
|
|
|
|
}
|
2017-05-19 09:53:41 +00:00
|
|
|
if c.DataDir == "" && !c.DevMode {
|
2013-12-24 00:20:51 +00:00
|
|
|
return nil, fmt.Errorf("Must configure a DataDir")
|
|
|
|
}
|
2017-05-19 09:53:41 +00:00
|
|
|
acls, err := newACLManager(c)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2013-12-24 00:20:51 +00:00
|
|
|
|
2017-05-19 09:53:41 +00:00
|
|
|
a := &Agent{
|
2017-06-21 04:43:55 +00:00
|
|
|
config: c,
|
|
|
|
acls: acls,
|
|
|
|
checkReapAfter: make(map[types.CheckID]time.Duration),
|
|
|
|
checkMonitors: make(map[types.CheckID]*CheckMonitor),
|
|
|
|
checkTTLs: make(map[types.CheckID]*CheckTTL),
|
|
|
|
checkHTTPs: make(map[types.CheckID]*CheckHTTP),
|
|
|
|
checkTCPs: make(map[types.CheckID]*CheckTCP),
|
|
|
|
checkDockers: make(map[types.CheckID]*CheckDocker),
|
|
|
|
eventCh: make(chan serf.UserEvent, 1024),
|
|
|
|
eventBuf: make([]*UserEvent, 256),
|
|
|
|
joinLANNotifier: &systemd.Notifier{},
|
|
|
|
reloadCh: make(chan chan error),
|
|
|
|
retryJoinCh: make(chan error),
|
|
|
|
shutdownCh: make(chan struct{}),
|
|
|
|
endpoints: make(map[string]string),
|
2017-07-26 18:03:43 +00:00
|
|
|
tokens: new(token.Store),
|
2016-08-16 07:05:55 +00:00
|
|
|
}
|
2017-06-30 21:56:05 +00:00
|
|
|
|
2017-07-26 18:03:43 +00:00
|
|
|
// Set up the initial state of the token store based on the config.
|
|
|
|
a.tokens.UpdateUserToken(a.config.ACLToken)
|
|
|
|
a.tokens.UpdateAgentToken(a.config.ACLAgentToken)
|
|
|
|
a.tokens.UpdateAgentMasterToken(a.config.ACLAgentMasterToken)
|
2017-08-03 22:39:31 +00:00
|
|
|
a.tokens.UpdateACLReplicationToken(a.config.ACLReplicationToken)
|
2017-07-26 18:03:43 +00:00
|
|
|
|
2017-05-19 09:53:41 +00:00
|
|
|
return a, nil
|
|
|
|
}
|
2016-12-02 05:35:38 +00:00
|
|
|
|
2017-08-28 12:17:13 +00:00
|
|
|
func LocalConfig(cfg *config.RuntimeConfig) local.Config {
|
|
|
|
lc := local.Config{
|
|
|
|
AdvertiseAddr: cfg.AdvertiseAddrLAN.String(),
|
|
|
|
CheckUpdateInterval: cfg.CheckUpdateInterval,
|
|
|
|
Datacenter: cfg.Datacenter,
|
|
|
|
DiscardCheckOutput: cfg.DiscardCheckOutput,
|
|
|
|
NodeID: cfg.NodeID,
|
|
|
|
NodeName: cfg.NodeName,
|
|
|
|
TaggedAddresses: map[string]string{},
|
|
|
|
}
|
|
|
|
for k, v := range cfg.TaggedAddresses {
|
|
|
|
lc.TaggedAddresses[k] = v
|
|
|
|
}
|
|
|
|
return lc
|
|
|
|
}
|
|
|
|
|
2017-05-19 09:53:41 +00:00
|
|
|
func (a *Agent) Start() error {
|
|
|
|
c := a.config
|
|
|
|
|
2017-05-23 17:04:06 +00:00
|
|
|
logOutput := a.LogOutput
|
|
|
|
if a.logger == nil {
|
|
|
|
if logOutput == nil {
|
|
|
|
logOutput = os.Stderr
|
|
|
|
}
|
2017-05-30 23:05:21 +00:00
|
|
|
a.logger = log.New(logOutput, "", log.LstdFlags)
|
2017-05-19 15:51:39 +00:00
|
|
|
}
|
2016-12-14 07:21:14 +00:00
|
|
|
|
2017-01-18 06:20:11 +00:00
|
|
|
// Retrieve or generate the node ID before setting up the rest of the
|
|
|
|
// agent, which depends on it.
|
2017-05-19 09:53:41 +00:00
|
|
|
if err := a.setupNodeID(c); err != nil {
|
|
|
|
return fmt.Errorf("Failed to setup node ID: %v", err)
|
2017-01-18 06:20:11 +00:00
|
|
|
}
|
|
|
|
|
2017-08-28 12:17:09 +00:00
|
|
|
// create a notif channel to trigger state sychronizations
|
|
|
|
// when a consul server was added to the cluster.
|
2017-08-28 12:17:10 +00:00
|
|
|
serverUpCh := make(chan struct{}, 1)
|
2017-08-28 12:17:09 +00:00
|
|
|
|
|
|
|
// create a notif channel to trigger state synchronizations
|
|
|
|
// when the state has changed.
|
|
|
|
triggerCh := make(chan struct{}, 1)
|
|
|
|
|
2017-06-29 12:35:55 +00:00
|
|
|
// create the local state
|
2017-08-28 12:17:13 +00:00
|
|
|
a.State = local.NewState(LocalConfig(c), a.logger, a.tokens, triggerCh)
|
2017-08-28 12:17:09 +00:00
|
|
|
|
|
|
|
// create the state synchronization manager which performs
|
|
|
|
// regular and on-demand state synchronizations (anti-entropy).
|
|
|
|
a.sync = &ae.StateSyncer{
|
2017-08-28 12:17:13 +00:00
|
|
|
State: a.State,
|
2017-08-28 12:17:09 +00:00
|
|
|
Interval: c.AEInterval,
|
|
|
|
ShutdownCh: a.shutdownCh,
|
2017-08-28 12:17:10 +00:00
|
|
|
ServerUpCh: serverUpCh,
|
2017-08-28 12:17:09 +00:00
|
|
|
TriggerCh: triggerCh,
|
|
|
|
Logger: a.logger,
|
|
|
|
}
|
2017-06-29 12:35:55 +00:00
|
|
|
|
|
|
|
// create the config for the rpc server/client
|
|
|
|
consulCfg, err := a.consulConfig()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-08-28 12:17:09 +00:00
|
|
|
// ServerUp is used to inform that a new consul server is now
|
|
|
|
// up. This can be used to speed up the sync process if we are blocking
|
|
|
|
// waiting to discover a consul server
|
|
|
|
// todo(fs): IMO, the non-blocking nature of this call should be hidden in the syncer
|
|
|
|
consulCfg.ServerUp = func() {
|
|
|
|
select {
|
2017-08-28 12:17:10 +00:00
|
|
|
case serverUpCh <- struct{}{}:
|
2017-08-28 12:17:09 +00:00
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
2017-06-29 12:35:55 +00:00
|
|
|
|
2016-08-16 07:05:55 +00:00
|
|
|
// Setup either the client or the server.
|
2017-09-25 18:40:42 +00:00
|
|
|
if c.ServerMode {
|
2017-08-03 22:39:31 +00:00
|
|
|
server, err := consul.NewServerLogger(consulCfg, a.logger, a.tokens)
|
2017-05-19 09:53:41 +00:00
|
|
|
if err != nil {
|
2017-06-29 12:35:55 +00:00
|
|
|
return fmt.Errorf("Failed to start Consul server: %v", err)
|
2017-05-19 09:53:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
a.delegate = server
|
2017-08-28 12:17:13 +00:00
|
|
|
a.State.SetDelegate(server)
|
2017-08-28 12:17:09 +00:00
|
|
|
a.sync.ClusterSize = func() int { return len(server.LANMembers()) }
|
2013-12-20 23:33:13 +00:00
|
|
|
} else {
|
2017-06-29 12:35:55 +00:00
|
|
|
client, err := consul.NewClientLogger(consulCfg, a.logger)
|
2017-05-19 09:53:41 +00:00
|
|
|
if err != nil {
|
2017-06-29 12:35:55 +00:00
|
|
|
return fmt.Errorf("Failed to start Consul client: %v", err)
|
2017-05-19 09:53:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
a.delegate = client
|
2017-08-28 12:17:13 +00:00
|
|
|
a.State.SetDelegate(client)
|
2017-08-28 12:17:09 +00:00
|
|
|
a.sync.ClusterSize = func() int { return len(client.LANMembers()) }
|
2013-12-20 23:33:13 +00:00
|
|
|
}
|
|
|
|
|
2017-01-05 22:10:26 +00:00
|
|
|
// Load checks/services/metadata.
|
2017-05-19 09:53:41 +00:00
|
|
|
if err := a.loadServices(c); err != nil {
|
|
|
|
return err
|
2014-11-24 08:36:03 +00:00
|
|
|
}
|
2017-05-19 09:53:41 +00:00
|
|
|
if err := a.loadChecks(c); err != nil {
|
|
|
|
return err
|
2014-11-24 08:36:03 +00:00
|
|
|
}
|
2017-05-19 09:53:41 +00:00
|
|
|
if err := a.loadMetadata(c); err != nil {
|
|
|
|
return err
|
2017-01-05 22:10:26 +00:00
|
|
|
}
|
2014-11-24 08:36:03 +00:00
|
|
|
|
2016-08-16 07:05:55 +00:00
|
|
|
// Start watching for critical services to deregister, based on their
|
|
|
|
// checks.
|
2017-05-19 09:53:41 +00:00
|
|
|
go a.reapServices()
|
2016-08-16 07:05:55 +00:00
|
|
|
|
|
|
|
// Start handling events.
|
2017-05-19 09:53:41 +00:00
|
|
|
go a.handleEvents()
|
2014-08-27 23:49:12 +00:00
|
|
|
|
2015-06-06 03:31:33 +00:00
|
|
|
// Start sending network coordinate to the server.
|
2017-05-19 09:53:41 +00:00
|
|
|
if !c.DisableCoordinates {
|
|
|
|
go a.sendCoordinate()
|
2015-06-06 03:31:33 +00:00
|
|
|
}
|
|
|
|
|
2016-08-16 07:05:55 +00:00
|
|
|
// Write out the PID file if necessary.
|
2017-05-19 09:53:41 +00:00
|
|
|
if err := a.storePid(); err != nil {
|
|
|
|
return err
|
2014-05-06 16:57:53 +00:00
|
|
|
}
|
2014-05-06 03:29:50 +00:00
|
|
|
|
2017-05-24 13:22:56 +00:00
|
|
|
// start DNS servers
|
|
|
|
if err := a.listenAndServeDNS(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// create listeners and unstarted servers
|
|
|
|
// see comment on listenHTTP why we are doing this
|
2017-09-25 18:40:42 +00:00
|
|
|
httpln, err := a.listenHTTP()
|
2017-05-24 13:22:56 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
// start HTTP and HTTPS servers
|
2017-05-24 13:22:56 +00:00
|
|
|
for _, l := range httpln {
|
2017-09-25 18:40:42 +00:00
|
|
|
srv := NewHTTPServer(l.Addr(), a)
|
2017-05-24 13:22:56 +00:00
|
|
|
if err := a.serveHTTP(l, srv); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
a.httpServers = append(a.httpServers, srv)
|
|
|
|
}
|
2017-06-02 09:55:29 +00:00
|
|
|
|
2017-06-09 08:03:49 +00:00
|
|
|
// register watches
|
2017-06-24 19:52:41 +00:00
|
|
|
if err := a.reloadWatches(a.config); err != nil {
|
2017-06-09 08:03:49 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-06-02 09:55:29 +00:00
|
|
|
// start retry join
|
2017-08-19 08:44:19 +00:00
|
|
|
go a.retryJoinLAN()
|
|
|
|
go a.retryJoinWAN()
|
2017-06-02 09:55:29 +00:00
|
|
|
|
2017-05-24 13:22:56 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *Agent) listenAndServeDNS() error {
|
2017-09-25 18:40:42 +00:00
|
|
|
notif := make(chan net.Addr, len(a.config.DNSAddrs))
|
|
|
|
for _, addr := range a.config.DNSAddrs {
|
2017-05-24 13:22:56 +00:00
|
|
|
// create server
|
|
|
|
s, err := NewDNSServer(a)
|
2017-05-19 09:53:41 +00:00
|
|
|
if err != nil {
|
2017-05-24 13:22:56 +00:00
|
|
|
return err
|
2017-05-19 09:53:41 +00:00
|
|
|
}
|
2017-05-24 13:22:56 +00:00
|
|
|
a.dnsServers = append(a.dnsServers, s)
|
|
|
|
|
|
|
|
// start server
|
|
|
|
a.wgServers.Add(1)
|
2017-09-25 18:40:42 +00:00
|
|
|
go func(addr net.Addr) {
|
2017-05-24 13:22:56 +00:00
|
|
|
defer a.wgServers.Done()
|
2017-09-25 18:40:42 +00:00
|
|
|
err := s.ListenAndServe(addr.Network(), addr.String(), func() { notif <- addr })
|
2017-05-24 13:22:56 +00:00
|
|
|
if err != nil && !strings.Contains(err.Error(), "accept") {
|
2017-09-25 18:40:42 +00:00
|
|
|
a.logger.Printf("[ERR] agent: Error starting DNS server %s (%s): %v", addr.String(), addr.Network(), err)
|
2017-05-24 13:22:56 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
}(addr)
|
2017-05-19 09:53:41 +00:00
|
|
|
}
|
|
|
|
|
2017-05-24 13:22:56 +00:00
|
|
|
// wait for servers to be up
|
|
|
|
timeout := time.After(time.Second)
|
2017-09-25 18:40:42 +00:00
|
|
|
for range a.config.DNSAddrs {
|
2017-05-24 13:22:56 +00:00
|
|
|
select {
|
2017-09-25 18:40:42 +00:00
|
|
|
case addr := <-notif:
|
|
|
|
a.logger.Printf("[INFO] agent: Started DNS server %s (%s)", addr.String(), addr.Network())
|
2017-05-24 13:22:56 +00:00
|
|
|
continue
|
|
|
|
case <-timeout:
|
|
|
|
return fmt.Errorf("agent: timeout starting DNS servers")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
2017-05-19 09:53:41 +00:00
|
|
|
}
|
|
|
|
|
2017-05-24 13:22:56 +00:00
|
|
|
// listenHTTP binds listeners to the provided addresses and also returns
|
|
|
|
// pre-configured HTTP servers which are not yet started. The motivation is
|
|
|
|
// that in the current startup/shutdown setup we de-couple the listener
|
|
|
|
// creation from the server startup assuming that if any of the listeners
|
|
|
|
// cannot be bound we fail immediately and later failures do not occur.
|
|
|
|
// Therefore, starting a server with a running listener is assumed to not
|
|
|
|
// produce an error.
|
|
|
|
//
|
|
|
|
// The second motivation is that an HTTPS server needs to use the same TLSConfig
|
|
|
|
// on both the listener and the HTTP server. When listeners and servers are
|
|
|
|
// created at different times this becomes difficult to handle without keeping
|
|
|
|
// the TLS configuration somewhere or recreating it.
|
|
|
|
//
|
|
|
|
// This approach should ultimately be refactored to the point where we just
|
|
|
|
// start the server and any error should trigger a proper shutdown of the agent.
|
2017-09-25 18:40:42 +00:00
|
|
|
func (a *Agent) listenHTTP() ([]net.Listener, error) {
|
2017-05-19 09:53:41 +00:00
|
|
|
var ln []net.Listener
|
2017-05-24 13:22:56 +00:00
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
start := func(proto string, addrs []net.Addr) error {
|
|
|
|
for _, addr := range addrs {
|
|
|
|
var l net.Listener
|
|
|
|
var err error
|
2017-05-24 13:22:56 +00:00
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
switch x := addr.(type) {
|
|
|
|
case *net.UnixAddr:
|
|
|
|
l, err = a.listenSocket(x.Name)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-05-24 13:22:56 +00:00
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
case *net.TCPAddr:
|
|
|
|
l, err = net.Listen("tcp", x.String())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-05-30 23:05:21 +00:00
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
l = &tcpKeepAliveListener{l.(*net.TCPListener)}
|
2017-05-19 09:53:41 +00:00
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
if proto == "https" {
|
|
|
|
tlscfg, err := a.config.IncomingHTTPSConfig()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
l = tls.NewListener(l, tlscfg)
|
|
|
|
}
|
|
|
|
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("unsupported address type %T", addr)
|
2017-05-19 09:53:41 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
ln = append(ln, l)
|
2017-05-19 09:53:41 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
return nil
|
|
|
|
}
|
2017-05-24 13:22:56 +00:00
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
if err := start("http", a.config.HTTPAddrs); err != nil {
|
|
|
|
for _, l := range ln {
|
|
|
|
l.Close()
|
2017-05-31 08:24:32 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if err := start("https", a.config.HTTPSAddrs); err != nil {
|
|
|
|
for _, l := range ln {
|
|
|
|
l.Close()
|
|
|
|
}
|
|
|
|
return nil, err
|
2017-05-19 09:53:41 +00:00
|
|
|
}
|
2017-05-24 13:22:56 +00:00
|
|
|
return ln, nil
|
|
|
|
}
|
2017-05-19 09:53:41 +00:00
|
|
|
|
2017-05-30 23:05:21 +00:00
|
|
|
// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
|
|
|
|
// connections. It's used by NewHttpServer so dead TCP connections
|
|
|
|
// eventually go away.
|
|
|
|
type tcpKeepAliveListener struct {
|
|
|
|
*net.TCPListener
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
|
|
|
|
tc, err := ln.AcceptTCP()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
tc.SetKeepAlive(true)
|
|
|
|
tc.SetKeepAlivePeriod(30 * time.Second)
|
|
|
|
return tc, nil
|
|
|
|
}
|
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
func (a *Agent) listenSocket(path string) (net.Listener, error) {
|
2017-05-24 13:22:56 +00:00
|
|
|
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
|
|
|
a.logger.Printf("[WARN] agent: Replacing socket %q", path)
|
|
|
|
}
|
|
|
|
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
|
|
|
|
return nil, fmt.Errorf("error removing socket file: %s", err)
|
|
|
|
}
|
|
|
|
l, err := net.Listen("unix", path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
user, group, mode := a.config.UnixSocketUser, a.config.UnixSocketGroup, a.config.UnixSocketMode
|
|
|
|
if err := setFilePermissions(path, user, group, mode); err != nil {
|
|
|
|
return nil, fmt.Errorf("Failed setting up socket: %s", err)
|
2017-05-24 13:22:56 +00:00
|
|
|
}
|
|
|
|
return l, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *Agent) serveHTTP(l net.Listener, srv *HTTPServer) error {
|
2017-05-19 09:53:41 +00:00
|
|
|
// https://github.com/golang/go/issues/20239
|
|
|
|
//
|
2017-05-24 13:22:56 +00:00
|
|
|
// In go.8.1 there is a race between Serve and Shutdown. If
|
2017-05-19 09:53:41 +00:00
|
|
|
// Shutdown is called before the Serve go routine was scheduled then
|
|
|
|
// the Serve go routine never returns. This deadlocks the agent
|
|
|
|
// shutdown for some tests since it will wait forever.
|
2017-05-30 23:05:21 +00:00
|
|
|
//
|
|
|
|
// Since we need to check for an unexported type (*tls.listener)
|
|
|
|
// we cannot just perform a type check since the compiler won't let
|
|
|
|
// us. We might be able to use reflection but the fmt.Sprintf() hack
|
|
|
|
// works just as well.
|
2017-05-31 07:41:16 +00:00
|
|
|
srv.proto = "http"
|
2017-05-24 13:22:56 +00:00
|
|
|
if strings.Contains("*tls.listener", fmt.Sprintf("%T", l)) {
|
|
|
|
srv.proto = "https"
|
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
notif := make(chan net.Addr)
|
2017-05-24 13:22:56 +00:00
|
|
|
a.wgServers.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer a.wgServers.Done()
|
2017-09-25 18:40:42 +00:00
|
|
|
notif <- l.Addr()
|
2017-05-24 13:22:56 +00:00
|
|
|
err := srv.Serve(l)
|
|
|
|
if err != nil && err != http.ErrServerClosed {
|
|
|
|
a.logger.Print(err)
|
|
|
|
}
|
|
|
|
}()
|
2017-05-19 09:53:41 +00:00
|
|
|
|
2017-05-24 13:22:56 +00:00
|
|
|
select {
|
|
|
|
case addr := <-notif:
|
|
|
|
if srv.proto == "https" {
|
2017-09-25 18:40:42 +00:00
|
|
|
a.logger.Printf("[INFO] agent: Started HTTPS server on %s (%s)", addr.String(), addr.Network())
|
2017-05-24 13:22:56 +00:00
|
|
|
} else {
|
2017-09-25 18:40:42 +00:00
|
|
|
a.logger.Printf("[INFO] agent: Started HTTP server on %s (%s)", addr.String(), addr.Network())
|
2017-05-24 13:22:56 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
case <-time.After(time.Second):
|
|
|
|
return fmt.Errorf("agent: timeout starting HTTP servers")
|
2017-05-19 09:53:41 +00:00
|
|
|
}
|
2013-12-20 01:14:46 +00:00
|
|
|
}
|
|
|
|
|
2017-06-24 19:52:41 +00:00
|
|
|
// reloadWatches stops any existing watch plans and attempts to load the given
|
|
|
|
// set of watches.
|
2017-09-25 18:40:42 +00:00
|
|
|
func (a *Agent) reloadWatches(cfg *config.RuntimeConfig) error {
|
2017-09-26 20:47:27 +00:00
|
|
|
// Stop the current watches.
|
|
|
|
for _, wp := range a.watchPlans {
|
|
|
|
wp.Stop()
|
|
|
|
}
|
|
|
|
a.watchPlans = nil
|
|
|
|
|
|
|
|
// Return if there are no watches now.
|
|
|
|
if len(cfg.Watches) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-06-24 19:52:41 +00:00
|
|
|
// Watches use the API to talk to this agent, so that must be enabled.
|
2017-09-26 20:47:27 +00:00
|
|
|
if len(cfg.HTTPAddrs) == 0 && len(cfg.HTTPSAddrs) == 0 {
|
2017-06-09 08:03:49 +00:00
|
|
|
return fmt.Errorf("watch plans require an HTTP or HTTPS endpoint")
|
|
|
|
}
|
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
// Compile the watches
|
|
|
|
var watchPlans []*watch.Plan
|
|
|
|
for _, params := range cfg.Watches {
|
2017-10-22 01:39:09 +00:00
|
|
|
if handlerType, ok := params["handler_type"]; !ok {
|
|
|
|
params["handler_type"] = "script"
|
|
|
|
} else if handlerType != "http" && handlerType != "script" {
|
|
|
|
return fmt.Errorf("Handler type '%s' not recognized", params["handler_type"])
|
|
|
|
}
|
|
|
|
|
|
|
|
// Parse the watches, excluding 'handler' and 'args'
|
2017-10-04 23:48:00 +00:00
|
|
|
wp, err := watch.ParseExempt(params, []string{"handler", "args"})
|
2017-09-25 18:40:42 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Failed to parse watch (%#v): %v", params, err)
|
|
|
|
}
|
|
|
|
|
2017-10-04 23:48:00 +00:00
|
|
|
// Get the handler and subprocess arguments
|
|
|
|
handler, hasHandler := wp.Exempt["handler"]
|
|
|
|
args, hasArgs := wp.Exempt["args"]
|
|
|
|
if hasHandler {
|
|
|
|
a.logger.Printf("[WARN] agent: The 'handler' field in watches has been deprecated " +
|
|
|
|
"and replaced with the 'args' field. See https://www.consul.io/docs/agent/watches.html")
|
|
|
|
}
|
|
|
|
if _, ok := handler.(string); hasHandler && !ok {
|
2017-09-25 18:40:42 +00:00
|
|
|
return fmt.Errorf("Watch handler must be a string")
|
|
|
|
}
|
2017-10-04 23:48:00 +00:00
|
|
|
if raw, ok := args.([]interface{}); hasArgs && ok {
|
|
|
|
var parsed []string
|
|
|
|
for _, arg := range raw {
|
|
|
|
if v, ok := arg.(string); !ok {
|
|
|
|
return fmt.Errorf("Watch args must be a list of strings")
|
|
|
|
} else {
|
|
|
|
parsed = append(parsed, v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
wp.Exempt["args"] = parsed
|
|
|
|
} else if hasArgs && !ok {
|
|
|
|
return fmt.Errorf("Watch args must be a list of strings")
|
|
|
|
}
|
2017-10-22 01:39:09 +00:00
|
|
|
if hasHandler && hasArgs || hasHandler && wp.HandlerType == "http" || hasArgs && wp.HandlerType == "http" {
|
|
|
|
return fmt.Errorf("Only one watch handler allowed")
|
2017-10-04 23:48:00 +00:00
|
|
|
}
|
2017-10-22 01:39:09 +00:00
|
|
|
if !hasHandler && !hasArgs && wp.HandlerType != "http" {
|
|
|
|
return fmt.Errorf("Must define a watch handler")
|
2017-10-04 23:48:00 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
|
|
|
|
// Store the watch plan
|
|
|
|
watchPlans = append(watchPlans, wp)
|
|
|
|
}
|
|
|
|
|
2017-09-26 20:47:27 +00:00
|
|
|
// Determine the primary http(s) endpoint.
|
|
|
|
var netaddr net.Addr
|
|
|
|
if len(cfg.HTTPAddrs) > 0 {
|
|
|
|
netaddr = cfg.HTTPAddrs[0]
|
|
|
|
} else {
|
|
|
|
netaddr = cfg.HTTPSAddrs[0]
|
2017-06-24 19:52:41 +00:00
|
|
|
}
|
2017-09-26 20:47:27 +00:00
|
|
|
addr := netaddr.String()
|
|
|
|
if netaddr.Network() == "unix" {
|
2017-09-25 18:40:42 +00:00
|
|
|
addr = "unix://" + addr
|
|
|
|
}
|
|
|
|
|
2017-06-24 19:52:41 +00:00
|
|
|
// Fire off a goroutine for each new watch plan.
|
2017-09-25 18:40:42 +00:00
|
|
|
for _, wp := range watchPlans {
|
2017-06-24 19:52:41 +00:00
|
|
|
a.watchPlans = append(a.watchPlans, wp)
|
2017-06-09 08:03:49 +00:00
|
|
|
go func(wp *watch.Plan) {
|
2017-10-04 23:48:00 +00:00
|
|
|
if h, ok := wp.Exempt["handler"]; ok {
|
2017-10-22 01:39:09 +00:00
|
|
|
wp.Handler = makeWatchHandler(a.LogOutput, h)
|
|
|
|
} else if h, ok := wp.Exempt["args"]; ok {
|
|
|
|
wp.Handler = makeWatchHandler(a.LogOutput, h)
|
2017-10-04 23:48:00 +00:00
|
|
|
} else {
|
2017-10-22 01:39:09 +00:00
|
|
|
httpConfig := wp.Exempt["http_handler_config"].(*watch.HttpHandlerConfig)
|
|
|
|
wp.Handler = makeHTTPWatchHandler(a.LogOutput, httpConfig)
|
2017-10-04 23:48:00 +00:00
|
|
|
}
|
2017-06-09 08:03:49 +00:00
|
|
|
wp.LogOutput = a.LogOutput
|
|
|
|
if err := wp.Run(addr); err != nil {
|
2017-06-24 19:52:41 +00:00
|
|
|
a.logger.Printf("[ERR] Failed to run watch: %v", err)
|
2017-06-09 08:03:49 +00:00
|
|
|
}
|
|
|
|
}(wp)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-12-20 23:33:13 +00:00
|
|
|
// consulConfig is used to return a consul configuration
|
2017-05-03 21:47:25 +00:00
|
|
|
func (a *Agent) consulConfig() (*consul.Config, error) {
|
2013-12-20 23:33:13 +00:00
|
|
|
// Start with the provided config or default config
|
2017-05-03 19:12:30 +00:00
|
|
|
base := consul.DefaultConfig()
|
2017-06-30 09:09:52 +00:00
|
|
|
|
2017-01-18 06:20:11 +00:00
|
|
|
// This is set when the agent starts up
|
|
|
|
base.NodeID = a.config.NodeID
|
|
|
|
|
2015-11-29 04:40:05 +00:00
|
|
|
// Apply dev mode
|
|
|
|
base.DevMode = a.config.DevMode
|
|
|
|
|
2013-12-20 23:33:13 +00:00
|
|
|
// Override with our config
|
2017-09-25 18:40:42 +00:00
|
|
|
// todo(fs): these are now always set in the runtime config so we can simplify this
|
|
|
|
// todo(fs): or is there a reason to keep it like that?
|
|
|
|
base.Datacenter = a.config.Datacenter
|
|
|
|
base.DataDir = a.config.DataDir
|
|
|
|
base.NodeName = a.config.NodeName
|
|
|
|
|
|
|
|
base.CoordinateUpdateBatchSize = a.config.ConsulCoordinateUpdateBatchSize
|
|
|
|
base.CoordinateUpdateMaxBatches = a.config.ConsulCoordinateUpdateMaxBatches
|
|
|
|
base.CoordinateUpdatePeriod = a.config.ConsulCoordinateUpdatePeriod
|
|
|
|
|
|
|
|
base.RaftConfig.HeartbeatTimeout = a.config.ConsulRaftHeartbeatTimeout
|
|
|
|
base.RaftConfig.LeaderLeaseTimeout = a.config.ConsulRaftLeaderLeaseTimeout
|
|
|
|
base.RaftConfig.ElectionTimeout = a.config.ConsulRaftElectionTimeout
|
|
|
|
|
|
|
|
base.SerfLANConfig.MemberlistConfig.BindAddr = a.config.SerfBindAddrLAN.IP.String()
|
2017-09-29 14:12:04 +00:00
|
|
|
base.SerfLANConfig.MemberlistConfig.BindPort = a.config.SerfBindAddrLAN.Port
|
2017-09-25 18:40:42 +00:00
|
|
|
base.SerfLANConfig.MemberlistConfig.AdvertiseAddr = a.config.SerfAdvertiseAddrLAN.IP.String()
|
2017-09-29 14:12:04 +00:00
|
|
|
base.SerfLANConfig.MemberlistConfig.AdvertisePort = a.config.SerfAdvertiseAddrLAN.Port
|
2017-09-25 18:40:42 +00:00
|
|
|
base.SerfLANConfig.MemberlistConfig.GossipVerifyIncoming = a.config.EncryptVerifyIncoming
|
|
|
|
base.SerfLANConfig.MemberlistConfig.GossipVerifyOutgoing = a.config.EncryptVerifyOutgoing
|
|
|
|
base.SerfLANConfig.MemberlistConfig.GossipInterval = a.config.ConsulSerfLANGossipInterval
|
|
|
|
base.SerfLANConfig.MemberlistConfig.ProbeInterval = a.config.ConsulSerfLANProbeInterval
|
|
|
|
base.SerfLANConfig.MemberlistConfig.ProbeTimeout = a.config.ConsulSerfLANProbeTimeout
|
|
|
|
base.SerfLANConfig.MemberlistConfig.SuspicionMult = a.config.ConsulSerfLANSuspicionMult
|
|
|
|
|
|
|
|
base.SerfWANConfig.MemberlistConfig.BindAddr = a.config.SerfBindAddrWAN.IP.String()
|
2017-09-29 14:12:04 +00:00
|
|
|
base.SerfWANConfig.MemberlistConfig.BindPort = a.config.SerfBindAddrWAN.Port
|
2017-09-25 18:40:42 +00:00
|
|
|
base.SerfWANConfig.MemberlistConfig.AdvertiseAddr = a.config.SerfAdvertiseAddrWAN.IP.String()
|
2017-09-29 14:12:04 +00:00
|
|
|
base.SerfWANConfig.MemberlistConfig.AdvertisePort = a.config.SerfAdvertiseAddrWAN.Port
|
2017-09-25 18:40:42 +00:00
|
|
|
base.SerfWANConfig.MemberlistConfig.GossipVerifyIncoming = a.config.EncryptVerifyIncoming
|
|
|
|
base.SerfWANConfig.MemberlistConfig.GossipVerifyOutgoing = a.config.EncryptVerifyOutgoing
|
|
|
|
base.SerfWANConfig.MemberlistConfig.GossipInterval = a.config.ConsulSerfWANGossipInterval
|
|
|
|
base.SerfWANConfig.MemberlistConfig.ProbeInterval = a.config.ConsulSerfWANProbeInterval
|
|
|
|
base.SerfWANConfig.MemberlistConfig.ProbeTimeout = a.config.ConsulSerfWANProbeTimeout
|
|
|
|
base.SerfWANConfig.MemberlistConfig.SuspicionMult = a.config.ConsulSerfWANSuspicionMult
|
|
|
|
|
|
|
|
base.RPCAddr = a.config.RPCBindAddr
|
|
|
|
base.RPCAdvertise = a.config.RPCAdvertiseAddr
|
|
|
|
|
|
|
|
if a.config.ReconnectTimeoutLAN != 0 {
|
|
|
|
base.SerfLANConfig.ReconnectTimeout = a.config.ReconnectTimeoutLAN
|
|
|
|
}
|
|
|
|
if a.config.ReconnectTimeoutWAN != 0 {
|
|
|
|
base.SerfWANConfig.ReconnectTimeout = a.config.ReconnectTimeoutWAN
|
|
|
|
}
|
|
|
|
|
|
|
|
base.Segment = a.config.SegmentName
|
2017-08-29 00:58:22 +00:00
|
|
|
if len(a.config.Segments) > 0 {
|
|
|
|
segments, err := a.segmentConfig()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2017-08-14 14:36:07 +00:00
|
|
|
}
|
2017-08-29 00:58:22 +00:00
|
|
|
base.Segments = segments
|
2017-08-14 14:36:07 +00:00
|
|
|
}
|
2013-12-25 00:48:07 +00:00
|
|
|
if a.config.Bootstrap {
|
|
|
|
base.Bootstrap = true
|
|
|
|
}
|
2014-06-18 17:32:19 +00:00
|
|
|
if a.config.RejoinAfterLeave {
|
|
|
|
base.RejoinAfterLeave = true
|
|
|
|
}
|
2014-06-20 00:08:48 +00:00
|
|
|
if a.config.BootstrapExpect != 0 {
|
|
|
|
base.BootstrapExpect = a.config.BootstrapExpect
|
2014-06-16 21:36:12 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.RPCProtocol > 0 {
|
|
|
|
base.ProtocolVersion = uint8(a.config.RPCProtocol)
|
2014-03-09 22:57:03 +00:00
|
|
|
}
|
2017-02-24 04:32:13 +00:00
|
|
|
if a.config.RaftProtocol != 0 {
|
|
|
|
base.RaftConfig.ProtocolVersion = raft.ProtocolVersion(a.config.RaftProtocol)
|
|
|
|
}
|
2014-08-05 22:36:08 +00:00
|
|
|
if a.config.ACLMasterToken != "" {
|
|
|
|
base.ACLMasterToken = a.config.ACLMasterToken
|
|
|
|
}
|
2014-08-05 22:20:35 +00:00
|
|
|
if a.config.ACLDatacenter != "" {
|
|
|
|
base.ACLDatacenter = a.config.ACLDatacenter
|
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.ACLTTL != 0 {
|
2014-08-05 22:20:35 +00:00
|
|
|
base.ACLTTL = a.config.ACLTTL
|
|
|
|
}
|
|
|
|
if a.config.ACLDefaultPolicy != "" {
|
|
|
|
base.ACLDefaultPolicy = a.config.ACLDefaultPolicy
|
|
|
|
}
|
|
|
|
if a.config.ACLDownPolicy != "" {
|
|
|
|
base.ACLDownPolicy = a.config.ACLDownPolicy
|
|
|
|
}
|
2017-08-03 22:39:31 +00:00
|
|
|
base.EnableACLReplication = a.config.EnableACLReplication
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.ACLEnforceVersion8 {
|
|
|
|
base.ACLEnforceVersion8 = a.config.ACLEnforceVersion8
|
2016-12-08 01:58:23 +00:00
|
|
|
}
|
2017-10-02 22:10:21 +00:00
|
|
|
if a.config.ACLEnableKeyListPolicy {
|
|
|
|
base.ACLEnableKeyListPolicy = a.config.ACLEnableKeyListPolicy
|
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.SessionTTLMin != 0 {
|
2015-03-27 05:30:04 +00:00
|
|
|
base.SessionTTLMin = a.config.SessionTTLMin
|
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.AutopilotCleanupDeadServers {
|
|
|
|
base.AutopilotConfig.CleanupDeadServers = a.config.AutopilotCleanupDeadServers
|
2017-02-22 20:53:32 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.AutopilotLastContactThreshold != 0 {
|
|
|
|
base.AutopilotConfig.LastContactThreshold = a.config.AutopilotLastContactThreshold
|
2017-03-01 22:04:40 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.AutopilotMaxTrailingLogs != 0 {
|
|
|
|
base.AutopilotConfig.MaxTrailingLogs = uint64(a.config.AutopilotMaxTrailingLogs)
|
2017-03-01 22:04:40 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.AutopilotServerStabilizationTime != 0 {
|
|
|
|
base.AutopilotConfig.ServerStabilizationTime = a.config.AutopilotServerStabilizationTime
|
2017-03-01 22:04:40 +00:00
|
|
|
}
|
2017-03-21 23:36:44 +00:00
|
|
|
if a.config.NonVotingServer {
|
|
|
|
base.NonVoter = a.config.NonVotingServer
|
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.AutopilotRedundancyZoneTag != "" {
|
|
|
|
base.AutopilotConfig.RedundancyZoneTag = a.config.AutopilotRedundancyZoneTag
|
2017-03-21 23:36:44 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.AutopilotDisableUpgradeMigration {
|
|
|
|
base.AutopilotConfig.DisableUpgradeMigration = a.config.AutopilotDisableUpgradeMigration
|
2017-03-21 23:36:44 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.AutopilotUpgradeVersionTag != "" {
|
|
|
|
base.AutopilotConfig.UpgradeVersionTag = a.config.AutopilotUpgradeVersionTag
|
2017-07-18 02:05:24 +00:00
|
|
|
}
|
2013-12-20 23:33:13 +00:00
|
|
|
|
2017-05-03 20:59:06 +00:00
|
|
|
// make sure the advertise address is always set
|
|
|
|
if base.RPCAdvertise == nil {
|
|
|
|
base.RPCAdvertise = base.RPCAddr
|
|
|
|
}
|
|
|
|
|
2017-09-01 22:02:50 +00:00
|
|
|
// Rate limiting for RPC calls.
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.RPCRateLimit > 0 {
|
|
|
|
base.RPCRate = a.config.RPCRateLimit
|
2017-09-01 22:02:50 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.RPCMaxBurst > 0 {
|
|
|
|
base.RPCMaxBurst = a.config.RPCMaxBurst
|
2017-09-01 22:02:50 +00:00
|
|
|
}
|
|
|
|
|
2017-10-10 22:19:50 +00:00
|
|
|
// RPC-related performance configs.
|
|
|
|
if a.config.RPCHoldTimeout > 0 {
|
|
|
|
base.RPCHoldTimeout = a.config.RPCHoldTimeout
|
|
|
|
}
|
|
|
|
if a.config.LeaveDrainTime > 0 {
|
|
|
|
base.LeaveDrainTime = a.config.LeaveDrainTime
|
|
|
|
}
|
|
|
|
|
2017-05-03 10:57:11 +00:00
|
|
|
// set the src address for outgoing rpc connections
|
2017-05-10 07:30:19 +00:00
|
|
|
// Use port 0 so that outgoing connections use a random port.
|
2017-05-15 20:10:36 +00:00
|
|
|
if !ipaddr.IsAny(base.RPCAddr.IP) {
|
2017-05-10 07:30:19 +00:00
|
|
|
base.RPCSrcAddr = &net.TCPAddr{IP: base.RPCAddr.IP}
|
|
|
|
}
|
2017-05-03 10:57:11 +00:00
|
|
|
|
2014-06-06 22:36:40 +00:00
|
|
|
// Format the build string
|
|
|
|
revision := a.config.Revision
|
|
|
|
if len(revision) > 8 {
|
|
|
|
revision = revision[:8]
|
|
|
|
}
|
2017-05-03 19:12:30 +00:00
|
|
|
base.Build = fmt.Sprintf("%s%s:%s", a.config.Version, a.config.VersionPrerelease, revision)
|
2014-06-06 22:36:40 +00:00
|
|
|
|
2014-04-04 23:52:39 +00:00
|
|
|
// Copy the TLS configuration
|
2017-04-28 23:15:55 +00:00
|
|
|
base.VerifyIncoming = a.config.VerifyIncoming || a.config.VerifyIncomingRPC
|
2017-05-10 21:25:48 +00:00
|
|
|
if a.config.CAPath != "" || a.config.CAFile != "" {
|
|
|
|
base.UseTLS = true
|
|
|
|
}
|
2014-04-04 23:52:39 +00:00
|
|
|
base.VerifyOutgoing = a.config.VerifyOutgoing
|
2015-05-11 22:16:13 +00:00
|
|
|
base.VerifyServerHostname = a.config.VerifyServerHostname
|
2014-04-04 23:52:39 +00:00
|
|
|
base.CAFile = a.config.CAFile
|
2017-04-27 08:29:39 +00:00
|
|
|
base.CAPath = a.config.CAPath
|
2014-04-04 23:52:39 +00:00
|
|
|
base.CertFile = a.config.CertFile
|
|
|
|
base.KeyFile = a.config.KeyFile
|
2014-06-13 18:27:44 +00:00
|
|
|
base.ServerName = a.config.ServerName
|
2017-09-25 18:40:42 +00:00
|
|
|
base.Domain = a.config.DNSDomain
|
2017-02-01 20:52:04 +00:00
|
|
|
base.TLSMinVersion = a.config.TLSMinVersion
|
2017-04-27 08:29:39 +00:00
|
|
|
base.TLSCipherSuites = a.config.TLSCipherSuites
|
|
|
|
base.TLSPreferServerCipherSuites = a.config.TLSPreferServerCipherSuites
|
2014-04-04 23:52:39 +00:00
|
|
|
|
2014-08-27 23:49:12 +00:00
|
|
|
// Setup the user event callback
|
|
|
|
base.UserEventHandler = func(e serf.UserEvent) {
|
|
|
|
select {
|
|
|
|
case a.eventCh <- e:
|
|
|
|
case <-a.shutdownCh:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-12-21 00:39:32 +00:00
|
|
|
// Setup the loggers
|
2017-05-19 15:51:39 +00:00
|
|
|
base.LogOutput = a.LogOutput
|
2017-06-29 12:35:55 +00:00
|
|
|
|
2017-09-07 19:17:20 +00:00
|
|
|
// This will set up the LAN keyring, as well as the WAN and any segments
|
|
|
|
// for servers.
|
2017-07-17 19:48:45 +00:00
|
|
|
if err := a.setupKeyrings(base); err != nil {
|
|
|
|
return nil, fmt.Errorf("Failed to configure keyring: %v", err)
|
2017-06-29 12:35:55 +00:00
|
|
|
}
|
|
|
|
|
2017-05-03 21:47:25 +00:00
|
|
|
return base, nil
|
2013-12-20 23:33:13 +00:00
|
|
|
}
|
|
|
|
|
2017-08-29 00:58:22 +00:00
|
|
|
// Setup the serf and memberlist config for any defined network segments.
|
2017-09-07 23:37:11 +00:00
|
|
|
func (a *Agent) segmentConfig() ([]consul.NetworkSegment, error) {
|
|
|
|
var segments []consul.NetworkSegment
|
2017-08-29 00:58:22 +00:00
|
|
|
config := a.config
|
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
for _, s := range config.Segments {
|
2017-08-29 00:58:22 +00:00
|
|
|
serfConf := consul.DefaultConfig().SerfLANConfig
|
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
serfConf.MemberlistConfig.BindAddr = s.Bind.IP.String()
|
|
|
|
serfConf.MemberlistConfig.BindPort = s.Bind.Port
|
|
|
|
serfConf.MemberlistConfig.AdvertiseAddr = s.Advertise.IP.String()
|
|
|
|
serfConf.MemberlistConfig.AdvertisePort = s.Advertise.Port
|
2017-08-30 19:51:10 +00:00
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
if config.ReconnectTimeoutLAN != 0 {
|
|
|
|
serfConf.ReconnectTimeout = config.ReconnectTimeoutLAN
|
2017-08-29 00:58:22 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if config.EncryptVerifyIncoming {
|
|
|
|
serfConf.MemberlistConfig.GossipVerifyIncoming = config.EncryptVerifyIncoming
|
2017-08-29 00:58:22 +00:00
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if config.EncryptVerifyOutgoing {
|
|
|
|
serfConf.MemberlistConfig.GossipVerifyOutgoing = config.EncryptVerifyOutgoing
|
2017-08-29 00:58:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var rpcAddr *net.TCPAddr
|
2017-09-25 18:40:42 +00:00
|
|
|
if s.RPCListener {
|
2017-08-29 00:58:22 +00:00
|
|
|
rpcAddr = &net.TCPAddr{
|
2017-09-25 18:40:42 +00:00
|
|
|
IP: s.Bind.IP,
|
|
|
|
Port: a.config.ServerPort,
|
2017-08-29 00:58:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-09-07 23:37:11 +00:00
|
|
|
segments = append(segments, consul.NetworkSegment{
|
2017-09-25 18:40:42 +00:00
|
|
|
Name: s.Name,
|
2017-08-30 23:44:04 +00:00
|
|
|
Bind: serfConf.MemberlistConfig.BindAddr,
|
|
|
|
Advertise: serfConf.MemberlistConfig.AdvertiseAddr,
|
2017-09-25 18:40:42 +00:00
|
|
|
Port: s.Bind.Port,
|
2017-08-29 00:58:22 +00:00
|
|
|
RPCAddr: rpcAddr,
|
|
|
|
SerfConfig: serfConf,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return segments, nil
|
|
|
|
}
|
|
|
|
|
2017-02-01 18:27:04 +00:00
|
|
|
// makeRandomID will generate a random UUID for a node.
|
|
|
|
func (a *Agent) makeRandomID() (string, error) {
|
|
|
|
id, err := uuid.GenerateUUID()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
a.logger.Printf("[DEBUG] Using random ID %q as node ID", id)
|
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// makeNodeID will try to find a host-specific ID, or else will generate a
|
|
|
|
// random ID. The returned ID will always be formatted as a GUID. We don't tell
|
|
|
|
// the caller whether this ID is random or stable since the consequences are
|
|
|
|
// high for us if this changes, so we will persist it either way. This will let
|
|
|
|
// gopsutil change implementations without affecting in-place upgrades of nodes.
|
|
|
|
func (a *Agent) makeNodeID() (string, error) {
|
2017-04-13 05:05:38 +00:00
|
|
|
// If they've disabled host-based IDs then just make a random one.
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.DisableHostNodeID {
|
2017-04-13 05:05:38 +00:00
|
|
|
return a.makeRandomID()
|
|
|
|
}
|
|
|
|
|
2017-02-01 18:27:04 +00:00
|
|
|
// Try to get a stable ID associated with the host itself.
|
|
|
|
info, err := host.Info()
|
|
|
|
if err != nil {
|
|
|
|
a.logger.Printf("[DEBUG] Couldn't get a unique ID from the host: %v", err)
|
|
|
|
return a.makeRandomID()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make sure the host ID parses as a UUID, since we don't have complete
|
|
|
|
// control over this process.
|
|
|
|
id := strings.ToLower(info.HostID)
|
|
|
|
if _, err := uuid.ParseUUID(id); err != nil {
|
|
|
|
a.logger.Printf("[DEBUG] Unique ID %q from host isn't formatted as a UUID: %v",
|
|
|
|
id, err)
|
|
|
|
return a.makeRandomID()
|
|
|
|
}
|
|
|
|
|
2017-04-10 18:57:24 +00:00
|
|
|
// Hash the input to make it well distributed. The reported Host UUID may be
|
|
|
|
// similar across nodes if they are on a cloud provider or on motherboards
|
|
|
|
// created from the same batch.
|
|
|
|
buf := sha512.Sum512([]byte(id))
|
|
|
|
id = fmt.Sprintf("%08x-%04x-%04x-%04x-%12x",
|
|
|
|
buf[0:4],
|
|
|
|
buf[4:6],
|
|
|
|
buf[6:8],
|
|
|
|
buf[8:10],
|
|
|
|
buf[10:16])
|
|
|
|
|
2017-02-01 18:27:04 +00:00
|
|
|
a.logger.Printf("[DEBUG] Using unique ID %q from host as node ID", id)
|
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
2017-02-01 03:13:49 +00:00
|
|
|
// setupNodeID will pull the persisted node ID, if any, or create a random one
|
2017-01-18 06:20:11 +00:00
|
|
|
// and persist it.
|
2017-09-25 18:40:42 +00:00
|
|
|
func (a *Agent) setupNodeID(config *config.RuntimeConfig) error {
|
2017-01-18 06:20:11 +00:00
|
|
|
// If they've configured a node ID manually then just use that, as
|
|
|
|
// long as it's valid.
|
|
|
|
if config.NodeID != "" {
|
2017-03-14 02:51:56 +00:00
|
|
|
config.NodeID = types.NodeID(strings.ToLower(string(config.NodeID)))
|
2017-01-18 06:20:11 +00:00
|
|
|
if _, err := uuid.ParseUUID(string(config.NodeID)); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-02-01 18:27:04 +00:00
|
|
|
// For dev mode we have no filesystem access so just make one.
|
2017-01-18 06:20:11 +00:00
|
|
|
if a.config.DevMode {
|
2017-02-01 18:27:04 +00:00
|
|
|
id, err := a.makeNodeID()
|
2017-01-18 06:20:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
config.NodeID = types.NodeID(id)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Load saved state, if any. Since a user could edit this, we also
|
|
|
|
// validate it.
|
|
|
|
fileID := filepath.Join(config.DataDir, "node-id")
|
|
|
|
if _, err := os.Stat(fileID); err == nil {
|
|
|
|
rawID, err := ioutil.ReadFile(fileID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
nodeID := strings.TrimSpace(string(rawID))
|
2017-03-14 02:51:56 +00:00
|
|
|
nodeID = strings.ToLower(nodeID)
|
2017-01-18 06:20:11 +00:00
|
|
|
if _, err := uuid.ParseUUID(nodeID); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
config.NodeID = types.NodeID(nodeID)
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we still don't have a valid node ID, make one.
|
|
|
|
if config.NodeID == "" {
|
2017-02-01 18:27:04 +00:00
|
|
|
id, err := a.makeNodeID()
|
2017-01-18 06:20:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := lib.EnsurePath(fileID, false); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := ioutil.WriteFile(fileID, []byte(id), 0600); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
config.NodeID = types.NodeID(id)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-09-07 19:17:20 +00:00
|
|
|
// setupBaseKeyrings configures the LAN and WAN keyrings.
|
|
|
|
func (a *Agent) setupBaseKeyrings(config *consul.Config) error {
|
2017-07-17 19:48:45 +00:00
|
|
|
// If the keyring file is disabled then just poke the provided key
|
|
|
|
// into the in-memory keyring.
|
|
|
|
if a.config.DisableKeyringFile {
|
|
|
|
if a.config.EncryptKey == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
keys := []string{a.config.EncryptKey}
|
|
|
|
if err := loadKeyring(config.SerfLANConfig, keys); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.ServerMode {
|
2017-07-17 19:48:45 +00:00
|
|
|
if err := loadKeyring(config.SerfWANConfig, keys); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, we need to deal with the keyring files.
|
pkg refactor
command/agent/* -> agent/*
command/consul/* -> agent/consul/*
command/agent/command{,_test}.go -> command/agent{,_test}.go
command/base/command.go -> command/base.go
command/base/* -> command/*
commands.go -> command/commands.go
The script which did the refactor is:
(
cd $GOPATH/src/github.com/hashicorp/consul
git mv command/agent/command.go command/agent.go
git mv command/agent/command_test.go command/agent_test.go
git mv command/agent/flag_slice_value{,_test}.go command/
git mv command/agent .
git mv command/base/command.go command/base.go
git mv command/base/config_util{,_test}.go command/
git mv commands.go command/
git mv consul agent
rmdir command/base/
gsed -i -e 's|package agent|package command|' command/agent{,_test}.go
gsed -i -e 's|package agent|package command|' command/flag_slice_value{,_test}.go
gsed -i -e 's|package base|package command|' command/base.go command/config_util{,_test}.go
gsed -i -e 's|package main|package command|' command/commands.go
gsed -i -e 's|base.Command|BaseCommand|' command/commands.go
gsed -i -e 's|agent.Command|AgentCommand|' command/commands.go
gsed -i -e 's|\tCommand:|\tBaseCommand:|' command/commands.go
gsed -i -e 's|base\.||' command/commands.go
gsed -i -e 's|command\.||' command/commands.go
gsed -i -e 's|command|c|' main.go
gsed -i -e 's|range Commands|range command.Commands|' main.go
gsed -i -e 's|Commands: Commands|Commands: command.Commands|' main.go
gsed -i -e 's|base\.BoolValue|BoolValue|' command/operator_autopilot_set.go
gsed -i -e 's|base\.DurationValue|DurationValue|' command/operator_autopilot_set.go
gsed -i -e 's|base\.StringValue|StringValue|' command/operator_autopilot_set.go
gsed -i -e 's|base\.UintValue|UintValue|' command/operator_autopilot_set.go
gsed -i -e 's|\bCommand\b|BaseCommand|' command/base.go
gsed -i -e 's|BaseCommand Options|Command Options|' command/base.go
gsed -i -e 's|base.Command|BaseCommand|' command/*.go
gsed -i -e 's|c\.Command|c.BaseCommand|g' command/*.go
gsed -i -e 's|\tCommand:|\tBaseCommand:|' command/*_test.go
gsed -i -e 's|base\.||' command/*_test.go
gsed -i -e 's|\bCommand\b|AgentCommand|' command/agent{,_test}.go
gsed -i -e 's|cmd.AgentCommand|cmd.BaseCommand|' command/agent.go
gsed -i -e 's|cli.AgentCommand = new(Command)|cli.Command = new(AgentCommand)|' command/agent_test.go
gsed -i -e 's|exec.AgentCommand|exec.Command|' command/agent_test.go
gsed -i -e 's|exec.BaseCommand|exec.Command|' command/agent_test.go
gsed -i -e 's|NewTestAgent|agent.NewTestAgent|' command/agent_test.go
gsed -i -e 's|= TestConfig|= agent.TestConfig|' command/agent_test.go
gsed -i -e 's|: RetryJoin|: agent.RetryJoin|' command/agent_test.go
gsed -i -e 's|\.\./\.\./|../|' command/config_util_test.go
gsed -i -e 's|\bverifyUniqueListeners|VerifyUniqueListeners|' agent/config{,_test}.go command/agent.go
gsed -i -e 's|\bserfLANKeyring\b|SerfLANKeyring|g' agent/{agent,keyring,testagent}.go command/agent.go
gsed -i -e 's|\bserfWANKeyring\b|SerfWANKeyring|g' agent/{agent,keyring,testagent}.go command/agent.go
gsed -i -e 's|\bNewAgent\b|agent.New|g' command/agent{,_test}.go
gsed -i -e 's|\bNewAgent|New|' agent/{acl_test,agent,testagent}.go
gsed -i -e 's|\bAgent\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bBool\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bConfig\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bDefaultConfig\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bDevConfig\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bMergeConfig\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bReadConfigPaths\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bParseMetaPair\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bSerfLANKeyring\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|\bSerfWANKeyring\b|agent.&|g' command/agent{,_test}.go
gsed -i -e 's|circonus\.agent|circonus|g' command/agent{,_test}.go
gsed -i -e 's|logger\.agent|logger|g' command/agent{,_test}.go
gsed -i -e 's|metrics\.agent|metrics|g' command/agent{,_test}.go
gsed -i -e 's|// agent.Agent|// agent|' command/agent{,_test}.go
gsed -i -e 's|a\.agent\.Config|a.Config|' command/agent{,_test}.go
gsed -i -e 's|agent\.AppendSliceValue|AppendSliceValue|' command/{configtest,validate}.go
gsed -i -e 's|consul/consul|agent/consul|' GNUmakefile
gsed -i -e 's|\.\./test|../../test|' agent/consul/server_test.go
# fix imports
f=$(grep -rl 'github.com/hashicorp/consul/command/agent' * | grep '\.go')
gsed -i -e 's|github.com/hashicorp/consul/command/agent|github.com/hashicorp/consul/agent|' $f
goimports -w $f
f=$(grep -rl 'github.com/hashicorp/consul/consul' * | grep '\.go')
gsed -i -e 's|github.com/hashicorp/consul/consul|github.com/hashicorp/consul/agent/consul|' $f
goimports -w $f
goimports -w command/*.go main.go
)
2017-06-09 22:28:28 +00:00
|
|
|
fileLAN := filepath.Join(a.config.DataDir, SerfLANKeyring)
|
|
|
|
fileWAN := filepath.Join(a.config.DataDir, SerfWANKeyring)
|
2014-10-10 18:13:30 +00:00
|
|
|
|
|
|
|
if a.config.EncryptKey == "" {
|
|
|
|
goto LOAD
|
|
|
|
}
|
|
|
|
if _, err := os.Stat(fileLAN); err != nil {
|
|
|
|
if err := initKeyring(fileLAN, a.config.EncryptKey); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.ServerMode {
|
2014-10-10 18:13:30 +00:00
|
|
|
if _, err := os.Stat(fileWAN); err != nil {
|
|
|
|
if err := initKeyring(fileWAN, a.config.EncryptKey); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
LOAD:
|
|
|
|
if _, err := os.Stat(fileLAN); err == nil {
|
|
|
|
config.SerfLANConfig.KeyringFile = fileLAN
|
|
|
|
}
|
|
|
|
if err := loadKeyringFile(config.SerfLANConfig); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-09-25 18:40:42 +00:00
|
|
|
if a.config.ServerMode {
|
2014-10-10 18:13:30 +00:00
|
|
|
if _, err := os.Stat(fileWAN); err == nil {
|
|
|
|
config.SerfWANConfig.KeyringFile = fileWAN
|
|
|
|
}
|
|
|
|
if err := loadKeyringFile(config.SerfWANConfig); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-09-07 19:17:20 +00:00
|
|
|
// setupKeyrings is used to initialize and load keyrings during agent startup.
|
|
|
|
func (a *Agent) setupKeyrings(config *consul.Config) error {
|
|
|
|
// First set up the LAN and WAN keyrings.
|
|
|
|
if err := a.setupBaseKeyrings(config); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// If there's no LAN keyring then there's nothing else to set up for
|
|
|
|
// any segments.
|
|
|
|
lanKeyring := config.SerfLANConfig.MemberlistConfig.Keyring
|
|
|
|
if lanKeyring == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Copy the initial state of the LAN keyring into each segment config.
|
|
|
|
// Segments don't have their own keyring file, they rely on the LAN
|
|
|
|
// holding the state so things can't get out of sync.
|
|
|
|
k, pk := lanKeyring.GetKeys(), lanKeyring.GetPrimaryKey()
|
|
|
|
for _, segment := range config.Segments {
|
|
|
|
keyring, err := memberlist.NewKeyring(k, pk)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
segment.SerfConfig.MemberlistConfig.Keyring = keyring
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-06-19 14:36:09 +00:00
|
|
|
// registerEndpoint registers a handler for the consul RPC server
|
2017-06-16 07:54:09 +00:00
|
|
|
// under a unique name while making it accessible under the provided
|
|
|
|
// name. This allows overwriting handlers for the golang net/rpc
|
|
|
|
// service which does not allow this.
|
2017-06-19 14:36:09 +00:00
|
|
|
func (a *Agent) registerEndpoint(name string, handler interface{}) error {
|
2017-06-16 07:54:09 +00:00
|
|
|
srv, ok := a.delegate.(*consul.Server)
|
|
|
|
if !ok {
|
|
|
|
panic("agent must be a server")
|
|
|
|
}
|
|
|
|
realname := fmt.Sprintf("%s-%d", name, time.Now().UnixNano())
|
|
|
|
a.endpointsLock.Lock()
|
|
|
|
a.endpoints[name] = realname
|
|
|
|
a.endpointsLock.Unlock()
|
|
|
|
return srv.RegisterEndpoint(realname, handler)
|
|
|
|
}
|
|
|
|
|
2013-12-20 23:33:13 +00:00
|
|
|
// RPC is used to make an RPC call to the Consul servers
|
|
|
|
// This allows the agent to implement the Consul.Interface
|
|
|
|
func (a *Agent) RPC(method string, args interface{}, reply interface{}) error {
|
2017-08-10 01:51:55 +00:00
|
|
|
a.endpointsLock.RLock()
|
2017-06-16 07:54:09 +00:00
|
|
|
// fast path: only translate if there are overrides
|
|
|
|
if len(a.endpoints) > 0 {
|
|
|
|
p := strings.SplitN(method, ".", 2)
|
|
|
|
if e := a.endpoints[p[0]]; e != "" {
|
|
|
|
method = e + "." + p[1]
|
|
|
|
}
|
|
|
|
}
|
2017-08-10 01:51:55 +00:00
|
|
|
a.endpointsLock.RUnlock()
|
2017-05-15 14:05:17 +00:00
|
|
|
return a.delegate.RPC(method, args, reply)
|
2013-12-20 23:33:13 +00:00
|
|
|
}
|
|
|
|
|
2016-10-26 02:20:24 +00:00
|
|
|
// SnapshotRPC performs the requested snapshot RPC against the Consul server in
|
|
|
|
// a streaming manner. The contents of in will be read and passed along as the
|
|
|
|
// payload, and the response message will determine the error status, and any
|
|
|
|
// return payload will be written to out.
|
|
|
|
func (a *Agent) SnapshotRPC(args *structs.SnapshotRequest, in io.Reader, out io.Writer,
|
2017-06-15 09:50:28 +00:00
|
|
|
replyFn structs.SnapshotReplyFn) error {
|
2017-05-15 14:05:17 +00:00
|
|
|
return a.delegate.SnapshotRPC(args, in, out, replyFn)
|
2016-10-26 02:20:24 +00:00
|
|
|
}
|
|
|
|
|
2014-04-18 05:46:31 +00:00
|
|
|
// Leave is used to prepare the agent for a graceful shutdown
|
2013-12-20 01:14:46 +00:00
|
|
|
func (a *Agent) Leave() error {
|
2017-05-15 14:05:17 +00:00
|
|
|
return a.delegate.Leave()
|
2013-12-20 01:14:46 +00:00
|
|
|
}
|
|
|
|
|
2017-06-20 07:29:20 +00:00
|
|
|
// ShutdownAgent is used to hard stop the agent. Should be preceded by
|
|
|
|
// Leave to do it gracefully. Should be followed by ShutdownEndpoints to
|
|
|
|
// terminate the HTTP and DNS servers as well.
|
|
|
|
func (a *Agent) ShutdownAgent() error {
|
2013-12-21 00:39:32 +00:00
|
|
|
a.shutdownLock.Lock()
|
|
|
|
defer a.shutdownLock.Unlock()
|
|
|
|
|
|
|
|
if a.shutdown {
|
|
|
|
return nil
|
|
|
|
}
|
2017-05-19 09:53:41 +00:00
|
|
|
a.logger.Println("[INFO] agent: Requesting shutdown")
|
|
|
|
|
2014-01-21 20:05:56 +00:00
|
|
|
// Stop all the checks
|
|
|
|
a.checkLock.Lock()
|
|
|
|
defer a.checkLock.Unlock()
|
|
|
|
for _, chk := range a.checkMonitors {
|
|
|
|
chk.Stop()
|
|
|
|
}
|
|
|
|
for _, chk := range a.checkTTLs {
|
|
|
|
chk.Stop()
|
|
|
|
}
|
2015-01-09 22:43:24 +00:00
|
|
|
for _, chk := range a.checkHTTPs {
|
|
|
|
chk.Stop()
|
|
|
|
}
|
2015-07-23 11:45:08 +00:00
|
|
|
for _, chk := range a.checkTCPs {
|
|
|
|
chk.Stop()
|
|
|
|
}
|
2017-07-18 18:57:27 +00:00
|
|
|
for _, chk := range a.checkDockers {
|
|
|
|
chk.Stop()
|
|
|
|
}
|
2015-07-23 11:45:08 +00:00
|
|
|
|
2017-05-22 21:59:54 +00:00
|
|
|
var err error
|
|
|
|
if a.delegate != nil {
|
|
|
|
err = a.delegate.Shutdown()
|
2017-05-23 10:15:25 +00:00
|
|
|
if _, ok := a.delegate.(*consul.Server); ok {
|
|
|
|
a.logger.Print("[INFO] agent: consul server down")
|
|
|
|
} else {
|
|
|
|
a.logger.Print("[INFO] agent: consul client down")
|
|
|
|
}
|
2017-05-22 21:59:54 +00:00
|
|
|
}
|
2013-12-21 00:39:32 +00:00
|
|
|
|
2014-05-06 16:57:53 +00:00
|
|
|
pidErr := a.deletePid()
|
|
|
|
if pidErr != nil {
|
|
|
|
a.logger.Println("[WARN] agent: could not delete pid file ", pidErr)
|
|
|
|
}
|
2014-05-06 03:29:50 +00:00
|
|
|
|
2017-06-19 19:34:08 +00:00
|
|
|
a.logger.Println("[INFO] agent: shutdown complete")
|
2013-12-21 00:39:32 +00:00
|
|
|
a.shutdown = true
|
2017-06-19 19:34:08 +00:00
|
|
|
close(a.shutdownCh)
|
2013-12-21 00:39:32 +00:00
|
|
|
return err
|
2017-06-20 07:29:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ShutdownEndpoints terminates the HTTP and DNS servers. Should be
|
|
|
|
// preceeded by ShutdownAgent.
|
|
|
|
func (a *Agent) ShutdownEndpoints() {
|
|
|
|
a.shutdownLock.Lock()
|
|
|
|
defer a.shutdownLock.Unlock()
|
|
|
|
|
|
|
|
if len(a.dnsServers) == 0 || len(a.httpServers) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, srv := range a.dnsServers {
|
|
|
|
a.logger.Printf("[INFO] agent: Stopping DNS server %s (%s)", srv.Server.Addr, srv.Server.Net)
|
|
|
|
srv.Shutdown()
|
|
|
|
}
|
|
|
|
a.dnsServers = nil
|
|
|
|
|
|
|
|
for _, srv := range a.httpServers {
|
2017-09-25 18:40:42 +00:00
|
|
|
a.logger.Printf("[INFO] agent: Stopping %s server %s (%s)", strings.ToUpper(srv.proto), srv.addr.String(), srv.addr.Network())
|
2017-06-20 07:29:20 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
|
|
|
defer cancel()
|
|
|
|
srv.Shutdown(ctx)
|
|
|
|
if ctx.Err() == context.DeadlineExceeded {
|
2017-09-25 18:40:42 +00:00
|
|
|
a.logger.Printf("[WARN] agent: Timeout stopping %s server %s (%s)", strings.ToUpper(srv.proto), srv.addr.String(), srv.addr.Network())
|
2017-06-20 07:29:20 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
a.httpServers = nil
|
|
|
|
|
|
|
|
a.logger.Println("[INFO] agent: Waiting for endpoints to shut down")
|
|
|
|
a.wgServers.Wait()
|
|
|
|
a.logger.Print("[INFO] agent: Endpoints down")
|
2013-12-21 00:39:32 +00:00
|
|
|
}
|
|
|
|
|
2017-05-19 15:51:39 +00:00
|
|
|
// ReloadCh is used to return a channel that can be
|
|
|
|
// used for triggering reloads and returning a response.
|
|
|
|
func (a *Agent) ReloadCh() chan chan error {
|
|
|
|
return a.reloadCh
|
|
|
|
}
|
|
|
|
|
2017-06-02 09:55:29 +00:00
|
|
|
// RetryJoinCh is a channel that transports errors
|
|
|
|
// from the retry join process.
|
|
|
|
func (a *Agent) RetryJoinCh() <-chan error {
|
|
|
|
return a.retryJoinCh
|
|
|
|
}
|
|
|
|
|
2014-04-18 05:46:31 +00:00
|
|
|
// ShutdownCh is used to return a channel that can be
|
|
|
|
// selected to wait for the agent to perform a shutdown.
|
2013-12-21 00:39:32 +00:00
|
|
|
func (a *Agent) ShutdownCh() <-chan struct{} {
|
|
|
|
return a.shutdownCh
|
2013-12-20 01:14:46 +00:00
|
|
|
}
|
2013-12-30 22:42:41 +00:00
|
|
|
|
|
|
|
// JoinLAN is used to have the agent join a LAN cluster
|
|
|
|
func (a *Agent) JoinLAN(addrs []string) (n int, err error) {
|
|
|
|
a.logger.Printf("[INFO] agent: (LAN) joining: %v", addrs)
|
2017-05-15 14:05:17 +00:00
|
|
|
n, err = a.delegate.JoinLAN(addrs)
|
2013-12-30 22:42:41 +00:00
|
|
|
a.logger.Printf("[INFO] agent: (LAN) joined: %d Err: %v", n, err)
|
2017-06-21 04:43:55 +00:00
|
|
|
if err == nil && a.joinLANNotifier != nil {
|
|
|
|
if notifErr := a.joinLANNotifier.Notify(systemd.Ready); notifErr != nil {
|
2017-06-27 21:32:38 +00:00
|
|
|
a.logger.Printf("[DEBUG] agent: systemd notify failed: %v", notifErr)
|
2017-06-21 04:43:55 +00:00
|
|
|
}
|
|
|
|
}
|
2013-12-30 22:42:41 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// JoinWAN is used to have the agent join a WAN cluster
|
|
|
|
func (a *Agent) JoinWAN(addrs []string) (n int, err error) {
|
|
|
|
a.logger.Printf("[INFO] agent: (WAN) joining: %v", addrs)
|
2017-05-15 14:05:17 +00:00
|
|
|
if srv, ok := a.delegate.(*consul.Server); ok {
|
|
|
|
n, err = srv.JoinWAN(addrs)
|
2013-12-30 22:42:41 +00:00
|
|
|
} else {
|
|
|
|
err = fmt.Errorf("Must be a server to join WAN cluster")
|
|
|
|
}
|
|
|
|
a.logger.Printf("[INFO] agent: (WAN) joined: %d Err: %v", n, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// ForceLeave is used to remove a failed node from the cluster
|
|
|
|
func (a *Agent) ForceLeave(node string) (err error) {
|
|
|
|
a.logger.Printf("[INFO] Force leaving node: %v", node)
|
2017-05-15 14:05:17 +00:00
|
|
|
err = a.delegate.RemoveFailedNode(node)
|
2013-12-30 22:42:41 +00:00
|
|
|
if err != nil {
|
|
|
|
a.logger.Printf("[WARN] Failed to remove node: %v", err)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2014-05-25 23:59:48 +00:00
|
|
|
// LocalMember is used to return the local node
|
|
|
|
func (a *Agent) LocalMember() serf.Member {
|
2017-05-15 14:05:17 +00:00
|
|
|
return a.delegate.LocalMember()
|
2014-05-25 23:59:48 +00:00
|
|
|
}
|
|
|
|
|
2014-04-18 05:46:31 +00:00
|
|
|
// LANMembers is used to retrieve the LAN members
|
2013-12-30 22:42:41 +00:00
|
|
|
func (a *Agent) LANMembers() []serf.Member {
|
2017-05-15 14:05:17 +00:00
|
|
|
return a.delegate.LANMembers()
|
2013-12-30 22:42:41 +00:00
|
|
|
}
|
|
|
|
|
2014-04-18 05:46:31 +00:00
|
|
|
// WANMembers is used to retrieve the WAN members
|
2013-12-30 22:42:41 +00:00
|
|
|
func (a *Agent) WANMembers() []serf.Member {
|
2017-05-15 14:05:17 +00:00
|
|
|
if srv, ok := a.delegate.(*consul.Server); ok {
|
|
|
|
return srv.WANMembers()
|
2013-12-30 22:42:41 +00:00
|
|
|
}
|
2017-04-21 01:59:42 +00:00
|
|
|
return nil
|
2013-12-30 22:42:41 +00:00
|
|
|
}
|
2014-01-21 19:52:25 +00:00
|
|
|
|
|
|
|
// StartSync is called once Services and Checks are registered.
|
|
|
|
// This is called to prevent a race between clients and the anti-entropy routines
|
|
|
|
func (a *Agent) StartSync() {
|
2017-08-28 12:17:09 +00:00
|
|
|
go a.sync.Run()
|
|
|
|
a.logger.Printf("[INFO] agent: starting state syncer")
|
2014-01-21 19:52:25 +00:00
|
|
|
}
|
2014-01-30 21:39:02 +00:00
|
|
|
|
2014-04-18 05:46:31 +00:00
|
|
|
// PauseSync is used to pause anti-entropy while bulk changes are make
|
2014-02-07 20:19:56 +00:00
|
|
|
func (a *Agent) PauseSync() {
|
2017-08-28 12:17:09 +00:00
|
|
|
a.sync.Pause()
|
2014-02-07 20:19:56 +00:00
|
|
|
}
|
|
|
|
|
2014-04-18 05:46:31 +00:00
|
|
|
// ResumeSync is used to unpause anti-entropy after bulk changes are make
|
2014-02-07 20:19:56 +00:00
|
|
|
func (a *Agent) ResumeSync() {
|
2017-08-28 12:17:09 +00:00
|
|
|
a.sync.Resume()
|
2014-02-07 20:19:56 +00:00
|
|
|
}
|
|
|
|
|
2017-08-14 14:36:07 +00:00
|
|
|
// GetLANCoordinate returns the coordinates of this node in the local pools
|
|
|
|
// (assumes coordinates are enabled, so check that before calling).
|
|
|
|
func (a *Agent) GetLANCoordinate() (lib.CoordinateSet, error) {
|
2017-05-15 14:05:17 +00:00
|
|
|
return a.delegate.GetLANCoordinate()
|
2015-10-16 02:28:31 +00:00
|
|
|
}
|
|
|
|
|
2015-06-06 03:31:33 +00:00
|
|
|
// sendCoordinate is a long-running loop that periodically sends our coordinate
|
|
|
|
// to the server. Closing the agent's shutdownChannel will cause this to exit.
|
|
|
|
func (a *Agent) sendCoordinate() {
|
2017-08-14 14:36:07 +00:00
|
|
|
OUTER:
|
2015-04-15 23:12:45 +00:00
|
|
|
for {
|
2015-06-30 19:02:05 +00:00
|
|
|
rate := a.config.SyncCoordinateRateTarget
|
|
|
|
min := a.config.SyncCoordinateIntervalMin
|
2016-01-29 19:42:34 +00:00
|
|
|
intv := lib.RateScaledInterval(rate, min, len(a.LANMembers()))
|
|
|
|
intv = intv + lib.RandomStagger(intv)
|
2015-06-06 03:31:33 +00:00
|
|
|
|
2015-04-15 23:12:45 +00:00
|
|
|
select {
|
2015-04-29 01:47:41 +00:00
|
|
|
case <-time.After(intv):
|
2015-10-27 21:30:29 +00:00
|
|
|
members := a.LANMembers()
|
|
|
|
grok, err := consul.CanServersUnderstandProtocol(members, 3)
|
|
|
|
if err != nil {
|
2017-07-14 05:33:47 +00:00
|
|
|
a.logger.Printf("[ERR] agent: Failed to check servers: %s", err)
|
2015-10-27 21:30:29 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
if !grok {
|
2017-07-14 05:33:47 +00:00
|
|
|
a.logger.Printf("[DEBUG] agent: Skipping coordinate updates until servers are upgraded")
|
2015-10-16 02:28:31 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-08-14 14:36:07 +00:00
|
|
|
cs, err := a.GetLANCoordinate()
|
2015-10-27 21:30:29 +00:00
|
|
|
if err != nil {
|
2017-07-14 05:33:47 +00:00
|
|
|
a.logger.Printf("[ERR] agent: Failed to get coordinate: %s", err)
|
2015-06-29 22:53:29 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-08-14 14:36:07 +00:00
|
|
|
for segment, coord := range cs {
|
|
|
|
req := structs.CoordinateUpdateRequest{
|
|
|
|
Datacenter: a.config.Datacenter,
|
|
|
|
Node: a.config.NodeName,
|
|
|
|
Segment: segment,
|
|
|
|
Coord: coord,
|
|
|
|
WriteRequest: structs.WriteRequest{Token: a.tokens.AgentToken()},
|
|
|
|
}
|
|
|
|
var reply struct{}
|
|
|
|
if err := a.RPC("Coordinate.Update", &req, &reply); err != nil {
|
|
|
|
if acl.IsErrPermissionDenied(err) {
|
|
|
|
a.logger.Printf("[WARN] agent: Coordinate update blocked by ACLs")
|
|
|
|
} else {
|
|
|
|
a.logger.Printf("[ERR] agent: Coordinate update error: %v", err)
|
|
|
|
}
|
|
|
|
continue OUTER
|
2017-07-14 05:33:47 +00:00
|
|
|
}
|
2015-04-15 23:12:45 +00:00
|
|
|
}
|
2015-04-19 00:49:49 +00:00
|
|
|
case <-a.shutdownCh:
|
2015-04-15 23:12:45 +00:00
|
|
|
return
|
|
|
|
}
|
2015-04-13 20:45:42 +00:00
|
|
|
}
|
2015-04-09 20:23:14 +00:00
|
|
|
}
|
|
|
|
|
2016-08-16 19:52:30 +00:00
|
|
|
// reapServicesInternal does a single pass, looking for services to reap.
|
|
|
|
func (a *Agent) reapServicesInternal() {
|
2017-08-28 12:17:12 +00:00
|
|
|
reaped := make(map[string]bool)
|
2017-08-28 12:17:13 +00:00
|
|
|
for checkID, cs := range a.State.CriticalCheckStates() {
|
2017-08-28 12:17:12 +00:00
|
|
|
serviceID := cs.Check.ServiceID
|
|
|
|
|
2016-08-16 19:52:30 +00:00
|
|
|
// There's nothing to do if there's no service.
|
2017-08-28 12:17:12 +00:00
|
|
|
if serviceID == "" {
|
2016-08-16 19:52:30 +00:00
|
|
|
continue
|
|
|
|
}
|
2016-08-16 07:05:55 +00:00
|
|
|
|
2016-08-16 19:52:30 +00:00
|
|
|
// There might be multiple checks for one service, so
|
|
|
|
// we don't need to reap multiple times.
|
2017-08-28 12:17:12 +00:00
|
|
|
if reaped[serviceID] {
|
2016-08-16 19:52:30 +00:00
|
|
|
continue
|
|
|
|
}
|
2016-08-16 07:05:55 +00:00
|
|
|
|
2016-08-16 19:52:30 +00:00
|
|
|
// See if there's a timeout.
|
2017-08-28 12:17:12 +00:00
|
|
|
// todo(fs): this looks fishy... why is there anoter data structure in the agent with its own lock?
|
2016-08-16 19:52:30 +00:00
|
|
|
a.checkLock.Lock()
|
2017-08-28 12:17:12 +00:00
|
|
|
timeout := a.checkReapAfter[checkID]
|
2016-08-16 19:52:30 +00:00
|
|
|
a.checkLock.Unlock()
|
|
|
|
|
|
|
|
// Reap, if necessary. We keep track of which service
|
|
|
|
// this is so that we won't try to remove it again.
|
2017-08-28 12:17:12 +00:00
|
|
|
if timeout > 0 && cs.CriticalFor() > timeout {
|
|
|
|
reaped[serviceID] = true
|
2016-08-16 19:52:30 +00:00
|
|
|
a.RemoveService(serviceID, true)
|
|
|
|
a.logger.Printf("[INFO] agent: Check %q for service %q has been critical for too long; deregistered service",
|
|
|
|
checkID, serviceID)
|
2016-08-16 07:05:55 +00:00
|
|
|
}
|
|
|
|
}
|
2016-08-16 19:52:30 +00:00
|
|
|
}
|
2016-08-16 07:05:55 +00:00
|
|
|
|
2016-08-16 19:52:30 +00:00
|
|
|
// reapServices is a long running goroutine that looks for checks that have been
|
|
|
|
// critical too long and dregisters their associated services.
|
|
|
|
func (a *Agent) reapServices() {
|
2016-08-16 07:05:55 +00:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-time.After(a.config.CheckReapInterval):
|
2016-08-16 19:52:30 +00:00
|
|
|
a.reapServicesInternal()
|
2016-08-16 07:05:55 +00:00
|
|
|
|
|
|
|
case <-a.shutdownCh:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2017-06-15 16:46:06 +00:00
|
|
|
// persistedService is used to wrap a service definition and bundle it
|
|
|
|
// with an ACL token so we can restore both at a later agent start.
|
|
|
|
type persistedService struct {
|
|
|
|
Token string
|
|
|
|
Service *structs.NodeService
|
|
|
|
}
|
|
|
|
|
2014-11-24 08:36:03 +00:00
|
|
|
// persistService saves a service definition to a JSON file in the data dir
|
|
|
|
func (a *Agent) persistService(service *structs.NodeService) error {
|
2015-01-08 03:11:21 +00:00
|
|
|
svcPath := filepath.Join(a.config.DataDir, servicesDir, stringHash(service.ID))
|
2016-11-07 18:51:03 +00:00
|
|
|
|
2015-05-06 05:08:03 +00:00
|
|
|
wrapped := persistedService{
|
2017-08-28 12:17:13 +00:00
|
|
|
Token: a.State.ServiceToken(service.ID),
|
2015-05-06 05:08:03 +00:00
|
|
|
Service: service,
|
|
|
|
}
|
|
|
|
encoded, err := json.Marshal(wrapped)
|
|
|
|
if err != nil {
|
2016-04-26 22:03:26 +00:00
|
|
|
return err
|
2015-05-06 05:08:03 +00:00
|
|
|
}
|
2016-11-07 18:51:03 +00:00
|
|
|
|
2017-07-25 02:07:48 +00:00
|
|
|
return writeFileAtomic(svcPath, encoded)
|
2014-11-24 08:36:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// purgeService removes a persisted service definition file from the data dir
|
|
|
|
func (a *Agent) purgeService(serviceID string) error {
|
2015-01-08 03:11:21 +00:00
|
|
|
svcPath := filepath.Join(a.config.DataDir, servicesDir, stringHash(serviceID))
|
2014-11-24 08:36:03 +00:00
|
|
|
if _, err := os.Stat(svcPath); err == nil {
|
|
|
|
return os.Remove(svcPath)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// persistCheck saves a check definition to the local agent's state directory
|
2017-06-15 16:46:06 +00:00
|
|
|
func (a *Agent) persistCheck(check *structs.HealthCheck, chkType *structs.CheckType) error {
|
2016-06-06 08:53:30 +00:00
|
|
|
checkPath := filepath.Join(a.config.DataDir, checksDir, checkIDHash(check.CheckID))
|
2014-11-29 20:25:01 +00:00
|
|
|
|
|
|
|
// Create the persisted check
|
2015-04-28 19:44:46 +00:00
|
|
|
wrapped := persistedCheck{
|
|
|
|
Check: check,
|
|
|
|
ChkType: chkType,
|
2017-08-28 12:17:13 +00:00
|
|
|
Token: a.State.CheckToken(check.CheckID),
|
2015-04-28 19:44:46 +00:00
|
|
|
}
|
2014-11-29 20:25:01 +00:00
|
|
|
|
2015-04-28 19:44:46 +00:00
|
|
|
encoded, err := json.Marshal(wrapped)
|
2014-11-29 20:25:01 +00:00
|
|
|
if err != nil {
|
2016-04-26 22:03:26 +00:00
|
|
|
return err
|
2014-11-29 20:25:01 +00:00
|
|
|
}
|
2016-11-07 18:51:03 +00:00
|
|
|
|
2017-07-25 02:07:48 +00:00
|
|
|
return writeFileAtomic(checkPath, encoded)
|
2014-11-24 08:36:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// purgeCheck removes a persisted check definition file from the data dir
|
2016-06-06 20:19:31 +00:00
|
|
|
func (a *Agent) purgeCheck(checkID types.CheckID) error {
|
2016-06-06 08:53:30 +00:00
|
|
|
checkPath := filepath.Join(a.config.DataDir, checksDir, checkIDHash(checkID))
|
2014-11-24 08:36:03 +00:00
|
|
|
if _, err := os.Stat(checkPath); err == nil {
|
|
|
|
return os.Remove(checkPath)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-11-07 18:51:03 +00:00
|
|
|
// writeFileAtomic writes the given contents to a temporary file in the same
|
|
|
|
// directory, does an fsync and then renames the file to its real path
|
2017-07-25 02:07:48 +00:00
|
|
|
func writeFileAtomic(path string, contents []byte) error {
|
2016-11-09 23:22:53 +00:00
|
|
|
uuid, err := uuid.GenerateUUID()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
tempPath := fmt.Sprintf("%s-%s.tmp", path, uuid)
|
|
|
|
|
2016-11-07 18:51:03 +00:00
|
|
|
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
fh, err := os.OpenFile(tempPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if _, err := fh.Write(contents); err != nil {
|
2017-07-24 17:37:14 +00:00
|
|
|
fh.Close()
|
|
|
|
os.Remove(tempPath)
|
2016-11-07 18:51:03 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := fh.Sync(); err != nil {
|
2017-07-24 17:37:14 +00:00
|
|
|
fh.Close()
|
|
|
|
os.Remove(tempPath)
|
2016-11-07 18:51:03 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := fh.Close(); err != nil {
|
2017-07-24 17:37:14 +00:00
|
|
|
os.Remove(tempPath)
|
2016-11-07 18:51:03 +00:00
|
|
|
return err
|
|
|
|
}
|
2017-07-24 17:37:14 +00:00
|
|
|
if err := os.Rename(tempPath, path); err != nil {
|
|
|
|
os.Remove(tempPath)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
2016-11-07 18:51:03 +00:00
|
|
|
}
|
|
|
|
|
2014-01-30 21:39:02 +00:00
|
|
|
// AddService is used to add a service entry.
|
|
|
|
// This entry is persistent and the agent will make a best effort to
|
|
|
|
// ensure it is registered
|
2017-06-15 16:46:06 +00:00
|
|
|
func (a *Agent) AddService(service *structs.NodeService, chkTypes []*structs.CheckType, persist bool, token string) error {
|
2014-01-30 21:39:02 +00:00
|
|
|
if service.Service == "" {
|
|
|
|
return fmt.Errorf("Service name missing")
|
|
|
|
}
|
|
|
|
if service.ID == "" && service.Service != "" {
|
|
|
|
service.ID = service.Service
|
|
|
|
}
|
2015-01-14 01:52:17 +00:00
|
|
|
for _, check := range chkTypes {
|
2017-10-10 23:54:06 +00:00
|
|
|
if err := check.Validate(); err != nil {
|
|
|
|
return fmt.Errorf("Check is not valid: %v", err)
|
2015-01-14 01:52:17 +00:00
|
|
|
}
|
2014-01-30 21:39:02 +00:00
|
|
|
}
|
|
|
|
|
2015-02-09 17:22:51 +00:00
|
|
|
// Warn if the service name is incompatible with DNS
|
2017-08-03 19:47:07 +00:00
|
|
|
if InvalidDnsRe.MatchString(service.Service) {
|
2015-02-09 17:22:51 +00:00
|
|
|
a.logger.Printf("[WARN] Service name %q will not be discoverable "+
|
2015-02-09 17:59:21 +00:00
|
|
|
"via DNS due to invalid characters. Valid characters include "+
|
|
|
|
"all alpha-numerics and dashes.", service.Service)
|
2015-02-09 17:22:51 +00:00
|
|
|
}
|
|
|
|
|
2015-02-09 17:30:06 +00:00
|
|
|
// Warn if any tags are incompatible with DNS
|
|
|
|
for _, tag := range service.Tags {
|
2017-08-03 19:47:07 +00:00
|
|
|
if InvalidDnsRe.MatchString(tag) {
|
2016-10-05 12:45:01 +00:00
|
|
|
a.logger.Printf("[DEBUG] Service tag %q will not be discoverable "+
|
2015-02-09 17:59:21 +00:00
|
|
|
"via DNS due to invalid characters. Valid characters include "+
|
|
|
|
"all alpha-numerics and dashes.", tag)
|
2015-02-09 17:30:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-06 19:28:42 +00:00
|
|
|
// Pause the service syncs during modification
|
|
|
|
a.PauseSync()
|
|
|
|
defer a.ResumeSync()
|
|
|
|
|
|
|
|
// Take a snapshot of the current state of checks (if any), and
|
|
|
|
// restore them before resuming anti-entropy.
|
|
|
|
snap := a.snapshotCheckState()
|
|
|
|
defer a.restoreCheckState(snap)
|
|
|
|
|
2014-01-30 21:39:02 +00:00
|
|
|
// Add the service
|
2017-08-28 12:17:13 +00:00
|
|
|
a.State.AddService(service, token)
|
2014-01-30 21:39:02 +00:00
|
|
|
|
2014-11-24 08:36:03 +00:00
|
|
|
// Persist the service to a file
|
2015-11-29 04:40:05 +00:00
|
|
|
if persist && !a.config.DevMode {
|
2014-11-25 03:24:32 +00:00
|
|
|
if err := a.persistService(service); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2014-11-24 09:58:39 +00:00
|
|
|
}
|
2014-11-24 08:36:03 +00:00
|
|
|
|
2014-01-30 21:39:02 +00:00
|
|
|
// Create an associated health check
|
2015-01-14 01:52:17 +00:00
|
|
|
for i, chkType := range chkTypes {
|
2017-05-15 19:49:13 +00:00
|
|
|
checkID := string(chkType.CheckID)
|
|
|
|
if checkID == "" {
|
|
|
|
checkID = fmt.Sprintf("service:%s", service.ID)
|
|
|
|
if len(chkTypes) > 1 {
|
|
|
|
checkID += fmt.Sprintf(":%d", i+1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
name := chkType.Name
|
|
|
|
if name == "" {
|
|
|
|
name = fmt.Sprintf("Service '%s' check", service.Service)
|
2015-01-14 01:52:17 +00:00
|
|
|
}
|
2014-01-30 21:39:02 +00:00
|
|
|
check := &structs.HealthCheck{
|
|
|
|
Node: a.config.NodeName,
|
2016-06-06 20:19:31 +00:00
|
|
|
CheckID: types.CheckID(checkID),
|
2017-05-15 19:49:13 +00:00
|
|
|
Name: name,
|
2017-04-19 23:00:11 +00:00
|
|
|
Status: api.HealthCritical,
|
2014-11-07 02:24:04 +00:00
|
|
|
Notes: chkType.Notes,
|
2014-01-30 21:39:02 +00:00
|
|
|
ServiceID: service.ID,
|
|
|
|
ServiceName: service.Service,
|
|
|
|
}
|
2015-04-12 00:53:48 +00:00
|
|
|
if chkType.Status != "" {
|
|
|
|
check.Status = chkType.Status
|
|
|
|
}
|
2015-05-05 00:36:17 +00:00
|
|
|
if err := a.AddCheck(check, chkType, persist, token); err != nil {
|
2014-01-30 21:39:02 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveService is used to remove a service entry.
|
|
|
|
// The agent will make a best effort to ensure it is deregistered
|
2014-11-26 07:58:02 +00:00
|
|
|
func (a *Agent) RemoveService(serviceID string, persist bool) error {
|
2015-01-26 16:06:49 +00:00
|
|
|
// Validate ServiceID
|
|
|
|
if serviceID == "" {
|
|
|
|
return fmt.Errorf("ServiceID missing")
|
|
|
|
}
|
|
|
|
|
2015-09-15 12:22:08 +00:00
|
|
|
// Remove service immediately
|
2017-08-28 12:17:13 +00:00
|
|
|
if err := a.State.RemoveService(serviceID); err != nil {
|
2016-11-09 21:56:54 +00:00
|
|
|
a.logger.Printf("[WARN] agent: Failed to deregister service %q: %s", serviceID, err)
|
|
|
|
return nil
|
|
|
|
}
|
2014-01-30 21:39:02 +00:00
|
|
|
|
2014-11-24 08:36:03 +00:00
|
|
|
// Remove the service from the data dir
|
2014-11-26 07:58:02 +00:00
|
|
|
if persist {
|
|
|
|
if err := a.purgeService(serviceID); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2014-11-24 08:36:03 +00:00
|
|
|
}
|
|
|
|
|
2014-01-30 21:39:02 +00:00
|
|
|
// Deregister any associated health checks
|
2017-08-28 12:17:13 +00:00
|
|
|
for checkID, check := range a.State.Checks() {
|
2017-08-28 12:17:11 +00:00
|
|
|
if check.ServiceID != serviceID {
|
2015-01-14 01:52:17 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
if err := a.RemoveCheck(checkID, persist); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2015-01-08 06:26:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("[DEBUG] agent: removed service %q", serviceID)
|
|
|
|
return nil
|
2014-01-30 21:39:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// AddCheck is used to add a health check to the agent.
|
|
|
|
// This entry is persistent and the agent will make a best effort to
|
|
|
|
// ensure it is registered. The Check may include a CheckType which
|
|
|
|
// is used to automatically update the check status
|
2017-06-15 16:46:06 +00:00
|
|
|
func (a *Agent) AddCheck(check *structs.HealthCheck, chkType *structs.CheckType, persist bool, token string) error {
|
2014-01-30 21:39:02 +00:00
|
|
|
if check.CheckID == "" {
|
|
|
|
return fmt.Errorf("CheckID missing")
|
|
|
|
}
|
2017-07-17 18:20:35 +00:00
|
|
|
|
|
|
|
if chkType != nil {
|
2017-10-10 23:54:06 +00:00
|
|
|
if err := chkType.Validate(); err != nil {
|
|
|
|
return fmt.Errorf("Check is not valid: %v", err)
|
2017-07-17 18:20:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if chkType.IsScript() && !a.config.EnableScriptChecks {
|
2017-07-20 05:15:04 +00:00
|
|
|
return fmt.Errorf("Scripts are disabled on this agent; to enable, configure 'enable_script_checks' to true")
|
2017-07-17 18:20:35 +00:00
|
|
|
}
|
2014-01-30 21:39:02 +00:00
|
|
|
}
|
|
|
|
|
2015-01-14 01:52:17 +00:00
|
|
|
if check.ServiceID != "" {
|
2017-08-28 12:17:13 +00:00
|
|
|
s := a.State.Service(check.ServiceID)
|
2017-08-28 12:17:11 +00:00
|
|
|
if s == nil {
|
2015-01-14 01:52:17 +00:00
|
|
|
return fmt.Errorf("ServiceID %q does not exist", check.ServiceID)
|
|
|
|
}
|
2017-08-28 12:17:11 +00:00
|
|
|
check.ServiceName = s.Service
|
2015-01-14 01:52:17 +00:00
|
|
|
}
|
|
|
|
|
2014-01-30 21:39:02 +00:00
|
|
|
a.checkLock.Lock()
|
|
|
|
defer a.checkLock.Unlock()
|
|
|
|
|
|
|
|
// Check if already registered
|
|
|
|
if chkType != nil {
|
2017-07-12 14:01:42 +00:00
|
|
|
switch {
|
|
|
|
|
|
|
|
case chkType.IsTTL():
|
2014-06-17 23:48:19 +00:00
|
|
|
if existing, ok := a.checkTTLs[check.CheckID]; ok {
|
|
|
|
existing.Stop()
|
2017-07-12 14:01:42 +00:00
|
|
|
delete(a.checkTTLs, check.CheckID)
|
2014-01-30 21:39:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
ttl := &CheckTTL{
|
2017-08-28 12:17:13 +00:00
|
|
|
Notify: a.State,
|
2014-01-30 21:39:02 +00:00
|
|
|
CheckID: check.CheckID,
|
|
|
|
TTL: chkType.TTL,
|
|
|
|
Logger: a.logger,
|
|
|
|
}
|
2015-06-05 23:17:07 +00:00
|
|
|
|
|
|
|
// Restore persisted state, if any
|
2015-06-08 16:35:10 +00:00
|
|
|
if err := a.loadCheckState(check); err != nil {
|
2015-06-05 23:17:07 +00:00
|
|
|
a.logger.Printf("[WARN] agent: failed restoring state for check %q: %s",
|
|
|
|
check.CheckID, err)
|
|
|
|
}
|
|
|
|
|
2014-01-30 21:39:02 +00:00
|
|
|
ttl.Start()
|
|
|
|
a.checkTTLs[check.CheckID] = ttl
|
|
|
|
|
2017-07-12 14:01:42 +00:00
|
|
|
case chkType.IsHTTP():
|
2015-01-09 22:43:24 +00:00
|
|
|
if existing, ok := a.checkHTTPs[check.CheckID]; ok {
|
|
|
|
existing.Stop()
|
2017-07-12 14:01:42 +00:00
|
|
|
delete(a.checkHTTPs, check.CheckID)
|
2015-01-09 22:43:24 +00:00
|
|
|
}
|
|
|
|
if chkType.Interval < MinInterval {
|
|
|
|
a.logger.Println(fmt.Sprintf("[WARN] agent: check '%s' has interval below minimum of %v",
|
|
|
|
check.CheckID, MinInterval))
|
|
|
|
chkType.Interval = MinInterval
|
|
|
|
}
|
|
|
|
|
|
|
|
http := &CheckHTTP{
|
2017-08-28 12:17:13 +00:00
|
|
|
Notify: a.State,
|
2016-11-03 20:17:30 +00:00
|
|
|
CheckID: check.CheckID,
|
|
|
|
HTTP: chkType.HTTP,
|
2017-06-06 23:11:56 +00:00
|
|
|
Header: chkType.Header,
|
|
|
|
Method: chkType.Method,
|
2016-11-03 20:17:30 +00:00
|
|
|
Interval: chkType.Interval,
|
|
|
|
Timeout: chkType.Timeout,
|
|
|
|
Logger: a.logger,
|
|
|
|
TLSSkipVerify: chkType.TLSSkipVerify,
|
2015-01-09 22:43:24 +00:00
|
|
|
}
|
|
|
|
http.Start()
|
|
|
|
a.checkHTTPs[check.CheckID] = http
|
|
|
|
|
2017-07-12 14:01:42 +00:00
|
|
|
case chkType.IsTCP():
|
2015-07-23 11:45:08 +00:00
|
|
|
if existing, ok := a.checkTCPs[check.CheckID]; ok {
|
|
|
|
existing.Stop()
|
2017-07-12 14:01:42 +00:00
|
|
|
delete(a.checkTCPs, check.CheckID)
|
2015-07-23 11:45:08 +00:00
|
|
|
}
|
|
|
|
if chkType.Interval < MinInterval {
|
|
|
|
a.logger.Println(fmt.Sprintf("[WARN] agent: check '%s' has interval below minimum of %v",
|
|
|
|
check.CheckID, MinInterval))
|
|
|
|
chkType.Interval = MinInterval
|
|
|
|
}
|
|
|
|
|
|
|
|
tcp := &CheckTCP{
|
2017-08-28 12:17:13 +00:00
|
|
|
Notify: a.State,
|
2015-07-23 11:45:08 +00:00
|
|
|
CheckID: check.CheckID,
|
|
|
|
TCP: chkType.TCP,
|
|
|
|
Interval: chkType.Interval,
|
|
|
|
Timeout: chkType.Timeout,
|
|
|
|
Logger: a.logger,
|
|
|
|
}
|
|
|
|
tcp.Start()
|
|
|
|
a.checkTCPs[check.CheckID] = tcp
|
|
|
|
|
2017-07-12 14:01:42 +00:00
|
|
|
case chkType.IsDocker():
|
2015-10-22 22:29:13 +00:00
|
|
|
if existing, ok := a.checkDockers[check.CheckID]; ok {
|
|
|
|
existing.Stop()
|
2017-07-12 14:01:42 +00:00
|
|
|
delete(a.checkDockers, check.CheckID)
|
2015-10-22 22:29:13 +00:00
|
|
|
}
|
|
|
|
if chkType.Interval < MinInterval {
|
|
|
|
a.logger.Println(fmt.Sprintf("[WARN] agent: check '%s' has interval below minimum of %v",
|
|
|
|
check.CheckID, MinInterval))
|
|
|
|
chkType.Interval = MinInterval
|
|
|
|
}
|
2017-10-05 04:41:27 +00:00
|
|
|
if chkType.Script != "" {
|
|
|
|
a.logger.Printf("[WARN] agent: check %q has the 'script' field, which has been deprecated "+
|
|
|
|
"and replaced with the 'args' field. See https://www.consul.io/docs/agent/checks.html",
|
|
|
|
check.CheckID)
|
|
|
|
}
|
2015-10-22 22:29:13 +00:00
|
|
|
|
2017-07-12 14:01:42 +00:00
|
|
|
if a.dockerClient == nil {
|
|
|
|
dc, err := NewDockerClient(os.Getenv("DOCKER_HOST"), CheckBufSize)
|
|
|
|
if err != nil {
|
|
|
|
a.logger.Printf("[ERR] agent: error creating docker client: %s", err)
|
|
|
|
return err
|
|
|
|
}
|
2017-07-19 09:53:38 +00:00
|
|
|
a.logger.Printf("[DEBUG] agent: created docker client for %s", dc.host)
|
2017-07-12 14:01:42 +00:00
|
|
|
a.dockerClient = dc
|
|
|
|
}
|
|
|
|
|
2015-10-22 22:29:13 +00:00
|
|
|
dockerCheck := &CheckDocker{
|
2017-08-28 12:17:13 +00:00
|
|
|
Notify: a.State,
|
2015-10-22 22:29:13 +00:00
|
|
|
CheckID: check.CheckID,
|
2015-11-18 15:40:02 +00:00
|
|
|
DockerContainerID: chkType.DockerContainerID,
|
2015-10-22 22:29:13 +00:00
|
|
|
Shell: chkType.Shell,
|
|
|
|
Script: chkType.Script,
|
2017-10-04 23:48:00 +00:00
|
|
|
ScriptArgs: chkType.ScriptArgs,
|
2015-10-22 22:29:13 +00:00
|
|
|
Interval: chkType.Interval,
|
|
|
|
Logger: a.logger,
|
2017-07-12 14:01:42 +00:00
|
|
|
client: a.dockerClient,
|
2015-10-26 23:45:12 +00:00
|
|
|
}
|
2015-10-22 22:29:13 +00:00
|
|
|
dockerCheck.Start()
|
|
|
|
a.checkDockers[check.CheckID] = dockerCheck
|
2017-07-12 14:01:42 +00:00
|
|
|
|
|
|
|
case chkType.IsMonitor():
|
2015-10-26 22:02:23 +00:00
|
|
|
if existing, ok := a.checkMonitors[check.CheckID]; ok {
|
|
|
|
existing.Stop()
|
2017-07-12 14:01:42 +00:00
|
|
|
delete(a.checkMonitors, check.CheckID)
|
2015-10-26 22:02:23 +00:00
|
|
|
}
|
|
|
|
if chkType.Interval < MinInterval {
|
2017-10-04 23:48:00 +00:00
|
|
|
a.logger.Printf("[WARN] agent: check '%s' has interval below minimum of %v",
|
|
|
|
check.CheckID, MinInterval)
|
2015-10-26 22:02:23 +00:00
|
|
|
chkType.Interval = MinInterval
|
|
|
|
}
|
2017-10-04 23:48:00 +00:00
|
|
|
if chkType.Script != "" {
|
|
|
|
a.logger.Printf("[WARN] agent: check %q has the 'script' field, which has been deprecated "+
|
|
|
|
"and replaced with the 'args' field. See https://www.consul.io/docs/agent/checks.html",
|
|
|
|
check.CheckID)
|
|
|
|
}
|
2015-10-26 22:02:23 +00:00
|
|
|
|
|
|
|
monitor := &CheckMonitor{
|
2017-08-28 12:17:13 +00:00
|
|
|
Notify: a.State,
|
2017-10-04 23:48:00 +00:00
|
|
|
CheckID: check.CheckID,
|
|
|
|
Script: chkType.Script,
|
|
|
|
ScriptArgs: chkType.ScriptArgs,
|
|
|
|
Interval: chkType.Interval,
|
|
|
|
Timeout: chkType.Timeout,
|
|
|
|
Logger: a.logger,
|
2015-10-26 22:02:23 +00:00
|
|
|
}
|
|
|
|
monitor.Start()
|
|
|
|
a.checkMonitors[check.CheckID] = monitor
|
2017-07-12 14:01:42 +00:00
|
|
|
|
|
|
|
default:
|
2015-10-27 02:52:32 +00:00
|
|
|
return fmt.Errorf("Check type is not valid")
|
2014-01-30 21:39:02 +00:00
|
|
|
}
|
2016-08-16 07:05:55 +00:00
|
|
|
|
|
|
|
if chkType.DeregisterCriticalServiceAfter > 0 {
|
|
|
|
timeout := chkType.DeregisterCriticalServiceAfter
|
|
|
|
if timeout < a.config.CheckDeregisterIntervalMin {
|
|
|
|
timeout = a.config.CheckDeregisterIntervalMin
|
|
|
|
a.logger.Println(fmt.Sprintf("[WARN] agent: check '%s' has deregister interval below minimum of %v",
|
|
|
|
check.CheckID, a.config.CheckDeregisterIntervalMin))
|
|
|
|
}
|
|
|
|
a.checkReapAfter[check.CheckID] = timeout
|
|
|
|
} else {
|
|
|
|
delete(a.checkReapAfter, check.CheckID)
|
|
|
|
}
|
2014-01-30 21:39:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add to the local state for anti-entropy
|
2017-08-28 12:17:13 +00:00
|
|
|
err := a.State.AddCheck(check, token)
|
2017-07-18 21:06:37 +00:00
|
|
|
if err != nil {
|
2017-07-18 21:54:20 +00:00
|
|
|
a.cancelCheckMonitors(check.CheckID)
|
2017-07-18 21:06:37 +00:00
|
|
|
return err
|
|
|
|
}
|
2014-11-24 08:36:03 +00:00
|
|
|
|
|
|
|
// Persist the check
|
2015-11-29 04:40:05 +00:00
|
|
|
if persist && !a.config.DevMode {
|
2014-11-29 20:25:01 +00:00
|
|
|
return a.persistCheck(check, chkType)
|
2014-11-25 03:24:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2014-01-30 21:39:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveCheck is used to remove a health check.
|
|
|
|
// The agent will make a best effort to ensure it is deregistered
|
2016-06-06 20:19:31 +00:00
|
|
|
func (a *Agent) RemoveCheck(checkID types.CheckID, persist bool) error {
|
2015-01-26 16:06:49 +00:00
|
|
|
// Validate CheckID
|
|
|
|
if checkID == "" {
|
|
|
|
return fmt.Errorf("CheckID missing")
|
|
|
|
}
|
|
|
|
|
2014-01-30 21:39:02 +00:00
|
|
|
// Add to the local state for anti-entropy
|
2017-08-28 12:17:13 +00:00
|
|
|
a.State.RemoveCheck(checkID)
|
2014-01-30 21:39:02 +00:00
|
|
|
|
|
|
|
a.checkLock.Lock()
|
|
|
|
defer a.checkLock.Unlock()
|
|
|
|
|
2017-07-18 21:54:20 +00:00
|
|
|
a.cancelCheckMonitors(checkID)
|
|
|
|
|
|
|
|
if persist {
|
|
|
|
if err := a.purgeCheck(checkID); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := a.purgeCheckState(checkID); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
a.logger.Printf("[DEBUG] agent: removed check %q", checkID)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *Agent) cancelCheckMonitors(checkID types.CheckID) {
|
2014-01-30 21:39:02 +00:00
|
|
|
// Stop any monitors
|
2016-08-16 07:05:55 +00:00
|
|
|
delete(a.checkReapAfter, checkID)
|
2014-01-30 21:39:02 +00:00
|
|
|
if check, ok := a.checkMonitors[checkID]; ok {
|
|
|
|
check.Stop()
|
|
|
|
delete(a.checkMonitors, checkID)
|
|
|
|
}
|
2015-01-12 22:34:39 +00:00
|
|
|
if check, ok := a.checkHTTPs[checkID]; ok {
|
|
|
|
check.Stop()
|
|
|
|
delete(a.checkHTTPs, checkID)
|
|
|
|
}
|
2015-07-23 11:45:08 +00:00
|
|
|
if check, ok := a.checkTCPs[checkID]; ok {
|
|
|
|
check.Stop()
|
|
|
|
delete(a.checkTCPs, checkID)
|
|
|
|
}
|
2014-01-30 21:39:02 +00:00
|
|
|
if check, ok := a.checkTTLs[checkID]; ok {
|
|
|
|
check.Stop()
|
|
|
|
delete(a.checkTTLs, checkID)
|
|
|
|
}
|
2017-07-18 18:50:37 +00:00
|
|
|
if check, ok := a.checkDockers[checkID]; ok {
|
|
|
|
check.Stop()
|
|
|
|
delete(a.checkDockers, checkID)
|
|
|
|
}
|
2014-01-30 21:39:02 +00:00
|
|
|
}
|
|
|
|
|
2016-08-16 07:05:55 +00:00
|
|
|
// updateTTLCheck is used to update the status of a TTL check via the Agent API.
|
|
|
|
func (a *Agent) updateTTLCheck(checkID types.CheckID, status, output string) error {
|
2014-01-30 21:39:02 +00:00
|
|
|
a.checkLock.Lock()
|
|
|
|
defer a.checkLock.Unlock()
|
|
|
|
|
2016-08-16 07:05:55 +00:00
|
|
|
// Grab the TTL check.
|
2014-01-30 21:39:02 +00:00
|
|
|
check, ok := a.checkTTLs[checkID]
|
|
|
|
if !ok {
|
2016-06-20 22:25:21 +00:00
|
|
|
return fmt.Errorf("CheckID %q does not have associated TTL", checkID)
|
2014-01-30 21:39:02 +00:00
|
|
|
}
|
|
|
|
|
2016-08-16 07:05:55 +00:00
|
|
|
// Set the status through CheckTTL to reset the TTL.
|
2014-01-30 21:39:02 +00:00
|
|
|
check.SetStatus(status, output)
|
2015-06-05 23:17:07 +00:00
|
|
|
|
2016-08-16 07:05:55 +00:00
|
|
|
// We don't write any files in dev mode so bail here.
|
2015-11-29 04:40:05 +00:00
|
|
|
if a.config.DevMode {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-08-16 07:05:55 +00:00
|
|
|
// Persist the state so the TTL check can come up in a good state after
|
|
|
|
// an agent restart, especially with long TTL values.
|
2015-06-05 23:17:07 +00:00
|
|
|
if err := a.persistCheckState(check, status, output); err != nil {
|
|
|
|
return fmt.Errorf("failed persisting state for check %q: %s", checkID, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// persistCheckState is used to record the check status into the data dir.
|
|
|
|
// This allows the state to be restored on a later agent start. Currently
|
|
|
|
// only useful for TTL based checks.
|
|
|
|
func (a *Agent) persistCheckState(check *CheckTTL, status, output string) error {
|
|
|
|
// Create the persisted state
|
|
|
|
state := persistedCheckState{
|
|
|
|
CheckID: check.CheckID,
|
|
|
|
Status: status,
|
|
|
|
Output: output,
|
|
|
|
Expires: time.Now().Add(check.TTL).Unix(),
|
|
|
|
}
|
|
|
|
|
|
|
|
// Encode the state
|
|
|
|
buf, err := json.Marshal(state)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the state dir if it doesn't exist
|
|
|
|
dir := filepath.Join(a.config.DataDir, checkStateDir)
|
|
|
|
if err := os.MkdirAll(dir, 0700); err != nil {
|
|
|
|
return fmt.Errorf("failed creating check state dir %q: %s", dir, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write the state to the file
|
2016-06-06 08:53:30 +00:00
|
|
|
file := filepath.Join(dir, checkIDHash(check.CheckID))
|
2016-11-07 18:51:03 +00:00
|
|
|
|
|
|
|
// Create temp file in same dir, to make more likely atomic
|
2016-08-03 15:32:21 +00:00
|
|
|
tempFile := file + ".tmp"
|
|
|
|
|
2016-11-07 20:24:31 +00:00
|
|
|
// persistCheckState is called frequently, so don't use writeFileAtomic to avoid calling fsync here
|
2016-08-03 15:32:21 +00:00
|
|
|
if err := ioutil.WriteFile(tempFile, buf, 0600); err != nil {
|
|
|
|
return fmt.Errorf("failed writing temp file %q: %s", tempFile, err)
|
|
|
|
}
|
|
|
|
if err := os.Rename(tempFile, file); err != nil {
|
|
|
|
return fmt.Errorf("failed to rename temp file from %q to %q: %s", tempFile, file, err)
|
2015-06-05 23:17:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-06-08 16:35:10 +00:00
|
|
|
// loadCheckState is used to restore the persisted state of a check.
|
|
|
|
func (a *Agent) loadCheckState(check *structs.HealthCheck) error {
|
2015-06-05 23:17:07 +00:00
|
|
|
// Try to read the persisted state for this check
|
2016-06-06 08:53:30 +00:00
|
|
|
file := filepath.Join(a.config.DataDir, checkStateDir, checkIDHash(check.CheckID))
|
2015-06-05 23:17:07 +00:00
|
|
|
buf, err := ioutil.ReadFile(file)
|
|
|
|
if err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return fmt.Errorf("failed reading file %q: %s", file, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Decode the state data
|
|
|
|
var p persistedCheckState
|
|
|
|
if err := json.Unmarshal(buf, &p); err != nil {
|
2017-06-08 07:50:47 +00:00
|
|
|
a.logger.Printf("[ERR] agent: failed decoding check state: %s", err)
|
2016-11-07 18:51:03 +00:00
|
|
|
return a.purgeCheckState(check.CheckID)
|
2015-06-05 23:17:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Check if the state has expired
|
2015-06-05 23:45:05 +00:00
|
|
|
if time.Now().Unix() >= p.Expires {
|
2015-06-05 23:17:07 +00:00
|
|
|
a.logger.Printf("[DEBUG] agent: check state expired for %q, not restoring", check.CheckID)
|
2015-06-05 23:59:41 +00:00
|
|
|
return a.purgeCheckState(check.CheckID)
|
2015-06-05 23:17:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Restore the fields from the state
|
|
|
|
check.Output = p.Output
|
|
|
|
check.Status = p.Status
|
2014-01-30 21:39:02 +00:00
|
|
|
return nil
|
|
|
|
}
|
2014-02-24 00:42:39 +00:00
|
|
|
|
2015-06-05 23:57:14 +00:00
|
|
|
// purgeCheckState is used to purge the state of a check from the data dir
|
2016-06-06 20:19:31 +00:00
|
|
|
func (a *Agent) purgeCheckState(checkID types.CheckID) error {
|
2016-06-06 08:53:30 +00:00
|
|
|
file := filepath.Join(a.config.DataDir, checkStateDir, checkIDHash(checkID))
|
2015-06-05 23:57:14 +00:00
|
|
|
err := os.Remove(file)
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-06-02 09:35:59 +00:00
|
|
|
func (a *Agent) GossipEncrypted() bool {
|
|
|
|
return a.delegate.Encrypted()
|
|
|
|
}
|
|
|
|
|
2014-02-24 00:42:39 +00:00
|
|
|
// Stats is used to get various debugging state from the sub-systems
|
|
|
|
func (a *Agent) Stats() map[string]map[string]string {
|
2017-05-15 14:05:17 +00:00
|
|
|
stats := a.delegate.Stats()
|
2014-02-24 00:42:39 +00:00
|
|
|
stats["agent"] = map[string]string{
|
2017-08-28 12:17:12 +00:00
|
|
|
"check_monitors": strconv.Itoa(len(a.checkMonitors)),
|
|
|
|
"check_ttls": strconv.Itoa(len(a.checkTTLs)),
|
|
|
|
}
|
2017-08-28 12:17:13 +00:00
|
|
|
for k, v := range a.State.Stats() {
|
2017-08-28 12:17:12 +00:00
|
|
|
stats["agent"][k] = v
|
2014-02-24 00:42:39 +00:00
|
|
|
}
|
2014-06-06 21:40:22 +00:00
|
|
|
|
|
|
|
revision := a.config.Revision
|
|
|
|
if len(revision) > 8 {
|
|
|
|
revision = revision[:8]
|
|
|
|
}
|
|
|
|
stats["build"] = map[string]string{
|
|
|
|
"revision": revision,
|
|
|
|
"version": a.config.Version,
|
|
|
|
"prerelease": a.config.VersionPrerelease,
|
|
|
|
}
|
2014-02-24 00:42:39 +00:00
|
|
|
return stats
|
|
|
|
}
|
2014-05-06 03:29:50 +00:00
|
|
|
|
2014-05-06 19:43:33 +00:00
|
|
|
// storePid is used to write out our PID to a file if necessary
|
2014-05-06 16:57:53 +00:00
|
|
|
func (a *Agent) storePid() error {
|
2014-05-06 19:43:33 +00:00
|
|
|
// Quit fast if no pidfile
|
2014-05-06 03:29:50 +00:00
|
|
|
pidPath := a.config.PidFile
|
2014-05-06 19:43:33 +00:00
|
|
|
if pidPath == "" {
|
|
|
|
return nil
|
|
|
|
}
|
2014-05-06 03:29:50 +00:00
|
|
|
|
2014-05-06 19:43:33 +00:00
|
|
|
// Open the PID file
|
|
|
|
pidFile, err := os.OpenFile(pidPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Could not open pid file: %v", err)
|
2014-05-06 03:29:50 +00:00
|
|
|
}
|
2014-05-06 19:43:33 +00:00
|
|
|
defer pidFile.Close()
|
2014-05-06 16:57:53 +00:00
|
|
|
|
2014-05-06 19:43:33 +00:00
|
|
|
// Write out the PID
|
|
|
|
pid := os.Getpid()
|
|
|
|
_, err = pidFile.WriteString(fmt.Sprintf("%d", pid))
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Could not write to pid file: %s", err)
|
|
|
|
}
|
2014-05-06 16:57:53 +00:00
|
|
|
return nil
|
2014-05-06 03:29:50 +00:00
|
|
|
}
|
|
|
|
|
2014-05-06 19:43:33 +00:00
|
|
|
// deletePid is used to delete our PID on exit
|
2014-05-06 16:57:53 +00:00
|
|
|
func (a *Agent) deletePid() error {
|
2014-05-06 19:43:33 +00:00
|
|
|
// Quit fast if no pidfile
|
2014-05-06 03:29:50 +00:00
|
|
|
pidPath := a.config.PidFile
|
2014-05-06 19:43:33 +00:00
|
|
|
if pidPath == "" {
|
|
|
|
return nil
|
|
|
|
}
|
2014-05-06 03:29:50 +00:00
|
|
|
|
2014-05-06 19:43:33 +00:00
|
|
|
stat, err := os.Stat(pidPath)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Could not remove pid file: %s", err)
|
|
|
|
}
|
2014-05-06 03:29:50 +00:00
|
|
|
|
2014-05-06 19:43:33 +00:00
|
|
|
if stat.IsDir() {
|
|
|
|
return fmt.Errorf("Specified pid file path is directory")
|
2014-05-06 03:29:50 +00:00
|
|
|
}
|
2014-05-06 16:57:53 +00:00
|
|
|
|
2014-05-06 19:43:33 +00:00
|
|
|
err = os.Remove(pidPath)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Could not remove pid file: %s", err)
|
|
|
|
}
|
2014-05-06 16:57:53 +00:00
|
|
|
return nil
|
2014-05-06 03:29:50 +00:00
|
|
|
}
|
2014-11-26 07:58:02 +00:00
|
|
|
|
2015-01-08 02:05:46 +00:00
|
|
|
// loadServices will load service definitions from configuration and persisted
|
|
|
|
// definitions on disk, and load them into the local agent.
|
2017-09-25 18:40:42 +00:00
|
|
|
func (a *Agent) loadServices(conf *config.RuntimeConfig) error {
|
2014-11-26 07:58:02 +00:00
|
|
|
// Register the services from config
|
|
|
|
for _, service := range conf.Services {
|
|
|
|
ns := service.NodeService()
|
2017-10-10 23:54:06 +00:00
|
|
|
chkTypes, err := service.CheckTypes()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Failed to validate checks for service %q: %v", service.Name, err)
|
|
|
|
}
|
2015-05-05 00:36:17 +00:00
|
|
|
if err := a.AddService(ns, chkTypes, false, service.Token); err != nil {
|
2017-10-10 23:54:06 +00:00
|
|
|
return fmt.Errorf("Failed to register service %q: %v", service.Name, err)
|
2014-11-26 07:58:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Load any persisted services
|
2015-01-08 05:24:47 +00:00
|
|
|
svcDir := filepath.Join(a.config.DataDir, servicesDir)
|
2015-06-04 21:33:30 +00:00
|
|
|
files, err := ioutil.ReadDir(svcDir)
|
|
|
|
if err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return fmt.Errorf("Failed reading services dir %q: %s", svcDir, err)
|
2014-11-26 07:58:02 +00:00
|
|
|
}
|
2015-06-04 21:33:30 +00:00
|
|
|
for _, fi := range files {
|
|
|
|
// Skip all dirs
|
|
|
|
if fi.IsDir() {
|
|
|
|
continue
|
|
|
|
}
|
2014-11-26 07:58:02 +00:00
|
|
|
|
2017-07-24 17:37:14 +00:00
|
|
|
// Skip all partially written temporary files
|
|
|
|
if strings.HasSuffix(fi.Name(), "tmp") {
|
|
|
|
a.logger.Printf("[WARN] Ignoring temporary service file %v", fi.Name())
|
|
|
|
continue
|
|
|
|
}
|
2017-07-25 02:07:48 +00:00
|
|
|
|
2015-06-04 21:33:30 +00:00
|
|
|
// Open the file for reading
|
|
|
|
file := filepath.Join(svcDir, fi.Name())
|
|
|
|
fh, err := os.Open(file)
|
2015-01-08 05:24:47 +00:00
|
|
|
if err != nil {
|
2015-06-04 21:33:30 +00:00
|
|
|
return fmt.Errorf("failed opening service file %q: %s", file, err)
|
2015-01-08 05:24:47 +00:00
|
|
|
}
|
2015-06-04 21:33:30 +00:00
|
|
|
|
|
|
|
// Read the contents into a buffer
|
|
|
|
buf, err := ioutil.ReadAll(fh)
|
|
|
|
fh.Close()
|
2015-01-08 05:24:47 +00:00
|
|
|
if err != nil {
|
2015-06-04 21:33:30 +00:00
|
|
|
return fmt.Errorf("failed reading service file %q: %s", file, err)
|
2015-01-08 05:24:47 +00:00
|
|
|
}
|
|
|
|
|
2015-06-04 21:33:30 +00:00
|
|
|
// Try decoding the service definition
|
|
|
|
var p persistedService
|
|
|
|
if err := json.Unmarshal(buf, &p); err != nil {
|
2015-04-28 19:18:41 +00:00
|
|
|
// Backwards-compatibility for pre-0.5.1 persisted services
|
2015-06-04 21:33:30 +00:00
|
|
|
if err := json.Unmarshal(buf, &p.Service); err != nil {
|
|
|
|
return fmt.Errorf("failed decoding service file %q: %s", file, err)
|
2015-04-28 19:18:41 +00:00
|
|
|
}
|
2015-01-08 05:24:47 +00:00
|
|
|
}
|
2015-06-04 21:33:30 +00:00
|
|
|
serviceID := p.Service.ID
|
2015-01-08 05:24:47 +00:00
|
|
|
|
2017-08-28 12:17:13 +00:00
|
|
|
if a.State.Service(serviceID) != nil {
|
2015-01-08 05:24:47 +00:00
|
|
|
// Purge previously persisted service. This allows config to be
|
|
|
|
// preferred over services persisted from the API.
|
2015-01-08 06:26:40 +00:00
|
|
|
a.logger.Printf("[DEBUG] agent: service %q exists, not restoring from %q",
|
2015-06-04 21:33:30 +00:00
|
|
|
serviceID, file)
|
|
|
|
if err := a.purgeService(serviceID); err != nil {
|
|
|
|
return fmt.Errorf("failed purging service %q: %s", serviceID, err)
|
|
|
|
}
|
2015-01-08 05:24:47 +00:00
|
|
|
} else {
|
2015-01-08 06:26:40 +00:00
|
|
|
a.logger.Printf("[DEBUG] agent: restored service definition %q from %q",
|
2015-06-04 21:33:30 +00:00
|
|
|
serviceID, file)
|
|
|
|
if err := a.AddService(p.Service, nil, false, p.Token); err != nil {
|
|
|
|
return fmt.Errorf("failed adding service %q: %s", serviceID, err)
|
|
|
|
}
|
2015-01-08 05:24:47 +00:00
|
|
|
}
|
2015-06-04 21:33:30 +00:00
|
|
|
}
|
2015-01-08 05:24:47 +00:00
|
|
|
|
2015-06-04 21:33:30 +00:00
|
|
|
return nil
|
2014-11-26 07:58:02 +00:00
|
|
|
}
|
|
|
|
|
2015-01-08 02:05:46 +00:00
|
|
|
// unloadServices will deregister all services other than the 'consul' service
|
|
|
|
// known to the local agent.
|
|
|
|
func (a *Agent) unloadServices() error {
|
2017-08-28 12:17:13 +00:00
|
|
|
for id := range a.State.Services() {
|
2017-08-28 12:17:11 +00:00
|
|
|
if err := a.RemoveService(id, false); err != nil {
|
|
|
|
return fmt.Errorf("Failed deregistering service '%s': %v", id, err)
|
2014-11-26 07:58:02 +00:00
|
|
|
}
|
|
|
|
}
|
2015-01-08 02:05:46 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// loadChecks loads check definitions and/or persisted check definitions from
|
|
|
|
// disk and re-registers them with the local agent.
|
2017-09-25 18:40:42 +00:00
|
|
|
func (a *Agent) loadChecks(conf *config.RuntimeConfig) error {
|
2014-11-26 07:58:02 +00:00
|
|
|
// Register the checks from config
|
|
|
|
for _, check := range conf.Checks {
|
|
|
|
health := check.HealthCheck(conf.NodeName)
|
2017-05-15 19:49:13 +00:00
|
|
|
chkType := check.CheckType()
|
2015-05-05 00:36:17 +00:00
|
|
|
if err := a.AddCheck(health, chkType, false, check.Token); err != nil {
|
2014-11-26 07:58:02 +00:00
|
|
|
return fmt.Errorf("Failed to register check '%s': %v %v", check.Name, err, check)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Load any persisted checks
|
2015-01-08 05:24:47 +00:00
|
|
|
checkDir := filepath.Join(a.config.DataDir, checksDir)
|
2015-06-04 21:33:30 +00:00
|
|
|
files, err := ioutil.ReadDir(checkDir)
|
|
|
|
if err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return fmt.Errorf("Failed reading checks dir %q: %s", checkDir, err)
|
2014-11-26 07:58:02 +00:00
|
|
|
}
|
2015-06-04 21:33:30 +00:00
|
|
|
for _, fi := range files {
|
|
|
|
// Ignore dirs - we only care about the check definition files
|
|
|
|
if fi.IsDir() {
|
|
|
|
continue
|
|
|
|
}
|
2014-11-26 07:58:02 +00:00
|
|
|
|
2015-06-04 21:33:30 +00:00
|
|
|
// Open the file for reading
|
|
|
|
file := filepath.Join(checkDir, fi.Name())
|
|
|
|
fh, err := os.Open(file)
|
2015-01-08 05:24:47 +00:00
|
|
|
if err != nil {
|
2015-06-04 21:33:30 +00:00
|
|
|
return fmt.Errorf("Failed opening check file %q: %s", file, err)
|
2015-01-08 05:24:47 +00:00
|
|
|
}
|
2015-06-04 21:33:30 +00:00
|
|
|
|
|
|
|
// Read the contents into a buffer
|
|
|
|
buf, err := ioutil.ReadAll(fh)
|
|
|
|
fh.Close()
|
2015-01-08 05:24:47 +00:00
|
|
|
if err != nil {
|
2015-06-04 21:33:30 +00:00
|
|
|
return fmt.Errorf("failed reading check file %q: %s", file, err)
|
2015-01-08 05:24:47 +00:00
|
|
|
}
|
|
|
|
|
2015-06-04 21:33:30 +00:00
|
|
|
// Decode the check
|
2015-01-08 05:24:47 +00:00
|
|
|
var p persistedCheck
|
2015-06-04 21:33:30 +00:00
|
|
|
if err := json.Unmarshal(buf, &p); err != nil {
|
|
|
|
return fmt.Errorf("Failed decoding check file %q: %s", file, err)
|
2015-01-08 05:24:47 +00:00
|
|
|
}
|
2015-06-04 21:33:30 +00:00
|
|
|
checkID := p.Check.CheckID
|
2015-01-08 05:24:47 +00:00
|
|
|
|
2017-08-28 12:17:13 +00:00
|
|
|
if a.State.Check(checkID) != nil {
|
2015-01-08 05:24:47 +00:00
|
|
|
// Purge previously persisted check. This allows config to be
|
|
|
|
// preferred over persisted checks from the API.
|
2015-01-08 06:26:40 +00:00
|
|
|
a.logger.Printf("[DEBUG] agent: check %q exists, not restoring from %q",
|
2015-06-04 21:33:30 +00:00
|
|
|
checkID, file)
|
|
|
|
if err := a.purgeCheck(checkID); err != nil {
|
|
|
|
return fmt.Errorf("Failed purging check %q: %s", checkID, err)
|
|
|
|
}
|
2015-01-08 05:24:47 +00:00
|
|
|
} else {
|
|
|
|
// Default check to critical to avoid placing potentially unhealthy
|
|
|
|
// services into the active pool
|
2017-04-19 23:00:11 +00:00
|
|
|
p.Check.Status = api.HealthCritical
|
2015-01-08 05:24:47 +00:00
|
|
|
|
2015-05-05 00:36:17 +00:00
|
|
|
if err := a.AddCheck(p.Check, p.ChkType, false, p.Token); err != nil {
|
2015-03-11 23:13:19 +00:00
|
|
|
// Purge the check if it is unable to be restored.
|
|
|
|
a.logger.Printf("[WARN] agent: Failed to restore check %q: %s",
|
2015-06-04 21:33:30 +00:00
|
|
|
checkID, err)
|
|
|
|
if err := a.purgeCheck(checkID); err != nil {
|
|
|
|
return fmt.Errorf("Failed purging check %q: %s", checkID, err)
|
|
|
|
}
|
2015-03-11 23:13:19 +00:00
|
|
|
}
|
2015-01-08 06:26:40 +00:00
|
|
|
a.logger.Printf("[DEBUG] agent: restored health check %q from %q",
|
2015-06-04 21:33:30 +00:00
|
|
|
p.Check.CheckID, file)
|
2015-01-08 05:24:47 +00:00
|
|
|
}
|
2015-06-04 21:33:30 +00:00
|
|
|
}
|
2015-01-08 05:24:47 +00:00
|
|
|
|
2015-06-04 21:33:30 +00:00
|
|
|
return nil
|
2014-11-26 07:58:02 +00:00
|
|
|
}
|
2015-01-08 02:05:46 +00:00
|
|
|
|
|
|
|
// unloadChecks will deregister all checks known to the local agent.
|
|
|
|
func (a *Agent) unloadChecks() error {
|
2017-08-28 12:17:13 +00:00
|
|
|
for id := range a.State.Checks() {
|
2017-08-28 12:17:11 +00:00
|
|
|
if err := a.RemoveCheck(id, false); err != nil {
|
|
|
|
return fmt.Errorf("Failed deregistering check '%s': %s", id, err)
|
2015-01-08 02:05:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2015-01-15 08:16:34 +00:00
|
|
|
|
2015-02-17 20:00:04 +00:00
|
|
|
// snapshotCheckState is used to snapshot the current state of the health
|
|
|
|
// checks. This is done before we reload our checks, so that we can properly
|
|
|
|
// restore into the same state.
|
2016-06-06 20:19:31 +00:00
|
|
|
func (a *Agent) snapshotCheckState() map[types.CheckID]*structs.HealthCheck {
|
2017-08-28 12:17:13 +00:00
|
|
|
return a.State.Checks()
|
2015-02-17 20:00:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// restoreCheckState is used to reset the health state based on a snapshot.
|
|
|
|
// This is done after we finish the reload to avoid any unnecessary flaps
|
|
|
|
// in health state and potential session invalidations.
|
2016-06-06 20:19:31 +00:00
|
|
|
func (a *Agent) restoreCheckState(snap map[types.CheckID]*structs.HealthCheck) {
|
2015-02-17 20:00:04 +00:00
|
|
|
for id, check := range snap {
|
2017-08-28 12:17:13 +00:00
|
|
|
a.State.UpdateCheck(id, check.Status, check.Output)
|
2015-02-17 20:00:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-11 19:41:12 +00:00
|
|
|
// loadMetadata loads node metadata fields from the agent config and
|
2017-01-05 22:10:26 +00:00
|
|
|
// updates them on the local agent.
|
2017-09-25 18:40:42 +00:00
|
|
|
func (a *Agent) loadMetadata(conf *config.RuntimeConfig) error {
|
2017-08-28 12:17:12 +00:00
|
|
|
meta := map[string]string{}
|
|
|
|
for k, v := range conf.NodeMeta {
|
|
|
|
meta[k] = v
|
2017-01-11 19:41:12 +00:00
|
|
|
}
|
2017-08-28 12:17:12 +00:00
|
|
|
meta[structs.MetaSegmentKey] = conf.SegmentName
|
2017-08-28 12:17:13 +00:00
|
|
|
return a.State.LoadMetadata(meta)
|
2017-01-11 19:41:12 +00:00
|
|
|
}
|
|
|
|
|
2017-01-05 22:10:26 +00:00
|
|
|
// unloadMetadata resets the local metadata state
|
2017-01-11 19:41:12 +00:00
|
|
|
func (a *Agent) unloadMetadata() {
|
2017-08-28 12:17:13 +00:00
|
|
|
a.State.UnloadMetadata()
|
2017-01-05 22:10:26 +00:00
|
|
|
}
|
|
|
|
|
2015-01-15 20:20:57 +00:00
|
|
|
// serviceMaintCheckID returns the ID of a given service's maintenance check
|
2016-06-06 20:19:31 +00:00
|
|
|
func serviceMaintCheckID(serviceID string) types.CheckID {
|
2016-11-29 21:15:20 +00:00
|
|
|
return types.CheckID(structs.ServiceMaintPrefix + serviceID)
|
2015-01-15 20:20:57 +00:00
|
|
|
}
|
|
|
|
|
2015-01-15 08:25:36 +00:00
|
|
|
// EnableServiceMaintenance will register a false health check against the given
|
|
|
|
// service ID with critical status. This will exclude the service from queries.
|
2015-09-10 18:43:59 +00:00
|
|
|
func (a *Agent) EnableServiceMaintenance(serviceID, reason, token string) error {
|
2017-08-28 12:17:13 +00:00
|
|
|
service, ok := a.State.Services()[serviceID]
|
2015-01-15 18:51:00 +00:00
|
|
|
if !ok {
|
2015-01-15 08:16:34 +00:00
|
|
|
return fmt.Errorf("No service registered with ID %q", serviceID)
|
|
|
|
}
|
|
|
|
|
2015-01-15 20:20:57 +00:00
|
|
|
// Check if maintenance mode is not already enabled
|
|
|
|
checkID := serviceMaintCheckID(serviceID)
|
2017-08-28 12:17:13 +00:00
|
|
|
if _, ok := a.State.Checks()[checkID]; ok {
|
2015-01-15 18:51:00 +00:00
|
|
|
return nil
|
2015-01-15 08:16:34 +00:00
|
|
|
}
|
|
|
|
|
2015-01-21 20:21:57 +00:00
|
|
|
// Use default notes if no reason provided
|
|
|
|
if reason == "" {
|
2015-01-21 22:45:09 +00:00
|
|
|
reason = defaultServiceMaintReason
|
2015-01-21 20:21:57 +00:00
|
|
|
}
|
|
|
|
|
2015-01-15 08:16:34 +00:00
|
|
|
// Create and register the critical health check
|
|
|
|
check := &structs.HealthCheck{
|
|
|
|
Node: a.config.NodeName,
|
2015-01-15 20:20:57 +00:00
|
|
|
CheckID: checkID,
|
2015-01-15 08:16:34 +00:00
|
|
|
Name: "Service Maintenance Mode",
|
2015-01-21 20:21:57 +00:00
|
|
|
Notes: reason,
|
2015-01-15 08:16:34 +00:00
|
|
|
ServiceID: service.ID,
|
|
|
|
ServiceName: service.Service,
|
2017-04-19 23:00:11 +00:00
|
|
|
Status: api.HealthCritical,
|
2015-01-15 08:16:34 +00:00
|
|
|
}
|
2015-09-10 18:43:59 +00:00
|
|
|
a.AddCheck(check, nil, true, token)
|
2015-01-22 19:14:28 +00:00
|
|
|
a.logger.Printf("[INFO] agent: Service %q entered maintenance mode", serviceID)
|
2015-01-15 08:16:34 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-01-15 08:25:36 +00:00
|
|
|
// DisableServiceMaintenance will deregister the fake maintenance mode check
|
|
|
|
// if the service has been marked as in maintenance.
|
2015-01-15 08:16:34 +00:00
|
|
|
func (a *Agent) DisableServiceMaintenance(serviceID string) error {
|
2017-08-28 12:17:13 +00:00
|
|
|
if _, ok := a.State.Services()[serviceID]; !ok {
|
2015-01-15 08:16:34 +00:00
|
|
|
return fmt.Errorf("No service registered with ID %q", serviceID)
|
|
|
|
}
|
|
|
|
|
2015-01-15 20:20:57 +00:00
|
|
|
// Check if maintenance mode is enabled
|
|
|
|
checkID := serviceMaintCheckID(serviceID)
|
2017-08-28 12:17:13 +00:00
|
|
|
if _, ok := a.State.Checks()[checkID]; !ok {
|
2015-01-15 20:20:57 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-01-15 08:16:34 +00:00
|
|
|
// Deregister the maintenance check
|
2015-01-15 20:20:57 +00:00
|
|
|
a.RemoveCheck(checkID, true)
|
2015-01-22 19:14:28 +00:00
|
|
|
a.logger.Printf("[INFO] agent: Service %q left maintenance mode", serviceID)
|
2015-01-15 20:20:57 +00:00
|
|
|
|
2015-01-15 08:16:34 +00:00
|
|
|
return nil
|
|
|
|
}
|
2015-01-15 19:20:22 +00:00
|
|
|
|
|
|
|
// EnableNodeMaintenance places a node into maintenance mode.
|
2015-09-10 18:43:59 +00:00
|
|
|
func (a *Agent) EnableNodeMaintenance(reason, token string) {
|
2015-01-15 19:20:22 +00:00
|
|
|
// Ensure node maintenance is not already enabled
|
2017-08-28 12:17:13 +00:00
|
|
|
if _, ok := a.State.Checks()[structs.NodeMaint]; ok {
|
2015-01-15 19:20:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-01-21 20:21:57 +00:00
|
|
|
// Use a default notes value
|
|
|
|
if reason == "" {
|
2015-01-21 22:45:09 +00:00
|
|
|
reason = defaultNodeMaintReason
|
2015-01-21 20:21:57 +00:00
|
|
|
}
|
|
|
|
|
2015-01-15 19:20:22 +00:00
|
|
|
// Create and register the node maintenance check
|
|
|
|
check := &structs.HealthCheck{
|
|
|
|
Node: a.config.NodeName,
|
2016-11-29 21:15:20 +00:00
|
|
|
CheckID: structs.NodeMaint,
|
2015-01-15 19:20:22 +00:00
|
|
|
Name: "Node Maintenance Mode",
|
2015-01-21 20:21:57 +00:00
|
|
|
Notes: reason,
|
2017-04-19 23:00:11 +00:00
|
|
|
Status: api.HealthCritical,
|
2015-01-15 19:20:22 +00:00
|
|
|
}
|
2015-09-10 18:43:59 +00:00
|
|
|
a.AddCheck(check, nil, true, token)
|
2015-01-22 19:14:28 +00:00
|
|
|
a.logger.Printf("[INFO] agent: Node entered maintenance mode")
|
2015-01-15 19:20:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DisableNodeMaintenance removes a node from maintenance mode
|
|
|
|
func (a *Agent) DisableNodeMaintenance() {
|
2017-08-28 12:17:13 +00:00
|
|
|
if _, ok := a.State.Checks()[structs.NodeMaint]; !ok {
|
2015-01-15 20:20:57 +00:00
|
|
|
return
|
|
|
|
}
|
2016-11-29 21:15:20 +00:00
|
|
|
a.RemoveCheck(structs.NodeMaint, true)
|
2015-01-22 19:14:28 +00:00
|
|
|
a.logger.Printf("[INFO] agent: Node left maintenance mode")
|
2015-01-15 19:20:22 +00:00
|
|
|
}
|
2015-11-12 17:19:33 +00:00
|
|
|
|
2017-09-25 18:40:42 +00:00
|
|
|
func (a *Agent) ReloadConfig(newCfg *config.RuntimeConfig) error {
|
2017-06-02 12:56:49 +00:00
|
|
|
// Bulk update the services and checks
|
|
|
|
a.PauseSync()
|
|
|
|
defer a.ResumeSync()
|
|
|
|
|
|
|
|
// Snapshot the current state, and restore it afterwards
|
|
|
|
snap := a.snapshotCheckState()
|
|
|
|
defer a.restoreCheckState(snap)
|
|
|
|
|
|
|
|
// First unload all checks, services, and metadata. This lets us begin the reload
|
|
|
|
// with a clean slate.
|
|
|
|
if err := a.unloadServices(); err != nil {
|
2017-06-24 19:52:41 +00:00
|
|
|
return fmt.Errorf("Failed unloading services: %s", err)
|
2017-06-02 12:56:49 +00:00
|
|
|
}
|
|
|
|
if err := a.unloadChecks(); err != nil {
|
2017-06-24 19:52:41 +00:00
|
|
|
return fmt.Errorf("Failed unloading checks: %s", err)
|
2017-06-02 12:56:49 +00:00
|
|
|
}
|
|
|
|
a.unloadMetadata()
|
|
|
|
|
|
|
|
// Reload service/check definitions and metadata.
|
|
|
|
if err := a.loadServices(newCfg); err != nil {
|
2017-06-24 19:52:41 +00:00
|
|
|
return fmt.Errorf("Failed reloading services: %s", err)
|
2017-06-02 12:56:49 +00:00
|
|
|
}
|
|
|
|
if err := a.loadChecks(newCfg); err != nil {
|
2017-06-24 19:52:41 +00:00
|
|
|
return fmt.Errorf("Failed reloading checks: %s", err)
|
2017-06-02 12:56:49 +00:00
|
|
|
}
|
|
|
|
if err := a.loadMetadata(newCfg); err != nil {
|
2017-06-24 19:52:41 +00:00
|
|
|
return fmt.Errorf("Failed reloading metadata: %s", err)
|
2017-06-02 12:56:49 +00:00
|
|
|
}
|
|
|
|
|
2017-06-24 19:52:41 +00:00
|
|
|
if err := a.reloadWatches(newCfg); err != nil {
|
|
|
|
return fmt.Errorf("Failed reloading watches: %v", err)
|
2017-06-02 12:56:49 +00:00
|
|
|
}
|
|
|
|
|
2017-08-08 19:33:30 +00:00
|
|
|
// Update filtered metrics
|
2017-09-25 18:40:42 +00:00
|
|
|
metrics.UpdateFilter(newCfg.TelemetryAllowedPrefixes, newCfg.TelemetryBlockedPrefixes)
|
2017-08-08 19:33:30 +00:00
|
|
|
|
2017-08-28 12:17:13 +00:00
|
|
|
a.State.SetDiscardCheckOutput(newCfg.DiscardCheckOutput)
|
2017-10-11 00:04:52 +00:00
|
|
|
|
2017-06-24 19:52:41 +00:00
|
|
|
return nil
|
2017-06-02 12:56:49 +00:00
|
|
|
}
|