Ejemplo n.º 1
0
 def disable(self, service):
     if not AbstractServiceManager.CHCONF_AVAILABLE:
         raise NotImplementedError()
     try:
         utils.execute('chkconfig', '--del', str(service))
     except ScalixExternalCommandFailed as _:
         return False
     return True
Ejemplo n.º 2
0
 def enable(self, service):
     if not AbstractServiceManager.CHCONF_AVAILABLE:
         raise NotImplementedError()
     try:
         cmd = ['chkconfig', '--level', '345', str(service), 'on']
         utils.execute(cmd)
     except ScalixExternalCommandFailed as _:
         return False
     return True
Ejemplo n.º 3
0
    def __init__(self, name):
        self.name = name
        self.__exists = False
        self.commands = []

        try:
            utils.execute('service', self.name)
        except ScalixExternalCommandFailed as exception:
            output = exception.stderr or exception.stdout
            commands = output.split(' ')[-1].strip()
            commands = commands.strip('{}')
            self.commands = [arg.strip() for arg in commands.split('|')]
            self.__exists = True
Ejemplo n.º 4
0
    def get_ips(self):
        """ get ips setted in system local netwoworks which starts with
        127.x.x.x or 192.x.x.x will ignore

        @rtype list
        @return list of ip's in system

        """
        #print(socket.gethostbyname(socket.gethostname()))
        try:
            lines = utils.execute("ip", "address", "|",
                                  utils.bash_command("grep"),
                                  "[[:space:]]inet[[:space:]]")

            pattern = r"inet\s(\d{1,3}[^127|^192]\.\d{1,3}\.\d{1,3}\.\d{1,3})"
            result = []
            for line in lines:
                match = re.match(pattern, line.strip())
                if match:
                    result.append(match.group(1))
            return result

        except ScalixExternalCommandException as exception:
            logger.warning("Could not get ips ", exception)
            return False
Ejemplo n.º 5
0
 def reload(self, force=False):
     if force:
         return self.force_reload()
     try:
         return utils.execute('service', self.name, 'reload')
     except ScalixExternalCommandException as exception:
         logger.critical("failed to reload service", exception)
Ejemplo n.º 6
0
    def get_ips(self):
        """ get ips setted in system local netwoworks which starts with
        127.x.x.x or 192.x.x.x will ignore

        @rtype list
        @return list of ip's in system

        """
        #print(socket.gethostbyname(socket.gethostname()))
        try:
            lines = utils.execute("ip", "address", "|",
                                  utils.bash_command("grep"),
                                  "[[:space:]]inet[[:space:]]")

            pattern = r"inet\s(\d{1,3}[^127|^192]\.\d{1,3}\.\d{1,3}\.\d{1,3})"
            result = []
            for line in lines:
                match = re.match(pattern, line.strip())
                if match:
                    result.append(match.group(1))
            return result

        except ScalixExternalCommandException as exception:
            logger.warning("Could not get ips ", exception)
            return False
Ejemplo n.º 7
0
 def run_levels(self):
     levels = []
     if AbstractServiceManager.CHCONF_AVAILABLE:
         try:
             lines = utils.execute('chkconfig', '--list', self.name)
             levels = re.findall(r'(\d)\:on', lines[0])
         except ScalixExternalCommandFailed as _:
             # got message service * supports chkconfig,
             # but is not referenced in any runlevel
             # (run 'chkconfig --add httpd')
             pass
     else:
         cmd = ['ls', '-1', '/etc/rc?.d/*{0}'.format(self.name)]
         lines = utils.execute(cmd, escape=False)
         levels = [line[7] for line in lines]
     return levels
Ejemplo n.º 8
0
 def is_running(self):
     cmd = [
         'ps', 'aux', '|',
         utils.bash_command('grep'),
         "$(echo '{0}' | sed s/^\(.\)/[\\1]/g )".format(self.name)
     ]
     lines = utils.execute(cmd)
     return not lines
Ejemplo n.º 9
0
 def __call__(self, *args):
     cmd = ['service', self.name]
     if args[0] not in self.commands:
         raise NotImplementedError(
             "Service {name} does not support {cmd}".format(name=self.name,
                                                            cmd=args[0]))
     cmd.append(*args)
     try:
         return utils.execute(cmd)
     except ScalixExternalCommandException as exception:
         logger.critical("Service init failed ", exception)
Ejemplo n.º 10
0
    def get_mx_records(self, domain):
        """ tries to get mx record for domain

        @type bool
        @return True or False

        """
        try:
            lines = utils.execute("dig", "-t", "MX", "+short", domain)
            return [i.strip() for i in lines]
        except ScalixExternalCommandException as exception:
            logger.warning("Could not get MX records ", exception)
            return False
Ejemplo n.º 11
0
    def get_mx_records(self, domain):
        """ tries to get mx record for domain

        @type bool
        @return True or False

        """
        try:
            lines = utils.execute("dig", "-t", "MX", "+short", domain)
            return [i.strip() for i in lines]
        except ScalixExternalCommandException as exception:
            logger.warning("Could not get MX records ", exception)
            return False
Ejemplo n.º 12
0
    def run_level(self):
        """Returns run level on linux

        @rtype: int
        @return int if could not determine run level it will return -1

        """
        try:
            cmd = ["runlevel", "|", utils.bash_command("gawk"), "'{print $2}'"]
            return int(utils.execute(cmd)[0])
        except ScalixExternalCommandException as exception:
            logger.critical("Could not get run level", exception)
            return -1
Ejemplo n.º 13
0
    def run_level(self):
        """Returns run level on linux

        @rtype: int
        @return int if could not determine run level it will return -1

        """
        try:
            cmd = ["runlevel", "|", utils.bash_command("gawk"), "'{print $2}'"]
            return int(utils.execute(cmd)[0])
        except ScalixExternalCommandException as exception:
            logger.critical("Could not get run level", exception)
            return -1
Ejemplo n.º 14
0
    def memory_total(self):
        """ get total memory in system(linux only)

        @rtype int
        @return total memory or -1 if something went wrong

        """
        try:
            #gawk '/MemTotal/ { print $2 }' /proc/meminfo
            result = utils.execute("gawk", "'/MemTotal/ { print $2 }'",
                               "/proc/meminfo")
            return int(result[0]) * 1024
        except ScalixExternalCommandException as exception:
            logger.critical("Could not get total memory", exception)
            return -1
Ejemplo n.º 15
0
    def memory_total(self):
        """ get total memory in system(linux only)

        @rtype int
        @return total memory or -1 if something went wrong

        """
        try:
            #gawk '/MemTotal/ { print $2 }' /proc/meminfo
            result = utils.execute("gawk", "'/MemTotal/ { print $2 }'",
                                   "/proc/meminfo")
            return int(result[0]) * 1024
        except ScalixExternalCommandException as exception:
            logger.critical("Could not get total memory", exception)
            return -1
Ejemplo n.º 16
0
    def get_java_version(raw=False):
        """get version of installed java virtual machine

        @return string if java installed and available in system or None if java
        not installed

        """
        try:
            lines = utils.execute("java", "-version")
            if raw or not lines:
                return lines
            version = re.search(r'^java version "(.*)"$', lines[0].strip())
            if version:
                return version.group(0)
        except ScalixExternalCommandException as exception:
            logger.warning("Could not get java version", exception)
Ejemplo n.º 17
0
    def get_java_version(raw=False):
        """get version of installed java virtual machine

        @return string if java installed and available in system or None if java
        not installed

        """
        try:
            lines = utils.execute("java", "-version")
            if raw or not lines:
                return lines
            version = re.search(r'^java version "(.*)"$', lines[0].strip())
            if version:
                return version.group(0)
        except ScalixExternalCommandException as exception:
            logger.warning("Could not get java version", exception)
Ejemplo n.º 18
0
    def memory_free(self):
        """ get free memory in system(linux only)
        @rtype int
        @return total memory or -1 if something went wrong

        """
        try:
            #"gawk '/MemFree/ { print $2 }' /proc/meminfo"
            cmd = [
                "gawk",
                "'/MemFree|Buffers|Cached/ {mem=mem+int($2)} END {print mem}'",
                "/proc/meminfo"
            ]
            return int(utils.execute(cmd)[0]) * 1024
        except ScalixExternalCommandException as exception:
            logger.critical("Could not get free memory", exception)
            return -1
Ejemplo n.º 19
0
    def memory_free(self):
        """ get free memory in system(linux only)
        @rtype int
        @return total memory or -1 if something went wrong

        """
        try:
            #"gawk '/MemFree/ { print $2 }' /proc/meminfo"
            cmd = [
                "gawk",
                "'/MemFree|Buffers|Cached/ {mem=mem+int($2)} END {print mem}'",
                "/proc/meminfo"
            ]
            return int(utils.execute(cmd)[0]) * 1024
        except ScalixExternalCommandException as exception:
            logger.critical("Could not get free memory", exception)
            return -1
Ejemplo n.º 20
0
    def listening_port(self, port):
        """checks if port opened

        @param port: port number integer
        @return: on success tulip which contain
        (Proto, Recv-Q, Send-Q, Local Address, Foreign Address, State)
        or False
        """

        try:
            result = utils.execute("netstat", "-ln", "|",
                                   utils.bash_command("grep"),
                                   ":{0:d}[^0-9]".format(port))
            return (i for i in result[0].strip().split())

        except ScalixExternalCommandException as exception:
            logger.warning("Could not get port is listening ", exception)
        return ()
Ejemplo n.º 21
0
    def listening_port(self, port):
        """checks if port opened

        @param port: port number integer
        @return: on success tulip which contain
        (Proto, Recv-Q, Send-Q, Local Address, Foreign Address, State)
        or False
        """

        try:
            result = utils.execute("netstat", "-ln", "|",
                                   utils.bash_command("grep"),
                                   ":{0:d}[^0-9]".format(port))
            return (i for i in result[0].strip().split())

        except ScalixExternalCommandException as exception:
            logger.warning("Could not get port is listening ", exception)
        return ()
Ejemplo n.º 22
0
    def determine_interface(self, ip_str):
        """ get network interface on which ip setted

        @param ip string
        @return string name of interface or None

        """
        try:
            cmd = ["ip", "addr", "show", "|", utils.bash_command("grep"),
                   "[[:space:]]inet[[:space:]]{0}/".format(ip_str), "|",
                   utils.bash_command("head"), "-1", "|",
                   utils.bash_command("gawk"), "'{ print $NF }'"]
            lines = utils.execute(cmd)
            if lines:
                return lines[0].strip()

        except ScalixExternalCommandException as exception:
            logger.warning("Could not determine interface", exception)
Ejemplo n.º 23
0
    def partition_size(self, folder):
        """ get folder size in system(linux only)

        @rtype int
        @param folder - string full path to the folder
        @return size or -1 if something went wrong some

        """
        try:
            #"df -lP %s | gawk '{print $4}'"
            result = utils.execute("df", "-BK", "-lP", folder, "|",
                                   utils.bash_command("gawk"), "'{print int($4)}'")
            try:
                return int(result[1]) * 1024
            except (UnicodeEncodeError, ValueError) as exception:
                logger.critical("Could not get partition size", exception,
                                result)
                return -1
        except ScalixExternalCommandException as exception:
            logger.critical("Could not get partition size", exception)
            return -1
Ejemplo n.º 24
0
    def determine_interface(self, ip_str):
        """ get network interface on which ip setted

        @param ip string
        @return string name of interface or None

        """
        try:
            cmd = [
                "ip", "addr", "show", "|",
                utils.bash_command("grep"),
                "[[:space:]]inet[[:space:]]{0}/".format(ip_str), "|",
                utils.bash_command("head"), "-1", "|",
                utils.bash_command("gawk"), "'{ print $NF }'"
            ]
            lines = utils.execute(cmd)
            if lines:
                return lines[0].strip()

        except ScalixExternalCommandException as exception:
            logger.warning("Could not determine interface", exception)
Ejemplo n.º 25
0
    def partition_size(self, folder):
        """ get folder size in system(linux only)

        @rtype int
        @param folder - string full path to the folder
        @return size or -1 if something went wrong some

        """
        try:
            #"df -lP %s | gawk '{print $4}'"
            result = utils.execute("df", "-BK", "-lP", folder, "|",
                                   utils.bash_command("gawk"),
                                   "'{print int($4)}'")
            try:
                return int(result[1]) * 1024
            except (UnicodeEncodeError, ValueError) as exception:
                logger.critical("Could not get partition size", exception,
                                result)
                return -1
        except ScalixExternalCommandException as exception:
            logger.critical("Could not get partition size", exception)
            return -1
Ejemplo n.º 26
0
 def stop(self):
     try:
         return utils.execute('service', self.name, 'stop')
     except ScalixExternalCommandException as exception:
         logger.critical("failed to stop service", exception)
Ejemplo n.º 27
0
 def enable(self, service):
     try:
         utils.execute('update-rc.d', str(service), 'defaults')
     except ScalixExternalCommandException as _:
         return False
     return True
Ejemplo n.º 28
0
 def disable(self, service):
     try:
         utils.execute('update-rc.d', '-f', str(service), 'remove')
     except ScalixExternalCommandException as _:
         return False
     return True
Ejemplo n.º 29
0
 def restart(self):
     try:
         return utils.execute('service', self.name, 'restart')
     except ScalixExternalCommandException as exception:
         logger.critical("failed to restart service", exception)
Ejemplo n.º 30
0
 def status(self):
     try:
         return utils.execute('service', self.name, 'status')[0]
     except ScalixExternalCommandException as exception:
         logger.critical("failed to get status of the service", exception)
Ejemplo n.º 31
0
 def force_reload(self):
     try:
         return utils.execute('service', self.name, 'force-reload')
     except ScalixExternalCommandException as exception:
         logger.critical("failed to force-reload service", exception)