fslinstaller.py 63.5 KB
Newer Older
1
#!/usr/bin/env python
2
3
4
#
# FSL installer script.
#
Paul McCarthy's avatar
Paul McCarthy committed
5
6
7
8
"""This is the FSL installation script. It can be used to install FSL, or
to update an existing FSL installation.  This script can be executed with
Python 2.7 or newer.
"""
9
10


11
from __future__ import print_function, division, unicode_literals
12

13
14
15
import functools      as ft
import os.path        as op
import subprocess     as sp
16
import textwrap       as tw
17
18
19
import                   argparse
import                   contextlib
import                   getpass
Paul McCarthy's avatar
Paul McCarthy committed
20
import                   hashlib
21
22
import                   json
import                   logging
23
import                   os
24
import                   platform
25
import                   re
26
import                   readline
27
28
import                   shlex
import                   shutil
29
import                   sys
30
import                   tempfile
31
import                   threading
Paul McCarthy's avatar
Paul McCarthy committed
32
import                   traceback
33

34
# TODO check py2/3
35
36
37
try:
    import urllib.request as urlrequest
except ImportError:
38
    import urllib as urlrequest
39

40
41
42
43
44
45
try:                import queue
except ImportError: import Queue as queue


PY2 = sys.version[0] == '2'

46

47
48
49
log = logging.getLogger(__name__)


Paul McCarthy's avatar
Paul McCarthy committed
50
51
# this sometimes gets set to fslinstaller.pyc, so rstrip c
__absfile__ = op.abspath(__file__).rstrip('c')
52
53


Paul McCarthy's avatar
Paul McCarthy committed
54
__version__ = '1.4.0'
55
"""Installer script version number. This must be updated
Paul McCarthy's avatar
Paul McCarthy committed
56
whenever a new version of the installer script is released.
Paul McCarthy's avatar
Paul McCarthy committed
57
58
59
60
61
62
63
"""


DEFAULT_INSTALLATION_DIRECTORY = '/usr/local/fsl'
"""Default FSL installation directory. """


Paul McCarthy's avatar
Paul McCarthy committed
64
FSL_INSTALLER_MANIFEST = 'https://fsl.fmrib.ox.ac.uk/fsldownloads/fslconda/releases/manifest.json'
Paul McCarthy's avatar
Paul McCarthy committed
65
"""URL to download the FSL installer manifest file from. The installer
66
67
68
69
70
manifest file is a JSON file which contains information about available FSL
versions.

See the Context.download_manifest function, and an example manifest file
in test/data/manifest.json, for more details.
Paul McCarthy's avatar
Paul McCarthy committed
71

Paul McCarthy's avatar
Paul McCarthy committed
72
73
A custom manifest URL can be specified with the -a/--manifest command-line
option.
74
75
76
"""


77
78
FIRST_FSL_CONDA_RELEASE = '6.0.6'
"""Oldest conda-based FSL version that can be updated in-place by this
Paul McCarthy's avatar
Paul McCarthy committed
79
installer script. Versions older than this will need to be overwritten.
80
81
82
83
84
85
"""


@ft.total_ordering
class Version(object):
    """Class to represent and compare version strings.  Accepted version
Paul McCarthy's avatar
Paul McCarthy committed
86
    strings are of the form W.X.Y.Z, where W, X, Y, and Z are all integers.
87
88
    """
    def __init__(self, verstr):
89
90
91
92
93
94
95
96
97
98
99
100
        # Version identifiers for official FSL
        # releases will have up to four
        # components (X.Y.Z.W), but We accept
        # any number of (integer) components,
        # as internal releases may have more.
        components = []

        for comp in verstr.split('.'):
            try:              components.append(int(comp))
            except Exception: break

        self.components = components
Paul McCarthy's avatar
Paul McCarthy committed
101
        self.verstr     = verstr
102
103
104
105
106

    def __str__(self):
        return self.verstr

    def __eq__(self, other):
Paul McCarthy's avatar
Paul McCarthy committed
107
108
109
110
        for sn, on in zip(self.components, other.components):
            if sn != on:
                 return False
        return len(self.components) == len(other.components)
111
112

    def __lt__(self, other):
Paul McCarthy's avatar
Paul McCarthy committed
113
        for p1, p2 in zip(self.components, other.components):
114
115
            if p1 < p2: return True
            if p1 > p2: return False
116
        return len(self.components) < len(other.components)
117
118


Paul McCarthy's avatar
Paul McCarthy committed
119
120
121
class Context(object):
    """Bag of information and settings created in main, and passed around
    this script.
122
123
124

    Several settings are lazily evaluated on first access, but once evaluated,
    their values are immutable.
Paul McCarthy's avatar
Paul McCarthy committed
125
126
127
    """

    def __init__(self, args):
128
129
130
        """Create the context with the argparse.Namespace object containing
        parsed command-line arguments.
        """
131

132
        self.args  = args
