forked from opensciencegrid/cvmfs-singularity-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cvmfs-singularity-sync
executable file
·380 lines (312 loc) · 13.1 KB
/
cvmfs-singularity-sync
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
#!/usr/bin/python
# NOTE:
# This file is forked from singularity 2.2's "cli.py". I have left the
# copyright notice below untouched; this file remains under the same license.
# - Brian Bockelman
'''
bootstrap.py: python helper for Singularity command line tool
Copyright (c) 2016, Vanessa Sochat. All rights reserved.
"Singularity" Copyright (c) 2016, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of any
required approvals from the U.S. Dept. of Energy). All rights reserved.
This software is licensed under a customized 3-clause BSD license. Please
consult LICENSE file distributed with the sources of this project regarding
your rights to use or distribute this software.
NOTICE. This Software was developed under funding from the U.S. Department of
Energy and the U.S. Government consequently retains certain rights. As such,
the U.S. Government has been granted for itself and others acting on its
behalf a paid-up, nonexclusive, irrevocable, worldwide license in the Software
to reproduce, distribute copies to the public, prepare derivative works, and
perform publicly and display publicly, and to permit other to do so.
'''
import sys
import platform
# enable cross-platform/multi-distro support by setting singularity_path
# to appropriate location or to None
singularity_path = None
if platform.system() == 'Linux':
distro,version,id = platform.linux_distribution(full_distribution_name=False)
if distro == 'debian':
singularity_path = '/usr/lib/x86_64-linux-gnu/singularity/python'
elif distro == 'redhat':
singularity_path = '/usr/libexec/singularity/python'
if singularity_path not in sys.path and singularity_path is not None:
sys.path.insert(0,singularity_path)
from docker.api import get_layer, create_runscript, get_manifest, get_config, get_images, get_tags
from utils import extract_tar, change_permissions
import argparse
import os
import re
import sys
import stat
import errno
import fnmatch
import urllib2
import hashlib
import tempfile
def main():
parser = argparse.ArgumentParser(description="Bootstrap Docker images for Singularity containers deployed to CVMFS")
# Name of the docker image, required
parser.add_argument("--docker",
dest='docker',
help="name of Docker image to bootstrap, in format library/ubuntu:latest",
type=str,
default=None)
# Name of the docker image, required
parser.add_argument("--images-url",
dest='filelist',
help="URL to download a list of Docker images from",
type=str,
default=None)
# root file system of singularity image
parser.add_argument("--rootfs",
dest='rootfs',
help="the path for the root filesystem to extract to",
type=str,
default=None)
# Docker registry (default is registry-1.docker.io)
parser.add_argument("--registry",
dest='registry',
help="the registry path to use, to replace registry-1.docker.io",
type=str,
default=None)
# Flag to indicate a token is not required
parser.add_argument("--no-token",
dest='notoken',
action="store_true",
help="Indicate that auth is not required",
default=False)
try:
args = parser.parse_args()
except:
parser.print_help()
sys.exit(0)
# Find root filesystem location
if args.rootfs:
singularity_rootfs = args.rootfs
else:
singularity_rootfs = '/cvmfs/singularity.opensciencegrid.org'
singularity_rootfs = os.path.abspath(singularity_rootfs)
# Does the registry require a token?
doauth = not args.notoken
# Do we have a docker image specified?
if not args.docker and not args.filelist:
print >> sys.stderr, "No docker image or file list specified.."
return 1
if args.docker:
image = args.docker
return publish_image(image, singularity_rootfs, args.registry, doauth)
else:
final_retval = 0
fp = urllib2.urlopen(args.filelist)
for image in fp:
image = image.strip()
if image.startswith("#") or not image:
continue
namespace, repo_name, repo_tag = parse_image(image)
if '*' in repo_tag: # Treat wildcards as a glob
tag_names = get_tags(namespace, repo_name, registry=args.registry, auth=doauth)
repo_tag = fnmatch.filter(tag_names, repo_tag)
else:
repo_tag = [repo_tag]
for tag in repo_tag:
image = '%s/%s:%s' % (namespace, repo_name, tag)
retval = publish_image(image, singularity_rootfs, args.registry, doauth)
if retval:
final_retval = retval
print "All requested images have been attempted; final return code: %d" % final_retval
return final_retval
_in_txn = False
def start_txn(singularity_rootfs):
global _in_txn
if _in_txn:
return 0
if not singularity_rootfs.startswith("/cvmfs/singularity.opensciencegrid.org"):
return 0
if os.path.exists("/var/spool/cvmfs/singularity.opensciencegrid.org/in_transaction.lock"):
result = os.system("cvmfs_server abort -f singularity.opensciencegrid.org")
if result:
print >> sys.stderr, "Failed to abort lingering transaction (exit status %d)."
return 1
result = os.system("cvmfs_server transaction singularity.opensciencegrid.org")
if result:
print >> sys.stderr, "Transaction start failed (exit status %d); will not attempt update." % result
return 1
_in_txn = True
# Test CVMFS mount if applicable.
test_dir = os.path.join(singularity_rootfs, "library")
if not os.path.exists(test_dir):
try:
os.makedirs(test_dir)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
def publish_txn():
global _in_txn
if _in_txn:
_in_txn = False
return os.system("cvmfs_server publish singularity.opensciencegrid.org")
return 0
def make_final_symlink(image_dir, singularity_rootfs, namespace, repo_name, repo_tag):
"""
Create symlink: $ROOTFS/.images/$HASH -> $ROOTFS/$NAMESPACE/$IMAGE:$TAG
"""
final_path = os.path.join(singularity_rootfs, namespace, "%s:%s" % (repo_name, repo_tag))
final_dir = os.path.split(final_path)[0]
if not os.path.exists(final_dir):
retval = start_txn(singularity_rootfs)
if retval:
return retval
try:
os.makedirs(final_dir)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
if os.path.exists(final_path):
# Final symlink exists and is already correct.
link_value = os.readlink(final_path)
if link_value == image_dir:
print "Image is already latest revision."
return 0
# Otherwise, clear the symlink; we will recreate. Since CVMFS is transactional,
# we don't care that an unlink / symlink is not atomic.
retval = start_txn(singularity_rootfs)
if retval:
return retval
os.unlink(final_path)
retval = start_txn(singularity_rootfs)
if retval:
return retval
os.symlink(image_dir, final_path)
return 0
def parse_image(image):
"""
Parse an image string into image components, setting appropriate defaults.
Returns a tuple of (namespace, repo_name, repo_tag).
"""
# INPUT PARSING -------------------------------------------
# Parse image name, repo name, and namespace
# First split the docker image name by /
image = image.split('/')
# If there are two parts, we have namespace with repo (and maybe tab)
if len(image) == 2:
namespace = image[0]
image = image[1]
# Otherwise, we must be using library namespace
else:
namespace = "library"
image = image[0]
# Now split the docker image name by :
image = image.split(':')
if len(image) == 2:
repo_name = image[0]
repo_tag = image[1]
# Otherwise, assume latest of an image
else:
repo_name = image[0]
repo_tag = "latest"
return namespace, repo_name, repo_tag
def publish_image(image, singularity_rootfs, registry, doauth):
# Tell the user the namespace, repo name and tag
namespace, repo_name, repo_tag = parse_image(image)
print("Docker image to publish: %s/%s:%s" % (namespace, repo_name, repo_tag))
# IMAGE METADATA -------------------------------------------
# Use Docker Registry API (version 2.0) to get images ids, manifest
# Get an image manifest - has image ids to parse, and will be
# used later to get Cmd
manifest = get_manifest(repo_name=repo_name,
namespace=namespace,
repo_tag=repo_tag,
registry=registry,
auth=doauth)
# Get images from manifest using version 2.0 of Docker Registry API
images = get_images(manifest=manifest,
registry=registry,
auth=doauth)
images = images[::-1]
# Calculate a unique hash across all layers. We'll use that as the identifier
# for the final image.
hasher = hashlib.sha256()
for layerinfo in manifest['fsLayers']:
layer_hash = layerinfo['blobSum'].split(":")[-1]
hasher.update(layer_hash)
image_hash = hasher.hexdigest()
# The image is staged to $ROOTFS/.images/$HASH
image_dir = os.path.join(singularity_rootfs, ".images", image_hash[0:2], image_hash[2:])
# If the image has already been staged, simply return.
if os.path.exists(image_dir):
make_final_symlink(image_dir, singularity_rootfs, namespace, repo_name, repo_tag)
return publish_txn()
else:
print "Image dir, %s, does not exist; triggering CVMFS mount." % image_dir
retval = start_txn(singularity_rootfs)
if os.path.exists(image_dir): # Same as above
make_final_symlink(image_dir, singularity_rootfs, namespace, repo_name, repo_tag)
return publish_txn()
if retval:
return retval
try:
os.makedirs(image_dir)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
# DOWNLOAD LAYERS -------------------------------------------
# Each is a .tar.gz file, obtained from registry with curl
# Create a temporary directory for targzs
tmpdir = tempfile.mkdtemp(prefix="singularity-image-", dir="/var/tmp")
for image_id in images:
# Download the layer
targz = get_layer(image_id=image_id,
namespace=namespace,
repo_name=repo_name,
download_folder=tmpdir,
registry=registry,
auth=doauth)
# Extract image and remove tar
extract_tar(targz, image_dir)
os.remove(targz)
for (dirpath, dirnames, filenames) in os.walk(image_dir):
for fname in filenames:
full_fname = os.path.join(dirpath, fname)
st = os.lstat(full_fname)
old_mode = stat.S_IMODE(st.st_mode)
if (old_mode & 0444) == 0000:
new_mode = old_mode | 0400
print "Fixing mode of", full_fname, "to", oct(new_mode)
os.chmod(full_fname, new_mode)
for dname in dirnames:
full_dname = os.path.join(dirpath, dname)
st = os.lstat(full_dname)
if not stat.S_ISDIR(st.st_mode):
continue
old_mode = stat.S_IMODE(st.st_mode)
if old_mode & 0111 == 0:
new_mode = old_mode | 0100
print "Fixing mode of", full_dname, "to", oct(new_mode)
os.chmod(full_dname, new_mode)
if old_mode & 0222 == 0:
new_mode = old_mode | 0200
print "Fixing mode of", full_dname, "to", oct(new_mode)
os.chmod(full_dname, new_mode)
os.rmdir(tmpdir)
# Various fixups to make the image compatible with CVMFS and singularity.
srv = os.path.join(image_dir, "srv")
cvmfs = os.path.join(image_dir, "cvmfs")
dev = os.path.join(image_dir, "dev")
proc = os.path.join(image_dir, "proc")
sys_dir = os.path.join(image_dir, "sys")
if not os.path.exists(srv):
os.makedirs(srv)
if not os.path.exists(cvmfs):
os.makedirs(cvmfs)
if not os.path.exists(dev):
os.makedirs(dev)
if not os.path.exists(proc):
os.makedirs(proc)
if not os.path.exists(sys_dir):
os.makedirs(sys_dir)
make_final_symlink(image_dir, singularity_rootfs, namespace, repo_name, repo_tag)
# Publish CVMFS as necessary.
return publish_txn()
if __name__ == '__main__':
sys.exit(main())