Skip to content
Snippets Groups Projects
envsetup.py 7.08 KiB
Newer Older
Stéphane Diemer's avatar
Stéphane Diemer committed
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Environment setup script for MediaServer
'''
import imp
import os
import sys
import traceback

import utils
from utils import log


class EnvSetup():
    PY_SETUP_NAME = '0_setup.py'
    BASH_SETUP_NAME = '0_setup.sh'

    def __init__(self, *args):
        self.display_header()
Stéphane Diemer's avatar
Stéphane Diemer committed
        args = list(args)
        # Check current dir
        root_dir = utils.get_dir(__file__)
        if root_dir != '':
            os.chdir(root_dir)
        # Add to python path
        if root_dir not in sys.path:
            sys.path.append(root_dir)
        # Get available actions
        self.root_dir = root_dir
        names = os.listdir(root_dir)
        self.actions = list()
        for name in names:
            path = os.path.join(root_dir, name)
            if os.path.isdir(path):
                try:
                    index = int(name.split('.')[0])
                except ValueError:
                    continue
                label = name[len(str(index)) + 1:].strip()
                if not label:
                    log('No label found for dir %s.' % name)
                    continue
                if os.path.isfile(os.path.join(path, self.PY_SETUP_NAME)):
                    setup_module = imp.load_source('setup_%s' % name, os.path.join(path, self.PY_SETUP_NAME))
                    self.actions.append(dict(index=index, label=label, path=path, fct=setup_module.setup))
                elif os.path.isfile(os.path.join(path, self.BASH_SETUP_NAME)):
                    self.actions.append(dict(index=index, label=label, path=path, fct='bash -e "%s"' % os.path.join(path, self.BASH_SETUP_NAME)))
Stéphane Diemer's avatar
Stéphane Diemer committed
                else:
                    self.actions.append(dict(index=index, label=label, path=path, fct=None))
        self.actions.sort(key=lambda a: a['index'])
        if not self.actions:
            log('No action available.')
            sys.exit(1)
        # Check that this script is run by root
        debug = '-d' in args
        if debug:
            args.remove('-d')
        code, out = utils.exec_cmd(['whoami'], get_out=True)
        if out != 'root' and not debug:
            log('This script should be run as root user.')
            sys.exit(1)
        # Load conf
        utils.load_conf()
        if args:
            # Run command
            for arg in args:
                self.run(arg, interactive=False)
        else:
            # Open main menu
            self.menu()

    def display_header(self):
        log('\033[96m-------------------------------------\033[0m')
        log('\033[96m- Environment setup for MediaServer -\033[0m')
        log('\033[96m-------------------------------------\033[0m')

Stéphane Diemer's avatar
Stéphane Diemer committed
    def menu(self):
        # Show main menu
        log('Actions:')
        for action in self.actions:
            if action['fct']:
                log('  %s: %s' % (action['index'], action['label']))
            else:
                log('  \033[1;94m%s\033[0m' % (action['label']))
        log('')
        log('  t: Run tests')
        log('  c: Configuration status')
Stéphane Diemer's avatar
Stéphane Diemer committed
        log('  e: Exit\n')
        log('Info:')
        log('\033[0;36m  To setup a system entirely for a determined purpose (Worker, MS, CM, ...), you can use envsetup-launcher:\033[0m')
        log('\033[0;36m  bash /root/envsetup/envsetup-launcher.sh\033[0m')
        log('\nWhat action do you want to start ?')
        try:
            target = input('---> ').strip()
        except (KeyboardInterrupt, EOFError):
            log('')
            target = 'e'
        self.run(target)

    def run(self, target, interactive=True):
        if target == 'e':
            log('Exit')
            sys.exit(0)
        exit_code = 0
        if target == 't':
            # Run tests
            path = os.path.join(self.root_dir, 'tests')
            if not os.path.isdir(path):
                exit_code = 1
                log('The tests dir is missing (%s).' % path)
            else:
                os.chdir(path)
                names = os.listdir(path)
                names.sort()
                results = list()
                for name in names:
                    log('\033[1;95m-- Test "%s" --\033[0;0m' % name)
                    test_path = os.path.join(path, name)
                    try:
                        code = utils.exec_cmd(test_path)
                        if code != 0:
                            raise Exception('Command exited with code %s.' % code)
                    except Exception as e:
                        exit_code = 1
                        log(e)
                        results.append((False, test_path))
                    else:
                        results.append((True, test_path))
                log('\nTests results:')
                for success, test_path in results:
                    if success:
                        log('  %s: \033[92msuccess\033[0m' % test_path)
                    else:
                        log('  %s: \033[91mfailure\033[0m' % test_path)
        elif target == 'c':
            # Display current configuration
            log('Configuration status:')
            override = utils.get_conf('_override')
            if not override:
                log('Configuration status not available.')
            else:
                log('Is default | Name | Value')
                for name, is_overriden in override.items():
                    is_default = '\033[93m no ' if is_overriden else '\033[94m yes'
                    log('%s\033[0m | \033[95m%s\033[0m | \033[96m%s\033[0m' % (is_default, name, utils.get_conf(name)))
Stéphane Diemer's avatar
Stéphane Diemer committed
        else:
            # Run an action
            found = False
            for action in self.actions:
                if target == str(action['index']) and action['fct']:
                    found = True
                    log('Starting action %s: %s setup.' % (action['index'], action['label']))
Stéphane Diemer's avatar
Stéphane Diemer committed
                    log('Please wait, the setup is in progress...    ')
                    try:
                        os.chdir(action['path'])
                        if isinstance(action['fct'], str):
                            utils.run_commands([action['fct']])
Stéphane Diemer's avatar
Stéphane Diemer committed
                        else:
                            action['fct'](interactive)
                    except Exception as e:
                        exit_code = 1
                        if isinstance(action['fct'], str):
                            log(action['fct'])
                        else:
                            log(traceback.format_exc())
                        log('Unable to setup %s:\n%s\n' % (action['label'], e))
                    else:
                        log('%s setup complete.\n' % action['label'])
                    os.chdir(self.root_dir)
                    break
            if not found:
                exit_code = 1
                log('Invalid action requested: "%s".' % target)
        if interactive:
            try:
                input('Press enter to continue.')
            except (KeyboardInterrupt, EOFError):
                log('')
                sys.exit(exit_code)
            self.display_header()
Stéphane Diemer's avatar
Stéphane Diemer committed
            self.menu()
        else:
            sys.exit(exit_code)


if __name__ == '__main__':
    EnvSetup(*sys.argv[1:])