forked from dan-sullivan/termux-udocker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udocker.py
executable file
·4615 lines (4253 loc) · 177 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 python
"""
========
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 string
import re
import subprocess
import time
import pwd
import grp
import platform
__author__ = "[email protected]"
__credits__ = ["PRoot http://proot.me"]
__license__ = "Licensed under the Apache License, Version 2.0"
__version__ = "1.0.4"
__date__ = "2017"
# 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
if PY_VER < "2.6":
try:
import posixpath
except ImportError:
pass
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.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
# udocker installation tarball
tarball = (
"https://owncloud.indigo-datacloud.eu/index.php"
"/s/2F1DRs4TMyexq6R/download"
)
autoinstall = True
config = "udocker.conf"
keystore = "keystore"
# for tmp files only
tmpdir = "/tmp"
# defaults for container execution
cmd = ["/bin/bash", "-i"] # Comand to execute
# dafault 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/lib/dri", "/lib/dri",
"/usr/lib64/dri", "/lib64/dri",
)
# PRoot seccomp
proot_noseccomp = None
# Pass host env variables
valid_host_env = ("TERM")
# CPU affinity executables to use with: run --cpuset-cpus="1,2,3-4"
cpu_affinity_exec_tools = ("taskset -c ", "numactl -C ")
# 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
# 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"
# -------------------------------------------------------------
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.tmpdir = os.getenv("UDOCKER_TMP", Config.tmpdir)
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().out(config_file, ":", key, "=", val, l=Msg.DBG)
try:
exec('Config.%s=%s' % (key, val))
except(NameError, AttributeError, TypeError, IndexError,
SyntaxError):
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:
self._read_config("/etc/" + Config.config)
if self._read_config(config_file):
return True
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"""
return pwd.getpwuid(os.getuid()).pw_name
def userhome(self):
"""Get user home dir"""
return pwd.getpwuid(os.getuid()).pw_dir
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 oskernel(self):
"""Get operating system"""
try:
return platform.release()
except (NameError, AttributeError):
return "4.2.0"
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 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 != os.getuid():
raise IOError("not owner of keystore: %s" %
(self.keystore_file))
keystore_dir = os.path.dirname(self.keystore_file)
if FileUtil(keystore_dir).uid() != os.getuid():
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
"""
ERR = 0
MSG = 1
WAR = 2
INF = 3
VER = 4
DBG = 5
DEF = INF
level = 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):
"""Define debug 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
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)
try:
output = subprocess.check_output(cmd, shell=True,
stderr=Msg().chlderr,
close_fds=True)
except subprocess.CalledProcessError:
return ""
matched = re.match("^(\\S+) ", output)
if matched:
return matched.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):
try:
self.filename = os.path.abspath(filename)
self.basename = os.path.basename(self.filename)
except (AttributeError, TypeError):
self.filename = filename
self.basename = filename
self._tmpdir = Config.tmpdir
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("/"):
filename = filename + "/"
FileUtil.safe_prefixes.append(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() != os.getuid():
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
else:
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):
"""Read file content to a buffer"""
try:
filep = open(self.filename, "r")
except (IOError, OSError, TypeError):
return ""
else:
buf = filep.read()
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
"""
out_file = FileUtil("findexec").mktmp()
try:
filep = open(out_file, "w")
except (IOError, OSError):
return ""
subprocess.call(cmd_to_use, shell=True, stderr=Msg.chlderr,
stdout=filep, close_fds=True)
exec_pathname = FileUtil(out_file).getdata()
filep.close()
FileUtil(out_file).remove()
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 invoking 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)):
for directory in path:
full_path = rootdir + directory + "/" + self.basename
if os.path.exists(full_path):
return directory + "/" + self.basename
return ""
return ""
def copyto(self, dest_filename, mode="w"):
"""Copy self.filename to another file. We avoid shutil to have
the fewest possible dependencies on other Python modules.
"""
try:
fpsrc = open(self.filename, "rb")
except (IOError, OSError):
return False
try:
fpdst = open(dest_filename, mode + "b")
except (IOError, OSError):
fpsrc.close()
return False
while True:
copy_buffer = fpsrc.read(1024 * 1024)
if not copy_buffer:
break
fpdst.write(copy_buffer)
fpsrc.close()
fpdst.close()
return True
class UdockerTools(object):
"""Download and setup of the udocker supporting tools
Includes: proot and alternative python modules, these
are downloaded to facilitate the installation by the
end-user.
"""
def __init__(self, localrepo):
self.localrepo = localrepo # LocalRepository object
self._autoinstall = Config.autoinstall # True / False
self._tarball = Config.tarball # URL or file
self.curl = GetURL()
def _version_isequal(self, filename):
"""Is version inside file equal to this udocker version"""
version = FileUtil(filename).getdata().strip()
return version and version == __version__
def is_available(self):
"""Are the tools already installed"""
return self._version_isequal(self.localrepo.libdir + "/VERSION")
def _download(self):
"""Get the tools tarball containing the binaries"""
tarball_file = FileUtil("udockertools").mktmp()
(hdr, dummy) = self.curl.get(self._tarball, ofile=tarball_file)
if hdr.data["X-ND-CURLSTATUS"]:
return ""
return tarball_file
def _verify_version(self, tarball_file):
"""verify the tarball version"""
tmpdir = FileUtil("VERSION").mktmpdir()
if not tmpdir:
return False
cmd = "cd " + tmpdir + " ; "
cmd += "tar --strip-components=2 -x"
if Msg.level >= Msg.VER:
cmd += "v"
cmd += "zf " + tarball_file + " udocker_dir/lib/VERSION ; "
status = subprocess.call(cmd, shell=True, close_fds=True)
if status:
return False
status = self._version_isequal(tmpdir + "/VERSION")
FileUtil(tmpdir).mktmpdir()
return status
def _install(self, tarball_file):
"""Install the tarball"""
cmd = "cd " + self.localrepo.bindir + " ; "
cmd += "tar --strip-components=2 -x"
if Msg.level >= Msg.VER:
cmd += "v"
cmd += "zf " + tarball_file + " udocker_dir/bin ; "
cmd += "/bin/chmod u+rx *"
status = subprocess.call(cmd, shell=True, close_fds=True)
if status:
return False
cmd = "cd " + self.localrepo.libdir + " ; "
cmd += "tar --strip-components=2 -x"
if Msg.level >= Msg.VER:
cmd += "v"
cmd += "zf " + tarball_file + " udocker_dir/lib ; "
cmd += "/bin/chmod u+rx *"
status = subprocess.call(cmd, shell=True, close_fds=True)
if status:
return False
return True
def _instructions(self):
"""
Udocker installation instructions are available at:
https://indigo-dc.gitbooks.io/udocker/content/
Udocker requires additional tools to run. These are available
in the tarball that comprises udocker. The tarballs are available
at the INDIGO-DataCloud repository under tarballs at:
http://repo.indigo-datacloud.eu/
Udocker can be installed with these instructions:
1) set UDOCKER_TARBALL to a remote URL or local filename e.g.
$ export UDOCKER_TARBALL=http://host/path
or
$ export UDOCKER_TARBALL=/tmp/filename
2) run udocker and installation will proceed
./udocker
The correct tarball version for this udocker executable is:
"""
Msg().out(self._instructions.__doc__, __version__, l=Msg.ERR)
def install(self):
"""Get the udocker tarball and install the binaries"""
if self.is_available():
return True
elif not self._autoinstall:
Msg().out("Warning: no engine available and autoinstall disabled",
l=Msg.WAR)
return None
elif not self._tarball:
Msg().err("Error: UDOCKER_TARBALL not defined")
self._instructions()
return False
else:
Msg().out("Info: installing from tarball", __version__,
l=Msg.INF)
tarball_file = ""
if "://" in self._tarball:
tarball_file = self._download()
elif os.path.exists(self._tarball):
tarball_file = self._tarball
if not tarball_file:
Msg().err("Error: accessing tarball:",
self._tarball)
self._instructions()
else:
if not self._verify_version(tarball_file):
Msg().err("Error: wrong tarball version:",
self._tarball)
self._instructions()
elif self._install(tarball_file):
return True
else:
Msg().err("Error: installing tarball:",
self._tarball)
self._instructions()
if "://" in self._tarball:
FileUtil(tarball_file).remove()
return False
class NixAuthentication(object):
"""Provides abstraction and useful methods to manage
passwd and group based authentication, both for the
host system and for the container.
If passwd_file and group_file are None then the host
system authentication databases are used.
"""
def __init__(self, passwd_file=None, group_file=None):
self.passwd_file = passwd_file
self.group_file = group_file
def _get_user_from_host(self, wanted_user):
"""get user information from the host /etc/passwd"""
wanted_uid = ""
if (isinstance(wanted_user, (int, long)) or
re.match("^\\d+$", wanted_user)):
wanted_uid = str(wanted_user)
wanted_user = ""
if wanted_uid:
try:
usr = pwd.getpwuid(int(wanted_uid))
except (IOError, OSError, KeyError):
return("", "", "", "", "", "")
return(str(usr.pw_name), str(usr.pw_uid), str(usr.pw_gid),
str(usr.pw_gecos), usr.pw_dir, usr.pw_shell)
else:
try:
usr = pwd.getpwnam(wanted_user)
except (IOError, OSError, KeyError):
return("", "", "", "", "", "")
return(str(usr.pw_name), str(usr.pw_uid), str(usr.pw_gid),
str(usr.pw_gecos), usr.pw_dir, usr.pw_shell)
def _get_group_from_host(self, wanted_group):
"""get group information from the host /etc/group"""
wanted_gid = ""
if (isinstance(wanted_group, (int, long)) or
re.match("^\\d+$", wanted_group)):
wanted_gid = str(wanted_group)
wanted_group = ""
if wanted_gid:
try:
hgr = grp.getgrgid(int(wanted_gid))
except (IOError, OSError, KeyError):
return("", "", "")
return(str(hgr.gr_name), str(hgr.gr_gid), str(hgr.gr_mem))
else:
try:
hgr = grp.getgrnam(wanted_group)
except (IOError, OSError, KeyError):
return("", "", "")
return(str(hgr.gr_name), str(hgr.gr_gid), str(hgr.gr_mem))
def _get_user_from_file(self, wanted_user):
"""Get user from a passwd file"""
wanted_uid = ""
if (isinstance(wanted_user, (int, long)) or
re.match("^\\d+$", wanted_user)):
wanted_uid = str(wanted_user)
wanted_user = ""
try:
inpasswd = open(self.passwd_file)
except (IOError, OSError):
return("", "", "", "", "", "")
else:
for line in inpasswd:
(user, dummy, uid, gid, gecos, home,
shell) = line.strip().split(":")
if wanted_user and user == wanted_user:
return(user, uid, gid, gecos, home, shell)
if wanted_uid and uid == wanted_uid:
return(user, uid, gid, gecos, home, shell)
inpasswd.close()
return("", "", "", "", "", "")
def _get_group_from_file(self, wanted_group):
"""Get group from a group file"""
wanted_gid = ""
if (isinstance(wanted_group, (int, long)) or
re.match("^\\d+$", wanted_group)):
wanted_gid = str(wanted_group)
wanted_group = ""
try:
ingroup = open(self.group_file)