com.google.api.Metric Java Examples

The following examples show how to use com.google.api.Metric. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StackdriverExportUtils.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static Metric createMetric(
    io.opencensus.metrics.export.MetricDescriptor metricDescriptor,
    List<LabelValue> labelValues,
    String domain,
    Map<LabelKey, LabelValue> constantLabels) {
  Metric.Builder builder = Metric.newBuilder();
  builder.setType(generateType(metricDescriptor.getName(), domain));
  Map<String, String> stringTagMap = Maps.newHashMap();
  List<LabelKey> labelKeys = metricDescriptor.getLabelKeys();
  for (int i = 0; i < labelValues.size(); i++) {
    String value = labelValues.get(i).getValue();
    if (value == null) {
      continue;
    }
    stringTagMap.put(labelKeys.get(i).getKey(), value);
  }
  for (Map.Entry<LabelKey, LabelValue> constantLabel : constantLabels.entrySet()) {
    String constantLabelKey = constantLabel.getKey().getKey();
    String constantLabelValue = constantLabel.getValue().getValue();
    constantLabelValue = constantLabelValue == null ? "" : constantLabelValue;
    stringTagMap.put(constantLabelKey, constantLabelValue);
  }
  builder.putAllLabels(stringTagMap);
  return builder.build();
}
 
Example #2
Source File: BigQueryRunner.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private TimeSeries prepareMetric(MetricDescriptor requiredMetric, long metricValue) {
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();
  TypedValue value = TypedValue.newBuilder().setInt64Value(metricValue).build();

  Point point = Point.newBuilder().setInterval(interval).setValue(value).build();

  List<Point> pointList = Lists.newArrayList();
  pointList.add(point);

  Metric metric = Metric.newBuilder().setType(requiredMetric.getName()).build();

  return TimeSeries.newBuilder().setMetric(metric).addAllPoints(pointList).build();
}
 
Example #3
Source File: StackdriverMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private TimeSeries createTimeSeries(Meter.Id id, TypedValue typedValue, MetricDescriptor.ValueType valueType,
                                    @Nullable String statistic) {
    if (client != null)
        createMetricDescriptorIfNecessary(client, id, valueType, statistic);

    String metricType = metricType(id, statistic);

    Map<String, String> metricLabels = getConventionTags(id).stream()
            .collect(Collectors.toMap(Tag::getKey, Tag::getValue));

    return TimeSeries.newBuilder()
            .setMetric(Metric.newBuilder()
                    .setType(metricType)
                    .putAllLabels(metricLabels)
                    .build())
            .setResource(MonitoredResource.newBuilder()
                    .setType(config.resourceType())
                    .putLabels("project_id", config.projectId())
                    .putAllLabels(config.resourceLabels())
                    .build())
            .setMetricKind(MetricDescriptor.MetricKind.GAUGE) // https://cloud.google.com/monitoring/api/v3/metrics-details#metric-kinds
            .setValueType(valueType)
            .addPoints(Point.newBuilder()
                    .setInterval(interval)
                    .setValue(typedValue)
                    .build())
            .build();
}
 
Example #4
Source File: StackdriverExportUtils.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
static List<TimeSeries> createTimeSeriesList(
    io.opencensus.metrics.export.Metric metric,
    MonitoredResource monitoredResource,
    String domain,
    String projectId,
    Map<LabelKey, LabelValue> constantLabels) {
  List<TimeSeries> timeSeriesList = Lists.newArrayList();
  io.opencensus.metrics.export.MetricDescriptor metricDescriptor = metric.getMetricDescriptor();

  if (!projectId.equals(cachedProjectIdForExemplar)) {
    cachedProjectIdForExemplar = projectId;
  }

  // Shared fields for all TimeSeries generated from the same Metric
  TimeSeries.Builder shared = TimeSeries.newBuilder();
  shared.setMetricKind(createMetricKind(metricDescriptor.getType()));
  shared.setResource(monitoredResource);
  shared.setValueType(createValueType(metricDescriptor.getType()));

  // Each entry in timeSeriesList will be converted into an independent TimeSeries object
  for (io.opencensus.metrics.export.TimeSeries timeSeries : metric.getTimeSeriesList()) {
    // TODO(mayurkale): Consider using setPoints instead of builder clone and addPoints.
    TimeSeries.Builder builder = shared.clone();
    builder.setMetric(
        createMetric(metricDescriptor, timeSeries.getLabelValues(), domain, constantLabels));

    io.opencensus.common.Timestamp startTimeStamp = timeSeries.getStartTimestamp();
    for (io.opencensus.metrics.export.Point point : timeSeries.getPoints()) {
      builder.addPoints(createPoint(point, startTimeStamp));
    }
    timeSeriesList.add(builder.build());
  }
  return timeSeriesList;
}
 
