-
Notifications
You must be signed in to change notification settings - Fork 207
/
utils.py
2676 lines (2211 loc) · 84.6 KB
/
utils.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
"""
Common functions used by cime python scripts
Warning: you cannot use CIME Classes in this module as it causes circular dependencies
"""
import shlex
import configparser
import io, logging, gzip, sys, os, time, re, shutil, glob, string, random, importlib, fnmatch
import importlib.util
import errno, signal, warnings, filecmp
import stat as statlib
from argparse import Action
from contextlib import contextmanager
# pylint: disable=deprecated-module
from distutils import file_util
# Return this error code if the scripts worked but tests failed
TESTS_FAILED_ERR_CODE = 100
logger = logging.getLogger(__name__)
# Fix to pass user defined `srcroot` to `CIME.XML.generic_xml.GenericXML`
# where it's used to resolve $SRCROOT in XML config files.
GLOBAL = {}
CASE_SUCCESS = "success"
CASE_FAILURE = "error"
def deprecate_action(message):
class ActionStoreDeprecated(Action):
def __call__(self, parser, namespace, values, option_string=None):
raise DeprecationWarning(f"{option_string} is deprecated{message}")
return ActionStoreDeprecated
def import_from_file(name, file_path):
loader = importlib.machinery.SourceFileLoader(name, file_path)
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return module
@contextmanager
def redirect_stdout(new_target):
old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
try:
yield new_target # run some code with the replaced stdout
finally:
sys.stdout = old_target # restore to the previous value
@contextmanager
def redirect_stderr(new_target):
old_target, sys.stderr = sys.stderr, new_target # replace sys.stdout
try:
yield new_target # run some code with the replaced stdout
finally:
sys.stderr = old_target # restore to the previous value
@contextmanager
def redirect_stdout_stderr(new_target):
old_stdout, old_stderr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = new_target, new_target
try:
yield new_target
finally:
sys.stdout, sys.stderr = old_stdout, old_stderr
@contextmanager
def redirect_logger(new_target, logger_name):
ch = logging.StreamHandler(stream=new_target)
ch.setLevel(logging.DEBUG)
log = logging.getLogger(logger_name)
root_log = logging.getLogger()
orig_handlers = log.handlers
orig_root_loggers = root_log.handlers
try:
root_log.handlers = []
log.handlers = [ch]
yield log
finally:
root_log.handlers = orig_root_loggers
log.handlers = orig_handlers
class IndentFormatter(logging.Formatter):
def __init__(self, indent, fmt=None, datefmt=None):
logging.Formatter.__init__(self, fmt, datefmt)
self._indent = indent
def format(self, record):
record.msg = "{}{}".format(self._indent, record.msg)
out = logging.Formatter.format(self, record)
return out
def set_logger_indent(indent):
root_log = logging.getLogger()
root_log.handlers = []
formatter = IndentFormatter(indent)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
root_log.addHandler(handler)
class EnvironmentContext(object):
"""
Context manager for environment variables
Usage:
os.environ['MYVAR'] = 'oldvalue'
with EnvironmentContex(MYVAR='myvalue', MYVAR2='myvalue2'):
print os.getenv('MYVAR') # Should print myvalue.
print os.getenv('MYVAR2') # Should print myvalue2.
print os.getenv('MYVAR') # Should print oldvalue.
print os.getenv('MYVAR2') # Should print None.
CREDIT: https://github.com/sakurai-youhei/envcontext
"""
def __init__(self, **kwargs):
self.envs = kwargs
self.old_envs = {}
def __enter__(self):
self.old_envs = {}
for k, v in self.envs.items():
self.old_envs[k] = os.environ.get(k)
os.environ[k] = v
def __exit__(self, *args):
for k, v in self.old_envs.items():
if v:
os.environ[k] = v
else:
del os.environ[k]
# This should be the go-to exception for CIME use. It's a subclass
# of SystemExit in order suppress tracebacks, which users generally
# hate seeing. It's a subclass of Exception because we want it to be
# "catchable". If you are debugging CIME and want to see the stacktrace,
# run your CIME command with the --debug flag.
class CIMEError(SystemExit, Exception):
pass
def expect(condition, error_msg, exc_type=CIMEError, error_prefix="ERROR:"):
"""
Similar to assert except doesn't generate an ugly stacktrace. Useful for
checking user error, not programming error.
>>> expect(True, "error1")
>>> expect(False, "error2") # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
CIMEError: ERROR: error2
"""
# Without this line we get a futurewarning on the use of condition below
warnings.filterwarnings("ignore")
if not condition:
if logger.isEnabledFor(logging.DEBUG):
import pdb
pdb.set_trace() # pylint: disable=forgotten-debug-statement
msg = error_prefix + " " + error_msg
raise exc_type(msg)
def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
return "".join(random.choice(chars) for _ in range(size))
def check_name(fullname, additional_chars=None, fullpath=False):
"""
check for unallowed characters in name, this routine only
checks the final name and does not check if path exists or is
writable
>>> check_name("test.id", additional_chars=".")
False
>>> check_name("case.name", fullpath=False)
True
>>> check_name("/some/file/path/case.name", fullpath=True)
True
>>> check_name("mycase+mods")
False
>>> check_name("mycase?mods")
False
>>> check_name("mycase*mods")
False
>>> check_name("/some/full/path/name/")
False
"""
chars = r"+*?<>/{}[\]~`@:"
if additional_chars is not None:
chars += additional_chars
if fullname.endswith("/"):
return False
if fullpath:
_, name = os.path.split(fullname)
else:
name = fullname
match = re.search(r"[" + re.escape(chars) + "]", name)
if match is not None:
logger.warning(
"Illegal character {} found in name {}".format(match.group(0), name)
)
return False
return True
# Should only be called from get_cime_config()
def _read_cime_config_file():
"""
READ the config file in ~/.cime, this file may contain
[main]
CIME_MODEL=e3sm,cesm,ufs
PROJECT=someprojectnumber
"""
allowed_sections = ("main", "create_test")
allowed_in_main = (
"cime_model",
"project",
"charge_account",
"srcroot",
"mail_type",
"mail_user",
"machine",
"mpilib",
"compiler",
"input_dir",
"cime_driver",
)
allowed_in_create_test = (
"mail_type",
"mail_user",
"save_timing",
"single_submit",
"test_root",
"output_root",
"baseline_root",
"clean",
"machine",
"mpilib",
"compiler",
"parallel_jobs",
"proc_pool",
"walltime",
"job_queue",
"allow_baseline_overwrite",
"wait",
"force_procs",
"force_threads",
"input_dir",
"pesfile",
"retry",
"walltime",
)
cime_config_file = os.path.abspath(
os.path.join(os.path.expanduser("~"), ".cime", "config")
)
cime_config = configparser.ConfigParser()
if os.path.isfile(cime_config_file):
cime_config.read(cime_config_file)
for section in cime_config.sections():
expect(
section in allowed_sections,
"Unknown section {} in .cime/config\nallowed sections are {}".format(
section, allowed_sections
),
)
if cime_config.has_section("main"):
for item, _ in cime_config.items("main"):
expect(
item in allowed_in_main,
'Unknown option in config section "main": "{}"\nallowed options are {}'.format(
item, allowed_in_main
),
)
if cime_config.has_section("create_test"):
for item, _ in cime_config.items("create_test"):
expect(
item in allowed_in_create_test,
'Unknown option in config section "test": "{}"\nallowed options are {}'.format(
item, allowed_in_create_test
),
)
else:
logger.debug("File {} not found".format(cime_config_file))
cime_config.add_section("main")
return cime_config
_CIMECONFIG = None
def get_cime_config():
global _CIMECONFIG
if not _CIMECONFIG:
_CIMECONFIG = _read_cime_config_file()
return _CIMECONFIG
def reset_cime_config():
"""
Useful to keep unit tests from interfering with each other
"""
global _CIMECONFIG
_CIMECONFIG = None
def copy_local_macros_to_dir(destination, extra_machdir=None):
"""
Copy any local macros files to the path given by 'destination'.
Local macros files are potentially found in:
(1) extra_machdir/cmake_macros/*.cmake
(2) $HOME/.cime/*.cmake
"""
local_macros = []
if extra_machdir:
if os.path.isdir(os.path.join(extra_machdir, "cmake_macros")):
local_macros.extend(
glob.glob(os.path.join(extra_machdir, "cmake_macros/*.cmake"))
)
dotcime = None
home = os.environ.get("HOME")
if home:
dotcime = os.path.join(home, ".cime")
if dotcime and os.path.isdir(dotcime):
local_macros.extend(glob.glob(dotcime + "/*.cmake"))
for macro in local_macros:
safe_copy(macro, destination)
def get_python_libs_location_within_cime():
"""
From within CIME, return subdirectory of python libraries
"""
return os.path.join("scripts", "lib")
def get_cime_root(case=None):
"""
Return the absolute path to the root of CIME that contains this script
"""
real_file_dir = os.path.dirname(os.path.realpath(__file__))
cimeroot = os.path.abspath(os.path.join(real_file_dir, ".."))
if case is not None:
case_cimeroot = os.path.abspath(case.get_value("CIMEROOT"))
cimeroot = os.path.abspath(cimeroot)
expect(
cimeroot == case_cimeroot,
"Inconsistent CIMEROOT variable: case -> '{}', file location -> '{}'".format(
case_cimeroot, cimeroot
),
)
logger.debug("CIMEROOT is " + cimeroot)
return cimeroot
def get_config_path():
cimeroot = get_cime_root()
return os.path.join(cimeroot, "CIME", "data", "config")
def get_schema_path():
config_path = get_config_path()
return os.path.join(config_path, "xml_schemas")
def get_template_path():
cimeroot = get_cime_root()
return os.path.join(cimeroot, "CIME", "data", "templates")
def get_tools_path():
cimeroot = get_cime_root()
return os.path.join(cimeroot, "CIME", "Tools")
def get_src_root():
"""
Return the absolute path to the root of SRCROOT.
"""
cime_config = get_cime_config()
if "SRCROOT" in os.environ:
srcroot = os.environ["SRCROOT"]
logger.debug("SRCROOT from environment: {}".format(srcroot))
elif cime_config.has_option("main", "SRCROOT"):
srcroot = cime_config.get("main", "SRCROOT")
logger.debug("SRCROOT from user config: {}".format(srcroot))
elif "SRCROOT" in GLOBAL:
srcroot = GLOBAL["SRCROOT"]
logger.debug("SRCROOT from internal GLOBAL: {}".format(srcroot))
else:
# If the share directory exists in the CIME root then it's
# assumed it's also the source root. This should only
# occur when the local "Externals.cfg" is used to install
# requirements for running/testing without a specific model.
if os.path.isdir(os.path.join(get_cime_root(), "share")):
srcroot = os.path.abspath(os.path.join(get_cime_root()))
else:
srcroot = os.path.abspath(os.path.join(get_cime_root(), ".."))
logger.debug("SRCROOT from implicit detection: {}".format(srcroot))
return srcroot
def get_cime_default_driver():
driver = os.environ.get("CIME_DRIVER")
if driver:
logger.debug("Setting CIME_DRIVER={} from environment".format(driver))
else:
cime_config = get_cime_config()
if cime_config.has_option("main", "CIME_DRIVER"):
driver = cime_config.get("main", "CIME_DRIVER")
if driver:
logger.debug(
"Setting CIME_driver={} from ~/.cime/config".format(driver)
)
from CIME.config import Config
config = Config.load_defaults()
if not driver:
driver = config.driver_default
expect(
driver in config.driver_choices,
"Attempt to set invalid driver {}".format(driver),
)
return driver
def get_all_cime_models():
config_path = get_config_path()
models = []
for entry in os.listdir(config_path):
if os.path.isdir(os.path.join(config_path, entry)):
models.append(entry)
models.remove("xml_schemas")
return models
def set_model(model):
"""
Set the model to be used in this session
"""
cime_config = get_cime_config()
cime_models = get_all_cime_models()
if not cime_config.has_section("main"):
cime_config.add_section("main")
expect(
model in cime_models,
"model {} not recognized. The acceptable values of CIME_MODEL currently are {}".format(
model, cime_models
),
)
cime_config.set("main", "CIME_MODEL", model)
def get_model():
"""
Get the currently configured model value
The CIME_MODEL env variable may or may not be set
>>> os.environ["CIME_MODEL"] = "garbage"
>>> get_model() # doctest:+ELLIPSIS +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
CIMEError: ERROR: model garbage not recognized
>>> del os.environ["CIME_MODEL"]
>>> set_model('rocky') # doctest:+ELLIPSIS +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
CIMEError: ERROR: model rocky not recognized
>>> set_model('e3sm')
>>> get_model()
'e3sm'
>>> reset_cime_config()
"""
model = os.environ.get("CIME_MODEL")
cime_models = get_all_cime_models()
if model in cime_models:
logger.debug("Setting CIME_MODEL={} from environment".format(model))
else:
expect(
model is None,
"model {} not recognized. The acceptable values of CIME_MODEL currently are {}".format(
model, cime_models
),
)
cime_config = get_cime_config()
if cime_config.has_option("main", "CIME_MODEL"):
model = cime_config.get("main", "CIME_MODEL")
if model is not None:
logger.debug("Setting CIME_MODEL={} from ~/.cime/config".format(model))
# One last try
if model is None:
srcroot = get_src_root()
if os.path.isfile(os.path.join(srcroot, "bin", "git-fleximod")):
model = "cesm"
elif os.path.isfile(os.path.join(srcroot, "Externals.cfg")):
model = "cesm"
with open(os.path.join(srcroot, "Externals.cfg")) as fd:
for line in fd:
if re.search("ufs", line):
model = "ufs"
else:
model = "e3sm"
# This message interfers with the correct operation of xmlquery
# logger.debug("Guessing CIME_MODEL={}, set environment variable if this is incorrect".format(model))
if model is not None:
set_model(model)
return model
modelroot = os.path.join(get_cime_root(), "CIME", "config")
models = os.listdir(modelroot)
msg = ".cime/config or environment variable CIME_MODEL must be set to one of: "
msg += ", ".join(
[
model
for model in models
if os.path.isdir(os.path.join(modelroot, model)) and model != "xml_schemas"
]
)
expect(False, msg)
def _get_path(filearg, from_dir):
if not filearg.startswith("/") and from_dir is not None:
filearg = os.path.join(from_dir, filearg)
return filearg
def _convert_to_fd(filearg, from_dir, mode="a"):
filearg = _get_path(filearg, from_dir)
return open(filearg, mode)
_hack = object()
def _line_defines_python_function(line, funcname):
"""Returns True if the given line defines the function 'funcname' as a top-level definition
("top-level definition" means: not something like a class method; i.e., the def should
be at the start of the line, not indented)
"""
if re.search(r"^def\s+{}\s*\(".format(funcname), line) or re.search(
r"^from\s.+\simport.*\s{}(?:,|\s|$)".format(funcname), line
):
return True
return False
def file_contains_python_function(filepath, funcname):
"""Checks whether the given file contains a top-level definition of the function 'funcname'
Returns a boolean value (True if the file contains this function definition, False otherwise)
"""
has_function = False
with open(filepath, "r") as fd:
for line in fd.readlines():
if _line_defines_python_function(line, funcname):
has_function = True
break
return has_function
def fixup_sys_path(*additional_paths):
cimeroot = get_cime_root()
if cimeroot not in sys.path or sys.path.index(cimeroot) > 0:
sys.path.insert(0, cimeroot)
tools_path = get_tools_path()
if tools_path not in sys.path or sys.path.index(tools_path) > 1:
sys.path.insert(1, tools_path)
for i, x in enumerate(additional_paths):
if x not in sys.path or sys.path.index(x) > 2 + i:
sys.path.insert(2 + i, x)
def import_and_run_sub_or_cmd(
cmd,
cmdargs,
subname,
subargs,
config_dir,
compname,
logfile=None,
case=None,
from_dir=None,
timeout=None,
):
sys_path_old = sys.path
# ensure we provide `get_src_root()` and `get_tools_path()` to sys.path
# allowing imported modules to correctly import `CIME` module or any
# tool under `CIME/Tools`.
fixup_sys_path(config_dir)
try:
mod = importlib.import_module(f"{compname}_cime_py")
getattr(mod, subname)(*subargs)
except (ModuleNotFoundError, AttributeError) as e:
# * ModuleNotFoundError if importlib can not find module,
# * AttributeError if importlib finds the module but
# {subname} is not defined in the module
expect(
os.path.isfile(cmd),
f"Could not find {subname} file for component {compname}",
)
# TODO shouldn't need to use logger.isEnabledFor for debug logging
if isinstance(e, ModuleNotFoundError) and logger.isEnabledFor(logging.DEBUG):
logger.info(
"WARNING: Could not import module '{}_cime_py'".format(compname)
)
try:
run_sub_or_cmd(
cmd, cmdargs, subname, subargs, logfile, case, from_dir, timeout
)
except Exception as e1:
raise e1 from None
except Exception:
if logfile:
with open(logfile, "a") as log_fd:
log_fd.write(str(sys.exc_info()[1]))
expect(False, "{} FAILED, cat {}".format(cmd, logfile))
else:
raise
sys.path = sys_path_old
def run_sub_or_cmd(
cmd, cmdargs, subname, subargs, logfile=None, case=None, from_dir=None, timeout=None
):
"""
This code will try to import and run each cmd as a subroutine
if that fails it will run it as a program in a seperate shell
Raises exception on failure.
"""
if file_contains_python_function(cmd, subname):
do_run_cmd = False
else:
do_run_cmd = True
if not do_run_cmd:
# ensure we provide `get_src_root()` and `get_tools_path()` to sys.path
# allowing imported modules to correctly import `CIME` module or any
# tool under `CIME/Tools`.
fixup_sys_path()
try:
mod = import_from_file(subname, cmd)
logger.info(" Calling {}".format(cmd))
# Careful: logfile code is not thread safe!
if logfile:
with open(logfile, "w") as log_fd:
with redirect_logger(log_fd, subname):
with redirect_stdout_stderr(log_fd):
getattr(mod, subname)(*subargs)
else:
getattr(mod, subname)(*subargs)
except (SyntaxError, AttributeError) as _:
pass # Need to try to run as shell command
except Exception:
if logfile:
with open(logfile, "a") as log_fd:
log_fd.write(str(sys.exc_info()[1]))
expect(False, "{} FAILED, cat {}".format(cmd, logfile))
else:
raise
else:
return # Running as python function worked, we're done
logger.info(" Running {} ".format(cmd))
if case is not None:
case.flush()
fullcmd = cmd
if isinstance(cmdargs, list):
for arg in cmdargs:
fullcmd += " " + str(arg)
else:
fullcmd += " " + cmdargs
if logfile:
fullcmd += " >& {} ".format(logfile)
stat, output, _ = run_cmd(
"{}".format(fullcmd), combine_output=True, from_dir=from_dir, timeout=timeout
)
if output: # Will be empty if logfile
logger.info(output)
if stat != 0:
if logfile:
expect(False, "{} FAILED, cat {}".format(fullcmd, logfile))
else:
expect(False, "{} FAILED, see above".format(fullcmd))
# refresh case xml object from file
if case is not None:
case.read_xml()
def run_cmd(
cmd,
input_str=None,
from_dir=None,
verbose=None,
arg_stdout=_hack,
arg_stderr=_hack,
env=None,
combine_output=False,
timeout=None,
executable=None,
shell=True,
):
"""
Wrapper around subprocess to make it much more convenient to run shell commands
>>> run_cmd('ls file_i_hope_doesnt_exist')[0] != 0
True
"""
import subprocess # Not safe to do globally, module not available in older pythons
# Real defaults for these value should be subprocess.PIPE
if arg_stdout is _hack:
arg_stdout = subprocess.PIPE
elif isinstance(arg_stdout, str):
arg_stdout = _convert_to_fd(arg_stdout, from_dir)
if arg_stderr is _hack:
arg_stderr = subprocess.STDOUT if combine_output else subprocess.PIPE
elif isinstance(arg_stderr, str):
arg_stderr = _convert_to_fd(arg_stdout, from_dir)
if verbose != False and (verbose or logger.isEnabledFor(logging.DEBUG)):
logger.info(
"RUN: {}\nFROM: {}".format(
cmd, os.getcwd() if from_dir is None else from_dir
)
)
if input_str is not None:
stdin = subprocess.PIPE
else:
stdin = None
if not shell:
cmd = shlex.split(cmd)
# ensure we have an environment to use if not being over written by parent
if env is None:
# persist current environment
env = os.environ.copy()
# Always provide these variables for anything called externally.
# `CIMEROOT` is provided for external scripts, makefiles, etc that
# may reference it. `PYTHONPATH` is provided to ensure external
# python can correctly import the CIME module and anything under
# `CIME/tools`.
#
# `get_tools_path()` is provided for backwards compatibility.
# External python prior to the CIME module move would use `CIMEROOT`
# or build a relative path and append `sys.path` to import
# `standard_script_setup`. Providing `PYTHONPATH` fixes protential
# broken paths in external python.
env.update(
{
"CIMEROOT": f"{get_cime_root()}",
"PYTHONPATH": f"{get_cime_root()}:{get_tools_path()}",
}
)
if timeout:
with Timeout(timeout):
proc = subprocess.Popen(
cmd,
shell=shell,
stdout=arg_stdout,
stderr=arg_stderr,
stdin=stdin,
cwd=from_dir,
executable=executable,
env=env,
)
output, errput = proc.communicate(input_str)
else:
proc = subprocess.Popen(
cmd,
shell=shell,
stdout=arg_stdout,
stderr=arg_stderr,
stdin=stdin,
cwd=from_dir,
executable=executable,
env=env,
)
output, errput = proc.communicate(input_str)
# In Python3, subprocess.communicate returns bytes. We want to work with strings
# as much as possible, so we convert bytes to string (which is unicode in py3) via
# decode. For python2, we do NOT want to do this since decode will yield unicode
# strings which are not necessarily compatible with the system's default base str type.
if output is not None:
try:
output = output.decode("utf-8", errors="ignore")
except AttributeError:
pass
if errput is not None:
try:
errput = errput.decode("utf-8", errors="ignore")
except AttributeError:
pass
# Always strip outputs
if output:
output = output.strip()
if errput:
errput = errput.strip()
stat = proc.wait()
if isinstance(arg_stdout, io.IOBase):
arg_stdout.close() # pylint: disable=no-member
if isinstance(arg_stderr, io.IOBase) and arg_stderr is not arg_stdout:
arg_stderr.close() # pylint: disable=no-member
if verbose != False and (verbose or logger.isEnabledFor(logging.DEBUG)):
if stat != 0:
logger.info(" stat: {:d}\n".format(stat))
if output:
logger.info(" output: {}\n".format(output))
if errput:
logger.info(" errput: {}\n".format(errput))
return stat, output, errput
def run_cmd_no_fail(
cmd,
input_str=None,
from_dir=None,
verbose=None,
arg_stdout=_hack,
arg_stderr=_hack,
env=None,
combine_output=False,
timeout=None,
executable=None,
):
"""
Wrapper around subprocess to make it much more convenient to run shell commands.
Expects command to work. Just returns output string.
>>> run_cmd_no_fail('echo foo') == 'foo'
True
>>> run_cmd_no_fail('echo THE ERROR >&2; false') # doctest:+ELLIPSIS +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
CIMEError: ERROR: Command: 'echo THE ERROR >&2; false' failed with error ...
>>> run_cmd_no_fail('grep foo', input_str=b'foo') == 'foo'
True
>>> run_cmd_no_fail('echo THE ERROR >&2', combine_output=True) == 'THE ERROR'
True
"""
stat, output, errput = run_cmd(
cmd,
input_str,
from_dir,
verbose,
arg_stdout,
arg_stderr,
env,
combine_output,
executable=executable,
timeout=timeout,
)
if stat != 0:
# If command produced no errput, put output in the exception since we
# have nothing else to go on.
errput = output if not errput else errput
if errput is None:
if combine_output:
if isinstance(arg_stdout, str):
errput = "See {}".format(_get_path(arg_stdout, from_dir))
else:
errput = ""
elif isinstance(arg_stderr, str):
errput = "See {}".format(_get_path(arg_stderr, from_dir))
else:
errput = ""
expect(
False,
"Command: '{}' failed with error '{}' from dir '{}'".format(
cmd, errput, os.getcwd() if from_dir is None else from_dir
),
)
return output
def normalize_case_id(case_id):
"""
Given a case_id, return it in form TESTCASE.GRID.COMPSET.PLATFORM
>>> normalize_case_id('ERT.ne16_g37.B1850C5.sandiatoss3_intel')
'ERT.ne16_g37.B1850C5.sandiatoss3_intel'
>>> normalize_case_id('ERT.ne16_g37.B1850C5.sandiatoss3_intel.test-mod')
'ERT.ne16_g37.B1850C5.sandiatoss3_intel.test-mod'
>>> normalize_case_id('ERT.ne16_g37.B1850C5.sandiatoss3_intel.G.20151121')
'ERT.ne16_g37.B1850C5.sandiatoss3_intel'
>>> normalize_case_id('ERT.ne16_g37.B1850C5.sandiatoss3_intel.test-mod.G.20151121')
'ERT.ne16_g37.B1850C5.sandiatoss3_intel.test-mod'
"""
sep_count = case_id.count(".")
expect(
sep_count >= 3 and sep_count <= 6,
"Case '{}' needs to be in form: TESTCASE.GRID.COMPSET.PLATFORM[.TESTMOD] or TESTCASE.GRID.COMPSET.PLATFORM[.TESTMOD].GC.TESTID".format(
case_id
),
)
if sep_count in [5, 6]:
return ".".join(case_id.split(".")[:-2])
else:
return case_id
def parse_test_name(test_name):
"""
Given a CIME test name TESTCASE[_CASEOPTS].GRID.COMPSET[.MACHINE_COMPILER[.TESTMODS]],
return each component of the testname with machine and compiler split.
Do not error if a partial testname is provided (TESTCASE or TESTCASE.GRID) instead
parse and return the partial results.
TESTMODS use hyphens in a special way:
- A single hyphen stands for a path separator (for example, 'test-mods' resolves to
the path 'test/mods')
- A double hyphen separates multiple test mods (for example, 'test-mods--other-dir-path'
indicates two test mods: 'test/mods' and 'other/dir/path')
If there are one or more TESTMODS, then the testmods component of the result will be a