-
-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathpodman_container_lib.py
1927 lines (1562 loc) · 70.9 KB
/
podman_container_lib.py
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
from __future__ import (absolute_import, division, print_function)
import json # noqa: F402
import os # noqa: F402
import shlex # noqa: F402
from ansible.module_utils._text import to_bytes, to_native # noqa: F402
from ansible_collections.containers.podman.plugins.module_utils.podman.common import LooseVersion
from ansible_collections.containers.podman.plugins.module_utils.podman.common import lower_keys
from ansible_collections.containers.podman.plugins.module_utils.podman.common import generate_systemd
from ansible_collections.containers.podman.plugins.module_utils.podman.common import delete_systemd
from ansible_collections.containers.podman.plugins.module_utils.podman.common import diff_generic
from ansible_collections.containers.podman.plugins.module_utils.podman.common import createcommand
from ansible_collections.containers.podman.plugins.module_utils.podman.quadlet import create_quadlet_state
from ansible_collections.containers.podman.plugins.module_utils.podman.quadlet import ContainerQuadlet
__metaclass__ = type
ARGUMENTS_SPEC_CONTAINER = dict(
name=dict(required=True, type='str'),
executable=dict(default='podman', type='str'),
state=dict(type='str', default='started', choices=[
'absent', 'present', 'stopped', 'started', 'created', 'quadlet']),
image=dict(type='str'),
annotation=dict(type='dict'),
arch=dict(type='str'),
attach=dict(type='list', elements='str', choices=['stdout', 'stderr', 'stdin']),
authfile=dict(type='path'),
blkio_weight=dict(type='int'),
blkio_weight_device=dict(type='dict'),
cap_add=dict(type='list', elements='str', aliases=['capabilities']),
cap_drop=dict(type='list', elements='str'),
cgroup_conf=dict(type='dict'),
cgroup_parent=dict(type='path'),
cgroupns=dict(type='str'),
cgroups=dict(type='str'),
chrootdirs=dict(type='str'),
cidfile=dict(type='path'),
cmd_args=dict(type='list', elements='str'),
conmon_pidfile=dict(type='path'),
command=dict(type='raw'),
cpu_period=dict(type='int'),
cpu_quota=dict(type='int'),
cpu_rt_period=dict(type='int'),
cpu_rt_runtime=dict(type='int'),
cpu_shares=dict(type='int'),
cpus=dict(type='str'),
cpuset_cpus=dict(type='str'),
cpuset_mems=dict(type='str'),
decryption_key=dict(type='str', no_log=False),
delete_depend=dict(type='bool'),
delete_time=dict(type='str'),
delete_volumes=dict(type='bool'),
detach=dict(type='bool', default=True),
debug=dict(type='bool', default=False),
detach_keys=dict(type='str', no_log=False),
device=dict(type='list', elements='str'),
device_cgroup_rule=dict(type='str'),
device_read_bps=dict(type='list', elements='str'),
device_read_iops=dict(type='list', elements='str'),
device_write_bps=dict(type='list', elements='str'),
device_write_iops=dict(type='list', elements='str'),
dns=dict(type='list', elements='str', aliases=['dns_servers']),
dns_option=dict(type='str', aliases=['dns_opts']),
dns_search=dict(type='str', aliases=['dns_search_domains']),
entrypoint=dict(type='str'),
env=dict(type='dict'),
env_file=dict(type='list', elements='path', aliases=['env_files']),
env_host=dict(type='bool'),
env_merge=dict(type='dict'),
etc_hosts=dict(type='dict', aliases=['add_hosts']),
expose=dict(type='list', elements='str', aliases=[
'exposed', 'exposed_ports']),
force_restart=dict(type='bool', default=False,
aliases=['restart']),
force_delete=dict(type='bool', default=True),
generate_systemd=dict(type='dict', default={}),
gidmap=dict(type='list', elements='str'),
gpus=dict(type='str'),
group_add=dict(type='list', elements='str', aliases=['groups']),
group_entry=dict(type='str'),
healthcheck=dict(type='str', aliases=['health_cmd']),
healthcheck_interval=dict(type='str', aliases=['health_interval']),
healthcheck_retries=dict(type='int', aliases=['health_retries']),
healthcheck_start_period=dict(type='str', aliases=['health_start_period']),
health_startup_cmd=dict(type='str'),
health_startup_interval=dict(type='str'),
health_startup_retries=dict(type='int'),
health_startup_success=dict(type='int'),
health_startup_timeout=dict(type='str'),
healthcheck_timeout=dict(type='str', aliases=['health_timeout']),
healthcheck_failure_action=dict(type='str', choices=[
'none', 'kill', 'restart', 'stop'], aliases=['health_on_failure']),
hooks_dir=dict(type='list', elements='str'),
hostname=dict(type='str'),
hostuser=dict(type='str'),
http_proxy=dict(type='bool'),
image_volume=dict(type='str', choices=['bind', 'tmpfs', 'ignore']),
image_strict=dict(type='bool', default=False),
init=dict(type='bool'),
init_ctr=dict(type='str', choices=['once', 'always']),
init_path=dict(type='str'),
interactive=dict(type='bool'),
ip=dict(type='str'),
ip6=dict(type='str'),
ipc=dict(type='str', aliases=['ipc_mode']),
kernel_memory=dict(type='str'),
label=dict(type='dict', aliases=['labels']),
label_file=dict(type='str'),
log_driver=dict(type='str', choices=[
'k8s-file', 'journald', 'json-file']),
log_level=dict(
type='str',
choices=["debug", "info", "warn", "error", "fatal", "panic"]),
log_opt=dict(type='dict', aliases=['log_options'],
options=dict(
max_size=dict(type='str'),
path=dict(type='str'),
tag=dict(type='str'))),
mac_address=dict(type='str'),
memory=dict(type='str'),
memory_reservation=dict(type='str'),
memory_swap=dict(type='str'),
memory_swappiness=dict(type='int'),
mount=dict(type='list', elements='str', aliases=['mounts']),
network=dict(type='list', elements='str', aliases=['net', 'network_mode']),
network_aliases=dict(type='list', elements='str', aliases=['network_alias']),
no_healthcheck=dict(type='bool'),
no_hosts=dict(type='bool'),
oom_kill_disable=dict(type='bool'),
oom_score_adj=dict(type='int'),
os=dict(type='str'),
passwd=dict(type='bool', no_log=False),
passwd_entry=dict(type='str', no_log=False),
personality=dict(type='str'),
pid=dict(type='str', aliases=['pid_mode']),
pid_file=dict(type='path'),
pids_limit=dict(type='str'),
platform=dict(type='str'),
pod=dict(type='str'),
pod_id_file=dict(type='path'),
preserve_fd=dict(type='list', elements='str'),
preserve_fds=dict(type='str'),
privileged=dict(type='bool'),
publish=dict(type='list', elements='str', aliases=[
'ports', 'published', 'published_ports']),
publish_all=dict(type='bool'),
pull=dict(type='str', choices=['always', 'missing', 'never', 'newer']),
quadlet_dir=dict(type='path'),
quadlet_filename=dict(type='str'),
quadlet_file_mode=dict(type='raw'),
quadlet_options=dict(type='list', elements='str'),
rdt_class=dict(type='str'),
read_only=dict(type='bool'),
read_only_tmpfs=dict(type='bool'),
recreate=dict(type='bool', default=False),
requires=dict(type='list', elements='str'),
restart_policy=dict(type='str'),
restart_time=dict(type='str'),
retry=dict(type='int'),
retry_delay=dict(type='str'),
rm=dict(type='bool', aliases=['remove', 'auto_remove']),
rmi=dict(type='bool'),
rootfs=dict(type='bool'),
seccomp_policy=dict(type='str'),
secrets=dict(type='list', elements='str', no_log=True),
sdnotify=dict(type='str'),
security_opt=dict(type='list', elements='str'),
shm_size=dict(type='str'),
shm_size_systemd=dict(type='str'),
sig_proxy=dict(type='bool'),
stop_signal=dict(type='int'),
stop_timeout=dict(type='int'),
stop_time=dict(type='str'),
subgidname=dict(type='str'),
subuidname=dict(type='str'),
sysctl=dict(type='dict'),
systemd=dict(type='str'),
timeout=dict(type='int'),
timezone=dict(type='str'),
tls_verify=dict(type='bool'),
tmpfs=dict(type='dict'),
tty=dict(type='bool'),
uidmap=dict(type='list', elements='str'),
ulimit=dict(type='list', elements='str', aliases=['ulimits']),
umask=dict(type='str'),
unsetenv=dict(type='list', elements='str'),
unsetenv_all=dict(type='bool'),
user=dict(type='str'),
userns=dict(type='str', aliases=['userns_mode']),
uts=dict(type='str'),
variant=dict(type='str'),
volume=dict(type='list', elements='str', aliases=['volumes']),
volumes_from=dict(type='list', elements='str'),
workdir=dict(type='str', aliases=['working_dir'])
)
def init_options():
default = {}
opts = ARGUMENTS_SPEC_CONTAINER
for k, v in opts.items():
if 'default' in v:
default[k] = v['default']
else:
default[k] = None
return default
def update_options(opts_dict, container):
def to_bool(x):
return str(x).lower() not in ['no', 'false']
aliases = {}
for k, v in ARGUMENTS_SPEC_CONTAINER.items():
if 'aliases' in v:
for alias in v['aliases']:
aliases[alias] = k
for k in list(container):
if k in aliases:
key = aliases[k]
container[key] = container.pop(k)
else:
key = k
if ARGUMENTS_SPEC_CONTAINER[key]['type'] == 'list' and not isinstance(container[key], list):
opts_dict[key] = [container[key]]
elif ARGUMENTS_SPEC_CONTAINER[key]['type'] == 'bool' and not isinstance(container[key], bool):
opts_dict[key] = to_bool(container[key])
elif ARGUMENTS_SPEC_CONTAINER[key]['type'] == 'int' and not isinstance(container[key], int):
opts_dict[key] = int(container[key])
else:
opts_dict[key] = container[key]
return opts_dict
def set_container_opts(input_vars):
default_options_templ = init_options()
options_dict = update_options(default_options_templ, input_vars)
return options_dict
class PodmanModuleParams:
"""Creates list of arguments for podman CLI command.
Arguments:
action {str} -- action type from 'run', 'stop', 'create', 'delete',
'start', 'restart'
params {dict} -- dictionary of module parameters
"""
def __init__(self, action, params, podman_version, module):
self.params = params
self.action = action
self.podman_version = podman_version
self.module = module
def construct_command_from_params(self):
"""Create a podman command from given module parameters.
Returns:
list -- list of byte strings for Popen command
"""
if self.action in ['start', 'stop', 'delete', 'restart']:
return self.start_stop_delete()
if self.action in ['create', 'run']:
cmd = [self.action, '--name', self.params['name']]
all_param_methods = [func for func in dir(self)
if callable(getattr(self, func))
and func.startswith("addparam")]
params_set = (i for i in self.params if self.params[i] is not None)
for param in params_set:
func_name = "_".join(["addparam", param])
if func_name in all_param_methods:
cmd = getattr(self, func_name)(cmd)
cmd.append(self.params['image'])
if self.params['command']:
if isinstance(self.params['command'], list):
cmd += self.params['command']
else:
cmd += self.params['command'].split()
return [to_bytes(i, errors='surrogate_or_strict') for i in cmd]
def start_stop_delete(self):
def complete_params(cmd):
if self.params['attach'] and self.action == 'start':
cmd.append('--attach')
if self.params['detach'] is False and self.action == 'start' and '--attach' not in cmd:
cmd.append('--attach')
if self.params['detach_keys'] and self.action == 'start':
cmd += ['--detach-keys', self.params['detach_keys']]
if self.params['sig_proxy'] and self.action == 'start':
cmd.append('--sig-proxy')
if self.params['stop_time'] and self.action == 'stop':
cmd += ['--time', self.params['stop_time']]
if self.params['restart_time'] and self.action == 'restart':
cmd += ['--time', self.params['restart_time']]
if self.params['delete_depend'] and self.action == 'delete':
cmd.append('--depend')
if self.params['delete_time'] and self.action == 'delete':
cmd += ['--time', self.params['delete_time']]
if self.params['delete_volumes'] and self.action == 'delete':
cmd.append('--volumes')
if self.params['force_delete'] and self.action == 'delete':
cmd.append('--force')
return cmd
if self.action in ['stop', 'start', 'restart']:
cmd = complete_params([self.action]) + [self.params['name']]
return [to_bytes(i, errors='surrogate_or_strict') for i in cmd]
if self.action == 'delete':
cmd = complete_params(['rm']) + [self.params['name']]
return [to_bytes(i, errors='surrogate_or_strict') for i in cmd]
def check_version(self, param, minv=None, maxv=None):
if minv and LooseVersion(minv) > LooseVersion(
self.podman_version):
self.module.fail_json(msg="Parameter %s is supported from podman "
"version %s only! Current version is %s" % (
param, minv, self.podman_version))
if maxv and LooseVersion(maxv) < LooseVersion(
self.podman_version):
self.module.fail_json(msg="Parameter %s is supported till podman "
"version %s only! Current version is %s" % (
param, minv, self.podman_version))
def addparam_annotation(self, c):
for annotate in self.params['annotation'].items():
c += ['--annotation', '='.join(annotate)]
return c
def addparam_arch(self, c):
return c + ['--arch=%s' % self.params['arch']]
def addparam_attach(self, c):
for attach in self.params['attach']:
c += ['--attach=%s' % attach]
return c
def addparam_authfile(self, c):
return c + ['--authfile', self.params['authfile']]
def addparam_blkio_weight(self, c):
return c + ['--blkio-weight', self.params['blkio_weight']]
def addparam_blkio_weight_device(self, c):
for blkio in self.params['blkio_weight_device'].items():
c += ['--blkio-weight-device', ':'.join(blkio)]
return c
def addparam_cap_add(self, c):
for cap_add in self.params['cap_add']:
c += ['--cap-add', cap_add]
return c
def addparam_cap_drop(self, c):
for cap_drop in self.params['cap_drop']:
c += ['--cap-drop', cap_drop]
return c
def addparam_cgroups(self, c):
self.check_version('--cgroups', minv='1.6.0')
return c + ['--cgroups=%s' % self.params['cgroups']]
def addparam_cgroupns(self, c):
self.check_version('--cgroupns', minv='1.6.2')
return c + ['--cgroupns=%s' % self.params['cgroupns']]
def addparam_cgroup_parent(self, c):
return c + ['--cgroup-parent', self.params['cgroup_parent']]
def addparam_cgroup_conf(self, c):
for cgroup in self.params['cgroup_conf'].items():
c += ['--cgroup-conf=%s' % '='.join([str(i) for i in cgroup])]
return c
def addparam_chrootdirs(self, c):
return c + ['--chrootdirs', self.params['chrootdirs']]
def addparam_cidfile(self, c):
return c + ['--cidfile', self.params['cidfile']]
def addparam_conmon_pidfile(self, c):
return c + ['--conmon-pidfile', self.params['conmon_pidfile']]
def addparam_cpu_period(self, c):
return c + ['--cpu-period', self.params['cpu_period']]
def addparam_cpu_quota(self, c):
return c + ['--cpu-quota', self.params['cpu_quota']]
def addparam_cpu_rt_period(self, c):
return c + ['--cpu-rt-period', self.params['cpu_rt_period']]
def addparam_cpu_rt_runtime(self, c):
return c + ['--cpu-rt-runtime', self.params['cpu_rt_runtime']]
def addparam_cpu_shares(self, c):
return c + ['--cpu-shares', self.params['cpu_shares']]
def addparam_cpus(self, c):
return c + ['--cpus', self.params['cpus']]
def addparam_cpuset_cpus(self, c):
return c + ['--cpuset-cpus', self.params['cpuset_cpus']]
def addparam_cpuset_mems(self, c):
return c + ['--cpuset-mems', self.params['cpuset_mems']]
def addparam_decryption_key(self, c):
return c + ['--decryption-key=%s' % self.params['decryption_key']]
def addparam_detach(self, c):
# Remove detach from create command and don't set if attach is true
if self.action == 'create' or self.params['attach']:
return c
return c + ['--detach=%s' % self.params['detach']]
def addparam_detach_keys(self, c):
return c + ['--detach-keys', self.params['detach_keys']]
def addparam_device(self, c):
for dev in self.params['device']:
c += ['--device', dev]
return c
def addparam_device_cgroup_rule(self, c):
return c + ['--device-cgroup-rule=%s' % self.params['device_cgroup_rule']]
def addparam_device_read_bps(self, c):
for dev in self.params['device_read_bps']:
c += ['--device-read-bps', dev]
return c
def addparam_device_read_iops(self, c):
for dev in self.params['device_read_iops']:
c += ['--device-read-iops', dev]
return c
def addparam_device_write_bps(self, c):
for dev in self.params['device_write_bps']:
c += ['--device-write-bps', dev]
return c
def addparam_device_write_iops(self, c):
for dev in self.params['device_write_iops']:
c += ['--device-write-iops', dev]
return c
def addparam_dns(self, c):
return c + ['--dns', ','.join(self.params['dns'])]
def addparam_dns_option(self, c):
return c + ['--dns-option', self.params['dns_option']]
def addparam_dns_search(self, c):
return c + ['--dns-search', self.params['dns_search']]
def addparam_entrypoint(self, c):
return c + ['--entrypoint=%s' % self.params['entrypoint']]
def addparam_env(self, c):
for env_value in self.params['env'].items():
c += ['--env',
b"=".join([to_bytes(k, errors='surrogate_or_strict')
for k in env_value])]
return c
def addparam_env_file(self, c):
for env_file in self.params['env_file']:
c += ['--env-file', env_file]
return c
def addparam_env_host(self, c):
self.check_version('--env-host', minv='1.5.0')
return c + ['--env-host=%s' % self.params['env_host']]
# Exception for etc_hosts and add-host
def addparam_etc_hosts(self, c):
for host_ip in self.params['etc_hosts'].items():
c += ['--add-host', ':'.join(host_ip)]
return c
def addparam_env_merge(self, c):
for env_merge in self.params['env_merge'].items():
c += ['--env-merge',
b"=".join([to_bytes(k, errors='surrogate_or_strict')
for k in env_merge])]
return c
def addparam_expose(self, c):
for exp in self.params['expose']:
c += ['--expose', exp]
return c
def addparam_gidmap(self, c):
for gidmap in self.params['gidmap']:
c += ['--gidmap', gidmap]
return c
def addparam_gpus(self, c):
return c + ['--gpus', self.params['gpus']]
def addparam_group_add(self, c):
for g in self.params['group_add']:
c += ['--group-add', g]
return c
def addparam_group_entry(self, c):
return c + ['--group-entry', self.params['group_entry']]
# Exception for healthcheck and healthcheck-command
def addparam_healthcheck(self, c):
return c + ['--healthcheck-command', self.params['healthcheck']]
def addparam_healthcheck_interval(self, c):
return c + ['--healthcheck-interval',
self.params['healthcheck_interval']]
def addparam_healthcheck_retries(self, c):
return c + ['--healthcheck-retries',
self.params['healthcheck_retries']]
def addparam_healthcheck_start_period(self, c):
return c + ['--healthcheck-start-period',
self.params['healthcheck_start_period']]
def addparam_health_startup_cmd(self, c):
return c + ['--health-startup-cmd', self.params['health_startup_cmd']]
def addparam_health_startup_interval(self, c):
return c + ['--health-startup-interval', self.params['health_startup_interval']]
def addparam_healthcheck_timeout(self, c):
return c + ['--healthcheck-timeout',
self.params['healthcheck_timeout']]
def addparam_health_startup_retries(self, c):
return c + ['--health-startup-retries', self.params['health_startup_retries']]
def addparam_health_startup_success(self, c):
return c + ['--health-startup-success', self.params['health_startup_success']]
def addparam_health_startup_timeout(self, c):
return c + ['--health-startup-timeout', self.params['health_startup_timeout']]
def addparam_healthcheck_failure_action(self, c):
return c + ['--health-on-failure',
self.params['healthcheck_failure_action']]
def addparam_hooks_dir(self, c):
for hook_dir in self.params['hooks_dir']:
c += ['--hooks-dir=%s' % hook_dir]
return c
def addparam_hostname(self, c):
return c + ['--hostname', self.params['hostname']]
def addparam_hostuser(self, c):
return c + ['--hostuser', self.params['hostuser']]
def addparam_http_proxy(self, c):
return c + ['--http-proxy=%s' % self.params['http_proxy']]
def addparam_image_volume(self, c):
return c + ['--image-volume', self.params['image_volume']]
def addparam_init(self, c):
if self.params['init']:
c += ['--init']
return c
def addparam_init_path(self, c):
return c + ['--init-path', self.params['init_path']]
def addparam_init_ctr(self, c):
return c + ['--init-ctr', self.params['init_ctr']]
def addparam_interactive(self, c):
return c + ['--interactive=%s' % self.params['interactive']]
def addparam_ip(self, c):
return c + ['--ip', self.params['ip']]
def addparam_ip6(self, c):
return c + ['--ip6', self.params['ip6']]
def addparam_ipc(self, c):
return c + ['--ipc', self.params['ipc']]
def addparam_kernel_memory(self, c):
return c + ['--kernel-memory', self.params['kernel_memory']]
def addparam_label(self, c):
for label in self.params['label'].items():
c += ['--label', b'='.join([to_bytes(la, errors='surrogate_or_strict')
for la in label])]
return c
def addparam_label_file(self, c):
return c + ['--label-file', self.params['label_file']]
def addparam_log_driver(self, c):
return c + ['--log-driver', self.params['log_driver']]
def addparam_log_opt(self, c):
for k, v in self.params['log_opt'].items():
if v is not None:
c += ['--log-opt',
b"=".join([to_bytes(k.replace('max_size', 'max-size'),
errors='surrogate_or_strict'),
to_bytes(v,
errors='surrogate_or_strict')])]
return c
def addparam_log_level(self, c):
return c + ['--log-level', self.params['log_level']]
def addparam_mac_address(self, c):
return c + ['--mac-address', self.params['mac_address']]
def addparam_memory(self, c):
return c + ['--memory', self.params['memory']]
def addparam_memory_reservation(self, c):
return c + ['--memory-reservation', self.params['memory_reservation']]
def addparam_memory_swap(self, c):
return c + ['--memory-swap', self.params['memory_swap']]
def addparam_memory_swappiness(self, c):
return c + ['--memory-swappiness', self.params['memory_swappiness']]
def addparam_mount(self, c):
for mnt in self.params['mount']:
if mnt:
c += ['--mount', mnt]
return c
def addparam_network(self, c):
if LooseVersion(self.podman_version) >= LooseVersion('4.0.0'):
for net in self.params['network']:
c += ['--network', net]
return c
return c + ['--network', ",".join(self.params['network'])]
# Exception for network_aliases and network-alias
def addparam_network_aliases(self, c):
for alias in self.params['network_aliases']:
c += ['--network-alias', alias]
return c
def addparam_no_hosts(self, c):
return c + ['--no-hosts=%s' % self.params['no_hosts']]
def addparam_no_healthcheck(self, c):
if self.params['no_healthcheck']:
c += ['--no-healthcheck']
return c
def addparam_oom_kill_disable(self, c):
return c + ['--oom-kill-disable=%s' % self.params['oom_kill_disable']]
def addparam_oom_score_adj(self, c):
return c + ['--oom-score-adj', self.params['oom_score_adj']]
def addparam_os(self, c):
return c + ['--os', self.params['os']]
def addparam_passwd(self, c):
if self.params['passwd']:
c += ['--passwd']
return c
def addparam_passwd_entry(self, c):
return c + ['--passwd-entry', self.params['passwd_entry']]
def addparam_personality(self, c):
return c + ['--personality', self.params['personality']]
def addparam_pid(self, c):
return c + ['--pid', self.params['pid']]
def addparam_pid_file(self, c):
return c + ['--pid-file', self.params['pid_file']]
def addparam_pids_limit(self, c):
return c + ['--pids-limit', self.params['pids_limit']]
def addparam_platform(self, c):
return c + ['--platform', self.params['platform']]
def addparam_pod(self, c):
return c + ['--pod', self.params['pod']]
def addparam_pod_id_file(self, c):
return c + ['--pod-id-file', self.params['pod_id_file']]
def addparam_preserve_fd(self, c):
for fd in self.params['preserve_fd']:
c += ['--preserve-fd', fd]
return c
def addparam_preserve_fds(self, c):
return c + ['--preserve-fds', self.params['preserve_fds']]
def addparam_privileged(self, c):
return c + ['--privileged=%s' % self.params['privileged']]
def addparam_publish(self, c):
for pub in self.params['publish']:
c += ['--publish', pub]
return c
def addparam_publish_all(self, c):
return c + ['--publish-all=%s' % self.params['publish_all']]
def addparam_pull(self, c):
return c + ['--pull=%s' % self.params['pull']]
def addparam_rdt_class(self, c):
return c + ['--rdt-class', self.params['rdt_class']]
def addparam_read_only(self, c):
return c + ['--read-only=%s' % self.params['read_only']]
def addparam_read_only_tmpfs(self, c):
return c + ['--read-only-tmpfs=%s' % self.params['read_only_tmpfs']]
def addparam_requires(self, c):
return c + ['--requires', ",".join(self.params['requires'])]
# Exception for restart_policy and restart
def addparam_restart_policy(self, c):
return c + ['--restart=%s' % self.params['restart_policy']]
def addparam_retry(self, c):
return c + ['--retry', self.params['retry']]
def addparam_retry_delay(self, c):
return c + ['--retry-delay', self.params['retry_delay']]
def addparam_rm(self, c):
if self.params['rm']:
c += ['--rm']
return c
def addparam_rmi(self, c):
if self.params['rmi']:
c += ['--rmi']
return c
def addparam_rootfs(self, c):
return c + ['--rootfs=%s' % self.params['rootfs']]
def addparam_sdnotify(self, c):
return c + ['--sdnotify=%s' % self.params['sdnotify']]
def addparam_seccomp_policy(self, c):
return c + ['--seccomp-policy', self.params['seccomp_policy']]
# Exception for secrets and secret
def addparam_secrets(self, c):
for secret in self.params['secrets']:
c += ['--secret', secret]
return c
def addparam_security_opt(self, c):
for secopt in self.params['security_opt']:
c += ['--security-opt', secopt]
return c
def addparam_shm_size(self, c):
return c + ['--shm-size', self.params['shm_size']]
def addparam_shm_size_systemd(self, c):
return c + ['--shm-size-systemd', self.params['shm_size_systemd']]
def addparam_sig_proxy(self, c):
return c + ['--sig-proxy=%s' % self.params['sig_proxy']]
def addparam_stop_signal(self, c):
return c + ['--stop-signal', self.params['stop_signal']]
def addparam_stop_timeout(self, c):
return c + ['--stop-timeout', self.params['stop_timeout']]
def addparam_subgidname(self, c):
return c + ['--subgidname', self.params['subgidname']]
def addparam_subuidname(self, c):
return c + ['--subuidname', self.params['subuidname']]
def addparam_sysctl(self, c):
for sysctl in self.params['sysctl'].items():
c += ['--sysctl',
b"=".join([to_bytes(k, errors='surrogate_or_strict')
for k in sysctl])]
return c
def addparam_systemd(self, c):
return c + ['--systemd=%s' % str(self.params['systemd']).lower()]
def addparam_timeout(self, c):
return c + ['--timeout', self.params['timeout']]
# Exception for timezone and tz
def addparam_timezone(self, c):
return c + ['--tz=%s' % self.params['timezone']]
def addparam_tls_verify(self, c):
return c + ['--tls-verify=%s' % self.params['tls_verify']]
def addparam_tmpfs(self, c):
for tmpfs in self.params['tmpfs'].items():
c += ['--tmpfs', ':'.join(tmpfs)]
return c
def addparam_tty(self, c):
return c + ['--tty=%s' % self.params['tty']]
def addparam_uidmap(self, c):
for uidmap in self.params['uidmap']:
c += ['--uidmap', uidmap]
return c
def addparam_ulimit(self, c):
for u in self.params['ulimit']:
c += ['--ulimit', u]
return c
def addparam_umask(self, c):
return c + ['--umask', self.params['umask']]
def addparam_unsetenv(self, c):
for unsetenv in self.params['unsetenv']:
c += ['--unsetenv', unsetenv]
return c
def addparam_unsetenv_all(self, c):
if self.params['unsetenv_all']:
c += ['--unsetenv-all']
return c
def addparam_user(self, c):
return c + ['--user', self.params['user']]
def addparam_userns(self, c):
return c + ['--userns', self.params['userns']]
def addparam_uts(self, c):
return c + ['--uts', self.params['uts']]
def addparam_variant(self, c):
return c + ['--variant', self.params['variant']]
def addparam_volume(self, c):
for vol in self.params['volume']:
if vol:
c += ['--volume', vol]
return c
def addparam_volumes_from(self, c):
for vol in self.params['volumes_from']:
c += ['--volumes-from', vol]
return c
def addparam_workdir(self, c):
return c + ['--workdir', self.params['workdir']]
# Add your own args for podman command
def addparam_cmd_args(self, c):
return c + self.params['cmd_args']
class PodmanDefaults:
def __init__(self, image_info, podman_version):
self.version = podman_version
self.image_info = image_info
self.defaults = {
"detach": True,
"log_level": "error",
"tty": False,
}
def default_dict(self):
# make here any changes to self.defaults related to podman version
# https://github.com/containers/libpod/pull/5669
if (LooseVersion(self.version) >= LooseVersion('1.8.0')
and LooseVersion(self.version) < LooseVersion('1.9.0')):
self.defaults['cpu_shares'] = 1024
if (LooseVersion(self.version) >= LooseVersion('3.0.0')):
self.defaults['log_level'] = "warning"
return self.defaults
class PodmanContainerDiff:
def __init__(self, module, module_params, info, image_info, podman_version):
self.module = module
self.module_params = module_params
self.version = podman_version
self.default_dict = None
self.info = lower_keys(info)
self.image_info = lower_keys(image_info)
self.params = self.defaultize()
self.diff = {'before': {}, 'after': {}}
self.non_idempotent = {}
def defaultize(self):
params_with_defaults = {}
self.default_dict = PodmanDefaults(
self.image_info, self.version).default_dict()
for p in self.module_params:
if self.module_params[p] is None and p in self.default_dict:
params_with_defaults[p] = self.default_dict[p]
else:
params_with_defaults[p] = self.module_params[p]
return params_with_defaults
def _diff_update_and_compare(self, param_name, before, after):
if before != after:
self.diff['before'].update({param_name: before})
self.diff['after'].update({param_name: after})
return True
return False
def _diff_generic(self, module_arg, cmd_arg, boolean_type=False):
"""
Generic diff function for module arguments from CreateCommand
in Podman inspection output.
Args:
module_arg (str): module argument name
cmd_arg (str): command line argument name
boolean_type (bool): if True, then argument is boolean type
Returns:
bool: True if there is a difference, False otherwise
"""
info_config = self.info["config"]
before, after = diff_generic(self.params, info_config, module_arg, cmd_arg, boolean_type)
return self._diff_update_and_compare(module_arg, before, after)
def diffparam_annotation(self):
before = self.info['config']['annotations'] or {}
after = before.copy()
if self.module_params['annotation'] is not None:
after.update(self.params['annotation'])
return self._diff_update_and_compare('annotation', before, after)
def diffparam_arch(self):
return self._diff_generic('arch', '--arch')
def diffparam_authfile(self):
return self._diff_generic('authfile', '--authfile')
def diffparam_blkio_weight(self):
return self._diff_generic('blkio_weight', '--blkio-weight')
def diffparam_blkio_weight_device(self):
return self._diff_generic('blkio_weight_device', '--blkio-weight-device')
def diffparam_cap_add(self):
before = self.info['effectivecaps'] or []
before = [i.lower() for i in before]
after = []
if self.module_params['cap_add'] is not None:
for cap in self.module_params['cap_add']:
cap = cap.lower()
cap = cap if cap.startswith('cap_') else 'cap_' + cap
after.append(cap)
after += before
before, after = sorted(list(set(before))), sorted(list(set(after)))
return self._diff_update_and_compare('cap_add', before, after)
def diffparam_cap_drop(self):
before = self.info['effectivecaps'] or []
before = [i.lower() for i in before]
after = before[:]
if self.module_params['cap_drop'] is not None:
for cap in self.module_params['cap_drop']:
cap = cap.lower()
cap = cap if cap.startswith('cap_') else 'cap_' + cap
if cap in after:
after.remove(cap)
before, after = sorted(list(set(before))), sorted(list(set(after)))
return self._diff_update_and_compare('cap_drop', before, after)
def diffparam_cgroup_conf(self):
return self._diff_generic('cgroup_conf', '--cgroup-conf')
def diffparam_cgroup_parent(self):
return self._diff_generic('cgroup_parent', '--cgroup-parent')
def diffparam_cgroupns(self):
return self._diff_generic('cgroupns', '--cgroupns')