Beispiel #1
0
 def configure_kernel_variables(self):
     logger.info('Configuring sysctl variables')
     kvars = self.conf.get_subset(m_class=model.system.SysctlVariable)
     conf_files.SysctlFile(kvars).apply()
     c = Command('sysctl --system')
     c.run()
     c.watch_output()
Beispiel #2
0
 def setup_hostname(self):
     hostname = self.conf.get_hostname()
     logger.info('Setting up hostname %s', hostname)
     cf = conf_files.HostnameConfFile(hostname)
     cf.apply()
     c = Command('hostname -F %s' % cf.get_path())
     c.run()
     c.watch_output()
Beispiel #3
0
 def install_packages(self):
     pkgs = self.conf.get_subset(m_type=model.system.Package)
     install_cmd = self._INSTALLER + ' '.join([str(pkg.value) for pkg in pkgs])
     c = Command(install_cmd)
     c.run()
     out, retcode = c.watch_output()
     logger.info(out)
Beispiel #4
0
 def install_special_packages(self):
     spec_pkgs = self.conf.get_subset(m_type=model.system.SpecialPackage)
     for pkg in spec_pkgs:
         install_cmd = self._INSTALLER_COMMAND_TEMPLATE.render(installer=self._INSTALLER, pkg=pkg)
         c = Command(install_cmd)
         c.run()
         out, retcode = c.watch_output()
         logger.info(out)
Beispiel #5
0
 def install_packages(self):
     pkgs = self.conf.get_subset(m_type=model.system.Package)
     for pkg in pkgs:
         install_cmd = self._INSTALLER + pkg.value
         c = Command(install_cmd)
         c.run()
         out, _ = c.watch_output()
         logger.info(out)
Beispiel #6
0
 def run_service_cmd(cls, action, service):
     if action == cls.Actions.ENABLE:
         c = Command(f'chkconfig {service.name} on')
     elif action == cls.Actions.DISABLE:
         c = Command(f'chkconfig {service.name} off')
     else:
         c = Command(f'service {service.name} {action.value}')
     c.run()
     return c.watch_output()
Beispiel #7
0
 def get_package_version(cls, package) -> Optional[str]:
     rpm_cmd = Command('%s -qa %s' % (cls.CMD_RPM, package))
     rpm_cmd.run()
     out, ret_code = rpm_cmd.watch_output()
     if ret_code == 0 and len(out):
         first_match = out.split()[0]  # strip whitespaces
         #  "kernel-4.18.0-67.el8.x86_64".split("kernel-") -> [[], ['4.18.0-67.el8.x86_64']]
         return first_match.split('%s-' % package)[1]
     else:
         return None
Beispiel #8
0
 def get_profile():
     cmd = Command('tuned-adm active')
     cmd.run()
     out, ret = cmd.watch_output()
     if ret:
         return None
     re_match = re.search(r'.*: (.*)\n', out)
     if re_match:
         return re_match.group(1)
     else:
         return None
Beispiel #9
0
    def generate_pcp_config(self):
        for pcp in self.conf.get_subset(m_type=model.system.PCPConfiguration):
            logger.info(f'Generating PCP configuration: {pcp}')
            if os.path.exists(pcp.config_path):
                logger.info('PCP config already exists >> Deleting ')
                os.remove(pcp.config_path)

            os.makedirs(pcp.log_path, exist_ok=True)
            cmd = Command(f'pmlogconf -c {pcp.config_path}').run()
            out, ret_code = cmd.watch_output()
            if ret_code:
                logger.error(f'PCP cannot generate configuration! Log: {out}')
Beispiel #10
0
 def submit(self):
     logger.info('Starting rsync results')
     for rsync in self.configuration.get_subset(m_class=RsyncHost):
         logger.info('Rsyncing results to %s', ':'.join([rsync.server, rsync.destination]))
         c = Command(self._RSYNC_TEMPLATE.render(path=self.package.path, rsync=rsync))
         c.run()
         out, ret = c.watch_output()
         if not ret:
             logger.info('Rsync successful')
         else:
             logger.error('Rsync failed')
             logger.error(out)
Beispiel #11
0
    def parse_output_into_dict():
        cmd = Command('lscpu')
        ret_dict = {}
        cmd.run()
        out, ret_code = cmd.watch_output()
        for line in out.split('\n'):
            if line:  # skip blank line
                first_double_dot = line.find(':')
                ret_dict[
                    line[:first_double_dot].strip()] = line[first_double_dot +
                                                            1:].strip()

        return ret_dict
Beispiel #12
0
 def set_profile(profile):
     cmd = Command('tuned-adm profile %s' % profile)
     cmd.run()
     return cmd.watch_output()
Beispiel #13
0
 def setenforce(level):
     cmd = Command('setenforce %s' % level)
     cmd.run()
     out, ret_code = cmd.watch_output()
     return out
Beispiel #14
0
 def run_service_cmd(cls, action, service):
     c = Command(f'systemctl {action.value} {service.name}')
     c.run()
     return c.watch_output()
Beispiel #15
0
class CommandTool(object):

    PROGRAM_NAME = ''
    MAPPING: List[CommandArgument] = []

    def __init__(self, **kwargs):
        super().__init__()

        self._init_class_attr()  # set object attributes from MAPPING
        self.__dict__.update(
            kwargs)  # update object attributes with constructor arguments

        self._cmd = None
        self._exit_code = None
        self._output = None

    def __str__(self):
        def str_mapping():
            """
            Nicely format object attributes when printing to stdout
            :return: str
            """
            ret_str = ''
            for arg in self.MAPPING:
                ret_str += '\t{} {}\n'.format(arg.class_name,
                                              self.__dict__[arg.class_name])
            return ret_str

        return '{}\n{}'.format(self.PROGRAM_NAME, str_mapping())

    def __call__(self):
        self.run()

    def _init_class_attr(self):
        """
        Create object attributes for each argument defined in MAPPING.
        """
        for arg in self.MAPPING:
            self.__dict__[arg.class_name] = arg.default_value

    def _make_cli_args(self, args):
        """
        Create arguments for program from arguments list. There might be more argument lists, so this method is generic
        for each list.
        :param args: arguments list
        :return: formated string of attributes
        """
        ret_str = ''
        for arg in args:
            arg_value = self.__dict__[arg.class_name]
            if arg_value is not None:
                if arg.argument_type == bool:  # True/False argument
                    ret_str += ' {}'.format(arg.argument_name)
                else:  # key value argument
                    ret_str += ' {} {}'.format(arg.argument_name, arg_value)

            elif arg.required:  # if required and not set-> error
                raise MissingRequiredArgument(
                    'Argument {} is required in {} command.'.format(
                        arg.argument_name, self.PROGRAM_NAME))

        return ret_str

    def _make_cmd(self):
        """
        Create Command object from name of program and local attributes
        :return: Command object
        """
        return self.PROGRAM_NAME + self._make_cli_args(self.MAPPING)

    def run(self):
        """
        Execute current command.
        """
        self._cmd = Command(self._make_cmd())
        self._cmd.run()

    def watch_output(self):
        """
        Wait for end of program and return stdout of process.
        :return: stdout, exit code
        """
        if self._output is None and self._exit_code is None:
            self._output, self._exit_code = self._cmd.watch_output()
        return self._output, self._exit_code

    def clone(self):
        """
        Create a duplicate of current object and delete reference to running process.
        :return: object clone
        """
        cloned = self.__class__(**self.__dict__)
        cloned._cmd, cloned._exit_code, cloned._output = None, None, None
        return cloned

    def success(self):
        """
        Check if program execution was OK.
        :return: True if success else False
        """
        return self._exit_code == 0

    def clear(self):
        """
        Kill process and delete reference to Command obj
        """
        self._cmd.terminate()
        self._cmd, self._exit_code, self._output = None, None, None