Paul McCarthy's avatar
Paul McCarthy committed
133
        self.shell = op.basename(os.environ.get('SHELL', 'sh')).lower()
Paul McCarthy's avatar
Paul McCarthy committed
134
135

        # These attributes are updated on-demand via
136
137
138
139
140
141
142
        # the property accessors defined below, or all
        # all updated via the finalise-settings method.
        self.__platform       = None
        self.__cuda           = None
        self.__manifest       = None
        self.__build          = None
        self.__destdir        = None
Paul McCarthy's avatar
Paul McCarthy committed
143
144
        self.__need_admin     = None
        self.__admin_password = None
145

Paul McCarthy's avatar
Paul McCarthy committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
        # These attributes are set by main - exists is
        # a flag denoting whether the dest dir already
        # exists, and update is the version string of
        # the existing FSL installation if the user
        # has selected to update it, or None otherwise.
        self.exists = False
        self.update = None

        # If the destination directory already exists,
        # and the user chooses to overwrite it, it is
        # moved so that, if the installation fails, it
        # can be restored. The new path is stored
        # here - refer to overwrite_destdir.
        self.old_destdir = None

161
        # The download_fsl_environment function stores
162
        # the path to the FSL conda environment file,
163
164
        # list of conda channels, and versions of a
        # small set of "base" packages here.
165
166
        self.environment_file     = None
        self.environment_channels = None
167
        self.fsl_base_packages    = None
Paul McCarthy's avatar
Paul McCarthy committed
168
169
170
171
172

        # The config_logging function stores the path
        # to the fslinstaller log file here.
        self.logfile = None

173
174

    def finalise_settings(self):
175
176
        """Finalise values for all information and settings in the Context.
        """
Paul McCarthy's avatar
Paul McCarthy committed
177
        self.manifest
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
        self.platform
        self.cuda
        self.build
        self.destdir
        self.need_admin
        self.admin_password


    @property
    def platform(self):
        """The platform we are running on, e.g. "linux-64", "macos-64". """
        if self.__platform is None:
            self.__platform = Context.identify_platform()
        return self.__platform


    @property
    def cuda(self):
        """The available CUDA version, or a CUDA version requested by the user.
        """
        if self.__cuda is not None:
            return self.__cuda
        if self.args.cuda is not None:
            self.__cuda = self.args.cuda
        if self.__cuda is None:
            self.__cuda = Context.identify_cuda()
        return self.__cuda


    @property
    def build(self):
        """Returns a suitable FSL build (a dictionary entry from the FSL
210
211
        installer manifest) for the target platform and requested FSL/CUDA
        versions.
212
213
214
215
216
217
218
219
220
221

        The returned dictionary has the following elements:
          - 'version'      FSL version.
          - 'platform':    Platform identifier (e.g. 'linux-64')
          - 'environment': Environment file to download
          - 'sha256':      Checksum of environment file
          - 'output':      Number of lines of expected output, for reporting
                           progress
          - 'cuda':        X.Y CUDA version, if a CUDA-enabled version of FSL
                           is to be installed.
222
223
        """

Paul McCarthy's avatar
Paul McCarthy committed
224
225
226
227
228
        if self.__build is not None:
            return self.__build

        # defaults to "latest" if
        # not specified by the user
229
230
231
        fslversion = self.args.fslversion

        if fslversion not in self.manifest['versions']:
Paul McCarthy's avatar
Paul McCarthy committed
232
233
            available = ', '.join(self.manifest['versions'].keys())
            raise Exception(
Paul McCarthy's avatar
Paul McCarthy committed
234
                'FSL version "{}" is not available - available '
Paul McCarthy's avatar
Paul McCarthy committed
235
                'versions: {}'.format(fslversion, available))
236
237
238
239

        if fslversion == 'latest':
            fslversion = self.manifest['versions']['latest']

Paul McCarthy's avatar
Paul McCarthy committed
240
241
242
243
244
245
246
        # Find refs to all compatible builds,
        # separating the default (no CUDA) build
        # from CUDA-enabled builds. We assume
        # that there is only one default build
        # for each platform.
        default    = None
        candidates = []
247
248

        for build in self.manifest['versions'][fslversion]:
Paul McCarthy's avatar
Paul McCarthy committed
249
250
251
252
253
254
255
256
            if build['platform'] == self.platform:
                if build.get('cuda', None) is None:
                    default = build
                else:
                    candidates.append(build)

        if (default is None) and (len(candidates) == 0):
            raise Exception(
257
258
259
                'Cannot find a version of FSL matching platform '
                '{} and CUDA {}'.format(self.platform, self.cuda))

Paul McCarthy's avatar
Paul McCarthy committed
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
        # If we have CUDA (or the user has
        # specifically requested a CUDA build),
        # try and find a suitable build
        match = default
        if self.cuda is not None:
            candidates = sorted(candidates, key=lambda b: float(b['cuda']))

            for build in reversed(candidates):
                if self.cuda >= float(build['cuda']):
                    match = build
                    break
            else:
                available = [b['cuda'] for b in candidates]
                printmsg('Could not find a suitable FSL CUDA '
                         'build for CUDA version {} (available: '
                         '{}. Installing default (non-CUDA) '
                         'FSL build.'.format(self.cuda, available),
                         WARNING)
                printmsg('You can use the --cuda command-line option '
                         'to install a FSL build that is compatible '
                         'with a specific CUDA version', INFO)

        printmsg('FSL {} [CUDA: {}] selected for installation'.format(
            match['version'], match.get('cuda', 'n/a')))

        self.__build = match
286
        return match
Paul McCarthy's avatar
Paul McCarthy committed
287
288
289
290


    @property
    def destdir(self):
291
292
293
        """Installation directory. If not specified at the command line, the
        user is prompted to enter a directory.
        """
294
295
296
297
298
299
300
301
302

        if self.__destdir is not None:
            return self.__destdir

        # The loop below validates the destination directory
        # both when specified at commmand line or
        # interactively.  In either case, if invalid, the
        # user is re-prompted to enter a new destination.
        destdir = None
Paul McCarthy's avatar
Paul McCarthy committed
303
304
        if self.args.dest is not None: response = self.args.dest
        else:                          response = None
305
306
307
308

        while destdir is None:

            if response is None:
Paul McCarthy's avatar
Paul McCarthy committed
309
                printmsg('\nWhere do you want to install FSL?',
310
                         IMPORTANT, EMPHASIS)
311
312
313
314
                printmsg('Press enter to install to the default location '
                         '[{}]\n'.format(DEFAULT_INSTALLATION_DIRECTORY), INFO)
                response = prompt('FSL installation directory [{}]:'.format(
                    DEFAULT_INSTALLATION_DIRECTORY), QUESTION, EMPHASIS)
315
                response = response.rstrip(op.sep)
316

317
318
                if response == '':
                    response = DEFAULT_INSTALLATION_DIRECTORY
319

320
            response  = op.expanduser(op.expandvars(response))
321
322
323
324
325
326
327
328
329
330
            response  = op.abspath(response)
            parentdir = op.dirname(response)
            if op.exists(parentdir):
                destdir = response
            else:
                printmsg('Destination directory {} does not '
                         'exist!'.format(parentdir), ERROR)
                response = None

        self.__destdir = destdir
Paul McCarthy's avatar
Paul McCarthy committed
331
332
333
334
335
        return self.__destdir


    @property
    def need_admin(self):
336
337
338
        """Returns True if administrator privileges will be needed to install
        FSL.
        """
Paul McCarthy's avatar
Paul McCarthy committed
339
340
        if self.__need_admin is not None:
            return self.__need_admin
341
342
343
        parentdir = op.dirname(self.destdir)
        self.__need_admin = Context.check_need_admin(parentdir)
        return self.__need_admin
Paul McCarthy's avatar
Paul McCarthy committed
344
345
346
347


    @property
    def admin_password(self):
348
349
        """Returns the user's administrator password, prompting them if needed.
        """
Paul McCarthy's avatar
Paul McCarthy committed
350
351
352
353
354
355
356
357
358
        if self.__admin_password is not None:
            return self.__admin_password
        if self.__need_admin == False:
            return None
        self.__admin_password = Context.get_admin_password()


    @property
    def manifest(self):
359
        """Returns the FSL installer manifest as a dictionary. """
Paul McCarthy's avatar
Paul McCarthy committed
360
        if self.__manifest is None:
361
362
            self.__manifest = Context.download_manifest(self.args.manifest,
                                                        self.args.workdir)
Paul McCarthy's avatar
Paul McCarthy committed
363
364
365
366
367
368
369
370
371
372
373
374
375
376
        return self.__manifest


    @staticmethod
    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)
        """

        platforms = {
            ('linux',  'x86_64') : 'linux-64',
377
            ('darwin', 'x86_64') : 'macos-64',
378
379
380

            # M1 builds (and possbily ARM for Linux)
            # will be added in the future
Paul McCarthy's avatar
Paul McCarthy committed
381
382
383
384
385
386
387
388
            ('darwin', 'arm64')  : 'macos-64',
        }

        system = platform.system().lower()
        cpu    = platform.machine()
        key    = (system, cpu)

        if key not in platforms:
Paul McCarthy's avatar
Paul McCarthy committed
389
390
391
            supported = ', '.join(['[{}, {}]' for s, c in platforms])
            raise Exception('This platform [{}, {}] is unrecognised or '
                            'unsupported! Supported platforms: {}'.format(
392
                                system, cpu, supported))
Paul McCarthy's avatar
Paul McCarthy committed
393
394
395
396
397
398
399

        return platforms[key]


    @staticmethod
    def identify_cuda():
        """Identifies the CUDA version supported on the platform. Returns a
Paul McCarthy's avatar
Paul McCarthy committed
400
401
        float representing the X.Y CUDA version, or None if CUDA is not
        available on the platform.
