text
stringlengths
81
112k
Set a value. Value is a tuple: (<timestamp>, <new_value>) def value(self, new_value): """Set a value. Value is a tuple: (<timestamp>, <new_value>) """ self._value = (datetime.now(), new_value) self.history_add(self._value)
Add a value in the history def history_add(self, value): """Add a value in the history """ if self._history_max_size is None or self.history_len() < self._history_max_size: self._history.append(value) else: self._history = self._history[1:] + [value]
Return the history in ISO JSON format def history_json(self, nb=0): """Return the history in ISO JSON format""" return [(i[0].isoformat(), i[1]) for i in self._history[-nb:]]
Return the mean on the <nb> values in the history. def history_mean(self, nb=5): """Return the mean on the <nb> values in the history. """ _, v = zip(*self._history) return sum(v[-nb:]) / float(v[-1] - v[-nb])
Load the AMP configuration files. def load_configs(self): """Load the AMP configuration files.""" if self.config is None: return False # Display a warning (deprecated) message if the monitor section exist if "monitor" in self.config.sections(): logger.warning("A...
Update the command result attributed. def update(self): """Update the command result attributed.""" # Get the current processes list (once) processlist = glances_processes.getlist() # Iter upon the AMPs dict for k, v in iteritems(self.get()): if not v.enable(): ...
Return the AMPS process list according to the amp_value Search application monitored processes by a regular expression def _build_amps_list(self, amp_value, processlist): """Return the AMPS process list according to the amp_value Search application monitored processes by a regular expression ...
Update stats in the CSV output file. def update(self, stats): """Update stats in the CSV output file.""" # Get the stats all_stats = stats.getAllExportsAsDict(plugin_list=self.plugins_to_export()) # Init data with timestamp (issue#708) if self.first_line: csv_header...
Update and/or return the CPU using the psutil library. def __get_cpu(self): """Update and/or return the CPU using the psutil library.""" # Never update more than 1 time per cached_time if self.timer_cpu.finished(): self.cpu_percent = psutil.cpu_percent(interval=0.0) # Re...
Update and/or return the per CPU list using the psutil library. def __get_percpu(self): """Update and/or return the per CPU list using the psutil library.""" # Never update more than 1 time per cached_time if self.timer_percpu.finished(): self.percpu_percent = [] for cpu...
Display modules list def display_modules_list(self): """Display modules list""" print("Plugins list: {}".format( ', '.join(sorted(self.stats.getPluginsList(enable=False))))) print("Exporters list: {}".format( ', '.join(sorted(self.stats.getExportsList(enable=False)))))
Main loop for the CLI. return True if we should continue (no exit key has been pressed) def __serve_forever(self): """Main loop for the CLI. return True if we should continue (no exit key has been pressed) """ # Start a counter used to compute the time needed for # upd...
Wrapper to the serve_forever function. def serve_forever(self): """Wrapper to the serve_forever function.""" loop = True while loop: loop = self.__serve_forever() self.end()
End of the standalone CLI. def end(self): """End of the standalone CLI.""" if not self.quiet: self.screen.end() # Exit from export modules self.stats.end() # Check Glances version versus PyPI one if self.outdated.is_outdated(): print("You are us...
Return the hashed password, salt + SHA-256. def get_hash(self, salt, plain_password): """Return the hashed password, salt + SHA-256.""" return hashlib.sha256(salt.encode() + plain_password.encode()).hexdigest()
Hash password with a salt based on UUID (universally unique identifier). def hash_password(self, plain_password): """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 +...
Encode the plain_password with the salt of the hashed_password. Return the comparison with the encrypted_password. def check_password(self, hashed_password, plain_password): """Encode the plain_password with the salt of the hashed_password. Return the comparison with the encrypted_password. ...
Get the password from a Glances client or server. For Glances server, get the password (confirm=True, clear=False): 1) from the password file (if it exists) 2) from the CLI Optionally: save the password to a file (hashed with salt + SHA-256) For Glances client, get the ...
Save the hashed password to the Glances folder. def save_password(self, hashed_password): """Save the hashed password to the Glances folder.""" # Create the glances directory safe_makedirs(self.password_dir) # Create/overwrite the password file with open(self.password_file, 'wb...
Load the hashed password from the Glances folder. def load_password(self): """Load the hashed password from the Glances folder.""" # Read the password file, if it exists with open(self.password_file, 'r') as file_pwd: hashed_password = file_pwd.read() return hashed_password
Return the sparkline. def get(self): """Return the sparkline.""" ret = sparklines(self.percents)[0] if self.__with_text: percents_without_none = [x for x in self.percents if x is not None] if len(percents_without_none) > 0: ret = '{}{:5.1f}%'.format(ret, ...
Update CPU stats using the input method. def update(self): """Update CPU stats using the input method.""" # Grab stats into self.stats if self.input_method == 'local': stats = self.update_local() elif self.input_method == 'snmp': stats = self.update_snmp() ...
Update CPU stats using psutil. def update_local(self): """Update CPU stats using psutil.""" # Grab CPU stats using psutil's cpu_percent and cpu_times_percent # Get all possible values for CPU stats: user, system, idle, # nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2....
Update CPU stats using SNMP. def update_snmp(self): """Update CPU stats using SNMP.""" # Init new stats stats = self.get_init_value() # Update stats using SNMP if self.short_system_name in ('windows', 'esxi'): # Windows or VMWare ESXi # You can find the...
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 for key in ['user', 'system', 'iowait']: if key in self.stats: se...
Return the list to display in the UI. def msg_curse(self, args=None, max_width=None): """Return the list to display in the UI.""" # Init the return message ret = [] # Only process if stats exist and plugin not disable if not self.stats or self.args.percpu or self.is_disable(): ...
Update Wifi stats using the input method. Stats is a list of dict (one dict per hotspot) :returns: list -- Stats is a list of dict (hotspot) def update(self): """Update Wifi stats using the input method. Stats is a list of dict (one dict per hotspot) :returns: list -- Stats ...
Overwrite the default get_alert method. Alert is on signal quality where lower is better... :returns: string -- Signal alert def get_alert(self, value): """Overwrite the default get_alert method. Alert is on signal quality where lower is better... :returns: string -- Signal ...
Update stats views. def update_views(self): """Update stats views.""" # Call the father's method super(Plugin, self).update_views() # Add specifics informations # Alert on signal thresholds for i in self.stats: self.views[i[self.get_key()]]['signal']['decora...
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 import_...
Update the FS stats using the input method. def update(self): """Update the FS 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 the stats using t...
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: self.views[i[self.get_key()]]['used']['decoration'] = self.get_alert...
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...
Update RAM memory stats using the input method. def update(self): """Update RAM 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 MEM using ...
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...
Add an new item (key, value) to the current history. def add(self, key, value, description='', history_max_size=None): """Add an new item (key, value) to the current history.""" if key not in self.stats_history: self.stats_history[key] = GlancesAttribute(key, ...
Get the history as a dict of list def get(self, nb=0): """Get the history as a dict of list""" return {i: self.stats_history[i].history_raw(nb=nb) for i in self.stats_history}
Get the history as a dict of list (with list JSON compliant) def get_json(self, nb=0): """Get the history as a dict of list (with list JSON compliant)""" return {i: self.stats_history[i].history_json(nb=nb) for i in self.stats_history}
Load AMP parameters from the configuration file. def load_config(self, config): """Load AMP parameters from the configuration file.""" # Read AMP confifuration. # For ex, the AMP foo should have the following section: # # [foo] # enable=true # regex=\/usr\/bin\/...
Return True|False if the AMP is enabled in the configuration file (enable=true|false). def enable(self): """Return True|False if the AMP is enabled in the configuration file (enable=true|false).""" ret = self.get('enable') if ret is None: return False else: retur...
Return True|False if the AMP shoukd be displayed in oneline (one_lineline=true|false). def one_line(self): """Return True|False if the AMP shoukd be displayed in oneline (one_lineline=true|false).""" ret = self.get('one_line') if ret is None: return False else: r...
Return True is the AMP should be updated: - AMP is enable - only update every 'refresh' seconds def should_update(self): """Return True is the AMP should be updated: - AMP is enable - only update every 'refresh' seconds """ if self.timer.finished(): s...
Store the result (string) into the result key of the AMP if one_line is true then replace \n by separator def set_result(self, result, separator=''): """Store the result (string) into the result key of the AMP if one_line is true then replace \n by separator """ if self.one_line...
Return the result of the AMP (as a string) def result(self): """ Return the result of the AMP (as a string)""" ret = self.get('result') if ret is not None: ret = u(ret) return ret
Wrapper for the children update def update_wrapper(self, process_list): """Wrapper for the children update""" # Set the number of running process self.set_count(len(process_list)) # Call the children update method if self.should_update(): return self.update(process_l...
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 # Here, update is c...
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 args.disable_process: ...
Parse the decision tree and return the message. Note: message corresponding to the current threasholds values def global_message(): """Parse the decision tree and return the message. Note: message corresponding to the current threasholds values """ # Compute the weight for each item in the tree ...
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 display plugin enable... if not self.stats or self.is_disable(): ...
Compare a with b using the tolerance (if numerical). def approx_equal(self, a, b, tolerance=0.0): """Compare a with b using the tolerance (if numerical).""" if str(int(a)).isdigit() and str(int(b)).isdigit(): return abs(a - b) <= max(abs(a), abs(b)) * tolerance else: ret...
Export the stats to the JSON file. def export(self, name, columns, points): """Export the stats to the JSON file.""" # Check for completion of loop for all exports if name == self.plugins_to_export()[0] and self.buffer != {}: # One whole loop has been completed # Flush ...
Overwrite the exit method to close threads. def exit(self): """Overwrite the exit method to close threads.""" for t in itervalues(self.thread_list): t.stop() # Call the father class super(Plugin, self).exit()
Overwrite the default export method. - Only exports containers - The key is the first container name def get_export(self): """Overwrite the default export method. - Only exports containers - The key is the first container name """ ret = [] try: ...
Connect to the Docker server. def connect(self): """Connect to the Docker server.""" try: ret = docker.from_env() except Exception as e: logger.error("docker plugin - Can not connect to Docker ({})".format(e)) ret = None return ret
Return the all tag of the Glances/Docker configuration file. # By default, Glances only display running containers # Set the following key to True to display all containers all=True def _all_tag(self): """Return the all tag of the Glances/Docker configuration file. # By defaul...
Update Docker stats using the input method. def update(self): """Update Docker stats using the input method.""" # Init new stats stats = self.get_init_value() # The Docker-py lib is mandatory if import_error_tag: return self.stats if self.input_method == 'l...
Return the container CPU usage. Input: id is the full container id all_stats is the output of the stats method of the Docker API Output: a dict {'total': 1.49} def get_docker_cpu(self, container_id, all_stats): """Return the container CPU usage. Input: id is the full co...
Return the container MEMORY. Input: id is the full container id all_stats is the output of the stats method of the Docker API Output: a dict {'rss': 1015808, 'cache': 356352, 'usage': ..., 'max_usage': ...} def get_docker_memory(self, container_id, all_stats): """Return the con...
Return the container network usage using the Docker API (v1.0 or higher). Input: id is the full container id Output: a dict {'time_since_update': 3000, 'rx': 10, 'tx': 65}. with: time_since_update: number of seconds elapsed between the latest grab rx: Number of byte rece...
Return the container IO usage using the Docker API (v1.0 or higher). Input: id is the full container id Output: a dict {'time_since_update': 3000, 'ior': 10, 'iow': 65}. with: time_since_update: number of seconds elapsed between the latest grab ior: Number of byte readed...
Update stats views. def update_views(self): """Update stats views.""" # Call the father's method super(Plugin, self).update_views() if 'containers' not in self.stats: return False # Add specifics informations # Alert for i in self.stats['containers'...
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 non null) and display plugin enable... if not self.s...
Build the container name. def _msg_name(self, container, max_width): """Build the container name.""" name = container['name'] if len(name) > max_width: name = '_' + name[-max_width + 1:] else: name = name[:max_width] return ' {:{width}}'.format(name, widt...
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 i in self._stats_stream: self._stats = i time.sleep(0.1) if...
Stop the thread. def stop(self, timeout=None): """Stop the thread.""" logger.debug("docker plugin - Close thread for container {}".format(self._container.name)) self._stopper.set()
Return true if plugin is enabled. def is_enable(self, plugin_name=None): """Return true if plugin is enabled.""" if not plugin_name: plugin_name = self.plugin_name try: d = getattr(self.args, 'disable_' + plugin_name) except AttributeError: return Tru...
Return the object 'd' in a JSON format. Manage the issue #815 for Windows OS def _json_dumps(self, d): """Return the object 'd' in a JSON format. Manage the issue #815 for Windows OS """ try: return json.dumps(d) except UnicodeDecodeError: retur...
Init the stats history (dict of GlancesAttribute). def init_stats_history(self): """Init the stats history (dict of GlancesAttribute).""" if self.history_enable(): init_list = [a['name'] for a in self.get_items_history_list()] logger.debug("Stats history activated for plugin {} ...
Reset the stats history (dict of GlancesAttribute). def reset_stats_history(self): """Reset the stats history (dict of GlancesAttribute).""" if self.history_enable(): reset_list = [a['name'] for a in self.get_items_history_list()] logger.debug("Reset history for plugin {} (items...
Update stats history. def update_stats_history(self): """Update stats history.""" # If the plugin data is a dict, the dict's key should be used if self.get_key() is None: item_name = '' else: item_name = self.get_key() # Build the history if self....
Return the history (RAW format). - 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 def get_raw_history(self, item=None, nb=0): """Return the history (RAW format). - the stats his...
Return the history (JSON format). - 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): """Return th...
Return the stats history (JSON format). def get_stats_history(self, item=None, nb=0): """Return the stats history (JSON format).""" s = self.get_json_history(nb=nb) if item is None: return self._json_dumps(s) if isinstance(s, dict): try: return ...
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): """Get the trend regarding to the last nb values. The trend is the diff between the mean of the last nb values and ...
Get the stats sorted by an alias (if present) or key. def sorted_stats(self): """Get the stats sorted by an alias (if present) or key.""" key = self.get_key() return sorted(self.stats, key=lambda stat: tuple(map( lambda part: int(part) if part.isdigit() else part.lower(), ...
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): """Update stats using SNMP. If bulk=True, use a bulk request instead of a get request. """ snmp_oid = snmp_oid or {} from glances.s...
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): """Return the stats object for a specific item in JSON format. Stats should be a list of dict (processlist, network...) """ if i...
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): """Return the stats object for a specific item=value in JSON format. Stats should be a list of dict (processlist, network...) ...
Update 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...
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 ...
Return the views (in JSON). def get_json_views(self, item=None, key=None, option=None): """Return the views (in JSON).""" return self._json_dumps(self.get_views(item, key, option))
Load limits from the configuration file, if it exists. def load_limits(self, config): """Load limits from the configuration file, if it exists.""" # By default set the history length to 3 points per second during one day self._limits['history_size'] = 28800 if not hasattr(config, 'has_...
Return the stat name with an optional header def get_stat_name(self, header=""): """"Return the stat name with an optional header""" ret = self.plugin_name if header != "": ret += '_' + header return ret
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 = CRITIC...
Manage the action for the current stat. def manage_action(self, stat_name, trigger, header, action_key): """Manage the action for the current stat.""" # Here is a command line for the current trigger ? try: ...
Get the alert log. def get_alert_log(self, current=0, minimum=0, maximum=100, header="", action_key=None): """Get the alert log.""" return self.get_alert(current=current, ...
Return the limit value for the alert. def get_limit(self, criticity, stat_name=""): """Return the limit value for the alert.""" # Get the limit for stat + header # Exemple: network_wlan0_rx_careful try: limit = self._limits[stat_name + '_' + criticity] except KeyErro...
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=""): """Return the tuple (action, repeat) for the alert. - action is a command line - repeat is a bool """ # Get the a...
Return the log tag for the alert. def get_limit_log(self, stat_name, default_action=False): """Return the log tag for the alert.""" # Get the log tag for stat + header # Exemple: network_wlan0_rx_log try: log_tag = self._limits[stat_name + '_log'] except KeyError: ...
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): """Return the configuration (header_) value for the current plugin. ...or the one given by the plugin_name var. ""...
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 True if the value is in th...
Return the alias name for the relative header or None if nonexist. def has_alias(self, header): """Return the alias name for the relative header or None if nonexist.""" try: # Force to lower case (issue #1126) return self._limits[self.plugin_name + '_' + header.lower() + '_' + '...
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...
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 ...
Make a nice human-readable string out of number. Number of decimal places increases as quantity approaches 1. CASE: 613421788 RESULT: 585M low_precision: 585M CASE: 5307033647 RESULT: 4.94G low_precision: 4.9G CASE: 44968414685 RESULT: 41.9G...
Return the trend message. Do not take into account if trend < significant def trend_msg(self, trend, significant=1): """Return the trend message. Do not take into account if trend < significant """ ret = '-' if trend is None: ret = ' ' elif trend > ...
Check if the plugin is enabled. def _check_decorator(fct): """Check if the plugin is enabled.""" 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): """Log (DEBUG) the result of the function fct.""" def wrapper(*args, **kw): ret = fct(*args, **kw) logger.debug("%s %s %s return %s" % ( args[0].__class__.__name__, args[0...
Update HDD stats using the input method. def update(self): """Update HDD 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 stats = self.glancesgrabhddtemp...