Returns a list with a single metric datum for the specified retry or
request count predefined metric; or an empty list if there is none.

@param metricType
must be either {@link Field#RequestCount} or
{@link Field#RetryCount}; or else GIGO.
965075
protected List<MetricDatum> metricOfRequestOrRetryCount(
            Field metricType, Request<?> req, Object resp) {
        AWSRequestMetrics m = req.getAWSRequestMetrics();
        TimingInfo ti = m.getTimingInfo();
        // Always retrieve the request count even for retry which is equivalent
        // to the number of requests minus one.
        Number counter = ti.getCounter(Field.RequestCount.name());
        if (counter == null) {
            // this is possible if one of the request handlers screwed up
            return Collections.emptyList();
        }
        int requestCount = counter.intValue();
        if (requestCount < 1) {
            LogFactory.getLog(getClass()).debug(
                "request count must be at least one");
            return Collections.emptyList();
        }
        final double count = metricType == Field.RequestCount
                           ? requestCount
                           : requestCount-1 // retryCount = requestCount - 1
                           ;
        if (count < 1) {
            return Collections.emptyList();
        } else {
            return Collections.singletonList(new MetricDatum()
                .withMetricName(req.getServiceName())
                .withDimensions(new Dimension()
                    .withName(Dimensions.MetricType.name())
                    .withValue(metricType.name()))
                .withUnit(StandardUnit.Count)
                .withValue(Double.valueOf(count))
                .withTimestamp(endTimestamp(ti)))
                ;
        }
    }
722464
public static MetricType from(Metric in) {
        if (Gauge.class.isInstance(in))
            return MetricType.GAUGE;
        if (Counter.class.isInstance(in))
            return MetricType.COUNTER;
        if (Histogram.class.isInstance(in))
            return MetricType.HISTOGRAM;
        if (Meter.class.isInstance(in))
            return MetricType.METERED;
        if (Timer.class.isInstance(in))
            return MetricType.TIMER;
        return MetricType.INVALID;
    }
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);
  }
1039480
List<MetricDatum> metricData() {
        Batch batch = new Batch();
        return getMeters().stream().flatMap(m -> m.match(
                batch::gaugeData,
                batch::counterData,
                batch::timerData,
                batch::summaryData,
                batch::longTaskTimerData,
                batch::timeGaugeData,
                batch::functionCounterData,
                batch::functionTimerData,
                batch::metricData)
        ).collect(toList());
    }
297993
private MetricImpl getCommittedMetric(MetricImpl.MetricType metricType) {
        return (MetricImpl)committedMetrics.get(metricType.name());
    }
458675
public static Map<String, Double> getMetrics(Map conf, String topologyName, MetaType metricType, Integer window) {
        NimbusClientWrapper nimbusClient = null;
        Iface client = null;
        Map<String, Double> summary = new HashMap<>();

        try {
            nimbusClient = new NimbusClientWrapper();
            nimbusClient.init(conf);

            client = nimbusClient.getClient();

            String topologyId = client.getTopologyId(topologyName);

            if (metricType == null) {
                metricType = MetaType.TASK;
            }

            List<MetricInfo> allTaskMetrics = client.getMetrics(topologyId, metricType.getT());
            if (allTaskMetrics == null) {
                throw new RuntimeException("Failed to get metrics");
            }

            if (window == null || !AsmWindow.TIME_WINDOWS.contains(window)) {
                window = AsmWindow.M1_WINDOW;
            }

            for (MetricInfo taskMetrics : allTaskMetrics) {

                Map<String, Map<Integer, MetricSnapshot>> metrics = taskMetrics.get_metrics();
                if (metrics == null) {
                    System.out.println("Failed to get task metrics");
                    continue;
                }
                for (Entry<String, Map<Integer, MetricSnapshot>> entry : metrics.entrySet()) {
                    String key = entry.getKey();

                    MetricSnapshot metric = entry.getValue().get(window);
                    if (metric == null) {
                        throw new RuntimeException("Failed to get one minute metrics of " + key);
                    }

                    if (metric.get_metricType() == MetricType.COUNTER.getT()) {
                        summary.put(key, (double) metric.get_longValue());
                    } else if (metric.get_metricType() == MetricType.GAUGE.getT()) {
                        summary.put(key, metric.get_doubleValue());
                    } else {
                        summary.put(key, metric.get_mean());
                    }
                }
            }

            return summary;

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (client != null) {
                nimbusClient.cleanup();
            }
        }
    }
