Optional metric handler for 'items' stats

        key: "items:<slab_id>:<metric_name>" format
        value: return untouched

        Like all optional metric handlers returns metric, tags, value
556554
def get_slabs_stats(key, value):
        
        slabbed_key = key.split(':')
        tags = []
        if len(slabbed_key) == 2:
            slab_id = slabbed_key[0]
            metric = slabbed_key[1]
            tags = ["slab:{}".format(slab_id)]
        else:
            metric = slabbed_key[0]

        return metric, tags, value
977370
async def get_metrics(self, *tags):
        
        log.debug("Retrieving metrics for %s",
                  ', '.join(tags) if tags else "all units")

        metrics_facade = client.MetricsDebugFacade.from_connection(
            self.connection())

        entities = [client.Entity(tag) for tag in tags]
        metrics_result = await metrics_facade.GetMetrics(entities)

        metrics = collections.defaultdict(list)

        for entity_metrics in metrics_result.results:
            error = entity_metrics.error
            if error:
                if "is not a valid tag" in error:
                    raise ValueError(error.message)
                else:
                    raise Exception(error.message)

            for metric in entity_metrics.metrics:
                metrics[metric.unit].append(vars(metric))

        return metrics
1289479
def metrics(self, name):
        
        return [
            MetricStub(
                ensure_unicode(stub.name),
                stub.type,
                stub.value,
                normalize_tags(stub.tags),
                ensure_unicode(stub.hostname),
            )
            for stub in self._metrics.get(to_string(name), [])
        ]
1162630
def format_item(self, item):
        
        # http://jsonapi.org/format/#document-top-level
        # Primary data MUST be either... a single resource object, a single resource
        # identifier object, or null, for requests that target single resources
        if not item:
            return None

        ret = self.dict_class()
        ret[TYPE] = self.opts.type_

        # Get the schema attributes so we can confirm `dump-to` values exist
        attributes = {
            (get_dump_key(self.fields[field]) or field): field
            for field in self.fields
        }

        for field_name, value in iteritems(item):
            attribute = attributes[field_name]
            if attribute == ID:
                ret[ID] = value
            elif isinstance(self.fields[attribute], DocumentMeta):
                if not self.document_meta:
                    self.document_meta = self.dict_class()
                self.document_meta.update(value)
            elif isinstance(self.fields[attribute], ResourceMeta):
                if 'meta' not in ret:
                    ret['meta'] = self.dict_class()
                ret['meta'].update(value)
            elif isinstance(self.fields[attribute], BaseRelationship):
                if value:
                    if 'relationships' not in ret:
                        ret['relationships'] = self.dict_class()
                    ret['relationships'][self.inflect(field_name)] = value
            else:
                if 'attributes' not in ret:
                    ret['attributes'] = self.dict_class()
                ret['attributes'][self.inflect(field_name)] = value

        links = self.get_resource_links(item)
        if links:
            ret['links'] = links
        return ret
459922
async def info(self):
        '''
        
        '''
        stat = self._items.stat()
        return {'indx': self._items.index(), 'metrics': self._metrics.index(), 'stat': stat}
1090101
def assert_metric(self, name, value=None, tags=None, count=None, at_least=1, hostname=None, metric_type=None):
        
        self._asserted.add(name)
        tags = normalize_tags(tags, sort=True)

        candidates = []
        for metric in self.metrics(name):
            if value is not None and not self.is_aggregate(metric.type) and value != metric.value:
                continue

            if tags and tags != sorted(metric.tags):
                continue

            if hostname and hostname != metric.hostname:
                continue

            if metric_type is not None and metric_type != metric.type:
                continue

            candidates.append(metric)

        if value is not None and candidates and all(self.is_aggregate(m.type) for m in candidates):
            got = sum(m.value for m in candidates)
            msg = "Expected count value for '{}': {}, got {}".format(name, value, got)
            assert value == got, msg

        if count is not None:
            msg = "Needed exactly {} candidates for '{}', got {}".format(count, name, len(candidates))
            assert len(candidates) == count, msg
        else:
            msg = "Needed at least {} candidates for '{}', got {}".format(at_least, name, len(candidates))
            assert len(candidates) >= at_least, msg
1151859
def get(self, id=None, **kwargs):
        
        if id is not None:
            return self._get('metrics/%s' % id, data=kwargs)
        else:
            return self._get('metrics', data=kwargs)
467785
def queue_stats(self, queue, tags):
        
        for mname, pymqi_value in iteritems(metrics.queue_metrics()):
            try:
                mname = '{}.queue.{}'.format(self.METRIC_PREFIX, mname)
                m = queue.inquire(pymqi_value)
                self.gauge(mname, m, tags=tags)
            except pymqi.Error as e:
                self.warning("Error getting queue stats for {}: {}".format(queue, e))

        for mname, func in iteritems(metrics.queue_metrics_functions()):
            try:
                mname = '{}.queue.{}'.format(self.METRIC_PREFIX, mname)
                m = func(queue)
                self.gauge(mname, m, tags=tags)
            except pymqi.Error as e:
                self.warning("Error getting queue stats for {}: {}".format(queue, e))
647767
def get_stats_item(self, item):
        
        if isinstance(self.stats, dict):
            try:
                return self._json_dumps({item: self.stats[item]})
            except KeyError as e:
                logger.error("Cannot get item {} ({})".format(item, e))
                return None
        elif isinstance(self.stats, list):
            try:
                # Source:
                # http://stackoverflow.com/questions/4573875/python-get-index-of-dictionary-item-in-list
                # But https://github.com/nicolargo/glances/issues/1401
                return self._json_dumps({item: list(map(itemgetter(item), self.stats))})
            except (KeyError, ValueError) as e:
                logger.error("Cannot get item {} ({})".format(item, e))
                return None
        else:
            return None
862411
def metadata(check):
    
    metric_sources = get_metric_sources()

    if check:
        if check not in metric_sources:
            abort('Metadata file `{}` does not exist.'.format(get_metadata_file(check)))
        metric_sources = [check]
    else:
        metric_sources = sorted(metric_sources)

    errors = False

    for current_check in metric_sources:
        if current_check.startswith('datadog_checks_'):
            continue

        # get any manifest info needed for validation
        manifest = load_manifest(current_check)
        try:
            metric_prefix = manifest['metric_prefix'].rstrip('.')
        except KeyError:
            metric_prefix = None

        metadata_file = get_metadata_file(current_check)

        # To make logging less verbose, common errors are counted for current check
        metric_prefix_count = defaultdict(int)
        empty_count = defaultdict(int)
        empty_warning_count = defaultdict(int)
        duplicate_set = set()
        metric_prefix_error_shown = False

        # Python 2 csv module does not support unicode
        with open(metadata_file, 'rb' if PY2 else 'r', encoding=None if PY2 else 'utf-8') as f:
            reader = csv.DictReader(f, delimiter=',')

            # Read header
            if PY2:
                reader._fieldnames = [key.decode('utf-8') for key in reader.fieldnames]
            else:
                reader._fieldnames = reader.fieldnames

            for row in reader:

                # Number of rows is correct. Since metric is first in the list, should be safe to access
                if len(row) != len(ALL_HEADERS):
                    errors = True
                    echo_failure('{}: {} Has the wrong amount of columns'.format(current_check, row['metric_name']))
                    continue

                if PY2:
                    for key, value in iteritems(row):
                        if value is not None:
                            row[key] = value.decode('utf-8')

                # all headers exist, no invalid headers
                all_keys = set(row)
                if all_keys != ALL_HEADERS:
                    invalid_headers = all_keys.difference(ALL_HEADERS)
                    if invalid_headers:
                        errors = True
                        echo_failure('{}: Invalid column {}'.format(current_check, invalid_headers))

                    missing_headers = ALL_HEADERS.difference(all_keys)
                    if missing_headers:
                        errors = True
                        echo_failure('{}: Missing columns {}'.format(current_check, missing_headers))

                    continue

                # duplicate metric_name
                if row['metric_name'] and row['metric_name'] not in duplicate_set:
                    duplicate_set.add(row['metric_name'])
                else:
                    errors = True
                    echo_failure('{}: `{}` is a duplicate metric_name'.format(current_check, row['metric_name']))

                # metric_name header
                if metric_prefix:
                    if not row['metric_name'].startswith(metric_prefix):
                        prefix = row['metric_name'].split('.')[0]
                        metric_prefix_count[prefix] += 1
                else:
                    errors = True
                    if not metric_prefix_error_shown and current_check not in PROVIDER_INTEGRATIONS:
                        metric_prefix_error_shown = True
                        echo_failure('{}: metric_prefix does not exist in manifest'.format(current_check))

                # metric_type header
                if row['metric_type'] and row['metric_type'] not in VALID_METRIC_TYPE:
                    errors = True
                    echo_failure('{}: `{}` is an invalid metric_type.'.format(current_check, row['metric_type']))

                # unit_name header
                if row['unit_name'] and row['unit_name'] not in VALID_UNIT_NAMES:
                    errors = True
                    echo_failure('{}: `{}` is an invalid unit_name.'.format(current_check, row['unit_name']))

                # orientation header
                if row['orientation'] and row['orientation'] not in VALID_ORIENTATION:
                    errors = True
                    echo_failure('{}: `{}` is an invalid orientation.'.format(current_check, row['orientation']))

                # empty required fields
                for header in REQUIRED_HEADERS:
                    if not row[header]:
                        empty_count[header] += 1

                # empty description field, description is recommended
                if not row['description']:
                    empty_warning_count['description'] += 1
                # exceeds max allowed length of description
                elif len(row['description']) > MAX_DESCRIPTION_LENGTH:
                    errors = True
                    echo_failure(
                        '{}: `{}` exceeds the max length: {} for descriptions.'.format(
                            current_check, row['metric_name'], MAX_DESCRIPTION_LENGTH
                        )
                    )

        for header, count in iteritems(empty_count):
            errors = True
            echo_failure('{}: {} is empty in {} rows.'.format(current_check, header, count))

        for header, count in iteritems(empty_warning_count):
            echo_warning('{}: {} is empty in {} rows.'.format(current_check, header, count))

        for prefix, count in iteritems(metric_prefix_count):
            # Don't spam this warning when we're validating everything
            if check:
                echo_warning(
                    '{}: `{}` appears {} time(s) and does not match metric_prefix '
                    'defined in the manifest.'.format(current_check, prefix, count)
                )

    if errors:
        abort()
1327120
def indicator_details(indicator):
    
    metrics = format_metrics_json(indicator)

    metrics_list = set(indicator.metrics
                       .filter(name__in=metrics_name_map.keys())
                       .values_list('name', flat=True))
    null_metrics = default_metrics
    for keys in metrics_list:
        null_metrics.pop(metrics_name_map[keys], None)

    metrics.update(null_metrics)

    return {type(indicator).__name__: {
            'valor': indicator.value,
            'metricas': metrics, },
            }
121155
function isItemTag (tagName, prefix, local, feedType) {
  return tagName === 'item' || tagName === 'entry'
    || (local === 'item' && (prefix === '' || feedType === 'rdf'))
    || (local === 'entry' && (prefix === '' || feedType === 'atom'));
}
891256
def CollectMetrics(self, request, context):
        """"""
        LOG.debug("CollectMetrics called")
        try:
            metrics_to_collect = []
            for metric in request.metrics:
                metrics_to_collect.append(Metric(pb=metric))
            metrics_collected = self.plugin.collect(metrics_to_collect)
            return MetricsReply(metrics=[m.pb for m in metrics_collected])
        except Exception as err:
            msg = "message: {}\n\nstack trace: {}".format(
                err, traceback.format_exc())
            return MetricsReply(metrics=[], error=msg)
1131066
function Metric(key, value, ts) {
  var m = this;
  this.key = key;
  this.value = value;
  this.ts = ts;

  // return a string representation of this metric appropriate 
  // for sending to the graphite collector. does not include
  // a trailing newline.
  this.toText = function() {
    return m.key + " " + m.value + " " + m.ts;
  };

  this.toPickle = function() {
    return MARK + STRING + '\'' + m.key + '\'\n' + MARK + LONG + m.ts + 'L\n' + STRING + '\'' + m.value + '\'\n' + TUPLE + TUPLE + APPEND;
  };
}
984923
def get_item_key(self, item):
        """"""
        try:
            ret = item[item['key']]
        except KeyError:
            logger.error("No 'key' available in {}".format(item))
        if isinstance(ret, list):
            return ret[0]
        else:
            return ret
1030022
def run_tag_from_session_and_metric(session_name, metric_name):
  
  assert isinstance(session_name, six.string_types)
  assert isinstance(metric_name, api_pb2.MetricName)
  # os.path.join() will append a final slash if the group is empty; it seems
  # like multiplexer.Tensors won't recognize paths that end with a '/' so
  # we normalize the result of os.path.join() to remove the final '/' in that
  # case.
  run = os.path.normpath(os.path.join(session_name, metric_name.group))
  tag = metric_name.tag
  return run, tag
376178
def stats(type=nil)
      type = nil if ![nil, :items,:slabs,:settings].include? type
      values = {}
      ring.servers.each do |server|
        values["#{server.name}"] = server.alive? ? server.request(:stats,type.to_s) : nil
      end
      values
    end