Repository navigation
Expand file tree
/
Copy pathcs_exec_environment.py
More file actions
2087 lines (1639 loc) · 64.7 KB
/
Copy pathcs_exec_environment.py
File metadata and controls
2087 lines (1639 loc) · 64.7 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# This file is part of code_saturne, a general-purpose CFD tool.
#
# Copyright (C) 1998-2022 EDF S.A.
#
# This program 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; either version 2 of the License, or (at your option) any later
# version.
#
# This program 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
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301, USA.
#-------------------------------------------------------------------------------
import configparser
import datetime
import fnmatch
import os
import subprocess
import sys
import platform
import tempfile
try:
from code_saturne.base import cs_batch
except Exception:
import cs_batch
saved_os_env_vars = {}
#===============================================================================
# Utility functions
#===============================================================================
def abs_exec_path(path):
"""
Find an executable in the system path.
"""
abs_path = None
if os.path.isabs(path):
return path
else:
try:
for d in os.getenv('PATH').split():
f = os.path.join(d, path)
if os.path.isfile(f):
return f
except Exception:
pass
return None
#---------------------------------------------------------------------------
def separate_args(s):
"""
Separate arguments that may contain whitespace, depending on whether
whitespace is protected or not by ", ', and \ characters.
If quotes are found after the beginning of a string, such as in
--option="string 1", do not remove them.
"""
l = []
if s:
a = ''
sep = False
protected = False
in_quotes = ''
for i, c in enumerate(s):
if protected:
a += c
protected = False
else:
if c == '\\' and s[i+1:i+1].isalnum():
protected = True
elif c == '"' or c == "'":
if in_quotes == c:
a += c
in_quotes = ''
elif in_quotes != '':
a += c
else:
a += c
in_quotes = c
elif in_quotes != '':
a += c
elif (c == ' ' or c == '\t'):
if a != '':
if (a[0] == a[-1:]) and (a[0] == '"' or a[0] == "'"):
l.append(a[1:-1])
else:
l.append(a)
a = ''
else:
a += c
if a != '':
if (a[0] == a[-1:]) and (a[0] == '"' or a[0] == "'"):
l.append(a[1:-1])
else:
l.append(a)
return l
#---------------------------------------------------------------------------
def enquote_arg(s):
"""
Add quotes around argument if it contains whitespace, leave it
unchanged otherwise; if the argument already contains unprotected
quotes, do not add any more (so for example --option="string 1"
is unchanged).
"""
if s:
if (s.find(' ') > -1):
protect = False
for i in range(len(s)):
if s[i] == '\\':
protect = not protect
if not protect and s[i] == '"':
return s
return '"' + s + '"'
else:
return s
else:
return s
#-------------------------------------------------------------------------------
def assemble_args(cmd):
"""
Assemble separate arguments.
"""
l = ''
for s in cmd:
if (s.find(' ') > -1):
l += ' ' + enquote_arg(s)
else:
l += ' ' + s
return l.strip()
#-------------------------------------------------------------------------------
# Update command line arguments with no associated value
#-------------------------------------------------------------------------------
def update_command_no_value(args, options, present):
"""
Adds, updates, or removes parts of a command to pass a given option.
The command is provided as a list, and options defining a value may be
defined as a tuple (to allow for multiple variants).
If no option was previously present and a value is added, the first
syntax of the options tuple will be used.
"""
# Update first occurence
count = 0
target = 0
if present:
target = 1
for opt in options:
j = 0
while j < len(args):
if args[j] == opt:
count += 1
if count > target:
args.pop(j) # option
else:
j += 1
else:
j += 1
if count < target:
args.append(options[0])
# Special cases at end
i = 0
args_tail = []
while i < len(args):
if args[i][0] == '$' or args[i] == '&':
a = args.pop(i)
args_tail.append(a)
else:
i = i+1
args += args_tail
# Return updated list
return args
#-------------------------------------------------------------------------------
# Update command line arguments for a given value
#-------------------------------------------------------------------------------
def update_command_single_value(args, options, value):
"""
Adds, updates, or removes parts of a command to pass a given value.
The command is provided as a list, and options defining a value may be
defined as a tuple (to allow for multiple variants).
In all cases, this function assumes the option is followed by a single
value argument.
Options and values may be defined as separate (successive) arguments,
or be separated by a '=' character when the matching option
ends with '='. To allow both syntaxes, a given option may be passed
both with and without that separator; for example:
options = ('--param=', '--param', '-p').
If no option was previously present and a value is added, the first
syntax of the options tuple will be used.
"""
i = -1
# Update first occurence
if value:
val_s = str(value)
for opt in options:
if opt[-1:] == '=':
l = len(opt)
for arg in args:
if arg[:l] == opt:
i = args.index(arg)
break
if i > -1:
args[i] = opt + val_s
else:
if args.count(opt) > 0:
i = args.index(opt)
if i+1 < len(args):
args[i+1] = val_s
else:
args.append(val_s)
i = i+1
if i > -1:
i = i + 1
break
# Append if none found
if i == -1:
opt = options[0]
if opt[-1:] == '=':
args.append(opt + val_s)
else:
args.append(opt)
args.append(val_s)
i = len(args)
# Remove excess occurences
for opt in options:
j = i
if opt[-1:] == '=':
l = len(opt)
while j < len(args):
if args[j][:l] == opt:
args.pop(j)
else:
j = j+1
else:
while j < len(args):
if args[j] == opt:
args.pop(j) # option
if j < len(args):
args.pop(j) # matching value
else:
j = j+1
# Special cases at end
i = 0
args_tail = []
while i < len(args):
if args[i][0] == '$' or args[i] == '&':
a = args.pop(i)
args_tail.append(a)
else:
i = i+1
args += args_tail
# Return updated list
return args
#-------------------------------------------------------------------------------
# Get a single value from a command line
#-------------------------------------------------------------------------------
def get_command_single_value(args, options, default=None):
"""
Obtain a value from a command line if availble, or using a default otherwise
The command is provided as a list, and options defining a value may be
defined as a tuple (to allow for multiple variants).
In all cases, this function assumes the option is followed by a single
value argument.
Options and values may be defined as separate (successive) arguments,
or be separated by a '=' character when the matching option
ands with '='. To allow both syntaxes, a given option may be pased
both with and without that separator; for example:
options = ('--param=', '--param', '-p').
"""
for opt in options:
if opt[-1:] == '=':
l = len(opt)
for arg in args:
if arg[:l] == opt:
return arg[l:]
else:
if args.count(opt) > 0:
i = args.index(opt)
if i+1 < len(args):
return args[i+1]
return default
#---------------------------------------------------------------------------
def get_shell_type():
"""
Get name of current shell if available.
(Bourne shell variants are handled, C-shell variants are not).
"""
if sys.platform.startswith('win'):
return None
user_shell = os.getenv('SHELL')
if not user_shell:
user_shell = '/bin/sh'
elif user_shell[-3:] == 'csh':
user_shell = '/bin/sh'
return user_shell
#-------------------------------------------------------------------------------
def append_shell_shebang(l):
"""
Append lines for shell shebang or '@echo off' for a Windows COMMAND.
"""
if sys.platform.startswith('win'):
l.append('@echo off')
else:
user_shell = get_shell_type()
l.append('#!' + user_shell)
l.append('')
#-------------------------------------------------------------------------------
def write_shell_shebang(fd):
"""
Write the shell shebang or '@echo off' for a Windows COMMAND.
"""
if sys.platform.startswith('win'):
fd.write('@echo off\n\n')
else:
user_shell = get_shell_type()
fd.write('#!' + user_shell + '\n\n')
#-------------------------------------------------------------------------------
def append_script_comment(l, comment):
"""
Add a comment in a script buffer list in the correct form.
(starting with a '#' for Linux shells and 'rem' for Windows COMMAND).
"""
if sys.platform.startswith('win'):
l.append('rem ' + comment)
else:
l.append('# ' + comment)
#-------------------------------------------------------------------------------
def write_script_comment(fd, comment):
"""
Write a comment in a script in the correct form.
(starting with a '#' for Linux shells and 'rem' for Windows COMMAND).
"""
if sys.platform.startswith('win'):
fd.write('rem ')
else:
fd.write('# ')
fd.write(comment)
#-------------------------------------------------------------------------------
def write_export_env(fd, var, value):
"""
Write the correct command so as to export environment variables.
"""
if not value:
value = ''
if sys.platform.startswith('win'):
export_cmd = 'set ' + var + '=' + value
else:
if get_shell_type()[-3:] == 'csh': # handle C-type shells
export_cmd = 'setenv ' + var + ' ' + value
else: # handle Bourne-type shells
if value:
export_cmd = 'export ' + var + '=' + value
else:
export_cmd = 'unset ' + var
export_cmd = export_cmd + '\n'
fd.write(export_cmd)
#-------------------------------------------------------------------------------
def prepend_path_command(var, user_path):
"""
Determine the correct command so as to export PATH-type variables.
"""
# Caution: Windows PATH must NOT must double-quoted to account for blanks
# ======= in paths, contrary to UNIX systems
if sys.platform.startswith('win'):
export_cmd = 'set ' + var + '=' + user_path + ';%' + var + '%'
else:
if get_shell_type()[-3:] == 'csh': # handle C-type shells
export_cmd = 'setenv ' + var + ' "' + user_path + '":$' + var
else: # handle Bourne-type shells
export_cmd = 'export ' + var + '="' + user_path + '":$' + var
return export_cmd
#-------------------------------------------------------------------------------
def write_prepend_path(fd, var, user_path):
"""
Write the correct command so as to export PATH-type variables.
"""
export_cmd = prepend_path_command(var, user_path) + '\n'
fd.write(export_cmd)
#-------------------------------------------------------------------------------
def write_mps_start(fd):
"""
Write MPS start code in run script.
This assumes we use an MPMD type launcher script (whether
we have multiple programs or not) so as to be able to run
rank_specific code around the main executable.
"""
fd.write("""
# Determine node-local MPI rank id
#---------------------------------
mpi_local_rank_id=-1
# For Open MPI
if [ "$OMPI_COMM_WORLD_LOCAL_RANK" != "" ]; then
mpi_local_rank_id="$OMPI_COMM_WORLD_LOCAL_RANK"
elif [ "$MPI_LOCALNRANKS" != "" ]; then
mpi_local_rank_id="$MPI_LOCALNRANKS"
fi
# start MPS
#----------
if [ "$CUDA_MPS_PIPE_DIRECTORY" = "" ]; then
export CUDA_MPS_PIPE_DIRECTORY=/dev/shm/${USER}/mps
fi
if [ "$CUDA_MPS_LOG_DIRECTORY" = "" ]; then
export CUDA_MPS_LOG_DIRECTORY=/dev/shm/${USER}/mps_log
fi
if [ $mpi_local_rank_id = 0 ]; then
if [ $MPI_RANK = 0 ]; then
echo "Starting NVIDIA MPS ..."
echo "(pipes in $CUDA_MPS_PIPE_DIRECTORY,"
echo " logs in $CUDA_MPS_LOG_DIRECTORY)"
fi
rm -rf $CUDA_MPS_PIPE_DIRECTORY
rm -rf $CUDA_MPS_LOG_DIRECTORY
mkdir -p $CUDA_MPS_PIPE_DIRECTORY
mkdir -p $CUDA_MPS_LOG_DIRECTORY
nvidia-cuda-mps-control -d
fi
# Leave a bit of time for the MPS server to start
sleep 5
""")
#-------------------------------------------------------------------------------
def write_mps_stop(fd):
"""
Write MPS stop code in run script.
This assumes we use an MPMD type launcher script (whether
we have multiple programs or not) so as to be able to run
rank_specific code around the main executable.
"""
fd.write("""
# stop MPS
#----------
if [ $mpi_local_rank_id = 0 ]; then
if [ $MPI_RANK = 0 ]; then
echo "Stopping NVIDIA MPS ..."
fi
echo "quit" | nvidia-cuda-mps-control
sleep 1
rm -rf $CUDA_MPS_PIPE_DIRECTORY
rm -rf $CUDA_MPS_LOG_DIRECTORY
fi
""")
#-------------------------------------------------------------------------------
def clean_path(path):
"""
Remove duplicates from path.
"""
# Case for a string
if type(path) == str:
if not path:
return ''
if sys.platform.startswith('win'):
s = ';'
else:
s = ':'
vals = path.split(s)
clean_path(vals)
value = ''
for v in vals:
if value:
value += s + v
else:
value = v
return value
# Case for a list
elif type(path) == list:
i = len(path) - 1
while i > -1:
if path.count(i) > 1 or not path[i]:
path.pop(i)
i -= 1
return path
#-------------------------------------------------------------------------------
def get_script_positional_args():
"""
Write the positional arguments with a newline character.
"""
if sys.platform.startswith('win'):
args = '%*'
else:
args = '"$@"'
return args
#-------------------------------------------------------------------------------
def get_script_return_code():
"""
Write the return code with a newline character.
"""
if sys.platform.startswith('win'):
ret_code = '%ERROR_LEVEL%'
else:
ret_code = '$?'
return ret_code
#-------------------------------------------------------------------------------
def clean_os_environ_for_shell():
"""
Clean environment relative to sub-shells.
"""
# In case LMOD is present, avoid warnings on macros
# for called scripts.
is_bash = False
shell = get_shell_type()
if 'bash' in shell:
is_bash = True
# In case LMOD is present, avoid warnings on macros
# for called scripts.
for ev in ('BASH_FUNC_module%%', 'BASH_FUNC_ml%%'):
if ev in os.environ:
if is_bash:
saved_os_env_vars[ev] = os.environ[ev]
del os.environ[ev]
#-------------------------------------------------------------------------------
def full_os_environ_for_shell(env=None):
"""
Return environment relative to sub-shells.
"""
if saved_os_env_vars:
if env:
s_env = env.copy()
else:
s_env = os.environ.copy()
for key in saved_os_env_vars.keys():
s_env[key] = saved_os_env_vars[key]
else:
if env:
s_env = env
else:
s_env = os.environ
return s_env
#-------------------------------------------------------------------------------
def run_command(args, pkg = None, echo = False,
stdout = sys.stdout, stderr = sys.stderr, env = None):
"""
Run a command.
"""
if echo == True:
if type(args) == str:
stdout.write(str(args) + '\n')
else:
l = ''
for s in args:
if (s.find(' ') > -1):
l += ' ' + enquote_arg(s)
else:
l += ' ' + s
stdout.write(l.strip() + '\n')
# Modify the PATH for relocatable installation: add code_saturne "bindir"
if pkg != None:
if pkg.config.features['relocatable'] == "yes":
if sys.platform.startswith("win"):
sep = ";"
else:
sep = ":"
saved_path = os.environ['PATH']
os.environ['PATH'] = pkg.get_dir('bindir') + sep + saved_path
# As a workaround for a bug in which the standard output an error
# are "lost" (observed in an apparently random manner, with Python 2.4),
# we only add the stdout and stderr keywords if they are non-default.
kwargs = {}
if (stdout != sys.stdout):
kwargs['stdout'] = stdout
if (stderr != sys.stderr):
kwargs['stderr'] = stderr
returncode = 1
try:
if type(args) == str:
p = subprocess.Popen(args,
shell=True,
executable=get_shell_type(),
universal_newlines=True,
env=full_os_environ_for_shell(env),
**kwargs)
else:
p = subprocess.Popen(args,
universal_newlines=True,
env=env,
**kwargs)
p.communicate()
returncode = p.returncode
except Exception as e:
import traceback
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=2, file=sys.stderr)
print("")
print("Failed calling subprocess with:")
print(" args = " + str(args))
print(" env = " + str(env))
print(" kwargs = " + str(kwargs))
sys.exit(1)
# Reset the PATH to its previous value
if pkg != None:
if pkg.config.features['relocatable'] == "yes":
os.environ['PATH'] = saved_path
return returncode
#-------------------------------------------------------------------------------
def get_command_output(cmd):
"""
Run a command and return it's standard output.
"""
p = subprocess.Popen(cmd,
shell=True,
executable=get_shell_type(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
output = p.communicate()
if p.returncode != 0:
sys.stderr.write(output[1] + '\n')
return ''
else:
return output[0]
#-------------------------------------------------------------------------------
def get_command_outputs(cmd):
"""
Run a command and return it's standard and error outputs.
"""
p = subprocess.Popen(cmd,
shell=True,
executable=get_shell_type(),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True)
return p.communicate()[0]
#-------------------------------------------------------------------------------
def set_modules(pkg):
"""
Set environment modules if present.
"""
if pkg.config.env_modules == "no":
return
cmd_prefix = pkg.config.env_modulecmd
cmds = ['purge']
for m in pkg.config.env_modules.strip().split():
cmds.append('load ' + m)
for cmd in cmds:
(output, error) = subprocess.Popen([cmd_prefix, 'python'] + cmd.split(),
universal_newlines=True,
stdout=subprocess.PIPE).communicate()
exec(output)
#-------------------------------------------------------------------------------
def source_shell_script(path):
"""
Source shell script.
"""
if not os.path.isfile(path):
sys.stderr.write('Warning:\n'
+ ' file ' + path + '\n'
+ 'not present, so cannot be sourced.\n\n')
if sys.platform.startswith('win'):
return
user_shell = None
# If shebang is present, try to use it.
# (TODO: handle more complex cases with env)
try:
f = open(path, 'r')
l = f.readline()
f.close()
if l[:2] == '#!':
e = l[2:].split()[0]
if e[-3:] != 'env':
user_shell = e
except Exception:
pass
if not user_shell:
user_shell = os.getenv('SHELL')
if not user_shell:
user_shell = '/bin/sh'
cmd = ['source ' + path + ' && env']
p = subprocess.Popen(cmd,
shell=True,
executable=user_shell,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
env=full_os_environ_for_shell())
output = p.communicate()[0]
for line in output.splitlines():
(key, _, value) = line.partition("=")
# For paths, cleanup (remove multiple values) first
if key[-4:] == 'PATH':
value = clean_path(value)
# Add key, value
os.environ[key] = value
# additional handling for Python path
if key == 'PYTHONPATH':
vals = value.split(':')
vals.reverse()
for v in vals:
if v:
sys.path.insert(0, v)
sys.path = clean_path(sys.path)
#-------------------------------------------------------------------------------
def get_rcfile(pkg):
"""
Get path to file rcfile in preferences file if present.
"""
config = configparser.ConfigParser()
config.read(pkg.get_configfiles())
if config.has_option('install', 'rcfile'):
rcfile = config.get('install', 'rcfile')
if not os.path.isabs(rcfile):
rcfile = '~/.' + rcfile
return rcfile
return ''
#-------------------------------------------------------------------------------
def source_rcfile(pkg):
"""
Source user environement if defined by rcfile in preferences file.
"""
rcfile = get_rcfile(pkg)
if rcfile:
source_shell_script(rcfile)
#-------------------------------------------------------------------------------
def get_ld_library_path_additions(pkg):
"""
return library search path additions.
With ELF shared libraries (Linux/Unix), We may need to add
paths to LD_LIBRARY_PATH, because if the compiler is configured
to use --enable-new-datgs,
DT_RUNPATH will be present instead of DT_RPATH in the library header,
and will have lower priority than LD_LIBRARY_PATH.
This function determines which paths should be added to
ld_library_path for safety.
"""
lib_dirs = []
ld_library_path = os.getenv('LD_LIBRARY_PATH')
if ld_library_path:
ld_library_path_dirs = ld_library_path.split(':')
for lib in pkg.config.deplibs:
if (pkg.config.libs[lib].have == True
and (not pkg.config.libs[lib].dynamic_load)):
ldflags = separate_args(pkg.config.libs[lib].flags['ldflags'])
for f in ldflags:
if f[0:2] == "-L":
d = f[2:]
if os.path.isdir(d):
if not (d in ld_library_path_dirs or d in lib_dirs):
lib_dirs.append(d)
return lib_dirs
#-------------------------------------------------------------------------------
def source_syrthes_env(pkg, verbose=True):
"""
Source SYRTHES environment
"""
# Determine SYRTHES home
syrthes_home = None
# Home based on configuration info
cfg_syrthes_home = None
config = configparser.ConfigParser()
config.read(pkg.get_configfiles())
if config.has_option('install', 'syrthes'):
cfg_syrthes_home = os.path.join(config.get('install', 'syrthes'))
if not os.path.isdir(cfg_syrthes_home):
sys.stderr.write("\nIncorrect install/syrthes entry "
+ "specified in one of:\n")
for f in pkg.get_configfiles():
sys.stderr.write(" " + f + "\n")
sys.stderr.write("Directory: '"
+ cfg_syrthes_home + "' does not exist.\n")
sys.exit(1)
cfg_syrthes_home = None
else:
syrthes_home = cfg_syrthes_home
# Home based on current environment
# Try to base Syrthes version on path used to import the syrthes module,
# for consistency with case creation parameters; it this is not enough,
# use existing environment or load one based on current configuration.
for p in sys.path:
if p[-14:] == '/share/syrthes' or p[-14:] == '\share\syrthes':
syr_profile = os.path.join(p[:-14], 'bin', 'syrthes.profile')
if os.path.isfile(syr_profile):
if verbose:
sys.stdout.write("Sourcing SYRTHES environment: " \
+ syr_profile + "\n")
try:
source_shell_script(syr_profile)
except Exception:
sys.stderr.write(" Failed sourcing SYRTHES environment.\n")
# Ensure exit from the loop once syrthes is found
break
env_syrthes_home = os.getenv('SYRTHES4_HOME')
if not env_syrthes_home:
env_syrthes_home = os.getenv('SYRTHES_HOME')
if not syrthes_home:
if verbose:
sys.stdout.write("Set syrthes_home based on SYRTHES4_HOME: " \
+ str(env_syrthes_home) + "\n")
syrthes_home = env_syrthes_home
if not syrthes_home:
sys.stderr.write("\nCannot locate SYRTHES installation.\n"
+ " Either the install/syrthes entry must be "
+ "specified in one of:\n")
for f in pkg.get_configfiles():
sys.stderr.write(" " + f + "\n")
sys.stderr.write(" or a syrthes.profile file must be sourced.\n")
sys.exit(1)
# Now source environment if not done already or different