Example #5
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createMetric() {
  assertThat(
          StackdriverExportUtils.createMetric(
              METRIC_DESCRIPTOR, LABEL_VALUE, CUSTOM_OPENCENSUS_DOMAIN, DEFAULT_CONSTANT_LABELS))
      .isEqualTo(
          Metric.newBuilder()
              .setType("custom.googleapis.com/opencensus/" + METRIC_NAME)
              .putLabels("KEY1", "VALUE1")
              .putLabels(StackdriverExportUtils.OPENCENSUS_TASK_KEY.getKey(), DEFAULT_TASK_VALUE)
              .build());
}
 
Example #6
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createMetric_WithExternalMetricDomain() {
  String prometheusDomain = "external.googleapis.com/prometheus/";
  assertThat(
          StackdriverExportUtils.createMetric(
              METRIC_DESCRIPTOR, LABEL_VALUE, prometheusDomain, DEFAULT_CONSTANT_LABELS))
      .isEqualTo(
          Metric.newBuilder()
              .setType(prometheusDomain + METRIC_NAME)
              .putLabels("KEY1", "VALUE1")
              .putLabels(StackdriverExportUtils.OPENCENSUS_TASK_KEY.getKey(), DEFAULT_TASK_VALUE)
              .build());
}
 
Example #7
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createMetric_EmptyLabel() {
  assertThat(
          StackdriverExportUtils.createMetric(
              METRIC_DESCRIPTOR_2,
              EMPTY_LABEL_VALUE,
              CUSTOM_OPENCENSUS_DOMAIN,
              DEFAULT_CONSTANT_LABELS))
      .isEqualTo(
          Metric.newBuilder()
              .setType("custom.googleapis.com/opencensus/" + METRIC_NAME)
              .putLabels(StackdriverExportUtils.OPENCENSUS_TASK_KEY.getKey(), DEFAULT_TASK_VALUE)
              .build());
}
 
Example #8
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createMetric_EmptyConstantLabels() {
  assertThat(
          StackdriverExportUtils.createMetric(
              METRIC_DESCRIPTOR_2,
              EMPTY_LABEL_VALUE,
              CUSTOM_OPENCENSUS_DOMAIN,
              EMPTY_CONSTANT_LABELS))
      .isEqualTo(
          Metric.newBuilder().setType("custom.googleapis.com/opencensus/" + METRIC_NAME).build());
}
 
Example #9
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createMetric_CustomConstantLabels() {
  Map<LabelKey, LabelValue> constantLabels =
      Collections.singletonMap(LabelKey.create("my_key", "desc"), LabelValue.create("value"));
  assertThat(
          StackdriverExportUtils.createMetric(
              METRIC_DESCRIPTOR_2, EMPTY_LABEL_VALUE, CUSTOM_OPENCENSUS_DOMAIN, constantLabels))
      .isEqualTo(
          Metric.newBuilder()
              .setType("custom.googleapis.com/opencensus/" + METRIC_NAME)
              .putAllLabels(Collections.singletonMap("my_key", "value"))
              .build());
}
 
Example #10
Source File: MonitoringServlet.java    From tomcat-runtime with Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  JsonNode body = objectMapper.readTree(req.getReader());
  String name = body.path("name").asText();
  long token = body.path("token").asLong();

  logger.info("Creating Time series with name " + name + " and token " + token);

  MetricServiceClient serviceClient = MetricServiceClient.create();

  TimeSeries timeSeries =
      TimeSeries.newBuilder()
          .addPoints(Point.newBuilder()
              .setValue(TypedValue.newBuilder().setInt64Value(token))
              .setInterval(TimeInterval.newBuilder()
                .setEndTime(Timestamp.now().toProto())))
          .setMetric(Metric.newBuilder().setType(name))
          .build();

  serviceClient.createTimeSeries(
      ProjectName.create(ServiceOptions.getDefaultProjectId()),
      Collections.singletonList(timeSeries));

  resp.setContentType("text/plain");
  resp.getWriter().println("OK");
}
 
