Takes a simple metric about a container, reports it as a rate or gauge.
        If several series are found for a given container, values are summed before submission.
322596
def _process_container_metric(self, type, metric_name, metric, scraper_config):
        
        if metric.type not in METRIC_TYPES:
            self.log.error("Metric type %s unsupported for metric %s" % (metric.type, metric.name))
            return

        samples = self._sum_values_by_context(metric, self._get_entity_id_if_container_metric)
        for c_id, sample in iteritems(samples):
            pod_uid = self._get_pod_uid(sample[self.SAMPLE_LABELS])
            if self.pod_list_utils.is_excluded(c_id, pod_uid):
                continue

            tags = tagger.tag(c_id, tagger.HIGH)
            tags += scraper_config['custom_tags']

            # FIXME we are forced to do that because the Kubelet PodList isn't updated
            # for static pods, see https://github.com/kubernetes/kubernetes/pull/59948
            pod = self._get_pod_by_metric_label(sample[self.SAMPLE_LABELS])
            if pod is not None and is_static_pending_pod(pod):
                tags += tagger.tag('kubernetes_pod://%s' % pod["metadata"]["uid"], tagger.HIGH)
                tags += self._get_kube_container_name(sample[self.SAMPLE_LABELS])
                tags = list(set(tags))

            val = sample[self.SAMPLE_VALUE]

            if "rate" == type:
                self.rate(metric_name, val, tags)
            elif "gauge" == type:
                self.gauge(metric_name, val, tags)
442657
def _report_container_spec_metrics(self, pod_list, instance_tags):
        """"""
        for pod in pod_list['items']:
            pod_name = pod.get('metadata', {}).get('name')
            pod_phase = pod.get('status', {}).get('phase')
            if self._should_ignore_pod(pod_name, pod_phase):
                continue

            for ctr in pod['spec']['containers']:
                if not ctr.get('resources'):
                    continue

                c_name = ctr.get('name', '')
                cid = None
                for ctr_status in pod['status'].get('containerStatuses', []):
                    if ctr_status.get('name') == c_name:
                        # it is already prefixed with 'runtime://'
                        cid = ctr_status.get('containerID')
                        break
                if not cid:
                    continue

                pod_uid = pod.get('metadata', {}).get('uid')
                if self.pod_list_utils.is_excluded(cid, pod_uid):
                    continue

                tags = tagger.tag('%s' % cid, tagger.HIGH) + instance_tags

                try:
                    for resource, value_str in iteritems(ctr.get('resources', {}).get('requests', {})):
                        value = self.parse_quantity(value_str)
                        self.gauge('{}.{}.requests'.format(self.NAMESPACE, resource), value, tags)
                except (KeyError, AttributeError) as e:
                    self.log.debug("Unable to retrieve container requests for %s: %s", c_name, e)

                try:
                    for resource, value_str in iteritems(ctr.get('resources', {}).get('limits', {})):
                        value = self.parse_quantity(value_str)
                        self.gauge('{}.{}.limits'.format(self.NAMESPACE, resource), value, tags)
                except (KeyError, AttributeError) as e:
                    self.log.debug("Unable to retrieve container limits for %s: %s", c_name, e)
798563
def metric(cls, name, count, elapsed):
        

        if name is None:
            warnings.warn("Ignoring unnamed metric", stacklevel=3)
            return

        with cls.lock:
            if not cls.instances:
                # first call
                shutil.rmtree(cls.outdir, ignore_errors=True)
                os.makedirs(cls.outdir)

                if cls.dump_atexit: atexit.register(cls.dump)

            try:
                self = cls.instances[name]
            except KeyError:
                self = cls.instances[name] = cls(name)

            self.writer.writerow((count, "%f"%elapsed))
1155926
def log_metrics(self, metrics_by_name, info):
        
        if self.metrics is None:
            # If, for whatever reason, the metrics collection has not been set
            # do not try to save anything there.
            return
        for key in metrics_by_name:
            query = {"run_id": self.run_entry['_id'],
                     "name": key}
            push = {"steps": {"$each": metrics_by_name[key]["steps"]},
                    "values": {"$each": metrics_by_name[key]["values"]},
                    "timestamps": {"$each": metrics_by_name[key]["timestamps"]}
                    }
            update = {"$push": push}
            result = self.metrics.update_one(query, update, upsert=True)
            if result.upserted_id is not None:
                # This is the first time we are storing this metric
                info.setdefault("metrics", []) \
                    .append({"name": key, "id": str(result.upserted_id)})
1015481
def add_metric(self, labels, value, created=None, timestamp=None):
        
        self.samples.append(Sample(self.name + '_total', dict(zip(self._labelnames, labels)), value, timestamp))
        if created is not None:
            self.samples.append(Sample(self.name + '_created', dict(zip(self._labelnames, labels)), created, timestamp))
