forked from indigo-dc/udocker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udocker.py
executable file
·7170 lines (6588 loc) · 281 KB
/
udocker.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 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
__author__ = "[email protected]"
__copyright__ = "Copyright 2017, 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.3"
__date__ = "2018"
# 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 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):
"""Execute a shell command and get its output"""
try:
content = self.check_output(cmd, shell=True,
stderr=Msg.chlderr,
close_fds=True)
except subprocess.CalledProcessError:
return None
return content.strip()
class Config(object):
"""Default configuration values for the whole application. Changes
to these values should be made via a configuration file read via
self.user_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
uid = os.getuid()
gid = os.getgid()
# udocker installation tarball
tarball_release = "1.1.3"
tarball = (
"https://owncloud.indigo-datacloud.eu/index.php"
"/s/iv4FOV1jZcfnGFH/download"
" "
"https://cernbox.cern.ch/index.php"
"/s/CS31ycKOpj2KzxO/download?x-access-token=eyJhbGciOiJIUzI1Ni"
"IsInR5cCI6IkpXVCJ9.eyJleHAiOiIyMDE4LTEwLTMwVDE4OjM1OjMyLjI2MD"
"AxMDA3OCswMTowMCIsImV4cGlyZXMiOjAsImlkIjoiMTQ1NjgwIiwiaXRlbV9"
"0eXBlIjowLCJtdGltZSI6MTU0MDkxNzA3Miwib3duZXIiOiJqb3JnZSIsInBh"
"dGgiOiJlb3Nob21lLWo6MjcyNTgzNjk2NDc1NzUwNDAiLCJwcm90ZWN0ZWQiO"
"mZhbHNlLCJyZWFkX29ubHkiOnRydWUsInNoYXJlX25hbWUiOiJ1ZG9ja2VyLT"
"EuMS4zLnRhci5neiIsInRva2VuIjoiQ1MzMXljS09wajJLenhPIn0._9LTvxM"
"V12NpxcZXaCg3PJeQfz94qYui4ccscrrvgVA"
" "
"https://download.ncg.ingrid.pt/webdav/udocker/udocker-1.1.3.tar.gz"
)
installinfo = ["https://raw.githubusercontent.com/indigo-dc/udocker/master/messages", ]
autoinstall = True
config = "udocker.conf"
keystore = "keystore"
# for tmp files only
tmpdir = "/tmp"
# defaults for container execution
cmd = ["/bin/bash", "-i"] # Comand to execute
# 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 to be mapped in contaners with: run --hostauth
hostauth_list = (
"/etc/passwd", "/etc/group",
"/etc/shadow", "/etc/gshadow",
)
# directories for DRI (direct rendering)
dri_list = (
"/usr/lib64/dri", "/lib64/dri",
"/usr/lib/dri", "/lib/dri",
)
# 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
# fakechroot sharable library directories
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",
)
# runc parameters
runc_nomqueue = None
# 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:[email protected]: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 = "" # force use of executable
# docker hub v1
dockerio_index_url = "https://index.docker.io"
# docker hub v2
dockerio_registry_url = "https://registry-1.docker.io"
# private repository v2
# dockerio_registry_url = "http://localhost:5000"
# registries table
docker_registries = {"docker.io": ["https://registry-1.docker.io",
"https://index.docker.io"],
}
# 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.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)
def _read_config(self, config_file):
"""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:
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 user_init(self, config_file):
"""
Try to load default values from config file
Defaults 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 username(self):
"""Get username"""
try:
return pwd.getpwuid(Config.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"):
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 "3.2.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(".")]
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
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",
"/lib/ld-linux.so.2",
"/lib/ld-linux.so",
"/bin/sh", "/bin/bash", "/bin/zsh", "/bin/csh", "/bin/tcsh",
"/bin/ls", "/bin/busybox",
"/system/bin/sh", "/system/bin/ls",
]
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):
cmd = "file %s" % (filename)
return Uprocess().get_output(cmd)
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|$)",
osinfo, re.MULTILINE)
if match:
distribution = match.group(1).split(" ")[0]
match = re.search(r"VERSION_ID=\"?(.+)\"?(\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 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 != -1 and keystore_uid != Config.uid:
raise IOError("not owner of keystore: %s" %
(self.keystore_file))
keystore_dir = os.path.dirname(self.keystore_file)
if FileUtil(keystore_dir).uid() != Config.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.unlink(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 layer_v1(self):
"""Get a 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):
try:
dummy = hashlib.sha256()
self._sha256_call = self._hashlib_sha256
except NameError:
self._sha256_call = self._openssl_sha256
def _hashlib_sha256(self, filename):
"""sha256 calculation using hashlib"""
hash_sha256 = hashlib.sha256()
try:
with open(filename, "rb") as filep:
for chunk in iter(lambda: filep.read(4096), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest()
except (IOError, OSError):
return ""
def _openssl_sha256(self, filename):
"""sha256 calculation using openssl"""
cmd = "openssl dgst -hex -r -sha256 %s" % (filename)
output = Uprocess().get_output(cmd)
if output is None:
return ""
match = re.match("^(\\S+) ", output)
if match:
return match.group(1)
return ""
def sha256(self, filename):
"""
Call the actual sha256 implementation selected in __init__
"""
return self._sha256_call(filename)
class FileUtil(object):
"""Some utilities to manipulate files"""
tmptrash = dict()
safe_prefixes = []
orig_umask = None
def __init__(self, filename=None):
self._tmpdir = Config.tmpdir
if filename == "-":
self.filename = "-"
self.basename = "-"
return
try:
self.filename = os.path.abspath(filename)
self.basename = os.path.basename(self.filename)
except (AttributeError, TypeError):
self.filename = filename
self.basename = filename
self._register_prefix(self._tmpdir)
def _register_prefix(self, prefix):
"""Register directory prefixes where remove() is allowed"""
if prefix not in FileUtil.safe_prefixes:
filename = prefix
if os.path.isdir(filename) and not filename.endswith("/"):
FileUtil.safe_prefixes.append(filename + "/")
FileUtil.safe_prefixes.append(os.path.realpath(filename) + "/")
else:
FileUtil.safe_prefixes.append(filename)
FileUtil.safe_prefixes.append(os.path.realpath(filename))
def register_prefix(self):
"""Register self.filename as prefix where remove() is allowed"""
self._register_prefix(self.filename)
def umask(self, new_umask=None):
"""Set umask"""
if new_umask is not None:
try:
old_umask = os.umask(new_umask)
except (TypeError, ValueError):
return False
if FileUtil.orig_umask is None:
FileUtil.orig_umask = old_umask
else:
try:
os.umask(FileUtil.orig_umask)
except (TypeError, ValueError):
return False
return True
def mktmp(self):
"""Generate a temporary filename"""
while True:
tmp_file = self._tmpdir + "/" + \
Unique().filename(self.basename)
if not os.path.exists(tmp_file):
FileUtil.tmptrash[tmp_file] = True
self.filename = tmp_file
return tmp_file
def mkdir(self):
"""Create directory"""
try:
os.makedirs(self.filename)
except (OSError, IOError, AttributeError):
return False
return True
def mktmpdir(self):
"""Create temporary directory"""
dirname = self.mktmp()
if FileUtil(dirname).mkdir():
return dirname
return None
def uid(self):
"""Get the file owner user id"""
try:
return os.stat(self.filename).st_uid
except (IOError, OSError):
return -1
def _is_safe_prefix(self, filename):
"""Check if file prefix falls under valid prefixes"""
for safe_prefix in FileUtil.safe_prefixes:
if filename.startswith(safe_prefix):
return True
return False
def remove(self, force=False):
"""Delete files or directories"""
if not os.path.exists(self.filename):
pass
elif self.filename.count("/") < 2:
Msg().err("Error: delete pathname too short: ", self.filename)
return False
elif self.uid() != Config.uid:
Msg().err("Error: delete not owner: ", self.filename)
return False
elif (not force) and (not self._is_safe_prefix(self.filename)):
Msg().err("Error: delete outside of directory tree: ",
self.filename)
return False
elif os.path.isfile(self.filename) or os.path.islink(self.filename):
try:
os.remove(self.filename)
except (IOError, OSError):
Msg().err("Error: deleting file: ", self.filename)
return False
elif os.path.isdir(self.filename):
cmd = "/bin/rm -Rf %s || /bin/chmod -R u+w %s && /bin/rm -Rf %s" % \
(self.filename, self.filename, self.filename)
if subprocess.call(cmd, stderr=Msg.chlderr, shell=True,
close_fds=True, env=None):
Msg().err("Error: deleting directory: ", self.filename)
return False
if self.filename in dict(FileUtil.tmptrash):
del FileUtil.tmptrash[self.filename]
return True
def verify_tar(self):
"""Verify a tar file"""
if not os.path.isfile(self.filename):
return False
else:
cmd = "tar t"
if Msg.level >= Msg.VER:
cmd += "v"
cmd += "f " + self.filename
if subprocess.call(cmd, shell=True, stderr=Msg.chlderr,
stdout=Msg.chldnul, close_fds=True):
return False
return True
def cleanup(self):
"""Delete all temporary files"""
tmptrash_copy = dict(FileUtil.tmptrash)
for filename in tmptrash_copy:
FileUtil(filename).remove()
def isdir(self):
"""Is filename a directory"""
try:
if os.path.isdir(self.filename):
return True
except (IOError, OSError, TypeError):
pass
return False
def size(self):
"""File size in bytes"""
try:
fstat = os.stat(self.filename)
return fstat.st_size
except (IOError, OSError, TypeError):
return -1
def getdata(self, mode="rb"):
"""Read file content to a buffer"""
try:
filep = open(self.filename, mode)
except (IOError, OSError, TypeError):
return ""
else:
buf = filep.read()
filep.close()
return buf
def get1stline(self, mode="rb"):
"""Read file 1st line to a buffer"""
try:
filep = open(self.filename, mode)
except (IOError, OSError, TypeError):
return ""
else:
buf = filep.readline().strip()
filep.close()
return buf
def putdata(self, buf, mode="wb"):
"""Write buffer to file"""
try:
filep = open(self.filename, mode)
except (IOError, OSError, TypeError):
return ""
else:
filep.write(buf)
filep.close()
return buf
def _find_exec(self, cmd_to_use):
"""This method is called by find_exec() invokes a command like
/bin/which or type to obtain the full pathname of an executable
"""
exec_pathname = Uprocess().get_output(cmd_to_use)
if exec_pathname is None:
return ""
if "not found" in exec_pathname:
return ""
if exec_pathname and exec_pathname.startswith("/"):
return exec_pathname.strip()
return ""
def find_exec(self):
"""Find an executable pathname by using which or type -p"""
cmd = self._find_exec("which " + self.basename)
if cmd:
return cmd
cmd = self._find_exec("type -p " + self.basename)
if cmd:
return cmd
return ""
def find_inpath(self, path, rootdir=""):
"""Find file in a path set such as PATH=/usr/bin:/bin"""
if isinstance(path, str):
if "=" in path:
path = "".join(path.split("=", 1)[1:])
path = path.split(":")
if isinstance(path, (list, tuple)):