-
Notifications
You must be signed in to change notification settings - Fork 1
/
handle.go
221 lines (191 loc) · 5.59 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package main
import (
"context"
"sync"
"time"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/client/lib/cpustats"
"github.com/hashicorp/nomad/plugins/drivers"
)
var (
measuredCPUStats = []string{"System Mode", "User Mode", "Percent"}
measuredMemStats = []string{"Usage", "Max Usage"}
)
// taskHandle should store all relevant runtime information
// such as process ID if this is a local task or other meta
// data if this driver deals with external APIs
type taskHandle struct {
// stateLock syncs access to all fields below
stateLock sync.RWMutex
driver *Driver
logger hclog.Logger
taskConfig *drivers.TaskConfig
procState drivers.TaskState
startedAt time.Time
completedAt time.Time
exitResult *drivers.ExitResult
collectionInterval time.Duration
// systemd unit name
unitName string
// task properties (periodically polled)
properties map[string]interface{}
totalCPUStats *cpustats.Tracker
}
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{
//"pid": strconv.Itoa(h.pid),
},
}
}
func (h *taskHandle) IsRunning() bool {
h.stateLock.RLock()
defer h.stateLock.RUnlock()
return h.procState == drivers.TaskStateRunning
}
func (h *taskHandle) runUnitMonitor() {
h.logger.Debug("Monitoring Unit", "unit", h.unitName)
timer := time.NewTimer(0)
defer func() {
h.logger.Debug("No longer monitoring Unit", "unit", h.unitName)
}()
for {
select {
case <-h.driver.ctx.Done():
return
case <-timer.C:
timer.Reset(h.collectionInterval)
}
gone := false
conn, err := h.driver.connection()
if err != nil {
h.logger.Warn("Unable to get unit properties, no dbus connection", "unit", h.unitName, "err", err)
gone = true
} else {
props, err := conn.GetAllPropertiesContext(h.driver.ctx, h.unitName)
if err == nil {
// cache latest known property set in handle. It's used by the stats collector
h.stateLock.Lock()
h.properties = props
h.stateLock.Unlock()
state := props["ActiveState"]
// is the unit still running?
if state == "inactive" || state == "failed" || props["SubState"] == "exited" {
gone = true
if props["Result"] == "oom-kill" {
// propagate OOM kills
h.exitResult.OOMKilled = true
}
h.exitResult.ExitCode = int(props["ExecMainStatus"].(int32))
// cleanup
_, err = conn.StopUnitContext(h.driver.ctx, h.unitName, "replace", nil)
if err != nil {
// Might not be a problem. This can be the case when we run a regular StopTask operation
h.logger.Debug("Unable to stop/remove completed unit", "unit", h.unitName, "err", err)
} else {
h.logger.Debug("Unit removed", "unit", h.unitName)
}
}
} else {
h.logger.Warn("Unable to get unit properties, may be gone", "unit", h.unitName, "err", err)
gone = true
}
}
if gone {
h.logger.Info("Unit is not running anymore", "unit", h.unitName)
// container was stopped, get exit code and other post mortem infos
h.stateLock.Lock()
h.completedAt = time.Now()
h.procState = drivers.TaskStateExited
h.stateLock.Unlock()
return
}
}
}
func (h *taskHandle) isRunning() bool {
h.stateLock.RLock()
defer h.stateLock.RUnlock()
return h.procState == drivers.TaskStateRunning
}
func (h *taskHandle) runExitWatcher(ctx context.Context, exitChannel chan *drivers.ExitResult) {
timer := time.NewTimer(0)
h.logger.Debug("Starting exitWatcher", "unit", h.unitName)
defer func() {
h.logger.Debug("Stopping exitWatcher", "unit", h.unitName)
// be sure to get the whole result
h.stateLock.Lock()
result := h.exitResult
h.stateLock.Unlock()
exitChannel <- result
close(exitChannel)
}()
for {
if !h.isRunning() {
return
}
select {
case <-ctx.Done():
return
case <-timer.C:
timer.Reset(time.Second)
}
}
}
func (h *taskHandle) runStatsEmitter(ctx context.Context, statsChannel chan *drivers.TaskResourceUsage, interval time.Duration) {
timer := time.NewTimer(0)
h.logger.Debug("Starting statsEmitter", "unit", h.unitName)
h.collectionInterval = interval
for {
select {
case <-ctx.Done():
h.logger.Debug("Stopping statsEmitter", "unit", h.unitName)
return
case <-timer.C:
timer.Reset(interval)
}
h.stateLock.Lock()
t := time.Now()
cpuNanosProp := h.properties["CPUUsageNSec"]
memoryProp := h.properties["MemoryCurrent"]
if cpuNanosProp == nil || memoryProp == nil {
h.stateLock.Unlock()
continue
}
cpuNanos := h.properties["CPUUsageNSec"].(uint64)
memory := h.properties["MemoryCurrent"].(uint64)
//FIXME implement cpu stats correctly
totalPercent := h.totalCPUStats.Percent(float64(cpuNanos))
cs := &drivers.CpuStats{
SystemMode: 0, //h.systemCPUStats.Percent(float64(h.containerStats.CPUStats.CPUUsage.UsageInKernelmode)),
UserMode: totalPercent,
Percent: totalPercent,
TotalTicks: h.totalCPUStats.TicksConsumed(totalPercent),
Measured: measuredCPUStats,
}
ms := &drivers.MemoryStats{
MaxUsage: memory,
Usage: memory,
RSS: memory,
Measured: measuredMemStats,
}
h.stateLock.Unlock()
// update uasge
usage := drivers.TaskResourceUsage{
ResourceUsage: &drivers.ResourceUsage{
CpuStats: cs,
MemoryStats: ms,
},
Timestamp: t.UTC().UnixNano(),
}
// send stats to nomad
statsChannel <- &usage
}
}