desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Scan the (ICMP) port structure (dict) and update the status key'
def _port_scan_icmp(self, port):
ret = None if WINDOWS: timeout_opt = '-w' count_opt = '-n' elif (MACOS or BSD): timeout_opt = '-t' count_opt = '-c' else: timeout_opt = '-W' count_opt = '-c' cmd = ['ping', count_opt, '1', timeout_opt, str(self._resolv_name(port['timeout'])), self._res...
'Scan the (TCP) port structure (dict) and update the status key'
def _port_scan_tcp(self, port):
ret = None try: socket.setdefaulttimeout(port['timeout']) _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except Exception as e: logger.debug('{}: Error while creating scanning socket'.format(self.plugin_name)) ip = self._resolv_name(port['host']) c...
'Init the plugin.'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args) self.display_curse = True self.glances_folders = None self.reset()
'Return the key of the list.'
def get_key(self):
return 'path'
'Reset/init the stats.'
def reset(self):
self.stats = []
'Load the foldered list from the config file, if it exists.'
def load_limits(self, config):
self.glances_folders = glancesFolderList(config)
'Update the foldered list.'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if (self.input_method == 'local'): if (self.glances_folders is None): return self.stats self.glances_folders.update() self.stats = self.glances_folders.get() else: pass return self.stats
'Manage limits of the folder list'
def get_alert(self, stat):
if (not isinstance(stat['size'], numbers.Number)): return 'DEFAULT' else: ret = 'OK' if ((stat['critical'] is not None) and (stat['size'] > (int(stat['critical']) * 1000000))): ret = 'CRITICAL' elif ((stat['warning'] is not None) and (stat['size'] > (int(stat['warning']) * 100000...
'Return the dict to display in the curse interface.'
def msg_curse(self, args=None):
ret = [] if ((not self.stats) or self.is_disable()): return ret msg = '{}'.format('FOLDERS') ret.append(self.curse_add_line(msg, 'TITLE')) for i in self.stats: ret.append(self.curse_new_line()) if (len(i['path']) > 15): path = ('_' + i['path'][((-15) + 1):]) ...
'Init the plugin.'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args) self.display_curse = True self.align = 'bottom'
'Reset/init the stats.'
def reset(self):
self.stats = ''
'Update current date/time.'
def update(self):
self.stats = datetime.now().strftime('%Y-%m-%d %H:%M:%S') return self.stats
'Return the string to display in the curse interface.'
def msg_curse(self, args=None):
ret = [] msg = '{:23}'.format(self.stats) ret.append(self.curse_add_line(msg)) return ret
'Init the plugin'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args) self.init_nvidia() self.display_curse = True self.reset()
'Reset/init the stats.'
def reset(self):
self.stats = []
'Init the NVIDIA API'
def init_nvidia(self):
if (not gpu_nvidia_tag): self.nvml_ready = False try: pynvml.nvmlInit() self.device_handles = get_device_handles() self.nvml_ready = True except Exception: logger.debug('pynvml could not be initialized.') self.nvml_ready = False return self.nvm...
'Return the key of the list.'
def get_key(self):
return 'gpu_id'
'Update the GPU stats'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if (not self.nvml_ready): return self.stats if (self.input_method == 'local'): self.stats = self.get_device_stats() elif (self.input_method == 'snmp'): pass return self.stats
'Update stats views.'
def update_views(self):
super(Plugin, self).update_views() for i in self.stats: self.views[i[self.get_key()]] = {'proc': {}, 'mem': {}} if ('proc' in i): alert = self.get_alert(i['proc'], header='proc') self.views[i[self.get_key()]]['proc']['decoration'] = alert if ('mem' in i): ...
'Return the dict to display in the curse interface.'
def msg_curse(self, args=None, max_width=None):
ret = [] if ((not self.stats) or (self.stats == []) or self.is_disable()): return ret same_name = all(((s['name'] == self.stats[0]['name']) for s in self.stats)) gpu_stats = self.stats[0] header = '' if (len(self.stats) > 1): header += '{} '.format(len(self.stats)) if same...
'Get GPU stats'
def get_device_stats(self):
stats = [] for (index, device_handle) in enumerate(self.device_handles): device_stats = {} device_stats['key'] = self.get_key() device_stats['gpu_id'] = index device_stats['name'] = get_device_name(device_handle) device_stats['mem'] = get_mem(device_handle) device...
'Overwrite the exit method to close the GPU API'
def exit(self):
if self.nvml_ready: try: pynvml.nvmlShutdown() except Exception as e: logger.debug('pynvml failed to shutdown correctly ({})'.format(e)) super(Plugin, self).exit()
'Init the plugin.'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args) self.display_curse = True self.public_address = PublicIpAddress().get() self.reset()
'Reset/init the stats.'
def reset(self):
self.stats = {}
'Update IP stats using the input method. Stats is dict'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if ((self.input_method == 'local') and netifaces_tag): try: default_gw = netifaces.gateways()['default'][netifaces.AF_INET] except (KeyError, AttributeError) as e: logger.debug('Cannot grab the default gateway ({})'.format(e)) else: ...
'Update stats views.'
def update_views(self):
super(Plugin, self).update_views() for key in iterkeys(self.stats): self.views[key]['optional'] = True
'Return the dict to display in the curse interface.'
def msg_curse(self, args=None):
ret = [] if ((not self.stats) or self.is_disable()): return ret msg = ' - ' ret.append(self.curse_add_line(msg)) msg = 'IP ' ret.append(self.curse_add_line(msg, 'TITLE')) msg = '{}'.format(self.stats['address']) ret.append(self.curse_add_line(msg)) if ('mask_cidr' in...
'Convert IP address to CIDR. Example: \'255.255.255.0\' will return 24'
@staticmethod def ip_to_cidr(ip):
return (sum([(int(x) << 8) for x in ip.split('.')]) // 8128)
'Get the first public IP address returned by one of the online services'
def get(self):
q = queue.Queue() for (u, j, k) in urls: t = threading.Thread(target=self._get_ip_public, args=(q, u, j, k)) t.daemon = True t.start() timer = Timer(self.timeout) ip = None while ((not timer.finished()) and (ip is None)): if (q.qsize() > 0): ip = q.get() ...
'Request the url service and put the result in the queue_target'
def _get_ip_public(self, queue_target, url, json=False, key=None):
try: response = urlopen(url, timeout=self.timeout).read().decode('utf-8') except Exception as e: logger.debug('IP plugin - Cannot open URL {} ({})'.format(url, e)) queue_target.put(None) else: try: if (not json): queue_target.p...
'Init the plugin.'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args) self.glancesgrabhddtemp = GlancesGrabHDDTemp(args=args) self.display_curse = False self.reset()
'Reset/init the stats.'
def reset(self):
self.stats = []
'Update HDD stats using the input method.'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if (self.input_method == 'local'): self.stats = self.glancesgrabhddtemp.get() else: pass return self.stats
'Init hddtemp stats.'
def __init__(self, host='127.0.0.1', port=7634, args=None):
self.args = args self.host = host self.port = port self.cache = '' self.reset()
'Reset/init the stats.'
def reset(self):
self.hddtemp_list = []
'Update the stats.'
def __update__(self):
self.reset() data = self.fetch() if (data == ''): return if (len(data) < 14): data = (self.cache if (len(self.cache) > 0) else self.fetch()) self.cache = data try: fields = data.split('|') except TypeError: fields = '' devices = ((len(fields) - 1) // 5) ...
'Fetch the data from hddtemp daemon.'
def fetch(self):
try: sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect((self.host, self.port)) data = sck.recv(4096) except socket.error as e: logger.debug('Cannot connect to an HDDtemp server ({}:{} => {})'.format(self.host, self.port, e)) logge...
'Get HDDs list.'
def get(self):
self.__update__() return self.hddtemp_list
'Init the plugin.'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args) self.reset()
'Reset/init the stats.'
def reset(self):
self.stats = None
'Update the stats.'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if (self.input_method == 'local'): try: self.stats = psutil_version_info except NameError: pass else: pass return self.stats
'Init the plugin.'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args, items_history_list=items_history_list) self.display_curse = True self.reset()
'Return the key of the list.'
def get_key(self):
return 'interface_name'
'Reset/init the stats.'
def reset(self):
self.stats = []
'Update network stats using the input method. Stats is a list of dict (one dict per interface)'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if (self.input_method == 'local'): try: netiocounters = psutil.net_io_counters(pernic=True) except UnicodeDecodeError: return self.stats netstatus = {} try: netstatus = psutil.net_if_stats() except AttributeError: ...
'Update stats views.'
def update_views(self):
super(Plugin, self).update_views() for i in self.stats: ifrealname = i['interface_name'].split(':')[0] bps_rx = int(((i['rx'] // i['time_since_update']) * 8)) bps_tx = int(((i['tx'] // i['time_since_update']) * 8)) alert_rx = self.get_alert(bps_rx, header=(ifrealname + '_rx')) ...
'Return the dict to display in the curse interface.'
def msg_curse(self, args=None, max_width=None):
ret = [] if ((not self.stats) or self.is_disable()): return ret if ((max_width is not None) and (max_width >= 23)): ifname_max_width = (max_width - 14) else: ifname_max_width = 9 msg = '{:{width}}'.format('NETWORK', width=ifname_max_width) ret.append(self.curse_add_line(m...
'Init the plugin.'
def __init__(self, args=None):
super(Plugin, self).__init__(args=args) self.glancesgrabbat = GlancesGrabBat() self.display_curse = False self.reset()
'Reset/init the stats.'
def reset(self):
self.stats = []
'Update battery capacity stats using the input method.'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if (self.input_method == 'local'): self.glancesgrabbat.update() self.stats = self.glancesgrabbat.get() elif (self.input_method == 'snmp'): pass return self.stats
'Init batteries stats.'
def __init__(self):
self.bat_list = [] if batinfo_tag: self.bat = batinfo.batteries() elif psutil_tag: self.bat = psutil else: self.bat = None
'Update the stats.'
def update(self):
if batinfo_tag: self.bat.update() self.bat_list = [{'label': 'Battery', 'value': self.battery_percent, 'unit': '%'}] elif (psutil_tag and hasattr(self.bat.sensors_battery(), 'percent')): self.bat_list = [{'label': 'Battery', 'value': int(self.bat.sensors_battery().percent), 'unit': '%'}]...
'Get the stats.'
def get(self):
return self.bat_list
'Get batteries capacity percent.'
@property def battery_percent(self):
if ((not batinfo_tag) or (not self.bat.stat)): return [] bsum = 0 for b in self.bat.stat: try: bsum += int(b.capacity) except ValueError: return [] return int((bsum / len(self.bat.stat)))
'Init the plugin.'
def __init__(self, args=None, config=None):
super(Plugin, self).__init__(args=args) self.args = args self.config = config self.display_curse = True self.glances_amps = glancesAmpsList(self.args, self.config) self.reset()
'Reset/init the stats.'
def reset(self):
self.stats = []
'Update the AMP list.'
@GlancesPlugin._check_decorator @GlancesPlugin._log_result_decorator def update(self):
self.reset() if (self.input_method == 'local'): for (k, v) in iteritems(self.glances_amps.update()): self.stats.append({'key': k, 'name': v.NAME, 'result': v.result(), 'refresh': v.refresh(), 'timer': v.time_until_refresh(), 'count': v.count(), 'countmin': v.count_min(), 'countmax': v.count_...
'Return the alert status relative to the process number.'
def get_alert(self, nbprocess=0, countmin=None, countmax=None, header='', log=False):
if (nbprocess is None): return 'OK' if (countmin is None): countmin = nbprocess if (countmax is None): countmax = nbprocess if (nbprocess > 0): if (int(countmin) <= int(nbprocess) <= int(countmax)): return 'OK' else: return 'WARNING' el...
'Return the dict to display in the curse interface.'
def msg_curse(self, args=None):
ret = [] if ((not self.stats) or args.disable_process or self.is_disable()): return ret for m in self.stats: if (m['result'] is None): continue first_column = '{}'.format(m['name']) first_column_style = self.get_alert(m['count'], m['countmin'], m['countmax']) ...
'Load the server list from the configuration file.'
def load(self, config):
server_list = [] if (config is None): logger.debug('No configuration file available. Cannot load server list.') elif (not config.has_section(self._section)): logger.warning(('No [%s] section in the configuration file. Cannot load server list...
'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
'Load the web list from the configuration file.'
def load(self, config):
web_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.' % se...
'Return the current server list (dict of dict).'
def get_web_list(self):
return self._web_list
'Set the key to the value for the pos (position in the list).'
def set_server(self, pos, key, value):
self._web_list[pos][key] = value
'Build the results.'
def __buid_result(self, varBinds):
ret = {} for (name, val) in varBinds: if (str(val) == ''): ret[name.prettyPrint()] = '' else: ret[name.prettyPrint()] = val.prettyPrint() if ret[name.prettyPrint()].startswith("b'"): ret[name.prettyPrint()] = ret[name.prettyPrint()][2:(-1)] ...
'Put results in table.'
def __get_result__(self, errorIndication, errorStatus, errorIndex, varBinds):
ret = {} if ((not errorIndication) or (not errorStatus)): ret = self.__buid_result(varBinds) return ret
'SNMP simple request (list of OID). One request per OID list. * oid: oid list > Return a dict'
def get_by_oid(self, *oid):
if (self.version == '3'): (errorIndication, errorStatus, errorIndex, varBinds) = self.cmdGen.getCmd(cmdgen.UsmUserData(self.user, self.auth), cmdgen.UdpTransportTarget((self.host, self.port)), *oid) else: (errorIndication, errorStatus, errorIndex, varBinds) = self.cmdGen.getCmd(cmdgen.CommunityD...
'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. * max_repetitions: This specifies the max...
def getbulk_by_oid(self, non_repeaters, max_repetitions, *oid):
if self.version.startswith('3'): (errorIndication, errorStatus, errorIndex, varBinds) = self.cmdGen.getCmd(cmdgen.UsmUserData(self.user, self.auth), cmdgen.UdpTransportTarget((self.host, self.port)), non_repeaters, max_repetitions, *oid) if self.version.startswith('2'): (errorIndication, errorSt...
'Main loop for the Web server.'
def serve_forever(self):
self.web.start(self.stats)
'End of the Web server.'
def end(self):
self.web.end() self.stats.end()
'Load server and password list from the confiuration file.'
def load(self):
self.static_server = GlancesStaticServer(config=self.config) self.password = GlancesPassword(config=self.config)
'Return the current server list (list of dict). Merge of static + autodiscover servers list.'
def get_servers_list(self):
ret = [] if self.args.browser: ret = self.static_server.get_servers_list() if (self.autodiscover_server is not None): ret = (self.static_server.get_servers_list() + self.autodiscover_server.get_servers_list()) return ret
'Return the URI for the given server dict.'
def __get_uri(self, server):
if (server['password'] != ''): if (server['status'] == 'PROTECTED'): clear_password = self.password.get_password(server['name']) if (clear_password is not None): server['password'] = self.password.sha256_hash(clear_password) return 'http://{}:{}@{}:{}'.format(...
'Update stats for the given server (picked from the server list)'
def __update_stats(self, server):
uri = self.__get_uri(server) t = GlancesClientTransport() t.set_timeout(3) try: s = ServerProxy(uri, transport=t) except Exception as e: logger.warning("Client browser couldn't create socket {}: {}".format(uri, e)) else: try: cpu_percent = (1...
'Connect and display the given server'
def __display_server(self, server):
logger.debug('Selected server: {}'.format(server)) self.screen.display_popup('Connect to {}:{}'.format(server['name'], server['port']), duration=1) if (server['password'] is None): clear_password = self.password.get_password(server['name']) if ((clear_password is None) or (self.g...
'Main client loop.'
def __serve_forever(self):
while True: logger.debug('Iter through the following server list: {}'.format(self.get_servers_list())) for v in self.get_servers_list(): thread = threading.Thread(target=self.__update_stats, args=[v]) thread.start() if (self.screen.active_server is N...
'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):
try: return self.__serve_forever() finally: self.end()
'Set the (key, value) for the selected server in the list.'
def set_in_selected(self, key, value):
if (self.screen.active_server >= len(self.static_server.get_servers_list())): self.autodiscover_server.set_server((self.screen.active_server - len(self.static_server.get_servers_list())), key, value) else: self.static_server.set_server(self.screen.active_server, key, value)
'End of the client browser session.'
def end(self):
self.screen.end()
'Init the AMP.'
def __init__(self, name=None, args=None):
self.NAME = name.capitalize() super(Amp, self).__init__(name=name, args=args)
'Update the AMP'
def update(self, process_list):
logger.debug('{}: Update stats using service {}'.format(self.NAME, self.get('service_cmd'))) try: res = self.get('command') except OSError as e: logger.debug('{}: Error while executing service ({})'.format(self.NAME, e)) else: if (res is not None): ...
'Init AMP classe.'
def __init__(self, name=None, args=None):
logger.debug('Init {} version {}'.format(self.NAME, self.VERSION)) if (name is None): self.amp_name = self.__class__.__module__[len('glances_'):] else: self.amp_name = name self.args = args self.configs = {} self.timer = Timer(0)
'Load AMP parameters from the configuration file.'
def load_config(self, config):
amp_section = ('amp_' + self.amp_name) if (hasattr(config, 'has_section') and config.has_section(amp_section)): logger.debug('{}: Load configuration'.format(self.NAME)) for (param, _) in config.items(amp_section): try: self.configs[param] = config.get_float_valu...
'Generic method to get the item in the AMP configuration'
def get(self, key):
if (key in self.configs): return self.configs[key] else: return None
'Return True|False if the AMP is enabled in the configuration file (enable=true|false).'
def enable(self):
ret = self.get('enable') if (ret is None): return False else: return ret.lower().startswith('true')
'Return regular expression used to identified the current application.'
def regex(self):
return self.get('regex')
'Return refresh time in seconds for the current application monitoring process.'
def refresh(self):
return self.get('refresh')
'Return True|False if the AMP shoukd be displayed in oneline (one_lineline=true|false).'
def one_line(self):
ret = self.get('one_line') if (ret is None): return False else: return ret.lower().startswith('true')
'Return time in seconds until refresh.'
def time_until_refresh(self):
return self.timer.get()
'Return True is the AMP should be updated: - AMP is enable - only update every \'refresh\' seconds'
def should_update(self):
if self.timer.finished(): self.timer.set(self.refresh()) self.timer.reset() return self.enable() return False
'Set the number of processes matching the regex'
def set_count(self, count):
self.configs['count'] = count
'Get the number of processes matching the regex'
def count(self):
return self.get('count')
'Get the minimum number of processes'
def count_min(self):
return self.get('countmin')
'Get the maximum number of processes'
def count_max(self):
return self.get('countmax')
'Store the result (string) into the result key of the AMP if one_line is true then replace by separator'
def set_result(self, result, separator=''):
if self.one_line(): self.configs['result'] = str(result).replace('\n', separator) else: self.configs['result'] = str(result)
'Return the result of the AMP (as a string)'
def result(self):
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):
self.set_count(len(process_list)) if self.should_update(): return self.update(process_list) else: return self.result()
'Update the AMP'
def update(self, process_list):
logger.debug('{}: Update stats using status URL {}'.format(self.NAME, self.get('status_url'))) res = requests.get(self.get('status_url')) if res.ok: self.set_result(res.text.rstrip()) else: logger.debug('{}: Can not grab status URL {} ({})'.format(s...
'Update the AMP'
def update(self, process_list):
logger.debug('{}: Update stats using service {}'.format(self.NAME, self.get('service_cmd'))) try: res = check_output(self.get('service_cmd').split(), stderr=STDOUT).decode('utf-8') except OSError as e: logger.debug('{}: Error while executing service ({})'.format...