/
git-results
executable file
·2023 lines (1764 loc) · 76.6 KB
/
git-results
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 python3
"""Created by Walt Woods, 2014"""
from __future__ import print_function
import argparse
import collections.abc
import datetime
import fnmatch
import inspect
import os
import pickle
import random
import re
import reprconf
import shlex
import shutil
import subprocess
import sys
# Note on tempfile - only used for configuration, not for any execution. This
# is so that if any of the git-results-* scripts invoke network file system
# activity, those files are accessible to all nodes with access to the NFS.
import tempfile
import textwrap
import threading
import time
import traceback
# For pickle, we're using git_results.* for class names. So, shenanigans
__oname__ = __name__
class __dummy(object):
pass
sys.modules['git_results'] = inspect.getmodule(__dummy)
__name__ = 'git_results'
if sys.version_info[0] > 2:
raw_input = input
ABORT_SUFFIX = '-abrt'
FAIL_SUFFIX = '-fail'
RUN_SUFFIX = '-run'
MANUAL_SUFFIX = '-manual-retry'
SUFFIXES = [ ABORT_SUFFIX, FAIL_SUFFIX, RUN_SUFFIX, MANUAL_SUFFIX, '' ]
# Overridden by tests to suppress raw_input
IS_TEST = (os.environ.get('GIT_RESULTS_TEST', '').strip() != '')
IS_TEST_FAIL_MANUAL = False
class HelpfulParser(argparse.ArgumentParser):
"""Prints help before an error.
https://stackoverflow.com/a/4042861/160205
"""
def error(self, message):
self.print_help()
sys.stderr.write('\n\nError: {}\n'.format(message))
self.exit(2)
class IndexStates(object):
ABORT = 'abrt'
FAIL = 'fail'
# GONE means BUILD FAILURE
GONE = 'gone'
OK = ' ok'
MOVE = 'move'
RUN = ' run'
MANUAL = 'rtry'
for key, val in IndexStates.__dict__.items():
if key[0] == '_':
continue
if len(val) != 4:
raise ValueError("IndexState {} has len(val) != 4".format(key))
class FolderState(object):
"""An object that tracks which files exist at init and at another time,
and can copy changes to another folder."""
def __init__(self, dir, resultsDir, args):
"""If dir is None, then this is an in-place operation, and we should
move (rather than copy) the results."""
self._args = args
self._dir = dir or os.path.abspath('.')
self._resultsDirRel = os.path.relpath(resultsDir, self._dir)
if not self._resultsDirRel.startswith(".."):
while True:
rdr = os.path.split(self._resultsDirRel)[0]
if not rdr:
break
self._resultsDirRel = rdr
self._files = set()
self._scan(self._dir)
def moveResultsTo(self, dir, trimCommonPaths = False):
"""Copy changes from self._dir to dir. Use most common path."""
allChanges = set()
self._scanChanges(self._dir, allChanges)
prefix = self._dir
if trimCommonPaths:
prefix = None
for c in allChanges:
if prefix is None:
prefix = c
else:
while not c.startswith(prefix):
prefix = os.path.dirname(prefix)
if prefix is None:
prefix = self._dir
elif not os.path.isdir(prefix):
# Only one file remains, the common path is its folder
prefix = os.path.dirname(prefix)
allErrors = []
for c in allChanges:
# Add 1 to len(prefix) so that we don't include the preceding slash,
# which would make os.path.join treat it as an absolute
target = os.path.join(dir, os.path.relpath(c, prefix))
safeMake(os.path.dirname(target))
nRetries = 4
for _retry in range(nRetries):
try:
os.rename(c, target)
except OSError as e:
if e.errno == 16 and _retry != nRetries - 1:
# Device busy, will retry
pass
elif e.errno == 2:
# 2 - No such file; was temporary
break
else:
allErrors.append("{0}: {1}".format(c, ''.join(
traceback.format_exception_only(
*sys.exc_info()[:2]))))
break
else:
break
# Will retry
time.sleep(1.)
if allErrors:
raise Exception("Errors during file move:\n\n{0}".format(
'\n\n'.join(allErrors)))
def forgetPath(self, path):
"""Forget a path and all subpaths."""
f = set()
for p in self._files:
if p.startswith(path):
f.add(p)
for p in f:
self._files.remove(p)
def _isBanned(self, path):
"""Gets a folder; returns True if it is banned (is our results dir)"""
if path == os.path.join(self._dir, self._resultsDirRel):
return True
return False
def _isIgnored(self, path):
"""Gets a file; returns True if it should be ignored."""
for ext in self._args.ignoreExt:
if path.endswith('.' + ext):
return True
# Ignore logic
relPath = os.path.relpath(path, self._dir)
excluded = False
for ext in self._args.ignore:
negate = False
if ext.startswith('!'):
negate = True
ext = ext[1:]
if '/' in ext:
if ext.startswith('/'):
ext = '^' + ext[1:]
r = re.compile(ext
.replace('\\*', '\\\\<STAR>')
.replace('**', '.\\<STAR>')
.replace('*', '[^/]\\<STAR>')
.replace('\\<STAR>', '*')
)
else:
r = re.compile(fnmatch.translate(ext))
if r.search(relPath) is not None:
excluded = not negate
return excluded
def _scan(self, path):
if self._isBanned(path):
return
for f in os.listdir(path):
ff = os.path.join(path, f)
if os.path.isfile(ff) and not self._isIgnored(ff):
self._files.add(ff)
if os.path.isdir(ff) and not os.path.islink(ff):
self._scan(ff)
def _scanChanges(self, path, changeset):
if self._isBanned(path):
return
for f in os.listdir(path):
ff = os.path.join(path, f)
if (os.path.isfile(ff) and ff not in self._files
and not self._isIgnored(ff)):
changeset.add(ff)
elif os.path.isdir(ff) and not os.path.islink(ff):
self._scanChanges(ff, changeset)
def checked(cmd, nonZeroOk = False, shell = False):
if not isinstance(cmd, (tuple, list)):
raise ValueError("Must always be a list or tuple so that quotes "
"aren't messed up")
p = subprocess.Popen(cmd, stdout = subprocess.PIPE,
stderr = subprocess.PIPE, shell = shell)
stdout, stderr = p.communicate()
r = p.poll()
if r != 0:
if (isinstance(nonZeroOk, (list, tuple)) and r in nonZeroOk
or nonZeroOk == True):
pass
else:
raise Exception("Command '{0}' failed with {1}".format(cmd, r))
return stdout.decode('utf-8')
def ensureGitignore(repoBase, resultsRoot):
output = checked([ "git", "status", "{0}/{1}/.gitignore".format(repoBase,
resultsRoot), "--porcelain", "--ignored" ]).strip()
if output and not output.startswith("!!"):
with open(os.path.join(repoBase, '.gitignore'), 'a') as f:
f.write("\n/{0}".format(resultsRoot))
def getPathForResumeKey(resumeKey, filename = None):
base = os.path.expanduser("~/.gitresults")
if resumeKey:
base = os.path.join(base, resumeKey)
if filename:
base = os.path.join(base, filename)
elif filename:
raise Exception("filename but no resumeKey?")
return base
def shellOpen(cmd):
"""Returns a subprocess.Popen object with stdout and stderr redirected to
pipes, using the correct environment.
This is done so that the supervisor has consistency with what the user
runs.
"""
osEnv = os.environ
env = {}
for k in [ 'HOME', 'LOGNAME', 'LANG' ]:
if k in osEnv:
env[k] = osEnv[k]
# For python applications, ensure that output is streamed constantly.
env['PYTHONUNBUFFERED'] = '1'
return subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True, env=env)
def tee(infile, *files):
"""Thanks to http://stackoverflow.com/a/4985080/160205, tee lines from the
given file to one or more other files.
"""
def fanout():
for line in iter(infile.readline, b''):
try:
assert isinstance(line, bytes)
line = line.decode('utf-8')
except:
line = (">>>>>>> git-results begin\n"
"{}\n"
">>>>>>> git-results end\n").format(
traceback.format_exc())
for f in files:
try:
f.write(line)
except:
# We can use below to log the exception. However, often
# this situation is caused by e.g. stderr being closed by
# the OS when launched via cron (because the cron process
# closes). Unless evidence is found that the file versions
# of stdout and stderr are lacking text, it's probably best
# to silently accept a closed stream and move on.
# Can't do much about a closed stderr or stdout
if f is sys.stderr or f is sys.stdout:
continue
tb = (">>>>>>> git-results begin\n"
"{}\n"
"\nWhile writing to {}: {}"
">>>>>>> git-results-end\n").format(
traceback.format_exc(), f, line)
with open(os.path.expanduser("~/git-results.log"), "a") as f2:
f2.write(tb)
infile.close()
t = threading.Thread(target = fanout)
t.daemon = True
t.start()
return t
def touch(fname):
"""Thanks to http://stackoverflow.com/questions/1158076/implement-touch-using-python"""
with open(fname, 'a'):
os.utime(fname, None)
def index_splitTag(repoBase, commitTag):
"""Splits (and validates) a commit tag into corresponding INDEX file and
the experiment index within the file (as a string)."""
if commitTag.startswith('/'):
raise ValueError("Should not be an absolute path! {}".format(commitTag))
indexDir, exp = os.path.split(os.path.join(repoBase, commitTag))
exp = exp.rsplit('-', 1)[0]
try:
int(exp)
except ValueError:
raise ValueError("Bad experiment number? {}".format(commitTag))
return (os.path.join(repoBase, indexDir, 'INDEX'), exp)
def indexExpunge(repoBase, commitTag):
"""Marks the given commitTag as GONE, for e.g. build failures. Never
deletes INDEX, since that is where we save the commit message. Which will
be used for the next default.
"""
# Update the index
indexUpdate(repoBase, commitTag, IndexStates.GONE)
class NotInIndexError(Exception):
pass
def indexRead(repoBase, commitTag):
"""Returns (index, state, message) for given commitTag's entry in INDEX
file. Raises NotInIndexError if commitTag not found in INDEX."""
indexFile, exp = index_splitTag(repoBase, commitTag)
if not os.path.lexists(indexFile):
raise NotInIndexError("Tag {} not found in INDEX (no INDEX)".format(
commitTag))
with open(indexFile, 'r') as f:
contents = f.read()
mState = None
mStart = None
mEnd = None
for m in re.finditer(r"^(\d+) \((....)\) - ", contents, re.MULTILINE):
if m.group(1) == exp:
mState = m.group(2)
mStart = m.end()
elif mStart is not None:
mEnd = m.start()
break
if mStart is None:
raise NotInIndexError("Tag {} not found in INDEX".format(commitTag))
if mEnd is None:
mEnd = len(contents)
return (exp, mState, contents[mStart:mEnd].strip())
def indexWrite(repoBase, commitTag, state, message):
"""Overwrites (or appends) the record for commitTag to the corresponding
INDEX file."""
indexFile, exp = index_splitTag(repoBase, commitTag)
safeMake(os.path.dirname(indexFile))
# Generate our record.
header = "{} ({}) - ".format(exp, state)
wrapper = textwrap.TextWrapper(width = 79, initial_indent = '',
subsequent_indent = ' ', replace_whitespace=True,
max_lines=3)
record = wrapper.fill(header + message.strip()) + "\n"
with open(indexFile, 'a+') as f:
f.seek(0)
contents = f.read()
fStart = None
fEnd = None
for m in re.finditer(r"^(\d+) \(....\) - ", contents, re.MULTILINE):
if m.group(1) == exp:
fStart = m.start()
elif fStart is not None:
fEnd = m.start()
break
if fStart is None:
# Append to end
f.seek(len(contents))
f.write(record)
else:
if fEnd is None:
fEnd = len(contents)
# Overwrite interval [fStart, fEnd)
f.seek(0)
f.truncate()
f.write(''.join([ contents[:fStart], record, contents[fEnd:] ]))
def indexUpdate(repoBase, commitTag, state):
"""Given a commitTag from git (with or without suffix) and a new index
state, update the (xxxx) portion of the INDEX file to reflect the given
state. Preserves the message.
"""
indexFile, exp = index_splitTag(repoBase, commitTag)
with open(indexFile, 'r+') as f:
contents = f.read()
lastMatch = None
for m in re.finditer(r"^{} \(....\) - ".format(int(exp)),
contents, re.MULTILINE):
lastMatch = m
if lastMatch is not None:
f.seek(lastMatch.start())
f.write("{} ({}) - ".format(int(exp), state))
else:
raise ValueError("{} not found in INDEX".format(commitTag))
def runExperiment(args, dir, workingDir, extraFiles, resultsDir, commitTag,
trimCommonPaths):
"""Given a directory to initialize and run our experiment in 'dir', run it
and put results in 'resultsDir'
workingDir - Relative to dir, where to execute from.
Populates args.isGoingToRetry if args.retry_until_stall is set.
dir can be None for current dir (not a temporary directory!)
"""
# If False, this is a retry that has already been built.
shouldBuild = True
# Folder state post-build; used to identify run results vs build
# intermediates
fs = None
if args.retry_until_stall:
# Set this attribute so that we have access to it.
args.isGoingToRetry = False
if os.path.lexists(getPathForResumeKey(args.retryKey, "build-state")):
shouldBuild = False
def writeRetryStats():
"""Write a bunch of stats from our closure"""
open(getPathForResumeKey(args.retryKey, "build-state.new"),
'wb').write(pickle.dumps({
'buildTime': preRun - preBuild,
'runStart': preRun,
'fs': fs,
'progress': lastProgress,
'retry': retryIndex }))
os.rename(getPathForResumeKey(args.retryKey, "build-state.new"),
getPathForResumeKey(args.retryKey, "build-state"))
if dir is None:
dirRelative = '.'
else:
dirRelative = dir
dir = os.path.abspath(dir)
resultsDirRelative = resultsDir
resultsDir = os.path.abspath(resultsDir)
odir = os.getcwd()
if dir is not None:
os.chdir(dir)
# Output files, will be opened later
output = None
error = None
try:
# Timers
preBuild = preRun = None
# Keeps track of last known completed progress _at the start_ of an
# execution.
# Used to determine stalls (intransient errors). Updated at end of
# execution (on failure) if there was a change in progress since the
# last update.
lastProgress = -1e300
# The current retry index.
retryIndex = 0
if shouldBuild:
buildHeartbeatStop = False
buildHeartbeat = None
if args.retry_until_stall:
def hbUpdate():
tsleep = max(1e-2, args.retry_delay / 3.0)
touch(getPathForResumeKey(args.retryKey, "heartbeat"))
while not buildHeartbeatStop:
time.sleep(tsleep)
touch(getPathForResumeKey(args.retryKey, "heartbeat"))
buildHeartbeat = threading.Thread(target = hbUpdate)
buildHeartbeat.daemon = True
buildHeartbeat.start()
# Build not previously completed, rebuild project
if dir is not None:
checked([ "git", "init" ])
checked([ "git", "remote", "add", "origin",
"file://" + args.base ])
checked([ "git", "fetch", "origin", commitTag ])
checked([ "git", "reset", "--hard", "FETCH_HEAD" ])
# Copy supplementary (extra) files over to our tree before build
cfgLeaf = os.path.dirname(args.tag_root)
for f in extraFiles:
fFrm, fTo = f.split(':')
shutil.copy2(os.path.join(args.cwd, fFrm),
os.path.join(dir, cfgLeaf, fTo))
# At this point, we have the directory with the right git-results-*.
os.chdir(workingDir or os.path.curdir)
preBuild = time.time()
if args.build:
print("Building {0} in {1}".format(commitTag, dirRelative))
# stderr redirection benefits nosetests, mainly.
p = shellOpen(args.build)
thread = tee(p.stdout, sys.stdout)
thread2 = tee(p.stderr, sys.stderr)
thread.join()
thread2.join()
r = p.wait()
if r != 0:
print("== BUILD FAILED ==")
sys.exit(1)
else:
print("Skipping build, none specified for {0}".format(
commitTag))
# Now that we've built it, snapshot the folder so we can copy whatever
# changed as results. We'll be a little smart and take off the
# greatest common path too...
changeRoot = os.path.join(dir or '.',
os.path.dirname(args.tag_root))
fs = FolderState(changeRoot, resultsDir, args)
for f in extraFiles:
_, fTo = f.split(':')
fs.forgetPath(os.path.join(os.path.join(dir, cfgLeaf, fTo)))
# Actual run starts now..ish. Yes, this doesn't include scanning
# the folder state. However, for a retry, we want to remember both
# how long the build took and the cumulative runtime.
preRun = time.time()
if args.retry_until_stall:
buildHeartbeatStop = True
buildHeartbeat.join()
# Save fs so that we know that we've already built
writeRetryStats()
touch(getPathForResumeKey(args.retryKey, "heartbeat"))
else:
# Previously built OK, use old values
try:
d = pickle.loads(open(getPathForResumeKey(args.retryKey,
"build-state"), 'rb').read(), encoding='bytes')
except pickle.UnpicklingError:
# Corrupt test; mark as failed, append to stderr!
with open('{0}/stderr'.format(resultsDir), 'a') as f:
f.write("\n\ngit-results detected bad formatting for "
"pickle file build-state; copied to result "
"directory and marking experiment failed")
return 1, False, False
fs = d['fs']
preRun = time.time() - (os.path.getmtime(getPathForResumeKey(
args.retryKey, "heartbeat")) - d['runStart'])
preBuild = preRun - d['buildTime']
lastProgress = d['progress']
retryIndex = d['retry']
touch(getPathForResumeKey(args.retryKey, "heartbeat"))
# Already have the directory with the right git-results-*.
os.chdir(workingDir or os.path.curdir)
hasProgress = args.retry_until_stall
print("Running {0} in {1}".format(commitTag, dirRelative))
print("=" * 79)
print("=" * 79)
threadsShouldDie = False
threads = []
if hasProgress:
def checkProgress():
"""Returns the monotonically increasing, floating-point number
that denotes progress. If retry_until_stall is set, also
updates the progress file associated with the retry."""
p = shellOpen(args.progress)
stdout, stderr = p.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
r = p.wait()
try:
value = float(stdout.strip().split('\n')[-1])
except ValueError:
raise ValueError(("Last non-blank line must be a "
+ "floating-point number; was: {}").format(
stdout.strip().split('\n')[-1]))
return value
if args.retry_until_stall:
# Update heartbeats
def hbUpdate():
tsleep = max(1e-2, args.retry_delay / 3.0)
touch(getPathForResumeKey(args.retryKey, "heartbeat"))
while not threadsShouldDie:
time.sleep(tsleep)
touch(getPathForResumeKey(args.retryKey, "heartbeat"))
hbThread = threading.Thread(target = hbUpdate)
hbThread.daemon = True
hbThread.start()
threads.append(hbThread)
iothreads = []
# Name of abort type, if applicable, or False for no abort type
didAbort = False
# Special handling for our runner script
line_buffered = 1
output = open('{0}/stdout'.format(resultsDir), 'a', line_buffered)
error = open('{0}/stderr'.format(resultsDir), 'a', line_buffered)
if not args.internal_retry_abort:
# Set up exit precautions...
def inner_check():
"""Function responsible for handling KeyboardInterrupt
behavior. Recurses as much as needed.
"""
nonlocal r, didAbort
try:
[t.join() for t in iothreads]
r = p.wait()
didAbort = "abort"
except KeyboardInterrupt:
inner_check()
# For whatever reason, KeyboardInterrupt() may manifest multiple
# times. Make sure that doesn't happen.
try:
try:
p = shellOpen(args.run)
iothreads = [ tee(p.stdout, output, sys.stdout),
tee(p.stderr, error, sys.stderr) ]
[ t.join() for t in iothreads ]
r = p.wait()
except KeyboardInterrupt:
# Child got Ctrl+C,
print("== CTRL+C caught by git-results; child should exit as per "
"CTRL+C semantics")
inner_check()
except:
traceback.print_exc()
inner_check()
except KeyboardInterrupt:
print("== CTRL+C caught by git-results; child should exit as per "
"CTRL+C semantics (2)")
inner_check()
else:
r = 1
didAbort = "abort"
# output, error are both closed in outer finally
allDone = time.time()
print("=" * 79)
print("=" * 79)
# Any exceptions raised cause the whole experiment to be deleted.
# So, catch them, redirect them to error, and
wasMoveFailure = False
try:
if r != 0 or didAbort:
error.write(("\n\ngit-results detected abnormal program "
"termination: {0}\n").format(r))
print("Non-zero exit status after {0}: {1}".format(
allDone - preRun, r))
if args.retry_until_stall and not didAbort:
# Chance of supervisor retry...
if not hasProgress:
raise Exception("No git-results-progress but "
"retry_until_stall?")
newProgress = checkProgress()
if lastProgress > newProgress:
raise Exception("Progress MUST be a non-decreasing "
+ "function")
elif lastProgress == newProgress:
# Stall; note that the FIRST potentially transient
# failure will happen with lastProgress != newProgress,
# so if retryIndex was 0, this is technically the first
# retry
retryIndex += 1
if args.retry_minimum > retryIndex:
args.isGoingToRetry = True
writeRetryStats()
else:
# Cannot retry! Switch to manual mode
args.isGoingToRetry = True
writeRetryStats()
didAbort = "manual"
else:
# Progress!
lastProgress = newProgress
retryIndex = 0
args.isGoingToRetry = True
writeRetryStats()
else:
print("OK after {0}".format(allDone - preRun))
if not args.retry_until_stall or not args.isGoingToRetry:
with open(os.path.join(resultsDir, 'git-results-message'),
'a') as f:
f.write("\n\n")
f.write("{0} after {1}s\n".format(
"OK" if r == 0 else "FAIL", allDone - preRun))
f.write("Build took {0}s\n".format(preRun - preBuild))
# If we reach here, everything ran OK, so copy files
print("Copying results to {0}".format(resultsDirRelative))
try:
fs.moveResultsTo(resultsDir, trimCommonPaths)
except:
wasMoveFailure = True
raise
except:
# Only thing we change is that our result is no longer zero.
tbErr = traceback.format_exc()
sys.stderr.write(tbErr)
error.write("\n\ngit-results error: {0}\n".format(tbErr))
if r == 0 and not wasMoveFailure:
# It's over 9000
r = 9001
# Terminate e.g. heartbeat thread
threadsShouldDie = True
[ t.join() for t in threads ]
return r, didAbort, wasMoveFailure
finally:
if output:
output.close()
if error:
error.close()
os.chdir(odir)
def safeMake(path):
try:
os.makedirs(path)
except OSError as e:
# exists
if e.errno != 17:
raise
def safeRemove(f):
"""Removes a single file, safely"""
try:
os.remove(f)
except OSError as e:
# No such file or directory
if e.errno != 2:
raise
def safeRemoveDir(d):
try:
shutil.rmtree(d)
except OSError as e:
# No such file or directory
if e.errno != 2:
raise
def safeRollback(d):
"""Delete d and all parent directories (up to most common directory with
current directory)
"""
try:
os.removedirs(d)
except OSError as e:
# Directory not empty OR no such file or directory (66 is mac os x)
if e.errno != 39 and e.errno != 2 and e.errno != 66:
raise
def setupExperiment(args, repoBase, resultsRoot, resultsLeaf, message):
"""Sets up the experiment skeleton and commits the git repo to an acceptable
state.
resultsRoot is the directory containing results.
resultsLeaf is the rest of the experiment path, within resultsRoot.
If message is unspecified, will prompt for a suitable message.
Returns the directory for results (absolute path), dated symlink path (for
rollback / updated), latest symlink path, and the commit tag to run.
"""
resultsDir = os.path.abspath(os.path.join(repoBase, resultsRoot))
experimentDir = os.path.join(resultsDir, resultsLeaf)
if not os.path.lexists(os.path.join(resultsDir, ".gitignore")):
if not IS_TEST:
r = raw_input("To do this, git-results needs to make a new "
"results directory:\n\n{0}\n\nin repository {1}.\nIt will "
"also be added to the repository's .gitignore. Is "
"this ok? (y/n) ".format(resultsRoot, repoBase))
r = r.strip().lower()
if r != 'y':
raise SystemExit("y not entered")
safeMake(resultsDir)
# If we don't make a file, it looks like results is always ignored even
# though it isn't. So, make a sensible .gitignore to start if people
# want to revision their results.
with open("{0}/.gitignore".format(resultsDir), 'w') as f:
f.write("/.tmp\n")
# Now that it's made, make sure it's ignored
ensureGitignore(repoBase, resultsRoot)
# Allow / encourage running same tag several times. We'll use /1, /2, etc
n = 1
if os.path.lexists(experimentDir):
# Folder containing results under this tag exists. Check both extant
# folders and INDEX file to get next index.
for run in os.listdir(experimentDir):
# Remove any suffixes
run = run.split('-', 1)[0]
try:
n = max(n, int(run) + 1)
except ValueError:
# Not an integer, probably a file someone bundled in with the
# results.
pass
indexFile = os.path.join(experimentDir, 'INDEX')
if os.path.lexists(indexFile):
for nid in re.finditer(r'^(\d+) \((....)\)',
open(indexFile).read(), re.M):
# GONE experiments are no longer registered, so their numbers
# can be reused. Trade-off is that the record will be
# overwritten.
if nid.group(2) != IndexStates.GONE:
n = max(n, int(nid.group(1)) + 1)
# the tag for this instance of the experiment
tag = "{0}/{1}/{2}".format(resultsRoot, resultsLeaf, n)
tagDir = os.path.join(experimentDir, "{0}".format(n))
## It's too easy to include files that shouldn't be included, like images
# or temporary files, without seeing git status. Therefore, check if we
# have local changes. If we do, inquire about that commit first.
cleanMessage = '' if not message else message
if not cleanMessage:
try:
_tag, _state, oldMessage = indexRead(repoBase, tag)
except NotInIndexError:
pass
else:
cleanMessage = oldMessage.strip()
if checked([ "git", "status", "--porcelain" ]).strip():
# Need to make a commit. Open up our message in git-results
branch = "git-results"
# Include the path to git-results.cfg as an annotation for the branch
pathToCur = os.path.relpath(os.path.dirname(resultsDir), repoBase)
if pathToCur != os.path.curdir:
branch += "-{}".format(pathToCur)
# If this fails, the branch didn't exist or we're already on it, both
# of which are fine
checked([ "git", "checkout", "-B", branch ])
checked([ "git", "add", "-A", repoBase ])
# Note that we run this outside of checked(), since we must share all
# input/output
cmd = [ "git", "commit", "-m", cleanMessage ]
if not IS_TEST:
# -e means edit the message in the git editor.
cmd.append("-e")
p = subprocess.Popen(cmd)
r = p.wait()
else:
# Bypass user-input sections for testing.
for s in ['echo', 'cat']:
if os.environ.get('EDITOR', '').startswith(s):
cmd.append("-e")
break
print(os.environ.get('EDITOR'))
checked(cmd)
print("DONE")
r = 0
if r != 0:
raise Exception("Command '{0}' failed with {1}".format(cmd, r))
# Read back commit message, use for git-results
curCommit = checked([ "git", "rev-parse", "HEAD" ]).strip()
cleanMessage = checked([ "git", "log", "--format=%B", "-n", "1",
curCommit ]).strip()
else:
# No commit necessary. Do we need a message anyway?
# NOTE: deliberately use "message" here, not "cleanMessage".
# cleanMessage was previously overwritten with the prior index state,
# so it would not be empty, but we'd still want to prompt for changes.
if not message:
cleanMessage = _getStringViaEditor("git-results needs an "
"experiment message", default=cleanMessage)
if len(cleanMessage) < 5 or cleanMessage.startswith("Please replace"):
raise ValueError("Message must be at least 5 characters; "
"got: '" + cleanMessage + "'")
curCommit = checked([ "git", "rev-parse", "HEAD" ]).strip()
# Actually make our folder
tagDirRun = tagDir + RUN_SUFFIX
safeMake(tagDirRun)
linkAs = None
latestLinkAs = None
try:
# Ensure INDEX file
indexWrite(repoBase, tag, IndexStates.RUN, cleanMessage)
# Dated linkage
now = datetime.datetime.now()
dated = os.path.join(resultsDir, 'dated', now.strftime("%Y"),
now.strftime("%m"))
safeMake(dated)
linkAs = os.path.join(dated, "{0}-{1}/{2}{3}".format(now.strftime("%d"),
resultsLeaf, n, RUN_SUFFIX))
safeMake(os.path.dirname(linkAs))
os.symlink(os.path.relpath(tagDirRun, os.path.dirname(linkAs)), linkAs)
latestLinkAs = os.path.join(resultsDir, 'latest', resultsLeaf + RUN_SUFFIX)
safeMake(os.path.dirname(latestLinkAs))
for s in SUFFIXES:
linkPath = os.path.join(resultsDir, 'latest', resultsLeaf + s)
if os.path.lexists(linkPath):
os.unlink(linkPath)
os.symlink(os.path.relpath(tagDirRun, os.path.dirname(latestLinkAs)),
latestLinkAs)
# Add our tag to the git repo
checked([ "git", "tag", "-a", "-m", cleanMessage, tag ])
# Write our message file
with open(os.path.join(tagDirRun, "git-results-message"), "w") as f:
f.write("{0}\n{1}\n".format(tag, "=" * min(79, len(tag))))
if cleanMessage:
f.write("{0}\n".format(cleanMessage))
f.write("\nCommit: {0}".format(curCommit))
f.write("\n\ngit-results\n-----------\n")
f.write("run: {}\nbuild: {}\n".format(args.run, args.build))
if args.progress:
f.write("progress: {}\n".format(args.progress))
f.write("\nStarted {0}".format(now.strftime("%Y-%m-%dT%H:%M:%S")))
except:
typ, err, tb = sys.exc_info()
try:
safeRemoveDir(tagDirRun)
safeRollback(os.path.dirname(tagDirRun))
if linkAs is not None:
safeRemove(linkAs)
safeRollback(os.path.dirname(linkAs))
if latestLinkAs is not None:
safeRemove(latestLinkAs)
safeRollback(os.path.dirname(latestLinkAs))
checked([ "git", "tag", "-d", tag ], nonZeroOk = [ 1 ])
indexExpunge(repoBase, tag)
except:
traceback.print_exc()
raise err