124450
def _metric_value(value_str, metric_type):
    
    if metric_type in (int, float):
        try:
            return metric_type(value_str)
        except ValueError:
            raise ValueError("Invalid {} metric value: {!r}".
                             format(metric_type.__class__.__name__, value_str))
    elif metric_type is six.text_type:
        # In Python 3, decode('unicode_escape) requires bytes, so we need
        # to encode to bytes. This also works in Python 2.
        return value_str.strip('"').encode('utf-8').decode('unicode_escape')
    else:
        assert metric_type is bool
        lower_str = value_str.lower()
        if lower_str == 'true':
            return True
        elif lower_str == 'false':
            return False
        else:
            raise ValueError("Invalid boolean metric value: {!r}".
                             format(value_str))
949116
@Override
  public void reportMetric(final IMetric<?> metric) throws MetricException {
    final String metricName = metric.getName();
    if (!this.historyListMapping.containsKey(metricName)) {
      logger.info("First time capturing metric: " + metricName);
      this.historyListMapping.put(metricName, new LinkedBlockingDeque<>());
    }
    synchronized (this.historyListMapping.get(metricName)) {
      logger.debug("Ingesting metric: " + metricName);
      this.historyListMapping.get(metricName).add(new InMemoryHistoryNode(metric.getValue()));
      cleanUsingTime(metricName, this.historyListMapping.get(metricName).peekLast().getTimestamp());
    }
  }
432505
def GetMetricTypes(self, request, context):
        """"""
        LOG.debug("GetMetricTypes called")
        try:
            metrics = self.plugin.update_catalog(ConfigMap(pb=request.config))
            return MetricsReply(metrics=[m.pb for m in metrics])
        except Exception as err:
            msg = "message: {}\n\nstack trace: {}".format(
                err, traceback.format_exc())
            return MetricsReply(metrics=[], error=msg)
570136
@Override
    public MetricCollector getInstance() {
        AWSCredentialsProvider provider = AwsSdkMetrics.getCredentialProvider();
        Region region = RegionUtils.getRegion(AwsSdkMetrics.getRegionName());
        Integer qSize = AwsSdkMetrics.getMetricQueueSize();
        Long timeoutMilli = AwsSdkMetrics.getQueuePollTimeoutMilli();
        CloudWatchMetricConfig config = new CloudWatchMetricConfig();
        ClientConfiguration clientConfig = new ClientConfiguration();
        if (provider != null)
            config.setCredentialsProvider(provider);
        if (region != null) {
            String endPoint = region.getServiceEndpoint(AmazonCloudWatch.ENDPOINT_PREFIX);
            config.setCloudWatchEndPoint(endPoint);
        }
        if (qSize != null)
            config.setMetricQueueSize(qSize.intValue());
        if (timeoutMilli != null)
            config.setQueuePollTimeoutMilli(timeoutMilli.longValue());
        config.setClientConfiguration(clientConfig);
        MetricCollectorSupport.startSingleton(config);
        return MetricCollectorSupport.getInstance();
    }
501874
private StandardUnit getMetricUnit(final String metricName) {
        String result = null;

        if (metricName.equals(Constants.CPU_UTILIZATION)) {
            result = Constants.UNIT_PERCENT;
        } else if (metricName.equals(Constants.DISK_READ_BYTES)) {
            result = Constants.UNIT_BYTES;
        } else if (metricName.equals(Constants.DISK_READ_OPS)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.DISK_WRITE_BYTES)) {
            result = Constants.UNIT_BYTES;
        } else if (metricName.equals(Constants.DISK_WRITE_OPS)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.NETWORK_IN)) {
            result = Constants.UNIT_BYTES;
        } else if (metricName.equals(Constants.NETWORK_OUT)) {
            result = Constants.UNIT_BYTES;
        } else if (metricName.equals(Constants.NETWORK_PACKETS_IN)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.NETWORK_PACKETS_OUT)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.STATUS_CHECK_FAILED)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.STATUS_CHECK_FAILED_INSTANCE)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.STATUS_CHECK_FAILED_SYSTEM)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.CPU_CREDIT_USAGE)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.ESTIMATED_CHARGES)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.CPU_CREDIT_BALANCE)) {
            result = Constants.UNIT_COUNT;
        }

        return StandardUnit.fromValue(result);
    }
472152
public void setMetricData(java.util.Collection<MetricDatapoint> metricData) {
        if (metricData == null) {
            this.metricData = null;
            return;
        }

        this.metricData = new java.util.ArrayList<MetricDatapoint>(metricData);
    }
131839
static Map<String, Double> processMetrics(String prefix, Iterable<MetricsInfo> metrics) {
    Map<String, Double> map = new HashMap<>();
    for (MetricsInfo r : metrics) {
      try {
        map.put(prefix + r.getName(), Double.valueOf(r.getValue()));
      } catch (NumberFormatException ne) {
        LOG.log(Level.SEVERE, "Could not parse metric, Name: "
            + r.getName() + " Value: " + r.getValue(), ne);
      }
    }
    return map;
  }