416966
def accumulate_metric(cls, name, value):
        
        metrics_cache = cls._get_metrics_cache()
        metrics_cache.setdefault(name, 0)
        metrics_cache.set(name, value)
436979
@SuppressWarnings("rawtypes")
  @Nullable
  private Metric collectGauge(String dropwizardName, Gauge gauge) {
    String metricName = DropWizardUtils.generateFullMetricName(dropwizardName, "gauge");
    String metricDescription = DropWizardUtils.generateFullMetricDescription(dropwizardName, gauge);

    // Figure out which gauge instance and call the right method to get value
    Type type;
    Value value;

    Object obj = gauge.getValue();
    if (obj instanceof Number) {
      type = Type.GAUGE_DOUBLE;
      value = Value.doubleValue(((Number) obj).doubleValue());
    } else if (obj instanceof Boolean) {
      type = Type.GAUGE_INT64;
      value = Value.longValue(((Boolean) obj) ? 1 : 0);
    } else {
      // Ignoring Gauge (gauge.getKey()) with unhandled type.
      return null;
    }

    MetricDescriptor metricDescriptor =
        MetricDescriptor.create(
            metricName, metricDescription, DEFAULT_UNIT, type, Collections.<LabelKey>emptyList());
    TimeSeries timeSeries =
        TimeSeries.createWithOnePoint(
            Collections.<LabelValue>emptyList(), Point.create(value, clock.now()), null);
    return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
  }
733861
@Override
  public void reportMetric(final IMetric<?> metric) throws MetricException {
    final String gangliaCommand = buildCommand(metric);

    if (gangliaCommand != null) {
      // executes shell command to report metric to ganglia dashboard
      try {
        final Process emission = Runtime.getRuntime().exec(gangliaCommand);
        final int exitCode;
        exitCode = emission.waitFor();
        if (exitCode != 0) {
          throw new MetricException("Failed to report metric using gmetric");
        }
      } catch (final Exception e) {
        throw new MetricException("Failed to report metric using gmetric");
      }
    } else {
      throw new MetricException("Failed to build ganglia Command");
    }
  }
683035
public void stats(String name, float value) {
		for (ICounters counter : _counters)
			counter.stats(name, value);
	}

	/**
	 * Records the last calculated measurement value.
	 * 
	 * Usually this method is used by metrics calculated externally.
	 * 
	 * @param name  a counter name of Last type.
	 * @param value a last value to record.
	 */
	public void last(String name, float value) {
		for (ICounters counter : _counters)
			counter.last(name, value);
	}

	/**
	 * Records the current time as a timestamp.
	 * 
	 * @param name a counter name of Timestamp type.
	 */
	public void timestampNow(String name) {
		timestamp(name, ZonedDateTime.now());
	}

	/**
	 * Records the given timestamp.
	 * 
	 * @param name  a counter name of Timestamp type.
	 * @param value a timestamp to record.
	 */
	public void timestamp(String name, ZonedDateTime value) {
		for (ICounters counter : _counters)
			counter.timestamp(name, value);
	}

	/**
	 * Increments counter by 1.
	 * 
	 * @param name a counter name of Increment type.
	 */
	public void incrementOne(String name) {
		increment(name, 1);
	}

	/**
	 * Increments counter by given value.
	 * 
	 * @param name  a counter name of Increment type.
	 * @param value a value to add to the counter.
	 */
	public void increment(String name, int value) {
		for (ICounters counter : _counters)
			counter.increment(name, value);
	}

}
643581
@Override
	public void notifyOfAddedMetric(Metric metric, String metricName, MetricGroup group) {
		final String fullName = group.getMetricIdentifier(metricName, this);

		synchronized (this) {
			if (metric instanceof Counter) {
				counters.put((Counter) metric, fullName);
				registry.register(fullName, new FlinkCounterWrapper((Counter) metric));
			}
			else if (metric instanceof Gauge) {
				gauges.put((Gauge<?>) metric, fullName);
				registry.register(fullName, FlinkGaugeWrapper.fromGauge((Gauge<?>) metric));
			} else if (metric instanceof Histogram) {
				Histogram histogram = (Histogram) metric;
				histograms.put(histogram, fullName);

				if (histogram instanceof DropwizardHistogramWrapper) {
					registry.register(fullName, ((DropwizardHistogramWrapper) histogram).getDropwizardHistogram());
				} else {
					registry.register(fullName, new FlinkHistogramWrapper(histogram));
				}
			} else if (metric instanceof Meter) {
				Meter meter = (Meter) metric;
				meters.put(meter, fullName);

				if (meter instanceof DropwizardMeterWrapper) {
					registry.register(fullName, ((DropwizardMeterWrapper) meter).getDropwizardMeter());
				} else {
					registry.register(fullName, new FlinkMeterWrapper(meter));
				}
			} else {
				log.warn("Cannot add metric of type {}. This indicates that the reporter " +
					"does not support this metric type.", metric.getClass().getName());
			}
		}
	}
