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) ])
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.')
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)
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
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)
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()
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))
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)
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)
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
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, )
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))
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
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)
def test_check_multiline_output(): a_command = ['echo', 'This a multi-\nline test!'] assert call(a_command) == [u'This a multi-', u'line test!']
def test_check_single_line_output(): a_command = ['echo', 'This a single line test!'] assert call(a_command) == [u'This a single line test!']
def disable_iptables(self): ''' Save, stop and disable IPTables ''' self.save_iptables() self.flush_iptables() self.stop_iptables() call(['systemctl', 'disable', 'iptables'])
def flush_iptables(self): ''' Flush rules ''' call(['iptables', '-F'])
def stop_iptables(self): ''' Stop IPTables ''' call(['systemctl', 'stop', 'iptables'])
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'
def disable_firewalld(self): ''' Disable FirewallD ''' self.stop_firewalld() call(['systemctl', 'disable', 'firewalld'])
def stop_firewalld(self): ''' Stop FirewallD ''' call(['systemctl', 'stop', 'firewalld'])
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
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'