forked from containers/podman-compose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
podman_compose.py
executable file
·3234 lines (2931 loc) · 109 KB
/
podman_compose.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# https://docs.docker.com/compose/compose-file/#service-configuration-reference
# https://docs.docker.com/samples/
# https://docs.docker.com/compose/gettingstarted/
# https://docs.docker.com/compose/django/
# https://docs.docker.com/compose/wordpress/
# TODO: podman pod logs --color -n -f pod_testlogs
import sys
import os
import getpass
import argparse
import itertools
import subprocess
import time
import re
import hashlib
import random
import json
import glob
from threading import Thread
import shlex
try:
from shlex import quote as cmd_quote
except ImportError:
from pipes import quote as cmd_quote # pylint: disable=deprecated-module
# import fnmatch
# fnmatch.fnmatchcase(env, "*_HOST")
import yaml
from dotenv import dotenv_values
__version__ = "1.0.7"
script = os.path.realpath(sys.argv[0])
# helper functions
def is_str(string_object):
return isinstance(string_object, str)
def is_dict(dict_object):
return isinstance(dict_object, dict)
def is_list(list_object):
return (
not is_str(list_object)
and not is_dict(list_object)
and hasattr(list_object, "__iter__")
)
# identity filter
def filteri(a):
return filter(lambda i: i, a)
def try_int(i, fallback=None):
try:
return int(i)
except ValueError:
pass
except TypeError:
pass
return fallback
def try_float(i, fallback=None):
try:
return float(i)
except ValueError:
pass
except TypeError:
pass
return fallback
def log(*msgs, sep=" ", end="\n"):
line = (sep.join([str(msg) for msg in msgs])) + end
sys.stderr.write(line)
sys.stderr.flush()
dir_re = re.compile(r"^[~/\.]")
propagation_re = re.compile(
"^(?:z|Z|O|U|r?shared|r?slave|r?private|r?unbindable|r?bind|(?:no)?(?:exec|dev|suid))$"
)
norm_re = re.compile("[^-_a-z0-9]")
num_split_re = re.compile(r"(\d+|\D+)")
PODMAN_CMDS = (
"pull",
"push",
"build",
"inspect",
"run",
"start",
"stop",
"rm",
"volume",
)
t_re = re.compile(r"^(?:(\d+)[m:])?(?:(\d+(?:\.\d+)?)s?)?$")
STOP_GRACE_PERIOD = "10"
def str_to_seconds(txt):
if not txt:
return None
if isinstance(txt, (int, float)):
return txt
match = t_re.match(txt.strip())
if not match:
return None
mins, sec = match[1], match[2]
mins = int(mins) if mins else 0
sec = float(sec) if sec else 0
# "podman stop" takes only int
# Error: invalid argument "3.0" for "-t, --time" flag: strconv.ParseUint: parsing "3.0": invalid syntax
return int(mins * 60.0 + sec)
def ver_as_list(a):
return [try_int(i, i) for i in num_split_re.findall(a)]
def strverscmp_lt(a, b):
a_ls = ver_as_list(a or "")
b_ls = ver_as_list(b or "")
return a_ls < b_ls
def parse_short_mount(mount_str, basedir):
mount_a = mount_str.split(":")
mount_opt_dict = {}
mount_opt = None
if len(mount_a) == 1:
# Anonymous: Just specify a path and let the engine creates the volume
# - /var/lib/mysql
mount_src, mount_dst = None, mount_str
elif len(mount_a) == 2:
mount_src, mount_dst = mount_a
# dest must start with / like /foo:/var/lib/mysql
# otherwise it's option like /var/lib/mysql:rw
if not mount_dst.startswith("/"):
mount_dst, mount_opt = mount_a
mount_src = None
elif len(mount_a) == 3:
mount_src, mount_dst, mount_opt = mount_a
else:
raise ValueError("could not parse mount " + mount_str)
if mount_src and dir_re.match(mount_src):
# Specify an absolute path mapping
# - /opt/data:/var/lib/mysql
# Path on the host, relative to the Compose file
# - ./cache:/tmp/cache
# User-relative path
# - ~/configs:/etc/configs/:ro
mount_type = "bind"
mount_src = os.path.abspath(
os.path.join(basedir, os.path.expanduser(mount_src))
)
else:
# Named volume
# - datavolume:/var/lib/mysql
mount_type = "volume"
mount_opts = filteri((mount_opt or "").split(","))
propagation_opts = []
for opt in mount_opts:
if opt == "ro":
mount_opt_dict["read_only"] = True
elif opt == "rw":
mount_opt_dict["read_only"] = False
elif opt in ("consistent", "delegated", "cached"):
mount_opt_dict["consistency"] = opt
elif propagation_re.match(opt):
propagation_opts.append(opt)
else:
# TODO: ignore
raise ValueError("unknown mount option " + opt)
mount_opt_dict["bind"] = {"propagation": ",".join(propagation_opts)}
return {
"type": mount_type,
"source": mount_src,
"target": mount_dst,
**mount_opt_dict,
}
# NOTE: if a named volume is used but not defined it
# gives ERROR: Named volume "abc" is used in service "xyz"
# but no declaration was found in the volumes section.
# unless it's anonymous-volume
def fix_mount_dict(compose, mount_dict, proj_name, srv_name):
"""
in-place fix mount dictionary to:
- define _vol to be the corresponding top-level volume
- if name is missing it would be source prefixed with project
- if no source it would be generated
"""
# if already applied nothing todo
if "_vol" in mount_dict:
return mount_dict
if mount_dict["type"] == "volume":
vols = compose.vols
source = mount_dict.get("source", None)
vol = (vols.get(source, None) or {}) if source else {}
name = vol.get("name", None)
mount_dict["_vol"] = vol
# handle anonymous or implied volume
if not source:
# missing source
vol["name"] = ("-" if compose.global_args.kubecompat else "_").join(
[
proj_name,
srv_name,
hashlib.sha256(mount_dict["target"].encode("utf-8")).hexdigest(),
]
)
elif not name:
external = vol.get("external", None)
if isinstance(external, dict):
vol["name"] = external.get("name", f"{source}")
elif external:
vol["name"] = f"{source}"
else:
vol["name"] = f"{proj_name}_{source}"
return mount_dict
# docker and docker-compose support subset of bash variable substitution
# https://docs.docker.com/compose/compose-file/#variable-substitution
# https://docs.docker.com/compose/env-file/
# https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
# $VARIABLE
# ${VARIABLE}
# ${VARIABLE:-default} default if not set or empty
# ${VARIABLE-default} default if not set
# ${VARIABLE:?err} raise error if not set or empty
# ${VARIABLE?err} raise error if not set
# $$ means $
var_re = re.compile(
r"""
\$(?:
(?P<escaped>\$) |
(?P<named>[_a-zA-Z][_a-zA-Z0-9]*) |
(?:{
(?P<braced>[_a-zA-Z][_a-zA-Z0-9]*)
(?:(?P<empty>:)?(?:
(?:-(?P<default>[^}]*)) |
(?:\?(?P<err>[^}]*))
))?
})
)
""",
re.VERBOSE,
)
def rec_subs(value, subs_dict):
"""
do bash-like substitution in value and if list of dictionary do that recursively
"""
if is_dict(value):
value = {k: rec_subs(v, subs_dict) for k, v in value.items()}
elif is_str(value):
def convert(m):
if m.group("escaped") is not None:
return "$"
name = m.group("named") or m.group("braced")
value = subs_dict.get(name)
if value == "" and m.group("empty"):
value = None
if value is not None:
return str(value)
if m.group("err") is not None:
raise RuntimeError(m.group("err"))
return m.group("default") or ""
value = var_re.sub(convert, value)
elif hasattr(value, "__iter__"):
value = [rec_subs(i, subs_dict) for i in value]
return value
def norm_as_list(src):
"""
given a dictionary {key1:value1, key2: None} or list
return a list of ["key1=value1", "key2"]
"""
if src is None:
dst = []
elif is_dict(src):
dst = [(f"{k}={v}" if v is not None else k) for k, v in src.items()]
elif is_list(src):
dst = list(src)
else:
dst = [src]
return dst
def norm_as_dict(src):
"""
given a list ["key1=value1", "key2"]
return a dictionary {key1:value1, key2: None}
"""
if src is None:
dst = {}
elif is_dict(src):
dst = dict(src)
elif is_list(src):
dst = [i.split("=", 1) for i in src if i]
dst = [(a if len(a) == 2 else (a[0], None)) for a in dst]
dst = dict(dst)
elif is_str(src):
key, value = src.split("=", 1) if "=" in src else (src, None)
dst = {key: value}
else:
raise ValueError("dictionary or iterable is expected")
return dst
def norm_ulimit(inner_value):
if is_dict(inner_value):
if not inner_value.keys() & {"soft", "hard"}:
raise ValueError("expected at least one soft or hard limit")
soft = inner_value.get("soft", inner_value.get("hard", None))
hard = inner_value.get("hard", inner_value.get("soft", None))
return f"{soft}:{hard}"
if is_list(inner_value):
return norm_ulimit(norm_as_dict(inner_value))
# if int or string return as is
return inner_value
# def tr_identity(project_name, given_containers):
# pod_name = f'pod_{project_name}'
# pod = dict(name=pod_name)
# containers = []
# for cnt in given_containers:
# containers.append(dict(cnt, pod=pod_name))
# return [pod], containers
def transform(args, project_name, given_containers):
if not args.in_pod:
pod_name = None
pods = []
else:
pod_name = f"pod_{project_name}"
pod = {"name": pod_name}
pods = [pod]
containers = []
for cnt in given_containers:
containers.append(dict(cnt, pod=pod_name))
return pods, containers
def assert_volume(compose, mount_dict):
"""
inspect volume to get directory
create volume if needed
"""
vol = mount_dict.get("_vol", None)
if mount_dict["type"] == "bind":
basedir = os.path.realpath(compose.dirname)
mount_src = mount_dict["source"]
mount_src = os.path.realpath(
os.path.join(basedir, os.path.expanduser(mount_src))
)
if not os.path.exists(mount_src):
try:
os.makedirs(mount_src, exist_ok=True)
except OSError:
pass
return
if mount_dict["type"] != "volume" or not vol or not vol.get("name", None):
return
proj_name = compose.project_name
vol_name = vol["name"]
is_ext = vol.get("external", None)
log(f"podman volume inspect {vol_name} || podman volume create {vol_name}")
# TODO: might move to using "volume list"
# podman volume list --format '{{.Name}}\t{{.MountPoint}}' -f 'label=io.podman.compose.project=HERE'
try:
_ = compose.podman.output([], "volume", ["inspect", vol_name]).decode("utf-8")
except subprocess.CalledProcessError as e:
if is_ext:
raise RuntimeError(f"External volume [{vol_name}] does not exists") from e
labels = vol.get("labels", None) or []
args = [
"create",
"--label",
f"io.podman.compose.project={proj_name}",
"--label",
f"com.docker.compose.project={proj_name}",
]
for item in norm_as_list(labels):
args.extend(["--label", item])
driver = vol.get("driver", None)
if driver:
args.extend(["--driver", driver])
driver_opts = vol.get("driver_opts", None) or {}
for opt, value in driver_opts.items():
args.extend(["--opt", f"{opt}={value}"])
args.append(vol_name)
compose.podman.output([], "volume", args)
_ = compose.podman.output([], "volume", ["inspect", vol_name]).decode("utf-8")
def mount_desc_to_mount_args(
compose, mount_desc, srv_name, cnt_name
): # pylint: disable=unused-argument
mount_type = mount_desc.get("type", None)
vol = mount_desc.get("_vol", None) if mount_type == "volume" else None
source = vol["name"] if vol else mount_desc.get("source", None)
target = mount_desc["target"]
opts = []
if mount_desc.get(mount_type, None):
# TODO: we might need to add mount_dict[mount_type]["propagation"] = "z"
mount_prop = mount_desc.get(mount_type, {}).get("propagation", None)
if mount_prop:
opts.append(f"{mount_type}-propagation={mount_prop}")
if mount_desc.get("read_only", False):
opts.append("ro")
if mount_type == "tmpfs":
tmpfs_opts = mount_desc.get("tmpfs", {})
tmpfs_size = tmpfs_opts.get("size", None)
if tmpfs_size:
opts.append(f"tmpfs-size={tmpfs_size}")
tmpfs_mode = tmpfs_opts.get("mode", None)
if tmpfs_mode:
opts.append(f"tmpfs-mode={tmpfs_mode}")
opts = ",".join(opts)
if mount_type == "bind":
return f"type=bind,source={source},destination={target},{opts}".rstrip(",")
if mount_type == "volume":
return f"type=volume,source={source},destination={target},{opts}".rstrip(",")
if mount_type == "tmpfs":
return f"type=tmpfs,destination={target},{opts}".rstrip(",")
raise ValueError("unknown mount type:" + mount_type)
def container_to_ulimit_args(cnt, podman_args):
ulimit = cnt.get("ulimits", [])
if ulimit is not None:
# ulimit can be a single value, i.e. ulimit: host
if is_str(ulimit):
podman_args.extend(["--ulimit", ulimit])
# or a dictionary or list:
else:
ulimit = norm_as_dict(ulimit)
ulimit = [
"{}={}".format(ulimit_key, norm_ulimit(inner_value))
for ulimit_key, inner_value in ulimit.items()
]
for i in ulimit:
podman_args.extend(["--ulimit", i])
def mount_desc_to_volume_args(
compose, mount_desc, srv_name, cnt_name
): # pylint: disable=unused-argument
mount_type = mount_desc["type"]
if mount_type not in ("bind", "volume"):
raise ValueError("unknown mount type:" + mount_type)
vol = mount_desc.get("_vol", None) if mount_type == "volume" else None
source = vol["name"] if vol else mount_desc.get("source", None)
if not source:
raise ValueError(f"missing mount source for {mount_type} on {srv_name}")
if compose.global_args.kubecompat:
source = source.lower().replace('_', '-')
target = mount_desc["target"]
opts = []
propagations = set(
filteri(mount_desc.get(mount_type, {}).get("propagation", "").split(","))
)
if mount_type != "bind":
propagations.update(
filteri(mount_desc.get("bind", {}).get("propagation", "").split(","))
)
opts.extend(propagations)
# --volume, -v[=[[SOURCE-VOLUME|HOST-DIR:]CONTAINER-DIR[:OPTIONS]]]
# [rw|ro]
# [z|Z]
# [[r]shared|[r]slave|[r]private]|[r]unbindable
# [[r]bind]
# [noexec|exec]
# [nodev|dev]
# [nosuid|suid]
# [O]
# [U]
read_only = mount_desc.get("read_only", None)
if read_only is not None:
opts.append("ro" if read_only else "rw")
args = f"{source}:{target}"
if opts:
args += ":" + ",".join(opts)
return args
def get_mnt_dict(compose, cnt, volume):
proj_name = compose.project_name
srv_name = cnt["_service"]
basedir = compose.dirname
if is_str(volume):
volume = parse_short_mount(volume, basedir)
return fix_mount_dict(compose, volume, proj_name, srv_name)
def get_mount_args(compose, cnt, volume):
volume = get_mnt_dict(compose, cnt, volume)
# proj_name = compose.project_name
srv_name = cnt["_service"]
mount_type = volume["type"]
assert_volume(compose, volume)
if compose.prefer_volume_over_mount:
if mount_type == "tmpfs":
# TODO: --tmpfs /tmp:rw,size=787448k,mode=1777
args = volume["target"]
tmpfs_opts = volume.get("tmpfs", {})
opts = []
size = tmpfs_opts.get("size", None)
if size:
opts.append(f"size={size}")
mode = tmpfs_opts.get("mode", None)
if mode:
opts.append(f"mode={mode}")
if opts:
args += ":" + ",".join(opts)
return ["--tmpfs", args]
args = mount_desc_to_volume_args(compose, volume, srv_name, cnt["name"])
return ["-v", args]
args = mount_desc_to_mount_args(compose, volume, srv_name, cnt["name"])
return ["--mount", args]
def get_secret_args(compose, cnt, secret):
secret_name = secret if is_str(secret) else secret.get("source", None)
if not secret_name or secret_name not in compose.declared_secrets.keys():
raise ValueError(
f'ERROR: undeclared secret: "{secret}", service: {cnt["_service"]}'
)
declared_secret = compose.declared_secrets[secret_name]
source_file = declared_secret.get("file", None)
dest_file = ""
secret_opts = ""
target = None if is_str(secret) else secret.get("target", None)
uid = None if is_str(secret) else secret.get("uid", None)
gid = None if is_str(secret) else secret.get("gid", None)
mode = None if is_str(secret) else secret.get("mode", None)
if source_file:
if not target:
dest_file = f"/run/secrets/{secret_name}"
elif not target.startswith("/"):
sec = target if target else secret_name
dest_file = f"/run/secrets/{sec}"
else:
dest_file = target
basedir = compose.dirname
source_file = os.path.realpath(
os.path.join(basedir, os.path.expanduser(source_file))
)
volume_ref = ["--volume", f"{source_file}:{dest_file}:ro,rprivate,rbind"]
if uid or gid or mode:
sec = target if target else secret_name
log(
f'WARNING: Service {cnt["_service"]} uses secret "{sec}" with uid, gid, or mode.'
+ " These fields are not supported by this implementation of the Compose file"
)
return volume_ref
# v3.5 and up added external flag, earlier the spec
# only required a name to be specified.
# docker-compose does not support external secrets outside of swarm mode.
# However accessing these via podman is trivial
# since these commands are directly translated to
# podman-create commands, albeit we can only support a 1:1 mapping
# at the moment
if declared_secret.get("external", False) or declared_secret.get("name", None):
secret_opts += f",uid={uid}" if uid else ""
secret_opts += f",gid={gid}" if gid else ""
secret_opts += f",mode={mode}" if mode else ""
# The target option is only valid for type=env,
# which in an ideal world would work
# for type=mount as well.
# having a custom name for the external secret
# has the same problem as well
ext_name = declared_secret.get("name", None)
err_str = 'ERROR: Custom name/target reference "{}" for mounted external secret "{}" is not supported'
if ext_name and ext_name != secret_name:
raise ValueError(err_str.format(secret_name, ext_name))
if target and target != secret_name:
raise ValueError(err_str.format(target, secret_name))
if target:
log(
'WARNING: Service "{}" uses target: "{}" for secret: "{}".'.format(
cnt["_service"], target, secret_name
)
+ " That is un-supported and a no-op and is ignored."
)
return ["--secret", "{}{}".format(secret_name, secret_opts)]
raise ValueError(
'ERROR: unparsable secret: "{}", service: "{}"'.format(
secret_name, cnt["_service"]
)
)
def container_to_res_args(cnt, podman_args):
# v2: https://docs.docker.com/compose/compose-file/compose-file-v2/#cpu-and-other-resources
# cpus, cpu_shares, mem_limit, mem_reservation
cpus_limit_v2 = try_float(cnt.get("cpus", None), None)
cpu_shares_v2 = try_int(cnt.get("cpu_shares", None), None)
mem_limit_v2 = cnt.get("mem_limit", None)
mem_res_v2 = cnt.get("mem_reservation", None)
# v3: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources
# spec: https://github.com/compose-spec/compose-spec/blob/master/deploy.md#resources
# deploy.resources.{limits,reservations}.{cpus, memory}
deploy = cnt.get("deploy", None) or {}
res = deploy.get("resources", None) or {}
limits = res.get("limits", None) or {}
cpus_limit_v3 = try_float(limits.get("cpus", None), None)
mem_limit_v3 = limits.get("memory", None)
reservations = res.get("reservations", None) or {}
# cpus_res_v3 = try_float(reservations.get('cpus', None), None)
mem_res_v3 = reservations.get("memory", None)
# add args
cpus = cpus_limit_v3 or cpus_limit_v2
if cpus:
podman_args.extend(
(
"--cpus",
str(cpus),
)
)
if cpu_shares_v2:
podman_args.extend(
(
"--cpu-shares",
str(cpu_shares_v2),
)
)
mem = mem_limit_v3 or mem_limit_v2
if mem:
podman_args.extend(
(
"-m",
str(mem).lower(),
)
)
mem_res = mem_res_v3 or mem_res_v2
if mem_res:
podman_args.extend(
(
"--memory-reservation",
str(mem_res).lower(),
)
)
def port_dict_to_str(port_desc):
# NOTE: `mode: host|ingress` is ignored
cnt_port = port_desc.get("target", None)
published = port_desc.get("published", None) or ""
host_ip = port_desc.get("host_ip", None)
protocol = port_desc.get("protocol", None) or "tcp"
if not cnt_port:
raise ValueError("target container port must be specified")
if host_ip:
ret = f"{host_ip}:{published}:{cnt_port}"
else:
ret = f"{published}:{cnt_port}" if published else f"{cnt_port}"
if protocol != "tcp":
ret += f"/{protocol}"
return ret
def norm_ports(ports_in):
if not ports_in:
ports_in = []
if isinstance(ports_in, str):
ports_in = [ports_in]
ports_out = []
for port in ports_in:
if isinstance(port, dict):
port = port_dict_to_str(port)
elif isinstance(port, int):
port = str(port)
elif not isinstance(port, str):
raise TypeError("port should be either string or dict")
ports_out.append(port)
return ports_out
def assert_cnt_nets(compose, cnt):
"""
create missing networks
"""
net = cnt.get("network_mode", None)
if net and not net.startswith("bridge"):
return
proj_name = compose.project_name
nets = compose.networks
default_net = compose.default_net
cnt_nets = cnt.get("networks", None)
if cnt_nets and is_dict(cnt_nets):
cnt_nets = list(cnt_nets.keys())
cnt_nets = norm_as_list(cnt_nets or default_net)
for net in cnt_nets:
net_desc = nets[net] or {}
is_ext = net_desc.get("external", None)
ext_desc = is_ext if is_dict(is_ext) else {}
default_net_name = net if is_ext else f"{proj_name}_{net}"
net_name = (
ext_desc.get("name", None) or net_desc.get("name", None) or default_net_name
)
try:
compose.podman.output([], "network", ["exists", net_name])
except subprocess.CalledProcessError as e:
if is_ext:
raise RuntimeError(
f"External network [{net_name}] does not exists"
) from e
args = [
"create",
"--label",
f"io.podman.compose.project={proj_name}",
"--label",
f"com.docker.compose.project={proj_name}",
]
# TODO: add more options here, like dns, ipv6, etc.
labels = net_desc.get("labels", None) or []
for item in norm_as_list(labels):
args.extend(["--label", item])
if net_desc.get("internal", None):
args.append("--internal")
driver = net_desc.get("driver", None)
if driver:
args.extend(("--driver", driver))
driver_opts = net_desc.get("driver_opts", None) or {}
for key, value in driver_opts.items():
args.extend(("--opt", f"{key}={value}"))
ipam = net_desc.get("ipam", None) or {}
ipam_driver = ipam.get("driver", None)
if ipam_driver:
args.extend(("--ipam-driver", ipam_driver))
ipam_config_ls = ipam.get("config", None) or []
if is_dict(ipam_config_ls):
ipam_config_ls = [ipam_config_ls]
for ipam_config in ipam_config_ls:
subnet = ipam_config.get("subnet", None)
ip_range = ipam_config.get("ip_range", None)
gateway = ipam_config.get("gateway", None)
if subnet:
args.extend(("--subnet", subnet))
if ip_range:
args.extend(("--ip-range", ip_range))
if gateway:
args.extend(("--gateway", gateway))
args.append(net_name)
compose.podman.output([], "network", args)
compose.podman.output([], "network", ["exists", net_name])
def get_net_args(compose, cnt):
service_name = cnt["service_name"]
net_args = []
mac_address = cnt.get("mac_address", None)
if mac_address:
net_args.extend(["--mac-address", mac_address])
is_bridge = False
net = cnt.get("network_mode", None)
if net:
if net == "none":
is_bridge = False
elif net == "host":
net_args.extend(["--network", net])
elif net.startswith("slirp4netns:"):
net_args.extend(["--network", net])
elif net.startswith("ns:"):
net_args.extend(["--network", net])
elif net.startswith("service:"):
other_srv = net.split(":", 1)[1].strip()
other_cnt = compose.container_names_by_service[other_srv][0]
net_args.extend(["--network", f"container:{other_cnt}"])
elif net.startswith("container:"):
other_cnt = net.split(":", 1)[1].strip()
net_args.extend(["--network", f"container:{other_cnt}"])
elif net.startswith("bridge"):
is_bridge = True
else:
print(f"unknown network_mode [{net}]")
sys.exit(1)
else:
is_bridge = True
proj_name = compose.project_name
default_net = compose.default_net
nets = compose.networks
cnt_nets = cnt.get("networks", None)
aliases = [service_name]
# NOTE: from podman manpage:
# NOTE: A container will only have access to aliases on the first network
# that it joins. This is a limitation that will be removed in a later
# release.
ip = None
ip6 = None
ip_assignments = 0
if cnt.get("_aliases", None):
aliases.extend(cnt.get("_aliases", None))
if cnt_nets and is_dict(cnt_nets):
prioritized_cnt_nets = []
# cnt_nets is {net_key: net_value, ...}
for net_key, net_value in cnt_nets.items():
net_value = net_value or {}
aliases.extend(norm_as_list(net_value.get("aliases", None)))
if net_value.get("ipv4_address", None) is not None:
ip_assignments = ip_assignments + 1
if net_value.get("ipv6_address", None) is not None:
ip_assignments = ip_assignments + 1
if not ip:
ip = net_value.get("ipv4_address", None)
if not ip6:
ip6 = net_value.get("ipv6_address", None)
net_priority = net_value.get("priority", 0)
prioritized_cnt_nets.append(
(
net_priority,
net_key,
)
)
# sort dict by priority
prioritized_cnt_nets.sort(reverse=True)
cnt_nets = [net_key for _, net_key in prioritized_cnt_nets]
cnt_nets = norm_as_list(cnt_nets or default_net)
net_names = []
for net in cnt_nets:
net_desc = nets[net] or {}
is_ext = net_desc.get("external", None)
ext_desc = is_ext if is_dict(is_ext) else {}
default_net_name = net if is_ext else f"{proj_name}_{net}"
net_name = (
ext_desc.get("name", None) or net_desc.get("name", None) or default_net_name
)
net_names.append(net_name)
net_names_str = ",".join(net_names)
if ip_assignments > 1:
multiple_nets = cnt.get("networks", None)
multiple_net_names = multiple_nets.keys()
for net_ in multiple_net_names:
net_desc = nets[net_] or {}
is_ext = net_desc.get("external", None)
ext_desc = is_ext if is_dict(is_ext) else {}
default_net_name = net_ if is_ext else f"{proj_name}_{net_}"
net_name = (
ext_desc.get("name", None)
or net_desc.get("name", None)
or default_net_name
)
ipv4 = multiple_nets[net_].get("ipv4_address", None)
ipv6 = multiple_nets[net_].get("ipv6_address", None)
if ipv4 is not None and ipv6 is not None:
net_args.extend(["--network", f"{net_name}:ip={ipv4},ip={ipv6}"])
elif ipv4 is None and ipv6 is not None:
net_args.extend(["--network", f"{net_name}:ip={ipv6}"])
elif ipv6 is None and ipv4 is not None:
net_args.extend(["--network", f"{net_name}:ip={ipv4}"])
else:
if is_bridge:
net_args.extend(
["--net", net_names_str, "--network-alias", ",".join(aliases)]
)
if ip:
net_args.append(f"--ip={ip}")
if ip6:
net_args.append(f"--ip6={ip6}")
return net_args
def container_to_args(compose, cnt, detached=True):
# TODO: double check -e , --add-host, -v, --read-only
dirname = compose.dirname
pod = cnt.get("pod", None) or ""
name = cnt["name"]
podman_args = [f"--name={name}"]
if detached:
podman_args.append("-d")
if pod:
podman_args.append(f"--pod={pod}")
deps = []
for dep_srv in cnt.get("_deps", None) or []:
deps.extend(compose.container_names_by_service.get(dep_srv, None) or [])
if deps:
deps_csv = ",".join(deps)
podman_args.append(f"--requires={deps_csv}")
sec = norm_as_list(cnt.get("security_opt", None))
for sec_item in sec:
podman_args.extend(["--security-opt", sec_item])
ann = norm_as_list(cnt.get("annotations", None))
for a in ann:
podman_args.extend(["--annotation", a])
if cnt.get("read_only", None):
podman_args.append("--read-only")
for i in cnt.get("labels", []):
podman_args.extend(["--label", i])
for c in cnt.get("cap_add", []):
podman_args.extend(["--cap-add", c])
for c in cnt.get("cap_drop", []):
podman_args.extend(["--cap-drop", c])
for item in cnt.get("group_add", []):
podman_args.extend(["--group-add", item])
for item in cnt.get("devices", []):
podman_args.extend(["--device", item])
for item in norm_as_list(cnt.get("dns", None)):
podman_args.extend(["--dns", item])
for item in norm_as_list(cnt.get("dns_opt", None)):
podman_args.extend(["--dns-opt", item])
for item in norm_as_list(cnt.get("dns_search", None)):
podman_args.extend(["--dns-search", item])
env_file = cnt.get("env_file", [])
if is_str(env_file):
env_file = [env_file]
for i in env_file:
i = os.path.realpath(os.path.join(dirname, i))
podman_args.extend(["--env-file", i])
env = norm_as_list(cnt.get("environment", {}))
for e in env:
podman_args.extend(["-e", e])
tmpfs_ls = cnt.get("tmpfs", [])
if is_str(tmpfs_ls):
tmpfs_ls = [tmpfs_ls]
for i in tmpfs_ls:
podman_args.extend(["--tmpfs", i])
for volume in cnt.get("volumes", []):
podman_args.extend(get_mount_args(compose, cnt, volume))
assert_cnt_nets(compose, cnt)
podman_args.extend(get_net_args(compose, cnt))
logging = cnt.get("logging", None)
if logging is not None:
podman_args.append(f'--log-driver={logging.get("driver", "k8s-file")}')
log_opts = logging.get("options") or {}
podman_args += [f"--log-opt={name}={value}" for name, value in log_opts.items()]
for secret in cnt.get("secrets", []):
podman_args.extend(get_secret_args(compose, cnt, secret))
for i in cnt.get("extra_hosts", []):
podman_args.extend(["--add-host", i])
for i in cnt.get("expose", []):
podman_args.extend(["--expose", i])
if cnt.get("publishall", None):
podman_args.append("-P")
ports = cnt.get("ports", None) or []
if isinstance(ports, str):
ports = [ports]
for port in ports:
if isinstance(port, dict):
port = port_dict_to_str(port)
elif not isinstance(port, str):
raise TypeError("port should be either string or dict")
podman_args.extend(["-p", port])
userns_mode = cnt.get("userns_mode", None)
if userns_mode is not None:
podman_args.extend(["--userns", userns_mode])
user = cnt.get("user", None)
if user is not None:
podman_args.extend(["-u", user])
if cnt.get("working_dir", None) is not None:
podman_args.extend(["-w", cnt["working_dir"]])
if cnt.get("hostname", None):
podman_args.extend(["--hostname", cnt["hostname"]])
if cnt.get("shm_size", None):
podman_args.extend(["--shm-size", str(cnt["shm_size"])])