forked from indigo-dc/udocker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathudocker.py
More file actions
executable file
·8547 lines (7856 loc) · 338 KB
/
udocker.py
File metadata and controls
executable file
·8547 lines (7856 loc) · 338 KB
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 python2
"""
========
udocker
========
Wrapper to execute basic docker containers without using docker.
This tool is a last resort for the execution of docker containers
where docker is unavailable. It only provides a limited set of
functionalities.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import sys
import os
import stat
import string
import re
import subprocess
import time
import pwd
import grp
import platform
import glob
import select
import ast
import ctypes
__author__ = "udocker@lip.pt"
__copyright__ = "Copyright 2019, LIP"
__credits__ = ["PRoot http://proot.me",
"runC https://runc.io",
"Fakechroot https://github.com/dex4er/fakechroot",
"Singularity http://singularity.lbl.gov"
]
__license__ = "Licensed under the Apache License, Version 2.0"
__version__ = "1.1.4"
__date__ = "2019"
# Python version major.minor
PY_VER = "%d.%d" % (sys.version_info[0], sys.version_info[1])
START_PATH = os.path.dirname(os.path.realpath(sys.argv[0]))
try:
import cStringIO
except ImportError:
from io import BytesIO as cStringIO
try:
import pycurl
except ImportError:
pass
try:
import uuid
except ImportError:
pass
try:
import random
except ImportError:
pass
try:
import base64
except ImportError:
pass
try:
import hashlib
except ImportError:
pass
try:
from getpass import getpass
except ImportError:
getpass = raw_input
try:
import json
except ImportError:
sys.path.append(START_PATH + "/../lib/simplejson")
sys.path.append(os.path.expanduser('~') + "/.udocker/lib/simplejson")
sys.path.append(str(os.getenv("UDOCKER_DIR")) + "/lib/simplejson")
try:
import simplejson as json
except ImportError:
pass
class Config(object):
"""Default configuration values for the whole application. Changes
to these values should be made via a configuration file read via
self.init() and that can reside in ~/.udocker/udocker.conf
"""
try:
verbose_level = int(os.getenv("UDOCKER_LOGLEVEL", ""))
except ValueError:
verbose_level = 3
homedir = os.path.expanduser('~') + "/.udocker"
topdir = homedir
bindir = None
libdir = None
reposdir = None
layersdir = None
containersdir = None
# udocker installation tarball
tarball_release = "1.1.4"
tarball = (
"https://owncloud.indigo-datacloud.eu/index.php"
"/s/QF09QQGUzG0P1pK/download"
" "
"https://raw.githubusercontent.com"
"/jorge-lip/udocker-builds/master/tarballs/udocker-1.1.4.tar.gz"
" "
"https://cernbox.cern.ch/index.php/s/g1qv4aycRoBFsDO/download"
" "
"https://download.ncg.ingrid.pt/webdav/udocker/udocker-1.1.4.tar.gz"
)
installinfo = [
"https://raw.githubusercontent.com/indigo-dc/udocker/master/messages", ]
installretry = 3
autoinstall = True
config = "udocker.conf"
keystore = "keystore"
# for tmp files only
tmpdir = "/tmp"
# default command to be executed within the containers
cmd = ["/bin/bash", "-i"]
# default path for executables
root_path = "/usr/sbin:/sbin:/usr/bin:/bin"
user_path = "/usr/local/bin:/usr/bin:/bin"
# directories to be mapped in contaners with: run --sysdirs
sysdirs_list = (
"/dev", "/proc", "/sys", "/etc/resolv.conf", "/etc/host.conf",
"/lib/modules",
)
# directories for DRI (direct rendering)
dri_list = (
"/usr/lib64/dri", "/lib64/dri",
"/usr/lib/dri", "/lib/dri",
)
# allowed file mountpoints for runC, these files can be copied in
mountpoint_prefixes = ("/etc", )
# container execution mode if not set via setup
# Change it to P2 if execution problems occur
default_execution_mode = "P1"
# PRoot override seccomp
# proot_noseccomp = True
proot_noseccomp = None
# PRoot kill-on-exit
proot_killonexit = True
# fakechroot engine get ld_library_paths from ld.so.cache
ld_so_cache = "/etc/ld.so.cache"
# fakechroot engine override fakechroot.so selection
# fakechroot_so = "libfakechroot-CentOS-7-x86_64.so"
fakechroot_so = None
# translate symbolic links in pathnames None means automatic
fakechroot_expand_symlinks = None
# sharable library directories
lib_dirs_list_x86_64 = (
"/usr/lib/x86_64-linux-gnu", "/usr/lib64",
)
lib_dirs_list_essential = (
"/lib/x86_64-linux-gnu", "/usr/lib/x86_64-linux-gnu",
"/lib64", "/usr/lib64", "/lib", "/usr/lib",
)
lib_dirs_list_append = ('.', )
# fakechroot access files, used to circunvent openmpi init issues
access_files = (
"/sys/class/infiniband", "/dev/open-mx", "/dev/myri0", "/dev/myri1",
"/dev/myri2", "/dev/myri3", "/dev/myri4", "/dev/myri5", "/dev/myri6",
"/dev/myri7", "/dev/myri8", "/dev/myri9", "/dev/ipath", "/dev/kgni0",
"/dev/mic/scif", "/dev/scif",
)
# Force the use of specific executables
# UDOCKER = use executable from the udocker binary distribution/tarball
use_proot_executable = "UDOCKER"
use_runc_executable = ""
use_singularity_executable = ""
# runc parameters
runc_nomqueue = None
runc_capabilities = [
"CAP_KILL", "CAP_NET_BIND_SERVICE", "CAP_CHOWN", "CAP_DAC_OVERRIDE",
"CAP_FOWNER", "CAP_FSETID", "CAP_KILL", "CAP_SETGID", "CAP_SETUID",
"CAP_SETPCAP", "CAP_NET_BIND_SERVICE", "CAP_NET_RAW", "CAP_SYS_CHROOT",
"CAP_MKNOD", "CAP_AUDIT_WRITE", "CAP_SETFCAP",
]
# singularity options -u --nv -w
singularity_options = ["-w", ]
# Pass host env variables
valid_host_env = ("TERM", "PATH", )
invalid_host_env = ("VTE_VERSION", )
# CPU affinity executables to use with: run --cpuset-cpus="1,2,3-4"
cpu_affinity_exec_tools = (["numactl", "-C", "%s", "--", ],
["taskset", "-c", "%s", ])
# Containers execution defaults
location = "" # run container in this location
# Curl settings
http_proxy = "" # ex. socks5://user:pass@127.0.0.1:1080
timeout = 12 # default timeout (secs)
download_timeout = 30 * 60 # file download timeout (secs)
ctimeout = 6 # default TCP connect timeout (secs)
http_agent = ""
http_insecure = False
use_curl_executable = ""
# docker hub index
dockerio_index_url = "https://hub.docker.com"
# docker hub registry
dockerio_registry_url = "https://registry.hub.docker.com"
# private repository v2
# dockerio_registry_url = "http://localhost:5000"
# registries table
docker_registries = {"docker.io": [dockerio_registry_url,
dockerio_index_url],
}
# nvidia files
nvi_etc_list = ['vulkan/icd.d/nvidia_icd.json',
'OpenCL/vendors/nvidia.icd'
]
nvi_bin_list = ['nvidia-bug-report.sh', 'nvidia-cuda-mps-control',
'nvidia-cuda-mps-server', 'nvidia-debugdump',
'nvidia-installer', 'nvidia-persistenced',
'nvidia-settings', 'nvidia-smi',
'nvidia-uninstall', 'nvidia-xconfig'
]
nvi_lib_list = ['libOpenCL.', 'libcuda.', 'libnvcuvid.',
'libnvidia-cfg.', 'libnvidia-compiler.',
'libnvidia-encode.', 'libnvidia-fatbinaryloader.',
'libnvidia-fbc.', 'libnvidia-ifr.', 'libnvidia-ml.',
'libnvidia-opencl.', 'libnvidia-ptxjitcompiler.',
'libnvidia-tls.', 'tls/libnvidia-tls.'
]
nvi_dev_list = ['/dev/nvidia', ]
# -------------------------------------------------------------
def _verify_config(self):
"""Config verification"""
if not Config.topdir:
Msg().err("Error: UDOCKER directory not found")
sys.exit(1)
def _override_config(self):
"""Override config with environment"""
Config.topdir = os.getenv("UDOCKER_DIR", Config.topdir)
Config.bindir = os.getenv("UDOCKER_BIN", Config.bindir)
Config.libdir = os.getenv("UDOCKER_LIB", Config.libdir)
Config.reposdir = os.getenv("UDOCKER_REPOS", Config.reposdir)
Config.layersdir = os.getenv("UDOCKER_LAYERS", Config.layersdir)
Config.containersdir = os.getenv("UDOCKER_CONTAINERS",
Config.containersdir)
Config.dockerio_index_url = os.getenv("UDOCKER_INDEX",
Config.dockerio_index_url)
Config.dockerio_registry_url = os.getenv("UDOCKER_REGISTRY",
Config.dockerio_registry_url)
Config.tarball = os.getenv("UDOCKER_TARBALL", Config.tarball)
Config.default_execution_mode = os.getenv("UDOCKER_DEFAULT_EXECUTION_MODE",
Config.default_execution_mode)
Config.fakechroot_so = os.getenv("UDOCKER_FAKECHROOT_SO",
Config.fakechroot_so)
Config.tmpdir = os.getenv("UDOCKER_TMP", Config.tmpdir)
Config.keystore = os.getenv("UDOCKER_KEYSTORE", Config.keystore)
Config.use_curl_executable = os.getenv("UDOCKER_USE_CURL_EXECUTABLE",
Config.use_curl_executable)
Config.use_proot_executable = os.getenv("UDOCKER_USE_PROOT_EXECUTABLE",
Config.use_proot_executable)
Config.use_runc_executable = os.getenv("UDOCKER_USE_RUNC_EXECUTABLE",
Config.use_runc_executable)
Config.use_singularity_executable = \
os.getenv("UDOCKER_USE_SINGULARITY_EXECUTABLE",
Config.use_singularity_executable)
fakechroot_expand_symlinks = \
os.getenv("UDOCKER_FAKECHROOT_EXPAND_SYMLINKS",
str(Config.fakechroot_expand_symlinks)).lower()
try:
Config.fakechroot_expand_symlinks = {
"false": False, "true": True,
"none": None, }[fakechroot_expand_symlinks]
except (KeyError, ValueError):
Msg().err("Error: in UDOCKER_FAKECHROOT_EXPAND_SYMLINKS")
def _read_config(self, config_file, ignore_keys=None):
"""Interpret config file content"""
cfile = FileUtil(config_file)
if cfile.size() == -1:
return False
data = cfile.getdata()
for line in data.split('\n'):
if not line.strip() or '=' not in line or line.startswith('#'):
continue
(key, val) = line.strip().split('=', 1)
key = key.strip()
Msg().err(config_file, ':', key, '=', val, l=Msg.DBG)
try:
if ignore_keys and key in ignore_keys:
continue
dummy = ast.literal_eval(val.strip())
exec('Config.%s=%s' % (key, val))
except(NameError, AttributeError, TypeError, IndexError,
SyntaxError, ValueError):
raise ValueError("config file: %s at: %s" %
(config_file, line.strip()))
if key == "verbose_level":
Msg().setlevel(Config.verbose_level)
return True
def init(self, config_file):
"""
Initial configuration loading
Values should be in the form x = y
"""
try:
if os.getenv("UDOCKER_NOSYSCONF") is None:
self._read_config("/etc/" + Config.config)
if self._read_config(config_file):
return
self._read_config(Config.topdir + '/' + Config.config)
if self.topdir != self.homedir:
self._read_config(Config.homedir + '/' + Config.config)
except ValueError as error:
Msg().err("Error:", error)
sys.exit(1)
self._override_config()
self._verify_config()
def container(self, config_file):
"""
Load configuration for a container
Values should be in the form x = y
"""
ignore_keys = ["topdir", "homedir", "reposdir", "layersdir",
"containersdir", "location", ]
try:
self._read_config(config_file, ignore_keys)
except ValueError as error:
Msg().err("Error:", error)
sys.exit(1)
self._override_config()
self._verify_config()
class Uprocess(object):
"""Provide alternative implementations for subprocess"""
def _check_output(self, *popenargs, **kwargs):
"""Alternative to subprocess.check_output"""
process = subprocess.Popen(*popenargs, stdout=subprocess.PIPE, **kwargs)
output, dummy = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd)
return output
def check_output(self, *popenargs, **kwargs):
"""Select check_output implementation"""
if PY_VER >= "2.7":
return subprocess.check_output(*popenargs, **kwargs)
return self._check_output(*popenargs, **kwargs)
def get_output(self, cmd, ignore_error=False):
"""Execute a command and get its output"""
if not cmd[0].startswith("/"):
cmd[0] = FileUtil(cmd[0]).find_inpath(Config.root_path + ":" + os.getenv("PATH", ""))
content = ""
try:
content = self.check_output(cmd, shell=False, stderr=Msg.chlderr,
close_fds=True)
except subprocess.CalledProcessError:
if not ignore_error:
return None
return content.strip()
def call(self, cmd, **kwargs):
"""Execute one shell command"""
if not cmd[0].startswith("/"):
cmd[0] = FileUtil(cmd[0]).find_inpath(Config.root_path + ":" +
os.getenv("PATH", ""))
kwargs["shell"] = False
return subprocess.call(cmd, **kwargs)
def pipe(self, cmd1, cmd2, **kwargs):
"""Pipe two shell commands"""
if not cmd1[0].startswith("/"):
cmd1[0] = FileUtil(cmd1[0]).find_inpath(Config.root_path + ":"
+ os.getenv("PATH", ""))
if not cmd2[0].startswith("/"):
cmd2[0] = FileUtil(cmd2[0]).find_inpath(Config.root_path + ":"
+ os.getenv("PATH", ""))
try:
proc_1 = subprocess.Popen(cmd1, stderr=Msg.chlderr, shell=False,
stdout=subprocess.PIPE, **kwargs)
except (OSError, ValueError):
return False
try:
proc_2 = subprocess.Popen(cmd2, stderr=Msg.chlderr, shell=False,
stdin=proc_1.stdout)
except (OSError, ValueError):
proc_1.kill()
return False
while proc_1.returncode is None or proc_2.returncode is None:
proc_1.wait()
proc_2.wait()
return not (proc_1.returncode or proc_2.returncode)
class HostInfo(object):
"""Get information from the host system"""
uid = os.getuid()
gid = os.getgid()
def username(self):
"""Get username"""
try:
return pwd.getpwuid(self.uid).pw_name
except KeyError:
return ""
def arch(self):
"""Get the host system architecture"""
arch = ""
try:
machine = platform.machine()
bits = platform.architecture()[0]
if machine == "x86_64":
if bits == "32bit":
arch = "i386"
else:
arch = "amd64"
elif machine in ("i386", "i486", "i586", "i686"):
arch = "i386"
elif machine.startswith("arm") or machine.startswith("aarch"):
if bits == "32bit":
arch = "arm"
else:
arch = "arm64"
except (NameError, AttributeError):
pass
return arch
def osversion(self):
"""Get operating system"""
try:
return platform.system().lower()
except (NameError, AttributeError):
return ""
def osdistribution(self):
"""Get operating system distribution"""
(distribution, version, dummy) = platform.linux_distribution()
return (distribution.split(' ')[0], version.split('.')[0])
def oskernel(self):
"""Get operating system"""
try:
return platform.release()
except (NameError, AttributeError):
return "6.1.1"
def oskernel_isgreater(self, ref_version):
"""Compare kernel version is greater or equal than ref_version"""
os_release = self.oskernel().split('-')[0]
os_version = [int(x) for x in os_release.split('.')[0:3]]
for idx in (0, 1, 2):
if os_version[idx] > ref_version[idx]:
return True
elif os_version[idx] < ref_version[idx]:
return False
return True
def cmd_has_option(self, executable, search_option, arg=None):
"""Check if executable has a given cli option"""
if not executable:
return False
arg_list = []
if arg and isinstance(arg, str):
arg_list = [arg]
elif isinstance(arg, list):
arg_list = arg
out = Uprocess().get_output([executable] + arg_list + ["--help"])
if out and search_option in re.split(r"[=|\*\[\]\n,; ]*", out):
return True
return False
def termsize(self):
"""Get guest operating system terminal size"""
try:
with open("/dev/tty") as tty:
cmd = ['stty', 'size']
lines, cols = Uprocess().check_output(cmd, stdin=tty).split()
return (int(lines), int(cols))
except (OSError, IOError):
pass
return (24, 80)
class GuestInfo(object):
"""Get os information from a directory tree"""
_binarylist = ["/lib64/ld-linux-x86-64.so",
"/lib64/ld-linux-x86-64.so.2",
"/lib64/ld-linux-x86-64.so.3",
"/bin/bash", "/bin/sh", "/bin/zsh",
"/bin/csh", "/bin/tcsh", "/bin/ash",
"/bin/ls", "/bin/busybox",
"/system/bin/sh", "/system/bin/ls",
"/lib/ld-linux.so",
"/lib/ld-linux.so.2",
]
def __init__(self, root_dir):
self._root_dir = root_dir
def get_filetype(self, filename):
"""Get the file architecture"""
if not filename.startswith(self._root_dir):
filename = self._root_dir + '/' + filename
if os.path.islink(filename):
f_path = os.readlink(filename)
if not f_path.startswith('/'):
f_path = os.path.dirname(filename) + '/' + f_path
return self.get_filetype(f_path)
if os.path.isfile(filename):
return Uprocess().get_output(["file", filename])
return ""
def arch(self):
"""Get guest system architecture"""
for filename in GuestInfo._binarylist:
f_path = self._root_dir + filename
filetype = self.get_filetype(f_path)
if not filetype:
continue
if "x86-64," in filetype:
return "amd64"
if "80386," in filetype:
return "i386"
if "ARM," in filetype:
if "64-bit" in filetype:
return "arm64"
else:
return "arm"
return ""
def osdistribution(self):
"""Get guest operating system distribution"""
for f_path in FileUtil(self._root_dir + "/etc/.+-release").match():
if os.path.exists(f_path):
osinfo = FileUtil(f_path).getdata()
match = re.match(r"([^=]+) release (\d+)", osinfo)
if match and match.group(1):
return (match.group(1).split(' ')[0],
match.group(2).split('.')[0])
f_path = self._root_dir + "/etc/lsb-release"
if os.path.exists(f_path):
distribution = ""
version = ""
osinfo = FileUtil(f_path).getdata()
match = re.search(r"DISTRIB_ID=(.+)(\n|$)",
osinfo, re.MULTILINE)
if match:
distribution = match.group(1).split(' ')[0]
match = re.search(r"DISTRIB_RELEASE=(.+)(\n|$)",
osinfo, re.MULTILINE)
if match:
version = match.group(1).split('.')[0]
if distribution and version:
return (distribution, version)
f_path = self._root_dir + "/etc/os-release"
if os.path.exists(f_path):
distribution = ""
version = ""
osinfo = FileUtil(f_path).getdata()
match = re.search(r"NAME=\"?([^ \n\"\.]+).*\"?(\n|$)",
osinfo, re.MULTILINE)
if match:
distribution = match.group(1).split(' ')[0]
match = re.search(r"VERSION_ID=\"?([^ \n\"\.]+).*\"?(\n|$)",
osinfo, re.MULTILINE)
if match:
version = match.group(1).split('.')[0]
if distribution and version:
return (distribution, version)
return ("", "")
def osversion(self):
"""Get guest operating system"""
if self.osdistribution()[0]:
return "linux"
return ""
class Unshare(object):
"""Place a process in a namespace"""
CLONE_NEWNS = 0x20000
CLONE_NEWUTS = 0x4000000
CLONE_NEWIPC = 0x8000000
CLONE_NEWUSER = 0x10000000
CLONE_NEWPID = 0x20000000
CLONE_NEWNET = 0x40000000
def unshare(self, flags):
"""Python implementation of unshare"""
try:
_unshare = ctypes.CDLL("libc.so.6").unshare
except OSError:
Msg().err("Error: in unshare: mapping libc")
return False
_unshare.restype = ctypes.c_int
_unshare.argtypes = (ctypes.c_int, )
if _unshare(flags) == -1:
Msg().err("Error: in unshare:", os.strerror())
return False
return True
def namespace_exec(self, method, flags=CLONE_NEWUSER):
"""Execute command in namespace"""
(pread1, pwrite1) = os.pipe()
(pread2, pwrite2) = os.pipe()
cpid = os.fork()
if cpid:
os.close(pwrite1)
os.read(pread1, 1) # wait
user = HostInfo().username()
newidmap = ["newuidmap", str(cpid), "0", str(HostInfo.uid), "1"]
for (subid, subcount) in NixAuthentication().user_in_subuid(user):
newidmap.extend(["1", subid, subcount])
subprocess.call(newidmap)
newidmap = ["newgidmap", str(cpid), "0", str(HostInfo.uid), "1"]
for (subid, subcount) in NixAuthentication().user_in_subgid(user):
newidmap.extend(["1", subid, subcount])
subprocess.call(newidmap)
os.close(pwrite2) # notify
(dummy, status) = os.waitpid(cpid, 0)
if status % 256:
Msg().err("Error: namespace exec action failed")
return False
return True
else:
self.unshare(flags)
os.close(pwrite2)
os.close(pwrite1) # notify
os.read(pread2, 1) # wait
try:
os.setgid(0)
os.setuid(0)
os.setgroups([0, 0, ])
except OSError:
Msg().err("Error: setting ids and groups")
return False
exit(int(method()))
return False
class KeyStore(object):
"""Basic storage for authentication tokens to be used
with dockerhub and private repositories
"""
def __init__(self, keystore_file):
"""Initialize keystone"""
self.keystore_file = keystore_file
self.credential = dict()
def _verify_keystore(self):
"""Verify the keystore file and directory"""
keystore_uid = FileUtil(self.keystore_file).uid()
if keystore_uid not in (-1, HostInfo.uid):
raise IOError("not owner of keystore: %s" %
(self.keystore_file))
keystore_dir = os.path.dirname(self.keystore_file)
if FileUtil(keystore_dir).uid() != HostInfo.uid:
raise IOError("keystore dir not found or not owner: %s" %
(keystore_dir))
if (keystore_uid != -1 and
(os.stat(self.keystore_file).st_mode & 0o077)):
raise IOError("keystore is accessible to group or others: %s" %
(self.keystore_file))
def _read_all(self):
"""Read all credentials from file"""
try:
with open(self.keystore_file, 'r') as filep:
return json.load(filep)
except (IOError, OSError, ValueError):
return dict()
def _shred(self):
"""Shred file content"""
self._verify_keystore()
try:
size = os.stat(self.keystore_file).st_size
with open(self.keystore_file, "rb+") as filep:
filep.write(' ' * size)
except (IOError, OSError):
return False
return True
def _write_all(self, auths):
"""Write all credentials to file"""
self._verify_keystore()
oldmask = None
try:
oldmask = os.umask(0o77)
with open(self.keystore_file, 'w') as filep:
json.dump(auths, filep)
os.umask(oldmask)
except (IOError, OSError):
if oldmask is not None:
os.umask(oldmask)
return False
return True
def get(self, url):
"""Get credential from keystore for given url"""
auths = self._read_all()
try:
self.credential = auths[url]
return self.credential["auth"]
except KeyError:
pass
return ""
def put(self, url, credential, email):
"""Put credential in keystore for given url"""
if not credential:
return False
auths = self._read_all()
auths[url] = {"auth": credential, "email": email, }
self._shred()
return self._write_all(auths)
def delete(self, url):
"""Delete credential from keystore for given url"""
self._verify_keystore()
auths = self._read_all()
try:
del auths[url]
except KeyError:
return False
self._shred()
return self._write_all(auths)
def erase(self):
"""Delete all credentials from keystore"""
self._verify_keystore()
try:
self._shred()
os.remove(self.keystore_file)
except (IOError, OSError):
return False
return True
class Msg(object):
"""Write messages to stdout and stderr. Allows to filter the
messages to be displayed through a verbose level, also allows
to control if child process that produce output through a
file descriptor should be redirected to /dev/null
"""
NIL = -1
ERR = 0
MSG = 1
WAR = 2
INF = 3
VER = 4
DBG = 5
DEF = INF
level = DEF
previous = DEF
nullfp = None
chlderr = sys.stderr
chldout = sys.stdout
chldnul = sys.stderr
def __init__(self, new_level=None):
"""
Initialize Msg level and /dev/null file pointers to be
used in subprocess calls to obfuscate output and errors
"""
if new_level is not None:
Msg.level = new_level
try:
if Msg.nullfp is None:
Msg.nullfp = open("/dev/null", 'w')
except (IOError, OSError):
Msg.chlderr = sys.stderr
Msg.chldout = sys.stdout
Msg.chldnul = sys.stderr
else:
Msg.chlderr = Msg.nullfp
Msg.chldout = Msg.nullfp
Msg.chldnul = Msg.nullfp
def setlevel(self, new_level=None):
"""Define debug level"""
if new_level is None:
new_level = Msg.previous
else:
Msg.previous = Msg.level
Msg.level = new_level
if Msg.level >= Msg.DBG:
Msg.chlderr = sys.stderr
Msg.chldout = sys.stdout
else:
Msg.chlderr = Msg.nullfp
Msg.chldout = Msg.nullfp
return Msg.previous
def out(self, *args, **kwargs):
"""Write text to stdout respecting verbose level"""
level = Msg.MSG
if 'l' in kwargs:
level = kwargs['l']
if level <= Msg.level:
sys.stdout.write(' '.join([str(x) for x in args]) + '\n')
def err(self, *args, **kwargs):
"""Write text to stderr respecting verbose level"""
level = Msg.ERR
if 'l' in kwargs:
level = kwargs['l']
if level <= Msg.level:
sys.stderr.write(' '.join([str(x) for x in args]) + '\n')
class Unique(object):
"""Produce unique identifiers for container names, temporary
file names and other purposes. If module uuid does not exist
it tries to use as last option the random generator.
"""
def __init__(self):
self.string_set = "abcdef"
self.def_name = "udocker"
def _rnd(self, size):
"""Generate a random string"""
return "".join(
random.sample(self.string_set * 64 + string.digits * 64, size))
def uuid(self, name):
"""Get an ID"""
if not name:
name = self.def_name
try:
return str(uuid.uuid3(uuid.uuid4(), str(name) + str(time.time())))
except (NameError, AttributeError):
return (("%s-%s-%s-%s-%s") %
(self._rnd(8), self._rnd(4), self._rnd(4),
self._rnd(4), self._rnd(12)))
def imagename(self):
"""Get a container image name"""
return self._rnd(16)
def imagetag(self):
"""Get a container image tag"""
return self._rnd(10)
def layer_v1(self):
"""Get a random container layer name"""
return self._rnd(64)
def filename(self, filename):
"""Get a filename"""
prefix = self.def_name + '-' + str(os.getpid()) + '-'
try:
return (prefix +
str(uuid.uuid3(uuid.uuid4(), str(time.time()))) +
'-' + str(filename))
except (NameError, AttributeError):
return prefix + self.uuid(filename) + '-' + str(filename)
class ChkSUM(object):
"""Checksumming for files"""
def __init__(self):
self._algorithms = dict()
try:
dummy = hashlib.sha256()
self._algorithms["sha256"] = self._hashlib_sha256
except NameError:
self._algorithms["sha256"] = self._openssl_sha256
try:
dummy = hashlib.sha512()
self._algorithms["sha512"] = self._hashlib_sha512
except NameError:
self._algorithms["sha512"] = self._openssl_sha512
def _hashlib(self, algorithm, filename):
"""hash calculation using hashlib"""
try:
with open(filename, "rb") as filep:
for chunk in iter(lambda: filep.read(4096), b""):
algorithm.update(chunk)
return algorithm.hexdigest()
except (IOError, OSError):
return ""
def _hashlib_sha256(self, filename):
"""sha256 calculation using hashlib"""
return self._hashlib(hashlib.sha256(), filename)
def _hashlib_sha512(self, filename):
"""sha512 calculation using hashlib"""
return self._hashlib(hashlib.sha512(), filename)
def _openssl(self, algorithm, filename):
"""hash calculation using openssl"""
cmd = ["openssl", "dgst", "-hex", "-r", algorithm, filename]
output = Uprocess().get_output(cmd)
if output is None:
return ""
match = re.match("^(\\S+) ", output)
if match:
return match.group(1)
return ""
def _openssl_sha256(self, filename):
"""sha256 calculation using openssl"""
return self._openssl("-sha256", filename)
def _openssl_sha512(self, filename):
"""sha512 calculation using openssl"""
return self._openssl("-sha512", filename)
def sha256(self, filename):
"""Call the actual implementation selected in __init__"""
return self._algorithms["sha256"](filename)
def sha512(self, filename):
"""Call the actual implementation selected in __init__"""
return self._algorithms["sha512"](filename)
def hash(self, filename, algorithm):
"""Compute hash algorithm for file"""
if algorithm in self._algorithms:
return self._algorithms[algorithm](filename)
return ""
class FileUtil(object):
"""Some utilities to manipulate files"""
tmptrash = dict()
safe_prefixes = []
orig_umask = None
def __init__(self, filename=None):