提交 d4ea4867 编写于 作者: A Alessio Sergi

Cleaning up *.py files

- remove obsolete code
- glances_password: update comments and fix typos
- re-apply fix to avoid string format conflicts (screwed up after
  feature branch merges)
- strip trailing whitespaces
- flake8
上级 621cd746
......@@ -50,9 +50,10 @@ class GlancesClient():
# Build the URI
if args.password != "":
uri = 'http://%s:%s@%s:%d' % (args.username, args.password, args.bind_address, args.port)
uri = 'http://{0}:{1}@{2}:{3}'.format(args.username, args.password,
args.bind_address, args.port)
else:
uri = 'http://%s:%d' % (args.bind_address, args.port)
uri = 'http://{0}:{1}'.format(args.bind_address, args.port)
# Try to connect to the URI
try:
......@@ -115,7 +116,7 @@ class GlancesClient():
if not self.stats.check_snmp():
print(_("Error: Connection to SNMP server failed"))
sys.exit(2)
sys.exit(2)
else:
ret = False
......@@ -157,7 +158,7 @@ class GlancesClient():
try:
server_stats = json.loads(self.client.getAll())
server_stats['monitor'] = json.loads(self.client.getAllMonitored())
except socket.error as e:
except socket.error:
# Client can not get server stats
return "Disconnected"
else:
......@@ -200,4 +201,4 @@ class GlancesClient():
End of the client session
"""
self.screen.end()
\ No newline at end of file
......@@ -31,7 +31,7 @@ import sys
try:
from psutil import __version__ as __psutil_version__
except ImportError:
print('psutil module not found. Glances cannot start.')
print('psutil library not found. Glances cannot start.')
sys.exit(1)
# Check psutil version
......
......@@ -22,7 +22,6 @@ Main Glances script
# Import system libs
import argparse
import sys
# Import Glances libs
from glances.core.glances_config import Config
......@@ -43,28 +42,8 @@ class GlancesMain(object):
# Set the default cache lifetime to 1 second (only for server)
# !!! Todo: configuration from the command line
cached_time = 1
# Default network bitrate is display in bit per second
# network_bytepersec_tag = False
# Display (or not) module
# diskio_tag = True
# fs_tag = True
# hddtemp_flag = True
# network_tag = True
# sensors_tag = True
# process_tag = True
# Display property
# use_bold = True
# percpu_tag = False
# Default configuration file
# conf_file_tag = True
# conf_file = ""
# Bind IP address (default is all interfaces)
# bind_ip = "0.0.0.0"
# By default, Glances is ran in standalone mode (no client/server)
client_tag = False
# server_tag = False
# Server IP address (no default value)
# server_ip = None
# Server TCP port number (default is 61209)
server_port = 61209
# Web Server TCP port number (default is 61208)
......@@ -72,12 +51,6 @@ class GlancesMain(object):
# Default username/password for client/server mode
username = "glances"
password = ""
# Output type (default is no output)
# output_list = ['html', 'csv']
# html_tag = False
# csv_tag = False
# output_file = None
# output_folder = None
def __init__(self):
"""Manage the command line arguments."""
......@@ -113,19 +86,19 @@ class GlancesMain(object):
dest='disable_log', help=_('disable log module'))
# CSV output feature
parser.add_argument('--output-csv', default=None,
dest='output_csv', help=_('export stats to a csv file'))
dest='output_csv', help=_('export stats to a CSV file'))
# Server option
parser.add_argument('-p', '--port', default=self.server_port, type=int, dest='port',
help=_('define the client/server TCP port [default: %d]') % self.server_port)
parser.add_argument('--password-badidea', dest='password_arg',
help=_('Define password from the command line'))
help=_('define password from the command line'))
parser.add_argument('--password', action='store_true', default=False, dest='password_prompt',
help=_('define a client/server password from the prompt or file'))
parser.add_argument('-s', '--server', action='store_true', default=False,
dest='server', help=_('run Glances in server mode'))
parser.add_argument('--snmp-community', default='public', dest='snmp_community',
help=_('SNMP community'))
parser.add_argument('--snmp-port', default=161, type=int,
parser.add_argument('--snmp-port', default=161, type=int,
dest='snmp_port', help=_('SNMP port'))
parser.add_argument('--snmp-version', default='2c', dest='snmp_version',
help=_('SNMP version (1, 2c or 3)'))
......@@ -210,7 +183,7 @@ class GlancesMain(object):
def __get_password(self, description='', confirm=False, clear=False):
"""
Read a password from the command line
Read a password from the command line
- with confirmation if confirm = True
- plain (clear password) if clear = True
"""
......
......@@ -18,11 +18,11 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
import getpass
import hashlib
import os
import sys
import uuid
import hashlib
import getpass
# Import Glances lib
from glances.core.glances_globals import (
......@@ -41,18 +41,16 @@ class glancesPassword:
def __init__(self):
self.password_path = self.get_password_path()
self.password_filename = __appname__ + '.pwd'
self.password_filename = 'glances.pwd'
self.password_filepath = os.path.join(self.password_path, self.password_filename)
def get_password_path(self):
"""
Get the path where the password file will be stored
On Linux and BSD the right place should be $XDG_DATA_HOME aka $HOME/.local/share/glances/foo.
On OS X: the right place is under user's Library folder aka $HOME/Library/glances/foo
On Windows: os.environ['APPDATA']+'/glances/'+foo
* Linux and BSD: ~/.config/glances
* OS X: ~/Library/glances
* Windows: %APPDATA%\glances
"""
# Get the system application data path for the current user
if is_linux or is_bsd:
app_path = os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config')
elif is_mac:
......@@ -69,22 +67,22 @@ class glancesPassword:
def get_hash(self, salt, plain_password):
"""
Return the hashed password SHA265 + salt
Return the hashed password salt + SHA-256
"""
return hashlib.sha256(salt.encode() + plain_password.encode()).hexdigest()
def hash_password(self, plain_password):
"""
Hash password with a salt based on UUID
Hash password with a salt based on UUID (universally unique identifier)
"""
salt = uuid.uuid4().hex
encrypted_password = self.get_hash(salt, plain_password)
return salt + '$' + encrypted_password
def check_password(self, hashed_password, plain_password):
"""
Encode the plain_password with the salt of the hashed_password
and return the comparaison with the encrypted_password
and return the comparison with the encrypted_password
"""
salt, encrypted_password = hashed_password.split('$')
re_encrypted_password = self.get_hash(salt, plain_password)
......@@ -93,26 +91,26 @@ class glancesPassword:
def get_password(self, description='', confirm=False, clear=False):
"""
For Glances server, get the password (confirm=True, clear=False)
1) from the password file (if the file exist)
1) from the password file (if it exists)
2) from the CLI
Optinnaly: save the password to a file (hashed with SHA256 + SALT)
Optionally: save the password to a file (hashed with salt + SHA-256)
For Glances client, get the password (confirm=False, clear=True)
1) From the CLI
2) The password is hashed with SHA256 (only SHA string transit thrught the network)
1) from the CLI
2) the password is hashed with SHA-256 (only SHA string transit through the network)
"""
if os.path.exists(self.password_filepath) and not clear:
# If the password file exist then use it
sys.stdout.write(_("[Info] Read password from file %s\n") % self.password_filepath)
sys.stdout.write(_("[Info] Read password from file %s\n") % self.password_filepath)
password = self.load_password()
else:
# Else enter the password from the command line
if description != '':
sys.stdout.write("%s\n" % description)
# password_plain is the password MD5
# password_hashed is the hashed password
# password_plain is the plain SHA-256 password
# password_hashed is the salt + SHA-256 password
password_sha = hashlib.sha256(getpass.getpass(_("Password: "))).hexdigest()
password_hashed = self.hash_password(password_sha)
if confirm:
......@@ -123,7 +121,7 @@ class glancesPassword:
sys.stdout.write(_("[Error] Sorry, but passwords did not match...\n"))
sys.exit(1)
# Return the clear or hashed password
# Return the plain or hashed password
if clear:
password = password_sha
else:
......@@ -131,7 +129,7 @@ class glancesPassword:
# Save the hashed password to the password file
if not clear:
save_input = raw_input(_("Do you want to save the password (Yes|No) ? "))
save_input = raw_input(_("Do you want to save the password? (Yes|No) "))
if len(save_input) > 0 and save_input[0].upper() == _('Y'):
self.save_password(password_hashed)
......@@ -139,19 +137,19 @@ class glancesPassword:
def save_password(self, hashed_password):
"""
Save the hashed password to the Glances appdata folder
Save the hashed password to the Glances folder
"""
# Check if the Glances appdata folder already exist
# Check if the Glances folder already exist
if not os.path.exists(self.password_path):
# Create the Glances appdata folder
# Create the Glances folder
try:
os.mkdir(self.password_path)
except Exception as e:
sys.stdout.write(_("[Warning] Glances application data folder can not be created (%s)\n") % e)
return
# Create/overwrite the password file to the Glances application data folder
# Create/overwrite the password file to the Glances folder
try:
file_pwd = open(self.password_filepath, 'w')
except Exception as e:
......@@ -164,10 +162,10 @@ class glancesPassword:
def load_password(self):
"""
Load the hashed password from the Glances appdata folder
Load the hashed password from the Glances folder
"""
# Create/overwrite the password file to the Glances application data folder
# Create/overwrite the password file to the Glances folder
try:
file_pwd = open(self.password_filepath, 'r')
except Exception as e:
......
......@@ -21,21 +21,18 @@ import sys
try:
from pysnmp.entity.rfc3413.oneliner import cmdgen
except ImportError, e:
print("Error importing PySNMP lib: %s" % e)
except ImportError:
print("PySNMP library not found.")
print("Install using pip: # pip install pysnmp")
sys.exit(2)
class GlancesSNMPClient(object):
""" SNMP client class (based on PySNMP) """
def __init__(self, host="localhost",
port=161,
version="2c",
community="public",
user="private",
auth=""):
def __init__(self, host='localhost', port=161, version='2c',
community='public', user='private', auth=''):
super(GlancesSNMPClient, self).__init__()
self.cmdGen = cmdgen.CommandGenerator()
......@@ -54,9 +51,9 @@ class GlancesSNMPClient(object):
"""
ret = {}
if not (errorIndication or errorStatus):
if not errorIndication or not errorStatus:
for name, val in varBinds:
if (str(val) == ''):
if str(val) == '':
ret[name.prettyPrint()] = ''
else:
ret[name.prettyPrint()] = val.prettyPrint()
......@@ -70,7 +67,7 @@ class GlancesSNMPClient(object):
> Return a dict
"""
if (self.version == '3'):
if self.version == '3':
errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.getCmd(
cmdgen.UsmUserData(self.user, self.auth),
cmdgen.UdpTransportTarget((self.host, self.port)),
......@@ -86,11 +83,11 @@ class GlancesSNMPClient(object):
def __bulk_result__(self, errorIndication, errorStatus, errorIndex, varBindTable):
ret = []
if not (errorIndication or errorStatus):
if not errorIndication or not errorStatus:
for varBindTableRow in varBindTable:
item = {}
for name, val in varBindTableRow:
if (str(val) == ''):
if str(val) == '':
item[name.prettyPrint()] = ''
else:
item[name.prettyPrint()] = val.prettyPrint()
......@@ -100,10 +97,10 @@ class GlancesSNMPClient(object):
def getbulk_by_oid(self, non_repeaters, max_repetitions, *oid):
"""
SNMP getbulk request
In contrast to snmpwalk, this information will typically be gathered in a
In contrast to snmpwalk, this information will typically be gathered in a
single transaction with the agent, rather than one transaction per variable found.
* non_repeaters: This specifies the number of supplied variables that should not be iterated over.
* max_repetitions: This specifies the maximum number of iterations over the repeating variables.
* non_repeaters: This specifies the number of supplied variables that should not be iterated over.
* max_repetitions: This specifies the maximum number of iterations over the repeating variables.
* oid: oid list
> Return a list of dicts
"""
......@@ -112,7 +109,7 @@ class GlancesSNMPClient(object):
errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.getCmd(
cmdgen.UsmUserData(self.user, self.auth),
cmdgen.UdpTransportTarget((self.host, self.port)),
non_repeaters,
non_repeaters,
max_repetitions,
*oid
)
......@@ -120,7 +117,7 @@ class GlancesSNMPClient(object):
errorIndication, errorStatus, errorIndex, varBindTable = self.cmdGen.bulkCmd(
cmdgen.CommunityData(self.community),
cmdgen.UdpTransportTarget((self.host, self.port)),
non_repeaters,
non_repeaters,
max_repetitions,
*oid
)
......
......@@ -44,7 +44,7 @@ class GlancesStats(object):
def __getattr__(self, item):
"""
Overwrite the getattr in case of attribute is not found
The goal is to dynamicaly generate the following methods:
The goal is to dynamically generate the following methods:
- getPlugname(): return Plugname stat in JSON format
"""
......@@ -80,7 +80,7 @@ class GlancesStats(object):
plug != (header + "plugin.py")):
# Import the plugin
m = __import__(os.path.basename(plug)[:-3])
# Add the plugin to the dictionnary
# Add the plugin to the dictionary
# The key is the plugin name
# for example, the file glances_xxx.py
# generate self._plugins_list["xxx"] = ...
......@@ -126,9 +126,9 @@ class GlancesStats(object):
def getAll(self):
"""
Return all the stats
Return all the stats
"""
return [ self._plugins[p].get_raw() for p in self._plugins ]
return [self._plugins[p].get_raw() for p in self._plugins]
def get_plugin_list(self):
# Return the plugin list
......@@ -238,7 +238,7 @@ class GlancesStatsClientSNMP(GlancesStats):
"""
Chek if SNMP is available on the server
"""
# Import the SNMP client class
from glances.core.glances_snmp import GlancesSNMPClient
......@@ -267,4 +267,3 @@ class GlancesStatsClientSNMP(GlancesStats):
except Exception as e:
print "ERROR: Update %s failed (%s)" % (p, e)
# pass
......@@ -19,8 +19,8 @@
import sys
import threading
import msvcrt
import msvcrt
try:
import colorconsole
import colorconsole.terminal
......
......@@ -22,14 +22,14 @@ import sys
try:
import csv
except ImportError:
print('CSV module not found. Glances cannot extract to .csv file.')
print('CSV module not found. Glances cannot export to CSV file.')
sys.exit(1)
# Import Glances libs
from glances.core.glances_globals import is_py3
# List of stats enable in the CSV output
csv_stats_list = [ 'cpu', 'load', 'mem', 'memswap' ]
csv_stats_list = ['cpu', 'load', 'mem', 'memswap']
class glancesCsv:
......@@ -56,7 +56,7 @@ class glancesCsv:
print(_("Cannot create the CSV output file: %s") % error)
sys.exit(2)
print("{0}: {1}".format(_("Stats dumped in the CSV file"), self.__csvfile_name))
print(_("Stats dumped in the CSV file: {0}").format(self.__csvfile_name))
def exit(self):
self.__csvfile_fd.close()
......@@ -72,8 +72,8 @@ class glancesCsv:
i = 0
for p in stats.getAllPlugins():
if p in csv_stats_list:
# First line for comment: csv_comment
csv_comment = [ '# ' + str(p) + ': ' + '|'.join(all_stats[i].keys()) ]
# First line for comment: csv_comment
csv_comment = ['# ' + str(p) + ': ' + '|'.join(all_stats[i].keys())]
self.__csvfile.writerow(csv_comment)
# Second line for stats (CSV): csv_stats
self.__csvfile.writerow(all_stats[i].values())
......
......@@ -45,7 +45,7 @@ class Plugin(GlancesPlugin):
self.line_curse = -1
# Init the stats
self.reset()
self.reset()
def reset(self):
"""
......
......@@ -17,7 +17,7 @@
# 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/>.
"""
Batinfo (batterie) plugin
Batinfo (battery) plugin
"""
# Batinfo library (optional; Linux-only)
......@@ -46,7 +46,7 @@ class Plugin(GlancesPlugin):
self.glancesgrabbat = glancesGrabBat()
# Init stats
self.reset()
self.reset()
def reset(self):
"""
......
......@@ -28,9 +28,10 @@ from glances.plugins.glances_plugin import GlancesPlugin
# percentage of user CPU time: .1.3.6.1.4.1.2021.11.9.0
# percentages of system CPU time: .1.3.6.1.4.1.2021.11.10.0
# percentages of idle CPU time: .1.3.6.1.4.1.2021.11.11.0
snmp_oid = { 'user': '1.3.6.1.4.1.2021.11.9.0',
'system': '1.3.6.1.4.1.2021.11.10.0',
'idle': '1.3.6.1.4.1.2021.11.11.0' }
snmp_oid = {'user': '1.3.6.1.4.1.2021.11.9.0',
'system': '1.3.6.1.4.1.2021.11.10.0',
'idle': '1.3.6.1.4.1.2021.11.11.0'}
class Plugin(GlancesPlugin):
"""
......@@ -53,7 +54,7 @@ class Plugin(GlancesPlugin):
# Init stats
self.first_call = True
self.reset()
self.reset()
def reset(self):
"""
......@@ -124,13 +125,12 @@ class Plugin(GlancesPlugin):
# Total CPU usage
msg = "{0:>6.1%}".format((100 - self.stats['idle']) / 100)
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:"))
# Nice CPU
if 'nice' in self.stats:
msg = " {0:8}".format(_("nice:"))
ret.append(self.curse_add_line(msg))
msg = "{0:>6.1%}".format(self.stats['nice'] / 100)
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
......@@ -139,46 +139,40 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg))
msg = "{0:>6.1%}".format(self.stats['user'] / 100)
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:"))
# IRQ CPU
if 'irq' in self.stats:
msg = " {0:8}".format(_("irq:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0:>6.1%}".format(self.stats['irq'] / 100)
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%'))
msg = "{0:>6.1%}".format(self.stats['system'] / 100)
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:8}".format(_("irq:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.stats['irq'] / 100, '>6.1%'))
# IOWait CPU
if 'iowait' in self.stats:
msg = " {0:8}".format(_("iowait:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0:>6.1%}".format(self.stats['iowait'] / 100)
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())
# Nice CPU
if 'nice' in self.stats:
msg = "{0:8}".format(_("nice:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['nice'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# Idles CPU
# ret.append(self.curse_add_line(" ", optional=True))
# Idle CPU
if 'idle' in self.stats:
msg = ""
if 'nice' in self.stats:
msg = " "
msg += "{0:8}".format(_("idle:"))
msg = "{0:8}".format(_("idle:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.stats['idle'] / 100, '>6.1%'))
msg = "{0:>6.1%}".format(self.stats['idle'] / 100)
ret.append(self.curse_add_line(msg))
# Steal CPU usage
if 'steal' in self.stats:
msg = " {0:8}".format(_("steal:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0:>6.1%}".format(self.stats['steal'] / 100)
ret.append(self.curse_add_line(msg, self.get_alert(self.stats['steal'], header="steal"), optional=True))
# Return the message with decoration
return ret
......@@ -47,7 +47,7 @@ class Plugin(GlancesPlugin):
self.line_curse = 3
# Init the stats
self.reset()
self.reset()
def reset(self):
"""
......@@ -107,7 +107,7 @@ class Plugin(GlancesPlugin):
continue
else:
self.stats.append(diskstat)
# Save stats to compute next bitrate
self.diskio_old = diskio_new
elif self.get_input() == 'snmp':
......
......@@ -22,7 +22,7 @@ import psutil
from glances.plugins.glances_plugin import GlancesPlugin
# SNMP OID
# The snmpd.conf needs to be edited.
# The snmpd.conf needs to be edited.
# Add the following to enable it on all disk
# ...
# includeAllDisks 10%
......@@ -35,11 +35,11 @@ from glances.plugins.glances_plugin import GlancesPlugin
# Used space on the disk: .1.3.6.1.4.1.2021.9.1.8.1
# Percentage of space used on disk: .1.3.6.1.4.1.2021.9.1.9.1
# Percentage of inodes used on disk: .1.3.6.1.4.1.2021.9.1.10.1
snmp_oid = { 'mnt_point': '1.3.6.1.4.1.2021.9.1.2',
'device_name': '1.3.6.1.4.1.2021.9.1.3',
'size': '1.3.6.1.4.1.2021.9.1.6',
'used': '1.3.6.1.4.1.2021.9.1.8',
'percent': '1.3.6.1.4.1.2021.9.1.9' }
snmp_oid = {'mnt_point': '1.3.6.1.4.1.2021.9.1.2',
'device_name': '1.3.6.1.4.1.2021.9.1.3',
'size': '1.3.6.1.4.1.2021.9.1.6',
'used': '1.3.6.1.4.1.2021.9.1.8',
'percent': '1.3.6.1.4.1.2021.9.1.9'}
class Plugin(GlancesPlugin):
......@@ -62,7 +62,7 @@ class Plugin(GlancesPlugin):
self.line_curse = 4
# Init the stats
self.reset()
self.reset()
def reset(self):
"""
......@@ -150,7 +150,7 @@ class Plugin(GlancesPlugin):
for i in sorted(self.stats, key=lambda fs: fs['mnt_point']):
# New line
ret.append(self.curse_new_line())
if (len(i['mnt_point']) + len(i['device_name'].split('/')[-1])) <= 6:
if len(i['mnt_point']) + len(i['device_name'].split('/')[-1]) <= 6:
# If possible concatenate mode info... Glances touch inside :)
mnt_point = i['mnt_point'] + ' (' + i['device_name'].split('/')[-1] + ')'
elif len(i['mnt_point']) > 9:
......
......@@ -42,7 +42,7 @@ class Plugin(GlancesPlugin):
self.display_curse = False
# Init stats
self.reset()
self.reset()
def reset(self):
"""
......@@ -67,7 +67,6 @@ class Plugin(GlancesPlugin):
# Not available for the moment
pass
return self.stats
......
......@@ -31,9 +31,9 @@ from glances.plugins.glances_plugin import GlancesPlugin
# 1 minute Load: .1.3.6.1.4.1.2021.10.1.3.1
# 5 minute Load: .1.3.6.1.4.1.2021.10.1.3.2
# 15 minute Load: .1.3.6.1.4.1.2021.10.1.3.3
snmp_oid = { 'min1': '1.3.6.1.4.1.2021.10.1.3.1',
'min5': '1.3.6.1.4.1.2021.10.1.3.2',
'min15': '1.3.6.1.4.1.2021.10.1.3.3' }
snmp_oid = {'min1': '1.3.6.1.4.1.2021.10.1.3.1',
'min5': '1.3.6.1.4.1.2021.10.1.3.2',
'min15': '1.3.6.1.4.1.2021.10.1.3.3'}
class Plugin(GlancesPlugin):
......@@ -75,7 +75,7 @@ class Plugin(GlancesPlugin):
# Call CorePlugin in order to display the core number
try:
nb_log_core = CorePlugin().update()["log"]
except:
except Exception:
nb_log_core = 0
if self.get_input() == 'local':
......@@ -84,20 +84,17 @@ class Plugin(GlancesPlugin):
# Get the load using the os standard lib
try:
load = os.getloadavg()
except OSError:
self.stats = {}
except AttributeError:
# For Windows OS...
except (OSError, AttributeError):
self.stats = {}
else:
self.stats = {'min1': load[0],
'min5': load[1],
'min15': load[2],
'cpucore': nb_log_core }
'cpucore': nb_log_core}
elif self.get_input() == 'snmp':
# Update stats using SNMP
self.stats = self.set_stats_snmp(snmp_oid=snmp_oid)
self.stats['cpucore'] = nb_log_core
if self.stats['min1'] == '':
......@@ -106,7 +103,7 @@ class Plugin(GlancesPlugin):
for key in self.stats.iterkeys():
self.stats[key] = float(self.stats[key])
return self.stats
def msg_curse(self, args=None):
......@@ -123,11 +120,11 @@ class Plugin(GlancesPlugin):
# Build the string message
# Header
msg = "{0:8}".format(_("LOAD"))
msg = "{0:4}".format(_("LOAD"))
ret.append(self.curse_add_line(msg, "TITLE"))
# Core number
if (self.stats['cpucore'] > 0):
msg = "{0:>6}".format(str(self.stats['cpucore'])+_("core"))
if self.stats['cpucore'] > 0:
msg = _("{0:>5}-core").format(self.stats['cpucore'])
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
......
......@@ -31,12 +31,12 @@ from glances.plugins.glances_plugin import GlancesPlugin
# Total RAM Shared: .1.3.6.1.4.1.2021.4.13.0
# Total RAM Buffered: .1.3.6.1.4.1.2021.4.14.0
# Total Cached Memory: .1.3.6.1.4.1.2021.4.15.0
snmp_oid = { 'total': '1.3.6.1.4.1.2021.4.5.0',
# 'used': '1.3.6.1.4.1.2021.4.6.0',
'free': '1.3.6.1.4.1.2021.4.11.0',
'shared': '1.3.6.1.4.1.2021.4.13.0',
'buffers': '1.3.6.1.4.1.2021.4.14.0',
'cached': '1.3.6.1.4.1.2021.4.15.0' }
snmp_oid = {'total': '1.3.6.1.4.1.2021.4.5.0',
# 'used': '1.3.6.1.4.1.2021.4.6.0',
'free': '1.3.6.1.4.1.2021.4.11.0',
'shared': '1.3.6.1.4.1.2021.4.13.0',
'buffers': '1.3.6.1.4.1.2021.4.14.0',
'cached': '1.3.6.1.4.1.2021.4.15.0'}
class Plugin(GlancesPlugin):
......@@ -59,7 +59,7 @@ class Plugin(GlancesPlugin):
self.line_curse = 1
# Init the stats
self.reset()
self.reset()
def reset(self):
"""
......@@ -113,8 +113,7 @@ class Plugin(GlancesPlugin):
# Update stats using SNMP
self.stats = self.set_stats_snmp(snmp_oid=snmp_oid)
if self.stats['total'] == '':
if self.stats['total'] == '':
self.reset()
return self.stats
......
......@@ -27,8 +27,8 @@ from glances.plugins.glances_plugin import GlancesPlugin
# SNMP OID
# Total Swap Size: .1.3.6.1.4.1.2021.4.3.0
# Available Swap Space: .1.3.6.1.4.1.2021.4.4.0
snmp_oid = { 'total': '1.3.6.1.4.1.2021.4.3.0',
'free': '1.3.6.1.4.1.2021.4.4.0' }
snmp_oid = {'total': '1.3.6.1.4.1.2021.4.3.0',
'free': '1.3.6.1.4.1.2021.4.4.0'}
class Plugin(GlancesPlugin):
......@@ -51,7 +51,7 @@ class Plugin(GlancesPlugin):
self.line_curse = 1
# Init the stats
self.reset()
self.reset()
def reset(self):
"""
......@@ -87,7 +87,7 @@ class Plugin(GlancesPlugin):
# Update stats using SNMP
self.stats = self.set_stats_snmp(snmp_oid=snmp_oid)
if self.stats['total'] == '':
if self.stats['total'] == '':
self.reset()
return self.stats
......
......@@ -30,9 +30,9 @@ from glances.plugins.glances_plugin import GlancesPlugin
# SNMP OID
# http://www.net-snmp.org/docs/mibs/interfaces.html
# Dict key = interface_name
snmp_oid = { 'interface_name': '1.3.6.1.2.1.2.2.1.2',
'cumulative_rx': '1.3.6.1.2.1.2.2.1.10',
'cumulative_tx': '1.3.6.1.2.1.2.2.1.16' }
snmp_oid = {'interface_name': '1.3.6.1.2.1.2.2.1.2',
'cumulative_rx': '1.3.6.1.2.1.2.2.1.10',
'cumulative_tx': '1.3.6.1.2.1.2.2.1.16'}
class Plugin(GlancesPlugin):
......@@ -115,14 +115,13 @@ class Plugin(GlancesPlugin):
continue
else:
self.stats.append(netstat)
# Save stats to compute next bitrate
self.network_old = network_new
elif self.get_input() == 'snmp':
# Update stats using SNMP
# SNMP bulk command to get all network interface in one shot
netiocounters = self.set_stats_snmp(snmp_oid=snmp_oid, bulk=True)
......@@ -159,7 +158,7 @@ class Plugin(GlancesPlugin):
continue
else:
self.stats.append(netstat)
# Save stats to compute next bitrate
self.network_old = network_new
......
......@@ -147,7 +147,7 @@ class Plugin(GlancesPlugin):
# No per CPU stat ? Exit...
if self.stats == []:
msg = "{0}".format(_("PER CPU not available"))
msg = _("PER CPU not available")
ret.append(self.curse_add_line(msg, "TITLE"))
return ret
......
......@@ -32,13 +32,13 @@ class Plugin(GlancesPlugin):
def __init__(self, args=None):
GlancesPlugin.__init__(self, args=args)
self.reset()
self.reset()
def reset(self):
"""
Reset/init the stats
"""
self.stats = None
self.stats = None
def update(self):
"""
......
......@@ -58,7 +58,7 @@ class Plugin(GlancesPlugin):
self.line_curse = 5
# Init the stats
self.reset()
self.reset()
def reset(self):
"""
......@@ -72,7 +72,7 @@ class Plugin(GlancesPlugin):
"""
# Reset the stats
self.reset()
self.reset()
if self.get_input() == 'local':
# Update stats using the standard system lib
......
......@@ -28,8 +28,8 @@ import platform
from glances.plugins.glances_plugin import GlancesPlugin
# SNMP OID
snmp_oid = { 'hostname': '1.3.6.1.2.1.1.5.0',
'os_name': '1.3.6.1.2.1.1.1.0' }
snmp_oid = {'hostname': '1.3.6.1.2.1.1.5.0',
'os_name': '1.3.6.1.2.1.1.1.0'}
class Plugin(GlancesPlugin):
"""
......@@ -51,7 +51,7 @@ class Plugin(GlancesPlugin):
self.line_curse = 0
# Init the stats
self.reset()
self.reset()
def reset(self):
"""
......
......@@ -27,7 +27,7 @@ import psutil
from glances.plugins.glances_plugin import GlancesPlugin
# SNMP OID
snmp_oid = { '_uptime': '1.3.6.1.2.1.1.3.0' }
snmp_oid = {'_uptime': '1.3.6.1.2.1.1.3.0'}
class Plugin(GlancesPlugin):
"""
......@@ -49,7 +49,7 @@ class Plugin(GlancesPlugin):
# Enter -1 to diplay bottom
self.line_curse = 0
# Init the stats
self.reset()
self.reset()
def reset(self):
"""
......@@ -74,7 +74,7 @@ class Plugin(GlancesPlugin):
elif self.get_input() == 'snmp':
# Update stats using SNMP
uptime = self.set_stats_snmp(snmp_oid=snmp_oid)['_uptime']
try:
try:
# In hundredths of seconds
self.stats = str(timedelta(seconds=int(uptime) / 100))
except:
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册