forked from cms-sw/pkgtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmsBuild
executable file
·4104 lines (3696 loc) · 171 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/python -u
#
# Driver script for building rpms from a configuration specified in CMSDIST.
#
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
from commands import getstatusoutput
from urllib2 import urlopen, URLError
from time import strftime
import sys
import copy
from ConfigParser import ConfigParser
from ConfigParser import InterpolationMissingOptionError
import re, os
import traceback
from optparse import OptionParser, OptionGroup
import fnmatch
from shutil import rmtree
import urllib2
from glob import glob
import itertools
import pickle
logLevel = 10
NORMAL=10
DEBUG=20
TRACE=30
DEFAULT_CVS_SERVER=":pserver:[email protected]:2401/local/reps/CMSSW"
DEFAULT_CVS_PASSWORD="AA_:yZZ3e"
DEFAULT_SPEC_REPOSITORY_MODULE="CMSDIST"
removeInitialSpace = re.compile ("^[ ]*", re.M)
cmsBuildFilename = abspath(__file__)
def fatal(message):
print "ERROR: " + message
sys.exit(1)
def die(message):
fatal(message)
# Minimal string sanitization.
def sanitize(s):
return re.sub("[^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))
# A recursive globbing helper.
def recursive_glob(treeroot, pattern):
results = []
for base, dirs, files in walk(treeroot):
goodfiles = fnmatch.filter(files, pattern) + fnmatch.filter(dirs, pattern)
results.extend(join(base, f) for f in goodfiles)
return results
rpm_db_cache = {}
def downloadUrllib2(source, destDir, options):
try:
dest = "/".join([destDir.rstrip("/"), basename(source)])
req = urllib2.Request(source, headers={"Cache-Control": "no-cache"})
s = urllib2.urlopen(req)
f = file(dest+".tmp","w")
# 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()
os.rename(dest+".tmp",dest)
except URLError, e:
if not "SOURCES/cache" in source:
log("Error while downloading %s: %s" % (source, e))
return False
except Exception, e:
print source, destDir
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 = 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"), "", 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("\.git$", "", re.sub("[?].*", "",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 (":pserver:.*")
isPserver = pserverUrlRe.match (cvsroot)
cvspassFilename = None
if args.has_key ("passwd") 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 (dirname(cmsBuildFilename), '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:
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)
command = format("cd %(exportpath)s &&"
"git init &&"
"git pull --tags %(protocol)s%(gitroot)s refs/heads/%(branch)s &&"
"git reset --hard %(tag)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"])
downloadHandlers = {'cvs': downloadCvs,
'cmstc': downloadTc,
'http': downloadUrllib2,
'https': downloadUrllib2,
'ftp': downloadUrllib2,
'ftps': downloadUrllib2,
'git': downloadGit,
'svn': downloadSvn}
def getUrlChecksum (s):
m = md5adder (s)
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
def download (source, dest, options):
# Syntactic sugar for git:/some/path to be equal to git+:///some/path
if source.startswith("git:") and not source.startswith("git://"):
source = "git+://" + source[4:]
# 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 ("([^:+]*)([^:]*)://.*")
match = urlTypeRe.match (source)
if not urlTypeRe.match (source):
raise MalformedUrl (source)
downloadHandler = downloadHandlers[match.group (1)]
checksum = getUrlChecksum (source)
filename = source.rsplit("/", 1)[1]
downloadDir = join (cacheDir, checksum)
try:
makedirs (downloadDir)
except OSError, e:
if not exists(downloadDir):
raise downloadDir
realFile = join (downloadDir,filename)
if exists (realFile) and not exists (join (dest, filename)):
symlink (realFile, join (dest, filename))
return True
if exists (realFile):
return True
cachedFile = "%s/%s/SOURCES/cache/%s/%s" % (options.server.rstrip ("/"), options.repository, checksum, filename)
downloadOptions = DownloadOptions(options)
log ("Trying to fetch cached file: %s" % cachedFile, DEBUG)
success = downloadHandlers["http"] (cachedFile, downloadDir, downloadOptions)
if not success:
success = downloadHandler (source, downloadDir, downloadOptions)
if success:
f=open (join (downloadDir, "url"), 'w')
f.write ("%s\n" % source)
f.close ()
if exists (realFile) and not exists (join (dest, filename)):
symlink (realFile, join (dest, filename))
return success
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 NotCorrectlyBootstrapped (Exception):
def __init__ (self, why):
self.why = why
class UnknownCompiler (Exception):
pass
# The initial id for a given tag. Change to 1 if you always want to have -cms.
INITIAL_ID = 0
def tagToId (tag, origTag):
return int ((tag or 0) and (tag.replace (origTag, "") or 1))
def idToTag (tagId, origTag):
if not tagId:
return ""
elif tagId == 1:
return origTag
else:
return "%s%s" % (origTag, tagId)
# Parses the `### RPM <group> <package> <realversion>` header.
# Such a header defines the package name, group and real version
# for a given package.
# Notice that for a package which matches the compiler
# name we allow the overriding of its version with the one specified
# in the `compilerVersion` settings.
# Notice also that the one can specify /bin/sh commands in backticks
# for the version, so that stuff like the date can be added to the
# version (useful for IB and alikes).
# FIXME: notice that for compatibility with old packages, which were
# specifying a -CMSXYZ tag by hand, we remove such a suffix from
# the version. This is probably not needed anymore and can go.
def parseRPMLine (specLines, opts):
findRpmRe = re.compile ("^### RPM[ ]*([^ ]*)\s*([^ ]*)\s*(.*)")
for line in specLines:
match = findRpmRe.match (line)
if not match:
continue
results = [x.strip (" ") for x in match.groups ()]
results[2] = re.sub ("-CMS.*","",results[2])
group, name, version = results
error, output = getstatusoutput("echo %s" % version)
if error:
raise MalformedSpec
version = output.split("\n")[0]
if opts.compilerVersion and name == opts.compilerName:
version = opts.compilerVersion
return (group, name, version)
raise MalformedSpec
def parseNoCompilerLine(specLines):
findNoCompilerRe = re.compile ("^## NOCOMPILER")
for line in specLines:
if findNoCompilerRe.match(line):
return True
return False
def parseBuildRequireToolfileLine(specLines):
findBRToolfileRe = re.compile ("^## BUILDREQUIRE-TOOLFILE")
for line in specLines:
if findBRToolfileRe.match(line):
return True
return False
class PkgInfo (object):
""" Minimal information about a package.
"""
def __init__ (self, pkg):
self.name = pkg.name
self.realVersion = pkg.realVersion
self.group = pkg.group
self.checksum = pkg.checksum
self.cmsplatf = pkg.cmsplatf
def id (self):
return "%(group)s+%(name)s+%(realVersion)s" % self.__dict__
def getPkgName (filename):
return re.match ("(.*)-1-[1-9]+[.].*", basename(filename)).group (1)
def getPkgChecksumFile (officialRpmLocation, buildOptions=None):
try:
link = readlink (officialRpmLocation)
except OSError:
log ("""ERROR! File %(officialRpmLocation)s is not a link!?!?
Are you running in an old cmsBuild.sh/install.sh area?
If so, please remove the old package by doing:
rm -rf %(officialRpmLocation)s
and try again.
""" % locals ())
sys.exit (1)
if not exists (link):
packageName = getPkgName (officialRpmLocation)
cmsBuildExec = sys.argv[0]
workdir = buildOptions.workDir and "--work-dir %s"% buildOptions.workDir or ""
doNotBootstrap = buildOptions.bootstrap and "" or "--do-not-bootstrap"
architecture = "--architecture %s" % buildOptions.architecture
cmsdist = "--cmsdist %s" % buildOptions.cmsdist
brokenLink = join(buildOptions.workDir, officialRpmLocation)
log ("""ERROR: File
%(brokenLink)s
links to
%(link)s
but the latter does not exists. Please run:
# %(cmsBuildExec)s %(cmsdist)s %(architecture)s %(workdir)s %(doNotBootstrap)s deprecate-local %(packageName)s
to fix the problem and then try again.
""" % locals ())
sys.exit (1)
checksum = re.match (".*/(.*)/.*/.*", link).groups ()[0]
if not checksum:
log ("""ERROR: malformed link found: %(link)s.""" % locals ())
sys.exit (1)
return checksum
class TagCacheAptImpl (object):
""" Concrete implementation of the tag cache which relies on the
apt repository information and locally found packages. Consistency
is enforced by policy (only one person is allowed to upload packages
for a given tag) and by checking at upload time that packages are not
already in the repository.
"""
def __init__ (self, options):
self.options = options
def update (self):
if self.options.bootstrap:
aptGetUpdateCommand = "apt-get update -o Acquire::http::No-Cache=true -o Acquire::http::Pipeline-Depth=0"
error, output = getstatusoutput (aptGetUpdateCommand)
if error:
die("Error while executing apt-get update.\n%s" % output)
aptCacheCommand = "apt-cache search SpecChecksum"
error, output = getstatusoutput(aptCacheCommand)
if error:
die("Error while executing apt-cache search SpecCheckum.\n%s" % output)
lines = [line for line in output.split("\n") if line]
chksumRE = re.compile("\s+-\s+.*?SpecChecksum:")
pairs = [chksumRE.sub(' ',line).split() for line in lines]
try:
self.cache = dict(pairs)
except:
die("Malformed apt-cache output.")
def requestTag (self, pkgInfo, tag):
""" requestTag returns a unique tag (i.e. the mnemonic suffix at the
end of the package name) based on what is found in the online
database and in the local build area.
@a pkgInfo is the structure which holds the information about a
tag.
@a tag the mnemonic tag to be used to keep track of different
package builds. E.g. "cms" or "ge"
@return a unique tag (ie cmsXXX) which can be used for the package.
"""
tags = {}
if self.options.bootstrap:
matchingPackages = [(n, self.cache[n]) for n in self.cache if pkgInfo.id() in n]
for name, checksum in matchingPackages:
tempTag = name.replace(pkgInfo.id (), "").strip ("-")
tags[tempTag] = checksum
for package in listdir (join ("RPMS", pkgInfo.cmsplatf)):
if pkgInfo.id() not in package:
continue
linkName = join ("RPMS", pkgInfo.cmsplatf, package)
checksum = getPkgChecksumFile (linkName, self.options)
tempTag = getPkgName(package).replace (pkgInfo.id (), "").strip ("-")
tags[tempTag] = checksum
for i in itertools.count(INITIAL_ID):
finalTag = idToTag (i, tag)
if finalTag not in tags:
break
return finalTag
def getTag (self, pkg):
""" getTag looks up for a tag associated to an md5 sum the following way.
1) Look up in the cache apt-cache search results.
2) Looks up in RPMS/cache/<checksum> to see if a package is already there.
"""
output = ""
if self.options.bootstrap:
matchingPackages = [n for n in self.cache if self.cache[n]==pkg.checksum]
if len(matchingPackages)>1:
orderedPackages = []
for n in matchingPackages:
if exists("%s/RPMS/cache/" % self.options.workDir + "%(checksum)s/%(cmsplatf)s/" % pkg.__dict__ + n + "-%(rpmVersion)s-%(pkgRevision)s.%(cmsplatf)s.rpm" % pkg.__dict__):
orderedPackages.insert(0,n)
else:
orderedPackages.append(n)
matchingPackages = orderedPackages
if len(matchingPackages):
output = matchingPackages[0]
else:
return None
else:
try:
assert (pkg.cmsplatf and pkg.cmsplatf != "%cmsplatf")
assert (pkg.checksum and pkg.checksum != "%checksum" and pkg.checksum != "%{nil}")
rpmCachePath = join (abspath ("RPMS"),
"cache/%(checksum)s/%(cmsplatf)s" % pkg.__dict__)
if "%{" in rpmCachePath:
print "ERROR: you seem to be using an old rpm-preamble.file in your CMSDIST."
print "Please make sure you update it to revision 1.20 at least."
sys.exit(1)
files = listdir (rpmCachePath % pkg.__dict__)
if len (files) > 1 + len(pkg.subpackages):
log ("""ERROR: %s structure is hoosed. You might want to do:
cmsBuild remove %s""" % (rpmCachePath,
getPkgName(files[0])))
sys.exit (1)
elif not len (files):
return None
output = getPkgName(files[0])
except OSError:
return None
if not output:
return None
fullVersion = output.rsplit("+", 1)[1]
if "-" not in fullVersion:
return ""
tag = fullVersion.rsplit("-", 1)[1]
# Return tag if it is not part of realVersion
if not pkg.realVersion.endswith("-"+tag):
return tag
return ""
def packageChecksums (self, package):
"""
"""
assert (False and "Not implemented for the time being.")
global tags_cache
tags_cache = None
# FIXME: write a more valuable description
DEFAULT_SECTIONS = {"": """
""",
"%%description": """
No description
""",
"%prep": """
%%setup -n %n-%realversion
""",
"%build": """
%initenv
./configure --prefix=%i
make
""",
"%install": """
%initenv
make install
""",
"%pre": """
if [ X"$(id -u)" = X0 ]; then
echo "*** CMS SOFTWARE INSTALLATION ABORTED ***"
echo "CMS software cannot be installed as the super-user."
echo "(We recommend reading a unix security guide)."
exit 1
fi
""",
"%post": """
if [ "X$CMS_INSTALL_PREFIX" = "X" ] ; then CMS_INSTALL_PREFIX=$RPM_INSTALL_PREFIX; export CMS_INSTALL_PREFIX; fi
%{relocateConfig}etc/profile.d/init.sh
%{relocateConfig}etc/profile.d/init.csh
""",
"%preun": """
""",
"%postun": """
if [ "X$CMS_INSTALL_PREFIX" = "X" ] ; then CMS_INSTALL_PREFIX=$RPM_INSTALL_PREFIX; export CMS_INSTALL_PREFIX; fi
""",
"%files": """
%{i}/
%dir %{instroot}/
%dir %{instroot}/%{cmsplatf}/
%dir %{instroot}/%{cmsplatf}/%{pkgcategory}/
%dir %{instroot}/%{cmsplatf}/%{pkgcategory}/%{pkgname}/
"""}
COMPILER_DETECTION = { "gcc": "gcc -v 2>&1 | grep version | sed -e \'s|.*\\([0-9][.][0-9][.][0-9]\\).*|\\1|\'",
"icc": "echo no detection callback for icc."}
# Preambles. %dynamic_path_var is defined in rpm-preamble.
INITENV_PREAMBLE = [
("CMD_SH", "if", "[ -f %i/etc/profile.d/dependencies-setup.sh ]; then . %i/etc/profile.d/dependencies-setup.sh; fi"),
("CMD_CSH", "if", "( -f %i/etc/profile.d/dependencies-setup.csh ) source %i/etc/profile.d/dependencies-setup.csh; endif"),
("SETV", "%(uppername)s_ROOT", "%i"),
("SETV", "%(uppername)s_VERSION", "%v"),
("SETV", "%(uppername)s_REVISION", "%pkgrevision"),
("SETV", "%(uppername)s_CATEGORY", "%pkgcategory"),
("+PATH", "PATH", "%i/bin"),
("+PATH", "%%{dynamic_path_var}", "%i/lib")]
DEFAULT_PREAMBLE = """
"""
DEFAULT_DESCRIPTION_PREAMBLE = """
"""
DEFAULT_PREP_PREAMBLE = """
%initenv
[ -d %i ] && chmod -R u+w %i
rm -fr %i
"""
DEFAULT_BUILD_PREAMBLE = """
%initenv
"""
DEFAULT_INSTALL_PREABLE = """
mkdir -p %i
mkdir -p %_rpmdir
mkdir -p %_srcrpmdir
%initenv
"""
DEFAULT_PRE_PREAMBLE = """
if [ X"$(id -u)" = X0 ]; then
echo "*** CMS SOFTWARE INSTALLATION ABORTED ***"
echo "CMS software cannot be installed as the super-user."
echo "(We recommend reading a unix security guide)."
exit 1
fi
"""
DEFAULT_POST_PREAMBLE = """
if [ "X$CMS_INSTALL_PREFIX" = "X" ] ; then CMS_INSTALL_PREFIX=$RPM_INSTALL_PREFIX; export CMS_INSTALL_PREFIX; fi
%{relocateConfig}etc/profile.d/init.sh
%{relocateConfig}etc/profile.d/init.csh
"""
DEFAULT_PREUN_PREAMBLE = """
"""
DEFAULT_POSTUN_PREAMBLE = """
if [ "X$CMS_INSTALL_PREFIX" = "X" ] ; then CMS_INSTALL_PREFIX=$RPM_INSTALL_PREFIX; export CMS_INSTALL_PREFIX; fi
"""
DEFAULT_FILES_PREAMBLE = """
%%defattr(-, root, root)
"""
COMMANDS_SH = {"SETV": """%(var)s="%(value)s"\n""",
"SET": """export %(var)s="%(value)s";\n""",
"+PATH": """[ ! -d %(value)s ] || export %(var)s="%(value)s${%(var)s:+:$%(var)s}";\n""",
"UNSET": """unset %(var)s || true\n""",
"CMD": """%(var)s %(value)s\n""",
"CMD_SH": """%(var)s %(value)s\n""",
"CMD_CSH": "",
"ALIAS": """alias %(var)s="%(value)s"\n""",
"ALIAS_CSH": "",
"ALIAS_SH": """alias %(var)s="%(value)s"\n"""}
COMMANDS_CSH = {"SETV": """set %(var)s="%(value)s"\n""",
"SET": """setenv %(var)s "%(value)s"\n""",
"+PATH": """if ( -d %(value)s ) then\n"""
""" if ( ${?%(var)s} ) then\n"""
""" setenv %(var)s "%(value)s:$%(var)s"\n"""
""" else\n"""
""" setenv %(var)s "%(value)s"\n"""
""" endif\n"""
"""endif\n""",
"UNSET": """unset %(var)s || true\n""",
"CMD": """%(var)s %(value)s\n""",
"CMD_SH": "",
"CMD_CSH": """%(var)s %(value)s\n""",
"ALIAS": """alias %(var)s "%(value)s"\n""",
"ALIAS_SH": "",
"ALIAS_CSH":"""alias %(var)s "%(value)s"\n"""}
SPEC_HEADER = """
%%define pkgname %(name)s
%%define pkgversion %(version)s
%%define pkgcategory %(group)s
%%define cmsroot %(workDir)s
%%define instroot %(workDir)s/%(tempDirPrefix)s/BUILDROOT/%(checksum)s%(installDir)s
%%define realversion %(realVersion)s
%%define gccver %(compilerRealVersion)s
%%define compilerRealVersion %(compilerRealVersion)s
%%define pkgrevision %(pkgRevision)s
%%define pkgreqs %(pkgreqs)s
%%define directpkgreqs %(directpkgreqs)s
%%define specchecksum %(checksum)s
%%define cmscompiler %(compilerName)s
%%define cmsbuildApiVersion 1
%%define installroot %(installDir)s
%%define tempprefix %(tempDirPrefix)s
Name: %(group)s+%(name)s+%(version)s
Group: %(group)s
Version: %(rpmVersion)s
Release: %(pkgRevision)s
License: "As required by the orginal provider of the software."
Summary: %(summary)s SpecChecksum:%(checksum)s
%(requiresStatement)s
Packager: CMS <[email protected]>
Distribution: CMS
Vendor: CMS
Provides: %(group)s+%(name)s+%(version)s
Obsoletes: %(group)s+%(name)s+%(version)s
Prefix: %(installDir)s
"""
DEFAULT_INSTALL_POSTAMBLE="""
# Avoid pkgconfig dependency. Notice you still need to keep the rm statement
# to support architectures not being build with cmsBuild > V00-19-XX
%if "%{?keep_pkgconfig:set}" != "set"
if [ -d "%i/lib/pkgconfig" ]; then rm -rf %i/lib/pkgconfig; fi
%endif
# Do not package libtool and archive libraries, unless required.
%if "%{?keep_archives:set}" != "set"
# Don't need archive libraries.
rm -f %i/lib/*.{l,}a
%endif
# Strip executable / paths which were specified in the strip_files macro.
%if "%{?strip_files:set}" == "set"
for x in %strip_files
do
if [ -e $x ]
then
find $x -type f -perm -a+x -exec %strip {} \;
fi
done
%endif
# remove files / directories which were specified by the drop_files macro.
%if "%{?drop_files:set}" == "set"
for x in %drop_files
do
if [ -e $x ]; then rm -rf $x; fi
done
%endif
case %{cmsplatf} in
osx* )
for x in `find %{i} -type f -perm -u+x | grep -v -e "[.]pyc"`;
do
if [ "X`file --mime $x | sed -e 's| ||g' | cut -d: -f2 | cut -d\; -f1`" = Xapplication/octet-stream ]
then
chmod +w $x
old_install_name=`otool -D $x | tail -1 | sed -e's|:$||'`
new_install_name=`basename $old_install_name`
install_name_tool -change $old_install_name $new_install_name -id $new_install_name $x
# Make sure also dependencies do not have an hardcoded path.
for dep in `otool -L $x | sed -e"s|[^\\t\\s ]*%{instroot}|%{instroot}|" | grep -e '^/' | sed -e's|(.*||'`
do
install_name_tool -change $dep `basename $dep` $x
done
chmod -w $x
fi
done
;;
* )
;;
esac
"""