forked from easybuilders/easybuild-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheasyblock.py
More file actions
3586 lines (2962 loc) · 160 KB
/
easyblock.py
File metadata and controls
3586 lines (2962 loc) · 160 KB
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-2020 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# https://github.com/easybuilders/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/>.
# #
"""
Generic EasyBuild support for building and installing software.
The EasyBlock class should serve as a base class for all easyblocks.
:author: Stijn De Weirdt (Ghent University)
:author: Dries Verdegem (Ghent University)
:author: Kenneth Hoste (Ghent University)
:author: Pieter De Baets (Ghent University)
:author: Jens Timmerman (Ghent University)
:author: Toon Willems (Ghent University)
:author: Ward Poelmans (Ghent University)
:author: Fotis Georgatos (Uni.Lu, NTUA)
:author: Damian Alvarez (Forschungszentrum Juelich GmbH)
:author: Maxime Boissonneault (Compute Canada)
:author: Davide Vanzo (Vanderbilt University)
"""
import copy
import glob
import inspect
import os
import re
import stat
import tempfile
import time
import traceback
from datetime import datetime
from distutils.version import LooseVersion
import easybuild.tools.environment as env
from easybuild.base import fancylogger
from easybuild.framework.easyconfig import EASYCONFIGS_PKG_SUBDIR
from easybuild.framework.easyconfig.easyconfig import ITERATE_OPTIONS, EasyConfig, ActiveMNS, get_easyblock_class
from easybuild.framework.easyconfig.easyconfig import get_module_path, letter_dir_for, resolve_template
from easybuild.framework.easyconfig.format.format import SANITY_CHECK_PATHS_DIRS, SANITY_CHECK_PATHS_FILES
from easybuild.framework.easyconfig.parser import fetch_parameters_from_easyconfig
from easybuild.framework.easyconfig.style import MAX_LINE_LENGTH
from easybuild.framework.easyconfig.tools import get_paths_for
from easybuild.framework.easyconfig.templates import TEMPLATE_NAMES_EASYBLOCK_RUN_STEP, template_constant_dict
from easybuild.framework.extension import resolve_exts_filter_template
from easybuild.tools import config, run
from easybuild.tools.build_details import get_build_stats
from easybuild.tools.build_log import EasyBuildError, dry_run_msg, dry_run_warning, dry_run_set_dirs
from easybuild.tools.build_log import print_error, print_msg, print_warning
from easybuild.tools.config import FORCE_DOWNLOAD_ALL, FORCE_DOWNLOAD_PATCHES, FORCE_DOWNLOAD_SOURCES
from easybuild.tools.config import build_option, build_path, get_log_filename, get_repository, get_repositorypath
from easybuild.tools.config import install_path, log_path, package_path, source_paths
from easybuild.tools.environment import restore_env, sanitize_env
from easybuild.tools.filetools import CHECKSUM_TYPE_MD5, CHECKSUM_TYPE_SHA256
from easybuild.tools.filetools import adjust_permissions, apply_patch, back_up_file
from easybuild.tools.filetools import change_dir, convert_name, compute_checksum, copy_file, derive_alt_pypi_url
from easybuild.tools.filetools import diff_files, download_file, encode_class_name, extract_file
from easybuild.tools.filetools import find_backup_name_candidate, get_source_tarball_from_git, is_alt_pypi_url
from easybuild.tools.filetools import is_sha256_checksum, mkdir, move_file, move_logs, read_file, remove_dir
from easybuild.tools.filetools import remove_file, rmtree2, verify_checksum, weld_paths, write_file, dir_contains_files
from easybuild.tools.hooks import BUILD_STEP, CLEANUP_STEP, CONFIGURE_STEP, EXTENSIONS_STEP, FETCH_STEP, INSTALL_STEP
from easybuild.tools.hooks import MODULE_STEP, PACKAGE_STEP, PATCH_STEP, PERMISSIONS_STEP, POSTITER_STEP, POSTPROC_STEP
from easybuild.tools.hooks import PREPARE_STEP, READY_STEP, SANITYCHECK_STEP, SOURCE_STEP, TEST_STEP, TESTCASES_STEP
from easybuild.tools.hooks import load_hooks, run_hook
from easybuild.tools.run import run_cmd
from easybuild.tools.jenkins import write_to_xml
from easybuild.tools.module_generator import ModuleGeneratorLua, ModuleGeneratorTcl, module_generator, dependencies_for
from easybuild.tools.module_naming_scheme.utilities import det_full_ec_version
from easybuild.tools.modules import ROOT_ENV_VAR_NAME_PREFIX, VERSION_ENV_VAR_NAME_PREFIX, DEVEL_ENV_VAR_NAME_PREFIX
from easybuild.tools.modules import Lmod, curr_module_paths, invalidate_module_caches_for, get_software_root
from easybuild.tools.modules import get_software_root_env_var_name, get_software_version_env_var_name
from easybuild.tools.package.utilities import package
from easybuild.tools.py2vs3 import extract_method_name, string_type
from easybuild.tools.repository.repository import init_repository
from easybuild.tools.systemtools import det_parallelism, use_group
from easybuild.tools.utilities import INDENT_4SPACES, get_class_for, quote_str
from easybuild.tools.utilities import remove_unwanted_chars, time2str, trace_msg
from easybuild.tools.version import this_is_easybuild, VERBOSE_VERSION, VERSION
MODULE_ONLY_STEPS = [MODULE_STEP, PREPARE_STEP, READY_STEP, POSTITER_STEP, SANITYCHECK_STEP]
# string part of URL for Python packages on PyPI that indicates needs to be rewritten (see derive_alt_pypi_url)
PYPI_PKG_URL_PATTERN = 'pypi.python.org/packages/source/'
# Directory name in which to store reproducability files
REPROD = 'reprod'
_log = fancylogger.getLogger('easyblock')
class EasyBlock(object):
"""Generic support for building and installing software, base class for actual easyblocks."""
# static class method for extra easyconfig parameter definitions
# this makes it easy to access the information without needing an instance
# subclasses of EasyBlock should call this method with a dictionary
@staticmethod
def extra_options(extra=None):
"""
Extra options method which will be passed to the EasyConfig constructor.
"""
if extra is None:
extra = {}
if not isinstance(extra, dict):
_log.nosupport("Found 'extra' value of type '%s' in extra_options, should be 'dict'" % type(extra), '2.0')
return extra
#
# INIT
#
def __init__(self, ec):
"""
Initialize the EasyBlock instance.
:param ec: a parsed easyconfig file (EasyConfig instance)
"""
# keep track of original working directory, so we can go back there
self.orig_workdir = os.getcwd()
# list of pre- and post-step hooks
self.hooks = load_hooks(build_option('hooks'))
# list of patch/source files, along with checksums
self.patches = []
self.src = []
self.checksums = []
# build/install directories
self.builddir = None
self.installdir = None # software
self.installdir_mod = None # module file
# extensions
self.exts = []
self.exts_all = None
self.ext_instances = []
self.skip = None
self.module_extra_extensions = '' # extra stuff for module file required by extensions
# indicates whether or not this instance represents an extension or not;
# may be set to True by ExtensionEasyBlock
self.is_extension = False
# easyconfig for this application
if isinstance(ec, EasyConfig):
self.cfg = ec
else:
raise EasyBuildError("Value of incorrect type passed to EasyBlock constructor: %s ('%s')", type(ec), ec)
# modules interface with default MODULEPATH
self.modules_tool = self.cfg.modules_tool
# module generator
self.module_generator = module_generator(self, fake=True)
self.mod_filepath = self.module_generator.get_module_filepath()
self.mod_file_backup = None
self.set_default_module = self.cfg.set_default_module
# modules footer/header
self.modules_footer = None
modules_footer_path = build_option('modules_footer')
if modules_footer_path is not None:
self.modules_footer = read_file(modules_footer_path)
self.modules_header = None
modules_header_path = build_option('modules_header')
if modules_header_path is not None:
self.modules_header = read_file(modules_header_path)
# determine install subdirectory, based on module name
self.install_subdir = None
# indicates whether build should be performed in installation dir
self.build_in_installdir = self.cfg['buildininstalldir']
# list of locations to include in RPATH filter used by toolchain
self.rpath_filter_dirs = []
# list of locations to include in RPATH used by toolchain
self.rpath_include_dirs = []
# logging
self.log = None
self.logfile = None
self.logdebug = build_option('debug')
self.postmsg = '' # allow a post message to be set, which can be shown as last output
self.current_step = None
# list of loaded modules
self.loaded_modules = []
# iterate configure/build/options
self.iter_idx = 0
self.iter_opts = {}
# sanity check fail error messages to report (if any)
self.sanity_check_fail_msgs = []
# robot path
self.robot_path = build_option('robot_path')
# original module path
self.orig_modulepath = os.getenv('MODULEPATH')
# keep track of initial environment we start in, so we can restore it if needed
self.initial_environ = copy.deepcopy(os.environ)
self.reset_environ = None
self.tweaked_env_vars = {}
# should we keep quiet?
self.silent = build_option('silent')
# are we doing a dry run?
self.dry_run = build_option('extended_dry_run')
# initialize logger
self._init_log()
# try and use the specified group (if any)
group_name = build_option('group')
group_spec = self.cfg['group']
if group_spec is not None:
if isinstance(group_spec, tuple):
if len(group_spec) == 2:
group_spec = group_spec[0]
else:
raise EasyBuildError("Found group spec in tuple format that is not a 2-tuple: %s", str(group_spec))
self.log.warning("Group spec '%s' is overriding config group '%s'." % (group_spec, group_name))
group_name = group_spec
self.group = None
if group_name is not None:
self.group = use_group(group_name)
# generate build/install directories
self.gen_builddir()
self.gen_installdir()
self.ignored_errors = False
if self.dry_run:
self.init_dry_run()
self.log.info("Init completed for application name %s version %s" % (self.name, self.version))
# INIT/CLOSE LOG
def _init_log(self):
"""
Initialize the logger.
"""
if self.log is not None:
return
self.logfile = get_log_filename(self.name, self.version, add_salt=True)
fancylogger.logToFile(self.logfile, max_bytes=0)
self.log = fancylogger.getLogger(name=self.__class__.__name__, fname=False)
self.log.info(this_is_easybuild())
this_module = inspect.getmodule(self)
eb_class = self.__class__.__name__
eb_mod_name = this_module.__name__
eb_mod_loc = this_module.__file__
self.log.info("This is easyblock %s from module %s (%s)", eb_class, eb_mod_name, eb_mod_loc)
if self.dry_run:
self.dry_run_msg("*** DRY RUN using '%s' easyblock (%s @ %s) ***\n", eb_class, eb_mod_name, eb_mod_loc)
def close_log(self):
"""
Shutdown the logger.
"""
self.log.info("Closing log for application name %s version %s" % (self.name, self.version))
fancylogger.logToFile(self.logfile, enable=False)
#
# DRY RUN UTILITIES
#
def init_dry_run(self):
"""Initialise easyblock instance for performing a dry run."""
# replace build/install dirs with temporary directories in dry run mode
tmp_root_dir = os.path.realpath(os.path.join(tempfile.gettempdir(), '__ROOT__'))
self.builddir = os.path.join(tmp_root_dir, self.builddir.lstrip(os.path.sep))
self.installdir = os.path.join(tmp_root_dir, self.installdir.lstrip(os.path.sep))
self.installdir_mod = os.path.join(tmp_root_dir, self.installdir_mod.lstrip(os.path.sep))
# register fake build/install dirs so the original values can be printed during dry run
dry_run_set_dirs(tmp_root_dir, self.builddir, self.installdir, self.installdir_mod)
def dry_run_msg(self, msg, *args):
"""Print dry run message."""
if args:
msg = msg % args
dry_run_msg(msg, silent=self.silent)
#
# FETCH UTILITY FUNCTIONS
#
def get_checksum_for(self, checksums, filename=None, index=None):
"""
Obtain checksum for given filename.
:param checksums: a list or tuple of checksums (or None)
:param filename: name of the file to obtain checksum for
:param index: index of file in list
"""
# if checksums are provided as a dict, lookup by source filename as key
if isinstance(checksums, (list, tuple)):
if index is not None and index < len(checksums) and (index >= 0 or abs(index) <= len(checksums)):
return checksums[index]
else:
return None
elif checksums is None:
return None
else:
raise EasyBuildError("Invalid type for checksums (%s), should be list, tuple or None.", type(checksums))
def fetch_sources(self, sources=None, checksums=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)
:param sources: list of sources to fetch (if None, use 'sources' easyconfig parameter)
:param checksums: list of checksums for sources
"""
if sources is None:
sources = self.cfg['sources']
if checksums is None:
checksums = self.cfg['checksums']
for index, source in enumerate(sources):
extract_cmd, download_filename, source_urls, git_config = None, None, None, None
if isinstance(source, string_type):
filename = source
elif isinstance(source, dict):
# Making a copy to avoid modifying the object with pops
source = source.copy()
filename = source.pop('filename', None)
extract_cmd = source.pop('extract_cmd', None)
download_filename = source.pop('download_filename', None)
source_urls = source.pop('source_urls', None)
git_config = source.pop('git_config', None)
if source:
raise EasyBuildError("Found one or more unexpected keys in 'sources' specification: %s", source)
elif isinstance(source, (list, tuple)) and len(source) == 2:
self.log.deprecated("Using a 2-element list/tuple to specify sources is deprecated, "
"use a dictionary with 'filename', 'extract_cmd' keys instead", '4.0')
filename, extract_cmd = source
else:
raise EasyBuildError("Unexpected source spec, not a string or dict: %s", source)
# check if the sources can be located
force_download = build_option('force_download') in [FORCE_DOWNLOAD_ALL, FORCE_DOWNLOAD_SOURCES]
path = self.obtain_file(filename, download_filename=download_filename, force_download=force_download,
urls=source_urls, git_config=git_config)
if path:
self.log.debug('File %s found for source %s' % (path, filename))
self.src.append({
'name': filename,
'path': path,
'cmd': extract_cmd,
'checksum': self.get_checksum_for(checksums, filename=filename, index=index),
# always set a finalpath
'finalpath': self.builddir,
})
else:
raise EasyBuildError('No file found for source %s', filename)
self.log.info("Added sources: %s", self.src)
def fetch_patches(self, patch_specs=None, extension=False, checksums=None):
"""
Add a list of patches.
All patches will be checked if a file exists (or can be located)
"""
if patch_specs is None:
patch_specs = self.cfg['patches']
patches = []
for index, patch_spec in enumerate(patch_specs):
# check if the patches can be located
copy_file = False
suff = None
level = None
if isinstance(patch_spec, (list, tuple)):
if not len(patch_spec) == 2:
raise EasyBuildError("Unknown patch specification '%s', only 2-element lists/tuples are supported!",
str(patch_spec))
patch_file = patch_spec[0]
# this *must* be of typ int, nothing else
# no 'isinstance(..., int)', since that would make True/False also acceptable
if type(patch_spec[1]) == int:
level = patch_spec[1]
elif isinstance(patch_spec[1], string_type):
# non-patch files are assumed to be files to copy
if not patch_spec[0].endswith('.patch'):
copy_file = True
suff = patch_spec[1]
else:
raise EasyBuildError("Wrong patch spec '%s', only int/string are supported as 2nd element",
str(patch_spec))
else:
patch_file = patch_spec
force_download = build_option('force_download') in [FORCE_DOWNLOAD_ALL, FORCE_DOWNLOAD_PATCHES]
path = self.obtain_file(patch_file, extension=extension, force_download=force_download)
if path:
self.log.debug('File %s found for patch %s' % (path, patch_spec))
patchspec = {
'name': patch_file,
'path': path,
'checksum': self.get_checksum_for(checksums, filename=patch_file, index=index),
}
if suff:
if copy_file:
patchspec['copy'] = suff
else:
patchspec['sourcepath'] = suff
if level is not None:
patchspec['level'] = level
if extension:
patches.append(patchspec)
else:
self.patches.append(patchspec)
else:
raise EasyBuildError('No file found for patch %s', patch_spec)
if extension:
self.log.info("Fetched extension patches: %s", patches)
return patches
else:
self.log.info("Added patches: %s" % self.patches)
def fetch_extension_sources(self, skip_checksums=False):
"""
Find source file for extensions.
"""
exts_sources = []
exts_list = self.cfg.get_ref('exts_list')
if self.dry_run:
self.dry_run_msg("\nList of sources/patches for extensions:")
for ext in exts_list:
if (isinstance(ext, list) or isinstance(ext, tuple)) and ext:
# expected format: (name, version, options (dict))
ext_name = ext[0]
if len(ext) == 1:
exts_sources.append({'name': ext_name})
else:
ext_version = ext[1]
# make sure we grab *raw* dict of default options for extension,
# since it may use template values like %(name)s & %(version)s
ext_options = copy.deepcopy(self.cfg.get_ref('exts_default_options'))
if len(ext) == 3:
if isinstance(ext_options, dict):
ext_options.update(ext[2])
else:
raise EasyBuildError("Unexpected type (non-dict) for 3rd element of %s", ext)
elif len(ext) > 3:
raise EasyBuildError('Extension specified in unknown format (list/tuple too long)')
ext_src = {
'name': ext_name,
'version': ext_version,
'options': ext_options,
}
# construct dictionary with template values;
# inherited from parent, except for name/version templates which are specific to this extension
template_values = copy.deepcopy(self.cfg.template_values)
template_values.update(template_constant_dict(ext_src))
# resolve templates in extension options
ext_options = resolve_template(ext_options, template_values)
checksums = ext_options.get('checksums', [])
# use default template for name of source file if none is specified
default_source_tmpl = resolve_template('%(name)s-%(version)s.tar.gz', template_values)
fn = ext_options.get('source_tmpl', default_source_tmpl)
if ext_options.get('nosource', None):
exts_sources.append(ext_src)
else:
source_urls = ext_options.get('source_urls', [])
force_download = build_option('force_download') in [FORCE_DOWNLOAD_ALL, FORCE_DOWNLOAD_SOURCES]
src_fn = self.obtain_file(fn, extension=True, urls=source_urls, force_download=force_download)
if src_fn:
ext_src.update({'src': src_fn})
if not skip_checksums:
# report both MD5 and SHA256 checksums, since both are valid default checksum types
for checksum_type in (CHECKSUM_TYPE_MD5, CHECKSUM_TYPE_SHA256):
src_checksum = compute_checksum(src_fn, checksum_type=checksum_type)
self.log.info("%s checksum for %s: %s", checksum_type, src_fn, src_checksum)
# verify checksum (if provided)
self.log.debug('Verifying checksums for extension source...')
fn_checksum = self.get_checksum_for(checksums, filename=src_fn, index=0)
if verify_checksum(src_fn, fn_checksum):
self.log.info('Checksum for extension source %s verified', fn)
elif build_option('ignore_checksums'):
print_warning("Ignoring failing checksum verification for %s" % fn)
else:
raise EasyBuildError('Checksum verification for extension source %s failed', fn)
ext_patches = self.fetch_patches(patch_specs=ext_options.get('patches', []), extension=True)
if ext_patches:
self.log.debug('Found patches for extension %s: %s' % (ext_name, ext_patches))
ext_src.update({'patches': ext_patches})
if not skip_checksums:
for patch in ext_patches:
patch = patch['path']
# report both MD5 and SHA256 checksums,
# since both are valid default checksum types
for checksum_type in (CHECKSUM_TYPE_MD5, CHECKSUM_TYPE_SHA256):
checksum = compute_checksum(patch, checksum_type=checksum_type)
self.log.info("%s checksum for %s: %s", checksum_type, patch, checksum)
# verify checksum (if provided)
self.log.debug('Verifying checksums for extension patches...')
for idx, patch in enumerate(ext_patches):
patch = patch['path']
checksum = self.get_checksum_for(checksums[1:], filename=patch, index=idx)
if verify_checksum(patch, checksum):
self.log.info('Checksum for extension patch %s verified', patch)
elif build_option('ignore_checksums'):
print_warning("Ignoring failing checksum verification for %s" % patch)
else:
raise EasyBuildError('Checksum for extension patch %s failed', patch)
else:
self.log.debug('No patches found for extension %s.' % ext_name)
exts_sources.append(ext_src)
else:
raise EasyBuildError("Source for extension %s not found.", ext)
elif isinstance(ext, string_type):
exts_sources.append({'name': ext})
else:
raise EasyBuildError("Extension specified in unknown format (not a string/list/tuple)")
return exts_sources
def obtain_file(self, filename, extension=False, urls=None, download_filename=None, force_download=False,
git_config=None):
"""
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://:")
:param filename: filename of source
:param extension: indicates whether locations for extension sources should also be considered
:param urls: list of source URLs where this file may be available
:param download_filename: filename with which the file should be downloaded, and then renamed to <filename>
:param force_download: always try to download file, even if it's already available in source path
:param git_config: dictionary to define how to download a git repository
"""
srcpaths = source_paths()
# should we download or just try and find it?
if re.match(r"^(https?|ftp)://", filename):
# URL detected, so let's try and download it
url = filename
filename = url.split('/')[-1]
# figure out where to download the file to
filepath = os.path.join(srcpaths[0], letter_dir_for(self.name), self.name)
if extension:
filepath = os.path.join(filepath, "extensions")
self.log.info("Creating path %s to download file to" % filepath)
mkdir(filepath, parents=True)
try:
fullpath = os.path.join(filepath, filename)
# only download when it's not there yet
if os.path.exists(fullpath):
if force_download:
print_warning("Found file %s at %s, but re-downloading it anyway..." % (filename, filepath))
else:
self.log.info("Found file %s at %s, no need to download it", filename, filepath)
return fullpath
if download_file(filename, url, fullpath):
return fullpath
except IOError as err:
raise EasyBuildError("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 = []
# always look first in the dir of the current eb file
ebpath = [os.path.dirname(self.cfg.path)]
# always consider robot + easyconfigs install paths as a fall back (e.g. for patch files, test cases, ...)
common_filepaths = []
if self.robot_path:
common_filepaths.extend(self.robot_path)
common_filepaths.extend(get_paths_for(subdir=EASYCONFIGS_PKG_SUBDIR, robot_path=self.robot_path))
for path in ebpath + common_filepaths + srcpaths:
# create list of candidate filepaths
namepath = os.path.join(path, self.name)
letterpath = os.path.join(path, letter_dir_for(self.name), self.name)
# most likely paths
candidate_filepaths = [
letterpath, # easyblocks-style subdir
namepath, # subdir with software name
path, # directly in directory
]
# see if file can be found at that location
for cfp in candidate_filepaths:
fullpath = os.path.join(cfp, filename)
# also check in 'extensions' subdir for extensions
if extension:
fullpaths = [
os.path.join(cfp, "extensions", filename),
os.path.join(cfp, "packages", filename), # legacy
fullpath
]
else:
fullpaths = [fullpath]
for fp in fullpaths:
if os.path.isfile(fp):
self.log.info("Found file %s at %s", filename, fp)
foundfile = os.path.abspath(fp)
break # no need to try further
else:
failedpaths.append(fp)
if foundfile:
if force_download:
print_warning("Found file %s at %s, but re-downloading it anyway..." % (filename, foundfile))
foundfile = None
break # no need to try other source paths
targetdir = os.path.join(srcpaths[0], self.name.lower()[0], self.name)
if foundfile:
if self.dry_run:
self.dry_run_msg(" * %s found at %s", filename, foundfile)
return foundfile
elif git_config:
return get_source_tarball_from_git(filename, targetdir, git_config)
else:
# try and download source files from specified source URLs
if urls:
source_urls = urls[:]
else:
source_urls = []
source_urls.extend(self.cfg['source_urls'])
mkdir(targetdir, parents=True)
for url in source_urls:
if extension:
targetpath = os.path.join(targetdir, "extensions", filename)
else:
targetpath = os.path.join(targetdir, filename)
url_filename = download_filename or filename
if isinstance(url, string_type):
if url[-1] in ['=', '/']:
fullurl = "%s%s" % (url, url_filename)
else:
fullurl = "%s/%s" % (url, url_filename)
elif isinstance(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], url_filename, url[1])
else:
self.log.warning("Source URL %s is of unknown type, so ignoring it." % url)
continue
# PyPI URLs may need to be converted due to change in format of these URLs,
# cfr. https://bitbucket.org/pypa/pypi/issues/438
if PYPI_PKG_URL_PATTERN in fullurl and not is_alt_pypi_url(fullurl):
alt_url = derive_alt_pypi_url(fullurl)
if alt_url:
_log.debug("Using alternate PyPI URL for %s: %s", fullurl, alt_url)
fullurl = alt_url
else:
_log.debug("Failed to derive alternate PyPI URL for %s, so retaining the original", fullurl)
if self.dry_run:
self.dry_run_msg(" * %s will be downloaded to %s", filename, targetpath)
if extension and urls:
# extensions typically have custom source URLs specified, only mention first
self.dry_run_msg(" (from %s, ...)", fullurl)
downloaded = True
else:
self.log.debug("Trying to download file %s from %s to %s ..." % (filename, fullurl, targetpath))
downloaded = False
try:
if download_file(filename, fullurl, targetpath):
downloaded = True
except IOError as 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)
if self.dry_run:
self.dry_run_msg(" * %s (MISSING)", filename)
return filename
else:
raise EasyBuildError("Couldn't find file %s anywhere, and downloading it didn't work either... "
"Paths attempted (in order): %s ", filename, ', '.join(failedpaths))
#
# GETTER/SETTER UTILITY FUNCTIONS
#
@property
def name(self):
"""
Shortcut the get the module name.
"""
return self.cfg['name']
@property
def version(self):
"""
Shortcut the get the module version.
"""
return self.cfg['version']
@property
def toolchain(self):
"""
Toolchain used to build this easyblock
"""
return self.cfg.toolchain
@property
def full_mod_name(self):
"""
Full module name (including subdirectory in module install path)
"""
return self.cfg.full_mod_name
@property
def short_mod_name(self):
"""
Short module name (not including subdirectory in module install path)
"""
return self.cfg.short_mod_name
@property
def mod_subdir(self):
"""
Subdirectory in module install path
"""
return self.cfg.mod_subdir
@property
def moduleGenerator(self):
"""
Module generator (DEPRECATED, use self.module_generator instead).
"""
self.log.nosupport("self.moduleGenerator is replaced by self.module_generator", '2.0')
#
# DIRECTORY UTILITY FUNCTIONS
#
def gen_builddir(self):
"""Generate the (unique) name for the builddir"""
clean_name = remove_unwanted_chars(self.name)
# if a toolchain version starts with a -, remove the - so prevent a -- in the path name
tc = self.cfg['toolchain']
tcversion = tc['version'].lstrip('-')
lastdir = "%s%s-%s%s" % (self.cfg['versionprefix'], tc['name'], tcversion, self.cfg['versionsuffix'])
builddir = os.path.join(os.path.abspath(build_path()), clean_name, self.version, lastdir)
# make sure build dir is unique if cleanupoldbuild is False or not set
if not self.cfg.get('cleanupoldbuild', False):
uniq_builddir = builddir
suff = 0
while(os.path.isdir(uniq_builddir)):
uniq_builddir = "%s.%d" % (builddir, suff)
suff += 1
builddir = uniq_builddir
self.builddir = builddir
self.log.info("Build dir set to %s" % self.builddir)
def make_builddir(self):
"""
Create the build directory.
"""
if not self.build_in_installdir:
# self.builddir should be already set by gen_builddir()
if not self.builddir:
raise EasyBuildError("self.builddir not set, make sure gen_builddir() is called first!")
self.log.debug("Creating the build directory %s (cleanup: %s)", self.builddir, self.cfg['cleanupoldbuild'])
else:
self.log.info("Changing build dir to %s" % self.installdir)
self.builddir = self.installdir
self.log.info("Overriding 'cleanupoldinstall' (to False), 'cleanupoldbuild' (to True) "
"and 'keeppreviousinstall' because we're building in the installation directory.")
# force cleanup before installation
if build_option('module_only'):
self.log.debug("Disabling cleanupoldbuild because we run as module-only")
self.cfg['cleanupoldbuild'] = False
else:
self.cfg['cleanupoldbuild'] = True
self.cfg['keeppreviousinstall'] = False
# avoid cleanup after installation
self.cfg['cleanupoldinstall'] = False
# always make build dir,
# unless we're building in installation directory and we iterating over a list of (pre)config/build/installopts,
# otherwise we wipe the already partially populated installation directory,
# see https://github.com/easybuilders/easybuild-framework/issues/2556
if not (self.build_in_installdir and self.iter_idx > 0):
# make sure we no longer sit in the build directory before cleaning it.
change_dir(self.orig_workdir)
self.make_dir(self.builddir, self.cfg['cleanupoldbuild'])
trace_msg("build dir: %s" % self.builddir)
def reset_env(self):
"""
Reset environment.
When iterating over builddependencies, every time we start a new iteration
we need to restore the environment to where it was before the relevant modules
were loaded.
"""
env.reset_changes()
if self.reset_environ is None:
self.reset_environ = copy.deepcopy(os.environ)
else:
restore_env(self.reset_environ)
def gen_installdir(self):
"""
Generate the name of the installation directory.
"""
basepath = install_path()
if basepath:
self.install_subdir = ActiveMNS().det_install_subdir(self.cfg)
self.installdir = os.path.join(os.path.abspath(basepath), self.install_subdir)
self.log.info("Software install dir set to %s" % self.installdir)
mod_basepath = install_path('mod')
mod_path_suffix = build_option('suffix_modules_path')
self.installdir_mod = os.path.join(os.path.abspath(mod_basepath), mod_path_suffix)
self.log.info("Module install dir set to %s" % self.installdir_mod)
else:
raise EasyBuildError("Can't set installation directory")
def make_installdir(self, dontcreate=None):
"""
Create the installation directory.
"""
self.log.debug("Creating the installation directory %s (cleanup: %s)" % (self.installdir,
self.cfg['cleanupoldinstall']))
if self.build_in_installdir:
self.cfg['keeppreviousinstall'] = True
dontcreate = (dontcreate is None and self.cfg['dontcreateinstalldir']) or dontcreate
self.make_dir(self.installdir, self.cfg['cleanupoldinstall'], dontcreateinstalldir=dontcreate)
def make_dir(self, dir_name, clean, dontcreateinstalldir=False):
"""
Create the directory.
"""
if os.path.exists(dir_name):
self.log.info("Found old directory %s" % dir_name)
if self.cfg['keeppreviousinstall']:
self.log.info("Keeping old directory %s (hopefully you know what you are doing)", dir_name)
return
elif build_option('module_only'):
self.log.info("Not touching existing directory %s in module-only mode...", dir_name)
elif clean:
remove_dir(dir_name)
self.log.info("Removed old directory %s", dir_name)
else:
self.log.info("Moving existing directory %s out of the way...", dir_name)
timestamp = time.strftime("%Y%m%d-%H%M%S")
backupdir = "%s.%s" % (dir_name, timestamp)
move_file(dir_name, backupdir)
self.log.info("Moved old directory %s to %s", dir_name, backupdir)
if dontcreateinstalldir:
olddir = dir_name
dir_name = os.path.dirname(dir_name)
self.log.info("Cleaning only, no actual creation of %s, only verification/defining of dirname %s",
olddir, dir_name)
if os.path.exists(dir_name):
return
# if not, create dir as usual
mkdir(dir_name, parents=True)
#
# MODULE UTILITY FUNCTIONS
#
def make_devel_module(self, create_in_builddir=False):
"""
Create a develop module file which sets environment based on the build
Usage: module load name, which loads the module you want to use. $EBDEVELNAME should then be the full path
to the devel module file. So now you can module load $EBDEVELNAME.
WARNING: you cannot unload using $EBDEVELNAME (for now: use module unload `basename $EBDEVELNAME`)
"""
self.log.info("Making devel module...")
# load fake module
fake_mod_data = self.load_fake_module(purge=True)
header = self.module_generator.MODULE_SHEBANG
if header:
header += '\n'
load_lines = []
# capture all the EBDEVEL vars
# these should be all the dependencies and we should load them
recursive_unload = self.cfg['recursive_module_unload']
depends_on = self.cfg['module_depends_on']
for key in os.environ:
# legacy support
if key.startswith(DEVEL_ENV_VAR_NAME_PREFIX):
if not key.endswith(convert_name(self.name, upper=True)):
path = os.environ[key]
if os.path.isfile(path):
mod_name = path.rsplit(os.path.sep, 1)[-1]
load_statement = self.module_generator.load_module(mod_name, recursive_unload=recursive_unload,
depends_on=depends_on)
load_lines.append(load_statement)
elif key.startswith('SOFTDEVEL'):
self.log.nosupport("Environment variable SOFTDEVEL* being relied on", '2.0')
env_lines = []
for (key, val) in env.get_changes().items():
# check if non-empty string
# TODO: add unset for empty vars?
if val.strip():
env_lines.append(self.module_generator.set_environment(key, val))