Paul McCarthy's avatar
Paul McCarthy committed
402
403
        """

Paul McCarthy's avatar
Paul McCarthy committed
404
405
        # see below - no_cuda is set to prevent unnecessary
        # attempts to call nvidia-smi more than once
406
407
408
        if getattr(Context.identify_cuda, 'no_cuda', False):
            return None

Paul McCarthy's avatar
Paul McCarthy committed
409
        try:
410
            output = Process.check_output('nvidia-smi')
411
        except Exception:
412
            Context.identify_cuda.no_cuda = True
Paul McCarthy's avatar
Paul McCarthy committed
413
414
            return None

415
416
417
418
419
420
421
422
        pat   = r'CUDA Version: (\S+)'
        lines = output.split('\n')
        for line in lines:
            match = re.search(pat, line)
            if match:
                cudaver = match.group(1)
                break
        else:
Paul McCarthy's avatar
Paul McCarthy committed
423
424
425
            # message for debugging - the output
            # will be present in the logfile
            log.debug('Could not parse nvidia-smi output')
426
            Context.identify_cuda.no_cuda = True
427
            return None
Paul McCarthy's avatar
Paul McCarthy committed
428

Paul McCarthy's avatar
Paul McCarthy committed
429
        return float(cudaver)
Paul McCarthy's avatar
Paul McCarthy committed
430
431
432
433
434
435
436


    @staticmethod
    def check_need_admin(dirname):
        """Returns True if dirname needs administrator privileges to write to,
        False otherwise.
        """
437
438
        # os.supports_effective_ids added in
        # python 3.3, so can't be used here
Paul McCarthy's avatar
Paul McCarthy committed
439
440
441
442
443
444
445
446
        return not os.access(dirname, os.W_OK | os.X_OK)


    @staticmethod
    def get_admin_password():
        """Prompt the user for their administrator password."""

        def validate_admin_password(password):
447
            proc = Process.sudo_popen(['true'], password, stdin=sp.PIPE)
448
449
            proc.communicate()
            return proc.returncode == 0
Paul McCarthy's avatar
Paul McCarthy committed
450

Paul McCarthy's avatar
Paul McCarthy committed
451
452
453
454
455
456
457
        for attempt in range(3):
            if attempt == 0:
                msg = 'Your administrator password is needed to ' \
                      'install FSL: '
            else:
                msg = 'Your administrator password is needed to ' \
                      'install FSL [attempt {} of 3]:'.format(attempt + 1)
458
            printmsg(msg, IMPORTANT, end='')
Paul McCarthy's avatar
Paul McCarthy committed
459
460
461
            password = getpass.getpass('')
            valid    = validate_admin_password(password)

Paul McCarthy's avatar
Paul McCarthy committed
462
            if valid:
463
                printmsg('Password accepted', INFO)
Paul McCarthy's avatar
Paul McCarthy committed
464
465
466
                break
            else:
                printmsg('Incorrect password', WARNING)
Paul McCarthy's avatar
Paul McCarthy committed
467
468

        if not valid:
Paul McCarthy's avatar
Paul McCarthy committed
469
            raise Exception('Incorrect password')
Paul McCarthy's avatar
Paul McCarthy committed
470
471
472
473
474

        return password


    @staticmethod
475
    def download_manifest(url, workdir=None):
Paul McCarthy's avatar
Paul McCarthy committed
476
        """Downloads the installer manifest file, which contains information
477
        about available FSL versions, and the most recent version number of the
Paul McCarthy's avatar
Paul McCarthy committed
478
479
        installer (this script).

480
481
482
        The manifest file is a JSON file. Lines beginning
        with a double-forward-slash are ignored. See test/data/manifes.json
        for an example.
Paul McCarthy's avatar
Paul McCarthy committed
483
484
485

        This function modifies the manifest structure by adding a 'version'
        attribute to all FSL build entries.
Paul McCarthy's avatar
Paul McCarthy committed
486
487
488
489
        """

        log.debug('Downloading FSL installer manifest from %s', url)

490
        with tempdir(workdir):
Paul McCarthy's avatar
Paul McCarthy committed
491
492
            download_file(url, 'manifest.json')
            with open('manifest.json') as f:
493
494
495
496
                lines = f.readlines()

        # Drop comments
        lines = [l for l in lines if not l.lstrip().startswith('//')]
Paul McCarthy's avatar
Paul McCarthy committed
497

Paul McCarthy's avatar
Paul McCarthy committed
498
499
500
501
502
503
504
505
506
507
        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
Paul McCarthy's avatar
Paul McCarthy committed
508
509


510
511
512
513
514
515
516
517
518
519
520
521
# 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
EMPHASIS  = 7
UNDERLINE = 8
RESET     = 9
ANSICODES = {
522
523
524
525
526
527
528
529
530
    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
531
532
533
}


534
def printmsg(msg='', *msgtypes, **kwargs):
535
536
    """Prints msg according to the ANSI codes provided in msgtypes.
    All other keyword arguments are passed through to the print function.
