com.google.monitoring.v3.CreateTimeSeriesRequest Java Examples

The following examples show how to use com.google.monitoring.v3.CreateTimeSeriesRequest. 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: BigQueryRunnerTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  bout = new ByteArrayOutputStream();
  PrintStream out = new PrintStream(bout);

  MetricServiceClient metricsClient = MetricServiceClient.create(metricsServiceStub);
  app = new BigQueryRunner(metricsClient, BigQueryOptions.getDefaultInstance().getService(), out);

  when(metricsServiceStub.listMetricDescriptorsPagedCallable()).thenReturn(listCallable);
  when(listCallable.call(any(ListMetricDescriptorsRequest.class))).thenReturn(listResponse);
  when(listResponse.iterateAll()).thenReturn(Collections.EMPTY_LIST);

  when(metricsServiceStub.createMetricDescriptorCallable()).thenReturn(createMetricCallable);
  when(createMetricCallable.call(any(CreateMetricDescriptorRequest.class))).thenReturn(null);

  when(metricsServiceStub.createTimeSeriesCallable()).thenReturn(createTimeSeriesCallable);
  when(createTimeSeriesCallable.call(any(CreateTimeSeriesRequest.class)))
      .thenReturn(Empty.getDefaultInstance());
}
 
Example #2
Source File: BigQueryRunnerTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void testRun() throws Exception {
  app.runQuery();
  String got = bout.toString();
  assertThat(got).contains("Done writing metrics.");
  verify(metricsServiceStub).listMetricDescriptorsPagedCallable();

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

  verify(metricsServiceStub).createTimeSeriesCallable();
  verify(createTimeSeriesCallable).call(createTimeSeriesRequest.capture());
  CreateTimeSeriesRequest actual = createTimeSeriesRequest.getValue();
  assertEquals(2, actual.getTimeSeriesCount());
  assertThat(actual.getTimeSeries(0).getMetric().getType()).isEqualTo(
      "custom.googleapis.com/queryDuration");
  assertThat(actual.getTimeSeries(0).getPoints(0).getValue().getInt64Value()).isGreaterThan(0L);
  assertThat(actual.getTimeSeries(1).getMetric().getType()).isEqualTo(
      "custom.googleapis.com/rowsReturned");
  assertThat(actual.getTimeSeries(1).getPoints(0).getValue().getInt64Value()).isGreaterThan(0L);
}
 
Example #3
Source File: CreateTimeSeriesExporterTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  doReturn(mockCreateMetricDescriptorCallable).when(mockStub).createMetricDescriptorCallable();
  doReturn(mockCreateTimeSeriesCallable).when(mockStub).createTimeSeriesCallable();
  doReturn(null)
      .when(mockCreateMetricDescriptorCallable)
      .call(any(CreateMetricDescriptorRequest.class));
  doReturn(null).when(mockCreateTimeSeriesCallable).call(any(CreateTimeSeriesRequest.class));
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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;
}