-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathdriver.go
1707 lines (1522 loc) · 60.1 KB
/
driver.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
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package main
import (
"context"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"time"
"github.com/armon/circbuf"
"github.com/containers/image/v5/docker"
dockerArchive "github.com/containers/image/v5/docker/archive"
ociArchive "github.com/containers/image/v5/oci/archive"
"github.com/containers/image/v5/pkg/shortnames"
"github.com/containers/image/v5/types"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad-driver-podman/api"
"github.com/hashicorp/nomad-driver-podman/registry"
"github.com/hashicorp/nomad-driver-podman/version"
"github.com/hashicorp/nomad/client/lib/cpustats"
"github.com/hashicorp/nomad/client/taskenv"
"github.com/hashicorp/nomad/drivers/shared/eventer"
nstructs "github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/nomad/plugins/base"
"github.com/hashicorp/nomad/plugins/drivers"
"github.com/hashicorp/nomad/plugins/drivers/fsisolation"
"github.com/hashicorp/nomad/plugins/shared/hclspec"
pstructs "github.com/hashicorp/nomad/plugins/shared/structs"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/ryanuber/go-glob"
"golang.org/x/sync/singleflight"
)
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
LOG_DRIVER_NOMAD = "nomad"
LOG_DRIVER_JOURNALD = "journald"
labelAllocID = "com.hashicorp.nomad.alloc_id"
labelJobName = "com.hashicorp.nomad.job_name"
labelJobID = "com.hashicorp.nomad.job_id"
labelTaskGroupName = "com.hashicorp.nomad.task_group_name"
labelTaskName = "com.hashicorp.nomad.task_name"
labelNamespace = "com.hashicorp.nomad.namespace"
labelNodeName = "com.hashicorp.nomad.node_name"
labelNodeID = "com.hashicorp.nomad.node_id"
)
var (
// pluginInfo is the response returned for the PluginInfo RPC
pluginInfo = &base.PluginInfoResponse{
Type: base.PluginTypeDriver,
PluginApiVersions: []string{drivers.ApiVersion010},
PluginVersion: version.Version,
Name: pluginName,
}
// capabilities is returned by the Capabilities RPC and indicates what
// optional features this driver supports
capabilities = &drivers.Capabilities{
SendSignals: true,
Exec: true,
FSIsolation: fsisolation.Image,
NetIsolationModes: []drivers.NetIsolationMode{
drivers.NetIsolationModeGroup,
drivers.NetIsolationModeHost,
drivers.NetIsolationModeTask,
},
MustInitiateNetwork: false,
}
)
// 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 *PluginConfig
// nomadConfig is the client config from nomad
nomadConfig *base.ClientDriverConfig
// compute contains information about the available cpu compute
compute cpustats.Compute
// 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
// Podman clients
podmanClients map[string]*api.API
// For any call where it's unspecified/unknown which podman should be used
defaultPodman *api.API
// singleflight group to prevent parallel image downloads
pullGroup singleflight.Group
}
// 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
LogStreamer bool
}
// NewPodmanDriver returns a new DriverPlugin implementation
func NewPodmanDriver(logger hclog.Logger) drivers.DriverPlugin {
ctx, cancel := context.WithCancel(context.Background())
return &Driver{
eventer: eventer.NewEventer(ctx, logger),
config: &PluginConfig{},
tasks: newTaskStore(),
ctx: ctx,
signalShutdown: cancel,
logger: logger.Named(pluginName),
}
}
// PluginInfo returns metadata about the podman driver plugin
func (d *Driver) PluginInfo() (*base.PluginInfoResponse, error) {
return pluginInfo, nil
}
// ConfigSchema function allows a plugin to tell Nomad the schema for its configuration.
// This configuration is given in a plugin block of the client configuration.
// The schema is defined with the hclspec package.
func (d *Driver) ConfigSchema() (*hclspec.Spec, error) {
return configSpec, nil
}
// SetConfig function is called when starting the plugin for the first time.
// The Config given has two different configuration fields. The first PluginConfig,
// is an encoded configuration from the plugin block of the client config.
// The second, AgentConfig, is the Nomad agent's configuration which is given to all plugins.
func (d *Driver) SetConfig(cfg *base.Config) error {
var pluginConfig PluginConfig
if len(cfg.PluginConfig) != 0 {
if err := base.MsgPackDecode(cfg.PluginConfig, &pluginConfig); err != nil {
return err
}
}
d.config = &pluginConfig
if cfg.AgentConfig != nil {
d.nomadConfig = cfg.AgentConfig.Driver
}
var timeout time.Duration
if pluginConfig.ClientHttpTimeout != "" {
t, err := time.ParseDuration(pluginConfig.ClientHttpTimeout)
if err != nil {
return err
}
timeout = t
}
switch {
case len(d.config.Socket) > 0 && d.config.SocketPath != "":
return fmt.Errorf("error: can't define socket blocks and socket_path, they're mutually exclusive.")
case len(d.config.Socket) > 0:
d.podmanClients = d.makePodmanClients(d.config.Socket, timeout)
case d.config.SocketPath != "":
d.podmanClients = make(map[string]*api.API)
d.podmanClients["default"] = d.newPodmanClient(timeout, d.config.SocketPath, true)
d.defaultPodman = d.podmanClients["default"]
default:
d.podmanClients = make(map[string]*api.API)
uid := os.Getuid()
if uid == 0 {
d.podmanClients["default"] = d.newPodmanClient(timeout, "unix:///run/podman/podman.sock", true)
} else {
d.podmanClients["default"] = d.newPodmanClient(timeout, fmt.Sprintf("unix:///run/user/%d/podman/podman.sock", uid), true)
}
d.defaultPodman = d.podmanClients["default"]
}
d.compute = cfg.AgentConfig.Compute()
return nil
}
func (d *Driver) makePodmanClients(sockets []PluginSocketConfig, timeout time.Duration) map[string]*api.API {
podmanClients := make(map[string]*api.API)
var firstEntry *api.API
foundDefaultPodman := false
for i, sock := range sockets {
var podmanClient *api.API
if sock.Name == "" {
sock.Name = "default"
}
if sock.Name == "default" && !foundDefaultPodman {
foundDefaultPodman = true
podmanClient = d.newPodmanClient(timeout, sock.SocketPath, true)
d.defaultPodman = podmanClient
} else {
podmanClient = d.newPodmanClient(timeout, sock.SocketPath, false)
}
// Case when there are two socket blocks with the same name or
// if there's one with name="default" and one without name.
if _, ok := podmanClients[sock.Name]; ok {
d.logger.Error(fmt.Sprintf("There is already a socket with the name: %s ", sock.Name))
} else {
podmanClients[sock.Name] = podmanClient
}
if i == 0 {
firstEntry = podmanClient
}
}
// If no socket was default, the first entry becomes the default
if !foundDefaultPodman {
firstEntry.SetClientAsDefault(true)
d.defaultPodman = firstEntry
}
return podmanClients
}
// We need to make a "clean" name that can be used safely in logging, journald, attributes in the UI, ...
func cleanUpSocketName(name string) string {
var result strings.Builder
for i := 0; i < len(name); i++ {
b := name[i]
if !(('a' <= b && b <= 'z') || ('A' <= b && b <= 'Z') || ('0' <= b && b <= '9')) {
result.WriteByte('_')
} else {
result.WriteByte(b)
}
}
return result.String()
}
func (d *Driver) getPodmanClient(clientName string) (*api.API, error) {
p, ok := d.podmanClients[clientName]
if ok {
return p, nil
}
return nil, fmt.Errorf("podman client with name %q was not found, check your podman driver config", clientName)
}
// newPodmanClient returns Podman client configured with the provided timeout.
// This method must be called after the driver configuration has been loaded.
func (d *Driver) newPodmanClient(timeout time.Duration, socketPath string, defaultPodman bool) *api.API {
clientConfig := api.DefaultClientConfig()
clientConfig.HttpTimeout = timeout
clientConfig.SocketPath = socketPath
clientConfig.DefaultPodman = defaultPodman
return api.NewClient(d.logger, clientConfig)
}
// TaskConfigSchema returns the schema for the driver configuration of the task.
func (d *Driver) TaskConfigSchema() (*hclspec.Spec, error) {
return taskConfigSpec, nil
}
// Capabilities define what features the driver implements.
func (d *Driver) Capabilities() (*drivers.Capabilities, error) {
return capabilities, nil
}
// Fingerprint is called by the client when the plugin is started.
// It allows the driver to indicate its health to the client.
// The channel returned should immediately send an initial Fingerprint,
// then send periodic updates at an interval that is appropriate for the driver
// until the context is canceled.
func (d *Driver) Fingerprint(ctx context.Context) (<-chan *drivers.Fingerprint, error) {
// emit warnings about known bad configs
d.config.LogWarnings(d.logger)
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 {
attrs := map[string]*pstructs.Attribute{}
allClientsAreHealthy := true
unhealthyClients := []string{}
allClientsAreUnhealthy := true
for name, podmanClient := range d.podmanClients {
// Ping podman api
apiVersion, err := podmanClient.Ping(d.ctx)
attrPrefix := fmt.Sprintf("driver.podman.%s", cleanUpSocketName(name))
if podmanClient.IsDefaultClient() {
attrPrefix = "driver.podman"
}
if err != nil || apiVersion == "" {
d.logger.Error("Could not get podman version", "error", err)
attrs[fmt.Sprintf("%s.health", attrPrefix)] = pstructs.NewStringAttribute("unhealthy")
allClientsAreHealthy = false
unhealthyClients = append(unhealthyClients, name)
continue
}
info, err := podmanClient.SystemInfo(d.ctx)
if err != nil {
d.logger.Error("Could not get podman info", "error", err)
attrs[fmt.Sprintf("%s.health", attrPrefix)] = pstructs.NewStringAttribute("unhealthy")
allClientsAreHealthy = false
unhealthyClients = append(unhealthyClients, name)
continue
}
allClientsAreUnhealthy = false
podmanClient.SetAPIVersion(apiVersion)
podmanClient.SetRootless(info.Host.Security.Rootless)
podmanClient.SetCgroupV2(info.Host.CGroupsVersion == "v2")
podmanClient.SetCgroupMgr(info.Host.CgroupManager)
podmanClient.SetAppArmor(info.Host.Security.AppArmorEnabled)
attrs[fmt.Sprintf("%s.appArmor", attrPrefix)] = pstructs.NewBoolAttribute(info.Host.Security.AppArmorEnabled)
attrs[fmt.Sprintf("%s.capabilities", attrPrefix)] = pstructs.NewStringAttribute(info.Host.Security.DefaultCapabilities)
attrs[fmt.Sprintf("%s.cgroupVersion", attrPrefix)] = pstructs.NewStringAttribute(info.Host.CGroupsVersion)
attrs[fmt.Sprintf("%s.defaultPodman", attrPrefix)] = pstructs.NewBoolAttribute(podmanClient.IsDefaultClient())
attrs[fmt.Sprintf("%s.health", attrPrefix)] = pstructs.NewStringAttribute("healthy")
attrs[fmt.Sprintf("%s.socketName", attrPrefix)] = pstructs.NewStringAttribute(name)
attrs[fmt.Sprintf("%s.ociRuntime", attrPrefix)] = pstructs.NewStringAttribute(info.Host.OCIRuntime.Path)
attrs[fmt.Sprintf("%s.rootless", attrPrefix)] = pstructs.NewBoolAttribute(info.Host.Security.Rootless)
attrs[fmt.Sprintf("%s.seccompEnabled", attrPrefix)] = pstructs.NewBoolAttribute(info.Host.Security.SECCOMPEnabled)
attrs[fmt.Sprintf("%s.selinuxEnabled", attrPrefix)] = pstructs.NewBoolAttribute(info.Host.Security.SELinuxEnabled)
attrs[fmt.Sprintf("%s.socket", attrPrefix)] = pstructs.NewStringAttribute(info.Host.RemoteSocket.Path)
attrs[fmt.Sprintf("%s.version", attrPrefix)] = pstructs.NewStringAttribute(apiVersion)
}
switch {
case allClientsAreHealthy:
attrs["driver.podman"] = pstructs.NewBoolAttribute(true)
return &drivers.Fingerprint{
Attributes: attrs,
Health: drivers.HealthStateHealthy,
HealthDescription: "All Podman sockets are responding.",
}
case allClientsAreUnhealthy:
attrs["driver.podman"] = pstructs.NewBoolAttribute(false)
return &drivers.Fingerprint{
Attributes: attrs,
Health: drivers.HealthStateUndetected,
HealthDescription: "Cannot connect to any Podman socket.",
}
default:
attrs["driver.podman"] = pstructs.NewBoolAttribute(true)
slices.Sort(unhealthyClients) // If not sorted, we generate a new fingerprint log entry every time the order changes
return &drivers.Fingerprint{
Attributes: attrs,
Health: drivers.HealthStateUnhealthy,
HealthDescription: fmt.Sprintf("Cannot fingerprint certain podman sockets: %s", strings.Join(unhealthyClients, ", ")),
}
}
}
// RecoverTask detects running tasks when nomad client or task driver is restarted.
// When a driver is restarted it is not expected to persist any internal state to disk.
// To support this, Nomad will attempt to recover a task that was previously started
// if the driver does not recognize the task ID. During task recovery,
// Nomad calls RecoverTask passing the TaskHandle that was returned by the StartTask function.
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: %w", err)
}
d.logger.Debug("Checking for recoverable task", "task", handle.Config.Name, "taskid", handle.Config.ID, "container", taskState.ContainerID)
var inspectData api.InspectContainerData
// We need to parse the task config for our driver to be able to find the Socket field (*drivers.TaskConfig itself is a generic task struct from the nomad repo)
var podmanTaskConfig TaskConfig
if err := taskState.TaskConfig.DecodeDriverConfig(&podmanTaskConfig); err != nil {
return fmt.Errorf("error: cannot decode task config")
}
podmanTaskSocketName := podmanTaskConfig.Socket
if podmanTaskConfig.Socket == "" {
podmanTaskSocketName = "default"
}
taskPodmanClient, err := d.getPodmanClient(podmanTaskSocketName)
if err == nil {
inspectData, err = taskPodmanClient.ContainerInspect(d.ctx, taskState.ContainerID)
if errors.Is(err, api.ContainerNotFound) {
d.logger.Debug("Recovery lookup found no container", "task", handle.Config.ID, "container", taskState.ContainerID, "error", err)
return err
} else if err != nil {
d.logger.Warn("Recovery lookup failed", "task", handle.Config.ID, "container", taskState.ContainerID, "error", err)
return err
}
} else {
d.logger.Warn("Did not find podman client for this task", "task", handle.Config.ID, "container", taskState.ContainerID, "podmanClient", podmanTaskSocketName, "error", err)
return fmt.Errorf("error: cannot find the podman socket for this task. Socket might have been removed from driver config but still referenced in Task. podmanClient=%s", podmanTaskSocketName)
}
h := &TaskHandle{
containerID: taskState.ContainerID,
driver: d,
podmanClient: taskPodmanClient,
taskConfig: taskState.TaskConfig,
procState: drivers.TaskStateUnknown,
startedAt: taskState.StartedAt,
exitResult: &drivers.ExitResult{},
logger: d.logger.Named(fmt.Sprintf("podman.%s", podmanTaskSocketName)),
logPointer: time.Now(), // do not rewind log to the startetAt date.
logStreamer: taskState.LogStreamer,
collectionInterval: time.Second,
totalCPUStats: cpustats.New(d.compute),
userCPUStats: cpustats.New(d.compute),
systemCPUStats: cpustats.New(d.compute),
removeContainerOnExit: d.config.GC.Container,
}
switch {
case inspectData.State.Running:
d.logger.Info("Recovered a still running container", "container", inspectData.State.Pid)
h.procState = drivers.TaskStateRunning
case inspectData.State.Status == "exited":
// Are we allowed to restart a stopped container?
if d.config.RecoverStopped {
d.logger.Debug("Found a stopped container, try to start it", "container", inspectData.State.Pid, "podman client", podmanTaskSocketName)
if err = taskPodmanClient.ContainerStart(d.ctx, inspectData.ID); err != nil {
d.logger.Warn("Recovery restart failed", "task", handle.Config.ID, "container", taskState.ContainerID, "podman client", podmanTaskSocketName, "error", err)
} else {
d.logger.Info("Restarted a container during recovery", "container", inspectData.ID, "podman client", podmanTaskSocketName)
h.procState = drivers.TaskStateRunning
}
} else {
// No, let's cleanup here to prepare for a StartTask()
d.logger.Debug("Found a stopped container, removing it", "container", inspectData.ID, "podman client", podmanTaskSocketName)
if err = taskPodmanClient.ContainerDelete(d.ctx, inspectData.ID, true, true); err != nil {
d.logger.Warn("Recovery cleanup failed", "task", handle.Config.ID, "container", inspectData.ID, "podman client", podmanTaskSocketName)
}
h.procState = drivers.TaskStateExited
}
default:
d.logger.Warn("Recovery restart failed, unknown container state", "state", inspectData.State.Status, "container", taskState.ContainerID, "podman client", podmanTaskSocketName)
h.procState = drivers.TaskStateUnknown
}
d.tasks.Set(handle.Config.ID, h)
go h.runContainerMonitor()
d.logger.Debug("Recovered container handle", "container", taskState.ContainerID, "podman client", podmanTaskSocketName)
return nil
}
// BuildContainerName returns the podman container name for a given TaskConfig
func BuildContainerName(cfg *drivers.TaskConfig) string {
return BuildContainerNameForTask(cfg.Name, cfg)
}
// BuildContainerNameForTask returns the podman container name for a specific Task in our group
func BuildContainerNameForTask(taskName string, cfg *drivers.TaskConfig) string {
return fmt.Sprintf("%s-%s", taskName, cfg.AllocID)
}
// StartTask creates and starts a new Container based on the given TaskConfig.
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 podmanTaskConfig TaskConfig
if err := cfg.DecodeDriverConfig(&podmanTaskConfig); err != nil {
return nil, nil, fmt.Errorf("failed to decode driver config: %w", err)
}
handle := drivers.NewTaskHandle(taskHandleVersion)
handle.Config = cfg
if podmanTaskConfig.Image == "" {
return nil, nil, fmt.Errorf("image name required")
}
var podmanClient *api.API
podmanTaskSocketName := podmanTaskConfig.Socket
if podmanTaskConfig.Socket == "" {
podmanTaskSocketName = "default"
podmanClient = d.defaultPodman
} else {
var err error
podmanClient, err = d.getPodmanClient(podmanTaskSocketName)
if err != nil {
return nil, nil, fmt.Errorf("podman client with name %q not found, check your podman driver config", podmanTaskSocketName)
}
}
rootless := podmanClient.IsRootless()
createOpts := api.SpecGenerator{}
createOpts.ContainerBasicConfig.LogConfiguration = &api.LogConfig{}
var allArgs []string
if podmanTaskConfig.Command != "" {
allArgs = append(allArgs, podmanTaskConfig.Command)
}
allArgs = append(allArgs, podmanTaskConfig.Args...)
// Parse entrypoint.
switch v := podmanTaskConfig.Entrypoint.(type) {
case string:
// Check for a string type to maintain backwards compatibility.
d.logger.Warn("Defining the entrypoint as a string has been deprecated, use a list of strings instead.")
createOpts.ContainerBasicConfig.Entrypoint = append(createOpts.ContainerBasicConfig.Entrypoint, v)
case []interface{}:
entrypoint := make([]string, len(v))
for i, e := range v {
entrypoint[i] = fmt.Sprintf("%v", e)
}
createOpts.ContainerBasicConfig.Entrypoint = entrypoint
case nil:
default:
return nil, nil, fmt.Errorf("invalid entrypoint type %T", podmanTaskConfig.Entrypoint)
}
containerName := BuildContainerName(cfg)
// ensure to include port_map into tasks environment map
cfg.Env = taskenv.SetPortMapEnvs(cfg.Env, podmanTaskConfig.PortMap)
if len(podmanTaskConfig.Labels) > 0 {
createOpts.ContainerBasicConfig.Labels = podmanTaskConfig.Labels
}
labels := make(map[string]string, len(podmanTaskConfig.Labels)+1)
for k, v := range podmanTaskConfig.Labels {
labels[k] = v
}
if len(d.config.ExtraLabels) > 0 {
// main mandatory label
labels[labelAllocID] = cfg.AllocID
}
// optional labels, as configured in plugin configuration
for _, configurationExtraLabel := range d.config.ExtraLabels {
if glob.Glob(configurationExtraLabel, "job_name") {
labels[labelJobName] = cfg.JobName
}
if glob.Glob(configurationExtraLabel, "job_id") {
labels[labelJobID] = cfg.JobID
}
if glob.Glob(configurationExtraLabel, "task_group_name") {
labels[labelTaskGroupName] = cfg.TaskGroupName
}
if glob.Glob(configurationExtraLabel, "task_name") {
labels[labelTaskName] = cfg.Name
}
if glob.Glob(configurationExtraLabel, "namespace") {
labels[labelNamespace] = cfg.Namespace
}
if glob.Glob(configurationExtraLabel, "node_name") {
labels[labelNodeName] = cfg.NodeName
}
if glob.Glob(configurationExtraLabel, "node_id") {
labels[labelNodeID] = cfg.NodeID
}
}
podmanTaskConfig.Labels = labels
d.logger.Debug("applied labels on the container", "labels", podmanTaskConfig.Labels)
// Basic config options
createOpts.ContainerBasicConfig.Name = containerName
createOpts.ContainerBasicConfig.Command = allArgs
createOpts.ContainerBasicConfig.Env = cfg.Env
createOpts.ContainerBasicConfig.Hostname = podmanTaskConfig.Hostname
createOpts.ContainerBasicConfig.Sysctl = podmanTaskConfig.Sysctl
createOpts.ContainerBasicConfig.Terminal = podmanTaskConfig.Tty
createOpts.ContainerBasicConfig.Labels = podmanTaskConfig.Labels
// Logging
if !podmanTaskConfig.Logging.Empty() {
switch podmanTaskConfig.Logging.Driver {
case "", LOG_DRIVER_NOMAD:
if !d.config.DisableLogCollection {
createOpts.LogConfiguration.Driver = "k8s-file"
createOpts.ContainerBasicConfig.LogConfiguration.Path = cfg.StdoutPath
}
case LOG_DRIVER_JOURNALD:
createOpts.LogConfiguration.Driver = "journald"
default:
return nil, nil, fmt.Errorf("Invalid task logging.driver option")
}
createOpts.ContainerBasicConfig.LogConfiguration.Options = podmanTaskConfig.Logging.Options
} else {
d.logger.Trace("no podman log driver provided, defaulting to plugin config")
switch d.config.Logging.Driver {
case "", LOG_DRIVER_NOMAD:
if !d.config.DisableLogCollection {
createOpts.LogConfiguration.Driver = "k8s-file"
createOpts.ContainerBasicConfig.LogConfiguration.Path = cfg.StdoutPath
}
case LOG_DRIVER_JOURNALD:
createOpts.LogConfiguration.Driver = "journald"
default:
return nil, nil, fmt.Errorf("Invalid plugin logging.driver option")
}
createOpts.ContainerBasicConfig.LogConfiguration.Options = d.config.Logging.Options
}
// Storage config options
createOpts.ContainerStorageConfig.Init = podmanTaskConfig.Init
createOpts.ContainerStorageConfig.Image = podmanTaskConfig.Image
createOpts.ContainerStorageConfig.InitPath = podmanTaskConfig.InitPath
createOpts.ContainerStorageConfig.WorkDir = podmanTaskConfig.WorkingDir
allMounts, err := d.containerMounts(cfg, &podmanTaskConfig)
if err != nil {
return nil, nil, err
}
createOpts.ContainerStorageConfig.Mounts = allMounts
createOpts.ContainerStorageConfig.Devices = make([]spec.LinuxDevice, len(podmanTaskConfig.Devices))
for idx, device := range podmanTaskConfig.Devices {
createOpts.ContainerStorageConfig.Devices[idx] = spec.LinuxDevice{Path: device}
}
// Set the nomad slice as cgroup parent
if podmanClient.IsCgroupV2() && podmanClient.GetCgroupMgr() == "systemd" {
createOpts.ContainerCgroupConfig.CgroupParent = "nomad.slice"
}
// Resources config options
createOpts.ContainerResourceConfig.ResourceLimits = &spec.LinuxResources{
Memory: &spec.LinuxMemory{},
CPU: &spec.LinuxCPU{},
}
err = setCPUResources(podmanTaskConfig, cfg.Resources.LinuxResources, createOpts.ContainerResourceConfig.ResourceLimits.CPU)
if err != nil {
return nil, nil, err
}
hard, soft, err := memoryLimits(cfg.Resources.NomadResources.Memory, podmanTaskConfig.MemoryReservation)
if err != nil {
return nil, nil, err
}
createOpts.ContainerResourceConfig.ResourceLimits.Memory.Reservation = soft
createOpts.ContainerResourceConfig.ResourceLimits.Memory.Limit = hard
// set PidsLimit only if configured.
if podmanTaskConfig.PidsLimit > 0 {
createOpts.ContainerResourceConfig.ResourceLimits.Pids = &spec.LinuxPids{
Limit: podmanTaskConfig.PidsLimit,
}
}
if podmanTaskConfig.MemorySwap != "" {
swap, memErr := memoryInBytes(podmanTaskConfig.MemorySwap)
if memErr != nil {
return nil, nil, memErr
}
createOpts.ContainerResourceConfig.ResourceLimits.Memory.Swap = &swap
}
if !podmanClient.IsCgroupV2() {
swappiness := uint64(podmanTaskConfig.MemorySwappiness)
createOpts.ContainerResourceConfig.ResourceLimits.Memory.Swappiness = &swappiness
}
// FIXME: can fail for nonRoot due to missing cpu limit delegation permissions,
// see https://github.com/containers/podman/blob/master/troubleshooting.md
if !rootless {
cpuShares := uint64(cfg.Resources.LinuxResources.CPUShares)
createOpts.ContainerResourceConfig.ResourceLimits.CPU.Shares = &cpuShares
}
ulimits, ulimitErr := sliceMergeUlimit(podmanTaskConfig.Ulimit)
if ulimitErr != nil {
return nil, nil, fmt.Errorf("failed to parse ulimit configuration: %w", ulimitErr)
}
createOpts.ContainerResourceConfig.Rlimits = ulimits
// Security config options
createOpts.ContainerSecurityConfig.CapAdd = podmanTaskConfig.CapAdd
createOpts.ContainerSecurityConfig.CapDrop = podmanTaskConfig.CapDrop
createOpts.ContainerSecurityConfig.SelinuxOpts = podmanTaskConfig.SelinuxOpts
createOpts.ContainerSecurityConfig.User = cfg.User
createOpts.ContainerSecurityConfig.Privileged = podmanTaskConfig.Privileged
createOpts.ContainerSecurityConfig.ReadOnlyFilesystem = podmanTaskConfig.ReadOnlyRootfs
createOpts.ContainerSecurityConfig.ApparmorProfile = podmanTaskConfig.ApparmorProfile
// add security_opt if configured
if securiyOptsErr := parseSecurityOpt(podmanTaskConfig.SecurityOpt, &createOpts); securiyOptsErr != nil {
return nil, nil, fmt.Errorf("failed to parse security_opt configuration: %w", securiyOptsErr)
}
// Populate --userns mode only if configured
if podmanTaskConfig.UserNS != "" {
userns := strings.SplitN(podmanTaskConfig.UserNS, ":", 2)
mode := api.NamespaceMode(userns[0])
// Populate value only if specified
if len(userns) > 1 {
createOpts.ContainerSecurityConfig.UserNS = api.Namespace{NSMode: mode, Value: userns[1]}
} else {
createOpts.ContainerSecurityConfig.UserNS = api.Namespace{NSMode: mode}
}
}
// populate shm_size if configured
if podmanTaskConfig.ShmSize != "" {
shmsize, memErr := memoryInBytes(podmanTaskConfig.ShmSize)
if memErr != nil {
return nil, nil, memErr
}
createOpts.ContainerStorageConfig.ShmSize = &shmsize
}
// Network config options
if cfg.DNS != nil {
for _, strdns := range cfg.DNS.Servers {
ipdns := net.ParseIP(strdns)
if ipdns == nil {
return nil, nil, fmt.Errorf("Invalid dns server address, dns=%v", strdns)
}
createOpts.ContainerNetworkConfig.DNSServers = append(createOpts.ContainerNetworkConfig.DNSServers, ipdns)
}
createOpts.ContainerNetworkConfig.DNSSearch = append(createOpts.ContainerNetworkConfig.DNSSearch, cfg.DNS.Searches...)
createOpts.ContainerNetworkConfig.DNSOptions = append(createOpts.ContainerNetworkConfig.DNSOptions, cfg.DNS.Options...)
} else if len(d.config.DNSServers) > 0 {
// no task DNS specific, try load default DNS from plugin config
for _, strdns := range d.config.DNSServers {
ipdns := net.ParseIP(strdns)
if ipdns == nil {
return nil, nil, fmt.Errorf("Invalid dns server address from plugin config, dns=%v", strdns)
}
createOpts.ContainerNetworkConfig.DNSServers = append(createOpts.ContainerNetworkConfig.DNSServers, ipdns)
}
}
// Configure network
if cfg.NetworkIsolation != nil && cfg.NetworkIsolation.Path != "" {
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Path
createOpts.ContainerNetworkConfig.NetNS.Value = cfg.NetworkIsolation.Path
} else {
switch {
case podmanTaskConfig.NetworkMode == "":
if !rootless {
// should we join the group shared network namespace?
if cfg.NetworkIsolation != nil && cfg.NetworkIsolation.Mode == drivers.NetIsolationModeGroup {
// yes, join the group ns namespace
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Path
createOpts.ContainerNetworkConfig.NetNS.Value = cfg.NetworkIsolation.Path
} else {
// no, simply attach a rootful container to the default podman bridge
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Bridge
}
} else {
// slirp4netns is default for rootless podman
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Slirp
}
case podmanTaskConfig.NetworkMode == "bridge":
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Bridge
case podmanTaskConfig.NetworkMode == "host":
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Host
case podmanTaskConfig.NetworkMode == "none":
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.NoNetwork
case podmanTaskConfig.NetworkMode == "slirp4netns":
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Slirp
case strings.HasPrefix(podmanTaskConfig.NetworkMode, "container:"):
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.FromContainer
createOpts.ContainerNetworkConfig.NetNS.Value = strings.TrimPrefix(podmanTaskConfig.NetworkMode, "container:")
case strings.HasPrefix(podmanTaskConfig.NetworkMode, "ns:"):
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Path
createOpts.ContainerNetworkConfig.NetNS.Value = strings.TrimPrefix(podmanTaskConfig.NetworkMode, "ns:")
case strings.HasPrefix(podmanTaskConfig.NetworkMode, "task:"):
otherTaskName := strings.TrimPrefix(podmanTaskConfig.NetworkMode, "task:")
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.FromContainer
createOpts.ContainerNetworkConfig.NetNS.Value = BuildContainerNameForTask(otherTaskName, cfg)
default:
return nil, nil, fmt.Errorf("Unknown/Unsupported network mode: %s", podmanTaskConfig.NetworkMode)
}
}
// carefully add extra hosts (--add-host)
if extraHostsErr := setExtraHosts(podmanTaskConfig.ExtraHosts, &createOpts); extraHostsErr != nil {
return nil, nil, extraHostsErr
}
portMappings, err := d.portMappings(cfg, podmanTaskConfig)
if err != nil {
return nil, nil, err
}
createOpts.ContainerNetworkConfig.PortMappings = portMappings
containerID := ""
recoverRunningContainer := false
// check if there is a container with same name
otherContainerInspect, err := podmanClient.ContainerInspect(d.ctx, containerName)
if err == nil {
// ok, seems we found a container with similar name
if otherContainerInspect.State.Running {
// it's still running. So let's use it instead of creating a new one
d.logger.Info("Detect running container with same name, we reuse it", "task", cfg.ID, "container", otherContainerInspect.ID)
containerID = otherContainerInspect.ID
recoverRunningContainer = true
} else {
// let's remove the old, dead container
d.logger.Info("Detect stopped container with same name, removing it", "task", cfg.ID, "container", otherContainerInspect.ID)
if err = podmanClient.ContainerDelete(d.ctx, otherContainerInspect.ID, true, true); err != nil {
return nil, nil, nstructs.WrapRecoverable(fmt.Sprintf("failed to remove dead container: %v", err), err)
}
}
} else if !errors.Is(err, api.ContainerNotFound) {
return nil, nil, fmt.Errorf("failed to inspect container: %s: %w", containerName, err)
}
if !recoverRunningContainer {
imagePullTimeout, parseErr := time.ParseDuration(podmanTaskConfig.ImagePullTimeout)
if parseErr != nil {
return nil, nil, fmt.Errorf("failed to parse image_pull_timeout: %w", parseErr)
}
imageID, createErr := d.createImage(
createOpts.Image,
&podmanTaskConfig.Auth,
podmanTaskConfig.AuthSoftFail,
podmanTaskConfig.ForcePull,
podmanClient,
imagePullTimeout,
cfg,
)
if createErr != nil {
return nil, nil, fmt.Errorf("failed to create image: %s: %w", createOpts.Image, createErr)
}
createOpts.Image = imageID
createResponse, createErr := podmanClient.ContainerCreate(d.ctx, createOpts)
for _, w := range createResponse.Warnings {
d.logger.Warn("Create Warning", "warning", w)
}
if createErr != nil {
return nil, nil, fmt.Errorf("failed to start task, could not create container: %w", createErr)
}
containerID = createResponse.Id
}
cleanup := func() {
d.logger.Debug("Cleaning up", "container", containerID)
if cleanupErr := podmanClient.ContainerDelete(d.ctx, containerID, true, true); cleanupErr != nil {
d.logger.Error("failed to clean up from an error in Start", "error", cleanupErr)
}
}
h := &TaskHandle{
containerID: containerID,
driver: d,
podmanClient: podmanClient,
taskConfig: cfg,
procState: drivers.TaskStateRunning,
exitResult: &drivers.ExitResult{},
startedAt: time.Now(),
logger: d.logger.Named(fmt.Sprintf("podman.%s", podmanTaskSocketName)),
logStreamer: podmanTaskConfig.Logging.Driver == LOG_DRIVER_JOURNALD,
logPointer: time.Now(),
collectionInterval: time.Second,
totalCPUStats: cpustats.New(d.compute),
userCPUStats: cpustats.New(d.compute),
systemCPUStats: cpustats.New(d.compute),
removeContainerOnExit: d.config.GC.Container,
}
if !recoverRunningContainer {
if startErr := podmanClient.ContainerStart(d.ctx, containerID); startErr != nil {
cleanup()
return nil, nil, fmt.Errorf("failed to start task, could not start container: %w", startErr)
}
}
inspectData, err := podmanClient.ContainerInspect(d.ctx, containerID)
if err != nil {
d.logger.Error("failed to inspect container", "error", err)
cleanup()
return nil, nil, fmt.Errorf("failed to start task, could not inspect container : %w", err)
}
driverNet := &drivers.DriverNetwork{
PortMap: podmanTaskConfig.PortMap,
IP: inspectData.NetworkSettings.IPAddress,
AutoAdvertise: true,
}
driverState := TaskState{
ContainerID: containerID,
TaskConfig: cfg,
LogStreamer: h.logStreamer,
StartedAt: h.startedAt,
Net: driverNet,
}
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: %w", err)
}
d.tasks.Set(cfg.ID, h)
go h.runContainerMonitor()
d.logger.Info("Completely started container", "taskID", cfg.ID, "container", containerID, "ip", inspectData.NetworkSettings.IPAddress)
return handle, driverNet, nil
}
func memoryLimits(r drivers.MemoryResources, reservation string) (hard, soft *int64, err error) {
memoryMax := r.MemoryMaxMB * 1024 * 1024
memory := r.MemoryMB * 1024 * 1024
var reserved *int64
if reservation != "" {
reservation, err := memoryInBytes(reservation)
if err != nil {
return nil, nil, err
}
reserved = &reservation
}
if memoryMax > 0 {
if reserved != nil && *reserved < memory {
memory = *reserved
}
return &memoryMax, &memory, nil
}
if memory > 0 {
return &memory, reserved, nil
}
// We may never actually be here
return nil, reserved, nil
}
func setCPUResources(cfg TaskConfig, systemResources *drivers.LinuxResources, taskCPU *spec.LinuxCPU) error {
// always assign cpuset
taskCPU.Cpus = systemResources.CpusetCpus
// only set bandwidth if hard limit is enabled
// currently only docker and podman drivers provide this ability
if !cfg.CPUHardLimit {
return nil
}
period := cfg.CPUCFSPeriod
if period > 1000000 {
return fmt.Errorf("invalid value for cpu_cfs_period, %d is bigger than 1000000", period)
}
if period == 0 {
period = 100000 // matches cgroup default
}
if period < 1000 {
period = 1000
}