forked from squaresLab/BugZoo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepairbox
More file actions
executable file
·846 lines (702 loc) · 30.1 KB
/
repairbox
File metadata and controls
executable file
·846 lines (702 loc) · 30.1 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
#!/usr/bin/env python
import os
import yaml
import subprocess
import shutil
import argparse
import time
import json
import requests
from tabulate import tabulate
from tempfile import NamedTemporaryFile
from pprint import pprint as pp
DEVNULL = open(os.devnull, 'w')
remote_tag_versions = None
def error(msg):
print("Error: {}".format(msg))
exit(1)
"""
Determines the version of a given resource that exists on DockerHub, if
any.
"""
def get_remote_version(identifier):
global remote_tag_versions
try:
if remote_tag_versions is None:
r = requests.get('https://api.microbadger.com/v1/images/squareslab/repairbox')
remote_tag_versions = r.json()['Versions']
remote_tag_versions = [v["Labels"] for v in remote_tag_versions if "Labels" in v]
remote_tag_versions = \
{v["rbox.identifier"]: v["rbox.version"] \
for v in remote_tag_versions \
if "rbox.version" in v and "rbox.identifier" in v}
remote_tag_versions = {str(t): Version.from_string(str(v)) \
for (t, v) in remote_tag_versions.items()}
except KeyError:
remote_tag_versions = {}
except ValueError:
print("WARNING: MicroBadger appears to be offline. Artefacts cannot be downloaded.\n")
remote_tag_versions = {}
return None
return remote_tag_versions.get(identifier, None)
"""
Determines which version of a given resource is installed (via its tag)
"""
def get_image_version(tag):
tag = "squareslab/repairbox:{}".format(tag)
try:
cmd = "docker inspect {}".format(tag)
data = json.loads(subprocess.check_output(cmd, stderr=DEVNULL, shell=True))
version = data[0]['Config']["Labels"]["rbox.version"]
return Version.from_string(version)
except KeyError:
error("failed to find `rbox.version` label for image: {}".format(tag))
except subprocess.CalledProcessError as e:
return None
"""
Builds a docker container image using a given Dockerfile, tag, and set of
build-time arguments
@param fn The Dockerfile for this container image
@param tag The tag for container image
@param version The version of this container image
@param parent The tag for the parent container image, if any
@param args An optional dict of build-time arguments
"""
def dockerbuild(fn, tag, version, identifier=None, parent=None, args={}):
# we actually create a clone of the original Dockerfile, with a few
# nifty changes
d = os.path.dirname(fn)
contents = []
with open(fn, "r") as f:
contents = [line.rstrip('\n') for line in f]
# inject a FROM command, if relevant
if not parent is None:
contents = [l for l in contents if not l.startswith('FROM ')]
contents.insert(0, "FROM squareslab/repairbox:{}".format(parent))
# inject a LABEL command
contents.append("LABEL rbox.version='{}' rbox.identifier='{}'".format(str(version), identifier))
# we then write the modified Dockerfile to the directory of the original
# Dockerfile
tmp_fn = os.path.join(d, ".Dockerfile")
with open(tmp_fn, "w") as f:
f.write("\n".join(contents))
tag = "squareslab/repairbox:{}".format(tag)
args = ["--build-arg {}='{}'".format(k,v) for (k,v) in args.items()]
args = ' '.join(args)
cmd = "docker build -f {} {} -t {} {}".format(tmp_fn, args, tag, d)
crashfile = "{}.rbox.crash".format(int(time.time()))
try:
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
status = out.splitlines()[-1].startswith('Successfully ')
except subprocess.CalledProcessError as e:
# save crash log
with open(crashfile, "w") as cf:
cf.write("Attempting to build image: {}\n".format(tag))
cf.write("Command: {}\n".format(cmd))
cf.write(e.output)
status = False
finally:
os.remove(tmp_fn)
if not status:
print("Failed to build image: {}".format(tag))
print("Saved error log to: {}".format(crashfile))
exit(1)
"""
Represents a version of a particular resource
"""
class Version(object):
@staticmethod
def from_string(s):
parts = [int(k) for k in s.split('.')]
parent = None
version = None
for part in parts:
parent = version = Version(part, parent)
return version
def __init__(self, num, parent=None):
assert(type(num) is int)
assert(num >= 0)
self.__num = num
self.__parent = parent
def suffix(self):
return self.__num
def prefix(self):
return self.__parent
def __str__(self):
s = "{}.".format(str(self.__parent)) if self.__parent else ""
s += str(self.__num)
return s
def __eq__(self, other):
return (not other is None) \
and self.__num == other.suffix() \
and self.__parent == other.prefix()
"""
Used to model all resources except for tools.
"""
class Resource(object):
def __init__(self, location, name, dockerfile, version_suffix, build_ctx, parent=None, buildargs={}):
self.location = location
self.dockerfile = os.path.join(os.path.dirname(location), dockerfile)
self.name = str(name)
self.__buildargs = buildargs
self.parent = parent
assert build_ctx is None or isinstance(build_ctx, str)
if build_ctx is None:
self.__buildctx = None
else:
self.__buildctx = os.path.join(os.path.dirname(location), build_ctx)
self.__buildctx = os.path.abspath(self.__buildctx)
if self.parent:
self.__version_latest = Version(version_suffix, parent.version_latest())
else:
self.__version_latest = Version(version_suffix)
assert parent is None or isinstance(parent, Resource)
assert os.path.isfile(self.dockerfile), \
"Dockerfile not found for resource: {}".format(self.identifier())
def tag(self):
return self.identifier('-')
def identifier(self, delimiter=':'):
if self.parent and not isinstance(self.parent, BaseImage):
return self.parent.identifier(delimiter) + delimiter + self.name
return self.name
def version_latest(self):
return self.__version_latest
def version_installed(self):
try:
return self.__version_installed
except AttributeError:
self.__version_installed = get_image_version(self.tag())
return self.__version_installed
def is_installed(self):
return not (self.version_installed() is None)
def is_latest(self):
return self.version_latest() == self.version_installed()
"""
Uninstalls this resource, by removing its Docker container image
"""
def uninstall(self):
if not self.is_installed():
return
print("uninstalling resource: {}".format(self.identifier()))
cmd = "docker rmi squareslab/repairbox:{}".format(self.tag())
try:
subprocess.check_call(cmd, shell=True)
except subprocess.CalledProcessError as e:
exit("failed to uninstall resource: {}".format(self.identifier()))
def build(self):
if self.is_latest():
return
if self.parent:
self.parent.build()
print("building image: {}".format(self.name))
ptag = self.parent.tag() if self.parent else None
# create a temporary Dockerfile if a build context is in use
if self.__buildctx is None:
dockerfile = self.dockerfile
else:
dockerfile = os.path.join(self.__buildctx, ".Dockerfile")
shutil.copyfile(self.dockerfile, dockerfile)
try:
dockerbuild(dockerfile,
self.tag(),
self.version_latest(),
self.identifier(),
ptag,
self.__buildargs)
# if we're using a build context, ensure that the temporary Dockerfile
# is destroyed
finally:
if not self.__buildctx is None and os.path.isfile(dockerfile):
#os.remove(dockerfile)
pass
self.__version_installed = self.__version_latest
"""
All datasets must sit on top of a base image. Ideally, all bug scenarios should
only use one base image, but there are cases where different base images may
be needed (e.g., 32-bit containers).
"""
class BaseImage(Resource):
@staticmethod
def load(fn):
with open(fn, "r") as f:
try:
data = yaml.load(f)
return BaseImage(fn,
data['base'],
data['dockerfile'],
data['version'],
data.get('build-context', None),
data.get('build-arguments', {}))
except yaml.YAMLError as exc:
raise Exception("Failed to load base image: {}".format(fn))
def __init__(self, location, name, dockerfile, version_suffix, build_ctx, build_args):
super(BaseImage, self).__init__(location, name, dockerfile, version_suffix, build_ctx, None, build_args)
class Dataset(Resource):
@staticmethod
def load(fn, bases):
with open(fn, "r") as f:
try:
data = yaml.load(f)
return Dataset( fn,
data['dataset'],
bases[data['base']],
data['dockerfile'],
data['version'],
data.get('build-context', None),
data.get('build-arguments', {}))
except yaml.YAMLError as exc:
raise Exception("Failed to load dataset: {}".format(fn))
def __init__(self, location, name, base, dockerfile, version_latest, build_ctx, build_args):
assert not base is None and isinstance(base, BaseImage)
super(Dataset, self).__init__(location, name, dockerfile, version_latest, build_ctx, base, build_args)
"""
All programs must belong to a dataset.
"""
class Program(Resource):
@staticmethod
def find(dataset, program, database):
identifier = "{}:{}".format(dataset, program)
return database[identifier]
@staticmethod
def load(fn, datasets):
with open(fn, "r") as f:
try:
data = yaml.load(f)
dataset = datasets[data['dataset']]
assert not dataset is None, "no dataset found: {}".format(dsname)
return Program(fn,
data['program'],
dataset,
data['dockerfile'],
data['version'],
data.get('build-context', None),
data.get('build-arguments', {}))
except yaml.YAMLError as exc:
raise Exception("Failed to load program: {}".format(fn))
def __init__(self, location, name, dataset, dockerfile, version_suffix, build_ctx, build_args):
assert not dataset is None and isinstance(dataset, Dataset)
super(Program, self).__init__(location, name, dockerfile, version_suffix, build_ctx, dataset, build_args)
def dataset(self):
return self.parent
"""
All bugs must belong to a dataset, but they need not belong to a program.
"""
class Bug(Resource):
@staticmethod
def load(fn, programs, datasets):
with open(fn, "r") as f:
try:
data = yaml.load(f)
# find the dataset to which the bug belongs
dsname = data['dataset']
dataset = datasets[dsname]
assert not dataset is None, "no dataset found: {}".format(dsname)
# find the program to which the bug belongs, if any
if 'program' in data:
parent = Program.find(dsname, data['program'], programs)
else:
parent = dataset
return Bug(fn,
data['bug'],
data['dockerfile'],
data.get('build-arguments', {}),
data['version'],
data.get('build-context', None),
parent)
except yaml.YAMLError as exc:
print(exc)
raise Exception("Failed to load bug: {}".format(fn))
def __init__(self, location, name, dockerfile, buildargs, version_suffix, build_ctx, parent):
assert not parent is None and \
(isinstance(parent, Dataset) or isinstance(parent, Program))
super(Bug, self).__init__(location, name, dockerfile, version_suffix, build_ctx, parent, buildargs)
def program(self):
if isinstance(self.parent, Program):
return self.parent
return None
def dataset(self):
if isinstance(self.parent, Program):
return self.parent.parent
return self.parent
def version_remote(self):
try:
return self.__version_remote
except AttributeError:
self.__version_remote = get_remote_version(self.identifier())
return self.__version_remote
"""
Installs this resource. Tries to download the remote image, if it is
up-to-date. If the remote image is not up-to-date, the image will be built
locally, instead.
"""
def install(self):
if self.is_installed():
return
if self.version_remote() == self.version_latest():
self.download()
else:
self.build()
"""
Attempts to upload the container image for this bug to DockerHub
"""
def upload(self):
self.build()
if self.version_remote() == self.version_installed():
return
print("uploading bug: {}".format(self.name))
tag = "squareslab/repairbox:{}".format(self.tag())
cmd = "docker push {}".format(tag)
try:
subprocess.check_call(cmd, shell=True)
except subprocess.CalledProcessError as e:
exit("failed to push container image: {}".format(tag))
print("uploaded bug: {}".format(self.name))
self.__version_remote = self.version_installed()
"""
Attempts to download the container image for this bug to DockerHub
"""
def download(self):
if self.version_remote() is None:
print("skipping download: {} (no remote)".format(self.name))
return
print("downloading bug: {}".format(self.name))
cmd = ["docker", "pull", "squareslab/repairbox:{}".format(self.tag())]
try:
subprocess.check_call(cmd, stderr=DEVNULL)
except subprocess.CalledProcessError as e:
exit("failed to download resource: {}".format(self.identifier()))
self.__version_installed = self.version_remote()
class Tool(object):
@staticmethod
def load(fn):
with open(fn, "r") as f:
try:
data = yaml.load(f)
env = data.get('environment', {})
return Tool(fn, data['tool'], data['image'], env)
except yaml.YAMLError as exc:
print(exc)
raise Exception("Failed to load tool: {}".format(fn))
def __init__(self, location, name, image, environment):
self.location = location
self.name = name
self.image = image
self.environment = environment
assert isinstance(environment, dict)
def identifier(self):
return self.name
def install(self):
if self.is_installed():
return
print("Installing tool: {}".format(self.name))
cmd = ["docker", "pull", self.image]
try:
subprocess.check_call(cmd, stderr=DEVNULL)
except subprocess.CalledProcessError as e:
exit("Failed to install tool: {}".format(self.name))
print("Installed tool: {}".format(self.name))
def is_installed(self):
cmd = ["docker", "inspect", self.image]
return subprocess.call(cmd, stdout=DEVNULL, stderr=DEVNULL) == 0
class RepairBox(object):
"""
Constructs a new RepairBox interface
"""
def __init__(self, location=os.path.dirname(os.path.realpath(__file__))):
self.location = location
# find all bases, datasets, programs, bugs and tools
self.bases = []
self.datasets = []
self.programs = []
self.bugs = []
self.tools = []
for (root, dirs, files) in os.walk(location):
self.bases += \
[os.path.join(root, f) for f in files if f.endswith(".base.yaml")]
self.datasets += \
[os.path.join(root, f) for f in files if f.endswith(".dataset.yaml")]
self.programs += \
[os.path.join(root, f) for f in files if f.endswith(".program.yaml")]
self.bugs += \
[os.path.join(root, f) for f in files if f.endswith(".bug.yaml")]
self.tools += \
[os.path.join(root, f) for f in files if f.endswith(".tool.yaml")]
# parse and type check manifests
self.bases = [BaseImage.load(fn) for fn in self.bases]
self.bases = {base.name: base for base in self.bases}
self.datasets = [Dataset.load(fn, self.bases) for fn in self.datasets]
self.datasets = {ds.name: ds for ds in self.datasets}
self.programs = [Program.load(fn, self.datasets) for fn in self.programs]
self.programs = {p.identifier(): p for p in self.programs}
self.bugs = [Bug.load(fn, self.programs, self.datasets) for fn in self.bugs]
self.bugs = {bug.identifier(): bug for bug in self.bugs}
self.tools = [Tool.load(fn) for fn in self.tools]
self.tools = {t.identifier(): t for t in self.tools}
"""
Gets a list of all bugs belonging to a given resource identifier
"""
def get(self, identifier):
parts = len(identifier.split(':'))
if identifier == 'all':
return [self.bugs[name] for name in sorted(self.bugs.keys())]
elif parts == 3 or (parts == 2 and identifier in self.bugs):
if not identifier in self.bugs:
error("failed to find bug: {}".format(identifier))
return [self.bugs[identifier]]
elif parts == 2:
if not identifier in self.programs:
error("failed to find program: {}".format(identifier))
program = self.programs[identifier]
bugs = [bug for (name, bug) in sorted(self.bugs.items()) if bug.program() == program]
return bugs
elif parts == 1:
if not identifier in self.datasets:
error("failed to find dataset: {}".format(identifier))
dataset = self.datasets[identifier]
bugs = [bug for (name, bug) in sorted(self.bugs.items()) if bug.dataset() == dataset]
return bugs
else:
error("illegal resource identifier")
"""
Returns a list of all tools registered with RepairBox, sorted alphabetically
"""
def list_tools(self, quiet=False):
if quiet:
return '\n'.join(sorted(self.tools.keys()))
hdrs = ["Tool", "Image", "Installed"]
tbl = []
for name in sorted(self.tools.keys()):
tool = self.tools[name]
tbl.append([name, tool.image, tool.is_installed()])
return tabulate(tbl, hdrs)
"""
Returns a list of all the bugs within RepairBox, sorted alphabetically
"""
def list_bugs(self, quiet=False):
if quiet:
return '\n'.join(sorted(self.bugs.keys()))
hdrs = ["Bug", "Latest", "Installed", "Remote"]
tbl = []
for bug in sorted(self.bugs.keys()):
bug = self.bugs[bug]
vlatest = bug.version_latest()
vinstalled = bug.version_installed()
vremote = bug.version_remote()
tbl.append([bug.identifier(), str(vlatest), str(vinstalled), str(vremote)])
return tabulate(tbl, hdrs)
"""
Returns a list of all the datasets within RepairBox, sorted alphabetically
"""
def list_datasets(self, quiet=False):
if quiet:
return '\n'.join(sorted(self.datasets.keys()))
hdrs = ["Dataset", "Programs", "Bugs"]
tbl = []
for (name, dataset) in self.datasets.items():
num_programs = sum(1 for p in self.programs.values() if p.dataset() == dataset)
num_bugs = sum(1 for b in self.bugs.values() if b.dataset() == dataset)
tbl.append([dataset.identifier(), num_programs, num_bugs])
return tabulate(tbl, hdrs)
"""
Returns a list of all the programs within RepairBox, sorted alphabetically
"""
def list_programs(self, quiet=False):
if quiet:
return '\n'.join(sorted(self.programs.keys()))
hdrs = ["Program", "Bugs"]
tbl = []
for (name, program) in self.programs.items():
num_bugs = sum(1 for b in self.bugs.values() if b.program() == program)
tbl.append([program.identifier(), num_bugs])
return tabulate(tbl, hdrs)
"""
Prints a list of all artefacts of a given kind within RepairBox, sorted alphabetically
"""
def list(self, kind, quiet):
lister = ({ 'bugs': lambda: self.list_bugs(quiet),
'programs': lambda: self.list_programs(quiet),
'datasets': lambda: self.list_datasets(quiet),
'tools': lambda: self.list_tools(quiet)})
print(lister[kind]())
"""
Builds all bug images belonging to a given resource identifier
"""
def build(self, identifier):
for bug in self.get(identifier):
bug.build()
"""
Uploads all bug images belonging to a given resource identifier
"""
def upload(self, identifier):
for bug in self.get(identifier):
bug.upload()
"""
Downloads all bug images belonging to a given resource identifier
"""
def download(self, identifier):
for bug in self.get(identifier):
bug.download()
"""
Installs either: all bug images belonging to a given resource identifier.
"""
def install(self, identifier, kind):
if kind == 'bug':
for bug in self.get(identifier):
bug.install()
elif kind == 'tool':
if not identifier in self.tools:
error("Failed to find tool: {}".format(identifier))
tool = self.tools[identifier]
if tool.is_installed():
print("Tool already installed: {}".format(identifier))
else:
tool.install()
"""
Uninstalls all bug images belonging to a given resource identifier
"""
def uninstall(self, identifier):
for bug in self.get(identifier):
bug.uninstall()
def execute(self, bug, volumes, tools, command):
return self.launch(bug, volumes, tools, command, True)
"""
Launches a named repair box
"""
def launch(self, bug, volumes=[], tools=[], command='/bin/bash', headless=False):
# ensure the bug exists and is installed
if not bug in self.bugs:
error("failed to locate bug with identifier: {}".format(bug))
bug = self.bugs[bug]
bug.install()
# ensure the tools exist and are installed
env = {}
for tool in tools:
if not tool in self.tools:
error("failed to locate tool: {}".format(tool))
self.tools[tool].install()
env.update(self.tools[tool].environment)
# TODO: sanity check the volume commands
volume_arguments = []
for volume in volumes:
volume_arguments += ["-v", volume]
tool_containers = []
# generate a file containing the environmental variables for this execution
# we use volume mounting to load these variables, rather than "--env";
# this allows us to load nested env. vars
env = "\n".join(["{}={}".format(k, v) for (k, v) in env.items()])
env_file = NamedTemporaryFile()
env_file.write(env)
env_file.flush()
# Determine if should we run headless or interactive
run_mode = "-i" if headless else "-it"
try:
# launch the tools containers
for tool in tools:
tool = self.tools[tool]
cmd = ["docker", "create", "--log-driver", "none", tool.image]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, _) = p.communicate()
container = str(out)[:12]
tool_containers.append(container)
# prepare the arguments for this tool
volume_arguments += ["--volumes-from", container]
# launch the bug container
cmd = ["docker", "run", run_mode, "--rm", "--log-driver", "none"]
cmd += ["-v", "{}:{}".format(env_file.name, "/experiment/.env")]
cmd += volume_arguments
cmd += ["squareslab/repairbox:{}".format(bug.tag())]
# compute the command
command = "sudo chown \$(whoami) /experiment/.env && source /experiment/.env && {}".format(command)
cmd += ["/bin/bash", "-c \"{}\"".format(command)]
# I really don't like this, but sadly it's needed to stop Python weirdly quoting args
# TODO: find a nicer solution
cmd = " ".join(cmd)
p = subprocess.Popen(cmd, shell=True)
p.communicate()
# ensure all containers are destroyed
finally:
env_file.close()
for c in tool_containers:
cmd = ["docker", "rm", c]
p = subprocess.Popen(cmd, stdout=DEVNULL, stderr=DEVNULL)
p.communicate()
if __name__ == "__main__":
rbox = RepairBox()
with open(os.path.join(os.path.dirname(__file__), "banner.txt"), "r") as f:
desc = f.read()
parser = argparse.ArgumentParser(description=desc,
formatter_class=argparse.RawDescriptionHelpFormatter)
subparsers = parser.add_subparsers()
parser.add_argument('--version', action='version', version='0.0.1')
# action: build
build_parser = subparsers.add_parser('build')
build_parser.add_argument('identifier',
help='identifier of the resource whose boxes should be built')
build_parser.set_defaults(func=lambda args: rbox.build(args.identifier))
# action: upload
upload_parser = subparsers.add_parser('upload')
upload_parser.add_argument('identifier',
help='identifier of the resource whose boxes should be uploaded')
upload_parser.set_defaults(func=lambda args: rbox.upload(args.identifier))
# action: download
download_parser = subparsers.add_parser('download')
download_parser.add_argument('identifier',
help='identifier of the resource whose boxes should be downloaded')
download_parser.set_defaults(func=lambda args: rbox.download(args.identifier))
# action: download
install_parser = subparsers.add_parser('install')
install_parser.add_argument('kind',
choices=['bug','tool'],
help='used to specify whether a set of bugs, or a tool should be installed')
install_parser.add_argument('identifier',
help='identifier of the artefact that should be installed')
install_parser.set_defaults(func=lambda args: rbox.install(args.identifier, args.kind))
# action: download
uninstall_parser = subparsers.add_parser('uninstall')
uninstall_parser.add_argument('identifier',
help='identifier of the resource whose boxes should be uninstalled')
uninstall_parser.set_defaults(func=lambda args: rbox.uninstall(args.identifier))
# action: list
list_parser = subparsers.add_parser('list')
list_parser.add_argument( '--quiet', '-q',
action='store_true',
help='print only the list of artefacts')
list_parser.add_argument( 'kind',
choices=['bugs', 'programs', 'datasets', 'tools'],
help='the kind of artefacts that should be listed')
list_parser.set_defaults(func=lambda args: rbox.list(args.kind, args.quiet))
# action: execute
execute_parser = subparsers.add_parser('execute')
execute_parser.add_argument('bug',
help='identifier for a bug')
execute_parser.add_argument('-v',
help='volume mounting command',
dest='volumes',
action='append',
default=[])
execute_parser.add_argument('--with',
help='name of a tool',
dest='tools',
action='append',
default=[])
execute_parser.add_argument('command',
help='the command that should be executed inside the repair box')
execute_parser.set_defaults(func=lambda args: rbox.execute(args.bug, args.volumes, args.tools, args.command))
# action: launch
launch_parser = subparsers.add_parser('launch')
launch_parser.add_argument('bug',
help='identifier for a bug')
launch_parser.add_argument('-v',
help='volume mounting command',
dest='volumes',
action='append',
default=[])
launch_parser.add_argument('--with',
help='name of a tool',
dest='tools',
action='append',
default=[])
launch_parser.set_defaults(func=lambda args: rbox.launch(args.bug, args.volumes, args.tools))
args = parser.parse_args()
if 'func' in vars(args):
args.func(args)