2015-08-23 22:30:16 +00:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
2017-04-29 22:43:23 +00:00
|
|
|
"bytes"
|
2015-08-30 01:16:49 +00:00
|
|
|
"crypto/md5"
|
|
|
|
"encoding/hex"
|
2015-08-29 22:46:10 +00:00
|
|
|
"fmt"
|
2017-04-29 22:43:23 +00:00
|
|
|
"io"
|
2016-10-17 18:41:22 +00:00
|
|
|
"io/ioutil"
|
2015-08-23 22:30:16 +00:00
|
|
|
"log"
|
2015-08-30 01:16:49 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2016-06-03 21:23:18 +00:00
|
|
|
"strings"
|
2015-08-23 22:30:16 +00:00
|
|
|
"sync"
|
2015-11-03 17:24:26 +00:00
|
|
|
"time"
|
2015-08-23 22:30:16 +00:00
|
|
|
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics "github.com/armon/go-metrics"
|
2017-04-29 22:43:23 +00:00
|
|
|
"github.com/boltdb/bolt"
|
2016-12-16 23:11:56 +00:00
|
|
|
"github.com/golang/snappy"
|
2016-10-17 18:41:22 +00:00
|
|
|
"github.com/hashicorp/consul-template/signals"
|
2016-02-07 01:08:12 +00:00
|
|
|
"github.com/hashicorp/go-multierror"
|
2017-04-21 19:20:05 +00:00
|
|
|
version "github.com/hashicorp/go-version"
|
2016-12-16 23:11:56 +00:00
|
|
|
"github.com/hashicorp/nomad/client/allocdir"
|
2015-08-30 01:16:49 +00:00
|
|
|
"github.com/hashicorp/nomad/client/config"
|
2015-08-23 23:49:48 +00:00
|
|
|
"github.com/hashicorp/nomad/client/driver"
|
2016-03-15 17:53:20 +00:00
|
|
|
"github.com/hashicorp/nomad/client/getter"
|
2016-10-17 18:41:22 +00:00
|
|
|
"github.com/hashicorp/nomad/client/vaultclient"
|
2015-08-23 22:30:16 +00:00
|
|
|
"github.com/hashicorp/nomad/nomad/structs"
|
2017-05-01 22:06:18 +00:00
|
|
|
"github.com/ugorji/go/codec"
|
2015-11-14 06:07:13 +00:00
|
|
|
|
2016-04-12 01:46:16 +00:00
|
|
|
"github.com/hashicorp/nomad/client/driver/env"
|
2016-06-12 03:15:50 +00:00
|
|
|
dstructs "github.com/hashicorp/nomad/client/driver/structs"
|
|
|
|
cstructs "github.com/hashicorp/nomad/client/structs"
|
2015-08-23 22:30:16 +00:00
|
|
|
)
|
|
|
|
|
2016-02-17 05:00:49 +00:00
|
|
|
const (
|
|
|
|
// killBackoffBaseline is the baseline time for exponential backoff while
|
|
|
|
// killing a task.
|
|
|
|
killBackoffBaseline = 5 * time.Second
|
|
|
|
|
2016-10-11 19:31:40 +00:00
|
|
|
// killBackoffLimit is the limit of the exponential backoff for killing
|
2016-02-17 05:00:49 +00:00
|
|
|
// the task.
|
2016-03-03 00:27:01 +00:00
|
|
|
killBackoffLimit = 2 * time.Minute
|
2016-02-17 05:00:49 +00:00
|
|
|
|
|
|
|
// killFailureLimit is how many times we will attempt to kill a task before
|
|
|
|
// giving up and potentially leaking resources.
|
2016-03-03 00:27:01 +00:00
|
|
|
killFailureLimit = 5
|
2016-10-17 18:41:22 +00:00
|
|
|
|
|
|
|
// vaultBackoffBaseline is the baseline time for exponential backoff when
|
|
|
|
// attempting to retrieve a Vault token
|
|
|
|
vaultBackoffBaseline = 5 * time.Second
|
|
|
|
|
|
|
|
// vaultBackoffLimit is the limit of the exponential backoff when attempting
|
|
|
|
// to retrieve a Vault token
|
|
|
|
vaultBackoffLimit = 3 * time.Minute
|
|
|
|
|
|
|
|
// vaultTokenFile is the name of the file holding the Vault token inside the
|
|
|
|
// task's secret directory
|
|
|
|
vaultTokenFile = "vault_token"
|
2016-02-17 05:00:49 +00:00
|
|
|
)
|
|
|
|
|
2017-04-29 22:43:23 +00:00
|
|
|
var (
|
|
|
|
// taskRunnerStateAllKey holds all the task runners state. At the moment
|
|
|
|
// there is no need to split it
|
|
|
|
taskRunnerStateAllKey = []byte("simple-all")
|
|
|
|
)
|
|
|
|
|
2017-09-10 23:25:13 +00:00
|
|
|
// taskRestartEvent wraps a TaskEvent with additional metadata to control
|
|
|
|
// restart behavior.
|
|
|
|
type taskRestartEvent struct {
|
|
|
|
// taskEvent to report
|
|
|
|
taskEvent *structs.TaskEvent
|
|
|
|
|
|
|
|
// if false, don't count against restart count
|
|
|
|
failure bool
|
|
|
|
}
|
|
|
|
|
2017-09-13 06:15:46 +00:00
|
|
|
func newTaskRestartEvent(reason string, failure bool) *taskRestartEvent {
|
2017-09-10 23:25:13 +00:00
|
|
|
return &taskRestartEvent{
|
2017-09-13 06:15:46 +00:00
|
|
|
taskEvent: structs.NewTaskEvent(structs.TaskRestartSignal).SetRestartReason(reason),
|
2017-09-10 23:25:13 +00:00
|
|
|
failure: failure,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-08-23 22:32:46 +00:00
|
|
|
// TaskRunner is used to wrap a task within an allocation and provide the execution context.
|
|
|
|
type TaskRunner struct {
|
2017-04-29 22:43:23 +00:00
|
|
|
stateDB *bolt.DB
|
2015-11-05 19:12:31 +00:00
|
|
|
config *config.Config
|
|
|
|
updater TaskStateUpdater
|
|
|
|
logger *log.Logger
|
2015-12-18 20:17:13 +00:00
|
|
|
restartTracker *RestartTracker
|
2017-02-01 00:43:57 +00:00
|
|
|
consul ConsulServiceAPI
|
2015-08-23 22:30:16 +00:00
|
|
|
|
2016-06-12 03:15:50 +00:00
|
|
|
// running marks whether the task is running
|
|
|
|
running bool
|
|
|
|
runningLock sync.Mutex
|
|
|
|
|
2016-06-12 16:32:38 +00:00
|
|
|
resourceUsage *cstructs.TaskResourceUsage
|
2016-05-25 04:33:13 +00:00
|
|
|
resourceUsageLock sync.RWMutex
|
2016-04-29 18:06:19 +00:00
|
|
|
|
2017-09-10 23:25:13 +00:00
|
|
|
alloc *structs.Allocation
|
2016-10-17 18:41:22 +00:00
|
|
|
task *structs.Task
|
2016-12-03 01:04:07 +00:00
|
|
|
taskDir *allocdir.TaskDir
|
2016-10-17 18:41:22 +00:00
|
|
|
|
2017-05-17 00:33:50 +00:00
|
|
|
// envBuilder is used to build the task's environment
|
|
|
|
envBuilder *env.Builder
|
2016-10-17 18:41:22 +00:00
|
|
|
|
2017-06-16 23:35:16 +00:00
|
|
|
// driverNet is the network information returned by the driver
|
|
|
|
driverNet *cstructs.DriverNetwork
|
|
|
|
driverNetLock sync.Mutex
|
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
// updateCh is used to receive updated versions of the allocation
|
2016-06-12 03:15:50 +00:00
|
|
|
updateCh chan *structs.Allocation
|
|
|
|
|
2016-02-10 21:44:53 +00:00
|
|
|
handle driver.DriverHandle
|
|
|
|
handleLock sync.Mutex
|
2015-08-23 22:30:16 +00:00
|
|
|
|
2016-03-15 17:53:20 +00:00
|
|
|
// artifactsDownloaded tracks whether the tasks artifacts have been
|
|
|
|
// downloaded
|
2016-12-03 01:04:07 +00:00
|
|
|
//
|
|
|
|
// Must acquire persistLock when accessing
|
2016-03-15 17:53:20 +00:00
|
|
|
artifactsDownloaded bool
|
|
|
|
|
2016-12-03 01:04:07 +00:00
|
|
|
// taskDirBuilt tracks whether the task has built its directory.
|
|
|
|
//
|
|
|
|
// Must acquire persistLock when accessing
|
|
|
|
taskDirBuilt bool
|
|
|
|
|
2017-01-10 21:24:45 +00:00
|
|
|
// createdResources are all the resources created by the task driver
|
|
|
|
// across all attempts to start the task.
|
2017-02-10 01:44:58 +00:00
|
|
|
// Simple gets and sets should use {get,set}CreatedResources
|
2017-01-14 00:46:08 +00:00
|
|
|
createdResources *driver.CreatedResources
|
|
|
|
createdResourcesLock sync.Mutex
|
2017-01-10 21:24:45 +00:00
|
|
|
|
2016-12-16 23:11:56 +00:00
|
|
|
// payloadRendered tracks whether the payload has been rendered to disk
|
|
|
|
payloadRendered bool
|
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
// vaultFuture is the means to wait for and get a Vault token
|
|
|
|
vaultFuture *tokenFuture
|
|
|
|
|
|
|
|
// recoveredVaultToken is the token that was recovered through a restore
|
|
|
|
recoveredVaultToken string
|
|
|
|
|
|
|
|
// vaultClient is used to retrieve and renew any needed Vault token
|
|
|
|
vaultClient vaultclient.VaultClient
|
2016-09-14 20:30:01 +00:00
|
|
|
|
2016-10-05 20:41:29 +00:00
|
|
|
// templateManager is used to manage any consul-templates this task may have
|
|
|
|
templateManager *TaskTemplateManager
|
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
// startCh is used to trigger the start of the task
|
|
|
|
startCh chan struct{}
|
|
|
|
|
2016-10-05 20:41:29 +00:00
|
|
|
// unblockCh is used to unblock the starting of the task
|
|
|
|
unblockCh chan struct{}
|
|
|
|
unblocked bool
|
|
|
|
unblockLock sync.Mutex
|
|
|
|
|
|
|
|
// restartCh is used to restart a task
|
2017-09-10 23:25:13 +00:00
|
|
|
restartCh chan *taskRestartEvent
|
2016-10-05 20:41:29 +00:00
|
|
|
|
|
|
|
// signalCh is used to send a signal to a task
|
|
|
|
signalCh chan SignalEvent
|
|
|
|
|
2016-08-11 07:20:53 +00:00
|
|
|
destroy bool
|
|
|
|
destroyCh chan struct{}
|
|
|
|
destroyLock sync.Mutex
|
|
|
|
destroyEvent *structs.TaskEvent
|
2016-10-17 18:41:22 +00:00
|
|
|
|
|
|
|
// waitCh closing marks the run loop as having exited
|
|
|
|
waitCh chan struct{}
|
2016-09-02 22:39:22 +00:00
|
|
|
|
2017-01-10 21:24:45 +00:00
|
|
|
// persistLock must be acquired when accessing fields stored by
|
|
|
|
// SaveState. SaveState is called asynchronously to TaskRunner.Run by
|
|
|
|
// AllocRunner, so all state fields must be synchronized using this
|
|
|
|
// lock.
|
2016-09-02 22:39:22 +00:00
|
|
|
persistLock sync.Mutex
|
2017-04-29 22:43:23 +00:00
|
|
|
|
|
|
|
// persistedHash is the hash of the last persisted snapshot. It is used to
|
2017-08-07 21:13:05 +00:00
|
|
|
// detect if a new snapshot has to be written to disk.
|
2017-04-29 22:43:23 +00:00
|
|
|
persistedHash []byte
|
2017-08-31 19:22:53 +00:00
|
|
|
|
|
|
|
// baseLabels are used when emitting tagged metrics. All task runner metrics
|
|
|
|
// will have these tags, and optionally more.
|
|
|
|
baseLabels []metrics.Label
|
2015-08-23 22:30:16 +00:00
|
|
|
}
|
|
|
|
|
2015-08-30 01:16:49 +00:00
|
|
|
// taskRunnerState is used to snapshot the state of the task runner
|
|
|
|
type taskRunnerState struct {
|
2016-03-29 00:24:10 +00:00
|
|
|
Version string
|
|
|
|
HandleID string
|
|
|
|
ArtifactDownloaded bool
|
2016-12-03 01:04:07 +00:00
|
|
|
TaskDirBuilt bool
|
2016-12-16 23:11:56 +00:00
|
|
|
PayloadRendered bool
|
2017-04-29 22:43:23 +00:00
|
|
|
CreatedResources *driver.CreatedResources
|
2017-06-16 23:35:16 +00:00
|
|
|
DriverNetwork *cstructs.DriverNetwork
|
2017-04-29 22:43:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *taskRunnerState) Hash() []byte {
|
|
|
|
h := md5.New()
|
|
|
|
|
|
|
|
io.WriteString(h, s.Version)
|
|
|
|
io.WriteString(h, s.HandleID)
|
|
|
|
io.WriteString(h, fmt.Sprintf("%v", s.ArtifactDownloaded))
|
|
|
|
io.WriteString(h, fmt.Sprintf("%v", s.TaskDirBuilt))
|
|
|
|
io.WriteString(h, fmt.Sprintf("%v", s.PayloadRendered))
|
|
|
|
h.Write(s.CreatedResources.Hash())
|
2017-06-16 23:35:16 +00:00
|
|
|
h.Write(s.DriverNetwork.Hash())
|
2017-04-29 22:43:23 +00:00
|
|
|
|
|
|
|
return h.Sum(nil)
|
2015-08-30 01:16:49 +00:00
|
|
|
}
|
|
|
|
|
2017-08-10 00:25:29 +00:00
|
|
|
// TaskStateUpdater is used to signal that tasks state has changed. If lazySync
|
|
|
|
// is set the event won't be immediately pushed to the server.
|
2017-08-08 04:26:04 +00:00
|
|
|
type TaskStateUpdater func(taskName, state string, event *structs.TaskEvent, lazySync bool)
|
2015-08-30 02:42:35 +00:00
|
|
|
|
2016-10-05 20:41:29 +00:00
|
|
|
// SignalEvent is a tuple of the signal and the event generating it
|
|
|
|
type SignalEvent struct {
|
2016-10-10 21:49:37 +00:00
|
|
|
// s is the signal to be sent
|
2016-10-05 20:41:29 +00:00
|
|
|
s os.Signal
|
2016-10-10 21:49:37 +00:00
|
|
|
|
|
|
|
// e is the task event generating the signal
|
2016-10-05 20:41:29 +00:00
|
|
|
e *structs.TaskEvent
|
2016-10-10 21:49:37 +00:00
|
|
|
|
|
|
|
// result should be used to send back the result of the signal
|
|
|
|
result chan<- error
|
2016-10-05 20:41:29 +00:00
|
|
|
}
|
|
|
|
|
2015-08-23 22:32:46 +00:00
|
|
|
// NewTaskRunner is used to create a new task context
|
2015-08-30 02:42:35 +00:00
|
|
|
func NewTaskRunner(logger *log.Logger, config *config.Config,
|
2017-04-29 22:43:23 +00:00
|
|
|
stateDB *bolt.DB, updater TaskStateUpdater, taskDir *allocdir.TaskDir,
|
2016-10-17 18:41:22 +00:00
|
|
|
alloc *structs.Allocation, task *structs.Task,
|
2017-02-01 00:43:57 +00:00
|
|
|
vaultClient vaultclient.VaultClient, consulClient ConsulServiceAPI) *TaskRunner {
|
2016-02-04 00:16:48 +00:00
|
|
|
|
2016-02-05 20:07:56 +00:00
|
|
|
// Merge in the task resources
|
|
|
|
task.Resources = alloc.TaskResources[task.Name]
|
|
|
|
|
2016-02-04 00:16:48 +00:00
|
|
|
// Build the restart tracker.
|
|
|
|
tg := alloc.Job.LookupTaskGroup(alloc.TaskGroup)
|
|
|
|
if tg == nil {
|
2017-11-03 22:42:15 +00:00
|
|
|
logger.Printf("[ERR] client: alloc %q for missing task group %q", alloc.ID, alloc.TaskGroup)
|
2016-02-04 00:16:48 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
restartTracker := newRestartTracker(tg.RestartPolicy, alloc.Job.Type)
|
2015-11-03 17:24:26 +00:00
|
|
|
|
2017-05-17 00:33:50 +00:00
|
|
|
// Initialize the environment builder
|
2017-05-18 18:34:40 +00:00
|
|
|
envBuilder := env.NewBuilder(config.Node, alloc, task, config.Region)
|
2017-05-17 00:33:50 +00:00
|
|
|
|
2015-08-23 22:32:46 +00:00
|
|
|
tc := &TaskRunner{
|
2017-01-10 21:24:45 +00:00
|
|
|
config: config,
|
2017-04-29 22:43:23 +00:00
|
|
|
stateDB: stateDB,
|
2017-01-10 21:24:45 +00:00
|
|
|
updater: updater,
|
|
|
|
logger: logger,
|
|
|
|
restartTracker: restartTracker,
|
|
|
|
alloc: alloc,
|
|
|
|
task: task,
|
|
|
|
taskDir: taskDir,
|
2017-05-17 00:33:50 +00:00
|
|
|
envBuilder: envBuilder,
|
2017-01-10 21:24:45 +00:00
|
|
|
createdResources: driver.NewCreatedResources(),
|
2017-02-01 00:43:57 +00:00
|
|
|
consul: consulClient,
|
2017-01-10 21:24:45 +00:00
|
|
|
vaultClient: vaultClient,
|
|
|
|
vaultFuture: NewTokenFuture().Set(""),
|
|
|
|
updateCh: make(chan *structs.Allocation, 64),
|
|
|
|
destroyCh: make(chan struct{}),
|
|
|
|
waitCh: make(chan struct{}),
|
|
|
|
startCh: make(chan struct{}, 1),
|
|
|
|
unblockCh: make(chan struct{}),
|
2017-09-10 23:25:13 +00:00
|
|
|
restartCh: make(chan *taskRestartEvent),
|
2017-01-10 21:24:45 +00:00
|
|
|
signalCh: make(chan SignalEvent),
|
2015-08-23 22:30:16 +00:00
|
|
|
}
|
2016-02-19 22:49:43 +00:00
|
|
|
|
2017-09-26 22:26:33 +00:00
|
|
|
tc.baseLabels = []metrics.Label{
|
|
|
|
{
|
|
|
|
Name: "job",
|
|
|
|
Value: tc.alloc.Job.Name,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Name: "task_group",
|
|
|
|
Value: tc.alloc.TaskGroup,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Name: "alloc_id",
|
|
|
|
Value: tc.alloc.ID,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Name: "task",
|
|
|
|
Value: tc.task.Name,
|
|
|
|
},
|
|
|
|
}
|
2017-08-31 19:22:53 +00:00
|
|
|
|
2015-08-23 22:30:16 +00:00
|
|
|
return tc
|
|
|
|
}
|
|
|
|
|
2016-03-22 20:49:52 +00:00
|
|
|
// MarkReceived marks the task as received.
|
|
|
|
func (r *TaskRunner) MarkReceived() {
|
2017-09-26 22:26:33 +00:00
|
|
|
// We lazy sync this since there will be a follow up message almost
|
|
|
|
// immediately.
|
|
|
|
r.updater(r.task.Name, structs.TaskStatePending, structs.NewTaskEvent(structs.TaskReceived), true)
|
2016-03-22 20:49:52 +00:00
|
|
|
}
|
|
|
|
|
2015-08-29 22:46:10 +00:00
|
|
|
// WaitCh returns a channel to wait for termination
|
|
|
|
func (r *TaskRunner) WaitCh() <-chan struct{} {
|
|
|
|
return r.waitCh
|
|
|
|
}
|
|
|
|
|
2017-07-21 21:00:32 +00:00
|
|
|
// getHandle returns the task's handle or nil
|
|
|
|
func (r *TaskRunner) getHandle() driver.DriverHandle {
|
|
|
|
r.handleLock.Lock()
|
|
|
|
h := r.handle
|
|
|
|
r.handleLock.Unlock()
|
|
|
|
return h
|
|
|
|
}
|
|
|
|
|
2017-05-02 20:31:56 +00:00
|
|
|
// pre060StateFilePath returns the path to our state file that would have been
|
|
|
|
// written pre v0.6.0
|
|
|
|
// COMPAT: Remove in 0.7.0
|
|
|
|
func (r *TaskRunner) pre060StateFilePath() string {
|
2015-08-30 01:16:49 +00:00
|
|
|
// Get the MD5 of the task name
|
|
|
|
hashVal := md5.Sum([]byte(r.task.Name))
|
|
|
|
hashHex := hex.EncodeToString(hashVal[:])
|
|
|
|
dirName := fmt.Sprintf("task-%s", hashHex)
|
|
|
|
|
|
|
|
// Generate the path
|
2017-05-02 20:31:56 +00:00
|
|
|
return filepath.Join(r.config.StateDir, "alloc", r.alloc.ID, dirName, "state.json")
|
2015-08-30 01:16:49 +00:00
|
|
|
}
|
|
|
|
|
2017-04-21 19:20:05 +00:00
|
|
|
// RestoreState is used to restore our state. If a non-empty string is returned
|
|
|
|
// the task is restarted with the string as the reason. This is useful for
|
|
|
|
// backwards incompatible upgrades that need to restart tasks with a new
|
|
|
|
// executor.
|
|
|
|
func (r *TaskRunner) RestoreState() (string, error) {
|
2017-05-02 20:31:56 +00:00
|
|
|
// COMPAT: Remove in 0.7.0
|
2018-03-11 19:06:05 +00:00
|
|
|
// 0.6.0 transitioned from individual state files to a single bolt-db.
|
2017-05-02 20:31:56 +00:00
|
|
|
// The upgrade path is to:
|
|
|
|
// Check if old state exists
|
|
|
|
// If so, restore from that and delete old state
|
|
|
|
// Restore using state database
|
2017-04-29 22:43:23 +00:00
|
|
|
|
2015-08-30 01:16:49 +00:00
|
|
|
var snap taskRunnerState
|
2017-05-02 20:31:56 +00:00
|
|
|
|
|
|
|
// Check if the old snapshot is there
|
|
|
|
oldPath := r.pre060StateFilePath()
|
|
|
|
if err := pre060RestoreState(oldPath, &snap); err == nil {
|
|
|
|
// Delete the old state
|
|
|
|
os.RemoveAll(oldPath)
|
|
|
|
} else if !os.IsNotExist(err) {
|
|
|
|
// Something corrupt in the old state file
|
2017-05-09 18:06:05 +00:00
|
|
|
return "", err
|
2017-05-02 20:31:56 +00:00
|
|
|
} else {
|
|
|
|
// We are doing a normal restore
|
|
|
|
err := r.stateDB.View(func(tx *bolt.Tx) error {
|
|
|
|
bkt, err := getTaskBucket(tx, r.alloc.ID, r.task.Name)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to get task bucket: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := getObject(bkt, taskRunnerStateAllKey, &snap); err != nil {
|
|
|
|
return fmt.Errorf("failed to read task runner state: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
2017-05-09 18:06:05 +00:00
|
|
|
return "", err
|
2017-05-02 20:31:56 +00:00
|
|
|
}
|
|
|
|
|
2015-08-30 01:16:49 +00:00
|
|
|
}
|
|
|
|
|
2017-05-02 20:31:56 +00:00
|
|
|
// Restore fields from the snapshot
|
2016-03-29 00:24:10 +00:00
|
|
|
r.artifactsDownloaded = snap.ArtifactDownloaded
|
2016-12-03 01:04:07 +00:00
|
|
|
r.taskDirBuilt = snap.TaskDirBuilt
|
2016-12-16 23:11:56 +00:00
|
|
|
r.payloadRendered = snap.PayloadRendered
|
2017-02-10 01:44:58 +00:00
|
|
|
r.setCreatedResources(snap.CreatedResources)
|
2017-06-16 23:35:16 +00:00
|
|
|
r.driverNet = snap.DriverNetwork
|
2017-02-09 21:54:33 +00:00
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
if r.task.Vault != nil {
|
|
|
|
// Read the token from the secret directory
|
2016-12-03 01:04:07 +00:00
|
|
|
tokenPath := filepath.Join(r.taskDir.SecretsDir, vaultTokenFile)
|
2016-10-17 18:41:22 +00:00
|
|
|
data, err := ioutil.ReadFile(tokenPath)
|
|
|
|
if err != nil {
|
2016-10-18 21:58:20 +00:00
|
|
|
if !os.IsNotExist(err) {
|
2017-04-21 19:20:05 +00:00
|
|
|
return "", fmt.Errorf("failed to read token for task %q in alloc %q: %v", r.task.Name, r.alloc.ID, err)
|
2016-10-17 18:41:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Token file doesn't exist
|
|
|
|
} else {
|
|
|
|
// Store the recovered token
|
|
|
|
r.recoveredVaultToken = string(data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-08-30 02:14:47 +00:00
|
|
|
// Restore the driver
|
2017-04-21 19:20:05 +00:00
|
|
|
restartReason := ""
|
2015-08-30 02:14:47 +00:00
|
|
|
if snap.HandleID != "" {
|
2016-12-03 01:04:07 +00:00
|
|
|
d, err := r.createDriver()
|
2015-08-30 02:14:47 +00:00
|
|
|
if err != nil {
|
2017-04-21 19:20:05 +00:00
|
|
|
return "", err
|
2015-08-30 02:14:47 +00:00
|
|
|
}
|
|
|
|
|
2017-06-16 23:35:16 +00:00
|
|
|
// Add the restored network driver to the environment
|
|
|
|
r.envBuilder.SetDriverNetwork(r.driverNet)
|
|
|
|
|
|
|
|
// Open a connection to the driver handle
|
2017-05-23 00:46:40 +00:00
|
|
|
ctx := driver.NewExecContext(r.taskDir, r.envBuilder.Build())
|
2016-12-03 01:04:07 +00:00
|
|
|
handle, err := d.Open(ctx, snap.HandleID)
|
2015-11-09 23:55:31 +00:00
|
|
|
|
|
|
|
// In the case it fails, we relaunch the task in the Run() method.
|
2015-08-30 02:14:47 +00:00
|
|
|
if err != nil {
|
2017-03-02 21:21:34 +00:00
|
|
|
r.logger.Printf("[ERR] client: failed to open handle to task %q for alloc %q: %v",
|
2015-12-14 22:53:49 +00:00
|
|
|
r.task.Name, r.alloc.ID, err)
|
2017-04-21 19:20:05 +00:00
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
2017-04-21 23:20:37 +00:00
|
|
|
if pre06ScriptCheck(snap.Version, r.task.Driver, r.task.Services) {
|
2017-04-25 18:41:03 +00:00
|
|
|
restartReason = pre06ScriptCheckReason
|
2015-08-30 02:14:47 +00:00
|
|
|
}
|
2017-02-01 00:43:57 +00:00
|
|
|
|
2017-06-16 23:35:16 +00:00
|
|
|
if err := r.registerServices(d, handle, r.driverNet); err != nil {
|
2017-04-13 16:52:16 +00:00
|
|
|
// Don't hard fail here as there's a chance this task
|
|
|
|
// registered with Consul properly when it initial
|
|
|
|
// started.
|
|
|
|
r.logger.Printf("[WARN] client: failed to register services and checks with consul for task %q in alloc %q: %v",
|
2017-02-01 00:43:57 +00:00
|
|
|
r.task.Name, r.alloc.ID, err)
|
|
|
|
}
|
|
|
|
|
2016-02-10 21:44:53 +00:00
|
|
|
r.handleLock.Lock()
|
2015-08-30 02:14:47 +00:00
|
|
|
r.handle = handle
|
2016-02-10 21:44:53 +00:00
|
|
|
r.handleLock.Unlock()
|
2016-06-28 20:47:59 +00:00
|
|
|
|
|
|
|
r.runningLock.Lock()
|
|
|
|
r.running = true
|
|
|
|
r.runningLock.Unlock()
|
2015-08-30 02:14:47 +00:00
|
|
|
}
|
2017-04-21 19:20:05 +00:00
|
|
|
return restartReason, nil
|
|
|
|
}
|
2017-05-02 20:31:56 +00:00
|
|
|
|
2017-04-25 18:41:03 +00:00
|
|
|
// ver06 is used for checking for pre-0.6 script checks
|
2017-04-21 19:20:05 +00:00
|
|
|
var ver06 = version.Must(version.NewVersion("0.6.0dev"))
|
|
|
|
|
2017-04-25 18:41:03 +00:00
|
|
|
// pre06ScriptCheckReason is the restart reason given when a pre-0.6 script
|
|
|
|
// check is found on an exec/java task.
|
|
|
|
const pre06ScriptCheckReason = "upgrading pre-0.6 script checks"
|
|
|
|
|
2017-05-04 23:49:00 +00:00
|
|
|
// pre06ScriptCheck returns true if version is prior to 0.6.0dev, has a script
|
|
|
|
// check, and uses exec or java drivers.
|
2017-04-21 23:20:37 +00:00
|
|
|
func pre06ScriptCheck(ver, driver string, services []*structs.Service) bool {
|
2017-04-25 18:41:03 +00:00
|
|
|
if driver != "exec" && driver != "java" && driver != "mock_driver" {
|
2017-04-21 23:20:37 +00:00
|
|
|
// Only exec and java are affected
|
|
|
|
return false
|
|
|
|
}
|
2017-04-21 19:20:05 +00:00
|
|
|
v, err := version.NewVersion(ver)
|
|
|
|
if err != nil {
|
|
|
|
// Treat it as old
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if !v.LessThan(ver06) {
|
|
|
|
// >= 0.6.0dev
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
for _, service := range services {
|
|
|
|
for _, check := range service.Checks {
|
|
|
|
if check.Type == "script" {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
2015-08-30 01:16:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// SaveState is used to snapshot our state
|
|
|
|
func (r *TaskRunner) SaveState() error {
|
2017-07-20 17:17:41 +00:00
|
|
|
r.destroyLock.Lock()
|
|
|
|
defer r.destroyLock.Unlock()
|
|
|
|
if r.destroy {
|
|
|
|
// Don't save state if already destroyed
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-09-02 22:39:22 +00:00
|
|
|
r.persistLock.Lock()
|
2017-05-09 17:50:24 +00:00
|
|
|
defer r.persistLock.Unlock()
|
2015-08-30 01:16:49 +00:00
|
|
|
snap := taskRunnerState{
|
2017-08-16 22:42:15 +00:00
|
|
|
Version: r.config.Version.VersionNumber(),
|
2016-03-29 00:24:10 +00:00
|
|
|
ArtifactDownloaded: r.artifactsDownloaded,
|
2016-12-03 01:04:07 +00:00
|
|
|
TaskDirBuilt: r.taskDirBuilt,
|
2016-12-16 23:11:56 +00:00
|
|
|
PayloadRendered: r.payloadRendered,
|
2017-02-10 01:44:58 +00:00
|
|
|
CreatedResources: r.getCreatedResources(),
|
2015-08-30 01:16:49 +00:00
|
|
|
}
|
2016-12-03 01:04:07 +00:00
|
|
|
|
2016-02-10 21:44:53 +00:00
|
|
|
r.handleLock.Lock()
|
2015-08-30 02:14:47 +00:00
|
|
|
if r.handle != nil {
|
|
|
|
snap.HandleID = r.handle.ID()
|
|
|
|
}
|
2016-02-10 21:44:53 +00:00
|
|
|
r.handleLock.Unlock()
|
2017-04-29 22:43:23 +00:00
|
|
|
|
2017-06-16 23:35:16 +00:00
|
|
|
r.driverNetLock.Lock()
|
|
|
|
snap.DriverNetwork = r.driverNet.Copy()
|
|
|
|
r.driverNetLock.Unlock()
|
|
|
|
|
2017-05-02 20:31:56 +00:00
|
|
|
// If nothing has changed avoid the write
|
2017-04-29 22:43:23 +00:00
|
|
|
h := snap.Hash()
|
|
|
|
if bytes.Equal(h, r.persistedHash) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-05-01 22:06:18 +00:00
|
|
|
// Serialize the object
|
|
|
|
var buf bytes.Buffer
|
|
|
|
if err := codec.NewEncoder(&buf, structs.MsgpackHandle).Encode(&snap); err != nil {
|
|
|
|
return fmt.Errorf("failed to serialize snapshot: %v", err)
|
|
|
|
}
|
|
|
|
|
2017-04-29 22:43:23 +00:00
|
|
|
// Start the transaction.
|
2017-05-01 18:09:08 +00:00
|
|
|
return r.stateDB.Batch(func(tx *bolt.Tx) error {
|
|
|
|
// Grab the task bucket
|
|
|
|
taskBkt, err := getTaskBucket(tx, r.alloc.ID, r.task.Name)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to retrieve allocation bucket: %v", err)
|
|
|
|
}
|
2017-04-29 22:43:23 +00:00
|
|
|
|
2017-05-01 22:06:18 +00:00
|
|
|
if err := putData(taskBkt, taskRunnerStateAllKey, buf.Bytes()); err != nil {
|
2017-05-01 18:09:08 +00:00
|
|
|
return fmt.Errorf("failed to write task_runner state: %v", err)
|
|
|
|
}
|
2017-04-29 22:43:23 +00:00
|
|
|
|
2017-05-01 18:09:08 +00:00
|
|
|
// Store the hash that was persisted
|
|
|
|
tx.OnCommit(func() {
|
|
|
|
r.persistedHash = h
|
|
|
|
})
|
2017-04-29 22:43:23 +00:00
|
|
|
|
2017-05-01 18:09:08 +00:00
|
|
|
return nil
|
2017-04-29 22:43:23 +00:00
|
|
|
})
|
2015-08-30 01:16:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DestroyState is used to cleanup after ourselves
|
|
|
|
func (r *TaskRunner) DestroyState() error {
|
2016-12-03 01:04:07 +00:00
|
|
|
r.persistLock.Lock()
|
|
|
|
defer r.persistLock.Unlock()
|
|
|
|
|
2017-05-02 20:31:56 +00:00
|
|
|
return r.stateDB.Update(func(tx *bolt.Tx) error {
|
|
|
|
if err := deleteTaskBucket(tx, r.alloc.ID, r.task.Name); err != nil {
|
|
|
|
return fmt.Errorf("failed to delete task bucket: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
2015-08-30 01:16:49 +00:00
|
|
|
}
|
|
|
|
|
2015-11-14 06:07:13 +00:00
|
|
|
// setState is used to update the state of the task runner
|
2017-08-08 04:26:04 +00:00
|
|
|
func (r *TaskRunner) setState(state string, event *structs.TaskEvent, lazySync bool) {
|
2017-10-31 15:35:14 +00:00
|
|
|
event.PopulateEventDisplayMessage()
|
2017-11-03 14:34:30 +00:00
|
|
|
|
2017-05-02 20:31:56 +00:00
|
|
|
// Persist our state to disk.
|
|
|
|
if err := r.SaveState(); err != nil {
|
|
|
|
r.logger.Printf("[ERR] client: failed to save state of Task Runner for task %q: %v", r.task.Name, err)
|
|
|
|
}
|
|
|
|
|
2015-11-14 06:07:13 +00:00
|
|
|
// Indicate the task has been updated.
|
2017-08-08 04:26:04 +00:00
|
|
|
r.updater(r.task.Name, state, event, lazySync)
|
2016-02-02 01:47:53 +00:00
|
|
|
}
|
|
|
|
|
2016-04-12 01:46:16 +00:00
|
|
|
// createDriver makes a driver for the task
|
|
|
|
func (r *TaskRunner) createDriver() (driver.Driver, error) {
|
2016-11-30 00:39:36 +00:00
|
|
|
// Create a task-specific event emitter callback to expose minimal
|
|
|
|
// state to drivers
|
|
|
|
eventEmitter := func(m string, args ...interface{}) {
|
|
|
|
msg := fmt.Sprintf(m, args...)
|
2016-12-20 19:51:09 +00:00
|
|
|
r.logger.Printf("[DEBUG] client: driver event for alloc %q: %s", r.alloc.ID, msg)
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStatePending, structs.NewTaskEvent(structs.TaskDriverMessage).SetDriverMessage(msg), false)
|
2016-11-30 00:39:36 +00:00
|
|
|
}
|
|
|
|
|
2017-05-23 00:46:40 +00:00
|
|
|
driverCtx := driver.NewDriverContext(r.task.Name, r.alloc.ID, r.config, r.config.Node, r.logger, eventEmitter)
|
2017-05-17 00:33:50 +00:00
|
|
|
d, err := driver.NewDriver(r.task.Driver, driverCtx)
|
2015-08-23 23:49:48 +00:00
|
|
|
if err != nil {
|
2016-08-10 22:17:32 +00:00
|
|
|
return nil, fmt.Errorf("failed to create driver '%s' for alloc %s: %v",
|
2015-12-14 22:53:49 +00:00
|
|
|
r.task.Driver, r.alloc.ID, err)
|
2015-08-30 02:14:47 +00:00
|
|
|
}
|
2017-05-17 00:33:50 +00:00
|
|
|
|
|
|
|
return d, err
|
2015-08-30 02:14:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Run is a long running routine used to manage the task
|
|
|
|
func (r *TaskRunner) Run() {
|
|
|
|
defer close(r.waitCh)
|
|
|
|
r.logger.Printf("[DEBUG] client: starting task context for '%s' (alloc '%s')",
|
2015-12-14 22:53:49 +00:00
|
|
|
r.task.Name, r.alloc.ID)
|
2015-08-30 02:14:47 +00:00
|
|
|
|
2016-03-24 17:55:14 +00:00
|
|
|
if err := r.validateTask(); err != nil {
|
|
|
|
r.setState(
|
|
|
|
structs.TaskStateDead,
|
2017-08-08 04:26:04 +00:00
|
|
|
structs.NewTaskEvent(structs.TaskFailedValidation).SetValidationError(err).SetFailsTask(),
|
|
|
|
false)
|
2016-03-24 17:55:14 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-05-18 17:49:39 +00:00
|
|
|
// Create a temporary driver so that we can determine the FSIsolation
|
|
|
|
// required. run->startTask will create a new driver after environment
|
|
|
|
// has been setup (env vars, templates, artifacts, secrets, etc).
|
|
|
|
tmpDrv, err := r.createDriver()
|
2017-01-08 01:35:44 +00:00
|
|
|
if err != nil {
|
|
|
|
e := fmt.Errorf("failed to create driver of task %q for alloc %q: %v", r.task.Name, r.alloc.ID, err)
|
|
|
|
r.setState(
|
|
|
|
structs.TaskStateDead,
|
2017-08-08 04:26:04 +00:00
|
|
|
structs.NewTaskEvent(structs.TaskSetupFailure).SetSetupError(e).SetFailsTask(),
|
|
|
|
false)
|
2017-01-08 01:35:44 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Build base task directory structure regardless of FS isolation abilities.
|
|
|
|
// This needs to happen before we start the Vault manager and call prestart
|
|
|
|
// as both those can write to the task directories
|
2017-05-18 17:49:39 +00:00
|
|
|
if err := r.buildTaskDir(tmpDrv.FSIsolation()); err != nil {
|
2017-01-08 01:35:44 +00:00
|
|
|
e := fmt.Errorf("failed to build task directory for %q: %v", r.task.Name, err)
|
|
|
|
r.setState(
|
|
|
|
structs.TaskStateDead,
|
2017-08-08 04:26:04 +00:00
|
|
|
structs.NewTaskEvent(structs.TaskSetupFailure).SetSetupError(e).SetFailsTask(),
|
|
|
|
false)
|
2017-01-08 01:35:44 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
// If there is no Vault policy leave the static future created in
|
|
|
|
// NewTaskRunner
|
|
|
|
if r.task.Vault != nil {
|
|
|
|
// Start the go-routine to get a Vault token
|
2016-10-18 18:22:16 +00:00
|
|
|
r.vaultFuture.Clear()
|
2016-10-17 18:41:22 +00:00
|
|
|
go r.vaultManager(r.recoveredVaultToken)
|
2016-04-12 01:46:16 +00:00
|
|
|
}
|
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
// Start the run loop
|
2015-11-16 20:26:11 +00:00
|
|
|
r.run()
|
2016-10-17 18:41:22 +00:00
|
|
|
|
|
|
|
// Do any cleanup necessary
|
|
|
|
r.postrun()
|
|
|
|
|
2015-11-14 06:07:13 +00:00
|
|
|
return
|
|
|
|
}
|
2015-08-23 23:49:48 +00:00
|
|
|
|
2016-03-24 17:55:14 +00:00
|
|
|
// validateTask validates the fields of the task and returns an error if the
|
|
|
|
// task is invalid.
|
|
|
|
func (r *TaskRunner) validateTask() error {
|
|
|
|
var mErr multierror.Error
|
|
|
|
|
|
|
|
// Validate the user.
|
|
|
|
unallowedUsers := r.config.ReadStringListToMapDefault("user.blacklist", config.DefaultUserBlacklist)
|
|
|
|
checkDrivers := r.config.ReadStringListToMapDefault("user.checked_drivers", config.DefaultUserCheckedDrivers)
|
|
|
|
if _, driverMatch := checkDrivers[r.task.Driver]; driverMatch {
|
|
|
|
if _, unallowed := unallowedUsers[r.task.User]; unallowed {
|
|
|
|
mErr.Errors = append(mErr.Errors, fmt.Errorf("running as user %q is disallowed", r.task.User))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Validate the artifacts
|
|
|
|
for i, artifact := range r.task.Artifacts {
|
|
|
|
// Verify the artifact doesn't escape the task directory.
|
|
|
|
if err := artifact.Validate(); err != nil {
|
|
|
|
// If this error occurs there is potentially a server bug or
|
2018-03-11 18:26:25 +00:00
|
|
|
// malicious, server spoofing.
|
2016-03-24 17:55:14 +00:00
|
|
|
r.logger.Printf("[ERR] client: allocation %q, task %v, artifact %#v (%v) fails validation: %v",
|
|
|
|
r.alloc.ID, r.task.Name, artifact, i, err)
|
|
|
|
mErr.Errors = append(mErr.Errors, fmt.Errorf("artifact (%d) failed validation: %v", i, err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-24 19:13:47 +00:00
|
|
|
// Validate the Service names
|
2017-05-17 00:33:50 +00:00
|
|
|
taskEnv := r.envBuilder.Build()
|
2016-10-24 19:13:47 +00:00
|
|
|
for i, service := range r.task.Services {
|
2017-05-17 00:33:50 +00:00
|
|
|
name := taskEnv.ReplaceEnv(service.Name)
|
2016-10-24 19:13:47 +00:00
|
|
|
if err := service.ValidateName(name); err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, fmt.Errorf("service (%d) failed validation: %v", i, err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-03-24 17:55:14 +00:00
|
|
|
if len(mErr.Errors) == 1 {
|
|
|
|
return mErr.Errors[0]
|
|
|
|
}
|
|
|
|
return mErr.ErrorOrNil()
|
|
|
|
}
|
|
|
|
|
2016-10-18 18:36:04 +00:00
|
|
|
// tokenFuture stores the Vault token and allows consumers to block till a valid
|
|
|
|
// token exists
|
2016-10-17 18:41:22 +00:00
|
|
|
type tokenFuture struct {
|
|
|
|
waiting []chan struct{}
|
|
|
|
token string
|
|
|
|
set bool
|
|
|
|
m sync.Mutex
|
|
|
|
}
|
|
|
|
|
2016-10-18 18:36:04 +00:00
|
|
|
// NewTokenFuture returns a new token future without any token set
|
2016-10-17 18:41:22 +00:00
|
|
|
func NewTokenFuture() *tokenFuture {
|
|
|
|
return &tokenFuture{}
|
|
|
|
}
|
|
|
|
|
2016-10-18 18:36:04 +00:00
|
|
|
// Wait returns a channel that can be waited on. When this channel unblocks, a
|
|
|
|
// valid token will be available via the Get method
|
2016-10-17 18:41:22 +00:00
|
|
|
func (f *tokenFuture) Wait() <-chan struct{} {
|
|
|
|
f.m.Lock()
|
|
|
|
defer f.m.Unlock()
|
|
|
|
|
|
|
|
c := make(chan struct{})
|
|
|
|
if f.set {
|
|
|
|
close(c)
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
f.waiting = append(f.waiting, c)
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
2016-10-18 18:36:04 +00:00
|
|
|
// Set sets the token value and unblocks any caller of Wait
|
2016-10-17 18:41:22 +00:00
|
|
|
func (f *tokenFuture) Set(token string) *tokenFuture {
|
|
|
|
f.m.Lock()
|
|
|
|
defer f.m.Unlock()
|
|
|
|
|
|
|
|
f.set = true
|
|
|
|
f.token = token
|
|
|
|
for _, w := range f.waiting {
|
|
|
|
close(w)
|
|
|
|
}
|
|
|
|
f.waiting = nil
|
|
|
|
return f
|
|
|
|
}
|
|
|
|
|
2016-10-18 18:36:04 +00:00
|
|
|
// Clear clears the set vault token.
|
2016-10-17 18:41:22 +00:00
|
|
|
func (f *tokenFuture) Clear() *tokenFuture {
|
|
|
|
f.m.Lock()
|
|
|
|
defer f.m.Unlock()
|
|
|
|
|
|
|
|
f.token = ""
|
|
|
|
f.set = false
|
|
|
|
return f
|
|
|
|
}
|
|
|
|
|
2016-10-18 18:36:04 +00:00
|
|
|
// Get returns the set Vault token
|
2016-10-17 18:41:22 +00:00
|
|
|
func (f *tokenFuture) Get() string {
|
|
|
|
f.m.Lock()
|
|
|
|
defer f.m.Unlock()
|
|
|
|
return f.token
|
|
|
|
}
|
|
|
|
|
2016-10-18 18:36:04 +00:00
|
|
|
// vaultManager should be called in a go-routine and manages the derivation,
|
|
|
|
// renewal and handling of errors with the Vault token. The optional parameter
|
|
|
|
// allows setting the initial Vault token. This is useful when the Vault token
|
|
|
|
// is recovered off disk.
|
2016-10-17 18:41:22 +00:00
|
|
|
func (r *TaskRunner) vaultManager(token string) {
|
2017-03-29 20:17:50 +00:00
|
|
|
// Helper for stopping token renewal
|
|
|
|
stopRenewal := func() {
|
|
|
|
if err := r.vaultClient.StopRenewToken(r.vaultFuture.Get()); err != nil {
|
|
|
|
r.logger.Printf("[WARN] client: failed to stop token renewal for task %v in alloc %q: %v", r.task.Name, r.alloc.ID, err)
|
|
|
|
}
|
|
|
|
}
|
2017-03-28 17:53:15 +00:00
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
// updatedToken lets us store state between loops. If true, a new token
|
|
|
|
// has been retrieved and we need to apply the Vault change mode
|
|
|
|
var updatedToken bool
|
|
|
|
|
|
|
|
OUTER:
|
|
|
|
for {
|
|
|
|
// Check if we should exit
|
|
|
|
select {
|
|
|
|
case <-r.waitCh:
|
2017-03-29 20:17:50 +00:00
|
|
|
stopRenewal()
|
2016-10-17 18:41:22 +00:00
|
|
|
return
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
|
|
|
// Clear the token
|
|
|
|
r.vaultFuture.Clear()
|
|
|
|
|
|
|
|
// Check if there already is a token which can be the case for
|
|
|
|
// restoring the TaskRunner
|
|
|
|
if token == "" {
|
|
|
|
// Get a token
|
2016-10-23 01:08:30 +00:00
|
|
|
var exit bool
|
|
|
|
token, exit = r.deriveVaultToken()
|
|
|
|
if exit {
|
|
|
|
// Exit the manager
|
2016-10-17 18:41:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write the token to disk
|
|
|
|
if err := r.writeToken(token); err != nil {
|
|
|
|
e := fmt.Errorf("failed to write Vault token to disk")
|
|
|
|
r.logger.Printf("[ERR] client: %v for task %v on alloc %q: %v", e, r.task.Name, r.alloc.ID, err)
|
2016-10-21 00:27:16 +00:00
|
|
|
r.Kill("vault", e.Error(), true)
|
2016-10-17 18:41:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start the renewal process
|
|
|
|
renewCh, err := r.vaultClient.RenewToken(token, 30)
|
|
|
|
|
|
|
|
// An error returned means the token is not being renewed
|
|
|
|
if err != nil {
|
|
|
|
r.logger.Printf("[ERR] client: failed to start renewal of Vault token for task %v on alloc %q: %v", r.task.Name, r.alloc.ID, err)
|
|
|
|
token = ""
|
|
|
|
goto OUTER
|
|
|
|
}
|
|
|
|
|
|
|
|
// The Vault token is valid now, so set it
|
|
|
|
r.vaultFuture.Set(token)
|
|
|
|
|
|
|
|
if updatedToken {
|
|
|
|
switch r.task.Vault.ChangeMode {
|
|
|
|
case structs.VaultChangeModeSignal:
|
|
|
|
s, err := signals.Parse(r.task.Vault.ChangeSignal)
|
|
|
|
if err != nil {
|
|
|
|
e := fmt.Errorf("failed to parse signal: %v", err)
|
|
|
|
r.logger.Printf("[ERR] client: %v", err)
|
2016-10-21 00:27:16 +00:00
|
|
|
r.Kill("vault", e.Error(), true)
|
2016-10-17 18:41:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := r.Signal("vault", "new Vault token acquired", s); err != nil {
|
|
|
|
r.logger.Printf("[ERR] client: failed to send signal to task %v for alloc %q: %v", r.task.Name, r.alloc.ID, err)
|
2016-10-21 00:27:16 +00:00
|
|
|
r.Kill("vault", fmt.Sprintf("failed to send signal to task: %v", err), true)
|
2016-10-17 18:41:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
case structs.VaultChangeModeRestart:
|
2017-09-15 21:57:18 +00:00
|
|
|
const noFailure = false
|
|
|
|
r.Restart("vault", "new Vault token acquired", noFailure)
|
2016-10-17 18:41:22 +00:00
|
|
|
case structs.VaultChangeModeNoop:
|
|
|
|
fallthrough
|
|
|
|
default:
|
|
|
|
r.logger.Printf("[ERR] client: Invalid Vault change mode: %q", r.task.Vault.ChangeMode)
|
|
|
|
}
|
|
|
|
|
|
|
|
// We have handled it
|
|
|
|
updatedToken = false
|
|
|
|
|
|
|
|
// Call the handler
|
|
|
|
r.updatedTokenHandler()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start watching for renewal errors
|
|
|
|
select {
|
|
|
|
case err := <-renewCh:
|
|
|
|
// Clear the token
|
|
|
|
token = ""
|
|
|
|
r.logger.Printf("[ERR] client: failed to renew Vault token for task %v on alloc %q: %v", r.task.Name, r.alloc.ID, err)
|
2017-03-29 20:17:50 +00:00
|
|
|
stopRenewal()
|
2016-10-17 18:41:22 +00:00
|
|
|
|
|
|
|
// Check if we have to do anything
|
|
|
|
if r.task.Vault.ChangeMode != structs.VaultChangeModeNoop {
|
|
|
|
updatedToken = true
|
|
|
|
}
|
|
|
|
case <-r.waitCh:
|
2017-03-29 20:17:50 +00:00
|
|
|
stopRenewal()
|
2016-10-17 18:41:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-18 18:36:04 +00:00
|
|
|
// deriveVaultToken derives the Vault token using exponential backoffs. It
|
2016-10-23 01:20:50 +00:00
|
|
|
// returns the Vault token and whether the manager should exit.
|
2016-10-23 01:08:30 +00:00
|
|
|
func (r *TaskRunner) deriveVaultToken() (token string, exit bool) {
|
2016-10-17 18:41:22 +00:00
|
|
|
attempts := 0
|
|
|
|
for {
|
|
|
|
tokens, err := r.vaultClient.DeriveToken(r.alloc, []string{r.task.Name})
|
2016-10-18 21:58:20 +00:00
|
|
|
if err == nil {
|
2016-10-23 01:08:30 +00:00
|
|
|
return tokens[r.task.Name], false
|
|
|
|
}
|
|
|
|
|
2018-03-13 22:09:03 +00:00
|
|
|
// Check if this is a server side error
|
|
|
|
if structs.IsServerSide(err) {
|
|
|
|
r.logger.Printf("[ERR] client: failed to derive Vault token for task %v on alloc %q: %v",
|
|
|
|
r.task.Name, r.alloc.ID, err)
|
2018-03-13 23:19:16 +00:00
|
|
|
r.Kill("vault", fmt.Sprintf("server error deriving vault token: %v", err), true)
|
2018-03-13 22:09:03 +00:00
|
|
|
return "", true
|
|
|
|
}
|
2016-10-23 01:08:30 +00:00
|
|
|
// Check if we can't recover from the error
|
2017-03-24 22:26:05 +00:00
|
|
|
if !structs.IsRecoverable(err) {
|
2016-10-23 01:08:30 +00:00
|
|
|
r.logger.Printf("[ERR] client: failed to derive Vault token for task %v on alloc %q: %v",
|
|
|
|
r.task.Name, r.alloc.ID, err)
|
2016-10-25 00:04:10 +00:00
|
|
|
r.Kill("vault", fmt.Sprintf("failed to derive token: %v", err), true)
|
2016-10-23 01:08:30 +00:00
|
|
|
return "", true
|
2016-10-18 21:58:20 +00:00
|
|
|
}
|
2016-10-17 18:41:22 +00:00
|
|
|
|
2016-10-18 21:58:20 +00:00
|
|
|
// Handle the retry case
|
|
|
|
backoff := (1 << (2 * uint64(attempts))) * vaultBackoffBaseline
|
|
|
|
if backoff > vaultBackoffLimit {
|
|
|
|
backoff = vaultBackoffLimit
|
|
|
|
}
|
2016-10-23 01:08:30 +00:00
|
|
|
r.logger.Printf("[ERR] client: failed to derive Vault token for task %v on alloc %q: %v; retrying in %v",
|
|
|
|
r.task.Name, r.alloc.ID, err, backoff)
|
2016-10-17 18:41:22 +00:00
|
|
|
|
2016-10-18 21:58:20 +00:00
|
|
|
attempts++
|
|
|
|
|
|
|
|
// Wait till retrying
|
|
|
|
select {
|
|
|
|
case <-r.waitCh:
|
2016-10-23 01:08:30 +00:00
|
|
|
return "", true
|
2016-10-18 21:58:20 +00:00
|
|
|
case <-time.After(backoff):
|
2016-10-17 18:41:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-18 18:36:04 +00:00
|
|
|
// writeToken writes the given token to disk
|
2016-10-17 18:41:22 +00:00
|
|
|
func (r *TaskRunner) writeToken(token string) error {
|
2016-12-03 01:04:07 +00:00
|
|
|
tokenPath := filepath.Join(r.taskDir.SecretsDir, vaultTokenFile)
|
2016-10-17 18:41:22 +00:00
|
|
|
if err := ioutil.WriteFile(tokenPath, []byte(token), 0777); err != nil {
|
|
|
|
return fmt.Errorf("failed to save Vault tokens to secret dir for task %q in alloc %q: %v", r.task.Name, r.alloc.ID, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-10-18 18:36:04 +00:00
|
|
|
// updatedTokenHandler is called when a new Vault token is retrieved. Things
|
|
|
|
// that rely on the token should be updated here.
|
2016-10-17 18:41:22 +00:00
|
|
|
func (r *TaskRunner) updatedTokenHandler() {
|
|
|
|
|
|
|
|
// Update the tasks environment
|
2017-05-17 00:33:50 +00:00
|
|
|
r.envBuilder.SetVaultToken(r.vaultFuture.Get(), r.task.Vault.Env)
|
2016-03-15 17:53:20 +00:00
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
if r.templateManager != nil {
|
|
|
|
r.templateManager.Stop()
|
|
|
|
|
|
|
|
// Create a new templateManager
|
|
|
|
var err error
|
2017-08-10 00:25:29 +00:00
|
|
|
r.templateManager, err = NewTaskTemplateManager(&TaskTemplateManagerConfig{
|
|
|
|
Hooks: r,
|
|
|
|
Templates: r.task.Templates,
|
|
|
|
ClientConfig: r.config,
|
|
|
|
VaultToken: r.vaultFuture.Get(),
|
|
|
|
TaskDir: r.taskDir.Dir,
|
|
|
|
EnvBuilder: r.envBuilder,
|
|
|
|
MaxTemplateEventRate: DefaultMaxTemplateEventRate,
|
|
|
|
})
|
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("failed to build task's template manager: %v", err)
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStateDead,
|
|
|
|
structs.NewTaskEvent(structs.TaskSetupFailure).SetSetupError(err).SetFailsTask(),
|
|
|
|
false)
|
2016-10-17 18:41:22 +00:00
|
|
|
r.logger.Printf("[ERR] client: alloc %q, task %q %v", r.alloc.ID, r.task.Name, err)
|
2016-11-04 23:57:24 +00:00
|
|
|
r.Kill("vault", err.Error(), true)
|
2016-10-17 18:41:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// prestart handles life-cycle tasks that occur before the task has started.
|
2017-07-21 23:17:42 +00:00
|
|
|
// Since it's run asynchronously with the main Run() loop the alloc & task are
|
|
|
|
// passed in to avoid racing with updates.
|
|
|
|
func (r *TaskRunner) prestart(alloc *structs.Allocation, task *structs.Task, resultCh chan bool) {
|
|
|
|
if task.Vault != nil {
|
2016-10-17 18:41:22 +00:00
|
|
|
// Wait for the token
|
2017-07-21 23:17:42 +00:00
|
|
|
r.logger.Printf("[DEBUG] client: waiting for Vault token for task %v in alloc %q", task.Name, alloc.ID)
|
2016-10-17 18:41:22 +00:00
|
|
|
tokenCh := r.vaultFuture.Wait()
|
|
|
|
select {
|
|
|
|
case <-tokenCh:
|
|
|
|
case <-r.waitCh:
|
|
|
|
resultCh <- false
|
|
|
|
return
|
|
|
|
}
|
2017-07-21 23:17:42 +00:00
|
|
|
r.logger.Printf("[DEBUG] client: retrieved Vault token for task %v in alloc %q", task.Name, alloc.ID)
|
|
|
|
r.envBuilder.SetVaultToken(r.vaultFuture.Get(), task.Vault.Env)
|
2016-10-17 18:41:22 +00:00
|
|
|
}
|
|
|
|
|
2016-12-16 23:11:56 +00:00
|
|
|
// If the job is a dispatch job and there is a payload write it to disk
|
2017-07-21 23:17:42 +00:00
|
|
|
requirePayload := len(alloc.Job.Payload) != 0 &&
|
2017-01-26 05:06:16 +00:00
|
|
|
(r.task.DispatchPayload != nil && r.task.DispatchPayload.File != "")
|
2016-12-16 23:11:56 +00:00
|
|
|
if !r.payloadRendered && requirePayload {
|
2017-07-21 23:17:42 +00:00
|
|
|
renderTo := filepath.Join(r.taskDir.LocalDir, task.DispatchPayload.File)
|
|
|
|
decoded, err := snappy.Decode(nil, alloc.Job.Payload)
|
2016-12-16 23:11:56 +00:00
|
|
|
if err != nil {
|
|
|
|
r.setState(
|
|
|
|
structs.TaskStateDead,
|
2017-08-08 04:26:04 +00:00
|
|
|
structs.NewTaskEvent(structs.TaskSetupFailure).SetSetupError(err).SetFailsTask(),
|
|
|
|
false)
|
2016-12-16 23:11:56 +00:00
|
|
|
resultCh <- false
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-01-08 01:17:38 +00:00
|
|
|
if err := os.MkdirAll(filepath.Dir(renderTo), 07777); err != nil {
|
|
|
|
r.setState(
|
|
|
|
structs.TaskStateDead,
|
2017-08-08 04:26:04 +00:00
|
|
|
structs.NewTaskEvent(structs.TaskSetupFailure).SetSetupError(err).SetFailsTask(),
|
|
|
|
false)
|
2017-01-08 01:17:38 +00:00
|
|
|
resultCh <- false
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-12-16 23:11:56 +00:00
|
|
|
if err := ioutil.WriteFile(renderTo, decoded, 0777); err != nil {
|
|
|
|
r.setState(
|
|
|
|
structs.TaskStateDead,
|
2017-08-08 04:26:04 +00:00
|
|
|
structs.NewTaskEvent(structs.TaskSetupFailure).SetSetupError(err).SetFailsTask(),
|
|
|
|
false)
|
2016-12-16 23:11:56 +00:00
|
|
|
resultCh <- false
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
r.payloadRendered = true
|
|
|
|
}
|
|
|
|
|
2015-08-23 22:30:16 +00:00
|
|
|
for {
|
2016-12-03 01:04:07 +00:00
|
|
|
r.persistLock.Lock()
|
|
|
|
downloaded := r.artifactsDownloaded
|
|
|
|
r.persistLock.Unlock()
|
|
|
|
|
2016-03-15 17:53:20 +00:00
|
|
|
// Download the task's artifacts
|
2017-07-21 23:17:42 +00:00
|
|
|
if !downloaded && len(task.Artifacts) > 0 {
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStatePending, structs.NewTaskEvent(structs.TaskDownloadingArtifacts), false)
|
2017-05-18 23:47:20 +00:00
|
|
|
taskEnv := r.envBuilder.Build()
|
2017-07-21 23:17:42 +00:00
|
|
|
for _, artifact := range task.Artifacts {
|
2017-05-17 00:33:50 +00:00
|
|
|
if err := getter.GetArtifact(taskEnv, artifact, r.taskDir.Dir); err != nil {
|
2016-11-04 23:57:24 +00:00
|
|
|
wrapped := fmt.Errorf("failed to download artifact %q: %v", artifact.GetterSource, err)
|
2017-03-01 21:02:38 +00:00
|
|
|
r.logger.Printf("[DEBUG] client: %v", wrapped)
|
2016-08-25 00:40:11 +00:00
|
|
|
r.setState(structs.TaskStatePending,
|
2017-08-08 04:26:04 +00:00
|
|
|
structs.NewTaskEvent(structs.TaskArtifactDownloadFailed).SetDownloadError(wrapped), false)
|
2017-03-27 22:37:15 +00:00
|
|
|
r.restartTracker.SetStartError(structs.WrapRecoverable(wrapped.Error(), err))
|
2016-03-15 17:53:20 +00:00
|
|
|
goto RESTART
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-03 01:04:07 +00:00
|
|
|
r.persistLock.Lock()
|
2016-03-15 17:53:20 +00:00
|
|
|
r.artifactsDownloaded = true
|
2016-12-03 01:04:07 +00:00
|
|
|
r.persistLock.Unlock()
|
2016-03-15 17:53:20 +00:00
|
|
|
}
|
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
// We don't have to wait for any template
|
2017-07-21 23:17:42 +00:00
|
|
|
if len(task.Templates) == 0 {
|
2016-10-17 18:41:22 +00:00
|
|
|
// Send the start signal
|
|
|
|
select {
|
|
|
|
case r.startCh <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
|
|
|
resultCh <- true
|
|
|
|
return
|
2016-10-05 20:41:29 +00:00
|
|
|
}
|
|
|
|
|
2016-10-31 18:29:26 +00:00
|
|
|
// Build the template manager
|
|
|
|
if r.templateManager == nil {
|
|
|
|
var err error
|
2017-08-10 00:25:29 +00:00
|
|
|
r.templateManager, err = NewTaskTemplateManager(&TaskTemplateManagerConfig{
|
|
|
|
Hooks: r,
|
|
|
|
Templates: r.task.Templates,
|
|
|
|
ClientConfig: r.config,
|
|
|
|
VaultToken: r.vaultFuture.Get(),
|
|
|
|
TaskDir: r.taskDir.Dir,
|
|
|
|
EnvBuilder: r.envBuilder,
|
|
|
|
MaxTemplateEventRate: DefaultMaxTemplateEventRate,
|
|
|
|
})
|
2016-10-31 18:29:26 +00:00
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("failed to build task's template manager: %v", err)
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStateDead, structs.NewTaskEvent(structs.TaskSetupFailure).SetSetupError(err).SetFailsTask(), false)
|
2017-07-21 23:17:42 +00:00
|
|
|
r.logger.Printf("[ERR] client: alloc %q, task %q %v", alloc.ID, task.Name, err)
|
2016-10-31 18:29:26 +00:00
|
|
|
resultCh <- false
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-05 20:41:29 +00:00
|
|
|
// Block for consul-template
|
2016-10-17 18:41:22 +00:00
|
|
|
// TODO Hooks should register themselves as blocking and then we can
|
2018-03-11 18:36:59 +00:00
|
|
|
// periodically enumerate what we are still blocked on
|
2016-10-05 20:41:29 +00:00
|
|
|
select {
|
|
|
|
case <-r.unblockCh:
|
2016-10-17 18:41:22 +00:00
|
|
|
// Send the start signal
|
|
|
|
select {
|
|
|
|
case r.startCh <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
2016-10-05 20:41:29 +00:00
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
resultCh <- true
|
|
|
|
return
|
|
|
|
case <-r.waitCh:
|
|
|
|
// The run loop has exited so exit too
|
|
|
|
resultCh <- false
|
|
|
|
return
|
2016-10-05 20:41:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
RESTART:
|
|
|
|
restart := r.shouldRestart()
|
|
|
|
if !restart {
|
2016-10-17 18:41:22 +00:00
|
|
|
resultCh <- false
|
|
|
|
return
|
2016-10-05 20:41:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
// postrun is used to do any cleanup that is necessary after exiting the runloop
|
|
|
|
func (r *TaskRunner) postrun() {
|
|
|
|
// Stop the template manager
|
2016-10-18 21:58:20 +00:00
|
|
|
if r.templateManager != nil {
|
|
|
|
r.templateManager.Stop()
|
|
|
|
}
|
2016-10-17 18:41:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// run is the main run loop that handles starting the application, destroying
|
|
|
|
// it, restarts and signals.
|
2016-10-05 20:41:29 +00:00
|
|
|
func (r *TaskRunner) run() {
|
|
|
|
// Predeclare things so we can jump to the RESTART
|
|
|
|
var stopCollection chan struct{}
|
2016-10-17 18:41:22 +00:00
|
|
|
var handleWaitCh chan *dstructs.WaitResult
|
2016-10-05 20:41:29 +00:00
|
|
|
|
2017-02-28 18:29:12 +00:00
|
|
|
// If we already have a handle, populate the stopCollection and handleWaitCh
|
|
|
|
// to fix the invariant that it exists.
|
2017-07-21 21:00:32 +00:00
|
|
|
handleEmpty := r.getHandle() == nil
|
2017-02-28 18:29:12 +00:00
|
|
|
|
|
|
|
if !handleEmpty {
|
|
|
|
stopCollection = make(chan struct{})
|
|
|
|
go r.collectResourceUsageStats(stopCollection)
|
|
|
|
handleWaitCh = r.handle.WaitCh()
|
|
|
|
}
|
|
|
|
|
2016-10-05 20:41:29 +00:00
|
|
|
for {
|
2016-10-17 18:41:22 +00:00
|
|
|
// Do the prestart activities
|
|
|
|
prestartResultCh := make(chan bool, 1)
|
2017-07-21 23:17:42 +00:00
|
|
|
go r.prestart(r.alloc, r.task, prestartResultCh)
|
2015-11-16 20:26:11 +00:00
|
|
|
|
2016-02-29 00:56:05 +00:00
|
|
|
WAIT:
|
2015-11-16 20:26:11 +00:00
|
|
|
for {
|
|
|
|
select {
|
2016-10-17 18:41:22 +00:00
|
|
|
case success := <-prestartResultCh:
|
|
|
|
if !success {
|
2017-01-10 21:24:45 +00:00
|
|
|
r.cleanup()
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStateDead, nil, false)
|
2016-10-17 18:41:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
case <-r.startCh:
|
|
|
|
// Start the task if not yet started or it is being forced. This logic
|
|
|
|
// is necessary because in the case of a restore the handle already
|
|
|
|
// exists.
|
2017-07-21 21:00:32 +00:00
|
|
|
handleEmpty := r.getHandle() == nil
|
2016-10-17 18:41:22 +00:00
|
|
|
if handleEmpty {
|
|
|
|
startErr := r.startTask()
|
|
|
|
r.restartTracker.SetStartError(startErr)
|
|
|
|
if startErr != nil {
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState("", structs.NewTaskEvent(structs.TaskDriverFailure).SetDriverError(startErr), true)
|
2016-10-17 18:41:22 +00:00
|
|
|
goto RESTART
|
|
|
|
}
|
|
|
|
|
|
|
|
// Mark the task as started
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStateRunning, structs.NewTaskEvent(structs.TaskStarted), false)
|
2016-10-17 18:41:22 +00:00
|
|
|
r.runningLock.Lock()
|
|
|
|
r.running = true
|
|
|
|
r.runningLock.Unlock()
|
|
|
|
|
2017-02-28 18:29:12 +00:00
|
|
|
if stopCollection == nil {
|
|
|
|
stopCollection = make(chan struct{})
|
|
|
|
go r.collectResourceUsageStats(stopCollection)
|
|
|
|
}
|
2016-10-17 18:41:22 +00:00
|
|
|
|
2017-02-28 18:29:12 +00:00
|
|
|
handleWaitCh = r.handle.WaitCh()
|
|
|
|
}
|
2016-10-17 18:41:22 +00:00
|
|
|
|
|
|
|
case waitRes := <-handleWaitCh:
|
2016-02-29 00:56:05 +00:00
|
|
|
if waitRes == nil {
|
|
|
|
panic("nil wait")
|
|
|
|
}
|
|
|
|
|
2016-06-12 03:15:50 +00:00
|
|
|
r.runningLock.Lock()
|
|
|
|
r.running = false
|
|
|
|
r.runningLock.Unlock()
|
|
|
|
|
2016-06-07 21:34:21 +00:00
|
|
|
// Stop collection of the task's resource usage
|
2016-05-31 23:09:05 +00:00
|
|
|
close(stopCollection)
|
|
|
|
|
2016-02-29 00:56:05 +00:00
|
|
|
// Log whether the task was successful or not.
|
|
|
|
r.restartTracker.SetWaitResult(waitRes)
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState("", r.waitErrorToEvent(waitRes), true)
|
2016-02-29 00:56:05 +00:00
|
|
|
if !waitRes.Successful() {
|
|
|
|
r.logger.Printf("[INFO] client: task %q for alloc %q failed: %v", r.task.Name, r.alloc.ID, waitRes)
|
|
|
|
} else {
|
|
|
|
r.logger.Printf("[INFO] client: task %q for alloc %q completed successfully", r.task.Name, r.alloc.ID)
|
|
|
|
}
|
|
|
|
|
|
|
|
break WAIT
|
2015-11-16 20:26:11 +00:00
|
|
|
case update := <-r.updateCh:
|
2016-02-04 03:43:44 +00:00
|
|
|
if err := r.handleUpdate(update); err != nil {
|
|
|
|
r.logger.Printf("[ERR] client: update to task %q failed: %v", r.task.Name, err)
|
2015-11-16 20:26:11 +00:00
|
|
|
}
|
2016-09-14 20:30:01 +00:00
|
|
|
|
2016-10-05 20:41:29 +00:00
|
|
|
case se := <-r.signalCh:
|
2017-03-24 19:04:22 +00:00
|
|
|
r.runningLock.Lock()
|
|
|
|
running := r.running
|
|
|
|
r.runningLock.Unlock()
|
|
|
|
common := fmt.Sprintf("signal %v to task %v for alloc %q", se.s, r.task.Name, r.alloc.ID)
|
|
|
|
if !running {
|
|
|
|
// Send no error
|
|
|
|
r.logger.Printf("[DEBUG] client: skipping %s", common)
|
|
|
|
se.result <- nil
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
r.logger.Printf("[DEBUG] client: sending %s", common)
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStateRunning, se.e, false)
|
2016-10-05 20:41:29 +00:00
|
|
|
|
2016-10-10 21:49:37 +00:00
|
|
|
res := r.handle.Signal(se.s)
|
|
|
|
se.result <- res
|
2016-10-05 20:41:29 +00:00
|
|
|
|
2017-09-10 23:25:13 +00:00
|
|
|
case restartEvent := <-r.restartCh:
|
2017-03-24 19:04:22 +00:00
|
|
|
r.runningLock.Lock()
|
|
|
|
running := r.running
|
|
|
|
r.runningLock.Unlock()
|
|
|
|
common := fmt.Sprintf("task %v for alloc %q", r.task.Name, r.alloc.ID)
|
|
|
|
if !running {
|
2017-03-24 19:24:47 +00:00
|
|
|
r.logger.Printf("[DEBUG] client: skipping restart of %v: task isn't running", common)
|
2017-03-24 19:04:22 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-09-10 23:25:13 +00:00
|
|
|
r.logger.Printf("[DEBUG] client: restarting %s: %v", common, restartEvent.taskEvent.RestartReason)
|
|
|
|
r.setState(structs.TaskStateRunning, restartEvent.taskEvent, false)
|
2016-10-21 00:27:16 +00:00
|
|
|
r.killTask(nil)
|
2016-10-17 18:41:22 +00:00
|
|
|
|
|
|
|
close(stopCollection)
|
2016-10-05 20:41:29 +00:00
|
|
|
|
2016-11-04 22:10:18 +00:00
|
|
|
if handleWaitCh != nil {
|
|
|
|
<-handleWaitCh
|
|
|
|
}
|
2016-11-04 21:39:56 +00:00
|
|
|
|
2017-09-14 22:27:39 +00:00
|
|
|
r.restartTracker.SetRestartTriggered(restartEvent.failure)
|
2016-10-05 22:11:09 +00:00
|
|
|
break WAIT
|
2016-10-05 20:41:29 +00:00
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
case <-r.destroyCh:
|
2016-10-17 18:41:22 +00:00
|
|
|
r.runningLock.Lock()
|
|
|
|
running := r.running
|
|
|
|
r.runningLock.Unlock()
|
|
|
|
if !running {
|
2017-01-10 21:24:45 +00:00
|
|
|
r.cleanup()
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStateDead, r.destroyEvent, false)
|
2016-10-17 18:41:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-04-28 08:19:15 +00:00
|
|
|
// Remove from consul before killing the task so that traffic
|
|
|
|
// can be rerouted
|
2017-07-21 20:35:40 +00:00
|
|
|
interpTask := interpolateServices(r.envBuilder.Build(), r.task)
|
|
|
|
r.consul.RemoveTask(r.alloc.ID, interpTask)
|
2017-04-28 08:19:15 +00:00
|
|
|
|
2017-08-17 00:54:11 +00:00
|
|
|
// Delay actually killing the task if configured. See #244
|
|
|
|
if r.task.ShutdownDelay > 0 {
|
2017-08-17 18:28:33 +00:00
|
|
|
r.logger.Printf("[DEBUG] client: delaying shutdown of alloc %q task %q for %q",
|
|
|
|
r.alloc.ID, r.task.Name, r.task.ShutdownDelay)
|
2017-08-17 00:54:11 +00:00
|
|
|
<-time.After(r.task.ShutdownDelay)
|
|
|
|
}
|
|
|
|
|
2016-10-17 18:41:22 +00:00
|
|
|
// Store the task event that provides context on the task
|
|
|
|
// destroy. The Killed event is set from the alloc_runner and
|
|
|
|
// doesn't add detail
|
2016-10-21 00:27:16 +00:00
|
|
|
var killEvent *structs.TaskEvent
|
2016-09-14 20:30:01 +00:00
|
|
|
if r.destroyEvent.Type != structs.TaskKilled {
|
2016-10-17 18:41:22 +00:00
|
|
|
if r.destroyEvent.Type == structs.TaskKilling {
|
2016-10-21 00:27:16 +00:00
|
|
|
killEvent = r.destroyEvent
|
2016-10-17 18:41:22 +00:00
|
|
|
} else {
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStateRunning, r.destroyEvent, false)
|
2016-10-17 18:41:22 +00:00
|
|
|
}
|
2016-09-14 20:30:01 +00:00
|
|
|
}
|
|
|
|
|
2016-10-21 00:27:16 +00:00
|
|
|
r.killTask(killEvent)
|
2016-10-17 18:41:22 +00:00
|
|
|
close(stopCollection)
|
2017-01-10 21:24:45 +00:00
|
|
|
|
|
|
|
// Wait for handler to exit before calling cleanup
|
|
|
|
<-handleWaitCh
|
|
|
|
r.cleanup()
|
|
|
|
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStateDead, nil, false)
|
2016-02-29 00:56:05 +00:00
|
|
|
return
|
2015-08-29 22:46:10 +00:00
|
|
|
}
|
2015-08-23 22:30:16 +00:00
|
|
|
}
|
2015-11-14 06:07:13 +00:00
|
|
|
|
2016-02-29 00:56:05 +00:00
|
|
|
RESTART:
|
2017-04-19 00:18:23 +00:00
|
|
|
// shouldRestart will block if the task should restart after a delay.
|
2016-10-05 20:41:29 +00:00
|
|
|
restart := r.shouldRestart()
|
|
|
|
if !restart {
|
2017-01-10 21:24:45 +00:00
|
|
|
r.cleanup()
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStateDead, nil, false)
|
2015-11-16 20:26:11 +00:00
|
|
|
return
|
|
|
|
}
|
2015-11-14 06:07:13 +00:00
|
|
|
|
2016-02-29 00:56:05 +00:00
|
|
|
// Clear the handle so a new driver will be created.
|
2016-02-29 18:45:08 +00:00
|
|
|
r.handleLock.Lock()
|
2016-02-29 00:56:05 +00:00
|
|
|
r.handle = nil
|
2016-10-17 18:41:22 +00:00
|
|
|
handleWaitCh = nil
|
2016-06-07 21:34:21 +00:00
|
|
|
stopCollection = nil
|
2016-02-29 18:45:08 +00:00
|
|
|
r.handleLock.Unlock()
|
2015-11-16 20:26:11 +00:00
|
|
|
}
|
2015-11-14 06:07:13 +00:00
|
|
|
}
|
|
|
|
|
2017-04-12 20:33:33 +00:00
|
|
|
// cleanup removes Consul entries and calls Driver.Cleanup when a task is
|
|
|
|
// stopping. Errors are logged.
|
2017-01-10 21:24:45 +00:00
|
|
|
func (r *TaskRunner) cleanup() {
|
2017-04-12 20:33:33 +00:00
|
|
|
// Remove from Consul
|
2017-07-21 20:35:40 +00:00
|
|
|
interpTask := interpolateServices(r.envBuilder.Build(), r.task)
|
|
|
|
r.consul.RemoveTask(r.alloc.ID, interpTask)
|
2017-04-12 20:33:33 +00:00
|
|
|
|
2017-01-13 01:21:54 +00:00
|
|
|
drv, err := r.createDriver()
|
|
|
|
if err != nil {
|
|
|
|
r.logger.Printf("[ERR] client: error creating driver to cleanup resources: %v", err)
|
|
|
|
return
|
2017-01-10 21:24:45 +00:00
|
|
|
}
|
2017-01-13 01:21:54 +00:00
|
|
|
|
2017-02-10 01:44:58 +00:00
|
|
|
res := r.getCreatedResources()
|
2017-01-31 18:51:32 +00:00
|
|
|
|
2017-05-23 00:46:40 +00:00
|
|
|
ctx := driver.NewExecContext(r.taskDir, r.envBuilder.Build())
|
2017-01-13 01:21:54 +00:00
|
|
|
attempts := 1
|
2017-01-14 00:46:08 +00:00
|
|
|
var cleanupErr error
|
|
|
|
for retry := true; retry; attempts++ {
|
2017-01-19 23:07:01 +00:00
|
|
|
cleanupErr = drv.Cleanup(ctx, res)
|
|
|
|
retry = structs.IsRecoverable(cleanupErr)
|
2017-01-13 01:21:54 +00:00
|
|
|
|
2017-01-14 00:46:08 +00:00
|
|
|
// Copy current createdResources state in case SaveState is
|
|
|
|
// called between retries
|
2017-02-10 01:44:58 +00:00
|
|
|
r.setCreatedResources(res)
|
2017-01-14 00:46:08 +00:00
|
|
|
|
2017-01-13 01:21:54 +00:00
|
|
|
// Retry 3 times with sleeps between
|
2017-01-20 00:48:23 +00:00
|
|
|
if !retry || attempts > 3 {
|
2017-01-13 01:21:54 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
time.Sleep(time.Duration(attempts) * time.Second)
|
|
|
|
}
|
|
|
|
|
2017-01-14 00:46:08 +00:00
|
|
|
if cleanupErr != nil {
|
|
|
|
r.logger.Printf("[ERR] client: error cleaning up resources for task %q after %d attempts: %v", r.task.Name, attempts, cleanupErr)
|
2017-01-13 01:21:54 +00:00
|
|
|
}
|
|
|
|
return
|
2017-01-10 21:24:45 +00:00
|
|
|
}
|
|
|
|
|
2016-10-06 22:21:59 +00:00
|
|
|
// shouldRestart returns if the task should restart. If the return value is
|
|
|
|
// true, the task's restart policy has already been considered and any wait time
|
|
|
|
// between restarts has been applied.
|
2016-10-05 20:41:29 +00:00
|
|
|
func (r *TaskRunner) shouldRestart() bool {
|
|
|
|
state, when := r.restartTracker.GetState()
|
|
|
|
reason := r.restartTracker.GetReason()
|
|
|
|
switch state {
|
|
|
|
case structs.TaskNotRestarting, structs.TaskTerminated:
|
|
|
|
r.logger.Printf("[INFO] client: Not restarting task: %v for alloc: %v ", r.task.Name, r.alloc.ID)
|
|
|
|
if state == structs.TaskNotRestarting {
|
|
|
|
r.setState(structs.TaskStateDead,
|
|
|
|
structs.NewTaskEvent(structs.TaskNotRestarting).
|
2017-08-08 04:26:04 +00:00
|
|
|
SetRestartReason(reason).SetFailsTask(),
|
|
|
|
false)
|
2016-10-05 20:41:29 +00:00
|
|
|
}
|
|
|
|
return false
|
|
|
|
case structs.TaskRestarting:
|
|
|
|
r.logger.Printf("[INFO] client: Restarting task %q for alloc %q in %v", r.task.Name, r.alloc.ID, when)
|
|
|
|
r.setState(structs.TaskStatePending,
|
|
|
|
structs.NewTaskEvent(structs.TaskRestarting).
|
|
|
|
SetRestartDelay(when).
|
2017-08-08 04:26:04 +00:00
|
|
|
SetRestartReason(reason),
|
|
|
|
false)
|
2016-10-05 20:41:29 +00:00
|
|
|
default:
|
|
|
|
r.logger.Printf("[ERR] client: restart tracker returned unknown state: %q", state)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2017-04-19 00:18:23 +00:00
|
|
|
// Unregister from Consul while waiting to restart.
|
2017-07-21 20:35:40 +00:00
|
|
|
interpTask := interpolateServices(r.envBuilder.Build(), r.task)
|
|
|
|
r.consul.RemoveTask(r.alloc.ID, interpTask)
|
2017-04-19 00:18:23 +00:00
|
|
|
|
2016-10-05 20:41:29 +00:00
|
|
|
// Sleep but watch for destroy events.
|
|
|
|
select {
|
|
|
|
case <-time.After(when):
|
|
|
|
case <-r.destroyCh:
|
|
|
|
}
|
|
|
|
|
|
|
|
// Destroyed while we were waiting to restart, so abort.
|
|
|
|
r.destroyLock.Lock()
|
|
|
|
destroyed := r.destroy
|
|
|
|
r.destroyLock.Unlock()
|
|
|
|
if destroyed {
|
2016-10-21 00:27:16 +00:00
|
|
|
r.logger.Printf("[DEBUG] client: Not restarting task: %v because it has been destroyed", r.task.Name)
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStateDead, r.destroyEvent, false)
|
2016-10-05 20:41:29 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2016-10-21 00:27:16 +00:00
|
|
|
// killTask kills the running task. A killing event can optionally be passed and
|
|
|
|
// this event is used to mark the task as being killed. It provides a means to
|
|
|
|
// store extra information.
|
|
|
|
func (r *TaskRunner) killTask(killingEvent *structs.TaskEvent) {
|
2016-10-05 22:11:09 +00:00
|
|
|
r.runningLock.Lock()
|
|
|
|
running := r.running
|
|
|
|
r.runningLock.Unlock()
|
|
|
|
if !running {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-10-21 00:27:16 +00:00
|
|
|
// Get the kill timeout
|
2016-10-05 22:11:09 +00:00
|
|
|
timeout := driver.GetKillTimeout(r.task.KillTimeout, r.config.MaxKillTimeout)
|
2016-10-21 00:27:16 +00:00
|
|
|
|
|
|
|
// Build the event
|
|
|
|
var event *structs.TaskEvent
|
|
|
|
if killingEvent != nil {
|
|
|
|
event = killingEvent
|
|
|
|
event.Type = structs.TaskKilling
|
|
|
|
} else {
|
|
|
|
event = structs.NewTaskEvent(structs.TaskKilling)
|
|
|
|
}
|
|
|
|
event.SetKillTimeout(timeout)
|
|
|
|
|
|
|
|
// Mark that we received the kill event
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStateRunning, event, false)
|
2016-10-05 22:11:09 +00:00
|
|
|
|
2017-07-21 21:00:32 +00:00
|
|
|
handle := r.getHandle()
|
2017-04-13 16:52:16 +00:00
|
|
|
|
2016-10-05 22:11:09 +00:00
|
|
|
// Kill the task using an exponential backoff in-case of failures.
|
2017-04-13 16:52:16 +00:00
|
|
|
destroySuccess, err := r.handleDestroy(handle)
|
2016-10-05 22:11:09 +00:00
|
|
|
if !destroySuccess {
|
|
|
|
// We couldn't successfully destroy the resource created.
|
|
|
|
r.logger.Printf("[ERR] client: failed to kill task %q. Resources may have been leaked: %v", r.task.Name, err)
|
|
|
|
}
|
|
|
|
|
2016-10-06 22:21:59 +00:00
|
|
|
r.runningLock.Lock()
|
|
|
|
r.running = false
|
|
|
|
r.runningLock.Unlock()
|
|
|
|
|
2016-10-05 22:11:09 +00:00
|
|
|
// Store that the task has been destroyed and any associated error.
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState("", structs.NewTaskEvent(structs.TaskKilled).SetKillError(err), true)
|
2016-10-05 22:11:09 +00:00
|
|
|
}
|
|
|
|
|
2016-12-03 01:04:07 +00:00
|
|
|
// startTask creates the driver, task dir, and starts the task.
|
2016-06-07 21:34:21 +00:00
|
|
|
func (r *TaskRunner) startTask() error {
|
2016-02-29 00:56:05 +00:00
|
|
|
// Create a driver
|
2016-12-03 01:04:07 +00:00
|
|
|
drv, err := r.createDriver()
|
2016-02-29 00:56:05 +00:00
|
|
|
if err != nil {
|
2016-11-30 00:39:36 +00:00
|
|
|
return fmt.Errorf("failed to create driver of task %q for alloc %q: %v",
|
|
|
|
r.task.Name, r.alloc.ID, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run prestart
|
2017-05-23 00:46:40 +00:00
|
|
|
ctx := driver.NewExecContext(r.taskDir, r.envBuilder.Build())
|
2017-06-09 17:29:41 +00:00
|
|
|
presp, err := drv.Prestart(ctx, r.task)
|
2017-01-10 21:24:45 +00:00
|
|
|
|
|
|
|
// Merge newly created resources into previously created resources
|
2017-06-09 17:29:41 +00:00
|
|
|
if presp != nil {
|
2017-05-23 20:29:01 +00:00
|
|
|
r.createdResourcesLock.Lock()
|
2017-06-09 17:29:41 +00:00
|
|
|
r.createdResources.Merge(presp.CreatedResources)
|
2017-05-23 20:29:01 +00:00
|
|
|
r.createdResourcesLock.Unlock()
|
2017-06-13 21:02:11 +00:00
|
|
|
|
|
|
|
// Set any network configuration returned by the driver
|
|
|
|
r.envBuilder.SetDriverNetwork(presp.Network)
|
2017-05-19 18:08:49 +00:00
|
|
|
}
|
|
|
|
|
2017-01-10 21:24:45 +00:00
|
|
|
if err != nil {
|
2017-03-27 22:37:15 +00:00
|
|
|
wrapped := fmt.Sprintf("failed to initialize task %q for alloc %q: %v",
|
2016-02-29 00:56:05 +00:00
|
|
|
r.task.Name, r.alloc.ID, err)
|
2017-03-27 22:37:15 +00:00
|
|
|
r.logger.Printf("[WARN] client: error from prestart: %s", wrapped)
|
|
|
|
return structs.WrapRecoverable(wrapped, err)
|
2016-02-29 00:56:05 +00:00
|
|
|
}
|
|
|
|
|
2017-05-23 00:46:40 +00:00
|
|
|
// Create a new context for Start since the environment may have been updated.
|
|
|
|
ctx = driver.NewExecContext(r.taskDir, r.envBuilder.Build())
|
|
|
|
|
2016-02-29 00:56:05 +00:00
|
|
|
// Start the job
|
2017-06-09 17:29:41 +00:00
|
|
|
sresp, err := drv.Start(ctx, r.task)
|
2016-02-29 00:56:05 +00:00
|
|
|
if err != nil {
|
2017-03-27 22:37:15 +00:00
|
|
|
wrapped := fmt.Sprintf("failed to start task %q for alloc %q: %v",
|
2016-02-29 00:56:05 +00:00
|
|
|
r.task.Name, r.alloc.ID, err)
|
2017-03-27 22:37:15 +00:00
|
|
|
r.logger.Printf("[WARN] client: %s", wrapped)
|
|
|
|
return structs.WrapRecoverable(wrapped, err)
|
2016-10-29 00:49:46 +00:00
|
|
|
|
2016-02-29 00:56:05 +00:00
|
|
|
}
|
|
|
|
|
2017-12-21 00:18:49 +00:00
|
|
|
// Log driver network information
|
|
|
|
if sresp.Network != nil && sresp.Network.IP != "" {
|
|
|
|
if sresp.Network.AutoAdvertise {
|
|
|
|
r.logger.Printf("[INFO] client: alloc %s task %s auto-advertising detected IP %s",
|
|
|
|
r.alloc.ID, r.task.Name, sresp.Network.IP)
|
|
|
|
} else {
|
2018-01-16 23:24:14 +00:00
|
|
|
r.logger.Printf("[TRACE] client: alloc %s task %s detected IP %s but not auto-advertising",
|
2017-12-21 00:18:49 +00:00
|
|
|
r.alloc.ID, r.task.Name, sresp.Network.IP)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if sresp.Network == nil || sresp.Network.IP == "" {
|
2018-01-16 23:24:14 +00:00
|
|
|
r.logger.Printf("[TRACE] client: alloc %s task %s could not detect a driver IP", r.alloc.ID, r.task.Name)
|
2017-12-21 00:18:49 +00:00
|
|
|
}
|
|
|
|
|
2017-06-13 21:02:11 +00:00
|
|
|
// Update environment with the network defined by the driver's Start method.
|
2017-06-09 17:29:41 +00:00
|
|
|
r.envBuilder.SetDriverNetwork(sresp.Network)
|
|
|
|
|
|
|
|
if err := r.registerServices(drv, sresp.Handle, sresp.Network); err != nil {
|
2017-04-13 16:52:16 +00:00
|
|
|
// All IO is done asynchronously, so errors from registering
|
|
|
|
// services are hard failures.
|
|
|
|
r.logger.Printf("[ERR] client: failed to register services and checks for task %q alloc %q: %v", r.task.Name, r.alloc.ID, err)
|
|
|
|
|
|
|
|
// Kill the started task
|
2017-06-09 17:29:41 +00:00
|
|
|
if destroyed, err := r.handleDestroy(sresp.Handle); !destroyed {
|
2017-04-13 16:52:16 +00:00
|
|
|
r.logger.Printf("[ERR] client: failed to kill task %q alloc %q. Resources may be leaked: %v",
|
|
|
|
r.task.Name, r.alloc.ID, err)
|
|
|
|
}
|
|
|
|
return structs.NewRecoverableError(err, false)
|
|
|
|
}
|
|
|
|
|
2016-02-29 00:56:05 +00:00
|
|
|
r.handleLock.Lock()
|
2017-06-09 17:29:41 +00:00
|
|
|
r.handle = sresp.Handle
|
2016-02-29 00:56:05 +00:00
|
|
|
r.handleLock.Unlock()
|
2017-02-01 00:43:57 +00:00
|
|
|
|
2017-06-16 23:35:16 +00:00
|
|
|
// Need to persist the driver network between restarts
|
|
|
|
r.driverNetLock.Lock()
|
|
|
|
r.driverNet = sresp.Network
|
|
|
|
r.driverNetLock.Unlock()
|
|
|
|
|
2017-04-13 16:52:16 +00:00
|
|
|
return nil
|
|
|
|
}
|
2017-02-01 00:43:57 +00:00
|
|
|
|
2017-04-13 16:52:16 +00:00
|
|
|
// registerServices and checks with Consul.
|
2017-06-09 17:29:41 +00:00
|
|
|
func (r *TaskRunner) registerServices(d driver.Driver, h driver.DriverHandle, n *cstructs.DriverNetwork) error {
|
2017-04-13 16:52:16 +00:00
|
|
|
var exec driver.ScriptExecutor
|
|
|
|
if d.Abilities().Exec {
|
|
|
|
// Allow set the script executor if the driver supports it
|
|
|
|
exec = h
|
2017-02-01 00:43:57 +00:00
|
|
|
}
|
2017-07-21 20:35:40 +00:00
|
|
|
interpolatedTask := interpolateServices(r.envBuilder.Build(), r.task)
|
2017-08-26 05:40:18 +00:00
|
|
|
return r.consul.RegisterTask(r.alloc.ID, interpolatedTask, r, exec, n)
|
2016-02-29 00:56:05 +00:00
|
|
|
}
|
|
|
|
|
2017-02-01 00:43:57 +00:00
|
|
|
// interpolateServices interpolates tags in a service and checks with values from the
|
|
|
|
// task's environment.
|
2017-07-21 20:35:40 +00:00
|
|
|
func interpolateServices(taskEnv *env.TaskEnv, task *structs.Task) *structs.Task {
|
|
|
|
taskCopy := task.Copy()
|
|
|
|
for _, service := range taskCopy.Services {
|
2017-02-01 00:43:57 +00:00
|
|
|
for _, check := range service.Checks {
|
|
|
|
check.Name = taskEnv.ReplaceEnv(check.Name)
|
|
|
|
check.Type = taskEnv.ReplaceEnv(check.Type)
|
|
|
|
check.Command = taskEnv.ReplaceEnv(check.Command)
|
|
|
|
check.Args = taskEnv.ParseAndReplace(check.Args)
|
|
|
|
check.Path = taskEnv.ReplaceEnv(check.Path)
|
|
|
|
check.Protocol = taskEnv.ReplaceEnv(check.Protocol)
|
|
|
|
check.PortLabel = taskEnv.ReplaceEnv(check.PortLabel)
|
|
|
|
check.InitialStatus = taskEnv.ReplaceEnv(check.InitialStatus)
|
2017-08-16 00:53:10 +00:00
|
|
|
check.Method = taskEnv.ReplaceEnv(check.Method)
|
|
|
|
if len(check.Header) > 0 {
|
|
|
|
header := make(map[string][]string, len(check.Header))
|
|
|
|
for k, vs := range check.Header {
|
|
|
|
newVals := make([]string, len(vs))
|
|
|
|
for i, v := range vs {
|
|
|
|
newVals[i] = taskEnv.ReplaceEnv(v)
|
|
|
|
}
|
|
|
|
header[taskEnv.ReplaceEnv(k)] = newVals
|
|
|
|
}
|
|
|
|
check.Header = header
|
|
|
|
}
|
2017-02-01 00:43:57 +00:00
|
|
|
}
|
|
|
|
service.Name = taskEnv.ReplaceEnv(service.Name)
|
|
|
|
service.PortLabel = taskEnv.ReplaceEnv(service.PortLabel)
|
|
|
|
service.Tags = taskEnv.ParseAndReplace(service.Tags)
|
|
|
|
}
|
2017-07-21 20:35:40 +00:00
|
|
|
return taskCopy
|
2017-02-01 00:43:57 +00:00
|
|
|
}
|
|
|
|
|
2016-12-03 01:04:07 +00:00
|
|
|
// buildTaskDir creates the task directory before driver.Prestart. It is safe
|
|
|
|
// to call multiple times as its state is persisted.
|
|
|
|
func (r *TaskRunner) buildTaskDir(fsi cstructs.FSIsolation) error {
|
|
|
|
r.persistLock.Lock()
|
2017-03-02 21:21:34 +00:00
|
|
|
built := r.taskDirBuilt
|
2016-12-03 01:04:07 +00:00
|
|
|
r.persistLock.Unlock()
|
|
|
|
|
2017-03-03 04:45:46 +00:00
|
|
|
// We do not set the state again since this only occurs during restoration
|
|
|
|
// and the task dir is already built. The reason we call Build again is to
|
|
|
|
// ensure that the task dir invariants are still held.
|
|
|
|
if !built {
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState(structs.TaskStatePending,
|
|
|
|
structs.NewTaskEvent(structs.TaskSetup).SetMessage(structs.TaskBuildingTaskDir),
|
|
|
|
false)
|
2017-03-03 04:45:46 +00:00
|
|
|
}
|
2017-02-23 02:26:34 +00:00
|
|
|
|
2016-12-03 01:04:07 +00:00
|
|
|
chroot := config.DefaultChrootEnv
|
|
|
|
if len(r.config.ChrootEnv) > 0 {
|
|
|
|
chroot = r.config.ChrootEnv
|
|
|
|
}
|
2017-03-02 21:21:34 +00:00
|
|
|
if err := r.taskDir.Build(built, chroot, fsi); err != nil {
|
2016-12-03 01:04:07 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Mark task dir as successfully built
|
|
|
|
r.persistLock.Lock()
|
|
|
|
r.taskDirBuilt = true
|
|
|
|
r.persistLock.Unlock()
|
2017-05-18 17:49:39 +00:00
|
|
|
|
2017-05-23 00:46:40 +00:00
|
|
|
// Set path and host related env vars
|
|
|
|
driver.SetEnvvars(r.envBuilder, fsi, r.taskDir, r.config)
|
2016-12-03 01:04:07 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-05-31 23:09:05 +00:00
|
|
|
// collectResourceUsageStats starts collecting resource usage stats of a Task.
|
|
|
|
// Collection ends when the passed channel is closed
|
|
|
|
func (r *TaskRunner) collectResourceUsageStats(stopCollection <-chan struct{}) {
|
2016-05-27 01:23:44 +00:00
|
|
|
// start collecting the stats right away and then start collecting every
|
|
|
|
// collection interval
|
|
|
|
next := time.NewTimer(0)
|
|
|
|
defer next.Stop()
|
2016-04-29 18:06:19 +00:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-next.C:
|
2016-06-03 21:23:18 +00:00
|
|
|
next.Reset(r.config.StatsCollectionInterval)
|
2017-07-21 21:00:32 +00:00
|
|
|
handle := r.getHandle()
|
|
|
|
if handle == nil {
|
2016-09-20 18:29:34 +00:00
|
|
|
continue
|
|
|
|
}
|
2017-07-21 21:00:32 +00:00
|
|
|
ru, err := handle.Stats()
|
2016-06-03 21:23:18 +00:00
|
|
|
|
2016-04-29 18:06:19 +00:00
|
|
|
if err != nil {
|
2017-01-09 21:47:06 +00:00
|
|
|
// Check if the driver doesn't implement stats
|
|
|
|
if err.Error() == driver.DriverStatsNotImplemented.Error() {
|
|
|
|
r.logger.Printf("[DEBUG] client: driver for task %q in allocation %q doesn't support stats", r.task.Name, r.alloc.ID)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-06-03 21:23:18 +00:00
|
|
|
// We do not log when the plugin is shutdown as this is simply a
|
|
|
|
// race between the stopCollection channel being closed and calling
|
|
|
|
// Stats on the handle.
|
|
|
|
if !strings.Contains(err.Error(), "connection is shut down") {
|
|
|
|
r.logger.Printf("[WARN] client: error fetching stats of task %v: %v", r.task.Name, err)
|
|
|
|
}
|
|
|
|
continue
|
2016-06-01 14:36:07 +00:00
|
|
|
}
|
2016-06-03 21:23:18 +00:00
|
|
|
|
|
|
|
r.resourceUsageLock.Lock()
|
2016-06-12 16:32:38 +00:00
|
|
|
r.resourceUsage = ru
|
2016-06-03 21:23:18 +00:00
|
|
|
r.resourceUsageLock.Unlock()
|
2016-08-22 16:34:24 +00:00
|
|
|
if ru != nil {
|
|
|
|
r.emitStats(ru)
|
|
|
|
}
|
2016-05-31 23:09:05 +00:00
|
|
|
case <-stopCollection:
|
2016-04-29 18:06:19 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-12 03:15:50 +00:00
|
|
|
// LatestResourceUsage returns the last resource utilization datapoint collected
|
|
|
|
func (r *TaskRunner) LatestResourceUsage() *cstructs.TaskResourceUsage {
|
2016-04-29 18:06:19 +00:00
|
|
|
r.resourceUsageLock.RLock()
|
|
|
|
defer r.resourceUsageLock.RUnlock()
|
2016-06-12 03:15:50 +00:00
|
|
|
r.runningLock.Lock()
|
|
|
|
defer r.runningLock.Unlock()
|
|
|
|
|
|
|
|
// If the task is not running there can be no latest resource
|
|
|
|
if !r.running {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-06-12 16:32:38 +00:00
|
|
|
return r.resourceUsage
|
2016-04-29 18:06:19 +00:00
|
|
|
}
|
|
|
|
|
2016-02-04 03:43:44 +00:00
|
|
|
// handleUpdate takes an updated allocation and updates internal state to
|
|
|
|
// reflect the new config for the task.
|
|
|
|
func (r *TaskRunner) handleUpdate(update *structs.Allocation) error {
|
|
|
|
// Extract the task group from the alloc.
|
|
|
|
tg := update.Job.LookupTaskGroup(update.TaskGroup)
|
|
|
|
if tg == nil {
|
|
|
|
return fmt.Errorf("alloc '%s' missing task group '%s'", update.ID, update.TaskGroup)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Extract the task.
|
2016-02-07 01:08:12 +00:00
|
|
|
var updatedTask *structs.Task
|
2016-02-04 03:43:44 +00:00
|
|
|
for _, t := range tg.Tasks {
|
|
|
|
if t.Name == r.task.Name {
|
2016-11-04 21:53:37 +00:00
|
|
|
updatedTask = t.Copy()
|
2017-09-10 23:25:13 +00:00
|
|
|
break
|
2016-02-04 03:43:44 +00:00
|
|
|
}
|
|
|
|
}
|
2016-02-07 01:08:12 +00:00
|
|
|
if updatedTask == nil {
|
2016-02-04 03:43:44 +00:00
|
|
|
return fmt.Errorf("task group %q doesn't contain task %q", tg.Name, r.task.Name)
|
|
|
|
}
|
2016-02-05 20:07:56 +00:00
|
|
|
|
|
|
|
// Merge in the task resources
|
2016-02-07 01:08:12 +00:00
|
|
|
updatedTask.Resources = update.TaskResources[updatedTask.Name]
|
2016-02-04 03:43:44 +00:00
|
|
|
|
2017-12-06 23:40:56 +00:00
|
|
|
// Interpolate the old task with the old env before updating the env as
|
|
|
|
// updating services in Consul need both the old and new interpolations
|
|
|
|
// to find differences.
|
|
|
|
oldInterpolatedTask := interpolateServices(r.envBuilder.Build(), r.task)
|
|
|
|
|
|
|
|
// Now it's safe to update the environment
|
2017-05-23 22:57:35 +00:00
|
|
|
r.envBuilder.UpdateTask(update, updatedTask)
|
|
|
|
|
2016-02-07 01:08:12 +00:00
|
|
|
var mErr multierror.Error
|
2016-02-10 21:44:53 +00:00
|
|
|
r.handleLock.Lock()
|
2016-02-04 03:43:44 +00:00
|
|
|
if r.handle != nil {
|
2017-04-13 16:52:16 +00:00
|
|
|
drv, err := r.createDriver()
|
|
|
|
if err != nil {
|
|
|
|
// Something has really gone wrong; don't continue
|
|
|
|
r.handleLock.Unlock()
|
|
|
|
return fmt.Errorf("error accessing driver when updating task %q: %v", r.task.Name, err)
|
|
|
|
}
|
|
|
|
|
2017-02-01 00:43:57 +00:00
|
|
|
// Update will update resources and store the new kill timeout.
|
2016-02-07 01:08:12 +00:00
|
|
|
if err := r.handle.Update(updatedTask); err != nil {
|
|
|
|
mErr.Errors = append(mErr.Errors, fmt.Errorf("updating task resources failed: %v", err))
|
2016-02-04 03:43:44 +00:00
|
|
|
}
|
2017-04-04 00:08:08 +00:00
|
|
|
|
2017-05-23 22:57:35 +00:00
|
|
|
// Update services in Consul
|
2017-12-06 23:40:56 +00:00
|
|
|
newInterpolatedTask := interpolateServices(r.envBuilder.Build(), updatedTask)
|
|
|
|
if err := r.updateServices(drv, r.handle, oldInterpolatedTask, newInterpolatedTask); err != nil {
|
2017-04-04 00:08:08 +00:00
|
|
|
mErr.Errors = append(mErr.Errors, fmt.Errorf("error updating services and checks in Consul: %v", err))
|
|
|
|
}
|
2016-02-04 03:43:44 +00:00
|
|
|
}
|
2016-02-10 21:44:53 +00:00
|
|
|
r.handleLock.Unlock()
|
2016-02-04 03:43:44 +00:00
|
|
|
|
|
|
|
// Update the restart policy.
|
|
|
|
if r.restartTracker != nil {
|
|
|
|
r.restartTracker.SetPolicy(tg.RestartPolicy)
|
|
|
|
}
|
|
|
|
|
2016-02-07 01:08:12 +00:00
|
|
|
// Store the updated alloc.
|
2016-02-04 03:43:44 +00:00
|
|
|
r.alloc = update
|
2016-02-07 01:08:12 +00:00
|
|
|
r.task = updatedTask
|
|
|
|
return mErr.ErrorOrNil()
|
2016-02-04 03:43:44 +00:00
|
|
|
}
|
|
|
|
|
2017-12-06 23:40:56 +00:00
|
|
|
// updateServices and checks with Consul. Tasks must be interpolated!
|
|
|
|
func (r *TaskRunner) updateServices(d driver.Driver, h driver.ScriptExecutor, oldTask, newTask *structs.Task) error {
|
2017-04-13 16:52:16 +00:00
|
|
|
var exec driver.ScriptExecutor
|
|
|
|
if d.Abilities().Exec {
|
|
|
|
// Allow set the script executor if the driver supports it
|
|
|
|
exec = h
|
|
|
|
}
|
2017-06-16 23:35:16 +00:00
|
|
|
r.driverNetLock.Lock()
|
|
|
|
net := r.driverNet.Copy()
|
|
|
|
r.driverNetLock.Unlock()
|
2017-12-06 23:40:56 +00:00
|
|
|
return r.consul.UpdateTask(r.alloc.ID, oldTask, newTask, r, exec, net)
|
2017-04-13 16:52:16 +00:00
|
|
|
}
|
|
|
|
|
2016-02-17 05:00:49 +00:00
|
|
|
// handleDestroy kills the task handle. In the case that killing fails,
|
|
|
|
// handleDestroy will retry with an exponential backoff and will give up at a
|
|
|
|
// given limit. It returns whether the task was destroyed and the error
|
|
|
|
// associated with the last kill attempt.
|
2017-04-13 16:52:16 +00:00
|
|
|
func (r *TaskRunner) handleDestroy(handle driver.DriverHandle) (destroyed bool, err error) {
|
2016-02-17 05:00:49 +00:00
|
|
|
// Cap the number of times we attempt to kill the task.
|
|
|
|
for i := 0; i < killFailureLimit; i++ {
|
2017-04-13 16:52:16 +00:00
|
|
|
if err = handle.Kill(); err != nil {
|
2016-02-17 05:00:49 +00:00
|
|
|
// Calculate the new backoff
|
|
|
|
backoff := (1 << (2 * uint64(i))) * killBackoffBaseline
|
|
|
|
if backoff > killBackoffLimit {
|
|
|
|
backoff = killBackoffLimit
|
|
|
|
}
|
|
|
|
|
|
|
|
r.logger.Printf("[ERR] client: failed to kill task '%s' for alloc %q. Retrying in %v: %v",
|
|
|
|
r.task.Name, r.alloc.ID, backoff, err)
|
2017-09-26 22:26:33 +00:00
|
|
|
time.Sleep(backoff)
|
2016-02-17 05:00:49 +00:00
|
|
|
} else {
|
|
|
|
// Kill was successful
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-09-10 23:25:13 +00:00
|
|
|
// Restart will restart the task.
|
|
|
|
func (r *TaskRunner) Restart(source, reason string, failure bool) {
|
2016-10-05 20:41:29 +00:00
|
|
|
reasonStr := fmt.Sprintf("%s: %s", source, reason)
|
2017-09-13 06:15:46 +00:00
|
|
|
event := newTaskRestartEvent(reasonStr, failure)
|
2016-10-05 20:41:29 +00:00
|
|
|
|
|
|
|
select {
|
|
|
|
case r.restartCh <- event:
|
|
|
|
case <-r.waitCh:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Signal will send a signal to the task
|
2016-10-10 21:49:37 +00:00
|
|
|
func (r *TaskRunner) Signal(source, reason string, s os.Signal) error {
|
2016-10-05 20:41:29 +00:00
|
|
|
|
|
|
|
reasonStr := fmt.Sprintf("%s: %s", source, reason)
|
|
|
|
event := structs.NewTaskEvent(structs.TaskSignaling).SetTaskSignal(s).SetTaskSignalReason(reasonStr)
|
|
|
|
|
2016-10-10 21:49:37 +00:00
|
|
|
resCh := make(chan error)
|
|
|
|
se := SignalEvent{
|
|
|
|
s: s,
|
|
|
|
e: event,
|
|
|
|
result: resCh,
|
|
|
|
}
|
2017-03-24 19:04:22 +00:00
|
|
|
|
2016-10-05 20:41:29 +00:00
|
|
|
select {
|
2016-10-10 21:49:37 +00:00
|
|
|
case r.signalCh <- se:
|
2016-10-05 20:41:29 +00:00
|
|
|
case <-r.waitCh:
|
|
|
|
}
|
2016-10-10 21:49:37 +00:00
|
|
|
|
|
|
|
return <-resCh
|
2016-10-05 20:41:29 +00:00
|
|
|
}
|
|
|
|
|
2016-10-21 00:27:16 +00:00
|
|
|
// Kill will kill a task and store the error, no longer restarting the task. If
|
|
|
|
// fail is set, the task is marked as having failed.
|
|
|
|
func (r *TaskRunner) Kill(source, reason string, fail bool) {
|
2016-10-05 20:41:29 +00:00
|
|
|
reasonStr := fmt.Sprintf("%s: %s", source, reason)
|
|
|
|
event := structs.NewTaskEvent(structs.TaskKilling).SetKillReason(reasonStr)
|
2016-10-21 00:27:16 +00:00
|
|
|
if fail {
|
|
|
|
event.SetFailsTask()
|
|
|
|
}
|
2016-10-05 20:41:29 +00:00
|
|
|
|
|
|
|
r.logger.Printf("[DEBUG] client: killing task %v for alloc %q: %v", r.task.Name, r.alloc.ID, reasonStr)
|
2016-10-17 18:41:22 +00:00
|
|
|
r.Destroy(event)
|
2016-10-05 20:41:29 +00:00
|
|
|
}
|
|
|
|
|
2017-08-08 04:26:04 +00:00
|
|
|
func (r *TaskRunner) EmitEvent(source, message string) {
|
2017-11-03 14:34:30 +00:00
|
|
|
event := structs.NewTaskEvent(source).
|
|
|
|
SetMessage(message)
|
2017-08-08 04:26:04 +00:00
|
|
|
r.setState("", event, false)
|
|
|
|
r.logger.Printf("[DEBUG] client: event from %q for task %q in alloc %q: %v",
|
|
|
|
source, r.task.Name, r.alloc.ID, message)
|
|
|
|
}
|
|
|
|
|
2016-10-05 20:41:29 +00:00
|
|
|
// UnblockStart unblocks the starting of the task. It currently assumes only
|
|
|
|
// consul-template will unblock
|
|
|
|
func (r *TaskRunner) UnblockStart(source string) {
|
|
|
|
r.unblockLock.Lock()
|
|
|
|
defer r.unblockLock.Unlock()
|
|
|
|
if r.unblocked {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-10-06 22:17:34 +00:00
|
|
|
r.logger.Printf("[DEBUG] client: unblocking task %v for alloc %q: %v", r.task.Name, r.alloc.ID, source)
|
2016-10-18 18:22:16 +00:00
|
|
|
r.unblocked = true
|
2016-10-05 20:41:29 +00:00
|
|
|
close(r.unblockCh)
|
|
|
|
}
|
|
|
|
|
2015-11-14 06:07:13 +00:00
|
|
|
// Helper function for converting a WaitResult into a TaskTerminated event.
|
2016-06-12 03:15:50 +00:00
|
|
|
func (r *TaskRunner) waitErrorToEvent(res *dstructs.WaitResult) *structs.TaskEvent {
|
2015-11-16 22:46:18 +00:00
|
|
|
return structs.NewTaskEvent(structs.TaskTerminated).
|
|
|
|
SetExitCode(res.ExitCode).
|
|
|
|
SetSignal(res.Signal).
|
|
|
|
SetExitMessage(res.Err)
|
2015-08-23 22:30:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Update is used to update the task of the context
|
2016-02-04 03:43:44 +00:00
|
|
|
func (r *TaskRunner) Update(update *structs.Allocation) {
|
2015-08-23 22:30:16 +00:00
|
|
|
select {
|
2015-08-23 22:36:06 +00:00
|
|
|
case r.updateCh <- update:
|
2015-08-23 22:30:16 +00:00
|
|
|
default:
|
2015-08-29 22:46:10 +00:00
|
|
|
r.logger.Printf("[ERR] client: dropping task update '%s' (alloc '%s')",
|
2016-02-04 03:43:44 +00:00
|
|
|
r.task.Name, r.alloc.ID)
|
2015-08-23 22:30:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-08-11 07:20:53 +00:00
|
|
|
// Destroy is used to indicate that the task context should be destroyed. The
|
|
|
|
// event parameter provides a context for the destroy.
|
|
|
|
func (r *TaskRunner) Destroy(event *structs.TaskEvent) {
|
2015-08-23 22:36:06 +00:00
|
|
|
r.destroyLock.Lock()
|
|
|
|
defer r.destroyLock.Unlock()
|
2015-08-23 22:30:16 +00:00
|
|
|
|
2015-08-23 22:36:06 +00:00
|
|
|
if r.destroy {
|
2015-08-23 22:30:16 +00:00
|
|
|
return
|
|
|
|
}
|
2015-08-23 22:36:06 +00:00
|
|
|
r.destroy = true
|
2016-08-11 07:20:53 +00:00
|
|
|
r.destroyEvent = event
|
2015-08-23 22:36:06 +00:00
|
|
|
close(r.destroyCh)
|
2015-08-23 22:30:16 +00:00
|
|
|
}
|
2016-06-01 14:36:07 +00:00
|
|
|
|
2017-02-10 01:44:58 +00:00
|
|
|
// getCreatedResources returns the resources created by drivers. It will never
|
|
|
|
// return nil.
|
|
|
|
func (r *TaskRunner) getCreatedResources() *driver.CreatedResources {
|
|
|
|
r.createdResourcesLock.Lock()
|
|
|
|
if r.createdResources == nil {
|
|
|
|
r.createdResources = driver.NewCreatedResources()
|
|
|
|
}
|
|
|
|
cr := r.createdResources.Copy()
|
|
|
|
r.createdResourcesLock.Unlock()
|
|
|
|
|
|
|
|
return cr
|
|
|
|
}
|
|
|
|
|
|
|
|
// setCreatedResources updates the resources created by drivers. If passed nil
|
|
|
|
// it will set createdResources to an initialized struct.
|
|
|
|
func (r *TaskRunner) setCreatedResources(cr *driver.CreatedResources) {
|
|
|
|
if cr == nil {
|
|
|
|
cr = driver.NewCreatedResources()
|
|
|
|
}
|
|
|
|
r.createdResourcesLock.Lock()
|
|
|
|
r.createdResources = cr.Copy()
|
|
|
|
r.createdResourcesLock.Unlock()
|
|
|
|
}
|
|
|
|
|
2017-08-31 16:29:15 +00:00
|
|
|
func (r *TaskRunner) setGaugeForMemory(ru *cstructs.TaskResourceUsage) {
|
|
|
|
if !r.config.DisableTaggedMetrics {
|
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "memory", "rss"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.MemoryStats.RSS), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "memory", "rss"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.MemoryStats.RSS), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "memory", "cache"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.MemoryStats.Cache), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "memory", "swap"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.MemoryStats.Swap), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "memory", "max_usage"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.MemoryStats.MaxUsage), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "memory", "kernel_usage"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.MemoryStats.KernelUsage), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "memory", "kernel_max_usage"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.MemoryStats.KernelMaxUsage), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if r.config.BackwardsCompatibleMetrics {
|
2016-06-11 20:09:34 +00:00
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "memory", "rss"}, float32(ru.ResourceUsage.MemoryStats.RSS))
|
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "memory", "cache"}, float32(ru.ResourceUsage.MemoryStats.Cache))
|
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "memory", "swap"}, float32(ru.ResourceUsage.MemoryStats.Swap))
|
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "memory", "max_usage"}, float32(ru.ResourceUsage.MemoryStats.MaxUsage))
|
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "memory", "kernel_usage"}, float32(ru.ResourceUsage.MemoryStats.KernelUsage))
|
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "memory", "kernel_max_usage"}, float32(ru.ResourceUsage.MemoryStats.KernelMaxUsage))
|
2016-06-06 22:31:50 +00:00
|
|
|
}
|
2017-08-31 16:29:15 +00:00
|
|
|
}
|
2016-06-06 22:31:50 +00:00
|
|
|
|
2017-08-31 16:29:15 +00:00
|
|
|
func (r *TaskRunner) setGaugeForCPU(ru *cstructs.TaskResourceUsage) {
|
|
|
|
if !r.config.DisableTaggedMetrics {
|
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "total_percent"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.CpuStats.Percent), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "system"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.CpuStats.SystemMode), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "user"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.CpuStats.UserMode), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "throttled_time"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.CpuStats.ThrottledTime), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "throttled_periods"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.CpuStats.ThrottledPeriods), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "total_ticks"},
|
2017-08-31 19:22:53 +00:00
|
|
|
float32(ru.ResourceUsage.CpuStats.TotalTicks), r.baseLabels)
|
2017-08-31 16:29:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if r.config.BackwardsCompatibleMetrics {
|
2016-06-21 00:30:25 +00:00
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "cpu", "total_percent"}, float32(ru.ResourceUsage.CpuStats.Percent))
|
2016-06-11 20:09:34 +00:00
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "cpu", "system"}, float32(ru.ResourceUsage.CpuStats.SystemMode))
|
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "cpu", "user"}, float32(ru.ResourceUsage.CpuStats.UserMode))
|
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "cpu", "throttled_time"}, float32(ru.ResourceUsage.CpuStats.ThrottledTime))
|
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "cpu", "throttled_periods"}, float32(ru.ResourceUsage.CpuStats.ThrottledPeriods))
|
2016-06-21 00:30:25 +00:00
|
|
|
metrics.SetGauge([]string{"client", "allocs", r.alloc.Job.Name, r.alloc.TaskGroup, r.alloc.ID, r.task.Name, "cpu", "total_ticks"}, float32(ru.ResourceUsage.CpuStats.TotalTicks))
|
2016-06-06 22:31:50 +00:00
|
|
|
}
|
2016-06-01 14:36:07 +00:00
|
|
|
}
|
2017-08-31 16:29:15 +00:00
|
|
|
|
|
|
|
// emitStats emits resource usage stats of tasks to remote metrics collector
|
|
|
|
// sinks
|
|
|
|
func (r *TaskRunner) emitStats(ru *cstructs.TaskResourceUsage) {
|
2017-09-04 02:56:47 +00:00
|
|
|
if !r.config.PublishAllocationMetrics {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-11-15 21:21:06 +00:00
|
|
|
// If the task is not running don't emit anything
|
|
|
|
r.runningLock.Lock()
|
|
|
|
running := r.running
|
|
|
|
r.runningLock.Unlock()
|
|
|
|
if !running {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-09-04 02:56:47 +00:00
|
|
|
if ru.ResourceUsage.MemoryStats != nil {
|
2017-08-31 16:29:15 +00:00
|
|
|
r.setGaugeForMemory(ru)
|
|
|
|
}
|
|
|
|
|
2017-09-04 02:56:47 +00:00
|
|
|
if ru.ResourceUsage.CpuStats != nil {
|
2017-08-31 16:29:15 +00:00
|
|
|
r.setGaugeForCPU(ru)
|
|
|
|
}
|
|
|
|
}
|