This repository has been archived by the owner on Oct 10, 2020. It is now read-only.
/
syscontainers.py
2733 lines (2325 loc) · 112 KB
/
syscontainers.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
import os
import sys
import json
from . import util
import tempfile
import tarfile
from string import Template
import calendar
import shutil
import stat # pylint: disable=bad-python3-import
import subprocess
import time
import errno
from .client import AtomicDocker
from Atomic.backends._docker_errors import NoDockerDaemon
from ctypes import cdll, CDLL
import uuid
from .rpm_host_install import RPMHostInstall, RPM_NAME_PREFIX
import __main__
import selinux
try:
import gi
try:
gi.require_version('OSTree', '1.0')
from gi.repository import Gio, GLib, OSTree # pylint: disable=no-name-in-module
OSTREE_PRESENT = True
except ValueError:
OSTREE_PRESENT = False
except ImportError:
OSTREE_PRESENT = False
try:
from subprocess import DEVNULL # pylint: disable=no-name-in-module
except ImportError:
DEVNULL = open(os.devnull, 'wb')
HOME = os.path.expanduser("~")
ATOMIC_LIBEXEC = os.environ.get('ATOMIC_LIBEXEC', '/usr/libexec/atomic')
ATOMIC_VAR = '/var/lib/containers/atomic'
ATOMIC_USR = '/usr/lib/containers/atomic'
ATOMIC_VAR_USER = "%s/.containers/atomic" % HOME
OSTREE_OCIIMAGE_PREFIX = "ociimage/"
SYSTEMD_UNIT_FILES_DEST = "/etc/systemd/system"
SYSTEMD_UNIT_FILES_DEST_USER = "%s/.config/systemd/user" % HOME
SYSTEMD_TMPFILES_DEST = "/etc/tmpfiles.d"
SYSTEMD_TMPFILES_DEST_USER = "%s/.containers/tmpfiles" % HOME
SYSTEMD_UNIT_FILES_DEST_PREFIX = "%s/usr/lib/systemd/system"
SYSTEMD_TMPFILES_DEST_PREFIX = "%s/usr/lib/tmpfiles.d"
SYSTEMD_UNIT_FILE_DEFAULT_TEMPLATE = """
[Unit]
Description=$NAME
[Service]
ExecStartPre=$EXEC_STARTPRE
ExecStart=$EXEC_START
ExecStop=$EXEC_STOP
ExecStopPost=$EXEC_STOPPOST
Restart=on-failure
WorkingDirectory=$DESTDIR
PIDFile=$PIDFILE
[Install]
WantedBy=multi-user.target
"""
TEMPLATE_FORCED_VARIABLES = ["DESTDIR", "NAME", "EXEC_START", "EXEC_STOP",
"EXEC_STARTPRE", "EXEC_STOPPOST", "HOST_UID",
"HOST_GID", "IMAGE_ID", "IMAGE_NAME"]
TEMPLATE_OVERRIDABLE_VARIABLES = ["RUN_DIRECTORY", "STATE_DIRECTORY", "CONF_DIRECTORY", "UUID", "PIDFILE",
"ALL_PROCESS_CAPABILITIES"]
class SystemContainers(object):
(CHECKOUT_MODE_INSTALL, CHECKOUT_MODE_UPGRADE, CHECKOUT_MODE_UPGRADE_CONTROLLED) = range(3)
"""
Provides an interface for manipulating system containers.
"""
def __init__(self):
"""
Initializes a new instance of the SystemContainers class.
"""
self.atomic_config = util.get_atomic_config()
self.backend = None
self.user = util.is_user_mode()
self.args = None
self.setvalues = None
self.display = False
self.runtime = None
self._repo_location = None
self._runtime_from_info_file = None
def get_atomic_config_item(self, config_item):
"""
Returns a specific configuration item from the atomic configuration file.
:param config_item: Items to retrieve from the config.
:type config_item: list
:rtype: mixed
"""
return util.get_atomic_config_item(config_item, atomic_config=self.atomic_config)
def _do_syncfs(self, rootfs, rootfs_fd):
# Fallback to sync --file-system if loading it from libc fails.
try:
cdll.LoadLibrary("libc.so.6")
libc = CDLL("libc.so.6")
if libc.syncfs(rootfs_fd) == 0:
return
except (NameError, AttributeError, OSError):
pass
util.check_call(["sync", "--file-system", rootfs], stdin=DEVNULL,
stdout=DEVNULL,
stderr=DEVNULL)
@property
def available(self):
return OSTREE_PRESENT
def _checkout_layer(self, repo, rootfs_fd, rootfs, rev):
options = OSTree.RepoCheckoutAtOptions() # pylint: disable=no-member
options.overwrite_mode = OSTree.RepoCheckoutOverwriteMode.UNION_FILES
options.process_whiteouts = True
options.disable_fsync = True
options.no_copy_fallback = True
if self.user:
options.mode = OSTree.RepoCheckoutMode.USER
repo.checkout_at(options, rootfs_fd, rootfs, rev)
def set_args(self, args):
"""
Sets arguments used by other methods. Generally populated via CLI.
:param args: Argument instance
:type args: argparse.Namespace or object
"""
self.args = args
try:
self.backend = args.backend
except (NameError, AttributeError):
self.backend = None
if not self.backend:
self.backend = self.get_atomic_config_item(["default_storage"]) or "ostree"
try:
self.display = self.args.display
except (NameError, AttributeError):
pass
try:
self.setvalues = args.setvalues
except (NameError, AttributeError):
pass
try:
self.runtime = self.args.runtime
except (NameError, AttributeError):
pass
if not self.user and not self.runtime:
self.runtime = self.get_atomic_config_item(["runtime"])
@staticmethod
def _split_set_args(setvalues):
values = {}
for i in setvalues:
split = i.find("=")
if split < 0:
raise ValueError("Invalid value '%s'. Expected form NAME=VALUE" % i)
key, val = i[:split], i[split+1:]
values[key] = val
return values
def _pull_image_to_ostree(self, repo, image, upgrade, src_creds=None):
if not repo:
raise ValueError("Cannot find a configured OSTree repo")
if image.startswith("ostree:") and image.count(':') > 1:
self._check_system_ostree_image(repo, image, upgrade)
elif image.startswith("docker:") and image.count(':') > 1:
image = self._pull_docker_image(repo, image.replace("docker:", "", 1))
elif image.startswith("dockertar:/"):
tarpath = image.replace("dockertar:/", "", 1)
image = self._pull_docker_tar(repo, tarpath, os.path.basename(tarpath).replace(".tar", ""))
else: # Assume "oci:"
self._check_system_oci_image(repo, image, upgrade, src_creds=src_creds)
return image
def pull_image(self, image=None, **kwargs):
"""
Public method for pulling an image from an external location into ostree.
:param image: Name of the image to pull. If not provided self.args.image is used.
:type image: str or None
:param kwargs: Arguments to pass to the pull
:type kwargs: dict or None
"""
src_creds = kwargs.get('src_creds')
self._pull_image_to_ostree(self._get_ostree_repo(), image or self.args.image, True, src_creds=src_creds)
def install_user_container(self, image, name):
"""
Installs a new user container.
:param image: Name of the image to use to create the new user container.
:type image: str
:param name: The name to call the new user container.
:type name: str
:returns: Shell call result from self.install()
:rtype: int
"""
try:
runtime = self._get_oci_runtime()
util.check_call([runtime, "--version"], stdout=DEVNULL)
except util.FileNotFound:
raise ValueError("Cannot install the container: the runtime {} is not installed".format(runtime))
if not "--user" in str(util.check_output(["systemctl", "--help"], stdin=DEVNULL, stderr=DEVNULL)):
raise ValueError("Cannot install the container: systemctl does not support --user")
# Same entrypoint
return self.install(image, name)
def _create_rootfs(self, rootfs):
"""
Ensure the rootfs directory exists and it has the correct SELinux label.
"""
if os.getuid() == 0 and selinux.is_selinux_enabled() != 0:
label = selinux.getfilecon("/")[1]
selinux.setfscreatecon_raw(label)
try:
os.makedirs(rootfs)
finally:
selinux.setfscreatecon_raw(None)
def build_rpm(self, repo, name, image, values, destination):
"""
Create a checkout and generate an RPM file
:param repo: OSTree repo used to checkout contents.
:type repo: OSTree.Repo
:param name: Name of the container to use when building.
:type name: str
:param image: Name of the image to build the container and rpm from.
:type image: str
:param values: Values to be used when expanding templates.
:type values: dict
:param destination: Location on disk to place the generated rpm.
:type destination: str
:returns: The path to the new rpm or None
:rtype: str or None
"""
installed_files = None
temp_dir = tempfile.mkdtemp()
rpm_content = os.path.join(temp_dir, "rpmroot")
rootfs = os.path.join(rpm_content, "usr/lib/containers/atomic", name)
self._create_rootfs(rootfs)
try:
self._checkout_wrapper(repo, name, image, 0, SystemContainers.CHECKOUT_MODE_INSTALL, values=values, destination=rootfs, prefix=rpm_content)
if self.display:
return None
img = self.inspect_system_image(image)
if installed_files is None:
with open(os.path.join(rootfs, "info"), "r") as info_file:
info = json.loads(info_file.read())
installed_files = info["installed-files"] if "installed-files" in info else None
image_id = img["ImageId"]
labels = {k.lower() : v for k, v in img.get('Labels', {}).items()}
ret = RPMHostInstall.generate_rpm_from_rootfs(rootfs, temp_dir, name, image_id, labels, True, installed_files=installed_files, display=self.display)
if ret:
rpm_built = RPMHostInstall.find_rpm(ret)
generated_rpm = os.path.join(destination, os.path.basename(rpm_built))
shutil.move(rpm_built, generated_rpm)
return generated_rpm
finally:
shutil.rmtree(temp_dir)
return None
@staticmethod
def _gather_installed_files_info (checkout, name):
"""
Get the corresponding fields from info file based on the container name
:param checkout: path for checkout
:param name: name for the container
:returns: info object, rpm_installed field value, installed_files_checksum field value
"""
with open(os.path.join(checkout, name, "info"), "r") as info_file:
info = json.loads(info_file.read())
rpm_installed = info["rpm-installed"] if "rpm-installed" in info else None
installed_files_checksum = info["installed-files-checksum"] if "installed-files-checksum" in info else None
if installed_files_checksum is None:
installed_files = info["installed-files"] if "installed-files" in info else None
installed_files_checksum = {k : "" for k in installed_files}
return info, rpm_installed, installed_files_checksum
@staticmethod
def _get_remote_location(remote_input):
"""
Parse the remote input and return actual remote path
:param remote_input: input path from user
:returns: the parsed remote location
"""
if not remote_input:
return None
remote_path = os.path.realpath(remote_input)
if not os.path.exists(remote_path):
raise ValueError("The container's rootfs is set to remote, but the remote rootfs does not exist")
# Here we know remote path does exist on the fs
remote_rootfs = os.path.sep.join([remote_path, "rootfs"])
if os.path.exists(remote_rootfs):
util.write_out("The remote rootfs for this container is set to be {}".format(remote_rootfs))
elif os.path.exists(os.path.sep.join([remote_path, "usr"])): # Assume that the user directly gave the location of the rootfs
remote_path = os.path.dirname(remote_path) # Use the parent directory as the "container location"
else:
raise ValueError("--remote was specified but the given location does not contain a rootfs")
return remote_path
@staticmethod
def _rewrite_rootfs(destination, remote_rootfs):
"""
When remote rootfs is specified, we rewrite the ['root']['path']
:param destination: the destination of the container
:param remote_rootfs: remote rootfs location
"""
destination_path = os.path.join(destination, "config.json")
with open(destination_path, 'r') as config_file:
try:
config = json.loads(config_file.read())
except ValueError:
raise ValueError("Invalid config.json file in given remote location: {}.".format(destination_path))
config['root']['path'] = remote_rootfs
with open(destination_path, 'w') as config_file:
config_file.write(json.dumps(config, indent=4))
# create a symlink to the real rootfs, so that it is possible
# to access the rootfs in the same way as in the not --remote case.
os.symlink(remote_rootfs, os.path.join(destination, "rootfs"))
def _prepare_rootfs_dirs(self, remote_path, destination, extract_only=False):
"""
Generate rootfs path based on user inputs and make directories accordingly
:param remote_path: path for remote
:param destination: the destination location for a container
:param extract_only: if specified, only image layers will be checked out to destination
"""
if extract_only:
rootfs = destination
elif remote_path:
rootfs = os.path.join(remote_path, "rootfs")
else:
destination = self._canonicalize_location(destination)
rootfs = os.path.join(destination, "rootfs")
if remote_path:
if not os.path.exists(destination):
os.makedirs(destination)
else:
if not os.path.exists(rootfs):
self._create_rootfs(rootfs)
return rootfs
def _write_config_to_dest(self, destination, exports_dir, values=None):
"""
Write config.json based on user specified directories and the corresponding values
Note: we also assume the destination directory are existant/made before calling this function
:param destination: destination location for the container that will be containing config.json file
:param exports_dir: the directory user specified that is going to copy to the host
:values: values to substitute when the config template exist
"""
src = os.path.join(exports_dir, "config.json")
destination_config = os.path.join(destination, "config.json")
src_config_template = src + ".template"
# Check for config.json in exports (user defined) directory
if os.path.exists(src):
shutil.copy(src, destination_config)
# Else, if we have a template, populate it
elif os.path.exists(src_config_template):
with open(src_config_template, 'r') as infile:
util.write_template(src_config_template, infile.read(), values, destination_config)
# Otherwise, use a default one
else:
self._generate_default_oci_configuration(destination)
@staticmethod
def _get_manifest_attributes(manifest, attr_name, default_value):
"""
Collects corresponding information from manifest file
based on attribtue name
:returns attribtues' corresponding value if it does exist
else returns a default value that is predefined
"""
if manifest is not None and attr_name in manifest:
return manifest[attr_name]
return default_value
def _upgrade_tempfiles_clean(self, manifest, options, was_service_active):
"""
When upgrading a container, we stop the service and remove previously
installed tmpfiles, before restarting the service
:param manifest: dictionary loaded from manifest json file
:param options: a dictionary which contains user input collectively
:param was_service_active: a boolean to indicate whether the container service was active
"""
# The thought process here might be a bit tricky. When noContainerService is true, has_container_service
# will have the opposite value. Thus goes with the 'not' sign. Then because of the 'not', the default return
# value when noContainerService is not present should be False so that has_container_service will have
# a default value of True
has_container_service = not(SystemContainers._get_manifest_attributes(manifest, "noContainerService", False))
if has_container_service and options["upgrade_mode"] != SystemContainers.CHECKOUT_MODE_INSTALL:
if was_service_active:
self._systemctl_command("stop", options["name"])
if os.path.exists(options["tmpfilesout"]):
try:
self._systemd_tmpfiles("--remove", options["tmpfilesout"])
except subprocess.CalledProcessError:
pass
def _update_rename_file_value(self, manifest, values):
"""
Substitute entries from rename_files content in manifest by the generated input values
:param manifest: dictionary loaded from manifest json file
:param values: the generated input values
"""
rename_files = SystemContainers._get_manifest_attributes(manifest, "renameFiles", {})
if rename_files:
for k, v in rename_files.items():
template = Template(v)
try:
new_v = template.substitute(values)
except KeyError as e:
raise ValueError("The template file 'manifest.json' still contains an unreplaced value for: '%s'" % \
(str(e)))
rename_files[k] = new_v
def _handle_system_package_files(self, options, manifest, exports):
"""
Based on user specified 'system-package' info, Check if an rpm can be generated from /exports,
if not, then we remove the old files installed and copy the new files from /exports/hostfs/xxxxx
:param manifest: dictionary loaded from manifest json file
:param exports: the export directory
:param options: a dictionary which contains input from users collectively
"""
installed_files_template = SystemContainers._get_manifest_attributes(manifest, "installedFilesTemplate", [])
rename_files = SystemContainers._get_manifest_attributes(manifest, "renameFiles", {})
use_links = SystemContainers._get_manifest_attributes(manifest, "useLinks", True)
# let's check if we can generate an rpm from the /exports directory
rpm_file = rpm_installed = None
if options["system_package"] == 'yes':
img_obj = self.inspect_system_image(options["img"])
image_id = img_obj["ImageId"]
labels = {k.lower() : v for k, v in img_obj.get('Labels', {}).items()}
(rpm_installed, rpm_file, _) = RPMHostInstall.generate_rpm(options["name"], image_id, labels, exports, options["destination"], values=options["values"], installed_files_template=installed_files_template, rename_files=rename_files, defaultversion=options["deployment"])
if rpm_installed or options["system_package"] == 'absent':
new_installed_files_checksum = {}
else:
new_installed_files_checksum = RPMHostInstall.rm_add_files_to_host(options["installed_files_checksum"], exports, options["prefix"] or "/", files_template=installed_files_template, values=options["values"], rename_files=rename_files, use_links=use_links)
new_installed_files = list(new_installed_files_checksum.keys())
# Here, we pack the created attributes into a dictionary
rpm_install_content = {"new_installed_files" : new_installed_files,
"new_installed_files_checksum" : new_installed_files_checksum,
"rpm_installed" : rpm_installed,
"rpm_file" : rpm_file}
return rpm_install_content
def _write_info_file(self, options, manifest, rpm_install_content, image_id, rev):
"""
Based on the information collected before in '_do_checkout' function, we collect and write this
information in json format into a info file at the container location
:param options: a dictionary which contains user's input collectively
:param manifest: dictionary loaded from manifest json file
:param rpm_install_content: a dictionary collected after handling system_package related actions
:param image_id: the id of the image
:param rev: the refspec of the corresponding image
"""
installed_files_template = SystemContainers._get_manifest_attributes(manifest, "installedFilesTemplate", [])
rename_files = SystemContainers._get_manifest_attributes(manifest, "renameFiles", {})
has_container_service = not(SystemContainers._get_manifest_attributes(manifest, "noContainerService", False))
use_links = SystemContainers._get_manifest_attributes(manifest, "useLinks", True)
try:
with open(os.path.join(options["destination"], "info"), 'w') as info_file:
info = {"image" : options["img"],
"revision" : image_id,
"ostree-commit": rev,
'created' : calendar.timegm(time.gmtime()),
"values" : options["values"],
"has-container-service" : has_container_service,
"installed-files": rpm_install_content["new_installed_files"],
"installed-files-checksum": rpm_install_content["new_installed_files_checksum"],
"installed-files-template": installed_files_template,
"rename-installed-files" : rename_files,
"rpm-installed" : rpm_install_content["rpm_installed"],
"system-package" : options["system_package"],
"remote" : options["remote"],
"use-links" : use_links,
"runtime" : self._get_oci_runtime()}
info_file.write(json.dumps(info, indent=4))
info_file.write("\n")
except (NameError, AttributeError, OSError, IOError) as e:
for i in rpm_install_content["new_installed_files"]:
os.remove(os.path.join(options["prefix"] or "/", os.path.relpath(i, "/")))
raise e
@staticmethod
def _get_manifest_json(manifest_dir, image):
manifest_file = os.path.join(manifest_dir, "manifest.json")
manifest = None
if os.path.exists(manifest_file):
with open(manifest_file, "r") as f:
try:
manifest = json.loads(f.read())
except ValueError:
raise ValueError("Invalid manifest.json file in image: {}.".format(image))
return manifest
def install(self, image, name):
"""
External container install logic.
:param image: The name of the image
:type image: str
:param name: The name of the checkout
:type name: str
:returns: Shell call result
:rtype: int
"""
return_value = None
try:
runtime = self._get_oci_runtime()
util.check_call([runtime, "--version"], stdout=DEVNULL)
except util.FileNotFound:
raise ValueError("Cannot install the container: the runtime {} is not installed".format(runtime))
# If we don't have a dockertar file or a reference to a docker engine image
if not image.startswith('dockertar:/') and not (image.startswith("docker:") and image.count(':') > 1):
image = util.remove_skopeo_prefixes(image)
labels = self.inspect_system_image(image).get('Labels', {})
# And we have a run-once label
if labels and labels.get('atomic.run') == 'once':
# Execute the _run_once method and set the return_value
return_value = self._run_once(image, name)
# If we don't have a return_value then use the traditional install
if return_value is None:
return_value = self._install(image, name)
# Return
return return_value
def _run_once(self, image, name, args=None):
"""
Runs the container once and then removes it.
:param image: The name of the image
:type image: str
:param name: The name of the checkout
:type name: str
:returns: Shell call result
:rtype: int
"""
# Create a temporary directory to house the oneshot container
base_dir = os.path.join(self.get_ostree_repo_location(), "tmp/atomic-container", str(os.getpid()))
tmpfiles_destination = None
mounted_from_storage = False
try:
rootfs = os.path.sep.join([base_dir, 'rootfs'])
self._create_rootfs(rootfs)
try:
upperdir = os.path.sep.join([base_dir, 'upperdir'])
workdir = os.path.sep.join([base_dir, 'workdir'])
for i in [upperdir, workdir]:
os.makedirs(i)
self.mount_from_storage(image, rootfs, upperdir, workdir)
mounted_from_storage = True
except (subprocess.CalledProcessError, ValueError):
# Extract the image to a temp directory.
self.extract(image, rootfs)
# This part should be shared with install.
values = {}
if self.args.setvalues is not None:
setvalues = SystemContainers._split_set_args(self.args.setvalues)
for k, v in setvalues.items():
values[k] = v
exports = os.path.sep.join([rootfs, 'exports'])
manifest = SystemContainers._get_manifest_json(exports, image)
# if we got here, we know there is one image
repo = self._get_ostree_repo()
imgs = self._resolve_image(repo, image)
_, rev = imgs[0]
image_manifest = self._image_manifest(repo, rev)
image_id = rev
if image_manifest:
image_manifest = json.loads(image_manifest)
image_id = SystemContainers._get_image_id(repo, rev, image_manifest) or image_id
self._amend_values(values, manifest, name, image, image_id, base_dir)
self._write_config_to_dest(base_dir, exports, values)
if args is not None:
conf_file = os.path.sep.join([base_dir, "config.json"])
tty = os.isatty(0)
self._rewrite_config_args(conf_file, conf_file, args, tty=tty)
template_tmpfiles = os.path.sep.join([rootfs, 'exports', 'tmpfiles.template'])
# If we have a tmpfiles template, populate it
if os.path.exists(template_tmpfiles):
with open(template_tmpfiles, 'r') as infile:
tmp = os.path.sep.join([base_dir, 'tmpfiles.conf'])
util.write_template(template_tmpfiles, infile.read(), values, tmp)
self._systemd_tmpfiles("--create", tmp, quiet=True)
tmpfiles_destination = tmp
# Get the start command for the system container
(start_command, _, _, _) = self._generate_systemd_startstop_directives(name, unit_file_support_pidfile=False)
# Move to the base directory to start the system container
os.chdir(base_dir)
# ... and run it. We use call() because the actual
# run may be expected to fail.
return util.call(start_command)
finally:
if tmpfiles_destination:
try:
self._systemd_tmpfiles("--remove", tmpfiles_destination, quiet=True)
except subprocess.CalledProcessError:
pass
# Remove the temporary checkout
if mounted_from_storage:
util.call("umount %s" % rootfs)
shutil.rmtree(base_dir)
def _install(self, image, name):
"""
Internal container install logic.
"""
repo = self._get_ostree_repo()
if not repo:
raise ValueError("Cannot find a configured OSTree repo")
if self.args.system and self.user:
raise ValueError("Only root can use --system")
accepted_system_package_values = ['auto', 'build', 'no', 'yes']
if self.args.system_package not in accepted_system_package_values:
raise ValueError("Invalid --system-package mode. Accepted values: '%s'" % "', '".join(accepted_system_package_values))
if self.get_checkout(name):
util.write_out("%s already present" % (name))
return
image = self._pull_image_to_ostree(repo, image, False)
if self.args.system_package == 'auto' and self.user:
self.args.system_package = 'absent'
if self.args.system_package in ['build'] and not self.args.system:
raise ValueError("Only --system can generate rpms")
values = {}
if self.args.setvalues is not None:
setvalues = SystemContainers._split_set_args(self.args.setvalues)
for k, v in setvalues.items():
values[k] = v
if self.args.system_package == 'build':
destination = self.build_rpm(repo, name, image, values, os.getcwd())
if destination:
util.write_out("Generated rpm %s" % destination)
return False
self._checkout_wrapper(repo, name, image, 0, SystemContainers.CHECKOUT_MODE_INSTALL, values=values, remote=self.args.remote, system_package=self.args.system_package)
def _check_oci_configuration_file(self, conf_dir_path, remote=None, include_all=False):
conf_path = os.path.join(conf_dir_path, "config.json")
with open(conf_path, 'r') as conf:
try:
configuration = json.loads(conf.read())
except ValueError:
raise ValueError("Invalid json in configuration file: {}.".format(conf_path))
# empty file, nothing to do here
if len(configuration) == 0:
return []
if not 'root' in configuration or \
not 'readonly' in configuration['root'] or \
not configuration['root']['readonly']:
raise ValueError("Invalid configuration file. Only readonly images are supported")
if configuration['root']['path'] != 'rootfs' and not remote:
raise ValueError("Invalid configuration file. Path must be 'rootfs'")
missing_source_paths = []
# Ensure that the source path specified in bind/rbind exists
if "mounts" in configuration:
for mount in configuration["mounts"]:
if not "type" in mount:
continue
if "source" in mount and "bind" in mount["type"]:
source = mount["source"]
if include_all or not os.path.exists(source):
missing_source_paths.append(source)
return missing_source_paths
def _generate_default_oci_configuration(self, destination):
conf_path = os.path.join(destination, "config.json")
try:
# Try to use $RUNTIME spec to generate a default configuration file.
args = [self._get_oci_runtime(), 'spec']
util.subp(args, cwd=destination)
with open(conf_path, 'r') as conf:
configuration = json.loads(conf.read())
configuration['root']['readonly'] = True
configuration['root']['path'] = 'rootfs'
configuration['process']['terminal'] = False
configuration['process']['args'] = ['run.sh']
with open(conf_path, 'w') as conf:
conf.write(json.dumps(configuration, indent=4))
return
except: #pylint: disable=bare-except
pass
# If we got here it means an error happened before, so create an empty file.
with open(conf_path, 'w') as conf:
conf.write('{}')
def _get_oci_runtime(self):
if self.runtime:
return self.runtime
if self._runtime_from_info_file:
return self._runtime_from_info_file
if self.user:
return util.BWRAP_OCI_PATH
return util.RUNC_PATH
def _generate_systemd_startstop_directives(self, name, pidfile=None, unit_file_support_pidfile=False):
runtime = self._get_oci_runtime()
return self._generate_systemd_runtime_startstop_directives(name, runtime, pidfile=pidfile, unit_file_support_pidfile=unit_file_support_pidfile)
def _generate_systemd_runtime_startstop_directives(self, name, runtime, pidfile=None, unit_file_support_pidfile=False):
runtime_has_pidfile = "--pid-file" in str(util.check_output([runtime, "run", "--help"], stderr=DEVNULL))
systemd_cgroup = " --systemd-cgroup" if "--systemd-cgroup" in str(util.check_output([runtime, "--help"], stderr=DEVNULL)) else ""
if unit_file_support_pidfile and runtime_has_pidfile:
start = "{} {} run -d --pid-file {} '{}'".format(runtime, systemd_cgroup, pidfile, name)
stoppost = "{} delete '{}'".format(runtime, name)
return [start, "", "", stoppost]
else:
commands = ["run", "kill"]
return ["{}{} {} '{}'".format(runtime, systemd_cgroup, command, name) for command in commands] + ["", ""]
def _get_systemd_destination_files(self, name, prefix=None):
if self.user:
unitfileout = os.path.join(SYSTEMD_UNIT_FILES_DEST_USER, "%s.service" % name)
tmpfilesout = os.path.join(SYSTEMD_TMPFILES_DEST_USER, "%s.conf" % name)
else:
if prefix:
unitfileout = os.path.join(SYSTEMD_UNIT_FILES_DEST_PREFIX % prefix, "%s.service" % name)
tmpfilesout = os.path.join(SYSTEMD_TMPFILES_DEST_PREFIX % prefix, "%s.conf" % name)
else:
unitfileout = os.path.join(SYSTEMD_UNIT_FILES_DEST, "%s.service" % name)
tmpfilesout = os.path.join(SYSTEMD_TMPFILES_DEST, "%s.conf" % name)
return unitfileout, tmpfilesout
def _checkout_wrapper(self, repo, name, img, deployment, mode, values=None, destination=None, extract_only=False, remote=None, prefix=None, installed_files_checksum=None, system_package='no'):
"""
Wrapper function that groups parameters into a dictionary for better readbility
returns the same result that _checkout returns
"""
options = {"name" : name,
"img" : img,
"deployment" : deployment,
"upgrade_mode" : mode,
"values" : values,
"destination" : destination,
"extract_only" : extract_only,
"remote" : remote,
"prefix" : prefix,
"installed_files_checksum" : installed_files_checksum,
"system_package" : system_package}
return self._checkout(repo, options)
def _checkout(self, repo, options):
options["destination"] = options["destination"] or os.path.join(self._get_system_checkout_path(), "{}.{}".format(options["name"], options["deployment"]))
unitfileout, tmpfilesout = self._get_systemd_destination_files(options["name"], options["prefix"])
options["unitfileout"] = unitfileout
options["tmpfilesout"] = tmpfilesout
install_mode = options["upgrade_mode"] == SystemContainers.CHECKOUT_MODE_INSTALL
if install_mode:
for f in [unitfileout, tmpfilesout]:
if os.path.exists(f):
raise ValueError("The file %s already exists." % f)
try:
return self._do_checkout(repo, options)
except (GLib.Error, ValueError, OSError, subprocess.CalledProcessError, KeyboardInterrupt) as e:
if not options["extract_only"] and install_mode:
try:
shutil.rmtree(options["destination"])
except OSError:
pass
try:
os.unlink(unitfileout)
except OSError:
pass
try:
os.unlink(tmpfilesout)
except OSError:
pass
raise e
@staticmethod
def _template_support_pidfile(template):
return "$EXEC_STOPPOST" in template and "$PIDFILE" in template
@staticmethod
def _get_image_id(repo, rev, image_manifest):
# Allow to override the image id read from the manifest so that
# we can test atomic updates even though the image itself was not
# changed. This must be used only for tests.
if os.environ.get("ATOMIC_OSTREE_TEST_FORCE_IMAGE_ID"):
return os.environ.get("ATOMIC_OSTREE_TEST_FORCE_IMAGE_ID")
digest = SystemContainers._get_commit_metadata(repo, rev, "docker.digest")
if digest is not None:
return SystemContainers._drop_sha256_prefix(digest)
if 'Digest' in image_manifest:
image_id = image_manifest['Digest']
elif 'config' in image_manifest and 'digest' in image_manifest['config']:
image_id = image_manifest['config']['digest']
else:
return None
return SystemContainers._drop_sha256_prefix(image_id)
# Accept both name and version Id, and return the ostree rev
def _resolve_image(self, repo, img, allow_multiple=False):
img = util.remove_skopeo_prefixes(img)
imagebranch = SystemContainers._get_ostree_image_branch(img)
rev = repo.resolve_rev(imagebranch, True)[1]
if rev:
return [(imagebranch, rev)]
# if we could not find an image with the specified name, check if it is the prefix
# of an ID, and allow it only for tagged images.
if not str.isalnum(str(img)):
return None
tagged_images = [i for i in self.get_system_images(get_all=True, repo=repo) if i['RepoTags']]
matches = [i for i in tagged_images if i['ImageId'].startswith(img)]
if len(matches) == 0:
return None
if len(matches) > 1 and not allow_multiple:
# more than one match, error out
raise ValueError("more images matching prefix `%s`" % img)
# only one image, use it
def get_image(i):
repotag = i['RepoTags'][0]
if repotag == '<none>':
imagebranch = "%s%s" % (OSTREE_OCIIMAGE_PREFIX, i['Id'])
else:
imagebranch = "%s%s" % (OSTREE_OCIIMAGE_PREFIX, SystemContainers._encode_to_ostree_ref(repotag))
return imagebranch, i['OSTree-rev']
return [get_image(i) for i in matches]
def _should_be_installed_rpm(self, exports):
if os.path.exists("/run/ostree-booted"):
return False
for i in ["rpm.spec", "rpm.spec.template", "hostfs"]:
if os.path.exists(os.path.join(exports, i)):
return True
return False
@staticmethod
def _get_all_capabilities():
all_caps = util.get_all_known_process_capabilities()
return ",\n".join(['"%s"' % i for i in all_caps]) + "\n"
def _amend_values(self, values, manifest, name, image, image_id, destination, prefix=None, unit_file_support_pidfile=False):
# When installing a new system container, set values in this order:
#
# 1) What comes from manifest.json, if present, as default value.
# 2) What the user sets explictly as --set
# 3) Values for DESTDIR and NAME
if "RUN_DIRECTORY" not in values:
if self.user:
values["RUN_DIRECTORY"] = os.environ.get("XDG_RUNTIME_DIR", "/run/user/%s" % (os.getuid()))
else:
values["RUN_DIRECTORY"] = "/run"
if "PIDFILE" not in values:
values["PIDFILE"] = os.path.sep.join([values["RUN_DIRECTORY"], "container-{}.pid".format(name)])
if "CONF_DIRECTORY" not in values:
if self.user:
values["CONF_DIRECTORY"] = os.path.join(HOME, ".config")
else:
values["CONF_DIRECTORY"] = "/etc"
if "STATE_DIRECTORY" not in values:
if self.user:
values["STATE_DIRECTORY"] = os.path.join(HOME, ".data")
else:
values["STATE_DIRECTORY"] = "/var/lib"
if "ALL_PROCESS_CAPABILITIES" not in values:
values["ALL_PROCESS_CAPABILITIES"] = SystemContainers._get_all_capabilities()
if 'RUNTIME' not in values:
values["RUNTIME"] = self._get_oci_runtime()
if 'ATOMIC' not in values:
values["ATOMIC"] = os.path.abspath(__main__.__file__)
if manifest is not None and "defaultValues" in manifest:
for key, val in manifest["defaultValues"].items():
if key not in values:
values[key] = val
if "UUID" not in values:
values["UUID"] = str(uuid.uuid4())
values["DESTDIR"] = os.path.join("/", os.path.relpath(destination, prefix)) if prefix else destination
values["NAME"] = name
directives = self._generate_systemd_startstop_directives(name, pidfile=values["PIDFILE"], unit_file_support_pidfile=unit_file_support_pidfile)
values["EXEC_START"], values["EXEC_STOP"], values["EXEC_STARTPRE"], values["EXEC_STOPPOST"] = directives
values["HOST_UID"] = os.getuid()
values["HOST_GID"] = os.getgid()
values["IMAGE_NAME"] = image
values["IMAGE_ID"] = image_id
return values
@staticmethod
def _is_repo_on_the_same_filesystem(repo, destdir):
"""
:param repo: Existing ostree repository.
:type repo: str
:param destdir: path to check. It is created if it doesn't exist. It must be
writeable as we create a temporary file there.
:type destdir: str
"""
repo_stat = os.stat(repo)
try:
destdir_stat = os.stat(destdir)
except OSError as e:
if e.errno == errno.ENOENT:
# The directory doesn't exist
os.makedirs(destdir)
destdir_stat = os.stat(destdir)
else:
raise e
# Simple case: st_dev is different
if repo_stat.st_dev != destdir_stat.st_dev:
return False
src_file = os.path.join(repo, "config")
dest_file = os.path.join(destdir, "samefs-check-{}".format(os.getpid()))