fslinstaller.py 55.2 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
32
import                   threading
import                   time
Paul McCarthy's avatar
Paul McCarthy committed
33
import                   traceback
34

35
# TODO check py2/3
36
37
38
39
40
41
42
43
try:
    import                   urllib
    import urllib.parse   as urlparse
    import urllib.request as urlrequest
except ImportError:
    import urllib2 as urllib
    import urllib2 as urlparse
    import urllib2 as urlrequest
44

45
46
47
48
49
50
try:                import queue
except ImportError: import Queue as queue


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

51

52
53
54
log = logging.getLogger(__name__)


55
56
57
__absfile__ = op.abspath(__file__)


Paul McCarthy's avatar
Paul McCarthy committed
58
__version__ = '0.0.0'
Paul McCarthy's avatar
Paul McCarthy committed
59
60
"""Installer script version number. This is automatically updated
whenever a new version of the installer script is released.
Paul McCarthy's avatar
Paul McCarthy committed
61
62
63
64
65
66
67
68
69
"""


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


FSL_INSTALLER_MANIFEST = 'http://18.133.213.73/installer/manifest,json'
"""URL to download the FSL installer manifest file from. The installer
70
71
72
73
74
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
75

Paul McCarthy's avatar
Paul McCarthy committed
76
77
A custom manifest URL can be specified with the -a/--manifest command-line
option.
78
79
80
"""


81
82
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
83
installer script. Versions older than this will need to be overwritten.
84
85
86
87
88
89
"""


@ft.total_ordering
class Version(object):
    """Class to represent and compare version strings.  Accepted version
Paul McCarthy's avatar
Paul McCarthy committed
90
    strings are of the form W.X.Y.Z, where W, X, Y, and Z are all integers.
91
92
    """
    def __init__(self, verstr):
Paul McCarthy's avatar
Paul McCarthy committed
93
94
95
96
        # The major/minor numbers of FSL versions
        # change very infrequently for various
        # reasons, so we accept a fourth "hotfix"
        # number.
97
        self.components = list(map(int, verstr.split('.')[:4]))
Paul McCarthy's avatar
Paul McCarthy committed
98
        self.verstr     = verstr
99
100
101
102
103

    def __str__(self):
        return self.verstr

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

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


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

    Several settings are lazily evaluated on first access, but once evaluated,
    their values are immutable.
Paul McCarthy's avatar
Paul McCarthy committed
122
123
124
    """

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

129
        self.args  = args
130
        self.shell = op.basename(os.environ['SHELL']).lower()
Paul McCarthy's avatar
Paul McCarthy committed
131
132

        # These attributes are updated on-demand via
133
134
135
136
137
138
139
        # 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
140
141
        self.__need_admin     = None
        self.__admin_password = None
142

Paul McCarthy's avatar
Paul McCarthy committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
        # 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

        # The install_fsl function stores the path
        # to the FSL conda environment file here
        self.environment_file = None

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

166
167

    def finalise_settings(self):
168
169
        """Finalise values for all information and settings in the Context.
        """
Paul McCarthy's avatar
Paul McCarthy committed
170
        self.manifest
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
        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
203
204
        installer manifest) for the target platform and requested FSL/CUDA
        versions.
205
206
207
208
209
210
211
212
213
214

        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.
215
216
        """

Paul McCarthy's avatar
Paul McCarthy committed
217
218
219
220
221
        if self.__build is not None:
            return self.__build

        # defaults to "latest" if
        # not specified by the user
222
223
224
        fslversion = self.args.fslversion

        if fslversion not in self.manifest['versions']:
Paul McCarthy's avatar
Paul McCarthy committed
225
226
227
228
            available = ', '.join(self.manifest['versions'].keys())
            raise Exception(
                'FSL version {} is not available - available '
                'versions: {}'.format(args.fslversion, available))
229
230
231
232

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

Paul McCarthy's avatar
Paul McCarthy committed
233
234
235
236
237
238
239
        # 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 = []
240
241

        for build in self.manifest['versions'][fslversion]:
Paul McCarthy's avatar
Paul McCarthy committed
242
243
244
245
246
247
248
249
            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(
250
251
252
                'Cannot find a version of FSL matching platform '
                '{} and CUDA {}'.format(self.platform, self.cuda))

Paul McCarthy's avatar
Paul McCarthy committed
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
        # 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
279
        return match
Paul McCarthy's avatar
Paul McCarthy committed
280
281
282
283


    @property
    def destdir(self):
284
285
286
        """Installation directory. If not specified at the command line, the
        user is prompted to enter a directory.
        """
287
288
289
290
291
292
293
294
295

        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
296
297
        if self.args.dest is not None: response = self.args.dest
        else:                          response = None
298
299
300
301

        while destdir is None:

            if response is None:
Paul McCarthy's avatar
Paul McCarthy committed
302
                printmsg('\nWhere do you want to install FSL?',
303
                         IMPORTANT, EMPHASIS)
304
305
306
307
                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)
308
                response = response.rstrip(op.sep)
309

310
311
                if response == '':
                    response = DEFAULT_INSTALLATION_DIRECTORY
312

313
            response  = op.expanduser(op.expandvars(response))
314
315
316
317
318
319
320
321
322
323
            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
324
325
326
327
328
        return self.__destdir


    @property
    def need_admin(self):
329
330
331
        """Returns True if administrator privileges will be needed to install
        FSL.
        """
Paul McCarthy's avatar
Paul McCarthy committed
332
333
        if self.__need_admin is not None:
            return self.__need_admin
334
335
336
        parentdir = op.dirname(self.destdir)
        self.__need_admin = Context.check_need_admin(parentdir)
        return self.__need_admin
Paul McCarthy's avatar
Paul McCarthy committed
337
338
339
340


    @property
    def admin_password(self):
341
342
        """Returns the user's administrator password, prompting them if needed.
        """
Paul McCarthy's avatar
Paul McCarthy committed
343
344
345
346
347
348
349
350
351
        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):
352
        """Returns the FSL installer manifest as a dictionary. """
Paul McCarthy's avatar
Paul McCarthy committed
353
        if self.__manifest is None:
354
355
            self.__manifest = Context.download_manifest(self.args.manifest,
                                                        self.args.workdir)
Paul McCarthy's avatar
Paul McCarthy committed
356
357
358
359
360
361
362
363
364
365
366
367
368
369
        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',
370
            ('darwin', 'x86_64') : 'macos-64',
371
372
373

            # M1 builds (and possbily ARM for Linux)
            # will be added in the future
Paul McCarthy's avatar
Paul McCarthy committed
374
375
376
377
378
379
380
381
            ('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
382
383
384
            supported = ', '.join(['[{}, {}]' for s, c in platforms])
            raise Exception('This platform [{}, {}] is unrecognised or '
                            'unsupported! Supported platforms: {}'.format(
385
                                system, cpu, supported))
Paul McCarthy's avatar
Paul McCarthy committed
386
387
388
389
390
391
392

        return platforms[key]


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

Paul McCarthy's avatar
Paul McCarthy committed
397
398
        # see below - no_cuda is set to prevent unnecessary
        # attempts to call nvidia-smi more than once
399
400
401
        if getattr(Context.identify_cuda, 'no_cuda', False):
            return None

Paul McCarthy's avatar
Paul McCarthy committed
402
        try:
403
            output = Process.check_output('nvidia-smi')
404
        except Exception:
405
            Context.identify_cuda.no_cuda = True
Paul McCarthy's avatar
Paul McCarthy committed
406
407
            return None

408
409
410
411
412
413
414
415
        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
416
417
418
            # message for debugging - the output
            # will be present in the logfile
            log.debug('Could not parse nvidia-smi output')
419
            Context.identify_cuda.no_cuda = True
420
            return None
Paul McCarthy's avatar
Paul McCarthy committed
421

Paul McCarthy's avatar
Paul McCarthy committed
422
        return float(cudaver)
Paul McCarthy's avatar
Paul McCarthy committed
423
424
425
426
427
428
429


    @staticmethod
    def check_need_admin(dirname):
        """Returns True if dirname needs administrator privileges to write to,
        False otherwise.
        """
430
431
        # os.supports_effective_ids added in
        # python 3.3, so can't be used here
Paul McCarthy's avatar
Paul McCarthy committed
432
433
434
435
436
437
438
439
        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):
440
            proc = Process.sudo_popen(['true'], password)
441
442
            proc.communicate()
            return proc.returncode == 0
Paul McCarthy's avatar
Paul McCarthy committed
443

Paul McCarthy's avatar
Paul McCarthy committed
444
445
446
447
448
449
450
        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)
451
            printmsg(msg, IMPORTANT, end='')
Paul McCarthy's avatar
Paul McCarthy committed
452
453
454
            password = getpass.getpass('')
            valid    = validate_admin_password(password)

Paul McCarthy's avatar
Paul McCarthy committed
455
            if valid:
456
                printmsg('Password accepted', INFO)
Paul McCarthy's avatar
Paul McCarthy committed
457
458
459
                break
            else:
                printmsg('Incorrect password', WARNING)
Paul McCarthy's avatar
Paul McCarthy committed
460
461

        if not valid:
Paul McCarthy's avatar
Paul McCarthy committed
462
            raise Exception('Incorrect password')
Paul McCarthy's avatar
Paul McCarthy committed
463
464
465
466
467

        return password


    @staticmethod
468
    def download_manifest(url, workdir=None):
Paul McCarthy's avatar
Paul McCarthy committed
469
470
471
472
        """Downloads the installer manifest file, which contains information
        about available FSL vesrions, and the most recent version number of the
        installer (this script).

473
474
475
        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
476
477
478

        This function modifies the manifest structure by adding a 'version'
        attribute to all FSL build entries.
Paul McCarthy's avatar
Paul McCarthy committed
479
480
481
482
        """

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

483
        with tempdir(workdir):
Paul McCarthy's avatar
Paul McCarthy committed
484
485
            download_file(url, 'manifest.json')
            with open('manifest.json') as f:
486
487
488
489
                lines = f.readlines()

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

Paul McCarthy's avatar
Paul McCarthy committed
491
492
493
494
495
496
497
498
499
500
        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
501
502


503
504
505
506
507
508
509
510
511
512
513
514
# 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 = {
515
516
517
518
519
520
521
522
523
    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
524
525
526
}


527
def printmsg(msg='', *msgtypes, **kwargs):
528
529
    """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
530
531
532
533
534

    :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.
535
    """
Paul McCarthy's avatar
Paul McCarthy committed
536
    logmsg   = kwargs.pop('log', msg != '')
537
538
    msgcodes = [ANSICODES[t] for t in msgtypes]
    msgcodes = ''.join(msgcodes)
Paul McCarthy's avatar
Paul McCarthy committed
539
540
    if logmsg:
        log.debug(msg)
541
    print('{}{}{}'.format(msgcodes, msg, ANSICODES[RESET]), **kwargs)
542
    sys.stdout.flush()
543
544
545
546
547
548


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
549
    printmsg(prompt, *msgtypes, end='', log=False, **kwargs)
550

Paul McCarthy's avatar
Paul McCarthy committed
551
552
553
554
555
556
    if PY2: response = raw_input(' ').strip()
    else:   response = input(    ' ').strip()

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

    return response
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
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
629
        printmsg(log=False)
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

    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
656
        printmsg(this, end='\r', log=False)
657
658
659
        self.__last_spin = this

    def count(self, value):
660

661
        value = self.fmt(value)
662
663
664
665

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

Paul McCarthy's avatar
Paul McCarthy committed
666
        printmsg(line, end='\r', log=False)
667
668
669

    def progress(self, value, total):

670
        value = min(value, total)
671
672
673
674
675
676

        # 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

677
678
679
680
681
682
        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
683
        #     - space+spin at the end
684
        width     = width - (len(suffix) + 5)
685
686
        completed = int(round(width * (value  / total)))
        remaining = width - completed
687
688
689
        progress  = '[{}{}] {}'.format('#' * completed,
                                       ' ' * remaining,
                                       suffix)
690

Paul McCarthy's avatar
Paul McCarthy committed
691
692
        printmsg(progress, end='', log=False)
        printmsg(' ', end='', log=False)
693
        self.spin()
Paul McCarthy's avatar
Paul McCarthy committed
694
        printmsg(end='\r', log=False)
695
696
697
698
699
700
701


    @staticmethod
    def get_terminal_width(fallback=None):
        """Return the number of columns in the current terminal, or fallback
        if it cannot be determined.
        """
702
        # os.get_terminal_size added in python
703
704
705
706
        # 3.3, so we try it but fall back to tput
        if hasattr(os, 'get_terminal_size'):
            return os.get_terminal_size()[0]

707
        try:
Paul McCarthy's avatar
Paul McCarthy committed
708
            result = sp.check_output(('tput', 'cols'))
709
            return int(result.strip())
710
        except Exception:
711
712
713
            return fallback


714
@contextlib.contextmanager
715
716
717
718
719
720
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.
721
722
    """

