open-nomad/drivers/mock/handle.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

98 lines
2.2 KiB
Go
Raw Normal View History

package mock
import (
2018-10-12 23:56:13 +00:00
"context"
"sync"
"time"
hclog "github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/client/lib/fifo"
"github.com/hashicorp/nomad/plugins/drivers"
)
2018-10-31 18:52:51 +00:00
// taskHandle supervises a mock task
type taskHandle struct {
logger hclog.Logger
2019-01-04 22:04:45 +00:00
pluginExitAfter time.Duration
killAfter time.Duration
waitCh chan interface{}
taskConfig *drivers.TaskConfig
command Command
execCommand *Command
// stateLock guards the procState field
2018-10-31 18:52:51 +00:00
stateLock sync.RWMutex
procState drivers.TaskState
startedAt time.Time
completedAt time.Time
exitResult *drivers.ExitResult
2018-10-12 23:56:13 +00:00
// Calling kill closes killCh if it is not already closed
kill context.CancelFunc
killCh <-chan struct{}
2019-01-05 00:08:47 +00:00
// Recovered is set to true if the handle was created while being recovered
Recovered bool
}
2018-10-31 18:52:51 +00:00
func (h *taskHandle) TaskStatus() *drivers.TaskStatus {
h.stateLock.RLock()
defer h.stateLock.RUnlock()
return &drivers.TaskStatus{
ID: h.taskConfig.ID,
Name: h.taskConfig.Name,
State: h.procState,
StartedAt: h.startedAt,
CompletedAt: h.completedAt,
ExitResult: h.exitResult,
DriverAttributes: map[string]string{},
}
}
func (h *taskHandle) IsRunning() bool {
h.stateLock.Lock()
defer h.stateLock.Unlock()
return h.procState == drivers.TaskStateRunning
}
2018-10-31 18:52:51 +00:00
func (h *taskHandle) run() {
defer func() {
h.stateLock.Lock()
h.procState = drivers.TaskStateExited
h.stateLock.Unlock()
h.completedAt = time.Now()
close(h.waitCh)
}()
h.stateLock.Lock()
h.procState = drivers.TaskStateRunning
h.stateLock.Unlock()
2018-10-12 23:56:13 +00:00
2019-01-04 22:04:45 +00:00
var pluginExitTimer <-chan time.Time
if h.pluginExitAfter != 0 {
timer := time.NewTimer(h.pluginExitAfter)
defer timer.Stop()
pluginExitTimer = timer.C
}
2019-04-01 19:56:43 +00:00
stdout, err := fifo.OpenWriter(h.taskConfig.StdoutPath)
if err != nil {
2018-10-12 23:56:13 +00:00
h.logger.Error("failed to write to stdout", "error", err)
h.exitResult = &drivers.ExitResult{Err: err}
return
}
2019-04-01 19:56:43 +00:00
stderr, err := fifo.OpenWriter(h.taskConfig.StderrPath)
2019-01-05 00:08:47 +00:00
if err != nil {
h.logger.Error("failed to write to stderr", "error", err)
h.exitResult = &drivers.ExitResult{Err: err}
return
}
h.exitResult = runCommand(h.command, stdout, stderr, h.killCh, pluginExitTimer, h.logger)
}