Paul McCarthy's avatar
Paul McCarthy committed
537
538
539
540
541

    :arg msgtypes: Message types to control formatting
    :arg log:      If True (default), the message is logged.

    All other keyword arguments are passed to the built-in print function.
542
    """
Paul McCarthy's avatar
Paul McCarthy committed
543
    logmsg   = kwargs.pop('log', msg != '')
544
545
    msgcodes = [ANSICODES[t] for t in msgtypes]
    msgcodes = ''.join(msgcodes)
Paul McCarthy's avatar
Paul McCarthy committed
546
547
    if logmsg:
        log.debug(msg)
548
    print('{}{}{}'.format(msgcodes, msg, ANSICODES[RESET]), **kwargs)
549
    sys.stdout.flush()
550
551
552
553
554
555


def prompt(prompt, *msgtypes, **kwargs):
    """Prompts the user for some input. msgtypes and kwargs are passed
    through to the printmsg function.
    """
Paul McCarthy's avatar
Paul McCarthy committed
556
    printmsg(prompt, *msgtypes, end='', log=False, **kwargs)
557

Paul McCarthy's avatar
Paul McCarthy committed
558
559
560
561
562
563
    if PY2: response = raw_input(' ').strip()
    else:   response = input(    ' ').strip()

    log.debug('%s: %s', prompt, response)

    return response
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
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
                        Progress.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):
Paul McCarthy's avatar
Paul McCarthy committed
636
        printmsg(log=False)
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

    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]

Paul McCarthy's avatar
Paul McCarthy committed
663
        printmsg(this, end='\r', log=False)
664
665
666
        self.__last_spin = this

    def count(self, value):
667

668
        value = self.fmt(value)
669
670
671
672

        if self.label is None: line = '{} ...'.format(value)
        else:                  line = '{}{} ...'.format(value, self.label)

Paul McCarthy's avatar
Paul McCarthy committed
673
        printmsg(line, end='\r', log=False)
674
675
676

    def progress(self, value, total):

677
        value = min(value, total)
678
679
680
681
682
683

        # arbitrary fallback of 50 columns if
        # terminal width cannot be determined
        if self.width is None: width = Progress.get_terminal_width(50)
        else:                  width = self.width

684
685
686
687
688
689
        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
690
        #     - space+spin at the end
691
        width     = width - (len(suffix) + 5)
692
693
        completed = int(round(width * (value  / total)))
        remaining = width - completed
694
695
696
        progress  = '[{}{}] {}'.format('#' * completed,
                                       ' ' * remaining,
                                       suffix)
697

Paul McCarthy's avatar
Paul McCarthy committed
698
699
        printmsg(progress, end='', log=False)
        printmsg(' ', end='', log=False)
700
        self.spin()
Paul McCarthy's avatar
Paul McCarthy committed
701
        printmsg(end='\r', log=False)
702
703
704
705
706
707
708


    @staticmethod
    def get_terminal_width(fallback=None):
        """Return the number of columns in the current terminal, or fallback
        if it cannot be determined.
        """
709
        # os.get_terminal_size added in python
710
        # 3.3, so we try it but fall back to tput
711
        try:
712
            return os.get_terminal_size()[0]
713
714
        except Exception:
            pass
715

716
        try:
Paul McCarthy's avatar
Paul McCarthy committed
717
            result = sp.check_output(('tput', 'cols'))
718
            return int(result.strip())
719
        except Exception:
720
721
722
            return fallback


723
724
725
726
727
728
729
730
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)


731
@contextlib.contextmanager
732
733
734
735
736
737
def tempdir(override_dir=None):
    """Returns a context manager which creates, changes into, and returns a
    temporary directory, and then deletes it on exit.

    If override_dir is not None, instead of creating and changing into a
    temporary directory, this function just changes into override_dir.
738
739
    """

740
741
742
    if override_dir is None: tmpdir = tempfile.mkdtemp()
    else:                    tmpdir = override_dir

743
744
745
    prevdir = os.getcwd()

    try:
746
747
        os.chdir(tmpdir)
        yield tmpdir
748
749
750

    finally:
        os.chdir(prevdir)
751
752
        if override_dir is None:
            shutil.rmtree(tmpdir)
753
754


755
def sha256(filename, check_against=None, blocksize=1048576):
Paul McCarthy's avatar
Paul McCarthy committed
756
757
758
    """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.
759
760
    """

Paul McCarthy's avatar
Paul McCarthy committed
761
    hashobj = hashlib.sha256()
762

Paul McCarthy's avatar
Paul McCarthy committed
763
764
765
766
767
768
    with open(filename, 'rb') as f:
        while True:
            block = f.read(blocksize)
            if len(block) == 0:
                break
            hashobj.update(block)
769

Paul McCarthy's avatar
Paul McCarthy committed
770
771
    checksum = hashobj.hexdigest()

772
    if check_against is not None:
Paul McCarthy's avatar
Paul McCarthy committed
773
        if checksum != check_against:
Paul McCarthy's avatar
Paul McCarthy committed
774
775
            raise Exception('File {} does not match expected checksum '
                            '({})'.format(filename, check_against))
776
777

    return checksum
778
779


780
def download_file(url, destination, progress=None, blocksize=131072):
Paul McCarthy's avatar
Paul McCarthy committed
781
782
    """Download a file from url, saving it to destination. """

783
784
    def default_progress(downloaded, total):
        pass
Paul McCarthy's avatar
Paul McCarthy committed
785

786
787
788
789
    if progress is None:
        progress = default_progress

    log.debug('Downloading %s ...', url)
Paul McCarthy's avatar
Paul McCarthy committed
790

791
792
793
794
    # Path to local file
    if op.exists(url):
        url = 'file:' + urlrequest.pathname2url(op.abspath(url))

795
    req = None
Paul McCarthy's avatar
Paul McCarthy committed
796
    try:
797
798
799
800
        # py2: urlopen result cannot be
        # used as a context manager
        req = urlrequest.urlopen(url)
        with open(destination, 'wb') as outf:
Paul McCarthy's avatar
Paul McCarthy committed
801
802
803
804
805
806

            try:             total = int(req.headers['content-length'])
            except KeyError: total = None

            downloaded = 0

Paul McCarthy's avatar
Paul McCarthy committed
807
            progress(downloaded, total)
Paul McCarthy's avatar
Paul McCarthy committed
808
809
810
811
812
813
            while True:
                block = req.read(blocksize)
                if len(block) == 0:
                    break
                downloaded += len(block)
                outf.write(block)
814
                progress(downloaded, total)
Paul McCarthy's avatar
Paul McCarthy committed
815

816
    finally:
817
818
        if req:
            req.close()
Paul McCarthy's avatar
Paul McCarthy committed
819
820


821
class Process(object):
822
    """Container for a subprocess.Popen object, allowing non-blocking
823
824
825
826
827
828
829
    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
830
831
    """

832

833
    def __init__(self, cmd, admin=False, ctx=None, log_output=True, **kwargs):
834
835
        """Run the specified command. Starts threads to capture stdout and
        stderr.
836

837
838
839
840
841
842
843
        :arg cmd:        Command to run - passed directly to subprocess.Popen
        :arg admin:      Run the command with administrative privileges
        :arg ctx:        The installer Context. Only used for admin password -
                         can be None if admin is False.
        :arg log_output: If True, the command and all of its stdout/stderr are
                         logged.
        :arg kwargs:     Passed to subprocess.Popen
844
        """
845

846
847
848
849
850
851
852
853
854
855
        self.ctx        = ctx
        self.cmd        = cmd
        self.admin      = admin
        self.log_output = log_output
        self.stdoutq    = queue.Queue()
        self.stderrq    = queue.Queue()

        if log_output:
            log.debug('Running %s [as admin: %s]', cmd, admin)

856
        self.popen = Process.popen(self.cmd, self.admin, self.ctx, **kwargs)
857

858
        # threads for consuming stdout/stderr
859
860
        self.stdout_thread = threading.Thread(
            target=Process.forward_stream,
861
            args=(self.popen.stdout, self.stdoutq, cmd, 'stdout', log_output))
862
863
        self.stderr_thread = threading.Thread(
            target=Process.forward_stream,
864
            args=(self.popen.stderr, self.stderrq, cmd, 'stderr', log_output))
865

866
867
868
869
        self.stdout_thread.daemon = True
        self.stderr_thread.daemon = True
        self.stdout_thread.start()
        self.stderr_thread.start()
870
871


872
873
874
875
876
877
878
879
880
    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()


881
882
883
884
885
886
887
888
889
890
891
    @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


892
    @staticmethod
893
    def check_output(cmd, *args, **kwargs):
894
895
896
        """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.
897

898
        :arg cmd: The command to run, as a string
899
900
        """

901
        proc = Process(cmd, *args, **kwargs)
902
        proc.wait()
903

904
        if proc.returncode != 0:
Paul McCarthy's avatar
Paul McCarthy committed
905
            raise RuntimeError('This command returned an error: ' + cmd)
906

907
908
909
910
911
912
913
914
        stdout = ''
        while True:
            try:
                stdout += proc.stdoutq.get_nowait()
            except queue.Empty:
                break

        return stdout
915
916
917


    @staticmethod
918
    def check_call(cmd, *args, **kwargs):
919
920
921
922
        """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.

923
        :arg cmd: The command to run, as a string
924
        """
925
        proc = Process(cmd, *args, **kwargs)
926
        proc.wait()
927
        if proc.returncode != 0:
Paul McCarthy's avatar
Paul McCarthy committed
928
            raise RuntimeError('This command returned an error: ' + cmd)
929
930
931


    @staticmethod
932
    def monitor_progress(cmd, total=None, *args, **kwargs):
933
        """Runs the given command(s), and shows a progress bar under the
