forked from easybuilders/easybuild-framework
-
Notifications
You must be signed in to change notification settings - Fork 1
/
filetools.py
1148 lines (966 loc) · 38.1 KB
/
filetools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##
# Copyright 2009-2013 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://vscentrum.be/nl/en),
# the Hercules foundation (http://www.herculesstichting.be/in_English)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# http://github.com/hpcugent/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/>.
##
"""
Set of file tools.
@author: Stijn De Weirdt (Ghent University)
@author: Dries Verdegem (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Pieter De Baets (Ghent University)
@author: Jens Timmerman (Ghent University)
@author: Toon Willems (Ghent University)
"""
import binascii
import errno
import os
import re
import shutil
import signal
import stat
import subprocess
import tempfile
import time
import urllib
import zlib
from vsc import fancylogger
from vsc.utils.missing import all
import easybuild.tools.build_log # @UnusedImport (required to get an EasyBuildLog object from fancylogger.getLogger)
import easybuild.tools.environment as env
from easybuild.tools.asyncprocess import Popen, PIPE, STDOUT
from easybuild.tools.asyncprocess import send_all, recv_some
_log = fancylogger.getLogger('filetools', fname=False)
errorsFoundInLog = 0
# constants for strictness levels
IGNORE = 'ignore'
WARN = 'warn'
ERROR = 'error'
# default strictness level
strictness = WARN
# easyblock class prefix
EASYBLOCK_CLASS_PREFIX = 'EB_'
# character map for encoding strings
STRING_ENCODING_CHARMAP = {
r' ': "_space_",
r'!': "_exclamation_",
r'"': "_quotation_",
r'#': "_hash_",
r'$': "_dollar_",
r'%': "_percent_",
r'&': "_ampersand_",
r'(': "_leftparen_",
r')': "_rightparen_",
r'*': "_asterisk_",
r'+': "_plus_",
r',': "_comma_",
r'-': "_minus_",
r'.': "_period_",
r'/': "_slash_",
r':': "_colon_",
r';': "_semicolon_",
r'<': "_lessthan_",
r'=': "_equals_",
r'>': "_greaterthan_",
r'?': "_question_",
r'@': "_atsign_",
r'[': "_leftbracket_",
r'\'': "_apostrophe_",
r'\\': "_backslash_",
r']': "_rightbracket_",
r'^': "_circumflex_",
r'_': "_underscore_",
r'`': "_backquote_",
r'{': "_leftcurly_",
r'|': "_verticalbar_",
r'}': "_rightcurly_",
r'~': "_tilde_",
}
# default checksum for source and patch files
DEFAULT_CHECKSUM = 'md5'
# map of checksum types to checksum functions
CHECKSUM_FUNCTIONS = {
'adler32': lambda p: '0x%s' % zlib.adler32(open(p, 'r').read()),
'crc32': lambda p: '0x%s' % binascii.crc32(open(p, 'r').read()),
'size': lambda p: os.path.getsize(p),
}
try:
# preferred over md5/sha modules, but only available in Python 2.5 and more recent
import hashlib
CHECKSUM_FUNCTIONS['md5'] = lambda p: hashlib.md5(open(p, 'r').read()).hexdigest()
CHECKSUM_FUNCTIONS['sha1'] = lambda p: hashlib.sha1(open(p, 'r').read()).hexdigest()
except ImportError:
import md5, sha
CHECKSUM_FUNCTIONS['md5'] = lambda p: md5.md5(open(p, 'r').read()).hexdigest()
CHECKSUM_FUNCTIONS['sha1'] = lambda p: sha.sha(open(p, 'r').read()).hexdigest()
def read_file(path, log_error=True):
"""Read contents of file at given path, in a robust way."""
f = None
# note: we can't use try-except-finally, because Python 2.4 doesn't support it as a single block
try:
f = open(path, 'r')
txt = f.read()
f.close()
return txt
except IOError, err:
# make sure file handle is always closed
if f is not None:
f.close()
if log_error:
_log.error("Failed to read %s: %s" % (path, err))
else:
return None
def write_file(path, txt):
"""Write given contents to file at given path (overwrites current file contents!)."""
f = None
# note: we can't use try-except-finally, because Python 2.4 doesn't support it as a single block
try:
f = open(path, 'w')
f.write(txt)
f.close()
except IOError, err:
# make sure file handle is always closed
if f is not None:
f.close()
_log.error("Failed to write to %s: %s" % (path, err))
def extract_file(fn, dest, cmd=None, extra_options=None, overwrite=False):
"""
Given filename fn, try to extract in directory dest
- returns the directory name in case of success
"""
if not os.path.isfile(fn):
_log.error("Can't extract file %s: no such file" % fn)
if not os.path.isdir(dest):
## try to create it
try:
os.makedirs(dest)
except OSError, err:
_log.exception("Can't extract file %s: directory %s can't be created: %err " % (fn, dest, err))
## use absolute pathnames from now on
absDest = os.path.abspath(dest)
## change working directory
try:
_log.debug("Unpacking %s in directory %s." % (fn, absDest))
os.chdir(absDest)
except OSError, err:
_log.error("Can't change to directory %s: %s" % (absDest, err))
if not cmd:
cmd = extract_cmd(fn, overwrite=overwrite)
else:
# complete command template with filename
cmd = cmd % fn
if not cmd:
_log.error("Can't extract file %s with unknown filetype" % fn)
if extra_options:
cmd = "%s %s" % (cmd, extra_options)
run_cmd(cmd, simple=True)
return find_base_dir()
def which(cmd):
"""Return (first) path in $PATH for specified command, or None if command is not found."""
paths = os.environ.get('PATH', '').split(os.pathsep)
for path in paths:
cmd_path = os.path.join(path, cmd)
# only accept path is command is there, and both readable and executable
if os.access(cmd_path, os.R_OK | os.X_OK):
_log.info("Command %s found at %s" % (cmd, cmd_path))
return cmd_path
_log.warning("Could not find command '%s' (with permissions to read/execute it) in $PATH (%s)" % (cmd, paths))
return None
def det_common_path_prefix(paths):
"""Determine common path prefix for a given list of paths."""
if not isinstance(paths, list):
_log.error("det_common_path_prefix: argument must be of type list (got %s: %s)" % (type(paths), paths))
elif not paths:
return None
# initial guess for common prefix
prefix = paths[0]
found_common = False
while not found_common and prefix != os.path.dirname(prefix):
prefix = os.path.dirname(prefix)
found_common = all([p.startswith(prefix) for p in paths])
if found_common:
# prefix may be empty string for relative paths with a non-common prefix
return prefix.rstrip(os.path.sep) or None
else:
return None
def download_file(filename, url, path):
"""Download a file from the given URL, to the specified path."""
_log.debug("Downloading %s from %s to %s" % (filename, url, path))
# make sure directory exists
basedir = os.path.dirname(path)
if not os.path.exists(basedir):
os.makedirs(basedir)
downloaded = False
attempt_cnt = 0
# try downloading three times max.
while not downloaded and attempt_cnt < 3:
(_, httpmsg) = urllib.urlretrieve(url, path)
if httpmsg.type == "text/html" and not filename.endswith('.html'):
_log.warning("HTML file downloaded but not expecting it, so assuming invalid download.")
_log.debug("removing downloaded file %s from %s" % (filename, path))
try:
os.remove(path)
except OSError, err:
_log.error("Failed to remove downloaded file:" % err)
else:
_log.info("Downloading file %s from url %s: done" % (filename, url))
downloaded = True
return path
attempt_cnt += 1
_log.warning("Downloading failed at attempt %s, retrying..." % attempt_cnt)
# failed to download after multiple attempts
return None
def compute_checksum(path, checksum_type=DEFAULT_CHECKSUM):
"""
Compute checksum of specified file.
@param path: Path of file to compute checksum for
@param checksum_type: Type of checksum ('adler32', 'crc32', 'md5' (default), 'sha1', 'size')
"""
if not checksum_type in CHECKSUM_FUNCTIONS:
_log.error("Unknown checksum type (%s), supported types are: %s" % (checksum_type, CHECKSUM_FUNCTIONS.keys()))
try:
checksum = CHECKSUM_FUNCTIONS[checksum_type](path)
except IOError, err:
_log.error("Failed to read %s: %s" % (path, err))
except MemoryError, err:
_log.warning("A memory error occured when computing the checksum for %s: %s" % (path, err))
checksum = 'dummy_checksum_due_to_memory_error'
return checksum
def verify_checksum(path, checksums):
"""
Verify checksum of specified file.
@param file: path of file to verify checksum of
@param checksum: checksum value (and type, optionally, default is MD5), e.g., 'af314', ('sha', '5ec1b')
"""
# if no checksum is provided, pretend checksum to be valid
if checksums is None:
return True
# make sure we have a list of checksums
if not isinstance(checksums, list):
checksums = [checksums]
for checksum in checksums:
if isinstance(checksum, basestring):
# default checksum type unless otherwise specified is MD5 (most common(?))
typ = DEFAULT_CHECKSUM
elif isinstance(checksum, tuple) and len(checksum) == 2:
typ, checksum = checksum
else:
_log.error("Invalid checksum spec '%s', should be a string (MD5) or 2-tuple (type, value)." % checksum)
actual_checksum = compute_checksum(path, typ)
_log.debug("Computed %s checksum for %s: %s (correct checksum: %s)" % (typ, path, actual_checksum, checksum))
if actual_checksum != checksum:
return False
# if we land here, all checksums have been verified to be correct
return True
def find_base_dir():
"""
Try to locate a possible new base directory
- this is typically a single subdir, e.g. from untarring a tarball
- when extracting multiple tarballs in the same directory,
expect only the first one to give the correct path
"""
def get_local_dirs_purged():
## e.g. always purge the log directory
ignoreDirs = ["easybuild"]
lst = os.listdir(os.getcwd())
for ignDir in ignoreDirs:
if ignDir in lst:
lst.remove(ignDir)
return lst
lst = get_local_dirs_purged()
new_dir = os.getcwd()
while len(lst) == 1:
new_dir = os.path.join(os.getcwd(), lst[0])
if not os.path.isdir(new_dir):
break
try:
os.chdir(new_dir)
except OSError, err:
_log.exception("Changing to dir %s from current dir %s failed: %s" % (new_dir, os.getcwd(), err))
lst = get_local_dirs_purged()
# make sure it's a directory, and not a (single) file that was in a tarball for example
while not os.path.isdir(new_dir):
new_dir = os.path.dirname(new_dir)
_log.debug("Last dir list %s" % lst)
_log.debug("Possible new dir %s found" % new_dir)
return new_dir
def extract_cmd(fn, overwrite=False):
"""
Determines the file type of file fn, returns extract cmd
- based on file suffix
- better to use Python magic?
"""
ff = [x.lower() for x in fn.split('.')]
ftype = None
# gzipped or gzipped tarball
if ff[-1] in ['gz']:
ftype = 'gunzip %s'
if ff[-2] in ['tar']:
ftype = 'tar xzf %s'
if ff[-1] in ['tgz', 'gtgz']:
ftype = 'tar xzf %s'
# bzipped or bzipped tarball
if ff[-1] in ['bz2']:
ftype = 'bunzip2 %s'
if ff[-2] in ['tar']:
ftype = 'tar xjf %s'
if ff[-1] in ['tbz', 'tbz2', 'tb2']:
ftype = 'tar xjf %s'
# xzipped or xzipped tarball
if ff[-1] in ['xz']:
ftype = 'unxz %s'
if ff[-2] in ['tar']:
ftype = 'unxz %s --stdout | tar x'
if ff[-1] in ['txz']:
ftype = 'unxz %s --stdout | tar x'
# tarball
if ff[-1] in ['tar']:
ftype = 'tar xf %s'
# zip file
if ff[-1] in ['zip']:
if overwrite:
ftype = 'unzip -qq -o %s'
else:
ftype = 'unzip -qq %s'
if not ftype:
_log.error('Unknown file type from file %s (%s)' % (fn, ff))
return ftype % fn
def apply_patch(patchFile, dest, fn=None, copy=False, level=None):
"""
Apply a patch to source code in directory dest
- assume unified diff created with "diff -ru old new"
"""
if not os.path.isfile(patchFile):
_log.error("Can't find patch %s: no such file" % patchFile)
return
if fn and not os.path.isfile(fn):
_log.error("Can't patch file %s: no such file" % fn)
return
if not os.path.isdir(dest):
_log.error("Can't patch directory %s: no such directory" % dest)
return
## copy missing files
if copy:
try:
shutil.copy2(patchFile, dest)
_log.debug("Copied patch %s to dir %s" % (patchFile, dest))
return 'ok'
except IOError, err:
_log.error("Failed to copy %s to dir %s: %s" % (patchFile, dest, err))
return
## use absolute paths
apatch = os.path.abspath(patchFile)
adest = os.path.abspath(dest)
try:
os.chdir(adest)
_log.debug("Changing to directory %s" % adest)
except OSError, err:
_log.error("Can't change to directory %s: %s" % (adest, err))
return
if not level:
# Guess p level
# - based on +++ lines
# - first +++ line that matches an existing file determines guessed level
# - we will try to match that level from current directory
patchreg = re.compile(r"^\s*\+\+\+\s+(?P<file>\S+)")
try:
f = open(apatch)
txt = "ok"
plusLines = []
while txt:
txt = f.readline()
found = patchreg.search(txt)
if found:
plusLines.append(found)
f.close()
except IOError, err:
_log.error("Can't read patch %s: %s" % (apatch, err))
return
if not plusLines:
_log.error("Can't guess patchlevel from patch %s: no testfile line found in patch" % apatch)
return
p = None
for line in plusLines:
## locate file by stripping of /
f = line.group('file')
tf2 = f.split('/')
n = len(tf2)
plusFound = False
i = None
for i in range(n):
if os.path.isfile('/'.join(tf2[i:])):
plusFound = True
break
if plusFound:
p = i
break
else:
_log.debug('No match found for %s, trying next +++ line of patch file...' % f)
if p == None: # p can also be zero, so don't use "not p"
## no match
_log.error("Can't determine patch level for patch %s from directory %s" % (patchFile, adest))
else:
_log.debug("Guessed patch level %d for patch %s" % (p, patchFile))
else:
p = level
_log.debug("Using specified patch level %d for patch %s" % (level, patchFile))
patchCmd = "patch -b -p%d -i %s" % (p, apatch)
result = run_cmd(patchCmd, simple=True)
if not result:
_log.error("Patching with patch %s failed" % patchFile)
return
return result
def adjust_cmd(func):
"""Make adjustments to given command, if required."""
def inner(cmd, *args, **kwargs):
# SuSE hack
# - profile is not resourced, and functions (e.g. module) is not inherited
if 'PROFILEREAD' in os.environ and (len(os.environ['PROFILEREAD']) > 0):
filepaths = ['/etc/profile.d/modules.sh']
extra = ''
for fp in filepaths:
if os.path.exists(fp):
extra = ". %s &&%s" % (fp, extra)
else:
_log.warning("Can't find file %s" % fp)
cmd = "%s %s" % (extra, cmd)
return func(cmd, *args, **kwargs)
return inner
@adjust_cmd
def run_cmd(cmd, log_ok=True, log_all=False, simple=False, inp=None, regexp=True, log_output=False, path=None):
"""
Executes a command cmd
- returns exitcode and stdout+stderr (mixed)
- no input though stdin
- if log_ok or log_all are set -> will log.error if non-zero exit-code
- if simple is True -> instead of returning a tuple (output, ec) it will just return True or False signifying succes
- inp is the input given to the command
- regexp -> Regex used to check the output for errors. If True will use default (see parselogForError)
- if log_output is True -> all output of command will be logged to a tempfile
- path is the path run_cmd should chdir to before doing anything
"""
try:
if path:
os.chdir(path)
_log.debug("run_cmd: running cmd %s (in %s)" % (cmd, os.getcwd()))
except:
_log.info("running cmd %s in non-existing directory, might fail!" % cmd)
## Log command output
if log_output:
runLog = tempfile.NamedTemporaryFile(suffix='.log', prefix='easybuild-run_cmd-')
_log.debug('run_cmd: Command output will be logged to %s' % runLog.name)
runLog.write(cmd + "\n\n")
else:
runLog = None
readSize = 1024 * 8
try:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
stdin=subprocess.PIPE, close_fds=True, executable="/bin/bash")
except OSError, err:
_log.error("run_cmd init cmd %s failed:%s" % (cmd, err))
if inp:
p.stdin.write(inp)
p.stdin.close()
ec = p.poll()
stdouterr = ''
while ec < 0:
# need to read from time to time.
# - otherwise the stdout/stderr buffer gets filled and it all stops working
output = p.stdout.read(readSize)
if runLog:
runLog.write(output)
stdouterr += output
ec = p.poll()
# read remaining data (all of it)
stdouterr += p.stdout.read()
# not needed anymore. subprocess does this correct?
# ec=os.WEXITSTATUS(ec)
## Command log output
if log_output:
runLog.close()
return parse_cmd_output(cmd, stdouterr, ec, simple, log_all, log_ok, regexp)
@adjust_cmd
def run_cmd_qa(cmd, qa, no_qa=None, log_ok=True, log_all=False, simple=False, regexp=True, std_qa=None, path=None):
"""
Executes a command cmd
- looks for questions and tries to answer based on qa dictionary
- returns exitcode and stdout+stderr (mixed)
- no input though stdin
- if log_ok or log_all are set -> will log.error if non-zero exit-code
- if simple is True -> instead of returning a tuple (output, ec) it will just return True or False signifying succes
- regexp -> Regex used to check the output for errors. If True will use default (see parselogForError)
- if log_output is True -> all output of command will be logged to a tempfile
- path is the path run_cmd should chdir to before doing anything
"""
try:
if path:
os.chdir(path)
_log.debug("run_cmd_qa: running cmd %s (in %s)" % (cmd, os.getcwd()))
except:
_log.info("running cmd %s in non-existing directory, might fail!" % cmd)
# Part 1: process the QandA dictionary
# given initial set of Q and A (in dict), return dict of reg. exp. and A
#
# make regular expression that matches the string with
# - replace whitespace
# - replace newline
def escape_special(string):
return re.sub(r"([\+\?\(\)\[\]\*\.\\\$])" , r"\\\1", string)
split = '[\s\n]+'
regSplit = re.compile(r"" + split)
def process_QA(q, a):
splitq = [escape_special(x) for x in regSplit.split(q)]
regQtxt = split.join(splitq) + split.rstrip('+') + "*$"
## add optional split at the end
if not a.endswith('\n'):
a += '\n'
regQ = re.compile(r"" + regQtxt)
if regQ.search(q):
return (a, regQ)
else:
_log.error("runqanda: Question %s converted in %s does not match itself" % (q, regQtxt))
newQA = {}
_log.debug("newQA: ")
for question, answer in qa.items():
(a, regQ) = process_QA(question, answer)
newQA[regQ] = a
_log.debug("newqa[%s]: %s" % (regQ.pattern, a))
newstdQA = {}
if std_qa:
for question, answer in std_qa.items():
regQ = re.compile(r"" + question + r"[\s\n]*$")
if not answer.endswith('\n'):
answer += '\n'
newstdQA[regQ] = answer
_log.debug("newstdQA[%s]: %s" % (regQ.pattern, answer))
new_no_qa = []
if no_qa:
# simple statements, can contain wildcards
new_no_qa = [re.compile(r"" + x + r"[\s\n]*$") for x in no_qa]
_log.debug("New noQandA list is: %s" % [x.pattern for x in new_no_qa])
# Part 2: Run the command and answer questions
# - this needs asynchronous stdout
## Log command output
if log_all:
try:
runLog = tempfile.NamedTemporaryFile(suffix='.log', prefix='easybuild-cmdqa-')
_log.debug('run_cmd_qa: Command output will be logged to %s' % runLog.name)
runLog.write(cmd + "\n\n")
except IOError, err:
_log.error("Opening log file for Q&A failed: %s" % err)
else:
runLog = None
maxHitCount = 50
try:
p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, stdin=PIPE, close_fds=True, executable="/bin/bash")
except OSError, err:
_log.error("run_cmd_qa init cmd %s failed:%s" % (cmd, err))
ec = p.poll()
stdoutErr = ''
oldLenOut = -1
hitCount = 0
while ec < 0:
# need to read from time to time.
# - otherwise the stdout/stderr buffer gets filled and it all stops working
try:
tmpOut = recv_some(p)
if runLog:
runLog.write(tmpOut)
stdoutErr += tmpOut
# recv_some may throw Exception
except (IOError, Exception), err:
_log.debug("run_cmd_qa cmd %s: read failed: %s" % (cmd, err))
tmpOut = None
hit = False
for q, a in newQA.items():
res = q.search(stdoutErr)
if tmpOut and res:
fa = a % res.groupdict()
_log.debug("run_cmd_qa answer %s question %s out %s" % (fa, q.pattern, stdoutErr[-50:]))
send_all(p, fa)
hit = True
break
if not hit:
for q, a in newstdQA.items():
res = q.search(stdoutErr)
if tmpOut and res:
fa = a % res.groupdict()
_log.debug("run_cmd_qa answer %s standard question %s out %s" % (fa, q.pattern, stdoutErr[-50:]))
send_all(p, fa)
hit = True
break
if not hit:
if len(stdoutErr) > oldLenOut:
oldLenOut = len(stdoutErr)
else:
noqa = False
for r in new_no_qa:
if r.search(stdoutErr):
_log.debug("runqanda: noQandA found for out %s" % stdoutErr[-50:])
noqa = True
if not noqa:
hitCount += 1
else:
hitCount = 0
else:
hitCount = 0
if hitCount > maxHitCount:
# explicitly kill the child process before exiting
try:
os.killpg(p.pid, signal.SIGKILL)
os.kill(p.pid, signal.SIGKILL)
except OSError, err:
_log.debug("run_cmd_qa exception caught when killing child process: %s" % err)
_log.debug("run_cmd_qa: full stdouterr: %s" % stdoutErr)
_log.error("run_cmd_qa: cmd %s : Max nohits %s reached: end of output %s" % (cmd,
maxHitCount,
stdoutErr[-500:]
))
# the sleep below is required to avoid exiting on unknown 'questions' too early (see above)
time.sleep(1)
ec = p.poll()
# Process stopped. Read all remaining data
try:
if p.stdout:
readTxt = p.stdout.read()
stdoutErr += readTxt
if runLog:
runLog.write(readTxt)
except IOError, err:
_log.debug("runqanda cmd %s: remaining data read failed: %s" % (cmd, err))
# Not needed anymore. Subprocess does this correct?
# ec=os.WEXITSTATUS(ec)
return parse_cmd_output(cmd, stdoutErr, ec, simple, log_all, log_ok, regexp)
def parse_cmd_output(cmd, stdouterr, ec, simple, log_all, log_ok, regexp):
"""
will parse and perform error checks based on strictness setting
"""
if strictness == IGNORE:
check_ec = False
use_regexp = False
elif strictness == WARN:
check_ec = True
use_regexp = False
elif strictness == ERROR:
check_ec = True
use_regexp = True
else:
_log.error("invalid strictness setting: %s" % strictness)
# allow for overriding the regexp setting
if not regexp:
use_regexp = False
if ec and (log_all or log_ok):
# We don't want to error if the user doesn't care
if check_ec:
_log.error('cmd "%s" exited with exitcode %s and output:\n%s' % (cmd, ec, stdouterr))
else:
_log.warn('cmd "%s" exited with exitcode %s and output:\n%s' % (cmd, ec, stdouterr))
if not ec:
if log_all:
_log.info('cmd "%s" exited with exitcode %s and output:\n%s' % (cmd, ec, stdouterr))
else:
_log.debug('cmd "%s" exited with exitcode %s and output:\n%s' % (cmd, ec, stdouterr))
# parse the stdout/stderr for errors when strictness dictates this or when regexp is passed in
if use_regexp or regexp:
res = parse_log_for_error(stdouterr, regexp, msg="Command used: %s" % cmd)
if len(res) > 0:
message = "Found %s errors in command output (output: %s)" % (len(res), ", ".join([r[0] for r in res]))
if use_regexp:
_log.error(message)
else:
_log.warn(message)
if simple:
if ec:
# If the user does not care -> will return true
return not check_ec
else:
return True
else:
# Because we are not running in simple mode, we return the output and ec to the user
return (stdouterr, ec)
def modify_env(old, new):
"""
Compares 2 os.environ dumps. Adapts final environment.
"""
_log.deprecated("moved modify_env to tools.environment", "2.0")
return env.modify_env(old, new)
def convert_name(name, upper=False):
"""
Converts name so it can be used as variable name
"""
## no regexps
charmap = {
'+':'plus',
'-':'min'
}
for ch, new in charmap.items():
name = name.replace(ch, new)
if upper:
return name.upper()
else:
return name
def parse_log_for_error(txt, regExp=None, stdout=True, msg=None):
"""
txt is multiline string.
- in memory
regExp is a one-line regular expression
- default
"""
global errorsFoundInLog
if regExp and type(regExp) == bool:
regExp = r"(?<![(,-]|\w)(?:error|segmentation fault|failed)(?![(,-]|\.?\w)"
_log.debug('Using default regular expression: %s' % regExp)
elif type(regExp) == str:
pass
else:
_log.error("parselogForError no valid regExp used: %s" % regExp)
reg = re.compile(regExp, re.I)
res = []
for l in txt.split('\n'):
r = reg.search(l)
if r:
res.append([l, r.groups()])
errorsFoundInLog += 1
if stdout and res:
if msg:
_log.info("parseLogError msg: %s" % msg)
_log.info("parseLogError (some may be harmless) regExp %s found:\n%s" % (regExp,
'\n'.join([x[0] for x in res])
))
return res
def adjust_permissions(name, permissionBits, add=True, onlyfiles=False, onlydirs=False, recursive=True,
group_id=None, relative=True, ignore_errors=False):
"""
Add or remove (if add is False) permissionBits from all files (if onlydirs is False)
and directories (if onlyfiles is False) in path
"""
name = os.path.abspath(name)
if recursive:
_log.info("Adjusting permissions recursively for %s" % name)
allpaths = [name]
for root, dirs, files in os.walk(name):
paths = []
if not onlydirs:
paths += files
if not onlyfiles:
paths += dirs
for path in paths:
allpaths.append(os.path.join(root, path))
else:
_log.info("Adjusting permissions for %s" % name)
allpaths = [name]
failed_paths = []
fail_cnt = 0
for path in allpaths:
try:
if relative:
# relative permissions (add or remove)
perms = os.stat(path)[stat.ST_MODE]
if add:
os.chmod(path, perms | permissionBits)
else:
os.chmod(path, perms & ~permissionBits)
else:
# hard permissions bits (not relative)
os.chmod(path, permissionBits)
if group_id:
# only change the group id if it the current gid is different from what we want
cur_gid = os.stat(path).st_gid
if not cur_gid == group_id:
_log.debug("Changing group id of %s to %s" % (path, group_id))
os.chown(path, -1, group_id)
else:
_log.debug("Group id of %s is already OK (%s)" % (path, group_id))
except OSError, err:
if ignore_errors:
# ignore errors while adjusting permissions (for example caused by bad links)
_log.info("Failed to chmod/chown %s (but ignoring it): %s" % (path, err))
fail_cnt += 1
else:
failed_paths.append(path)
if failed_paths:
_log.error("Failed to chmod/chown several paths: %s (last error: %s)" % (failed_paths, err))
# we ignore some errors, but if there are to many, something is definitely wrong
fail_ratio = fail_cnt / float(len(allpaths))
max_fail_ratio = 0.5
if fail_ratio > max_fail_ratio:
_log.error("%.2f%% of permissions/owner operations failed (more than %.2f%%), something must be wrong..." % \
(100*fail_ratio, 100*max_fail_ratio))
elif fail_cnt > 0:
_log.debug("%.2f%% of permissions/owner operations failed, ignoring that..." % (100*fail_ratio))
def patch_perl_script_autoflush(path):
# patch Perl script to enable autoflush,
# so that e.g. run_cmd_qa receives all output to answer questions
txt = read_file(path)
origpath = "%s.eb.orig" % path
write_file(origpath, txt)
_log.debug("Patching Perl script %s for autoflush, original script copied to %s" % (path, origpath))
# force autoflush for Perl print buffer
lines = txt.split('\n')
newtxt = '\n'.join([
lines[0], # shebang line
"\nuse IO::Handle qw();",
"STDOUT->autoflush(1);\n", # extra newline to separate from actual script
] + lines[1:])
write_file(path, newtxt)
def mkdir(directory, parents=False):
"""
Create a directory
Directory is the path to create
When parents is True then no error if directory already exists
and make parent directories as needed (cfr. mkdir -p)
"""
if parents:
try:
os.makedirs(directory)
_log.debug("Succesfully created directory %s and needed parents" % directory)
except OSError, err:
if err.errno == errno.EEXIST: