Collect metrics from all registered metric sets
        :return:
515951
def collect(self):
        
        logger.debug("Collecting metrics")

        for name, metricset in compat.iteritems(self._metricsets):
            data = metricset.collect()
            if data:
                self._queue_func(constants.METRICSET, data)
1056119
def collect(self):
        
        if not os.access(self.PROC, os.R_OK):
            return False

        # Open PROC file
        file = open(self.PROC, 'r')

        # Get data
        for line in file:
            if line.startswith('slabinfo'):
                continue

            if line.startswith('#'):
                keys = line.split()[1:]
                continue

            data = line.split()

            for key in ['<active_objs>', '<num_objs>', '<objsize>',
                        '<objperslab>', '<pagesperslab>']:
                i = keys.index(key)
                metric_name = data[0] + '.' + key.replace(
                    '<', '').replace('>', '')
                metric_value = int(data[i])
                self.publish(metric_name, metric_value)

            for key in ['<limit>', '<batchcount>', '<sharedfactor>']:
                i = keys.index(key)
                metric_name = data[0] + '.tunables.' + key.replace(
                    '<', '').replace('>', '')
                metric_value = int(data[i])
                self.publish(metric_name, metric_value)

            for key in ['<active_slabs>', '<num_slabs>', '<sharedavail>']:
                i = keys.index(key)
                metric_name = data[0] + '.slabdata.' + key.replace(
                    '<', '').replace('>', '')
                metric_value = int(data[i])
                self.publish(metric_name, metric_value)

        # Close file
        file.close()
210389
def collect(self):
        

        if psutil is None:
            self.log.error('Unable to import module psutil')
            return {}

        for port_name, port_cfg in self.ports.iteritems():
            port = int(port_cfg['number'])
            stats = get_port_stats(port)

            for stat_name, stat_value in stats.iteritems():
                metric_name = '%s.%s' % (port_name, stat_name)
                self.publish(metric_name, stat_value)
266599
def _match_metric(self, metric):
        
        if len(self._compiled_filters) == 0:
            return True
        for (collector, filter_regex) in self._compiled_filters:
            if collector != metric.getCollectorPath():
                continue
            if filter_regex.match(metric.getMetricPath()):
                return True
        return False
748241
def get_metrics(self, start, end, period):
        """"""
        values = {}
        default_dimensions = {
            'Policy': self.policy.name, 'ResType': self.policy.resource_type,
            'Scope': 'Policy'}

        metrics = list(self.POLICY_METRICS)

        # Support action, and filter custom metrics
        for el in itertools.chain(
                self.policy.resource_manager.actions,
                self.policy.resource_manager.filters):
            if el.metrics:
                metrics.extend(el.metrics)

        session = utils.local_session(self.policy.session_factory)
        client = session.client('cloudwatch')

        for m in metrics:
            if isinstance(m, six.string_types):
                dimensions = default_dimensions
            else:
                m, m_dimensions = m
                dimensions = dict(default_dimensions)
                dimensions.update(m_dimensions)
            results = client.get_metric_statistics(
                Namespace=DEFAULT_NAMESPACE,
                Dimensions=[
                    {'Name': k, 'Value': v} for k, v
                    in dimensions.items()],
                Statistics=['Sum', 'Average'],
                StartTime=start,
                EndTime=end,
                Period=period,
                MetricName=m)
            values[m] = results['Datapoints']
        return values
199662
def _collect_monitor_metrics(self, conn, tags):
        
        for entry in conn.entries:
            # Get metrics from monitor backend
            dn = entry.entry_dn.lower()
            if dn.endswith(self.CONNECTIONS_METRICS_DN):
                self._handle_connections_entry(entry, tags)
            elif dn.endswith(self.OPERATIONS_METRICS_DN):
                self._handle_operations_entry(entry, tags)
            elif dn.endswith(self.STATISTICS_METRICS_DN):
                self._handle_statistics_entry(entry, tags)
            elif dn.endswith(self.THREADS_METRICS_DN):
                self._handle_threads_entry(entry, tags)
            elif dn.endswith(self.TIME_METRICS_DN):
                self._handle_time_entry(entry, tags)
            elif dn.endswith(self.WAITERS_METRICS_DN):
                self._handle_waiters_entry(entry, tags)
361325
protected List<Metric> filter(List<Metric> metrics) {
    final List<Metric> filtered = metrics.stream().filter(this::shouldIncludeMetric)
        .collect(Collectors.toList());
    LOGGER.debug("Filter: input {} metrics, output {} metrics",
        metrics.size(), filtered.size());
    return filtered;
  }
595743
def list_metrics(ctx):
    """"""
    config = ctx.obj["CONFIG"]

    if not exists(config):
        handle_no_cache(ctx)

    from wily.commands.list_metrics import list_metrics

    list_metrics()
895937
def metrics(self) -> list:
        
        my_metrics = [
            FramesMetric("frames"),
            FPSMetric("fps"),
            EpisodeRewardMetric('PMM:episode_rewards'),
            EpisodeRewardMetricQuantile('P09:episode_rewards', quantile=0.9),
            EpisodeRewardMetricQuantile('P01:episode_rewards', quantile=0.1),
            EpisodeLengthMetric("episode_length")
        ]

        return my_metrics + self.algo.metrics() + self.env_roller.metrics()
1163123
def make_multi_metric(*metrics):
    
    def multi_metric(name, count, elapsed):
        """Calls multiple metrics (closure)"""
        for m in metrics:
            m(name, count, elapsed)
    return multi_metric
731646
def collect_metrics(self):
        
        try:
            g = None
            u = resource.getrusage(resource.RUSAGE_SELF)
            if gc_.isenabled():
                c = list(gc_.get_count())
                th = list(gc_.get_threshold())
                g = GC(collect0=c[0] if not self.last_collect else c[0] - self.last_collect[0],
                       collect1=c[1] if not self.last_collect else c[
                           1] - self.last_collect[1],
                       collect2=c[2] if not self.last_collect else c[
                           2] - self.last_collect[2],
                       threshold0=th[0],
                       threshold1=th[1],
                       threshold2=th[2])

            thr = threading.enumerate()
            daemon_threads = [tr.daemon is True for tr in thr].count(True)
            alive_threads = [tr.daemon is False for tr in thr].count(True)
            dummy_threads = [type(tr) is threading._DummyThread for tr in thr].count(True)

            m = Metrics(ru_utime=u[0] if not self.last_usage else u[0] - self.last_usage[0],
                        ru_stime=u[1] if not self.last_usage else u[1] - self.last_usage[1],
                        ru_maxrss=u[2],
                        ru_ixrss=u[3],
                        ru_idrss=u[4],
                        ru_isrss=u[5],
                        ru_minflt=u[6] if not self.last_usage else u[6] - self.last_usage[6],
                        ru_majflt=u[7] if not self.last_usage else u[7] - self.last_usage[7],
                        ru_nswap=u[8] if not self.last_usage else u[8] - self.last_usage[8],
                        ru_inblock=u[9] if not self.last_usage else u[9] - self.last_usage[9],
                        ru_oublock=u[10] if not self.last_usage else u[10] - self.last_usage[10],
                        ru_msgsnd=u[11] if not self.last_usage else u[11] - self.last_usage[11],
                        ru_msgrcv=u[12] if not self.last_usage else u[12] - self.last_usage[12],
                        ru_nsignals=u[13] if not self.last_usage else u[13] - self.last_usage[13],
                        ru_nvcs=u[14] if not self.last_usage else u[14] - self.last_usage[14],
                        ru_nivcsw=u[15] if not self.last_usage else u[15] - self.last_usage[15],
                        alive_threads=alive_threads,
                        dummy_threads=dummy_threads,
                        daemon_threads=daemon_threads,
                        gc=g)

            self.last_usage = u
            if gc_.isenabled():
                self.last_collect = c

            return m
        except:
            logger.debug("collect_metrics", exc_info=True)
809879
def collect(self):
        
        lxc_metrics = ["memory.usage_in_bytes", "memory.limit_in_bytes"]
        if os.path.isdir(self.config["sys_path"]) is False:
            self.log.debug("sys_path '%s' isn't directory.",
                           self.config["sys_path"])
            return {}

        collected = {}
        for item in os.listdir(self.config["sys_path"]):
            fpath = "%s/%s" % (self.config["sys_path"], item)
            if os.path.isdir(fpath) is False:
                continue

            for lxc_metric in lxc_metrics:
                filename = "%s/%s" % (fpath, lxc_metric)
                metric_name = "%s.%s" % (
                    item.replace(".", "_"),
                    lxc_metric.replace("_in_bytes", ""))
                self.log.debug("Trying to collect from %s", filename)
                collected[metric_name] = self._read_file(filename)

        for key in collected.keys():
            if collected[key] is None:
                continue

            for unit in self.config["byte_unit"]:
                value = diamond.convertor.binary.convert(
                    collected[key],
                    oldUnit="B",
                    newUnit=unit)
                new_key = "%s_in_%ss" % (key, unit)
                self.log.debug("Publishing '%s %s'", new_key, value)
                self.publish(new_key, value, metric_type="GAUGE")
205981
def collect(self):
        
        stats = self.parse_stats_file(self.config["status_path"])
        if len(stats) == 0:
            return {}
        elif "info" not in stats.keys():
            return {}
        elif "programstatus" not in stats.keys():
            return {}

        metrics = self.get_icinga_stats(stats["programstatus"])
        if "hoststatus" in stats.keys():
            metrics = dict(
                metrics.items() + self.get_host_stats(
                    stats["hoststatus"]).items())

        if "servicestatus" in stats.keys():
            metrics = dict(
                metrics.items() + self.get_svc_stats(
                    stats["servicestatus"]).items())

        for metric in metrics.keys():
            self.log.debug("Publishing '%s %s'.", metric, metrics[metric])
            self.publish(metric, metrics[metric])
394571
def collect(self):  # pragma: NO COVER
        
        for v_name, view_data in self.view_name_to_data_map.items():
            if v_name not in self.registered_views:
                continue
            desc = self.registered_views[v_name]
            for tag_values in view_data.tag_value_aggregation_data_map:
                agg_data = view_data.tag_value_aggregation_data_map[tag_values]
                metric = self.to_metric(desc, tag_values, agg_data)
                yield metric
955100
def collect(self):
        
        devices = re.compile(self.config['devices'])

        for device in os.listdir('/dev'):
            if devices.match(device):

                command = [self.config['bin'], "-A", os.path.join('/dev',
                                                                  device)]

                if str_to_bool(self.config['use_sudo']):
                    command.insert(0, self.config['sudo_cmd'])

                attributes = subprocess.Popen(
                    command,
                    stdout=subprocess.PIPE
                ).communicate()[0].strip().splitlines()

                metrics = {}

                start_line = self.find_attr_start_line(attributes)
                for attr in attributes[start_line:]:
                    attribute = attr.split()
                    if attribute[1] != "Unknown_Attribute":
                        metric = "%s.%s" % (device, attribute[1])
                    else:
                        metric = "%s.%s" % (device, attribute[0])

                    # 234 Thermal_Throttle (...)  0/0
                    if '/' in attribute[9]:
                        expanded = attribute[9].split('/')
                        for i, subattribute in enumerate(expanded):
                            submetric = '%s_%d' % (metric, i)
                            if submetric not in metrics:
                                metrics[submetric] = subattribute
                            elif metrics[submetric] == 0 and subattribute > 0:
                                metrics[submetric] = subattribute
                    else:
                        # New metric? Store it
                        if metric not in metrics:
                            metrics[metric] = attribute[9]
                        # Duplicate metric? Only store if it has a larger value
                        # This happens semi-often with the Temperature_Celsius
                        # attribute You will have a PASS/FAIL after the real
                        # temp, so only overwrite if The earlier one was a
                        # PASS/FAIL (0/1)
                        elif metrics[metric] == 0 and attribute[9] > 0:
                            metrics[metric] = attribute[9]
                        else:
                            continue

                for metric in metrics.keys():
                    self.publish(metric, metrics[metric])
637410
def _collect_for_instance(self, instance, connection):
        """"""
        with connection.cursor() as cursor:
            for queue, metrics in self.get_queue_info(instance, cursor):
                for name, metric in metrics.items():
                    self.publish('.'.join((instance, queue, name)), metric)

        with connection.cursor() as cursor:
            consumers = self.get_consumer_info(instance, cursor)
            for queue, consumer, metrics in consumers:
                for name, metric in metrics.items():
                    key_parts = (instance, queue, 'consumers', consumer, name)
                    self.publish('.'.join(key_parts), metric)
1178709
def get_metrics(self):
        
        now = datetime.utcnow()
        metrics = set()
        for gauge in self.gauges.values():
            metrics.add(gauge.get_metric(now))
        return metrics