Example #11
Source File: MonitoringService.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 4 votes vote down vote up
private void flush() {
  HashMap<IMonitoringEvent, Long> flushEvents = null;
  synchronized (aggregateEvents) {
    flushEvents = new HashMap<>(aggregateEvents);
    aggregateEvents.clear();
  }

  try {
    Timestamp flushTime = Timestamps.fromMillis(System.currentTimeMillis());

    List<TimeSeries> timeSeriesList = new ArrayList<>();
    for (IMonitoringEvent event : monitoredEvents) {
      TimeInterval interval = TimeInterval.newBuilder()
          .setEndTime(flushTime)
          .build();
      TypedValue value = TypedValue.newBuilder()
          .setInt64Value(flushEvents.getOrDefault(event, 0L))
          .build();
      Point point = Point.newBuilder()
          .setInterval(interval)
          .setValue(value)
          .build();

      List<Point> pointList = new ArrayList<>();
      pointList.add(point);

      Metric metric = Metric.newBuilder()
          .setType(event.getMetricName())
          .build();

      TimeSeries timeSeries = TimeSeries.newBuilder()
          .setMetric(metric)
          .setMetricKind(MetricDescriptor.MetricKind.GAUGE)
          .setResource(monitoredResource)
          .addAllPoints(pointList)
          .build();

      timeSeriesList.add(timeSeries);
    }

    ProjectName projectName = ProjectName.of(projectId);
    CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder()
        .setName(projectName.toString())
        .addAllTimeSeries(timeSeriesList)
        .build();

    client.createTimeSeries(request);

    log.trace("Flushed {} non-zero time series", flushEvents.size());
    if (flushEvents.size() > 0) {
      log.info("Flushed: {}", flushEvents);
    }
  } catch (Throwable e) {
    log.error("Failed to flush time series", e);
  }
}
 
Example #12
Source File: StackdriverExportUtils.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static List<io.opencensus.metrics.export.Metric> convertSummaryMetric(
    io.opencensus.metrics.export.Metric summaryMetric) {
  List<io.opencensus.metrics.export.Metric> metricsList = Lists.newArrayList();
  final List<io.opencensus.metrics.export.TimeSeries> percentileTimeSeries = new ArrayList<>();
  final List<io.opencensus.metrics.export.TimeSeries> summaryCountTimeSeries = new ArrayList<>();
  final List<io.opencensus.metrics.export.TimeSeries> summarySumTimeSeries = new ArrayList<>();
  for (final io.opencensus.metrics.export.TimeSeries timeSeries :
      summaryMetric.getTimeSeriesList()) {
    final List<LabelValue> labelValuesWithPercentile =
        new ArrayList<>(timeSeries.getLabelValues());
    final io.opencensus.common.Timestamp timeSeriesTimestamp = timeSeries.getStartTimestamp();
    for (io.opencensus.metrics.export.Point point : timeSeries.getPoints()) {
      final io.opencensus.common.Timestamp pointTimestamp = point.getTimestamp();
      point
          .getValue()
          .match(
              Functions.<Void>returnNull(),
              Functions.<Void>returnNull(),
              Functions.<Void>returnNull(),
              new Function<Summary, Void>() {
                @Override
                public Void apply(Summary summary) {
                  Long count = summary.getCount();
                  if (count != null) {
                    createTimeSeries(
                        timeSeries.getLabelValues(),
                        Value.longValue(count),
                        pointTimestamp,
                        timeSeriesTimestamp,
                        summaryCountTimeSeries);
                  }
                  Double sum = summary.getSum();
                  if (sum != null) {
                    createTimeSeries(
                        timeSeries.getLabelValues(),
                        Value.doubleValue(sum),
                        pointTimestamp,
                        timeSeriesTimestamp,
                        summarySumTimeSeries);
                  }
                  Snapshot snapshot = summary.getSnapshot();
                  for (ValueAtPercentile valueAtPercentile : snapshot.getValueAtPercentiles()) {
                    labelValuesWithPercentile.add(
                        LabelValue.create(valueAtPercentile.getPercentile() + ""));
                    createTimeSeries(
                        labelValuesWithPercentile,
                        Value.doubleValue(valueAtPercentile.getValue()),
                        pointTimestamp,
                        null,
                        percentileTimeSeries);
                    labelValuesWithPercentile.remove(labelValuesWithPercentile.size() - 1);
                  }
                  return null;
                }
              },
              Functions.<Void>returnNull());
    }
  }

  // Metric for summary->count.
  if (summaryCountTimeSeries.size() > 0) {
    addMetric(
        metricsList,
        io.opencensus.metrics.export.MetricDescriptor.create(
            summaryMetric.getMetricDescriptor().getName() + SUMMARY_SUFFIX_COUNT,
            summaryMetric.getMetricDescriptor().getDescription(),
            "1",
            Type.CUMULATIVE_INT64,
            summaryMetric.getMetricDescriptor().getLabelKeys()),
        summaryCountTimeSeries);
  }

  // Metric for summary->sum.
  if (summarySumTimeSeries.size() > 0) {
    addMetric(
        metricsList,
        io.opencensus.metrics.export.MetricDescriptor.create(
            summaryMetric.getMetricDescriptor().getName() + SUMMARY_SUFFIX_SUM,
            summaryMetric.getMetricDescriptor().getDescription(),
            summaryMetric.getMetricDescriptor().getUnit(),
            Type.CUMULATIVE_DOUBLE,
            summaryMetric.getMetricDescriptor().getLabelKeys()),
        summarySumTimeSeries);
  }

  // Metric for summary->snapshot->percentiles.
  List<LabelKey> labelKeys = new ArrayList<>(summaryMetric.getMetricDescriptor().getLabelKeys());
  labelKeys.add(PERCENTILE_LABEL_KEY);
  addMetric(
      metricsList,
      io.opencensus.metrics.export.MetricDescriptor.create(
          summaryMetric.getMetricDescriptor().getName() + SNAPSHOT_SUFFIX_PERCENTILE,
          summaryMetric.getMetricDescriptor().getDescription(),
          summaryMetric.getMetricDescriptor().getUnit(),
          Type.GAUGE_DOUBLE,
          labelKeys),
      percentileTimeSeries);
  return metricsList;
}
 
Example #13
Source File: StackdriverExportUtils.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
private static void addMetric(
    List<io.opencensus.metrics.export.Metric> metricsList,
    io.opencensus.metrics.export.MetricDescriptor metricDescriptor,
    List<io.opencensus.metrics.export.TimeSeries> timeSeriesList) {
  metricsList.add(io.opencensus.metrics.export.Metric.create(metricDescriptor, timeSeriesList));
}
 
Example #14
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void createTimeSeriesList_Gauge() {
  io.opencensus.metrics.export.Metric metric =
      io.opencensus.metrics.export.Metric.create(
          GAUGE_METRIC_DESCRIPTOR, Arrays.asList(GAUGE_TIME_SERIES, GAUGE_TIME_SERIES_2));

  List<TimeSeries> timeSeriesList =
      StackdriverExportUtils.createTimeSeriesList(
          metric,
          DEFAULT_RESOURCE,
          CUSTOM_OPENCENSUS_DOMAIN,
          PROJECT_ID,
          DEFAULT_CONSTANT_LABELS);
  assertThat(timeSeriesList).hasSize(2);
  TimeSeries expected1 =
      TimeSeries.newBuilder()
          .setMetricKind(MetricKind.GAUGE)
          .setValueType(MetricDescriptor.ValueType.DOUBLE)
          .setMetric(
              StackdriverExportUtils.createMetric(
                  GAUGE_METRIC_DESCRIPTOR,
                  LABEL_VALUE,
                  CUSTOM_OPENCENSUS_DOMAIN,
                  DEFAULT_CONSTANT_LABELS))
          .setResource(MonitoredResource.newBuilder().setType("global"))
          .addPoints(StackdriverExportUtils.createPoint(POINT, null))
          .build();
  TimeSeries expected2 =
      TimeSeries.newBuilder()
          .setMetricKind(MetricKind.GAUGE)
          .setValueType(MetricDescriptor.ValueType.DOUBLE)
          .setMetric(
              StackdriverExportUtils.createMetric(
                  GAUGE_METRIC_DESCRIPTOR,
                  LABEL_VALUE_2,
                  CUSTOM_OPENCENSUS_DOMAIN,
                  DEFAULT_CONSTANT_LABELS))
          .setResource(MonitoredResource.newBuilder().setType("global"))
          .addPoints(StackdriverExportUtils.createPoint(POINT_2, null))
          .build();
  assertThat(timeSeriesList).containsExactly(expected1, expected2);
}
 
