2015-08-23 22:30:16 +00:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
2015-08-30 01:16:49 +00:00
|
|
|
"crypto/md5"
|
|
|
|
"encoding/hex"
|
2015-08-29 22:46:10 +00:00
|
|
|
"fmt"
|
2015-08-23 22:30:16 +00:00
|
|
|
"log"
|
2015-08-30 01:16:49 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
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
|
|
|
|
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"
|
2015-08-23 22:30:16 +00:00
|
|
|
"github.com/hashicorp/nomad/nomad/structs"
|
2015-11-14 06:07:13 +00:00
|
|
|
|
|
|
|
cstructs "github.com/hashicorp/nomad/client/driver/structs"
|
2015-08-23 22:30:16 +00:00
|
|
|
)
|
|
|
|
|
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 {
|
2015-11-05 19:12:31 +00:00
|
|
|
config *config.Config
|
|
|
|
updater TaskStateUpdater
|
|
|
|
logger *log.Logger
|
|
|
|
ctx *driver.ExecContext
|
|
|
|
allocID string
|
|
|
|
restartTracker restartTracker
|
2015-11-18 08:50:45 +00:00
|
|
|
consulClient *ConsulClient
|
2015-08-23 22:30:16 +00:00
|
|
|
|
2015-11-06 00:38:19 +00:00
|
|
|
task *structs.Task
|
2015-11-14 06:07:13 +00:00
|
|
|
state *structs.TaskState
|
2015-11-06 00:38:19 +00:00
|
|
|
updateCh chan *structs.Task
|
|
|
|
handle driver.DriverHandle
|
2015-08-23 22:30:16 +00:00
|
|
|
|
|
|
|
destroy bool
|
|
|
|
destroyCh chan struct{}
|
|
|
|
destroyLock sync.Mutex
|
2015-08-30 02:42:35 +00:00
|
|
|
waitCh chan struct{}
|
2015-11-09 20:36:07 +00:00
|
|
|
|
|
|
|
snapshotLock sync.Mutex
|
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 {
|
2015-08-30 02:14:47 +00:00
|
|
|
Task *structs.Task
|
|
|
|
HandleID string
|
2015-08-30 01:16:49 +00:00
|
|
|
}
|
|
|
|
|
2015-11-14 06:07:13 +00:00
|
|
|
// TaskStateUpdater is used to signal that tasks state has changed.
|
|
|
|
type TaskStateUpdater func(taskName string)
|
2015-08-30 02:42:35 +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,
|
|
|
|
updater TaskStateUpdater, ctx *driver.ExecContext,
|
2015-11-14 06:07:13 +00:00
|
|
|
allocID string, task *structs.Task, state *structs.TaskState,
|
2015-11-18 08:50:45 +00:00
|
|
|
restartTracker restartTracker, consulClient *ConsulClient) *TaskRunner {
|
2015-11-03 17:24:26 +00:00
|
|
|
|
2015-08-23 22:32:46 +00:00
|
|
|
tc := &TaskRunner{
|
2015-11-05 19:12:31 +00:00
|
|
|
config: config,
|
|
|
|
updater: updater,
|
|
|
|
logger: logger,
|
2015-11-06 00:38:19 +00:00
|
|
|
restartTracker: restartTracker,
|
2015-11-18 08:50:45 +00:00
|
|
|
consulClient: consulClient,
|
2015-11-05 19:12:31 +00:00
|
|
|
ctx: ctx,
|
|
|
|
allocID: allocID,
|
|
|
|
task: task,
|
2015-11-14 06:07:13 +00:00
|
|
|
state: state,
|
2015-11-05 19:12:31 +00:00
|
|
|
updateCh: make(chan *structs.Task, 8),
|
|
|
|
destroyCh: make(chan struct{}),
|
|
|
|
waitCh: make(chan struct{}),
|
2015-08-23 22:30:16 +00:00
|
|
|
}
|
|
|
|
return tc
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2015-08-30 01:16:49 +00:00
|
|
|
// stateFilePath returns the path to our state file
|
|
|
|
func (r *TaskRunner) stateFilePath() string {
|
|
|
|
// 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
|
|
|
|
path := filepath.Join(r.config.StateDir, "alloc", r.allocID,
|
|
|
|
dirName, "state.json")
|
|
|
|
return path
|
|
|
|
}
|
|
|
|
|
|
|
|
// RestoreState is used to restore our state
|
|
|
|
func (r *TaskRunner) RestoreState() error {
|
|
|
|
// Load the snapshot
|
|
|
|
var snap taskRunnerState
|
|
|
|
if err := restoreState(r.stateFilePath(), &snap); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Restore fields
|
|
|
|
r.task = snap.Task
|
|
|
|
|
2015-08-30 02:14:47 +00:00
|
|
|
// Restore the driver
|
|
|
|
if snap.HandleID != "" {
|
|
|
|
driver, err := r.createDriver()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
handle, err := driver.Open(r.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 {
|
|
|
|
r.logger.Printf("[ERR] client: failed to open handle to task '%s' for alloc '%s': %v",
|
|
|
|
r.task.Name, r.allocID, err)
|
2015-11-09 23:55:31 +00:00
|
|
|
return nil
|
2015-08-30 02:14:47 +00:00
|
|
|
}
|
|
|
|
r.handle = handle
|
|
|
|
}
|
2015-08-30 01:16:49 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// SaveState is used to snapshot our state
|
|
|
|
func (r *TaskRunner) SaveState() error {
|
2015-11-09 20:36:07 +00:00
|
|
|
r.snapshotLock.Lock()
|
|
|
|
defer r.snapshotLock.Unlock()
|
2015-08-30 01:16:49 +00:00
|
|
|
snap := taskRunnerState{
|
|
|
|
Task: r.task,
|
|
|
|
}
|
2015-08-30 02:14:47 +00:00
|
|
|
if r.handle != nil {
|
|
|
|
snap.HandleID = r.handle.ID()
|
|
|
|
}
|
2015-08-30 01:16:49 +00:00
|
|
|
return persistState(r.stateFilePath(), &snap)
|
|
|
|
}
|
|
|
|
|
|
|
|
// DestroyState is used to cleanup after ourselves
|
|
|
|
func (r *TaskRunner) DestroyState() error {
|
|
|
|
return os.RemoveAll(r.stateFilePath())
|
|
|
|
}
|
|
|
|
|
2015-11-16 20:10:29 +00:00
|
|
|
func (r *TaskRunner) appendEvent(event *structs.TaskEvent) {
|
|
|
|
capacity := 10
|
|
|
|
if r.state.Events == nil {
|
|
|
|
r.state.Events = make([]*structs.TaskEvent, 0, capacity)
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we hit capacity, then shift it.
|
|
|
|
if len(r.state.Events) == capacity {
|
|
|
|
old := r.state.Events
|
|
|
|
r.state.Events = make([]*structs.TaskEvent, 0, capacity)
|
|
|
|
r.state.Events = append(r.state.Events, old[1:]...)
|
|
|
|
}
|
|
|
|
|
|
|
|
r.state.Events = append(r.state.Events, event)
|
|
|
|
}
|
|
|
|
|
2015-11-14 06:07:13 +00:00
|
|
|
// setState is used to update the state of the task runner
|
|
|
|
func (r *TaskRunner) setState(state string, event *structs.TaskEvent) {
|
|
|
|
// Update the task.
|
|
|
|
r.state.State = state
|
2015-11-16 20:10:29 +00:00
|
|
|
r.appendEvent(event)
|
2015-11-14 06:07:13 +00:00
|
|
|
|
|
|
|
// Persist our state to disk.
|
2015-11-12 23:53:42 +00:00
|
|
|
if err := r.SaveState(); err != nil {
|
|
|
|
r.logger.Printf("[ERR] client: failed to save state of Task Runner: %v", r.task.Name)
|
|
|
|
}
|
2015-11-14 06:07:13 +00:00
|
|
|
|
|
|
|
// Indicate the task has been updated.
|
|
|
|
r.updater(r.task.Name)
|
2015-08-23 23:49:48 +00:00
|
|
|
}
|
|
|
|
|
2015-08-30 02:14:47 +00:00
|
|
|
// createDriver makes a driver for the task
|
|
|
|
func (r *TaskRunner) createDriver() (driver.Driver, error) {
|
2015-09-21 21:13:17 +00:00
|
|
|
driverCtx := driver.NewDriverContext(r.task.Name, r.config, r.config.Node, r.logger)
|
2015-09-10 01:06:23 +00:00
|
|
|
driver, err := driver.NewDriver(r.task.Driver, driverCtx)
|
2015-08-23 23:49:48 +00:00
|
|
|
if err != nil {
|
2015-08-30 02:14:47 +00:00
|
|
|
err = fmt.Errorf("failed to create driver '%s' for alloc %s: %v",
|
|
|
|
r.task.Driver, r.allocID, err)
|
|
|
|
r.logger.Printf("[ERR] client: %s", err)
|
|
|
|
}
|
|
|
|
return driver, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// startTask is used to start the task if there is no handle
|
|
|
|
func (r *TaskRunner) startTask() error {
|
|
|
|
// Create a driver
|
|
|
|
driver, err := r.createDriver()
|
|
|
|
if err != nil {
|
2015-11-14 06:07:13 +00:00
|
|
|
e := structs.NewTaskEvent(structs.TaskDriverFailure).SetDriverError(err)
|
|
|
|
r.setState(structs.TaskStateDead, e)
|
2015-08-30 02:14:47 +00:00
|
|
|
return err
|
2015-08-23 23:49:48 +00:00
|
|
|
}
|
2015-08-23 22:30:16 +00:00
|
|
|
|
2015-08-23 23:49:48 +00:00
|
|
|
// Start the job
|
|
|
|
handle, err := driver.Start(r.ctx, r.task)
|
|
|
|
if err != nil {
|
2015-08-29 22:46:10 +00:00
|
|
|
r.logger.Printf("[ERR] client: failed to start task '%s' for alloc '%s': %v",
|
|
|
|
r.task.Name, r.allocID, err)
|
2015-11-14 06:07:13 +00:00
|
|
|
e := structs.NewTaskEvent(structs.TaskDriverFailure).
|
|
|
|
SetDriverError(fmt.Errorf("failed to start: %v", err))
|
|
|
|
r.setState(structs.TaskStateDead, e)
|
2015-08-30 02:14:47 +00:00
|
|
|
return err
|
2015-08-23 23:49:48 +00:00
|
|
|
}
|
2015-08-30 02:14:47 +00:00
|
|
|
r.handle = handle
|
2015-11-14 06:07:13 +00:00
|
|
|
r.setState(structs.TaskStateRunning, structs.NewTaskEvent(structs.TaskStarted))
|
2015-08-30 02:14:47 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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')",
|
|
|
|
r.task.Name, r.allocID)
|
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
r.run()
|
2015-11-14 06:07:13 +00:00
|
|
|
return
|
|
|
|
}
|
2015-08-23 23:49:48 +00:00
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
func (r *TaskRunner) run() {
|
|
|
|
var forceStart bool
|
2015-08-23 22:30:16 +00:00
|
|
|
for {
|
2015-11-16 20:26:11 +00:00
|
|
|
// Start the task if not yet started or it is being forced.
|
|
|
|
if r.handle == nil || forceStart {
|
|
|
|
forceStart = false
|
|
|
|
if err := r.startTask(); err != nil {
|
|
|
|
return
|
2015-08-29 22:46:10 +00:00
|
|
|
}
|
2015-11-16 20:26:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Store the errors that caused use to stop waiting for updates.
|
|
|
|
var waitRes *cstructs.WaitResult
|
|
|
|
var destroyErr error
|
|
|
|
destroyed := false
|
|
|
|
|
2015-11-18 08:50:45 +00:00
|
|
|
// Register the services defined by the task with Consil
|
2015-11-18 09:18:29 +00:00
|
|
|
r.consulClient.Register(r.task, r.allocID)
|
2015-11-18 08:50:45 +00:00
|
|
|
|
2015-11-18 10:37:34 +00:00
|
|
|
// De-Register the services belonging to the task from consul
|
|
|
|
defer r.consulClient.Deregister(r.task)
|
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
OUTER:
|
|
|
|
// Wait for updates
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case waitRes = <-r.handle.WaitCh():
|
|
|
|
break OUTER
|
|
|
|
case update := <-r.updateCh:
|
|
|
|
// Update
|
|
|
|
r.task = update
|
|
|
|
if err := r.handle.Update(update); err != nil {
|
|
|
|
r.logger.Printf("[ERR] client: failed to update task '%s' for alloc '%s': %v", r.task.Name, r.allocID, err)
|
|
|
|
}
|
2015-11-19 01:33:29 +00:00
|
|
|
|
|
|
|
if err := r.consulClient.Register(update, r.allocID); err != nil {
|
|
|
|
r.logger.Printf("[ERR] client: failed to update service definition: %v", err)
|
|
|
|
}
|
2015-11-16 20:26:11 +00:00
|
|
|
case <-r.destroyCh:
|
2015-11-17 20:03:59 +00:00
|
|
|
// Avoid destroying twice
|
|
|
|
if destroyed {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
// Send the kill signal, and use the WaitCh to block until complete
|
|
|
|
if err := r.handle.Kill(); err != nil {
|
|
|
|
r.logger.Printf("[ERR] client: failed to kill task '%s' for alloc '%s': %v", r.task.Name, r.allocID, err)
|
|
|
|
destroyErr = err
|
|
|
|
}
|
|
|
|
destroyed = true
|
2015-08-29 22:46:10 +00:00
|
|
|
}
|
2015-08-23 22:30:16 +00:00
|
|
|
}
|
2015-11-14 06:07:13 +00:00
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
// If the user destroyed the task, we do not attempt to do any restarts.
|
|
|
|
if destroyed {
|
|
|
|
r.setState(structs.TaskStateDead, structs.NewTaskEvent(structs.TaskKilled).SetKillError(destroyErr))
|
|
|
|
return
|
|
|
|
}
|
2015-11-14 06:07:13 +00:00
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
// Log whether the task was successful or not.
|
|
|
|
if !waitRes.Successful() {
|
|
|
|
r.logger.Printf("[ERR] client: failed to complete task '%s' for alloc '%s': %v", r.task.Name, r.allocID, waitRes)
|
|
|
|
} else {
|
|
|
|
r.logger.Printf("[INFO] client: completed task '%s' for alloc '%s'", r.task.Name, r.allocID)
|
|
|
|
}
|
2015-11-14 06:07:13 +00:00
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
// Check if we should restart. If not mark task as dead and exit.
|
2015-11-23 18:56:38 +00:00
|
|
|
shouldRestart, when := r.restartTracker.nextRestart(waitRes.ExitCode)
|
|
|
|
waitEvent := r.waitErrorToEvent(waitRes)
|
2015-11-16 20:26:11 +00:00
|
|
|
if !shouldRestart {
|
|
|
|
r.logger.Printf("[INFO] client: Not restarting task: %v for alloc: %v ", r.task.Name, r.allocID)
|
|
|
|
r.setState(structs.TaskStateDead, waitEvent)
|
|
|
|
return
|
|
|
|
}
|
2015-11-14 06:07:13 +00:00
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
r.logger.Printf("[INFO] client: Restarting Task: %v", r.task.Name)
|
|
|
|
r.logger.Printf("[DEBUG] client: Sleeping for %v before restarting Task %v", when, r.task.Name)
|
|
|
|
r.setState(structs.TaskStatePending, waitEvent)
|
2015-11-14 06:07:13 +00:00
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
// Sleep but watch for destroy events.
|
|
|
|
select {
|
|
|
|
case <-time.After(when):
|
|
|
|
case <-r.destroyCh:
|
|
|
|
}
|
2015-11-14 06:07:13 +00:00
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
// Destroyed while we were waiting to restart, so abort.
|
|
|
|
r.destroyLock.Lock()
|
|
|
|
destroyed = r.destroy
|
|
|
|
r.destroyLock.Unlock()
|
|
|
|
if destroyed {
|
|
|
|
r.logger.Printf("[DEBUG] client: Not restarting task: %v because it's destroyed by user", r.task.Name)
|
|
|
|
r.setState(structs.TaskStateDead, structs.NewTaskEvent(structs.TaskKilled))
|
|
|
|
return
|
|
|
|
}
|
2015-11-14 06:07:13 +00:00
|
|
|
|
2015-11-16 20:26:11 +00:00
|
|
|
// Set force start because we are restarting the task.
|
|
|
|
forceStart = true
|
|
|
|
}
|
2015-11-18 08:50:45 +00:00
|
|
|
|
2015-11-14 06:07:13 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Helper function for converting a WaitResult into a TaskTerminated event.
|
|
|
|
func (r *TaskRunner) waitErrorToEvent(res *cstructs.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
|
2015-08-23 22:36:06 +00:00
|
|
|
func (r *TaskRunner) Update(update *structs.Task) {
|
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')",
|
|
|
|
update.Name, r.allocID)
|
2015-08-23 22:30:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Destroy is used to indicate that the task context should be destroyed
|
2015-08-23 22:36:06 +00:00
|
|
|
func (r *TaskRunner) Destroy() {
|
|
|
|
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
|
|
|
|
close(r.destroyCh)
|
2015-08-23 22:30:16 +00:00
|
|
|
}
|