Beispiel #1
0
def main():
    """Test all the switchmap-ng modules with unittests.

    Args:
        None

    Returns:
        None

    """
    # Determine unittest directory
    root_dir = general.root_directory()
    test_dir = ('%s/switchmap/test') % (root_dir)

    # Get list of test files
    test_files = os.listdir(test_dir)
    for filename in sorted(test_files):
        full_path = ('%s/%s') % (test_dir, filename)

        # Run the test
        if filename.startswith('test_'):
            run_script(full_path)

    # Print
    message = ('\nHooray - All Done OK!\n')
    print(message)
Beispiel #2
0
 def test_root_directory(self):
     """Testing method / function root_directory."""
     # Initializing key variables
     # Determine root directory for switchmap
     switchmap_dir = switchmap.__path__[0]
     components = switchmap_dir.split(os.sep)
     # Determine root directory 2 levels above
     root_dir = os.sep.join(components[0:-2])
     result = general.root_directory()
     self.assertEqual(result, root_dir)
Beispiel #3
0
    def __init__(self):
        """Method for intializing the class.

        Args:
            None

        Returns:
            None

        """
        # Initialize key variables
        self.root = ('%s/.switchmap') % (general.root_directory())
Beispiel #4
0
    def validate(self):
        """Validate .

        Args:
            None

        Returns:
            None

        """
        # Initialize key variables
        username = getpass.getuser()
        added_suggestions = ''
        line = '*' * 80
        prefix = """\

1) Edit file {}/etc/config.yaml with correct SNMP parameters \
and then restart the daemons.
2) You can restart switchmap-ng daemons with these commands:

   $ bin/switchmap-ng-cil restart api
   $ bin/switchmap-ng-cli restart poller
""".format(general.root_directory())

        #######################################################################
        #
        # Give suggestions as to what to do
        #
        # NOTE!
        #
        # The root user should only use the systemctl commands as the daemons
        # could be running as another user and lock and pid files will be owned
        # by that user. We don't want the daemons to crash at some other time
        # because these files are owned by root with denied delete privileges
        #######################################################################
        if username != 'root':
            added_suggestions = """{}
3) Switchmap-NG will not automatically restart after a reboot. \
You need to re-install as the "root" user for this to occur.
""".format(prefix)

            print('{}\n{}\n{}\n'.format(line, added_suggestions, line))
        else:
            print('{}\n{}\n{}\n'.format(line, prefix, line))

        # All done
        setup.print_ok(
            'Installation complete, pending changes mentioned above.')
Beispiel #5
0
    def _start(self, daemon, restart=False):
        """Start or restart daemon.

        Args:
            daemon: Name of daemon
            restart: Restart if True

        Returns:
            None

        """
        # Initialize key variables
        username = getpass.getuser()
        running = False
        if restart is True:
            attempt = 'restart'
        else:
            attempt = 'start'

        # Get status
        root_directory = general.root_directory()
        if restart is False:
            if username == 'root':
                script_name = (
                    '/bin/systemctl start {}.service'.format(daemon))
            else:
                script_name = (
                    '{}/bin/systemd/{} --start'.format(root_directory, daemon))
        else:
            if username == 'root':
                script_name = (
                    '/bin/systemctl restart {}.service'.format(daemon))
            else:
                script_name = (
                    '{}/bin/systemd/{} --restart --force'
                    ''.format(root_directory, daemon))

        # Attempt to restart / start
        response = general.run_script(script_name, die=False)
        if bool(response['returncode']) is True:
            log_message = ('Could not {} daemon {}.'.format(attempt, daemon))
            log.log2see_safe(1127, log_message)

        # Return after waiting for daemons to startup properly
        running = self._running(daemon)
        return running
