text stringlengths 81 112k |
|---|
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 ({})".for... |
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("Conne... |
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)
... |
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():
... |
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()
... |
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
... |
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
... |
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
... |
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'... |
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... |
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... |
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:
ra... |
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... |
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 ... |
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 perce... |
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[... |
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 t... |
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(), s... |
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.debu... |
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,
... |
Export the stats to the Statsd server.
def export(self, name, columns, points):
"""Export the stats to the Statsd server."""
if name == self.plugins_to_export()[0] and self.buffer != {}:
# One complete loop have been done
logger.debug("Export stats ({}) to RESTful endpoint ({})"... |
Init the monitored folder list.
The list is defined in the Glances configuration file.
def __set_folder_list(self, section):
"""Init the monitored folder list.
The list is defined in the Glances configuration file.
"""
for l in range(1, self.__folder_list_max_size + 1):
... |
Return the size of the directory given by path
path: <string>
def __folder_size(self, path):
"""Return the size of the directory given by path
path: <string>"""
ret = 0
for f in scandir(path):
if f.is_dir() and (f.name != '.' or f.name != '..'):
re... |
Update the command result attributed.
def update(self):
"""Update the command result attributed."""
# Only continue if monitor list is not empty
if len(self.__folder_list) == 0:
return self.__folder_list
# Iter upon the folder list
for i in range(len(self.get())):
... |
Return the bars.
def get(self):
"""Return the bars."""
frac, whole = modf(self.size * self.percent / 100.0)
ret = curses_bars[8] * int(whole)
if frac > 0:
ret += curses_bars[int(frac * 8)]
whole += 1
ret += self.__empty_char * int(self.size - whole)
... |
Init the connection to the CouchDB server.
def init(self):
"""Init the connection to the CouchDB server."""
if not self.export_enable:
return None
server_uri = 'tcp://{}:{}'.format(self.host, self.port)
try:
self.context = zmq.Context()
publisher = ... |
Close the socket and context
def exit(self):
"""Close the socket and context"""
if self.client is not None:
self.client.close()
if self.context is not None:
self.context.destroy() |
Write the points to the ZeroMQ server.
def export(self, name, columns, points):
"""Write the points to the ZeroMQ server."""
logger.debug("Export {} stats to ZeroMQ".format(name))
# Create DB input
data = dict(zip(columns, points))
# Do not publish empty stats
if data ... |
Init the connection to the Cassandra server.
def init(self):
"""Init the connection to the Cassandra server."""
if not self.export_enable:
return None
# if username and/or password are not set the connection will try to connect with no auth
auth_provider = PlainTextAuthProv... |
Write the points to the Cassandra cluster.
def export(self, name, columns, points):
"""Write the points to the Cassandra cluster."""
logger.debug("Export {} stats to Cassandra".format(name))
# Remove non number stats and convert all to float (for Boolean)
data = {k: float(v) for (k, v)... |
Close the Cassandra export module.
def exit(self):
"""Close the Cassandra export module."""
# To ensure all connections are properly closed
self.session.shutdown()
self.cluster.shutdown()
# Call the father method
super(Export, self).exit() |
Try to determine the name of a Linux distribution.
This function checks for the /etc/os-release file.
It takes the name from the 'NAME' field and the version from 'VERSION_ID'.
An empty string is returned if the above values cannot be determined.
def _linux_os_release():
"""Try to determine the name o... |
Update the host/system info using the input method.
Return the stats (dict)
def update(self):
"""Update the host/system info using the input method.
Return the stats (dict)
"""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
... |
Return the string to display in the curse interface.
def msg_curse(self, args=None, max_width=None):
"""Return the string to display in the curse interface."""
# Init the return message
ret = []
# Build the string message
if args.client:
# Client mode
if... |
Update swap memory stats using the input method.
def update(self):
"""Update swap memory stats using the input method."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
# Grab SWAP usi... |
Update stats views.
def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
# Alert and log
self.views['used']['decoration'] = self.get_alert_log(self.stats['used'], maximum=self.stats[... |
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 plugin not disabled
if not self.stats or self.is_disa... |
Update the AMP list.
def update(self):
"""Update the AMP list."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
for k, v in iteritems(self.glances_amps.update()):
stats.append({'key': k,
'name':... |
Return the alert status relative to the process number.
def get_alert(self, nbprocess=0, countmin=None, countmax=None, header="", log=False):
"""Return the alert status relative to the process number."""
if nbprocess is None:
return 'OK'
if countmin is None:
countmin = n... |
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
# Only process if stats exist and display plugin enable...
ret = []
if not self.stats or args.di... |
Update per-CPU stats using the input method.
def update(self):
"""Update per-CPU stats using the input method."""
# Init new stats
stats = self.get_init_value()
# Grab per-CPU stats using psutil's cpu_percent(percpu=True) and
# cpu_times_percent(percpu=True) methods
if ... |
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...
if not self.stats or not self.args.percpu or self.is_d... |
Overwrite the exit method to close threads.
def exit(self):
"""Overwrite the exit method to close threads."""
if self._thread is not None:
self._thread.stop()
# Call the father class
super(Plugin, self).exit() |
Update the ports list.
def update(self):
"""Update the ports list."""
if self.input_method == 'local':
# Only refresh:
# * if there is not other scanning thread
# * every refresh seconds (define in the configuration file)
if self._thread is None:
... |
Return the alert status relative to the port scan return value.
def get_ports_alert(self, port, header="", log=False):
"""Return the alert status relative to the port scan return value."""
ret = 'OK'
if port['status'] is None:
ret = 'CAREFUL'
elif port['status'] == 0:
... |
Return the alert status relative to the web/url scan return value.
def get_web_alert(self, web, header="", log=False):
"""Return the alert status relative to the web/url scan return value."""
ret = 'OK'
if web['status'] is None:
ret = 'CAREFUL'
elif web['status'] not in [200... |
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
# Only process if stats exist and display plugin enable...
ret = []
if not self.stats or args.di... |
Grab the stats.
Infinite loop, should be stopped by calling the stop() method.
def run(self):
"""Grab the stats.
Infinite loop, should be stopped by calling the stop() method.
"""
for p in self._stats:
# End of the thread has been asked
if self.stopped(... |
Stop the thread.
def stop(self, timeout=None):
"""Stop the thread."""
logger.debug("ports plugin - Close thread for scan list {}".format(self._stats))
self._stopper.set() |
Scan the Web/URL (dict) and update the status key.
def _web_scan(self, web):
"""Scan the Web/URL (dict) and update the status key."""
try:
req = requests.head(web['url'],
allow_redirects=True,
verify=web['ssl_verify'],
... |
Scan the port structure (dict) and update the status key.
def _port_scan(self, port):
"""Scan the port structure (dict) and update the status key."""
if int(port['port']) == 0:
return self._port_scan_icmp(port)
else:
return self._port_scan_tcp(port) |
Convert hostname to IP address.
def _resolv_name(self, hostname):
"""Convert hostname to IP address."""
ip = hostname
try:
ip = socket.gethostbyname(hostname)
except Exception as e:
logger.debug("{}: Cannot convert {} to IP address ({})".format(self.plugin_name, ... |
Scan the (ICMP) port structure (dict) and update the status key.
def _port_scan_icmp(self, port):
"""Scan the (ICMP) port structure (dict) and update the status key."""
ret = None
# Create the ping command
# Use the system ping command because it already have the steacky bit set
... |
Scan the (TCP) port structure (dict) and update the status key.
def _port_scan_tcp(self, port):
"""Scan the (TCP) port structure (dict) and update the status key."""
ret = None
# Create and configure the scanning socket
try:
socket.setdefaulttimeout(port['timeout'])
... |
Wrapper to load: plugins and export modules.
def load_modules(self, args):
"""Wrapper to load: plugins and export modules."""
# Init the plugins dict
# Active plugins dictionnary
self._plugins = collections.defaultdict(dict)
# Load the plugins
self.load_plugins(args=arg... |
Load the plugin (script), init it and add to the _plugin dict.
def _load_plugin(self, plugin_script, args=None, config=None):
"""Load the plugin (script), init it and add to the _plugin dict."""
# The key is the plugin name
# for example, the file glances_xxx.py
# generate self._plugins... |
Load all plugins in the 'plugins' folder.
def load_plugins(self, args=None):
"""Load all plugins in the 'plugins' folder."""
for item in os.listdir(plugins_path):
if (item.startswith(self.header) and
item.endswith(".py") and
item != (self.header + "pl... |
Load all export modules in the 'exports' folder.
def load_exports(self, args=None):
"""Load all export modules in the 'exports' folder."""
if args is None:
return False
header = "glances_"
# Build the export module available list
args_var = vars(locals()['args'])
... |
Return the plugins list.
if enable is True, only return the active plugins (default)
if enable is False, return all the plugins
Return: list of plugin name
def getPluginsList(self, enable=True):
"""Return the plugins list.
if enable is True, only return the active plugins (de... |
Return the exports list.
if enable is True, only return the active exporters (default)
if enable is False, return all the exporters
Return: list of export module name
def getExportsList(self, enable=True):
"""Return the exports list.
if enable is True, only return the active ... |
Load the stats limits (except the one in the exclude list).
def load_limits(self, config=None):
"""Load the stats limits (except the one in the exclude list)."""
# For each plugins, call the load_limits method
for p in self._plugins:
self._plugins[p].load_limits(config) |
Wrapper method to update the stats.
def update(self):
"""Wrapper method to update the stats."""
# For standalone and server modes
# For each plugins, call the update method
for p in self._plugins:
if self._plugins[p].is_disable():
# If current plugin is disab... |
Export all the stats.
Each export module is ran in a dedicated thread.
def export(self, input_stats=None):
"""Export all the stats.
Each export module is ran in a dedicated thread.
"""
# threads = []
input_stats = input_stats or {}
for e in self._exports:
... |
Return all the stats (dict).
def getAllAsDict(self):
"""Return all the stats (dict)."""
return {p: self._plugins[p].get_raw() for p in self._plugins} |
Return all the stats to be exported (list).
Default behavor is to export all the stat
if plugin_list is provided, only export stats of given plugin (list)
def getAllExports(self, plugin_list=None):
"""
Return all the stats to be exported (list).
Default behavor is to export all ... |
Return all the stats to be exported (list).
Default behavor is to export all the stat
if plugin_list is provided, only export stats of given plugin (list)
def getAllExportsAsDict(self, plugin_list=None):
"""
Return all the stats to be exported (list).
Default behavor is to expor... |
Return all the stats limits (dict).
Default behavor is to export all the limits
if plugin_list is provided, only export limits of given plugin (list)
def getAllLimitsAsDict(self, plugin_list=None):
"""
Return all the stats limits (dict).
Default behavor is to export all the limi... |
Return all the stats views (dict).
def getAllViewsAsDict(self):
"""Return all the stats views (dict)."""
return {p: self._plugins[p].get_views() for p in self._plugins} |
End of the Glances stats.
def end(self):
"""End of the Glances stats."""
# Close export modules
for e in self._exports:
self._exports[e].exit()
# Close plugins
for p in self._plugins:
self._plugins[p].exit() |
Update network stats using the input method.
Stats is a list of dict (one dict per interface)
def update(self):
"""Update network stats using the input method.
Stats is a list of dict (one dict per interface)
"""
# Init new stats
stats = self.get_init_value()
... |
Update stats views.
def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
# Alert
for i in self.stats:
ifrealname = i['interface_name'].split(':')[0]
# Convert... |
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... |
Init the connection to the ES server.
def init(self):
"""Init the connection to the ES server."""
if not self.export_enable:
return None
self.index='{}-{}'.format(self.index, datetime.utcnow().strftime("%Y.%m.%d"))
template_body = {
"mappings": {
"gla... |
Write the points to the ES server.
def export(self, name, columns, points):
"""Write the points to the ES server."""
logger.debug("Export {} stats to ElasticSearch".format(name))
# Create DB input
# https://elasticsearch-py.readthedocs.io/en/master/helpers.html
actions = []
... |
Update IP stats using the input method.
Stats is dict
def update(self):
"""Update IP stats using the input method.
Stats is dict
"""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local' and not import_error_tag:
# Update s... |
Update stats views.
def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
# Optional
for key in iterkeys(self.stats):
self.views[key]['optional'] = True |
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... |
Get the first public IP address returned by one of the online services.
def get(self):
"""Get the first public IP address returned by one of the online services."""
q = queue.Queue()
for u, j, k in urls:
t = threading.Thread(target=self._get_ip_public, args=(q, u, j, k))
... |
Request the url service and put the result in the queue_target.
def _get_ip_public(self, queue_target, url, json=False, key=None):
"""Request the url service and put the result in the queue_target."""
try:
response = urlopen(url, timeout=self.timeout).read().decode('utf-8')
except E... |
Update the AMP
def update(self, process_list):
"""Update the AMP"""
# Get the Nginx status
logger.debug('{}: Update stats using status URL {}'.format(self.NAME, self.get('status_url')))
res = requests.get(self.get('status_url'))
if res.ok:
# u'Active connections: 1 \... |
Init the connection to the Kafka server.
def init(self):
"""Init the connection to the Kafka server."""
if not self.export_enable:
return None
# Build the server URI with host and port
server_uri = '{}:{}'.format(self.host, self.port)
try:
s = KafkaProd... |
Write the points to the kafka server.
def export(self, name, columns, points):
"""Write the points to the kafka server."""
logger.debug("Export {} stats to Kafka".format(name))
# Create DB input
data = dict(zip(columns, points))
# Send stats to the kafka topic
# key=<p... |
Close the Kafka export module.
def exit(self):
"""Close the Kafka export module."""
# To ensure all connections are properly closed
self.client.flush()
self.client.close()
# Call the father method
super(Export, self).exit() |
Specific case for io_counters
Sum of io_r + io_w
def _sort_io_counters(process,
sortedby='io_counters',
sortedby_secondary='memory_percent'):
"""Specific case for io_counters
Sum of io_r + io_w"""
return process[sortedby][0] - process[sortedby][2] + process[s... |
Return a sort lambda function for the sortedbykey
def _sort_lambda(sortedby='cpu_percent',
sortedby_secondary='memory_percent'):
"""Return a sort lambda function for the sortedbykey"""
ret = None
if sortedby == 'io_counters':
ret = _sort_io_counters
elif sortedby == 'cpu_times'... |
Return the stats (dict) sorted by (sortedby).
Reverse the sort if reverse is True.
def sort_stats(stats,
sortedby='cpu_percent',
sortedby_secondary='memory_percent',
reverse=True):
"""Return the stats (dict) sorted by (sortedby).
Reverse the sort if reverse is... |
Update the global process count from the current processes list
def update_processcount(self, plist):
"""Update the global process count from the current processes list"""
# Update the maximum process ID (pid) number
self.processcount['pid_max'] = self.pid_max
# For each key in the proc... |
Get the maximum PID value.
On Linux, the value is read from the `/proc/sys/kernel/pid_max` file.
From `man 5 proc`:
The default value for this file, 32768, results in the same range of
PIDs as on earlier kernels. On 32-bit platfroms, 32768 is the maximum
value for pid_max. On 6... |
Reset the maximum values dict.
def reset_max_values(self):
"""Reset the maximum values dict."""
self._max_values = {}
for k in self._max_values_list:
self._max_values[k] = 0.0 |
Update the processes stats.
def update(self):
"""Update the processes stats."""
# Reset the stats
self.processlist = []
self.reset_processcount()
# Do not process if disable tag is set
if self.disable_tag:
return
# Time since last update (for disk_i... |
Update the AMP
def update(self, process_list):
"""Update the AMP"""
# Get the systemctl status
logger.debug('{}: Update stats using service {}'.format(self.NAME, self.get('service_cmd')))
try:
res = check_output(self.get('service_cmd').split(), stderr=STDOUT).decode('utf-8')... |
Convert seconds to human-readable time.
def seconds_to_hms(input_seconds):
"""Convert seconds to human-readable time."""
minutes, seconds = divmod(input_seconds, 60)
hours, minutes = divmod(minutes, 60)
hours = int(hours)
minutes = int(minutes)
seconds = str(int(seconds)).zfill(2)
return ... |
Return path, cmd and arguments for a process cmdline.
def split_cmdline(cmdline):
"""Return path, cmd and arguments for a process cmdline."""
path, cmd = os.path.split(cmdline[0])
arguments = ' '.join(cmdline[1:])
return path, cmd, arguments |
Update processes stats using the input method.
def update(self):
"""Update processes stats using the input method."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
# Note: Update is d... |
Return the alert relative to the Nice configuration list
def get_nice_alert(self, value):
"""Return the alert relative to the Nice configuration list"""
value = str(value)
try:
if value in self.get_limit('nice_critical'):
return 'CRITICAL'
except KeyError:
... |
Get curses data to display for a process.
- p is the process to display
- first is a tag=True if the process is the first on the list
def get_process_curses_data(self, p, first, args):
"""Get curses data to display for a process.
- p is the process to display
- first is a tag=... |
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 args.di... |
Build the header and add it to the ret dict.
def __msg_curse_header(self, ret, process_sort_key, args=None):
"""Build the header and add it to the ret dict."""
sort_style = 'SORT'
if args.disable_irix and 0 < self.nb_log_core < 10:
msg = self.layout_header['cpu'].format('CPU%/' + s... |
Build the sum message (only when filter is on) and add it to the ret dict.
* ret: list of string where the message is added
* sep_char: define the line separation char
* mmm: display min, max, mean or current (if mmm=None)
* args: Glances args
def __msg_curse_sum(self, ret, sep_char='_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.