-
Notifications
You must be signed in to change notification settings - Fork 203
/
Copy patheasyconfig.py
2724 lines (2213 loc) · 123 KB
/
easyconfig.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/>.
# #
"""
Easyconfig module that contains the EasyConfig class.
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)
* Alan O'Cais (Juelich Supercomputing Centre)
* Bart Oldeman (McGill University, Calcul Quebec, Compute Canada)
* Maxime Boissonneault (Universite Laval, Calcul Quebec, Compute Canada)
* Victor Holanda (CSCS, ETH Zurich)
"""
import copy
import difflib
import functools
import os
import re
from contextlib import contextmanager
import easybuild.tools.filetools as filetools
from easybuild.base import fancylogger
from easybuild.framework.easyconfig import MANDATORY
from easybuild.framework.easyconfig.constants import EASYCONFIG_CONSTANTS, EXTERNAL_MODULE_MARKER
from easybuild.framework.easyconfig.default import DEFAULT_CONFIG
from easybuild.framework.easyconfig.format.convert import Dependency
from easybuild.framework.easyconfig.format.format import DEPENDENCY_PARAMETERS
from easybuild.framework.easyconfig.format.one import EB_FORMAT_EXTENSION, retrieve_blocks_in_spec
from easybuild.framework.easyconfig.format.yeb import YEB_FORMAT_EXTENSION, is_yeb_format
from easybuild.framework.easyconfig.licenses import EASYCONFIG_LICENSES_DICT
from easybuild.framework.easyconfig.parser import DEPRECATED_PARAMETERS, REPLACED_PARAMETERS
from easybuild.framework.easyconfig.parser import EasyConfigParser, fetch_parameters_from_easyconfig
from easybuild.framework.easyconfig.templates import TEMPLATE_CONSTANTS, TEMPLATE_NAMES_DYNAMIC, template_constant_dict
from easybuild.tools import LooseVersion
from easybuild.tools.build_log import EasyBuildError, print_warning, print_msg
from easybuild.tools.config import GENERIC_EASYBLOCK_PKG, LOCAL_VAR_NAMING_CHECK_ERROR, LOCAL_VAR_NAMING_CHECK_LOG
from easybuild.tools.config import LOCAL_VAR_NAMING_CHECK_WARN
from easybuild.tools.config import Singleton, build_option, get_module_naming_scheme
from easybuild.tools.filetools import convert_name, copy_file, create_index, decode_class_name, encode_class_name
from easybuild.tools.filetools import find_backup_name_candidate, find_easyconfigs, load_index
from easybuild.tools.filetools import read_file, write_file
from easybuild.tools.hooks import PARSE, load_hooks, run_hook
from easybuild.tools.module_naming_scheme.mns import DEVEL_MODULE_SUFFIX
from easybuild.tools.module_naming_scheme.utilities import avail_module_naming_schemes, det_full_ec_version
from easybuild.tools.module_naming_scheme.utilities import det_hidden_modname, is_valid_module_name
from easybuild.tools.modules import modules_tool, NoModulesTool
from easybuild.tools.py2vs3 import OrderedDict, create_base_metaclass, string_type
from easybuild.tools.systemtools import check_os_dependency, pick_dep_version
from easybuild.tools.toolchain.toolchain import SYSTEM_TOOLCHAIN_NAME, is_system_toolchain
from easybuild.tools.toolchain.toolchain import TOOLCHAIN_CAPABILITIES, TOOLCHAIN_CAPABILITY_CUDA
from easybuild.tools.toolchain.utilities import get_toolchain, search_toolchain
from easybuild.tools.utilities import flatten, get_class_for, nub, quote_py_str, remove_unwanted_chars
from easybuild.tools.version import VERSION
from easybuild.toolchains.compiler.cuda import Cuda
_log = fancylogger.getLogger('easyconfig.easyconfig', fname=False)
# add license here to make it really MANDATORY (remove comment in default)
MANDATORY_PARAMS = ['name', 'version', 'homepage', 'description', 'toolchain']
# set of configure/build/install options that can be provided as lists for an iterated build
ITERATE_OPTIONS = ['builddependencies',
'preconfigopts', 'configopts', 'prebuildopts', 'buildopts', 'preinstallopts', 'installopts']
# name of easyconfigs archive subdirectory
EASYCONFIGS_ARCHIVE_DIR = '__archive__'
# prefix for names of local variables in easyconfig files
LOCAL_VAR_PREFIX = 'local_'
try:
import autopep8
HAVE_AUTOPEP8 = True
except ImportError as err:
_log.warning("Failed to import autopep8, dumping easyconfigs with reformatting enabled will not work: %s", err)
HAVE_AUTOPEP8 = False
_easyconfig_files_cache = {}
_easyconfigs_cache = {}
_path_indexes = {}
def handle_deprecated_or_replaced_easyconfig_parameters(ec_method):
"""Decorator to handle deprecated/replaced easyconfig parameters."""
def new_ec_method(self, key, *args, **kwargs):
"""Check whether any replace easyconfig parameters are still used"""
# map deprecated parameters to their replacements, issue deprecation warning(/error)
if key in DEPRECATED_PARAMETERS:
depr_key = key
key, ver = DEPRECATED_PARAMETERS[depr_key]
_log.deprecated("Easyconfig parameter '%s' is deprecated, use '%s' instead." % (depr_key, key), ver)
if key in REPLACED_PARAMETERS:
_log.nosupport("Easyconfig parameter '%s' is replaced by '%s'" % (key, REPLACED_PARAMETERS[key]), '2.0')
return ec_method(self, key, *args, **kwargs)
return new_ec_method
def is_local_var_name(name):
"""
Determine whether provided variable name can be considered as the name of a local variable:
One of the following suffices to be considered a name of a local variable:
* name starts with 'local_' or '_'
* name consists of a single letter
* name is __builtins__ (which is always defined)
"""
res = False
if name.startswith(LOCAL_VAR_PREFIX) or name.startswith('_'):
res = True
# __builtins__ is always defined as a 'local' variables
# single-letter local variable names are allowed (mainly for use in list comprehensions)
# in Python 2, variables defined in list comprehensions leak to the outside (no longer the case in Python 3)
elif name in ['__builtins__']:
res = True
# single letters are acceptable names for local variables
elif re.match('^[a-zA-Z]$', name):
res = True
return res
def triage_easyconfig_params(variables, ec):
"""
Triage supplied variables into known easyconfig parameters and other variables.
Unknown easyconfig parameters that have a single-letter name, or of which the name starts with 'local_'
are considered to be local variables.
:param variables: dictionary with names/values of variables that should be triaged
:param ec: dictionary with set of known easyconfig parameters
:return: 2-tuple with dict of names/values for known easyconfig parameters + unknown (non-local) variables
"""
# first make sure that none of the known easyconfig parameters have a name that makes it look like a local variable
wrong_params = []
for key in ec:
if is_local_var_name(key):
wrong_params.append(key)
if wrong_params:
raise EasyBuildError("Found %d easyconfig parameters that are considered local variables: %s",
len(wrong_params), ', '.join(sorted(wrong_params)))
ec_params, unknown_keys = {}, []
for key in variables:
# validations are skipped, just set in the config
if key in ec:
ec_params[key] = variables[key]
_log.debug("setting config option %s: value %s (type: %s)", key, ec_params[key], type(ec_params[key]))
elif key in REPLACED_PARAMETERS:
_log.nosupport("Easyconfig parameter '%s' is replaced by '%s'" % (key, REPLACED_PARAMETERS[key]), '2.0')
# anything else is considered to be a local variable in the easyconfig file;
# to catch mistakes (using unknown easyconfig parameters),
# and to protect against using a local variable name that may later become a known easyconfig parameter,
# we require that non-single letter names of local variables start with 'local_'
elif is_local_var_name(key):
_log.debug("Ignoring local variable '%s' (value: %s)", key, variables[key])
else:
unknown_keys.append(key)
return ec_params, unknown_keys
def toolchain_hierarchy_cache(func):
"""Function decorator to cache (and retrieve cached) toolchain hierarchy queries."""
cache = {}
@functools.wraps(func)
def cache_aware_func(toolchain, incl_capabilities=False):
"""Look up toolchain hierarchy in cache first, determine and cache it if not available yet."""
cache_key = (toolchain['name'], toolchain['version'], incl_capabilities)
# fetch from cache if available, cache it if it's not
if cache_key in cache:
_log.debug("Using cache to return hierarchy for toolchain %s: %s", str(toolchain), cache[cache_key])
return cache[cache_key]
else:
toolchain_hierarchy = func(toolchain, incl_capabilities)
cache[cache_key] = toolchain_hierarchy
return cache[cache_key]
# Expose clear method of cache to wrapped function
cache_aware_func.clear = cache.clear
return cache_aware_func
def det_subtoolchain_version(current_tc, subtoolchain_names, optional_toolchains, cands, incl_capabilities=False):
"""
Returns unique version for subtoolchain, in tc dict.
If there is no unique version:
* use '' for system, if system is not skipped.
* return None for skipped subtoolchains, that is,
optional toolchains or system toolchain without add_system_to_minimal_toolchains.
* in all other cases, raises an exception.
"""
# init with "skipped"
subtoolchain_version = None
# ensure we always have a tuple of alternative subtoolchain names, which makes things easier below
if isinstance(subtoolchain_names, string_type):
subtoolchain_names = (subtoolchain_names,)
system_subtoolchain = False
for subtoolchain_name in subtoolchain_names:
uniq_subtc_versions = set([subtc['version'] for subtc in cands if subtc['name'] == subtoolchain_name])
# system toolchain: bottom of the hierarchy
if is_system_toolchain(subtoolchain_name):
add_system_to_minimal_toolchains = build_option('add_system_to_minimal_toolchains')
if not add_system_to_minimal_toolchains and build_option('add_dummy_to_minimal_toolchains'):
depr_msg = "Use --add-system-to-minimal-toolchains instead of --add-dummy-to-minimal-toolchains"
_log.deprecated(depr_msg, '5.0')
add_system_to_minimal_toolchains = True
system_subtoolchain = True
if add_system_to_minimal_toolchains and not incl_capabilities:
subtoolchain_version = ''
elif len(uniq_subtc_versions) == 1:
subtoolchain_version = list(uniq_subtc_versions)[0]
elif len(uniq_subtc_versions) > 1:
raise EasyBuildError("Multiple versions of %s found in dependencies of toolchain %s: %s",
subtoolchain_name, current_tc['name'], ', '.join(sorted(uniq_subtc_versions)))
if subtoolchain_version is not None:
break
if not system_subtoolchain and subtoolchain_version is None:
if not all(n in optional_toolchains for n in subtoolchain_names):
subtoolchain_names = ' or '.join(subtoolchain_names)
# raise error if the subtoolchain considered now is not optional
raise EasyBuildError("No version found for subtoolchain %s in dependencies of %s",
subtoolchain_names, current_tc['name'])
return subtoolchain_version
@toolchain_hierarchy_cache
def get_toolchain_hierarchy(parent_toolchain, incl_capabilities=False):
r"""
Determine list of subtoolchains for specified parent toolchain.
Result starts with the most minimal subtoolchains first, ends with specified toolchain.
The system toolchain is considered the most minimal subtoolchain only if the add_system_to_minimal_toolchains
build option is enabled.
The most complex hierarchy we have now is goolfc which works as follows:
goolfc
/ \
gompic golfc(*)
\ / \ (*) optional toolchains, not compulsory for backwards compatibility
gcccuda golf(*)
\ /
GCC
/ |
GCCcore(*) |
\ |
(system: only considered if --add-system-to-minimal-toolchains configuration option is enabled)
:param parent_toolchain: dictionary with name/version of parent toolchain
:param incl_capabilities: also register toolchain capabilities in result
"""
# obtain list of all possible subtoolchains
_, all_tc_classes = search_toolchain('')
subtoolchains = {tc_class.NAME: getattr(tc_class, 'SUBTOOLCHAIN', None) for tc_class in all_tc_classes}
optional_toolchains = set(tc_class.NAME for tc_class in all_tc_classes if getattr(tc_class, 'OPTIONAL', False))
composite_toolchains = set(tc_class.NAME for tc_class in all_tc_classes if len(tc_class.__bases__) > 1)
# the parent toolchain is at the top of the hierarchy,
# we need a copy so that adding capabilities (below) doesn't affect the original object
toolchain_hierarchy = [copy.copy(parent_toolchain)]
# use a queue to handle a breadth-first-search of the hierarchy,
# which is required to take into account the potential for multiple subtoolchains
bfs_queue = [parent_toolchain]
visited = set()
while bfs_queue:
current_tc = bfs_queue.pop()
current_tc_name, current_tc_version = current_tc['name'], current_tc['version']
subtoolchain_names = subtoolchains[current_tc_name]
# if current toolchain has no subtoolchains, consider next toolchain in queue
if subtoolchain_names is None:
continue
# make sure we always have a list of subtoolchains, even if there's only one
if not isinstance(subtoolchain_names, list):
subtoolchain_names = [subtoolchain_names]
# grab the easyconfig of the current toolchain and search the dependencies for a version of the subtoolchain
path = robot_find_easyconfig(current_tc_name, current_tc_version)
if path is None:
raise EasyBuildError("Could not find easyconfig for %s toolchain version %s",
current_tc_name, current_tc_version)
# parse the easyconfig
parsed_ec = process_easyconfig(path, validate=False)[0]
# search for version of the subtoolchain in dependencies
# considers deps + toolchains of deps + deps of deps + toolchains of deps of deps
# consider both version and versionsuffix for dependencies
cands = []
for dep in parsed_ec['ec'].dependencies():
# skip dependencies that are marked as external modules
if dep['external_module']:
continue
# include dep and toolchain of dep as candidates
cands.extend([
{'name': dep['name'], 'version': dep['version'] + dep['versionsuffix']},
dep['toolchain'],
])
# find easyconfig file for this dep and parse it
ecfile = robot_find_easyconfig(dep['name'], det_full_ec_version(dep))
if ecfile is None:
raise EasyBuildError("Could not find easyconfig for dependency %s with version %s",
dep['name'], det_full_ec_version(dep))
easyconfig = process_easyconfig(ecfile, validate=False)[0]['ec']
# include deps and toolchains of deps of this dep, but skip dependencies marked as external modules
for depdep in easyconfig.dependencies():
if depdep['external_module']:
continue
cands.append({'name': depdep['name'], 'version': depdep['version'] + depdep['versionsuffix']})
cands.append(depdep['toolchain'])
for dep in subtoolchain_names:
# try to find subtoolchains with the same version as the parent
# only do this for composite toolchains, not single-compiler toolchains, whose
# versions match those of the component instead of being e.g. "2018a".
if dep in composite_toolchains:
ecfile = robot_find_easyconfig(dep, current_tc_version)
if ecfile is not None:
cands.append({'name': dep, 'version': current_tc_version})
# only retain candidates that match subtoolchain names
cands = [c for c in cands if any(c['name'] == x or c['name'] in x for x in subtoolchain_names)]
for subtoolchain_name in subtoolchain_names:
subtoolchain_version = det_subtoolchain_version(current_tc, subtoolchain_name, optional_toolchains, cands,
incl_capabilities=incl_capabilities)
# narrow down alternative subtoolchain names to a single one, based on the selected version
if isinstance(subtoolchain_name, tuple):
subtoolchain_name = [cand['name'] for cand in cands if cand['version'] == subtoolchain_version][0]
# add to hierarchy and move to next
if subtoolchain_version is not None and subtoolchain_name not in visited:
tc = {'name': subtoolchain_name, 'version': subtoolchain_version}
toolchain_hierarchy.insert(0, tc)
bfs_queue.insert(0, tc)
visited.add(subtoolchain_name)
# also add toolchain capabilities
if incl_capabilities:
for toolchain in toolchain_hierarchy:
toolchain_class, _ = search_toolchain(toolchain['name'])
tc = toolchain_class(version=toolchain['version'])
for capability in TOOLCHAIN_CAPABILITIES:
# cuda is the special case which doesn't have a family attribute
if capability == TOOLCHAIN_CAPABILITY_CUDA:
# use None rather than False, useful to have it consistent with the rest
toolchain[capability] = isinstance(tc, Cuda) or None
elif hasattr(tc, capability):
toolchain[capability] = getattr(tc, capability)()
_log.info("Found toolchain hierarchy for toolchain %s: %s", parent_toolchain, toolchain_hierarchy)
return toolchain_hierarchy
@contextmanager
def disable_templating(ec):
"""Temporarily disable templating on the given EasyConfig
Usage:
with disable_templating(ec):
# Do what you want without templating
# Templating set to previous value
"""
_log.deprecated("disable_templating(ec) was replaced by ec.disable_templating()", '5.0')
with ec.disable_templating() as old_value:
yield old_value
class EasyConfig(object):
"""
Class which handles loading, reading, validation of easyconfigs
"""
def __init__(self, path, extra_options=None, build_specs=None, validate=True, hidden=None, rawtxt=None,
auto_convert_value_types=True, local_var_naming_check=None):
"""
initialize an easyconfig.
:param path: path to easyconfig file to be parsed (ignored if rawtxt is specified)
:param extra_options: dictionary with extra variables that can be set for this specific instance
:param build_specs: dictionary of build specifications (see EasyConfig class, default: {})
:param validate: indicates whether validation should be performed (note: combined with 'validate' build option)
:param hidden: indicate whether corresponding module file should be installed hidden ('.'-prefixed)
:param rawtxt: raw contents of easyconfig file
:param auto_convert_value_types: indicates wether types of easyconfig values should be automatically converted
in case they are wrong
:param local_var_naming_check: mode to use when checking if local variables use the recommended naming scheme
"""
self.template_values = None
self.enable_templating = True # a boolean to control templating
self.log = fancylogger.getLogger(self.__class__.__name__, fname=False)
if path is not None and not os.path.isfile(path):
raise EasyBuildError("EasyConfig __init__ expected a valid path")
# read easyconfig file contents (or use provided rawtxt), so it can be passed down to avoid multiple re-reads
self.path = None
if rawtxt is None:
self.path = path
self.rawtxt = read_file(path)
self.log.debug("Raw contents from supplied easyconfig file %s: %s", path, self.rawtxt)
else:
self.rawtxt = rawtxt
self.log.debug("Supplied raw easyconfig contents: %s" % self.rawtxt)
# constructing easyconfig parser object includes a "raw" parse,
# which serves as a check to see whether supplied easyconfig file is an actual easyconfig...
self.log.info("Performing quick parse to check for valid easyconfig file...")
self.parser = EasyConfigParser(filename=self.path, rawcontent=self.rawtxt,
auto_convert_value_types=auto_convert_value_types)
self.modules_tool = modules_tool()
# use legacy module classes as default
self.valid_module_classes = build_option('valid_module_classes')
if self.valid_module_classes is not None:
self.log.info("Obtained list of valid module classes: %s" % self.valid_module_classes)
self._config = copy.deepcopy(DEFAULT_CONFIG)
# obtain name and easyblock specifications from raw easyconfig contents
self.software_name, self.easyblock = fetch_parameters_from_easyconfig(self.rawtxt, ['name', 'easyblock'])
# determine line of extra easyconfig parameters
if extra_options is None:
easyblock_class = get_easyblock_class(self.easyblock, name=self.software_name)
self.extra_options = easyblock_class.extra_options()
else:
self.extra_options = extra_options
if not isinstance(self.extra_options, dict):
tup = (type(self.extra_options), self.extra_options)
self.log.nosupport("extra_options return value should be of type 'dict', found '%s': %s" % tup, '2.0')
self.mandatory = MANDATORY_PARAMS[:]
# deep copy to make sure self.extra_options remains unchanged
self.extend_params(copy.deepcopy(self.extra_options))
# set valid stops
self.valid_stops = build_option('valid_stops')
self.log.debug("List of valid stops obtained: %s" % self.valid_stops)
# store toolchain
self._toolchain = None
self.validations = {
'moduleclass': self.valid_module_classes,
'stop': self.valid_stops,
}
self.external_modules_metadata = build_option('external_modules_metadata')
# list of all options to iterate over
self.iterate_options = []
self.iterating = False
# parse easyconfig file
self.build_specs = build_specs
self.parse()
self.local_var_naming(local_var_naming_check)
# check whether this easyconfig file is deprecated, and act accordingly if so
self.check_deprecated(self.path)
# perform validations
self.validation = build_option('validate') and validate
if self.validation:
self.validate(check_osdeps=build_option('check_osdeps'))
# filter hidden dependencies from list of dependencies
self.filter_hidden_deps()
self._all_dependencies = None
# keep track of whether the generated module file should be hidden
if hidden is None:
hidden = self['hidden'] or build_option('hidden')
self.hidden = hidden
# set installdir/module info
mns = ActiveMNS()
self.full_mod_name = mns.det_full_module_name(self)
self.short_mod_name = mns.det_short_module_name(self)
self.mod_subdir = mns.det_module_subdir(self)
self.set_default_module = False
self.software_license = None
@contextmanager
def disable_templating(self):
"""Temporarily disable templating on the given EasyConfig
Usage:
with ec.disable_templating():
# Do what you want without templating
# Templating set to previous value
"""
old_enable_templating = self.enable_templating
self.enable_templating = False
try:
yield old_enable_templating
finally:
self.enable_templating = old_enable_templating
def __str__(self):
"""Return a string representation of this EasyConfig instance"""
if self.path:
return '%s EasyConfig @ %s' % (self.name, self.path)
else:
return 'Raw %s EasyConfig' % self.name
def filename(self):
"""Determine correct filename for this easyconfig file."""
if is_yeb_format(self.path, self.rawtxt):
ext = YEB_FORMAT_EXTENSION
else:
ext = EB_FORMAT_EXTENSION
return '%s-%s%s' % (self.name, det_full_ec_version(self), ext)
def extend_params(self, extra, overwrite=True):
"""Extend list of known parameters via provided list of extra easyconfig parameters."""
self.log.debug("Extending list of known easyconfig parameters with: %s", ' '.join(extra.keys()))
if overwrite:
self._config.update(extra)
else:
for key in extra:
if key not in self._config:
self._config[key] = extra[key]
self.log.debug("Added new easyconfig parameter: %s", key)
else:
self.log.debug("Easyconfig parameter %s already known, not overwriting", key)
# extend mandatory keys
for key, value in extra.items():
if value[2] == MANDATORY:
self.mandatory.append(key)
self.log.debug("Updated list of mandatory easyconfig parameters: %s", self.mandatory)
def copy(self, validate=None):
"""
Return a copy of this EasyConfig instance.
"""
if validate is None:
validate = self.validation
# create a new EasyConfig instance
ec = EasyConfig(self.path, validate=validate, hidden=self.hidden, rawtxt=self.rawtxt)
# take a copy of the actual config dictionary (which already contains the extra options)
ec._config = copy.deepcopy(self._config)
# since rawtxt is defined, self.path may not get inherited, make sure it does
if self.path:
ec.path = self.path
# also copy template values, since re-generating them may not give the same set of template values straight away
ec.template_values = copy.deepcopy(self.template_values)
return ec
def update(self, key, value, allow_duplicate=True):
"""
Update an easyconfig parameter with the specified value (i.e. append to it).
Note: For dictionary easyconfig parameters, 'allow_duplicate' is ignored (since it's meaningless).
"""
if isinstance(value, string_type):
inval = [value]
elif isinstance(value, (list, dict, tuple)):
inval = value
else:
msg = "Can't update configuration value for %s, because the attempted"
msg += " update value, '%s', is not a string, list, tuple or dictionary."
raise EasyBuildError(msg, key, value)
# For easyconfig parameters that are dictionaries, input value must also be a dictionary
if isinstance(self[key], dict) and not isinstance(value, dict):
msg = "Can't update configuration value for %s, because the attempted"
msg += "update value (%s), is not a dictionary (type: %s)."
raise EasyBuildError(msg, key, value, type(value))
# Grab current parameter value so we can modify it
param_value = copy.deepcopy(self[key])
if isinstance(param_value, string_type):
for item in inval:
# re.search: only add value to string if it's not there yet (surrounded by whitespace)
if allow_duplicate or (not re.search(r'(^|\s+)%s(\s+|$)' % re.escape(item), param_value)):
param_value = param_value + ' %s ' % item
elif isinstance(param_value, (list, tuple)):
# make sure we have a list value so we can just append to it
param_value = list(param_value)
for item in inval:
if allow_duplicate or item not in param_value:
param_value.append(item)
# cast back to tuple if original value was a tuple
if isinstance(self[key], tuple):
param_value = tuple(param_value)
elif isinstance(param_value, dict):
param_value.update(inval)
else:
msg = "Can't update configuration value for %s, because it's not a string, list, tuple or dictionary."
raise EasyBuildError(msg, key)
# Overwrite easyconfig parameter value with updated value, preserving type
self[key] = param_value
def set_keys(self, params):
"""
Set keys in this EasyConfig instance based on supplied easyconfig parameter values.
If any unknown easyconfig parameters are encountered here, an error is raised.
:param params: a dict value with names/values of easyconfig parameters to set
"""
# disable templating when setting easyconfig parameters
# required to avoid problems with values that need more parsing to be done (e.g. dependencies)
with self.disable_templating():
for key in sorted(params.keys()):
# validations are skipped, just set in the config
if key in self._config.keys():
self[key] = params[key]
self.log.info("setting easyconfig parameter %s: value %s (type: %s)",
key, self[key], type(self[key]))
else:
raise EasyBuildError("Unknown easyconfig parameter: %s (value '%s')", key, params[key])
def parse(self):
"""
Parse the file and set options
mandatory requirements are checked here
"""
if self.build_specs is None:
arg_specs = {}
elif isinstance(self.build_specs, dict):
# build a new dictionary with only the expected keys, to pass as named arguments to get_config_dict()
arg_specs = self.build_specs
else:
raise EasyBuildError("Specifications should be specified using a dictionary, got %s",
type(self.build_specs))
self.log.debug("Obtained specs dict %s" % arg_specs)
self.log.info("Parsing easyconfig file %s with rawcontent: %s", self.path, self.rawtxt)
self.parser.set_specifications(arg_specs)
ec_vars = self.parser.get_config_dict()
self.log.debug("Parsed easyconfig as a dictionary: %s" % ec_vars)
# make sure all mandatory parameters are defined
# this includes both generic mandatory parameters and software-specific parameters defined via extra_options
missing_mandatory_keys = [key for key in self.mandatory if key not in ec_vars]
if missing_mandatory_keys:
raise EasyBuildError("mandatory parameters not provided in %s: %s", self.path, missing_mandatory_keys)
# provide suggestions for typos. Local variable names are excluded from this check
possible_typos = [(key, difflib.get_close_matches(key.lower(), self._config.keys(), 1, 0.85))
for key in ec_vars if not is_local_var_name(key) and key not in self]
typos = [(key, guesses[0]) for (key, guesses) in possible_typos if len(guesses) == 1]
if typos:
raise EasyBuildError("You may have some typos in your easyconfig file: %s",
', '.join(["%s -> %s" % typo for typo in typos]))
# set keys in current EasyConfig instance based on dict obtained by parsing easyconfig file
known_ec_params, self.unknown_keys = triage_easyconfig_params(ec_vars, self._config)
self.set_keys(known_ec_params)
# templating is disabled when parse_hook is called to allow for easy updating of mutable easyconfig parameters
# (see also comment in resolve_template)
with self.disable_templating():
# if any lists of dependency versions are specified over which we should iterate,
# deal with them now, before calling parse hook, parsing of dependencies & iterative easyconfig parameters
self.handle_multi_deps()
parse_hook_msg = None
if self.path:
parse_hook_msg = "Running %s hook for %s..." % (PARSE, os.path.basename(self.path))
# trigger parse hook
hooks = load_hooks(build_option('hooks'))
run_hook(PARSE, hooks, args=[self], msg=parse_hook_msg)
# parse dependency specifications
# it's important that templating is still disabled at this stage!
self.log.info("Parsing dependency specifications...")
def remove_false_versions(deps):
return [dep for dep in deps if not (isinstance(dep, dict) and dep['version'] is False)]
self['dependencies'] = remove_false_versions(self._parse_dependency(dep) for dep in self['dependencies'])
self['hiddendependencies'] = remove_false_versions(self._parse_dependency(dep, hidden=True) for dep in
self['hiddendependencies'])
# need to take into account that builddependencies may need to be iterated over,
# i.e. when the value is a list of lists of tuples
builddeps = self['builddependencies']
if builddeps and all(isinstance(x, (list, tuple)) for b in builddeps for x in b):
self.iterate_options.append('builddependencies')
builddeps = [[self._parse_dependency(dep, build_only=True) for dep in x] for x in builddeps]
else:
builddeps = [self._parse_dependency(dep, build_only=True) for dep in builddeps]
self['builddependencies'] = remove_false_versions(builddeps)
# keep track of parsed multi deps, they'll come in handy during sanity check & module steps...
self.multi_deps = self.get_parsed_multi_deps()
# update templating dictionary
self.generate_template_values()
# finalize dependencies w.r.t. minimal toolchains & module names
self._finalize_dependencies()
# indicate that this is a parsed easyconfig
self._config['parsed'] = [True, "This is a parsed easyconfig", "HIDDEN"]
def count_files(self):
"""
Determine number of files (sources + patches) required for this easyconfig.
"""
cnt = len(self['sources']) + len(self['patches'])
for ext in self['exts_list']:
if isinstance(ext, tuple) and len(ext) >= 3:
ext_opts = ext[2]
# check for 'sources' first, since that's also considered first by EasyBlock.fetch_extension_sources
if 'sources' in ext_opts:
cnt += len(ext_opts['sources'])
elif 'source_tmpl' in ext_opts:
cnt += 1
else:
# assume there's always one source file;
# for extensions using PythonPackage, no 'source' or 'sources' may be specified
cnt += 1
cnt += len(ext_opts.get('patches', []))
return cnt
def local_var_naming(self, local_var_naming_check):
"""Deal with local variables that do not follow the recommended naming scheme (if any)."""
if local_var_naming_check is None:
local_var_naming_check = build_option('local_var_naming_check')
if self.unknown_keys:
cnt = len(self.unknown_keys)
if self.path:
in_fn = "in %s" % os.path.basename(self.path)
else:
in_fn = ''
unknown_keys_msg = ', '.join(sorted(self.unknown_keys))
msg = "Use of %d unknown easyconfig parameters detected %s: %s\n" % (cnt, in_fn, unknown_keys_msg)
msg += "If these are just local variables please rename them to start with '%s', " % LOCAL_VAR_PREFIX
msg += "or try using --fix-deprecated-easyconfigs to do this automatically.\nFor more information, see "
msg += "https://easybuild.readthedocs.io/en/latest/Easyconfig-files-local-variables.html ."
# always log a warning if local variable that don't follow recommended naming scheme are found
self.log.warning(msg)
if local_var_naming_check == LOCAL_VAR_NAMING_CHECK_ERROR:
raise EasyBuildError(msg)
elif local_var_naming_check == LOCAL_VAR_NAMING_CHECK_WARN:
print_warning(msg, silent=build_option('silent'))
elif local_var_naming_check != LOCAL_VAR_NAMING_CHECK_LOG:
raise EasyBuildError("Unknown mode for checking local variable names: %s", local_var_naming_check)
def check_deprecated(self, path):
"""Check whether this easyconfig file is deprecated."""
depr_msgs = []
deprecated = self['deprecated']
if deprecated:
if isinstance(deprecated, string_type):
if 'easyconfig' not in build_option('silence_deprecation_warnings'):
depr_msgs.append("easyconfig file '%s' is marked as deprecated:\n%s\n" % (path, deprecated))
else:
raise EasyBuildError("Wrong type for value of 'deprecated' easyconfig parameter: %s", type(deprecated))
if self.toolchain.is_deprecated():
# allow use of deprecated toolchains when running unit tests,
# because test easyconfigs/modules often use old toolchain versions (and updating them is far from trivial)
if (not build_option('unit_testing_mode')
and 'toolchain' not in build_option('silence_deprecation_warnings')):
depr_msgs.append("toolchain '%(name)s/%(version)s' is marked as deprecated" % self['toolchain'])
if depr_msgs:
depr_msg = ', '.join(depr_msgs)
depr_maj_ver = int(str(VERSION).split('.')[0]) + 1
depr_ver = '%s.0' % depr_maj_ver
more_info_depr_ec = " (see also http://easybuild.readthedocs.org/en/latest/Deprecated-easyconfigs.html)"
self.log.deprecated(depr_msg, depr_ver, more_info=more_info_depr_ec, silent=build_option('silent'))
def validate(self, check_osdeps=True):
"""
Validate this easyonfig
- ensure certain easyconfig parameters are set to a known value (see self.validations)
- check OS dependencies
- check license
"""
self.log.info("Validating easyconfig")
for attr in self.validations:
self._validate(attr, self.validations[attr])
if check_osdeps:
self.log.info("Checking OS dependencies")
self.validate_os_deps()
else:
self.log.info("Not checking OS dependencies")
self.log.info("Checking skipsteps")
if not isinstance(self._config['skipsteps'][0], (list, tuple,)):
raise EasyBuildError('Invalid type for skipsteps. Allowed are list or tuple, got %s (%s)',
type(self._config['skipsteps'][0]), self._config['skipsteps'][0])
self.log.info("Checking build option lists")
self.validate_iterate_opts_lists()
self.log.info("Checking licenses")
self.validate_license()
def validate_license(self):
"""Validate the license"""
lic = self['software_license']
if lic is None:
# when mandatory, remove this possibility
if 'software_license' in self.mandatory:
raise EasyBuildError("Software license is mandatory, but 'software_license' is undefined")
elif lic in EASYCONFIG_LICENSES_DICT:
# create License instance
self.software_license = EASYCONFIG_LICENSES_DICT[lic]()
else:
known_licenses = ', '.join(sorted(EASYCONFIG_LICENSES_DICT.keys()))
raise EasyBuildError("Invalid license %s (known licenses: %s)", lic, known_licenses)
# TODO, when GROUP_SOURCE and/or GROUP_BINARY is True
# check the owner of source / binary (must match 'group' parameter from easyconfig)
return True
def validate_os_deps(self):
"""
validate presence of OS dependencies
osdependencies should be a single list
"""
not_found = []
for dep in self['osdependencies']:
# make sure we have a tuple
if isinstance(dep, string_type):
dep = (dep,)
elif not isinstance(dep, tuple):
raise EasyBuildError("Non-tuple value type for OS dependency specification: %s (type %s)",
dep, type(dep))
if not any(check_os_dependency(cand_dep) for cand_dep in dep):
not_found.append(dep)
if not_found:
raise EasyBuildError("One or more OS dependencies were not found: %s", not_found)
else:
self.log.info("OS dependencies ok: %s" % self['osdependencies'])
return True
def validate_iterate_opts_lists(self):
"""
Configure/build/install options specified as lists should have same length.
"""
# configure/build/install options may be lists, in case of an iterated build
# when lists are used, they should be all of same length
# list of length 1 are treated as if it were strings in EasyBlock
opt_counts = []
for opt in ITERATE_OPTIONS:
# only when builddependencies is a list of lists are we iterating over them
if opt == 'builddependencies' and not all(isinstance(e, list) for e in self.get_ref(opt)):
continue
opt_value = self.get(opt, None, resolve=False)
# anticipate changes in available easyconfig parameters (e.g. makeopts -> buildopts?)
if opt_value is None:
raise EasyBuildError("%s not available in self.cfg (anymore)?!", opt)
# keep track of list, supply first element as first option to handle
if isinstance(opt_value, (list, tuple)):
opt_counts.append((opt, len(opt_value)))
# make sure that options that specify lists have the same length
list_opt_lengths = [length for (opt, length) in opt_counts if length > 1]
if len(nub(list_opt_lengths)) > 1:
raise EasyBuildError("Build option lists for iterated build should have same length: %s", opt_counts)
return True
def start_iterating(self):
"""Start iterative mode."""
for opt in ITERATE_OPTIONS:
# builddpendencies is already handled, see __init__
if opt == 'builddependencies':
continue
# list of values indicates that this is a value to iterate over
if isinstance(self[opt], (list, tuple)):
self.iterate_options.append(opt)
# keep track of when we're iterating (used by builddependencies())
self.iterating = True
def stop_iterating(self):
"""Stop iterative mode."""
self.iterating = False
def filter_hidden_deps(self):
"""
Replace dependencies by hidden dependencies in list of (build) dependencies, where appropriate.
"""
faulty_deps = []
# obtain reference to original lists, so their elements can be changed in place
deps = {key: self.get_ref(key) for key in ('dependencies', 'builddependencies', 'hiddendependencies')}
if 'builddependencies' in self.iterate_options:
deplists = copy.deepcopy(deps['builddependencies'])
else:
deplists = [deps['builddependencies']]
deplists.append(deps['dependencies'])
for hidden_idx, hidden_dep in enumerate(deps['hiddendependencies']):
hidden_mod_name = ActiveMNS().det_full_module_name(hidden_dep)
visible_mod_name = ActiveMNS().det_full_module_name(hidden_dep, force_visible=True)