-
Notifications
You must be signed in to change notification settings - Fork 24
/
cmsBuild
executable file
·5114 lines (4536 loc) · 221 KB
/
cmsBuild
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 -u
# Driver script for building rpms from a configuration specified in CMSDIST.
#
import sys, socket
from os.path import abspath, join, exists, isdir, basename, dirname
from os import popen, getenv, symlink, listdir, readlink, unlink, getpid
from os import chdir, getcwd, environ, walk, sep, kill
from getpass import getuser
from tempfile import mkdtemp, mkstemp, NamedTemporaryFile
import base64, subprocess
from subprocess import getstatusoutput
from urllib.request import urlopen, Request
from urllib.error import URLError
import signal
def cmp(a, b): return (a > b) - (a < b)
from time import strftime, time, sleep
import copy
import re, os
import traceback
from optparse import OptionParser, OptionGroup
import fnmatch
from shutil import rmtree
from glob import glob
import itertools
import pickle
from hashlib import sha256
from cmsBuild_consts import *
from cmsdist_config import USE_COMPILER_VERSION, NO_VERSION_SUFFIX, NO_AUTO_RUNPATH
try: from monitor_build import run_monitor_on_command
except: run_monitor_on_command=None
import json
import pprint
urlRe = re.compile(r".*:.*/.*")
urlAuthRe = re.compile(r'^(http(s|)://)([^:]+:[^@]+)@(.+)$')
logLevel = 10
NORMAL = 10
DEBUG = 20
TRACE = 30
DEFAULT_CVS_SERVER = ":pserver:anonymous@cmscvs.cern.ch:2401/local/reps/CMSSW"
DEFAULT_CVS_PASSWORD = "AA_:yZZ3e"
DEFAULT_SPEC_REPOSITORY_MODULE = "CMSDIST"
CMSPKG_CMD = "cmspkg"
REF_CMSPKG_CMD = None
SERVER_TMP_UPLOAD_DIRECTORY = None
rpmEnvironmentScript = "true"
packageBuildOptions = ""
packageBuildOptionsChanged = None
PKGFactory = None
SystemCompilerVersion = {}
BlackListReferencePkgs = []
reference_rpm_db_cache = {}
rpm_db_cache = {}
cmspkg_upload_cache = {"": []}
rpm_upload_cache = {}
cms_debug_packages = {}
removeInitialSpace = re.compile(r"^[ ]*", re.M)
cmsBuildFilename = abspath(__file__)
pkgtools_dir = dirname (cmsBuildFilename)
build_stats = None
package_provides = {}
cmsdist_files = {}
pgo_packages = []
compiler_package_dependency = ["gcc-prerequisites"]
scheduler = None
scriptdir = ""
def fatal(message):
print ("ERROR: " + message)
sys.exit(1)
def die(message):
fatal(message)
def remoteRsync(opts):
return format("rsync -e 'ssh -o StrictHostKeyChecking=no %(sshOpts)s -p %(port)s' --rsync-path=/usr/bin/rsync --chmod=a+rX",
sshOpts = opts.sshOptions,
port = opts.uploadPort)
def getNonSystemPackages(pkgs, opts):
return [p for p in pkgs if p not in opts.useSystemTools] if opts.useSystemTools else pkgs
def cmsdist_file(name, ext, options, pkgname):
fname = 'spec' if ext == '.spec' else name + ext
s = join(pkgname, fname)
if not exists(join(options.cmsdist, s)):
s = name + ext
filename = join (options.cmsdist, s)
if exists (filename):
if not s in cmsdist_files:
cmsdist_files[s] = []
if not pkgname in cmsdist_files[s]:
cmsdist_files[s].append(pkgname)
return filename
def isNoVersionSuffix(name):
for reg in NO_VERSION_SUFFIX:
if reg.match(name): return True
return False
# Minimal string sanitization.
def sanitize(s):
return re.sub(r"[^a-zA-Z_0-9*./-]", "", s)
def log(message, level=0):
""" Asynchronous printouts method. Level should be NORMAL when a message
is intended to be seen by the user, DEBUG, when it's intended to be seen only
by the developer, and TRACE when it's a message that is describing state
of the action scheduler/worker during the build.
"""
if callable(message):
message = message()
if level <= logLevel:
message = removeInitialSpace.sub("", message)
print (message)
def setLogLevel(options):
global logLevel
if options.trace:
logLevel = TRACE
elif options.debug:
logLevel = DEBUG
else:
logLevel = NORMAL
# Check of online arch
def isOnline(arch):
if 'onl' in arch: return True
return False
def isDefaultRevision(rev):
if rev == '1' or rev.startswith('1.'): return True
return False
# We have our own version rather than using the one from os
# because the latter does not work seem to be thread safe.
def makedirs(path):
returncode, out = getstatusoutput("mkdir -p %s" % (path,))
if returncode != 0:
raise OSError("makedirs() failed (return: %s):\n%s" % (returncode, out))
def getPackages(packages): return [PKGFactory[p] for p in packages]
def getCompilerDetection():
return SYS_COMPILER_DETECTION if opts.systemCompiler else COMPILER_DETECTION
def detectCompilerVersion(compilerName):
global SystemCompilerVersion
if compilerName in SystemCompilerVersion: return SystemCompilerVersion[compilerName]
(error, version) = getstatusoutput(getCompilerDetection()[compilerName])
if error: raise UnknownCompiler()
SystemCompilerVersion[compilerName] = version.split("\n")[0]
return SystemCompilerVersion[compilerName]
def cmspkg_showpkgs(packages):
pkgs = ""
pkgs1 = ""
for pkg in packages:
pname = pkg.pkgName()
cmspkg_upload_cache[pname] = []
rpm_upload_cache[pname] = []
pkgs = pkgs+" "+pname
pkgs1 = pkgs1+" "+pname+"-1-"+pkg.pkgRevision
err, output = getstatusoutput("%s showpkg %s" % (CMSPKG_CMD, pkgs))
if err: return (err, output)
data = output.split("\n")
pkg = ""
for l in data:
if " - CMS Experiment package" in l:
pkg = l.split(" ")[0]
cmspkg_upload_cache[pkg].append(l)
err, output = getstatusoutput("%s ; rpm -q %s" % (rpmEnvironmentScript, pkgs1))
if err: return (err, output)
for l in output.split("\n"):
if '-1-' in l:
cmspkg_upload_cache[l.split('-1-')[0]].append(l)
err, output = getstatusoutput("%s ; rpm -q %s" % (rpmEnvironmentScript, pkgs))
if err: return (err, output)
for l in output.split("\n"):
if '-1-' in l:
rpm_upload_cache[l.split('-1-')[0]].append(l)
return (err, "")
def getPackageBuildOptions(opts):
buildOpts = []
if opts.buildOptions:
for macro in opts.buildOptions:
item = macro.split("=",1)
if len(item)==1: item.append("1")
buildOpts.append(item)
return buildOpts
def getRpmDefines(buildOptions=True):
rpmMacros = opts.rpmQueryDefines
if buildOptions:
rpmMacros = "%s %s" % (rpmMacros, packageBuildOptions)
return rpmMacros
#################################################################
# Utilities functions for installing packages from ref repository#
#################################################################
def should_install_from_reference(pkg):
if not pkg.options.reference: return False
if len([True for ex in BlackListReferencePkgs if ex.match(pkg.name)]): return False
return is_package_installed(pkg, reference_rpm_db_cache)
def get_cmspkg_repository(cmspkg):
e, o = getstatusoutput("%s repository" % cmspkg)
if e:
print ("Error: Unable to run ", ref_cmspkg)
print (o)
exit(1)
data = {}
for l in o.split("\n"):
if ":" in l:
x = [i.strip() for i in l.split(':', 1)]
data[x[0]] = x[1]
return data
def is_package_installed(pkg, rpm_cache):
return ((pkg.pkgName() in rpm_cache) and
(rpm_cache[pkg.pkgName()][0] == pkg.pkgRevision) and
(rpm_cache[pkg.pkgName()][1] == pkg.checksum))
def check_reference(opts):
global REF_CMSPKG_CMD, BlackListReferencePkgs
if not opts.reference: return
ref_cmspkg = join(opts.reference, "common", "cmspkg")
if not exists(ref_cmspkg):
print ("Error: Path %s is not a valid cmspkg installation area" % opts.reference)
exit(1)
REF_CMSPKG_CMD = "%s -a %s" % (ref_cmspkg, opts.architecture)
ok = True
# ref_data = get_cmspkg_repository (REF_CMSPKG_CMD)
# local_data = get_cmspkg_repository (CMSPKG_CMD)
# for v in [ "Server", "Repository", "ServerPath"]:
# if (not v in ref_data) or (not v in local_data): ok = False
# elif ref_data[v]!=local_data[v]: ok = False
if not ok:
print ("Error: Can not use directory %s as cmspkg reference area." % opts.reference)
print ("Error: Repository details mismatched")
print ("Local Server:", local_data)
print ("Reference Server:", ref_data)
exit(1)
log("Using reference repository:%s" % opts.reference, DEBUG)
black_list_file = join(pkgtools_dir, "black_list_reference_packages.txt")
black_list_pkgs = [opts.blackList]
if exists(black_list_file): black_list_pkgs += open(black_list_file).readlines()
for pkgs in [p.strip() for p in black_list_pkgs]:
if (not pkgs) or (pkgs.startswith("#")): continue
for pkg in [p.strip() for p in pkgs.split(",")]:
if pkg:
BlackListReferencePkgs.append(re.compile("^" + pkg + "$"))
log("Black listing package %s" % pkg, DEBUG)
rpmCacheUpdate(opts, reference_rpm_db_cache, REF_CMSPKG_CMD + " env -- ")
return
def install_reference(pkg):
ref_permission_error = 'Error: You do not have write permission'
log("About to build reference package %s using cmspkg..." % pkg.pkgName(), DEBUG)
command = "%s env -- rpm -qi %s" % (REF_CMSPKG_CMD, pkg.pkgName())
error, info = getstatusoutput(command)
if ref_permission_error in info: error = False
if error:
log("Command:\n %(command)s failed with the following message: %(info)s" % locals(), DEBUG)
raise RpmInstallFailed(pkg, info)
provides = savePackageProvides(pkg.pkgName(), pkg.options, rpm_cmd=REF_CMSPKG_CMD, read=True)
pkg_parts = pkg.pkgName().split("+", 2)
args = {"cmsroot": pkg.options.workDir, "refroot": pkg.options.reference, "cmsplatf": pkg.options.architecture}
args['pkgdir'] = join(pkg.options.architecture, *pkg_parts)
tmp_path = join(pkg.options.tempdir, "reference", pkg.pkgName())
makedirs(join(tmp_path,"BUILDROOT"))
tmp_spec = join(tmp_path, "package.spec")
spec = open(tmp_spec, "w")
infoReg = re.compile(r"^(Name|Version|Release|Group|License|Packager|Vendor|Summary)\s*:.*")
for l in info.split("\n"):
if infoReg.match(l):
spec.write(l + "\n")
for l in provides:
if ref_permission_error in l: continue
spec.write("Provides: " + l + "\n")
spec.write("Obsoletes: %s\n" % pkg.pkgName())
spec.write("Prefix: %s\n" % pkg.options.installDir)
spec.write(REFERENCE_PACKAGE_POST % args)
spec.close()
command = "%s; rpmbuild -bb --buildroot %s/BUILDROOT --define '_topdir %s' %s" % (rpmEnvironmentScript, tmp_path, tmp_path, tmp_spec)
error, output = getstatusoutput(command)
if error:
log("Command:\n %(command)s failed with the following message: %(output)s" % locals(), DEBUG)
raise RpmInstallFailed(pkg, output)
e, rpm_path = getstatusoutput("find %s -name '*.rpm'" % (tmp_path))
command = "%s ; rpm -Uvh --prefix %s %s" % (rpmEnvironmentScript, pkg.options.workDir, rpm_path)
error, output = getstatusoutput(command)
if error:
log("Command:\n %(command)s failed with the following message: %(output)s" % locals(), DEBUG)
raise RpmInstallFailed(pkg, output)
############################################################
def downloadUrllib2(source, destDir, options, cmscache=False):
try:
dest = "/".join([destDir.rstrip("/"), basename(source)])
headers={"Cache-Control": "no-cache"}
m = urlAuthRe.match(source)
if m:
source = m.group(1)+m.group(4)
headers['Authorization'] = "Basic %s" % base64.b64encode(m.group(3))
req = Request(source, headers=headers)
s = urlopen(req)
tmpfile = "%s.%f.tmp" % (dest, time())
f = open(tmpfile, "wb")
# Read in blocks to avoid using too much memory.
block_sz = 8192 * 16
while True:
buffer = s.read(block_sz)
if not buffer:
break
f.write(buffer)
f.close()
if not exists(dest):
os.rename(tmpfile, dest)
else:
unlink(tmpfile)
except URLError as e:
if cmscache:
log("Internal cached file not available %s: %s" % (source, e), DEBUG)
else:
log("Error while downloading %s: %s" % (source, e))
return False
except Exception as e:
log("Error while downloading %s: %s" % (source, e))
return False
return True
def parseUrl(url, requestedKind=None, defaults={}, required=[]):
match = re.match("([^+:]*)([^:]*)://([^?]*)(.*)", url)
if not match:
raise MalformedUrl(url)
parts = match.groups()
protocol, deliveryProtocol, server, arguments = match.groups()
arguments = arguments.strip("?")
# In case of urls of the kind:
# git+https://some.web.git.repository.net
# we consider "https" the actual protocol and
# "git" merely the request kind.
if requestedKind and not protocol == requestedKind:
raise MalformedUrl(url)
if deliveryProtocol:
protocol = deliveryProtocol.strip("+")
arguments.replace("&", "&")
args = list(defaults.items())
parsedArgs = re.split("&", arguments)
parsedArgs = [x.split("=") for x in parsedArgs]
parsedArgs = [(len(x) != 2 and [x[0], True]) or x for x in parsedArgs]
args.extend(parsedArgs)
argsDict = dict(args)
missingArgs = [arg for arg in required if arg not in argsDict]
if missingArgs:
raise MalformedUrl(url, missingArgs)
return protocol, server, argsDict
def parseTcUrl(url):
scheme, server, args = parseUrl(url, requestedKind="cmstc",
defaults={"cvsroot": DEFAULT_CVS_SERVER,
"passwd": DEFAULT_CVS_PASSWORD},
required=["tag", "output"])
return scheme, server, args
def parseCvsUrl(url):
scheme, cvsroot, args = parseUrl(url, requestedKind="cvs",
defaults={"strategy": "export",
"tag": "HEAD",
"passwd": DEFAULT_CVS_PASSWORD},
required=["module", "output"])
if not cvsroot:
cvsroot = DEFAULT_CVS_SERVER
cvsroot = cvsroot.replace(":/", ":2401/")
args["tag"] = re.sub(re.compile(r"^-r"), "", args["tag"])
if "export" not in args:
args["export"] = args["module"]
args["cvsroot"] = cvsroot
return (scheme, cvsroot, args)
def parseSvnUrl(url):
scheme, root, args = parseUrl(url, requestedKind="svn",
defaults={"strategy": "export",
"revision": "HEAD"},
required=["module", "output"])
if "export" not in args:
args["export"] = args["module"]
if "scheme" in args:
scheme = args["scheme"]
if not scheme in ["svn", "http", "https", "file"] and (not scheme.startswith('svn+')):
scheme = "svn+" + scheme
args["svnroot"] = "%(scheme)s://%(root)s" % {"scheme": scheme, "root": root}
return (scheme, root, args)
def parseGitUrl(url):
protocol, gitroot, args = parseUrl(url, requestedKind="git",
defaults={"obj": "master/HEAD"})
parts = args["obj"].rsplit("/", 1)
if len(parts) != 2:
parts += ["HEAD"]
args["branch"], args["tag"] = parts
if not "export" in args:
args["export"] = basename(re.sub(r"\.git$", "", re.sub(r"[?].*", "", gitroot)))
if args["tag"] != "HEAD":
args["export"] += args["tag"]
else:
args["export"] += args["branch"]
if not "output" in args:
args["output"] = args["export"] + ".tar.gz"
args["gitroot"] = gitroot
if not "filter" in args:
args["filter"] = "*"
args["filter"] = sanitize(args["filter"])
return protocol, gitroot, args
def createTempDir(workDir, subDir):
tempdir = join(workDir, subDir)
if not exists(tempdir):
makedirs(tempdir)
tempdir = mkdtemp(dir=tempdir)
return tempdir
def executeWithErrorCheck(command, errorMessage):
log(command, DEBUG)
error, output = getstatusoutput(command)
if error:
log(errorMessage + ":")
log("")
log(command)
log("")
log("resulted in:")
log(output)
return False
log(output, DEBUG)
return True
def packCheckout(tempdir, dest, *exports):
""" Use this helper method when download protocol is like cvs/svn/git
where the code is checked out in a temporary directory and then tarred
up.
"""
export = " ".join(['"%s"' % x for x in exports])
packCommand = """cd %(tempdir)s; tar -zcf "%(dest)s" %(export)s """
packCommand = packCommand % locals()
errorMessage = "Error while creating a tar archive for checked out area"
return executeWithErrorCheck(packCommand, errorMessage)
def downloadSvn(source, dest, options):
scheme, svnroot, args = parseSvnUrl(source)
tempdir = createTempDir(options.workDir, options.tempDirPrefix)
exportDir = join(tempdir, "checkout", args["export"])
if not exists(exportDir):
makedirs(exportDir)
args["dest"] = join(dest, args["output"].lstrip("/"))
args["tempdir"] = tempdir
args["exportdir"] = exportDir.rsplit("/", 1)[1]
args["exportpath"] = exportDir.rsplit("/", 1)[0]
if not args["revision"].isdigit():
args["revision"] = '"' + args["revision"] + '"'
command = """cd %(exportpath)s ; svn %(strategy)s --force --non-interactive --trust-server-cert -r%(revision)s "%(svnroot)s" "%(exportdir)s" """
command = command % args
message = "Error while downloading files from subversion repository"
ok = executeWithErrorCheck(command, message)
return ok and packCheckout(args["exportpath"], args["dest"], args["export"])
def downloadCvs(source, dest, options):
protocol, cvsroot, args = parseCvsUrl(source)
tempdir = createTempDir(options.workDir, options.tempDirPrefix)
pserverUrlRe = re.compile(r":pserver:.*")
isPserver = pserverUrlRe.match(cvsroot)
cvspassFilename = None
if 'passwd' in args and isPserver:
cvspassFilename = join(tempdir, "cvspass")
f = open(join(tempdir, "cvspass"), "w")
f.write("/1 %(cvsroot)s %(passwd)s\n" % args)
f.close()
exportDir = join(tempdir, "checkout")
if not exists(exportDir):
makedirs(exportDir)
args["dest"] = join(dest, args["output"].lstrip("/"))
args["tempdir"] = tempdir
args["exportdir"] = exportDir
args["passexport"] = (cvspassFilename and "CVS_PASSFILE=%s" % cvspassFilename) or ""
command = """cd %(exportdir)s ; %(passexport)s cvs -z6 -Q -d"%(cvsroot)s" %(strategy)s -d"%(export)s" -r"%(tag)s" "%(module)s" """
command = command % args
message = "Error while executing a %(strategy)s from CVS:" % args
ok = executeWithErrorCheck(command, message)
return ok and packCheckout(exportDir, args["dest"], args["export"])
def downloadTc(source, dest, options):
protocol, tagsSource, args = parseTcUrl(source)
tempdir = createTempDir(options.workDir, options.tempDirPrefix)
args["tempdir"] = tempdir
args["dest"] = join(dest, args["output"].lstrip("/"))
args["pmLocation"] = abspath(join(pkgtools_dir, 'cmspm'))
if "extratags" in args:
args["extratags"] = "--additional-tags " + args["extratags"]
else:
args["extratags"] = ""
if 'baserel' not in args:
command = """cd %(tempdir)s && %(pmLocation)s corel %(tag)s """
else:
command = '. ' + options.workDir + """/cmsset_default.sh && cd %(tempdir)s && %(pmLocation)s frombase %(tag)s %(baserel)s %(baserelver)s """
command += """ %(extratags)s -e -o src/PackageList.cmssw"""
command = command % args
log("Downloading %(tag)s from cmsTC." % args, DEBUG)
message = "Error while downloading sources using tag collector information."
ok = executeWithErrorCheck(command, message)
dirs = ["src"]
if exists("/".join([args["tempdir"], "poison"])): dirs.append("poison")
return ok and packCheckout(args["tempdir"], args["dest"], *dirs)
# Download a files from a git url. We do not clone the remote reposiotory, but
# we simply pull the branch we are interested in and then we drop all the git
# information while creating a tarball. The syntax to define a repository is
# the following:
#
# git:/local/repository?obj=BRANCH/TAG
# git://remote-repository?obj=BRANCH/TAG
# git+https://remote-repository-over-http/foo.git?obj=BRANCH/TAG
#
# If "obj" does not contain a "/", it's value will be considered a branch and TAG will be "HEAD".
# If "obj" is not specified, it will be "master/HEAD" by default.
# By default export is the <basename of the url without ".git">-TAG unless it is HEAD,
# in which case it will be <basename of the url without .git>-BRANCH.
# One can specify an additional parameter
#
# filter=<some-path>
#
# which will be used to pack only a subset of the checkout.
def downloadGit(source, dest, options):
protocol, gitroot, args = parseGitUrl(source)
tempdir = createTempDir(options.workDir, options.tempDirPrefix)
exportpath = join(tempdir, args["export"])
if protocol=="git": protocol="https"
if protocol:
protocol += "://"
if not protocol and not gitroot.endswith(".git"):
gitroot = join(gitroot, ".git")
dest = join(dest, args["output"].lstrip("/"))
args.update({"protocol": protocol, "tempdir": tempdir,
"gitroot": gitroot, "dest": dest,
"exportpath": exportpath})
makedirs(exportpath)
if "submodules" in args:
args["submodules"] = " git submodule update --recursive --init &&"
else:
args["submodules"] = ""
command = format("cd %(exportpath)s &&"
"git init &&"
"git pull --tags %(protocol)s%(gitroot)s refs/heads/%(branch)s &&"
"git reset --hard %(tag)s && %(submodules)s"
"find . ! -path '%(filter)s' -delete &&"
"rm -rf .git .gitattributes .gitignore", **args)
error, output = getstatusoutput(command % args)
if error:
log("Error while downloading sources from %s using git.\n\n"
"%s\n\n"
"resulted in:\n%s" % (gitroot, command % args, output))
return False
return packCheckout(args["tempdir"], args["dest"], args["export"])
def getPipSourceDependency(sources, default_pip_pkg):
pip_sources = [s for s in sources if s.startswith("pip://")]
if pip_sources:
deps = userCommandDependencies(pip_sources)
if (not deps) and default_pip_pkg: deps = [default_pip_pkg]
return deps
return []
def userCommandDependencies(sources):
extra_build_deps = {}
for s in [x for x in sources if "package_dependency=" in x]:
for d in s.split("package_dependency=",1)[-1].replace(' ','').split("&")[0].split(","):
extra_build_deps[d]=1
return extra_build_deps.keys()
def downloadCmd (source, dest, options, command, env_pkgs):
tarball = source.rsplit("/", 1)[1]
tempdir = createTempDir(options.workDir, options.tempDirPrefix)
cmd = "cd %s; " % tempdir
for d in env_pkgs: cmd = cmd + ". %s; " % PKGFactory[d].getInitEnvScript()
cmd = cmd + command
log("Download command: %s" % cmd, DEBUG)
error, output = getstatusoutput(cmd)
if error:
log("Error while downloading sources from %s.\n\n %s \n %s \n %s \n " % (
source, cmd, error, output))
return False
error, output = getstatusoutput('cd %s; tar cfz %s/%s .' % (tempdir, dest, tarball))
if error:
log("Error while downloading sources from %s.\n\n %s \n %s \n %s \n " % (
source, cmd, error, output))
return False
getstatusoutput("rm -rf %s" % tempdir)
return True
def downloadUserCommand(source, dest, options):
# Valid URL formats are
# usercommand://package?command=command-to-run&package_dependency=package[,package[,...]]&output=/tarbalname
try: from urllib import unquote
except: from urllib.parse import unquote
cmd = "echo 'ERROR: Missing command=command-to-run in the source URL.' && false"
for opt in source.split("?", 1)[1].split("&"):
if opt.startswith("command="):
cmd = unquote(opt.split('=',1)[-1])
return downloadCmd(source, dest, options, cmd, userCommandDependencies([source]))
def downloadPip(source, dest, options):
# Valid PIP URL formats are
# pip://package/version?[pip_options=downloadOptions&][pip=pip_command&][pip_package=package&]output=/tarbalname
# pip://package/version/tarbalname
url_parts = source.split("pip://", 1)[1].split("?", 1)
opts = []
if len(url_parts) > 1: opts = url_parts[1].split("&")
pkg = url_parts[0].split("/")
pack = pkg[0].strip()
tar_names = [pack.replace("-", "_"), pack] if '-' in pack else [pack]
for tar_name in tar_names:
pypi_file = '%s-%s.tar.gz' % (tar_name, pkg[1].strip())
pypi_url = 'https://pypi.io/packages/source/%s/%s/%s' % (pack[0], pack, pypi_file)
if downloadUrllib2(pypi_url, dest, options):
comm = "mv %s/%s src.tar.gz; echo src.tar.gz > files.list" % (dest, pypi_file)
return downloadCmd(source, dest, options, comm, [])
pack = pack + '==' + pkg[1].strip()
pip_opts = "--no-deps --no-binary=:all:"
pip="pip"
isSourceDownload=True
for opt in opts:
if opt.startswith("pip="): pip=opt.split('=',1)[-1]
elif opt.startswith("pip_options="):
pip_optsT = opt[12:].replace("+", " ").replace("%20", " ").replace("%3D", "=")
# hack here a alternative source location
pip_opts = ''
spSrc = pip_optsT.split()
for i in range(len(spSrc)):
if 'ALTSRC' in spSrc[i]:
pack = spSrc[i + 1]
i = i + 1
else:
pip_opts = pip_opts + ' ' + spSrc[i]
if "no-binary" in spSrc[i] and "all" not in spSrc[i]:
isSourceDownload=False #not totally robust - but basically use pip if source is overridden
if isSourceDownload:
log("Looking for sources at https://pypi.org/pypi/"+pack.split('=')[0]+"/json")
fj=urlopen("https://pypi.org/pypi/"+pack.split('=')[0]+"/json")
data=json.load(fj)
url=None
if "releases" in data and pack.split('=')[2] in data["releases"]:
for file in data["releases"][pack.split('=')[2]]:
if file["packagetype"] == "sdist":
url=file["url"]
if url is not None:
log("Found source on pypi - downloading")
tempdir = createTempDir(options.workDir, options.tempDirPrefix)
precmd = "cd %s; " % tempdir
downloadUrllib2(url, tempdir, options)
cmd="/bin/ls "+tempdir+" | grep -v files.list > "+os.path.join(tempdir,"files.list")
getstatusoutput(cmd)
o,e=getstatusoutput(precmd+"cat files.list")
cmd=precmd+"tar cfz "+os.path.join(dest,"source.tar.gz")+" `cat files.list` files.list"
o,e=getstatusoutput(cmd)
getstatusoutput("rm -rf %s" % tempdir)
return True
if not '--no-deps' in pip_opts: pip_opts = '--no-deps ' + pip_opts
if not '--no-cache-dir' in pip_opts: pip_opts = '--no-cache-dir ' + pip_opts
comm = pip + ' download ' + pip_opts + ' --disable-pip-version-check -q -d . ' + pack + '; /bin/ls | grep -v files.list > files.list'
return downloadCmd(source, dest, options, comm, getPipSourceDependency([source], options.pipPackage))
downloadHandlers = {'cvs': downloadCvs,
'cmstc': downloadTc,
'http': downloadUrllib2,
'https': downloadUrllib2,
'ftp': downloadUrllib2,
'ftps': downloadUrllib2,
'git': downloadGit,
'svn': downloadSvn,
'pip': downloadPip,
'usercommand': downloadUserCommand}
def fixUrl(s):
for x in ['no-cmssdt-cache=1', 'cmdist-generated=1']:
if x in s:
s = s.replace(x,'').replace("&&","&").replace("?&","?")
if s.endswith('&'): s=s[:-1]
if s.endswith('?'): s=s[:-1]
return s
def getUrlChecksum(s):
m = md5adder(fixUrl(s).encode())
return m.hexdigest()
def isProcessRunning(pid):
running = False
try:
os.kill(pid, 0)
running = True
except:
pass
return running
class cmsLock(object):
def __init__(self, dirname):
self.piddir = join(dirname, ".cmsLock")
self.pidfile = join(self.piddir, "pid")
self.pid = str(getpid())
self._hasLock = False
self._hasLock = self._get()
def __del__(self):
self._release()
def __nonzero__(self):
return self._hasLock
def _release(self, force=False):
if (self._hasLock or force):
try:
if exists(self.piddir): getstatusoutput("rm -rf %s" % self.piddir)
except:
pass
self._hasLock = False
def _get(self, count=0):
if count >= 5: return False
pid = self._readPid()
if pid:
if pid == self.pid: return True
if isProcessRunning(int(pid)): return False
self._create()
sleep(0.0001)
return self._get(count + 1)
def _readPid(self):
pid = None
try:
pid = open(self.pidfile).readlines()[0]
except:
pid = None
return pid
def _create(self):
self._release(True)
try:
makedirs(self.piddir)
lock = open(self.pidfile, 'w')
lock.write(self.pid)
lock.close()
except:
pass
# Helper class which contains only the options that are
# relevant for download.
class DownloadOptions(object):
def __init__(self, options):
self.workDir = options.workDir
self.tempDirPrefix = options.tempDirPrefix
self.cmsdist = options.cmsdist
self.pipPackage = options.pipPackage
def getLocalSources(pkg, source_name, downloadDir, filename):
# check if given package's source location is overwritten to local file
options = pkg.options
local_source_dict = options.localSources
pkg_name = pkg.name
if (not pkg_name in local_source_dict) or (not source_name in local_source_dict[pkg_name]):
return
local_source_path = local_source_dict[pkg_name][source_name].rstrip("/$")
log("Package %s source %s is taken from local path %s" % (pkg_name, source_name, local_source_path))
cmd = None
ls_basename = os.path.basename(local_source_path)
ls_dirname = os.path.dirname(local_source_path)
if filename.endswith(".rpm") or filename.endswith("none"):
log("WARNING: the filename extension is not overwritable: %s " % filename)
return
elif os.path.isfile(local_source_path):
cmd = "cp -f %(local_source_path)s %(downloadDir)s/%(filename)s" % locals()
elif filename.endswith(".tgz") or filename.endswith(".tar.gz"):
cmd = "cd %(ls_dirname)s; tar -czf %(downloadDir)s/%(filename)s %(ls_basename)s; cd -" % locals()
elif filename.endswith(".tar.xz"):
cmd = "cd %(ls_dirname)s; tar -cJf %(downloadDir)s/%(filename)s %(ls_basename)s; cd -" % locals()
elif filename.endswith(".bz2"):
cmd = "cd %(ls_dirname)s; tar -cvjSf %(downloadDir)s/%(filename)s %(ls_basename)s; cd -" % locals()
elif filename.endswith(".zip"):
cmd = "cd %(ls_dirname)s; zip -r %(downloadDir)s/%(filename)s %(ls_basename)s; cd -" % locals()
else:
fatal("DEVELOP ERROR file extension is unknown for: %s" % filename)
log("The command executed to package local sources: %s" % cmd, DEBUG)
error, output = getstatusoutput(cmd)
if error:
fatal("Error while packaging and moving local sources: \n\t error: %s \n\t error log: %s"
"\n\t filename: %s \n\t source: %s \n\t local source path: %s " %
(error, output, filename, source_name, local_source_path))
return
def download(source, dest, options, pkg=None):
source_name = pkg.sourcesNumbers[source] if pkg else None
noCmssdtCache = True if 'no-cmssdt-cache=1' in source else False
isCmsdistGenerated = True if 'cmdist-generated=1' in source else False
source = fixUrl(source)
checksum = getUrlChecksum(source)
# Syntactic sugar to allow the following urls for tag collector:
#
# cmstc:[base.]release[.tagset[.tagset[...]]]/src.tar.gz
#
# in place of:
#
# cmstc://?tag=release&baserel=base&extratag=tagset1,tagset2,..&module=CMSSW&export=src&output=/src.tar.gz
if source.startswith("cmstc:") and not source.startswith("cmstc://"):
url = source.split(":", 1)[1]
desc, output = url.rsplit("/", 1)
parts = desc.split(".")
releases = [x for x in parts if not x.isdigit()]
extratags = [x for x in parts if x.isdigit()]
if extratags:
extratags = "&extratags=" + ",".join(extratags)
if len(releases) == 1:
baserel = ""
release = "tag=" + releases[0]
elif len(releases) == 2:
baserel = "&baserel=" + releases[0]
release = releases[1]
else:
raise MalformedUrl(source)
source = "cmstc://?%s%s%s&module=CMSSW&export=src&output=/%s" % (release, baserel, extratags, output)
cacheDir = abspath(join(options.workDir, "SOURCES/cache"))
urlTypeRe = re.compile(r"([^:+]*)([^:]*)://.*")
match = urlTypeRe.match(source)
if not urlTypeRe.match(source):
raise MalformedUrl(source)
downloadHandler = downloadHandlers[match.group(1)]
filename = source.rsplit("/", 1)[1]
downloadDir = join(cacheDir, checksum[0:2], checksum)
try:
makedirs(downloadDir)
except OSError as e:
if not exists(downloadDir):
raise downloadDir
realFile = join(downloadDir, filename)
# This will will use source from local file system if --source for package was passed
if source_name and options.localSources:
getLocalSources(pkg, source_name, downloadDir, filename)
if exists(realFile):
if dest and not exists(join(dest, filename)):
symlink(realFile, join(dest, filename))
return True
srepos = [options.repository]
for exrepo in ['cms', 'comp', 'cms.week0', 'cms.week1']:
if not exrepo in srepos: srepos.append(exrepo)
success = False
for mirror in [ options.server ] + options.source_mirror:
for repo in srepos:
cachedFile = "%s/SOURCES/%s/%s/%s" % (mirror.rstrip("/"), repo, checksum, filename)
downloadOptions = DownloadOptions(options)
log("Trying to fetch cached file: %s" % cachedFile, DEBUG)
getstatusoutput("rm -f %s" % join(downloadDir, ".no-cmsrep-upload"))
success = downloadHandlers["http"](cachedFile, downloadDir, downloadOptions, True)
if success:
noCmssdtCache = options.repository.startswith(repo)
break
if not success:
log("Trying to fetch source file: %s" % source, DEBUG)
success = downloadHandler(source, downloadDir, downloadOptions)
if success:
if noCmssdtCache:
r=open (join (downloadDir, ".no-cmsrep-upload"), 'w')
r.close ()
f = open(join(downloadDir, "url"), 'w')
f.write("%s\n" % source)
f.close()
if dest and exists(realFile) and not exists(join(dest, filename)):
symlink(realFile, join(dest, filename))
return (success or isCmsdistGenerated)
class MalformedUrl(Exception):
def __init__(self, url, missingParams=[]):
if not missingParams:
self.args = ["ERROR: The following url is malformed: %(url)s." % locals()]
else:
self.args = ["ERROR: The following parameters are missing from url %(url)s: %(missingParams)s" % locals()]
class MalformedSpec(Exception):
pass
class RpmBuildFailed(Exception):
def __init__(self, package):
self.args = ["Failed to build package %s." % package.name]
self.pkg = package
class UnexpectedFile(Exception):
def __init__(self, filename):
self.args = ["""Unexpected file:\n %s\n
Please remove it and start again.""" % filename]
class RpmInstallFailed(Exception):
def __init__(self, package, why=""):
self.args = ["Failed to install package %s. Reason:\n%s" % (package.name, why)]
self.pkg = package
self.why = why
class UnableToDownload(Exception):
pass
class FileNotFound(Exception):
def __init__(self, filename):
log(filename)
self.filename = filename
def __repr__(self):
log("Unable to find file %s" % self.filename)
class IncludedFileNotFound(Exception):
def __init__(self, specname, filename):
log(specname)
log(filename)
self.specname = specname
self.filename = filename
def __repr__(self):
log("Unable to find file %s (required by spec %s)" % (self.filename, self.specname))
class NotCorrectlyBootstrapped(Exception):
def __init__(self, why):
self.why = why
class UnknownCompiler(Exception):
pass
def tagToId(tag, origTag):
return int((tag or 0) and (tag.replace(origTag, "") or 1))
def idToTag(tagId, origTag):
if not tagId: