fslinstaller.py 33.1 KB
Newer Older
1
#!/usr/bin/env python
2
3
4
#
# FSL installer script.
#
5
6


7
from __future__ import print_function, division, unicode_literals
8

9
10
11
import functools      as ft
import os.path        as op
import subprocess     as sp
12
import textwrap       as tw
13
14
15
16
17
import                   os
import                   sys
import                   argparse
import                   contextlib
import                   getpass
Paul McCarthy's avatar
Paul McCarthy committed
18
import                   hashlib
19
20
21
22
23
24
import                   json
import                   logging
import                   platform
import                   shlex
import                   shutil
import                   tempfile
25
26
import                   threading
import                   time
27

28
29
30
31
32
# TODO check py2/3
import                   urllib
import urllib.parse   as urlparse
import urllib.request as urlrequest

33
34
35
36
37
38
try:                import queue
except ImportError: import Queue as queue


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

39
40
41
42

log = logging.getLogger(__name__)


Paul McCarthy's avatar
Paul McCarthy committed
43
44
45
46
47
48
49
50
51
52
53
54
__version__ = '0.0.0'
"""Installer version number. This is automatically updated in release versions
whenever a new version is released.
"""


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
55
56
57
58
59
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
60
61
62
63
64
65
66
67
68
"""


class InvalidPassword(Exception):
    """Exception raised by Context.get_admin_password if the user gives an
    incorrect password.
    """


69
70
71
72
73
74
75
76
77
78
79
80
class UnknownVersion(Exception):
    """Exception raised by Context.build if the user has requested a FSL
    version that does not exist.
    """


class BuildNotAvailable(Exception):
    """Exception raised by Context.build if there is no available FSL version
    that matches the target platform and/or requested CUDA version.
    """


Paul McCarthy's avatar
Paul McCarthy committed
81
82
83
class Context(object):
    """Bag of information and settings created in main, and passed around
    this script.
84
85
86

    Several settings are lazily evaluated on first access, but once evaluated,
    their values are immutable.
Paul McCarthy's avatar
Paul McCarthy committed
87
88
89
    """

    def __init__(self, args):
90
91
92
        """Create the context with the argparse.Namespace object containing
        parsed command-line arguments.
        """
93
94

        self.args = args
Paul McCarthy's avatar
Paul McCarthy committed
95
96

        # These attributes are updated on-demand via
97
98
99
100
101
102
103
        # 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
104
105
        self.__need_admin     = None
        self.__admin_password = None
106
107
108


    def finalise_settings(self):
109
110
        """Finalise values for all information and settings in the Context.
        """
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
        self.platform
        self.cuda
        self.manifest
        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
        installer manifest) for the target platform and CUDA version.
        """

        fslversion = self.args.fslversion
        if fslversion is None:
            fslversion = 'latest'

        if fslversion not in self.manifest['versions']:
            raise UnknownVersion(
                'FSL version {} is not available'.format(args.fslversion))

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

        match = None

        for build in self.manifest['versions'][fslversion]:
            if build['platform']       == self.platform and \
               build.get('cuda', None) == self.cuda:
                match = build
                break
        else:
            raise BuildNotAvailable(
                'Cannot find a version of FSL matching platform '
                '{} and CUDA {}'.format(self.platform, self.cuda))

        return match
Paul McCarthy's avatar
Paul McCarthy committed
171
172
173
174


    @property
    def destdir(self):
175
176
177
178
179
        """Installation directory. If not specified at the command line, the
        user is prompted to enter a directory.
        """
        if self.args.dest is not None:
            self.__destdir = op.abspath(self.args.dest)
Paul McCarthy's avatar
Paul McCarthy committed
180
        if self.__destdir is None:
181
182
183
184
185
186
187
188
189
190
            while True:
                printmsg('Where do you want to install FSL?',
                         IMPORTANT, EMPHASIS)
                printmsg('Press enter to install to the default location [{}]'
                         .format(DEFAULT_INSTALLATION_DIRECTORY), INFO)
                response = prompt('FSL installation directory:', QUESTION)
                response = response.rstrip(op.sep)
                if response == '':
                    response = DEFAULT_INSTALLATION_DIRECTORY
                    break
