forked from hashicorp/nomad-driver-podman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
1486 lines (1307 loc) · 49.7 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"
"path/filepath"
"runtime"
"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/stats"
"github.com/hashicorp/nomad/client/taskenv"
"github.com/hashicorp/nomad/drivers/shared/eventer"
shelpers "github.com/hashicorp/nomad/helper/stats"
nstructs "github.com/hashicorp/nomad/nomad/structs"
"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"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/ryanuber/go-glob"
"golang.org/x/exp/slices"
"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: drivers.FSIsolationImage,
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
// 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
// podmanClient encapsulates podman remote calls
podman *api.API
// slowPodman is a Podman client with no timeout configured that is used
// for slow operations that may need longer timeouts.
slowPodman *api.API
// SystemInfo collected at first fingerprint query
systemInfo api.Info
// Queried from systemInfo: is podman running on a cgroupv2 system?
cgroupV2 bool
// Queried from systemInfo: name of the cgroup manager
cgroupMgr string
// 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
}
d.podman = d.newPodmanClient(timeout)
d.slowPodman = d.newPodmanClient(0)
return nil
}
// 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) *api.API {
clientConfig := api.DefaultClientConfig()
clientConfig.HttpTimeout = timeout
if d.config.SocketPath != "" {
clientConfig.SocketPath = d.config.SocketPath
}
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)
err := shelpers.Init()
if err != nil {
d.logger.Error("Could not init stats helper", "error", 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 {
attrs := map[string]*pstructs.Attribute{}
// Ping podman api
apiVersion, err := d.podman.Ping(d.ctx)
if err != nil || apiVersion == "" {
// not reachable?
// deactivate driver, forget podman details
d.systemInfo = api.Info{}
d.logger.Error("Could not get podman version", "error", err)
return &drivers.Fingerprint{
Attributes: attrs,
Health: drivers.HealthStateUndetected,
HealthDescription: "disabled",
}
}
// do we already know details about podman or is the version different?
if d.systemInfo.Version.APIVersion != apiVersion {
// no? then fetch and cache it
// try to connect and get version info
info, err := d.podman.SystemInfo(d.ctx)
if err != nil {
d.logger.Error("Could not get podman info", "error", err)
return &drivers.Fingerprint{
Attributes: attrs,
Health: drivers.HealthStateUndetected,
HealthDescription: "disabled",
}
}
// keep first received systemInfo in driver struct
// it is used to toggle cgroup v1/v2, rootless/rootful behavior
d.systemInfo = info
d.cgroupV2 = info.Host.CGroupsVersion == "v2"
d.cgroupMgr = info.Host.CgroupManager
}
attrs["driver.podman"] = pstructs.NewBoolAttribute(true)
attrs["driver.podman.version"] = pstructs.NewStringAttribute(apiVersion)
attrs["driver.podman.rootless"] = pstructs.NewBoolAttribute(d.systemInfo.Host.Security.Rootless)
attrs["driver.podman.cgroupVersion"] = pstructs.NewStringAttribute(d.systemInfo.Host.CGroupsVersion)
return &drivers.Fingerprint{
Attributes: attrs,
Health: drivers.HealthStateHealthy,
HealthDescription: "ready",
}
}
// 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)
inspectData, err := d.podman.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 nil
} else if err != nil {
d.logger.Warn("Recovery lookup failed", "task", handle.Config.ID, "container", taskState.ContainerID, "error", err)
return nil
}
h := &TaskHandle{
containerID: taskState.ContainerID,
driver: d,
taskConfig: taskState.TaskConfig,
procState: drivers.TaskStateUnknown,
startedAt: taskState.StartedAt,
exitResult: &drivers.ExitResult{},
logger: d.logger.Named("podmanHandle"),
logPointer: time.Now(), // do not rewind log to the startetAt date.
logStreamer: taskState.LogStreamer,
collectionInterval: time.Second,
totalCPUStats: stats.NewCpuStats(),
userCPUStats: stats.NewCpuStats(),
systemCPUStats: stats.NewCpuStats(),
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)
if err = d.podman.ContainerStart(d.ctx, inspectData.ID); err != nil {
d.logger.Warn("Recovery restart failed", "task", handle.Config.ID, "container", taskState.ContainerID, "error", err)
} else {
d.logger.Info("Restarted a container during recovery", "container", inspectData.ID)
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)
if err = d.podman.ContainerDelete(d.ctx, inspectData.ID, true, true); err != nil {
d.logger.Warn("Recovery cleanup failed", "task", handle.Config.ID, "container", inspectData.ID)
}
h.procState = drivers.TaskStateExited
}
default:
d.logger.Warn("Recovery restart failed, unknown container state", "state", inspectData.State.Status, "container", taskState.ContainerID)
h.procState = drivers.TaskStateUnknown
}
d.tasks.Set(handle.Config.ID, h)
go h.runContainerMonitor()
d.logger.Debug("Recovered container handle", "container", taskState.ContainerID)
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) {
rootless := d.systemInfo.Host.Security.Rootless
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: %w", err)
}
handle := drivers.NewTaskHandle(taskHandleVersion)
handle.Config = cfg
if driverConfig.Image == "" {
return nil, nil, fmt.Errorf("image name required")
}
createOpts := api.SpecGenerator{}
createOpts.ContainerBasicConfig.LogConfiguration = &api.LogConfig{}
var allArgs []string
if driverConfig.Command != "" {
allArgs = append(allArgs, driverConfig.Command)
}
allArgs = append(allArgs, driverConfig.Args...)
// Parse entrypoint.
switch v := driverConfig.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", driverConfig.Entrypoint)
}
containerName := BuildContainerName(cfg)
// ensure to include port_map into tasks environment map
cfg.Env = taskenv.SetPortMapEnvs(cfg.Env, driverConfig.PortMap)
if len(driverConfig.Labels) > 0 {
createOpts.ContainerBasicConfig.Labels = driverConfig.Labels
}
labels := make(map[string]string, len(driverConfig.Labels)+1)
for k, v := range driverConfig.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
}
}
driverConfig.Labels = labels
d.logger.Debug("applied labels on the container", "labels", driverConfig.Labels)
// Basic config options
createOpts.ContainerBasicConfig.Name = containerName
createOpts.ContainerBasicConfig.Command = allArgs
createOpts.ContainerBasicConfig.Env = cfg.Env
createOpts.ContainerBasicConfig.Hostname = driverConfig.Hostname
createOpts.ContainerBasicConfig.Sysctl = driverConfig.Sysctl
createOpts.ContainerBasicConfig.Terminal = driverConfig.Tty
createOpts.ContainerBasicConfig.Labels = driverConfig.Labels
// Logging
switch driverConfig.Logging.Driver {
case "", LOG_DRIVER_NOMAD:
// Only modify container logging path if LogCollection is not disabled
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 logging.driver option")
}
createOpts.ContainerBasicConfig.LogConfiguration.Options = driverConfig.Logging.Options
// Storage config options
createOpts.ContainerStorageConfig.Init = driverConfig.Init
createOpts.ContainerStorageConfig.Image = driverConfig.Image
createOpts.ContainerStorageConfig.InitPath = driverConfig.InitPath
createOpts.ContainerStorageConfig.WorkDir = driverConfig.WorkingDir
allMounts, err := d.containerMounts(cfg, &driverConfig)
if err != nil {
return nil, nil, err
}
createOpts.ContainerStorageConfig.Mounts = allMounts
createOpts.ContainerStorageConfig.Devices = make([]spec.LinuxDevice, len(driverConfig.Devices))
for idx, device := range driverConfig.Devices {
createOpts.ContainerStorageConfig.Devices[idx] = spec.LinuxDevice{Path: device}
}
// Set the nomad slice as cgroup parent
d.setupCgroup(&createOpts)
// Resources config options
createOpts.ContainerResourceConfig.ResourceLimits = &spec.LinuxResources{
Memory: &spec.LinuxMemory{},
CPU: &spec.LinuxCPU{},
}
err = setCPUResources(driverConfig, cfg.Resources.LinuxResources, createOpts.ContainerResourceConfig.ResourceLimits.CPU)
if err != nil {
return nil, nil, err
}
hard, soft, err := memoryLimits(cfg.Resources.NomadResources.Memory, driverConfig.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 driverConfig.PidsLimit > 0 {
createOpts.ContainerResourceConfig.ResourceLimits.Pids = &spec.LinuxPids{
Limit: driverConfig.PidsLimit,
}
}
if driverConfig.MemorySwap != "" {
swap, memErr := memoryInBytes(driverConfig.MemorySwap)
if memErr != nil {
return nil, nil, memErr
}
createOpts.ContainerResourceConfig.ResourceLimits.Memory.Swap = &swap
}
if !d.cgroupV2 {
swappiness := uint64(driverConfig.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(driverConfig.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 = driverConfig.CapAdd
createOpts.ContainerSecurityConfig.CapDrop = driverConfig.CapDrop
createOpts.ContainerSecurityConfig.SelinuxOpts = driverConfig.SelinuxOpts
createOpts.ContainerSecurityConfig.User = cfg.User
createOpts.ContainerSecurityConfig.Privileged = driverConfig.Privileged
createOpts.ContainerSecurityConfig.ReadOnlyFilesystem = driverConfig.ReadOnlyRootfs
createOpts.ContainerSecurityConfig.ApparmorProfile = driverConfig.ApparmorProfile
// Populate --userns mode only if configured
if driverConfig.UserNS != "" {
userns := strings.SplitN(driverConfig.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}
}
}
// 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")
}
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...)
}
// 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 driverConfig.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 driverConfig.NetworkMode == "bridge":
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Bridge
case driverConfig.NetworkMode == "host":
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Host
case driverConfig.NetworkMode == "none":
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.NoNetwork
case driverConfig.NetworkMode == "slirp4netns":
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Slirp
case strings.HasPrefix(driverConfig.NetworkMode, "container:"):
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.FromContainer
createOpts.ContainerNetworkConfig.NetNS.Value = strings.TrimPrefix(driverConfig.NetworkMode, "container:")
case strings.HasPrefix(driverConfig.NetworkMode, "ns:"):
createOpts.ContainerNetworkConfig.NetNS.NSMode = api.Path
createOpts.ContainerNetworkConfig.NetNS.Value = strings.TrimPrefix(driverConfig.NetworkMode, "ns:")
case strings.HasPrefix(driverConfig.NetworkMode, "task:"):
otherTaskName := strings.TrimPrefix(driverConfig.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", driverConfig.NetworkMode)
}
}
// carefully add extra hosts (--add-host)
if extraHostsErr := setExtraHosts(driverConfig.ExtraHosts, &createOpts); extraHostsErr != nil {
return nil, nil, extraHostsErr
}
portMappings, err := d.portMappings(cfg, driverConfig)
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 := d.podman.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 = d.podman.ContainerDelete(d.ctx, otherContainerInspect.ID, true, true); err != nil {
return nil, nil, nstructs.WrapRecoverable(fmt.Sprintf("failed to remove dead container: %v", err), err)
}
}
}
if !recoverRunningContainer {
imagePullTimeout, parseErr := time.ParseDuration(driverConfig.ImagePullTimeout)
if parseErr != nil {
return nil, nil, fmt.Errorf("failed to parse image_pull_timeout: %w", parseErr)
}
imageID, createErr := d.createImage(
createOpts.Image,
&driverConfig.Auth,
driverConfig.AuthSoftFail,
driverConfig.ForcePull,
imagePullTimeout,
cfg,
)
if createErr != nil {
return nil, nil, fmt.Errorf("failed to create image: %s: %w", createOpts.Image, createErr)
}
createOpts.Image = imageID
createResponse, createErr := d.podman.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 := d.podman.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,
taskConfig: cfg,
procState: drivers.TaskStateRunning,
exitResult: &drivers.ExitResult{},
startedAt: time.Now(),
logger: d.logger.Named("podmanHandle"),
logStreamer: driverConfig.Logging.Driver == LOG_DRIVER_JOURNALD,
logPointer: time.Now(),
collectionInterval: time.Second,
totalCPUStats: stats.NewCpuStats(),
userCPUStats: stats.NewCpuStats(),
systemCPUStats: stats.NewCpuStats(),
removeContainerOnExit: d.config.GC.Container,
}
if !recoverRunningContainer {
if startErr := d.podman.ContainerStart(d.ctx, containerID); startErr != nil {
cleanup()
return nil, nil, fmt.Errorf("failed to start task, could not start container: %w", startErr)
}
}
inspectData, err := d.podman.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: driverConfig.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
}
// setupCgroup customizes where the cgroup lives (v2 only)
func (d *Driver) setupCgroup(opts *api.SpecGenerator) {
if d.cgroupV2 && d.cgroupMgr == "systemd" {
opts.ContainerCgroupConfig.CgroupParent = "nomad.slice"
}
}
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
}
numCores := runtime.NumCPU()
quota := int64(systemResources.PercentTicks*float64(period)) * int64(numCores)
if quota < 1000 {
quota = 1000
}
taskCPU.Period = &period
taskCPU.Quota = "a
return nil
}
func memoryInBytes(strmem string) (int64, error) {
l := len(strmem)
if l < 2 {
return 0, fmt.Errorf("Invalid memory string: %s", strmem)
}
ival, err := strconv.Atoi(strmem[0 : l-1])
if err != nil {
return 0, err
}
switch strmem[l-1] {
case 'b':
return int64(ival), nil
case 'k':
return int64(ival) * 1024, nil
case 'm':
return int64(ival) * 1024 * 1024, nil
case 'g':
return int64(ival) * 1024 * 1024 * 1024, nil
default:
return 0, fmt.Errorf("Invalid memory string: %s", strmem)
}
}
func sliceMergeUlimit(ulimitsRaw map[string]string) ([]spec.POSIXRlimit, error) {
var ulimits []spec.POSIXRlimit
for name, ulimitRaw := range ulimitsRaw {
if len(ulimitRaw) == 0 {
return []spec.POSIXRlimit{}, fmt.Errorf("Malformed ulimit specification %v: %q, cannot be empty", name, ulimitRaw)
}
// hard limit is optional
if !strings.Contains(ulimitRaw, ":") {
ulimitRaw = ulimitRaw + ":" + ulimitRaw
}
split := strings.SplitN(ulimitRaw, ":", 2)
if len(split) < 2 {
return []spec.POSIXRlimit{}, fmt.Errorf("Malformed ulimit specification %v: %v", name, ulimitRaw)
}
soft, err := strconv.Atoi(split[0])
if err != nil {
return []spec.POSIXRlimit{}, fmt.Errorf("Malformed soft ulimit %v: %v", name, ulimitRaw)
}
hard, err := strconv.Atoi(split[1])
if err != nil {
return []spec.POSIXRlimit{}, fmt.Errorf("Malformed hard ulimit %v: %v", name, ulimitRaw)
}
ulimit := spec.POSIXRlimit{
Type: name,
Soft: uint64(soft),
Hard: uint64(hard),
}
ulimits = append(ulimits, ulimit)
}
return ulimits, nil
}
// Creates the requested image if missing from storage
// returns the 64-byte image ID as an unique image identifier
func (d *Driver) createImage(
image string,
auth *TaskAuthConfig,
authSoftFail bool,
forcePull bool,
imagePullTimeout time.Duration,
cfg *drivers.TaskConfig,
) (string, error) {
var imageID string
imageName := image
// If it is a shortname, we should not have to worry
// Let podman deal with it according to user configuration
if !shortnames.IsShortName(image) {
imageRef, err := parseImage(image)
if err != nil {
return imageID, fmt.Errorf("invalid image reference %s: %w", image, err)
}
switch transport := imageRef.Transport().Name(); transport {
case "docker":
imageName = imageRef.DockerReference().String()
case "oci-archive", "docker-archive":
// For archive transports, we cannot ask for a pull or
// check for existence in the API without image plumbing.
// Load the images instead
archiveData := imageRef.StringWithinTransport()
path := strings.Split(archiveData, ":")[0]
d.logger.Debug("Load image archive", "path", path)
_ = d.eventer.EmitEvent(&drivers.TaskEvent{
TaskID: cfg.ID,
TaskName: cfg.Name,
AllocID: cfg.AllocID,
Timestamp: time.Now(),
Message: "Loading image " + path,
})
imageName, err = d.podman.ImageLoad(d.ctx, path)
if err != nil {
return imageID, fmt.Errorf("error while loading image: %w", err)
}
}
}
imageID, err := d.podman.ImageInspectID(d.ctx, imageName)
if err != nil && !errors.Is(err, api.ImageNotFound) {
// If ImageInspectID errors, continue the operation and try
// to pull the image instead
d.logger.Warn("Unable to check for local image", "image", imageName, "error", err)
}
if !forcePull && imageID != "" {
d.logger.Debug("Found imageID", imageID, "for image", imageName, "in local storage")
return imageID, nil
}
d.logger.Info("Pulling image", "image", imageName)
_ = d.eventer.EmitEvent(&drivers.TaskEvent{
TaskID: cfg.ID,
TaskName: cfg.Name,
AllocID: cfg.AllocID,
Timestamp: time.Now(),
Message: "Pulling image " + imageName,
})
pc := ®istry.PullConfig{
Image: imageName,
TLSVerify: auth.TLSVerify,
RegistryConfig: ®istry.RegistryAuthConfig{
Username: auth.Username,
Password: auth.Password,
},
CredentialsFile: d.config.Auth.FileConfig,
CredentialsHelper: d.config.Auth.Helper,
AuthSoftFail: authSoftFail,
}
result, err, _ := d.pullGroup.Do(imageName, func() (interface{}, error) {
ctx, cancel := context.WithTimeout(context.Background(), imagePullTimeout)
defer cancel()
if imageID, err = d.slowPodman.ImagePull(ctx, pc); err != nil {
return imageID, fmt.Errorf("failed to start task, unable to pull image %s : %w", imageName, err)