Convert a OpenCensus Type to a StackDriver MetricKind
481173
@VisibleForTesting
  static MetricKind createMetricKind(Type type) {
    if (type == Type.GAUGE_INT64 || type == Type.GAUGE_DOUBLE) {
      return MetricKind.GAUGE;
    } else if (type == Type.CUMULATIVE_INT64
        || type == Type.CUMULATIVE_DOUBLE
        || type == Type.CUMULATIVE_DISTRIBUTION) {
      return MetricKind.CUMULATIVE;
    }
    return MetricKind.UNRECOGNIZED;
  }
205290
private static Map<Long, Double> _fillMetricTransform(QueryContext queryContext, Metric metric, long windowSizeInSeconds, long offsetInSeconds, double value) {
    	if(metric == null || metric.getDatapoints() == null || metric.getDatapoints().isEmpty()) {
    		return Collections.emptyMap();
    	}
    	
        Map<Long, Double> filledDatapoints = new TreeMap<>();
        Map<Long, Double> sortedDatapoints = new TreeMap<>(metric.getDatapoints());
        Long[] sortedTimestamps = new Long[sortedDatapoints.size()];

        sortedDatapoints.keySet().toArray(sortedTimestamps);

        Long[] startAndEndTimestamps = QueryUtils.getStartAndEndTimesWithMaxInterval(queryContext);
        
        Long startTimestamp = startAndEndTimestamps[0]>0 ? startAndEndTimestamps[0] : sortedTimestamps[0];
        Long endTimestamp = startAndEndTimestamps[1]>0 ? startAndEndTimestamps[1] : sortedTimestamps[sortedTimestamps.length - 1];

        // create a new datapoints map propagateDatpoints, which have all the
        // expected timestamps, then fill the missing value
        int index = 1;
        int numDatapoints = 0;
        while (startTimestamp <= endTimestamp && numDatapoints++ < MAX_DATAPOINTS_FOR_FILL) {
            filledDatapoints.put(startTimestamp, sortedDatapoints.containsKey(startTimestamp) ? sortedDatapoints.get(startTimestamp) : null);
            if (index >= sortedDatapoints.size()) {
              	startTimestamp = startTimestamp + windowSizeInSeconds * 1000;
                continue;
            }
            if ((startTimestamp + windowSizeInSeconds * 1000) < sortedTimestamps[index]) {
                startTimestamp = startTimestamp + windowSizeInSeconds * 1000;
            } else {
                startTimestamp = sortedTimestamps[index];
                index++;
            }
        }

        int newLength = filledDatapoints.size();
        List<Long> newTimestamps = new ArrayList<Long>();
        List<Double> newValues = new ArrayList<>();
        
        for (Map.Entry<Long, Double> entry : filledDatapoints.entrySet()) {
            newTimestamps.add(entry.getKey());
            newValues.add(entry.getValue());
        }
        for (int i = 0; i < newLength; i++) {
            if (newValues.get(i) != null) {
                continue;
            } else {
                filledDatapoints.put(newTimestamps.get(i) + offsetInSeconds * 1000, value);
            }
        }

        Map<Long, Double> cleanFilledDatapoints = new TreeMap<>();

        for (Map.Entry<Long, Double> entry : filledDatapoints.entrySet()) {
            if (entry.getValue() != null) {
                cleanFilledDatapoints.put(entry.getKey(), entry.getValue());
            }
        }
        return cleanFilledDatapoints;
    }
115051
private void _propagateMetricTransform(Metric metric, long windowSizeInSeconds, QueryContext queryContext) {
    	
    	// if the datapoint set is empty or has a single datapoint, return directly
    	if(metric.getDatapoints().isEmpty() || metric.getDatapoints().size() == 1) {
    		return;
    	}
      	Long[] startAndEndTimestamps = QueryUtils.getStartAndEndTimesWithMaxInterval(queryContext);
        Map<Long, Double> propagateDatapoints = new TreeMap<>();
        Map<Long, Double> sortedDatapoints = new TreeMap<>(metric.getDatapoints());
        Long[] sortedTimestamps = new Long[sortedDatapoints.size()];
        sortedDatapoints.keySet().toArray(sortedTimestamps);

        Long startTimestamp = sortedTimestamps[0];
        Long endTimestamp = Math.max(sortedTimestamps[sortedTimestamps.length - 1], startAndEndTimestamps[1]);

        // create a new datapoints map propagateDatpoints, which have all the
        // expected timestamps, then fill the missing value
        int index = 1;
        while (startTimestamp <= endTimestamp) {
            propagateDatapoints.put(startTimestamp, sortedDatapoints.containsKey(startTimestamp) ? sortedDatapoints.get(startTimestamp) : null);
            if (index >= sortedDatapoints.size()) {
             	startTimestamp = startTimestamp + windowSizeInSeconds * 1000;
                continue;
            }
            if ((startTimestamp + windowSizeInSeconds * 1000) < sortedTimestamps[index]) {
                startTimestamp = startTimestamp + windowSizeInSeconds * 1000;
            } else {
                startTimestamp = sortedTimestamps[index];
                index++;
            }
        }

        int newLength = propagateDatapoints.size();
        List<Long> newTimestamps = new ArrayList<Long>();
        List<Double> newValues = new ArrayList<>();

        for (Map.Entry<Long, Double> entry : propagateDatapoints.entrySet()) {
            newTimestamps.add(entry.getKey());
            newValues.add(entry.getValue());
        }

        Double prev = null;

        for (int i = 0; i < newLength; i++) {
            if (newValues.get(i) != null) {
                prev = newValues.get(i);
            } else {
                propagateDatapoints.put(newTimestamps.get(i), prev);
            }
        }
        
        metric.setDatapoints(propagateDatapoints);
    }
1270902
@VisibleForTesting
  static Timestamp convertTimestamp(io.opencensus.common.Timestamp censusTimestamp) {
    if (censusTimestamp.getSeconds() < 0) {
      // StackDriver doesn't handle negative timestamps.
      return Timestamp.newBuilder().build();
    }
    return Timestamp.newBuilder()
        .setSeconds(censusTimestamp.getSeconds())
        .setNanos(censusTimestamp.getNanos())
        .build();
  }
1311298
public static <T> void gauge(MetricNameDetails nameDetails, final Callable<T> impl) {
        gauge(nameDetails, new Gauge<T>() {
            @Override
            public T getValue() {
                try {
                    return impl.call();
                }
                catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
    }
294572
def _process_metric(self, data, metric, xtype, path, xform=None, tags=None, hostname=None):
        
        value = data

        # Traverse the nested dictionaries
        for key in path.split('.'):
            if value is not None:
                value = value.get(key)
            else:
                break

        if value is not None:
            if xform:
                value = xform(value)
            if xtype == "gauge":
                self.gauge(metric, value, tags=tags, hostname=hostname)
            else:
                self.rate(metric, value, tags=tags, hostname=hostname)
        else:
            self.log.debug("Metric not found: %s -> %s", path, metric)
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);
    }
294626
@Override
    protected void implementationSpecificPut(List<Metric> metrics,
                                             Set<String> scopeNames,
                                             Set<Pair<String, String>> scopesAndMetricNames,
                                             Map<String, MetatagsRecord> metatagsToPut) {
        requireNotDisposed();
        SystemAssert.requireArgument(metrics != null, "Metric list cannot be null.");

        for (Metric metric : metrics) {
            if (metric.getTags().isEmpty()) {
                _putWithoutTag(metric);
            }

            for (Entry<String, String> tag : metric.getTags().entrySet()) {
                _putWithTag(metric, tag);
            }
        }
    }
88588
@SuppressWarnings("unchecked")
  private void gatherOneMetric(
      String metricName,
      Metrics.MetricPublisherPublishMessage.Builder builder) {
    Object metricValue = metrics.get(metricName).getValueAndReset();
    // Decide how to handle the metric based on type
    if (metricValue == null) {
      return;
    }
    if (metricValue instanceof Map) {
      for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) metricValue).entrySet()) {
        if (entry.getKey() != null && entry.getValue() != null) {
          addDataToMetricPublisher(
              builder, metricName + "/" + entry.getKey().toString(), entry.getValue());
        }
      }
    } else if (metricValue instanceof Collection) {
      int index = 0;
      for (Object value : (Collection) metricValue) {
        addDataToMetricPublisher(builder, metricName + "/" + (index++), value);
      }
    } else {
      addDataToMetricPublisher(builder, metricName, metricValue);
    }
  }
