com.google.monitoring.v3.TimeSeries Java Examples

The following examples show how to use com.google.monitoring.v3.TimeSeries. 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: 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 #2
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 #3
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 #4
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Demonstrates listing time series using a filter. */
void listTimeSeries(String filter) throws IOException {
  // [START monitoring_read_timeseries_simple]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.of(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setStartTime(Timestamps.fromMillis(startMillis))
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();

  ListTimeSeriesRequest.Builder requestBuilder =
      ListTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .setFilter(filter)
          .setInterval(interval);

  ListTimeSeriesRequest request = requestBuilder.build();

  ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_simple]
}
 
Example #5
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 #6
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 #7
Source File: TimeSeriesSummary.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private Int64TimeSeriesSummary(TimeSeries timeSeries) {
  super(timeSeries);
  Point max = getMostRecentPoint(timeSeries);
  if (max == null) {
    return;
  }
  mostRecentValue = max.getValue().getInt64Value();
  values =
      Lists.newArrayList(
          Collections2.transform(
              timeSeries.getPointsList(), point -> point.getValue().getInt64Value()));
}
 
Example #8
Source File: TimeSeriesSummary.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private StringTimeSeriesSummary(TimeSeries timeSeries) {
  super(timeSeries);
  Point max = getMostRecentPoint(timeSeries);
  if (max == null) {
    return;
  }
  mostRecentValue = max.getValue().getStringValue();
  values =
      Lists.newArrayList(
          Collections2.transform(
              timeSeries.getPointsList(), point -> point.getValue().getStringValue()));
}
 
Example #9
Source File: TimeSeriesSummary.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
Point getMostRecentPoint(TimeSeries timeSeries) {
  Point max =
      Collections.max(
          timeSeries.getPointsList(),
          Comparator.comparingLong(p -> p.getInterval().getEndTime().getSeconds()));
  mostRecentRunTime = max.getInterval().getEndTime();
  return max;
}
 
Example #10
Source File: TimeSeriesSummary.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static TimeSeriesSummary fromTimeSeries(TimeSeries timeSeries) {
  switch (timeSeries.getValueType()) {
    case STRING:
      return new StringTimeSeriesSummary(timeSeries);
    case INT64:
      return new Int64TimeSeriesSummary(timeSeries);
    default:
      return null;
  }
}
 
Example #11
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Demonstrates listing time series and aggregating and reducing them. */
void listTimeSeriesReduce() throws IOException {
  // [START monitoring_read_timeseries_reduce]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.of(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setStartTime(Timestamps.fromMillis(startMillis))
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();

  Aggregation aggregation =
      Aggregation.newBuilder()
          .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
          .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
          .setCrossSeriesReducer(Aggregation.Reducer.REDUCE_MEAN)
          .build();

  ListTimeSeriesRequest.Builder requestBuilder =
      ListTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
          .setInterval(interval)
          .setAggregation(aggregation);

  ListTimeSeriesRequest request = requestBuilder.build();

  ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_reduce]
}
 
Example #12
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Demonstrates listing time series and aggregating them. */
void listTimeSeriesAggregrate() throws IOException {
  // [START monitoring_read_timeseries_align]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.of(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setStartTime(Timestamps.fromMillis(startMillis))
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();

  Aggregation aggregation =
      Aggregation.newBuilder()
          .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
          .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
          .build();

  ListTimeSeriesRequest.Builder requestBuilder =
      ListTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
          .setInterval(interval)
          .setAggregation(aggregation);

  ListTimeSeriesRequest request = requestBuilder.build();

  ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_align]
}
 
Example #13
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Demonstrates listing time series headers. */
void listTimeSeriesHeaders() throws IOException {
  // [START monitoring_read_timeseries_fields]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.of(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setStartTime(Timestamps.fromMillis(startMillis))
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();

  ListTimeSeriesRequest.Builder requestBuilder =
      ListTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
          .setInterval(interval)
          .setView(ListTimeSeriesRequest.TimeSeriesView.HEADERS);

  ListTimeSeriesRequest request = requestBuilder.build();

  ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

  System.out.println("Got timeseries headers: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_fields]
}
 
Example #14
Source File: CreateTimeSeriesExporterTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void export() {
  CreateTimeSeriesExporter exporter =
      new CreateTimeSeriesExporter(
          PROJECT_ID,
          new FakeMetricServiceClient(mockStub),
          DEFAULT_RESOURCE,
          null,
          DEFAULT_CONSTANT_LABELS);
  exporter.export(Collections.singletonList(METRIC));
  verify(mockStub, times(1)).createTimeSeriesCallable();

  List<TimeSeries> timeSeries =
      StackdriverExportUtils.createTimeSeriesList(
          METRIC,
          DEFAULT_RESOURCE,
          StackdriverExportUtils.CUSTOM_OPENCENSUS_DOMAIN,
          PROJECT_ID,
          DEFAULT_CONSTANT_LABELS);

  verify(mockCreateTimeSeriesCallable, times(1))
      .call(
          eq(
              CreateTimeSeriesRequest.newBuilder()
                  .setName("projects/" + PROJECT_ID)
                  .addAllTimeSeries(timeSeries)
                  .build()));
}
 
Example #15
Source File: StackdriverExportUtils.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static void createTimeSeries(
    List<LabelValue> labelValues,
    Value value,
    io.opencensus.common.Timestamp pointTimestamp,
    @javax.annotation.Nullable io.opencensus.common.Timestamp timeSeriesTimestamp,
    List<io.opencensus.metrics.export.TimeSeries> timeSeriesList) {
  timeSeriesList.add(
      io.opencensus.metrics.export.TimeSeries.createWithOnePoint(
          labelValues,
          io.opencensus.metrics.export.Point.create(value, pointTimestamp),
          timeSeriesTimestamp));
}
 
Example #16
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 #17
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 #18
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 #19
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();
}
 
Example #20
Source File: TimeSeriesSummary.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
private TimeSeriesSummary(TimeSeries timeSeries) {
  name = timeSeries.getMetric().getType();
}
 
Example #21
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 #22
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void createTimeSeriesList_Distribution() {
  List<TimeSeries> timeSeriesList =
      StackdriverExportUtils.createTimeSeriesList(
          DISTRIBUTION_METRIC,
          DEFAULT_RESOURCE,
          CUSTOM_OPENCENSUS_DOMAIN,
          PROJECT_ID,
          DEFAULT_CONSTANT_LABELS);

  assertThat(timeSeriesList.size()).isEqualTo(1);
  TimeSeries timeSeries = timeSeriesList.get(0);
  assertThat(timeSeries.getPointsCount()).isEqualTo(1);
  String expectedSpanName =
      "projects/id/traces/00000000000000000000000000000000/spans/0000000000000000";
  assertThat(timeSeries.getPoints(0).getValue().getDistributionValue())
      .isEqualTo(
          com.google.api.Distribution.newBuilder()
              .setCount(3)
              .setMean(0.6666666666666666)
              .setBucketOptions(
                  BucketOptions.newBuilder()
                      .setExplicitBuckets(
                          Explicit.newBuilder()
                              .addAllBounds(Arrays.asList(0.0, 1.0, 3.0, 5.0))
                              .build())
                      .build())
              .addAllBucketCounts(Arrays.asList(0L, 3L, 1L, 2L, 4L))
              .setSumOfSquaredDeviation(14)
              .addAllExemplars(
                  Arrays.<Distribution.Exemplar>asList(
                      Distribution.Exemplar.newBuilder()
                          .setValue(1.2)
                          .setTimestamp(StackdriverExportUtils.convertTimestamp(TIMESTAMP_2))
                          .addAttachments(
                              Any.newBuilder()
                                  .setTypeUrl(
                                      StackdriverExportUtils.EXEMPLAR_ATTACHMENT_TYPE_STRING)
                                  .setValue(ByteString.copyFromUtf8("value"))
                                  .build())
                          .build(),
                      Distribution.Exemplar.newBuilder()
                          .setValue(5.6)
                          .setTimestamp(StackdriverExportUtils.convertTimestamp(TIMESTAMP_3))
                          .addAttachments(
                              Any.newBuilder()
                                  .setTypeUrl(
                                      StackdriverExportUtils
                                          .EXEMPLAR_ATTACHMENT_TYPE_SPAN_CONTEXT)
                                  .setValue(
                                      SpanContext.newBuilder()
                                          .setSpanName(expectedSpanName)
                                          .build()
                                          .toByteString())
                                  .build())
                          .build()))
              .build());
}
 
Example #23
Source File: BigQueryRunner.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public void runQuery() throws InterruptedException {
  QueryJobConfiguration queryConfig =
      QueryJobConfiguration.newBuilder(
              "SELECT "
                  + "CONCAT('https://stackoverflow.com/questions/', CAST(id as STRING)) as url, "
                  + "view_count "
                  + "FROM `bigquery-public-data.stackoverflow.posts_questions` "
                  + "WHERE tags like '%google-bigquery%' "
                  + "ORDER BY favorite_count DESC LIMIT 10")
          // Use standard SQL syntax for queries.
          // See: https://cloud.google.com/bigquery/sql-reference/
          .setUseLegacySql(false)
          .build();

  List<TimeSeries> timeSeriesList = new ArrayList<>();

  long queryStartTime = System.currentTimeMillis();

  // Create a job ID so that we can safely retry.
  JobId jobId = JobId.of(UUID.randomUUID().toString());
  Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

  // Wait for the query to complete.
  queryJob = queryJob.waitFor();

  // Check for errors
  if (queryJob == null) {
    throw new RuntimeException("Job no longer exists");
  } else if (queryJob.getStatus().getError() != null) {
    // You can also look at queryJob.getStatus().getExecutionErrors() for all
    // errors, not just the latest one.
    throw new RuntimeException(queryJob.getStatus().getError().toString());
  }

  // Log the result metrics.
  TableResult result = queryJob.getQueryResults();

  long queryEndTime = System.currentTimeMillis();
  // Add query duration metric.
  timeSeriesList.add(prepareMetric(QUERY_DURATION_METRIC, queryEndTime - queryStartTime));

  // Add rows returned metric.
  timeSeriesList.add(prepareMetric(ROWS_RETURNED_METRIC, result.getTotalRows()));

  // Prepares the time series request
  CreateTimeSeriesRequest request =
      CreateTimeSeriesRequest.newBuilder()
          .setName(projectName)
          .addAllTimeSeries(timeSeriesList)
          .build();

  createMetricsIfNeeded();
  client.createTimeSeries(request);
  os.println("Done writing metrics.");

  mostRecentRunResult = result;
}
 
Example #24
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 #25
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;
}