forked from hashicorp/nomad
-
Notifications
You must be signed in to change notification settings - Fork 1
/
handle.go
98 lines (80 loc) · 2.22 KB
/
handle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package mock
import (
"context"
"sync"
"time"
hclog "github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/client/lib/fifo"
"github.com/hashicorp/nomad/plugins/drivers"
)
// taskHandle supervises a mock task
type taskHandle struct {
logger hclog.Logger
pluginExitAfter time.Duration
killAfter time.Duration
waitCh chan interface{}
taskConfig *drivers.TaskConfig
command Command
execCommand *Command
// stateLock guards the procState field
stateLock sync.RWMutex
procState drivers.TaskState
startedAt time.Time
completedAt time.Time
exitResult *drivers.ExitResult
// Calling kill closes killCh if it is not already closed
kill context.CancelFunc
killCh <-chan struct{}
// Recovered is set to true if the handle was created while being recovered
Recovered bool
}
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
}
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()
var pluginExitTimer <-chan time.Time
if h.pluginExitAfter != 0 {
timer := time.NewTimer(h.pluginExitAfter)
defer timer.Stop()
pluginExitTimer = timer.C
}
stdout, err := fifo.OpenWriter(h.taskConfig.StdoutPath)
if err != nil {
h.logger.Error("failed to write to stdout", "error", err)
h.exitResult = &drivers.ExitResult{Err: err}
return
}
stderr, err := fifo.OpenWriter(h.taskConfig.StderrPath)
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)
return
}