934
        assumption that cmd will produce "total" number of lines of output.
935
936
937
938

        :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.
939
940
941
942
        """
        if total is None: label = None
        else:             label = '%'

943
944
        if isstr(cmd): cmds = [cmd]
        else:          cmds =  cmd
945

946
947
948
949
        with Progress(label=label,
                      fmt='{:.0f}',
                      transform=Progress.percent) as prog:

950
            nlines = 0 if total else None
951

952
            for cmd in cmds:
953

954
                proc = Process(cmd, *args, **kwargs)
955
956
                prog.update(nlines, total)

957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
                while proc.returncode is None:
                    try:
                        line    = proc.stdoutq.get(timeout=0.5)
                        nlines  = (nlines + 1) if total else None

                    except queue.Empty:
                        pass

                    prog.update(nlines, total)
                    proc.popen.poll()

                # force progress bar to 100% when finished
                if proc.returncode == 0:
                    prog.update(total, total)
                else:
                    raise RuntimeError('This command returned '
                                       'an error: ' + cmd)
974

975
976

    @staticmethod
977
    def forward_stream(stream, queue, cmd, streamname, log_output):
978
979
980
        """Reads lines from stream and pushes them onto queue until popen
        is finished. Logs every line.

981
        :arg stream:     stream to forward
982
983
984
        :arg queue:      queue.Queue to push lines onto
        :arg cmd:        string - the command that is running
        :arg streamname: string - 'stdout' or 'stderr'
985
        :arg log_output: If True, log all stdout/stderr.
986
987
        """

988
        while True:
989
990
991
992
993
            line = stream.readline().decode('utf-8')
            if line == '':
                break
            else:
                queue.put(line)
994
                if log_output:
995
                    log.debug(' [%s]: %s', streamname, line.rstrip())
996
997
998


    @staticmethod
999
    def popen(cmd, admin=False, ctx=None, **kwargs):
1000
1001
        """Runs the given command via subprocess.Popen, as administrator if
        requested.
1002

1003
1004
1005
        :arg cmd:    The command to run, as a string

        :arg admin:  Whether to run with administrative privileges
1006

1007
1008
        :arg ctx:    The installer Context object. Only required if admin is
                     True.
1009

1010
1011
        :arg kwargs: Passed to subprocess.Popen. stdin, stdout, and stderr
                     will be silently clobbered
1012

1013
        :returns:    The subprocess.Popen object.
1014
1015
1016
1017
        """

        admin = admin and os.getuid() != 0

1018
        if admin: password = ctx.admin_password
1019
1020
        else:     password = None

1021
1022
1023
1024
        cmd              = shlex.split(cmd)
        kwargs['stdin']  = sp.PIPE
        kwargs['stdout'] = sp.PIPE
        kwargs['stderr'] = sp.PIPE
1025
1026

        if admin: proc = Process.sudo_popen(cmd, password, **kwargs)
1027
        else:     proc = sp.Popen(          cmd,           **kwargs)
1028
1029
1030
1031
1032

        return proc


    @staticmethod
1033
1034
1035
    def sudo_popen(cmd, password, **kwargs):
        """Runs "sudo cmd" using subprocess.Popen. Used by Process.popen.
        Assumes that kwargs contains stdin=sp.PIPE
1036
        """
1037

1038
1039
        cmd  = ['sudo', '-S', '-k'] + cmd
        proc = sp.Popen(cmd, **kwargs)
1040
        proc.stdin.write('{}\n'.format(password).encode())
1041
        return proc
1042
1043


1044
def list_available_versions(manifest):
1045
1046
    """Lists available FSL versions. """
    printmsg('Available FSL versions:', EMPHASIS)
1047
    for version in manifest['versions']:
1048
1049
1050
        if version == 'latest':
            continue
        printmsg(version, IMPORTANT, EMPHASIS)
1051
        for build in manifest['versions'][version]:
1052
1053
1054
1055
1056
1057
1058
1059
            if build.get('cuda', '').strip() != '':
                template = '  {platform} [CUDA {cuda}]'
            else:
                template = '  {platform}'
            printmsg(template.format(**build), EMPHASIS, end=' ')
            printmsg(build['environment'], INFO)


1060
1061
1062
1063
def download_fsl_environment(ctx):
    """Downloads the environment specification file for the selected FSL
    version.

1064
1065
1066
    If the (hidden) --environment option is provided, the specified file
    is used instead.

