forked from easybuilders/easybuild-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfiletools.py
More file actions
3199 lines (2623 loc) · 128 KB
/
Copy pathfiletools.py
File metadata and controls
3199 lines (2623 loc) · 128 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-2025 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/>.
# #
"""
Set of file tools.
Authors:
* Stijn De Weirdt (Ghent University)
* Dries Verdegem (Ghent University)
* Kenneth Hoste (Ghent University)
* Pieter De Baets (Ghent University)
* Jens Timmerman (Ghent University)
* Toon Willems (Ghent University)
* Ward Poelmans (Ghent University)
* Fotis Georgatos (Uni.Lu, NTUA)
* Sotiris Fragkiskos (NTUA, CERN)
* Davide Vanzo (ACCRE, Vanderbilt University)
* Damian Alvarez (Forschungszentrum Juelich GmbH)
* Maxime Boissonneault (Compute Canada)
"""
import datetime
import difflib
import filecmp
import glob
import hashlib
import inspect
import itertools
import os
import pathlib
import platform
import re
import shutil
import signal
import stat
import ssl
import sys
import tarfile
import tempfile
import time
import zlib
from functools import partial
from html.parser import HTMLParser
import urllib.request as std_urllib
from easybuild.base import fancylogger
from easybuild.tools import LooseVersion
# import build_log must stay, to use of EasyBuildLog
from easybuild.tools.build_log import EasyBuildError, EasyBuildExit, CWD_NOTFOUND_ERROR
from easybuild.tools.build_log import dry_run_msg, print_msg, print_warning
from easybuild.tools.config import DEFAULT_DOWNLOAD_INITIAL_WAIT_TIME, DEFAULT_DOWNLOAD_MAX_ATTEMPTS
from easybuild.tools.config import ERROR, GENERIC_EASYBLOCK_PKG, IGNORE, WARN, build_option, install_path
from easybuild.tools.output import PROGRESS_BAR_DOWNLOAD_ONE, start_progress_bar, stop_progress_bar, update_progress_bar
from easybuild.tools.hooks import load_source
from easybuild.tools.run import run_shell_cmd
from easybuild.tools.utilities import natural_keys, nub, remove_unwanted_chars, trace_msg
try:
import requests
HAVE_REQUESTS = True
except ImportError:
HAVE_REQUESTS = False
_log = fancylogger.getLogger('filetools', fname=False)
# 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_",
}
PATH_INDEX_FILENAME = '.eb-path-index'
CHECKSUM_TYPE_MD5 = 'md5'
CHECKSUM_TYPE_SHA256 = 'sha256'
DEFAULT_CHECKSUM = CHECKSUM_TYPE_SHA256
def _hashlib_md5():
"""
Wrapper function for hashlib.md5,
to set usedforsecurity to False when supported (Python >= 3.9)
"""
kwargs = {}
if sys.version_info >= (3, 9):
kwargs = {'usedforsecurity': False}
return hashlib.md5(**kwargs)
# map of checksum types to checksum functions
CHECKSUM_FUNCTIONS = {
'adler32': lambda p: calc_block_checksum(p, ZlibChecksum(zlib.adler32)),
'crc32': lambda p: calc_block_checksum(p, ZlibChecksum(zlib.crc32)),
CHECKSUM_TYPE_MD5: lambda p: calc_block_checksum(p, _hashlib_md5()),
'sha1': lambda p: calc_block_checksum(p, hashlib.sha1()),
CHECKSUM_TYPE_SHA256: lambda p: calc_block_checksum(p, hashlib.sha256()),
'sha512': lambda p: calc_block_checksum(p, hashlib.sha512()),
'size': lambda p: os.path.getsize(p),
}
CHECKSUM_TYPES = sorted(CHECKSUM_FUNCTIONS.keys())
EXTRACT_CMDS = {
# gzipped or gzipped tarball
'.gtgz': "tar xzf %(filepath)s",
'.gz': "gunzip -c %(filepath)s > %(target)s",
'.tar.gz': "tar xzf %(filepath)s",
'.tgz': "tar xzf %(filepath)s",
# bzipped or bzipped tarball
'.bz2': "bunzip2 -c %(filepath)s > %(target)s",
'.tar.bz2': "tar xjf %(filepath)s",
'.tb2': "tar xjf %(filepath)s",
'.tbz': "tar xjf %(filepath)s",
'.tbz2': "tar xjf %(filepath)s",
# xzipped or xzipped tarball;
# need to make sure that $TAPE is not set to avoid 'tar x' command failing,
# see https://github.com/easybuilders/easybuild-framework/issues/3652
'.tar.xz': "unset TAPE; unxz %(filepath)s --stdout | tar x",
'.txz': "unset TAPE; unxz %(filepath)s --stdout | tar x",
'.xz': "unxz %(filepath)s",
# tarball
'.tar': "tar xf %(filepath)s",
# zip file
'.zip': "unzip -qq %(filepath)s",
# iso file
'.iso': "7z x %(filepath)s",
# tar.Z: using compress (LZW), but can be handled with gzip so use 'z'
'.tar.z': "tar xzf %(filepath)s",
# shell scripts don't need to be unpacked, just copy there
'.sh': "cp -dR %(filepath)s .",
}
ZIPPED_PATCH_EXTS = ('.bz2', '.gz', '.xz')
# global set of names of locks that were created in this session
global_lock_names = set()
class ZlibChecksum:
"""
wrapper class for adler32 and crc32 checksums to
match the interface of the hashlib module
"""
def __init__(self, algorithm):
self.algorithm = algorithm
self.checksum = algorithm(b'') # use the same starting point as the module
self.blocksize = 64 # The same as md5/sha1
def update(self, data):
"""Calculates a new checksum using the old one and the new data"""
self.checksum = self.algorithm(data, self.checksum)
def hexdigest(self):
"""Return hex string of the checksum"""
return '0x%s' % (self.checksum & 0xffffffff)
def is_readable(path):
"""Return whether file at specified location exists and is readable."""
try:
return os.path.exists(path) and os.access(path, os.R_OK)
except OSError as err:
raise EasyBuildError("Failed to check whether %s is readable: %s", path, err)
def open_file(path, mode):
"""Open a (usually) text file. If mode is not binary, then utf-8 encoding will be used"""
# This is required for text files in Python 3, especially until Python 3.7 which implements PEP 540.
# This PEP opens files in UTF-8 mode if the C locale is used, see https://www.python.org/dev/peps/pep-0540
if 'b' not in mode:
return open(path, mode, encoding='utf-8')
else:
return open(path, mode)
def read_file(path, log_error=True, mode='r'):
"""Read contents of file at given path, in a robust way."""
txt = None
try:
with open_file(path, mode) as handle:
txt = handle.read()
except IOError as err:
if log_error:
raise EasyBuildError("Failed to read %s: %s", path, err)
return txt
def write_file(path, data, append=False, forced=False, backup=False, always_overwrite=True, verbose=False,
show_progress=False, size=None):
"""
Write given contents to file at given path;
overwrites current file contents without backup by default!
:param path: location of file
:param data: contents to write to file. Can be a file-like object of binary data
:param append: append to existing file rather than overwrite
:param forced: force actually writing file in (extended) dry run mode
:param backup: back up existing file before overwriting or modifying it
:param always_overwrite: don't require --force to overwrite an existing file
:param verbose: be verbose, i.e. inform where backup file was created
:param show_progress: show progress bar while writing file
:param size: size (in bytes) of data to write (used for progress bar)
"""
# early exit in 'dry run' mode
if not forced and build_option('extended_dry_run'):
dry_run_msg("file written: %s" % path, silent=build_option('silent'))
return
if os.path.exists(path):
if not append:
if always_overwrite or build_option('force'):
_log.info("Overwriting existing file %s", path)
else:
raise EasyBuildError("File exists, not overwriting it without --force: %s", path)
if backup:
backed_up_fp = back_up_file(path)
_log.info("Existing file %s backed up to %s", path, backed_up_fp)
if verbose:
print_msg("Backup of %s created at %s" % (path, backed_up_fp), silent=build_option('silent'))
# figure out mode to use for open file handle
# cfr. https://docs.python.org/3/library/functions.html#open
mode = 'a' if append else 'w'
data_is_file_obj = hasattr(data, 'read')
# special care must be taken with binary data
if isinstance(data, bytes) or data_is_file_obj:
mode += 'b'
# don't bother showing a progress bar for small files (< 10MB)
if size and size < 10 * (1024 ** 2):
_log.info("Not showing progress bar for downloading small file (size %s)", size)
show_progress = False
if show_progress:
start_progress_bar(PROGRESS_BAR_DOWNLOAD_ONE, size, label=os.path.basename(path))
# note: we can't use try-except-finally, because Python 2.4 doesn't support it as a single block
try:
mkdir(os.path.dirname(path), parents=True)
with open_file(path, mode) as fh:
if data_is_file_obj:
# if a file-like object was provided, read file in 1MB chunks
for chunk in iter(partial(data.read, 1024 ** 2), b''):
fh.write(chunk)
if show_progress:
update_progress_bar(PROGRESS_BAR_DOWNLOAD_ONE, progress_size=len(chunk))
else:
fh.write(data)
if show_progress:
stop_progress_bar(PROGRESS_BAR_DOWNLOAD_ONE)
except IOError as err:
raise EasyBuildError("Failed to write to %s: %s", path, err)
def is_binary(contents):
"""
Check whether given bytestring represents the contents of a binary file or not.
"""
return isinstance(contents, bytes) and b'\00' in bytes(contents)
def resolve_path(path):
"""
Return fully resolved path for given path.
:param path: path that (maybe) contains symlinks
"""
try:
resolved_path = os.path.realpath(path)
except (AttributeError, OSError, TypeError) as err:
raise EasyBuildError("Resolving path %s failed: %s", path, err)
return resolved_path
def symlink(source_path, symlink_path, use_abspath_source=True):
"""
Create a symlink at the specified path to the given path.
:param source_path: source file path
:param symlink_path: symlink file path
:param use_abspath_source: resolves the absolute path of source_path
"""
if use_abspath_source:
source_path = os.path.abspath(source_path)
if os.path.exists(symlink_path):
abs_source_path = os.path.abspath(source_path)
symlink_target_path = os.path.abspath(os.readlink(symlink_path))
if abs_source_path != symlink_target_path:
raise EasyBuildError("Trying to symlink %s to %s, but the symlink already exists and points to %s.",
source_path, symlink_path, symlink_target_path)
_log.info("Skipping symlinking %s to %s, link already exists", source_path, symlink_path)
else:
try:
os.symlink(source_path, symlink_path)
_log.info("Symlinked %s to %s", source_path, symlink_path)
except OSError as err:
raise EasyBuildError("Symlinking %s to %s failed: %s", source_path, symlink_path, err)
def remove_file(path):
"""Remove file at specified path."""
# early exit in 'dry run' mode
if build_option('extended_dry_run'):
dry_run_msg("file %s removed" % path, silent=build_option('silent'))
return
try:
# note: file may also be a broken symlink...
if os.path.exists(path) or os.path.islink(path):
os.remove(path)
except OSError as err:
raise EasyBuildError("Failed to remove file %s: %s", path, err)
def remove_dir(path):
"""Remove directory at specified path."""
# early exit in 'dry run' mode
if build_option('extended_dry_run'):
dry_run_msg("directory %s removed" % path, silent=build_option('silent'))
return
if os.path.exists(path):
ok = False
errors = []
# Try multiple times to cater for temporary failures on e.g. NFS mounted paths
max_attempts = 3
for i in range(0, max_attempts):
try:
shutil.rmtree(path)
ok = True
break
except OSError as err:
_log.debug("Failed to remove path %s with shutil.rmtree at attempt %d: %s" % (path, i, err))
errors.append(err)
time.sleep(2)
# make sure write permissions are enabled on entire directory
adjust_permissions(path, stat.S_IWUSR, add=True, recursive=True)
if ok:
_log.info("Path %s successfully removed." % path)
else:
raise EasyBuildError("Failed to remove directory %s even after %d attempts.\nReasons: %s",
path, max_attempts, errors)
def remove(paths):
"""
Remove single file/directory or list of files and directories
:param paths: path(s) to remove
"""
if isinstance(paths, str):
paths = [paths]
_log.info("Removing %d files & directories", len(paths))
for path in paths:
if os.path.isfile(path):
remove_file(path)
elif os.path.isdir(path):
remove_dir(path)
else:
raise EasyBuildError("Specified path to remove is not an existing file or directory: %s", path)
def get_cwd(must_exist=True):
"""
Retrieve current working directory
"""
try:
cwd = os.getcwd()
except FileNotFoundError as err:
if must_exist is True:
raise EasyBuildError(CWD_NOTFOUND_ERROR)
_log.debug("Failed to determine current working directory, but proceeding anyway: %s", err)
cwd = None
return cwd
def change_dir(path):
"""
Change to directory at specified location.
:param path: location to change to
:return: previous location we were in
"""
# determine origin working directory: can fail if non-existent
prev_dir = get_cwd(must_exist=False)
try:
os.chdir(path)
except OSError as err:
raise EasyBuildError("Failed to change from %s to %s: %s", prev_dir, path, err)
# determine final working directory: must exist
# stoplight meant to catch filesystems in a faulty state
get_cwd()
return prev_dir
def extract_file(fn, dest, cmd=None, extra_options=None, overwrite=False, forced=False, change_into_dir=False,
trace=True):
"""
Extract file at given path to specified directory
:param fn: path to file to extract
:param dest: location to extract to
:param cmd: extract command to use (derived from filename if not specified)
:param extra_options: extra options to pass to extract command
:param overwrite: overwrite existing unpacked file
:param forced: force extraction in (extended) dry run mode
:param change_into_dir: change into resulting directorys
:param trace: produce trace output for extract command being run
:return: path to directory (in case of success)
"""
if not os.path.isfile(fn) and not build_option('extended_dry_run'):
raise EasyBuildError(f"Can't extract file {fn}: no such file")
mkdir(dest, parents=True)
# use absolute pathnames from now on
abs_dest = os.path.abspath(dest)
# change working directory
_log.debug(f"Unpacking {fn} in directory {abs_dest}")
cwd = change_dir(abs_dest)
if cmd:
# complete command template with filename
cmd = cmd % fn
_log.debug(f"Using specified command to unpack {fn}: {cmd}")
else:
cmd = extract_cmd(fn, overwrite=overwrite)
_log.debug(f"Using command derived from file extension to unpack {fn}: {cmd}")
if not cmd:
raise EasyBuildError(f"Can't extract file {fn} with unknown filetype")
if extra_options:
cmd = f"{cmd} {extra_options}"
run_shell_cmd(cmd, in_dry_run=forced, hidden=not trace)
# note: find_base_dir also changes into the base dir!
base_dir = find_base_dir()
# if changing into obtained directory is not desired,
# change back to where we came from (unless that was a non-existing directory)
if not change_into_dir:
if cwd is None:
raise EasyBuildError(f"Can't change back to non-existing directory after extracting {fn} in {dest}")
else:
change_dir(cwd)
return base_dir
def which(cmd, retain_all=False, check_perms=True, log_ok=True, on_error=WARN):
"""
Return (first) path in $PATH for specified command, or None if command is not found
:param retain_all: returns *all* locations to the specified command in $PATH, not just the first one
:param check_perms: check whether candidate path has read/exec permissions before accepting it as a match
:param log_ok: Log an info message where the command has been found (if any)
:param on_error: What to do if the command was not found, default: WARN. Possible values: IGNORE, WARN, ERROR
"""
if on_error not in (IGNORE, WARN, ERROR):
raise EasyBuildError("Invalid value for 'on_error': %s", on_error)
if retain_all:
res = []
else:
res = None
paths = os.environ.get('PATH', '').split(os.pathsep)
for path in paths:
cmd_path = os.path.join(path, cmd)
# only accept path if command is there
if os.path.isfile(cmd_path):
if log_ok:
_log.info("Command %s found at %s", cmd, cmd_path)
if check_perms:
# check if read/executable permissions are available
if not os.access(cmd_path, os.R_OK | os.X_OK):
_log.info("No read/exec permissions for %s, so continuing search...", cmd_path)
continue
if retain_all:
res.append(cmd_path)
else:
res = cmd_path
break
if not res and on_error != IGNORE:
msg = "Could not find command '%s' (with permissions to read/execute it) in $PATH (%s)" % (cmd, paths)
if on_error == WARN:
_log.warning(msg)
else:
raise EasyBuildError(msg)
return res
def det_common_path_prefix(paths):
"""Determine common path prefix for a given list of paths."""
if not isinstance(paths, list):
raise EasyBuildError("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 normalize_path(path):
"""Normalize path removing empty and dot components.
Similar to os.path.normpath but does not resolve '..' which may return a wrong path when symlinks are used
"""
# In POSIX 3 or more leading slashes are equivalent to 1
if path.startswith(os.path.sep):
if path.startswith(os.path.sep * 2) and not path.startswith(os.path.sep * 3):
start_slashes = os.path.sep * 2
else:
start_slashes = os.path.sep
else:
start_slashes = ''
filtered_comps = (comp for comp in path.split(os.path.sep) if comp and comp != '.')
return start_slashes + os.path.sep.join(filtered_comps)
def is_parent_path(path1, path2):
"""
Return True if path1 is a prefix of path2
:param path1: absolute or relative path
:param path2: absolute or relative path
"""
path1 = os.path.realpath(path1)
path2 = os.path.realpath(path2)
common_path = os.path.commonprefix([path1, path2])
return common_path == path1
def is_alt_pypi_url(url):
"""Determine whether specified URL is already an alternative PyPI URL, i.e. whether it contains a hash."""
# example: .../packages/5b/03/e135b19fadeb9b1ccb45eac9f60ca2dc3afe72d099f6bd84e03cb131f9bf/easybuild-2.7.0.tar.gz
alt_url_regex = re.compile('/packages/[a-f0-9]{2}/[a-f0-9]{2}/[a-f0-9]{60}/[^/]+$')
res = bool(alt_url_regex.search(url))
_log.debug("Checking whether '%s' is an alternative PyPI URL using pattern '%s'...: %s",
url, alt_url_regex.pattern, res)
return res
def pypi_source_urls(pkg_name):
"""
Fetch list of source URLs (incl. source filename) for specified Python package from PyPI, using 'simple' PyPI API.
"""
# example: https://pypi.python.org/simple/easybuild
# see also:
# - https://www.python.org/dev/peps/pep-0503/
# - https://wiki.python.org/moin/PyPISimple
simple_url = 'https://pypi.python.org/simple/%s' % re.sub(r'[-_.]+', '-', pkg_name.lower())
tmpdir = tempfile.mkdtemp()
urls_html = os.path.join(tmpdir, '%s_urls.html' % pkg_name)
if download_file(os.path.basename(urls_html), simple_url, urls_html) is None:
_log.debug("Failed to download %s to determine available PyPI URLs for %s", simple_url, pkg_name)
res = []
else:
urls_txt = read_file(urls_html)
res = []
# note: don't use xml.etree.ElementTree to parse HTML page served by PyPI's simple API
# cfr. https://github.com/pypa/warehouse/issues/7886
class HrefHTMLParser(HTMLParser):
"""HTML parser to extract 'href' attribute values from anchor tags (<a href='...'>)."""
def handle_starttag(self, tag, attrs):
if tag == 'a':
attrs = dict(attrs)
if 'href' in attrs:
res.append(attrs['href'])
parser = HrefHTMLParser()
parser.feed(urls_txt)
# links are relative, transform them into full URLs; for example:
# from: ../../packages/<dir1>/<dir2>/<hash>/easybuild-<version>.tar.gz#md5=<md5>
# to: https://pypi.python.org/packages/<dir1>/<dir2>/<hash>/easybuild-<version>.tar.gz#md5=<md5>
res = [re.sub('.*/packages/', 'https://pypi.python.org/packages/', x) for x in res]
return res
def derive_alt_pypi_url(url):
"""Derive alternative PyPI URL for given URL."""
alt_pypi_url = None
# example input URL: https://pypi.python.org/packages/source/e/easybuild/easybuild-2.7.0.tar.gz
pkg_name, pkg_source = url.strip().split('/')[-2:]
cand_urls = pypi_source_urls(pkg_name)
# md5 for old PyPI, sha256 for new PyPi (Warehouse)
regex = re.compile('.*/%s(?:#md5=[a-f0-9]{32}|#sha256=[a-f0-9]{64})$' % pkg_source.replace('.', '\\.'), re.M)
for cand_url in cand_urls:
res = regex.match(cand_url)
if res:
# e.g.: https://pypi.python.org/packages/<dir1>/<dir2>/<hash>/easybuild-<version>.tar.gz#md5=<md5>
alt_pypi_url = res.group(0).split('#sha256')[0].split('#md5')[0]
break
if not alt_pypi_url:
_log.debug("Failed to extract hash using pattern '%s' from list of URLs: %s", regex.pattern, cand_urls)
return alt_pypi_url
def parse_http_header_fields_urlpat(arg, urlpat=None, header=None, urlpat_headers_collection=None, maxdepth=3):
"""
Recurse into multi-line string "[URLPAT::][HEADER:]FILE|FIELD" where FILE may be another such string or file
containing lines matching the same format, such as "^https://www.example.com::/path/to/headers.txt", and flatten
the result to dict e.g. {'^https://www.example.com': ['Authorization: Basic token', 'User-Agent: Special Agent']}
"""
if urlpat_headers_collection is None:
# this function call is not a recursive call
urlpat_headers = {}
else:
# copy existing header data to avoid modifying it
urlpat_headers = urlpat_headers_collection.copy()
# stop infinite recursion that might happen if a file.txt refers to itself
if maxdepth < 0:
raise EasyBuildError("Failed to parse_http_header_fields_urlpat (recursion limit)")
if not isinstance(arg, str):
raise EasyBuildError("Failed to parse_http_header_fields_urlpat (argument not a string)")
# HTTP header fields are separated by CRLF but splitting on LF is more convenient
for argline in arg.split('\n'):
argline = argline.strip() # remove optional whitespace (e.g. remaining CR)
if argline == '' or '#' in argline[0]:
continue # permit comment lines: ignore them
if os.path.isfile(os.path.join(get_cwd(), argline)):
# expand existing relative path to absolute
argline = os.path.join(os.path.join(get_cwd(), argline))
if os.path.isfile(argline):
# argline is a file path, so read that instead
_log.debug('File included in parse_http_header_fields_urlpat: %s' % argline)
argline = read_file(argline)
urlpat_headers = parse_http_header_fields_urlpat(argline, urlpat, header, urlpat_headers, maxdepth - 1)
continue
# URL pattern is separated by '::' from a HTTP header field
if '::' in argline:
[urlpat, argline] = argline.split('::', 1) # get the urlpat
# the remainder may be another parseable argument, recurse with same depth
urlpat_headers = parse_http_header_fields_urlpat(argline, urlpat, header, urlpat_headers, maxdepth)
continue
# Header field has format HEADER: FIELD, and FIELD may be another parseable argument
# except if FIELD contains colons, then argline is the final HEADER: FIELD to be returned
if ':' in argline and argline.count(':') == 1:
[argheader, argline] = argline.split(':', 1) # get the header and the remainder
# the remainder may be another parseable argument, recurse with same depth
# note that argheader would be forgotten in favor of the urlpat_headers returned by recursion,
# so pass on the header for reconstruction just in case there was nothing to recurse in
urlpat_headers = parse_http_header_fields_urlpat(argline, urlpat, argheader, urlpat_headers, maxdepth)
continue
if header is not None:
# parent caller didn't want to forget about the header, reconstruct as recursion stops here.
argline = header.strip() + ':' + argline
if urlpat is not None:
if urlpat in urlpat_headers.keys():
urlpat_headers[urlpat].append(argline) # add headers to the list
else:
urlpat_headers[urlpat] = list([argline]) # new list headers for this urlpat
else:
_log.warning("Non-empty argument to http-header-fields-urlpat ignored (missing URL pattern)")
# return a dict full of {urlpat: [list, of, headers]}
return urlpat_headers
def det_file_size(http_header):
"""
Determine size of file from provided HTTP header info (without downloading it).
"""
res = None
len_key = 'Content-Length'
if len_key in http_header:
size = http_header[len_key]
try:
res = int(size)
except (ValueError, TypeError) as err:
_log.warning("Failed to interpret size '%s' as integer value: %s", size, err)
return res
def download_file(filename, url, path, forced=False, trace=True, max_attempts=None, initial_wait_time=None):
"""
Download a file from the given URL, to the specified path.
:param filename: name of file to download
:param url: URL of file to download
:param path: path to download file to
:param forced: boolean to indicate whether force should be used to write the file
:param trace: boolean to indicate whether trace output should be printed
:param max_attempts: max. number of attempts to download file from specified URL
:param initial_wait_time: wait time (in seconds) after first attempt (doubled at each attempt)
"""
if max_attempts is None:
max_attempts = DEFAULT_DOWNLOAD_MAX_ATTEMPTS
if initial_wait_time is None:
initial_wait_time = DEFAULT_DOWNLOAD_INITIAL_WAIT_TIME
insecure = build_option('insecure_download')
_log.debug("Trying to download %s from %s to %s", filename, url, path)
timeout = build_option('download_timeout')
_log.debug("Using timeout of %s seconds for initiating download" % timeout)
# parse option HTTP header fields for URLs containing a pattern
http_header_fields_urlpat = build_option('http_header_fields_urlpat')
# compile a dict full of {urlpat: [header, list]}
urlpat_headers = dict()
if http_header_fields_urlpat is not None:
# there may be multiple options given, parse them all, while updating urlpat_headers
for arg in http_header_fields_urlpat:
urlpat_headers.update(parse_http_header_fields_urlpat(arg))
# make sure directory exists
basedir = os.path.dirname(path)
mkdir(basedir, parents=True)
# try downloading, three times max.
downloaded = False
attempt_cnt = 0
# use custom HTTP header
headers = {'User-Agent': 'EasyBuild', 'Accept': '*/*'}
# permit additional or override headers via http_headers_fields_urlpat option
# only append/override HTTP header fields that match current url
if urlpat_headers is not None:
for urlpatkey, http_header_fields in urlpat_headers.items():
if re.search(urlpatkey, url):
extraheaders = dict(hf.split(':', 1) for hf in http_header_fields)
for key, val in extraheaders.items():
headers[key] = val
_log.debug("Custom HTTP header field set: %s (value omitted from log)", key)
# for backward compatibility, and to avoid relying on 3rd party Python library 'requests'
url_req = std_urllib.Request(url, headers=headers)
used_urllib = std_urllib
switch_to_requests = False
wait = False
wait_time = initial_wait_time
while not downloaded and attempt_cnt < max_attempts:
attempt_cnt += 1
try:
if insecure:
print_warning("Not checking server certificates while downloading %s from %s." % (filename, url))
if used_urllib is std_urllib:
# urllib2 (Python 2) / urllib.request (Python 3) does the right thing for http proxy setups,
# urllib does not!
if insecure:
url_fd = std_urllib.urlopen(url_req, timeout=timeout, context=ssl._create_unverified_context())
else:
url_fd = std_urllib.urlopen(url_req, timeout=timeout)
status_code = url_fd.getcode()
size = det_file_size(url_fd.info())
else:
response = requests.get(url, headers=headers, stream=True, timeout=timeout, verify=(not insecure))
status_code = response.status_code
response.raise_for_status()
size = det_file_size(response.headers)
url_fd = response.raw
url_fd.decode_content = True
_log.debug("HTTP response code for given url %s: %s", url, status_code)
_log.info("File size for %s: %s", url, size)
# note: we pass the file object to write_file rather than reading the file first,
# to ensure the data is read in chunks (which prevents problems in Python 3.9+);
# cfr. https://github.com/easybuilders/easybuild-framework/issues/3455
# and https://bugs.python.org/issue42853
write_file(path, url_fd, forced=forced, backup=True, show_progress=True, size=size)
_log.info("Downloaded file %s from url %s to %s", filename, url, path)
downloaded = True
url_fd.close()
except used_urllib.HTTPError as err:
if used_urllib is std_urllib:
status_code = err.code
if status_code == 403 and attempt_cnt == 1:
switch_to_requests = True
elif status_code == 429: # too many requests
_log.warning(f"Downloading of {url} failed with HTTP status code 429 (Too many requests)")
wait = True
elif 400 <= status_code <= 499:
_log.warning("URL %s was not found (HTTP response code %s), not trying again" % (url, status_code))
break
else:
_log.warning("HTTPError occurred while trying to download %s to %s: %s" % (url, path, err))
except IOError as err:
_log.warning("IOError occurred while trying to download %s to %s: %s" % (url, path, err))
error_re = re.compile(r"<urlopen error \[Errno 1\] _ssl.c:.*: error:.*:"
"SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure>")
if error_re.match(str(err)):
switch_to_requests = True
except Exception as err:
raise EasyBuildError(
"Unexpected error occurred when trying to download %s to %s: %s", url, path, err,
exit_code=EasyBuildExit.FAIL_DOWNLOAD
)
if not downloaded and attempt_cnt < max_attempts:
_log.info("Attempt %d of downloading %s to %s failed, trying again..." % (attempt_cnt, url, path))
if used_urllib is std_urllib and switch_to_requests:
if not HAVE_REQUESTS:
raise EasyBuildError("SSL issues with urllib2. If you are using RHEL/CentOS 6.x please "
"install the python-requests and pyOpenSSL RPM packages and try again.")
_log.info("Downloading using requests package instead of urllib2")
used_urllib = requests
if wait:
_log.info(f"Waiting for {wait_time} seconds before trying download of {url} again...")
time.sleep(wait_time)
# exponential backoff
wait_time *= 2
if downloaded:
_log.info("Successful download of file %s from url %s to path %s" % (filename, url, path))
if trace:
trace_msg("download succeeded: %s" % url)
return path
else:
_log.warning("Download of %s to %s failed, done trying" % (url, path))
if trace:
trace_msg("download failed: %s" % url)
return None
def create_index(path, ignore_dirs=None):
"""
Create index for files in specified path.
"""
if ignore_dirs is None:
ignore_dirs = []
index = set()
if not os.path.exists(path):
raise EasyBuildError("Specified path does not exist: %s", path)
elif not os.path.isdir(path):
raise EasyBuildError("Specified path is not a directory: %s", path)
for (dirpath, dirnames, filenames) in os.walk(path, topdown=True, followlinks=True):
for filename in filenames:
# use relative paths in index
rel_dirpath = os.path.relpath(dirpath, path)
# avoid that relative paths start with './'
if rel_dirpath == '.':
rel_dirpath = ''
index.add(os.path.join(rel_dirpath, filename))
# do not consider (certain) hidden directories
# note: we still need to consider e.g., .local !
# replace list elements using [:], so os.walk doesn't process deleted directories
# see https://stackoverflow.com/questions/13454164/os-walk-without-hidden-folders
dirnames[:] = [d for d in dirnames if d not in ignore_dirs]
return index
def dump_index(path, max_age_sec=None):
"""
Create index for files in specified path, and dump it to file (alphabetically sorted).
"""
if max_age_sec is None:
max_age_sec = build_option('index_max_age')
index_fp = os.path.join(path, PATH_INDEX_FILENAME)
index_contents = create_index(path)
curr_ts = datetime.datetime.now()
if max_age_sec == 0:
end_ts = datetime.datetime.max
else:
end_ts = curr_ts + datetime.timedelta(0, max_age_sec)
lines = [
"# created at: %s" % str(curr_ts),
"# valid until: %s" % str(end_ts),
]
lines.extend(sorted(index_contents))
write_file(index_fp, '\n'.join(lines), always_overwrite=False)
return index_fp
def load_index(path, ignore_dirs=None):
"""
Load index for specified path, and return contents (or None if no index exists).
"""
if ignore_dirs is None:
ignore_dirs = []
index_fp = os.path.join(path, PATH_INDEX_FILENAME)
index = set()
if build_option('ignore_index'):
_log.info("Ignoring index for %s...", path)