723
724
725
    if override_dir is None: tmpdir = tempfile.mkdtemp()
    else:                    tmpdir = override_dir

726
727
728
    prevdir = os.getcwd()

    try:
729
730
        os.chdir(tmpdir)
        yield tmpdir
731
732
733

    finally:
        os.chdir(prevdir)
734
735
        if override_dir is None:
            shutil.rmtree(tmpdir)
736
737


738
def sha256(filename, check_against=None, blocksize=1048576):
Paul McCarthy's avatar
Paul McCarthy committed
739
740
741
    """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.
742
743
    """

Paul McCarthy's avatar
Paul McCarthy committed
744
    hashobj = hashlib.sha256()
745

Paul McCarthy's avatar
Paul McCarthy committed
746
747
748
749
750
751
    with open(filename, 'rb') as f:
        while True:
            block = f.read(blocksize)
            if len(block) == 0:
                break
            hashobj.update(block)
752

Paul McCarthy's avatar
Paul McCarthy committed
753
754
    checksum = hashobj.hexdigest()

755
    if check_against is not None:
Paul McCarthy's avatar
Paul McCarthy committed
756
        if checksum != check_against:
Paul McCarthy's avatar
Paul McCarthy committed
757
758
            raise Exception('File {} does not match expected checksum '
                            '({})'.format(filename, check_against))
759
760

    return checksum
761
762


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

766
767
    def default_progress(downloaded, total):
        pass
Paul McCarthy's avatar
Paul McCarthy committed
768

769
770
771
772
    if progress is None:
        progress = default_progress

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

774
    req = None
Paul McCarthy's avatar
Paul McCarthy committed
775
    try:
776
777
778
779
        # 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
780
781
782
783
784
785

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

            downloaded = 0

Paul McCarthy's avatar
Paul McCarthy committed
786
            progress(downloaded, total)
Paul McCarthy's avatar
Paul McCarthy committed
787
788
789
790
791
792
            while True:
                block = req.read(blocksize)
                if len(block) == 0:
                    break
                downloaded += len(block)
                outf.write(block)
793
                progress(downloaded, total)
Paul McCarthy's avatar
Paul McCarthy committed
794

795
    finally:
796
797
        if req:
            req.close()
Paul McCarthy's avatar
Paul McCarthy committed
798
799


800
class Process(object):
801
    """Container for a subprocess.Popen object, allowing non-blocking
802
803
804
805
806
807
808
    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
809
810
    """

811

812
    def __init__(self, cmd, admin=False, ctx=None, log_output=True, **kwargs):
813
814
        """Run the specified command. Starts threads to capture stdout and
        stderr.
815

816
817
818
819
820
821
822
        :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
823
        """
824

825
826
827
828
829
830
831
832
833
834
        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)

835
        self.popen = Process.popen(self.cmd, self.admin, self.ctx, **kwargs)
836

837
        # threads for consuming stdout/stderr
838
839
        self.stdout_thread = threading.Thread(
            target=Process.forward_stream,
840
            args=(self.popen.stdout, self.stdoutq, cmd, 'stdout', log_output))
