Beispiel #1
0
    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: {}".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 {} threshold for folder {}".format(
                        i, value["path"]))

            # Add the item to the list
            self.__folder_list.append(value)
Beispiel #2
0
    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
Beispiel #3
0
 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))
Beispiel #4
0
    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
Beispiel #5
0
    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)
Beispiel #6
0
 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))
Beispiel #7
0
 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)
Beispiel #8
0
 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)
Beispiel #9
0
    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
Beispiel #10
0
    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