def test_015_subsample(self): """Test subsampling function.""" print('INFO: [TEST_015] Subsampling') for l in [([1, 2, 3], 4), ([1, 2, 3, 4], 4), ([1, 2, 3, 4, 5, 6, 7], 4), ([1, 2, 3, 4, 5, 6, 7, 8], 4), (list(range(1, 800)), 4), (list(range(1, 8000)), 800)]: l_subsample = subsample(l[0], l[1]) self.assertLessEqual(len(l_subsample), l[1])
def update(self): """Update the command result attributed.""" # Only continue if monitor list is not empty if len(self.__folder_list) == 0: return self.__folder_list # Iter upon the folder list for i in range(len(self.get())): # Update folder size if not self.first_grab and not self.timer_folders[i].finished(): continue # Get folder size try: self.__folder_list[i]['size'] = self.__folder_size( self.path(i)) except OSError as e: logger.debug('Cannot get folder size ({}). Error: {}'.format( self.path(i), e)) if e.errno == 13: # Permission denied self.__folder_list[i]['size'] = '!' else: self.__folder_list[i]['size'] = '?' # Reset the timer self.timer_folders[i].reset() # It is no more the first time... self.first_grab = False return self.__folder_list
def __set_monitor_list(self, section, key): """Init the monitored processes list. The list is defined in the Glances configuration file. """ for l in range(1, self.__monitor_list_max_size + 1): value = {} key = "list_" + str(l) + "_" try: description = self.config.get_value(section, key + "description") regex = self.config.get_value(section, key + "regex") command = self.config.get_value(section, key + "command") countmin = self.config.get_value(section, key + "countmin") countmax = self.config.get_value(section, key + "countmax") except Exception as e: logger.error("Cannot read monitored list: {0}".format(e)) else: if description is not None and regex is not None: # Build the new item value["description"] = description try: re.compile(regex) except Exception: continue else: value["regex"] = regex value["command"] = command value["countmin"] = countmin value["countmax"] = countmax value["count"] = None value["result"] = None # Add the item to the list self.__monitor_list.append(value)
def __set_folder_list(self, section): """Init the monitored folder list. The list is defined in the Glances configuration file. """ for l in range(1, self.__folder_list_max_size + 1): value = {} key = 'folder_' + str(l) + '_' # Path is mandatory try: value['path'] = self.config.get_value(section, key + 'path') except Exception as e: logger.error("Cannot read folder list: {0}".format(e)) continue if value['path'] is None: continue # Optional conf keys for i in ['careful', 'warning', 'critical']: try: value[i] = self.config.get_value(section, key + i) except: value[i] = None logger.debug("No {0} threshold for folder {1}".format( i, value["path"])) # Add the item to the list self.__folder_list.append(value)
def __set_folder_list(self, section): """Init the monitored folder list. The list is defined in the Glances configuration file. """ for l in range(1, self.__folder_list_max_size + 1): value = {} key = 'folder_' + str(l) + '_' # Path is mandatory value['indice'] = str(l) value['path'] = self.config.get_value(section, key + 'path') if value['path'] is None: continue else: value['path'] = nativestr(value['path']) # Optional conf keys for i in ['careful', 'warning', 'critical']: # Read threshold value[i] = self.config.get_value(section, key + i) if value[i] is not None: logger.debug("{} threshold for folder {} is {}".format(i, value["path"], value[i])) # Read action action = self.config.get_value(section, key + i + '_action') if action is not None: value[i + '_action'] = action logger.debug("{} action for folder {} is {}".format(i, value["path"], value[i + '_action'])) # Add the item to the list self.__folder_list.append(value)
def __set_folder_list(self, section): """Init the monitored folder list. The list is defined in the Glances configuration file. """ for l in range(1, self.__folder_list_max_size + 1): value = {} key = 'folder_' + str(l) + '_' # Path is mandatory value['path'] = self.config.get_value(section, key + 'path') if value['path'] is None: continue else: value['path'] = nativestr(value['path']) # Optional conf keys for i in ['careful', 'warning', 'critical']: value[i] = self.config.get_value(section, key + i) if value[i] is None: logger.debug("No {} threshold for folder {}".format( i, value["path"])) # Add the item to the list self.__folder_list.append(value)
def __set_folder_list(self, section): """Init the monitored folder list. The list is defined in the Glances configuration file. """ for l in range(1, self.__folder_list_max_size + 1): value = {} key = 'folder_' + str(l) + '_' # Path is mandatory try: value['path'] = self.config.get_value(section, key + 'path') except Exception as e: logger.error("Cannot read folder list: {0}".format(e)) continue if value['path'] is None: continue # Optional conf keys for i in ['careful', 'warning', 'critical']: try: value[i] = self.config.get_value(section, key + i) except: value[i] = None logger.debug("No {0} threshold for folder {1}".format(i, value["path"])) # Add the item to the list self.__folder_list.append(value)
def __set_monitor_list(self, section, key): """Init the monitored processes list. The list is defined in the Glances configuration file. """ for l in range(1, self.__monitor_list_max_size + 1): value = {} key = "list_" + str(l) + "_" try: description = self.config.get_value(section, key + 'description') regex = self.config.get_value(section, key + 'regex') command = self.config.get_value(section, key + 'command') countmin = self.config.get_value(section, key + 'countmin') countmax = self.config.get_value(section, key + 'countmax') except Exception as e: logger.error("Cannot read monitored list: {0}".format(e)) else: if description is not None and regex is not None: # Build the new item value["description"] = description try: re.compile(regex) except Exception: continue else: value["regex"] = regex value["command"] = command value["countmin"] = countmin value["countmax"] = countmax value["count"] = None value["result"] = None # Add the item to the list self.__monitor_list.append(value)
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._section): logger.warning( "No [%s] section in the configuration file. Cannot load server list." % self._section) else: logger.info( "Start reading the [%s] section in the configuration file" % self._section) for i in range(1, 256): new_server = {} postfix = 'server_%s_' % str(i) # Read the server name (mandatory) for s in ['name', 'port', 'alias']: new_server[s] = config.get_value(self._section, '%s%s' % (postfix, s)) if new_server['name'] is not None: # Manage optionnal information if new_server['port'] is None: new_server['port'] = '61209' new_server['username'] = '******' # By default, try empty (aka no) password new_server['password'] = '' try: new_server['ip'] = gethostbyname(new_server['name']) except gaierror as e: logger.error( "Cannot get IP address for server %s (%s)" % (new_server['name'], e)) continue new_server[ 'key'] = new_server['name'] + ':' + new_server['port'] # Default status is 'UNKNOWN' new_server['status'] = 'UNKNOWN' # Server type is 'STATIC' new_server['type'] = 'STATIC' # Add the server to the list logger.debug("Add server %s to the static list" % new_server['name']) server_list.append(new_server) # Server list loaded logger.info("%s server(s) loaded from the configuration file" % len(server_list)) logger.debug("Static server list: %s" % server_list) return server_list
def __itemexist__(self, item_type): """Return the item position, if it exists. An item exist in the list if: * end is < 0 * item_type is matching Return -1 if the item is not found. """ for i in range(self.len()): if self.logs_list[i][1] < 0 and self.logs_list[i][3] == item_type: return i return -1
def export(self, name, columns, points): """Export the stats to the Statsd server.""" for i in range(len(columns)): if not isinstance(points[i], Number): continue stat_name = '{0}.{1}'.format(name, columns[i]) stat_value = points[i] try: self.client.gauge(stat_name, stat_value) except Exception as e: logger.error("Can not export stats to Statsd (%s)" % e) logger.debug("Export {0} stats to Statsd".format(name))
def __event_exist(self, event_type): """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. """ for i in range(self.len()): if self.events_list[i][1] < 0 and self.events_list[i][3] == event_type: return i return -1
def export(self, name, columns, points): """Export the stats to the Statsd server.""" 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(stat_name, stat_value) except Exception as e: logger.error("Can not export stats to Statsd (%s)" % e) logger.debug("Export {} stats to Statsd".format(name))
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 + " " + columns[i], 'metric': points[i]} logger.debug(data) try: self.client.send(data) except Exception as e: logger.error("Can not export stats to Riemann (%s)" % e)
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 + " " + columns[i], 'metric': points[i]} logger.debug(data) try: self.client.send(data) except Exception as e: logger.error("Cannot export stats to Riemann (%s)" % e)
def export(self, name, columns, points): """Write the points in RabbitMQ.""" 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]) logger.debug(data) try: self.client.basic_publish(exchange='', routing_key=self.queue, body=data) except Exception as e:
def export(self, name, columns, points): """Export the stats to the Statsd server.""" 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) except Exception as e: logger.error("Can not export stats %s to OpenTSDB (%s)" % (name, e)) logger.debug("Export {} stats to OpenTSDB".format(name))
def __update__(self): """Update the stats.""" # Reset the list self.reset() # Only update if --disable-hddtemp is not set if self.args is None or self.args.disable_hddtemp: return # Fetch the data # data = ("|/dev/sda|WDC WD2500JS-75MHB0|44|C|" # "|/dev/sdb|WDC WD2500JS-75MHB0|35|C|" # "|/dev/sdc|WDC WD3200AAKS-75B3A0|45|C|" # "|/dev/sdd|WDC WD3200AAKS-75B3A0|45|C|" # "|/dev/sde|WDC WD3200AAKS-75B3A0|43|C|" # "|/dev/sdf|???|ERR|*|" # "|/dev/sdg|HGST HTS541010A9E680|SLP|*|" # "|/dev/sdh|HGST HTS541010A9E680|UNK|*|") data = self.fetch() # Exit if no data if data == "": return # Safety check to avoid malformed data # Considering the size of "|/dev/sda||0||" as the minimum if len(data) < 14: data = self.cache if len(self.cache) > 0 else self.fetch() self.cache = data try: fields = data.split(b'|') except TypeError: fields = "" devices = (len(fields) - 1) // 5 for item in range(devices): offset = item * 5 hddtemp_current = {} device = os.path.basename(nativestr(fields[offset + 1])) temperature = fields[offset + 3] unit = nativestr(fields[offset + 4]) hddtemp_current['label'] = device try: hddtemp_current['value'] = float(temperature) except ValueError: # Temperature could be 'ERR', 'SLP' or 'UNK' (see issue #824) # Improper bytes/unicode in glances_hddtemp.py (see issue #887) hddtemp_current['value'] = nativestr(temperature) hddtemp_current['unit'] = unit self.hddtemp_list.append(hddtemp_current)
def export(self, name, columns, points): """Write the points in RabbitMQ.""" 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]) logger.debug(data) try: self.client.basic_publish(exchange='', routing_key=self.rabbitmq_queue, body=data) except Exception as e: logger.error("Can not export stats to RabbitMQ (%s)" % e)
def update(self): """Update the command result attributed.""" # Only continue if monitor list is not empty if len(self.__monitor_list) == 0: return self.__monitor_list # Search monitored processes by a regular expression processlist = [p for p in glances_processes.getalllist()] # Iter upon the monitored list for i in range(len(self.get())): monitoredlist = [ p for p in processlist for c in p['cmdline'] if re.search(self.regex(i), c) is not None ] self.__monitor_list[i]['count'] = len(monitoredlist) # Always get processes CPU and MEM self.__monitor_list[i][ 'default_result'] = 'CPU: {0:.1f}% | MEM: {1:.1f}%'.format( sum([p['cpu_percent'] for p in monitoredlist]), sum([p['memory_percent'] for p in monitoredlist])) if self.command(i) is not None: # Execute the user command line try: self.__monitor_list[i]['result'] = subprocess.check_output( self.command(i), shell=True) except subprocess.CalledProcessError: self.__monitor_list[i][ 'result'] = 'Error: ' + self.command(i) except Exception: self.__monitor_list[i]['result'] = 'Cannot execute command' # Only save the first line try: self.__monitor_list[i]['result'] = u( self.__monitor_list[i]['result']).split('\n')[0] except: self.__monitor_list[i]['result'] = '' if self.command( i) is None or self.__monitor_list[i]['result'] == '': # If there is no command specified in the conf file # then display CPU and MEM % self.__monitor_list[i]['result'] = self.__monitor_list[i][ 'default_result'] return self.__monitor_list
def update(self): """Update the command result attributed.""" # Only continue if monitor list is not empty if len(self.__folder_list) == 0: return self.__folder_list # Iter upon the folder list for i in range(len(self.get())): # Update folder size try: self.__folder_list[i]['size'] = self.__folder_size(self.path(i)) except Exception as e: self.__folder_list[i]['size'] = None logger.debug('Can get folder size ({0}). Error: {1}'.format(self.path(i), e)) return self.__folder_list
def load(self, config): """Load the server list from the configuration file.""" server_list = [] if config is None: logger.warning("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." % self._section) else: logger.info("Start reading the [%s] section in the configuration file" % self._section) for i in range(1, 256): new_server = {} postfix = "server_%s_" % str(i) # Read the server name (mandatory) for s in ["name", "port", "alias"]: new_server[s] = config.get_value(self._section, "%s%s" % (postfix, s)) if new_server["name"] is not None: # Manage optionnal information if new_server["port"] is None: new_server["port"] = "61209" new_server["username"] = "******" # By default, try empty (aka no) password new_server["password"] = "" try: new_server["ip"] = gethostbyname(new_server["name"]) except gaierror as e: logger.error("Cannot get IP address for server %s (%s)" % (new_server["name"], e)) continue new_server["key"] = new_server["name"] + ":" + new_server["port"] # Default status is 'UNKNOWN' new_server["status"] = "UNKNOWN" # Server type is 'STATIC' new_server["type"] = "STATIC" # Add the server to the list logger.debug("Add server %s to the static list" % new_server["name"]) server_list.append(new_server) # Server list loaded logger.info("%s server(s) loaded from the configuration file" % len(server_list)) logger.debug("Static server list: %s" % server_list) return server_list
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._section): logger.warning("No [%s] section in the configuration file. Cannot load server list." % self._section) else: logger.info("Start reading the [%s] section in the configuration file" % self._section) for i in range(1, 256): new_server = {} postfix = 'server_%s_' % str(i) # Read the server name (mandatory) for s in ['name', 'port', 'alias']: new_server[s] = config.get_value(self._section, '%s%s' % (postfix, s)) if new_server['name'] is not None: # Manage optionnal information if new_server['port'] is None: new_server['port'] = '61209' new_server['username'] = '******' # By default, try empty (aka no) password new_server['password'] = '' try: new_server['ip'] = gethostbyname(new_server['name']) except gaierror as e: logger.error("Cannot get IP address for server %s (%s)" % (new_server['name'], e)) continue new_server['key'] = new_server['name'] + ':' + new_server['port'] # Default status is 'UNKNOWN' new_server['status'] = 'UNKNOWN' # Server type is 'STATIC' new_server['type'] = 'STATIC' # Add the server to the list logger.debug("Add server %s to the static list" % new_server['name']) server_list.append(new_server) # Server list loaded logger.info("%s server(s) loaded from the configuration file" % len(server_list)) logger.debug("Static server list: %s" % server_list) return server_list
def update(self): """Update the command result attributed.""" # Only continue if monitor list is not empty if len(self.__folder_list) == 0: return self.__folder_list # Iter upon the folder list for i in range(len(self.get())): # Update folder size try: self.__folder_list[i]['size'] = self.__folder_size( self.path(i)) except Exception as e: self.__folder_list[i]['size'] = None logger.debug('Can get folder size ({0}). Error: {1}'.format( self.path(i), e)) return self.__folder_list
def update(self): """Update the command result attributed.""" # Only continue if monitor list is not empty if len(self.__folder_list) == 0: return self.__folder_list # Iter upon the folder list for i in range(len(self.get())): # Update folder size try: self.__folder_list[i]['size'] = self.__folder_size(self.path(i)) except OSError as e: logger.debug('Cannot get folder size ({}). Error: {}'.format(self.path(i), e)) if e.errno == 13: # Permission denied self.__folder_list[i]['size'] = '!' else: self.__folder_list[i]['size'] = '?' return self.__folder_list
def update(self): """Update the command result attributed.""" # Only continue if monitor list is not empty if len(self.__folder_list) == 0: return self.__folder_list # Iter upon the folder list for i in range(len(self.get())): # Update folder size try: self.__folder_list[i]['size'] = self.__folder_size(self.path(i)) except Exception as e: logger.debug('Cannot get folder size ({}). Error: {}'.format(self.path(i), e)) if e.errno == 13: # Permission denied self.__folder_list[i]['size'] = '!' else: self.__folder_list[i]['size'] = '?' return self.__folder_list
def update(self): """Update the command result attributed.""" # Only continue if monitor list is not empty if len(self.__monitor_list) == 0: return self.__monitor_list # Search monitored processes by a regular expression processlist = [p for p in glances_processes.getalllist()] # Iter upon the monitored list for i in range(len(self.get())): monitoredlist = [p for p in processlist for c in p["cmdline"] if re.search(self.regex(i), c) is not None] self.__monitor_list[i]["count"] = len(monitoredlist) # Always get processes CPU and MEM self.__monitor_list[i]["default_result"] = "CPU: {0:.1f}% | MEM: {1:.1f}%".format( sum([p["cpu_percent"] for p in monitoredlist]), sum([p["memory_percent"] for p in monitoredlist]) ) if self.command(i) is not None: # Execute the user command line try: self.__monitor_list[i]["result"] = subprocess.check_output(self.command(i), shell=True) except subprocess.CalledProcessError: self.__monitor_list[i]["result"] = "Error: " + self.command(i) except Exception: self.__monitor_list[i]["result"] = "Cannot execute command" # Only save the first line try: self.__monitor_list[i]["result"] = u(self.__monitor_list[i]["result"]).split("\n")[0] except: self.__monitor_list[i]["result"] = "" if self.command(i) is None or self.__monitor_list[i]["result"] == "": # If there is no command specified in the conf file # then display CPU and MEM % self.__monitor_list[i]["result"] = self.__monitor_list[i]["default_result"] return self.__monitor_list
def __set_folder_list(self, section): """Init the monitored folder list. The list is defined in the Glances configuration file. """ for l in range(1, self.__folder_list_max_size + 1): value = {} key = 'folder_' + str(l) + '_' # Path is mandatory value['indice'] = str(l) value['path'] = self.config.get_value(section, key + 'path') if value['path'] is None: continue else: value['path'] = nativestr(value['path']) # Optional conf keys # Refresh time value['refresh'] = int( self.config.get_value(section, key + 'refresh', default=self.__default_refresh)) self.timer_folders.append(Timer(value['refresh'])) # Thesholds for i in ['careful', 'warning', 'critical']: # Read threshold value[i] = self.config.get_value(section, key + i) if value[i] is not None: logger.debug("{} threshold for folder {} is {}".format( i, value["path"], value[i])) # Read action action = self.config.get_value(section, key + i + '_action') if action is not None: value[i + '_action'] = action logger.debug("{} action for folder {} is {}".format( i, value["path"], value[i + '_action'])) # Add the item to the list self.__folder_list.append(value)
def __update__(self): """Update the stats.""" # Reset the list self.reset() # Only update if --disable-hddtemp is not set if self.args is None or self.args.disable_hddtemp: return # Fetch the data data = self.fetch() # Exit if no data if data == "": return # Safety check to avoid malformed data # Considering the size of "|/dev/sda||0||" as the minimum if len(data) < 14: data = self.cache if len(self.cache) > 0 else self.fetch() self.cache = data try: fields = data.split(b'|') except TypeError: fields = "" devices = (len(fields) - 1) // 5 for item in range(devices): offset = item * 5 hddtemp_current = {} device = os.path.basename(nativestr(fields[offset + 1])) temperature = fields[offset + 3] unit = nativestr(fields[offset + 4]) hddtemp_current['label'] = device # Temperature could be 'ERR' or 'SLP' (see issue#824) hddtemp_current['value'] = float(temperature) if isinstance(temperature, numbers.Number) else temperature hddtemp_current['unit'] = unit self.hddtemp_list.append(hddtemp_current)
def __update__(self): """Update the stats.""" # Reset the list self.reset() # Only update if --disable-hddtemp is not set if self.args is None or self.args.disable_hddtemp: return # Fetch the data data = self.fetch() # Exit if no data if data == "": return # Safety check to avoid malformed data # Considering the size of "|/dev/sda||0||" as the minimum if len(data) < 14: data = self.cache if len(self.cache) > 0 else self.fetch() self.cache = data try: fields = data.split(b'|') except TypeError: fields = "" devices = (len(fields) - 1) // 5 for item in range(devices): offset = item * 5 hddtemp_current = {} device = os.path.basename(nativestr(fields[offset + 1])) temperature = fields[offset + 3] unit = nativestr(fields[offset + 4]) hddtemp_current['label'] = device hddtemp_current['value'] = float( temperature) if temperature != b'ERR' else temperature hddtemp_current['unit'] = unit self.hddtemp_list.append(hddtemp_current)
def load(self, config): """Load the ports list from the configuration file.""" 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." % self._section) else: logger.debug("Start reading the [%s] section in the configuration file" % self._section) refresh = int(config.get_value(self._section, 'refresh', default=self._default_refresh)) timeout = int(config.get_value(self._section, 'timeout', default=self._default_timeout)) # Add default gateway on top of the ports_list lits default_gateway = config.get_value(self._section, 'port_default_gateway', default='False') if default_gateway.lower().startswith('true') and netifaces_tag: new_port = {} try: new_port['host'] = netifaces.gateways()['default'][netifaces.AF_INET][0] except KeyError: new_port['host'] = None # ICMP new_port['port'] = 0 new_port['description'] = 'DefaultGateway' new_port['refresh'] = refresh new_port['timeout'] = timeout new_port['status'] = None new_port['rtt_warning'] = None logger.debug("Add default gateway %s to the static list" % (new_port['host'])) ports_list.append(new_port) # Read the scan list for i in range(1, 256): new_port = {} postfix = 'port_%s_' % str(i) # Read mandatories configuration key: host new_port['host'] = config.get_value(self._section, '%s%s' % (postfix, 'host')) if new_port['host'] is None: continue # Read optionals configuration keys # Port is set to 0 by default. 0 mean ICMP check instead of TCP check new_port['port'] = config.get_value(self._section, '%s%s' % (postfix, 'port'), 0) new_port['description'] = config.get_value(self._section, '%sdescription' % postfix, default="%s:%s" % (new_port['host'], new_port['port'])) # Default status new_port['status'] = None # Refresh rate in second new_port['refresh'] = refresh # Timeout in second new_port['timeout'] = int(config.get_value(self._section, '%stimeout' % postfix, default=timeout)) # RTT warning new_port['rtt_warning'] = config.get_value(self._section, '%srtt_warning' % postfix, default=None) if new_port['rtt_warning'] is not None: # Convert to second new_port['rtt_warning'] = int(new_port['rtt_warning']) / 1000.0 # Add the server to the list logger.debug("Add port %s:%s to the static list" % (new_port['host'], new_port['port'])) ports_list.append(new_port) # Ports list loaded logger.debug("Ports list loaded: %s" % ports_list) return ports_list
def load(self, config): """Load the ports list from the configuration file.""" 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." % self._section) else: logger.debug("Start reading the [%s] section in the configuration file" % self._section) refresh = int(config.get_value(self._section, 'refresh', default=self._default_refresh)) timeout = int(config.get_value(self._section, 'timeout', default=self._default_timeout)) # Add default gateway on top of the ports_list lits default_gateway = config.get_value(self._section, 'port_default_gateway', default='False') if default_gateway.lower().startswith('true') and netifaces_tag: new_port = {} new_port['host'] = netifaces.gateways()['default'][netifaces.AF_INET][0] # ICMP new_port['port'] = 0 new_port['description'] = 'DefaultGateway' new_port['refresh'] = refresh new_port['timeout'] = timeout new_port['status'] = None new_port['rtt_warning'] = None logger.debug("Add default gateway %s to the static list" % (new_port['host'])) ports_list.append(new_port) # Read the scan list for i in range(1, 256): new_port = {} postfix = 'port_%s_' % str(i) # Read mandatories configuration key: host new_port['host'] = config.get_value(self._section, '%s%s' % (postfix, 'host')) if new_port['host'] is None: continue # Read optionals configuration keys # Port is set to 0 by default. 0 mean ICMP check instead of TCP check new_port['port'] = config.get_value(self._section, '%s%s' % (postfix, 'port'), 0) new_port['description'] = config.get_value(self._section, '%sdescription' % postfix, default="%s:%s" % (new_port['host'], new_port['port'])) # Default status new_port['status'] = None # Refresh rate in second new_port['refresh'] = refresh # Timeout in second new_port['timeout'] = int(config.get_value(self._section, '%stimeout' % postfix, default=timeout)) # RTT warning new_port['rtt_warning'] = config.get_value(self._section, '%srtt_warning' % postfix, default=None) if new_port['rtt_warning'] is not None: # Convert to second new_port['rtt_warning'] = int(new_port['rtt_warning']) / 1000.0 # Add the server to the list logger.debug("Add port %s:%s to the static list" % (new_port['host'], new_port['port'])) ports_list.append(new_port) # Ports list loaded logger.debug("Ports list loaded: %s" % ports_list) return ports_list
def load(self, config): """Load the web list from the configuration file.""" 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." % self._section) else: logger.debug("Start reading the [%s] section in the configuration file" % self._section) refresh = int(config.get_value(self._section, 'refresh', default=self._default_refresh)) timeout = int(config.get_value(self._section, 'timeout', default=self._default_timeout)) # Read the web/url list for i in range(1, 256): new_web = {} postfix = 'web_%s_' % str(i) # Read mandatories configuration key: host new_web['url'] = config.get_value(self._section, '%s%s' % (postfix, 'url')) if new_web['url'] is None: continue url_parse = urlparse(new_web['url']) if not bool(url_parse.scheme) or not bool(url_parse.netloc): logger.error('Bad URL (%s) in the [%s] section of configuration file.' % (new_web['url'], self._section)) continue # Read optionals configuration keys # Default description is the URL without the http:// new_web['description'] = config.get_value(self._section, '%sdescription' % postfix, default="%s" % url_parse.netloc) # Default status new_web['status'] = None new_web['elapsed'] = 0 # Refresh rate in second new_web['refresh'] = refresh # Timeout in second new_web['timeout'] = int(config.get_value(self._section, '%stimeout' % postfix, default=timeout)) # RTT warning new_web['rtt_warning'] = config.get_value(self._section, '%srtt_warning' % postfix, default=None) if new_web['rtt_warning'] is not None: # Convert to second new_web['rtt_warning'] = int(new_web['rtt_warning']) / 1000.0 # Add the server to the list logger.debug("Add Web URL %s to the static list" % new_web['url']) web_list.append(new_web) # Ports list loaded logger.debug("Web list loaded: %s" % web_list) return web_list