forked from easybuilders/easybuild-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodules.py
More file actions
2071 lines (1714 loc) · 90.9 KB
/
modules.py
File metadata and controls
2071 lines (1714 loc) · 90.9 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-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/>.
##
"""
This python module implements the environment modules functionality:
- loading modules
- checking for available modules
- ...
Authors:
* Stijn De Weirdt (Ghent University)
* Dries Verdegem (Ghent University)
* Kenneth Hoste (Ghent University)
* Pieter De Baets (Ghent University)
* Jens Timmerman (Ghent University)
* David Brown (Pacific Northwest National Laboratory)
"""
import glob
import os
import re
import shlex
from enum import Enum
from easybuild.base import fancylogger
from easybuild.tools import LooseVersion
from easybuild.tools.build_log import EasyBuildError, EasyBuildExit, print_warning
from easybuild.tools.config import ERROR, EBROOT_ENV_VAR_ACTIONS, IGNORE, LOADED_MODULES_ACTIONS, PURGE
from easybuild.tools.config import SEARCH_PATH_BIN_DIRS, SEARCH_PATH_HEADER_DIRS, SEARCH_PATH_LIB_DIRS, UNLOAD, UNSET
from easybuild.tools.config import build_option, get_modules_tool, install_path
from easybuild.tools.environment import ORIG_OS_ENVIRON, restore_env, setvar, unset_env_vars
from easybuild.tools.filetools import convert_name, mkdir, normalize_path, path_matches, read_file, which, write_file
from easybuild.tools.module_naming_scheme.mns import DEVEL_MODULE_SUFFIX
from easybuild.tools.run import run_shell_cmd
from easybuild.tools.systemtools import get_shared_lib_ext
from easybuild.tools.utilities import get_subclasses, nub
# software root/version environment variable name prefixes
ROOT_ENV_VAR_NAME_PREFIX = "EBROOT"
VERSION_ENV_VAR_NAME_PREFIX = "EBVERSION"
DEVEL_ENV_VAR_NAME_PREFIX = "EBDEVEL"
# environment variables to reset/restore when running a module command (to avoid breaking it)
# see e.g., https://bugzilla.redhat.com/show_bug.cgi?id=719785
LD_ENV_VAR_KEYS = ['LD_LIBRARY_PATH', 'LD_PRELOAD']
OUTPUT_MATCHES = {
# matches whitespace and module-listing headers
'whitespace': re.compile(r"^\s*$|^(-+).*(-+)$"),
# matches errors such as "cmdTrace.c(713):ERROR:104: 'asdfasdf' is an unrecognized subcommand"
# # following errors should not be matches, they are considered warnings
# ModuleCmd_Avail.c(529):ERROR:57: Error while reading directory '/usr/local/modulefiles/SCIENTIFIC'
# ModuleCmd_Avail.c(804):ERROR:64: Directory '/usr/local/modulefiles/SCIENTIFIC/tremolo' not found
'error': re.compile(r"^\S+:(?P<level>\w+):(?P<code>(?!57|64)\d+):\s+(?P<msg>.*)$"),
# 'available' with --terse has one module per line, with some extra lines (module path(s), module directories...)
# regex below matches modules like 'ictce/3.2.1.015.u4', 'OpenMPI/1.6.4-no-OFED', ...
#
# Module lines notes:
# * module name may have '(default)' appended [modulecmd]
# ignored lines:
# * module paths lines may start with a (empty) set of '-'s, which will be followed by a space [modulecmd.tcl]
# * module paths may end with a ':' [modulecmd, lmod]
# * module directories lines may end with a '/' [lmod >= 5.1.5]
#
# Note: module paths may be relative paths!
#
# Example outputs for the different supported module tools, for the same set of modules files (only two, both GCC):
#
# $ modulecmd python avail --terse GCC > /dev/null
# /path/tomodules:
# GCC/4.6.3
# GCC/4.6.4(default)
#
# $ lmod python avail --terse GCC > /dev/null
# /path/to/modules:
# GCC/
# GCC/4.6.3
# GCC/4.6.4
#
# $ modulecmd.tcl python avail -t GCC > /dev/null
# -------- /path/to/modules --------
# GCC/4.6.3
# GCC/4.6.4
#
# Note on modulecmd.tcl: if the terminal is not wide enough, or the module path too long, the '-'s are not there!
#
# Any modules with a name that does not match the regex constructed below, will be HIDDEN from EasyBuild
#
'available': re.compile(r"""
^(?!-*\s) # disallow lines starting with (empty) list of '-'s followed by a space
(?P<mod_name> # start named group for module name
[^\s\(]*[^:/] # module name must not have '(' or whitespace in it, must not end with ':' or '/'
) # end named group for module name
(?P<default>\(default\))? # optional '(default)' that's not part of module name
(\([^()]+\))? # ignore '(...)' that is not part of module name (e.g. for symbolic versions)
\s*$ # ignore whitespace at the end of the line
""", re.VERBOSE),
}
# cache for result of module subcommands
# key: tuple with $MODULEPATH and (stringified) list of extra arguments/options for module subcommand
# value: result of module subcommand
MODULE_AVAIL_CACHE = {}
MODULE_SHOW_CACHE = {}
# cache for modules tool version
# cache key: module command
# value: corresponding (validated) module version
MODULE_VERSION_CACHE = {}
_log = fancylogger.getLogger('modules', fname=False)
class ModEnvVarType(Enum):
"""
Possible types of ModuleEnvironmentVariable:
- STRING: (list of) strings with no further meaning
- PATH: (list of) of paths to existing directories or files
- PATH_WITH_FILES: (list of) of paths to existing directories containing
one or more files
- PATH_WITH_TOP_FILES: (list of) of paths to existing directories
containing one or more files in its top directory
- """
STRING, PATH, PATH_WITH_FILES, PATH_WITH_TOP_FILES = range(0, 4)
class ModuleEnvironmentVariable:
"""
Environment variable data structure for modules
Contents of environment variable is a list of unique strings
"""
def __init__(self, contents, var_type=None, delim=os.pathsep):
"""
Initialize new environment variable
Actual contents of the environment variable are held in self.contents
By default, environment variable is a (list of) paths with files in them
Existence of paths and their contents are not checked at init
"""
self.contents = contents
self.delim = delim
if var_type is None:
var_type = ModEnvVarType.PATH_WITH_FILES
self.type = var_type
self.log = fancylogger.getLogger(self.__class__.__name__, fname=False)
def __repr__(self):
return repr(self.contents)
def __str__(self):
return self.delim.join(self.contents)
def __iter__(self):
return iter(self.contents)
@property
def contents(self):
return self._contents
@contents.setter
def contents(self, value):
"""Enforce that contents is a list of strings"""
if isinstance(value, str):
value = [value]
try:
str_list = [str(path) for path in value]
except TypeError as err:
raise TypeError("ModuleEnvironmentVariable.contents must be a list of strings") from err
self._contents = nub(str_list) # remove duplicates and keep order
@property
def type(self):
return self._type
@type.setter
def type(self, value):
"""Convert type to VarType"""
if isinstance(value, ModEnvVarType):
self._type = value
else:
try:
self._type = ModEnvVarType[value]
except KeyError as err:
raise EasyBuildError(f"Cannot create ModuleEnvironmentVariable with type {value}") from err
def append(self, item):
"""Shortcut to append to list of contents"""
self.contents += [item]
def extend(self, item):
"""Shortcut to extend list of contents"""
self.contents += item
def prepend(self, item):
"""Shortcut to prepend item to list of contents"""
self.contents = [item] + self.contents
def update(self, item):
"""Shortcut to replace list of contents with item"""
self.contents = item
def remove(self, *args):
"""Shortcut to remove items from list of contents"""
try:
self.contents.remove(*args)
except ValueError:
# item is not in the list, move along
self.log.debug(f"ModuleEnvironmentVariable does not contain item: {' '.join(args)}")
@property
def is_path(self):
path_like_types = [
ModEnvVarType.PATH,
ModEnvVarType.PATH_WITH_FILES,
ModEnvVarType.PATH_WITH_TOP_FILES,
]
return self.type in path_like_types
class ModuleLoadEnvironment:
"""Changes to environment variables that should be made when environment module is loaded"""
def __init__(self):
"""
Initialize default environment definition
Paths are relative to root of installation directory
"""
self.ACLOCAL_PATH = [os.path.join('share', 'aclocal')]
self.CLASSPATH = ['*.jar']
self.CMAKE_LIBRARY_PATH = ['lib64'] # only needed for installations with standalone lib64
self.CMAKE_PREFIX_PATH = ['']
self.CPATH = SEARCH_PATH_HEADER_DIRS
self.GI_TYPELIB_PATH = [os.path.join(x, 'girepository-*') for x in SEARCH_PATH_LIB_DIRS]
self.LD_LIBRARY_PATH = SEARCH_PATH_LIB_DIRS
self.LIBRARY_PATH = SEARCH_PATH_LIB_DIRS
self.MANPATH = ['man', os.path.join('share', 'man')]
self.PATH = SEARCH_PATH_BIN_DIRS + ['sbin']
self.PKG_CONFIG_PATH = [os.path.join(x, 'pkgconfig') for x in SEARCH_PATH_LIB_DIRS + ['share']]
self.XDG_DATA_DIRS = ['share']
def __setattr__(self, name, value):
"""
Specific restrictions for ModuleLoadEnvironment attributes:
- attribute names are uppercase
- attributes are instances of ModuleEnvironmentVariable
"""
if name != name.upper():
raise EasyBuildError(f"Names of ModuleLoadEnvironment attributes must be uppercase, got '{name}'")
try:
(contents, kwargs) = value
except ValueError:
contents, kwargs = value, {}
if not isinstance(kwargs, dict):
contents, kwargs = value, {}
# special variables that require files in their top directories
if name in ('LD_LIBRARY_PATH', 'PATH'):
kwargs.update({'var_type': ModEnvVarType.PATH_WITH_TOP_FILES})
return super().__setattr__(name, ModuleEnvironmentVariable(contents, **kwargs))
def __iter__(self):
"""Make the class iterable"""
yield from self.__dict__
def items(self):
"""
Return key-value pairs for each attribute that is a ModuleEnvironmentVariable
- key = attribute name
- value = its "contents" attribute
"""
for attr in self.__dict__:
yield attr, getattr(self, attr)
def update(self, new_env):
"""Update contents of environment from given dictionary"""
try:
for envar_name, envar_contents in new_env.items():
setattr(self, envar_name, envar_contents)
except AttributeError as err:
raise EasyBuildError("Cannot update ModuleLoadEnvironment from a non-dict variable") from err
@property
def as_dict(self):
"""
Return dict with mapping of ModuleEnvironmentVariables names with their contents
"""
return dict(self.items())
@property
def environ(self):
"""
Return dict with mapping of ModuleEnvironmentVariables names with their contents
Equivalent in shape to os.environ
"""
mapping = {}
for envar_name, envar_contents in self.items():
mapping.update({envar_name: str(envar_contents)})
return mapping
class ModulesTool(object):
"""An abstract interface to a tool that deals with modules."""
# name of this modules tool (used in log/warning/error messages)
NAME = None
# position and optionname
TERSE_OPTION = (0, '--terse')
# module command to use
COMMAND = None
# environment variable to determine path to module command;
# used as fallback in case command is not available in $PATH
COMMAND_ENVIRONMENT = None
# run module command explicitly using this shell
COMMAND_SHELL = None
# option to determine the version
VERSION_OPTION = '--version'
# minimal required version (cannot include -beta or rc)
REQ_VERSION = None
# minimal required version to check user's group in modulefile
REQ_VERSION_TCL_CHECK_GROUP = None
# deprecated version limit (support for versions below this version is deprecated)
DEPR_VERSION = None
# maximum version allowed (cannot include -beta or rc)
MAX_VERSION = None
# the regexp, should have a "version" group (multiline search)
VERSION_REGEXP = None
# modules tool user cache directory
USER_CACHE_DIR = None
def __init__(self, mod_paths=None, testing=False):
"""
Create a ModulesTool object
:param mod_paths: A list of paths where the modules can be located
@type mod_paths: list
"""
# this can/should be set to True during testing
self.testing = testing
self.log = fancylogger.getLogger(self.NAME, fname=False)
# DEPRECATED!
self._modules = []
# actual module command (i.e., not the 'module' wrapper function, but the binary)
self.cmd = self.COMMAND
if self.COMMAND_ENVIRONMENT:
env_cmd_path = os.environ.get(self.COMMAND_ENVIRONMENT)
else:
env_cmd_path = None
self.mod_paths = None
if mod_paths is not None:
self.set_mod_paths(mod_paths)
if env_cmd_path:
cmd_path = which(self.cmd, log_ok=False, on_error=IGNORE)
# only use command path in environment variable if command in not available in $PATH
if cmd_path is None:
self.cmd = env_cmd_path
self.log.debug("Set %s command via environment variable %s: %s",
self.NAME, self.COMMAND_ENVIRONMENT, self.cmd)
elif cmd_path != env_cmd_path:
self.log.debug("Different paths found for %s command '%s' via which/$PATH and $%s: %s vs %s",
self.NAME, self.COMMAND, self.COMMAND_ENVIRONMENT, cmd_path, env_cmd_path)
# make sure the module command was found
if self.cmd is None:
raise EasyBuildError("No command set for %s", self.NAME)
else:
self.log.debug('Using %s command %s', self.NAME, self.cmd)
# version of modules tool
self.version = None
# some initialisation/verification
self.check_cmd_avail()
self.check_module_path()
self.check_module_function(allow_mismatch=build_option('allow_modules_tool_mismatch'))
self.set_and_check_version()
self.supports_depends_on = False
self.supports_tcl_getenv = False
self.supports_tcl_check_group = False
self.supports_safe_auto_load = False
def __str__(self):
"""String representation of this ModulesTool instance."""
res = self.NAME
if self.version:
res += ' ' + self.version
else:
res += ' (unknown version)'
return res
def buildstats(self):
"""Return tuple with data to be included in buildstats"""
return (self.NAME, self.cmd, self.version)
def set_and_check_version(self):
"""Get the module version, and check any requirements"""
if self.cmd in MODULE_VERSION_CACHE:
self.version = MODULE_VERSION_CACHE[self.cmd]
self.log.debug("Found cached version for %s command %s: %s", self.NAME, self.COMMAND, self.version)
return
if self.VERSION_REGEXP is None:
raise EasyBuildError("No VERSION_REGEXP defined")
try:
txt = self.run_module(self.VERSION_OPTION, return_output=True, check_output=False, check_exit_code=False)
ver_re = re.compile(self.VERSION_REGEXP, re.M)
res = ver_re.search(txt)
if res:
self.version = res.group('version')
self.log.info("Found %s version %s", self.NAME, self.version)
else:
raise EasyBuildError("Failed to determine %s version from option '%s' output: %s",
self.NAME, self.VERSION_OPTION, txt)
except (OSError) as err:
raise EasyBuildError("Failed to check %s version: %s", self.NAME, err)
if self.REQ_VERSION is None and self.MAX_VERSION is None:
self.log.debug("No version requirement defined.")
elif build_option('modules_tool_version_check'):
self.log.debug("Checking whether %s version %s meets requirements", self.NAME, self.version)
version = LooseVersion(self.version)
if self.REQ_VERSION is not None:
self.log.debug("Required minimum %s version defined: %s", self.NAME, self.REQ_VERSION)
if version < self.REQ_VERSION or version.is_prerelease(self.REQ_VERSION, ['rc', '-beta']):
raise EasyBuildError("EasyBuild requires %s >= v%s, found v%s",
self.NAME, self.REQ_VERSION, self.version)
else:
self.log.debug('%s version %s matches requirement >= %s', self.NAME, self.version, self.REQ_VERSION)
if self.DEPR_VERSION is not None:
self.log.debug("Deprecated %s version limit defined: %s", self.NAME, self.DEPR_VERSION)
if version < self.DEPR_VERSION or version.is_prerelease(self.DEPR_VERSION, ['rc', '-beta']):
depr_msg = "Support for %s version < %s is deprecated, " % (self.NAME, self.DEPR_VERSION)
depr_msg += "found version %s" % self.version
self.log.deprecated(depr_msg, '6.0')
if self.MAX_VERSION is not None:
self.log.debug("Maximum allowed %s version defined: %s", self.NAME, self.MAX_VERSION)
if self.version > self.MAX_VERSION and not version.is_prerelease(self.MAX_VERSION, ['rc', '-beta']):
raise EasyBuildError("EasyBuild requires %s <= v%s, found v%s",
self.NAME, self.MAX_VERSION, self.version)
else:
self.log.debug('Version %s matches requirement <= %s', self.version, self.MAX_VERSION)
else:
self.log.debug("Skipping modules tool version '%s' requirements check", self.version)
MODULE_VERSION_CACHE[self.cmd] = self.version
def check_cmd_avail(self):
"""Check whether modules tool command is available."""
cmd_path = which(self.cmd, log_ok=False)
if cmd_path is not None:
self.cmd = cmd_path
self.log.info("Full path for %s command is %s, so using it", self.NAME, self.cmd)
else:
mod_tools = avail_modules_tools().keys()
error_msg = "%s modules tool can not be used, '%s' command is not available" % (self.NAME, self.cmd)
error_msg += "; use --modules-tool to specify a different modules tool to use (%s)" % ', '.join(mod_tools)
raise EasyBuildError(error_msg)
def check_module_function(self, allow_mismatch=False, regex=None):
"""Check whether selected module tool matches 'module' function definition."""
if self.testing:
# grab 'module' function definition from environment if it's there; only during testing
try:
output, exit_code = os.environ['module'], EasyBuildExit.SUCCESS
except KeyError:
output, exit_code = None, EasyBuildExit.FAIL_SYSTEM_CHECK
else:
cmd = "type module"
res = run_shell_cmd(cmd, fail_on_error=False, in_dry_run=True, hidden=True, output_file=False)
output, exit_code = res.output, res.exit_code
if regex is None:
regex = r".*%s" % os.path.basename(self.cmd)
mod_cmd_re = re.compile(regex, re.M)
mod_details = "pattern '%s' (%s)" % (mod_cmd_re.pattern, self.NAME)
if exit_code == EasyBuildExit.SUCCESS:
if mod_cmd_re.search(output):
self.log.debug("Found pattern '%s' in defined 'module' function." % mod_cmd_re.pattern)
else:
msg = "%s not found in defined 'module' function.\n" % mod_details
msg += "Specify the correct modules tool to avoid weird problems due to this mismatch, "
msg += "see the --modules-tool and --avail-modules-tools command line options.\n"
if allow_mismatch:
msg += "Obtained definition of 'module' function: %s" % output
self.log.warning(msg)
else:
msg += "Or alternatively, use --allow-modules-tool-mismatch to stop treating this as an error. "
msg += "Obtained definition of 'module' function: %s" % output
raise EasyBuildError(msg)
else:
# module function may not be defined (weird, but fine)
self.log.warning("No 'module' function defined, can't check if it matches %s." % mod_details)
def mk_module_cache_key(self, partial_key):
"""Create a module cache key, using the specified partial key, by combining it with the current $MODULEPATH."""
return ('MODULEPATH=%s' % os.environ.get('MODULEPATH', ''), self.COMMAND, partial_key)
def set_mod_paths(self, mod_paths=None):
"""
Set mod_paths, based on $MODULEPATH unless a list of module paths is specified.
:param mod_paths: list of entries for $MODULEPATH to use
"""
# make sure we don't have the same path twice, using nub
if mod_paths is None:
# no paths specified, so grab list of (existing) module paths from $MODULEPATH
self.mod_paths = nub(curr_module_paths())
else:
for mod_path in nub(mod_paths):
self.prepend_module_path(mod_path, set_mod_paths=False)
self.mod_paths = nub(mod_paths)
self.log.debug("$MODULEPATH after set_mod_paths: %s" % os.environ.get('MODULEPATH', ''))
def use(self, path, priority=None):
"""
Add path to $MODULEPATH via 'module use'.
:param path: path to add to $MODULEPATH
:param priority: priority for this path in $MODULEPATH (Lmod-specific)
"""
if priority:
self.log.info("Ignoring specified priority '%s' when running 'module use %s' (Lmod-specific)",
priority, path)
if not path:
raise EasyBuildError("Cannot add empty path to $MODULEPATH")
if not os.path.exists(path):
self.log.deprecated("Path '%s' for module.use should exist" % path, '5.0')
# make sure path exists before we add it
mkdir(path, parents=True)
self.run_module(['use', path])
def unuse(self, path):
"""Remove module path via 'module unuse'."""
self.run_module(['unuse', path])
def add_module_path(self, path, set_mod_paths=True):
"""
Add specified module path (using 'module use') if it's not there yet.
:param path: path to add to $MODULEPATH via 'use'
:param set_mod_paths: (re)set self.mod_paths
"""
path = normalize_path(path)
if path not in curr_module_paths(normalize=True):
# add module path via 'module use' and make sure self.mod_paths is synced
self.use(path)
if set_mod_paths:
self.set_mod_paths()
def remove_module_path(self, path, set_mod_paths=True):
"""
Remove specified module path (using 'module unuse').
:param path: path to remove from $MODULEPATH via 'unuse'
:param set_mod_paths: (re)set self.mod_paths
"""
# remove module path via 'module unuse' and make sure self.mod_paths is synced
path = normalize_path(path)
try:
# Unuse the path that is actually present in the environment
module_path = next(p for p in curr_module_paths() if normalize_path(p) == path)
except StopIteration:
pass
else:
self.unuse(module_path)
if set_mod_paths:
self.set_mod_paths()
def prepend_module_path(self, path, set_mod_paths=True, priority=None):
"""
Prepend given module path to list of module paths, or bump it to 1st place.
:param path: path to prepend to $MODULEPATH
:param set_mod_paths: (re)set self.mod_paths
:param priority: priority for this path in $MODULEPATH (Lmod-specific)
"""
if priority:
self.log.info("Ignoring specified priority '%s' when prepending %s to $MODULEPATH (Lmod-specific)",
priority, path)
# generic approach: remove the path first (if it's there), then add it again (to the front)
modulepath = curr_module_paths()
if not modulepath:
self.add_module_path(path, set_mod_paths=set_mod_paths)
elif os.path.realpath(modulepath[0]) != os.path.realpath(path):
self.remove_module_path(path, set_mod_paths=False)
self.add_module_path(path, set_mod_paths=set_mod_paths)
def check_module_path(self):
"""
Check if MODULEPATH is set and change it if necessary.
"""
# if self.mod_paths is not specified, define it and make sure the EasyBuild module path is in there (first)
if self.mod_paths is None:
# take (unique) module paths from environment
self.set_mod_paths()
self.log.debug("self.mod_paths set based on $MODULEPATH: %s" % self.mod_paths)
# determine module path for EasyBuild install path to be included in $MODULEPATH
eb_modpath = os.path.join(install_path(typ='modules'), build_option('suffix_modules_path'))
# make sure EasyBuild module path is in 1st place
mkdir(eb_modpath, parents=True)
self.prepend_module_path(eb_modpath)
self.log.info("Prepended list of module paths with path used by EasyBuild: %s" % eb_modpath)
# set the module path environment accordingly
curr_mod_paths = curr_module_paths()
self.log.debug("Current module paths: %s; target module paths: %s", curr_mod_paths, self.mod_paths)
if curr_mod_paths == self.mod_paths:
self.log.debug("Current value of $MODULEPATH already matches list of module path %s", self.mod_paths)
else:
# filter out tail of paths that already matches tail of target, to avoid unnecessary 'unuse' commands
idx = 1
while curr_mod_paths[-idx:] == self.mod_paths[-idx:]:
idx += 1
self.log.debug("Not prepending %d last entries of %s", idx - 1, self.mod_paths)
for mod_path in self.mod_paths[::-1][idx - 1:]:
self.prepend_module_path(mod_path)
self.log.info("$MODULEPATH set via list of module paths (w/ 'module use'): %s" % os.environ['MODULEPATH'])
def available(self, mod_name=None, extra_args=None):
"""
Return a list of available modules for the given (partial) module name;
use None to obtain a list of all available modules.
:param mod_name: a (partial) module name for filtering (default: None)
"""
if extra_args is None:
extra_args = []
if mod_name is None:
mod_name = ''
# cache 'avail' calls without an argument, since these are particularly expensive...
key = self.mk_module_cache_key(';'.join(extra_args))
if not mod_name and key in MODULE_AVAIL_CACHE:
ans = MODULE_AVAIL_CACHE[key]
self.log.debug("Found cached result for 'module avail' with key '%s': %s", key, ans)
else:
args = ['avail'] + extra_args + [mod_name]
mods = self.run_module(*args)
# sort list of modules in alphabetical order
mods.sort(key=lambda m: m['mod_name'])
ans = nub([mod['mod_name'] for mod in mods])
self.log.debug("'module available %s' gave %d answers: %s" % (mod_name, len(ans), ans))
if not mod_name:
MODULE_AVAIL_CACHE[key] = ans
self.log.debug("Cached result for 'module avail' with key '%s': %s", key, ans)
return ans
def module_wrapper_exists(self, mod_name, modulerc_fn='.modulerc', mod_wrapper_regex_template=None):
"""
Determine whether a module wrapper with specified name exists.
Only .modulerc file in Tcl syntax is considered here.
"""
if mod_wrapper_regex_template is None:
mod_wrapper_regex_template = "^[ ]*module-version (?P<wrapped_mod>[^ ]*) %s$"
wrapped_mod = None
mod_dir = os.path.dirname(mod_name)
wrapper_regex = re.compile(mod_wrapper_regex_template % os.path.basename(mod_name), re.M)
for mod_path in curr_module_paths():
modulerc_cand = os.path.join(mod_path, mod_dir, modulerc_fn)
if os.path.exists(modulerc_cand):
self.log.debug("Found %s that may define %s as a wrapper for a module file", modulerc_cand, mod_name)
res = wrapper_regex.search(read_file(modulerc_cand))
if res:
wrapped_mod = res.group('wrapped_mod')
self.log.debug("Confirmed that %s is a module wrapper for %s", mod_name, wrapped_mod)
break
mod_dir = os.path.dirname(mod_name)
if wrapped_mod is not None and not wrapped_mod.startswith(mod_dir):
# module wrapper uses 'short' module name of module being wrapped,
# so we need to correct it in case a hierarchical module naming scheme is used...
# e.g. 'Java/1.8.0_181' should become 'Core/Java/1.8.0_181' for wrapper 'Core/Java/1.8'
self.log.debug("Full module name prefix mismatch between module wrapper '%s' and wrapped module '%s'",
mod_name, wrapped_mod)
mod_name_parts = mod_name.split(os.path.sep)
wrapped_mod_subdir = ''
while not os.path.join(wrapped_mod_subdir, wrapped_mod).startswith(mod_dir) and mod_name_parts:
wrapped_mod_subdir = os.path.join(wrapped_mod_subdir, mod_name_parts.pop(0))
full_wrapped_mod_name = os.path.join(wrapped_mod_subdir, wrapped_mod)
if full_wrapped_mod_name.startswith(mod_dir):
self.log.debug("Full module name for wrapped module %s: %s", wrapped_mod, full_wrapped_mod_name)
wrapped_mod = full_wrapped_mod_name
else:
raise EasyBuildError("Failed to determine full module name for module wrapped by %s: %s | %s",
mod_name, wrapped_mod_subdir, wrapped_mod)
return wrapped_mod
def exist(self, mod_names, skip_avail=False, maybe_partial=True):
"""
Check if modules with specified names exists.
:param mod_names: list of module names
:param skip_avail: skip checking through 'module avail', only check via 'module show'
:param maybe_partial: indicates if the module name may be a partial module name
"""
def mod_exists_via_show(mod_name):
"""
Helper function to check whether specified module name exists through 'module show'.
:param mod_name: module name
"""
self.log.debug("Checking whether %s exists based on output of 'module show'", mod_name)
stderr = self.show(mod_name)
res = False
# Parse the output:
# - Skip whitespace
# - Any error -> Module does not exist
# - Check first non-whitespace line for something that looks like an absolute path terminated by a colon
mod_exists_regex = r'\s*/.+:\s*'
for line in stderr.split('\n'):
self.log.debug("Checking line '%s' to determine whether %s exists...", line, mod_name)
# skip whitespace lines
if OUTPUT_MATCHES['whitespace'].search(line):
self.log.debug("Treating line '%s' as whitespace, so skipping it", line)
continue
# if any errors occured, conclude that module doesn't exist
if OUTPUT_MATCHES['error'].search(line):
self.log.debug("Line '%s' looks like an error, so concluding that %s doesn't exist",
line, mod_name)
break
# skip warning lines, which may be produced by modules tool but should not be used
# to determine whether a module file exists
if line.startswith('WARNING: '):
self.log.debug("Skipping warning line '%s'", line)
continue
# skip lines that start with 'module-' (like 'module-version')
# that may appear with EnvironmentModulesC or EnvironmentModulesTcl,
# see https://github.com/easybuilders/easybuild-framework/issues/3376
if line.startswith('module-'):
self.log.debug("Skipping line '%s' since it starts with 'module-'", line)
continue
# if line matches pattern that indicates an existing module file, the module file exists
res = bool(re.match(mod_exists_regex, line))
self.log.debug("Result for existence check of %s based on 'module show' output line '%s': %s",
mod_name, line, res)
break
return res
if skip_avail:
avail_mod_names = []
elif len(mod_names) == 1:
# optimize for case of single module name ('avail' without arguments can be expensive)
avail_mod_names = self.available(mod_name=mod_names[0])
else:
avail_mod_names = self.available()
# differentiate between hidden and visible modules
mod_names = [(mod_name, not os.path.basename(mod_name).startswith('.')) for mod_name in mod_names]
mods_exist = []
for (mod_name, visible) in mod_names:
self.log.info("Checking whether %s exists...", mod_name)
if visible:
mod_exists = mod_name in avail_mod_names
# module name may be partial, so also check via 'module show' as fallback
if mod_exists:
self.log.info("Module %s exists (found in list of available modules)", mod_name)
elif maybe_partial:
self.log.info("Module %s not found in list of available modules, checking via 'module show'...",
mod_name)
mod_exists = mod_exists_via_show(mod_name)
else:
# hidden modules are not visible in 'avail', need to use 'show' instead
self.log.info("Checking whether hidden module %s exists via 'show'..." % mod_name)
mod_exists = mod_exists_via_show(mod_name)
# if no module file was found, check whether specified module name can be a 'wrapper' module...
# this fallback mechanism is important when using a hierarchical module naming scheme,
# where "full" module names (like Core/Java/11) are used to check whether modules exist already;
# Lmod will report module wrappers as non-existent when full module name is used,
# see https://github.com/TACC/Lmod/issues/446
if not mod_exists:
self.log.info("Module %s not found via module avail/show, checking whether it is a wrapper", mod_name)
wrapped_mod = self.module_wrapper_exists(mod_name)
if wrapped_mod is not None:
# module wrapper only really exists if the wrapped module file is also available
mod_exists = wrapped_mod in avail_mod_names or mod_exists_via_show(wrapped_mod)
self.log.debug("Result for existence check of wrapped module %s: %s", wrapped_mod, mod_exists)
self.log.info("Result for existence check of %s module: %s", mod_name, mod_exists)
mods_exist.append(mod_exists)
return mods_exist
def load(self, modules, mod_paths=None, purge=False, init_env=None, allow_reload=True):
"""
Load all requested modules.
:param modules: list of modules to load
:param mod_paths: list of module paths to activate before loading
:param purge: whether or not a 'module purge' should be run before loading
:param init_env: original environment to restore after running 'module purge'
:param allow_reload: allow reloading an already loaded module
"""
if mod_paths is None:
mod_paths = []
# purge all loaded modules if desired by restoring initial environment
# actually running 'module purge' is futile (and wrong/broken on some systems, e.g. Cray)
if purge:
# restore initial environment if provided
if init_env is None:
raise EasyBuildError("Initial environment required when purging before loading, but not available")
else:
restore_env(init_env)
# make sure $MODULEPATH is set correctly after purging
self.check_module_path()
# extend $MODULEPATH if needed
for mod_path in mod_paths:
full_mod_path = os.path.join(install_path('mod'), build_option('suffix_modules_path'), mod_path)
if os.path.exists(full_mod_path):
self.prepend_module_path(full_mod_path)
loaded_modules = self.loaded_modules()
for mod in modules:
if allow_reload or mod not in loaded_modules:
self.run_module('load', mod)
def unload(self, modules=None):
"""
Unload all requested modules.
"""
for mod in modules:
self.run_module('unload', mod)
def purge(self):
"""
Purge loaded modules.
"""
self.log.debug("List of loaded modules before purge: %s" % os.getenv('_LMFILES_'))
self.run_module('purge')
def show(self, mod_name):
"""
Run 'module show' for the specified module.
"""
key = self.mk_module_cache_key(mod_name)
if key in MODULE_SHOW_CACHE:
ans = MODULE_SHOW_CACHE[key]
self.log.debug("Found cached result for 'module show %s' with key '%s': %s", mod_name, key, ans)
else:
ans = self.run_module('show', mod_name, check_output=False, return_stderr=True)
MODULE_SHOW_CACHE[key] = ans
self.log.debug("Cached result for 'module show %s' with key '%s': %s", mod_name, key, ans)
return ans
def get_value_from_modulefile(self, mod_name, regex, strict=True):
"""
Get info from the module file for the specified module.
:param mod_name: module name
:param regex: (compiled) regular expression, with one group
"""
value = None
if self.exist([mod_name], skip_avail=True)[0]:
modinfo = self.show(mod_name)
res = regex.search(modinfo)
if res:
value = res.group(1)
elif strict:
raise EasyBuildError("Failed to determine value from 'show' (pattern: '%s') in %s",
regex.pattern, modinfo)
elif strict:
raise EasyBuildError("Can't get value from a non-existing module %s", mod_name)
return value
def modulefile_path(self, mod_name, strip_ext=False):
"""
Get the path of the module file for the specified module
:param mod_name: module name
:param strip_ext: strip (.lua) extension from module fileame (if present)"""
# (possible relative) path is always followed by a ':', and may be prepended by whitespace
# this works for both Environment Modules and Lmod
modpath_re = re.compile(r'^\s*(?P<modpath>[^/\n]*/[^\s]+):$', re.M)
modpath = self.get_value_from_modulefile(mod_name, modpath_re)
if strip_ext and modpath.endswith('.lua'):
modpath = os.path.splitext(modpath)[0]
return modpath
def set_path_env_var(self, key, paths):
"""Set path environment variable to the given list of paths."""
setvar(key, os.pathsep.join(paths), verbose=False)
def check_module_output(self, cmd, stdout, stderr):
"""Check output of 'module' command, see if if is potentially invalid."""
self.log.debug("No checking of module output implemented for %s", self.NAME)
def compose_cmd_list(self, args, opts=None):
"""
Compose full module command to run, based on provided arguments
:param args: list of arguments for module command
:return: list of strings representing the full module command to run
"""
if opts is None:
opts = []
cmdlist = [self.cmd, 'python']
if args[0] in ('available', 'avail', 'list',):
# run these in terse mode for easier machine reading
opts.append(self.TERSE_OPTION)
# inject options at specified location
for idx, opt in opts:
args.insert(idx, opt)
# prefix if a particular shell is specified, using shell argument to Popen doesn't work (no output produced (?))
if self.COMMAND_SHELL is not None:
if not isinstance(self.COMMAND_SHELL, (list, tuple)):
raise EasyBuildError("COMMAND_SHELL needs to be list or tuple, now %s (value %s)",
type(self.COMMAND_SHELL), self.COMMAND_SHELL)
cmdlist = self.COMMAND_SHELL + cmdlist
return cmdlist + args
def run_module(self, *args, **kwargs):
"""
Run module command.
:param args: list of arguments for module command; first argument should be the subcommand to run
:param kwargs: dictionary with options that control certain aspects of how to run the module command
"""
if isinstance(args[0], (list, tuple,)):
args = args[0]
else:
args = list(args)