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


7
from __future__ import print_function, division
8
9


10
11
12
13
14
15
16
17
import functools      as ft
import os.path        as op
import subprocess     as sp
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
27
28
29
30
31
32
33
34
# TODO check py2/3
import                   urllib
import urllib.parse   as urlparse
import urllib.request as urlrequest


log = logging.getLogger(__name__)


Paul McCarthy's avatar
Paul McCarthy committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
__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
manifest file is a JSON file which contains information about available
FSL versions. See the download_installer_manifest function for more
details.
"""


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


class Context(object):
    """Bag of information and settings created in main, and passed around
    this script.
    """

    def __init__(self, args):
        self.args     = args
        self.platform = Context.identify_platform()
        self.cuda     = Context.identify_cuda()

        # These attributes are updated on-demand via
        # the property accessors defined below.
        self.__destdir        = args.dest
        self.__need_admin     = None
        self.__admin_password = None
        self.__manifest       = None


    @property
    def destdir(self):
        if self.__destdir is None:
            printmsg('Where do you want to install FSL?', IMPORTANT, EMPHASIS)
            printmsg('Press enter to install to the default '
                     'location [{}]'.format(DEFAULT_INSTALLATION_DIRECTORY),
                     INFO)
            self.__destdir = prompt('FSL installation directory:', QUESTION)
        return self.__destdir


    @property
    def need_admin(self):
        if self.__need_admin is not None:
            return self.__need_admin
        if self.__destdir is None:
            raise RuntimeError('Destination directory has not been set')
        self.__need_admin = Context.check_need_admin(self.destdir)


    @property
    def admin_password(self):
        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):
        if self.__manifest is None:
            self.__manifest = Context.download_manifest(self.args.manifest)
        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',
            # ARM builds will be added in the future
            ('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
        string containing the 'X.Y' CUDA version, or None if CUDA is not supported.
        """

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

        cudaver = '9.2'  # todo
        cudaver = float(output)
        match   = None

        # Return the most suitable CUDA
        # version that we have a build for
        supported_cudas = [9.2, 10.2, 11.1]
        for supported in reversed(supported_cudas):
            if cudaver <= supported:
                match = supported
                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):
            printmsg("Checking sudo password", INFO)
            cmd = sp.Popen(shlex.split('sudo -S true'),
                           stdin=PIPE,
                           stdout=DEVNULL,
                           stderr=DEVNULL)
            cmd.stdin.write(sudo_pwd + '\n')
            cmd.stdin.flush()
            cmd.communicate()
            return cmd.returncode == 0

        printmsg('We need your administrator password to install FSL: ',
                 IMPORTANT, end='', flush=True)

        for _ in range(3):
            password = getpass.getpass('')
            valid    = validate_admin_password(password)

            if valid: break
            else:     printmsg("Incorrect password", WARNING)

        if not valid:
            raise InvalidPassword()

        return password


    @staticmethod
    def download_manifest(url):
        """Downloads the installer manifest file, which contains information
        about available FSL vesrions, and the most recent version number of the
        installer (this script).

        The manifest file is a JSON file with the following structure:

            {
              "installer" : {
                "version" : "1.2.3",         # Latest version of installer script
                "url"     : "http://abc.com" # URL to download installer script
                "sha256"  : "ab238........." # SHA256 checksum of installer script
              }
              "versions" : {

                # TODO
              }
            }
        """

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

        with tempdir():
            download_file(url, 'manifest.json')
            with open('manifest.json') as f:
                manifest = f.read()

        return json.loads(manifest)


238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# 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 = {
    INFO      : '\033[37m',
    IMPORTANT : '\033[92m',
    QUESTION  : '\033[36m\033[4m',
    PROMPT    : '\033[36m\033[1m',
    WARNING   : '\033[93m',
    ERROR     : '\033[91m',
    EMPHASIS  : '\033[1m',
    UNDERLINE : '\033[4m',
    RESET     : '\033[0m',
}


def printmsg(msg, *msgtypes, **kwargs):
    """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)


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


@contextlib.contextmanager
def tempdir():
    """Returns a context manager which creates and returns a temporary
    directory, and then deletes it on exit.
    """

    testdir = tempfile.mkdtemp()
    prevdir = os.getcwd()

    try:
        os.chdir(testdir)
        yield testdir

    finally:
        os.chdir(prevdir)
        shutil.rmtree(testdir)


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
309
310
311
312
class ChecksumError(Exception):
    """Exception raised by the sha256 function if a file checksume does
    not match the expected checksum.
    """
313
314


Paul McCarthy's avatar
Paul McCarthy committed
315
316
317
318
def sha256(filename, blocksize=1048576, check_against=None):
    """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.
319
320
    """

Paul McCarthy's avatar
Paul McCarthy committed
321
    hashobj = hashlib.sha256()
322

Paul McCarthy's avatar
Paul McCarthy committed
323
324
325
326
327
328
    with open(filename, 'rb') as f:
        while True:
            block = f.read(blocksize)
            if len(block) == 0:
                break
            hashobj.update(block)
329

Paul McCarthy's avatar
Paul McCarthy committed
330
331
332
333
334
335
    checksum = hashobj.hexdigest()

    if check_against:
        if checksum != check_against:
            raise ChecksumError('File {} does not match expected checksum: '
                                '{}'.format(filename, check_against))
336
337


Paul McCarthy's avatar
Paul McCarthy committed
338
339
340
341
class DownloadFailed(Exception):
    """Exception type raised by the download_file function if a
    download fails for some reason.
    """
342
343


Paul McCarthy's avatar
Paul McCarthy committed
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def download_file(url, destination, blocksize=1048576):
    """Download a file from url, saving it to destination. """

    def report_progress(downloaded, total):
        downloaded = downloaded / 1048576
        total      = total      / 1048576
        if total is not None:
            msg = '{:.1f} / {:.1f}MB ...'.format(downloaded, total)
        else:
            msg = '{:.1f}MB ...'.format(downloaded)
        printmsg(msg, end='\r')

    printmsg('Downloading {} ...'.format(url))

    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

            while True:
                block = req.read(blocksize)
                if len(block) == 0:
                    break
                downloaded += len(block)
                outf.write(block)
                report_progress(downloaded, total)

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


def self_update(ctx):
381
    """Checks to see if a newer version of the installer (this script) is