Paul McCarthy's avatar
Paul McCarthy committed
191
                response  = op.abspath(response)
192
                parentdir = op.dirname(response)
Paul McCarthy's avatar
Paul McCarthy committed
193
194
195
                if op.exists(parentdir):
                    break
                else:
196
197
                    printmsg('Destination directory {} does not '
                             'exist!'.format(parentdir), ERROR)
Paul McCarthy's avatar
Paul McCarthy committed
198

199
            self.__destdir = response
Paul McCarthy's avatar
Paul McCarthy committed
200
201
202
203
204
        return self.__destdir


    @property
    def need_admin(self):
205
206
207
        """Returns True if administrator privileges will be needed to install
        FSL.
        """
Paul McCarthy's avatar
Paul McCarthy committed
208
209
        if self.__need_admin is not None:
            return self.__need_admin
210
211
212
        parentdir = op.dirname(self.destdir)
        self.__need_admin = Context.check_need_admin(parentdir)
        return self.__need_admin
Paul McCarthy's avatar
Paul McCarthy committed
213
214
215
216


    @property
    def admin_password(self):
217
218
        """Returns the user's administrator password, prompting them if needed.
        """
Paul McCarthy's avatar
Paul McCarthy committed
219
220
221
222
223
224
225
226
227
228
229
        if self.__admin_password is not None:
            return self.__admin_password
        if self.__need_admin == False:
            return None
        if self.__destdir is None:
            raise RuntimeError('Destination directory has not been set')
        self.__admin_password = Context.get_admin_password()


    @property
    def manifest(self):
230
        """Returns the FSL installer manifest as a dictionary. """
Paul McCarthy's avatar
Paul McCarthy committed
231
        if self.__manifest is None:
232
233
            self.__manifest = Context.download_manifest(self.args.manifest,
                                                        self.args.workdir)
Paul McCarthy's avatar
Paul McCarthy committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
        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',
            ('darwin', 'x86_64') : 'linux-64',
249
250
251

            # M1 builds (and possbily ARM for Linux)
            # will be added in the future
Paul McCarthy's avatar
Paul McCarthy committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
            ('darwin', 'arm64')  : 'macos-64',
        }

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

        if key not in platforms:
            raise UnsupportedPlatform()

        return platforms[key]


    @staticmethod
    def identify_cuda():
        """Identifies the CUDA version supported on the platform. Returns a
268
269
        string containing the 'X.Y' CUDA version, or None if CUDA is not
        supported.
Paul McCarthy's avatar
Paul McCarthy committed
270
271
272
273
274
275
276
        """

        try:
            output = sp.check_output('nvidia-smi')
        except (sp.CalledProcessError, FileNotFoundError):
            return None

277
        cudaver = '9.2'  # TODO
Paul McCarthy's avatar
Paul McCarthy committed
278
279
280
281
        match   = None

        # Return the most suitable CUDA
        # version that we have a build for
282
283
284
285
        available_cudas = ['9.2', '10.2', '11.1']
        for available in reversed(supported_cudas):
            if float(cudaver) <= float(available):
                match = available
Paul McCarthy's avatar
Paul McCarthy committed
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
                break

        return match


    @staticmethod
    def check_need_admin(dirname):
        """Returns True if dirname needs administrator privileges to write to,
        False otherwise.
        """
        # TODO os.supports_effective_ids added in python 3.3
        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):
305
306
307
            proc = sudo_popen(['true'], password)
            proc.communicate()
            return proc.returncode == 0
Paul McCarthy's avatar
Paul McCarthy committed
308

Paul McCarthy's avatar
Paul McCarthy committed
309
310
311
312
313
314
315
316
        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)
            printmsg(msg, IMPORTANT, end='', flush=True)
Paul McCarthy's avatar
Paul McCarthy committed
317
318
319
            password = getpass.getpass('')
            valid    = validate_admin_password(password)

Paul McCarthy's avatar
Paul McCarthy committed
320
            if valid:
321
                printmsg('Password accepted', INFO)
Paul McCarthy's avatar
Paul McCarthy committed
322
323
324
                break
            else:
                printmsg('Incorrect password', WARNING)
Paul McCarthy's avatar
Paul McCarthy committed
325
326
327
328
329
330
331
332

        if not valid:
            raise InvalidPassword()

        return password


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

338
339
        The manifest file is a JSON file with the following structure (lines
        beginning with two forward-slashes are ignored):
Paul McCarthy's avatar
Paul McCarthy committed
340

341
          {
Paul McCarthy's avatar
Paul McCarthy committed
342
              "installer" : {
343
344
345
346
347
348
349
350
351
352

                  // Latest version of installer script
                  "version" : "1.2.3",

                  // URL to download installer script
                  "url"     : "http://abc.com/fslinstaller.py"

                  // SHA256 checksum of installer script
                  "sha256"  : "ab238........."
              },
Paul McCarthy's avatar
Paul McCarthy committed
353
354
              "versions" : {

355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
                  // Latest must be present, and must
                  // contain the version number of the
                  // latest release
                  "latest" : "6.1.0",
                  "6.1.0"  : {
                      'linux-64' : {
                          "environment" : "http;//abc.com/fsl-6.1.0-linux-64.yml",
                          "sha256"      : "ab23456...",
                      }
                      'macos-64' : {
                          "environment" : "http;//abc.com/fsl-6.1.0-macos-64.yml",
                          "sha256"      : "ab23456...",
                      }
                      'linux-64-cuda9.2' : {
                          "environment" : "http;//abc.com/fsl-6.1.0-linux-64-cuda9.2.yml",
                          "sha256"      : "ab23456...",
                      }
                      'linux-64-cuda10.2' : {
                          "environment" : "http;//abc.com/fsl-6.1.0-linux-64-cuda10.2.yml",
                          "sha256"      : "ab23456...",
                      }
                  }
                  "6.1.1" : {
                      ...
                  }
Paul McCarthy's avatar
Paul McCarthy committed
380
              }
381
          }
Paul McCarthy's avatar
Paul McCarthy committed
382
383
384
385
        """

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

386
        with tempdir(workdir):
Paul McCarthy's avatar
Paul McCarthy committed
387
388
            download_file(url, 'manifest.json')
            with open('manifest.json') as f:
389
390
391
392
                lines = f.readlines()

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

394
        return json.loads('\n'.join(lines))
Paul McCarthy's avatar
Paul McCarthy committed
395
396


397
398
399
400
401
402
403
404
405
406
407
408
# 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 = {
409
410
411
412
413
414
415
416
417
    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
418
419
420
}


421
def printmsg(msg='', *msgtypes, **kwargs):
422
423
424
425
426
427
    """Prints msg according to the ANSI codes provided in msgtypes.
    All other keyword arguments are passed through to the print function.
    """
    msgcodes = [ANSICODES[t] for t in msgtypes]
    msgcodes = ''.join(msgcodes)
    print('{}{}{}'.format(msgcodes, msg, ANSICODES[RESET]), **kwargs)
428
    sys.stdout.flush()
429
430
431
432
433
434
435
436
437
438


def prompt(prompt, *msgtypes, **kwargs):
    """Prompts the user for some input. msgtypes and kwargs are passed
    through to the printmsg function.
    """
    printmsg(prompt + ' ', *msgtypes, end='', **kwargs)
    return input().strip()


439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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):
        printmsg()

    def update(self, value=None, total=None):

        if total is None:
            total = self.total

        value, total = self.transform(value, total)

        if value is None and total is None:
            self.spin()
        elif value is not None and total is None:
            self.count(value)
        elif value is not None and total is not None:
            self.progress(value, total)

    def spin(self):

        symbols = ['|', '/', '-',  '\\']

        if self.__last_spin is not None: last = self.__last_spin
        else:                            last = symbols[-1]

        idx  = symbols.index(last)
        idx  = (idx + 1) % len(symbols)
        this = symbols[idx]

        printmsg(this, end='\r')
        self.__last_spin = this

    def count(self, value):
        value = self.fmt(value)
        line  = '{}{} ...'.format(value, self.label)
        printmsg(line, end='\r')

    def progress(self, value, total):

        fvalue = self.fmt(value)
        ftotal = self.fmt(total)
        suffix = '{} / {} {}'.format(fvalue, ftotal, self.label).rstrip()

        # 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

        width     = width - (len(suffix) + 3)
        completed = int(round(width * (value  / total)))
        remaining = width - completed
        line      = '[{}{}] {}'.format(
            '#' * completed,
            ' ' * remaining,
            suffix)

        printmsg(line, end='\r')


    @staticmethod
    def get_terminal_width(fallback=None):
        """Return the number of columns in the current terminal, or fallback
        if it cannot be determined.
        """
        # os.get_terminal_size added in python 3.3
        try:
            return int(sp.check_output('tput cols'.split()).strip())
        except (OSError, FileNotFoundError):
            return fallback


578
@contextlib.contextmanager
579
580
581
582
583
584
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.
585
586
    """

587
588
589
    if override_dir is None: tmpdir = tempfile.mkdtemp()
    else:                    tmpdir = override_dir

590
591
592
    prevdir = os.getcwd()

    try:
593
594
        os.chdir(tmpdir)
        yield tmpdir
595
596
597

    finally:
        os.chdir(prevdir)
598
599
        if override_dir is None:
            shutil.rmtree(tmpdir)
600
601
602
603
604
605
606
607
608
609
610
611
612
613


def memoize(f):
    """Decorator to memoize a function. """

    cache = f.cache = {}
    def g(*args, **kwargs):
        key = (f, tuple(args), frozenset(kwargs.items()))
        if key not in cache:
            cache[key] = f(*args, **kwargs)
        return cache[key]
    return g


Paul McCarthy's avatar
Paul McCarthy committed
614
615
616
617
class ChecksumError(Exception):
    """Exception raised by the sha256 function if a file checksume does
    not match the expected checksum.
    """
618
619


620
def sha256(filename, check_against=None, blocksize=1048576):
Paul McCarthy's avatar
Paul McCarthy committed
621
622
623
    """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.
624
625
    """

Paul McCarthy's avatar
Paul McCarthy committed
626
    hashobj = hashlib.sha256()
627

Paul McCarthy's avatar
Paul McCarthy committed
628
629
630
631
632
633
    with open(filename, 'rb') as f:
        while True:
            block = f.read(blocksize)
            if len(block) == 0:
                break
            hashobj.update(block)
634

Paul McCarthy's avatar
Paul McCarthy committed
635
636
    checksum = hashobj.hexdigest()

637
    if check_against is not None:
Paul McCarthy's avatar
Paul McCarthy committed
638
        if checksum != check_against:
639
640
641
642
            raise ChecksumError('File {} does not match expected checksum '
                                '({})'.format(filename, check_against))

    return checksum
643
644


Paul McCarthy's avatar
Paul McCarthy committed
645
646
647
648
class DownloadFailed(Exception):
    """Exception type raised by the download_file function if a
    download fails for some reason.
    """
649
650


Paul McCarthy's avatar
Paul McCarthy committed
651
def download_file(url, destination, progress=None, blocksize=1048576):
Paul McCarthy's avatar
Paul McCarthy committed
652
653
    """Download a file from url, saving it to destination. """

654
655
    def default_progress(downloaded, total):
        pass
Paul McCarthy's avatar
Paul McCarthy committed
656

657
658
659
660
    if progress is None:
        progress = default_progress

    log.debug('Downloading %s ...', url)
Paul McCarthy's avatar
Paul McCarthy committed
661
662
663
664
665
666
667
668
669
670

    try:
        with urlrequest.urlopen(url) as req, \
             open(destination, 'wb') as outf:

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

            downloaded = 0

Paul McCarthy's avatar
Paul McCarthy committed
671
            progress(downloaded, total)
Paul McCarthy's avatar
Paul McCarthy committed
672
673
674
675
676
677
            while True:
                block = req.read(blocksize)
                if len(block) == 0:
                    break
                downloaded += len(block)
                outf.write(block)
678
                progress(downloaded, total)
Paul McCarthy's avatar
Paul McCarthy committed
679
680
681
682
683
684

    except urllib.error.HTTPError as e:
        raise DownloadFailed(f'A network error has occurred while '
                             f'trying to download {destname}') from e


