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):
|
||||
"""
|
||||
Print with style ;)
|
||||
|
||||
"""
|
||||
Print with style ;)
|
||||
|
||||
Keyword arguments:
|
||||
astr -- String to colorize
|
||||
color -- Name of the color
|
||||
|
@ -32,27 +32,27 @@ def colorize(astr, color):
|
|||
'cyan' : '34',
|
||||
'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):
|
||||
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:
|
||||
v = v[0]
|
||||
if isinstance(v, dict):
|
||||
print((" ") * depth + ("%s: " % k))
|
||||
print((" ") * depth + ("%s: " % str(k)))
|
||||
pretty_print_dict(v, depth+1)
|
||||
elif isinstance(v, list):
|
||||
print((" ") * depth + ("%s: " % k))
|
||||
print((" ") * depth + ("%s: " % str(k)))
|
||||
for value in v:
|
||||
print((" ") * (depth+1) + "- " +str(value))
|
||||
else:
|
||||
print((" ") * depth + "%s: %s" % (k, str(v)))
|
||||
print((" ") * depth + "%s: %s" % (str(k), str(v)))
|
||||
|
||||
def win_msg(astr):
|
||||
"""
|
||||
Display a success message if isatty
|
||||
|
||||
"""
|
||||
Display a success message if isatty
|
||||
|
||||
Keyword arguments:
|
||||
astr -- Win message to display
|
||||
|
||||
|
@ -64,11 +64,11 @@ def win_msg(astr):
|
|||
def str_to_func(astr):
|
||||
"""
|
||||
Call a function from a string name
|
||||
|
||||
|
||||
Keyword arguments:
|
||||
astr -- Name of function to call
|
||||
|
||||
Returns:
|
||||
|
||||
Returns:
|
||||
Function
|
||||
|
||||
"""
|
||||
|
@ -79,7 +79,7 @@ def str_to_func(astr):
|
|||
mod = sys.modules[module]
|
||||
else:
|
||||
mod = sys.modules['__main__'] # default module
|
||||
|
||||
|
||||
func = getattr(mod, function)
|
||||
except (AttributeError, ImportError):
|
||||
#raise YunoHostError(168, _('Function is not defined'))
|
||||
|
@ -89,9 +89,9 @@ def str_to_func(astr):
|
|||
|
||||
|
||||
def validate(pattern, array):
|
||||
"""
|
||||
Validate attributes with a pattern
|
||||
|
||||
"""
|
||||
Validate attributes with a pattern
|
||||
|
||||
Keyword arguments:
|
||||
pattern -- Regex to match with the strings
|
||||
array -- List of strings to check
|
||||
|
@ -110,9 +110,9 @@ def validate(pattern, array):
|
|||
return True
|
||||
|
||||
def get_required_args(args, required_args, password=False):
|
||||
"""
|
||||
"""
|
||||
Input missing values or raise Exception
|
||||
|
||||
|
||||
Keyword arguments:
|
||||
args -- Available arguments
|
||||
required_args -- Dictionary of required arguments and input phrase
|
||||
|
@ -130,7 +130,7 @@ def get_required_args(args, required_args, password=False):
|
|||
else:
|
||||
raise Exception #FIX
|
||||
# Password
|
||||
if 'password' in required_args and password:
|
||||
if 'password' in required_args and password:
|
||||
if not args['password']:
|
||||
if os.isatty(1):
|
||||
args['password'] = getpass.getpass(colorize(required_args['password'] + ': ', 'cyan'))
|
||||
|
@ -161,7 +161,7 @@ def display_error(error):
|
|||
class YunoHostError(Exception):
|
||||
"""
|
||||
Custom exception
|
||||
|
||||
|
||||
Keyword arguments:
|
||||
code -- Integer error code
|
||||
message -- Error message to display
|
||||
|
@ -208,9 +208,9 @@ class YunoHostLDAP(Singleton):
|
|||
return self
|
||||
|
||||
def __init__(self, password=False):
|
||||
"""
|
||||
Connect to LDAP base
|
||||
|
||||
"""
|
||||
Connect to LDAP base
|
||||
|
||||
Initialize to localhost, base yunohost.org, prompt for password
|
||||
|
||||
"""
|
||||
|
@ -235,9 +235,9 @@ class YunoHostLDAP(Singleton):
|
|||
except: pass
|
||||
|
||||
def disconnect(self):
|
||||
"""
|
||||
Unbind from LDAP
|
||||
|
||||
"""
|
||||
Unbind from LDAP
|
||||
|
||||
Returns
|
||||
Boolean | YunoHostError
|
||||
|
||||
|
@ -251,9 +251,9 @@ class YunoHostLDAP(Singleton):
|
|||
|
||||
|
||||
def search(self, base=None, filter='(objectClass=*)', attrs=['dn']):
|
||||
"""
|
||||
Search in LDAP base
|
||||
|
||||
"""
|
||||
Search in LDAP base
|
||||
|
||||
Keyword arguments:
|
||||
base -- Base to search into
|
||||
filter -- LDAP filter
|
||||
|
@ -278,15 +278,15 @@ class YunoHostLDAP(Singleton):
|
|||
if 'dn' in attrs:
|
||||
entry['dn'] = [dn]
|
||||
result_list.append(entry)
|
||||
return result_list
|
||||
return result_list
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def add(self, rdn, attr_dict):
|
||||
"""
|
||||
Add LDAP entry
|
||||
|
||||
"""
|
||||
Add LDAP entry
|
||||
|
||||
Keyword arguments:
|
||||
rdn -- DN without domain
|
||||
attr_dict -- Dictionnary of attributes/values to add
|
||||
|
@ -306,9 +306,9 @@ class YunoHostLDAP(Singleton):
|
|||
return True
|
||||
|
||||
def remove(self, rdn):
|
||||
"""
|
||||
Remove LDAP entry
|
||||
|
||||
"""
|
||||
Remove LDAP entry
|
||||
|
||||
Keyword arguments:
|
||||
rdn -- DN without domain
|
||||
|
||||
|
@ -326,9 +326,9 @@ class YunoHostLDAP(Singleton):
|
|||
|
||||
|
||||
def update(self, rdn, attr_dict, new_rdn=False):
|
||||
"""
|
||||
Modify LDAP entry
|
||||
|
||||
"""
|
||||
Modify LDAP entry
|
||||
|
||||
Keyword arguments:
|
||||
rdn -- DN without domain
|
||||
attr_dict -- Dictionnary of attributes/values to add
|
||||
|
@ -355,9 +355,9 @@ class YunoHostLDAP(Singleton):
|
|||
|
||||
|
||||
def validate_uniqueness(self, value_dict):
|
||||
"""
|
||||
Check uniqueness of values
|
||||
|
||||
"""
|
||||
Check uniqueness of values
|
||||
|
||||
Keyword arguments:
|
||||
value_dict -- Dictionnary of attributes/values to check
|
||||
|
||||
|
|
|
@ -1,24 +1,14 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import xmlrpclib
|
||||
import json
|
||||
import psutil
|
||||
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 yunohost import YunoHostError, win_msg, colorize, validate, get_required_args
|
||||
|
||||
s = xmlrpclib.ServerProxy('http://127.0.0.1:61209')
|
||||
|
||||
def bytes2human(n):
|
||||
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
|
||||
prefix = {}
|
||||
|
@ -30,91 +20,10 @@ def bytes2human(n):
|
|||
return '%.1f%s' % (value, s)
|
||||
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):
|
||||
output = subprocess.Popen(['update-rc.d', args, 'defaults'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
||||
if output.wait() == 0:
|
||||
resultat = process_start(args)
|
||||
return process_start(args)
|
||||
return resultat
|
||||
else:
|
||||
raise YunoHostError(1, 'Enable : ' + args.title() + " " + _("failure"))
|
||||
|
@ -122,7 +31,7 @@ def process_enable(args):
|
|||
def process_disable(args):
|
||||
output = subprocess.Popen(['update-rc.d', args, 'remove'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
||||
if output.wait() == 0:
|
||||
resultat = process_stop(args)
|
||||
return process_stop(args)
|
||||
return resultat
|
||||
else:
|
||||
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):
|
||||
|
||||
if memory:
|
||||
resultat = check_memory()
|
||||
return resultat
|
||||
return json.loads(s.getMem())
|
||||
|
||||
elif cpu:
|
||||
resultat = check_cpu()
|
||||
return resultat
|
||||
elif disk:
|
||||
resultat = check_disk()
|
||||
return resultat
|
||||
return json.loads(s.getLoad())
|
||||
|
||||
elif ifconfig:
|
||||
resultat = ifconfig()
|
||||
return resultat
|
||||
# TODO: c'est pas ifconfig ça ;)
|
||||
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:
|
||||
resultat = uptime()
|
||||
return resultat
|
||||
uptime_value = (str(datetime.now() - datetime.fromtimestamp(psutil.BOOT_TIME)).split('.')[0])
|
||||
return { 'Uptime' : uptime_value }
|
||||
|
||||
elif public:
|
||||
resultat = public()
|
||||
return resultat
|
||||
try:
|
||||
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):
|
||||
if enable:
|
||||
resultat = process_enable(enable)
|
||||
return resultat
|
||||
return process_enable(enable)
|
||||
elif disable:
|
||||
resultat = process_disable(disable)
|
||||
return resultat
|
||||
return process_disable(disable)
|
||||
elif start:
|
||||
resultat = process_start(start)
|
||||
return resultat
|
||||
return process_start(start)
|
||||
elif stop:
|
||||
resultat = process_stop(stop)
|
||||
return resultat
|
||||
return process_stop(stop)
|
||||
elif check:
|
||||
resultat = process_check(check)
|
||||
return resultat
|
||||
return process_check(check)
|
||||
elif info:
|
||||
resultat = processcount()
|
||||
return resultat
|
||||
return json.loads(s.getProcessCount())
|
||||
|
|
Loading…
Reference in a new issue