1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
    Internal/development FSL versions may source packages from the internal
    FSL conda channel, which requires a username+password to authenticate.

    These are referred to in the environment file as ${FSLCONDA_USERNAME}
    and ${FSLCONDA_PASSWORD}.

    If the user has not provided a username+password on the command-line, they
    are prompted for them.
    """

1077
    if ctx.args.environment is None:
1078
1079
1080
1081
        build        = ctx.build
        url          = build['environment']
        checksum     = build.get('sha256',        None)
        basepkgnames = build.get('base_packages', [])
1082
    else:
1083
1084
1085
1086
        build        = {}
        url          = ctx.args.environment
        checksum     = None
        basepkgnames = []
1087
1088
1089
1090
1091
1092

    printmsg('Downloading FSL environment specification '
             'from {}...'.format(url))
    fname = url.split('/')[-1]
    download_file(url, fname)
    ctx.environment_file = op.abspath(fname)
1093
1094
    if (checksum is not None) and (not ctx.args.no_checksum):
        sha256(fname, checksum)
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122

    # Environment files for internal/dev FSL versions
    # will list the internal FSL conda channel with
    # ${FSLCONDA_USERNAME} and ${FSLCONDA_PASSWORD}
    # as placeholders for the username/password.
    with open(fname, 'rt') as f:
        need_auth = '${FSLCONDA_USERNAME}' in f.read()

    # We need a username/password to access the internal
    # FSL conda channel. Prompt the user if they haven't
    # provided credentials.
    if need_auth and (ctx.args.username is None):
        printmsg('A username and password are required to install '
                 'this version of FSL.', WARNING, EMPHASIS)
        ctx.args.username = prompt('Username:').strip()
        ctx.args.password = getpass.getpass('Password: ').strip()

    # Conda expands environment variables within a
    # .condarc file, but *not* within an environment.yml
    # file. So to authenticate to our internal channel
    # without storing credentials anywhere in plain text,
    # we *move* the channel list from the environment.yml
    # file into $FSLDIR/.condarc.
    #
    # Here we extract the channels from the environment
    # file, and save them to ctx.environment_channels.
    # The install_miniconda function will then add the
    # channels to $FSLDIR/.condarc.
1123
    #
1124
1125
1126
1127
    # A collection of "base" packages are installed
    # before any other packages. So we also extract the
    # version numbers of these base packages from the
    # environment file, and store them in the context.
1128
    copy     = '.' + op.basename(ctx.environment_file)
1129
1130
    channels = []
    basepkgs = {}
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
    shutil.move(ctx.environment_file, copy)
    with open(copy,                 'rt') as inf, \
         open(ctx.environment_file, 'wt') as outf:

        in_channels_section = False

        for line in inf:

            # start of channels list
            if line.strip() == 'channels:':
                in_channels_section = True
                continue

            if in_channels_section:
                # end of channels list
                if not line.strip().startswith('-'):
                    in_channels_section = False
                else:
                    channels.append(line.split()[-1])
                    continue

1152
1153
1154
1155
            # save base package versions, as
            # we install them separately
            for pkg in basepkgnames:
                if line.strip().startswith('- {}'.format(pkg)):
Paul McCarthy's avatar
Paul McCarthy committed
1156
                    pkgver        = line.split(' ', 2)[2]
1157
                    basepkgs[pkg] = pkgver.replace(' ', '=')
1158

1159
1160
1161
            outf.write(line)

    ctx.environment_channels = channels
1162
    ctx.fsl_base_packages    = basepkgs
1163
1164


Paul McCarthy's avatar
Paul McCarthy committed
1165
1166
1167
def download_miniconda(ctx):
    """Downloads the miniconda/miniforge installer and saves it as
    "miniconda.sh".
1168
1169

    This function assumes that it is run within a temporary/scratch directory.
1170
1171
    """

1172
    metadata = ctx.manifest['miniconda'][ctx.platform]
1173
1174
1175
    url      = metadata['url']
    checksum = metadata['sha256']
    output   = metadata.get('output', '').strip()
1176

1177
1178
    if output == '': output = None
    else:            output = int(output)
Paul McCarthy's avatar
Paul McCarthy committed
1179

1180
1181
    # Download
    printmsg('Downloading miniconda from {}...'.format(url))
1182
    with Progress('MB', transform=Progress.bytes_to_mb) as prog:
1183
        download_file(url, 'miniconda.sh', prog.update)
1184
    if not ctx.args.no_checksum:
Paul McCarthy's avatar
Paul McCarthy committed
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
        sha256('miniconda.sh', checksum)


def install_miniconda(ctx):
    """Downloads the miniconda/miniforge installer, and installs it to the
    destination directory.

    This function assumes that it is run within a temporary/scratch directory.
    """

    metadata = ctx.manifest['miniconda'][ctx.platform]
    url      = metadata['url']
    checksum = metadata['sha256']
    output   = metadata.get('output', '').strip()

    if output == '': output = None
    else:            output = int(output)
1202
1203

    # Install
1204
    printmsg('Installing miniconda at {}...'.format(ctx.destdir))
Paul McCarthy's avatar
Paul McCarthy committed
1205
    cmd = 'sh miniconda.sh -b -p {}'.format(ctx.destdir)
Paul McCarthy's avatar