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
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
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
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
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)
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
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
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)
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
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
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
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)
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
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 ()
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)
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
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)
def stop(self): try: return utils.execute('service', self.name, 'stop') except ScalixExternalCommandException as exception: logger.critical("failed to stop service", exception)
def enable(self, service): try: utils.execute('update-rc.d', str(service), 'defaults') except ScalixExternalCommandException as _: return False return True
def disable(self, service): try: utils.execute('update-rc.d', '-f', str(service), 'remove') except ScalixExternalCommandException as _: return False return True
def restart(self): try: return utils.execute('service', self.name, 'restart') except ScalixExternalCommandException as exception: logger.critical("failed to restart service", exception)
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)
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)