Example #15
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Demonstrates writing a time series value for the metric type
 * 'custom.google.apis.com/my_metric'.
 *
 * <p>This method assumes `my_metric` descriptor has already been created as a DOUBLE value_type
 * and GAUGE metric kind. If the metric descriptor doesn't exist, it will be auto-created.
 */
// CHECKSTYLE OFF: VariableDeclarationUsageDistance
void writeTimeSeries() throws IOException {
  // [START monitoring_write_timeseries]
  String projectId = System.getProperty("projectId");
  // Instantiates a client
  MetricServiceClient metricServiceClient = MetricServiceClient.create();

  // Prepares an individual data point
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();
  TypedValue value = TypedValue.newBuilder().setDoubleValue(123.45).build();
  Point point = Point.newBuilder().setInterval(interval).setValue(value).build();

  List<Point> pointList = new ArrayList<>();
  pointList.add(point);

  ProjectName name = ProjectName.of(projectId);

  // Prepares the metric descriptor
  Map<String, String> metricLabels = new HashMap<>();
  Metric metric =
      Metric.newBuilder()
          .setType("custom.googleapis.com/my_metric")
          .putAllLabels(metricLabels)
          .build();

  // Prepares the monitored resource descriptor
  Map<String, String> resourceLabels = new HashMap<>();
  resourceLabels.put("instance_id", "1234567890123456789");
  resourceLabels.put("zone", "us-central1-f");

  MonitoredResource resource =
      MonitoredResource.newBuilder().setType("gce_instance").putAllLabels(resourceLabels).build();

  // Prepares the time series request
  TimeSeries timeSeries =
      TimeSeries.newBuilder()
          .setMetric(metric)
          .setResource(resource)
          .addAllPoints(pointList)
          .build();

  List<TimeSeries> timeSeriesList = new ArrayList<>();
  timeSeriesList.add(timeSeries);

  CreateTimeSeriesRequest request =
      CreateTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .addAllTimeSeries(timeSeriesList)
          .build();

  // Writes time series data
  metricServiceClient.createTimeSeries(request);
  System.out.println("Done writing time series value.");
  // [END monitoring_write_timeseries]
}
 
Example #16
Source File: QuickstartSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void main(String... args) throws Exception {
  // Your Google Cloud Platform project ID
  String projectId = System.getProperty("projectId");

  if (projectId == null) {
    System.err.println("Usage: QuickstartSample -DprojectId=YOUR_PROJECT_ID");
    return;
  }

  // Instantiates a client
  MetricServiceClient metricServiceClient = MetricServiceClient.create();

  // Prepares an individual data point
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();
  TypedValue value = TypedValue.newBuilder().setDoubleValue(3.14).build();
  Point point = Point.newBuilder().setInterval(interval).setValue(value).build();

  List<Point> pointList = new ArrayList<>();
  pointList.add(point);

  ProjectName name = ProjectName.of(projectId);

  // Prepares the metric descriptor
  Map<String, String> metricLabels = new HashMap<String, String>();
  metricLabels.put("store_id", "Pittsburg");
  Metric metric =
      Metric.newBuilder()
          .setType("custom.googleapis.com/my_metric")
          .putAllLabels(metricLabels)
          .build();

  // Prepares the monitored resource descriptor
  Map<String, String> resourceLabels = new HashMap<String, String>();
  resourceLabels.put("instance_id", "1234567890123456789");
  resourceLabels.put("zone", "us-central1-f");
  MonitoredResource resource =
      MonitoredResource.newBuilder().setType("gce_instance").putAllLabels(resourceLabels).build();

  // Prepares the time series request
  TimeSeries timeSeries =
      TimeSeries.newBuilder()
          .setMetric(metric)
          .setResource(resource)
          .addAllPoints(pointList)
          .build();
  List<TimeSeries> timeSeriesList = new ArrayList<>();
  timeSeriesList.add(timeSeries);

  CreateTimeSeriesRequest request =
      CreateTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .addAllTimeSeries(timeSeriesList)
          .build();

  // Writes time series data
  metricServiceClient.createTimeSeries(request);

  System.out.printf("Done writing time series data.%n");

  metricServiceClient.close();
}