685
686
687
688
689
690
class Process(object):
    """Container for a subprocess.Popen object, allowing non-blocking access
    to its standard output and error streams via separate queues.
    """

    def __init__(self, ctx, cmd, admin, **kwargs):
691

692
693
694
695
696
697
        self.ctx     = ctx
        self.cmd     = cmd
        self.admin   = admin
        self.stdoutq = queue.Queue()
        self.stderrq = queue.Queue()
        self.popen   = Process.run(self.ctx, self.cmd, self.admin)
698

699
700
701
702
703
704
705
        # threads for gathering stdout/stderr
        self.stdout_thread = threading.Thread(
            target=Process.forward_stream,
            args=(self.popen, self.popen.stdout, self.stdoutq))
        self.stderr_thread = threading.Thread(
            target=Process.forward_stream,
            args=(self.popen, self.popen.stderr, self.stderrq))
706

707
708
709
710
        self.stdout_thread.daemon = True
        self.stderr_thread.daemon = True
        self.stdout_thread.start()
        self.stderr_thread.start()
711
712


713
714
715
    @staticmethod
    def forward_stream(popen, stream, queue):
        """Runs cmd, and pushes lines from its stdout to the queue. """
716

717
718
719
720
721
722
723
        while popen.returncode is None:
            line = stream.readline()
            popen.poll()
            if line == '':
                break
            else:
                queue.put(line)
724

725
726
727
728
729
        # process finished, flush the stream
        line = stream.readline()
        while line != '':
            queue.put(line)
            line = stream.readline()
730