841
842
        self.stderr_thread = threading.Thread(
            target=Process.forward_stream,
843
            args=(self.popen.stderr, self.stderrq, cmd, 'stderr', log_output))
844

845
846
847
848
        self.stdout_thread.daemon = True
        self.stderr_thread.daemon = True
        self.stdout_thread.start()
        self.stderr_thread.start()
849
850


851
852
853
854
855
856
857
858
859
    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()


860
861
862
863
864
865
866
867
868
869
870
    @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


871
    @staticmethod
872
    def check_output(cmd, *args, **kwargs):
873
874
875
        """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.
876

877
        :arg cmd: The command to run, as a string
878
879
        """

880
        proc = Process(cmd, *args, **kwargs)
881
        proc.wait()
882

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

886
887
888
889
890
891
892
893
        stdout = ''
        while True:
            try:
                stdout += proc.stdoutq.get_nowait()
            except queue.Empty:
                break

        return stdout
894
895
896


    @staticmethod
897
    def check_call(cmd, *args, **kwargs):
898
899
900
901
        """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.

902
        :arg cmd: The command to run, as a string
903
        """
904
        proc = Process(cmd, *args, **kwargs)
905
        proc.wait()
906
        if proc.returncode != 0:
Paul McCarthy's avatar
Paul McCarthy committed
907
            raise RuntimeError('This command returned an error: ' + cmd)
908
909
910


    @staticmethod
911
    def monitor_progress(cmd, total=None, *args, **kwargs):
912
913
914
915
916
917
918
919
920
921
        """Runs the given command, and shows a progress bar under the
        assumption that cmd will produce "total" number of lines of output.
        """
        if total is None: label = None
        else:             label = '%'

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

922
            proc   = Process(cmd, *args, **kwargs)
923
            nlines = 0 if total else None
924
925
926

            prog.update(nlines, total)

927
            while proc.returncode is None:
928
                try:
929
                    line    = proc.stdoutq.get(timeout=0.5)
930
931
                    nlines  = (nlines + 1) if total else None

932
                except queue.Empty:
933
                    pass
934
935

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

938
939
940
941
            # force progress bar to 100% when finished
            if proc.returncode == 0:
                prog.update(total, total)
            else:
Paul McCarthy's avatar
Paul McCarthy committed
942
                raise RuntimeError('This command returned an error: ' + cmd)
943

944
945

    @staticmethod
946
    def forward_stream(stream, queue, cmd, streamname, log_output):
947
948
949
        """Reads lines from stream and pushes them onto queue until popen
        is finished. Logs every line.

950
        :arg stream:     stream to forward
951
952
953
        :arg queue:      queue.Queue to push lines onto
        :arg cmd:        string - the command that is running
        :arg streamname: string - 'stdout' or 'stderr'
954
        :arg log_output: If True, log all stdout/stderr.
955
956
        """

957
        while True:
958
959
960
961
962
            line = stream.readline().decode('utf-8')
            if line == '':
                break
            else:
                queue.put(line)
963
                if log_output:
964
                    log.debug(' [%s]: %s', streamname, line.rstrip())
965
966
967


    @staticmethod
968
    def popen(cmd, admin=False, ctx=None, **kwargs):
969
970
        """Runs the given command via subprocess.Popen, as administrator if
        requested.
971

972
973
974
        :arg cmd:    The command to run, as a string

        :arg admin:  Whether to run with administrative privileges
975

976
977
        :arg ctx:    The installer Context object. Only required if admin is
                     True.
978

979
980
        :arg kwargs: Passed to subprocess.Popen. stdin, stdout, and stderr
                     will be silently clobbered
981

982
        :returns:    The subprocess.Popen object.
983
984
985
986
987
988
989
        """

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

        if admin: password = ctx.password
        else:     password = None

990
991
992
993
        cmd              = shlex.split(cmd)
        kwargs['stdin']  = sp.PIPE
        kwargs['stdout'] = sp.PIPE
        kwargs['stderr'] = sp.PIPE