612913
protected List<List<MetricSchemaRecord>> _fracture(List<Metric> metrics) {
		List<List<MetricSchemaRecord>> fracturedList = new ArrayList<>();

		List<MetricSchemaRecord> records = new ArrayList<>(_bulkIndexingSize);
		for(Metric metric : metrics) {
			if(metric.getTags().isEmpty()) {
				MetricSchemaRecord msr = new MetricSchemaRecord(metric.getScope(), metric.getMetric());
				msr.setNamespace(metric.getNamespace());
				records.add(msr);
				if(records.size() == _bulkIndexingSize) {
					fracturedList.add(records);
					records = new ArrayList<>(_bulkIndexingSize);
				}
				continue;
			}

			String retention  = metric.getMetatagsRecord()==null?null:metric.getMetatagsRecord().getMetatagValue(RETENTION_DISCOVERY);
			Integer retentionInt = null;
			if (retention != null) {
				try {
					retentionInt = Integer.parseInt(retention);
				}
				catch(NumberFormatException e) {
					_logger.debug("expect _retention_discovery_ to be a numeric value; {} is invalid", retention);
				}
			}
			for(Map.Entry<String, String> entry : metric.getTags().entrySet()) {
				records.add(new MetricSchemaRecord(metric.getNamespace(),
													metric.getScope(),
													metric.getMetric(),
													entry.getKey(),
													entry.getValue(),
													retentionInt));
				if(records.size() == _bulkIndexingSize) {
					fracturedList.add(records);
					records = new ArrayList<>(_bulkIndexingSize);
				}
			}
		}

		if(!records.isEmpty()) {
			fracturedList.add(records);
		}

		return fracturedList;
	}
215863
private Iterable<PutMetricDataRequest> toPutMetricDataRequests(Map<String, MetricDatum> uniqueMetrics) {
        // Opportunistically generates some machine metrics whenever there
        // is metrics consolidation
        for (MetricDatum datum: machineMetricFactory.generateMetrics()) {
            summarize(datum, uniqueMetrics);
        }
        List<PutMetricDataRequest> list = new ArrayList<PutMetricDataRequest>();
        List<MetricDatum> data = new ArrayList<MetricDatum>();
        for (MetricDatum m: uniqueMetrics.values()) {
            data.add(m);
            if (data.size() == CloudWatchMetricConfig.MAX_METRICS_DATUM_SIZE) {
                list.addAll(newPutMetricDataRequests(data));
                data.clear();
            }
        }

        if (data.size() > 0) {
            list.addAll(newPutMetricDataRequests(data));
        }
        return list;
    }
1011651
private Metric collectCounter(MetricName dropwizardMetric, Counter counter) {
    String metricName =
        DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "counter");

    String metricDescription =
        DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), counter);
    AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels =
        DropWizardUtils.generateLabels(dropwizardMetric);

    MetricDescriptor metricDescriptor =
        MetricDescriptor.create(
            metricName, metricDescription, DEFAULT_UNIT, Type.GAUGE_INT64, labels.getKey());

    TimeSeries timeSeries =
        TimeSeries.createWithOnePoint(
            labels.getValue(),
            Point.create(Value.longValue(counter.getCount()), clock.now()),
            null);
    return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
  }
1092141
public TopologyMaster.MetricResponse getMetrics(TopologyMaster.MetricRequest request) {
    String componentName = request.getComponentName();
    if (!cache.componentInstanceExists(componentName, null)) {
      return buildResponseNotOk(
          String.format("Unknown component %s found in MetricRequest %s", componentName, request)
      ).build();
    }
    if (request.getInstanceIdCount() > 0) {
      for (String instanceId : request.getInstanceIdList()) {
        if (!cache.componentInstanceExists(componentName, instanceId)) {
          return buildResponseNotOk(
              String.format("Unknown instance %s found in MetricRequest %s", instanceId, request)
          ).build();
        }
      }
    }
    if (!request.hasInterval() && !request.hasExplicitInterval()) {
      return buildResponseNotOk("No purgeIntervalSec or explicit purgeIntervalSec set").build();
    }

    MetricRequest request1 = MetricsCacheQueryUtils.fromProtobuf(request);
    MetricResponse response1 = cache.getMetrics(request1, metricNameType);
    TopologyMaster.MetricResponse response = MetricsCacheQueryUtils.toProtobuf(response1, request1);
    return response;
  }