626124
private Metric toMetric( Node node ) {
        if( node == null ) {
            return null;
        }

        Metric metric = new Metric();

        NodeList attributes = node.getChildNodes();
        for( int i = 0; i < attributes.getLength(); i++ ) {
            Node attribute = attributes.item(i);
            String name = attribute.getNodeName();

            if( name.equals("MetricName") ) {
                metric.setName(provider.getTextValue(attribute));
            }
            else if( name.equals("Namespace") ) {
                metric.setNamespace(provider.getTextValue(attribute));
            }
            else if( name.equals("Dimensions") ) {
                Map<String, String> dimensions = toMetadata(attribute.getChildNodes());
                if( dimensions != null ) {
                    metric.addMetadata(dimensions);
                }
            }
        }
        return metric;
    }
738026
private void parseMetricRule() {
    if (meta.getMetric() == null) {
      throw new IllegalStateException(
          "Timeseries metric UID object was null");
    }
    
    final String metric = meta.getMetric().getName();
    if (metric == null || metric.isEmpty()) {
      throw new IllegalStateException(
          "Timeseries metric name was null or empty");
    }
    
    processParsedValue(metric);
  }
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();
            }
        }
    }
507106
private static void fillValue2Node(List<MetricInfo> componentMetrics, Map<String, TopologyNode> nodes) {
        String NODE_DIM = MetricDef.EMMITTED_NUM;
        List<String> FILTER = Arrays.asList(MetricDef.EMMITTED_NUM, MetricDef.SEND_TPS, MetricDef.RECV_TPS);
        for (MetricInfo info : componentMetrics) {
            if (info == null) continue;
            for (Map.Entry<String, Map<Integer, MetricSnapshot>> metric : info.get_metrics().entrySet()) {
                String name = metric.getKey();
                String[] split_name = name.split("@");
                String metricName = UIMetricUtils.extractMetricName(split_name);
                String compName = UIMetricUtils.extractComponentName(split_name);

                TopologyNode node = nodes.get(compName);
                if (node != null && FILTER.contains(metricName)) {
                    for (Map.Entry<Integer, MetricSnapshot> winData : metric.getValue().entrySet()) {
                        node.putMapValue(metricName, winData.getKey(),
                                UIMetricUtils.getMetricValue(winData.getValue()));
                    }
                }

                if (metricName == null || !metricName.equals(NODE_DIM)) {
                    continue;
                }

                //get 60 window metric
                MetricSnapshot snapshot = metric.getValue().get(AsmWindow.M1_WINDOW);

                if (node != null) {
                    node.setValue(snapshot.get_longValue());
                    nodes.get(compName).setTitle("Emitted: " + UIMetricUtils.getMetricValue(snapshot));
                }
            }
        }
    }
110591
def MetricValueTypeFromPythonType(python_type):
  """"""
  if python_type in (int, long):
    return rdf_stats.MetricMetadata.ValueType.INT
  elif python_type == float:
    return rdf_stats.MetricMetadata.ValueType.FLOAT
  else:
    raise ValueError("Invalid value type: %s" % python_type)
678996
private boolean _canSkipWhileScanning(MetricSchemaRecordQuery query, RecordType type) {


		if( (RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type))
				&& !SchemaService.containsFilter(query.getTagKey())
				&& !SchemaService.containsFilter(query.getTagValue())
				&& !SchemaService.containsFilter(query.getNamespace())) {
			if(RecordType.METRIC.equals(type) && !SchemaService.containsFilter(query.getMetric())) {
				return false;
			}

			if(RecordType.SCOPE.equals(type) && !SchemaService.containsFilter(query.getScope())) {
				return false;
			}

			return true;
		}

		return false;
	}
432543
private static Metric createInternal(
      MetricDescriptor metricDescriptor, List<TimeSeries> timeSeriesList) {
    Utils.checkNotNull(metricDescriptor, "metricDescriptor");
    checkTypeMatch(metricDescriptor.getType(), timeSeriesList);
    return new AutoValue_Metric(metricDescriptor, timeSeriesList);
  }
1098476
static OcAgentMetricsServiceExportRpcHandler create(MetricsServiceStub stub) {
    OcAgentMetricsServiceExportRpcHandler exportRpcHandler =
        new OcAgentMetricsServiceExportRpcHandler();
    ExportResponseObserver exportResponseObserver = new ExportResponseObserver(exportRpcHandler);
    try {
      StreamObserver<ExportMetricsServiceRequest> exportRequestObserver =
          stub.export(exportResponseObserver);
      exportRpcHandler.setExportRequestObserver(exportRequestObserver);
    } catch (StatusRuntimeException e) {
      exportRpcHandler.onComplete(e);
    }
    return exportRpcHandler;
  }