994
995

        if admin: proc = Process.sudo_popen(cmd, password, **kwargs)
996
        else:     proc = sp.Popen(          cmd,           **kwargs)
997
998
999
1000
1001

        return proc


    @staticmethod
1002
1003
1004
    def sudo_popen(cmd, password, **kwargs):
        """Runs "sudo cmd" using subprocess.Popen. Used by Process.popen.
        Assumes that kwargs contains stdin=sp.PIPE
1005
        """
1006

1007
1008
1009
1010
        cmd  = ['sudo', '-S', '-k'] + cmd
        proc = sp.Popen(cmd, **kwargs)
        proc.stdin.write('{}\n'.format(password))
        return proc
1011
1012


1013
def list_available_versions(manifest):
1014
1015
    """Lists available FSL versions. """
    printmsg('Available FSL versions:', EMPHASIS)
1016
    for version in manifest['versions']:
1017
1018
1019
        if version == 'latest':
            continue
        printmsg(version, IMPORTANT, EMPHASIS)
1020
        for build in manifest['versions'][version]:
1021
1022
1023
1024
1025
1026
1027
1028
            if build.get('cuda', '').strip() != '':
                template = '  {platform} [CUDA {cuda}]'
            else:
                template = '  {platform}'
            printmsg(template.format(**build), EMPHASIS, end=' ')
            printmsg(build['environment'], INFO)


