desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Init the plugin.'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args, items_history_list=items_history_list) self.display_curse = True self.reset()
'Reset/init the stats.'
def reset(self):
self.stats = {}
'Update RAM memory stats using the input method.'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if (self.input_method == 'local'): vm_stats = psutil.virtual_memory() self.reset() for mem in ['total', 'available', 'percent', 'used', 'free', 'active', 'inactive', 'buffers', 'cached', 'wired', 'shared']: if hasattr(vm_stats, mem): self.stats[me...
'Update stats views.'
def update_views(self):
super(Plugin, self).update_views() self.views['used']['decoration'] = self.get_alert_log(self.stats['used'], maximum=self.stats['total']) for key in ['active', 'inactive', 'buffers', 'cached']: if (key in self.stats): self.views[key]['optional'] = True
'Return the dict to display in the curse interface.'
def msg_curse(self, args=None):
ret = [] if ((not self.stats) or self.is_disable()): return ret msg = '{}'.format('MEM') ret.append(self.curse_add_line(msg, 'TITLE')) msg = ' {:2}'.format(self.trend_msg(self.get_trend('percent'))) ret.append(self.curse_add_line(msg)) msg = '{:>7.1%}'.format((self.stats['percent'...
'Init the plugin of plugins class. All Glances\' plugins should inherit from this class. Most of the methods are already implemented in the father classes. Your plugin should return a dict or a list of dicts (stored in the self.stats). As an example, you can have a look on the mem plugin (for dict) or network (for list...
def __init__(self, args=None, items_history_list=None):
self.plugin_name = self.__class__.__module__[len('glances_'):] self.args = args self._align = 'left' self._input_method = 'local' self._short_system_name = None self.items_history_list = items_history_list self.stats_history = self.init_stats_history() self._limits = dict() self.acti...
'Return the raw stats.'
def __repr__(self):
return self.stats
'Return the human-readable stats.'
def __str__(self):
return str(self.stats)
'Reset the stats. This method should be overwrited by childs\' classes'
def reset(self):
self.stats = None
'Method to be called when Glances exit'
def exit(self):
logger.debug('Stop the {} plugin'.format(self.plugin_name))
'Return the key of the list.'
def get_key(self):
return None
'Return true if plugin is enabled'
def is_enable(self):
try: d = getattr(self.args, ('disable_' + self.plugin_name)) except AttributeError: return True else: return (d is False)
'Return true if plugin is disabled'
def is_disable(self):
return (not self.is_enable())
'Return the object \'d\' in a JSON format Manage the issue #815 for Windows OS'
def _json_dumps(self, d):
try: return json.dumps(d) except UnicodeDecodeError: return json.dumps(d, ensure_ascii=False)
'Init the stats history (dict of GlancesAttribute).'
def init_stats_history(self):
if self._history_enable(): init_list = [a['name'] for a in self.get_items_history_list()] logger.debug('Stats history activated for plugin {} (items: {})'.format(self.plugin_name, init_list)) return GlancesHistory()
'Reset the stats history (dict of GlancesAttribute).'
def reset_stats_history(self):
if self._history_enable(): reset_list = [a['name'] for a in self.get_items_history_list()] logger.debug('Reset history for plugin {} (items: {})'.format(self.plugin_name, reset_list)) self.stats_history.reset()
'Update stats history.'
def update_stats_history(self):
if (self.get_key() is None): item_name = '' else: item_name = self.get_key() if (self.stats and self._history_enable()): for i in self.get_items_history_list(): if isinstance(self.stats, list): for l in self.stats: self.stats_history.ad...
'Return the items history list.'
def get_items_history_list(self):
return self.items_history_list
'Return - the stats history (dict of list) if item is None - the stats history for the given item (list) instead - None if item did not exist in the history Limit to lasts nb items (all if nb=0)'
def get_raw_history(self, item=None, nb=0):
s = self.stats_history.get(nb=nb) if (item is None): return s elif (item in s): return s[item] else: return None
'Return: - the stats history (dict of list) if item is None - the stats history for the given item (list) instead - None if item did not exist in the history Limit to lasts nb items (all if nb=0)'
def get_json_history(self, item=None, nb=0):
s = self.stats_history.get_json(nb=nb) if (item is None): return s elif (item in s): return s[item] else: return None
'Return the stats history object to export. See get_raw_history for a full description'
def get_export_history(self, item=None):
return self.get_raw_history(item=item)
'Return the stats history as a JSON object (dict or None). Limit to lasts nb items (all if nb=0)'
def get_stats_history(self, item=None, nb=0):
s = self.get_json_history(nb=nb) if (item is None): return self._json_dumps(s) if isinstance(s, dict): try: return self._json_dumps({item: s[item]}) except KeyError as e: logger.error('Cannot get item history {} ({})'.format(item, e)) ...
'Get the trend regarding to the last nb values The trend is the diff between the mean of the last nb values and the current one.'
def get_trend(self, item, nb=6):
raw_history = self.get_raw_history(item=item, nb=nb) if ((raw_history is None) or (len(raw_history) < nb)): return None last_nb = [v[1] for v in raw_history] return (last_nb[(-1)] - mean(last_nb[:(-1)]))
'Get the input method.'
@property def input_method(self):
return self._input_method
'Set the input method. * local: system local grab (psutil or direct access) * snmp: Client server mode via SNMP * glances: Client server mode via Glances API'
@input_method.setter def input_method(self, input_method):
self._input_method = input_method
'Get the short detected OS name (SNMP).'
@property def short_system_name(self):
return self._short_system_name
'Set the short detected OS name (SNMP).'
@short_system_name.setter def short_system_name(self, short_name):
self._short_system_name = short_name
'Set the stats to input_stats.'
def set_stats(self, input_stats):
self.stats = input_stats
'Update stats using SNMP. If bulk=True, use a bulk request instead of a get request.'
def get_stats_snmp(self, bulk=False, snmp_oid=None):
snmp_oid = (snmp_oid or {}) from glances.snmp import GlancesSNMPClient clientsnmp = GlancesSNMPClient(host=self.args.client, port=self.args.snmp_port, version=self.args.snmp_version, community=self.args.snmp_community) ret = {} if bulk: snmpresult = clientsnmp.getbulk_by_oid(0, 10, itervalue...
'Return the stats object.'
def get_raw(self):
return self.stats
'Return the stats object to export.'
def get_export(self):
return self.get_raw()
'Return the stats object in JSON format.'
def get_stats(self):
return self._json_dumps(self.stats)
'Return the stats object for a specific item in JSON format. Stats should be a list of dict (processlist, network...)'
def get_stats_item(self, item):
if isinstance(self.stats, dict): try: return self._json_dumps({item: self.stats[item]}) except KeyError as e: logger.error('Cannot get item {} ({})'.format(item, e)) return None elif isinstance(self.stats, list): try: return sel...
'Return the stats object for a specific item=value in JSON format. Stats should be a list of dict (processlist, network...)'
def get_stats_value(self, item, value):
if (not isinstance(self.stats, list)): return None else: if value.isdigit(): value = int(value) try: return self._json_dumps({value: [i for i in self.stats if (i[item] == value)]}) except (KeyError, ValueError) as e: logger.error('Cannot get...
'Default builder fo the stats views. The V of MVC A dict of dict with the needed information to display the stats. Example for the stat xxx: \'xxx\': {\'decoration\': \'DEFAULT\', \'optional\': False, \'additional\': False, \'splittable\': False}'
def update_views(self):
ret = {} if (isinstance(self.get_raw(), list) and (self.get_raw() is not None) and (self.get_key() is not None)): for i in self.get_raw(): ret[i[self.get_key()]] = {} for key in listkeys(i): value = {'decoration': 'DEFAULT', 'optional': False, 'additional': False,...
'Set the views to input_views.'
def set_views(self, input_views):
self.views = input_views
'Return the views object. If key is None, return all the view for the current plugin else if option is None return the view for the specific key (all option) else return the view fo the specific key/option Specify item if the stats are stored in a dict of dict (ex: NETWORK, FS...)'
def get_views(self, item=None, key=None, option=None):
if (item is None): item_views = self.views else: item_views = self.views[item] if (key is None): return item_views elif (option is None): return item_views[key] elif (option in item_views[key]): return item_views[key][option] else: return 'DEFAULT'...
'Return views in JSON'
def get_json_views(self, item=None, key=None, option=None):
return self._json_dumps(self.get_views(item, key, option))
'Load limits from the configuration file, if it exists.'
def load_limits(self, config):
self._limits['history_size'] = 28800 if (not hasattr(config, 'has_section')): return False if config.has_section('global'): self._limits['history_size'] = config.get_float_value('global', 'history_size', default=28800) logger.debug('Load configuration key: {} = {}'.for...
'Return the limits object.'
@property def limits(self):
return self._limits
'Set the limits to input_limits.'
@limits.setter def limits(self, input_limits):
self._limits = input_limits
'Return stats for the action By default return all the stats. Can be overwrite by plugins implementation. For example, Docker will return self.stats[\'containers\']'
def get_stats_action(self):
return self.stats
'Return the alert status relative to a current value. Use this function for minor stats. 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 If highlight=True than 0.0 is highligh...
def get_alert(self, current=0, minimum=0, maximum=100, highlight_zero=True, is_max=False, header='', action_key=None, log=False):
if ((not highlight_zero) and (current == 0)): return 'DEFAULT' try: value = ((current * 100) / maximum) except ZeroDivisionError: return 'DEFAULT' except TypeError: return 'DEFAULT' if (header == ''): stat_name = self.plugin_name else: stat_name = ...
'Manage the threshold for the current stat'
def manage_threshold(self, stat_name, trigger):
glances_thresholds.add(stat_name, trigger)
'Manage the action for the current stat'
def manage_action(self, stat_name, trigger, header, action_key):
try: (command, repeat) = self.get_limit_action(trigger, stat_name=stat_name) except KeyError: self.actions.set(stat_name, trigger) else: if (action_key is None): action_key = header if isinstance(self.get_stats_action(), list): mustache_dict = {} ...
'Get the alert log.'
def get_alert_log(self, current=0, minimum=0, maximum=100, header='', action_key=None):
return self.get_alert(current=current, minimum=minimum, maximum=maximum, header=header, action_key=action_key, log=True)
'Return the limit value for the alert.'
def get_limit(self, criticity, stat_name=''):
try: limit = self._limits[((stat_name + '_') + criticity)] except KeyError: limit = self._limits[((self.plugin_name + '_') + criticity)] return limit
'Return the tuple (action, repeat) for the alert. - action is a command line - repeat is a bool'
def get_limit_action(self, criticity, stat_name=''):
ret = [((((stat_name + '_') + criticity) + '_action'), False), ((((stat_name + '_') + criticity) + '_action_repeat'), True), ((((self.plugin_name + '_') + criticity) + '_action'), False), ((((self.plugin_name + '_') + criticity) + '_action_repeat'), True)] for r in ret: if (r[0] in self._limits): ...
'Return the log tag for the alert.'
def get_limit_log(self, stat_name, default_action=False):
try: log_tag = self._limits[(stat_name + '_log')] except KeyError: try: log_tag = self._limits[(self.plugin_name + '_log')] except KeyError: return default_action return (log_tag[0].lower() == 'true')
'Return the configuration (header_) value for the current plugin. ...or the one given by the plugin_name var.'
def get_conf_value(self, value, header='', plugin_name=None):
if (plugin_name is None): plugin_name = self.plugin_name if (header != ''): plugin_name = ((plugin_name + '_') + header) try: return self._limits[((plugin_name + '_') + value)] except KeyError: return []
'Return True if the value is in the hide configuration list. The hide configuration list is defined in the glances.conf file. It is a comma separed list of regexp. Example for diskio: hide=sda2,sda5,loop.*'
def is_hide(self, value, header=''):
return (not all(((j is None) for j in [re.match(i, value) for i in self.get_conf_value('hide', header=header)])))
'Return the alias name for the relative header or None if nonexist.'
def has_alias(self, header):
try: return self._limits[((((self.plugin_name + '_') + header) + '_') + 'alias')][0] except (KeyError, IndexError): return None
'Return default string to display in the curse interface.'
def msg_curse(self, args=None, max_width=None):
return [self.curse_add_line(str(self.stats))]
'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 } ... ]) align | Message position'
def get_stats_display(self, args=None, max_width=None):
display_curse = False if hasattr(self, 'display_curse'): display_curse = self.display_curse if hasattr(self, 'align'): align_curse = self._align if (max_width is not None): ret = {'display': display_curse, 'msgdict': self.msg_curse(args, max_width=max_width), 'align': align_curse...
'Return a dict with. Where: msg: string decoration: DEFAULT: no decoration UNDERLINE: underline BOLD: bold TITLE: for stat title PROCESS: for process name STATUS: for process status NICE: for process niceness CPU_TIME: for process cpu time OK: Value is OK and non logged OK_LOG: Value is OK and logged CAREFUL: Value is ...
def curse_add_line(self, msg, decoration='DEFAULT', optional=False, additional=False, splittable=False):
return {'msg': msg, 'decoration': decoration, 'optional': optional, 'additional': additional, 'splittable': splittable}
'Go to a new line.'
def curse_new_line(self):
return self.curse_add_line('\n')
'Get the curse align.'
@property def align(self):
return self._align
'Set the curse align. value: left, right, bottom.'
@align.setter def align(self, value):
self._align = value
'Make a nice human-readable string out of number. 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: 4...
def auto_unit(self, number, low_precision=False, min_symbol='K'):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') if (min_symbol in symbols): symbols = symbols[symbols.index(min_symbol):] prefix = {'Y': 1208925819614629174706176L, 'Z': 1180591620717411303424L, 'E': 1152921504606846976, 'P': 1125899906842624, 'T': 1099511627776, 'G': 1073741824, 'M': 1048576, 'K...
'Return the trend message Do not take into account if trend < significant'
def trend_msg(self, trend, significant=1):
ret = '-' if (trend is None): ret = ' ' elif (trend > significant): ret = '/' elif (trend < (- significant)): ret = '\\' return ret
'Check if the plugin is enabled.'
def _check_decorator(fct):
def wrapper(self, *args, **kw): if self.is_enable(): ret = fct(self, *args, **kw) else: ret = self.stats return ret return wrapper
'Log (DEBUG) the result of the function fct.'
def _log_result_decorator(fct):
def wrapper(*args, **kw): ret = fct(*args, **kw) logger.debug(('%s %s %s return %s' % (args[0].__class__.__name__, args[0].__class__.__module__[len('glances_'):], fct.__name__, ret))) return ret return wrapper
'Init the plugin.'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args) self.display_curse = True self.reset() self.aws_ec2 = ThreadAwsEc2Grabber() self.aws_ec2.start()
'Reset/init the stats.'
def reset(self):
self.stats = {}
'Overwrite the exit method to close threads'
def exit(self):
self.aws_ec2.stop() super(Plugin, self).exit()
'Update the cloud stats. Return the stats (dict)'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if (not cloud_tag): return self.stats if (self.input_method == 'local'): self.stats = self.aws_ec2.stats return self.stats
'Return the string to display in the curse interface.'
def msg_curse(self, args=None):
ret = [] if ((not self.stats) or (self.stats == {}) or self.is_disable()): return ret if (('ami-id' in self.stats) and ('region' in self.stats)): msg = 'AWS EC2' ret.append(self.curse_add_line(msg, 'TITLE')) msg = ' {} instance {} ({})'.format(to_ascii(self.sta...
'Init the class'
def __init__(self):
logger.debug('cloud plugin - Create thread for AWS EC2') super(ThreadAwsEc2Grabber, self).__init__() self._stopper = threading.Event() self._stats = {}
'Function called to grab stats. Infinite loop, should be stopped by calling the stop() method'
def run(self):
if (not cloud_tag): logger.debug('cloud plugin - Requests lib is not installed') self.stop() return False for (k, v) in iteritems(self.AWS_EC2_API_METADATA): r_url = '{}/{}'.format(self.AWS_EC2_API_URL, v) try: r = requests.get(r_url, time...
'Stats getter'
@property def stats(self):
return self._stats
'Stats setter'
@stats.setter def stats(self, value):
self._stats = value
'Stop the thread'
def stop(self, timeout=None):
logger.debug('cloud plugin - Close thread for AWS EC2') self._stopper.set()
'Return True is the thread is stopped'
def stopped(self):
return self._stopper.isSet()
'Init the plugin.'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args, items_history_list=items_history_list) self.display_curse = True self.reset()
'Return the key of the list.'
def get_key(self):
return 'mnt_point'
'Reset/init the stats.'
def reset(self):
self.stats = []
'Update the FS stats using the input method.'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if (self.input_method == 'local'): try: fs_stat = psutil.disk_partitions(all=False) except UnicodeDecodeError: return self.stats for fstype in self.get_conf_value('allow'): try: fs_stat += [f for f in psutil.disk_partitions...
'Update stats views.'
def update_views(self):
super(Plugin, self).update_views() for i in self.stats: self.views[i[self.get_key()]]['used']['decoration'] = self.get_alert(i['used'], maximum=i['size'], header=i['mnt_point'])
'Return the dict to display in the curse interface.'
def msg_curse(self, args=None, max_width=None):
ret = [] if ((not self.stats) or self.is_disable()): return ret if ((max_width is not None) and (max_width >= 23)): fsname_max_width = (max_width - 14) else: fsname_max_width = 9 msg = '{:{width}}'.format('FILE SYS', width=fsname_max_width) ret.append(self.curse_add_li...
'Init the plugin.'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args, items_history_list=items_history_list) self.display_curse = True self.reset()
'Reset/init the stats.'
def reset(self):
self.stats = {}
'Update swap memory stats using the input method.'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if (self.input_method == 'local'): sm_stats = psutil.swap_memory() for swap in ['total', 'used', 'free', 'percent', 'sin', 'sout']: if hasattr(sm_stats, swap): self.stats[swap] = getattr(sm_stats, swap) elif (self.input_method == 'snmp'): if (...
'Update stats views.'
def update_views(self):
super(Plugin, self).update_views() self.views['used']['decoration'] = self.get_alert_log(self.stats['used'], maximum=self.stats['total'])
'Return the dict to display in the curse interface.'
def msg_curse(self, args=None):
ret = [] if ((not self.stats) or self.is_disable()): return ret msg = '{}'.format('SWAP') ret.append(self.curse_add_line(msg, 'TITLE')) msg = ' {:3}'.format(self.trend_msg(self.get_trend('percent'))) ret.append(self.curse_add_line(msg)) msg = '{:>6.1%}'.format((self.stats['percent...
'Init the plugin.'
def __init__(self, args=None, config=None):
super(Plugin, self).__init__(args=args) self.args = args self.config = config self.display_curse = True self.stats = (GlancesPortsList(config=config, args=args).get_ports_list() + GlancesWebList(config=config, args=args).get_web_list()) self.timer_ports = Timer(0) self._thread = None
'Overwrite the exit method to close threads'
def exit(self):
if (self._thread is not None): self._thread.stop() super(Plugin, self).exit()
'Reset/init the stats.'
def reset(self):
self.stats = []
'Update the ports list.'
@GlancesPlugin._log_result_decorator def update(self):
if (self.input_method == 'local'): if (self._thread is None): thread_is_running = False else: thread_is_running = self._thread.isAlive() if (self.timer_ports.finished() and (not thread_is_running)): self._thread = ThreadScanner(self.stats) self...
'Return the alert status relative to the port scan return value.'
def get_ports_alert(self, port, header='', log=False):
if (port['status'] is None): return 'CAREFUL' elif (port['status'] == 0): return 'CRITICAL' elif (isinstance(port['status'], (float, int)) and (port['rtt_warning'] is not None) and (port['status'] > port['rtt_warning'])): return 'WARNING' return 'OK'
'Return the alert status relative to the web/url scan return value.'
def get_web_alert(self, web, header='', log=False):
if (web['status'] is None): return 'CAREFUL' elif (web['status'] not in [200, 301, 302]): return 'CRITICAL' elif ((web['rtt_warning'] is not None) and (web['elapsed'] > web['rtt_warning'])): return 'WARNING' return 'OK'
'Return the dict to display in the curse interface.'
def msg_curse(self, args=None, max_width=None):
ret = [] if ((not self.stats) or args.disable_ports): return ret for p in self.stats: if ('host' in p): if (p['host'] is None): status = 'None' elif (p['status'] is None): status = 'Scanning' elif (isinstance(p['status'], bo...
'Init the class'
def __init__(self, stats):
logger.debug('ports plugin - Create thread for scan list {}'.format(stats)) super(ThreadScanner, self).__init__() self._stopper = threading.Event() self._stats = stats self.plugin_name = 'ports'
'Function called to grab stats. Infinite loop, should be stopped by calling the stop() method'
def run(self):
for p in self._stats: if self.stopped(): break if ('port' in p): self._port_scan(p) time.sleep(1) elif (('url' in p) and requests_tag): self._web_scan(p)
'Stats getter'
@property def stats(self):
return self._stats
'Stats setter'
@stats.setter def stats(self, value):
self._stats = value
'Stop the thread'
def stop(self, timeout=None):
logger.debug('ports plugin - Close thread for scan list {}'.format(self._stats)) self._stopper.set()
'Return True is the thread is stopped'
def stopped(self):
return self._stopper.isSet()
'Scan the Web/URL (dict) and update the status key'
def _web_scan(self, web):
try: req = requests.head(web['url'], allow_redirects=True, timeout=web['timeout']) except Exception as e: logger.debug(e) web['status'] = 'Error' web['elapsed'] = 0 else: web['status'] = req.status_code web['elapsed'] = req.elapsed.total_seconds() return w...
'Scan the port structure (dict) and update the status key'
def _port_scan(self, port):
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):
ip = hostname try: ip = socket.gethostbyname(hostname) except Exception as e: logger.debug('{}: Cannot convert {} to IP address ({})'.format(self.plugin_name, hostname, e)) return ip