提交 96781c6d 编写于 作者: A Alessio Sergi

Convert DOS to Unix line endings

上级 e8730ec5
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system lib
from psutil import process_iter, AccessDenied, NoSuchProcess
# Import Glances lib
from glances.core.glances_globals import is_BSD, is_Mac, is_Windows
from glances.core.glances_timer import Timer, getTimeSinceLastUpdate
class glancesProcesses:
"""
Get processed stats using the PsUtil lib
"""
def __init__(self, cache_timeout = 60):
"""
Init the class to collect stats about processes
"""
# Add internals caches because PSUtil do not cache all the stats
# See: https://code.google.com/p/psutil/issues/detail?id=462
self.username_cache = {}
self.cmdline_cache = {}
# The internals caches will be cleaned each 'cache_timeout' seconds
self.cache_timeout = cache_timeout
self.cache_timer = Timer(self.cache_timeout)
# Init the io dict
# key = pid
# value = [ read_bytes_old, write_bytes_old ]
self.io_old = {}
# Init
self.processlist = []
self.processcount = {'total': 0, 'running': 0, 'sleeping': 0, 'thread': 0}
def __get_process_stats(self, proc):
"""
Get process statistics
"""
procstat = {}
# Process ID
procstat['pid'] = proc.pid
# Process name (cached by PSUtil)
procstat['name'] = proc.name
# Process username (cached with internal cache)
try:
self.username_cache[procstat['pid']]
except:
try:
self.username_cache[procstat['pid']] = proc.username
except KeyError:
try:
self.username_cache[procstat['pid']] = proc.uids.real
except KeyError:
self.username_cache[procstat['pid']] = "?"
procstat['username'] = self.username_cache[procstat['pid']]
# Process command line (cached with internal cache)
try:
self.cmdline_cache[procstat['pid']]
except:
self.cmdline_cache[procstat['pid']] = ' '.join(proc.cmdline)
procstat['cmdline'] = self.cmdline_cache[procstat['pid']]
# Process status
procstat['status'] = str(proc.status)[:1].upper()
# Process nice
procstat['nice'] = proc.get_nice()
# Process memory
procstat['memory_info'] = proc.get_memory_info()
procstat['memory_percent'] = proc.get_memory_percent()
# Process CPU
procstat['cpu_times'] = proc.get_cpu_times()
procstat['cpu_percent'] = proc.get_cpu_percent(interval=0)
# Process network connections (TCP and UDP) (Experimental)
# !!! High CPU consumption
# try:
# procstat['tcp'] = len(proc.get_connections(kind="tcp"))
# procstat['udp'] = len(proc.get_connections(kind="udp"))
# except:
# procstat['tcp'] = 0
# procstat['udp'] = 0
# Process IO
# procstat['io_counters'] is a list:
# [read_bytes, write_bytes, read_bytes_old, write_bytes_old, io_tag]
# If io_tag = 0 > Access denied (display "?")
# If io_tag = 1 > No access denied (display the IO rate)
# Note Disk IO stat not available on Mac OS
if not is_Mac:
try:
# Get the process IO counters
proc_io = proc.get_io_counters()
io_new = [proc_io.read_bytes, proc_io.write_bytes]
except AccessDenied:
# Access denied to process IO (no root account)
# Put 0 in all values (for sort) and io_tag = 0 (for display)
procstat['io_counters'] = [0, 0] + [0, 0]
io_tag = 0
else:
# For IO rate computation
# Append saved IO r/w bytes
try:
procstat['io_counters'] = io_new + self.io_old[procstat['pid']]
except KeyError:
procstat['io_counters'] = io_new + [0, 0]
# then save the IO r/w bytes
self.io_old[procstat['pid']] = io_new
io_tag = 1
# Append the IO tag (for display)
procstat['io_counters'] += [io_tag]
return procstat
def update(self):
self.processlist = []
self.processcount = {'total': 0, 'running': 0, 'sleeping': 0, 'thread': 0}
# Get the time since last update
time_since_update = getTimeSinceLastUpdate('process_disk')
# For each existing process...
for proc in process_iter():
try:
# Get stats using the PSUtil
procstat = self.__get_process_stats(proc)
# Add a specific time_since_update stats for bitrate
procstat['time_since_update'] = time_since_update
# ignore the 'idle' process on Windows and *BSD
# ignore the 'kernel_task' process on OS X
# waiting for upstream patch from psutil
if (is_BSD and procstat['name'] == 'idle' or
is_Windows and procstat['name'] == 'System Idle Process' or
is_Mac and procstat['name'] == 'kernel_task'):
continue
# Update processcount (global statistics)
try:
self.processcount[str(proc.status)] += 1
except KeyError:
# Key did not exist, create it
self.processcount[str(proc.status)] = 1
else:
self.processcount['total'] += 1
# Update thread number (global statistics)
try:
self.processcount['thread'] += proc.get_num_threads()
except:
pass
except (NoSuchProcess, AccessDenied):
continue
else:
# Update processlist
self.processlist.append(procstat)
# Clean internals caches if timeout is reached
if (self.cache_timer.finished()):
self.username_cache = {}
self.cmdline_cache = {}
# Restart the timer
self.cache_timer.reset()
def getcount(self):
return self.processcount
def getlist(self, sortedby=None):
"""
Return the processlist
"""
if (sortedby is None):
# No need to sort...
return self.processlist
sortedreverse = True
if (sortedby == 'name'):
sortedreverse = False
if (sortedby == 'io_counters'):
# Specific case for io_counters
# Sum of io_r + io_w
try:
# Sort process by IO rate (sum IO read + IO write)
listsorted = sorted(self.processlist,
key=lambda process: process[sortedby][0] -
process[sortedby][2] + process[sortedby][1] -
process[sortedby][3],
reverse=sortedreverse)
except Exception:
listsorted = sorted(self.processlist,
key=lambda process: process['cpu_percent'],
reverse=sortedreverse)
else:
# Others sorts
listsorted = sorted(self.processlist,
key=lambda process: process[sortedby],
reverse=sortedreverse)
self.processlist = listsorted
return self.processlist
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system lib
from psutil import process_iter, AccessDenied, NoSuchProcess
# Import Glances lib
from glances.core.glances_globals import is_BSD, is_Mac, is_Windows
from glances.core.glances_timer import Timer, getTimeSinceLastUpdate
class glancesProcesses:
"""
Get processed stats using the PsUtil lib
"""
def __init__(self, cache_timeout=60):
"""
Init the class to collect stats about processes
"""
# Add internals caches because PSUtil do not cache all the stats
# See: https://code.google.com/p/psutil/issues/detail?id=462
self.username_cache = {}
self.cmdline_cache = {}
# The internals caches will be cleaned each 'cache_timeout' seconds
self.cache_timeout = cache_timeout
self.cache_timer = Timer(self.cache_timeout)
# Init the io dict
# key = pid
# value = [ read_bytes_old, write_bytes_old ]
self.io_old = {}
# Init
self.processlist = []
self.processcount = {'total': 0, 'running': 0, 'sleeping': 0, 'thread': 0}
def __get_process_stats(self, proc):
"""
Get process statistics
"""
procstat = {}
# Process ID
procstat['pid'] = proc.pid
# Process name (cached by PSUtil)
procstat['name'] = proc.name
# Process username (cached with internal cache)
try:
self.username_cache[procstat['pid']]
except:
try:
self.username_cache[procstat['pid']] = proc.username
except KeyError:
try:
self.username_cache[procstat['pid']] = proc.uids.real
except KeyError:
self.username_cache[procstat['pid']] = "?"
procstat['username'] = self.username_cache[procstat['pid']]
# Process command line (cached with internal cache)
try:
self.cmdline_cache[procstat['pid']]
except:
self.cmdline_cache[procstat['pid']] = ' '.join(proc.cmdline)
procstat['cmdline'] = self.cmdline_cache[procstat['pid']]
# Process status
procstat['status'] = str(proc.status)[:1].upper()
# Process nice
procstat['nice'] = proc.get_nice()
# Process memory
procstat['memory_info'] = proc.get_memory_info()
procstat['memory_percent'] = proc.get_memory_percent()
# Process CPU
procstat['cpu_times'] = proc.get_cpu_times()
procstat['cpu_percent'] = proc.get_cpu_percent(interval=0)
# Process network connections (TCP and UDP) (Experimental)
# !!! High CPU consumption
# try:
# procstat['tcp'] = len(proc.get_connections(kind="tcp"))
# procstat['udp'] = len(proc.get_connections(kind="udp"))
# except:
# procstat['tcp'] = 0
# procstat['udp'] = 0
# Process IO
# procstat['io_counters'] is a list:
# [read_bytes, write_bytes, read_bytes_old, write_bytes_old, io_tag]
# If io_tag = 0 > Access denied (display "?")
# If io_tag = 1 > No access denied (display the IO rate)
# Note Disk IO stat not available on Mac OS
if not is_Mac:
try:
# Get the process IO counters
proc_io = proc.get_io_counters()
io_new = [proc_io.read_bytes, proc_io.write_bytes]
except AccessDenied:
# Access denied to process IO (no root account)
# Put 0 in all values (for sort) and io_tag = 0 (for display)
procstat['io_counters'] = [0, 0] + [0, 0]
io_tag = 0
else:
# For IO rate computation
# Append saved IO r/w bytes
try:
procstat['io_counters'] = io_new + self.io_old[procstat['pid']]
except KeyError:
procstat['io_counters'] = io_new + [0, 0]
# then save the IO r/w bytes
self.io_old[procstat['pid']] = io_new
io_tag = 1
# Append the IO tag (for display)
procstat['io_counters'] += [io_tag]
return procstat
def update(self):
self.processlist = []
self.processcount = {'total': 0, 'running': 0, 'sleeping': 0, 'thread': 0}
# Get the time since last update
time_since_update = getTimeSinceLastUpdate('process_disk')
# For each existing process...
for proc in process_iter():
try:
# Get stats using the PSUtil
procstat = self.__get_process_stats(proc)
# Add a specific time_since_update stats for bitrate
procstat['time_since_update'] = time_since_update
# ignore the 'idle' process on Windows and *BSD
# ignore the 'kernel_task' process on OS X
# waiting for upstream patch from psutil
if (is_BSD and procstat['name'] == 'idle' or
is_Windows and procstat['name'] == 'System Idle Process' or
is_Mac and procstat['name'] == 'kernel_task'):
continue
# Update processcount (global statistics)
try:
self.processcount[str(proc.status)] += 1
except KeyError:
# Key did not exist, create it
self.processcount[str(proc.status)] = 1
else:
self.processcount['total'] += 1
# Update thread number (global statistics)
try:
self.processcount['thread'] += proc.get_num_threads()
except:
pass
except (NoSuchProcess, AccessDenied):
continue
else:
# Update processlist
self.processlist.append(procstat)
# Clean internals caches if timeout is reached
if (self.cache_timer.finished()):
self.username_cache = {}
self.cmdline_cache = {}
# Restart the timer
self.cache_timer.reset()
def getcount(self):
return self.processcount
def getlist(self, sortedby=None):
"""
Return the processlist
"""
if (sortedby is None):
# No need to sort...
return self.processlist
sortedreverse = True
if (sortedby == 'name'):
sortedreverse = False
if (sortedby == 'io_counters'):
# Specific case for io_counters
# Sum of io_r + io_w
try:
# Sort process by IO rate (sum IO read + IO write)
listsorted = sorted(self.processlist,
key=lambda process: process[sortedby][0] -
process[sortedby][2] + process[sortedby][1] -
process[sortedby][3],
reverse=sortedreverse)
except Exception:
listsorted = sorted(self.processlist,
key=lambda process: process['cpu_percent'],
reverse=sortedreverse)
else:
# Others sorts
listsorted = sorted(self.processlist,
key=lambda process: process[sortedby],
reverse=sortedreverse)
self.processlist = listsorted
return self.processlist
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system lib
from datetime import datetime, timedelta
# Import Glances lib
from glances_plugin import GlancesPlugin
from glances.core.glances_globals import glances_logs
class Plugin(GlancesPlugin):
"""
Glances's alert Plugin
Only for display
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 1
# Enter -1 to diplay bottom
self.line_curse = 5
def update(self):
"""
Nothing to do here
Just return the global glances_log
"""
# Set the stats to the glances_logs
self.stats = glances_logs.get()
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
if (self.stats == []):
msg = "{0}".format(_("No warning or critical alert detected"))
ret.append(self.curse_add_line(msg, "TITLE"))
else:
# Header
msg = "{0}".format(_("Warning or critical alerts"))
ret.append(self.curse_add_line(msg, "TITLE"))
logs_len = glances_logs.len()
if (logs_len > 1):
msg = " {0}".format(_("(lasts %s entries)") % logs_len)
else:
msg = " {0}".format(_("(one entry)"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Loop over alerts
for alert in self.stats:
# New line
ret.append(self.curse_new_line())
# Start
msg = "{0}".format(datetime.fromtimestamp(alert[0]))
ret.append(self.curse_add_line(msg))
# Duration
if (alert[1] > 0):
# If finished display duration
msg = " ({0})".format(datetime.fromtimestamp(alert[1]) - datetime.fromtimestamp(alert[0]))
else:
msg = _(" (ongoing)")
ret.append(self.curse_add_line(msg))
ret.append(self.curse_add_line(" - "))
# Infos
if (alert[1] > 0):
# If finished do not display status
msg = "{0} {1} {2}".format(alert[2], _("on"), alert[3])
ret.append(self.curse_add_line(msg))
else:
msg = "{0}".format(alert[3])
ret.append(self.curse_add_line(msg, decoration=alert[2]))
# Min / Mean / Max
msg = " ({0:.1f}/{1:.1f}/{2:.1f})".format(alert[6], alert[5], alert[4])
ret.append(self.curse_add_line(msg))
# else:
# msg = " {0}".format(_("Running..."))
# ret.append(self.curse_add_line(msg))
# !!! Debug only
# msg = " | {0}".format(alert)
# ret.append(self.curse_add_line(msg))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system lib
from datetime import datetime
# Import Glances lib
from glances_plugin import GlancesPlugin
from glances.core.glances_globals import glances_logs
class Plugin(GlancesPlugin):
"""
Glances's alert Plugin
Only for display
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 1
# Enter -1 to diplay bottom
self.line_curse = 5
def update(self):
"""
Nothing to do here
Just return the global glances_log
"""
# Set the stats to the glances_logs
self.stats = glances_logs.get()
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
if (self.stats == []):
msg = "{0}".format(_("No warning or critical alert detected"))
ret.append(self.curse_add_line(msg, "TITLE"))
else:
# Header
msg = "{0}".format(_("Warning or critical alerts"))
ret.append(self.curse_add_line(msg, "TITLE"))
logs_len = glances_logs.len()
if (logs_len > 1):
msg = " {0}".format(_("(lasts %s entries)") % logs_len)
else:
msg = " {0}".format(_("(one entry)"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Loop over alerts
for alert in self.stats:
# New line
ret.append(self.curse_new_line())
# Start
msg = "{0}".format(datetime.fromtimestamp(alert[0]))
ret.append(self.curse_add_line(msg))
# Duration
if (alert[1] > 0):
# If finished display duration
msg = " ({0})".format(datetime.fromtimestamp(alert[1]) - datetime.fromtimestamp(alert[0]))
else:
msg = _(" (ongoing)")
ret.append(self.curse_add_line(msg))
ret.append(self.curse_add_line(" - "))
# Infos
if (alert[1] > 0):
# If finished do not display status
msg = "{0} {1} {2}".format(alert[2], _("on"), alert[3])
ret.append(self.curse_add_line(msg))
else:
msg = "{0}".format(alert[3])
ret.append(self.curse_add_line(msg, decoration=alert[2]))
# Min / Mean / Max
msg = " ({0:.1f}/{1:.1f}/{2:.1f})".format(alert[6], alert[5], alert[4])
ret.append(self.curse_add_line(msg))
# else:
# msg = " {0}".format(_("Running..."))
# ret.append(self.curse_add_line(msg))
# !!! Debug only
# msg = " | {0}".format(alert)
# ret.append(self.curse_add_line(msg))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# batinfo library (optional; Linux-only)
try:
import batinfo
except:
pass
# Import Glances lib
from glances_plugin import GlancesPlugin
from glances.core.glances_timer import getTimeSinceLastUpdate
class Plugin(GlancesPlugin):
"""
Glances's batterie capacity Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# Init the sensor class
self.glancesgrabbat = glancesGrabBat()
def update(self):
"""
Update batterie capacity stats
"""
self.stats = self.glancesgrabbat.getcapacitypercent()
class glancesGrabBat:
"""
Get batteries stats using the Batinfo librairie
"""
def __init__(self):
"""
Init batteries stats
"""
try:
self.bat = batinfo.batteries()
self.initok = True
self.__update__()
except Exception:
self.initok = False
def __update__(self):
"""
Update the stats
"""
if self.initok:
try:
self.bat.update()
except Exception:
self.bat_list = []
else:
self.bat_list = self.bat.stat
else:
self.bat_list = []
def get(self):
# Update the stats
self.__update__()
return self.bat_list
def getcapacitypercent(self):
if not self.initok or self.bat_list == []:
return []
# Init the bsum (sum of percent) and bcpt (number of batteries)
# and Loop over batteries (yes a computer could have more than 1 battery)
bsum = 0
for bcpt in range(len(self.get())):
try:
bsum = bsum + int(self.bat_list[bcpt].capacity)
except ValueError:
return []
bcpt = bcpt + 1
# Return the global percent
return int(bsum / bcpt)
\ No newline at end of file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# batinfo library (optional; Linux-only)
try:
import batinfo
except:
pass
# Import Glances lib
from glances_plugin import GlancesPlugin
# from glances.core.glances_timer import getTimeSinceLastUpdate
class Plugin(GlancesPlugin):
"""
Glances's batterie capacity Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# Init the sensor class
self.glancesgrabbat = glancesGrabBat()
def update(self):
"""
Update batterie capacity stats
"""
self.stats = self.glancesgrabbat.getcapacitypercent()
class glancesGrabBat:
"""
Get batteries stats using the Batinfo librairie
"""
def __init__(self):
"""
Init batteries stats
"""
try:
self.bat = batinfo.batteries()
self.initok = True
self.__update__()
except Exception:
self.initok = False
def __update__(self):
"""
Update the stats
"""
if self.initok:
try:
self.bat.update()
except Exception:
self.bat_list = []
else:
self.bat_list = self.bat.stat
else:
self.bat_list = []
def get(self):
# Update the stats
self.__update__()
return self.bat_list
def getcapacitypercent(self):
if not self.initok or self.bat_list == []:
return []
# Init the bsum (sum of percent) and bcpt (number of batteries)
# and Loop over batteries (yes a computer could have more than 1 battery)
bsum = 0
for bcpt in range(len(self.get())):
try:
bsum = bsum + int(self.bat_list[bcpt].capacity)
except ValueError:
return []
bcpt = bcpt + 1
# Return the global percent
return int(bsum / bcpt)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
from psutil import NUM_CPUS
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' Core Plugin
Get stats about CPU core number
stats is integer (number of core)
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We dot not want to display the stat in the curse interface
# The core number is displayed by the load plugin
self.display_curse = False
def update(self):
"""
Update core stats
"""
# !!! Note: The PSUtil 2.0 include psutil.cpu_count() and psutil.cpu_count(logical=False)
# !!! TODO: We had to return a dict (with both hys and log cpu number) instead of a integer
try:
self.stats = NUM_CPUS
except Exception, e:
self.stats = None
return self.stats
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
from psutil import NUM_CPUS
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' Core Plugin
Get stats about CPU core number
stats is integer (number of core)
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We dot not want to display the stat in the curse interface
# The core number is displayed by the load plugin
self.display_curse = False
def update(self):
"""
Update core stats
"""
# !!! Note: The PSUtil 2.0 include psutil.cpu_count() and psutil.cpu_count(logical=False)
# !!! TODO: We had to return a dict (with both hys and log cpu number) instead of a integer
try:
self.stats = NUM_CPUS
except Exception, e:
self.stats = None
return self.stats
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
from psutil import cpu_times, cpu_times_percent
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' Cpu Plugin
stats is a dict
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = 1
def update(self):
"""
Update CPU stats
"""
# Grab CPU using the PSUtil cpu_times_percent method (PSUtil 0.7 or higher)
try:
cputimespercent = cpu_times_percent(interval=0, percpu=False)
except:
return self.update_deprecated()
self.stats = {}
for cpu in ['user', 'system', 'idle', 'nice',
'iowait', 'irq', 'softirq', 'steal']:
if hasattr(cputimespercent, cpu):
self.stats[cpu] = getattr(cputimespercent, cpu)
return self.stats
def update_deprecated(self):
"""
Update CPU stats
Only used if cpu_times_percent failed
"""
# Grab CPU using the PSUtil cpu_times method
cputime = cpu_times(percpu=False)
cputime_total = cputime.user + cputime.system + cputime.idle
# Only available on some OS
if hasattr(cputime, 'nice'):
cputime_total += cputime.nice
if hasattr(cputime, 'iowait'):
cputime_total += cputime.iowait
if hasattr(cputime, 'irq'):
cputime_total += cputime.irq
if hasattr(cputime, 'softirq'):
cputime_total += cputime.softirq
if hasattr(cputime, 'steal'):
cputime_total += cputime.steal
if not hasattr(self, 'cputime_old'):
self.cputime_old = cputime
self.cputime_total_old = cputime_total
self.stats = {}
else:
self.cputime_new = cputime
self.cputime_total_new = cputime_total
try:
percent = 100 / (self.cputime_total_new -
self.cputime_total_old)
self.stats = {'user': (self.cputime_new.user -
self.cputime_old.user) * percent,
'system': (self.cputime_new.system -
self.cputime_old.system) * percent,
'idle': (self.cputime_new.idle -
self.cputime_old.idle) * percent}
if hasattr(self.cputime_new, 'nice'):
self.stats['nice'] = (self.cputime_new.nice -
self.cputime_old.nice) * percent
if hasattr(self.cputime_new, 'iowait'):
self.stats['iowait'] = (self.cputime_new.iowait -
self.cputime_old.iowait) * percent
if hasattr(self.cputime_new, 'irq'):
self.stats['irq'] = (self.cputime_new.irq -
self.cputime_old.irq) * percent
if hasattr(self.cputime_new, 'softirq'):
self.stats['softirq'] = (self.cputime_new.softirq -
self.cputime_old.softirq) * percent
if hasattr(self.cputime_new, 'steal'):
self.stats['steal'] = (self.cputime_new.steal -
self.cputime_old.steal) * percent
self.cputime_old = self.cputime_new
self.cputime_total_old = self.cputime_total_new
except Exception, err:
self.stats = {}
return self.stats
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:8}".format(_("CPU"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Total CPU usage
msg = "{0}".format(format((100 - self.stats['idle']) / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# Steal CPU usage
ret.append(self.curse_add_line(" ", optional=True))
if ('steal' in self.stats):
msg = "{0:8}".format(_("steal:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.stats['steal'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg,
self.get_alert(self.stats['steal'], header="steal"), optional=True))
# New line
ret.append(self.curse_new_line())
# User CPU
if ('user' in self.stats):
msg = "{0:8}".format(_("user:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['user'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg,
self.get_alert_log(self.stats['user'], header="user")))
# IOWait CPU
ret.append(self.curse_add_line(" ", optional=True))
if ('iowait' in self.stats):
msg = "{0:8}".format(_("iowait:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.stats['iowait'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg,
self.get_alert_log(self.stats['iowait'], header="iowait"), optional=True))
# New line
ret.append(self.curse_new_line())
# System CPU
if ('system' in self.stats):
msg = "{0:8}".format(_("system:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['system'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg,
self.get_alert_log(self.stats['system'], header="system")))
# IRQ CPU
ret.append(self.curse_add_line(" ", optional=True))
if ('irq' in self.stats):
msg = "{0:7} {1}".format(
_("irq:"),
format(self.stats['irq'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, optional=True))
# New line
ret.append(self.curse_new_line())
# Nice CPU
if ('nice' in self.stats):
msg = "{0:7} {1}".format(
_("nice:"),
format(self.stats['nice'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, optional=True))
# Idles CPU
ret.append(self.curse_add_line(" ", optional=True))
if ('idle' in self.stats):
msg = "{0:7} {1}".format(
_("idle:"),
format(self.stats['idle'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# Return the message with decoration
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
from psutil import cpu_times, cpu_times_percent
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' Cpu Plugin
stats is a dict
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = 1
def update(self):
"""
Update CPU stats
"""
# Grab CPU using the PSUtil cpu_times_percent method (PSUtil 0.7 or higher)
try:
cputimespercent = cpu_times_percent(interval=0, percpu=False)
except:
return self.update_deprecated()
self.stats = {}
for cpu in ['user', 'system', 'idle', 'nice',
'iowait', 'irq', 'softirq', 'steal']:
if hasattr(cputimespercent, cpu):
self.stats[cpu] = getattr(cputimespercent, cpu)
return self.stats
def update_deprecated(self):
"""
Update CPU stats
Only used if cpu_times_percent failed
"""
# Grab CPU using the PSUtil cpu_times method
cputime = cpu_times(percpu=False)
cputime_total = cputime.user + cputime.system + cputime.idle
# Only available on some OS
if hasattr(cputime, 'nice'):
cputime_total += cputime.nice
if hasattr(cputime, 'iowait'):
cputime_total += cputime.iowait
if hasattr(cputime, 'irq'):
cputime_total += cputime.irq
if hasattr(cputime, 'softirq'):
cputime_total += cputime.softirq
if hasattr(cputime, 'steal'):
cputime_total += cputime.steal
if not hasattr(self, 'cputime_old'):
self.cputime_old = cputime
self.cputime_total_old = cputime_total
self.stats = {}
else:
self.cputime_new = cputime
self.cputime_total_new = cputime_total
try:
percent = 100 / (self.cputime_total_new -
self.cputime_total_old)
self.stats = {'user': (self.cputime_new.user -
self.cputime_old.user) * percent,
'system': (self.cputime_new.system -
self.cputime_old.system) * percent,
'idle': (self.cputime_new.idle -
self.cputime_old.idle) * percent}
if hasattr(self.cputime_new, 'nice'):
self.stats['nice'] = (self.cputime_new.nice -
self.cputime_old.nice) * percent
if hasattr(self.cputime_new, 'iowait'):
self.stats['iowait'] = (self.cputime_new.iowait -
self.cputime_old.iowait) * percent
if hasattr(self.cputime_new, 'irq'):
self.stats['irq'] = (self.cputime_new.irq -
self.cputime_old.irq) * percent
if hasattr(self.cputime_new, 'softirq'):
self.stats['softirq'] = (self.cputime_new.softirq -
self.cputime_old.softirq) * percent
if hasattr(self.cputime_new, 'steal'):
self.stats['steal'] = (self.cputime_new.steal -
self.cputime_old.steal) * percent
self.cputime_old = self.cputime_new
self.cputime_total_old = self.cputime_total_new
except Exception, err:
self.stats = {}
return self.stats
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:8}".format(_("CPU"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Total CPU usage
msg = "{0}".format(format((100 - self.stats['idle']) / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# Steal CPU usage
ret.append(self.curse_add_line(" ", optional=True))
if ('steal' in self.stats):
msg = "{0:8}".format(_("steal:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.stats['steal'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert(self.stats['steal'], header="steal"), optional=True))
# New line
ret.append(self.curse_new_line())
# User CPU
if ('user' in self.stats):
msg = "{0:8}".format(_("user:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['user'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert_log(self.stats['user'], header="user")))
# IOWait CPU
ret.append(self.curse_add_line(" ", optional=True))
if ('iowait' in self.stats):
msg = "{0:8}".format(_("iowait:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.stats['iowait'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert_log(self.stats['iowait'], header="iowait"), optional=True))
# New line
ret.append(self.curse_new_line())
# System CPU
if ('system' in self.stats):
msg = "{0:8}".format(_("system:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['system'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert_log(self.stats['system'], header="system")))
# IRQ CPU
ret.append(self.curse_add_line(" ", optional=True))
if ('irq' in self.stats):
msg = "{0:7} {1}".format(_("irq:"), format(self.stats['irq'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, optional=True))
# New line
ret.append(self.curse_new_line())
# Nice CPU
if ('nice' in self.stats):
msg = "{0:7} {1}".format(_("nice:"), format(self.stats['nice'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, optional=True))
# Idles CPU
ret.append(self.curse_add_line(" ", optional=True))
if ('idle' in self.stats):
msg = "{0:7} {1}".format(_("idle:"), format(self.stats['idle'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# Return the message with decoration
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system lib
from psutil import disk_io_counters
# Import Glances lib
from glances.core.glances_globals import is_Mac
from glances_plugin import GlancesPlugin
from glances.core.glances_timer import getTimeSinceLastUpdate
class Plugin(GlancesPlugin):
"""
Glances's disks IO Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = 3
def update(self):
"""
Update disk IO stats
"""
self.diskio = []
# Disk IO stat not available on Mac OS
if is_Mac:
self.stats = self.diskio
return self.stats
# By storing time data we enable Rx/s and Tx/s calculations in the
# XML/RPC API, which would otherwise be overly difficult work
# for users of the API
time_since_update = getTimeSinceLastUpdate('disk')
if not hasattr(self, 'diskio_old'):
try:
self.diskio_old = disk_io_counters(perdisk=True)
except IOError:
self.diskio_error_tag = True
else:
self.diskio_new = disk_io_counters(perdisk=True)
for disk in self.diskio_new:
try:
# Try necessary to manage dynamic disk creation/del
diskstat = {}
diskstat['time_since_update'] = time_since_update
diskstat['disk_name'] = disk
diskstat['read_bytes'] = (
self.diskio_new[disk].read_bytes -
self.diskio_old[disk].read_bytes)
diskstat['write_bytes'] = (
self.diskio_new[disk].write_bytes -
self.diskio_old[disk].write_bytes)
except Exception:
continue
else:
self.diskio.append(diskstat)
self.diskio_old = self.diskio_new
self.stats = self.diskio
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:8}".format(_("DISK I/O"))
ret.append(self.curse_add_line(msg, "TITLE"))
msg = " {0:>6}".format(_("In/s"))
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(_("Out/s"))
ret.append(self.curse_add_line(msg))
# Disk list (sorted by name)
for i in sorted(self.stats, key=lambda diskio: diskio['disk_name']):
# !!! TODO: manage the hide tag
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(i['disk_name'])
ret.append(self.curse_add_line(msg))
rxps = self.auto_unit(int(i['write_bytes'] // i['time_since_update']))
txps = self.auto_unit(int(i['read_bytes'] // i['time_since_update']))
msg = " {0:>6}".format(rxps)
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(txps)
ret.append(self.curse_add_line(msg))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system lib
from psutil import disk_io_counters
# Import Glances lib
from glances.core.glances_globals import is_Mac
from glances_plugin import GlancesPlugin
from glances.core.glances_timer import getTimeSinceLastUpdate
class Plugin(GlancesPlugin):
"""
Glances's disks IO Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = 3
def update(self):
"""
Update disk IO stats
"""
self.diskio = []
# Disk IO stat not available on Mac OS
if is_Mac:
self.stats = self.diskio
return self.stats
# By storing time data we enable Rx/s and Tx/s calculations in the
# XML/RPC API, which would otherwise be overly difficult work
# for users of the API
time_since_update = getTimeSinceLastUpdate('disk')
if not hasattr(self, 'diskio_old'):
try:
self.diskio_old = disk_io_counters(perdisk=True)
except IOError:
self.diskio_error_tag = True
else:
self.diskio_new = disk_io_counters(perdisk=True)
for disk in self.diskio_new:
try:
# Try necessary to manage dynamic disk creation/del
diskstat = {}
diskstat['time_since_update'] = time_since_update
diskstat['disk_name'] = disk
diskstat['read_bytes'] = (
self.diskio_new[disk].read_bytes -
self.diskio_old[disk].read_bytes)
diskstat['write_bytes'] = (
self.diskio_new[disk].write_bytes -
self.diskio_old[disk].write_bytes)
except Exception:
continue
else:
self.diskio.append(diskstat)
self.diskio_old = self.diskio_new
self.stats = self.diskio
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:8}".format(_("DISK I/O"))
ret.append(self.curse_add_line(msg, "TITLE"))
msg = " {0:>6}".format(_("In/s"))
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(_("Out/s"))
ret.append(self.curse_add_line(msg))
# Disk list (sorted by name)
for i in sorted(self.stats, key=lambda diskio: diskio['disk_name']):
# !!! TODO: manage the hide tag
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(i['disk_name'])
ret.append(self.curse_add_line(msg))
rxps = self.auto_unit(int(i['write_bytes'] // i['time_since_update']))
txps = self.auto_unit(int(i['read_bytes'] // i['time_since_update']))
msg = " {0:>6}".format(rxps)
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(txps)
ret.append(self.curse_add_line(msg))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from psutil import disk_partitions, disk_usage
from glances_plugin import GlancesPlugin
class glancesGrabFs:
"""
Get FS stats
Did not exist in PSUtil, so had to create it from scratch
"""
def __init__(self):
"""
Init FS stats
"""
# Ignore the following FS name
self.ignore_fsname = ('', 'cgroup', 'fusectl', 'gvfs-fuse-daemon',
'gvfsd-fuse', 'none')
# Ignore the following FS type
self.ignore_fstype = ('autofs', 'binfmt_misc', 'configfs', 'debugfs',
'devfs', 'devpts', 'devtmpfs', 'hugetlbfs',
'iso9660', 'linprocfs', 'mqueue', 'none',
'proc', 'procfs', 'pstore', 'rootfs',
'securityfs', 'sysfs', 'usbfs')
# ignore FS by mount point
self.ignore_mntpoint = ('', '/dev/shm', '/lib/init/rw', '/sys/fs/cgroup')
def __update__(self):
"""
Update the stats
"""
# Reset the list
self.fs_list = []
# Open the current mounted FS
fs_stat = disk_partitions(all=True)
for fs in range(len(fs_stat)):
fs_current = {}
fs_current['device_name'] = fs_stat[fs].device
if fs_current['device_name'] in self.ignore_fsname:
continue
fs_current['fs_type'] = fs_stat[fs].fstype
if fs_current['fs_type'] in self.ignore_fstype:
continue
fs_current['mnt_point'] = fs_stat[fs].mountpoint
if fs_current['mnt_point'] in self.ignore_mntpoint:
continue
try:
fs_usage = disk_usage(fs_current['mnt_point'])
except Exception:
continue
fs_current['size'] = fs_usage.total
fs_current['used'] = fs_usage.used
fs_current['avail'] = fs_usage.free
self.fs_list.append(fs_current)
def get(self):
self.__update__()
return self.fs_list
class Plugin(GlancesPlugin):
"""
Glances's File System (fs) Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# Init the FS class
self.glancesgrabfs = glancesGrabFs()
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = 4
def update(self):
"""
Update stats
"""
self.stats = self.glancesgrabfs.get()
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:8}".format(_("MOUNT"))
ret.append(self.curse_add_line(msg, "TITLE"))
msg = " {0:>6}".format(_("Used"))
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(_("Total"))
ret.append(self.curse_add_line(msg))
# Disk list (sorted by name)
for i in sorted(self.stats, key=lambda fs: fs['mnt_point']):
# New line
ret.append(self.curse_new_line())
# Cut mount point name if it is too long
if (len(i['mnt_point']) > 8):
mnt_point = '_' + i['mnt_point'][-7:]
else:
mnt_point = i['mnt_point']
msg = "{0:8}".format(mnt_point)
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(self.auto_unit(i['used']))
ret.append(self.curse_add_line(msg,
self.get_alert(i['used'],
max=i['size'])))
msg = " {0:>6}".format(self.auto_unit(i['size']))
ret.append(self.curse_add_line(msg))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from psutil import disk_partitions, disk_usage
from glances_plugin import GlancesPlugin
class glancesGrabFs:
"""
Get FS stats
Did not exist in PSUtil, so had to create it from scratch
"""
def __init__(self):
"""
Init FS stats
"""
# Ignore the following FS name
self.ignore_fsname = ('', 'cgroup', 'fusectl', 'gvfs-fuse-daemon',
'gvfsd-fuse', 'none')
# Ignore the following FS type
self.ignore_fstype = ('autofs', 'binfmt_misc', 'configfs', 'debugfs',
'devfs', 'devpts', 'devtmpfs', 'hugetlbfs',
'iso9660', 'linprocfs', 'mqueue', 'none',
'proc', 'procfs', 'pstore', 'rootfs',
'securityfs', 'sysfs', 'usbfs')
# ignore FS by mount point
self.ignore_mntpoint = ('', '/dev/shm', '/lib/init/rw', '/sys/fs/cgroup')
def __update__(self):
"""
Update the stats
"""
# Reset the list
self.fs_list = []
# Open the current mounted FS
fs_stat = disk_partitions(all=True)
for fs in range(len(fs_stat)):
fs_current = {}
fs_current['device_name'] = fs_stat[fs].device
if fs_current['device_name'] in self.ignore_fsname:
continue
fs_current['fs_type'] = fs_stat[fs].fstype
if fs_current['fs_type'] in self.ignore_fstype:
continue
fs_current['mnt_point'] = fs_stat[fs].mountpoint
if fs_current['mnt_point'] in self.ignore_mntpoint:
continue
try:
fs_usage = disk_usage(fs_current['mnt_point'])
except Exception:
continue
fs_current['size'] = fs_usage.total
fs_current['used'] = fs_usage.used
fs_current['avail'] = fs_usage.free
self.fs_list.append(fs_current)
def get(self):
self.__update__()
return self.fs_list
class Plugin(GlancesPlugin):
"""
Glances's File System (fs) Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# Init the FS class
self.glancesgrabfs = glancesGrabFs()
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = 4
def update(self):
"""
Update stats
"""
self.stats = self.glancesgrabfs.get()
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:8}".format(_("MOUNT"))
ret.append(self.curse_add_line(msg, "TITLE"))
msg = " {0:>6}".format(_("Used"))
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(_("Total"))
ret.append(self.curse_add_line(msg))
# Disk list (sorted by name)
for i in sorted(self.stats, key=lambda fs: fs['mnt_point']):
# New line
ret.append(self.curse_new_line())
# Cut mount point name if it is too long
if (len(i['mnt_point']) > 8):
mnt_point = '_' + i['mnt_point'][-7:]
else:
mnt_point = i['mnt_point']
msg = "{0:8}".format(mnt_point)
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(self.auto_unit(i['used']))
ret.append(self.curse_add_line(msg, self.get_alert(i['used'], max=i['size'])))
msg = " {0:>6}".format(self.auto_unit(i['size']))
ret.append(self.curse_add_line(msg))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
import socket
# Import Glances lib
from glances_plugin import GlancesPlugin
from glances.core.glances_timer import getTimeSinceLastUpdate
class Plugin(GlancesPlugin):
"""
Glances's HDD temperature sensors Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# Init the sensor class
self.glancesgrabhddtemp = glancesGrabHDDTemp()
# We do not want to display the stat in a dedicated area
# The HDD temp is displayed within the sensors plugin
self.display_curse = False
def update(self):
"""
Update Sensors stats
"""
self.stats = self.glancesgrabhddtemp.get()
class glancesGrabHDDTemp:
"""
Get hddtemp stats using a socket connection
"""
cache = ""
address = "127.0.0.1"
port = 7634
def __init__(self):
"""
Init hddtemp stats
"""
try:
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((self.address, self.port))
sck.close()
except Exception:
self.initok = False
else:
self.initok = True
def __update__(self):
"""
Update the stats
"""
# Reset the list
self.hddtemp_list = []
if self.initok:
data = ""
# Taking care of sudden deaths/stops of hddtemp daemon
try:
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((self.address, self.port))
data = sck.recv(4096)
sck.close()
except Exception:
hddtemp_current = {}
hddtemp_current['label'] = "hddtemp is gone"
hddtemp_current['value'] = 0
self.hddtemp_list.append(hddtemp_current)
return
else:
# Considering the size of "|/dev/sda||0||" as the minimum
if len(data) < 14:
if len(self.cache) == 0:
data = "|hddtemp error||0||"
else:
data = self.cache
self.cache = data
fields = data.decode('utf-8').split("|")
devices = (len(fields) - 1) // 5
for i in range(0, devices):
offset = i * 5
hddtemp_current = {}
temperature = fields[offset + 3]
if temperature == "ERR":
hddtemp_current['label'] = _("hddtemp error")
hddtemp_current['value'] = 0
elif temperature == "SLP":
hddtemp_current['label'] = fields[offset + 1].split("/")[-1] + " is sleeping"
hddtemp_current['value'] = 0
elif temperature == "UNK":
hddtemp_current['label'] = fields[offset + 1].split("/")[-1] + " is unknown"
hddtemp_current['value'] = 0
else:
hddtemp_current['label'] = fields[offset + 1].split("/")[-1]
try:
hddtemp_current['value'] = int(temperature)
except TypeError:
hddtemp_current['label'] = fields[offset + 1].split("/")[-1] + " is unknown"
hddtemp_current['value'] = 0
self.hddtemp_list.append(hddtemp_current)
def get(self):
self.__update__()
return self.hddtemp_list
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
import socket
# Import Glances lib
from glances_plugin import GlancesPlugin
# from glances.core.glances_timer import getTimeSinceLastUpdate
class Plugin(GlancesPlugin):
"""
Glances's HDD temperature sensors Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# Init the sensor class
self.glancesgrabhddtemp = glancesGrabHDDTemp()
# We do not want to display the stat in a dedicated area
# The HDD temp is displayed within the sensors plugin
self.display_curse = False
def update(self):
"""
Update Sensors stats
"""
self.stats = self.glancesgrabhddtemp.get()
class glancesGrabHDDTemp:
"""
Get hddtemp stats using a socket connection
"""
cache = ""
address = "127.0.0.1"
port = 7634
def __init__(self):
"""
Init hddtemp stats
"""
try:
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((self.address, self.port))
sck.close()
except Exception:
self.initok = False
else:
self.initok = True
def __update__(self):
"""
Update the stats
"""
# Reset the list
self.hddtemp_list = []
if self.initok:
data = ""
# Taking care of sudden deaths/stops of hddtemp daemon
try:
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((self.address, self.port))
data = sck.recv(4096)
sck.close()
except Exception:
hddtemp_current = {}
hddtemp_current['label'] = "hddtemp is gone"
hddtemp_current['value'] = 0
self.hddtemp_list.append(hddtemp_current)
return
else:
# Considering the size of "|/dev/sda||0||" as the minimum
if len(data) < 14:
if len(self.cache) == 0:
data = "|hddtemp error||0||"
else:
data = self.cache
self.cache = data
fields = data.decode('utf-8').split("|")
devices = (len(fields) - 1) // 5
for i in range(0, devices):
offset = i * 5
hddtemp_current = {}
temperature = fields[offset + 3]
if temperature == "ERR":
hddtemp_current['label'] = _("hddtemp error")
hddtemp_current['value'] = 0
elif temperature == "SLP":
hddtemp_current['label'] = fields[offset + 1].split("/")[-1] + " is sleeping"
hddtemp_current['value'] = 0
elif temperature == "UNK":
hddtemp_current['label'] = fields[offset + 1].split("/")[-1] + " is unknown"
hddtemp_current['value'] = 0
else:
hddtemp_current['label'] = fields[offset + 1].split("/")[-1]
try:
hddtemp_current['value'] = int(temperature)
except TypeError:
hddtemp_current['label'] = fields[offset + 1].split("/")[-1] + " is unknown"
hddtemp_current['value'] = 0
self.hddtemp_list.append(hddtemp_current)
def get(self):
self.__update__()
return self.hddtemp_list
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
from os import getloadavg
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
from glances_core import Plugin as CorePlugin
class Plugin(GlancesPlugin):
"""
Glances's Load Plugin
stats is a dict
"""
def __init__(self):
GlancesPlugin.__init__(self)
# Instance for the CorePlugin in order to display the core number
self.core_plugin = CorePlugin()
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 1
# Enter -1 to diplay bottom
self.line_curse = 1
def update(self):
"""
Update load stats
"""
try:
load = getloadavg()
self.stats = {'min1': load[0],
'min5': load[1],
'min15': load[2]}
except Exception, err:
self.stats = {}
return self.stats
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:4} ".format(_("LOAD"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Core number
msg = "{0:3}-core".format(self.core_plugin.update())
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# 1min load
msg = "{0:8}".format(_("1 min:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['min1'], '>5.2f'))
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# 5min load
msg = "{0:8}".format(_("5 min:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['min5'], '>5.2f'))
ret.append(self.curse_add_line(msg, self.get_alert_log(self.stats['min5'],
max=100*self.core_plugin.update())))
# New line
ret.append(self.curse_new_line())
# 15min load
msg = "{0:8}".format(_("15 min:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['min15'], '>5.2f'))
ret.append(self.curse_add_line(msg, self.get_alert_log(self.stats['min15'],
max=100*self.core_plugin.update())))
return ret
\ No newline at end of file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
from os import getloadavg
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
from glances_core import Plugin as CorePlugin
class Plugin(GlancesPlugin):
"""
Glances's Load Plugin
stats is a dict
"""
def __init__(self):
GlancesPlugin.__init__(self)
# Instance for the CorePlugin in order to display the core number
self.core_plugin = CorePlugin()
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 1
# Enter -1 to diplay bottom
self.line_curse = 1
def update(self):
"""
Update load stats
"""
try:
load = getloadavg()
self.stats = {'min1': load[0],
'min5': load[1],
'min15': load[2]}
except Exception, err:
self.stats = {}
return self.stats
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:4} ".format(_("LOAD"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Core number
msg = "{0:3}-core".format(self.core_plugin.update())
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# 1min load
msg = "{0:8}".format(_("1 min:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['min1'], '>5.2f'))
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# 5min load
msg = "{0:8}".format(_("5 min:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['min5'], '>5.2f'))
ret.append(self.curse_add_line(
msg, self.get_alert_log(self.stats['min5'], max=100 * self.core_plugin.update())))
# New line
ret.append(self.curse_new_line())
# 15min load
msg = "{0:8}".format(_("15 min:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['min15'], '>5.2f'))
ret.append(self.curse_add_line(
msg, self.get_alert_log(self.stats['min15'], max=100 * self.core_plugin.update())))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
import psutil
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances's memory Plugin
stats is a dict
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 2
# Enter -1 to diplay bottom
self.line_curse = 1
def update(self):
"""
Update MEM (RAM) stats
"""
# RAM
# psutil >= 0.6
if hasattr(psutil, 'virtual_memory'):
phymem = psutil.virtual_memory()
# buffers and cached (Linux, BSD)
buffers = getattr(phymem, 'buffers', 0)
cached = getattr(phymem, 'cached', 0)
# active and inactive not available on Windows
active = getattr(phymem, 'active', 0)
inactive = getattr(phymem, 'inactive', 0)
# phymem free and usage
total = phymem.total
free = phymem.available # phymem.free + buffers + cached
used = total - free
self.stats = {'total': total,
'percent': phymem.percent,
'used': used,
'free': free,
'active': active,
'inactive': inactive,
'buffers': buffers,
'cached': cached}
# psutil < 0.6
elif hasattr(psutil, 'phymem_usage'):
phymem = psutil.phymem_usage()
# buffers and cached (Linux, BSD)
buffers = getattr(psutil, 'phymem_buffers', 0)()
cached = getattr(psutil, 'cached_phymem', 0)()
# phymem free and usage
total = phymem.total
free = phymem.free + buffers + cached
used = total - free
# active and inactive not available for psutil < 0.6
self.stats = {'total': total,
'percent': phymem.percent,
'used': used,
'free': free,
'buffers': buffers,
'cached': cached}
else:
self.stats = {}
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:5} ".format(_("MEM"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Percent memory usage
msg = "{0}".format(format(self.stats['percent'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# Active memory usage
if ('active' in self.stats):
msg = " {0:8}".format(_("actif:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.auto_unit(self.stats['active']), '>6'))
ret.append(self.curse_add_line(msg, optional=True))
# New line
ret.append(self.curse_new_line())
# Total memory usage
msg = "{0:8}".format(_("total:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['total'], '>6')))
ret.append(self.curse_add_line(msg))
# Inactive memory usage
if ('inactive' in self.stats):
msg = " {0:8}".format(_("inactif:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.auto_unit(self.stats['inactive']), '>6'))
ret.append(self.curse_add_line(msg, optional=True))
# New line
ret.append(self.curse_new_line())
# Used memory usage
msg = "{0:8}".format(_("used:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['used'], '>6')))
ret.append(self.curse_add_line(msg,
self.get_alert_log(self.stats['used'],
max=self.stats['total'])))
# Buffers memory usage
if ('buffers' in self.stats):
msg = " {0:8}".format(_("buffers:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.auto_unit(self.stats['buffers']), '>6'))
ret.append(self.curse_add_line(msg, optional=True))
# New line
ret.append(self.curse_new_line())
# Free memory usage
msg = "{0:8}".format(_("free:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['free'], '>6')))
ret.append(self.curse_add_line(msg))
# Cached memory usage
if ('free' in self.stats):
msg = " {0:8}".format(_("cached:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.auto_unit(self.stats['cached']), '>6'))
ret.append(self.curse_add_line(msg, optional=True))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
import psutil
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances's memory Plugin
stats is a dict
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 2
# Enter -1 to diplay bottom
self.line_curse = 1
def update(self):
"""
Update MEM (RAM) stats
"""
# RAM
# psutil >= 0.6
if hasattr(psutil, 'virtual_memory'):
phymem = psutil.virtual_memory()
# buffers and cached (Linux, BSD)
buffers = getattr(phymem, 'buffers', 0)
cached = getattr(phymem, 'cached', 0)
# active and inactive not available on Windows
active = getattr(phymem, 'active', 0)
inactive = getattr(phymem, 'inactive', 0)
# phymem free and usage
total = phymem.total
free = phymem.available # phymem.free + buffers + cached
used = total - free
self.stats = {'total': total,
'percent': phymem.percent,
'used': used,
'free': free,
'active': active,
'inactive': inactive,
'buffers': buffers,
'cached': cached}
# psutil < 0.6
elif hasattr(psutil, 'phymem_usage'):
phymem = psutil.phymem_usage()
# buffers and cached (Linux, BSD)
buffers = getattr(psutil, 'phymem_buffers', 0)()
cached = getattr(psutil, 'cached_phymem', 0)()
# phymem free and usage
total = phymem.total
free = phymem.free + buffers + cached
used = total - free
# active and inactive not available for psutil < 0.6
self.stats = {'total': total,
'percent': phymem.percent,
'used': used,
'free': free,
'buffers': buffers,
'cached': cached}
else:
self.stats = {}
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:5} ".format(_("MEM"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Percent memory usage
msg = "{0}".format(format(self.stats['percent'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# Active memory usage
if ('active' in self.stats):
msg = " {0:8}".format(_("actif:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.auto_unit(self.stats['active']), '>6'))
ret.append(self.curse_add_line(msg, optional=True))
# New line
ret.append(self.curse_new_line())
# Total memory usage
msg = "{0:8}".format(_("total:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['total'], '>6')))
ret.append(self.curse_add_line(msg))
# Inactive memory usage
if ('inactive' in self.stats):
msg = " {0:8}".format(_("inactif:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.auto_unit(self.stats['inactive']), '>6'))
ret.append(self.curse_add_line(msg, optional=True))
# New line
ret.append(self.curse_new_line())
# Used memory usage
msg = "{0:8}".format(_("used:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['used'], '>6')))
ret.append(self.curse_add_line(
msg, self.get_alert_log(self.stats['used'], max=self.stats['total'])))
# Buffers memory usage
if ('buffers' in self.stats):
msg = " {0:8}".format(_("buffers:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.auto_unit(self.stats['buffers']), '>6'))
ret.append(self.curse_add_line(msg, optional=True))
# New line
ret.append(self.curse_new_line())
# Free memory usage
msg = "{0:8}".format(_("free:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['free'], '>6')))
ret.append(self.curse_add_line(msg))
# Cached memory usage
if ('free' in self.stats):
msg = " {0:8}".format(_("cached:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.auto_unit(self.stats['cached']), '>6'))
ret.append(self.curse_add_line(msg, optional=True))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
import psutil
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances's swap memory Plugin
stats is a dict
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 3
# Enter -1 to diplay bottom
self.line_curse = 1
def update(self):
"""
Update MEM (SWAP) stats
"""
# SWAP
# psutil >= 0.6
if hasattr(psutil, 'swap_memory'):
# Try... is an hack for issue #152
try:
virtmem = psutil.swap_memory()
except Exception:
self.stats = {}
else:
self.stats = {'total': virtmem.total,
'used': virtmem.used,
'free': virtmem.free,
'percent': virtmem.percent}
# psutil < 0.6
elif hasattr(psutil, 'virtmem_usage'):
virtmem = psutil.virtmem_usage()
self.stats = {'total': virtmem.total,
'used': virtmem.used,
'free': virtmem.free,
'percent': virtmem.percent}
else:
self.stats = {}
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:5} ".format(_("SWAP"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Percent memory usage
msg = "{0}".format(format(self.stats['percent'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# Total memory usage
msg = "{0:8}".format(_("total:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['total'], '>6')))
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# Used memory usage
msg = "{0:8}".format(_("used:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['used'], '>6')))
ret.append(self.curse_add_line(msg,
self.get_alert_log(self.stats['used'],
max=self.stats['total'])))
# New line
ret.append(self.curse_new_line())
# Free memory usage
msg = "{0:8}".format(_("free:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['free'], '>6')))
ret.append(self.curse_add_line(msg))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
import psutil
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances's swap memory Plugin
stats is a dict
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 3
# Enter -1 to diplay bottom
self.line_curse = 1
def update(self):
"""
Update MEM (SWAP) stats
"""
# SWAP
# psutil >= 0.6
if hasattr(psutil, 'swap_memory'):
# Try... is an hack for issue #152
try:
virtmem = psutil.swap_memory()
except Exception:
self.stats = {}
else:
self.stats = {'total': virtmem.total,
'used': virtmem.used,
'free': virtmem.free,
'percent': virtmem.percent}
# psutil < 0.6
elif hasattr(psutil, 'virtmem_usage'):
virtmem = psutil.virtmem_usage()
self.stats = {'total': virtmem.total,
'used': virtmem.used,
'free': virtmem.free,
'percent': virtmem.percent}
else:
self.stats = {}
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:5} ".format(_("SWAP"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Percent memory usage
msg = "{0}".format(format(self.stats['percent'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# Total memory usage
msg = "{0:8}".format(_("total:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['total'], '>6')))
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# Used memory usage
msg = "{0:8}".format(_("used:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['used'], '>6')))
ret.append(self.curse_add_line(
msg, self.get_alert_log(self.stats['used'], max=self.stats['total'])))
# New line
ret.append(self.curse_new_line())
# Free memory usage
msg = "{0:8}".format(_("free:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.auto_unit(self.stats['free'], '>6')))
ret.append(self.curse_add_line(msg))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import Glances lib
from glances_plugin import GlancesPlugin
from glances.core.glances_globals import glances_monitors
class Plugin(GlancesPlugin):
"""
Glances's monitor Plugin
Only for display
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 1
# Enter -1 to diplay bottom
self.line_curse = 3
def load_limits(self, config):
"""
No limit...
"""
pass
def update(self):
"""
Nothing to do here
Just return the global glances_log
"""
# Update the monitored list (result of command)
glances_monitors.update()
# Put it on the stats var
self.stats = glances_monitors.get()
return self.stats
def get_alert(self, nbprocess=0, countmin=None, countmax=None):
# Return the alert status relative to the process number
if (countmin is None):
countmin = nbprocess
if (countmax is None):
countmax = nbprocess
if (nbprocess > 0):
if (int(countmin) <= int(nbprocess) <= int(countmax)):
return 'OK'
else:
return 'WARNING'
else:
if (int(countmin) == 0):
return 'OK'
else:
return 'CRITICAL'
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
for m in self.stats:
msg = "{0:<16} ".format(str(m['description']))
ret.append(self.curse_add_line(msg,
self.get_alert(m['count'], m['countmin'], m['countmax'])))
msg = "{0:<3} ".format(m['count'] if (m['count'] > 1) else "")
ret.append(self.curse_add_line(msg))
msg = "{0:13} ".format(_("RUNNING") if (m['count'] >= 1) else _("NOT RUNNING"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(m['result'] if (m['count'] >= 1) else "")
ret.append(self.curse_add_line(msg))
ret.append(self.curse_new_line())
# Delete the last empty line
try:
ret.pop()
except IndexError:
pass
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import Glances lib
from glances_plugin import GlancesPlugin
from glances.core.glances_globals import glances_monitors
class Plugin(GlancesPlugin):
"""
Glances's monitor Plugin
Only for display
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 1
# Enter -1 to diplay bottom
self.line_curse = 3
def load_limits(self, config):
"""
No limit...
"""
pass
def update(self):
"""
Nothing to do here
Just return the global glances_log
"""
# Update the monitored list (result of command)
glances_monitors.update()
# Put it on the stats var
self.stats = glances_monitors.get()
return self.stats
def get_alert(self, nbprocess=0, countmin=None, countmax=None):
# Return the alert status relative to the process number
if (countmin is None):
countmin = nbprocess
if (countmax is None):
countmax = nbprocess
if (nbprocess > 0):
if (int(countmin) <= int(nbprocess) <= int(countmax)):
return 'OK'
else:
return 'WARNING'
else:
if (int(countmin) == 0):
return 'OK'
else:
return 'CRITICAL'
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
for m in self.stats:
msg = "{0:<16} ".format(str(m['description']))
ret.append(self.curse_add_line(
msg, self.get_alert(m['count'], m['countmin'], m['countmax'])))
msg = "{0:<3} ".format(m['count'] if (m['count'] > 1) else "")
ret.append(self.curse_add_line(msg))
msg = "{0:13} ".format(_("RUNNING") if (m['count'] >= 1) else _("NOT RUNNING"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(m['result'] if (m['count'] >= 1) else "")
ret.append(self.curse_add_line(msg))
ret.append(self.curse_new_line())
# Delete the last empty line
try:
ret.pop()
except IndexError:
pass
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
import json
try:
# psutil >= 1.0.0
from psutil import net_io_counters
except:
# psutil < 1.0.0
try:
from psutil import network_io_counters
except:
pass
# Import Glances lib
from glances_plugin import GlancesPlugin
from glances.core.glances_timer import getTimeSinceLastUpdate
class Plugin(GlancesPlugin):
"""
Glances's network Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = 2
def update(self):
"""
Update network stats
"""
network = []
# psutil >= 1.0.0
try:
get_net_io_counters = net_io_counters(pernic=True)
except IOError:
# psutil < 1.0.0
try:
get_net_io_counters = network_io_counters(pernic=True)
except IOError:
pass
# By storing time data we enable Rx/s and Tx/s calculations in the
# XML/RPC API, which would otherwise be overly difficult work
# for users of the API
time_since_update = getTimeSinceLastUpdate('net')
# Previous network interface stats are stored in the network_old variable
if not hasattr(self, 'network_old'):
# First call, we init the network_old var
try:
self.network_old = get_net_io_counters
except (IOError, UnboundLocalError):
pass
else:
network_new = get_net_io_counters
for net in network_new:
try:
# Try necessary to manage dynamic network interface
netstat = {}
netstat['time_since_update'] = time_since_update
netstat['interface_name'] = net
netstat['cumulative_rx'] = network_new[net].bytes_recv
netstat['rx'] = (network_new[net].bytes_recv -
self.network_old[net].bytes_recv)
netstat['cumulative_tx'] = network_new[net].bytes_sent
netstat['tx'] = (network_new[net].bytes_sent -
self.network_old[net].bytes_sent)
netstat['cumulative_cx'] = (netstat['cumulative_rx'] +
netstat['cumulative_tx'])
netstat['cx'] = netstat['rx'] + netstat['tx']
except Exception:
continue
else:
network.append(netstat)
self.network_old = network_new
self.stats = network
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:8}".format(_("NETWORK"))
ret.append(self.curse_add_line(msg, "TITLE"))
msg = " {0:>6}".format(_("Rx/s"))
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(_("Tx/s"))
ret.append(self.curse_add_line(msg))
# Interface list (sorted by name)
for i in sorted(self.stats, key=lambda network: network['interface_name']):
# Format stats
ifname = i['interface_name'].split(':')[0]
if (args.byte):
rxps = self.auto_unit(int(i['rx'] // i['time_since_update']))
txps = self.auto_unit(int(i['tx'] // i['time_since_update']))
else:
rxps = self.auto_unit(int(i['rx'] // i['time_since_update'] * 8)) + "b"
txps = self.auto_unit(int(i['tx'] // i['time_since_update'] * 8)) + "b"
# !!! TODO: manage the hide tag
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(ifname)
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(rxps)
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(txps)
ret.append(self.curse_add_line(msg))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
try:
# psutil >= 1.0.0
from psutil import net_io_counters
except:
# psutil < 1.0.0
try:
from psutil import network_io_counters
except:
pass
# Import Glances lib
from glances_plugin import GlancesPlugin
from glances.core.glances_timer import getTimeSinceLastUpdate
class Plugin(GlancesPlugin):
"""
Glances's network Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = 2
def update(self):
"""
Update network stats
"""
network = []
# psutil >= 1.0.0
try:
get_net_io_counters = net_io_counters(pernic=True)
except IOError:
# psutil < 1.0.0
try:
get_net_io_counters = network_io_counters(pernic=True)
except IOError:
pass
# By storing time data we enable Rx/s and Tx/s calculations in the
# XML/RPC API, which would otherwise be overly difficult work
# for users of the API
time_since_update = getTimeSinceLastUpdate('net')
# Previous network interface stats are stored in the network_old variable
if not hasattr(self, 'network_old'):
# First call, we init the network_old var
try:
self.network_old = get_net_io_counters
except (IOError, UnboundLocalError):
pass
else:
network_new = get_net_io_counters
for net in network_new:
try:
# Try necessary to manage dynamic network interface
netstat = {}
netstat['time_since_update'] = time_since_update
netstat['interface_name'] = net
netstat['cumulative_rx'] = network_new[net].bytes_recv
netstat['rx'] = (network_new[net].bytes_recv -
self.network_old[net].bytes_recv)
netstat['cumulative_tx'] = network_new[net].bytes_sent
netstat['tx'] = (network_new[net].bytes_sent -
self.network_old[net].bytes_sent)
netstat['cumulative_cx'] = (netstat['cumulative_rx'] +
netstat['cumulative_tx'])
netstat['cx'] = netstat['rx'] + netstat['tx']
except Exception:
continue
else:
network.append(netstat)
self.network_old = network_new
self.stats = network
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:8}".format(_("NETWORK"))
ret.append(self.curse_add_line(msg, "TITLE"))
msg = " {0:>6}".format(_("Rx/s"))
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(_("Tx/s"))
ret.append(self.curse_add_line(msg))
# Interface list (sorted by name)
for i in sorted(self.stats, key=lambda network: network['interface_name']):
# Format stats
ifname = i['interface_name'].split(':')[0]
if (args.byte):
rxps = self.auto_unit(int(i['rx'] // i['time_since_update']))
txps = self.auto_unit(int(i['tx'] // i['time_since_update']))
else:
rxps = self.auto_unit(int(i['rx'] // i['time_since_update'] * 8)) + "b"
txps = self.auto_unit(int(i['tx'] // i['time_since_update'] * 8)) + "b"
# !!! TODO: manage the hide tag
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(ifname)
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(rxps)
ret.append(self.curse_add_line(msg))
msg = " {0:>6}".format(txps)
ret.append(self.curse_add_line(msg))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
from datetime import datetime
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' Core Plugin
Get current date/time
stats is (string)
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = -1
def update(self):
"""
Update current date/time
"""
# Now
# Had to convert it to string because datetime is not JSON serializable
self.stats = datetime.now().strftime(_("%Y-%m-%d %H:%M:%S"))
return self.stats
def msg_curse(self, args=None):
"""
Return the string to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# 23 is the padding for the process list
msg = _("{0:23}").format(self.stats)
ret.append(self.curse_add_line(msg))
return ret
\ No newline at end of file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
from datetime import datetime
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' Core Plugin
Get current date/time
stats is (string)
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = -1
def update(self):
"""
Update current date/time
"""
# Had to convert it to string because datetime is not JSON serializable
self.stats = datetime.now().strftime(_("%Y-%m-%d %H:%M:%S"))
return self.stats
def msg_curse(self, args=None):
"""
Return the string to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# 23 is the padding for the process list
msg = _("{0:23}").format(self.stats)
ret.append(self.curse_add_line(msg))
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
from psutil import cpu_times
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' PerCpu Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = 1
def update(self):
"""
Update Per CPU stats
"""
# Grab CPU using the PSUtil cpu_times method
# Per-CPU
percputime = cpu_times(percpu=True)
percputime_total = []
for i in range(len(percputime)):
percputime_total.append(percputime[i].user +
percputime[i].system +
percputime[i].idle)
# Only available on some OS
for i in range(len(percputime)):
if hasattr(percputime[i], 'nice'):
percputime_total[i] += percputime[i].nice
for i in range(len(percputime)):
if hasattr(percputime[i], 'iowait'):
percputime_total[i] += percputime[i].iowait
for i in range(len(percputime)):
if hasattr(percputime[i], 'irq'):
percputime_total[i] += percputime[i].irq
for i in range(len(percputime)):
if hasattr(percputime[i], 'softirq'):
percputime_total[i] += percputime[i].softirq
for i in range(len(percputime)):
if hasattr(percputime[i], 'steal'):
percputime_total[i] += percputime[i].steal
if not hasattr(self, 'percputime_old'):
self.percputime_old = percputime
self.percputime_total_old = percputime_total
self.stats = []
else:
self.percputime_new = percputime
self.percputime_total_new = percputime_total
perpercent = []
self.stats = []
try:
for i in range(len(self.percputime_new)):
perpercent.append(100 / (self.percputime_total_new[i] -
self.percputime_total_old[i]))
cpu = {'user': (self.percputime_new[i].user -
self.percputime_old[i].user) * perpercent[i],
'system': (self.percputime_new[i].system -
self.percputime_old[i].system) * perpercent[i],
'idle': (self.percputime_new[i].idle -
self.percputime_old[i].idle) * perpercent[i]}
if hasattr(self.percputime_new[i], 'nice'):
cpu['nice'] = (self.percputime_new[i].nice -
self.percputime_old[i].nice) * perpercent[i]
if hasattr(self.percputime_new[i], 'iowait'):
cpu['iowait'] = (self.percputime_new[i].iowait -
self.percputime_old[i].iowait) * perpercent[i]
if hasattr(self.percputime_new[i], 'irq'):
cpu['irq'] = (self.percputime_new[i].irq -
self.percputime_old[i].irq) * perpercent[i]
if hasattr(self.percputime_new[i], 'softirq'):
cpu['softirq'] = (self.percputime_new[i].softirq -
self.percputime_old[i].softirq) * perpercent[i]
if hasattr(self.percputime_new[i], 'steal'):
cpu['steal'] = (self.percputime_new[i].steal -
self.percputime_old[i].steal) * perpercent[i]
self.stats.append(cpu)
self.percputime_old = self.percputime_new
self.percputime_total_old = self.percputime_total_new
except Exception, err:
self.stats = []
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:8}".format(_("PER CPU"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Total CPU usage
for cpu in self.stats:
msg = " {0}".format(format((100 - cpu['idle']) / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# User CPU
if ('user' in self.stats[0]):
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(_("user:"))
ret.append(self.curse_add_line(msg))
for cpu in self.stats:
msg = " {0}".format(format(cpu['user'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert(cpu['user'], header="user")))
# System CPU
if ('user' in self.stats[0]):
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(_("system:"))
ret.append(self.curse_add_line(msg))
for cpu in self.stats:
msg = " {0}".format(format(cpu['system'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert(cpu['system'], header="system")))
# IoWait CPU
if ('user' in self.stats[0]):
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(_("iowait:"))
ret.append(self.curse_add_line(msg))
for cpu in self.stats:
msg = " {0}".format(format(cpu['iowait'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert(cpu['iowait'], header="iowait")))
# Return the message with decoration
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
from psutil import cpu_times
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' PerCpu Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = 1
def update(self):
"""
Update Per CPU stats
"""
# Grab CPU using the PSUtil cpu_times method
# Per-CPU
percputime = cpu_times(percpu=True)
percputime_total = []
for i in range(len(percputime)):
percputime_total.append(percputime[i].user +
percputime[i].system +
percputime[i].idle)
# Only available on some OS
for i in range(len(percputime)):
if hasattr(percputime[i], 'nice'):
percputime_total[i] += percputime[i].nice
for i in range(len(percputime)):
if hasattr(percputime[i], 'iowait'):
percputime_total[i] += percputime[i].iowait
for i in range(len(percputime)):
if hasattr(percputime[i], 'irq'):
percputime_total[i] += percputime[i].irq
for i in range(len(percputime)):
if hasattr(percputime[i], 'softirq'):
percputime_total[i] += percputime[i].softirq
for i in range(len(percputime)):
if hasattr(percputime[i], 'steal'):
percputime_total[i] += percputime[i].steal
if not hasattr(self, 'percputime_old'):
self.percputime_old = percputime
self.percputime_total_old = percputime_total
self.stats = []
else:
self.percputime_new = percputime
self.percputime_total_new = percputime_total
perpercent = []
self.stats = []
try:
for i in range(len(self.percputime_new)):
perpercent.append(100 / (self.percputime_total_new[i] -
self.percputime_total_old[i]))
cpu = {'user': (self.percputime_new[i].user -
self.percputime_old[i].user) * perpercent[i],
'system': (self.percputime_new[i].system -
self.percputime_old[i].system) * perpercent[i],
'idle': (self.percputime_new[i].idle -
self.percputime_old[i].idle) * perpercent[i]}
if hasattr(self.percputime_new[i], 'nice'):
cpu['nice'] = (self.percputime_new[i].nice -
self.percputime_old[i].nice) * perpercent[i]
if hasattr(self.percputime_new[i], 'iowait'):
cpu['iowait'] = (self.percputime_new[i].iowait -
self.percputime_old[i].iowait) * perpercent[i]
if hasattr(self.percputime_new[i], 'irq'):
cpu['irq'] = (self.percputime_new[i].irq -
self.percputime_old[i].irq) * perpercent[i]
if hasattr(self.percputime_new[i], 'softirq'):
cpu['softirq'] = (self.percputime_new[i].softirq -
self.percputime_old[i].softirq) * perpercent[i]
if hasattr(self.percputime_new[i], 'steal'):
cpu['steal'] = (self.percputime_new[i].steal -
self.percputime_old[i].steal) * perpercent[i]
self.stats.append(cpu)
self.percputime_old = self.percputime_new
self.percputime_total_old = self.percputime_total_new
except Exception, err:
self.stats = []
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0:8}".format(_("PER CPU"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Total CPU usage
for cpu in self.stats:
msg = " {0}".format(format((100 - cpu['idle']) / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# User CPU
if ('user' in self.stats[0]):
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(_("user:"))
ret.append(self.curse_add_line(msg))
for cpu in self.stats:
msg = " {0}".format(format(cpu['user'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert(cpu['user'], header="user")))
# System CPU
if ('user' in self.stats[0]):
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(_("system:"))
ret.append(self.curse_add_line(msg))
for cpu in self.stats:
msg = " {0}".format(format(cpu['system'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert(cpu['system'], header="system")))
# IoWait CPU
if ('user' in self.stats[0]):
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(_("iowait:"))
ret.append(self.curse_add_line(msg))
for cpu in self.stats:
msg = " {0}".format(format(cpu['iowait'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert(cpu['iowait'], header="iowait")))
# Return the message with decoration
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
import json
# Import Glances lib
from glances.core.glances_globals import glances_logs
class GlancesPlugin(object):
"""
Main class for Glances' plugin
"""
def __init__(self):
# Plugin name (= module name without glances_)
self.plugin_name = self.__class__.__module__[len('glances_'):]
# Init the stats list
self.stats = None
# Init the limits dictionnary
self.limits = dict()
def load_limits(self, config):
"""
Load the limits from the configuration file
"""
if (hasattr(config, 'has_section')
and config.has_section(self.plugin_name)):
# print "Load limits for %s" % self.plugin_name
for s, v in config.items(self.plugin_name):
# Read limits
# print "\t%s = %s" % (self.plugin_name + '_' + s, v)
self.limits[self.plugin_name + '_' + s] = config.get_option(self.plugin_name, s)
def __repr__(self):
# Return the raw stats
return self.stats
def __str__(self):
# Return the human-readable stats
return str(self.stats)
def get_raw(self):
# Return the stats object
return self.stats
def get_stats(self):
# Return the stats object in JSON format for the RPC API
return json.dumps(self.stats)
def get_limits(self):
# Return the limits object
return self.limits
def get_alert(self, current=0, min=0, max=100, header="", log=False):
# Return the alert status relative to a current value
# Use this function for minor stat
# If current < CAREFUL of max then alert = OK
# If current > CAREFUL of max then alert = CAREFUL
# If current > WARNING of max then alert = WARNING
# If current > CRITICAL of max then alert = CRITICAL
# stat is USER, SYSTEM, IOWAIT or STEAL
#
# If defined 'header' is added between the plugin name and the status
# Only usefull for stats with several alert status
#
# If log=True than return the logged status
# Compute the %
try:
value = (current * 100) / max
except ZeroDivisionError:
return 'DEFAULT'
except TypeError:
return 'DEFAULT'
# Manage limits
ret = 'OK'
if (value > self.get_limit_critical(header=header)):
ret = 'CRITICAL'
elif (value > self.get_limit_warning(header=header)):
ret = 'WARNING'
elif (value > self.get_limit_careful(header=header)):
ret = 'CAREFUL'
# Manage log (if needed)
log_str = ""
if (log):
# Add _LOG to the return string
# So stats will be highlited with a specific color
log_str = "_LOG"
# Get the stat_name = plugin_name (+ header)
if (header == ""):
stat_name = self.plugin_name
else:
stat_name = self.plugin_name + '_' + header
# !!! TODO: Manage the process list (last param => [])
glances_logs.add(ret, stat_name.upper(), value, [])
# Default is ok
return ret + log_str
def get_alert_log(self, current=0, min=0, max=100, header=""):
return self.get_alert(current, min, max, header, log=True)
def get_limit_critical(self, header=""):
if (header == ""):
return self.limits[self.plugin_name + '_' + 'critical']
else:
return self.limits[self.plugin_name + '_' + header + '_' + 'critical']
def get_limit_warning(self, header=""):
if (header == ""):
return self.limits[self.plugin_name + '_' + 'warning']
else:
return self.limits[self.plugin_name + '_' + header + '_' + 'warning']
def get_limit_careful(self, header=""):
if (header == ""):
return self.limits[self.plugin_name + '_' + 'careful']
else:
return self.limits[self.plugin_name + '_' + header + '_' + 'careful']
def msg_curse(self, args):
"""
Return default string to display in the curse interface
"""
return [ self.curse_add_line(str(self.stats)) ]
def get_curse(self, args=None):
# Return a dict with all the information needed to display the stat
# key | description
#----------------------------
# display | Display the stat (True or False)
# msgdict | Message to display (list of dict [{ 'msg': msg, 'decoration': decoration } ... ])
# column | column number
# line | Line number
display_curse = False
column_curse = -1
line_curse = -1
if (hasattr(self, 'display_curse')):
display_curse = self.display_curse
if (hasattr(self, 'column_curse')):
column_curse = self.column_curse
if (hasattr(self, 'line_curse')):
line_curse = self.line_curse
return { 'display': display_curse,
'msgdict': self.msg_curse(args),
'column': column_curse,
'line': line_curse }
def curse_add_line(self, msg, decoration="DEFAULT", optional=False):
"""
Return a dict with: { 'msg': msg, 'decoration': decoration, 'optional': False }
with:
msg: string
decoration:
DEFAULT: no decoration
UNDERLINE: underline
BOLD: bold
TITLE: for stat title
OK: Value is OK and non logged
OK_LOG: Value is OK and logged
CAREFUL: Value is CAREFUL and non logged
CAREFUL_LOG: Value is CAREFUL and logged
WARNING: Value is WARINING and non logged
WARNING_LOG: Value is WARINING and logged
CRITICAL: Value is CRITICAL and non logged
CRITICAL_LOG: Value is CRITICAL and logged
optional: True if the stat is optional (display only if space is available)
"""
return { 'msg': msg, 'decoration': decoration, 'optional': optional }
def curse_new_line(self):
"""
Go to a new line
"""
return self.curse_add_line('\n')
def auto_unit(self, val, low_precision=False):
"""
Make a nice human readable string out of val
Number of decimal places increases as quantity approaches 1
examples:
CASE: 613421788 RESULT: 585M low_precision: 585M
CASE: 5307033647 RESULT: 4.94G low_precision: 4.9G
CASE: 44968414685 RESULT: 41.9G low_precision: 41.9G
CASE: 838471403472 RESULT: 781G low_precision: 781G
CASE: 9683209690677 RESULT: 8.81T low_precision: 8.8T
CASE: 1073741824 RESULT: 1024M low_precision: 1024M
CASE: 1181116006 RESULT: 1.10G low_precision: 1.1G
parameter 'low_precision=True' returns less decimal places.
potentially sacrificing precision for more readability
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {
'Y': 1208925819614629174706176,
'Z': 1180591620717411303424,
'E': 1152921504606846976,
'P': 1125899906842624,
'T': 1099511627776,
'G': 1073741824,
'M': 1048576,
'K': 1024
}
for key in reversed(symbols):
value = float(val) / prefix[key]
if value > 1:
fixed_decimal_places = 0
if value < 10:
fixed_decimal_places = 2
elif value < 100:
fixed_decimal_places = 1
if low_precision:
if key in 'MK':
fixed_decimal_places = 0
else:
fixed_decimal_places = min(1, fixed_decimal_places)
elif key in 'K':
fixed_decimal_places = 0
formatter = "{0:.%df}{1}" % fixed_decimal_places
return formatter.format(value, key)
return "{0!s}".format(val)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
import json
# Import Glances lib
from glances.core.glances_globals import glances_logs
class GlancesPlugin(object):
"""
Main class for Glances' plugin
"""
def __init__(self):
# Plugin name (= module name without glances_)
self.plugin_name = self.__class__.__module__[len('glances_'):]
# Init the stats list
self.stats = None
# Init the limits dictionnary
self.limits = dict()
def load_limits(self, config):
"""
Load the limits from the configuration file
"""
if (hasattr(config, 'has_section') and
config.has_section(self.plugin_name)):
# print "Load limits for %s" % self.plugin_name
for s, v in config.items(self.plugin_name):
# Read limits
# print "\t%s = %s" % (self.plugin_name + '_' + s, v)
self.limits[self.plugin_name + '_' + s] = config.get_option(self.plugin_name, s)
def __repr__(self):
# Return the raw stats
return self.stats
def __str__(self):
# Return the human-readable stats
return str(self.stats)
def get_raw(self):
# Return the stats object
return self.stats
def get_stats(self):
# Return the stats object in JSON format for the RPC API
return json.dumps(self.stats)
def get_limits(self):
# Return the limits object
return self.limits
def get_alert(self, current=0, min=0, max=100, header="", log=False):
# Return the alert status relative to a current value
# Use this function for minor stat
# If current < CAREFUL of max then alert = OK
# If current > CAREFUL of max then alert = CAREFUL
# If current > WARNING of max then alert = WARNING
# If current > CRITICAL of max then alert = CRITICAL
# stat is USER, SYSTEM, IOWAIT or STEAL
#
# If defined 'header' is added between the plugin name and the status
# Only usefull for stats with several alert status
#
# If log=True than return the logged status
# Compute the %
try:
value = (current * 100) / max
except ZeroDivisionError:
return 'DEFAULT'
except TypeError:
return 'DEFAULT'
# Manage limits
ret = 'OK'
if (value > self.get_limit_critical(header=header)):
ret = 'CRITICAL'
elif (value > self.get_limit_warning(header=header)):
ret = 'WARNING'
elif (value > self.get_limit_careful(header=header)):
ret = 'CAREFUL'
# Manage log (if needed)
log_str = ""
if (log):
# Add _LOG to the return string
# So stats will be highlited with a specific color
log_str = "_LOG"
# Get the stat_name = plugin_name (+ header)
if (header == ""):
stat_name = self.plugin_name
else:
stat_name = self.plugin_name + '_' + header
# !!! TODO: Manage the process list (last param => [])
glances_logs.add(ret, stat_name.upper(), value, [])
# Default is ok
return ret + log_str
def get_alert_log(self, current=0, min=0, max=100, header=""):
return self.get_alert(current, min, max, header, log=True)
def get_limit_critical(self, header=""):
if (header == ""):
return self.limits[self.plugin_name + '_' + 'critical']
else:
return self.limits[self.plugin_name + '_' + header + '_' + 'critical']
def get_limit_warning(self, header=""):
if (header == ""):
return self.limits[self.plugin_name + '_' + 'warning']
else:
return self.limits[self.plugin_name + '_' + header + '_' + 'warning']
def get_limit_careful(self, header=""):
if (header == ""):
return self.limits[self.plugin_name + '_' + 'careful']
else:
return self.limits[self.plugin_name + '_' + header + '_' + 'careful']
def msg_curse(self, args):
"""
Return default string to display in the curse interface
"""
return [self.curse_add_line(str(self.stats))]
def get_curse(self, args=None):
# Return a dict with all the information needed to display the stat
# key | description
#----------------------------
# display | Display the stat (True or False)
# msgdict | Message to display (list of dict [{ 'msg': msg, 'decoration': decoration } ... ])
# column | column number
# line | Line number
display_curse = False
column_curse = -1
line_curse = -1
if (hasattr(self, 'display_curse')):
display_curse = self.display_curse
if (hasattr(self, 'column_curse')):
column_curse = self.column_curse
if (hasattr(self, 'line_curse')):
line_curse = self.line_curse
return {'display': display_curse,
'msgdict': self.msg_curse(args),
'column': column_curse,
'line': line_curse}
def curse_add_line(self, msg, decoration="DEFAULT", optional=False):
"""
Return a dict with: { 'msg': msg, 'decoration': decoration, 'optional': False }
with:
msg: string
decoration:
DEFAULT: no decoration
UNDERLINE: underline
BOLD: bold
TITLE: for stat title
OK: Value is OK and non logged
OK_LOG: Value is OK and logged
CAREFUL: Value is CAREFUL and non logged
CAREFUL_LOG: Value is CAREFUL and logged
WARNING: Value is WARINING and non logged
WARNING_LOG: Value is WARINING and logged
CRITICAL: Value is CRITICAL and non logged
CRITICAL_LOG: Value is CRITICAL and logged
optional: True if the stat is optional (display only if space is available)
"""
return {'msg': msg, 'decoration': decoration, 'optional': optional}
def curse_new_line(self):
"""
Go to a new line
"""
return self.curse_add_line('\n')
def auto_unit(self, val, low_precision=False):
"""
Make a nice human readable string out of val
Number of decimal places increases as quantity approaches 1
examples:
CASE: 613421788 RESULT: 585M low_precision: 585M
CASE: 5307033647 RESULT: 4.94G low_precision: 4.9G
CASE: 44968414685 RESULT: 41.9G low_precision: 41.9G
CASE: 838471403472 RESULT: 781G low_precision: 781G
CASE: 9683209690677 RESULT: 8.81T low_precision: 8.8T
CASE: 1073741824 RESULT: 1024M low_precision: 1024M
CASE: 1181116006 RESULT: 1.10G low_precision: 1.1G
parameter 'low_precision=True' returns less decimal places.
potentially sacrificing precision for more readability
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {
'Y': 1208925819614629174706176,
'Z': 1180591620717411303424,
'E': 1152921504606846976,
'P': 1125899906842624,
'T': 1099511627776,
'G': 1073741824,
'M': 1048576,
'K': 1024
}
for key in reversed(symbols):
value = float(val) / prefix[key]
if value > 1:
fixed_decimal_places = 0
if value < 10:
fixed_decimal_places = 2
elif value < 100:
fixed_decimal_places = 1
if low_precision:
if key in 'MK':
fixed_decimal_places = 0
else:
fixed_decimal_places = min(1, fixed_decimal_places)
elif key in 'K':
fixed_decimal_places = 0
formatter = "{0:.%df}{1}" % fixed_decimal_places
return formatter.format(value, key)
return "{0!s}".format(val)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from glances_plugin import GlancesPlugin
from glances.core.glances_globals import glances_processes, process_auto_by
class Plugin(GlancesPlugin):
"""
Glances's processes Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# Nothing else to do...
# 'processes' is already init in the _processes.py script
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 1
# Enter -1 to diplay bottom
self.line_curse = 2
def update(self):
"""
Update processes stats
"""
# Here, update is call for processcount AND processlist
glances_processes.update()
self.stats = glances_processes.getcount()
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0} ".format(_("TASKS"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Compute processes
other = self.stats['total']
msg = "{0}".format(str(self.stats['total']))
ret.append(self.curse_add_line(msg))
if ('thread' in self.stats):
msg = " ({0} {1}),".format(str(self.stats['thread']), _("thr"))
ret.append(self.curse_add_line(msg))
if ('running' in self.stats):
other -= self.stats['running']
msg = " {0} {1},".format(str(self.stats['running']), _("run"))
ret.append(self.curse_add_line(msg))
if ('sleeping' in self.stats):
other -= self.stats['sleeping']
msg = " {0} {1},".format(str(self.stats['sleeping']), _("slp"))
ret.append(self.curse_add_line(msg))
msg = " {0} {1} ".format(str(other), _("oth"))
ret.append(self.curse_add_line(msg))
# Display sort information
if (args.process_sorted_by == 'auto'):
msg = "{0}".format(_("sorted automatically"))
ret.append(self.curse_add_line(msg))
msg = " {0} {1}".format(_("by"), process_auto_by)
ret.append(self.curse_add_line(msg))
else:
msg = "{0} {1}".format(_("sorted by"), args.process_sorted_by)
ret.append(self.curse_add_line(msg))
# Return the message with decoration
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from glances_plugin import GlancesPlugin
from glances.core.glances_globals import glances_processes, process_auto_by
class Plugin(GlancesPlugin):
"""
Glances's processes Plugin
stats is a list
"""
def __init__(self):
GlancesPlugin.__init__(self)
# Nothing else to do...
# 'processes' is already init in the _processes.py script
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = 1
# Enter -1 to diplay bottom
self.line_curse = 2
def update(self):
"""
Update processes stats
"""
# Here, update is call for processcount AND processlist
glances_processes.update()
self.stats = glances_processes.getcount()
def msg_curse(self, args=None):
"""
Return the dict to display in the curse interface
"""
# Init the return message
ret = []
# Build the string message
# Header
msg = "{0} ".format(_("TASKS"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Compute processes
other = self.stats['total']
msg = "{0}".format(str(self.stats['total']))
ret.append(self.curse_add_line(msg))
if ('thread' in self.stats):
msg = " ({0} {1}),".format(str(self.stats['thread']), _("thr"))
ret.append(self.curse_add_line(msg))
if ('running' in self.stats):
other -= self.stats['running']
msg = " {0} {1},".format(str(self.stats['running']), _("run"))
ret.append(self.curse_add_line(msg))
if ('sleeping' in self.stats):
other -= self.stats['sleeping']
msg = " {0} {1},".format(str(self.stats['sleeping']), _("slp"))
ret.append(self.curse_add_line(msg))
msg = " {0} {1} ".format(str(other), _("oth"))
ret.append(self.curse_add_line(msg))
# Display sort information
if (args.process_sorted_by == 'auto'):
msg = "{0}".format(_("sorted automatically"))
ret.append(self.curse_add_line(msg))
msg = " {0} {1}".format(_("by"), process_auto_by)
ret.append(self.curse_add_line(msg))
else:
msg = "{0} {1}".format(_("sorted by"), args.process_sorted_by)
ret.append(self.curse_add_line(msg))
# Return the message with decoration
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
from psutil import __version__ as __psutil_version__
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' PsUtil version Plugin
stats is a tuple
"""
def __init__(self):
GlancesPlugin.__init__(self)
def update(self):
"""
Update core stats
"""
# Return PsUtil version as a tuple
try:
self.stats = tuple([int(num) for num in __psutil_version__.split('.')])
except Exception, e:
self.stats = None
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
from psutil import __version__ as __psutil_version__
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' PsUtil version Plugin
stats is a tuple
"""
def __init__(self):
GlancesPlugin.__init__(self)
def update(self):
"""
Update core stats
"""
# Return PsUtil version as a tuple
try:
self.stats = tuple([int(num) for num in __psutil_version__.split('.')])
except Exception, e:
self.stats = None
此差异已折叠。
......@@ -25,6 +25,7 @@ import platform
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' Host/System Plugin
......@@ -39,12 +40,11 @@ class Plugin(GlancesPlugin):
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
# Enter -1 to right align
self.column_curse = 0
# Enter -1 to diplay bottom
self.line_curse = 0
def update(self):
"""
Update the host/system info
......@@ -71,7 +71,6 @@ class Plugin(GlancesPlugin):
else:
self.stats['os_version'] = ""
def msg_curse(self, args=None):
"""
Return the string to display in the curse interface
......@@ -94,18 +93,15 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg, "TITLE"))
# System info
if (self.stats['os_name'] == "Linux"):
msg = _(" ({0} {1} / {2} {3})").format(
self.stats['linux_distro'],
self.stats['platform'],
self.stats['os_name'],
self.stats['os_version'])
msg = _(" ({0} {1} / {2} {3})").format(self.stats['linux_distro'],
self.stats['platform'],
self.stats['os_name'],
self.stats['os_version'])
else:
msg = _(" ({0} {1} {2})").format(
self.stats['os_name'],
self.stats['os_version'],
self.stats['platform'])
msg = _(" ({0} {1} {2})").format(self.stats['os_name'],
self.stats['os_version'],
self.stats['platform'])
ret.append(self.curse_add_line(msg, optional=True))
# Return the message with decoration
# Return the message with decoration
return ret
\ No newline at end of file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
try:
from psutil import get_boot_time
except:
from putil import BOOT_TIME
from datetime import datetime
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' Uptime Plugin
Get stats about uptime
stats is date (string)
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = -1
# Enter -1 to diplay bottom
self.line_curse = 0
def update(self):
"""
Update uptime stat
"""
# Uptime
try:
# For PsUtil >= 0.7.0
self.uptime = datetime.now() - datetime.fromtimestamp(get_boot_time())
except:
self.uptime = datetime.now() - datetime.fromtimestamp(BOOT_TIME)
# Convert uptime to string (because datetime is not JSONifi)
self.stats = str(self.uptime).split('.')[0]
def msg_curse(self, args=None):
"""
Return the string to display in the curse interface
"""
# Init the return message
ret = []
# Add the line with decoration
ret.append(self.curse_add_line("Uptime: %s" % self.stats))
# Return the message with decoration
return ret
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Glances - An eye on your system
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
# Check for PSUtil already done in the glances_core script
try:
from psutil import get_boot_time
except:
from putil import BOOT_TIME
from datetime import datetime
# from ..plugins.glances_plugin import GlancesPlugin
from glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""
Glances' Uptime Plugin
Get stats about uptime
stats is date (string)
"""
def __init__(self):
GlancesPlugin.__init__(self)
# We want to display the stat in the curse interface
self.display_curse = True
# Set the message position
# It is NOT the curse position but the Glances column/line
# Enter -1 to right align
self.column_curse = -1
# Enter -1 to diplay bottom
self.line_curse = 0
def update(self):
"""
Update uptime stat
"""
try:
# For PsUtil >= 0.7.0
self.uptime = datetime.now() - datetime.fromtimestamp(get_boot_time())
except:
self.uptime = datetime.now() - datetime.fromtimestamp(BOOT_TIME)
# Convert uptime to string (because datetime is not JSONifi)
self.stats = str(self.uptime).split('.')[0]
def msg_curse(self, args=None):
"""
Return the string to display in the curse interface
"""
# Init the return message
ret = []
# Add the line with decoration
ret.append(self.curse_add_line("Uptime: %s" % self.stats))
# Return the message with decoration
return ret
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册