desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Seek to specified position into the chunk. Default position is 0 (start of chunk). If the file is not seekable, this will result in an error.'
def seek(self, pos, whence=0):
if self.closed: raise ValueError('I/O operation on closed file') if (not self.seekable): raise OSError('cannot seek') if (whence == 1): pos = (pos + self.size_read) elif (whence == 2): pos = (pos + self.chunksize) if ((pos < 0) or (pos > self.chunksize)...
'Read at most size bytes from the chunk. If size is omitted or negative, read until the end of the chunk.'
def read(self, size=(-1)):
if self.closed: raise ValueError('I/O operation on closed file') if (self.size_read >= self.chunksize): return '' if (size < 0): size = (self.chunksize - self.size_read) if (size > (self.chunksize - self.size_read)): size = (self.chunksize - self.size_read) ...
'Skip the rest of the chunk. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk.'
def skip(self):
if self.closed: raise ValueError('I/O operation on closed file') if self.seekable: try: n = (self.chunksize - self.size_read) if (self.align and (self.chunksize & 1)): n = (n + 1) self.file.seek(n, 1) self.size_read = (s...
'Init the class to collect stats about processes.'
def __init__(self, cache_timeout=60):
self.username_cache = {} self.cmdline_cache = {} self.cache_timeout = cache_timeout self.cache_timer = Timer(self.cache_timeout) self.io_old = {} self._enable_tree = False self.process_tree = None self.auto_sort = True self._sort_key = 'cpu_percent' self.allprocesslist = [] s...
'Enable process stats.'
def enable(self):
self.disable_tag = False self.update()
'Disable process stats.'
def disable(self):
self.disable_tag = True
'Enable extended process stats.'
def enable_extended(self):
self.disable_extended_tag = False self.update()
'Disable extended process stats.'
def disable_extended(self):
self.disable_extended_tag = True
'Get the maximum PID value. On Linux, the value is read from the `/proc/sys/kernel/pid_max` file. From `man 5 proc`: The default value for this file, 32768, results in the same range of PIDs as on earlier kernels. On 32-bit platfroms, 32768 is the maximum value for pid_max. On 64-bit systems, pid_max can be set to any ...
@property def pid_max(self):
if LINUX: try: with open('/proc/sys/kernel/pid_max', 'rb') as f: return int(f.read()) except (OSError, IOError): return None
'Get the maximum number of processes showed in the UI.'
@property def max_processes(self):
return self._max_processes
'Set the maximum number of processes showed in the UI.'
@max_processes.setter def max_processes(self, value):
self._max_processes = value
'Get the process filter (given by the user).'
@property def process_filter_input(self):
return self._filter.filter_input
'Get the process filter (current apply filter).'
@property def process_filter(self):
return self._filter.filter
'Set the process filter.'
@process_filter.setter def process_filter(self, value):
self._filter.filter = value
'Get the process filter key.'
@property def process_filter_key(self):
return self._filter.filter_key
'Get the process regular expression compiled.'
@property def process_filter_re(self):
return self._filter.filter_re
'Ignore kernel threads in process list.'
def disable_kernel_threads(self):
self.no_kernel_threads = True
'Enable process tree.'
def enable_tree(self):
self._enable_tree = True
'Return True if process tree is enabled, False instead.'
def is_tree_enabled(self):
return self._enable_tree
'Return True to sort processes in reverse \'key\' order, False instead.'
@property def sort_reverse(self):
if ((self.sort_key == 'name') or (self.sort_key == 'username')): return False return True
'Return the max values dict.'
def max_values(self):
return self._max_values
'Get the maximum values of the given stat (key).'
def get_max_values(self, key):
return self._max_values[key]
'Set the maximum value for a specific stat (key).'
def set_max_values(self, key, value):
self._max_values[key] = value
'Reset the maximum values dict.'
def reset_max_values(self):
self._max_values = {} for k in self._max_values_list: self._max_values[k] = 0.0
'Get mandatory_stats: for all processes. Needed for the sorting/filter step. Stats grabbed inside this method: * \'name\', \'cpu_times\', \'status\', \'ppid\' * \'username\', \'cpu_percent\', \'memory_percent\''
def __get_mandatory_stats(self, proc, procstat):
procstat['mandatory_stats'] = True try: procstat.update(proc.as_dict(attrs=['name', 'cpu_times', 'status', 'ppid'], ad_value='')) except psutil.NoSuchProcess: return None else: procstat['status'] = str(procstat['status'])[:1].upper() try: procstat.update(proc.as_dict(...
'Get standard_stats: only for displayed processes. Stats grabbed inside this method: * nice and memory_info'
def __get_standard_stats(self, proc, procstat):
procstat['standard_stats'] = True try: procstat.update(proc.as_dict(attrs=['nice', 'memory_info'])) except psutil.NoSuchProcess: pass return procstat
'Get extended stats, only for top processes (see issue #403). - cpu_affinity (Linux, Windows, FreeBSD) - ionice (Linux and Windows > Vista) - memory_full_info (Linux) - num_ctx_switches (not available on Illumos/Solaris) - num_fds (Unix-like) - num_handles (Windows) - num_threads (not available on *BSD) - memory_maps (...
def __get_extended_stats(self, proc, procstat):
procstat['extended_stats'] = True for stat in ['cpu_affinity', 'ionice', 'memory_full_info', 'num_ctx_switches', 'num_fds', 'num_handles', 'num_threads']: try: procstat.update(proc.as_dict(attrs=[stat])) except psutil.NoSuchProcess: pass except (ValueError, Attrib...
'Get stats of a running processes.'
def __get_process_stats(self, proc, mandatory_stats=True, standard_stats=True, extended_stats=False):
procstat = proc.as_dict(attrs=['pid']) if mandatory_stats: procstat = self.__get_mandatory_stats(proc, procstat) if ((procstat is not None) and standard_stats): procstat = self.__get_standard_stats(proc, procstat) if ((procstat is not None) and extended_stats and (not self.disable_extend...
'Update the processes stats.'
def update(self):
self.processlist = [] self.reset_processcount() if self.disable_tag: return time_since_update = getTimeSinceLastUpdate('process_disk') self.reset_max_values() self.processcount['pid_max'] = self.pid_max processdict = {} excluded_processes = set() for proc in psutil.process_it...
'Get the number of processes.'
def getcount(self):
return self.processcount
'Get the allprocesslist.'
def getalllist(self):
return self.allprocesslist
'Get the processlist.'
def getlist(self, sortedby=None):
return self.processlist
'Get the process tree.'
def gettree(self):
return self.process_tree
'Get the current sort key.'
@property def sort_key(self):
return self._sort_key
'Set the current sort key.'
@sort_key.setter def sort_key(self, key):
self._sort_key = key
'Chek if SNMP is available on the server.'
def check_snmp(self):
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, user=self.args.snmp_user, auth=self.args.snmp_auth) ret = (clientsnmp.get_by_oid('1.3.6.1.2.1.1.5.0') != {}) if r...
'Get the short os name from the OS name OID string.'
def get_system_name(self, oid_system_name):
short_system_name = None if (oid_system_name == ''): return short_system_name for (r, v) in iteritems(oid_to_short_system_name): if re.search(r, oid_system_name): short_system_name = v break return short_system_name
'Update the stats using SNMP.'
def update(self):
for p in self._plugins: if self._plugins[p].is_disable(): continue self._plugins[p].input_method = 'snmp' self._plugins[p].short_system_name = self.system_name try: self._plugins[p].update() except Exception as e: logger.error('Update {}...
'Load the password from the configuration file.'
def load(self, config):
password_dict = {} if (config is None): logger.warning('No configuration file available. Cannot load password list.') elif (not config.has_section(self._section)): logger.warning(('No [%s] section in the configuration file. Cannot load password...
'If host=None, return the current server list (dict). Else, return the host\'s password (or the default one if defined or None)'
def get_password(self, host=None):
if (host is None): return self._password_dict else: try: return self._password_dict[host] except (KeyError, TypeError): try: return self._password_dict['default'] except (KeyError, TypeError): return None
'Set a password for a specific host.'
def set_password(self, host, password):
self._password_dict[host] = password
'Return the current server list (list of dict).'
def get_servers_list(self):
return self._server_list
'Set the key to the value for the server_pos (position in the list).'
def set_server(self, server_pos, key, value):
self._server_list[server_pos][key] = value
'Add a new server to the list.'
def add_server(self, name, ip, port):
new_server = {'key': name, 'name': name.split(':')[0], 'ip': ip, 'port': port, 'username': 'glances', 'password': '', 'status': 'UNKNOWN', 'type': 'DYNAMIC'} self._server_list.append(new_server) logger.debug(('Updated servers list (%s servers): %s' % (len(self._server_list), self._server_list...
'Remove a server from the dict.'
def remove_server(self, name):
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)) logger.debug(('Updated servers list (%s servers): %s' % (len(self._server_list...
'Return the current server list (list of dict).'
def get_servers_list(self):
return self.servers.get_servers_list()
'Set the key to the value for the server_pos (position in the list).'
def set_server(self, server_pos, key, value):
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):
if (srv_type != zeroconf_type): return False logger.debug(('Check new Zeroconf server: %s / %s' % (srv_type, srv_name))) info = zeroconf.get_service_info(srv_type, srv_name) if info: new_server_ip = socket.inet_ntoa(info.address) new_server_port = info.port ...
'Remove the server from the list.'
def remove_service(self, zeroconf, srv_type, srv_name):
self.servers.remove_server(srv_name) logger.info(('Glances server %s removed from the autodetect list' % srv_name))
'Return the current server list (dict of dict).'
def get_servers_list(self):
if (zeroconf_tag and self.zeroconf_enable_tag): return self.listener.get_servers_list() else: return []
'Set the key to the value for the server_pos (position in the list).'
def set_server(self, server_pos, key, value):
if (zeroconf_tag and self.zeroconf_enable_tag): self.listener.set_server(server_pos, key, value)
'Try to find the active IP addresses.'
@staticmethod def find_active_ip_address():
import netifaces gateway_itf = netifaces.gateways()['default'][netifaces.AF_INET][1] return netifaces.ifaddresses(gateway_itf)[netifaces.AF_INET][0]['addr']
'Init the GlancesStatsClient class.'
def __init__(self, config=None, args=None):
super(GlancesStatsClient, self).__init__(config=config, args=args) self.config = config self.args = args
'Set the plugin list according to the Glances server.'
def set_plugins(self, input_plugins):
header = 'glances_' for item in input_plugins: try: plugin = __import__((header + item)) except ImportError: logger.error('Can not import {} plugin. Please upgrade your Glances client/server version.'.format(item)) else: l...
'Update all the stats.'
def update(self, input_stats):
for p in input_stats: self._plugins[p].set_stats(input_stats[p]) self._plugins[p].update_views()
'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/glances, /usr/local/etc/glances * Windows: %A...
def config_file_paths(self):
paths = [] if self.config_dir: paths.append(self.config_dir) paths.append(os.path.join(user_config_dir(), self.config_filename)) paths.append(os.path.join(system_config_dir(), self.config_filename)) return paths
'Read the config file, if it exists. Using defaults otherwise.'
def read(self):
for config_file in self.config_file_paths(): if os.path.exists(config_file): try: with open(config_file, encoding='utf-8') as f: self.parser.read_file(f) self.parser.read(f) logger.info("Read configuration file '{}'...
'Return the loaded configuration file.'
@property def loaded_config_file(self):
return self._loaded_config_file
'Return the configuration as a dict'
def as_dict(self):
dictionary = {} for section in self.parser.sections(): dictionary[section] = {} for option in self.parser.options(section): dictionary[section][option] = self.parser.get(section, option) return dictionary
'Return a list of all sections.'
def sections(self):
return self.parser.sections()
'Return the items list of a section.'
def items(self, section):
return self.parser.items(section)
'Return info about the existence of a section.'
def has_section(self, section):
return self.parser.has_section(section)
'Set default values for careful, warning and critical.'
def set_default_cwc(self, section, option_header=None, cwc=['50', '70', '90']):
if (option_header is None): header = '' else: header = (option_header + '_') self.set_default(section, (header + 'careful'), cwc[0]) self.set_default(section, (header + 'warning'), cwc[1]) self.set_default(section, (header + 'critical'), cwc[2])
'If the option did not exist, create a default value.'
def set_default(self, section, option, default):
if (not self.parser.has_option(section, option)): self.parser.set(section, option, default)
'Get the value of an option, if it exists.'
def get_value(self, section, option, default=None):
try: return self.parser.get(section, option) except NoOptionError: return default
'Get the int value of an option, if it exists.'
def get_int_value(self, section, option, default=0):
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):
try: return self.parser.getfloat(section, option) except NoOptionError: return float(default)
'Return the SHA-256 of the given password.'
def sha256_hash(self, plain_password):
return hashlib.sha256(b(plain_password)).hexdigest()
'Return the hashed password, salt + SHA-256.'
def get_hash(self, salt, plain_password):
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):
salt = uuid.uuid4().hex encrypted_password = self.get_hash(salt, plain_password) return ((salt + '$') + encrypted_password)
'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):
(salt, encrypted_password) = hashed_password.split('$') re_encrypted_password = self.get_hash(salt, plain_password) return (encrypted_password == re_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 password (confirm=False, clear=True): 1) from the...
def get_password(self, description='', confirm=False, clear=False):
if (os.path.exists(self.password_file) and (not clear)): logger.info('Read password from file {}'.format(self.password_file)) password = self.load_password() else: password_sha256 = self.sha256_hash(getpass.getpass(description)) password_hashed = self.hash_password(pa...
'Save the hashed password to the Glances folder.'
def save_password(self, hashed_password):
safe_makedirs(self.password_dir) with open(self.password_file, 'wb') as file_pwd: file_pwd.write(b(hashed_password))
'Load the hashed password from the Glances folder.'
def load_password(self):
with open(self.password_file, 'r') as file_pwd: hashed_password = file_pwd.read() return hashed_password
'Init the Cassandra export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.keyspace = None self.protocol_version = 3 self.replication_factor = 2 self.table = None self.export_enable = self.load_conf('cassandra', mandatories=['host', 'port', 'keyspace'], options=['protocol_version', 'replication_factor', 'table...
'Init the connection to the InfluxDB server.'
def init(self):
if (not self.export_enable): return None try: cluster = Cluster([self.host], port=int(self.port), protocol_version=int(self.protocol_version)) session = cluster.connect() except Exception as e: logger.critical(("Cannot connect to Cassandra cluster '%s:%s' (%...
'Write the points to the Cassandra cluster.'
def export(self, name, columns, points):
logger.debug('Export {} stats to Cassandra'.format(name)) data = {k: float(v) for (k, v) in dict(zip(columns, points)).iteritems() if isinstance(v, Number)} try: self.session.execute('\n INSERT INTO localhost (plugin...
'Close the Cassandra export module.'
def exit(self):
self.session.shutdown() self.cluster.shutdown() super(Export, self).exit()
'Init the OpenTSDB export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.prefix = None self.tags = None self.export_enable = self.load_conf('opentsdb', mandatories=['host', 'port'], options=['prefix', 'tags']) if (not self.export_enable): sys.exit(2) if (self.prefix is None): self.prefix = 'g...
'Init the connection to the OpenTSDB server.'
def init(self):
if (not self.export_enable): return None try: db = potsdb.Client(self.host, port=int(self.port), check_host=True) except Exception as e: logger.critical(('Cannot connect to OpenTSDB server %s:%s (%s)' % (self.host, self.port, e))) sys.exit(2) return db
'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(self.prefix, name, columns[i]) stat_value = points[i] tags = self.parse_tags(self.tags) try: self.client.send(stat_name, stat_value, **tags) ...
'Close the OpenTSDB export module.'
def exit(self):
self.client.wait() super(Export, self).exit()
'Init the export class.'
def __init__(self, config=None, args=None):
self.export_name = self.__class__.__module__[len('glances_'):] logger.debug(('Init export module %s' % self.export_name)) self.config = config self.args = args self.export_enable = False self.host = None self.port = None
'Close the export module.'
def exit(self):
logger.debug(('Finalise export interface %s' % self.export_name))
'Return the list of plugins to export.'
def plugins_to_export(self):
return ['cpu', 'percpu', 'load', 'mem', 'memswap', 'network', 'diskio', 'fs', 'processcount', 'ip', 'system', 'uptime', 'sensors', 'docker', 'uptime']
'Load the export <section> configuration in the Glances configuration file. :param section: name of the export section to load :param mandatories: a list of mandatories parameters to load :param options: a list of optionnals parameters to load :returns: Boolean -- True if section is found'
def load_conf(self, section, mandatories=['host', 'port'], options=None):
options = (options or []) if (self.config is None): return False try: for opt in mandatories: setattr(self, opt, self.config.get_value(section, opt)) except NoSectionError: logger.critical('No {} configuration found'.format(section)) return False ...
'Return the value of the item \'key\'.'
def get_item_key(self, item):
try: ret = item[item['key']] except KeyError: logger.error("No 'key' available in {}".format(item)) if isinstance(ret, list): return ret[0] else: return ret
'Parse tags into a dict. input tags: a comma separated list of \'key:value\' pairs. Example: foo:bar,spam:eggs output dtags: a dict of tags. Example: {\'foo\': \'bar\', \'spam\': \'eggs\'}'
def parse_tags(self, tags):
dtags = {} if tags: try: dtags = dict([x.split(':') for x in tags.split(',')]) except ValueError: logger.info('Invalid tags passed: %s', tags) dtags = {} return dtags
'Update stats to a server. The method builds two lists: names and values and calls the export method to export the stats. Be aware that CSV export overwrite this class and use a specific one.'
def update(self, stats):
if (not self.export_enable): return False all_stats = stats.getAllExportsAsDict(plugin_list=self.plugins_to_export()) all_limits = stats.getAllLimitsAsDict(plugin_list=self.plugins_to_export()) for plugin in self.plugins_to_export(): if isinstance(all_stats[plugin], dict): al...
'Build the export lists.'
def __build_export(self, stats):
export_names = [] export_values = [] if isinstance(stats, dict): if (('key' in iterkeys(stats)) and (stats['key'] in iterkeys(stats))): pre_key = '{}.'.format(stats[stats['key']]) else: pre_key = '' for (key, value) in iteritems(stats): if isinstan...
'Init the InfluxDB export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.user = None self.password = None self.db = None self.prefix = None self.tags = None self.export_enable = self.load_conf('influxdb', mandatories=['host', 'port', 'user', 'password', 'db'], options=['prefix', 'tags']) if (not self...
'Init the connection to the InfluxDB server.'
def init(self):
if (not self.export_enable): return None try: db = InfluxDBClient(host=self.host, port=self.port, username=self.user, password=self.password, database=self.db) get_all_db = [i['name'] for i in db.get_list_database()] self.version = INFLUXDB_09PLUS except InfluxDBClientError: ...
'Write the points to the InfluxDB server.'
def export(self, name, columns, points):
logger.debug('Export {} stats to InfluxDB'.format(name)) if (self.prefix is not None): name = ((self.prefix + '.') + name) if (self.version == INFLUXDB_08): data = [{'name': name, 'columns': columns, 'points': [points]}] else: for (i, _) in enumerate(points): ...
'Init the Prometheus export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.prefix = 'glances' self.export_enable = self.load_conf('prometheus', mandatories=['host', 'port'], options=['prefix']) if (not self.export_enable): sys.exit(2) self._metric_dict = {} self.init()
'Init the Prometheus Exporter'
def init(self):
try: start_http_server(port=int(self.port), addr=self.host) except Exception as e: logger.critical('Can not start Prometheus exporter on {}:{} ({})'.format(self.host, self.port, e)) sys.exit(2) else: logger.info('Start Prometheus exporter on {...
'Write the points to the Prometheus exporter using Gauge.'
def export(self, name, columns, points):
logger.debug('Export {} stats to Prometheus exporter'.format(name)) data = {k: float(v) for (k, v) in iteritems(dict(zip(columns, points))) if isinstance(v, Number)} for (k, v) in iteritems(data): metric_name = ((((self.prefix + self.METRIC_SEPARATOR) + name) + self.METRIC_SEPARATOR) ...
'Init the Kafka export IF.'
def __init__(self, config=None, args=None):
super(Export, self).__init__(config=config, args=args) self.topic = None self.compression = None self.export_enable = self.load_conf('kafka', mandatories=['host', 'port', 'topic'], options=['compression']) if (not self.export_enable): sys.exit(2) self.client = self.init()
'Init the connection to the Kafka server.'
def init(self):
if (not self.export_enable): return None server_uri = '{}:{}'.format(self.host, self.port) try: s = KafkaProducer(bootstrap_servers=server_uri, value_serializer=(lambda v: json.dumps(v).encode('utf-8')), compression_type=self.compression) except Exception as e: logger.critical(('...
'Write the points to the kafka server.'
def export(self, name, columns, points):
logger.debug('Export {} stats to Kafka'.format(name)) data = dict(zip(columns, points)) try: self.client.send(self.topic, key=name, value=data) except Exception as e: logger.error('Cannot export {} stats to Kafka ({})'.format(name, e))
'Close the Kafka export module.'
def exit(self):
self.client.flush() self.client.close() super(Export, self).exit()