com.google.api.MetricDescriptor Java Examples

The following examples show how to use com.google.api.MetricDescriptor. 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: ClearCustomMetricDescriptors.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public static void clearCustomMetricDescriptors(MetricServiceSettings settings, String projectId) {
    try {
        MetricServiceClient client = MetricServiceClient.create(settings);

        Iterable<MetricServiceClient.ListMetricDescriptorsPage> listMetricDescriptorsPages = client.listMetricDescriptors(ListMetricDescriptorsRequest.newBuilder()
                .setName("projects/" + projectId)
                .setFilter("metric.type = starts_with(\"custom.googleapis.com/\")")
                .build()).iteratePages();

        int deleted = 0;
        for (MetricServiceClient.ListMetricDescriptorsPage page : listMetricDescriptorsPages) {
            for (MetricDescriptor metricDescriptor : page.getValues()) {
                System.out.println("deleting " + metricDescriptor.getName());
                client.deleteMetricDescriptor(metricDescriptor.getName());
                deleted++;
            }
        }

        System.out.println("Deleted " + deleted + " custom metric descriptors");
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #2
Source File: BigQueryRunner.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private void createMetricsIfNeeded() {
  // If all required metrics already exist, no need to make service calls.
  if (REQUIRED_METRICS
      .stream()
      .map(MetricDescriptor::getDisplayName)
      .allMatch(existingMetrics::contains)) {
    return;
  }
  ListMetricDescriptorsRequest listMetricsRequest =
      ListMetricDescriptorsRequest.newBuilder()
          .setName(projectName)
          .setFilter(CUSTOM_METRIC_FILTER)
          .build();
  ListMetricDescriptorsPagedResponse listMetricsResponse =
      client.listMetricDescriptors(listMetricsRequest);

  for (MetricDescriptor existingMetric : listMetricsResponse.iterateAll()) {
    existingMetrics.add(existingMetric.getDisplayName());
  }

  REQUIRED_METRICS
      .stream()
      .filter(metric -> !existingMetrics.contains(metric.getDisplayName()))
      .forEach(this::createMetric);
}
 
Example #3
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 #4
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Returns the first page of all metric descriptors. */
void listMetricDescriptors() throws IOException {
  // [START monitoring_list_descriptors]
  // Your Google Cloud Platform project ID
  String projectId = System.getProperty("projectId");

  final MetricServiceClient client = MetricServiceClient.create();
  ProjectName name = ProjectName.of(projectId);

  ListMetricDescriptorsRequest request =
      ListMetricDescriptorsRequest.newBuilder().setName(name.toString()).build();
  ListMetricDescriptorsPagedResponse response = client.listMetricDescriptors(request);

  System.out.println("Listing descriptors: ");

  for (MetricDescriptor d : response.iterateAll()) {
    System.out.println(d.getName() + " " + d.getDisplayName());
  }
  // [END monitoring_list_descriptors]
}
 
Example #5
Source File: QuotaMetricRuleValidator.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
/** Checks that the metric names and costs in metric rules are valid. */
private void checkMetricRulesAreValid(Service service) {
  Set<String> metricNames = new HashSet<>();
  for (MetricDescriptor metric : service.getMetricsList()) {
    metricNames.add(metric.getName());
  }

  for (MetricRule rule : service.getQuota().getMetricRulesList()) {
    for (Entry<String, Long> entry : rule.getMetricCosts().entrySet()) {
      if (!metricNames.contains(entry.getKey())) {
        error(
            MessageLocationContext.createForRepeated(rule, "metric_costs", entry.getKey()),
            "Metric '%s' referenced by metric rule '%s' does not exist.",
            entry.getKey(),
            rule.getSelector());
      }
      if (entry.getValue() < 0) {
        error(
            MessageLocationContext.createForRepeated(rule, "metric_costs", entry.getKey()),
            "Metric cost %d for metric '%s' must not be negative.",
            entry.getValue(),
            entry.getKey());
      }
    }
  }
}
 
Example #6
Source File: QuotaMetricsExistValidator.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
private void checkMetricReferencesExist(Service service) {
  Set<String> metricNames = new HashSet<>();
  for (MetricDescriptor metric : service.getMetricsList()) {
    metricNames.add(metric.getName());
  }
  Quota quotaConfig = service.getQuota();
  for (QuotaLimit limit : quotaConfig.getLimitsList()) {
    if (!metricNames.contains(limit.getMetric())) {
      error(
          MessageLocationContext.create(limit, "metric"),
          "Metric '%s' referenced by quota limit '%s' does not exist.",
          limit.getMetric(),
          limit.getName());
    }
  }
}
 
Example #7
Source File: ServiceControlConfigValidator.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
private void validateMetrics(List<MetricDescriptor> metricsList) {
  // - Metrics list cannot be longer than predefined limit.
  validateMaxListSize(
      ResolvedLocation.create(SimpleLocation.TOPLEVEL),
      "metrics list",
      metricsList,
      bounds.getMaxMetrics());
  // - Metric name must be unique across merged lists.
  for (MetricDescriptor metric : metricsList) {
    if (metrics.containsKey(metric.getName())) {
      error(
          MessageLocationContext.create(metric, MetricDescriptor.NAME_FIELD_NUMBER),
          "The '%s' metric is already defined. The metric name must be unique.",
          metric.getName());
    }
    metrics.put(metric.getName(), false);
    validateMetric(metric);
  }
}
 
Example #8
Source File: QuotaBuilder.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
private List<MetricDescriptor> parseMetrics(
    ServiceManagementExtension extension, VendorExtensionProtoConverter extensionConverter) {
  if (extension.getMetrics() == null) {
    return ImmutableList.of();
  }
  try {
    String extensionJson = new ObjectMapper().writer().writeValueAsString(extension.getMetrics());
    return extensionConverter.convertJsonArrayToProto(
        MetricDescriptor.getDefaultInstance(),
        new ObjectMapper().readTree(extensionJson),
        "metrics");
  } catch (IOException ex) {
    diagCollector.addDiag(
        Diag.error(
            new SimpleLocation("metrics"),
            "Extension %s cannot be converted into proto type %s. Details: %s",
            "quota",
            MetricDescriptor.getDescriptor().getFullName(),
            ex.getMessage()));
    return ImmutableList.of();
  }
}
 
Example #9
Source File: ProtoApiFromOpenApi.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
private void checkMatchingMetrics(Service.Builder serviceBuilder, MetricRule metricRule) {
  Set<String> definedMetrics = new HashSet<>();
  for (MetricDescriptor definedMetric : serviceBuilder.getMetricsList()) {
    definedMetrics.add(definedMetric.getName());
  }
  Set<String> missingMetrics =
      Sets.difference(metricRule.getMetricCosts().keySet(), definedMetrics);

  if (!missingMetrics.isEmpty()) {
    diagCollector.addDiag(
        Diag.error(
            new SimpleLocation(MetricRuleGenerator.QUOTA_SWAGGER_EXTENSION),
            "Quota Extension for method '%s' references undefined metric(s) '%s'",
            metricRule.getSelector(),
            Joiner.on(',').join(missingMetrics)));
  }
}
 
Example #10
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createTimeSeriesList_withCustomMonitoredResource() {
  MonitoredResource resource =
      MonitoredResource.newBuilder().setType("global").putLabels("key", "value").build();
  List<TimeSeries> timeSeriesList =
      StackdriverExportUtils.createTimeSeriesList(
          METRIC, resource, CUSTOM_OPENCENSUS_DOMAIN, PROJECT_ID, DEFAULT_CONSTANT_LABELS);
  assertThat(timeSeriesList)
      .containsExactly(
          TimeSeries.newBuilder()
              .setMetricKind(MetricKind.CUMULATIVE)
              .setValueType(MetricDescriptor.ValueType.DOUBLE)
              .setMetric(
                  StackdriverExportUtils.createMetric(
                      METRIC_DESCRIPTOR,
                      LABEL_VALUE,
                      CUSTOM_OPENCENSUS_DOMAIN,
                      DEFAULT_CONSTANT_LABELS))
              .setResource(resource)
              .addPoints(StackdriverExportUtils.createPoint(POINT, TIMESTAMP_2))
              .build());
}
 
Example #11
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createTimeSeriesList_Cumulative() {
  List<TimeSeries> timeSeriesList =
      StackdriverExportUtils.createTimeSeriesList(
          METRIC,
          DEFAULT_RESOURCE,
          CUSTOM_OPENCENSUS_DOMAIN,
          PROJECT_ID,
          DEFAULT_CONSTANT_LABELS);
  assertThat(timeSeriesList).hasSize(1);
  TimeSeries expectedTimeSeries =
      TimeSeries.newBuilder()
          .setMetricKind(MetricKind.CUMULATIVE)
          .setValueType(MetricDescriptor.ValueType.DOUBLE)
          .setMetric(
              StackdriverExportUtils.createMetric(
                  METRIC_DESCRIPTOR,
                  LABEL_VALUE,
                  CUSTOM_OPENCENSUS_DOMAIN,
                  DEFAULT_CONSTANT_LABELS))
          .setResource(MonitoredResource.newBuilder().setType("global"))
          .addPoints(StackdriverExportUtils.createPoint(POINT, TIMESTAMP_2))
          .build();
  assertThat(timeSeriesList).containsExactly(expectedTimeSeries);
}
 
Example #12
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createMetricDescriptor_WithCustomConstantLabels() {
  Map<LabelKey, LabelValue> constantLabels =
      Collections.singletonMap(LabelKey.create("my_key", "desc"), LabelValue.create("value"));
  MetricDescriptor metricDescriptor =
      StackdriverExportUtils.createMetricDescriptor(
          METRIC_DESCRIPTOR,
          PROJECT_ID,
          "custom.googleapis.com/myorg/",
          "myorg/",
          constantLabels);
  assertThat(metricDescriptor.getLabelsList())
      .containsExactly(
          LabelDescriptor.newBuilder()
              .setKey(LABEL_KEY.get(0).getKey())
              .setDescription(LABEL_KEY.get(0).getDescription())
              .setValueType(ValueType.STRING)
              .build(),
          LabelDescriptor.newBuilder()
              .setKey("my_key")
              .setDescription("desc")
              .setValueType(ValueType.STRING)
              .build());
}
 
Example #13
Source File: CreateMetricDescriptorExporter.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
public void export(Collection<Metric> metrics) {
  ArrayList<Metric> registeredMetrics = new ArrayList<>(metrics.size());
  for (Metric metric : metrics) {
    final io.opencensus.metrics.export.MetricDescriptor metricDescriptor =
        metric.getMetricDescriptor();
    if (metricDescriptor.getType() == Type.SUMMARY) {
      List<Metric> convertedMetrics = StackdriverExportUtils.convertSummaryMetric(metric);
      registeredMetrics.ensureCapacity(registeredMetrics.size() + convertedMetrics.size());
      for (Metric convertedMetric : convertedMetrics) {
        if (registerMetricDescriptor(convertedMetric.getMetricDescriptor())) {
          registeredMetrics.add(convertedMetric);
        }
      }
    } else {
      if (registerMetricDescriptor(metricDescriptor)) {
        registeredMetrics.add(metric);
      }
    }
  }
  nextExporter.export(registeredMetrics);
}
 
Example #14
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 #15
Source File: StackdriverExportUtils.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static MetricDescriptor.ValueType createValueType(Type type) {
  if (type == Type.CUMULATIVE_DOUBLE || type == Type.GAUGE_DOUBLE) {
    return MetricDescriptor.ValueType.DOUBLE;
  } else if (type == Type.GAUGE_INT64 || type == Type.CUMULATIVE_INT64) {
    return MetricDescriptor.ValueType.INT64;
  } else if (type == Type.GAUGE_DISTRIBUTION || type == Type.CUMULATIVE_DISTRIBUTION) {
    return MetricDescriptor.ValueType.DISTRIBUTION;
  }
  return MetricDescriptor.ValueType.UNRECOGNIZED;
}
 
Example #16
Source File: BigQueryRunner.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private void createMetric(MetricDescriptor newMetric) {
  CreateMetricDescriptorRequest request =
      CreateMetricDescriptorRequest.newBuilder()
          .setName(projectName)
          .setMetricDescriptor(newMetric)
          .build();

  client.createMetricDescriptor(request);
}
 
Example #17
Source File: BigQueryRunner.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public List<TimeSeriesSummary> getTimeSeriesValues() {
  List<TimeSeriesSummary> summaries = Lists.newArrayList();
  createMetricsIfNeeded();
  for (MetricDescriptor metric : REQUIRED_METRICS) {
    ListTimeSeriesRequest listTimeSeriesRequest =
        ListTimeSeriesRequest.newBuilder()
            .setName(projectName)
            .setFilter(String.format("metric.type = \"%s\"", metric.getType()))
            .setInterval(
                TimeInterval.newBuilder()
                    .setStartTime(
                        Timestamps.subtract(
                            Timestamps.fromMillis(System.currentTimeMillis()),
                            com.google.protobuf.Duration.newBuilder()
                                .setSeconds(60L * 60L * 24L * 30L) //  30 days ago
                                .build()))
                    .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
                    .build())
            .build();
    try {
      ListTimeSeriesPagedResponse listTimeSeriesResponse =
          client.listTimeSeries(listTimeSeriesRequest);
      ArrayList<TimeSeries> timeSeries = Lists.newArrayList(listTimeSeriesResponse.iterateAll());
      summaries.addAll(
          timeSeries
              .stream()
              .map(TimeSeriesSummary::fromTimeSeries)
              .collect(Collectors.toList()));
    } catch (RuntimeException ex) {
      os.println("MetricDescriptors not yet synced. Please try again in a moment.");
    }
  }
  return summaries;
}
 
Example #18
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a metric descriptor.
 *
 * <p>See:
 * https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create
 *
 * @param type The metric type
 */
void createMetricDescriptor(String type) throws IOException {
  // [START monitoring_create_metric]
  // Your Google Cloud Platform project ID
  String projectId = System.getProperty("projectId");
  String metricType = CUSTOM_METRIC_DOMAIN + "/" + type;

  final MetricServiceClient client = MetricServiceClient.create();
  ProjectName name = ProjectName.of(projectId);

  MetricDescriptor descriptor =
      MetricDescriptor.newBuilder()
          .setType(metricType)
          .addLabels(
              LabelDescriptor.newBuilder()
                  .setKey("store_id")
                  .setValueType(LabelDescriptor.ValueType.STRING))
          .setDescription("This is a simple example of a custom metric.")
          .setMetricKind(MetricDescriptor.MetricKind.GAUGE)
          .setValueType(MetricDescriptor.ValueType.DOUBLE)
          .build();

  CreateMetricDescriptorRequest request =
      CreateMetricDescriptorRequest.newBuilder()
          .setName(name.toString())
          .setMetricDescriptor(descriptor)
          .build();

  client.createMetricDescriptor(request);
  // [END monitoring_create_metric]
}
 
Example #19
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 #20
Source File: StackdriverMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private void createMetricDescriptorIfNecessary(MetricServiceClient client, Meter.Id id,
                                               MetricDescriptor.ValueType valueType, @Nullable String statistic) {

    if (verifiedDescriptors.isEmpty()) {
        prePopulateVerifiedDescriptors();
    }

    final String metricType = metricType(id, statistic);
    if (!verifiedDescriptors.contains(metricType)) {
        MetricDescriptor descriptor = MetricDescriptor.newBuilder()
                .setType(metricType)
                .setDescription(id.getDescription() == null ? "" : id.getDescription())
                .setMetricKind(MetricDescriptor.MetricKind.GAUGE)
                .setValueType(valueType)
                .build();

        ProjectName name = ProjectName.of(config.projectId());

        CreateMetricDescriptorRequest request = CreateMetricDescriptorRequest.newBuilder()
                .setName(name.toString())
                .setMetricDescriptor(descriptor)
                .build();

        logger.trace("creating metric descriptor:{}{}", System.lineSeparator(), request);

        try {
            client.createMetricDescriptor(request);
            verifiedDescriptors.add(metricType);
        } catch (ApiException e) {
            logger.warn("failed to create metric descriptor in Stackdriver for meter " + id, e);
        }
    }
}
 
Example #21
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 #22
Source File: CreateMetricDescriptorExporterTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void export_MetricNameWithCustomDomain() {
  FakeMetricExporter fakeMetricExporter = new FakeMetricExporter();
  CreateMetricDescriptorExporter exporter =
      new CreateMetricDescriptorExporter(
          PROJECT_ID,
          new FakeMetricServiceClient(mockStub),
          null,
          DEFAULT_CONSTANT_LABELS,
          fakeMetricExporter);
  exporter.export(Arrays.asList(METRIC_5));

  verify(mockStub, times(1)).createMetricDescriptorCallable();

  MetricDescriptor descriptor =
      StackdriverExportUtils.createMetricDescriptor(
          METRIC_DESCRIPTOR_5,
          PROJECT_ID,
          CUSTOM_OPENCENSUS_DOMAIN,
          DEFAULT_DISPLAY_NAME_PREFIX,
          DEFAULT_CONSTANT_LABELS);
  verify(mockCreateMetricDescriptorCallable, times(1))
      .call(
          eq(
              CreateMetricDescriptorRequest.newBuilder()
                  .setName("projects/" + PROJECT_ID)
                  .setMetricDescriptor(descriptor)
                  .build()));
}
 
Example #23
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createMetricDescriptor_cumulative() {
  MetricDescriptor metricDescriptor =
      StackdriverExportUtils.createMetricDescriptor(
          METRIC_DESCRIPTOR_2,
          PROJECT_ID,
          CUSTOM_OPENCENSUS_DOMAIN,
          DEFAULT_DISPLAY_NAME_PREFIX,
          DEFAULT_CONSTANT_LABELS);
  assertThat(metricDescriptor.getName())
      .isEqualTo(
          "projects/"
              + PROJECT_ID
              + "/metricDescriptors/custom.googleapis.com/opencensus/"
              + METRIC_NAME);
  assertThat(metricDescriptor.getDescription()).isEqualTo(METRIC_DESCRIPTION);
  assertThat(metricDescriptor.getDisplayName()).isEqualTo("OpenCensus/" + METRIC_NAME);
  assertThat(metricDescriptor.getType())
      .isEqualTo("custom.googleapis.com/opencensus/" + METRIC_NAME);
  assertThat(metricDescriptor.getUnit()).isEqualTo("1");
  assertThat(metricDescriptor.getMetricKind()).isEqualTo(MetricKind.CUMULATIVE);
  assertThat(metricDescriptor.getValueType()).isEqualTo(MetricDescriptor.ValueType.INT64);
  assertThat(metricDescriptor.getLabelsList())
      .containsExactly(
          LabelDescriptor.newBuilder()
              .setKey(StackdriverExportUtils.OPENCENSUS_TASK_KEY.getKey())
              .setDescription(StackdriverExportUtils.OPENCENSUS_TASK_KEY.getDescription())
              .setValueType(ValueType.STRING)
              .build());
}
 
Example #24
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createMetricDescriptor() {
  MetricDescriptor metricDescriptor =
      StackdriverExportUtils.createMetricDescriptor(
          METRIC_DESCRIPTOR,
          PROJECT_ID,
          "custom.googleapis.com/myorg/",
          "myorg/",
          DEFAULT_CONSTANT_LABELS);
  assertThat(metricDescriptor.getName())
      .isEqualTo(
          "projects/"
              + PROJECT_ID
              + "/metricDescriptors/custom.googleapis.com/myorg/"
              + METRIC_NAME);
  assertThat(metricDescriptor.getDescription()).isEqualTo(METRIC_DESCRIPTION);
  assertThat(metricDescriptor.getDisplayName()).isEqualTo("myorg/" + METRIC_NAME);
  assertThat(metricDescriptor.getType()).isEqualTo("custom.googleapis.com/myorg/" + METRIC_NAME);
  assertThat(metricDescriptor.getUnit()).isEqualTo(METRIC_UNIT);
  assertThat(metricDescriptor.getMetricKind()).isEqualTo(MetricKind.CUMULATIVE);

  assertThat(metricDescriptor.getValueType()).isEqualTo(MetricDescriptor.ValueType.DOUBLE);
  assertThat(metricDescriptor.getLabelsList())
      .containsExactly(
          LabelDescriptor.newBuilder()
              .setKey(LABEL_KEY.get(0).getKey())
              .setDescription(LABEL_KEY.get(0).getDescription())
              .setValueType(ValueType.STRING)
              .build(),
          LabelDescriptor.newBuilder()
              .setKey(StackdriverExportUtils.OPENCENSUS_TASK_KEY.getKey())
              .setDescription(StackdriverExportUtils.OPENCENSUS_TASK_KEY.getDescription())
              .setValueType(ValueType.STRING)
              .build());
}
 
Example #25
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createValueType() {
  assertThat(StackdriverExportUtils.createValueType(Type.GAUGE_DOUBLE))
      .isEqualTo(MetricDescriptor.ValueType.DOUBLE);
  assertThat(StackdriverExportUtils.createValueType(Type.CUMULATIVE_INT64))
      .isEqualTo(MetricDescriptor.ValueType.INT64);
  assertThat(StackdriverExportUtils.createValueType(Type.GAUGE_INT64))
      .isEqualTo(MetricDescriptor.ValueType.INT64);
  assertThat(StackdriverExportUtils.createValueType(Type.CUMULATIVE_DOUBLE))
      .isEqualTo(MetricDescriptor.ValueType.DOUBLE);
  assertThat(StackdriverExportUtils.createValueType(Type.GAUGE_DISTRIBUTION))
      .isEqualTo(MetricDescriptor.ValueType.DISTRIBUTION);
  assertThat(StackdriverExportUtils.createValueType(Type.CUMULATIVE_DISTRIBUTION))
      .isEqualTo(MetricDescriptor.ValueType.DISTRIBUTION);
}
 
Example #26
Source File: CreateMetricDescriptorExporterTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void export() {
  FakeMetricExporter fakeMetricExporter = new FakeMetricExporter();
  CreateMetricDescriptorExporter exporter =
      new CreateMetricDescriptorExporter(
          PROJECT_ID,
          new FakeMetricServiceClient(mockStub),
          null,
          DEFAULT_CONSTANT_LABELS,
          fakeMetricExporter);
  exporter.export(Arrays.asList(METRIC, METRIC_2));

  verify(mockStub, times(2)).createMetricDescriptorCallable();

  MetricDescriptor descriptor =
      StackdriverExportUtils.createMetricDescriptor(
          METRIC_DESCRIPTOR,
          PROJECT_ID,
          CUSTOM_OPENCENSUS_DOMAIN,
          DEFAULT_DISPLAY_NAME_PREFIX,
          DEFAULT_CONSTANT_LABELS);
  verify(mockCreateMetricDescriptorCallable, times(1))
      .call(
          eq(
              CreateMetricDescriptorRequest.newBuilder()
                  .setName("projects/" + PROJECT_ID)
                  .setMetricDescriptor(descriptor)
                  .build()));

  MetricDescriptor descriptor2 =
      StackdriverExportUtils.createMetricDescriptor(
          METRIC_DESCRIPTOR_2,
          PROJECT_ID,
          CUSTOM_OPENCENSUS_DOMAIN,
          DEFAULT_DISPLAY_NAME_PREFIX,
          DEFAULT_CONSTANT_LABELS);
  verify(mockCreateMetricDescriptorCallable, times(1))
      .call(
          eq(
              CreateMetricDescriptorRequest.newBuilder()
                  .setName("projects/" + PROJECT_ID)
                  .setMetricDescriptor(descriptor2)
                  .build()));
  assertThat(fakeMetricExporter.getLastExported()).containsExactly(METRIC, METRIC_2);
}
 
Example #27
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 #28
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 #29
Source File: ServiceControlConfigValidator.java    From api-compiler with Apache License 2.0 4 votes vote down vote up
private void validateMetric(MetricDescriptor metric) {
  // - Metric name cannot be empty.
  // - Metric name cannot be longer than predefined limit.
  validateNonNullStringLength(
      MessageLocationContext.create(metric, MetricDescriptor.NAME_FIELD_NUMBER),
      "metric name",
      metric.getName());
  // - Metric display name cannot be longer than predefined limit.
  validateStringLength(
      MessageLocationContext.create(metric, MetricDescriptor.DISPLAY_NAME_FIELD_NUMBER),
      "metric display name",
      metric.getDisplayName());
  // - Metric description cannot be longer than predefined limit.
  validateStringLength(
      MessageLocationContext.create(metric, MetricDescriptor.DESCRIPTION_FIELD_NUMBER),
      "metric description",
      metric.getDescription());

  // - Label key value cannot be empty while the label keys list can be empty.
  validateLabels(
      MessageLocationContext.create(metric, MetricDescriptor.NAME_FIELD_NUMBER),
      String.format("'%s' metric", metric.getName()),
      metric.getLabelsList());

  // - Metric kind must be set to one of the predefined values except for
  // METRIC_KIND_UNSPECIFIED.
  if (metric.getMetricKind() == MetricKind.METRIC_KIND_UNSPECIFIED) {
    error(
        MessageLocationContext.create(metric, MetricDescriptor.NAME_FIELD_NUMBER),
        "The metric kind of the '%s' metric is not specified. "
            + "Allowed values are GAUGE, DELTA and CUMULATIVE.",
        metric.getName());
  }
  // - Metric value type must be set to one of the predefined values except for
  // VALUE_TYPE_UNSPECIFIED.
  if (metric.getValueType() == ValueType.VALUE_TYPE_UNSPECIFIED) {
    error(
        MessageLocationContext.create(metric, MetricDescriptor.NAME_FIELD_NUMBER),
        "The metric value type of the '%s' metric is not specified. "
            + "Allowed values are BOOL, INT64, DOUBLE, STRING, DISTRIBUTION and MONEY.",
        metric.getName());
  }

  // - Metrics of type BOOL and STRING must be of GAUGE kind.
  if ((metric.getValueType() == ValueType.BOOL || metric.getValueType() == ValueType.STRING)
      && metric.getMetricKind() != MetricKind.GAUGE) {
    error(
        MessageLocationContext.create(metric, MetricDescriptor.NAME_FIELD_NUMBER),
        "The '%s' metric is of %s type and of %s kind. "
            + "Metrics of value type BOOL and STRING must be of GUAGE kind.",
        metric.getName(),
        metric.getValueType().getValueDescriptor().getName(),
        metric.getMetricKind().getValueDescriptor().getName());
  }

  metricDescriptors.put(metric.getName(), metric);
}
 
Example #30
Source File: StackdriverMeterRegistry.java    From micrometer with Apache License 2.0 4 votes vote down vote up
TimeSeries createTimeSeries(Meter meter, Distribution distribution) {
    return createTimeSeries(meter.getId(),
            TypedValue.newBuilder().setDistributionValue(distribution).build(),
            MetricDescriptor.ValueType.DISTRIBUTION,
            null);
}