1230826
def set_metric(slug, value, category=None, expire=None, date=None):
    """"""
    get_r().set_metric(slug, value, category=category, expire=expire, date=date)
1274301
private void reportMeter(String name, Meter meter) {
        String prefixedName = prefix(name);
        if (!snapshots.hasDescriptor(prefixedName)) {

            MetricItem.Builder builder = MetricItem.Builder.create();

            builder.events("events");

            builder.events("m1_rate", 1, rateUnit);
            builder.events("m5_rate", 5, rateUnit);
            builder.events("m15_rate", 15, rateUnit);
            builder.events("mean_rate", rateUnit);
            snapshots.setDescriptor(prefixedName, builder.build());
        }

        Map<String, Number> values = new HashMap<>();

        addMetered(meter, values, "events");

        snapshots.addSnapshot(prefixedName, getTimestamp(), values);
    }
75587
def show_metrics(metrics, all_branches=False, all_tags=False):
    
    for branch, val in metrics.items():
        if all_branches or all_tags:
            logger.info("{branch}:".format(branch=branch))

        for fname, metric in val.items():
            lines = metric if type(metric) is list else metric.splitlines()

            if len(lines) > 1:
                logger.info("\t{fname}:".format(fname=fname))

                for line in lines:
                    logger.info("\t\t{content}".format(content=line))

            else:
                logger.info("\t{}: {}".format(fname, metric))
217413
protected void submitReport() {
    try {
      utilizationGauger.gauge();
      rpcCollector.reportTaskTrackerUtilization(
              utilizationGauger.getTaskTrackerUtilization(),
              utilizationGauger.getLocalJobUtilization());
    } catch (IOException e) {
      LOG.error(StringUtils.stringifyException(e));
    }
  }
848317
public void add(final Metric metric) {
		Preconditions.checkNotNull(metric);
		
		// get the aggregate for this minute
		
		MetricAggregate aggregate = getAggregate(metric.getIdentity());
		
		// add the current metric into the aggregate
		
		switch (metric.getIdentity().getType()) {
			case COUNTER: 
			case TIMER: 
			case AVERAGE:
				aggregate.setCount(aggregate.getCount() + 1);
				aggregate.setValue(aggregate.getValue() + metric.getValue());
			    break;
			case GAUGE:
				aggregate.setCount(1);
				if (metric.isIncrement()) {
					aggregate.setValue(aggregate.getValue() + metric.getValue());
				} else {
					aggregate.setValue(metric.getValue());
				}
			    break;	
			default:
				LOGGER.info("Unable to aggregate {} metric type", metric.getIdentity().getType());
				break;
		}
	}
806325
def metric(self, measurement_name, values, tags=None, timestamp=None):
        
        if not measurement_name or values in (None, {}):
            # Don't try to send empty data
            return

        tags = tags or {}

        # Do a shallow merge of the metric tags and global tags
        all_tags = dict(self.tags, **tags)

        # Create a metric line from the input and then send it to socket
        line = Line(measurement_name, values, all_tags, timestamp)
        self.send(line.to_line_protocol())
28403
def calculate_metrics(self, model, train_loader, valid_loader, metrics_dict):
        """"""
        # Check whether or not it's time for validation as well
        self.log_count += 1
        log_valid = (
            valid_loader is not None
            and self.valid_every_X
            and not (self.log_count % self.valid_every_X)
        )

        metrics_dict = {}

        # Calculate custom metrics
        if self.config["log_train_metrics_func"] is not None:
            func = self.config["log_train_metrics_func"]
            func_list = func if isinstance(func, list) else [func]
            for func in func_list:
                metrics_dict = self._calculate_custom_metrics(
                    model, train_loader, func, metrics_dict, split="train"
                )
        if self.config["log_valid_metrics_func"] is not None and log_valid:
            func = self.config["log_valid_metrics_func"]
            func_list = func if isinstance(func, list) else [func]
            for func in func_list:
                metrics_dict = self._calculate_custom_metrics(
                    model, valid_loader, func, metrics_dict, split="valid"
                )

        # Calculate standard metrics
        metrics_dict = self._calculate_standard_metrics(
            model, train_loader, self.log_train_metrics, metrics_dict, "train"
        )

        if log_valid:
            metrics_dict = self._calculate_standard_metrics(
                model, valid_loader, self.log_valid_metrics, metrics_dict, "valid"
            )

        return metrics_dict