-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathhandle.go
More file actions
211 lines (176 loc) · 5.67 KB
/
handle.go
File metadata and controls
211 lines (176 loc) · 5.67 KB
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
package main
import (
"context"
"fmt"
"os"
"strconv"
"sync"
"syscall"
"time"
hclog "github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/client/stats"
"github.com/hashicorp/nomad/plugins/drivers"
"github.com/pascomnet/nomad-driver-podman/iopodman"
)
const (
// containerMonitorIntv is the interval at which the driver checks if the
// container is still alive
containerMonitorIntv = 2 * time.Second
)
var (
MeasuredCpuStats = []string{"System Mode", "User Mode", "Percent"}
MeasuredMemStats = []string{"RSS"}
)
type TaskHandle struct {
initPid int
containerID string
logger hclog.Logger
driver *Driver
totalCpuStats *stats.CpuStats
userCpuStats *stats.CpuStats
systemCpuStats *stats.CpuStats
// stateLock syncs access to all fields below
stateLock sync.RWMutex
taskConfig *drivers.TaskConfig
procState drivers.TaskState
startedAt time.Time
completedAt time.Time
exitResult *drivers.ExitResult
}
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.initPid),
},
}
}
func (h *TaskHandle) IsRunning() bool {
h.stateLock.RLock()
defer h.stateLock.RUnlock()
return h.procState == drivers.TaskStateRunning
}
func (h *TaskHandle) run() {
h.stateLock.Lock()
if h.exitResult == nil {
h.exitResult = &drivers.ExitResult{}
}
h.stateLock.Unlock()
h.logger.Debug("Monitoring process", "container", h.containerID, "pid", h.initPid)
if ok, err := waitTillStopped(h.initPid); !ok {
h.logger.Error("failed to find container process", "error", err)
return
}
h.logger.Debug("Process stopped", "container", h.containerID, "pid", h.initPid)
h.stateLock.Lock()
defer h.stateLock.Unlock()
h.procState = drivers.TaskStateExited
h.exitResult.ExitCode = 0
h.exitResult.Signal = 0
h.completedAt = time.Now()
// TODO: detect if the task OOMed
}
func (h *TaskHandle) stats(ctx context.Context, interval time.Duration) (<-chan *drivers.TaskResourceUsage, error) {
ch := make(chan *drivers.TaskResourceUsage)
go h.handleStats(ctx, ch, interval)
return ch, nil
}
func (h *TaskHandle) handleStats(ctx context.Context, ch chan *drivers.TaskResourceUsage, interval time.Duration) {
defer close(ch)
timer := time.NewTimer(0)
// stats are polled relatively often so it should be better
// to open a long living varlink connection instead
// of re-opening it on each poll cycle in the for-loop.
varlinkConnection, err := h.driver.getConnection()
if err != nil {
h.logger.Error("failed to get varlink connection for stats", "err", err)
return
}
defer varlinkConnection.Close()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
timer.Reset(interval)
}
containerStats, err := iopodman.GetContainerStats().Call(varlinkConnection, h.containerID)
if err != nil {
h.logger.Error("Could not get container stats", "err", err)
// maybe varlink connection was lost, we should check and try to reconnect
// FIXME: reconnect
// try again
continue
}
t := time.Now()
//FIXME implement cpu stats correctly
//available := shelpers.TotalTicksAvailable()
//cpus := shelpers.CPUNumCores()
totalPercent := h.totalCpuStats.Percent(containerStats.Cpu * 10e16)
cs := &drivers.CpuStats{
SystemMode: h.systemCpuStats.Percent(float64(containerStats.System_nano)),
UserMode: h.userCpuStats.Percent(float64(containerStats.Cpu_nano)),
Percent: totalPercent,
TotalTicks: h.systemCpuStats.TicksConsumed(totalPercent),
Measured: MeasuredCpuStats,
}
//h.driver.logger.Info("stats", "cpu", containerStats.Cpu, "system", containerStats.System_nano, "user", containerStats.Cpu_nano, "percent", totalPercent, "ticks", cs.TotalTicks, "cpus", cpus, "available", available)
ms := &drivers.MemoryStats{
RSS: uint64(containerStats.Mem_usage),
Measured: MeasuredMemStats,
}
taskResUsage := drivers.TaskResourceUsage{
ResourceUsage: &drivers.ResourceUsage{
CpuStats: cs,
MemoryStats: ms,
},
Timestamp: t.UTC().UnixNano(),
}
select {
case <-ctx.Done():
return
case ch <- &taskResUsage:
}
}
}
// shutdown shuts down the container, with `timeout` grace period
// before killing the container with SIGKILL.
func (h *TaskHandle) shutdown(timeout time.Duration) error {
varlinkConnection, err := h.driver.getConnection()
if err != nil {
return fmt.Errorf("executor Shutdown failed, could not get podman connection: %v", err)
}
defer varlinkConnection.Close()
h.driver.logger.Debug("Stopping podman container", "container", h.containerID)
// TODO: we should respect the "signal" parameter here
if _, err := iopodman.StopContainer().Call(varlinkConnection, h.containerID, int64(timeout)); err != nil {
h.driver.logger.Warn("Could not stop container gracefully, killing it now", "containerID", h.containerID, "err", err)
if _, err := iopodman.KillContainer().Call(varlinkConnection, h.containerID, 9); err != nil {
h.driver.logger.Error("Could not kill container", "containerID", h.containerID, "err", err)
return fmt.Errorf("Could not kill container: %v", err)
}
}
return nil
}
// waitTillStopped blocks and returns true when container stops;
// returns false with an error message if the container processes cannot be identified.
//
func waitTillStopped(pid int) (bool, error) {
ps, err := os.FindProcess(pid)
if err != nil {
return false, err
}
for {
if err := ps.Signal(syscall.Signal(0)); err != nil {
return true, nil
}
time.Sleep(containerMonitorIntv)
}
}