text
stringlengths
81
112k
Return the sum of the stats value for the given key. * indice: If indice is set, get the p[key][indice] * mmm: display min, max, mean or current (if mmm=None) def __sum_stats(self, key, indice=None, mmm=None): """Return the sum of the stats value for the given key. * indice: If indice...
Return the stats (dict) sorted by (sortedby). def __sort_stats(self, sortedby=None): """Return the stats (dict) sorted by (sortedby).""" return sort_stats(self.stats, sortedby, reverse=glances_processes.sort_reverse)
Build and return the header line def build_header(self, plugin, attribute, stat): """Build and return the header line""" line = '' if attribute is not None: line += '{}.{}{}'.format(plugin, attribute, self.separator) else: if isinstance(stat, dict): ...
Build and return the data line def build_data(self, plugin, attribute, stat): """Build and return the data line""" line = '' if attribute is not None: line += '{}{}'.format(str(stat.get(attribute, self.na)), self.separator) else: ...
Display stats to stdout. Refresh every duration second. def update(self, stats, duration=3): """Display stats to stdout. Refresh every duration second. """ # Build the stats list line = '' for plugin, attribute in self.plugins_list: ...
Init the connection to the Riemann server. def init(self): """Init the connection to the Riemann server.""" if not self.export_enable: return None try: client = bernhard.Client(host=self.host, port=self.port) return client except Exception as e: ...
Write the points in Riemann. def export(self, name, columns, points): """Write the points in Riemann.""" for i in range(len(columns)): if not isinstance(points[i], Number): continue else: data = {'host': self.hostname, 'service': name + " " + colu...
Return the elapsed time since last update. def getTimeSinceLastUpdate(IOType): """Return the elapsed time since last update.""" global last_update_times # assert(IOType in ['net', 'disk', 'process_disk']) current_time = time() last_time = last_update_times.get(IOType) if not last_time: ...
Compute a simple mean subsampling. Data should be a list of numerical itervalues Return a subsampled list of sampling lenght def subsample(data, sampling): """Compute a simple mean subsampling. Data should be a list of numerical itervalues Return a subsampled list of sampling lenght """ ...
Compute a simple mean subsampling. Data should be a list of set (time, value) Return a subsampled list of sampling lenght def time_serie_subsample(data, sampling): """Compute a simple mean subsampling. Data should be a list of set (time, value) Return a subsampled list of sampling lenght ""...
Init the connection to the CouchDB server. def init(self): """Init the connection to the CouchDB server.""" if not self.export_enable: return None if self.user is None: server_uri = 'http://{}:{}/'.format(self.host, self.p...
Write the points to the CouchDB server. def export(self, name, columns, points): """Write the points to the CouchDB server.""" logger.debug("Export {} stats to CouchDB".format(name)) # Create DB input data = dict(zip(columns, points)) # Set the type to the current stat name ...
Update core stats. Stats is a dict (with both physical and log cpu number) instead of a integer. def update(self): """Update core stats. Stats is a dict (with both physical and log cpu number) instead of a integer. """ # Init new stats stats = self.get_init_value() ...
Return True if the theme *name* should be used. def is_theme(self, name): """Return True if the theme *name* should be used.""" return getattr(self.args, 'theme_' + name) or self.theme['name'] == name
Init cursors. def _init_cursor(self): """Init cursors.""" if hasattr(curses, 'noecho'): curses.noecho() if hasattr(curses, 'cbreak'): curses.cbreak() self.set_cursor(0)
Init the Curses color layout. def _init_colors(self): """Init the Curses color layout.""" # Set curses options try: if hasattr(curses, 'start_color'): curses.start_color() if hasattr(curses, 'use_default_colors'): curses.use_default_color...
Return the current sort in the loop def loop_position(self): """Return the current sort in the loop""" for i, v in enumerate(self._sort_loop): if v == glances_processes.sort_key: return i return 0
Disable the full quicklook mode def enable_fullquicklook(self): """Disable the full quicklook mode""" self.args.disable_quicklook = False for p in ['cpu', 'gpu', 'mem', 'memswap']: setattr(self.args, 'disable_' + p, True)
Shutdown the curses window. def end(self): """Shutdown the curses window.""" if hasattr(curses, 'echo'): curses.echo() if hasattr(curses, 'nocbreak'): curses.nocbreak() if hasattr(curses, 'curs_set'): try: curses.curs_set(1) ...
Return a dict of dict with all the stats display. stats: Global stats dict layer: ~ cs_status "None": standalone or server mode "Connected": Client is connected to a Glances server "SNMP": Client is connected to a SNMP server "Disconnected": Client is disc...
Display stats on the screen. stats: Stats database to display cs_status: "None": standalone or server mode "Connected": Client is connected to a Glances server "SNMP": Client is connected to a SNMP server "Disconnected": Client is disconnected from the se...
Display the firsts lines (header) in the Curses interface. system + ip + uptime (cloud) def __display_header(self, stat_display): """Display the firsts lines (header) in the Curses interface. system + ip + uptime (cloud) """ # First line self.new_line()...
Display the second line in the Curses interface. <QUICKLOOK> + CPU|PERCPU + <GPU> + MEM + SWAP + LOAD def __display_top(self, stat_display, stats): """Display the second line in the Curses interface. <QUICKLOOK> + CPU|PERCPU + <GPU> + MEM + SWAP + LOAD """ self.init_column() ...
Display the left sidebar in the Curses interface. def __display_left(self, stat_display): """Display the left sidebar in the Curses interface.""" self.init_column() if self.args.disable_left_sidebar: return for s in self._left_sidebar: if ((hasattr(self.args, '...
Display the right sidebar in the Curses interface. docker + processcount + amps + processlist + alert def __display_right(self, stat_display): """Display the right sidebar in the Curses interface. docker + processcount + amps + processlist + alert """ # Do not display anything...
Display a centered popup. If is_input is False: Display a centered popup with the given message during duration seconds If size_x and size_y: set the popup size else set it automatically Return True if the popup could be displayed If is_input is True: Displ...
Display the plugin_stats on the screen. If display_optional=True display the optional stats If display_additional=True display additionnal stats max_y: do not display line > max_y add_space: add x space (line) after the plugin def display_plugin(self, plugin_stats, ...
Clear and update the screen. stats: Stats database to display cs_status: "None": standalone or server mode "Connected": Client is connected to the server "Disconnected": Client is disconnected from the server def flush(self, stats, cs_status=None): """Clear ...
Update the screen. INPUT stats: Stats database to display duration: duration of the loop cs_status: "None": standalone or server mode "Connected": Client is connected to the server "Disconnected": Client is disconnected from the server return_...
Return the width of the formatted curses message. def get_stats_display_width(self, curse_msg, without_option=False): """Return the width of the formatted curses message.""" try: if without_option: # Size without options c = len(max(''.join([(u(u(nativestr(i[...
r"""Return the height of the formatted curses message. The height is defined by the number of '\n' (new line). def get_stats_display_height(self, curse_msg): r"""Return the height of the formatted curses message. The height is defined by the number of '\n' (new line). """ try:...
Build the results. def __buid_result(self, varBinds): """Build the results.""" ret = {} for name, val in varBinds: if str(val) == '': ret[name.prettyPrint()] = '' else: ret[name.prettyPrint()] = val.prettyPrint() # In Pytho...
SNMP simple request (list of OID). One request per OID list. * oid: oid list > Return a dict def get_by_oid(self, *oid): """SNMP simple request (list of OID). One request per OID list. * oid: oid list > Return a dict """ if self.version == '3'...
SNMP getbulk request. In contrast to snmpwalk, this information will typically be gathered in a single transaction with the agent, rather than one transaction per variable found. * non_repeaters: This specifies the number of supplied variables that should not be iterated over...
Load the server list from the configuration file. def load(self, config): """Load the server list from the configuration file.""" server_list = [] if config is None: logger.debug("No configuration file available. Cannot load server list.") elif not config.has_section(self._...
Set the key to the value for the server_pos (position in the list). def set_server(self, server_pos, key, value): """Set the key to the value for the server_pos (position in the list).""" self._server_list[server_pos][key] = value
Add a new server to the list. def add_server(self, name, ip, port): """Add a new server to the list.""" new_server = { 'key': name, # Zeroconf name with both hostname and port 'name': name.split(':')[0], # Short name 'ip': ip, # IP address seen by the client ...
Remove a server from the dict. def remove_server(self, name): """Remove a server from the dict.""" for i in self._server_list: if i['key'] == name: try: self._server_list.remove(i) logger.debug("Remove server %s from the list" % name) ...
Set the key to the value for the server_pos (position in the list). def set_server(self, server_pos, key, value): """Set the key to the value for the server_pos (position in the list).""" self.servers.set_server(server_pos, key, value)
Method called when a new Zeroconf client is detected. Return True if the zeroconf client is a Glances server Note: the return code will never be used def add_service(self, zeroconf, srv_type, srv_name): """Method called when a new Zeroconf client is detected. Return True if the zeroco...
Remove the server from the list. def remove_service(self, zeroconf, srv_type, srv_name): """Remove the server from the list.""" self.servers.remove_server(srv_name) logger.info( "Glances server %s removed from the autodetect list" % srv_name)
Set the key to the value for the server_pos (position in the list). def set_server(self, server_pos, key, value): """Set the key to the value for the server_pos (position in the list).""" if zeroconf_tag and self.zeroconf_enable_tag: self.listener.set_server(server_pos, key, value)
Try to find the active IP addresses. def find_active_ip_address(): """Try to find the active IP addresses.""" import netifaces # Interface of the default gateway gateway_itf = netifaces.gateways()['default'][netifaces.AF_INET][1] # IP address for the interface return net...
Compress result with deflate algorithm if the client ask for it. def compress(func): """Compress result with deflate algorithm if the client ask for it.""" def wrapper(*args, **kwargs): """Wrapper that take one function and return the compressed result.""" ret = func(*args, **kwargs) lo...
Load the outputs section of the configuration file. def load_config(self, config): """Load the outputs section of the configuration file.""" # Limit the number of processes to display in the WebUI if config is not None and config.has_section('outputs'): logger.debug('Read number of ...
Check if a username/password combination is valid. def check_auth(self, username, password): """Check if a username/password combination is valid.""" if username == self.args.username: from glances.password import GlancesPassword pwd = GlancesPassword() return pwd.ch...
Define route. def _route(self): """Define route.""" # REST API self._app.route('/api/%s/config' % self.API_VERSION, method="GET", callback=self._api_config) self._app.route('/api/%s/config/<item>' % self.API_VERSION, method="GET", callback...
Start the bottle. def start(self, stats): """Start the bottle.""" # Init stats self.stats = stats # Init plugin list self.plugins_list = self.stats.getPluginsList() # Bind the Bottle TCP address/port if self.args.open_web_browser: # Implementation o...
Bottle callback for index.html (/) file. def _index(self, refresh_time=None): """Bottle callback for index.html (/) file.""" if refresh_time is None or refresh_time < 1: refresh_time = self.args.time # Update the stat self.__update__() # Display return tem...
Glances API RESTful implementation. Return the help data or 404 error. def _api_help(self): """Glances API RESTful implementation. Return the help data or 404 error. """ response.content_type = 'application/json; charset=utf-8' # Update the stat view_data = se...
Glances API RESTFul implementation. @api {get} /api/%s/pluginslist Get plugins list @apiVersion 2.0 @apiName pluginslist @apiGroup plugin @apiSuccess {String[]} Plugins list. @apiSuccessExample Success-Response: HTTP/1.1 200 OK [ ...
Glances API RESTful implementation. Return the JSON representation of all the plugins HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error def _api_all(self): """Glances API RESTful implementation. Return the JSON representation of all the plugins ...
Glances API RESTful implementation. Return the JSON representation of all the plugins limits HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error def _api_all_limits(self): """Glances API RESTful implementation. Return the JSON representation of all ...
Glances API RESTful implementation. Return the JSON representation of all the plugins views HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error def _api_all_views(self): """Glances API RESTful implementation. Return the JSON representation of all th...
Glances API RESTful implementation. Return the JSON representation of a given plugin HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error def _api(self, plugin): """Glances API RESTful implementation. Return the JSON representation of a given plugin ...
Glances API RESTful implementation. Return the JSON representation of a given plugin history Limit to the last nb items (all if nb=0) HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error def _api_history(self, plugin, nb=0): """Glances API RESTful imp...
Glances API RESTful implementation. Return the JSON limits of a given plugin HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error def _api_limits(self, plugin): """Glances API RESTful implementation. Return the JSON limits of a given plugin H...
Glances API RESTful implementation. Return the JSON views of a given plugin HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error def _api_views(self, plugin): """Glances API RESTful implementation. Return the JSON views of a given plugin HTTP...
Father method for _api_item and _api_value. def _api_itemvalue(self, plugin, item, value=None, history=False, nb=0): """Father method for _api_item and _api_value.""" response.content_type = 'application/json; charset=utf-8' if plugin not in self.plugins_list: abort(400, "Unknown p...
Glances API RESTful implementation. Return the JSON representation of the couple plugin/history of item HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error def _api_item_history(self, plugin, item, nb=0): """Glances API RESTful implementation. Retur...
Glances API RESTful implementation. Return the process stats (dict) for the given item=value HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error def _api_value(self, plugin, item, value): """Glances API RESTful implementation. Return the process sta...
Glances API RESTful implementation. Return the JSON representation of the Glances configuration file HTTP/200 if OK HTTP/404 if others error def _api_config(self): """Glances API RESTful implementation. Return the JSON representation of the Glances configuration file H...
Glances API RESTful implementation. Return the JSON representation of the Glances configuration item HTTP/200 if OK HTTP/400 if item is not found HTTP/404 if others error def _api_config_item(self, item): """Glances API RESTful implementation. Return the JSON represent...
Glances API RESTful implementation. Return the JSON representation of the Glances command line arguments HTTP/200 if OK HTTP/404 if others error def _api_args(self): """Glances API RESTful implementation. Return the JSON representation of the Glances command line arguments ...
Glances API RESTful implementation. Return the JSON representation of the Glances command line arguments item HTTP/200 if OK HTTP/400 if item is not found HTTP/404 if others error def _api_args_item(self, item): """Glances API RESTful implementation. Return the JSON re...
Update disk I/O stats using the input method. def update(self): """Update disk I/O 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 stat using...
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...
Start Glances. def start(config, args): """Start Glances.""" # Load mode global mode if core.is_standalone(): from glances.standalone import GlancesStandalone as GlancesMode elif core.is_client(): if core.is_client_browser(): from glances.client_browser import GlancesC...
Main entry point for Glances. Select the mode (standalone, client or server) Run it... def main(): """Main entry point for Glances. Select the mode (standalone, client or server) Run it... """ # Catch the CTRL-C signal signal.signal(signal.SIGINT, __signal_handler) # Log Glances ...
r"""Return the per-user config dir (full path). - Linux, *BSD, SunOS: ~/.config/glances - macOS: ~/Library/Application Support/glances - Windows: %APPDATA%\glances def user_config_dir(): r"""Return the per-user config dir (full path). - Linux, *BSD, SunOS: ~/.config/glances - macOS: ~/Library...
r"""Return the per-user cache dir (full path). - Linux, *BSD, SunOS: ~/.cache/glances - macOS: ~/Library/Caches/glances - Windows: {%LOCALAPPDATA%,%APPDATA%}\glances\cache def user_cache_dir(): r"""Return the per-user cache dir (full path). - Linux, *BSD, SunOS: ~/.cache/glances - macOS: ~/Li...
r"""Return the system-wide config dir (full path). - Linux, SunOS: /etc/glances - *BSD, macOS: /usr/local/etc/glances - Windows: %APPDATA%\glances def system_config_dir(): r"""Return the system-wide config dir (full path). - Linux, SunOS: /etc/glances - *BSD, macOS: /usr/local/etc/glances ...
r"""Get a list of config file paths. The list is built taking into account of the OS, priority and location. * custom path: /path/to/glances * Linux, SunOS: ~/.config/glances, /etc/glances * *BSD: ~/.config/glances, /usr/local/etc/glances * macOS: ~/Library/Application Support/...
Read the config file, if it exists. Using defaults otherwise. def read(self): """Read the config file, if it exists. Using defaults otherwise.""" for config_file in self.config_file_paths(): logger.info('Search glances.conf file in {}'.format(config_file)) if os.path.exists(conf...
Return the configuration as a dict def as_dict(self): """Return the configuration as a dict""" dictionary = {} for section in self.parser.sections(): dictionary[section] = {} for option in self.parser.options(section): dictionary[section][option] = self.p...
Set default values for careful, warning and critical. def set_default_cwc(self, section, option_header=None, cwc=['50', '70', '90']): """Set default values for careful, warning and critical.""" if option_header is None: header = '' els...
If the option did not exist, create a default value. def set_default(self, section, option, default): """If the option did not exist, create a default value.""" if not self.parser.has_option(section, option): self.parser.set(section, option, default)
Get the value of an option, if it exists. If it did not exist, then return the default value. It allows user to define dynamic configuration key (see issue#1204) Dynamic vlaue should starts and end with the ` char Example: prefix=`hostname` def get_value(self, section, option, ...
Get the int value of an option, if it exists. def get_int_value(self, section, option, default=0): """Get the int value of an option, if it exists.""" try: return self.parser.getint(section, option) except NoOptionError: return int(default)
Get the float value of an option, if it exists. def get_float_value(self, section, option, default=0.0): """Get the float value of an option, if it exists.""" try: return self.parser.getfloat(section, option) except NoOptionError: return float(default)
Get the bool value of an option, if it exists. def get_bool_value(self, section, option, default=True): """Get the bool value of an option, if it exists.""" try: return self.parser.getboolean(section, option) except NoOptionError: return bool(default)
Return the event position, if it exists. An event exist if: * end is < 0 * event_type is matching Return -1 if the item is not found. def __event_exist(self, event_type): """Return the event position, if it exists. An event exist if: * end is < 0 * even...
Return the process sort key def get_event_sort_key(self, event_type): """Return the process sort key""" # Process sort depending on alert type if event_type.startswith("MEM"): # Sort TOP process by memory_percent ret = 'memory_percent' elif event_type.startswith(...
Define the process auto sort key from the alert type. def set_process_sort(self, event_type): """Define the process auto sort key from the alert type.""" if glances_processes.auto_sort: glances_processes.sort_key = self.get_event_sort_key(event_type)
Add a new item to the logs list. If 'event' is a 'new one', add it at the beginning of the list. If 'event' is not a 'new one', update the list . If event < peak_time then the alert is not set. def add(self, event_state, event_type, event_value, proc_list=None, proc_desc="", peak_t...
Add a new item in the log list. Item is added only if the criticity (event_state) is WARNING or CRITICAL. def _create_event(self, event_state, event_type, event_value, proc_list, proc_desc, peak_time): """Add a new item in the log list. Item is added only if the criticit...
Update an event in the list def _update_event(self, event_index, event_state, event_type, event_value, proc_list, proc_desc, peak_time): """Update an event in the list""" if event_state == "OK" or event_state == "CAREFUL": # Reset the automatic process sort key ...
Clean the logs list by deleting finished items. By default, only delete WARNING message. If critical = True, also delete CRITICAL message. def clean(self, critical=False): """Clean the logs list by deleting finished items. By default, only delete WARNING message. If critical =...
Chek if SNMP is available on the server. def check_snmp(self): """Chek if SNMP is available on the server.""" # Import the SNMP client class from glances.snmp import GlancesSNMPClient # Create an instance of the SNMP client clientsnmp = GlancesSNMPClient(host=self.args.client, ...
Get the short os name from the OS name OID string. def get_system_name(self, oid_system_name): """Get the short os name from the OS name OID string.""" short_system_name = None if oid_system_name == '': return short_system_name # Find the short name in the oid_to_short_os_...
Update the stats using SNMP. def update(self): """Update the stats using SNMP.""" # For each plugins, call the update method for p in self._plugins: if self._plugins[p].is_disable(): # If current plugin is disable # then continue to next plugin ...
Update RAID stats using the input method. def update(self): """Update RAID 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': # Update stats using the P...
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: return ret # M...
RAID alert messages. [available/used] means that ideally the array may have _available_ devices however, _used_ devices are in use. Obviously when used >= available then things are good. def raid_alert(self, status, used, available, type): """RAID alert messages. [available/us...
Update uptime stat using the input method. def update(self): """Update uptime stat using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib self.uptime = datetime.now(...
Update the cloud stats. Return the stats (dict) def update(self): """Update the cloud stats. Return the stats (dict) """ # Init new stats stats = self.get_init_value() # Requests lib is needed to get stats from the Cloud API if import_error_tag: ...
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 = [] if not self.stats or self.stats == {} or self.is_disable(): return ret ...
Grab plugin's stats. Infinite loop, should be stopped by calling the stop() method def run(self): """Grab plugin's stats. Infinite loop, should be stopped by calling the stop() method """ if import_error_tag: self.stop() return False for k, v i...
Generate the views. def generate_view_data(self): """Generate the views.""" self.view_data['version'] = '{} {}'.format('Glances', __version__) self.view_data['psutil_version'] = ' with psutil {}'.format(psutil_version) try: self.view_data['configuration_file'] = 'Configurat...
Return the list to display in the curse interface. def msg_curse(self, args=None, max_width=None): """Return the list to display in the curse interface.""" # Init the return message ret = [] # Build the string message # Header ret.append(self.curse_add_line(self.view_da...