-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_build.py
executable file
·2008 lines (1741 loc) · 75.4 KB
/
check_build.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/python3
import os
import urllib.request
import urllib.parse
import http.client
import socket
import ssl
import html
import math
import pickle
import sys
import glob
import re
import time
import shutil
import subprocess
from argparse import ArgumentParser
import datetime
import hashlib
import imp_build_utils
from imp_build_utils import SPECIAL_COMPONENTS, OK_STATES
import xml.sax
from xml.sax.handler import ContentHandler
import json
import yaml
import base64
import zlib
imp_testhtml = '/guitar3/home/www/html/imp/nightly/'
imp_testurl = 'http://salilab.org/imp/nightly/tests.html'
imp_downloadhtml = '/guitar3/home/www/html/imp/nightly/download/'
imp_lab_testhtml = '/guitar3/home/www/html/internal/imp-salilab/nightly/'
imp_lab_testurl = 'https://salilab.org/internal/imp-salilab/nightly/tests.html'
class ExcludedModule(object):
pass
class NoLogModule(object):
pass
class Error(object):
pass
class CircularDependencyError(Error):
pass
class FailedDependencyError(Error):
pass
class ExampleFailedError(Error):
pass
# Part of the build didn't start yet
class NotRunError(Error):
pass
class BuildNotRunError(NotRunError):
pass
class TestNotRunError(NotRunError):
pass
class ExampleNotRunError(NotRunError):
pass
class BenchmarkNotRunError(NotRunError):
pass
# Part of the build is still running
class RunningError(Error):
pass
class BuildRunningError(RunningError):
pass
class TestRunningError(RunningError):
pass
class ExampleRunningError(RunningError):
pass
class BenchmarkRunningError(RunningError):
pass
class MissingLogError(Error):
def __init__(self, logpath, abslogpath, description):
self._logpath = logpath
self._abslogpath = abslogpath
self._description = description
class ExtraLogError(Error):
def __init__(self, logpath, abslogpath):
self._logpath = logpath
self._abslogpath = abslogpath
class ModuleDisabledError(Error):
pass
class TestFailedError(Error):
pass
class BuildFailedError(Error):
pass
class BenchmarkFailedError(Error):
pass
class MissingOutputError(Error):
def __init__(self, output, logpath, abslogpath, description):
self._output = output
self._logpath = logpath
self._abslogpath = abslogpath
self._description = description
def byte_compile_python_dir(dirname):
"""Byte-compile a directory full of Python files.
Ignore errors from modules that contain invalid syntax."""
subprocess.call(['python3', '-m', 'compileall', '-f', '-qq', dirname])
def update_symlink(src, dest):
"""Atomically update the symlink from `src` to `dest`.
Make a symlink dest -> src. If dest already exists, rather than
deleting it and recreating it, make a new temporary symlink and then
rename it over the existing link. The latter action is atomic so there
is no window where the link does not exist (which might cause runs on
the cluster to fail)."""
tmplink = dest + '.tmp'
os.symlink(src, tmplink)
os.rename(tmplink, dest)
def _get_only_failed_modules(module_map, modules, archs):
failures = {}
for m in modules:
for a in archs:
err = module_map[m][a]
if err is not None \
and not isinstance(err, (ExcludedModule, NoLogModule,
TestNotRunError, NotRunError)):
failures[m] = failures[a] = None
return ([m for m in modules if m in failures],
[a for a in archs if a in failures])
def _get_text_module_map(name, module_map, modules, archs):
def _format_module_error(error):
if error is None or isinstance(error, (NoLogModule, TestNotRunError,
FailedDependencyError,
NotRunError)):
return "-"
elif isinstance(error, (BuildFailedError,
CircularDependencyError)):
return "BUILD"
elif isinstance(error, RunningError):
return "INCOM"
elif isinstance(error, BenchmarkFailedError):
return "BENCH"
elif isinstance(error, (TestFailedError, ExampleFailedError)):
return "TEST"
elif isinstance(error, ModuleDisabledError):
return "DISAB"
elif isinstance(error, ExcludedModule):
return "skip"
raise RuntimeError("Cannot handle error: " + str(error))
t = "%s module failure summary (BUILD = failed to build;\n" \
"TEST = failed tests; DISAB = disabled due to wrong configuration;\n" \
"skip = not built on this platform; only modules that failed on\n" \
"at least one architecture are shown)\n" \
% name
modules, archs = _get_only_failed_modules(module_map, modules, archs)
t += (" " * 13 +
" ".join("%-5s" % imp_build_utils.platforms_dict[x].very_short
for x in archs) + "\n")
for m in modules:
errs = [_format_module_error(module_map[m][arch])
for arch in archs]
t += "%-13s" % m[:13] + " ".join("%-5s" % e[:5] for e in errs) + "\n"
return t
class CoverageLink(object):
def __init__(self, desc, loc):
self.desc = desc
self.loc = loc
def parse_logdir(self, logdir):
return self.parse_file(os.path.join(logdir, self.loc, 'index.html'))
def parse_file(self, fname):
pass
def _extract_percentage(self, fname, regex):
# Get total percent coverage from index.html and add to desc
r = re.compile(regex)
try:
for line in open(fname):
m = r.search(line)
if m:
self.desc += " (%s%%)" % m.group(1)
return m.group(1)
except IOError:
pass
class PythonCoverageLink(CoverageLink):
def parse_file(self, fname):
return self._extract_percentage(fname,
r"<span class=.pc_cov.>(\d+)%</span>")
class CCoverageLink(CoverageLink):
def parse_file(self, fname):
return self._extract_percentage(
fname,
r'<td class="headerCovTableEntry\w+">(\d+\.\d+)(\s| )*%</td>')
class GitHubStatusUpdater(object):
"""Update the status of a repository in GitHub"""
def __init__(self, dryrun, owner, repo):
self.dryrun = dryrun
self.api_root = 'https://api.github.com/repos/%s/%s' % (owner, repo)
self.get_auth()
def get_auth(self):
"""Read the GitHub username and password to use.
The auth file has a simple YAML format:
username: foo
password: bar
"""
authfile = os.path.join(os.path.dirname(sys.argv[0]),
'githubauth.yaml')
with open(authfile) as fh:
self.auth = yaml.safe_load(fh)
def get_default_headers(self):
"""Get headers needed for every API request"""
authstr = self.auth['username'] + ":" + self.auth['password']
authstr = base64.b64encode(authstr.encode('ascii')).decode('ascii')
headers = {'Authorization': 'Basic %s' % authstr}
return headers
def get_statuses(self, sha):
headers = self.get_default_headers()
req = urllib.request.Request(
self.api_root + '/commits/%s/statuses' % sha, None, headers)
return json.load(urllib.request.urlopen(req))
def set_status(self, sha, state, target_url, description,
context="continuous-integration/salilab-nightly-builds",
duplicate=True):
if not duplicate:
for s in self.get_statuses(sha):
if s['context'] == context:
return
headers = self.get_default_headers()
headers['Content-Type'] = 'application/json'
data = json.dumps({'state': state, 'target_url': target_url,
'description': description, 'context': context})
data = data.encode('utf-8')
url = self.api_root + '/statuses/%s' % sha
if self.dryrun:
print(data)
return
else:
req = urllib.request.Request(url, data, headers)
try:
return urllib.request.urlopen(req).read()
except (urllib.request.HTTPError,
urllib.request.URLError) as error:
if hasattr(error, 'read'):
print(error.read())
print(str(error))
class LinkChecker(object):
def __init__(self, url_root, title, html, verbose):
self.nbroken = 0
self.url_root = url_root
self.title = title
self.html = html
self.verbose = verbose
self._broken_links = {}
self._checked_externals = {}
def check_link(self, fname, nline, link):
if link in self._broken_links:
self.add_broken_link(link, fname, nline)
elif (link.startswith('http:') or link.startswith('https:')
or link.startswith('//') or link.startswith('ftp:')):
if link not in self._checked_externals:
self._checked_externals[link] = None
self._check_http_link(fname, nline, link)
elif link in self._broken_links:
self.add_broken_link(link, fname, nline)
else:
if not os.path.exists(urllib.parse.urlsplit(link).path):
self.add_broken_link(link, fname, nline)
def log(self, msg):
if self.verbose:
print(" " + msg, file=sys.stderr)
def _check_http_link(self, fname, nline, link):
# Several websites forbid queries by bots; ninja-build.org has
# SSL issues; doxygen often times out
if ('wikipedia' in link or 'amazon.com' in link
or 'stackoverflow.com' in link
or 'anaconda.com' in link
or 'creativecommons.org' in link
or 'nih.gov/pmc/' in link
or 'atlassian.com' in link
or 'git-scm.com' in link
or 'graphviz.org' in link
or 'pubs.acs.org' in link
or 'msdn.microsoft' in link
or 'ninja-build.org' in link
or 'docs.github.com' in link
or 'cmake.org' in link
or link == 'http://www.doxygen.org/'):
self.log("Skipping check of link " + link)
else:
self.log("Checking external link " + link)
checklink = link
# If no scheme provided, assume http:
if checklink.startswith('//'):
checklink = 'http:' + checklink
try:
r = urllib.request.Request(checklink,
headers={'User-Agent': 'urllib'})
_ = urllib.request.urlopen(r, timeout=10)
except socket.timeout:
self.add_broken_link(link, fname, nline, 'timeout')
except (urllib.request.URLError, http.client.HTTPException,
ssl.SSLError, ssl.CertificateError,
socket.error) as detail:
self.add_broken_link(link, fname, nline, str(detail))
def add_broken_link(self, link, fname, nline, detail=None):
self.nbroken += 1
if link in self._broken_links:
self._broken_links[link][2] += 1
else:
self._broken_links[link] = [fname, nline, 0, detail]
def print_summary(self, outfh):
if self.html:
if self.nbroken == 0:
suffix = "s."
elif self.nbroken == 1:
suffix = ":"
else:
suffix = "s:"
print('<p>The %s has %d broken link%s</p>'
% (self.make_link(None, self.title), self.nbroken, suffix),
file=outfh)
if self.nbroken > 0:
print('<ul>', file=outfh)
for link, info in self._broken_links.items():
fname, nline, nothers, detail = info
if nothers > 1:
others = " (and %d other locations)" % nothers
elif nothers == 1:
others = " (and 1 other location)"
else:
others = ""
if detail:
detail = " (" + detail + ")"
else:
detail = ""
if self.html:
if link.startswith('http'):
link = '<a href="%s">%s</a>' % (link, link)
print('<li>%s%s from %s, line %d%s</li>'
% (link, html.escape(detail),
self.make_link(fname, fname), nline + 1, others),
file=outfh)
else:
print("Broken link %s%s from %s, line %d%s"
% (link, detail, fname, nline + 1, others), file=outfh)
if self.html and self.nbroken > 0:
print("</ul>", file=outfh)
def make_link(self, subdir, text):
if self.url_root is None:
return text
elif subdir:
return '<a href="%s">%s</a>' \
% (os.path.join(self.url_root, subdir), text)
else:
return '<a href="%s">%s</a>' % (self.url_root, text)
def check_file(self, fname):
r = re.compile('(?:href|src)="([^#"]+)[#"]')
# Some files aren't UTF-8, so accept any bytes
for nline, line in enumerate(open(fname, encoding='latin1')):
links = r.findall(line)
if len(links) > 0:
for link in links:
self.check_link(fname, nline, link)
def check_broken_links(html_dir, url_root, html, verbose, title,
outfh=sys.stdout):
if not os.path.exists(html_dir):
return 0
cwd = os.getcwd()
os.chdir(html_dir)
lc = LinkChecker(url_root, title, html, verbose)
nfiles = 0
for x in os.listdir('.'):
if x.endswith('.html'):
nfiles += 1
if nfiles % 100 == 0 and verbose:
print("Checking file #%d" % nfiles, file=sys.stderr)
lc.check_file(x)
lc.print_summary(outfh)
os.chdir(cwd)
return lc.nbroken
class Formatter(object):
pass
class TextFormatter(Formatter):
def print_product(self, comp, errors, module_map=None, modules=None,
module_coverage=False, archs=None, logdir=None):
if len(errors) == 0:
print("%s OK" % comp.name)
else:
print("%s FAILED" % comp.name)
for err in errors:
self._print_error(err)
if module_map:
print(_get_text_module_map(comp.name, module_map, modules, archs))
print()
def print_header(self, title=None):
pass
def print_footer(self):
pass
def print_start_products(self):
pass
def print_end_products(self):
pass
def print_new_repos(self, repos):
pass
def print_old_repos(self, repos):
pass
def _print_error(self, error):
if isinstance(error, MissingLogError):
print(" %s: log %s not generated" % (error._description,
error._logpath))
elif isinstance(error, ExtraLogError):
print(" Unexpected log %s generated" % error._logpath)
elif isinstance(error, MissingOutputError):
if error._logpath is None:
print(" %s: output %s not generated"
% (error._description, error._output))
else:
print(" %s: output %s not generated; see log %s"
% (error._description, error._output, error._logpath))
def get_imp_build_email_from():
"""Get the From: address for emails to the IMP-build mailing list"""
d = os.path.dirname(sys.argv[0])
fh = open(os.path.join(d, 'email-from.txt'))
for line in fh:
line = line.rstrip('\r\n')
if len(line) > 0 and not line.startswith('#'):
return line
raise ValueError("Could not read email address")
class Repository(object):
def __init__(self, name):
self.name = name
def set_verfile(self, newpath):
(self.newlongver, self.newversion, self.newrevision) = \
self._parse_verfile(newpath)
def _parse_verfile(self, path):
verfile = os.path.join(path, "build/%s-version" % self.name)
revfile = os.path.join(path, "build/%s-gitrev" % self.name)
with open(verfile, "r") as fh:
longver = fh.readline().rstrip('\r\n')
spl = longver.split(".")
if os.path.exists(revfile):
version = 'git'
with open(revfile, "r") as fh:
revision = fh.readline().rstrip('\r\n')
elif len(spl) > 1 and spl[-1].startswith('r'):
version = ".".join(spl[:-1])
revision = spl[-1]
elif longver.startswith('r'):
version = 'SVN'
revision = longver
else:
version = longver
revision = 'unknown'
return (longver, version, revision)
class Product(object):
def __init__(self, name, dir, module_coverage=False):
self.modules = []
self.units = {}
self.module_coverage = module_coverage
self.name = name
self.dir = dir
self.__logs = {}
self.__log_desc = {}
def update_status(self, dryrun):
pass
def set_component_file(self, path):
modfile = os.path.join(path, "build/%s-components" % self.dir)
if os.path.exists(modfile):
lines = [m.rstrip('\r\n')
for m in open(modfile).readlines()]
lines = [m for m in lines if len(m) > 0]
for line in lines:
typ, unit = line.split('\t')
self.units[unit] = typ
self.modules.append(unit)
def add_log(self, log, description, generated_files):
if log not in self.__logs:
self.__logs[log] = []
self.__log_desc[log] = description
lst = self.__logs[log]
if isinstance(generated_files, (list, tuple)):
lst.extend(generated_files)
else:
lst.append(generated_files)
def make_module_map(self, archs):
self.module_map = {}
self.archs = archs
for m in self.modules:
self.module_map[m] = dict.fromkeys(archs)
if self.units[m] == 'module':
self.module_map[m + ' examples'] = dict.fromkeys(archs)
self.module_map[m + ' benchmarks'] = dict.fromkeys(archs)
def exclude_component(self, module, archs):
if module not in self.module_map:
print("WARNING: ignoring attempt to exclude missing component %s"
% module)
return
if self.units[module] == 'module':
for a in archs:
self.module_map[module + ' examples'][a] = ExcludedModule()
self.module_map[module + ' benchmarks'][a] = ExcludedModule()
for a in archs:
self.module_map[module][a] = ExcludedModule()
def exclude_component_all(self, module):
self.exclude_component(module, self.archs)
def include_component(self, module, archs):
a = [x for x in self.archs if x not in archs]
self.exclude_component(module, a)
def check_logs(self, checker, formatters):
self._errors = []
for (log, generated_files) in self.__logs.items():
self.__check_log(log, self.__log_desc[log], generated_files,
checker, self._errors)
for cmake_log in self.cmake_logs:
self.__check_cmake_log(cmake_log, checker, self._errors)
self.__check_extra_logs(checker, self._errors)
self._check_module_errors(checker)
self.print_product(formatters, os.path.join(checker.logdir, self.dir))
lenerr = len(self._errors)
if self.get_module_state() != 'OK':
lenerr += 1
return lenerr
def _check_module_errors(self, checker):
pass
def get_module_state(self):
return 'OK'
def print_product(self, formatters, logdir):
self.state = self.get_module_state()
failure = (self.state != 'OK')
if failure:
if self.state in ('OK', 'TEST'):
for e in self._errors:
if isinstance(e, MissingOutputError):
self.state = 'BUILD'
break
elif isinstance(e, (MissingLogError, ExtraLogError)):
self.state = 'BADLOG'
if self.state == 'OK':
self.state == 'BUILD'
for f in formatters:
f.print_product(self, self._errors, self.module_map,
self.modules, self.module_coverage,
self.archs, logdir)
elif len(self.modules) > 0:
for f in formatters:
f.print_product(self, self._errors, self.module_map,
self.modules, self.module_coverage,
self.archs, logdir)
else:
for f in formatters:
f.print_product(self, self._errors)
def __check_extra_logs(self, checker, errors):
logmatch = os.path.join(checker.logdir, self.dir, "*.log")
all_logs = [os.path.basename(x) for x in glob.glob(logmatch)]
for log in all_logs:
if log not in self.__logs:
logpath = os.path.join(self.dir, log)
abslogpath = os.path.join(checker.logdir, logpath)
errors.append(ExtraLogError(logpath, abslogpath))
def __check_cmake_log(self, cmake_log, checker, errors):
for gen in cmake_log.generated_files:
filepath = os.path.join(checker.newbuilddir, gen)
if not os.path.exists(filepath):
desc = imp_build_utils.platforms_dict[cmake_log.arch].long
errors.append(MissingOutputError(gen, None, None, desc))
def __check_log(self, log, description, generated_files, checker, errors):
logpath = os.path.join(self.dir, log)
abslogpath = os.path.join(checker.logdir, logpath)
if not os.path.exists(abslogpath):
errors.append(MissingLogError(logpath, abslogpath,
description))
else:
for gen in generated_files:
filepath = os.path.join(checker.newbuilddir, gen)
if not os.path.exists(filepath):
errors.append(MissingOutputError(gen, logpath, abslogpath,
description))
class CMakeLog(object):
all_build_types = ['build', 'test', 'example', 'benchmark']
not_run_error = {'build': BuildNotRunError, 'test': TestNotRunError,
'example': ExampleNotRunError,
'benchmark': BenchmarkNotRunError}
running_error = {'build': BuildRunningError, 'test': TestRunningError,
'example': ExampleRunningError,
'benchmark': BenchmarkRunningError}
def __init__(self, arch, build_types, generated_files):
# Make sure build_types is correctly ordered
self.build_types = [x for x in self.all_build_types
if x in build_types]
self.arch = arch
if not isinstance(generated_files, (list, tuple)):
self.generated_files = [generated_files]
else:
self.generated_files = generated_files
def update_module_error(self, modmap, err, compname):
olderr = modmap[self.arch]
if isinstance(olderr, ExcludedModule):
if not isinstance(err, (NotRunError, ModuleDisabledError)):
print("WARNING: build of %s reported %s for %s, but component "
"is supposed to be excluded" % (compname, err,
self.arch))
return False
if err is None:
return False
modmap[self.arch] = err
return True
def check_extra_build_types(self, name, comp):
for build_type in self.all_build_types:
if build_type not in self.build_types:
if hasattr(comp, '%s_result' % build_type):
print("WARNING: %s in %s has extra build type %s"
% (name, self.arch, build_type))
def check_module_errors(self, comp, logdir):
logdir = os.path.join(logdir, self.arch)
summary = os.path.join(logdir, 'summary.pck')
if os.path.exists(summary):
with open(summary, 'rb') as fh:
summary = pickle.load(fh)
else:
summary = {}
for m in comp.units:
if m in summary:
self.check_extra_build_types(m, summary[m])
self.check_build_types(m, comp, summary)
def check_build_types(self, m, comp, summary):
if m in SPECIAL_COMPONENTS:
build_types = ['build']
else:
build_types = self.build_types[:]
example = 'example' in build_types
benchmark = 'benchmark' in build_types
if example:
build_types.remove('example')
if benchmark:
build_types.remove('benchmark')
self.get_build_result(m, comp, summary, build_types)
if comp.units[m] == 'module':
if example:
self.get_build_result(m + ' examples', comp, summary,
['example'])
else:
comp.module_map[m + ' examples'][self.arch] = ExcludedModule()
if benchmark:
self.get_build_result(m + ' benchmarks', comp, summary,
['benchmark'])
else:
comp.module_map[m + ' benchmarks'][self.arch] \
= ExcludedModule()
def get_build_result(self, m, comp, summary, build_types):
sm = m
if sm.endswith(' examples'):
sm = sm[:-9]
elif sm.endswith(' benchmarks'):
sm = sm[:-11]
for typ in build_types:
res = '%s_result' % typ
if sm in summary and summary[sm].get(res, 'notrun') != 'notrun':
res = summary[sm][res]
if res == 0:
err = None
elif res == 'circdep':
err = CircularDependencyError()
elif res == 'depfail':
err = FailedDependencyError()
elif res == 'disabled':
err = ModuleDisabledError()
elif res == 'running':
err = self.running_error[typ]()
else:
if typ == 'build':
err = BuildFailedError()
elif typ == 'test':
err = TestFailedError()
elif typ == 'example':
err = ExampleFailedError()
elif typ == 'benchmark':
err = BenchmarkFailedError()
else:
err = self.not_run_error[typ]()
if self.update_module_error(comp.module_map[m], err, m):
# Stop at first error
return
class IMPProduct(Product):
def __init__(self, name, dir, repo, *args, **kwargs):
super().__init__(name, dir, *args, **kwargs)
self.cmake_logs = []
self.repo = repo
def update_status(self, dryrun):
s = GitHubStatusUpdater(dryrun, "salilab", "imp")
s.set_status(sha=self.repo.newrevision,
state={'OK': 'success', 'TEST': 'success',
'BUILD': 'failure', 'BADLOG': 'error',
'INCOMPLETE': 'error'}[self.state],
description={
'OK': 'The build succeeded and all tests passed',
'TEST': 'The build succeeded although some tests '
'failed',
'BUILD': 'The build failed',
'BADLOG': 'A bad log file was produced',
'INCOMPLETE': 'The build system '
'ran out of time'}[self.state],
target_url="http://integrativemodeling.org/nightly/"
"results/?date=%s"
% datetime.date.today().strftime('%Y%m%d'))
def add_cmake_log(self, arch, build_types, generated_files):
self.cmake_logs.append(CMakeLog(arch, build_types, generated_files))
def _check_module_errors(self, checker):
for log in self.cmake_logs:
log.check_module_errors(
self, os.path.join(checker.logdir, self.dir))
def get_module_state(self):
states = ['BUILD', 'INCOMPLETE', 'TEST', 'OK']
state = 'OK'
for m in self.modules:
for a in self.archs:
err = self.module_map[m][a]
if isinstance(err, RunningError):
newstate = 'INCOMPLETE'
elif isinstance(err, (TestFailedError, ExampleFailedError,
BenchmarkFailedError)):
newstate = 'TEST'
elif isinstance(err, (BuildFailedError,
CircularDependencyError,
ModuleDisabledError)):
newstate = 'BUILD'
else:
newstate = 'OK'
if states.index(newstate) < states.index(state):
state = newstate
return state
class PruneDirectories(object):
def __init__(self, topdir):
self._topdir = topdir
def prune(self):
dirs_to_prune = self._get_dirs_to_prune()
for d in dirs_to_prune:
shutil.rmtree(os.path.join(self._topdir, d))
def _exclude_linked_dirs(self, dirs_to_prune, links):
for link in links:
full_link = os.path.join(self._topdir, link)
if os.path.exists(full_link):
dest = os.path.basename(os.readlink(full_link))
try:
dirs_to_prune.remove(dest)
except ValueError:
pass
def _get_dirs_to_prune(self):
today = datetime.datetime.today()
dirre = re.compile(r'(\d{4})(\d{2})(\d{2})')
alldirs = os.listdir(self._topdir)
alldirs.sort()
months = {}
dirs_to_prune = []
for d in alldirs:
m = dirre.match(d)
if m:
dirdate = datetime.datetime(int(m.group(1)), int(m.group(2)),
int(m.group(3)))
age = today - dirdate
# Prune directories older than 30 days, but leave one per month
if age.days > 30:
month = (dirdate.year, dirdate.month)
if month not in months:
months[month] = None
else:
dirs_to_prune.append(d)
self._exclude_linked_dirs(dirs_to_prune,
('nightly', 'stable',
'.last', 'last_ok_build'))
return dirs_to_prune
class Checker(object):
def __init__(self, dirroot):
self._products = []
self._repos = []
self.dirroot = dirroot
self.newbuilddir = os.path.join(dirroot, ".new")
self.logdir = os.path.join(self.newbuilddir, "build/logs")
self.builddir = os.path.join(dirroot, "stable")
self.timenow = time.time()
def add_product(self, prod):
self._products.append(prod)
prod.set_component_file(self.newbuilddir)
def add_repository(self, repo):
self._repos.append(repo)
repo.set_verfile(self.newbuilddir)
def print_header(self, formatter):
formatter.print_header()
def check_logs(self, formatters):
numerr = 0
for f in formatters:
self.print_header(f)
f.print_start_products()
for comp in self._products:
numerr += comp.check_logs(self, formatters)
for f in formatters:
f.print_end_products()
f.print_new_repos(self._repos)
if numerr > 0:
f.print_old_repos(self._repos)
f.print_footer()
return numerr
def copy_log_files(self, testhtml):
pass
def update_done_build(self, dryrun):
pass
def activate_new_build(self):
pass
def update_arch(arch_table, arch, cur):
cur.execute("SELECT id FROM " + arch_table + " WHERE NAME=%s", (arch,))
r = cur.fetchone()
if r is not None:
return r[0]
else:
cur.execute("INSERT INTO " + arch_table + " (name) values(%s)",
(arch,))
cur.execute("SELECT LAST_INSERT_ID()")
return cur.fetchone()[0]
def update_unit(unit_table, unit, cur, lab_only):
cur.execute("SELECT id FROM " + unit_table + " WHERE NAME=%s", (unit,))
r = cur.fetchone()
if r is not None:
return r[0]
else:
cur.execute("INSERT INTO " + unit_table +
" (name, lab_only) values(%s, %s)", (unit, lab_only))
cur.execute("SELECT LAST_INSERT_ID()")
return cur.fetchone()[0]
def update_name(name_table, name, unit_id, cur):
cur.execute("SELECT id FROM " + name_table + " WHERE name=%s AND unit=%s",
(name, unit_id))
r = cur.fetchone()
if r is not None:
return r[0]
else:
cur.execute("INSERT INTO " + name_table
+ " (name,unit) values(%s,%s)", (name, unit_id))
cur.execute("SELECT LAST_INSERT_ID()")
return cur.fetchone()[0]
update_benchmark_file = update_name
def update_benchmark_name(name_table, name, algorithm, file_id, cur):
cur.execute("SELECT id FROM " + name_table
+ " WHERE name=%s AND algorithm=%s AND file=%s",
(name, algorithm, file_id))
r = cur.fetchone()
if r is not None:
return r[0]
else:
cur.execute("INSERT INTO " + name_table
+ " (name,algorithm,file) values(%s,%s,%s)",
(name, algorithm, file_id))
cur.execute("SELECT LAST_INSERT_ID()")
return cur.fetchone()[0]
def connect_mysql():
import MySQLdb
d = os.path.dirname(sys.argv[0])
with open(os.path.join(d, 'imp-sql-args.pck'), 'rb') as fh: