glances: refactor glancesStats into three classes

refactor glancesStats into three classes. This way glances can support a
new backend like the Cloud Monitoring Agent in a more clean manner.
This commit is contained in:
Brandon Philips 2012-11-29 07:41:39 -08:00 committed by Brandon Philips
parent 4d472ac771
commit 007b3a3267

View File

@ -464,20 +464,18 @@ class glancesGrabSensors:
if self.initok:
sensors.cleanup()
class glancesStats:
class GlancesStats:
"""
This class store, update and give stats
"""
def __init__(self, server_tag = False, client_tag = False):
def __init__(self):
"""
Init the stats
"""
self.server_tag = server_tag
self.client_tag = client_tag
self._init_host()
# Init the fs stats
try:
@ -495,14 +493,55 @@ class glancesStats:
# Process list refresh
self.process_list_refresh = True
# Init the all_stats used by the server
# all_stats is a dict of dicts filled by the server
if (self.server_tag):
self.all_stats = collections.defaultdict(dict)
def _process_list_refresh(self):
if self.process_list_refresh:
self.process_first_grab = False
if not hasattr(self, 'process_all'):
self.process_all = [proc for proc in psutil.process_iter()]
self.process_first_grab = True
self.process = []
self.processcount = {'total': 0, 'running': 0, 'sleeping': 0}
# Manage new processes
process_new = [proc.pid for proc in self.process_all]
for proc in psutil.process_iter():
if proc.pid not in process_new:
self.process_all.append(proc)
# Grab stats from process list
for proc in self.process_all[:]:
try:
if not proc.is_running():
try:
self.process_all.remove(proc)
except Exception:
pass
except psutil.error.NoSuchProcess:
try:
self.process_all.remove(proc)
except Exception:
pass
else:
# Global stats
try:
self.processcount[str(proc.status)] += 1
except psutil.error.NoSuchProcess:
# Process non longer exist
pass
except KeyError:
# Key did not exist, create it
self.processcount[str(proc.status)] = 1
finally:
self.processcount['total'] += 1
# Per process stats
try:
self.process.append(self.__get_process_stats__(proc))
except Exception:
pass
# If it is the first grab then empty process list
if self.process_first_grab:
self.process = []
self.process_list_refresh = not self.process_list_refresh
# Cached informations (no need to be refreshed)
# Host and OS informations
if (not self.client_tag):
def _init_host(self):
self.host = {}
self.host['os_name'] = platform.system()
self.host['hostname'] = platform.node()
@ -524,8 +563,6 @@ class glancesStats:
self.host['os_version'] = " ".join(os_version[::2])
else:
self.host['os_version'] = ""
if (self.server_tag):
self.all_stats["host"] = self.host
def __get_process_stats_NEW__(self, proc):
"""
@ -591,17 +628,7 @@ class glancesStats:
Update the stats
"""
# Host information
# Only for client
if (self.client_tag):
if input_stats != {}:
self.host = input_stats["host"]
# CPU
if (self.client_tag):
if input_stats != {}:
self.cpu = input_stats["cpu"]
else:
if not hasattr(self, 'cputime_old'):
self.cputime_old = psutil.cpu_times()
self.cputime_total_old = (self.cputime_old.user +
@ -656,14 +683,8 @@ class glancesStats:
self.cputime_total_old = self.cputime_total_new
except Exception:
self.cpu = {}
if (self.server_tag):
self.all_stats["cpu"] = self.cpu
# PerCPU
if (self.client_tag):
if input_stats != {}:
self.percpu = input_stats["percpu"]
else:
if not hasattr(self, 'percputime_old'):
self.percputime_old = psutil.cpu_times(percpu = True)
self.percputime_total_old = []
@ -728,14 +749,8 @@ class glancesStats:
self.percputime_total_old = self.percputime_total_new
except Exception:
self.percpu = []
if (self.server_tag):
self.all_stats["percpu"] = self.percpu
# LOAD
if (self.client_tag):
if input_stats != {}:
self.load = input_stats["load"]
else:
if hasattr(os, 'getloadavg'):
getload = os.getloadavg()
self.load = {'min1': getload[0],
@ -743,15 +758,8 @@ class glancesStats:
'min15': getload[2]}
else:
self.load = {}
if (self.server_tag):
self.all_stats["load"] = self.load
# MEM
if (self.client_tag):
if input_stats != {}:
self.mem = input_stats["mem"]
self.memswap = input_stats["memswap"]
else:
if psutil_mem_vm:
# If PsUtil 0.6+
phymem = psutil.virtual_memory()
@ -796,15 +804,8 @@ class glancesStats:
'percent': virtmem.percent}
else:
self.memswap = {}
if (self.server_tag):
self.all_stats["mem"] = self.mem
self.all_stats["memswap"] = self.memswap
# NET
if (self.client_tag):
if input_stats != {}:
self.network = input_stats["network"]
else:
if psutil_network_io_tag:
self.network = []
if hasattr(psutil, 'network_io_counters'):
@ -826,27 +827,12 @@ class glancesStats:
else:
self.network.append(netstat)
self.network_old = self.network_new
if (self.server_tag):
self.all_stats["network"] = self.network
# SENSORS
if (self.client_tag):
if input_stats != {}:
try:
self.sensors = input_stats["sensors"]
except:
self.sensors = {}
else:
if (sensors_tag):
self.sensors = self.glancesgrabsensors.get()
if (self.server_tag):
self.all_stats["sensors"] = self.sensors
# DISK I/O
if (self.client_tag):
if input_stats != {}:
self.diskio = input_stats["diskio"]
else:
if psutil_disk_io_tag:
self.diskio = []
if psutil_disk_io_tag and hasattr(psutil, 'disk_io_counters'):
@ -870,89 +856,21 @@ class glancesStats:
else:
self.diskio.append(diskstat)
self.diskio_old = self.diskio_new
if (self.server_tag):
self.all_stats["diskio"] = self.diskio
# FILE SYSTEM
if (self.client_tag):
if input_stats != {}:
self.fs = input_stats["fs"]
else:
if psutil_fs_usage_tag:
self.fs = self.glancesgrabfs.get()
if (self.server_tag):
self.all_stats["fs"] = self.fs
# PROCESS
self._process_list_refresh()
# Initialiation of the running processes list
# Data are refreshed every two cycle (refresh_time * 2)
if (self.client_tag):
if input_stats != {}:
self.processcount = input_stats["processcount"]
self.process = input_stats["process"]
self.process_list_refresh = True
else:
if self.process_list_refresh:
self.process_first_grab = False
if not hasattr(self, 'process_all'):
self.process_all = [proc for proc in psutil.process_iter()]
self.process_first_grab = True
self.process = []
self.processcount = {'total': 0, 'running': 0, 'sleeping': 0}
# Manage new processes
process_new = [proc.pid for proc in self.process_all]
for proc in psutil.process_iter():
if proc.pid not in process_new:
self.process_all.append(proc)
# Grab stats from process list
for proc in self.process_all[:]:
try:
if not proc.is_running():
try:
self.process_all.remove(proc)
except Exception:
pass
except psutil.error.NoSuchProcess:
try:
self.process_all.remove(proc)
except Exception:
pass
else:
# Global stats
try:
self.processcount[str(proc.status)] += 1
except psutil.error.NoSuchProcess:
# Process non longer exist
pass
except KeyError:
# Key did not exist, create it
self.processcount[str(proc.status)] = 1
finally:
self.processcount['total'] += 1
# Per process stats
try:
self.process.append(self.__get_process_stats__(proc))
except Exception:
pass
# If it is the first grab then empty process list
if self.process_first_grab:
self.process = []
self.process_list_refresh = not self.process_list_refresh
if (self.server_tag):
self.all_stats["processcount"] = self.processcount
self.all_stats["process"] = self.process
# Get the current date/time
self.now = datetime.now()
# Get the number of core (CPU) (Used to display load alerts)
if (self.client_tag):
if input_stats != {}:
self.core_number = input_stats["core_number"]
else:
self.core_number = psutil.NUM_CPUS
if (self.server_tag):
self.all_stats["core_number"] = self.core_number
def update(self, input_stats = {}):
# Update the stats
@ -1045,6 +963,75 @@ class glancesStats:
return self.now
class GlancesStatsServer(GlancesStats):
def __init__(self):
GlancesStats.__init__(self)
# Init the all_stats used by the server
# all_stats is a dict of dicts filled by the server
self.all_stats = collections.defaultdict(dict)
self._init_host()
self.all_stats["host"] = self.host
def __update__(self, input_stats):
"""
Update the stats
"""
GlancesStats.__update__(self, input_stats)
self.process_list_refresh = True
self._process_list_refresh()
self.all_stats["cpu"] = self.cpu
self.all_stats["percpu"] = self.percpu
self.all_stats["load"] = self.load
self.all_stats["mem"] = self.mem
self.all_stats["memswap"] = self.memswap
self.all_stats["network"] = self.network
self.all_stats["sensors"] = self.sensors
self.all_stats["diskio"] = self.diskio
self.all_stats["fs"] = self.fs
self.all_stats["processcount"] = self.processcount
self.all_stats["process"] = self.process
self.all_stats["core_number"] = self.core_number
# Get the current date/time
self.now = datetime.now()
class GlancesStatsClient(GlancesStats):
def __init__(self):
GlancesStats.__init__(self)
# Cached informations (no need to be refreshed)
# Host and OS informations
def __update__(self, input_stats):
"""
Update the stats
"""
if input_stats != {}:
self.host = input_stats["host"]
self.cpu = input_stats["cpu"]
self.percpu = input_stats["percpu"]
self.load = input_stats["load"]
self.mem = input_stats["mem"]
self.memswap = input_stats["memswap"]
self.network = input_stats["network"]
try:
self.sensors = input_stats["sensors"]
except:
self.sensors = {}
self.diskio = input_stats["diskio"]
self.fs = input_stats["fs"]
self.processcount = input_stats["processcount"]
self.process = input_stats["process"]
self.core_number = input_stats["core_number"]
# Get the current date/time
self.now = datetime.now()
class glancesScreen:
"""
This class manage the screen (display and key pressed)
@ -2820,7 +2807,8 @@ def main():
server = GlancesServer(bind_ip, server_port, GlancesHandler, refresh_time)
# Init stats
stats = glancesStats(server_tag = True)
stats = GlancesStatsServer()
stats.update({})
elif client_tag:
# Init the client (displaying server stat in the CLI)
@ -2838,7 +2826,7 @@ def main():
logs = glancesLogs()
# Init stats
stats = glancesStats(client_tag = True)
stats = GlancesStatsClient()
# Init screen
screen = glancesScreen(refresh_time=refresh_time)
@ -2852,7 +2840,7 @@ def main():
logs = glancesLogs()
# Init stats
stats = glancesStats()
stats = GlancesStats()
# Init HTML output
if html_tag:
@ -2883,7 +2871,6 @@ def main():
else:
server_status = "Connected"
stats.update(server_stats)
# Update the screen
screen.update(stats, cs_status = server_status)
else: