mirror of
https://github.com/YunoHost/moulinette.git
synced 2024-09-03 20:06:31 +02:00
Refactor monitor functions
This commit is contained in:
parent
6b7213f511
commit
f00d6081ff
2 changed files with 90 additions and 167 deletions
88
yunohost.py
88
yunohost.py
|
@ -17,9 +17,9 @@ if not __debug__:
|
||||||
|
|
||||||
|
|
||||||
def colorize(astr, color):
|
def colorize(astr, color):
|
||||||
"""
|
"""
|
||||||
Print with style ;)
|
Print with style ;)
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
astr -- String to colorize
|
astr -- String to colorize
|
||||||
color -- Name of the color
|
color -- Name of the color
|
||||||
|
@ -32,27 +32,27 @@ def colorize(astr, color):
|
||||||
'cyan' : '34',
|
'cyan' : '34',
|
||||||
'purple': '35'
|
'purple': '35'
|
||||||
}
|
}
|
||||||
return "\033["+ color_dict[color] +"m\033[1m" + astr + "\033[m"
|
return "\033["+ color_dict[color] +"m\033[1m" + astr + "\033[m"
|
||||||
|
|
||||||
def pretty_print_dict(d, depth=0):
|
def pretty_print_dict(d, depth=0):
|
||||||
for k,v in sorted(d.items(), key=lambda x: x[0]):
|
for k,v in sorted(d.items(), key=lambda x: x[0]):
|
||||||
k = colorize(k, 'purple')
|
k = colorize(str(k), 'purple')
|
||||||
if isinstance(v, list) and len(v) == 1:
|
if isinstance(v, list) and len(v) == 1:
|
||||||
v = v[0]
|
v = v[0]
|
||||||
if isinstance(v, dict):
|
if isinstance(v, dict):
|
||||||
print((" ") * depth + ("%s: " % k))
|
print((" ") * depth + ("%s: " % str(k)))
|
||||||
pretty_print_dict(v, depth+1)
|
pretty_print_dict(v, depth+1)
|
||||||
elif isinstance(v, list):
|
elif isinstance(v, list):
|
||||||
print((" ") * depth + ("%s: " % k))
|
print((" ") * depth + ("%s: " % str(k)))
|
||||||
for value in v:
|
for value in v:
|
||||||
print((" ") * (depth+1) + "- " +str(value))
|
print((" ") * (depth+1) + "- " +str(value))
|
||||||
else:
|
else:
|
||||||
print((" ") * depth + "%s: %s" % (k, str(v)))
|
print((" ") * depth + "%s: %s" % (str(k), str(v)))
|
||||||
|
|
||||||
def win_msg(astr):
|
def win_msg(astr):
|
||||||
"""
|
"""
|
||||||
Display a success message if isatty
|
Display a success message if isatty
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
astr -- Win message to display
|
astr -- Win message to display
|
||||||
|
|
||||||
|
@ -64,11 +64,11 @@ def win_msg(astr):
|
||||||
def str_to_func(astr):
|
def str_to_func(astr):
|
||||||
"""
|
"""
|
||||||
Call a function from a string name
|
Call a function from a string name
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
astr -- Name of function to call
|
astr -- Name of function to call
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Function
|
Function
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
@ -79,7 +79,7 @@ def str_to_func(astr):
|
||||||
mod = sys.modules[module]
|
mod = sys.modules[module]
|
||||||
else:
|
else:
|
||||||
mod = sys.modules['__main__'] # default module
|
mod = sys.modules['__main__'] # default module
|
||||||
|
|
||||||
func = getattr(mod, function)
|
func = getattr(mod, function)
|
||||||
except (AttributeError, ImportError):
|
except (AttributeError, ImportError):
|
||||||
#raise YunoHostError(168, _('Function is not defined'))
|
#raise YunoHostError(168, _('Function is not defined'))
|
||||||
|
@ -89,9 +89,9 @@ def str_to_func(astr):
|
||||||
|
|
||||||
|
|
||||||
def validate(pattern, array):
|
def validate(pattern, array):
|
||||||
"""
|
"""
|
||||||
Validate attributes with a pattern
|
Validate attributes with a pattern
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
pattern -- Regex to match with the strings
|
pattern -- Regex to match with the strings
|
||||||
array -- List of strings to check
|
array -- List of strings to check
|
||||||
|
@ -110,9 +110,9 @@ def validate(pattern, array):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def get_required_args(args, required_args, password=False):
|
def get_required_args(args, required_args, password=False):
|
||||||
"""
|
"""
|
||||||
Input missing values or raise Exception
|
Input missing values or raise Exception
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
args -- Available arguments
|
args -- Available arguments
|
||||||
required_args -- Dictionary of required arguments and input phrase
|
required_args -- Dictionary of required arguments and input phrase
|
||||||
|
@ -130,7 +130,7 @@ def get_required_args(args, required_args, password=False):
|
||||||
else:
|
else:
|
||||||
raise Exception #FIX
|
raise Exception #FIX
|
||||||
# Password
|
# Password
|
||||||
if 'password' in required_args and password:
|
if 'password' in required_args and password:
|
||||||
if not args['password']:
|
if not args['password']:
|
||||||
if os.isatty(1):
|
if os.isatty(1):
|
||||||
args['password'] = getpass.getpass(colorize(required_args['password'] + ': ', 'cyan'))
|
args['password'] = getpass.getpass(colorize(required_args['password'] + ': ', 'cyan'))
|
||||||
|
@ -161,7 +161,7 @@ def display_error(error):
|
||||||
class YunoHostError(Exception):
|
class YunoHostError(Exception):
|
||||||
"""
|
"""
|
||||||
Custom exception
|
Custom exception
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
code -- Integer error code
|
code -- Integer error code
|
||||||
message -- Error message to display
|
message -- Error message to display
|
||||||
|
@ -208,9 +208,9 @@ class YunoHostLDAP(Singleton):
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def __init__(self, password=False):
|
def __init__(self, password=False):
|
||||||
"""
|
"""
|
||||||
Connect to LDAP base
|
Connect to LDAP base
|
||||||
|
|
||||||
Initialize to localhost, base yunohost.org, prompt for password
|
Initialize to localhost, base yunohost.org, prompt for password
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
@ -235,9 +235,9 @@ class YunoHostLDAP(Singleton):
|
||||||
except: pass
|
except: pass
|
||||||
|
|
||||||
def disconnect(self):
|
def disconnect(self):
|
||||||
"""
|
"""
|
||||||
Unbind from LDAP
|
Unbind from LDAP
|
||||||
|
|
||||||
Returns
|
Returns
|
||||||
Boolean | YunoHostError
|
Boolean | YunoHostError
|
||||||
|
|
||||||
|
@ -251,9 +251,9 @@ class YunoHostLDAP(Singleton):
|
||||||
|
|
||||||
|
|
||||||
def search(self, base=None, filter='(objectClass=*)', attrs=['dn']):
|
def search(self, base=None, filter='(objectClass=*)', attrs=['dn']):
|
||||||
"""
|
"""
|
||||||
Search in LDAP base
|
Search in LDAP base
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
base -- Base to search into
|
base -- Base to search into
|
||||||
filter -- LDAP filter
|
filter -- LDAP filter
|
||||||
|
@ -278,15 +278,15 @@ class YunoHostLDAP(Singleton):
|
||||||
if 'dn' in attrs:
|
if 'dn' in attrs:
|
||||||
entry['dn'] = [dn]
|
entry['dn'] = [dn]
|
||||||
result_list.append(entry)
|
result_list.append(entry)
|
||||||
return result_list
|
return result_list
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def add(self, rdn, attr_dict):
|
def add(self, rdn, attr_dict):
|
||||||
"""
|
"""
|
||||||
Add LDAP entry
|
Add LDAP entry
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
rdn -- DN without domain
|
rdn -- DN without domain
|
||||||
attr_dict -- Dictionnary of attributes/values to add
|
attr_dict -- Dictionnary of attributes/values to add
|
||||||
|
@ -306,9 +306,9 @@ class YunoHostLDAP(Singleton):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def remove(self, rdn):
|
def remove(self, rdn):
|
||||||
"""
|
"""
|
||||||
Remove LDAP entry
|
Remove LDAP entry
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
rdn -- DN without domain
|
rdn -- DN without domain
|
||||||
|
|
||||||
|
@ -326,9 +326,9 @@ class YunoHostLDAP(Singleton):
|
||||||
|
|
||||||
|
|
||||||
def update(self, rdn, attr_dict, new_rdn=False):
|
def update(self, rdn, attr_dict, new_rdn=False):
|
||||||
"""
|
"""
|
||||||
Modify LDAP entry
|
Modify LDAP entry
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
rdn -- DN without domain
|
rdn -- DN without domain
|
||||||
attr_dict -- Dictionnary of attributes/values to add
|
attr_dict -- Dictionnary of attributes/values to add
|
||||||
|
@ -355,9 +355,9 @@ class YunoHostLDAP(Singleton):
|
||||||
|
|
||||||
|
|
||||||
def validate_uniqueness(self, value_dict):
|
def validate_uniqueness(self, value_dict):
|
||||||
"""
|
"""
|
||||||
Check uniqueness of values
|
Check uniqueness of values
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
value_dict -- Dictionnary of attributes/values to check
|
value_dict -- Dictionnary of attributes/values to check
|
||||||
|
|
||||||
|
|
|
@ -1,24 +1,14 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
import os
|
import xmlrpclib
|
||||||
import sys
|
import json
|
||||||
import subprocess
|
import psutil
|
||||||
from urllib import urlopen
|
from urllib import urlopen
|
||||||
try:
|
|
||||||
import psutil
|
|
||||||
except ImportError:
|
|
||||||
sys.stderr.write('Error: Yunohost CLI Require psutil\n')
|
|
||||||
sys.stderr.write('apt-get install python-psutil\n')
|
|
||||||
sys.exit(1)
|
|
||||||
try:
|
|
||||||
import netifaces
|
|
||||||
except ImportError:
|
|
||||||
sys.stderr.write('Error: Yunohost CLI Require netifaces\n')
|
|
||||||
sys.stderr.write('apt-get install python-netifaces\n')
|
|
||||||
sys.exit(1)
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from yunohost import YunoHostError, win_msg, colorize, validate, get_required_args
|
from yunohost import YunoHostError, win_msg, colorize, validate, get_required_args
|
||||||
|
|
||||||
|
s = xmlrpclib.ServerProxy('http://127.0.0.1:61209')
|
||||||
|
|
||||||
def bytes2human(n):
|
def bytes2human(n):
|
||||||
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
|
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
|
||||||
prefix = {}
|
prefix = {}
|
||||||
|
@ -30,91 +20,10 @@ def bytes2human(n):
|
||||||
return '%.1f%s' % (value, s)
|
return '%.1f%s' % (value, s)
|
||||||
return "%sB" % n
|
return "%sB" % n
|
||||||
|
|
||||||
def check_disk():
|
|
||||||
result = {}
|
|
||||||
for part in psutil.disk_partitions(all=False):
|
|
||||||
usage = psutil.disk_usage(part.mountpoint)
|
|
||||||
result[part.mountpoint] = { 'Total' : str(bytes2human(usage.total)), 'Used' : str(bytes2human(usage.used)),
|
|
||||||
'Free' : str(bytes2human(usage.free)), 'Percent' : str(usage.percent) + '%' }
|
|
||||||
return { 'Partition' : result }
|
|
||||||
|
|
||||||
def check_cpu():
|
|
||||||
return { 'CPU' : psutil.cpu_percent(interval=3) }
|
|
||||||
|
|
||||||
def check_memory():
|
|
||||||
mem = getattr(psutil.phymem_usage(), "total")
|
|
||||||
memused = getattr(psutil.phymem_usage(), "used")
|
|
||||||
mempercent = getattr(psutil.phymem_usage(), "percent")
|
|
||||||
swap = getattr(psutil.virtmem_usage(), "total")
|
|
||||||
swapused = getattr(psutil.virtmem_usage(), "used")
|
|
||||||
swappercent = getattr(psutil.virtmem_usage(), "percent")
|
|
||||||
return { 'Memory' : { 'Total' : str(bytes2human(mem)), 'Used' : str(bytes2human(memused)), 'Percent' : str(mempercent) + '%' },
|
|
||||||
'Swap' : { 'Total' : str(bytes2human(swap)), 'Used' : str(bytes2human(swapused)), 'Percent' : str(swappercent) + '%' } }
|
|
||||||
|
|
||||||
def ifconfig():
|
|
||||||
listinterfaces = netifaces.interfaces()[1:]
|
|
||||||
for interface in listinterfaces:
|
|
||||||
try:
|
|
||||||
for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]:
|
|
||||||
ip = link['addr']
|
|
||||||
for link in netifaces.ifaddresses(interface)[netifaces.AF_LINK]:
|
|
||||||
mac = link['addr']
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
return { 'IP' : ip, 'MAC' : mac }
|
|
||||||
|
|
||||||
def uptime():
|
|
||||||
uptime = (str(datetime.now() - datetime.fromtimestamp(psutil.BOOT_TIME)).split('.')[0])
|
|
||||||
return { 'Uptime' : uptime }
|
|
||||||
|
|
||||||
def public():
|
|
||||||
try:
|
|
||||||
ip = str(urlopen('http://ip.yunohost.org').read())
|
|
||||||
except:
|
|
||||||
raise YunoHostError(1, _("No connection") )
|
|
||||||
return { 'Public IP' : ip }
|
|
||||||
|
|
||||||
def public():
|
|
||||||
try:
|
|
||||||
ip = str(urlopen('http://ip.yunohost.org').read())
|
|
||||||
except:
|
|
||||||
raise YunoHostError(1, "No connection" )
|
|
||||||
return { _("Public IP"): ip }
|
|
||||||
|
|
||||||
def processcount():
|
|
||||||
processcount = {'total': 0, 'running': 0, 'sleeping': 0}
|
|
||||||
process_all = [proc for proc in psutil.process_iter()]
|
|
||||||
for proc in process_all:
|
|
||||||
try:
|
|
||||||
if not proc.is_running():
|
|
||||||
try:
|
|
||||||
process_all.remove(proc)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
except psutil.error.NoSuchProcess:
|
|
||||||
try:
|
|
||||||
self.process_all.remove(proc)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
try:
|
|
||||||
processcount[str(proc.status)] += 1
|
|
||||||
except psutil.error.NoSuchProcess:
|
|
||||||
pass
|
|
||||||
except KeyError:
|
|
||||||
processcount[str(proc.status)] = 1
|
|
||||||
finally:
|
|
||||||
processcount['total'] += 1
|
|
||||||
try:
|
|
||||||
process.append(self.__get_process_stats__(proc))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return { 'Total' : str(processcount['total']), 'Running' : str(processcount['running']), 'Sleeping' : str(processcount['sleeping']) }
|
|
||||||
|
|
||||||
def process_enable(args):
|
def process_enable(args):
|
||||||
output = subprocess.Popen(['update-rc.d', args, 'defaults'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
output = subprocess.Popen(['update-rc.d', args, 'defaults'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
||||||
if output.wait() == 0:
|
if output.wait() == 0:
|
||||||
resultat = process_start(args)
|
return process_start(args)
|
||||||
return resultat
|
return resultat
|
||||||
else:
|
else:
|
||||||
raise YunoHostError(1, 'Enable : ' + args.title() + " " + _("failure"))
|
raise YunoHostError(1, 'Enable : ' + args.title() + " " + _("failure"))
|
||||||
|
@ -122,7 +31,7 @@ def process_enable(args):
|
||||||
def process_disable(args):
|
def process_disable(args):
|
||||||
output = subprocess.Popen(['update-rc.d', args, 'remove'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
output = subprocess.Popen(['update-rc.d', args, 'remove'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
||||||
if output.wait() == 0:
|
if output.wait() == 0:
|
||||||
resultat = process_stop(args)
|
return process_stop(args)
|
||||||
return resultat
|
return resultat
|
||||||
else:
|
else:
|
||||||
raise YunoHostError(1, 'Disable : ' + args.title() + " " + _("failure"))
|
raise YunoHostError(1, 'Disable : ' + args.title() + " " + _("failure"))
|
||||||
|
@ -155,41 +64,55 @@ def process_check(args):
|
||||||
|
|
||||||
|
|
||||||
def monitor_info(memory=False, cpu=False, disk=False, ifconfig=False, uptime=False, public=False):
|
def monitor_info(memory=False, cpu=False, disk=False, ifconfig=False, uptime=False, public=False):
|
||||||
|
|
||||||
if memory:
|
if memory:
|
||||||
resultat = check_memory()
|
return json.loads(s.getMem())
|
||||||
return resultat
|
|
||||||
elif cpu:
|
elif cpu:
|
||||||
resultat = check_cpu()
|
return json.loads(s.getLoad())
|
||||||
return resultat
|
|
||||||
elif disk:
|
|
||||||
resultat = check_disk()
|
|
||||||
return resultat
|
|
||||||
elif ifconfig:
|
elif ifconfig:
|
||||||
resultat = ifconfig()
|
# TODO: c'est pas ifconfig ça ;)
|
||||||
return resultat
|
result = {}
|
||||||
|
for k, fs in enumerate(json.loads(s.getNetwork())):
|
||||||
|
interface = fs['interface_name']
|
||||||
|
del fs['interface_name']
|
||||||
|
result[interface] = fs
|
||||||
|
return result
|
||||||
|
|
||||||
|
elif disk:
|
||||||
|
result = {}
|
||||||
|
for k, fs in enumerate(json.loads(s.getFs())):
|
||||||
|
if fs['fs_type'] != 'tmpfs' and fs['fs_type'] != 'rpc_pipefs':
|
||||||
|
mnt_point = str(fs['mnt_point'])
|
||||||
|
del fs['mnt_point']
|
||||||
|
result[mnt_point] = fs
|
||||||
|
return result
|
||||||
|
|
||||||
elif uptime:
|
elif uptime:
|
||||||
resultat = uptime()
|
uptime_value = (str(datetime.now() - datetime.fromtimestamp(psutil.BOOT_TIME)).split('.')[0])
|
||||||
return resultat
|
return { 'Uptime' : uptime_value }
|
||||||
|
|
||||||
elif public:
|
elif public:
|
||||||
resultat = public()
|
try:
|
||||||
return resultat
|
ip = str(urlopen('http://ip.yunohost.org').read())
|
||||||
|
except:
|
||||||
|
raise YunoHostError(1, _("No connection") )
|
||||||
|
return { 'Public IP' : ip }
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise YunoHostError(1, _('No arguments provided'))
|
||||||
|
|
||||||
def monitor_process(enable=None, disable=None, start=None, stop=None, check=None, info=False):
|
def monitor_process(enable=None, disable=None, start=None, stop=None, check=None, info=False):
|
||||||
if enable:
|
if enable:
|
||||||
resultat = process_enable(enable)
|
return process_enable(enable)
|
||||||
return resultat
|
|
||||||
elif disable:
|
elif disable:
|
||||||
resultat = process_disable(disable)
|
return process_disable(disable)
|
||||||
return resultat
|
|
||||||
elif start:
|
elif start:
|
||||||
resultat = process_start(start)
|
return process_start(start)
|
||||||
return resultat
|
|
||||||
elif stop:
|
elif stop:
|
||||||
resultat = process_stop(stop)
|
return process_stop(stop)
|
||||||
return resultat
|
|
||||||
elif check:
|
elif check:
|
||||||
resultat = process_check(check)
|
return process_check(check)
|
||||||
return resultat
|
|
||||||
elif info:
|
elif info:
|
||||||
resultat = processcount()
|
return json.loads(s.getProcessCount())
|
||||||
return resultat
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue