INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Write the points in RabbitMQ. | def export(self, name, columns, points):
"""Write the points in RabbitMQ."""
data = ('hostname=' + self.hostname + ', name=' + name +
', dateinfo=' + datetime.datetime.utcnow().isoformat())
for i in range(len(columns)):
if not isinstance(points[i], Number):
... |
Normalize name for the Statsd convention | def normalize(name):
"""Normalize name for the Statsd convention"""
# Name should not contain some specials chars (issue #1068)
ret = name.replace(':', '')
ret = ret.replace('%', '')
ret = ret.replace(' ', '_')
return ret |
Init the connection to the Statsd server. | def init(self):
"""Init the connection to the Statsd server."""
if not self.export_enable:
return None
logger.info(
"Stats will be exported to StatsD server: {}:{}".format(self.host,
self.port))
r... |
Export the stats to the Statsd server. | def export(self, name, columns, points):
"""Export the stats to the Statsd server."""
for i in range(len(columns)):
if not isinstance(points[i], Number):
continue
stat_name = '{}.{}'.format(name, columns[i])
stat_value = points[i]
try:
... |
Load the ports list from the configuration file. | def load(self, config):
"""Load the ports list from the configuration file."""
ports_list = []
if config is None:
logger.debug("No configuration file available. Cannot load ports list.")
elif not config.has_section(self._section):
logger.debug("No [%s] section in... |
Set the key to the value for the pos (position in the list). | def set_server(self, pos, key, value):
"""Set the key to the value for the pos (position in the list)."""
self._ports_list[pos][key] = value |
Init the connection to the OpenTSDB server. | def init(self):
"""Init the connection to the OpenTSDB server."""
if not self.export_enable:
return None
try:
db = potsdb.Client(self.host,
port=int(self.port),
check_host=True)
except Exception as e:
... |
Export the stats to the Statsd server. | def export(self, name, columns, points):
"""Export the stats to the Statsd server."""
for i in range(len(columns)):
if not isinstance(points[i], Number):
continue
stat_name = '{}.{}.{}'.format(self.prefix, name, columns[i])
stat_value = points[i]
... |
Build and return the logger.
env_key define the env var where a path to a specific JSON logger
could be defined
:return: logger -- Logger instance | def glances_logger(env_key='LOG_CFG'):
"""Build and return the logger.
env_key define the env var where a path to a specific JSON logger
could be defined
:return: logger -- Logger instance
"""
_logger = logging.getLogger()
# By default, use the LOGGING_CFG logger configuration
... |
Update the IRQ stats. | def update(self):
"""Update the IRQ stats."""
# Init new stats
stats = self.get_init_value()
# IRQ plugin only available on GNU/Linux
if not LINUX:
return self.stats
if self.input_method == 'local':
# Grab the stats
stats = self.irq.g... |
Return the dict to display in the curse interface. | def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only available on GNU/Linux
# Only process if stats exist and display plugin enable...
if not LINUX or not self.stats or not self... |
Build the header (contain the number of CPU).
CPU0 CPU1 CPU2 CPU3
0: 21 0 0 0 IO-APIC 2-edge timer | def __header(self, line):
"""Build the header (contain the number of CPU).
CPU0 CPU1 CPU2 CPU3
0: 21 0 0 0 IO-APIC 2-edge timer
"""
self.cpu_number = len(line.split())
return self.cpu_number |
Return the IRQ name, alias or number (choose the best for human).
IRQ line samples:
1: 44487 341 44 72 IO-APIC 1-edge i8042
LOC: 33549868 22394684 32474570 21855077 Local timer interrupts | def __humanname(self, line):
"""Return the IRQ name, alias or number (choose the best for human).
IRQ line samples:
1: 44487 341 44 72 IO-APIC 1-edge i8042
LOC: 33549868 22394684 32474570 21855077 Local timer interrupts
"""
... |
Return the IRQ sum number.
IRQ line samples:
1: 44487 341 44 72 IO-APIC 1-edge i8042
LOC: 33549868 22394684 32474570 21855077 Local timer interrupts
FIQ: usb_fiq | def __sum(self, line):
"""Return the IRQ sum number.
IRQ line samples:
1: 44487 341 44 72 IO-APIC 1-edge i8042
LOC: 33549868 22394684 32474570 21855077 Local timer interrupts
FIQ: usb_fiq
"""
splitted_line = line.sp... |
Load the IRQ file and update the internal dict. | def __update(self):
"""Load the IRQ file and update the internal dict."""
self.reset()
if not os.path.exists(self.IRQ_FILE):
# Correct issue #947: IRQ file do not exist on OpenVZ container
return self.stats
try:
with open(self.IRQ_FILE) as irq_proc:
... |
Init the connection to the MQTT server. | def init(self):
"""Init the connection to the MQTT server."""
if not self.export_enable:
return None
try:
client = paho.Client(client_id='glances_' + self.hostname,
clean_session=False)
client.username_pw_set(username=self.user... |
Write the points in MQTT. | def export(self, name, columns, points):
"""Write the points in MQTT."""
WHITELIST = '_-' + string.ascii_letters + string.digits
SUBSTITUTE = '_'
def whitelisted(s,
whitelist=WHITELIST,
substitute=SUBSTITUTE):
return ''.join(c... |
Update battery capacity stats using the input method. | def update(self):
"""Update battery capacity stats using the input method."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats
self.glancesgrabbat.update()
stats = self.glancesgrabbat.get()
elif s... |
Update the stats. | def update(self):
"""Update the stats."""
if batinfo_tag:
# Use the batinfo lib to grab the stats
# Compatible with multiple batteries
self.bat.update()
self.bat_list = [{
'label': 'Battery',
'value': self.battery_percent,
... |
Get batteries capacity percent. | def battery_percent(self):
"""Get batteries capacity percent."""
if not batinfo_tag or not self.bat.stat:
return []
# Init the bsum (sum of percent)
# and Loop over batteries (yes a computer could have more than 1 battery)
bsum = 0
for b in self.bat.stat:
... |
Load server and password list from the confiuration file. | def load(self):
"""Load server and password list from the confiuration file."""
# Init the static server list (if defined)
self.static_server = GlancesStaticServer(config=self.config)
# Init the password list (if defined)
self.password = GlancesPassword(config=self.config) |
Return the current server list (list of dict).
Merge of static + autodiscover servers list. | def get_servers_list(self):
"""Return the current server list (list of dict).
Merge of static + autodiscover servers list.
"""
ret = []
if self.args.browser:
ret = self.static_server.get_servers_list()
if self.autodiscover_server is not None:
... |
Return the URI for the given server dict. | def __get_uri(self, server):
"""Return the URI for the given server dict."""
# Select the connection mode (with or without password)
if server['password'] != "":
if server['status'] == 'PROTECTED':
# Try with the preconfigure password (only if status is PROTECTED)
... |
Update stats for the given server (picked from the server list) | def __update_stats(self, server):
"""
Update stats for the given server (picked from the server list)
"""
# Get the server URI
uri = self.__get_uri(server)
# Try to connect to the server
t = GlancesClientTransport()
t.set_timeout(3)
# Get common ... |
Connect and display the given server | def __display_server(self, server):
"""
Connect and display the given server
"""
# Display the Glances client for the selected server
logger.debug("Selected server {}".format(server))
# Connection can take time
# Display a popup
self.screen.display_popup(... |
Main client loop. | def __serve_forever(self):
"""Main client loop."""
# No need to update the server list
# It's done by the GlancesAutoDiscoverListener class (autodiscover.py)
# Or define staticaly in the configuration file (module static_list.py)
# For each server in the list, grab elementary sta... |
Set the (key, value) for the selected server in the list. | def set_in_selected(self, key, value):
"""Set the (key, value) for the selected server in the list."""
# Static list then dynamic one
if self.screen.active_server >= len(self.static_server.get_servers_list()):
self.autodiscover_server.set_server(
self.screen.active_se... |
Generate Graph file in the output folder. | def update(self, stats):
"""Generate Graph file in the output folder."""
if self.generate_every != 0 and self._timer.finished():
self.args.generate_graph = True
self._timer.reset()
if not self.args.generate_graph:
return
plugins = stats.getPluginsLi... |
Generate graph from the data.
Example for the mem plugin:
{'percent': [
(datetime.datetime(2018, 3, 24, 16, 27, 47, 282070), 51.8),
(datetime.datetime(2018, 3, 24, 16, 27, 47, 540999), 51.9),
(datetime.datetime(2018, 3, 24, 16, 27, 50, 653390), 52.0),
(da... | def export(self, title, data):
"""Generate graph from the data.
Example for the mem plugin:
{'percent': [
(datetime.datetime(2018, 3, 24, 16, 27, 47, 282070), 51.8),
(datetime.datetime(2018, 3, 24, 16, 27, 47, 540999), 51.9),
(datetime.datetime(2018, 3, 24, 1... |
Init all the command line arguments. | def init_args(self):
"""Init all the command line arguments."""
version = "Glances v" + __version__ + " with psutil v" + psutil_version
parser = argparse.ArgumentParser(
prog='glances',
conflict_handler='resolve',
formatter_class=argparse.RawDescriptionHelpFor... |
Parse command line arguments. | def parse_args(self):
"""Parse command line arguments."""
args = self.init_args().parse_args()
# Load the configuration file, if it exists
self.config = Config(args.conf_file)
# Debug mode
if args.debug:
from logging import DEBUG
logger.setLevel(... |
Return True if Glances is running in standalone mode. | def is_standalone(self):
"""Return True if Glances is running in standalone mode."""
return (not self.args.client and
not self.args.browser and
not self.args.server and
not self.args.webserver) |
Return True if Glances is running in client mode. | def is_client(self):
"""Return True if Glances is running in client mode."""
return (self.args.client or self.args.browser) and not self.args.server |
Read a password from the command line.
- if confirm = True, with confirmation
- if clear = True, plain (clear password) | def __get_password(self, description='',
confirm=False, clear=False, username='glances'):
"""Read a password from the command line.
- if confirm = True, with confirmation
- if clear = True, plain (clear password)
"""
from glances.password import GlancesPas... |
Return a list of tuples taken from self.args.stdout
[(plugin, attribute), ... ] | def build_list(self):
"""Return a list of tuples taken from self.args.stdout
[(plugin, attribute), ... ]"""
ret = []
for p in self.args.stdout.split(','):
if '.' in p:
p, a = p.split('.')
else:
a = None
ret.append((p, a)... |
Display stats to stdout.
Refresh every duration second. | def update(self,
stats,
duration=3):
"""Display stats to stdout.
Refresh every duration second.
"""
for plugin, attribute in self.plugins_list:
# Check if the plugin exist and is enable
if plugin in stats.getPluginsList() and \
... |
Update load stats. | def update(self):
"""Update load stats."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
# Get the load using the os standard lib
load = self._getloadavg()
if ... |
Update stats views. | def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
try:
# Alert and log
self.views['min15']['decoration'] = self.get_alert_log(self.stats['min15'], maximum=100 * sel... |
Return the dict to display in the curse interface. | def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist, not empty (issue #871) and plugin not disabled
if not self.stats or (self.stats == {}) or self.is_disable():... |
Update the stats. | def update(self):
"""Update the stats."""
# Reset stats
self.reset()
# Return psutil version as a tuple
if self.input_method == 'local':
# psutil version only available in local
try:
self.stats = psutil_version_info
except Name... |
Load outdated parameter in the global section of the configuration file. | def load_config(self, config):
"""Load outdated parameter in the global section of the configuration file."""
global_section = 'global'
if (hasattr(config, 'has_section') and
config.has_section(global_section)):
self.args.disable_check_update = config.get_value(globa... |
Wrapper to get the latest PyPI version (async)
The data are stored in a cached file
Only update online once a week | def get_pypi_version(self):
"""Wrapper to get the latest PyPI version (async)
The data are stored in a cached file
Only update online once a week
"""
if self.args.disable_check_update:
return
# If the cached file exist, read-it
cached_data = self._loa... |
Return True if a new version is available | def is_outdated(self):
"""Return True if a new version is available"""
if self.args.disable_check_update:
# Check is disabled by configuration
return False
logger.debug("Check Glances version (installed: {} / latest: {})".format(self.installed_version(), self.latest_vers... |
Load cache file and return cached data | def _load_cache(self):
"""Load cache file and return cached data"""
# If the cached file exist, read-it
max_refresh_date = timedelta(days=7)
cached_data = {}
try:
with open(self.cache_file, 'rb') as f:
cached_data = pickle.load(f)
except Except... |
Save data to the cache file. | def _save_cache(self):
"""Save data to the cache file."""
# Create the cache directory
safe_makedirs(self.cache_dir)
# Create/overwrite the cache file
try:
with open(self.cache_file, 'wb') as f:
pickle.dump(self.data, f)
except Exception as e:... |
Get the latest PyPI version (as a string) via the RESTful JSON API | def _update_pypi_version(self):
"""Get the latest PyPI version (as a string) via the RESTful JSON API"""
logger.debug("Get latest Glances version from the PyPI RESTful API ({})".format(PYPI_API_URL))
# Update the current time
self.data[u'refresh_date'] = datetime.now()
try:
... |
Set the cursor to position N-1 in the list. | def cursor_up(self, stats):
"""Set the cursor to position N-1 in the list."""
if 0 <= self.cursor_position - 1:
self.cursor_position -= 1
else:
if self._current_page - 1 < 0 :
self._current_page = self._page_max - 1
self.cursor_position = (... |
Set the cursor to position N-1 in the list. | def cursor_down(self, stats):
"""Set the cursor to position N-1 in the list."""
if self.cursor_position + 1 < self.get_pagelines(stats):
self.cursor_position += 1
else:
if self._current_page + 1 < self._page_max:
self._current_page += 1
... |
Set prev page. | def cursor_pageup(self, stats):
"""Set prev page."""
if self._current_page - 1 < 0:
self._current_page = self._page_max - 1
else:
self._current_page -= 1
self.cursor_position = 0 |
Set next page. | def cursor_pagedown(self, stats):
"""Set next page."""
if self._current_page + 1 < self._page_max:
self._current_page += 1
else:
self._current_page = 0
self.cursor_position = 0 |
Update the servers' list screen.
Wait for __refresh_time sec / catch key every 100 ms.
stats: Dict of dict with servers stats | def update(self,
stats,
duration=3,
cs_status=None,
return_to_browser=False):
"""Update the servers' list screen.
Wait for __refresh_time sec / catch key every 100 ms.
stats: Dict of dict with servers stats
"""
# Flush... |
Display the servers list.
Return:
True if the stats have been displayed
False if the stats have not been displayed (no server available) | def display(self, stats, cs_status=None):
"""Display the servers list.
Return:
True if the stats have been displayed
False if the stats have not been displayed (no server available)
"""
# Init the internal line/column for Glances Curses
self.init_line_col... |
https://stackoverflow.com/a/19719292
@return: True if the current user is an 'Admin' whatever that
means (root on Unix), otherwise False.
Warning: The inner function fails unless you have Windows XP SP2 or
higher. The failure causes a traceback to be printed and this
function to return False. | def is_admin():
"""
https://stackoverflow.com/a/19719292
@return: True if the current user is an 'Admin' whatever that
means (root on Unix), otherwise False.
Warning: The inner function fails unless you have Windows XP SP2 or
higher. The failure causes a traceback to be printed and this
func... |
Get SMART attribute data
:return: list of multi leveled dictionaries
each dict has a key "DeviceName" with the identification of the device in smartctl
also has keys of the SMART attribute id, with value of another dict of the attributes
[
{
... | def get_smart_data():
"""
Get SMART attribute data
:return: list of multi leveled dictionaries
each dict has a key "DeviceName" with the identification of the device in smartctl
also has keys of the SMART attribute id, with value of another dict of the attributes
[
... |
Update SMART stats using the input method. | def update(self):
"""Update SMART stats using the input method."""
# Init new stats
stats = self.get_init_value()
if import_error_tag:
return self.stats
if self.input_method == 'local':
stats = get_smart_data()
elif self.input_method == 'snmp':
... |
Init the Prometheus Exporter | def init(self):
"""Init the Prometheus Exporter"""
try:
start_http_server(port=int(self.port), addr=self.host)
except Exception as e:
logger.critical("Can not start Prometheus exporter on {}:{} ({})".format(self.host, self.port, e))
sys.exit(2)
else:
... |
Write the points to the Prometheus exporter using Gauge. | def export(self, name, columns, points):
"""Write the points to the Prometheus exporter using Gauge."""
logger.debug("Export {} stats to Prometheus exporter".format(name))
# Remove non number stats and convert all to float (for Boolean)
data = {k: float(v) for (k, v) in iteritems(dict(z... |
Return the list of plugins to export. | def _plugins_to_export(self):
"""Return the list of plugins to export."""
ret = self.exportable_plugins
for p in ret:
if getattr(self.args, 'disable_' + p):
ret.remove(p)
return ret |
Load the export <section> configuration in the Glances configuration file.
:param section: name of the export section to load
:param mandatories: a list of mandatories parameters to load
:param options: a list of optionnals parameters to load
:returns: Boolean -- True if section is fou... | def load_conf(self, section, mandatories=['host', 'port'], options=None):
"""Load the export <section> configuration in the Glances configuration file.
:param section: name of the export section to load
:param mandatories: a list of mandatories parameters to load
:param options: a list ... |
Return the value of the item 'key'. | def get_item_key(self, item):
"""Return the value of the item 'key'."""
try:
ret = item[item['key']]
except KeyError:
logger.error("No 'key' available in {}".format(item))
if isinstance(ret, list):
return ret[0]
else:
return ret |
Parse tags into a dict.
input tags: a comma separated list of 'key:value' pairs.
Example: foo:bar,spam:eggs
output dtags: a dict of tags.
Example: {'foo': 'bar', 'spam': 'eggs'} | def parse_tags(self, tags):
"""Parse tags into a dict.
input tags: a comma separated list of 'key:value' pairs.
Example: foo:bar,spam:eggs
output dtags: a dict of tags.
Example: {'foo': 'bar', 'spam': 'eggs'}
"""
dtags = {}
if tags:
tr... |
Update stats to a server.
The method builds two lists: names and values
and calls the export method to export the stats.
Note: this class can be overwrite (for example in CSV and Graph). | def update(self, stats):
"""Update stats to a server.
The method builds two lists: names and values
and calls the export method to export the stats.
Note: this class can be overwrite (for example in CSV and Graph).
"""
if not self.export_enable:
return False... |
Build the export lists. | def __build_export(self, stats):
"""Build the export lists."""
export_names = []
export_values = []
if isinstance(stats, dict):
# Stats is a dict
# Is there a key ?
if 'key' in iterkeys(stats) and stats['key'] in iterkeys(stats):
pre_k... |
Update the stats. | def update(self, input_stats=None):
"""Update the stats."""
input_stats = input_stats or {}
# Force update of all the stats
super(GlancesStatsServer, self).update()
# Build all_stats variable (concatenation of all the stats)
self.all_stats = self._set_stats(input_stats) |
Set the stats to the input_stats one. | def _set_stats(self, input_stats):
"""Set the stats to the input_stats one."""
# Build the all_stats with the get_raw() method of the plugins
return {p: self._plugins[p].get_raw() for p in self._plugins if self._plugins[p].is_enable()} |
Init the connection to the InfluxDB server. | def init(self):
"""Init the connection to the InfluxDB server."""
if not self.export_enable:
return None
try:
db = InfluxDBClient(host=self.host,
port=self.port,
username=self.user,
... |
Normalize data for the InfluxDB's data model. | def _normalize(self, name, columns, points):
"""Normalize data for the InfluxDB's data model."""
for i, _ in enumerate(points):
# Supported type:
# https://docs.influxdata.com/influxdb/v1.5/write_protocols/line_protocol_reference/
if points[i] is None:
... |
Write the points to the InfluxDB server. | def export(self, name, columns, points):
"""Write the points to the InfluxDB server."""
# Manage prefix
if self.prefix is not None:
name = self.prefix + '.' + name
# Write input to the InfluxDB database
try:
self.client.write_points(self._normalize(name, c... |
Set the filter (as a sting) and compute the regular expression
A filter could be one of the following:
- python > Process name of cmd start with python
- .*python.* > Process name of cmd contain python
- username:nicolargo > Process of nicolargo user | def filter(self, value):
"""Set the filter (as a sting) and compute the regular expression
A filter could be one of the following:
- python > Process name of cmd start with python
- .*python.* > Process name of cmd contain python
- username:nicolargo > Process of nicolargo user
... |
Return True if the process item match the current filter
The proces item is a dict. | def is_filtered(self, process):
"""Return True if the process item match the current filter
The proces item is a dict.
"""
if self.filter is None:
# No filter => Not filtered
return False
if self.filter_key is None:
# Apply filter on command l... |
Return True if the process[key] should be filtered according to the current filter | def _is_process_filtered(self, process, key=None):
"""Return True if the process[key] should be filtered according to the current filter"""
if key is None:
key = self.filter_key
try:
# If the item process[key] is a list, convert it to a string
# in order to ma... |
Load the password from the configuration file. | def load(self, config):
"""Load the password from the configuration file."""
password_dict = {}
if config is None:
logger.warning("No configuration file available. Cannot load password list.")
elif not config.has_section(self._section):
logger.warning("No [%s] se... |
If host=None, return the current server list (dict).
Else, return the host's password (or the default one if defined or None) | def get_password(self, host=None):
"""
If host=None, return the current server list (dict).
Else, return the host's password (or the default one if defined or None)
"""
if host is None:
return self._password_dict
else:
try:
return s... |
Update the AMP | def update(self, process_list):
"""Update the AMP"""
# Get the systemctl status
logger.debug('{}: Update stats using systemctl {}'.format(self.NAME, self.get('systemctl_cmd')))
try:
res = check_output(self.get('systemctl_cmd').split())
except (OSError, CalledProcessEr... |
Get GPU device memory consumption in percent. | def get_mem(device_handle):
"""Get GPU device memory consumption in percent."""
try:
memory_info = pynvml.nvmlDeviceGetMemoryInfo(device_handle)
return memory_info.used * 100.0 / memory_info.total
except pynvml.NVMLError:
return None |
Init the NVIDIA API. | def init_nvidia(self):
"""Init the NVIDIA API."""
if import_error_tag:
self.nvml_ready = False
try:
pynvml.nvmlInit()
self.device_handles = get_device_handles()
self.nvml_ready = True
except Exception:
logger.debug("pynvml coul... |
Update the GPU stats. | def update(self):
"""Update the GPU stats."""
# Init new stats
stats = self.get_init_value()
# !!! JUST FOR TEST (because i did not have any NVidia GPU... :()
# self.stats = [{"key": "gpu_id", "mem": None, "proc": 60, "gpu_id": 0, "name": "GeForce GTX 560 Ti"}]
# self.st... |
Return the dict to display in the curse interface. | def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist, not empty (issue #871) and plugin not disabled
if not self.stats or (self.stats == []) or self.is_disable():... |
Get GPU stats. | def get_device_stats(self):
"""Get GPU stats."""
stats = []
for index, device_handle in enumerate(self.device_handles):
device_stats = {}
# Dictionnary key is the GPU_ID
device_stats['key'] = self.get_key()
# GPU id (for multiple GPU, start at 0)
... |
Overwrite the exit method to close the GPU API. | def exit(self):
"""Overwrite the exit method to close the GPU API."""
if self.nvml_ready:
try:
pynvml.nvmlShutdown()
except Exception as e:
logger.debug("pynvml failed to shutdown correctly ({})".format(e))
# Call the father exit method
... |
Log and exit. | def log_and_exit(self, msg=''):
"""Log and exit."""
if not self.return_to_browser:
logger.critical(msg)
sys.exit(2)
else:
logger.error(msg) |
Login to a Glances server | def _login_glances(self):
"""Login to a Glances server"""
client_version = None
try:
client_version = self.client.init()
except socket.error as err:
# Fallback to SNMP
self.client_mode = 'snmp'
logger.error("Connection to Glances server fai... |
Login to a SNMP server | def _login_snmp(self):
"""Login to a SNMP server"""
logger.info("Trying to grab stats by SNMP...")
from glances.stats_client_snmp import GlancesStatsClientSNMP
# Init stats
self.stats = GlancesStatsClientSNMP(config=self.config, args=self.args)
if not self.stats.check_... |
Logon to the server. | def login(self):
"""Logon to the server."""
if self.args.snmp_force:
# Force SNMP instead of Glances server
self.client_mode = 'snmp'
else:
# First of all, trying to connect to a Glances server
if not self._login_glances():
return ... |
Update stats from Glances/SNMP server. | def update(self):
"""Update stats from Glances/SNMP server."""
if self.client_mode == 'glances':
return self.update_glances()
elif self.client_mode == 'snmp':
return self.update_snmp()
else:
self.end()
logger.critical("Unknown server mode: ... |
Get stats from Glances server.
Return the client/server connection status:
- Connected: Connection OK
- Disconnected: Connection NOK | def update_glances(self):
"""Get stats from Glances server.
Return the client/server connection status:
- Connected: Connection OK
- Disconnected: Connection NOK
"""
# Update the stats
try:
server_stats = json.loads(self.client.getAll())
excep... |
Main client loop. | def serve_forever(self):
"""Main client loop."""
# Test if client and server are in the same major version
if not self.login():
logger.critical("The server version is not compatible with the client")
self.end()
return self.client_mode
exitkey = False... |
Update the foldered list. | def update(self):
"""Update the foldered list."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Folder list only available in a full Glances environment
# Check if the glances_folder instance is init
if self.glances... |
Manage limits of the folder list. | def get_alert(self, stat, header=""):
"""Manage limits of the folder list."""
if not isinstance(stat['size'], numbers.Number):
ret = 'DEFAULT'
else:
ret = 'OK'
if stat['critical'] is not None and \
stat['size'] > int(stat['critical']) * 1000000... |
Return the dict to display in the curse interface. | def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist and display plugin enable...
if not self.stats or self.is_disable():
return ret
# Max si... |
Run the commands (in background).
- stats_name: plugin_name (+ header)
- criticity: criticity of the trigger
- commands: a list of command line with optional {{mustache}}
- If True, then repeat the action
- mustache_dict: Plugin stats (can be use within {{mustache}})
Re... | def run(self, stat_name, criticity, commands, repeat, mustache_dict=None):
"""Run the commands (in background).
- stats_name: plugin_name (+ header)
- criticity: criticity of the trigger
- commands: a list of command line with optional {{mustache}}
- If True, then repeat the act... |
A safe function for creating a directory tree. | def safe_makedirs(path):
"""A safe function for creating a directory tree."""
try:
os.makedirs(path)
except OSError as err:
if err.errno == errno.EEXIST:
if not os.path.isdir(path):
raise
else:
raise |
Set the plugin list according to the Glances server. | def set_plugins(self, input_plugins):
"""Set the plugin list according to the Glances server."""
header = "glances_"
for item in input_plugins:
# Import the plugin
try:
plugin = __import__(header + item)
except ImportError:
# Se... |
Update all the stats. | def update(self, input_stats):
"""Update all the stats."""
# For Glances client mode
for p in input_stats:
# Update plugin stats with items sent by the server
self._plugins[p].set_stats(input_stats[p])
# Update the views for the updated stats
self.... |
Update quicklook stats using the input method. | def update(self):
"""Update quicklook stats using the input method."""
# Init new stats
stats = self.get_init_value()
# Grab quicklook stats: CPU, MEM and SWAP
if self.input_method == 'local':
# Get the latest CPU percent value
stats['cpu'] = cpu_percent.... |
Update stats views. | def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
# Alert only
for key in ['cpu', 'mem', 'swap']:
if key in self.stats:
self.views[key]['decoration'] = ... |
Return the list to display in the UI. | def msg_curse(self, args=None, max_width=10):
"""Return the list to display in the UI."""
# Init the return message
ret = []
# Only process if stats exist...
if not self.stats or self.is_disable():
return ret
# Define the data: Bar (default behavor) or Spark... |
Create a new line to the Quickview. | def _msg_create_line(self, msg, data, key):
"""Create a new line to the Quickview."""
ret = []
ret.append(self.curse_add_line(msg))
ret.append(self.curse_add_line(data.pre_char, decoration='BOLD'))
ret.append(self.curse_add_line(data.get(), self.get_views(key=key, option='decora... |
Update the AMP | def update(self, process_list):
"""Update the AMP"""
# Get the systemctl status
logger.debug('{}: Update AMP stats using service {}'.format(self.NAME, self.get('service_cmd')))
try:
res = self.get('command')
except OSError as e:
logger.debug('{}: Error whi... |
Init the connection to the RESTful server. | def init(self):
"""Init the connection to the RESTful server."""
if not self.export_enable:
return None
# Build the RESTful URL where the stats will be posted
url = '{}://{}:{}{}'.format(self.protocol,
self.host,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.