-
Notifications
You must be signed in to change notification settings - Fork 690
/
application.py
1617 lines (1366 loc) · 63.1 KB
/
application.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
##
# Copyright 2009-2012 Stijn Deweirdt, Dries Verdegem, Kenneth Hoste, Pieter De Baets, Jens Timmerman
#
# This file is part of EasyBuild,
# originally created by the HPC team of the University of Ghent (http://ugent.be/hpc).
#
# http://github.com/hpcugent/easybuild
#
# EasyBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
from difflib import get_close_matches
from distutils.version import LooseVersion
import glob
import grp #@UnresolvedImport
import os
import shutil
import time
import urllib
import easybuild
from easybuild.tools.build_log import EasyBuildError, initLogger, removeLogHandler,print_msg
from easybuild.tools.config import source_path, buildPath, installPath
from easybuild.tools.filetools import unpack, patch, run_cmd, convertName
from easybuild.tools.module_generator import ModuleGenerator
from easybuild.tools.modules import Modules
from easybuild.tools.toolkit import Toolkit
from easybuild.tools.systemtools import get_core_count
class Application:
"""
This is the dummy Application class.
All other Application classes should be inherited from this one
"""
## INIT
def __init__(self, name=None, version=None, newBuild=True, debug=False):
"""
Initialize the Application instance.
"""
self.log = None
self.logfile = None
self.loghandler = None
self.logdebug = debug
self.patches = []
self.src = []
self.dep = []
self.tk = None
self.builddir = None
self.installdir = None
self.pkgs = None
self.skip = None
## final version
self.installversion = 'NOT_VALID'
## valid moduleclasses
self.validmoduleclasses = ['base', 'compiler', 'lib']
## vaild stop options
self.validstops = ['cfg', 'source', 'patch', 'configure', 'make', 'install', 'test', 'postproc', 'cleanup', 'packages']
# module generator
self.moduleGenerator = None
# extra stuff for module file required by packages
self.moduleExtraPackages = ''
# sanity check paths and result
self.sanityCheckPaths = None
self.sanityCheckOK = False
# indicates whether build should be performed in installation dir
self.build_in_installdir = False
# set name and version if they're provided
if name and version:
self.set_name_version(name, version, newBuild)
# allow a post message to be set, which can be shown as last output
self.postmsg = ''
# generic configuration parameters
self.cfg = {
'name':[None, "Name of software"],
'version':[None, "Version of software"],
'easybuildVersion': [None, "EasyBuild-version this spec-file was written for"],
'group':[None, "Name of the user group for which the software should be available"],
'versionsuffix':['', 'Additional suffix for software version (placed after toolkit name)'],
'versionprefix':['', 'Additional prefix for software version (placed before version and toolkit name)'],
'runtest':[None, 'Indicates if a test should be run after make; should specify argument after make (for e.g., "test" for make test) (Default: None)'],
'preconfigopts':['', 'Extra options pre-passed to configure.'],
'configopts':['', 'Extra options passed to configure (Default already has --prefix)'],
'premakeopts':['', 'Extra options pre-passed to make.'],
'makeopts':['', 'Extra options passed to make (Default already has -j X)'],
'installopts':['', 'Extra options for installation (Default: nothing)'],
'moduleclass':['base', 'Module class to be used for this software (Default: base) (Valid: %s)' % self.validmoduleclasses],
'moduleforceunload':[False, 'Force unload of all modules when loading the package (Default: False)'],
'moduleloadnoconflict':[False, "Don't check for conflicts, unload other versions instead (Default: False)"],
'startfrom':[None, 'Path to start the make in. If the path is absolute, use that path. If not, this is added to the guessed path.'],
'onlytkmod':[False, 'Boolean/string to indicate if the toolkit should only load the enviornment with module (True) or also set all other variables (False) like compiler CC etc (If string: comma separated list of variables that will be ignored). (Default: False)'],
'stop':[None, 'Keyword to halt the buildprocess at certain points. Valid are %s' % self.validstops],
'homepage':[None, 'The homepage of the software'],
'description':[None, 'A short description of the software'],
'parallel':[None, 'Degree of parallelism for e.g. make (default: based on the number of cores and restrictions in ulimit)'],
'maxparallel':[None, 'Max degree of parallelism (default: None)'],
'keeppreviousinstall':[False, 'Boolean to keep the previous installation with identical name. Default False, expert s only!'],
'cleanupoldbuild':[True, 'Boolean to remove (True) or backup (False) the previous build directory with identical name or not. Default True'],
'cleanupoldinstall':[True, 'Boolean to remove (True) or backup (False) the previous install directory with identical name or not. Default True'],
'dontcreateinstalldir':[False, 'Boolean to create (False) or not create (True) the install directory (Default False)'],
'toolkit':[None, 'Name and version of toolkit'],
'toolkitopts':['', 'Extra options for compilers'],
'keepsymlinks':[False, 'Boolean to determine whether symlinks are to be kept during copying or if the content of the files pointed to should be copied'],
'licenseServer':[None, 'License server for software'],
'licenseServerPort':[None, 'Port for license server'],
'key':[None, 'Key for installing software'],
'pkglist':[[], 'List with packages added to the baseinstallation (Default: [])'],
'pkgmodulenames':[{}, 'Dictionary with real modules names for packages, if they are different from the package name (Default: {})'],
'pkgloadmodule':[True, 'Load the to-be installed software using temporary module (Default: True)'],
'pkgtemplate':["%s-%s.tar.gz", "Template for package source file names (Default: %s-%s.tar.gz)"],
'pkgfindsource':[True, "Find sources for packages (Default: True)"],
'pkginstalldeps':[True, "Install dependencies for specified packages if necessary (Default: True)"],
'pkgdefaultclass':[None, "List of module for and name of the default package class (Default: None)"],
'skip':[False, "Skip existing software (Default: False)"],
'pkgfilter':[None, "Package filter details. List with template for cmd and input to cmd (templates for name, version and src). (Default: None)"],
'pkgpatches':[[], 'List with patches for packages (default: [])'],
'pkgcfgs':[{}, 'Dictionary with config parameters for packages (default: {})'],
'dependencies':[[], "List of dependencies (default: [])"],
'builddependencies':[[], "List of build dependencies (default: [])"],
'unpackOptions':[None, "Extra options for unpacking source (default: None)"],
'modextravars':[{}, "Extra environment variables to be added to module file (default: {})"],
'osdependencies':[[], "Packages that should be present on the system"],
'sources': [[], "List of source files"],
'sourceURLs' : [[], "List of URLs for source files"],
'patches': [[], "List of patches to apply"],
'tests': [[], "List of test-scripts to run after install. A test script should return a non-zero exit status to fail"],
'sanityCheckPaths': [{}, "List of files and directories to check (format: {'files':<list>, 'dirs':<list>}, default: {})"],
'buildstats' : [None, "A list of dicts with buildstats: build_time, platform, core_count, cpu_model, install_size, timestamp"],
}
# mandatory config entries
self.mandatory = ['name', 'version', 'homepage', 'description', 'toolkit']
def autobuild(self, ebfile, runTests):
"""
Build the software package described by cfg.
"""
self.process_ebfile(ebfile)
if self.getcfg('stop') and self.getcfg('stop') == 'cfg':
return True
self.log.info('Read easyconfig %s' % ebfile)
self.ready2build()
self.build()
# Last stop
if self.getcfg('stop'):
return True
self.make_module()
# Run tests
if runTests and self.getcfg('tests'):
self.runtests()
else:
self.log.debug("Skipping tests")
return True
def set_name_version(self, name, version, newBuild=True):
"""
Sets name and version
- also starts logger
"""
self.setcfg('name', name)
self.setcfg('version', version)
if newBuild:
self.setlogger()
def setlogger(self):
"""
Set the logger.
"""
if not self.log:
self.logfile, self.log, self.loghandler = initLogger(self.name(), self.version(),
self.logdebug, typ=self.__class__.__name__)
self.log.info("Init completed for application name %s version %s" % (self.name(), self.version()))
def closelog(self):
"""
Shutdown the logger.
"""
self.log.info("Closing log for application name %s version %s" % (self.name(), self.version()))
removeLogHandler(self.loghandler)
self.loghandler.close()
## PARALLELISM
def setparallelism(self, nr=None):
"""
Determines how many processes should be used (default: nr of procs - 1).
"""
if not nr and self.getcfg('parallel'):
nr = self.getcfg('parallel')
if nr:
try:
nr = int(nr)
except ValueError, err:
self.log.error("Parallelism %s not integer: %s" % (nr, err))
else:
nr = get_core_count()
## check ulimit -u
out, ec = run_cmd('ulimit -u')
try:
if out.startswith("unlimited"):
out = 2 ** 32 - 1
maxuserproc = int(out)
## assume 6 proc per buildthread + 15 overhead
maxnr = int((maxuserproc - 15) / 6)
if maxnr < nr:
nr = maxnr
self.log.info("Limit parallel builds to %s because max user processes is %s" % (nr, out))
except ValueError, err:
self.log.exception("Failed to determine max user processes (%s,%s): %s" % (ec, out, err))
maxpar = self.getcfg('maxparallel')
if maxpar and maxpar < nr:
self.log.info("Limiting parallellism from %s to %s" % (nr, maxpar))
nr = min(nr, maxpar)
self.setcfg('parallel', nr)
self.log.info("Setting parallelism: %s" % nr)
def addpatch(self, listOfPatches=None):
"""
Add a list of patches.
All patches will be checked if a file exists (or can be located)
"""
if listOfPatches:
for patchFile in listOfPatches:
## check if the patches can be located
suff = None
level = None
if type(patchFile) == list:
if not len(patchFile) == 2:
self.log.error("Unknown patch specification '%s', only two-element lists are supported!" % patchFile)
pf = patchFile[0]
if type(patchFile[1]) == int:
level = patchFile[1]
elif type(patchFile[1]) == str:
suff = patchFile[1]
else:
self.log.error("Wrong patch specification '%s', only int and string are supported as second element!" % patchFile)
else:
pf = patchFile
path = self.file_locate(pf)
if path:
self.log.debug('File %s found for patch %s' % (path, patchFile))
tmppatch = {'name':pf, 'path':path}
if suff:
tmppatch['copy'] = suff
if level:
tmppatch['level'] = level
self.patches.append(tmppatch)
else:
self.log.error('No file found for patch %s' % patchFile)
self.log.info("Added patches: %s" % self.patches)
def addsource(self, listOfSources=None):
"""
Add a list of source files (can be tarballs, isos, urls).
All source files will be checked if a file exists (or can be located)
"""
if listOfSources:
for source in listOfSources:
## check if the sources can be located
path = self.file_locate(source)
if path:
self.log.debug('File %s found for source %s' % (path, source))
self.src.append({'name':source, 'path':path})
else:
self.log.error('No file found for source %s' % source)
self.log.info("Added sources: %s" % self.src)
def settoolkit(self, name, version):
"""
Add the build toolkit to be used.
"""
self.tk = Toolkit(name, version)
self.log.info("Added toolkit: name %s version %s" % (self.tk.name, self.tk.version))
def add_dependency(self, dependencies=None):
"""
Add application dependencies. A dependency should be specified as a dictionary
or as a list of the following form: (name, version, suffix, dummy_boolean)
(suffix and dummy_boolean are optional)
"""
if dependencies and len(dependencies) > 0:
self.log.info("Adding dependencies: %s" % dependencies)
self.dep.extend([self.parse_dependency(d) for d in dependencies])
def parse_dependency(self, dep):
"""
Read a dependency declaration and transform it to a common format.
"""
result = {'name': '', 'version': '', 'prefix': '', 'suffix': ''}
if type(dep) == dict:
## check for name and version key
if not 'name' in dep:
self.log.error('Dependency without name.')
return
result.update(dep)
elif type(dep) in [list, tuple]:
result['name'] = dep[0]
if len(dep) >= 2:
result['version'] = dep[1]
if len(dep) >= 3:
result['suffix'] = dep[2]
if len(dep) >= 4:
result['dummy'] = dep[3]
else:
self.log.error('Dependency %s from unsupported type: %s.' % (dep, type(dep)))
return
if not 'version' in result:
self.log.warning('Dependency without version.')
if not 'tk' in result:
result['tk'] = self.tk.getDependencyVersion(result)
return result
## process EasyBuild spec file
def process_ebfile(self, fn):
"""
Read file fn, eval and add info
- assume certain predefined variable names
"""
if not os.path.isfile(fn) and self.log:
self.log.error("Can't import config from unknown filename %s" % fn)
try:
locs = {"self": self}
execfile(fn, {}, locs)
except (IOError, SyntaxError), err:
msg = "Parsing eb file %s failed: %s" % (fn, err)
if self.log:
self.log.exception(msg)
else:
raise EasyBuildError("%s: %s" % (msg, err))
## initialize logger
if 'name' in locs and 'version' in locs:
self.set_name_version(locs['name'], locs['version'])
else:
self.setlogger()
## check EasyBuild version
easybuildVersion = locs.get('easybuildVersion', None)
if not easybuildVersion:
self.log.warn("Easyconfig does not specify an EasyBuild-version (key 'easybuildVersion')! Assuming the latest version")
else:
if LooseVersion(easybuildVersion) < easybuild.VERSION:
self.log.warn("EasyBuild-version %s is older than the currently running one. Proceed with caution!" % easybuildVersion)
elif LooseVersion(easybuildVersion) > easybuild.VERSION:
self.log.error("EasyBuild-version %s is newer than the currently running one. Aborting!" % easybuildVersion)
## check for typos in eb file
for variable in locs.keys():
guess = get_close_matches(variable, self.cfg.keys(), 1, 0.85)
if len(guess) == 1 and variable not in self.cfg.keys():
# We might have a typo here
self.log.error("Don't you mean '%s' instead of '%s' as eb file variable." % (guess[0], variable))
for k in self.cfg.keys():
if k in locs:
self.setcfg(k, locs[k])
self.log.info("Using cfg option %s: value %s" % (k, self.getcfg(k)))
for k in self.mandatory:
if not k in locs:
self.log.error("No cfg option %s provided" % k)
if self.getcfg('stop') and not (self.getcfg('stop') in self.validstops):
self.log.error("Stop provided %s is not valid: %s" % (self.cfg['stop'], self.validstops))
if not (self.getcfg('moduleclass') in self.validmoduleclasses):
self.log.error("Moduleclass provided %s is not valid: %s" % (self.cfg['moduleclass'], self.validmoduleclasses))
if self.getcfg('stop') == 'cfg':
self.log.info("Stopping in parsing cfg")
return
if self.getcfg('osdependencies'):
self.check_osdeps(self.getcfg('osdependencies'))
if self.getcfg('sources'):
self.addsource(self.getcfg('sources'))
else:
self.log.info('no sources provided')
if self.getcfg('patches'):
self.addpatch(self.getcfg('patches'))
else:
self.log.info('no patches provided')
if self.getcfg('toolkit'):
self.log.debug("toolkit: %s" % self.getcfg('toolkit'))
tk = self.getcfg('toolkit')
self.settoolkit(tk['name'], tk['version'])
else:
self.log.error('no toolkit defined')
if self.getcfg('toolkitopts'):
self.tk.setOptions(self.getcfg('toolkitopts'))
if self.getcfg('dependencies'):
self.add_dependency(self.getcfg('dependencies'))
else:
self.log.info('no dependencies provided')
# Build dependencies
builddeps = [self.parse_dependency(d) for d in self.getcfg('builddependencies')]
self.add_dependency(builddeps)
self.setcfg('builddependencies', builddeps)
self.setparallelism()
self.make_installversion()
def getcfg(self, key):
"""
Get a configuration item.
"""
return self.cfg[key][0]
def setcfg(self, key, value):
"""
Set configuration key to value.
"""
self.cfg[key][0] = value
def updatecfg(self, key, value):
"""
Update a string configuration value with a value (i.e. append to it).
"""
prev_value = self.getcfg(key)
if not type(prev_value) == str:
self.log.error("Can't update configuration value for %s, because it's not a string." % key)
new_value = '%s %s ' % (prev_value, value)
self.setcfg(key, new_value)
def check_osdeps(self, osdeps):
"""
Check if packages are available from OS. osdeps should be a list of dependencies.
If an element of osdeps is a list, checks will pass if one of the elements of the list is found
"""
not_found = []
for check in osdeps:
if type(check) != list:
check = [check]
# find at least one element of check
# - using rpm -q for now --> can be run as non-root!!
# - should be extended to files later?
for d in check:
cmd = "rpm -q %s" % d
(rpmout, ec) = run_cmd(cmd, simple=False, log_all=False, log_ok=False)
if ec == 0:
self.log.debug("Found osdep %s" % d)
else:
not_found.append(d)
self.log.info("Couldn't find OS dependency check %s: %s" % (check, rpmout))
if not not_found:
self.log.info("OS dependencies ok: %s" % osdeps)
else:
self.log.error("One or more OS dependencies were not found: %s" % not_found)
## BUILD
def ready2build(self):
"""
Verify if all is ok to start build.
"""
# Check whether modules are loaded
loadedmods = Modules().loaded_modules()
if len(loadedmods) > 0:
self.log.warning("Loaded modules detected: %s" % loadedmods)
# Do all dependencies have a toolkit version
self.tk.addDependencies(self.dep)
if not len(self.dep) == len(self.tk.dependencies):
self.log.debug("dep %s (%s)\ntk.dep %s (%s)" % (len(self.dep), self.dep, len(self.tk.dependencies), self.tk.dependencies))
self.log.error('Not all dependencies have a matching toolkit version')
# Check if the application is not loaded at the moment
envName = "SOFTROOT%s" % convertName(self.name(), upper=True)
if envName in os.environ:
self.log.error("Module is already loaded (%s is set), installation cannot continue." % envName)
# Check if main install needs to be skipped
# - if a current module can be found, skip is ok
# -- this is potentially very dangerous
if self.getcfg('skip'):
if Modules().exists(self.name(), self.installversion):
self.skip = True
self.log.info("Current version (name: %s, version: %s) found. Going to skip actually main build and potential exitsing packages. Expert only." % (self.name(), self.installversion))
else:
self.log.info("No current version (name: %s, version: %s) found. Not skipping anything." % (self.name(), self.installversion))
def file_locate(self, filename, pkg=False):
"""
Locate the file with the given name
- searches in different subdirectories of source path
- supports fetching file from the web if path is specified as an url (i.e. starts with "http://:")
"""
srcpath = source_path()
# make sure we always deal with a list, to avoid code duplication
if type(srcpath) == str:
srcpaths = [srcpath]
elif type(srcpath) == list:
srcpaths = srcpath
else:
self.log.error("Source path '%s' has incorrect type: %s" % (srcpath, type(srcpath)))
def download(filename, url, path):
self.log.debug("Downloading %s from %s to %s" % (filename, url, path))
# make sure directory exists
basedir = os.path.dirname(path)
if not os.path.exists(basedir):
os.makedirs(basedir)
downloaded = False
attempt_cnt = 0
# try downloading three times max.
while not downloaded and attempt_cnt < 3:
(_, httpmsg) = urllib.urlretrieve(url, path)
if httpmsg.type == "text/html" and not filename.endswith('.html'):
self.log.warning("HTML file downloaded but not expecting it, so assuming invalid download.")
self.log.debug("removing downloaded file %s from %s" % (filename, path))
try:
os.remove(path)
except OSError, err:
self.log.error("Failed to remove downloaded file:" % err)
else:
self.log.info("Downloading file %s from url %s: done" % (filename, url))
downloaded = True
return path
attempt_cnt += 1
self.log.warning("Downloading failed at attempt %s, retrying..." % attempt_cnt)
# failed to download after multiple attempts
return None
# should we download or just try and find it?
if filename.startswith("http://") or filename.startswith("ftp://"):
# URL detected, so let's try and download it
url = filename
filename = url.split('/')[-1]
# figure out where to download the file to
for srcpath in srcpaths:
filepath = os.path.join(srcpath, self.name()[0].lower(), self.name())
if pkg:
filepath = os.path.join(filepath, "packages")
if os.path.isdir(filepath):
self.log.info("Going to try and download file to %s" % filepath)
break
# if no path was found, let's just create it in the last source path
if not os.path.isdir(filepath):
try:
self.log.info("No path found to download file to, so creating it: %s" % filepath)
os.makedirs(filepath)
except OSError, err:
self.log.error("Failed to create %s: %s" % (filepath, err))
try:
fullpath = os.path.join(filepath, filename)
if download(filename, url, fullpath):
return fullpath
except IOError, err:
self.log.exception("Downloading file %s from url %s to %s failed: %s" % (filename, url, fullpath, err))
else:
# try and find file in various locations
foundfile = None
failedpaths = []
for srcpath in srcpaths:
# create list of candidate filepaths
namepath = os.path.join(srcpath, self.name())
fst_letter_path_low = os.path.join(srcpath, self.name().lower()[0])
# most likely paths
candidate_filepaths = [os.path.join(fst_letter_path_low, self.name()), # easyblocks-style subdir
namepath, # subdir with software package name
srcpath, # directly in sources directory
]
# also consider easyconfigs path for patch files
if filename.endswith(".patch"):
for path in get_paths_for(self.log, "easyconfigs"):
candidate_filepaths.append(os.path.join(
path,
"easybuild",
"easyconfigs",
self.name().lower()[0],
self.name()
))
# see if file can be found at that location
for cfp in candidate_filepaths:
fullpath = os.path.join(cfp, filename)
# also check in packages subdir for packages
if pkg:
fullpaths = [os.path.join(cfp, "packages", filename), fullpath]
else:
fullpaths = [fullpath]
for fp in fullpaths:
if os.path.isfile(fp):
self.log.info("Found file %s at %s" % (filename, fp))
foundfile = fp
break # no need to try further
else:
failedpaths.append(fp)
if foundfile:
break # no need to try other source paths
if foundfile:
return foundfile
else:
# try and download source files from specified source URLs
sourceURLs = self.getcfg('sourceURLs')
targetdir = candidate_filepaths[0]
if not os.path.isdir(targetdir):
try:
os.makedirs(targetdir)
except OSError, err:
self.log.error("Failed to create directory %s to download source file %s into" % (targetdir, filename))
for url in sourceURLs:
if pkg:
targetpath = os.path.join(targetdir, "packages", filename)
else:
targetpath = os.path.join(targetdir, filename)
if type(url) == str:
fullurl = "%s/%s" % (url, filename)
elif type(url) == tuple:
## URLs that require a suffix, e.g., SourceForge download links
## e.g. http://sourceforge.net/projects/math-atlas/files/Stable/3.8.4/atlas3.8.4.tar.bz2/download
fullurl = "%s/%s/%s" % (url[0], filename, url[1])
else:
self.log.warning("Source URL %s is of unknown type, so ignoring it." % url)
continue
self.log.debug("Trying to download file %s from %s to %s ..." % (filename, fullurl, targetpath))
downloaded = False
try:
if download(filename, fullurl, targetpath):
downloaded = True
except IOError, err:
self.log.debug("Failed to download %s from %s: %s" % (filename, url, err))
failedpaths.append(fullurl)
continue
if downloaded:
# if fetching from source URL worked, we're done
self.log.info("Successfully downloaded source file %s from %s" % (filename, fullurl))
return targetpath
else:
failedpaths.append(fullurl)
self.log.error("Couldn't find file %s anywhere, and downloading it didn't work either...\nPaths attempted (in order): %s " % (filename, ', '.join(failedpaths)))
def apply_patch(self, beginpath=None):
"""
Apply the patches
"""
for tmp in self.patches:
self.log.info("Applying patch %s" % tmp['name'])
copy = False
## default: patch first source
srcind = 0
if 'source' in tmp:
srcind = tmp['source']
srcpathsuffix = ''
if 'sourcepaht' in tmp:
srcpathsuffix = tmp['sourcepath']
elif 'copy' in tmp:
srcpathsuffix = tmp['copy']
copy = True
if not beginpath:
beginpath = self.src[srcind]['finalpath']
src = os.path.abspath("%s/%s" % (beginpath, srcpathsuffix))
level = None
if 'level' in tmp:
level = tmp['level']
if not patch(tmp['path'], src, copy=copy, level=level):
self.log.error("Applying patch %s failed" % tmp['name'])
def unpack_src(self):
"""
Unpack the source files.
"""
for tmp in self.src:
self.log.info("Unpacking source %s" % tmp['name'])
srcdir = unpack(tmp['path'], self.builddir, extra_options=self.getcfg('unpackOptions'))
if srcdir:
self.src[self.src.index(tmp)]['finalpath'] = srcdir
else:
self.log.error("Unpacking source %s failed" % tmp['name'])
def build(self):
"""
Build software
- make builddir
- generate install location name
- unpack sources
- patch sources
- prepare dependencies
- prepare toolkit
- configure
- make (use parallelism?)
- test
- make install location
- install
"""
try:
print_msg("preparing...", self.log)
self.gen_installdir()
self.make_builddir()
## SOURCE
print_msg("unpacking...", self.log)
self.runstep('source', [self.unpack_src], skippable=True)
## PATCH
self.runstep('patch', [self.apply_patch], skippable=True)
self.tk.prepare(self.getcfg('onlytkmod'))
self.startfrom()
## CONFIGURE
print_msg("configuring...", self.log)
self.runstep('configure', [self.configure], skippable=True)
## MAKE
print_msg("building...", self.log)
self.runstep('make', [self.make], skippable=True)
## TEST
print_msg("testing...", self.log)
self.runstep('test', [self.test], skippable=True)
## INSTALL
print_msg("installing...", self.log)
self.runstep('install', [self.make_installdir, self.make_install], skippable=True)
## Packages
self.runstep('packages', [self.packages])
print_msg("finishing up...", self.log)
## POSTPROC
self.runstep('postproc', [self.postproc], skippable=True)
## CLEANUP
self.runstep('cleanup', [self.cleanup])
## SANITY CHECK
self.runstep('sanity check', [self.sanitycheck], skippable=False)
except StopException:
pass
def runstep(self, step, methods, skippable=False):
"""
Run step, returns false when execution should be stopped
"""
if skippable and self.skip:
self.log.info("Skipping %s" % step)
else:
for m in methods:
m()
if self.getcfg('stop') == step:
self.log.info("Stopping after %s step." % step)
raise StopException(step)
def postproc(self):
"""
Do some postprocessing
- set file permissions ....
Installing user must be member of the group that it is changed to
"""
if self.getcfg('group'):
gid = grp.getgrnam(self.getcfg('group'))[2]
chngsuccess = []
chngfailure = []
for root, _, files in os.walk(self.installdir):
try:
os.chown(root, -1, gid)
os.chmod(root, 0750)
chngsuccess.append(root)
except OSError, err:
self.log.error("Failed to change group for %s: %s" % (root, err))
chngfailure.append(root)
for f in files:
absfile = os.path.join(root, f)
try:
os.chown(absfile, -1, gid)
os.chmod(root, 0750)
chngsuccess.append(absfile)
except OSError, err:
self.log.debug("Failed to chown/chmod %s (but ignoring it): %s" % (absfile, err))
chngfailure.append(absfile)
if len(chngfailure) > 0:
self.log.error("Unable to change group permissions of file(s). Are you a member of this group?:\n --> %s" % "\n --> ".join(chngfailure))
else:
self.log.info("Successfully made software only available for group %s" % self.getcfg('group'))
def cleanup(self):
"""
Cleanup leftover mess: remove/clean build directory
except when we're building in the installation directory,
otherwise we remove the installation
"""
if not self.build_in_installdir:
try:
shutil.rmtree(self.builddir)
self.log.info("Cleaning up builddir %s" % (self.builddir))
except OSError, err:
self.log.exception("Cleaning up builddir %s failed: %s" % (self.builddir, err))
def sanitycheck(self):
"""
Do a sanity check on the installation
- if *any* of the files/subdirectories in the installation directory listed
in sanityCheckPaths are non-existent (or empty), the sanity check fails
"""
# prepare sanity check paths
self.sanityCheckPaths = self.getcfg('sanityCheckPaths')
if not self.sanityCheckPaths:
self.sanityCheckPaths = {'files':[],
'dirs':["bin", "lib"]
}
self.log.info("Using default sanity check paths: %s" % self.sanityCheckPaths)
else:
ks = self.sanityCheckPaths.keys()
ks.sort()
valnottypes = [type(x) != list for x in self.sanityCheckPaths.values()]
lenvals = [len(x) for x in self.sanityCheckPaths.values()]
if not ks == ["dirs", "files"] or sum(valnottypes) > 0 or sum(lenvals) == 0:
self.log.error("Incorrect format for sanityCheckPaths (should only have 'files' and 'dirs' keys, values should be lists (at least one non-empty)).")
self.log.info("Using customized sanity check paths: %s" % self.sanityCheckPaths)
self.sanityCheckOK = True
# check is files exist
for f in self.sanityCheckPaths['files']:
p = os.path.join(self.installdir, f)
if not os.path.exists(p):
self.log.debug("Sanity check: did not find file %s in %s" % (f, self.installdir))
self.sanityCheckOK = False
break
else:
self.log.debug("Sanity check: found file %s in %s" % (f, self.installdir))
if self.sanityCheckOK:
# check if directories exist, and whether they are non-empty
for d in self.sanityCheckPaths['dirs']:
p = os.path.join(self.installdir, d)
if not os.path.isdir(p) or not os.listdir(p):
self.log.debug("Sanity check: did not find non-empty directory %s in %s" % (d, self.installdir))
self.sanityCheckOK = False
break
else:
self.log.debug("Sanity check: found non-empty directory %s in %s" % (d, self.installdir))
# pass or fail
if not self.sanityCheckOK:
self.log.error("Sanity check failed!")
else:
self.log.debug("Sanity check passed!")
def startfrom(self):
"""
Return the directory where to start the whole configure/make/make install cycle from
- typically self.src[0]['finalpath']
- startfrom option
-- if abspath: use that
-- else, treat it as subdir for regular procedure
"""
tmpdir = ''
if self.getcfg('startfrom'):
tmpdir = self.getcfg('startfrom')
if not os.path.isabs(tmpdir):
if len(self.src) > 0 and not self.skip:
self.setcfg('startfrom', os.path.join(self.src[0]['finalpath'], tmpdir))
else:
self.setcfg('startfrom', os.path.join(self.builddir, tmpdir))
try:
os.chdir(self.getcfg('startfrom'))
self.log.debug("Changed to real build directory %s" % (self.getcfg('startfrom')))
except OSError, err:
self.log.exception("Can't change to real build directory %s: %s" % (self.getcfg('startfrom'), err))
def configure(self, cmd_prefix=''):
"""
Configure step
- typically ./configure --prefix=/install/path style
"""
cmd = "%s %s./configure --prefix=%s %s" % (self.getcfg('preconfigopts'), cmd_prefix,
self.installdir, self.getcfg('configopts'))
run_cmd(cmd, log_all=True, simple=True)
def make(self, verbose=False):
"""
Start the actual build
- typical: make -j X
"""
paracmd = ''
if self.getcfg('parallel'):
paracmd = "-j %s" % self.getcfg('parallel')
cmd = "%s make %s %s" % (self.getcfg('premakeopts'), paracmd, self.getcfg('makeopts'))
run_cmd(cmd, log_all=True, simple=True, log_output=verbose)
def test(self):
"""
Test the compilation
- default: None
"""
if self.getcfg('runtest'):
cmd = "make %s" % (self.getcfg('runtest'))
run_cmd(cmd, log_all=True, simple=True)
def make_install(self):
"""
Create the installation in correct location
- typical: make install
"""
cmd = "make install %s" % (self.getcfg('installopts'))
run_cmd(cmd, log_all=True, simple=True)