-
Notifications
You must be signed in to change notification settings - Fork 203
/
easyblock.py
4851 lines (4011 loc) · 223 KB
/
easyblock.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-2024 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.
Authors:
* Stijn De Weirdt (Ghent University)
* Dries Verdegem (Ghent University)
* Kenneth Hoste (Ghent University)
* Pieter De Baets (Ghent University)
* Jens Timmerman (Ghent University)
* Toon Willems (Ghent University)
* Ward Poelmans (Ghent University)
* Fotis Georgatos (Uni.Lu, NTUA)
* Damian Alvarez (Forschungszentrum Juelich GmbH)
* Maxime Boissonneault (Compute Canada)
* Davide Vanzo (Vanderbilt University)
* Caspar van Leeuwen (SURF)
"""
import copy
import glob
import inspect
import json
import os
import re
import stat
import tempfile
import time
import traceback
from datetime import datetime
import easybuild.tools.environment as env
import easybuild.tools.toolchain as toolchain
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 dump_env_easyblock, get_paths_for
from easybuild.framework.easyconfig.templates import TEMPLATE_NAMES_EASYBLOCK_RUN_STEP, template_constant_dict
from easybuild.framework.extension import Extension, resolve_exts_filter_template
from easybuild.tools import LooseVersion, 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 CHECKSUM_PRIORITY_JSON, DEFAULT_ENVVAR_USERS_MODULES
from easybuild.tools.config import FORCE_DOWNLOAD_ALL, FORCE_DOWNLOAD_PATCHES, FORCE_DOWNLOAD_SOURCES
from easybuild.tools.config import EASYBUILD_SOURCES_URL # noqa
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, change_dir, check_lock
from easybuild.tools.filetools import compute_checksum, convert_name, copy_file, create_lock, create_patch_info
from easybuild.tools.filetools import derive_alt_pypi_url, diff_files, dir_contains_files, download_file
from easybuild.tools.filetools import 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_binary, is_sha256_checksum, mkdir, move_file, move_logs, read_file, remove_dir
from easybuild.tools.filetools import remove_file, remove_lock, verify_checksum, weld_paths, write_file, symlink
from easybuild.tools.hooks import BUILD_STEP, CLEANUP_STEP, CONFIGURE_STEP, EXTENSIONS_STEP, FETCH_STEP, INSTALL_STEP
from easybuild.tools.hooks import MODULE_STEP, MODULE_WRITE, PACKAGE_STEP, PATCH_STEP, PERMISSIONS_STEP, POSTITER_STEP
from easybuild.tools.hooks import POSTPROC_STEP, PREPARE_STEP, READY_STEP, SANITYCHECK_STEP, SOURCE_STEP
from easybuild.tools.hooks import SINGLE_EXTENSION, TEST_STEP, TESTCASES_STEP, load_hooks, run_hook
from easybuild.tools.run import check_async_cmd, 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.output import PROGRESS_BAR_DOWNLOAD_ALL, PROGRESS_BAR_EASYCONFIG, PROGRESS_BAR_EXTENSIONS
from easybuild.tools.output import show_progress_bars, start_progress_bar, stop_progress_bar, update_progress_bar
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 check_linked_shared_libs, det_parallelism, get_linked_libs_raw
from easybuild.tools.systemtools import get_shared_lib_ext, pick_system_specific_value, use_group
from easybuild.tools.utilities import INDENT_4SPACES, get_class_for, nub, quote_str
from easybuild.tools.utilities import remove_unwanted_chars, time2str, trace_msg
from easybuild.tools.version import this_is_easybuild, VERBOSE_VERSION, VERSION
DEFAULT_BIN_LIB_SUBDIRS = ('bin', 'lib', 'lib64')
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 reproducibility 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()
# dict of all hooks (mapping of name to function)
self.hooks = load_hooks(build_option('hooks'))
# list of patch/source files, along with checksums
self.patches = []
self.src = []
self.checksums = []
self.json_checksums = None
# 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
# Create empty progress bar
self.progress_bar = None
self.pbar_task = 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 = []
# keep track of whether module is loaded during sanity check step (to avoid re-loading)
self.sanity_check_module_loaded = False
# info required to roll back loading of fake module during sanity check (see _sanity_check_step method)
self.fake_mod_data = None
# 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))
def post_init(self):
"""
Run post-initialization tasks.
"""
if self.build_in_installdir:
# self.builddir is set by self.gen_builddir(),
# but needs to be correct if the build is performed in the installation directory
self.log.info("Changing build dir to %s", self.installdir)
self.builddir = self.installdir
# 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
"""
checksum = None
# sometimes, filename are specified as a dict
if isinstance(filename, dict):
filename = filename['filename']
# if checksums are provided as a dict, lookup by source filename as key
if isinstance(checksums, dict):
if filename is not None and filename in checksums:
checksum = checksums[filename]
else:
checksum = None
elif isinstance(checksums, (list, tuple)):
if index is not None and index < len(checksums) and (index >= 0 or abs(index) <= len(checksums)):
checksum = checksums[index]
else:
checksum = None
elif checksums is None:
checksum = None
else:
raise EasyBuildError("Invalid type for checksums (%s), should be dict, list, tuple or None.",
type(checksums))
if checksum is None or build_option("checksum_priority") == CHECKSUM_PRIORITY_JSON:
json_checksums = self.get_checksums_from_json()
return json_checksums.get(filename, None)
else:
return checksum
def get_checksums_from_json(self, always_read=False):
"""
Get checksums for this software that are provided in a checksums.json file
:param always_read: always read the checksums.json file, even if it has been read before
"""
if always_read or self.json_checksums is None:
path = self.obtain_file("checksums.json", no_download=True, warning_only=True)
if path is not None:
self.log.info("Loading checksums from file %s", path)
json_txt = read_file(path)
self.json_checksums = json.loads(json_txt)
else:
# if the file can't be found, return an empty dict
self.json_checksums = {}
return self.json_checksums
def fetch_source(self, source, checksum=None, extension=False, download_instructions=None):
"""
Get a specific source (tarball, iso, url)
Will be tested for existence or can be located
:param source: source to be found (single dictionary in 'sources' list, or filename)
:param checksum: checksum corresponding to source
:param extension: flag if being called from collect_exts_file_info()
"""
filename, download_filename, extract_cmd = None, None, None
source_urls, git_config, alt_location = None, None, None
if source is None:
raise EasyBuildError("fetch_source called with empty 'source' argument")
elif 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)
alt_location = source.pop('alt_location', 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, extension=extension, download_filename=download_filename,
force_download=force_download, urls=source_urls, git_config=git_config,
download_instructions=download_instructions, alt_location=alt_location)
if path is None:
raise EasyBuildError('No file found for source %s', filename)
self.log.debug('File %s found for source %s' % (path, filename))
src = {
'name': filename,
'path': path,
'cmd': extract_cmd,
'checksum': checksum,
# always set a finalpath
'finalpath': self.builddir,
}
return src
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']
# Single source should be re-wrapped as a list, and checksums with it
if isinstance(sources, dict):
sources = [sources]
if isinstance(checksums, string_type):
checksums = [checksums]
# Loop over the list of sources; list of checksums must match >= in size
for index, source in enumerate(sources):
if source is None:
raise EasyBuildError("Empty source in sources list at index %d", index)
checksum = self.get_checksum_for(checksums=checksums, filename=source, index=index)
src_spec = self.fetch_source(source, checksum=checksum)
if src_spec:
self.src.append(src_spec)
else:
raise EasyBuildError("Unable to retrieve source %s", source)
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)
"""
post_install_patches = []
if patch_specs is None:
# if no patch_specs are specified, use all pre-install and post-install patches
post_install_patches = self.cfg['postinstallpatches']
patch_specs = self.cfg['patches'] + post_install_patches
patches = []
for index, patch_spec in enumerate(patch_specs):
patch_info = create_patch_info(patch_spec)
patch_info['postinstall'] = patch_spec in post_install_patches
force_download = build_option('force_download') in [FORCE_DOWNLOAD_ALL, FORCE_DOWNLOAD_PATCHES]
alt_location = patch_info.pop('alt_location', None)
path = self.obtain_file(patch_info['name'], extension=extension, force_download=force_download,
alt_location=alt_location)
if path:
self.log.debug('File %s found for patch %s', path, patch_spec)
patch_info['path'] = path
patch_info['checksum'] = self.get_checksum_for(checksums, filename=patch_info['name'], index=index)
if extension:
patches.append(patch_info)
else:
self.patches.append(patch_info)
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):
"""
Fetch source and patch files for extensions (DEPRECATED, use collect_exts_file_info instead).
"""
depr_msg = "EasyBlock.fetch_extension_sources is deprecated, use EasyBlock.collect_exts_file_info instead"
self.log.deprecated(depr_msg, '5.0')
return self.collect_exts_file_info(fetch_files=True, verify_checksums=not skip_checksums)
def collect_exts_file_info(self, fetch_files=True, verify_checksums=True):
"""
Collect information on source and patch files for extensions.
:param fetch_files: whether or not to fetch files (if False, path to files will be missing from info)
:param verify_checksums: whether or not to verify checksums
:return: list of dict values, one per extension, with information on source/patch files.
"""
exts_sources = []
exts_list = self.cfg.get_ref('exts_list')
if verify_checksums and not fetch_files:
raise EasyBuildError("Can't verify checksums for extension files if they are not being fetched")
if self.dry_run:
self.dry_run_msg("\nList of sources/patches for extensions:")
force_download = build_option('force_download') in [FORCE_DOWNLOAD_ALL, FORCE_DOWNLOAD_SOURCES]
for ext in exts_list:
if isinstance(ext, (list, tuple)) and ext:
# expected format: (name, version, options (dict))
# name and version can use templates, resolved via parent EC
ext_name = resolve_template(ext[0], self.cfg.template_values)
if len(ext) == 1:
exts_sources.append({'name': ext_name})
else:
ext_version = resolve_template(ext[1], self.cfg.template_values)
# 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,
}
# if a particular easyblock is specified, make sure it's used
# (this is picked up by init_ext_instances)
ext_src['easyblock'] = ext_options.get('easyblock', None)
# 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)
source_urls = ext_options.get('source_urls', [])
checksums = ext_options.get('checksums', [])
download_instructions = ext_options.get('download_instructions')
if ext_options.get('nosource', None):
self.log.debug("No sources for extension %s, as indicated by 'nosource'", ext_name)
elif ext_options.get('sources', None):
sources = ext_options['sources']
# only a single source file is supported for extensions currently,
# see https://github.com/easybuilders/easybuild-framework/issues/3463
if isinstance(sources, list):
if len(sources) == 1:
source = sources[0]
else:
error_msg = "'sources' spec for %s in exts_list must be single element list. Is: %s"
raise EasyBuildError(error_msg, ext_name, sources)
else:
source = sources
# always pass source spec as dict value to fetch_source method,
# mostly so we can inject stuff like source URLs
if isinstance(source, string_type):
source = {'filename': source}
elif not isinstance(source, dict):
raise EasyBuildError("Incorrect value type for source of extension %s: %s",
ext_name, source)
# if no custom source URLs are specified in sources spec,
# inject the ones specified for this extension
if 'source_urls' not in source:
source['source_urls'] = source_urls
if fetch_files:
src = self.fetch_source(source, checksums, extension=True,
download_instructions=download_instructions)
ext_src.update({
# keep track of custom extract command (if any)
'extract_cmd': src['cmd'],
# copy 'path' entry to 'src' for use with extensions
'src': src['path'],
})
else:
# 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)
# if no sources are specified via 'sources', fall back to 'source_tmpl'
src_fn = ext_options.get('source_tmpl')
if src_fn is None:
src_fn = default_source_tmpl
elif not isinstance(src_fn, string_type):
error_msg = "source_tmpl value must be a string! (found value of type '%s'): %s"
raise EasyBuildError(error_msg, type(src_fn).__name__, src_fn)
if fetch_files:
src_path = self.obtain_file(src_fn, extension=True, urls=source_urls,
force_download=force_download,
download_instructions=download_instructions)
if src_path:
ext_src.update({'src': src_path})
else:
raise EasyBuildError("Source for extension %s not found.", ext)
# verify checksum for extension sources
if verify_checksums and 'src' in ext_src:
src_path = ext_src['src']
src_fn = os.path.basename(src_path)
# report both MD5 and SHA256 checksums, since both are valid default checksum types
src_checksums = {}
for checksum_type in (CHECKSUM_TYPE_MD5, CHECKSUM_TYPE_SHA256):
src_checksum = compute_checksum(src_path, checksum_type=checksum_type)
src_checksums[checksum_type] = src_checksum
self.log.info("%s checksum for %s: %s", checksum_type, src_path, 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_path, fn_checksum, src_checksums):
self.log.info('Checksum for extension source %s verified', src_fn)
elif build_option('ignore_checksums'):
print_warning("Ignoring failing checksum verification for %s" % src_fn)
else:
raise EasyBuildError('Checksum verification for extension source %s failed', src_fn)
# locate extension patches (if any), and verify checksums
ext_patches = ext_options.get('patches', [])
if fetch_files:
ext_patches = self.fetch_patches(patch_specs=ext_patches, extension=True)
else:
ext_patches = [create_patch_info(p) for p in ext_patches]
if ext_patches:
self.log.debug('Found patches for extension %s: %s', ext_name, ext_patches)
ext_src.update({'patches': ext_patches})
if verify_checksums:
computed_checksums = {}
for patch in ext_patches:
patch = patch['path']
computed_checksums[patch] = {}
# 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)
computed_checksums[patch][checksum_type] = checksum
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']
patch_fn = os.path.basename(patch)
checksum = self.get_checksum_for(checksums, filename=patch_fn, index=idx+1)
if verify_checksum(patch, checksum, computed_checksums[patch]):
self.log.info('Checksum for extension patch %s verified', patch_fn)
elif build_option('ignore_checksums'):
print_warning("Ignoring failing checksum verification for %s" % patch_fn)
else:
raise EasyBuildError("Checksum verification for extension patch %s failed",
patch_fn)
else:
self.log.debug('No patches found for extension %s.' % ext_name)
exts_sources.append(ext_src)
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, no_download=False, download_instructions=None, alt_location=None,
warning_only=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://:")
: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
:param no_download: do not try to download the file
:param download_instructions: instructions to manually add source (used for complex cases)
:param alt_location: alternative location to use instead of self.name
"""
srcpaths = source_paths()
# We don't account for the checksums file in the progress bar
if filename != 'checksum.json':
update_progress_bar(PROGRESS_BAR_DOWNLOAD_ALL, label=filename)
if alt_location is None:
location = self.name
else:
location = alt_location
# 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(location), location)
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:
if not warning_only:
raise EasyBuildError("Downloading file %s "
"from url %s to %s failed: %s", filename, url, fullpath, err)
else:
self.log.warning("Downloading file %s "
"from url %s to %s failed: %s", filename, url, fullpath, err)
return None
else:
# try and find file in various locations
foundfile = None
failedpaths = []
# always look first in the dir of the current eb file unless alt_location is set
if alt_location is None:
ebpath = [os.path.dirname(self.cfg.path)]
self.log.info("Considering directory in which easyconfig file is located when searching for %s: %s",
filename, ebpath[0])
else:
ebpath = []
self.log.info("Not considering directory in which easyconfig file is located when searching for %s "
"because alt_location is set to %s", filename, alt_location)
# 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, location)
letterpath = os.path.join(path, letter_dir_for(location), location)
# 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
name_letter = location.lower()[0]
targetdir = os.path.join(srcpaths[0], name_letter, location)
if foundfile:
if self.dry_run:
self.dry_run_msg(" * %s found at %s", filename, foundfile)
return foundfile
elif no_download:
if self.dry_run:
self.dry_run_msg(" * %s (MISSING)", filename)
return filename
else:
if not warning_only:
raise EasyBuildError("Couldn't find file %s anywhere, and downloading it is disabled... "
"Paths attempted (in order): %s ", filename, ', '.join(failedpaths))
else:
self.log.warning("Couldn't find file %s anywhere, and downloading it is disabled... "
"Paths attempted (in order): %s ", filename, ', '.join(failedpaths))
return None
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'])
# Add additional URLs as configured.
for url in build_option("extra_source_urls"):
url += "/" + name_letter + "/" + location
source_urls.append(url)
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:
error_msg = "Couldn't find file %s anywhere, "
if download_instructions is None:
download_instructions = self.cfg['download_instructions']
if download_instructions is not None and download_instructions != "":
msg = "\nDownload instructions:\n\n" + download_instructions + '\n'
print_msg(msg, prefix=False, stderr=True)
error_msg += "please follow the download instructions above, and make the file available "
error_msg += "in the active source path (%s)" % ':'.join(source_paths())
else:
# flatten list to string with '%' characters escaped (literal '%' desired in 'sprintf')
failedpaths_msg = ', '.join(failedpaths).replace('%', '%%')
error_msg += "and downloading it didn't work either... "
error_msg += "Paths attempted (in order): %s " % failedpaths_msg
if not warning_only:
raise EasyBuildError(error_msg, filename)
else:
self.log.warning(error_msg, filename)
return None
#
# 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.