Beispiel #6
0
    def __init__(self):
        """Function for intializing the class.

        Args:
            None

        Returns:
            None

        """
        # Initialize key variables
        running_username = getpass.getuser()
        daemon_username = configuration.Config().username()
        self.root_directory = general.root_directory()
        switchmap_user_exists = True
        self.switchmap_user = None
        self.running_as_root = False

        # Set the username we need to be running as
        if running_username == 'root':
            try:
                # Get GID and UID for user
                self.switchmap_user = daemon_username
                self.gid = getpwnam(self.switchmap_user).pw_gid
                self.uid = getpwnam(self.switchmap_user).pw_uid
            except KeyError:
                switchmap_user_exists = False

            # Die if user doesn't exist
            if switchmap_user_exists is False:
                log_message = (
                    'User {} not found. Please try again.'
                    ''.format(self.switchmap_user))
                log.log2die_safe(1129, log_message)
        else:
            self.switchmap_user = daemon_username

        # If running as the root user, then the switchmap user needs to exist
        if running_username == 'root':
            self.running_as_root = True
            return
Beispiel #7
0
    def _install_pip3_packages(self):
        """Install PIP3 packages.

        Args:
            None

        Returns:
            None

        """
        # Initialize key variables
        username = self.username

        # Don't attempt to install packages if running in the Travis CI
        # environment
        if 'TRAVIS' in os.environ and 'CI' in os.environ:
            return

        # Determine whether PIP3 exists
        print_ok(
            'Installing required pip3 packages from requirements.txt file.')
        pip3 = general.search_file('pip3')
        if pip3 is None:
            log_message = ('Cannot find python "pip3". Please install.')
            log.log2die_safe(1052, log_message)

        # Install required PIP packages
        requirements_file = (
            '%s/requirements.txt') % (general.root_directory())

        if username == 'root':
            script_name = (
                'pip3 install --upgrade --requirement %s'
                '') % (requirements_file)
        else:
            script_name = (
                'pip3 install --user --upgrade --requirement %s'
                '') % (requirements_file)
        general.run_script(script_name)
Beispiel #8
0
    def _create_directory_entries(self, key, _config):
        """Update the configuration with good defaults for directories.

        Args:
            key: Configuration key related to a directory.
            _config: Configuration dictionary

        Returns:
            updated: True if we have to update a value

        """
        # Initialize key variables
        updated = False
        config = copy.deepcopy(_config)
        dir_dict = {
            'log_directory': 'log',
            'cache_directory': 'cache',
        }
        directory = general.root_directory()

        # Setup the key value to a known good default
        if key in config['main']:
            # Verify whether key value is empty
            if config['main'][key] is not None:
                # Create
                if os.path.isdir(config['main'][key]) is False:
                    config['main'][key] = ('%s/%s') % (
                        directory, dir_dict[key])
                    updated = True
            else:
                config['main'][key] = ('%s/%s') % (directory, dir_dict[key])
                updated = True
        else:
            config['main'][key] = ('%s/%s') % (directory, dir_dict[key])
            updated = True

        # Return
        return (updated, config)
Beispiel #9
0
    def __init__(self):
        """Function for intializing the class.

        Args:
            None

        Returns:
            None

        """
        # Initialize key variables
        self.none = None
        self.root_directory = general.root_directory()
        # Update the configuration directory
        # 'SWITCHMAP_CONFIGDIR' is used for unittesting
        if 'SWITCHMAP_CONFIGDIR' in os.environ:
            config_directory = os.environ['SWITCHMAP_CONFIGDIR']
        else:
            config_directory = '{}/etc'.format(self.root_directory)
        directories = [config_directory]

        # Return
        self.config_dict = general.read_yaml_files(directories)
Beispiel #10
0
    def test_config_directories(self):
        """Testing method / function config_directories."""
        # Initializing key variables
        # Initialize key variables
        save_directory = None

        if 'SWITCHMAP_CONFIGDIR' in os.environ:
            save_directory = os.environ['SWITCHMAP_CONFIGDIR']

            # Try with no SWITCHMAP_CONFIGDIR
            os.environ.pop('SWITCHMAP_CONFIGDIR', None)
            directory = '{}/etc'.format(general.root_directory())
            result = general.config_directories()
            self.assertEqual(result, [directory])

        # Test with SWITCHMAP_CONFIGDIR set
        directory = tempfile.mkdtemp()
        os.environ['SWITCHMAP_CONFIGDIR'] = directory
        result = general.config_directories()
        self.assertEqual(result, [directory])

        # Restore state
        if save_directory is not None:
            os.environ['SWITCHMAP_CONFIGDIR'] = save_directory