731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795

    @staticmethod
    def sudo_popen(cmd, password, **kwargs):
        """Runs "sudo cmd" using subprocess.Popen.
        Assumes that kwargs contains stdin=sp.PIPE
        """

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


    @staticmethod
    def run(ctx, cmd, admin=False):
        """Starts the given command, as administrator if requested. Returns
        the subprocess.Popen object.
        """

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

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

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

        cmd = shlex.split(cmd)

        # set universal_newlines to force text
        # based stdin/out on both py2 and py3
        kwargs = dict(stdin=sp.PIPE,
                      stdout=sp.PIPE,
                      stderr=sp.PIPE,
                      universal_newlines=True)

        if admin: proc = Process.sudo_popen(cmd, password, **kwargs)
        else:     proc = sp.Popen(          cmd, **kwargs)

        return proc


    @staticmethod
    def monitor_progress(ctx, cmd, total=None, **kwargs):
        """Creates a Process object to run cmd, 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:

            proc   = Process(ctx, cmd, **kwargs)
            nlines = 0
            while proc.popen.returncode is None:

                try:
                    line = proc.stdoutq.get(timeout=1)
                except queue.Empty:
                    continue

                nlines += 1
                prog.update(nlines, total)
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822


class UnsupportedPlatform(Exception):
    """Exception raised by the identify_platform function if FSL is not
    available on this platform.
    """


def list_available_versions(ctx):
    """Lists available FSL versions. """
    printmsg('Available FSL versions:', EMPHASIS)
    for version in ctx.manifest['versions']:
        if version == 'latest':
            continue
        printmsg(version, IMPORTANT, EMPHASIS)
        for build in ctx.manifest['versions'][version]:
            if build.get('cuda', '').strip() != '':
                template = '  {platform} [CUDA {cuda}]'
            else:
                template = '  {platform}'
            printmsg(template.format(**build), EMPHASIS, end=' ')
            printmsg(build['environment'], INFO)


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

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

827
    metadata = ctx.manifest['installer']['miniconda'][ctx.platform]
828

829
830
831
    url      = metadata['url']
    checksum = metadata['sha256']
    output   = metadata.get('output', '').strip()
832

833
834
    if output == '': output = None
    else:            output = int(output)
Paul McCarthy's avatar
Paul McCarthy committed
835

836
837
838
839
    # Download
    printmsg('Downloading miniconda from {}...'.format(url))
    # with Progress('MB', transform=Progress.bytes_to_mb) as prog:
    #     download_file(url, 'miniforge.sh', prog.update)
840
    sha256('miniforge.sh', checksum)
841
842
843

    # Install
    printmsg('Installing miniconda to {}...'.format(ctx.destdir))
844
    cmd = 'sh miniforge.sh -b -p {}'.format(ctx.destdir)
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
    Process.monitor_progress(ctx, cmd, output, admin=ctx.need_admin)

    # 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)

    Process.run(ctx, 'mv .condarc {}'.format(ctx.destdir, admin=ctx.need_admin))
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916


def install_fsl(ctx):
    """Install FSL into ctx.destdir (which is assumed to be a miniforge
    installation.
    """

    builds = ctx.manifest['versions'][ctx.args.fslversion][ctx.platform]
    for build in builds:
        if ctx.cuda == build.get('cuda', None):
            break
    else:
        raise

    if cudaver is not None:
        filename = 'fsl-{}-{}-cuda-{}.yml'.format(fslversion,
                                                  platform,
                                                  cudaver)
    else:
        filename = 'fsl-{}-{}.yml'.format(fslversion, platform)

    download_file(base + filename, 'environment.yml')

    conda = op.join(destdir, 'bin', 'conda')

    run(ctx, conda + ' env update -n base -f environment.yml',
        admin=ctx.need_admin)


def configure_environment(ctx):
    """Configures the user's shell environment (e.g. ~/.bash_profile). """
    # TODO
    pass


Paul McCarthy's avatar
Paul McCarthy committed
917
def self_update(ctx):
918
    """Checks to see if a newer version of the installer (this script) is
919
    available and if so, downloads it to a temporary file, and runs it in
Paul McCarthy's avatar
Paul McCarthy committed
920
    place of this script.
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
    """

    @ft.total_ordering
    class Version(object):
        """Class to hold and compare FSL installer version strings.  Version
        strings must be of the form X.Y.Z, where X, Y, and Z are all integers.
        """
        def __init__(self, verstr):
            major, minor, patch = verstr.split('.')[:3]
            self.verstr         = verstr
            self.major          = int(major)
            self.minor          = int(minor)
            self.patch          = int(patch)

        def __str__(self):
            return self.verstr

        def __eq__(self, other):
            return all((self.major == other.major,
                        self.minor == other.minor,
                        self.patch == other.patch))

        def __lt__(self, other):
            for p1, p2 in zip((self.major,  self.minor,  self.patch),
                              (other.major, other.minor, other.patch)):
                if p1 < p2: return True
                if p1 > p2: return False
            return False

    thisver   = Version(__version__)
Paul McCarthy's avatar
Paul McCarthy committed
951
    latestver = Version(ctx.manifest['installer']['version'])
952
953
954
955
956
957

    if latestver <= thisver:
        log.debug('Installer is up to date (this vesrion: %s, '
                  'latest version: %s)', thisver, latestver)
        return

Paul McCarthy's avatar
Paul McCarthy committed
958
959
    log.debug('New version of installer is available '
              '(%s) - self-updating', latestver)
960

Paul McCarthy's avatar
Paul McCarthy committed
961
962
963
    tmpf = tempfile.NamedTemporaryFile(delete=False)
    tmpf.close()
    tmpf = tmpf.name
964

Paul McCarthy's avatar
Paul McCarthy committed
965
    download_file(ctx.manifest['installer']['url'], tmpf)
966
967
968

    if not ctx.args.disable_checksum:
        sha256(tmpf, ctx.manifest['installer']['sha256'])
969

Paul McCarthy's avatar
Paul McCarthy committed
970
971
972
    cmd = [sys.executable, tmpf] + sys.argv[1:]
    log.debug('Running new installer: %s', cmd)
    os.execv(sys.executable, cmd)
973
974


975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def overwrite_destdir(ctx):
    """Called by main if the destination directory already exists.
    Asks the user if they want to overwrite it and, if they say yes,
    removes the existing destination directory. Otherwise exits.
    """
    printmsg('Destination directory [{}] already exists!'
             .format(ctx.destdir), WARNING, EMPHASIS)
    response = prompt('Do you want to overwrite it [N/y]?',
                      WARNING, EMPHASIS)
    if response.lower() not in ('y', 'yes'):
        printmsg('Aborting installation', ERROR, EMPHASIS)
        sys.exit(1)

    printmsg('Deleting directory {}'.format(ctx.destdir), IMPORTANT)
    Process.run(ctx, 'rm -r {}'.format(ctx.destdir), admin=ctx.need_admin)




994
995
996
997
998
999
1000
def parse_args(argv=None):
    """Parse command-line arguments, returns an argparse.Namespace object. """

    helps = {
        'dest' :                'Install FSL into this folder (default: '
                                '{})'.format(DEFAULT_INSTALLATION_DIRECTORY),
        'version'             : 'Print installer version number and exit',
Paul McCarthy's avatar
Paul McCarthy committed
1001
        'disable_self_update' : 'Do not automatically update the installer '
1002
1003
1004
1005
1006
                                'script',
        'listversions'        : 'List available versions of FSL',
        'fslversion'          : 'Download this specific version of FSL',
        'cuda'                : 'Install FSL for this CUDA version (default: '
                                'automatically detected)',
Paul McCarthy's avatar
Paul McCarthy committed
1007
1008
1009
1010
1011
1012

        # Path to local installer manifest file
        'manifest'            : argparse.SUPPRESS,

        # Print debugging messages
        'debug'               : argparse.SUPPRESS,
1013
1014
1015

        # Disable SHA256 checksum validation of downloaded files
        'disable_checksum'    : argparse.SUPPRESS,
1016
1017
1018
1019

        # Store temp files in this directory (must already
        # exist) rather than in a temporary directory
        'workdir'             : argparse.SUPPRESS,
1020
1021
1022
    }

    parser = argparse.ArgumentParser()
1023
1024
1025
1026
    parser.add_argument('-v', '--version', action='version',
                        version=__version__, help=helps['version'])
    parser.add_argument('-D', '--debug', action='store_true',
                        help=helps['debug'])
Paul McCarthy's avatar
Paul McCarthy committed
1027
1028
    parser.add_argument('-m', '--manifest', default=FSL_INSTALLER_MANIFEST,
                        help=helps['manifest'])
1029
1030
1031
1032
    parser.add_argument('-u', '--disable_self_update', action='store_true',
                        help=helps['disable_self_update'])
    parser.add_argument('-d', '--dest', metavar='DESTDIR',
                        help=helps['dest'])
1033
1034
    parser.add_argument('-s', '--disable_checksum', action='store_true',
                        help=helps['disable_checksum'])
1035
    parser.add_argument('-w', '--workdir', help=helps['workdir'])
1036
1037
1038
1039
    parser.add_argument('-l', '--listversions', action='store_true',
                        help=helps['listversions'])
    parser.add_argument('-V', '--fslversion', default='latest',
                        help=helps['version'])
1040
    parser.add_argument('-c', '--cuda', help=helps['cuda'])
1041
1042

    args = parser.parse_args(argv)
1043

1044
    logging.basicConfig()
1045
1046
    if args.debug: logging.getLogger().setLevel(logging.DEBUG)
    else:          logging.getLogger().setLevel(logging.WARNING)
1047
1048

    return args
1049
1050
1051


def main(argv=None):
1052
1053

    args = parse_args(argv)
Paul McCarthy's avatar
Paul McCarthy committed
1054
1055
1056
1057
    ctx  = Context(args)

    if not args.disable_self_update:
        self_update(ctx)
1058

1059
1060
    printmsg('FSL installer version:', EMPHASIS, UNDERLINE, end='')
    printmsg(' ' + __version__ + '\n')
1061
1062

    if args.listversions:
Paul McCarthy's avatar
Paul McCarthy committed
1063
        list_available_versions(ctx)
1064
1065
        sys.exit(0)

1066
1067
    ctx.finalise_settings()

1068
1069
1070
1071
    if op.exists(ctx.destdir):
        overwrite_destdir(ctx)

    printmsg('Installing FSL into {}\n'.format(ctx.destdir), EMPHASIS)
1072

1073
    with tempdir(args.workdir):
1074
        install_miniconda(ctx)
1075
        #install_fsl(ctx)
1076
1077
1078
1079


if __name__ == '__main__':
    sys.exit(main())