Paul McCarthy's avatar
Paul McCarthy committed
1029
1030
1031
def download_miniconda(ctx):
    """Downloads the miniconda/miniforge installer and saves it as
    "miniconda.sh".
1032
1033

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

1036
    metadata = ctx.manifest['miniconda'][ctx.platform]
1037
1038
1039
    url      = metadata['url']
    checksum = metadata['sha256']
    output   = metadata.get('output', '').strip()
1040

1041
1042
    if output == '': output = None
    else:            output = int(output)
Paul McCarthy's avatar
Paul McCarthy committed
1043

1044
1045
    # Download
    printmsg('Downloading miniconda from {}...'.format(url))
1046
    with Progress('MB', transform=Progress.bytes_to_mb) as prog:
1047
        download_file(url, 'miniconda.sh', prog.update)
1048
    if not ctx.args.no_checksum:
Paul McCarthy's avatar
Paul McCarthy committed
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
        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)
1066
1067

    # Install
1068
    printmsg('Installing miniconda at {}...'.format(ctx.destdir))
Paul McCarthy's avatar
Paul McCarthy committed
1069
    cmd = 'sh miniconda.sh -b -p {}'.format(ctx.destdir)
1070
    Process.monitor_progress(cmd, output, ctx.need_admin, ctx)
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105

    # Create .condarc config file
    condarc = tw.dedent("""
    # Putting a .condarc file into the root environment
    # directory will override ~/.condarc if it exists,
    # but will not override a system condarc (e.g. at
    # /etc/condarc/condarc). There is currently no
    # workaround for this - see:
    #  - https://github.com/conda/conda/issues/8599
    #  - https://github.com/conda/conda/issues/8804

    # Try and make package downloads more robust
    remote_read_timeout_secs:    240
    remote_connect_timeout_secs: 20
    remote_max_retries:          10
    remote_backoff_factor:       5
    safety_checks:               warn

    # Channel priority is important. In older versions
    # of FSL we placed the FSL conda channel at the
    # bottom (lowest priority) for legacy reasons (to
    # ensure that conda-forge versions of e.g. VTK were
    # preferred over legacy FSL conda versions).
    #
    # https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-channels.html
    channel_priority: strict
    channels:
      - http://18.133.213.73/production/
      - conda-forge
      - defaults
    """)

    with open('.condarc', 'wt') as f:
        f.write(condarc)

1106
1107
    Process.check_call('cp .condarc {}'.format(ctx.destdir),
                       ctx.need_admin, ctx)
1108
1109


Paul McCarthy's avatar
Paul McCarthy committed
1110
def install_fsl(ctx):
1111
    """Install FSL into ctx.destdir (which is assumed to be a miniconda
1112
    installation.
1113

Paul McCarthy's avatar
Paul McCarthy committed
1114
    This function assumes that it is run within a temporary/scratch directory.
1115
1116
    """

1117
1118
1119
1120
    build    = ctx.build
    url      = build['environment']
    checksum = build['sha256']

Paul McCarthy's avatar
Paul McCarthy committed
1121
1122
1123
1124
1125
    # expected number of output lines for new
    # install or upgrade, used for progress
    # reporting. If manifest does not contain
    # expected #lines, we fall back to a spinner.
    if ctx.update is None:
1126
1127
        output = build.get('output', {}).get('install', None)
    else:
Paul McCarthy's avatar
Paul McCarthy committed
1128
        output = build.get('output', {}).get(ctx.update, None)
1129
1130
1131

    if output in ('', None): output = None
    else:                    output = int(output)
1132
1133
1134

    printmsg('Downloading FSL environment specification '
             'from {}...'.format(url))
Paul McCarthy's avatar
Paul McCarthy committed
1135
1136
1137
1138
1139
    fname = url.split('/')[-1]
    download_file(url, fname)
    ctx.environment_file = op.abspath(fname)
    if not ctx.args.no_checksum:
        sha256(fname, build['sha256'])
1140
1141

    conda = op.join(ctx.destdir, 'bin', 'conda')
Paul McCarthy's avatar
Paul McCarthy committed
1142
    cmd   = conda + ' env update -n base -f ' + fname
1143
1144
1145

    printmsg('Installing FSL into {}...'.format(ctx.destdir))

Paul McCarthy's avatar
Paul McCarthy committed
1146
1147
1148
    # 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
1149
1150
    env = os.environ.copy()
    env['FSL_CREATE_WRAPPER_SCRIPTS'] = '1'
Paul McCarthy's avatar
Paul McCarthy committed
1151
    env['FSLDIR']                     = ctx.destdir
1152

1153
    Process.monitor_progress(cmd, output, ctx.need_admin, ctx, env=env)
1154

1155

1156
1157
1158
1159
def finalise_installation(ctx):
    """Performs some finalisation tasks. Includes:
      - Saving the installed version to $FSLDIR/etc/fslversion
      - Saving this installer script and the environment file to
Paul McCarthy's avatar
Paul McCarthy committed
1160
        $FSLDIR/etc/
1161
1162
1163
1164
1165
1166
1167
    """
    with open('fslversion', 'wt') as f:
        f.write(ctx.build['version'])

    call    = ft.partial(Process.check_call, admin=ctx.need_admin, ctx=ctx)
    etcdir  = op.join(ctx.destdir, 'etc')

Paul McCarthy's avatar
Paul McCarthy committed
1168
1169
1170
    call('cp fslversion {}'.format(etcdir))
    call('cp {} {}'        .format(ctx.environment_file, etcdir))
    call('cp {} {}'        .format(__absfile__,          etcdir))
1171
1172


1173
1174
1175
1176
1177
1178
def post_install_cleanup(ctx):
    """Cleans up the FSL directory after installation. """

    conda = op.join(ctx.destdir, 'bin', 'conda')
    cmd   = conda + ' clean -y --all'

1179
    Process.check_call(cmd, ctx.need_admin, ctx)
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196


def patch_file(filename, searchline, numlines, content):
    """Used by configure_shell and configure_matlab. Adds to, modifies,
    or creates the specified file.

    If a line matching searchline is found in the file, numlines (starting
    from searchline) are replaced with content.

    Otherwise, content is appended to the end of the file.
    """

    content = content.split('\n')

    if op.isfile(filename):
        with open(filename) as f:
            lines = [l.strip() for l in f.readlines()]
1197
    else:
1198
        lines = []
1199

1200
1201
1202
1203
    # replace block
    try:
        idx   = lines.index(searchline)
        lines = lines[:idx] + content + lines[idx + numlines:]
1204

1205
1206
1207
    # append to end
    except ValueError:
        lines = lines + [''] + content
1208

1209
1210
    with open(filename, 'wt') as f:
        f.write('\n'.join(lines))