2019-11-27 21:41:45 +00:00
|
|
|
package taskrunner
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2019-12-18 16:23:16 +00:00
|
|
|
"github.com/hashicorp/go-hclog"
|
2019-11-27 21:41:45 +00:00
|
|
|
"github.com/hashicorp/nomad/client/allocrunner/interfaces"
|
2019-12-06 20:46:46 +00:00
|
|
|
ti "github.com/hashicorp/nomad/client/allocrunner/taskrunner/interfaces"
|
2019-11-27 21:41:45 +00:00
|
|
|
"github.com/hashicorp/nomad/client/consul"
|
|
|
|
"github.com/hashicorp/nomad/nomad/structs"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// the name of this hook, used in logs
|
2020-01-15 14:41:23 +00:00
|
|
|
sidsHookName = "consul_si_token"
|
2019-11-27 21:41:45 +00:00
|
|
|
|
|
|
|
// sidsBackoffBaseline is the baseline time for exponential backoff when
|
|
|
|
// attempting to retrieve a Consul SI token
|
|
|
|
sidsBackoffBaseline = 5 * time.Second
|
|
|
|
|
|
|
|
// sidsBackoffLimit is the limit of the exponential backoff when attempting
|
|
|
|
// to retrieve a Consul SI token
|
|
|
|
sidsBackoffLimit = 3 * time.Minute
|
|
|
|
|
2020-01-15 15:56:48 +00:00
|
|
|
// sidsDerivationTimeout limits the amount of time we may spend trying to
|
|
|
|
// derive a SI token. If the hook does not get a token within this amount of
|
|
|
|
// time, the result is a failure.
|
|
|
|
sidsDerivationTimeout = 5 * time.Minute
|
|
|
|
|
2019-11-27 21:41:45 +00:00
|
|
|
// sidsTokenFile is the name of the file holding the Consul SI token inside
|
|
|
|
// the task's secret directory
|
2019-12-06 20:46:46 +00:00
|
|
|
sidsTokenFile = "si_token"
|
2019-11-27 21:41:45 +00:00
|
|
|
|
|
|
|
// sidsTokenFilePerms is the level of file permissions granted on the file
|
|
|
|
// in the secrets directory for the task
|
|
|
|
sidsTokenFilePerms = 0440
|
|
|
|
)
|
|
|
|
|
|
|
|
type sidsHookConfig struct {
|
|
|
|
alloc *structs.Allocation
|
|
|
|
task *structs.Task
|
|
|
|
sidsClient consul.ServiceIdentityAPI
|
2019-12-06 20:46:46 +00:00
|
|
|
lifecycle ti.TaskLifecycle
|
2019-11-27 21:41:45 +00:00
|
|
|
logger hclog.Logger
|
|
|
|
}
|
|
|
|
|
|
|
|
// Service Identities hook for managing SI tokens of connect enabled tasks.
|
|
|
|
type sidsHook struct {
|
2019-12-06 20:46:46 +00:00
|
|
|
// alloc is the allocation
|
|
|
|
alloc *structs.Allocation
|
|
|
|
|
|
|
|
// taskName is the name of the task
|
2019-12-18 16:23:16 +00:00
|
|
|
task *structs.Task
|
2019-12-06 20:46:46 +00:00
|
|
|
|
|
|
|
// sidsClient is the Consul client [proxy] for requesting SI tokens
|
2019-11-27 21:41:45 +00:00
|
|
|
sidsClient consul.ServiceIdentityAPI
|
|
|
|
|
2019-12-06 20:46:46 +00:00
|
|
|
// lifecycle is used to signal, restart, and kill a task
|
|
|
|
lifecycle ti.TaskLifecycle
|
|
|
|
|
2020-01-15 15:56:48 +00:00
|
|
|
// derivationTimeout is the amount of time we may wait for Consul to successfully
|
|
|
|
// provide a SI token. Making this configurable for testing, otherwise
|
|
|
|
// default to sidsDerivationTimeout
|
|
|
|
derivationTimeout time.Duration
|
|
|
|
|
2019-12-06 20:46:46 +00:00
|
|
|
// logger is used to log
|
|
|
|
logger hclog.Logger
|
|
|
|
|
|
|
|
// lock variables that can be manipulated after hook creation
|
|
|
|
lock sync.Mutex
|
|
|
|
// firstRun keeps track of whether the hook is being called for the first
|
|
|
|
// time (for this task) during the lifespan of the Nomad Client process.
|
2019-11-27 21:41:45 +00:00
|
|
|
firstRun bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func newSIDSHook(c sidsHookConfig) *sidsHook {
|
|
|
|
return &sidsHook{
|
2020-01-15 15:56:48 +00:00
|
|
|
alloc: c.alloc,
|
|
|
|
task: c.task,
|
|
|
|
sidsClient: c.sidsClient,
|
|
|
|
lifecycle: c.lifecycle,
|
|
|
|
derivationTimeout: sidsDerivationTimeout,
|
|
|
|
logger: c.logger.Named(sidsHookName),
|
|
|
|
firstRun: true,
|
2019-11-27 21:41:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *sidsHook) Name() string {
|
|
|
|
return sidsHookName
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *sidsHook) Prestart(
|
|
|
|
ctx context.Context,
|
|
|
|
req *interfaces.TaskPrestartRequest,
|
2019-12-18 16:23:16 +00:00
|
|
|
resp *interfaces.TaskPrestartResponse) error {
|
2019-11-27 21:41:45 +00:00
|
|
|
|
|
|
|
h.lock.Lock()
|
|
|
|
defer h.lock.Unlock()
|
|
|
|
|
|
|
|
// do nothing if we have already done things
|
|
|
|
if h.earlyExit() {
|
2019-12-18 16:23:16 +00:00
|
|
|
resp.Done = true
|
2019-11-27 21:41:45 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// optimistically try to recover token from disk
|
|
|
|
token, err := h.recoverToken(req.TaskDir.SecretsDir)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// need to ask for a new SI token & persist it to disk
|
|
|
|
if token == "" {
|
|
|
|
if token, err = h.deriveSIToken(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := h.writeToken(req.TaskDir.SecretsDir, token); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-18 16:23:16 +00:00
|
|
|
h.logger.Info("derived SI token", "task", h.task.Name, "si_task", h.task.Kind.Value())
|
|
|
|
|
|
|
|
resp.Done = true
|
2019-11-27 21:41:45 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// earlyExit returns true if the Prestart hook has already been executed during
|
|
|
|
// the instantiation of this task runner.
|
|
|
|
//
|
|
|
|
// assumes h is locked
|
|
|
|
func (h *sidsHook) earlyExit() bool {
|
|
|
|
if h.firstRun {
|
|
|
|
h.firstRun = false
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// writeToken writes token into the secrets directory for the task.
|
|
|
|
func (h *sidsHook) writeToken(dir string, token string) error {
|
|
|
|
tokenPath := filepath.Join(dir, sidsTokenFile)
|
|
|
|
if err := ioutil.WriteFile(tokenPath, []byte(token), sidsTokenFilePerms); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to write SI token")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// recoverToken returns the token saved to disk in the secrets directory for the
|
|
|
|
// task if it exists, or the empty string if the file does not exist. an error
|
|
|
|
// is returned only for some other (e.g. disk IO) error.
|
|
|
|
func (h *sidsHook) recoverToken(dir string) (string, error) {
|
|
|
|
tokenPath := filepath.Join(dir, sidsTokenFile)
|
|
|
|
token, err := ioutil.ReadFile(tokenPath)
|
|
|
|
if err != nil {
|
|
|
|
if !os.IsNotExist(err) {
|
2019-12-18 16:23:16 +00:00
|
|
|
h.logger.Error("failed to recover SI token", "error", err)
|
2019-11-27 21:41:45 +00:00
|
|
|
return "", errors.Wrap(err, "failed to recover SI token")
|
|
|
|
}
|
2019-12-18 16:23:16 +00:00
|
|
|
h.logger.Trace("no pre-existing SI token to recover", "task", h.task.Name)
|
2019-11-27 21:41:45 +00:00
|
|
|
return "", nil // token file does not exist yet
|
|
|
|
}
|
2019-12-18 16:23:16 +00:00
|
|
|
h.logger.Trace("recovered pre-existing SI token", "task", h.task.Name)
|
2019-11-27 21:41:45 +00:00
|
|
|
return string(token), nil
|
|
|
|
}
|
|
|
|
|
2020-01-15 16:41:52 +00:00
|
|
|
// siDerivationResult is used to pass along the result of attempting to derive
|
|
|
|
// an SI token between the goroutine doing the derivation and its caller
|
|
|
|
type siDerivationResult struct {
|
|
|
|
token string
|
|
|
|
err error
|
|
|
|
}
|
|
|
|
|
2019-11-27 21:41:45 +00:00
|
|
|
// deriveSIToken spawns and waits on a goroutine which will make attempts to
|
|
|
|
// derive an SI token until a token is successfully created, or ctx is signaled
|
|
|
|
// done.
|
|
|
|
func (h *sidsHook) deriveSIToken(ctx context.Context) (string, error) {
|
2020-01-30 18:59:04 +00:00
|
|
|
ctx, cancel := context.WithTimeout(ctx, h.derivationTimeout)
|
2020-01-15 15:56:48 +00:00
|
|
|
defer cancel()
|
|
|
|
|
2020-01-15 16:41:52 +00:00
|
|
|
resultCh := make(chan siDerivationResult)
|
2019-11-27 21:41:45 +00:00
|
|
|
|
|
|
|
// keep trying to get the token in the background
|
2020-01-30 18:59:04 +00:00
|
|
|
go h.tryDerive(ctx, resultCh)
|
2019-11-27 21:41:45 +00:00
|
|
|
|
|
|
|
// wait until we get a token, or we get a signal to quit
|
|
|
|
for {
|
|
|
|
select {
|
2020-01-15 16:41:52 +00:00
|
|
|
case result := <-resultCh:
|
|
|
|
if result.err != nil {
|
2020-01-30 19:40:56 +00:00
|
|
|
h.logger.Error("failed to derive SI token", "error", result.err)
|
|
|
|
h.kill(ctx, errors.Wrap(result.err, "failed to derive SI token"))
|
2020-01-15 16:41:52 +00:00
|
|
|
return "", result.err
|
|
|
|
}
|
|
|
|
return result.token, nil
|
2020-01-30 18:59:04 +00:00
|
|
|
case <-ctx.Done():
|
|
|
|
return "", ctx.Err()
|
2019-11-27 21:41:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-30 19:40:56 +00:00
|
|
|
func (h *sidsHook) kill(ctx context.Context, reason error) {
|
|
|
|
if err := h.lifecycle.Kill(ctx,
|
2019-12-06 20:46:46 +00:00
|
|
|
structs.NewTaskEvent(structs.TaskKilling).
|
|
|
|
SetFailsTask().
|
2020-01-30 19:40:56 +00:00
|
|
|
SetDisplayMessage(reason.Error()),
|
|
|
|
); err != nil {
|
|
|
|
h.logger.Error("failed to kill task", "kill_reason", reason, "error", err)
|
|
|
|
}
|
2019-12-06 20:46:46 +00:00
|
|
|
}
|
|
|
|
|
2019-11-27 21:41:45 +00:00
|
|
|
// tryDerive loops forever until a token is created, or ctx is done.
|
2020-01-15 16:41:52 +00:00
|
|
|
func (h *sidsHook) tryDerive(ctx context.Context, ch chan<- siDerivationResult) {
|
2019-12-06 20:46:46 +00:00
|
|
|
for attempt := 0; backoff(ctx, attempt); attempt++ {
|
|
|
|
|
2019-12-19 23:40:30 +00:00
|
|
|
tokens, err := h.sidsClient.DeriveSITokens(h.alloc, []string{h.task.Name})
|
2019-12-06 20:46:46 +00:00
|
|
|
|
|
|
|
switch {
|
|
|
|
case err == nil:
|
2020-01-15 16:41:52 +00:00
|
|
|
token, exists := tokens[h.task.Name]
|
|
|
|
if !exists {
|
|
|
|
err := errors.New("response does not include token for task")
|
|
|
|
h.logger.Error("derive SI token is missing token for task", "error", err, "task", h.task.Name)
|
|
|
|
ch <- siDerivationResult{token: "", err: err}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
ch <- siDerivationResult{token: token, err: nil}
|
2019-12-06 20:46:46 +00:00
|
|
|
return
|
|
|
|
case structs.IsServerSide(err):
|
|
|
|
// the error is known to be a server problem, just die
|
2019-12-19 23:40:30 +00:00
|
|
|
h.logger.Error("failed to derive SI token", "error", err, "task", h.task.Name, "server_side", true)
|
2020-01-15 16:41:52 +00:00
|
|
|
ch <- siDerivationResult{token: "", err: err}
|
|
|
|
return
|
2019-12-06 20:46:46 +00:00
|
|
|
case !structs.IsRecoverable(err):
|
|
|
|
// the error is known not to be recoverable, just die
|
2019-12-19 23:40:30 +00:00
|
|
|
h.logger.Error("failed to derive SI token", "error", err, "task", h.task.Name, "recoverable", false)
|
2020-01-15 16:41:52 +00:00
|
|
|
ch <- siDerivationResult{token: "", err: err}
|
|
|
|
return
|
2019-12-06 20:46:46 +00:00
|
|
|
|
|
|
|
default:
|
|
|
|
// the error is marked recoverable, retry after some backoff
|
2020-01-15 16:41:52 +00:00
|
|
|
h.logger.Error("failed attempt to derive SI token", "error", err, "recoverable", true)
|
2019-11-27 21:41:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-18 16:23:16 +00:00
|
|
|
func backoff(ctx context.Context, attempt int) bool {
|
|
|
|
next := computeBackoff(attempt)
|
2019-11-27 21:41:45 +00:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return false
|
|
|
|
case <-time.After(next):
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func computeBackoff(attempt int) time.Duration {
|
2019-12-06 20:46:46 +00:00
|
|
|
switch attempt {
|
|
|
|
case 0:
|
2019-11-27 21:41:45 +00:00
|
|
|
return 0
|
2019-12-06 20:46:46 +00:00
|
|
|
case 1:
|
|
|
|
// go fast on first retry, because a unit test should be fast
|
|
|
|
return 100 * time.Millisecond
|
2019-11-27 21:41:45 +00:00
|
|
|
default:
|
2019-12-06 20:46:46 +00:00
|
|
|
wait := time.Duration(attempt) * sidsBackoffBaseline
|
|
|
|
if wait > sidsBackoffLimit {
|
|
|
|
wait = sidsBackoffLimit
|
|
|
|
}
|
|
|
|
return wait
|
2019-11-27 21:41:45 +00:00
|
|
|
}
|
|
|
|
}
|