예제 #1
0
def add_boot_entry():
    debug = 'debug' if os.getenv('LEAPP_DEBUG', '0') == '1' else ''

    kernel_dst_path, initram_dst_path = get_boot_file_paths()
    call([
        '/usr/sbin/grubby', '--add-kernel={0}'.format(kernel_dst_path),
        '--initrd={0}'.format(initram_dst_path),
        '--title=RHEL Upgrade Initramfs', '--copy-default', '--make-default',
        '--args="{DEBUG} enforcing=0 rd.plymouth=0 plymouth.enable=0"'.format(
            DEBUG=debug)
    ])
예제 #2
0
def enable_sctp():
    """
    Enables the SCTP module by removing it from being black listed.
    """

    api.current_logger().info('Enabling SCTP.')
    call([
        '/usr/bin/sed', '-i', 's/^\s*blacklist.*sctp/#&/',
        '/etc/modprobe.d/sctp_diag-blacklist.conf',
        '/etc/modprobe.d/sctp-blacklist.conf'
    ])
    api.current_logger().info('Enabled SCTP.')
예제 #3
0
def _get_active_kernel_modules(logger):
    lines = call(['lsmod'])
    for l in lines[1:]:
        name = l.split(' ')[0]

        # Read parameters of the given module as exposed by the
        # `/sys` VFS, if there are no parameters exposed we just
        # take the name of the module
        base_path = '/sys/module/{module}'.format(module=name)
        parameters_path = os.path.join(base_path, 'parameters')
        if not os.path.exists(parameters_path):
            yield ActiveKernelModule(filename=name, parameters=[])
            continue

        # Use `modinfo` to probe for signature information
        parameter_dict = {}
        try:
            signature = call(['modinfo', '-F', 'signature', name], split=False)
        except CalledProcessError:
            signature = None

        signature_string = None
        if signature:
            # Remove whitspace from the signature string
            signature_string = re.sub(r"\s+", "", signature, flags=re.UNICODE)

        # Since we're using the `/sys` VFS we need to use `os.listdir()` to get
        # all the property names and then just read from all the listed paths
        parameters = sorted(os.listdir(parameters_path))
        for param in parameters:
            try:
                with open(os.path.join(parameters_path, param),
                          mode='r') as fp:
                    parameter_dict[param] = fp.read().strip()
            except IOError as exc:
                # Some parameters are write-only, in that case we just log the name of parameter
                # and the module and continue
                if exc.errno in (errno.EACCES, errno.EPERM):
                    msg = 'Unable to read parameter "{param}" of kernel module "{name}"'
                    logger.warning(msg.format(param=param, name=name))
                else:
                    raise exc

        # Project the dictionary as a list of key values
        items = [
            KernelModuleParameter(name=k, value=v)
            for (k, v) in six.iteritems(parameter_dict)
        ]

        yield ActiveKernelModule(filename=name,
                                 parameters=items,
                                 signature=signature_string)
예제 #4
0
def was_sctp_used():
    """
    Determines whether SCTP has been used in the path month, by checking the journalctl.

    :return: True if SCTP usage has been found.
    :rtype: bool
    """
    try:
        call(['check_syslog_for_sctp.sh'])
    except CalledProcessError:
        api.current_logger().debug(
            'Nothing regarding SCTP was found on journal.')
        return False
    api.current_logger().debug('Found logs regarding SCTP on journal.')
    return True
예제 #5
0
    def process(self):
        nm_config = NetworkManagerConfig()
        try:
            # Use 'NM --print-config' to read the configurationo so
            # that the main configuration file and other files in
            # various directories get merged in the right way.
            r = call(['NetworkManager', '--print-config'], split=False)
        except (OSError, CalledProcessError) as e:
            self.log.warning(
                'Error reading NetworkManager configuration: {}'.format(e))
            return

        parser = ConfigParser()

        try:
            if hasattr(parser, 'read_string'):
                # Python 3
                parser.read_string(r)
            else:
                # Python 2
                from cStringIO import StringIO
                parser.readfp(StringIO(r))
        except ParsingError as e:
            self.log.warning(
                'Error parsing NetworkManager configuration: {}'.format(e))
            return

        if parser.has_option('main', 'dhcp'):
            nm_config.dhcp = parser.get("main", "dhcp")

        self.produce(nm_config)
예제 #6
0
 def save_iptables(self):
     ''' Save IPTables '''
     f = open('iptables_bck_workfile', 'w')
     ret = call(['iptables-save'])
     for line in ret:
         f.write(line+'\n')
     f.close()
예제 #7
0
def _get_repositories():
    def asbool(x):
        return x == 0

    @aslist
    def _parse(r):
        with open(r, mode='r') as fp:
            cp = configparser.ConfigParser()
            cp.readfp(fp)
            for section in cp.sections():
                prepared = {'repoid': section, 'additional_fields': {}}
                data = dict(cp.items(section))
                for key in data.keys():
                    if key in RepositoryData.fields:
                        if isinstance(RepositoryData.fields[key],
                                      fields.Boolean):
                            data[key] = asbool(data[key])
                        prepared[key] = data[key]
                    else:
                        prepared['additional_fields'][key] = data[key]
                prepared['additional_fields'] = json.dumps(
                    prepared['additional_fields'])
                yield RepositoryData(**prepared)

    repos = call(
        ['find', '/etc/yum.repos.d/', '-type', 'f', '-name', '*.repo'])
    for repo in repos:
        yield RepositoryFile(file=repo, data=_parse(repo))
예제 #8
0
    def process(self):
        nm_enabled = self.unit_enabled('NetworkManager.service')
        nmwo_enabled = self.unit_enabled('NetworkManager-wait-online.service')
        self.log_services_state('initial', nm_enabled, nmwo_enabled)

        if not nm_enabled and nmwo_enabled:
            self.log.info('Disabling NetworkManager-wait-online.service')

            try:
                call(['systemctl', 'disable', 'NetworkManager-wait-online.service'])
            except (OSError, CalledProcessError) as e:
                self.log.warning('Error disabling NetworkManager-wait-online.service: {}'.format(e))
                return

            nm_enabled = self.unit_enabled('NetworkManager.service')
            nmwo_enabled = self.unit_enabled('NetworkManager-wait-online.service')
            self.log_services_state('after upgrade', nm_enabled, nmwo_enabled)
예제 #9
0
def scan_pci_devices(producer):
    ''' Scan system PCI Devices '''
    try:
        output = call(['lspci', '-mm'])
    except subprocess.CalledProcessError:
        output = []

    devices = parse_pci_devices(output)
    produce_pci_devices(producer, devices)
예제 #10
0
 def unit_enabled(self, name):
     try:
         ret = call(['systemctl', 'is-enabled', name])
         if len(ret) > 0:
             enabled = ret[0] == 'enabled'
         else:
             enabled = False
     except (OSError, CalledProcessError):
         enabled = False
     return enabled
예제 #11
0
    def _get_firewall_status(service_name):
        try:
            ret_list = call(['systemctl', 'is-active', service_name])
            active = ret_list[0] == 'active'
        except CalledProcessError:
            active = False
            logger.debug('The %s service is likely not active' % service_name)

        try:
            ret_list = call(['systemctl', 'is-enabled', service_name])
            enabled = ret_list[0] == 'enabled'
        except CalledProcessError:
            enabled = False
            logger.debug('The %s service is likely not enabled nor running' %
                         service_name)

        return FirewallStatus(
            active=active,
            enabled=enabled,
        )
예제 #12
0
    def process(self):
        for nm_config in self.consume(NetworkManagerConfig):
            if nm_config.dhcp != '' and nm_config.dhcp != 'dhclient':
                self.log.info('DHCP client is {}, nothing to do'.format(
                    nm_config.dhcp))
                return

            try:
                r = call(['nm-update-client-ids.py'])
            except (OSError, CalledProcessError) as e:
                self.log.warning('Error calling script: {}'.format(e))
                return

            self.log.info('Updated client-ids: {}'.format(r))
예제 #13
0
def guard_call(cmd, guards=()):
    try:
        return call(cmd), None
    except subprocess.CalledProcessError as e:
        # return custom error if process failed
        error = ErrorData(details=str(e))

        # collect output from guards for possible spurious failure
        guard_errors = []
        for guard in guards:
            err = guard()
            if err:
                guard_errors.append(err)

        if guard_errors:
            error.spurious = '. Possible spurious failure: {cause}'.format(cause=' '.join(guard_errors))

        return None, error
예제 #14
0
def _get_sysctls():
    unstable = ('fs.dentry-state', 'fs.file-nr', 'fs.inode-nr',
                'fs.inode-state', 'kernel.random.uuid',
                'kernel.random.entropy_avail', 'kernel.ns_last_pid',
                'net.netfilter.nf_conntrack_count',
                'net.netfilter.nf_conntrack_events', 'kernel.sched_domain.',
                'dev.cdrom.info', 'kernel.pty.nr')

    variables = []
    for sc in call(['sysctl', '-a']):
        name = sc.split(' ', 1)[0]
        # if the sysctl name has an unstable prefix, we skip
        if anyhasprefix(name, unstable):
            continue
        variables.append(sc)

    # sort our variables so they can be diffed directly when needed
    for var in sorted(variables):
        name, value = tuple(map(type(var).strip, var.split('=')))
        yield SysctlVariable(name=name, value=value)
예제 #15
0
def test_check_multiline_output():
    a_command = ['echo', 'This a multi-\nline test!']
    assert call(a_command) == [u'This a multi-', u'line test!']
예제 #16
0
def test_check_single_line_output():
    a_command = ['echo', 'This a single line test!']
    assert call(a_command) == [u'This a single line test!']
예제 #17
0
 def disable_iptables(self):
     ''' Save, stop and disable IPTables '''
     self.save_iptables()
     self.flush_iptables()
     self.stop_iptables()
     call(['systemctl', 'disable', 'iptables'])
예제 #18
0
 def flush_iptables(self):
     ''' Flush rules '''
     call(['iptables', '-F'])
예제 #19
0
 def stop_iptables(self):
     ''' Stop IPTables '''
     call(['systemctl', 'stop', 'iptables'])
예제 #20
0
def test_check_single_line_output_no_split():
    a_command = ['echo', 'This a single line No Split test!']
    assert call(a_command,
                split=False) == u'This a single line No Split test!\n'
예제 #21
0
 def disable_firewalld(self):
     ''' Disable FirewallD '''
     self.stop_firewalld()
     call(['systemctl', 'disable', 'firewalld'])
예제 #22
0
 def stop_firewalld(self):
     ''' Stop FirewallD '''
     call(['systemctl', 'stop', 'firewalld'])
예제 #23
0
def is_xfs_without_ftype(mp):
    for l in call(['/usr/sbin/xfs_info', '{}'.format(mp)]):
        if 'ftype=0' in l:
            return True
    
    return False
예제 #24
0
def test_check_multiline_output_no_split():
    a_command = ['echo', 'This a multi-\nline No Split test!']
    assert call(a_command,
                split=False) == u'This a multi-\nline No Split test!\n'