2016-06-13 23:29:07 +00:00
|
|
|
// Package consul is used by Nomad to register all services both static services
|
|
|
|
// and dynamic via allocations.
|
|
|
|
//
|
|
|
|
// Consul Service IDs have the following format: ${nomadServicePrefix}-${groupName}-${serviceKey}
|
|
|
|
// groupName takes on one of the following values:
|
|
|
|
// - server
|
|
|
|
// - client
|
|
|
|
// - executor-${alloc-id}-${task-name}
|
|
|
|
//
|
|
|
|
// serviceKey should be generated by service registrators.
|
|
|
|
// If the serviceKey is being generated by the executor for a Nomad Task.Services
|
|
|
|
// the following helper should be used:
|
|
|
|
// NOTE: Executor should interpolate the service prior to calling
|
|
|
|
// func GenerateTaskServiceKey(service *structs.Service) string
|
|
|
|
//
|
|
|
|
// The Nomad Client reaps services registered from dead allocations that were
|
|
|
|
// not properly cleaned up by the executor (this is not the expected case).
|
|
|
|
//
|
|
|
|
// TODO fix this comment
|
|
|
|
// The Consul ServiceIDs generated by the executor will contain the allocation
|
|
|
|
// ID. Thus the client can generate the list of Consul ServiceIDs to keep by
|
|
|
|
// calling the following method on all running allocations the client is aware
|
|
|
|
// of:
|
|
|
|
// func GenerateExecutorServiceKeyPrefixFromAlloc(allocID string) string
|
2016-03-23 07:50:41 +00:00
|
|
|
package consul
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2016-07-08 23:31:54 +00:00
|
|
|
"net"
|
2016-03-23 17:43:35 +00:00
|
|
|
"net/url"
|
2016-07-08 23:31:54 +00:00
|
|
|
"strconv"
|
2016-03-23 07:50:41 +00:00
|
|
|
"strings"
|
2016-03-24 01:03:02 +00:00
|
|
|
"sync"
|
2016-03-23 07:50:41 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
consul "github.com/hashicorp/consul/api"
|
2016-03-23 17:43:35 +00:00
|
|
|
"github.com/hashicorp/go-multierror"
|
2016-03-23 07:50:41 +00:00
|
|
|
|
|
|
|
"github.com/hashicorp/nomad/nomad/structs"
|
2016-05-24 06:23:57 +00:00
|
|
|
"github.com/hashicorp/nomad/nomad/structs/config"
|
|
|
|
"github.com/hashicorp/nomad/nomad/types"
|
2016-03-23 07:50:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2016-05-24 06:23:57 +00:00
|
|
|
// initialSyncBuffer is the max time an initial sync will sleep
|
|
|
|
// before syncing.
|
|
|
|
initialSyncBuffer = 30 * time.Second
|
|
|
|
|
|
|
|
// initialSyncDelay is the delay before an initial sync.
|
|
|
|
initialSyncDelay = 5 * time.Second
|
|
|
|
|
2016-06-13 23:29:07 +00:00
|
|
|
// nomadServicePrefix is the first prefix that scopes all Nomad registered
|
|
|
|
// services
|
2016-06-14 00:32:18 +00:00
|
|
|
nomadServicePrefix = "_nomad"
|
2016-06-10 01:45:51 +00:00
|
|
|
|
2016-03-23 21:34:43 +00:00
|
|
|
// The periodic time interval for syncing services and checks with Consul
|
2016-12-03 00:44:18 +00:00
|
|
|
defaultSyncInterval = 6 * time.Second
|
2016-03-25 02:30:02 +00:00
|
|
|
|
2016-12-03 00:44:18 +00:00
|
|
|
// defaultSyncJitter provides a little variance in the frequency at which
|
2016-05-24 06:23:57 +00:00
|
|
|
// Syncer polls Consul.
|
2016-12-03 00:44:18 +00:00
|
|
|
defaultSyncJitter = time.Second
|
2016-05-24 06:23:57 +00:00
|
|
|
|
2016-03-25 02:30:02 +00:00
|
|
|
// ttlCheckBuffer is the time interval that Nomad can take to report Consul
|
|
|
|
// the check result
|
|
|
|
ttlCheckBuffer = 31 * time.Second
|
2016-05-27 08:35:10 +00:00
|
|
|
|
2016-06-11 03:05:14 +00:00
|
|
|
// DefaultQueryWaitDuration is the max duration the Consul Agent will
|
|
|
|
// spend waiting for a response from a Consul Query.
|
|
|
|
DefaultQueryWaitDuration = 2 * time.Second
|
|
|
|
|
2016-06-11 03:26:15 +00:00
|
|
|
// ServiceTagHTTP is the tag assigned to HTTP services
|
|
|
|
ServiceTagHTTP = "http"
|
2016-05-27 08:35:10 +00:00
|
|
|
|
2016-06-11 03:26:15 +00:00
|
|
|
// ServiceTagRPC is the tag assigned to RPC services
|
|
|
|
ServiceTagRPC = "rpc"
|
2016-05-27 22:58:28 +00:00
|
|
|
|
|
|
|
// ServiceTagSerf is the tag assigned to Serf services
|
|
|
|
ServiceTagSerf = "serf"
|
2016-03-23 07:50:41 +00:00
|
|
|
)
|
|
|
|
|
2016-06-13 23:29:07 +00:00
|
|
|
// consulServiceID and consulCheckID are the IDs registered with Consul
|
|
|
|
type consulServiceID string
|
|
|
|
type consulCheckID string
|
|
|
|
|
|
|
|
// ServiceKey is the generated service key that is used to build the Consul
|
|
|
|
// ServiceID
|
|
|
|
type ServiceKey string
|
|
|
|
|
|
|
|
// ServiceDomain is the domain of services registered by Nomad
|
|
|
|
type ServiceDomain string
|
|
|
|
|
|
|
|
const (
|
|
|
|
ClientDomain ServiceDomain = "client"
|
|
|
|
ServerDomain ServiceDomain = "server"
|
|
|
|
)
|
|
|
|
|
|
|
|
// NewExecutorDomain returns a domain specific to the alloc ID and task
|
|
|
|
func NewExecutorDomain(allocID, task string) ServiceDomain {
|
|
|
|
return ServiceDomain(fmt.Sprintf("executor-%s-%s", allocID, task))
|
|
|
|
}
|
|
|
|
|
2016-06-02 07:56:55 +00:00
|
|
|
// Syncer allows syncing of services and checks with Consul
|
|
|
|
type Syncer struct {
|
2016-06-10 01:32:04 +00:00
|
|
|
client *consul.Client
|
|
|
|
consulAvailable bool
|
2016-06-02 07:56:55 +00:00
|
|
|
|
2016-06-13 04:28:56 +00:00
|
|
|
// servicesGroups and checkGroups are named groups of services and checks
|
|
|
|
// respectively that will be flattened and reconciled with Consul when
|
|
|
|
// SyncServices() is called. The key to the servicesGroups map is unique
|
|
|
|
// per handler and is used to allow the Agent's services to be maintained
|
|
|
|
// independently of the Client or Server's services.
|
2016-06-13 23:29:07 +00:00
|
|
|
servicesGroups map[ServiceDomain]map[ServiceKey]*consul.AgentServiceRegistration
|
|
|
|
checkGroups map[ServiceDomain]map[ServiceKey][]*consul.AgentCheckRegistration
|
2016-06-13 04:28:56 +00:00
|
|
|
groupsLock sync.RWMutex
|
2016-06-10 01:21:22 +00:00
|
|
|
|
2016-06-07 16:37:39 +00:00
|
|
|
// The "Consul Registry" is a collection of Consul Services and
|
|
|
|
// Checks all guarded by the registryLock.
|
|
|
|
registryLock sync.RWMutex
|
2016-06-02 07:56:55 +00:00
|
|
|
|
2016-06-13 23:29:07 +00:00
|
|
|
// checkRunners are delegated Consul checks being ran by the Syncer
|
|
|
|
checkRunners map[consulCheckID]*CheckRunner
|
2016-06-07 16:37:39 +00:00
|
|
|
|
|
|
|
addrFinder func(portLabel string) (string, int)
|
2016-06-07 14:01:13 +00:00
|
|
|
createDelegatedCheck func(*structs.ServiceCheck, string) (Check, error)
|
2016-06-13 23:29:07 +00:00
|
|
|
delegateChecks map[string]struct{} // delegateChecks are the checks that the Nomad client runs and reports to Consul
|
2016-06-07 16:37:39 +00:00
|
|
|
// End registryLock guarded attributes.
|
2016-06-02 07:56:55 +00:00
|
|
|
|
|
|
|
logger *log.Logger
|
|
|
|
|
|
|
|
shutdownCh chan struct{}
|
|
|
|
shutdown bool
|
|
|
|
shutdownLock sync.Mutex
|
|
|
|
|
2016-06-02 16:15:30 +00:00
|
|
|
// notifyShutdownCh is used to notify a Syncer it needs to shutdown.
|
|
|
|
// This can happen because there was an explicit call to the Syncer's
|
|
|
|
// Shutdown() method, or because the calling task signaled the
|
|
|
|
// program is going to exit by closing its shutdownCh.
|
|
|
|
notifyShutdownCh chan struct{}
|
|
|
|
|
2016-06-02 07:56:55 +00:00
|
|
|
// periodicCallbacks is walked sequentially when the timer in Run
|
|
|
|
// fires.
|
|
|
|
periodicCallbacks map[string]types.PeriodicCallback
|
|
|
|
notifySyncCh chan struct{}
|
|
|
|
periodicLock sync.RWMutex
|
2016-12-03 00:44:18 +00:00
|
|
|
|
|
|
|
// The periodic time interval for syncing services and checks with Consul
|
|
|
|
syncInterval time.Duration
|
|
|
|
|
|
|
|
// syncJitter provides a little variance in the frequency at which
|
|
|
|
// Syncer polls Consul.
|
|
|
|
syncJitter time.Duration
|
2016-06-02 07:56:55 +00:00
|
|
|
}
|
|
|
|
|
2016-05-23 14:29:08 +00:00
|
|
|
// NewSyncer returns a new consul.Syncer
|
2016-06-10 15:29:57 +00:00
|
|
|
func NewSyncer(consulConfig *config.ConsulConfig, shutdownCh chan struct{}, logger *log.Logger) (*Syncer, error) {
|
2016-06-17 05:51:06 +00:00
|
|
|
var consulClientConfig *consul.Config
|
2016-03-23 07:50:41 +00:00
|
|
|
var err error
|
2016-06-17 05:51:06 +00:00
|
|
|
consulClientConfig, err = consulConfig.ApiConfig()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2016-06-10 15:19:02 +00:00
|
|
|
}
|
|
|
|
|
2016-06-17 05:51:06 +00:00
|
|
|
var consulClient *consul.Client
|
|
|
|
if consulClient, err = consul.NewClient(consulClientConfig); err != nil {
|
2016-03-23 07:50:41 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2016-05-23 18:09:31 +00:00
|
|
|
consulSyncer := Syncer{
|
2016-06-17 05:51:06 +00:00
|
|
|
client: consulClient,
|
2016-05-24 06:23:57 +00:00
|
|
|
logger: logger,
|
2016-06-10 01:32:04 +00:00
|
|
|
consulAvailable: true,
|
2016-06-02 16:15:30 +00:00
|
|
|
shutdownCh: shutdownCh,
|
2016-06-13 23:29:07 +00:00
|
|
|
servicesGroups: make(map[ServiceDomain]map[ServiceKey]*consul.AgentServiceRegistration),
|
|
|
|
checkGroups: make(map[ServiceDomain]map[ServiceKey][]*consul.AgentCheckRegistration),
|
|
|
|
checkRunners: make(map[consulCheckID]*CheckRunner),
|
2016-05-24 06:23:57 +00:00
|
|
|
periodicCallbacks: make(map[string]types.PeriodicCallback),
|
2016-11-18 18:09:22 +00:00
|
|
|
notifySyncCh: make(chan struct{}, 1),
|
2016-08-30 21:36:56 +00:00
|
|
|
// default noop implementation of addrFinder
|
2016-12-03 00:44:18 +00:00
|
|
|
addrFinder: func(string) (string, int) { return "", 0 },
|
|
|
|
syncInterval: defaultSyncInterval,
|
|
|
|
syncJitter: defaultSyncJitter,
|
2016-03-23 07:50:41 +00:00
|
|
|
}
|
2016-06-13 23:29:07 +00:00
|
|
|
|
2016-05-23 18:09:31 +00:00
|
|
|
return &consulSyncer, nil
|
2016-03-23 07:50:41 +00:00
|
|
|
}
|
|
|
|
|
2016-03-25 02:30:02 +00:00
|
|
|
// SetDelegatedChecks sets the checks that nomad is going to run and report the
|
|
|
|
// result back to consul
|
2016-06-07 14:01:13 +00:00
|
|
|
func (c *Syncer) SetDelegatedChecks(delegateChecks map[string]struct{}, createDelegatedCheckFn func(*structs.ServiceCheck, string) (Check, error)) *Syncer {
|
2016-03-24 17:06:40 +00:00
|
|
|
c.delegateChecks = delegateChecks
|
2016-06-07 14:01:13 +00:00
|
|
|
c.createDelegatedCheck = createDelegatedCheckFn
|
2016-03-24 17:06:40 +00:00
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
2016-05-14 07:36:26 +00:00
|
|
|
// SetAddrFinder sets a function to find the host and port for a Service given its port label
|
2016-05-22 15:24:54 +00:00
|
|
|
func (c *Syncer) SetAddrFinder(addrFinder func(string) (string, int)) *Syncer {
|
2016-04-12 05:55:19 +00:00
|
|
|
c.addrFinder = addrFinder
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
2016-06-13 23:29:07 +00:00
|
|
|
// GenerateServiceKey should be called to generate a serviceKey based on the
|
2016-06-12 23:36:49 +00:00
|
|
|
// Service.
|
2016-06-13 23:29:07 +00:00
|
|
|
func GenerateServiceKey(service *structs.Service) ServiceKey {
|
|
|
|
var key string
|
2016-06-10 01:45:51 +00:00
|
|
|
numTags := len(service.Tags)
|
|
|
|
switch numTags {
|
|
|
|
case 0:
|
2016-06-13 23:29:07 +00:00
|
|
|
key = fmt.Sprintf("%s", service.Name)
|
2016-05-24 06:23:57 +00:00
|
|
|
default:
|
2016-06-13 23:29:07 +00:00
|
|
|
tags := strings.Join(service.Tags, "-")
|
|
|
|
key = fmt.Sprintf("%s-%s", service.Name, tags)
|
2016-05-24 06:23:57 +00:00
|
|
|
}
|
2016-06-13 23:29:07 +00:00
|
|
|
return ServiceKey(key)
|
2016-05-24 06:23:57 +00:00
|
|
|
}
|
|
|
|
|
2016-06-13 23:29:07 +00:00
|
|
|
// SetServices stores the map of Nomad Services to the provided service
|
|
|
|
// domain name.
|
|
|
|
func (c *Syncer) SetServices(domain ServiceDomain, services map[ServiceKey]*structs.Service) error {
|
2016-03-23 17:43:35 +00:00
|
|
|
var mErr multierror.Error
|
2016-06-13 04:28:56 +00:00
|
|
|
numServ := len(services)
|
2016-06-13 23:29:07 +00:00
|
|
|
registeredServices := make(map[ServiceKey]*consul.AgentServiceRegistration, numServ)
|
|
|
|
registeredChecks := make(map[ServiceKey][]*consul.AgentCheckRegistration, numServ)
|
|
|
|
for serviceKey, service := range services {
|
|
|
|
serviceReg, err := c.createService(service, domain, serviceKey)
|
|
|
|
if err != nil {
|
2016-03-23 17:43:35 +00:00
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
continue
|
|
|
|
}
|
2016-06-13 23:29:07 +00:00
|
|
|
registeredServices[serviceKey] = serviceReg
|
2016-03-23 17:43:35 +00:00
|
|
|
|
2016-06-10 01:21:22 +00:00
|
|
|
// Register the check(s) for this service
|
2016-03-23 17:43:35 +00:00
|
|
|
for _, chk := range service.Checks {
|
2016-06-10 01:21:22 +00:00
|
|
|
// Create a Consul check registration
|
2016-06-13 04:28:56 +00:00
|
|
|
chkReg, err := c.createCheckReg(chk, serviceReg)
|
2016-03-24 22:09:50 +00:00
|
|
|
if err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
continue
|
|
|
|
}
|
2016-06-13 04:28:56 +00:00
|
|
|
|
2016-03-25 17:36:31 +00:00
|
|
|
// creating a nomad check if we have to handle this particular check type
|
2016-06-10 03:31:14 +00:00
|
|
|
c.registryLock.RLock()
|
2016-03-25 17:36:31 +00:00
|
|
|
if _, ok := c.delegateChecks[chk.Type]; ok {
|
2016-06-13 23:29:07 +00:00
|
|
|
_, ok := c.checkRunners[consulCheckID(chkReg.ID)]
|
2016-06-10 03:31:14 +00:00
|
|
|
c.registryLock.RUnlock()
|
|
|
|
if ok {
|
2016-06-10 01:21:22 +00:00
|
|
|
continue
|
|
|
|
}
|
2016-06-13 04:28:56 +00:00
|
|
|
|
2016-06-07 14:01:13 +00:00
|
|
|
nc, err := c.createDelegatedCheck(chk, chkReg.ID)
|
2016-03-25 17:36:31 +00:00
|
|
|
if err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
continue
|
|
|
|
}
|
2016-06-13 04:28:56 +00:00
|
|
|
|
2016-03-25 17:36:31 +00:00
|
|
|
cr := NewCheckRunner(nc, c.runCheck, c.logger)
|
2016-06-10 03:31:14 +00:00
|
|
|
c.registryLock.Lock()
|
2016-06-13 23:29:07 +00:00
|
|
|
// TODO type the CheckRunner
|
|
|
|
c.checkRunners[consulCheckID(nc.ID())] = cr
|
2016-06-10 03:31:14 +00:00
|
|
|
c.registryLock.Unlock()
|
|
|
|
} else {
|
|
|
|
c.registryLock.RUnlock()
|
2016-03-25 17:36:31 +00:00
|
|
|
}
|
2016-06-13 04:28:56 +00:00
|
|
|
|
2016-06-13 23:29:07 +00:00
|
|
|
registeredChecks[serviceKey] = append(registeredChecks[serviceKey], chkReg)
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-10 01:21:22 +00:00
|
|
|
if len(mErr.Errors) > 0 {
|
|
|
|
return mErr.ErrorOrNil()
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
|
|
|
|
2016-08-30 21:36:56 +00:00
|
|
|
// Update the services and checks groups for this domain
|
2016-06-13 04:28:56 +00:00
|
|
|
c.groupsLock.Lock()
|
2016-08-30 21:36:56 +00:00
|
|
|
|
|
|
|
// Create map for service group if it doesn't exist
|
|
|
|
serviceKeys, ok := c.servicesGroups[domain]
|
|
|
|
if !ok {
|
|
|
|
serviceKeys = make(map[ServiceKey]*consul.AgentServiceRegistration, len(registeredServices))
|
|
|
|
c.servicesGroups[domain] = serviceKeys
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove stale services
|
|
|
|
for existingServiceKey := range serviceKeys {
|
|
|
|
if _, ok := registeredServices[existingServiceKey]; !ok {
|
|
|
|
// Exisitng service needs to be removed
|
|
|
|
delete(serviceKeys, existingServiceKey)
|
2016-06-13 23:29:07 +00:00
|
|
|
}
|
2016-08-30 21:36:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add registered services
|
|
|
|
for serviceKey, service := range registeredServices {
|
2016-06-13 23:29:07 +00:00
|
|
|
serviceKeys[serviceKey] = service
|
|
|
|
}
|
2016-08-30 21:36:56 +00:00
|
|
|
|
|
|
|
// Create map for check group if it doesn't exist
|
|
|
|
checkKeys, ok := c.checkGroups[domain]
|
|
|
|
if !ok {
|
|
|
|
checkKeys = make(map[ServiceKey][]*consul.AgentCheckRegistration, len(registeredChecks))
|
|
|
|
c.checkGroups[domain] = checkKeys
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove stale checks
|
|
|
|
for existingCheckKey := range checkKeys {
|
|
|
|
if _, ok := registeredChecks[existingCheckKey]; !ok {
|
|
|
|
// Exisitng check needs to be removed
|
|
|
|
delete(checkKeys, existingCheckKey)
|
2016-06-13 23:29:07 +00:00
|
|
|
}
|
2016-08-30 21:36:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add registered checks
|
|
|
|
for checkKey, checks := range registeredChecks {
|
|
|
|
checkKeys[checkKey] = checks
|
2016-06-13 23:29:07 +00:00
|
|
|
}
|
2016-06-13 04:28:56 +00:00
|
|
|
c.groupsLock.Unlock()
|
|
|
|
|
|
|
|
// Sync immediately
|
|
|
|
c.SyncNow()
|
2016-06-10 01:21:22 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// SyncNow expires the current timer forcing the list of periodic callbacks
|
|
|
|
// to be synced immediately.
|
|
|
|
func (c *Syncer) SyncNow() {
|
|
|
|
select {
|
|
|
|
case c.notifySyncCh <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-13 23:29:07 +00:00
|
|
|
// flattenedServices returns a flattened list of services that are registered
|
|
|
|
// locally
|
2016-06-10 01:21:22 +00:00
|
|
|
func (c *Syncer) flattenedServices() []*consul.AgentServiceRegistration {
|
|
|
|
const initialNumServices = 8
|
|
|
|
services := make([]*consul.AgentServiceRegistration, 0, initialNumServices)
|
2016-06-13 04:28:56 +00:00
|
|
|
c.groupsLock.RLock()
|
2016-06-13 12:05:35 +00:00
|
|
|
defer c.groupsLock.RUnlock()
|
2016-06-10 01:21:22 +00:00
|
|
|
for _, servicesGroup := range c.servicesGroups {
|
|
|
|
for _, service := range servicesGroup {
|
|
|
|
services = append(services, service)
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
|
|
|
}
|
2016-06-10 01:21:22 +00:00
|
|
|
return services
|
2016-03-23 07:50:41 +00:00
|
|
|
}
|
|
|
|
|
2016-06-13 23:29:07 +00:00
|
|
|
// flattenedChecks returns a flattened list of checks that are registered
|
|
|
|
// locally
|
2016-06-13 04:28:56 +00:00
|
|
|
func (c *Syncer) flattenedChecks() []*consul.AgentCheckRegistration {
|
|
|
|
const initialNumChecks = 8
|
|
|
|
checks := make([]*consul.AgentCheckRegistration, 0, initialNumChecks)
|
|
|
|
c.groupsLock.RLock()
|
|
|
|
for _, checkGroup := range c.checkGroups {
|
|
|
|
for _, check := range checkGroup {
|
2016-06-13 23:29:07 +00:00
|
|
|
checks = append(checks, check...)
|
2016-06-13 04:28:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
c.groupsLock.RUnlock()
|
|
|
|
return checks
|
|
|
|
}
|
|
|
|
|
2016-06-02 16:15:30 +00:00
|
|
|
func (c *Syncer) signalShutdown() {
|
|
|
|
select {
|
|
|
|
case c.notifyShutdownCh <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-03-23 21:34:43 +00:00
|
|
|
// Shutdown de-registers the services and checks and shuts down periodic syncing
|
2016-05-22 15:24:54 +00:00
|
|
|
func (c *Syncer) Shutdown() error {
|
2016-03-23 17:43:35 +00:00
|
|
|
var mErr multierror.Error
|
2016-03-24 01:03:02 +00:00
|
|
|
|
|
|
|
c.shutdownLock.Lock()
|
|
|
|
if !c.shutdown {
|
|
|
|
c.shutdown = true
|
2016-03-23 21:23:32 +00:00
|
|
|
}
|
2016-03-24 01:03:02 +00:00
|
|
|
c.shutdownLock.Unlock()
|
2016-03-25 02:19:13 +00:00
|
|
|
|
2016-06-02 16:15:30 +00:00
|
|
|
c.signalShutdown()
|
|
|
|
|
2016-03-25 02:19:13 +00:00
|
|
|
// Stop all the checks that nomad is running
|
2016-06-10 03:31:14 +00:00
|
|
|
c.registryLock.RLock()
|
2016-06-13 23:29:07 +00:00
|
|
|
defer c.registryLock.RUnlock()
|
2016-03-25 04:17:33 +00:00
|
|
|
for _, cr := range c.checkRunners {
|
|
|
|
cr.Stop()
|
2016-03-25 02:19:13 +00:00
|
|
|
}
|
|
|
|
|
2016-08-31 17:43:55 +00:00
|
|
|
// De-register all the services registered by this syncer from Consul
|
2016-08-31 00:10:15 +00:00
|
|
|
services, err := c.queryAgentServices()
|
|
|
|
if err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
}
|
|
|
|
for serviceID := range services {
|
2016-06-13 23:29:07 +00:00
|
|
|
convertedID := string(serviceID)
|
|
|
|
if err := c.client.Agent().ServiceDeregister(convertedID); err != nil {
|
|
|
|
c.logger.Printf("[WARN] consul.syncer: failed to deregister service ID %+q: %v", convertedID, err)
|
2016-03-23 17:43:35 +00:00
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return mErr.ErrorOrNil()
|
2016-03-23 07:50:41 +00:00
|
|
|
}
|
|
|
|
|
2016-06-10 02:58:33 +00:00
|
|
|
// queryChecks queries the Consul Agent for a list of Consul checks that
|
|
|
|
// have been registered with this Consul Syncer.
|
2016-06-13 23:29:07 +00:00
|
|
|
func (c *Syncer) queryChecks() (map[consulCheckID]*consul.AgentCheck, error) {
|
2016-06-10 02:58:33 +00:00
|
|
|
checks, err := c.client.Agent().Checks()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return c.filterConsulChecks(checks), nil
|
|
|
|
}
|
2016-03-23 22:28:55 +00:00
|
|
|
|
2016-06-10 02:55:01 +00:00
|
|
|
// queryAgentServices queries the Consul Agent for a list of Consul services that
|
|
|
|
// have been registered with this Consul Syncer.
|
2016-06-13 23:29:07 +00:00
|
|
|
func (c *Syncer) queryAgentServices() (map[consulServiceID]*consul.AgentService, error) {
|
2016-06-10 02:55:01 +00:00
|
|
|
services, err := c.client.Agent().Services()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-06-13 23:29:07 +00:00
|
|
|
return c.filterConsulServices(services), nil
|
2016-06-10 02:55:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// syncChecks synchronizes this Syncer's Consul Checks with the Consul Agent.
|
|
|
|
func (c *Syncer) syncChecks() error {
|
|
|
|
var mErr multierror.Error
|
|
|
|
consulChecks, err := c.queryChecks()
|
2016-03-23 22:28:55 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-06-10 02:58:33 +00:00
|
|
|
// Synchronize checks with Consul
|
2016-08-23 16:09:20 +00:00
|
|
|
missingChecks, existingChecks, changedChecks, staleChecks := c.calcChecksDiff(consulChecks)
|
2016-06-10 02:58:33 +00:00
|
|
|
for _, check := range missingChecks {
|
|
|
|
if err := c.registerCheck(check); err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
}
|
|
|
|
}
|
2016-08-23 16:09:20 +00:00
|
|
|
for _, check := range existingChecks {
|
|
|
|
c.ensureCheckRunning(check)
|
|
|
|
}
|
2016-06-10 02:58:33 +00:00
|
|
|
for _, check := range changedChecks {
|
|
|
|
// NOTE(sean@): Do we need to deregister the check before
|
|
|
|
// re-registering it? Not deregistering to avoid missing the
|
|
|
|
// TTL but doesn't correct reconcile any possible drift with
|
|
|
|
// the check.
|
|
|
|
//
|
|
|
|
// if err := c.deregisterCheck(check.ID); err != nil {
|
|
|
|
// mErr.Errors = append(mErr.Errors, err)
|
|
|
|
// }
|
|
|
|
if err := c.registerCheck(check); err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, check := range staleChecks {
|
2016-06-13 23:29:07 +00:00
|
|
|
if err := c.deregisterCheck(consulCheckID(check.ID)); err != nil {
|
2016-06-10 02:58:33 +00:00
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return mErr.ErrorOrNil()
|
|
|
|
}
|
|
|
|
|
|
|
|
// compareConsulCheck takes a consul.AgentCheckRegistration instance and
|
|
|
|
// compares it with a consul.AgentCheck. Returns true if they are equal
|
|
|
|
// according to consul.AgentCheck, otherwise false.
|
|
|
|
func compareConsulCheck(localCheck *consul.AgentCheckRegistration, consulCheck *consul.AgentCheck) bool {
|
|
|
|
if consulCheck.CheckID != localCheck.ID ||
|
|
|
|
consulCheck.Name != localCheck.Name ||
|
|
|
|
consulCheck.Notes != localCheck.Notes ||
|
|
|
|
consulCheck.ServiceID != localCheck.ServiceID {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// calcChecksDiff takes the argument (consulChecks) and calculates the delta
|
2016-08-31 00:10:15 +00:00
|
|
|
// between the consul.Syncer's list of known checks (c.flattenedChecks()).
|
|
|
|
// Four arrays are returned:
|
2016-06-10 02:58:33 +00:00
|
|
|
//
|
|
|
|
// 1) a slice of checks that exist only locally in the Syncer and are missing
|
|
|
|
// from the Consul Agent (consulChecks) and therefore need to be registered.
|
|
|
|
//
|
|
|
|
// 2) a slice of checks that exist in both the local consul.Syncer's
|
|
|
|
// tracked list and Consul Agent (consulChecks).
|
|
|
|
//
|
|
|
|
// 3) a slice of checks that exist in both the local consul.Syncer's
|
|
|
|
// tracked list and Consul Agent (consulServices) but have diverged state.
|
|
|
|
//
|
|
|
|
// 4) a slice of checks that exist only in the Consul Agent (consulChecks)
|
|
|
|
// and should be removed because the Consul Agent has drifted from the
|
|
|
|
// Syncer.
|
2016-06-13 23:29:07 +00:00
|
|
|
func (c *Syncer) calcChecksDiff(consulChecks map[consulCheckID]*consul.AgentCheck) (
|
2016-06-13 01:20:48 +00:00
|
|
|
missingChecks []*consul.AgentCheckRegistration,
|
|
|
|
equalChecks []*consul.AgentCheckRegistration,
|
|
|
|
changedChecks []*consul.AgentCheckRegistration,
|
|
|
|
staleChecks []*consul.AgentCheckRegistration) {
|
|
|
|
|
2016-06-10 02:58:33 +00:00
|
|
|
type mergedCheck struct {
|
|
|
|
check *consul.AgentCheckRegistration
|
|
|
|
// 'l' == Nomad local only
|
|
|
|
// 'e' == equal
|
|
|
|
// 'c' == changed
|
|
|
|
// 'a' == Consul agent only
|
|
|
|
state byte
|
|
|
|
}
|
|
|
|
var (
|
|
|
|
localChecksCount = 0
|
|
|
|
equalChecksCount = 0
|
|
|
|
changedChecksCount = 0
|
|
|
|
agentChecks = 0
|
|
|
|
)
|
2016-08-31 00:10:15 +00:00
|
|
|
flattenedChecks := c.flattenedChecks()
|
|
|
|
localChecks := make(map[string]*mergedCheck, len(flattenedChecks)+len(consulChecks))
|
|
|
|
for _, localCheck := range flattenedChecks {
|
2016-06-10 02:58:33 +00:00
|
|
|
localChecksCount++
|
|
|
|
localChecks[localCheck.ID] = &mergedCheck{localCheck, 'l'}
|
|
|
|
}
|
|
|
|
for _, consulCheck := range consulChecks {
|
|
|
|
if localCheck, found := localChecks[consulCheck.CheckID]; found {
|
|
|
|
localChecksCount--
|
|
|
|
if compareConsulCheck(localCheck.check, consulCheck) {
|
|
|
|
equalChecksCount++
|
|
|
|
localChecks[consulCheck.CheckID].state = 'e'
|
|
|
|
} else {
|
|
|
|
changedChecksCount++
|
|
|
|
localChecks[consulCheck.CheckID].state = 'c'
|
2016-03-23 22:28:55 +00:00
|
|
|
}
|
2016-06-10 02:58:33 +00:00
|
|
|
} else {
|
|
|
|
agentChecks++
|
|
|
|
agentCheckReg := &consul.AgentCheckRegistration{
|
|
|
|
ID: consulCheck.CheckID,
|
|
|
|
Name: consulCheck.Name,
|
|
|
|
Notes: consulCheck.Notes,
|
|
|
|
ServiceID: consulCheck.ServiceID,
|
|
|
|
}
|
|
|
|
localChecks[consulCheck.CheckID] = &mergedCheck{agentCheckReg, 'a'}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
missingChecks = make([]*consul.AgentCheckRegistration, 0, localChecksCount)
|
|
|
|
equalChecks = make([]*consul.AgentCheckRegistration, 0, equalChecksCount)
|
|
|
|
changedChecks = make([]*consul.AgentCheckRegistration, 0, changedChecksCount)
|
|
|
|
staleChecks = make([]*consul.AgentCheckRegistration, 0, agentChecks)
|
|
|
|
for _, check := range localChecks {
|
|
|
|
switch check.state {
|
|
|
|
case 'l':
|
|
|
|
missingChecks = append(missingChecks, check.check)
|
|
|
|
case 'e':
|
|
|
|
equalChecks = append(equalChecks, check.check)
|
|
|
|
case 'c':
|
|
|
|
changedChecks = append(changedChecks, check.check)
|
|
|
|
case 'a':
|
|
|
|
staleChecks = append(staleChecks, check.check)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return missingChecks, equalChecks, changedChecks, staleChecks
|
|
|
|
}
|
2016-06-10 02:55:01 +00:00
|
|
|
|
|
|
|
// compareConsulService takes a consul.AgentServiceRegistration instance and
|
|
|
|
// compares it with a consul.AgentService. Returns true if they are equal
|
|
|
|
// according to consul.AgentService, otherwise false.
|
|
|
|
func compareConsulService(localService *consul.AgentServiceRegistration, consulService *consul.AgentService) bool {
|
|
|
|
if consulService.ID != localService.ID ||
|
|
|
|
consulService.Service != localService.Name ||
|
|
|
|
consulService.Port != localService.Port ||
|
|
|
|
consulService.Address != localService.Address ||
|
|
|
|
consulService.EnableTagOverride != localService.EnableTagOverride {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
serviceTags := make(map[string]byte, len(localService.Tags))
|
|
|
|
for _, tag := range localService.Tags {
|
|
|
|
serviceTags[tag] = 'l'
|
|
|
|
}
|
|
|
|
for _, tag := range consulService.Tags {
|
|
|
|
if _, found := serviceTags[tag]; !found {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
serviceTags[tag] = 'b'
|
|
|
|
}
|
|
|
|
for _, state := range serviceTags {
|
|
|
|
if state == 'l' {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// calcServicesDiff takes the argument (consulServices) and calculates the
|
|
|
|
// delta between the consul.Syncer's list of known services
|
2016-08-31 00:10:15 +00:00
|
|
|
// (c.flattenedServices()). Four arrays are returned:
|
2016-06-10 02:55:01 +00:00
|
|
|
//
|
|
|
|
// 1) a slice of services that exist only locally in the Syncer and are
|
|
|
|
// missing from the Consul Agent (consulServices) and therefore need to be
|
|
|
|
// registered.
|
|
|
|
//
|
|
|
|
// 2) a slice of services that exist in both the local consul.Syncer's
|
|
|
|
// tracked list and Consul Agent (consulServices) *AND* are identical.
|
|
|
|
//
|
|
|
|
// 3) a slice of services that exist in both the local consul.Syncer's
|
|
|
|
// tracked list and Consul Agent (consulServices) but have diverged state.
|
|
|
|
//
|
|
|
|
// 4) a slice of services that exist only in the Consul Agent
|
|
|
|
// (consulServices) and should be removed because the Consul Agent has
|
|
|
|
// drifted from the Syncer.
|
2016-06-13 23:29:07 +00:00
|
|
|
func (c *Syncer) calcServicesDiff(consulServices map[consulServiceID]*consul.AgentService) (missingServices []*consul.AgentServiceRegistration, equalServices []*consul.AgentServiceRegistration, changedServices []*consul.AgentServiceRegistration, staleServices []*consul.AgentServiceRegistration) {
|
2016-06-10 02:55:01 +00:00
|
|
|
type mergedService struct {
|
|
|
|
service *consul.AgentServiceRegistration
|
|
|
|
// 'l' == Nomad local only
|
|
|
|
// 'e' == equal
|
|
|
|
// 'c' == changed
|
|
|
|
// 'a' == Consul agent only
|
|
|
|
state byte
|
|
|
|
}
|
|
|
|
var (
|
|
|
|
localServicesCount = 0
|
|
|
|
equalServicesCount = 0
|
|
|
|
changedServicesCount = 0
|
|
|
|
agentServices = 0
|
|
|
|
)
|
2016-08-31 00:10:15 +00:00
|
|
|
flattenedServices := c.flattenedServices()
|
|
|
|
localServices := make(map[string]*mergedService, len(flattenedServices)+len(consulServices))
|
|
|
|
for _, localService := range flattenedServices {
|
2016-06-10 02:55:01 +00:00
|
|
|
localServicesCount++
|
|
|
|
localServices[localService.ID] = &mergedService{localService, 'l'}
|
|
|
|
}
|
|
|
|
for _, consulService := range consulServices {
|
|
|
|
if localService, found := localServices[consulService.ID]; found {
|
|
|
|
localServicesCount--
|
|
|
|
if compareConsulService(localService.service, consulService) {
|
|
|
|
equalServicesCount++
|
|
|
|
localServices[consulService.ID].state = 'e'
|
|
|
|
} else {
|
|
|
|
changedServicesCount++
|
|
|
|
localServices[consulService.ID].state = 'c'
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
agentServices++
|
|
|
|
agentServiceReg := &consul.AgentServiceRegistration{
|
|
|
|
ID: consulService.ID,
|
|
|
|
Name: consulService.Service,
|
|
|
|
Tags: consulService.Tags,
|
|
|
|
Port: consulService.Port,
|
|
|
|
Address: consulService.Address,
|
|
|
|
}
|
|
|
|
localServices[consulService.ID] = &mergedService{agentServiceReg, 'a'}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
missingServices = make([]*consul.AgentServiceRegistration, 0, localServicesCount)
|
|
|
|
equalServices = make([]*consul.AgentServiceRegistration, 0, equalServicesCount)
|
|
|
|
changedServices = make([]*consul.AgentServiceRegistration, 0, changedServicesCount)
|
|
|
|
staleServices = make([]*consul.AgentServiceRegistration, 0, agentServices)
|
|
|
|
for _, service := range localServices {
|
|
|
|
switch service.state {
|
|
|
|
case 'l':
|
|
|
|
missingServices = append(missingServices, service.service)
|
|
|
|
case 'e':
|
|
|
|
equalServices = append(equalServices, service.service)
|
|
|
|
case 'c':
|
|
|
|
changedServices = append(changedServices, service.service)
|
|
|
|
case 'a':
|
|
|
|
staleServices = append(staleServices, service.service)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return missingServices, equalServices, changedServices, staleServices
|
|
|
|
}
|
|
|
|
|
|
|
|
// syncServices synchronizes this Syncer's Consul Services with the Consul
|
|
|
|
// Agent.
|
|
|
|
func (c *Syncer) syncServices() error {
|
2016-06-13 23:29:07 +00:00
|
|
|
consulServices, err := c.queryAgentServices()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2016-06-10 02:55:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Synchronize services with Consul
|
|
|
|
var mErr multierror.Error
|
|
|
|
missingServices, _, changedServices, removedServices := c.calcServicesDiff(consulServices)
|
|
|
|
for _, service := range missingServices {
|
|
|
|
if err := c.client.Agent().ServiceRegister(service); err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, service := range changedServices {
|
|
|
|
// Re-register the local service
|
|
|
|
if err := c.client.Agent().ServiceRegister(service); err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, service := range removedServices {
|
|
|
|
if err := c.deregisterService(service.ID); err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
2016-03-23 22:28:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return mErr.ErrorOrNil()
|
|
|
|
}
|
|
|
|
|
2016-03-23 21:34:43 +00:00
|
|
|
// registerCheck registers a check definition with Consul
|
2016-05-22 15:24:54 +00:00
|
|
|
func (c *Syncer) registerCheck(chkReg *consul.AgentCheckRegistration) error {
|
2016-06-10 03:31:14 +00:00
|
|
|
c.registryLock.RLock()
|
2016-06-13 23:29:07 +00:00
|
|
|
if cr, ok := c.checkRunners[consulCheckID(chkReg.ID)]; ok {
|
2016-03-25 04:17:33 +00:00
|
|
|
cr.Start()
|
2016-03-25 02:00:24 +00:00
|
|
|
}
|
2016-06-10 03:31:14 +00:00
|
|
|
c.registryLock.RUnlock()
|
2016-03-24 21:12:09 +00:00
|
|
|
return c.client.Agent().CheckRegister(chkReg)
|
|
|
|
}
|
|
|
|
|
2016-08-23 22:33:44 +00:00
|
|
|
// ensureCheckRunning starts the check runner for a check if it's not already running
|
2016-08-23 16:09:20 +00:00
|
|
|
func (c *Syncer) ensureCheckRunning(chk *consul.AgentCheckRegistration) {
|
|
|
|
c.registryLock.RLock()
|
|
|
|
defer c.registryLock.RUnlock()
|
2016-08-23 22:33:44 +00:00
|
|
|
if cr, ok := c.checkRunners[consulCheckID(chk.ID)]; ok && !cr.Started() {
|
|
|
|
c.logger.Printf("[DEBUG] consul.syncer: starting runner for existing check. %v", chk.ID)
|
2016-08-23 16:09:20 +00:00
|
|
|
cr.Start()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-13 04:28:56 +00:00
|
|
|
// createCheckReg creates a Check that can be registered with Nomad. It also
|
|
|
|
// creates a Nomad check for the check types that it can handle.
|
2016-07-08 21:09:27 +00:00
|
|
|
func (c *Syncer) createCheckReg(check *structs.ServiceCheck, serviceReg *consul.AgentServiceRegistration) (*consul.AgentCheckRegistration, error) {
|
2016-03-23 17:43:35 +00:00
|
|
|
chkReg := consul.AgentCheckRegistration{
|
2016-07-08 21:09:27 +00:00
|
|
|
ID: check.Hash(serviceReg.ID),
|
2016-03-23 17:43:35 +00:00
|
|
|
Name: check.Name,
|
2016-07-08 21:09:27 +00:00
|
|
|
ServiceID: serviceReg.ID,
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
|
|
|
chkReg.Timeout = check.Timeout.String()
|
2016-03-23 21:23:32 +00:00
|
|
|
chkReg.Interval = check.Interval.String()
|
2016-07-08 21:09:27 +00:00
|
|
|
host, port := serviceReg.Address, serviceReg.Port
|
|
|
|
if check.PortLabel != "" {
|
|
|
|
host, port = c.addrFinder(check.PortLabel)
|
|
|
|
}
|
2016-03-23 17:43:35 +00:00
|
|
|
switch check.Type {
|
|
|
|
case structs.ServiceCheckHTTP:
|
|
|
|
if check.Protocol == "" {
|
|
|
|
check.Protocol = "http"
|
|
|
|
}
|
2016-08-11 01:27:19 +00:00
|
|
|
base := url.URL{
|
2016-03-23 17:43:35 +00:00
|
|
|
Scheme: check.Protocol,
|
2016-07-08 23:31:54 +00:00
|
|
|
Host: net.JoinHostPort(host, strconv.Itoa(port)),
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
2016-08-11 18:49:48 +00:00
|
|
|
relative, err := url.Parse(check.Path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
url := base.ResolveReference(relative)
|
2016-03-23 17:43:35 +00:00
|
|
|
chkReg.HTTP = url.String()
|
|
|
|
case structs.ServiceCheckTCP:
|
2016-07-08 23:31:54 +00:00
|
|
|
chkReg.TCP = net.JoinHostPort(host, strconv.Itoa(port))
|
2016-03-23 17:43:35 +00:00
|
|
|
case structs.ServiceCheckScript:
|
2016-03-25 02:30:02 +00:00
|
|
|
chkReg.TTL = (check.Interval + ttlCheckBuffer).String()
|
2016-03-24 22:09:50 +00:00
|
|
|
default:
|
2016-06-11 22:17:20 +00:00
|
|
|
return nil, fmt.Errorf("check type %+q not valid", check.Type)
|
2016-03-24 20:05:08 +00:00
|
|
|
}
|
2016-08-16 19:05:15 +00:00
|
|
|
chkReg.Status = check.InitialStatus
|
2016-03-24 22:09:50 +00:00
|
|
|
return &chkReg, nil
|
2016-03-23 07:50:41 +00:00
|
|
|
}
|
|
|
|
|
2016-06-13 23:29:07 +00:00
|
|
|
// generateConsulServiceID takes the domain and service key and returns a Consul
|
|
|
|
// ServiceID
|
|
|
|
func generateConsulServiceID(domain ServiceDomain, key ServiceKey) consulServiceID {
|
|
|
|
return consulServiceID(fmt.Sprintf("%s-%s-%s", nomadServicePrefix, domain, key))
|
|
|
|
}
|
|
|
|
|
2016-06-10 02:55:01 +00:00
|
|
|
// createService creates a Consul AgentService from a Nomad ConsulService.
|
2016-06-13 23:29:07 +00:00
|
|
|
func (c *Syncer) createService(service *structs.Service, domain ServiceDomain, key ServiceKey) (*consul.AgentServiceRegistration, error) {
|
2016-06-07 16:37:39 +00:00
|
|
|
c.registryLock.RLock()
|
|
|
|
defer c.registryLock.RUnlock()
|
|
|
|
|
|
|
|
srv := consul.AgentServiceRegistration{
|
2016-06-13 23:29:07 +00:00
|
|
|
ID: string(generateConsulServiceID(domain, key)),
|
2016-06-07 16:37:39 +00:00
|
|
|
Name: service.Name,
|
|
|
|
Tags: service.Tags,
|
2016-03-23 07:50:41 +00:00
|
|
|
}
|
2016-04-12 05:55:19 +00:00
|
|
|
host, port := c.addrFinder(service.PortLabel)
|
2016-04-14 07:56:39 +00:00
|
|
|
if host != "" {
|
|
|
|
srv.Address = host
|
|
|
|
}
|
|
|
|
|
|
|
|
if port != 0 {
|
|
|
|
srv.Port = port
|
|
|
|
}
|
|
|
|
|
2016-03-23 07:50:41 +00:00
|
|
|
return &srv, nil
|
|
|
|
}
|
|
|
|
|
2016-03-23 17:43:35 +00:00
|
|
|
// deregisterService de-registers a service with the given ID from consul
|
2016-06-10 02:55:01 +00:00
|
|
|
func (c *Syncer) deregisterService(serviceID string) error {
|
|
|
|
return c.client.Agent().ServiceDeregister(serviceID)
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
|
|
|
|
2016-06-10 02:58:33 +00:00
|
|
|
// deregisterCheck de-registers a check from Consul
|
2016-06-13 23:29:07 +00:00
|
|
|
func (c *Syncer) deregisterCheck(id consulCheckID) error {
|
2016-06-10 02:58:33 +00:00
|
|
|
c.registryLock.Lock()
|
|
|
|
defer c.registryLock.Unlock()
|
|
|
|
|
|
|
|
// Deleting from Consul Agent
|
2016-06-13 23:29:07 +00:00
|
|
|
if err := c.client.Agent().CheckDeregister(string(id)); err != nil {
|
2016-06-10 02:58:33 +00:00
|
|
|
// CheckDeregister() will be reattempted again in a future
|
|
|
|
// sync.
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove the check from the local registry
|
2016-06-13 23:29:07 +00:00
|
|
|
if cr, ok := c.checkRunners[id]; ok {
|
2016-03-25 04:17:33 +00:00
|
|
|
cr.Stop()
|
2016-06-13 23:29:07 +00:00
|
|
|
delete(c.checkRunners, id)
|
2016-03-24 20:05:08 +00:00
|
|
|
}
|
2016-03-25 02:00:24 +00:00
|
|
|
|
2016-06-10 02:58:33 +00:00
|
|
|
return nil
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
|
|
|
|
2016-05-23 14:24:00 +00:00
|
|
|
// Run triggers periodic syncing of services and checks with Consul. This is
|
|
|
|
// a long lived go-routine which is stopped during shutdown.
|
|
|
|
func (c *Syncer) Run() {
|
2016-06-12 23:42:56 +00:00
|
|
|
sync := time.NewTimer(0)
|
2016-03-23 07:50:41 +00:00
|
|
|
for {
|
|
|
|
select {
|
2016-03-25 21:18:04 +00:00
|
|
|
case <-sync.C:
|
2016-12-03 00:44:18 +00:00
|
|
|
d := c.syncInterval - c.syncJitter
|
2016-05-24 06:23:57 +00:00
|
|
|
sync.Reset(d)
|
|
|
|
|
2016-06-10 01:29:10 +00:00
|
|
|
if err := c.SyncServices(); err != nil {
|
|
|
|
if c.consulAvailable {
|
2016-06-13 12:05:35 +00:00
|
|
|
c.logger.Printf("[DEBUG] consul.syncer: error in syncing: %v", err)
|
2016-04-02 21:48:10 +00:00
|
|
|
}
|
2016-06-10 03:42:54 +00:00
|
|
|
c.consulAvailable = false
|
2016-04-02 21:48:10 +00:00
|
|
|
} else {
|
2016-06-10 01:29:10 +00:00
|
|
|
if !c.consulAvailable {
|
2016-06-13 12:05:35 +00:00
|
|
|
c.logger.Printf("[DEBUG] consul.syncer: syncs succesful")
|
2016-06-10 01:29:10 +00:00
|
|
|
}
|
|
|
|
c.consulAvailable = true
|
2016-03-23 07:50:41 +00:00
|
|
|
}
|
2016-05-24 06:23:57 +00:00
|
|
|
case <-c.notifySyncCh:
|
2016-11-18 18:09:22 +00:00
|
|
|
sync.Reset(0)
|
2016-03-23 07:50:41 +00:00
|
|
|
case <-c.shutdownCh:
|
2016-06-02 16:15:30 +00:00
|
|
|
c.Shutdown()
|
|
|
|
case <-c.notifyShutdownCh:
|
2016-03-25 21:18:04 +00:00
|
|
|
sync.Stop()
|
2016-06-13 12:05:35 +00:00
|
|
|
c.logger.Printf("[INFO] consul.syncer: shutting down syncer ")
|
2016-03-23 07:50:41 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-24 06:23:57 +00:00
|
|
|
// RunHandlers executes each handler (randomly)
|
2016-06-07 15:59:17 +00:00
|
|
|
func (c *Syncer) RunHandlers() error {
|
2016-05-24 06:23:57 +00:00
|
|
|
c.periodicLock.RLock()
|
|
|
|
handlers := make(map[string]types.PeriodicCallback, len(c.periodicCallbacks))
|
|
|
|
for name, fn := range c.periodicCallbacks {
|
|
|
|
handlers[name] = fn
|
|
|
|
}
|
|
|
|
c.periodicLock.RUnlock()
|
2016-06-07 15:59:17 +00:00
|
|
|
|
|
|
|
var mErr multierror.Error
|
2016-05-24 06:28:42 +00:00
|
|
|
for _, fn := range handlers {
|
2016-06-07 15:59:17 +00:00
|
|
|
if err := fn(); err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
}
|
2016-05-24 06:23:57 +00:00
|
|
|
}
|
2016-06-07 15:59:17 +00:00
|
|
|
return mErr.ErrorOrNil()
|
2016-05-24 06:23:57 +00:00
|
|
|
}
|
|
|
|
|
2016-06-10 01:29:10 +00:00
|
|
|
// SyncServices sync the services with the Consul Agent
|
|
|
|
func (c *Syncer) SyncServices() error {
|
2016-08-09 19:24:50 +00:00
|
|
|
var mErr multierror.Error
|
2016-06-07 15:59:17 +00:00
|
|
|
if err := c.syncServices(); err != nil {
|
2016-08-09 19:24:50 +00:00
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
2016-06-07 15:59:17 +00:00
|
|
|
if err := c.syncChecks(); err != nil {
|
2016-08-09 19:24:50 +00:00
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
}
|
|
|
|
if err := c.RunHandlers(); err != nil {
|
2016-06-10 01:29:10 +00:00
|
|
|
return err
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
2016-08-09 19:24:50 +00:00
|
|
|
return mErr.ErrorOrNil()
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
|
|
|
|
2016-06-13 23:29:07 +00:00
|
|
|
// filterConsulServices prunes out all the service who were not registered with
|
|
|
|
// the syncer
|
|
|
|
func (c *Syncer) filterConsulServices(consulServices map[string]*consul.AgentService) map[consulServiceID]*consul.AgentService {
|
|
|
|
localServices := make(map[consulServiceID]*consul.AgentService, len(consulServices))
|
2016-11-18 18:09:42 +00:00
|
|
|
c.groupsLock.RLock()
|
|
|
|
defer c.groupsLock.RUnlock()
|
2016-06-07 16:37:39 +00:00
|
|
|
for serviceID, service := range consulServices {
|
2016-06-13 23:29:07 +00:00
|
|
|
for domain := range c.servicesGroups {
|
|
|
|
if strings.HasPrefix(service.ID, fmt.Sprintf("%s-%s", nomadServicePrefix, domain)) {
|
|
|
|
localServices[consulServiceID(serviceID)] = service
|
|
|
|
break
|
|
|
|
}
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
|
|
|
}
|
2016-06-07 16:37:39 +00:00
|
|
|
return localServices
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// filterConsulChecks prunes out all the consul checks which do not have
|
2016-06-10 02:58:33 +00:00
|
|
|
// services with Syncer's idPrefix.
|
2016-06-13 23:29:07 +00:00
|
|
|
func (c *Syncer) filterConsulChecks(consulChecks map[string]*consul.AgentCheck) map[consulCheckID]*consul.AgentCheck {
|
|
|
|
localChecks := make(map[consulCheckID]*consul.AgentCheck, len(consulChecks))
|
2016-11-18 18:09:42 +00:00
|
|
|
c.groupsLock.RLock()
|
|
|
|
defer c.groupsLock.RUnlock()
|
2016-06-10 02:58:33 +00:00
|
|
|
for checkID, check := range consulChecks {
|
2016-06-13 23:29:07 +00:00
|
|
|
for domain := range c.checkGroups {
|
|
|
|
if strings.HasPrefix(check.ServiceID, fmt.Sprintf("%s-%s", nomadServicePrefix, domain)) {
|
|
|
|
localChecks[consulCheckID(checkID)] = check
|
|
|
|
break
|
|
|
|
}
|
2016-03-23 17:43:35 +00:00
|
|
|
}
|
|
|
|
}
|
2016-06-10 02:58:33 +00:00
|
|
|
return localChecks
|
2016-03-23 07:50:41 +00:00
|
|
|
}
|
2016-03-23 22:36:46 +00:00
|
|
|
|
2016-06-10 03:01:55 +00:00
|
|
|
// consulPresent indicates whether the Consul Agent is responding
|
2016-05-28 01:17:37 +00:00
|
|
|
func (c *Syncer) consulPresent() bool {
|
|
|
|
_, err := c.client.Agent().Self()
|
|
|
|
return err == nil
|
|
|
|
}
|
|
|
|
|
2016-03-24 20:05:08 +00:00
|
|
|
// runCheck runs a check and updates the corresponding ttl check in consul
|
2016-05-22 15:24:54 +00:00
|
|
|
func (c *Syncer) runCheck(check Check) {
|
2016-03-24 20:05:08 +00:00
|
|
|
res := check.Run()
|
2016-05-05 17:01:38 +00:00
|
|
|
if res.Duration >= check.Timeout() {
|
2016-06-08 17:38:00 +00:00
|
|
|
c.logger.Printf("[DEBUG] consul.syncer: check took time: %v, timeout: %v", res.Duration, check.Timeout())
|
2016-05-05 17:01:38 +00:00
|
|
|
}
|
2016-03-25 02:00:24 +00:00
|
|
|
state := consul.HealthCritical
|
|
|
|
output := res.Output
|
2016-03-25 21:26:56 +00:00
|
|
|
switch res.ExitCode {
|
|
|
|
case 0:
|
2016-03-25 02:00:24 +00:00
|
|
|
state = consul.HealthPassing
|
2016-03-25 21:26:56 +00:00
|
|
|
case 1:
|
2016-03-25 02:00:24 +00:00
|
|
|
state = consul.HealthWarning
|
2016-03-25 21:26:56 +00:00
|
|
|
default:
|
|
|
|
state = consul.HealthCritical
|
2016-03-25 02:00:24 +00:00
|
|
|
}
|
2016-04-05 17:15:38 +00:00
|
|
|
if res.Err != nil {
|
|
|
|
state = consul.HealthCritical
|
|
|
|
output = res.Err.Error()
|
|
|
|
}
|
2016-03-25 02:00:24 +00:00
|
|
|
if err := c.client.Agent().UpdateTTL(check.ID(), output, state); err != nil {
|
2016-06-10 01:32:04 +00:00
|
|
|
if c.consulAvailable {
|
2016-06-11 22:17:20 +00:00
|
|
|
c.logger.Printf("[DEBUG] consul.syncer: check %+q failed, disabling Consul checks until until next successful sync: %v", check.ID(), err)
|
2016-06-10 01:32:04 +00:00
|
|
|
c.consulAvailable = false
|
2016-04-02 21:48:10 +00:00
|
|
|
} else {
|
2016-06-10 01:32:04 +00:00
|
|
|
c.consulAvailable = true
|
2016-04-02 21:48:10 +00:00
|
|
|
}
|
2016-03-24 20:05:08 +00:00
|
|
|
}
|
|
|
|
}
|
2016-05-14 07:36:26 +00:00
|
|
|
|
2016-06-14 00:32:18 +00:00
|
|
|
// ReapUnmatched prunes all services that do not exist in the passed domains
|
|
|
|
func (c *Syncer) ReapUnmatched(domains []ServiceDomain) error {
|
2016-06-13 12:05:35 +00:00
|
|
|
servicesInConsul, err := c.ConsulClient().Agent().Services()
|
|
|
|
if err != nil {
|
2016-06-13 23:29:07 +00:00
|
|
|
return err
|
2016-06-13 12:05:35 +00:00
|
|
|
}
|
|
|
|
|
2016-06-13 23:29:07 +00:00
|
|
|
var mErr multierror.Error
|
|
|
|
for serviceID := range servicesInConsul {
|
|
|
|
// Skip any service that was not registered by Nomad
|
|
|
|
if !strings.HasPrefix(serviceID, nomadServicePrefix) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Filter services that do not exist in the desired domains
|
|
|
|
match := false
|
|
|
|
for _, domain := range domains {
|
|
|
|
// Include the hyphen so it is explicit to that domain otherwise it
|
|
|
|
// maybe a subset match
|
|
|
|
desired := fmt.Sprintf("%s-%s-", nomadServicePrefix, domain)
|
|
|
|
if strings.HasPrefix(serviceID, desired) {
|
|
|
|
match = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !match {
|
|
|
|
if err := c.deregisterService(serviceID); err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, err)
|
|
|
|
}
|
2016-06-13 12:05:35 +00:00
|
|
|
}
|
|
|
|
}
|
2016-06-13 23:29:07 +00:00
|
|
|
|
|
|
|
return mErr.ErrorOrNil()
|
2016-06-13 12:05:35 +00:00
|
|
|
}
|
|
|
|
|
2016-05-24 06:23:57 +00:00
|
|
|
// AddPeriodicHandler adds a uniquely named callback. Returns true if
|
|
|
|
// successful, false if a handler with the same name already exists.
|
|
|
|
func (c *Syncer) AddPeriodicHandler(name string, fn types.PeriodicCallback) bool {
|
|
|
|
c.periodicLock.Lock()
|
|
|
|
defer c.periodicLock.Unlock()
|
|
|
|
if _, found := c.periodicCallbacks[name]; found {
|
2016-06-11 22:17:20 +00:00
|
|
|
c.logger.Printf("[ERROR] consul.syncer: failed adding handler %+q", name)
|
2016-05-24 06:23:57 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
c.periodicCallbacks[name] = fn
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2016-06-11 03:26:15 +00:00
|
|
|
// NumHandlers returns the number of callbacks registered with the syncer
|
2016-05-24 06:23:57 +00:00
|
|
|
func (c *Syncer) NumHandlers() int {
|
|
|
|
c.periodicLock.RLock()
|
|
|
|
defer c.periodicLock.RUnlock()
|
|
|
|
return len(c.periodicCallbacks)
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemovePeriodicHandler removes a handler with a given name.
|
|
|
|
func (c *Syncer) RemovePeriodicHandler(name string) {
|
|
|
|
c.periodicLock.Lock()
|
|
|
|
defer c.periodicLock.Unlock()
|
|
|
|
delete(c.periodicCallbacks, name)
|
|
|
|
}
|
|
|
|
|
2016-06-11 03:26:15 +00:00
|
|
|
// ConsulClient returns the Consul client used by the Syncer.
|
2016-05-24 06:23:57 +00:00
|
|
|
func (c *Syncer) ConsulClient() *consul.Client {
|
|
|
|
return c.client
|
|
|
|
}
|