How to use the glances.compat.range function in Glances

To help you get started, we’ve selected a few Glances examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nicolargo / glances / glances / plugins / sensors / glances_hddtemp.py View on Github external
# 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)
github nicolargo / glances / glances / exports / glances_riemann.py View on Github external
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)
github nicolargo / glances / glances / exports / glances_statsd.py View on Github external
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(normalize(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))
github nicolargo / glances / glances / monitor_list.py View on Github external
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)
github nicolargo / glances / glances / web_list.py View on Github external
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,
github nicolargo / glances / glances / folder_list.py View on Github external
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()
github nicolargo / glances / glances / events.py View on Github external
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
github nicolargo / glances / glances / monitor_list.py View on Github external
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 = 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: