-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathdriver.go
More file actions
511 lines (428 loc) · 14.6 KB
/
driver.go
File metadata and controls
511 lines (428 loc) · 14.6 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
package main
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/client/stats"
"github.com/hashicorp/nomad/drivers/shared/eventer"
"github.com/hashicorp/nomad/plugins/base"
"github.com/hashicorp/nomad/plugins/drivers"
"github.com/hashicorp/nomad/plugins/shared/hclspec"
pstructs "github.com/hashicorp/nomad/plugins/shared/structs"
"github.com/pascomnet/nomad-driver-podman/iopodman"
shelpers "github.com/hashicorp/nomad/helper/stats"
"github.com/varlink/go/varlink"
)
const (
// pluginName is the name of the plugin
pluginName = "podman"
// fingerprintPeriod is the interval at which the driver will send fingerprint responses
fingerprintPeriod = 30 * time.Second
// taskHandleVersion is the version of task handle which this driver sets
// and understands how to decode driver state
taskHandleVersion = 1
)
var (
// pluginInfo is the response returned for the PluginInfo RPC
pluginInfo = &base.PluginInfoResponse{
Type: base.PluginTypeDriver,
PluginApiVersions: []string{drivers.ApiVersion010},
PluginVersion: "0.0.1-dev",
Name: pluginName,
}
// configSpec is the hcl specification returned by the ConfigSchema RPC
configSpec = hclspec.NewObject(map[string]*hclspec.Spec{
"enabled": hclspec.NewDefault(
hclspec.NewAttr("enabled", "bool", false),
hclspec.NewLiteral("true"),
),
})
// taskConfigSpec is the hcl specification for the driver config section of
// a task within a job. It is returned in the TaskConfigSchema RPC
taskConfigSpec = hclspec.NewObject(map[string]*hclspec.Spec{
"image": hclspec.NewAttr("image", "string", true),
})
// capabilities is returned by the Capabilities RPC and indicates what
// optional features this driver supports
capabilities = &drivers.Capabilities{
SendSignals: false,
Exec: false,
FSIsolation: drivers.FSIsolationNone,
}
)
// Driver is a driver for running podman containers
type Driver struct {
// eventer is used to handle multiplexing of TaskEvents calls such that an
// event can be broadcast to all callers
eventer *eventer.Eventer
// config is the driver configuration set by the SetConfig RPC
config *Config
// nomadConfig is the client config from nomad
nomadConfig *base.ClientDriverConfig
// tasks is the in memory datastore mapping taskIDs to rawExecDriverHandles
tasks *taskStore
// ctx is the context for the driver. It is passed to other subsystems to
// coordinate shutdown
ctx context.Context
// signalShutdown is called when the driver is shutting down and cancels the
// ctx passed to any subsystems
signalShutdown context.CancelFunc
// logger will log to the Nomad agent
logger hclog.Logger
}
// Config is the driver configuration set by the SetConfig RPC call
type Config struct {
Enabled bool `codec:"enabled"`
}
// TaskConfig is the driver configuration of a task within a job
type TaskConfig struct {
Image string `codec:"image"`
}
// TaskState is the state which is encoded in the handle returned in
// StartTask. This information is needed to rebuild the task state and handler
// during recovery.
type TaskState struct {
TaskConfig *drivers.TaskConfig
ContainerID string
StartedAt time.Time
Net *drivers.DriverNetwork
}
// NewPodmanDriver returns a new DriverPlugin implementation
func NewPodmanDriver(logger hclog.Logger) drivers.DriverPlugin {
ctx, cancel := context.WithCancel(context.Background())
logger = logger.Named(pluginName)
return &Driver{
eventer: eventer.NewEventer(ctx, logger),
config: &Config{},
tasks: newTaskStore(),
ctx: ctx,
signalShutdown: cancel,
logger: logger,
}
}
func (d *Driver) PluginInfo() (*base.PluginInfoResponse, error) {
return pluginInfo, nil
}
func (d *Driver) ConfigSchema() (*hclspec.Spec, error) {
return configSpec, nil
}
func (d *Driver) SetConfig(cfg *base.Config) error {
var config Config
if len(cfg.PluginConfig) != 0 {
if err := base.MsgPackDecode(cfg.PluginConfig, &config); err != nil {
return err
}
}
d.config = &config
if cfg.AgentConfig != nil {
d.nomadConfig = cfg.AgentConfig.Driver
}
return nil
}
func (d *Driver) Shutdown(ctx context.Context) error {
d.signalShutdown()
return nil
}
func (d *Driver) TaskConfigSchema() (*hclspec.Spec, error) {
return taskConfigSpec, nil
}
func (d *Driver) Capabilities() (*drivers.Capabilities, error) {
return capabilities, nil
}
func (d *Driver) Fingerprint(ctx context.Context) (<-chan *drivers.Fingerprint, error) {
err := shelpers.Init()
if err != nil {
d.logger.Error("Could not init stats helper", "err", err)
return nil, err
}
ch := make(chan *drivers.Fingerprint)
go d.handleFingerprint(ctx, ch)
return ch, nil
}
func (d *Driver) handleFingerprint(ctx context.Context, ch chan<- *drivers.Fingerprint) {
defer close(ch)
ticker := time.NewTimer(0)
for {
select {
case <-ctx.Done():
return
case <-d.ctx.Done():
return
case <-ticker.C:
ticker.Reset(fingerprintPeriod)
ch <- d.buildFingerprint()
}
}
}
func (d *Driver) buildFingerprint() *drivers.Fingerprint {
var health drivers.HealthState
var desc string
attrs := map[string]*pstructs.Attribute{}
// be negative and guess that we will not be able to get a podman connection
health = drivers.HealthStateUndetected
desc = "disabled"
// try to connect if the driver is enabled
if d.config.Enabled {
varlinkConnection, err := d.getConnection()
if err != nil {
d.logger.Error("Could not connect to podman", "err", err)
} else {
defer varlinkConnection.Close()
// see if we get the system info from podman
info, err := iopodman.GetInfo().Call(varlinkConnection)
if err == nil {
// yay! we can enable the driver
health = drivers.HealthStateHealthy
desc = "ready"
// TODO: we would have more data here... maybe we can return more details to nomad
attrs["driver.podman"] = pstructs.NewBoolAttribute(true)
attrs["driver.podman.version"] = pstructs.NewStringAttribute(info.Podman.Podman_version)
} else {
d.logger.Error("Cound not get podman info", "err", err)
}
}
}
return &drivers.Fingerprint{
Attributes: attrs,
Health: health,
HealthDescription: desc,
}
}
func (d *Driver) RecoverTask(handle *drivers.TaskHandle) error {
if handle == nil {
return fmt.Errorf("error: handle cannot be nil")
}
if _, ok := d.tasks.Get(handle.Config.ID); ok {
return nil
}
var taskState TaskState
if err := handle.GetDriverState(&taskState); err != nil {
return fmt.Errorf("failed to decode task state from handle: %v", err)
}
varlinkConnection, err := d.getConnection()
if err != nil {
return fmt.Errorf("failed to recover container ref: %v", err)
}
defer varlinkConnection.Close()
// FIXME: duplicated code. share more code with StartTask
filters := []string{"id=" + taskState.ContainerID}
psOpts := iopodman.PsOpts{
Filters: &filters,
}
psContainers, err := iopodman.Ps().Call(varlinkConnection, psOpts)
if err != nil {
return fmt.Errorf("failt to recover task, could not get container info: %v", err)
}
if len(psContainers) != 1 {
return fmt.Errorf("failt to recover task, problem with Ps()")
}
d.logger.Debug("Recovered podman container", "container", taskState.ContainerID, "pid", psContainers[0].PidNum)
h := &TaskHandle{
initPid: int(psContainers[0].PidNum),
containerID: taskState.ContainerID,
driver: d,
taskConfig: taskState.TaskConfig,
procState: drivers.TaskStateRunning,
startedAt: taskState.StartedAt,
exitResult: &drivers.ExitResult{},
logger: d.logger,
totalCpuStats: stats.NewCpuStats(),
userCpuStats: stats.NewCpuStats(),
systemCpuStats: stats.NewCpuStats(),
}
d.tasks.Set(taskState.TaskConfig.ID, h)
go h.run()
return nil
}
func (d *Driver) StartTask(cfg *drivers.TaskConfig) (*drivers.TaskHandle, *drivers.DriverNetwork, error) {
if _, ok := d.tasks.Get(cfg.ID); ok {
return nil, nil, fmt.Errorf("task with ID %q already started", cfg.ID)
}
var driverConfig TaskConfig
if err := cfg.DecodeDriverConfig(&driverConfig); err != nil {
return nil, nil, fmt.Errorf("failed to decode driver config: %v", err)
}
// d.logger.Info("starting podman task", "driver_cfg", hclog.Fmt("%+v", driverConfig))
handle := drivers.NewTaskHandle(taskHandleVersion)
handle.Config = cfg
varlinkConnection, err := d.getConnection()
if err != nil {
return nil, nil, fmt.Errorf("failt to start task, could not connect to podman: %v", err)
}
defer varlinkConnection.Close()
args := []string{driverConfig.Image}
containerName := fmt.Sprintf("%s-%s", cfg.Name, cfg.AllocID)
memoryLimit := fmt.Sprintf("%dm", cfg.Resources.NomadResources.Memory.MemoryMB)
cpuShares := cfg.Resources.LinuxResources.CPUShares
allocMounts := []string{
fmt.Sprintf("type=bind,source=%s,target=/nomad/alloc", cfg.TaskDir().SharedAllocDir),
fmt.Sprintf("type=bind,source=%s,target=/nomad/local", cfg.TaskDir().LocalDir),
fmt.Sprintf("type=bind,source=%s,target=/nomad/secrets", cfg.TaskDir().SecretsDir),
}
createOpts := iopodman.Create{
Args: args,
Name: &containerName,
Mount: &allocMounts,
Memory: &memoryLimit,
MemorySwap: &memoryLimit,
CpuShares: &cpuShares,
}
containerID, err := iopodman.CreateContainer().Call(varlinkConnection, createOpts)
if err != nil {
return nil, nil, fmt.Errorf("failt to start task, could not create container: %v", err)
}
d.logger.Info("Created container", "container", containerID)
cleanup := func() {
d.logger.Debug("Cleaning up", "container", containerID)
if _, err := iopodman.RemoveContainer().Call(varlinkConnection, containerID, true, true); err != nil {
d.logger.Error("failed to clean up from an error in Start", "error", err)
}
}
_, err = iopodman.StartContainer().Call(varlinkConnection, containerID)
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("failt to start task, could not start container: %v", err)
}
d.logger.Info("Started container", "containerId", containerID)
// FIXME: there is some podman race condition to end up in a deadlock here
//
d.logger.Info("inspecting container", "containerId", containerID)
inspectJSON, err := iopodman.InspectContainer().Call(varlinkConnection, containerID)
if err != nil {
d.logger.Error("failt to inspect container", "err", err)
cleanup()
return nil, nil, fmt.Errorf("failt to start task, could not inspect container : %v", err)
}
var inspectData iopodman.InspectContainerData
err = json.Unmarshal([]byte(inspectJSON), &inspectData)
if err != nil {
cleanup()
d.logger.Error("failt to unmarshal inspect container", "err", err)
return nil, nil, fmt.Errorf("failt to start task, could not unmarshal inspect container : %v", err)
}
d.logger.Debug("Started podman container", "container", containerID, "pid", inspectData.State.Pid, "ip", inspectData.NetworkSettings.IPAddress)
net := &drivers.DriverNetwork{
// // PortMap: driverConfig.PortMap,
IP: inspectData.NetworkSettings.IPAddress,
AutoAdvertise: true,
}
h := &TaskHandle{
initPid: inspectData.State.Pid,
containerID: containerID,
driver: d,
taskConfig: cfg,
procState: drivers.TaskStateRunning,
startedAt: time.Now().Round(time.Millisecond),
logger: d.logger,
totalCpuStats: stats.NewCpuStats(),
userCpuStats: stats.NewCpuStats(),
systemCpuStats: stats.NewCpuStats(),
}
driverState := TaskState{
ContainerID: containerID,
TaskConfig: cfg,
StartedAt: h.startedAt,
Net: net,
}
if err := handle.SetDriverState(&driverState); err != nil {
d.logger.Error("failed to start task, error setting driver state", "error", err)
cleanup()
return nil, nil, fmt.Errorf("failed to set driver state: %v", err)
}
d.tasks.Set(cfg.ID, h)
go h.run()
d.logger.Debug("Completely started", "containerID", containerID)
return handle, net, nil
}
func (d *Driver) WaitTask(ctx context.Context, taskID string) (<-chan *drivers.ExitResult, error) {
handle, ok := d.tasks.Get(taskID)
if !ok {
return nil, drivers.ErrTaskNotFound
}
ch := make(chan *drivers.ExitResult)
go d.handleWait(ctx, handle, ch)
return ch, nil
}
func (d *Driver) handleWait(ctx context.Context, handle *TaskHandle, ch chan *drivers.ExitResult) {
defer close(ch)
//
// Wait for process completion by polling status from handler.
// We cannot use the following alternatives:
// * Process.Wait() requires LXC container processes to be children
// of self process; but LXC runs container in separate PID hierarchy
// owned by PID 1.
// * lxc.Container.Wait() holds a write lock on container and prevents
// any other calls, including stats.
//
// Going with simplest approach of polling for handler to mark exit.
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-d.ctx.Done():
return
case <-ticker.C:
s := handle.TaskStatus()
if s.State == drivers.TaskStateExited {
ch <- handle.exitResult
}
}
}
}
func (d *Driver) StopTask(taskID string, timeout time.Duration, signal string) error {
handle, ok := d.tasks.Get(taskID)
if !ok {
return drivers.ErrTaskNotFound
}
err := handle.shutdown(timeout)
return err
}
func (d *Driver) DestroyTask(taskID string, force bool) error {
handle, ok := d.tasks.Get(taskID)
if !ok {
return drivers.ErrTaskNotFound
}
if handle.IsRunning() && !force {
return fmt.Errorf("cannot destroy running task")
}
if handle.IsRunning() {
d.logger.Info("Have to destroyTask but container is still running", "containerID", handle.containerID)
// we can not do anything, so catching the error is useless
handle.shutdown(1 * time.Minute)
}
d.tasks.Delete(taskID)
return nil
}
func (d *Driver) InspectTask(taskID string) (*drivers.TaskStatus, error) {
handle, ok := d.tasks.Get(taskID)
if !ok {
return nil, drivers.ErrTaskNotFound
}
return handle.TaskStatus(), nil
}
func (d *Driver) TaskStats(ctx context.Context, taskID string, interval time.Duration) (<-chan *drivers.TaskResourceUsage, error) {
d.logger.Error("TaskStats called")
handle, ok := d.tasks.Get(taskID)
if !ok {
return nil, drivers.ErrTaskNotFound
}
return handle.stats(ctx, interval)
}
func (d *Driver) TaskEvents(ctx context.Context) (<-chan *drivers.TaskEvent, error) {
return d.eventer.TaskEvents(ctx)
}
func (d *Driver) SignalTask(taskID string, signal string) error {
return fmt.Errorf("Pdoman driver does not support signals")
}
func (d *Driver) ExecTask(taskID string, cmd []string, timeout time.Duration) (*drivers.ExecTaskResult, error) {
return nil, fmt.Errorf("Pdoman driver does not support exec")
}
func (d *Driver) getConnection() (*varlink.Connection, error) {
// FIXME: a parameter for the socket would be nice
varlinkConnection, err := varlink.NewConnection("unix://run/podman/io.podman")
return varlinkConnection, err
}