Paul McCarthy's avatar
Paul McCarthy committed
382
383
    available and if so, downloads it as a temporary file, and runs it in
    place of this script.
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
    """

    @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
414
    latestver = Version(ctx.manifest['installer']['version'])
415
416
417
418
419
420

    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
421
422
    log.debug('New version of installer is available '
              '(%s) - self-updating', latestver)
423

Paul McCarthy's avatar
Paul McCarthy committed
424
425
426
    tmpf = tempfile.NamedTemporaryFile(delete=False)
    tmpf.close()
    tmpf = tmpf.name
427

Paul McCarthy's avatar
Paul McCarthy committed
428
429
    download_file(ctx.manifest['installer']['url'], tmpf)
    sha256(tmpf, check_against=ctx.manifest['installer']['sha256'])
430

Paul McCarthy's avatar
Paul McCarthy committed
431
432
433
    cmd = [sys.executable, tmpf] + sys.argv[1:]
    log.debug('Running new installer: %s', cmd)
    os.execv(sys.executable, cmd)
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459


def run(cmd, admin=False, display_output=False):
    """Runs the given command, as administrator if requested. """
    admin = admin and os.getuid() != 0
    cmd   = shlex.split(cmd)

    if admin:
        password = get_admin_password()
        cmd      = ['sudo', '-S'] + cmd
        proc     = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)

        proc.stdin.write(password + '\n')
        proc.stdin.flush()
    else:
        proc = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)

    (output, error) = proc.communicate()


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


Paul McCarthy's avatar
Paul McCarthy committed
460
def list_available_versions(ctx):
461
    """Lists available FSL versions. """
Paul McCarthy's avatar
Paul McCarthy committed
462
    manifest = download_installer_manifest()
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


def install_miniforge(platform, destdir, **kwargs):
    """Downloads the miniforge installer, and installs it to destdir.
    Keyword arguments are passed through to the run function.
    """

    url_base = 'https://github.com/conda-forge/miniforge/' \
               'releases/latest/download/'
    urls     = {
        'linux-64' : url_base + 'Miniforge3-Linux-x86_64.sh',
        'macos-64' : url_base + 'Miniforge3-MacOSX-x86_64.sh',
    }

    download_file(urls[platform], 'miniforge.sh')

    run('sh miniforge.sh -b -p {}'.format(destdir), **kwargs)


def install_fsl(destdir, fslversion, platform, cudaver, **kwargs):
    """Install FSL into destdir (which is assumed to be a miniforge
    installation.

    Keyword arguments are passed through to the run function.
    """
    base = 'http://18.133.213.73/fslinstaller/'

    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(conda + ' env update -n base -f environment.yml', **kwargs)


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
511
        'disable_self_update' : 'Do not automatically update the installer '
512
513
514
515
516
                                '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
517
518
519
520
521
522

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

        # Print debugging messages
        'debug'               : argparse.SUPPRESS,
523
524
525
    }

    parser = argparse.ArgumentParser()
526
527
528
529
    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
530
531
    parser.add_argument('-m', '--manifest', default=FSL_INSTALLER_MANIFEST,
                        help=helps['manifest'])
532
533
534
535
536
537
538
539
540
541
542
543
    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'])
    parser.add_argument('-l', '--listversions', action='store_true',
                        help=helps['listversions'])
    parser.add_argument('-V', '--fslversion', default='latest',
                        help=helps['version'])
    parser.add_argument('-c', '--cuda', default='latest',
                        help=helps['cuda'])

    args = parser.parse_args(argv)
544

545
546
    logging.basicConfig()
    if args.debug:
Paul McCarthy's avatar
Paul McCarthy committed
547
        logging.getLogger().setLevel(logging.DEBUG)
548
    else:
Paul McCarthy's avatar
Paul McCarthy committed
549
        logging.getLogger().setLevel(logging.WARNING)
550
551

    return args
552
553
554


def main(argv=None):
555
556

    args = parse_args(argv)
Paul McCarthy's avatar
Paul McCarthy committed
557
558
559
560
    ctx  = Context(args)

    if not args.disable_self_update:
        self_update(ctx)
561
562
563
564
565

    printmsg('FSL installer version: ', EMPHASIS, end='')
    printmsg(__version__ + '\n')

    if args.listversions:
Paul McCarthy's avatar
Paul McCarthy committed
566
        list_available_versions(ctx)
567
568
        sys.exit(0)

Paul McCarthy's avatar
Paul McCarthy committed
569
570
    ctx.need_admin     = need_admin(args.dest)
    ctx.admin_password = get_admin_password()
571
572

    with tempdir():
Paul McCarthy's avatar
Paul McCarthy committed
573
574
        install_miniforge(ctx)
        install_fsl(ctx)
575
576
577
578


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