com.google.monitoring.v3.TimeInterval Java Examples

The following examples show how to use com.google.monitoring.v3.TimeInterval. 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: StackdriverExportUtils.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static Point createPoint(
    io.opencensus.metrics.export.Point point,
    @javax.annotation.Nullable io.opencensus.common.Timestamp startTimestamp) {
  TimeInterval.Builder timeIntervalBuilder = TimeInterval.newBuilder();
  timeIntervalBuilder.setEndTime(convertTimestamp(point.getTimestamp()));
  if (startTimestamp != null) {
    timeIntervalBuilder.setStartTime(convertTimestamp(startTimestamp));
  }

  Point.Builder builder = Point.newBuilder();
  builder.setInterval(timeIntervalBuilder.build());
  builder.setValue(createTypedValue(point.getValue()));
  return builder.build();
}
 
Example #3
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createPoint() {
  assertThat(StackdriverExportUtils.createPoint(POINT, null))
      .isEqualTo(
          com.google.monitoring.v3.Point.newBuilder()
              .setInterval(
                  TimeInterval.newBuilder()
                      .setEndTime(StackdriverExportUtils.convertTimestamp(TIMESTAMP))
                      .build())
              .setValue(StackdriverExportUtils.createTypedValue(VALUE_DOUBLE))
              .build());
}
 
Example #4
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createPoint_Cumulative() {
  assertThat(StackdriverExportUtils.createPoint(POINT, TIMESTAMP_2))
      .isEqualTo(
          com.google.monitoring.v3.Point.newBuilder()
              .setInterval(
                  TimeInterval.newBuilder()
                      .setStartTime(StackdriverExportUtils.convertTimestamp(TIMESTAMP_2))
                      .setEndTime(StackdriverExportUtils.convertTimestamp(TIMESTAMP))
                      .build())
              .setValue(StackdriverExportUtils.createTypedValue(VALUE_DOUBLE))
              .build());
}
 
Example #5
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 #6
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 #7
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 #8
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 #9
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 #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: MetricScaler.java    From cloud-bigtable-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the latest value for the metric defined by {@link #CPU_METRIC}.
 * @return
 * @throws IOException
 */
Point getLatestValue() throws IOException {
  // [START get_bigtable_cpu]
  Timestamp now = timeXMinutesAgo(0);
  Timestamp fiveMinutesAgo = timeXMinutesAgo(5);
  TimeInterval interval =
      TimeInterval.newBuilder().setStartTime(fiveMinutesAgo).setEndTime(now).build();
  String filter = "metric.type=\"" + CPU_METRIC + "\"";
  ListTimeSeriesPagedResponse response =
      metricServiceClient.listTimeSeries(projectName, filter, interval, TimeSeriesView.FULL);
  return response.getPage().getValues().iterator().next().getPointsList().get(0);
  // [END get_bigtable_cpu]
}
 
Example #12
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 #13
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 #14
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();
}