desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Init the ZeroMQ export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.prefix = None self.export_enable = self.load_conf('zeromq', mandatories=['host', 'port', 'prefix'], options=[]) if (not self.export_enable): sys.exit(2) self.context = None self.client = self.init()
'Init the connection to the CouchDB server.'
def init(self):
if (not self.export_enable): return None server_uri = 'tcp://{}:{}'.format(self.host, self.port) try: self.context = zmq.Context() publisher = self.context.socket(zmq.PUB) publisher.bind(server_uri) except Exception as e: logger.critical(('Cannot connect to ...
'Close the socket and context'
def exit(self):
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):
logger.debug('Export {} stats to ZeroMQ'.format(name)) data = dict(zip(columns, points)) if (data == {}): return False message = [b(self.prefix), b(name), asbytes(json.dumps(data))] try: self.client.send_multipart(message) except Exception as e: logger.error('...
'Init the ES export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.index = None self.export_enable = self.load_conf('elasticsearch', mandatories=['host', 'port', 'index'], options=[]) if (not self.export_enable): sys.exit(2) self.client = self.init()
'Init the connection to the ES server.'
def init(self):
if (not self.export_enable): return None try: es = Elasticsearch(hosts=['{}:{}'.format(self.host, self.port)]) except Exception as e: logger.critical(('Cannot connect to ElasticSearch server %s:%s (%s)' % (self.host, self.port, e))) sys.exit(2) else: ...
'Write the points to the ES server.'
def export(self, name, columns, points):
logger.debug('Export {} stats to ElasticSearch'.format(name)) actions = [] for (c, p) in zip(columns, points): action = {'_index': self.index, '_type': name, '_id': c, '_source': {'value': str(p), 'timestamp': datetime.now()}} actions.append(action) try: helpers.bulk(...
'Init the CouchDB export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.db = None self.user = None self.password = None self.export_enable = self.load_conf('couchdb', mandatories=['host', 'port', 'db'], options=['user', 'password']) if (not self.export_enable): sys.exit(2) self.client = self.ini...
'Init the connection to the CouchDB server.'
def init(self):
if (not self.export_enable): return None if (self.user is None): server_uri = 'http://{}:{}/'.format(self.host, self.port) else: server_uri = 'http://{}:{}@{}:{}/'.format(self.user, self.password, self.host, self.port) try: s = couchdb.Server(server_uri) except Except...
'Return the CouchDB database object'
def database(self):
return self.client[self.db]
'Write the points to the CouchDB server.'
def export(self, name, columns, points):
logger.debug('Export {} stats to CouchDB'.format(name)) data = dict(zip(columns, points)) data['type'] = name data['time'] = couchdb.mapping.DateTimeField()._to_json(datetime.now()) try: self.client[self.db].save(data) except Exception as e: logger.error('Cannot ex...
'Return the output folder where the graph are generated.'
def get_output_folder(self):
return self.output_folder
'Return True if Glances can generate history graphs.'
def graph_enabled(self):
return matplotlib_check
'Reset all the history.'
def reset(self, stats):
if (not self.graph_enabled()): return False for p in stats.getAllPlugins(): h = stats.get_plugin(p).get_stats_history() if (h is not None): stats.get_plugin(p).reset_stats_history() return True
'Get the item\'s color.'
def get_graph_color(self, item):
try: ret = item['color'] except KeyError: return '#FFFFFF' else: return ret
'Get the item\'s legend.'
def get_graph_legend(self, item):
return item['description']
'Get the item\'s Y unit.'
def get_graph_yunit(self, item, pre_label=''):
try: unit = (' (%s)' % item['y_unit']) except KeyError: unit = '' if (pre_label == ''): label = '' else: label = pre_label.split('_')[0] return ('%s%s' % (label, unit))
'Generate graphs from plugins history. Return the number of output files generated by the function.'
def generate_graph(self, stats):
if (not self.graph_enabled()): return 0 index_all = 0 for p in stats.getAllPlugins(): h = stats.get_plugin(p).get_export_history() ih = stats.get_plugin(p).get_items_history_list() if ((h is None) or (ih is None)): continue plt.clf() index_graph = ...
'Init the Statsd export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.prefix = None self.export_enable = self.load_conf('statsd', mandatories=['host', 'port'], options=['prefix']) if (not self.export_enable): sys.exit(2) if (self.prefix is None): self.prefix = 'glances' self.client = self....
'Init the connection to the Statsd server.'
def init(self):
if (not self.export_enable): return None logger.info('Stats will be exported to StatsD server: {}:{}'.format(self.host, self.port)) return StatsClient(self.host, int(self.port), prefix=self.prefix)
'Export the stats to the Statsd server.'
def export(self, name, columns, points):
for i in range(len(columns)): if (not isinstance(points[i], Number)): continue stat_name = '{}.{}'.format(name, columns[i]) stat_value = points[i] try: self.client.gauge(normalize(stat_name), stat_value) except Exception as e: logger.error(...
'Init the CSV export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.csv_filename = args.export_csv try: if PY3: self.csv_file = open(self.csv_filename, 'w', newline='') else: self.csv_file = open(self.csv_filename, 'wb') self.writer = csv.writer(self.csv_file) exc...
'Close the CSV file.'
def exit(self):
logger.debug(('Finalise export interface %s' % self.export_name)) self.csv_file.close()
'Update stats in the CSV output file.'
def update(self, stats):
all_stats = stats.getAllExports() plugins = stats.getAllPlugins() if self.first_line: csv_header = ['timestamp'] csv_data = [time.strftime('%Y-%m-%d %H:%M:%S')] for (i, plugin) in enumerate(plugins): if (plugin in self.plugins_to_export()): if isinstance(all_stats[i], ...
'Init the Riemann export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.export_enable = self.load_conf('riemann', mandatories=['host', 'port'], options=[]) if (not self.export_enable): sys.exit(2) self.hostname = socket.gethostname() self.client = self.init()
'Init the connection to the Riemann server.'
def init(self):
if (not self.export_enable): return None try: client = bernhard.Client(host=self.host, port=self.port) return client except Exception as e: logger.critical(('Connection to Riemann failed : %s ' % e)) return None
'Write the points in Riemann.'
def export(self, name, columns, points):
for i in range(len(columns)): if (not isinstance(points[i], Number)): continue else: data = {'host': self.hostname, 'service': ((name + ' ') + columns[i]), 'metric': points[i]} logger.debug(data) try: self.client.send(data) ...
'Init the RabbitMQ export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.user = None self.password = None self.queue = None self.export_enable = self.load_conf('rabbitmq', mandatories=['host', 'port', 'user', 'password', 'queue'], options=[]) if (not self.export_enable): sys.exit(2) self.hostname...
'Init the connection to the rabbitmq server.'
def init(self):
if (not self.export_enable): return None try: parameters = pika.URLParameters((((((((('amqp://' + self.user) + ':') + self.password) + '@') + self.host) + ':') + self.port) + '/')) connection = pika.BlockingConnection(parameters) channel = connection.channel() return chan...
'Write the points in RabbitMQ.'
def export(self, name, columns, points):
data = ((((('hostname=' + self.hostname) + ', name=') + name) + ', dateinfo=') + datetime.datetime.utcnow().isoformat()) for i in range(len(columns)): if (not isinstance(points[i], Number)): continue else: data += (((', ' + columns[i]) + '=') + str(points[i])) ...
'Main loop for the CLI.'
def __serve_forever(self):
self.schedule.enter(self.refresh_time, priority=0, action=self.__serve_forever, argument=()) self.stats.update() if (not self.quiet): self.screen.update(self.stats) self.stats.export(self.stats)
'Wrapper to the serve_forever function. This function will restore the terminal to a sane state before re-raising the exception and generating a traceback.'
def serve_forever(self):
self.__serve_forever() try: self.schedule.run() finally: self.end()
'End of the standalone CLI.'
def end(self):
if (not self.quiet): self.screen.end() self.stats.end() if self.outdated.is_outdated(): print 'You are using Glances version {}, however version {} is available.'.format(self.outdated.installed_version(), self.outdated.latest_version()) print 'You sho...
'Return the tree as a string for debugging.'
def __str__(self):
lines = [] nodes_to_print = collections.deque([collections.deque([('#', self)])]) while nodes_to_print: (indent_str, current_node) = nodes_to_print[(-1)].pop() if (not nodes_to_print[(-1)]): nodes_to_print.pop() if current_node.is_root: lines.append(indent_str...
'Set sorting key or func for use with __iter__. This affects the whole tree from this node.'
def set_sorting(self, key, reverse):
if ((self.sort_key != key) or (self.sort_reverse != reverse)): nodes_to_flag_unsorted = collections.deque([self]) while nodes_to_flag_unsorted: current_node = nodes_to_flag_unsorted.pop() current_node.children_sorted = False current_node.sort_key = key ...
'Return \'weight\' of a process and all its children for sorting.'
def get_weight(self):
if ((self.sort_key == 'name') or (self.sort_key == 'username')): return self.stats[self.sort_key] total = 0 nodes_to_sum = collections.deque([self]) while nodes_to_sum: current_node = nodes_to_sum.pop() if isinstance(self.sort_key, collections.Callable): total += self...
'Return the number of nodes in the tree.'
def __len__(self):
total = 0 nodes_to_sum = collections.deque([self]) while nodes_to_sum: current_node = nodes_to_sum.pop() if (not current_node.is_root): total += 1 nodes_to_sum.extend(current_node.children) return total
'Iterator returning ProcessTreeNode in sorted order, recursively.'
def __iter__(self):
if (not self.is_root): (yield self) if (not self.children_sorted): self.children.sort(key=self.__class__.get_weight, reverse=self.sort_reverse) self.children_sorted = True for child in self.children: for n in iter(child): (yield n)
'Iterator returning ProcessTreeNode in sorted order. Return only children of this node, non recursive. If exclude_incomplete_stats is True, exclude processes not having full statistics. It can happen after a resort (change of sort key) because process stats are not grabbed immediately, but only at next full update.'
def iter_children(self, exclude_incomplete_stats=True):
if (not self.children_sorted): self.children.sort(key=self.__class__.get_weight, reverse=self.sort_reverse) self.children_sorted = True for child in self.children: if ((not exclude_incomplete_stats) or ('time_since_update' in child.stats)): (yield child)
'Search in tree for the ProcessTreeNode owning process. Return it or None if not found.'
def find_process(self, process):
nodes_to_search = collections.deque([self]) while nodes_to_search: current_node = nodes_to_search.pop() if ((not current_node.is_root) and (current_node.process.pid == process.pid)): return current_node nodes_to_search.extend(current_node.children)
'Build a process tree using using parent/child relationships. Return the tree root node.'
@staticmethod def build_tree(process_dict, sort_key, sort_reverse, hide_kernel_threads, excluded_processes):
tree_root = ProcessTreeNode(root=True) nodes_to_add_last = collections.deque() for (process, stats) in iteritems(process_dict): new_node = ProcessTreeNode(process, stats, sort_key, sort_reverse) try: parent_process = process.parent() except psutil.NoSuchProcess: ...
'Stop the server'
def end(self):
self.server_close() self.finished = True
'Main loop'
def serve_forever(self):
while (not self.finished): self.handle_request()
'Overwrite the getattr method in case of attribute is not found. The goal is to dynamically generate the API get\'Stats\'() methods.'
def __getattr__(self, item):
header = 'get' if item.startswith(header): try: self.__update__() return getattr(self.stats, item) except Exception: raise AttributeError(item) else: raise AttributeError(item)
'Add an user to the dictionary.'
def add_user(self, username, password):
self.server.user_dict[username] = password self.server.isAuth = True
'Call the main loop.'
def serve_forever(self):
if (self.args.password != ''): self.add_user(self.args.username, self.args.password) self.server.serve_forever()
'End of the Glances server session.'
def end(self):
if (not self.args.disable_autodiscover): self.autodiscover_client.close() self.server.end()
'Log and exit.'
def log_and_exit(self, msg=''):
if (not self.return_to_browser): logger.critical(msg) sys.exit(2) else: logger.error(msg)
'Get the client mode.'
@property def client_mode(self):
return self._client_mode
'Set the client mode. - \'glances\' = Glances server (default) - \'snmp\' = SNMP (fallback)'
@client_mode.setter def client_mode(self, mode):
self._client_mode = mode
'Login to a Glances server'
def _login_glances(self):
client_version = None try: client_version = self.client.init() except socket.error as err: self.client_mode = 'snmp' logger.error('Connection to Glances server failed ({} {})'.format(err.errno, err.strerror)) fallbackmsg = 'No Glances server found ...
'Login to a SNMP server'
def _login_snmp(self):
logger.info('Trying to grab stats by SNMP...') from glances.stats_client_snmp import GlancesStatsClientSNMP self.stats = GlancesStatsClientSNMP(config=self.config, args=self.args) if (not self.stats.check_snmp()): self.log_and_exit('Connection to SNMP server failed') ...
'Logon to the server.'
def login(self):
if self.args.snmp_force: self.client_mode = 'snmp' elif (not self._login_glances()): return False if (self.client_mode == 'snmp'): if (not self._login_snmp()): return False logger.debug('Load limits from the client configuration file') self.stats...
'Update stats from Glances/SNMP server.'
def update(self):
if (self.client_mode == 'glances'): return self.update_glances() elif (self.client_mode == 'snmp'): return self.update_snmp() else: self.end() logger.critical('Unknown server mode: {}'.format(self.client_mode)) sys.exit(2)
'Get stats from Glances server. Return the client/server connection status: - Connected: Connection OK - Disconnected: Connection NOK'
def update_glances(self):
try: server_stats = json.loads(self.client.getAll()) except socket.error: return 'Disconnected' except Fault: return 'Disconnected' else: self.stats.update(server_stats) return 'Connected'
'Get stats from SNMP server. Return the client/server connection status: - SNMP: Connection with SNMP server OK - Disconnected: Connection NOK'
def update_snmp(self):
try: self.stats.update() except Exception: return 'Disconnected' else: return 'SNMP'
'Main client loop.'
def serve_forever(self):
if (not self.login()): logger.critical('The server version is not compatible with the client') self.end() return self.client_mode exitkey = False try: while (True and (not exitkey)): cs_status = self.update() exitkey = self.scre...
'End of the client session.'
def end(self):
self.screen.end()
'Manage the command line arguments.'
def __init__(self):
self.args = self.parse_args()
'Init all the command line arguments.'
def init_args(self):
version = ((('Glances v' + __version__) + ' with psutil v') + psutil_version) parser = argparse.ArgumentParser(prog='glances', conflict_handler='resolve', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=self.example_of_use) parser.add_argument('-V', '--version', action='version', ve...
'Parse command line arguments.'
def parse_args(self):
args = self.init_args().parse_args() self.config = Config(args.conf_file) if args.debug: from logging import DEBUG logger.setLevel(DEBUG) if (args.port is None): if args.webserver: args.port = self.web_server_port else: args.port = self.server_port...
'Return True if Glances is running in standalone mode.'
def is_standalone(self):
return ((not self.args.client) and (not self.args.browser) and (not self.args.server) and (not self.args.webserver))
'Return True if Glances is running in client mode.'
def is_client(self):
return ((self.args.client or self.args.browser) and (not self.args.server))
'Return True if Glances is running in client browser mode.'
def is_client_browser(self):
return (self.args.browser and (not self.args.server))
'Return True if Glances is running in server mode.'
def is_server(self):
return ((not self.args.client) and self.args.server)
'Return True if Glances is running in Web server mode.'
def is_webserver(self):
return ((not self.args.client) and self.args.webserver)
'Return configuration file object.'
def get_config(self):
return self.config
'Return the arguments.'
def get_args(self):
return self.args
'Return the mode.'
def get_mode(self):
return self.mode
'Read an username from the command line.'
def __get_username(self, description=''):
return input(description)
'Read a password from the command line. - if confirm = True, with confirmation - if clear = True, plain (clear password)'
def __get_password(self, description='', confirm=False, clear=False, username='glances'):
from glances.password import GlancesPassword password = GlancesPassword(username=username) return password.get_password(description, confirm, clear)
'Init the folder list from the configuration file, if it exists.'
def __init__(self, config):
self.config = config if ((self.config is not None) and self.config.has_section('folders')): if scandir_tag: logger.debug('Folder list configuration detected') self.__set_folder_list('folders') else: logger.error('Scandir not found. Please ...
'Init the monitored folder list. The list is defined in the Glances configuration file.'
def __set_folder_list(self, section):
for l in range(1, (self.__folder_list_max_size + 1)): value = {} key = (('folder_' + str(l)) + '_') value['path'] = self.config.get_value(section, (key + 'path')) if (value['path'] is None): continue for i in ['careful', 'warning', 'critical']: value[i...
'Meta function to return key value of item. Return None if not defined or item > len(list)'
def __get__(self, item, key):
if (item < len(self.__folder_list)): try: return self.__folder_list[item][key] except Exception: return None else: return None
'Return the size of the directory given by path path: <string>'
def __folder_size(self, path):
ret = 0 for f in scandir(path): if (f.is_dir() and ((f.name != '.') or (f.name != '..'))): ret += self.__folder_size(os.path.join(path, f.name)) else: try: ret += f.stat().st_size except OSError: pass return ret
'Update the command result attributed.'
def update(self):
if (len(self.__folder_list) == 0): return self.__folder_list for i in range(len(self.get())): try: self.__folder_list[i]['size'] = self.__folder_size(self.path(i)) except OSError as e: logger.debug('Cannot get folder size ({}). Error: {}'.format(...
'Return the monitored list (list of dict).'
def get(self):
return self.__folder_list
'Set the monitored list (list of dict).'
def set(self, newlist):
self.__folder_list = newlist
'Return the path of the item number (item).'
def path(self, item):
return self.__get__(item, 'path')
'Return the careful threshold of the item number (item).'
def careful(self, item):
return self.__get__(item, 'careful')
'Return the warning threshold of the item number (item).'
def warning(self, item):
return self.__get__(item, 'warning')
'Return the critical threshold of the item number (item).'
def critical(self, item):
return self.__get__(item, 'critical')
'Return the key of the per CPU list.'
def get_key(self):
return 'cpu_number'
'Update and/or return the CPU using the psutil library. If percpu, return the percpu stats'
def get(self, percpu=False):
if percpu: return self.__get_percpu() else: return self.__get_cpu()
'Update and/or return the CPU using the psutil library.'
def __get_cpu(self):
if self.timer_cpu.finished(): self.cpu_percent = psutil.cpu_percent(interval=0.0) self.timer_cpu = Timer(self.cached_time) return self.cpu_percent
'Update and/or return the per CPU list using the psutil library.'
def __get_percpu(self):
if self.timer_percpu.finished(): self.percpu_percent = [] for (cpu_number, cputimes) in enumerate(psutil.cpu_times_percent(interval=0.0, percpu=True)): cpu = {'key': self.get_key(), 'cpu_number': cpu_number, 'total': round((100 - cputimes.idle), 1), 'user': cputimes.user, 'system': cputi...
'Init the Outdated class'
def __init__(self, args, config):
self.args = args self.config = config self.cache_dir = user_cache_dir() self.cache_file = os.path.join(self.cache_dir, 'glances-version.db') self.data = {u'installed_version': __version__, u'latest_version': '0.0', u'refresh_date': datetime.now()} self.load_config(config) logger.debug('Check...
'Load outdated parameter in the global section of the configuration file.'
def load_config(self, config):
global_section = 'global' if (hasattr(config, 'has_section') and config.has_section(global_section)): self.args.disable_check_update = (config.get_value(global_section, 'check_update').lower() == 'false') else: logger.debug('Cannot find section {} in the configuration fi...
'Wrapper to get the latest PyPI version (async) The data are stored in a cached file Only update online once a week'
def get_pypi_version(self):
if self.args.disable_check_update: return cached_data = self._load_cache() if (cached_data == {}): thread = threading.Thread(target=self._update_pypi_version) thread.start() else: self.data['latest_version'] = cached_data['latest_version'] logger.debug('Get Gla...
'Return True if a new version is available'
def is_outdated(self):
if self.args.disable_check_update: return False logger.debug('Check Glances version (installed: {} / latest: {})'.format(self.installed_version(), self.latest_version())) return (LooseVersion(self.latest_version()) > LooseVersion(self.installed_version()))
'Load cache file and return cached data'
def _load_cache(self):
max_refresh_date = timedelta(days=7) cached_data = {} try: with open(self.cache_file, 'rb') as f: cached_data = pickle.load(f) except Exception as e: logger.debug('Cannot read version from cache file: {} ({})'.format(self.cache_file, e)) else: ...
'Save data to the cache file.'
def _save_cache(self):
safe_makedirs(self.cache_dir) try: with open(self.cache_file, 'wb') as f: pickle.dump(self.data, f) except Exception as e: logger.error('Cannot write version to cache file {} ({})'.format(self.cache_file, e))
'Get the latest PyPI version (as a string) via the RESTful JSON API'
def _update_pypi_version(self):
logger.debug('Get latest Glances version from the PyPI RESTful API ({})'.format(PYPI_API_URL)) self.data[u'refresh_date'] = datetime.now() try: res = urlopen(PYPI_API_URL, timeout=3).read() except (HTTPError, URLError) as e: logger.debug('Cannot get Glanc...
'Load the ports list from the configuration file.'
def load(self, config):
ports_list = [] if (config is None): logger.debug('No configuration file available. Cannot load ports list.') elif (not config.has_section(self._section)): logger.debug(('No [%s] section in the configuration file. Cannot load ports list.' % ...
'Return the current server list (dict of dict).'
def get_ports_list(self):
return self._ports_list
'Set the key to the value for the pos (position in the list).'
def set_server(self, pos, key, value):
self._ports_list[pos][key] = value
'Return the threshold dict. If stat_name is None, return the threshold for all plugins (dict of Threshold*) Else return the Threshold* instance for the given plugin'
def get(self, stat_name=None):
if (stat_name is None): return self._thresholds if (stat_name in self._thresholds): return self._thresholds[stat_name] else: return {}
'Add a new threshold to the dict (key = stat_name)'
def add(self, stat_name, threshold_description):
if (threshold_description not in self.threshold_list): return False else: self._thresholds[stat_name] = getattr(self.current_module, ('GlancesThreshold' + threshold_description.capitalize()))() return True
'Override the default comparaison behavior'
def __cmp__(self, other):
return self.value().__cmp__(other.value())
'Return the active server or None if it\'s the browser list.'
@property def active_server(self):
return self._active_server