-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfslinstaller.py
2838 lines (2232 loc) · 94.2 KB
/
fslinstaller.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
#!/usr/bin/env python
#
# SHBASECOPYRIGHT
#
# FSL installer script.
#
"""This is the FSL installation script, which can be used to install FSL.
This script must:
- be able to be executed with Python 2.7 or newer.
- be able to be executed in a "vanilla" Python environment, with no third
party dependencies.
- be self-contained, with no dependencies on any other modules (apart from
the Python standard library).
- be importable as a Python module - this script contains functions and
classes that may be used by other scripts.
"""
from __future__ import print_function, division, unicode_literals
import functools as ft
import os.path as op
import subprocess as sp
import textwrap as tw
import argparse
import contextlib
import datetime
import fnmatch
import getpass
import glob
import hashlib
import json
import logging
import os
import platform
import pwd
import readline
import shlex
import shutil
import ssl
import sys
import tempfile
import threading
import time
import traceback
try:
import urllib.request as urlrequest
except ImportError:
import urllib
import urllib2 as urlrequest
urlrequest.pathname2url = urllib.pathname2url
try: import urllib.parse as urlparse
except ImportError: import urlparse
try: import queue
except ImportError: import Queue as queue
PYVER = sys.version_info[:2]
log = logging.getLogger(__name__)
# this sometimes gets set to fslinstaller.pyc, so rstrip c
__absfile__ = op.abspath(__file__).rstrip('c')
__version__ = '3.8.2'
"""Installer script version number. This must be updated
whenever a new version of the installer script is released.
"""
DEFAULT_INSTALLATION_DIRECTORY = op.join(op.expanduser('~'), 'fsl')
"""Default FSL installation directory. """
DEFAULT_ROOT_INSTALLATION_DIRECTORY = '/usr/local/fsl/'
"""Default FSL installation directory when the installer is run as root. """
FSL_RELEASE_MANIFEST = 'https://fsl.fmrib.ox.ac.uk/fsldownloads/' \
'fslconda/releases/manifest.json'
"""URL to download the FSL installer manifest file from. The installer
manifest file is a JSON file which contains information about available FSL
versions.
See the download_manifest function, and an example manifest file
in test/data/manifest.json, for more details.
A custom manifest URL can be specified with the -a/--manifest command-line
option.
"""
FSL_DEV_RELEASES = 'https://fsl.fmrib.ox.ac.uk/fsldownloads/' \
'fslconda/releases/devreleases.txt'
"""URL to the devreleases.txt file, which contains a list of available
internal/development FSL releases. See the download_dev_releases function
for more details.
"""
# List of modifiers which can be used to change how
# a message is printed by the printmsg function.
INFO = 1
IMPORTANT = 2
QUESTION = 3
PROMPT = 4
WARNING = 5
ERROR = 6
EMPH = 7
EMPHASIS = 7
UNDERLINE = 8
RESET = 9
ANSICODES = {
INFO : '\033[37m', # Light grey
IMPORTANT : '\033[92m', # Green
QUESTION : '\033[36m\033[4m', # Blue+underline
PROMPT : '\033[36m\033[1m', # Bright blue+bold
WARNING : '\033[93m', # Yellow
ERROR : '\033[91m', # Red
EMPHASIS : '\033[1m', # White+bold
UNDERLINE : '\033[4m', # Underline
RESET : '\033[0m', # Used internally
}
def get_terminal_width(fallback=None):
"""Return the number of columns in the current terminal, or fallback
if it cannot be determined.
"""
# os.get_terminal_size added in python
# 3.3, so we try it but fall back to
# COLUMNS, or tput as a last resort.
try:
return shutil.get_terminal_size()[0]
except Exception:
pass
try:
return int(os.environ['COLUMNS'])
except Exception:
pass
try:
result = Process.check_output('tput cols', log_output=False)
return int(result.strip())
except Exception:
return fallback
def printmsg(*args, **kwargs):
"""Prints a sequence of strings formatted with ANSI codes. Expects
positional arguments to be of the form::
printable, ANSICODE, printable, ANSICODE, ...
:arg log: Must be specified as a keyword argument. If True (default),
the message is logged.
:arg fill: Must be specified as a keyword argument. If True (default),
the message is wrapped to the terminal width.
All other keyword arguments are passed through to the print function.
"""
args = list(args)
blockids = [i for i in range(len(args)) if (args[i] not in ANSICODES)]
logmsg = kwargs.pop('log', True)
fill = kwargs.pop('fill', True)
coded = ''
uncoded = ''
for i, idx in enumerate(blockids):
if i == len(blockids) - 1:
slc = slice(idx + 1, None)
else:
slc = slice(idx + 1, blockids[i + 1])
msg = args[idx]
msgcodes = args[slc]
msgcodes = [ANSICODES[c] for c in msgcodes]
msgcodes = ''.join(msgcodes)
uncoded += msg
coded += '{}{}{}'.format(msgcodes, msg, ANSICODES[RESET])
if len(blockids) > 0:
if fill:
width = get_terminal_width(70)
coded = tw.fill(coded, width, replace_whitespace=False)
print(coded, **kwargs)
if logmsg:
log.debug(uncoded)
sys.stdout.flush()
def prompt(promptmsg, *msgtypes, **kwargs):
"""Prompts the user for some input. msgtypes and kwargs are passed
through to the printmsg function.
"""
printmsg(promptmsg, *msgtypes, end='', log=False, **kwargs)
if PYVER[0] == 2: response = raw_input(' ').strip()
else: response = input( ' ').strip()
log.debug('%s: %s', promptmsg, response)
return response
def post_request(url, data):
"""Send JSON data to a URL via a HTTP POST request. """
data = json.dumps(data).encode('utf-8')
headers = {}
headers['Content-Type'] = 'application/json'
resp = None
try:
req = urlrequest.Request(url,
headers=headers,
data=data)
resp = urlrequest.urlopen(req)
finally:
if resp:
resp.close()
def identify_platform():
"""Figures out what platform we are running on. Returns a platform
identifier string - one of:
- "linux-64" (Linux, x86_64)
- "macos-64" (macOS, x86_64)
- "macos-M1" (macOS, M1)
Note that these identifiers are for FSL releases, and are not the
same as the platform identifiers used by conda.
"""
platforms = {
('linux', 'x86_64') : 'linux-64',
('darwin', 'x86_64') : 'macos-64',
('darwin', 'arm64') : 'macos-M1',
}
system = platform.system().lower()
cpu = platform.machine()
key = (system, cpu)
if key not in platforms:
supported = ', '.join(['[{}, {}]' for s, c in platforms])
raise Exception('This platform [{}, {}] is unrecognised or '
'unsupported! Supported platforms: {}'.format(
system, cpu, supported))
return platforms[key]
def timestamp():
"""Return a string containing the local time, with time zone offset.
"""
now = datetime.datetime.now()
offset = (now - datetime.datetime.utcnow())
offset = round(offset.total_seconds())
hours = int(offset / 3600)
minutes = int((offset % 3600) / 60)
now = now.strftime('%Y-%m-%dT%H:%M:%S')
return '{}{:+03d}:{:02d}'.format(now, hours, minutes)
def check_need_admin(dirname):
"""Returns True if dirname needs administrator privileges to write to,
False otherwise.
"""
# os.supports_effective_ids added in
# python 3.3, so can't be used here
return not os.access(dirname, os.W_OK | os.X_OK)
def get_admin_password(action='install FSL'):
"""Prompt the user for their administrator password. An Exception is raised
if an incorrect password is entered three times.a
:arg action: String which describes what the password is needed for, i.e.:
"Your administrator password is needed to {action}"
:returns: the validated administrator password
"""
def validate_admin_password(password):
proc = Process.sudo_popen(['true'], password, stdin=sp.PIPE)
proc.communicate()
return proc.returncode == 0
msg = 'Your administrator password is needed to {}'.format(action)
for attempt in range(3):
if attempt == 0: msg = '{}:'.format(msg)
else: msg = '{} [attempt {} of 3]:'.format(msg, attempt + 1)
printmsg(msg, IMPORTANT, end='')
password = getpass.getpass('')
valid = validate_admin_password(password)
if valid:
printmsg('Password accepted', INFO)
break
else:
printmsg('Incorrect password', WARNING)
if not valid:
raise Exception('Incorrect password')
return password
def isstr(s):
"""Returns True if s is a string, False otherwise. Works on python 2.7
and >=3.3.
"""
try: return isinstance(s, basestring)
except Exception: return isinstance(s, str)
def match_any(s, patterns):
"""Test if the string s matches any of the fnmatch-style patterns.
Returns the matched pattern, or None.
"""
for pat in patterns:
if fnmatch.fnmatch(s, pat):
return pat
return None
@contextlib.contextmanager
def tempdir(override_dir=None, change_into=True, delete=True):
"""Returns a context manager which creates, changes into, and returns a
temporary directory, and then deletes it on exit (unless delete is False).
If override_dir is not None, instead of creating and changing into a
temporary directory, this function just changes into override_dir.
"""
if override_dir is None: tmpdir = tempfile.mkdtemp()
else: tmpdir = override_dir
prevdir = os.getcwd()
try:
if change_into:
os.chdir(tmpdir)
yield tmpdir
finally:
if change_into:
os.chdir(prevdir)
if delete and override_dir is None:
shutil.rmtree(tmpdir)
def warn_on_error(*msgargs, **msgkwargs):
"""Decorator which tries to run a function, and prints a message if it
fails. The arguments after the function are passed to the printmsg
function, e.g.:
@warn_on_error('Function failed!', WARNING)
def function(a, b):
...
function('a', 'b')
:arg toscreen: Defaults to True. Print the warning to the screen.
:arg tolog: Defaults to True. Print the warning to the log file.
"""
toscreen = msgkwargs.pop('toscreen', True)
tolog = msgkwargs.pop('tolog', True)
def decorator(function):
def wrapper(*args, **kwargs):
try:
function(*args, **kwargs)
except Exception as e:
if toscreen: printmsg(*msgargs, **msgkwargs)
if tolog: log.debug('%s', e, exc_info=True)
return wrapper
return decorator
@contextlib.contextmanager
def tempfilename(permissions=None, delete=True):
"""Returns a context manager which creates a temporary file, yields its
name, then deletes the file on exit.
"""
fname = None
try:
tmpf = tempfile.NamedTemporaryFile(delete=False)
fname = tmpf.name
tmpf.close()
if permissions:
os.chmod(fname, permissions)
yield fname
finally:
if delete and fname and op.exists(fname):
os.remove(fname)
def sha256(filename, check_against=None, blocksize=1048576):
"""Calculate the SHA256 checksum of the given file. If check_against
is provided, it is compared against the calculated checksum, and an
error is raised if they are not the same.
"""
hashobj = hashlib.sha256()
with open(filename, 'rb') as f:
while True:
block = f.read(blocksize)
if len(block) == 0:
break
hashobj.update(block)
checksum = hashobj.hexdigest()
if check_against is not None:
if checksum != check_against:
raise Exception('File {} does not match expected checksum '
'({})'.format(filename, check_against))
return checksum
def clean_environ():
"""Return a dict containing a set of sanitised environment variables.
All FSL and conda related variables are removed.
"""
env = os.environ.copy()
for v in list(env.keys()):
if any(('FSL' in v, 'CONDA' in v, 'MAMBA' in v, 'PYTHON' in v)):
env.pop(v)
return env
def install_environ(fsldir, username=None, password=None):
"""Returns a dict containing some environment variables that should
be added to the shell environment when the FSL conda environment is
being installed.
"""
env = {}
# post-link scripts call $FSLDIR/share/fsl/sbin/createFSLWrapper
# (part of fsl/base), which will only do its thing if the following
# env vars are set
env['FSL_CREATE_WRAPPER_SCRIPTS'] = '1'
env['FSLDIR'] = fsldir
# Make sure HTTP proxy variables, if set,
# are available to the conda env command
for v in ['http_proxy', 'https_proxy',
'HTTP_PROXY', 'HTTPS_PROXY']:
if v in os.environ:
env[v] = os.environ[v]
# Tell mamba not to abort if the download is taking time
# https://github.com/mamba-org/mamba/issues/1941
env['MAMBA_NO_LOW_SPEED_LIMIT'] = '1'
# FSL environments which source packages from the internal
# FSL conda channel will refer to the channel as:
#
# http://${FSLCONDA_USERNAME}:${FSLCONDA_PASSWORD}/abc.com/
#
# so we need to set those variables
if username: env['FSLCONDA_USERNAME'] = username
if password: env['FSLCONDA_PASSWORD'] = password
return env
def download_file(url,
destination,
progress=None,
blocksize=131072,
ssl_verify=True):
"""Download a file from url, saving it to destination. """
def default_progress(downloaded, total):
pass
if progress is None:
progress = default_progress
log.debug('Downloading %s ...', url)
# Path to local file
if op.exists(url):
url = 'file:' + urlrequest.pathname2url(op.abspath(url))
# We create and use an unconfigured SSL
# context to disable SSL verification.
# Otherwise pass None causes urlopen to
# use default behaviour.
kwargs = {}
if not ssl_verify:
# - The urlopen(context) argument is not available in py3.3
# - py3.4 does not have PROTOCOL_TLS
# - PROTOCOL_TLS deprecated in py3.10
if PYVER == (3, 3): pro = None
elif hasattr(ssl, 'PROTOCOL_TLS_CLIENT'): pro = ssl.PROTOCOL_TLS_CLIENT
elif hasattr(ssl, 'PROTOCOL_TLS'): pro = ssl.PROTOCOL_TLS
elif hasattr(ssl, 'PROTOCOL_TLSv1_2'): pro = ssl.PROTOCOL_TLSv1_2
elif hasattr(ssl, 'PROTOCOL_TLSv1_1'): pro = ssl.PROTOCOL_TLSv1_1
elif hasattr(ssl, 'PROTOCOL_TLSv1'): pro = ssl.PROTOCOL_TLSv1
else: pro = None
if pro is None:
printmsg('SSL verification cannot be skipped - if this is '
'a problem, try running the installer with a newer '
'version of Python.', INFO)
else:
printmsg('Skipping SSL verification - this '
'is not recommended!', WARNING)
sslctx = ssl.SSLContext(pro)
sslctx.check_hostname = False
sslctx.verify_mode = ssl.CERT_NONE
kwargs['context'] = sslctx
req = None
try:
# py2: urlopen result cannot be
# used as a context manager
req = urlrequest.urlopen(url, **kwargs)
with open(destination, 'wb') as outf:
try: total = int(req.headers['content-length'])
except KeyError: total = None
downloaded = 0
progress(downloaded, total)
while True:
block = req.read(blocksize)
if len(block) == 0:
break
downloaded += len(block)
outf.write(block)
progress(downloaded, total)
finally:
if req:
req.close()
def download_manifest(url, workdir=None, **kwargs):
"""Downloads the installer manifest file, which contains information
about available FSL versions, and the most recent version number of the
installer (this script).
Keyword arguments are passed through to the download_file function.
The manifest file is a JSON file. Lines beginning with a double-forward
slash are ignored.
This function modifies the manifest structure by adding a 'version'
attribute to all FSL build entries.
"""
log.debug('Downloading FSL installer manifest from %s', url)
with tempdir(workdir):
try:
download_file(url, 'manifest.json', **kwargs)
except Exception as e:
log.debug('Error downloading FSL release manifest from %s',
url, exc_info=True)
raise Exception('Unable to download FSL release manifest '
'from {} [{}]!'.format(url, str(e)))
with open('manifest.json') as f:
lines = f.readlines()
# Drop comments
lines = [l for l in lines if not l.lstrip().startswith('//')]
manifest = json.loads('\n'.join(lines))
# Add "version" to every build
for version, builds in manifest['versions'].items():
if version == 'latest':
continue
for build in builds:
build['version'] = version
return manifest
def download_dev_releases(url, workdir=None, **kwargs):
"""Downloads the FSL_DEV_RELEASES file. This file contains a list of
available development manifest URLS. Returns a list of tuples, one
for each development release, with each tuple containing:
- URL to the manifest file
- Version identifier
- Commit hash (on the fsl/conda/manifest repository)
- Branch name (on the fsl/conda/manifest repository)
The list is sorted by date, newest first.
Keyword arguments are passed through to the download_file function.
"""
# parse a dev manifest file name, returning
# a sequence containing the tage, date, commit
# hash, and branch name. Dev manifest files
# are named like so:
#
# manifest-<tag>.<date>.<commit>.<branch>.json
#
# where <tag> is the tag of the most recent
# public FSL release, and everything else is
# self-explanatory.
def parse_devrelease_name(url):
name = urlparse.urlparse(url).path
name = op.basename(name)
name = name.lstrip('manifest-').rstrip('.json')
# The devrelease list may contain public
# releases too - sniff the commit, and if
# it doesn't look like a commit hash,
# assume that this file corresponds to a
# public release.
commit = name.rsplit('.', 2)[-2]
# public release or dev release
if len(commit) < 7: bits = [name, None, None]
else: bits = name.rsplit('.', 2)
return bits
# list of (url, version, commit, branch)
devreleases = []
with tempdir(workdir):
try:
download_file(url, 'devreleases.txt', **kwargs)
except Exception as e:
log.debug('Error downloading devreleases.txt from %s',
url, exc_info=True)
raise Exception('Unable to download development manifest '
'list from {}!'.format(url))
with open('devreleases.txt', 'rt') as f:
urls = f.read().strip().split('\n')
urls = [l.strip() for l in urls]
for url in urls:
devreleases.append([url] + parse_devrelease_name(url))
# sort by version, newest first
return sorted(devreleases, key=lambda r: Version(r[1]), reverse=True)
class Progress(object):
"""Simple progress reporter. Displays one of the following:
- If both a value and total are provided, a progress bar is shown
- If only a value is provided, a cumulative count is shown
- If nothing is provided, a spinner is shown.
Use as a context manager, and call the update method to report progress,
e,g:
with Progress('%') as p:
for i in range(100):
p.update(i + 1, 100)
"""
def __init__(self,
label='',
transform=None,
fmt='{:.1f}',
total=None,
width=None):
"""Create a Progress reporter.
:arg label: Units (e.g. "MB", "%",)
:arg transform: Function to transform values (see e.g.
Progress.bytes_to_mb)
:arg fmt: Template string used to format value / total.
:arg total: Maximum value - overrides the total value passed to
the update method.
:arg width: Maximum width, if a progress bar is displayed. Default
is to automatically infer the terminal width (see
get_terminal_width).
"""
if transform is None:
transform = Progress.default_transform
self.width = width
self.fmt = fmt.format
self.total = total
self.label = label
self.transform = transform
# used by the spin function
self.__last_spin = None
@staticmethod
def default_transform(val, total):
return val, total
@staticmethod
def bytes_to_mb(val, total):
if val is not None: val = val / 1048576
if total is not None: total = total / 1048576
return val, total
@staticmethod
def percent(val, total):
if val is None or total is None:
return val, total
return 100 * (val / total), 100
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
printmsg('', log=False, fill=False)
def update(self, value=None, total=None):
if total is None:
total = self.total
value, total = self.transform(value, total)
if value is None and total is None:
self.spin()
elif value is not None and total is None:
self.count(value)
elif value is not None and total is not None:
self.progress(value, total)
def spin(self):
symbols = ['|', '/', '-', '\\']
if self.__last_spin is not None: last = self.__last_spin
else: last = symbols[-1]
idx = symbols.index(last)
idx = (idx + 1) % len(symbols)
this = symbols[idx]
printmsg(this, end='\r', log=False, fill=False)
self.__last_spin = this
def count(self, value):
value = self.fmt(value)
if self.label is None: line = '{} ...'.format(value)
else: line = '{}{} ...'.format(value, self.label)
printmsg(line, end='\r', log=False, fill=False)
def progress(self, value, total):
value = min(value, total)
# arbitrary fallback of 50 columns if
# terminal width cannot be determined
if self.width is None: width = get_terminal_width(50)
else: width = self.width
fvalue = self.fmt(value)
ftotal = self.fmt(total)
suffix = '{} / {} {}'.format(fvalue, ftotal, self.label).rstrip()
# +5: - square brackets around bar
# - space between bar and tally
# - space+spin at the end
width = width - (len(suffix) + 5)
completed = int(round(width * (value / total)))
remaining = width - completed
progress = '[{}{}] {}'.format('#' * completed,
' ' * remaining,
suffix)
printmsg(progress, end='', log=False, fill=False)
printmsg(' ', end='', log=False, fill=False)
self.spin()
printmsg(end='\r', log=False, fill=False)
class Process(object):
"""Container for a subprocess.Popen object, allowing non-blocking
line-based access to its standard output and error streams via separate
queues, while logging all outputs.
Don't create a Process directly - use one of the following static methods:
- Process.check_output
- Process.check_call
- Process.monitor_progress
"""
def __init__(self,
cmd,
admin=False,
password=None,
log_output=True,
print_output=False,
append_env=None,
**kwargs):
"""Run the specified command. Starts threads to capture stdout and
stderr.
:arg cmd: Command to run - passed through shlex.split, then
passed to subprocess.Popen
:arg admin: Run the command with administrative privileges
:arg password: Administrator password - can be None if admin is
False.
:arg log_output: If True, the command and all of its stdout/stderr
are logged.
:arg print_output: If True, the command and all of its stdout/stderr
are logged.
:arg append_env: Dictionary of additional environment to be set when
the command is run.
:arg kwargs: Passed to subprocess.Popen
"""
self.cmd = cmd
self.stdoutq = queue.Queue()
self.stderrq = queue.Queue()
if log_output:
log.debug('Running %s [as admin: %s]', cmd, admin)
self.popen = Process.popen(cmd, admin, password,
append_env=append_env, **kwargs)
# threads for consuming stdout/stderr
self.stdout_thread = threading.Thread(
target=Process.forward_stream,
args=(self.popen.stdout, self.stdoutq, cmd,
'stdout', log_output, print_output))
self.stderr_thread = threading.Thread(
target=Process.forward_stream,
args=(self.popen.stderr, self.stderrq, cmd,
'stderr', log_output, print_output))
self.stdout_thread.daemon = True
self.stderr_thread.daemon = True
self.stdout_thread.start()
self.stderr_thread.start()
def wait(self):
"""Waits for the process to terminate, then waits for the stdout
and stderr consumer threads to finish.
"""
self.popen.wait()
self.stdout_thread.join()
self.stderr_thread.join()
@property
def returncode(self):
"""Process return code. Returns None until the process has terminated,
and the stdout/stderr consumer threads have finished.
"""
if self.popen.returncode is None: return None
if self.stdout_thread.is_alive(): return None
if self.stderr_thread.is_alive(): return None
return self.popen.returncode
@staticmethod
def check_output(cmd, *args, **kwargs):
"""Behaves like subprocess.check_output. Runs the given command, then
waits until it finishes, and return its standard output. An error
is raised if the process returns a non-zero exit code, unless a keyword
argument `check=False` is specified.
:arg cmd: The command to run, as a string
"""
check = kwargs.pop('check', True)
proc = Process(cmd, *args, **kwargs)
proc.wait()
if check and (proc.returncode != 0):
raise RuntimeError('This command returned an error: ' + cmd)
stdout = ''
while True:
try:
stdout += proc.stdoutq.get_nowait()
except queue.Empty:
break
return stdout
@staticmethod
def check_call(cmd, *args, **kwargs):
"""Behaves like subprocess.check_call. Runs the given command, then
waits until it finishes. An error is raised if the process returns a
non-zero exit code, unless a keyword argument `check=False` is
specified.
:arg cmd: The command to run, as a string
"""
check = kwargs.pop('check', True)
proc = Process(cmd, *args, **kwargs)
proc.wait()
if check and proc.returncode != 0:
raise RuntimeError('This command returned an error: ' + cmd)
return proc.returncode
@staticmethod
def monitor_progress(cmd, total=None, *args, **kwargs):
"""Runs the given command(s), and shows a progress bar under the
assumption that cmd will produce "total" number of lines of output.
:arg cmd: The commmand to run as a string, or a sequence of
multiple commands.
:arg total: Total number of lines of standard output to expect.
:arg timeout: Refresh rate in seconds. Must be passed as a keyword
argument.
:arg progfunc: Function which returns a number indicating how far
the process has progressed. If provided, this
function is called, instead of standard output
lines being monitored. The function is passed a
reference to the Process object. Must be passed as a
keyword argument.
"""
timeout = kwargs.pop('timeout', 0.5)
progfunc = kwargs.pop('progfunc', None)
if total is None: label = None
else: label = '%'
if progfunc is None:
nlines = [0]
def progfunc(proc):
try:
_ = proc.stdoutq.get_nowait()
nlines[0] = nlines[0] + 1
except queue.Empty:
pass
return nlines[0]
if isstr(cmd): cmds = [cmd]