From 2e683f4c6416cb146f920557138e41da9121d91a Mon Sep 17 00:00:00 2001 From: Bill Prin Date: Wed, 16 Mar 2016 12:16:20 -0700 Subject: [PATCH] Add Monitoring v3 Samples MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refactor v2 samples in to separate directory By default I skip tests, but they pass. Will send in incoming PR to add -DskipTests=false to the travis file (because since the tests require service account setup I don’t want to run them by default.) --- monitoring/{ => v2}/pom.xml | 2 +- .../main/java/CloudMonitoringAuthSample.java | 5 +- .../java/CloudMonitoringAuthSampleTest.java | 0 monitoring/v3/README.md | 48 +++ monitoring/v3/list_resources_example.sh | 2 + monitoring/v3/pom.xml | 103 ++++++ monitoring/v3/run_custom_metrics.sh | 2 + .../v3/src/main/java/CreateCustomMetric.java | 324 ++++++++++++++++++ .../v3/src/main/java/ListResources.java | 211 ++++++++++++ .../src/test/java/CreateCustomMetricTest.java | 91 +++++ .../v3/src/test/java/ListResourcesTest.java | 91 +++++ pom.xml | 3 +- 12 files changed, 876 insertions(+), 6 deletions(-) rename monitoring/{ => v2}/pom.xml (98%) rename monitoring/{ => v2}/src/main/java/CloudMonitoringAuthSample.java (92%) rename monitoring/{ => v2}/src/test/java/CloudMonitoringAuthSampleTest.java (100%) create mode 100644 monitoring/v3/README.md create mode 100755 monitoring/v3/list_resources_example.sh create mode 100644 monitoring/v3/pom.xml create mode 100755 monitoring/v3/run_custom_metrics.sh create mode 100644 monitoring/v3/src/main/java/CreateCustomMetric.java create mode 100644 monitoring/v3/src/main/java/ListResources.java create mode 100644 monitoring/v3/src/test/java/CreateCustomMetricTest.java create mode 100644 monitoring/v3/src/test/java/ListResourcesTest.java diff --git a/monitoring/pom.xml b/monitoring/v2/pom.xml similarity index 98% rename from monitoring/pom.xml rename to monitoring/v2/pom.xml index 0c23082dca1..de8cec1a2f2 100644 --- a/monitoring/pom.xml +++ b/monitoring/v2/pom.xml @@ -9,7 +9,7 @@ doc-samples com.google.cloud 1.0.0 - .. + ../.. diff --git a/monitoring/src/main/java/CloudMonitoringAuthSample.java b/monitoring/v2/src/main/java/CloudMonitoringAuthSample.java similarity index 92% rename from monitoring/src/main/java/CloudMonitoringAuthSample.java rename to monitoring/v2/src/main/java/CloudMonitoringAuthSample.java index 41caaf51063..537c074ed34 100644 --- a/monitoring/src/main/java/CloudMonitoringAuthSample.java +++ b/monitoring/v2/src/main/java/CloudMonitoringAuthSample.java @@ -28,6 +28,7 @@ /** * Simple command-line program to demonstrate connecting to and retrieving data * from the Google Cloud Monitoring API using application default credentials. + * Please see README.md on instructions to run. */ public final class CloudMonitoringAuthSample { @@ -97,10 +98,6 @@ public static void main(final String[] args) throws Exception { System.out.println("Timeseries.list raw response:"); System.out.println(timeseriesListRequest.execute().toPrettyString()); - // This example only demonstrates completing the OAuth flow and displaying - // the raw response from a simple request. See the API client library docs - // for applicable methods for working with the returned data, including - // getting results and paging through results. } } diff --git a/monitoring/src/test/java/CloudMonitoringAuthSampleTest.java b/monitoring/v2/src/test/java/CloudMonitoringAuthSampleTest.java similarity index 100% rename from monitoring/src/test/java/CloudMonitoringAuthSampleTest.java rename to monitoring/v2/src/test/java/CloudMonitoringAuthSampleTest.java diff --git a/monitoring/v3/README.md b/monitoring/v3/README.md new file mode 100644 index 00000000000..728d7ac5a5b --- /dev/null +++ b/monitoring/v3/README.md @@ -0,0 +1,48 @@ +# Cloud Monitoring Sample + +Simple command-line program to demonstrate connecting to the Google +Monitoring API to retrieve API data. + +This also includes an example of how to create a cusom metric and +write a TimeSeries value to it. + +## Prerequisites to run locally: + + * [Maven 3](https://maven.apache.org) + + +Go to the [Google Developers Console](https://console.developer.google.com). + + * Go too API Manager -> Credentials + * Click ['New Credentials', and create a Service Account](https://console.developers.google.com/project/_/apiui/credential/serviceaccount) + Download the JSON for this service account, and set the `GOOGLE_APPLICATION_CREDENTIALS` + environment variable to point to the file containing the JSON credentials. + + ``` + export GOOGLE_APPLICATION_CREDENTIALS=~/Downloads/-0123456789abcdef.json + ``` + +# Set Up Your Local Dev Environment + +To run locally: + * `mvn clean install` + * `./run_monitoring_example.sh + * `./run_custom_metrics.sh + +## Run Tests + +The tests emulate what the scripts accomplish, so there isn't a reason why they need to be run if the examples work. +However, if you'd like to run them, change TEST_PROJECT_ID in ListResourcesTest to the appropriate project ID +that matches the Service Account pointed to by GOOGLE_APPLICATION_CREDENTIALS, then run: + + mvn test -DskipTests=false + +## Contributing changes + +See CONTRIBUTING.md + +## Licensing + +* See [LICENSE](LICENSE) + + diff --git a/monitoring/v3/list_resources_example.sh b/monitoring/v3/list_resources_example.sh new file mode 100755 index 00000000000..7b0f63cbe0a --- /dev/null +++ b/monitoring/v3/list_resources_example.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +mvn exec:java -Dexec.mainClass=ListResources -Dexec.args="$1" diff --git a/monitoring/v3/pom.xml b/monitoring/v3/pom.xml new file mode 100644 index 00000000000..050db509de7 --- /dev/null +++ b/monitoring/v3/pom.xml @@ -0,0 +1,103 @@ + + 4.0.0 + com.google.cloud.monotoring.samples + cloud-monitoring-v3-samples + 0.1-SNAPSHOT + jar + + + doc-samples + com.google.cloud + 1.0.0 + ../.. + + + + + 1.19.0 + 1.19.0 + UTF-8 + true + + + + + com.google.api-client + google-api-client + 1.20.0 + + + com.google.oauth-client + google-oauth-client + ${project.oauth.version} + + + com.google.http-client + google-http-client-jackson2 + ${project.http.version} + + + com.google.oauth-client + google-oauth-client-jetty + ${project.oauth.version} + + + com.google.code.gson + gson + 2.3.1 + + + junit + junit + test + 4.12 + + + com.jcabi + jcabi-matchers + test + 1.3 + + + joda-time + joda-time + 2.9 + + + org.apache.commons + commons-lang3 + 3.4 + + + + com.google.apis + google-api-services-monitoring + v3-rev1-1.21.0 + + + + + + + maven-compiler-plugin + 2.3.2 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.4.2 + + ${skipTests} + + + + + + + diff --git a/monitoring/v3/run_custom_metrics.sh b/monitoring/v3/run_custom_metrics.sh new file mode 100755 index 00000000000..6c2652cfe4d --- /dev/null +++ b/monitoring/v3/run_custom_metrics.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +mvn exec:java -Dexec.mainClass=CreateCustomMetric -Dexec.args="$1" diff --git a/monitoring/v3/src/main/java/CreateCustomMetric.java b/monitoring/v3/src/main/java/CreateCustomMetric.java new file mode 100644 index 00000000000..18cdc4b5073 --- /dev/null +++ b/monitoring/v3/src/main/java/CreateCustomMetric.java @@ -0,0 +1,324 @@ +/** + * Copyright (c) 2015 Google Inc. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +import com.google.api.services.monitoring.v3.Monitoring; +import com.google.api.services.monitoring.v3.model.CreateTimeSeriesRequest; +import com.google.api.services.monitoring.v3.model.LabelDescriptor; +import com.google.api.services.monitoring.v3.model.ListMetricDescriptorsResponse; +import com.google.api.services.monitoring.v3.model.ListTimeSeriesResponse; +import com.google.api.services.monitoring.v3.model.Metric; +import com.google.api.services.monitoring.v3.model.MetricDescriptor; +import com.google.api.services.monitoring.v3.model.MonitoredResource; +import com.google.api.services.monitoring.v3.model.Point; +import com.google.api.services.monitoring.v3.model.TimeInterval; +import com.google.api.services.monitoring.v3.model.TimeSeries; +import com.google.api.services.monitoring.v3.model.TypedValue; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; + +import org.joda.time.DateTime; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.TimeZone; + + + + +/** + * Class to demonstrate creating a custom metric with Cloud Monitoring. This class provides a few + * functions that create a custom GAUGE metric, writes a timeseries value to it, then reads that + * metric's value back within the last 5 minutes to see the value written. + */ +public class CreateCustomMetric { + + /** + * Cloud Monitoring v3 REST client. + */ + private Monitoring monitoringService; + + private static SimpleDateFormat rfc3339 = + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"); + + static { + rfc3339.setTimeZone(TimeZone.getTimeZone("UTC")); + } + + /** + * Identifier for project resource, in format 'projects/your-project-id'. + */ + private String projectResource; + + /** + * All custom metrics should use this domain as their prefix. + */ + static final String CUSTOM_METRIC_DOMAIN = "custom.googleapis.com"; + + /** + * Name of our custom metric to create. + */ + static final String DEFAULT_METRIC_TYPE = "custom_measurement"; + + /** + * The specific metric type for the instance of this class. Defaults to DEFAULT_METRIC_TYPE. + */ + private String metricType; + + /** + * The specific metric name, which is based on the project resource and the type. + */ + private String metricName; + + + /** + * GAUGE metrics measure a value at a point in time. + */ + static final String METRIC_KIND = "GAUGE"; + + /** + * Upper bound for random number to write to metric, defaults to 10. + */ + private int bound = 10; + + /** + * Constructs an instance of the class using the default metric name. + */ + public CreateCustomMetric(Monitoring monitoringService, String projectResource) { + this.monitoringService = monitoringService; + this.projectResource = projectResource; + this.metricType = CUSTOM_METRIC_DOMAIN + "/" + DEFAULT_METRIC_TYPE; + this.metricName = projectResource + "/metricDescriptors/" + metricType; + + } + + /** + * Constructs an instance of the class using the default metric name, and takes in a random + * number generaotr (used for test purposes). + * Package-private to be accessible to tests. + */ + CreateCustomMetric(Monitoring monitoringService, String projectResource, + String metricName, int bound) { + this.monitoringService = monitoringService; + this.projectResource = projectResource; + this.metricType = CUSTOM_METRIC_DOMAIN + "/" + DEFAULT_METRIC_TYPE; + this.metricName = projectResource + "/metricDescriptors/" + metricType; + this.bound = bound; + } + + /** + * Constructs an instance of the class with the metric name specified. + */ + public CreateCustomMetric(Monitoring monitoringService, String projectResource, + String metricName) { + this.monitoringService = monitoringService; + this.projectResource = projectResource; + this.metricType = CUSTOM_METRIC_DOMAIN + "/" + metricName; + this.metricName = projectResource + "/metricDescriptors/" + metricType; + } + + /** + * Returns now in RFC3339 format. This is the end-time of the window + * this example views the TimeSeries in. + */ + private static String getNow() { + DateTime dt = new DateTime(); + return rfc3339.format(dt.toDate()); + } + + /** + * Returns 5 minutes before now to create a window to view timeseries in. + */ + private static String getStartTime() { + DateTime dt = new DateTime().minusMinutes(5); + return rfc3339.format(dt.toDate()); + } + + /** + * Dummy method to get an arbitrary data point. + */ + private long getRandomPoint() { + long value = new Random().nextInt(bound); + System.out.println("Returning value " + value); + return value; + } + + /** + * This method creates a custom metric with arbitrary names, description, + * and units. + * Package-private to be accessible to tests. + */ + MetricDescriptor createCustomMetric() throws IOException { + MetricDescriptor metricDescriptor = new MetricDescriptor(); + + + metricDescriptor.setName(metricName); + metricDescriptor.setType(metricType); + + LabelDescriptor labelDescriptor = new LabelDescriptor(); + labelDescriptor.setKey("environment"); + labelDescriptor.setValueType("STRING"); + labelDescriptor.setDescription("An arbitrary measurement."); + labelDescriptor.setDescription("Custom Metric"); + List labelDescriptorList = new ArrayList(); + labelDescriptorList.add(labelDescriptor); + metricDescriptor.setLabels(labelDescriptorList); + + metricDescriptor.setMetricKind(METRIC_KIND); + metricDescriptor.setValueType("INT64"); + // Fake custom metric with unit 'items' + metricDescriptor.setUnit("items"); + + + MetricDescriptor descriptorResponse = this.monitoringService.projects() + .metricDescriptors() + .create(projectResource, metricDescriptor) + .execute(); + System.out.println("create response" + descriptorResponse.toPrettyString()); + return descriptorResponse; + + } + + /** + * Retrieve the custom metric created by createCustomMetric. It can sometimes take a few moments + * before a new custom metric is ready to have TimeSeries written to it, so this method is used + * to check when it is ready. + */ + public MetricDescriptor getCustomMetric() throws IOException { + Monitoring.Projects.MetricDescriptors.List metrics = + monitoringService.projects().metricDescriptors() + .list(projectResource); + metrics.setFilter("metric.type=\"" + metricType + "\""); + ListMetricDescriptorsResponse response = metrics.execute(); + List descriptors = response.getMetricDescriptors(); + System.out.println("reading custom metric"); + if (descriptors == null || descriptors.isEmpty()) { + System.out.println("No metric descriptor matching that label found."); + return null; + } else { + System.out.println(descriptors.get(0).toPrettyString()); + return descriptors.get(0); + } + } + + /** + * Writes a timeseries value for the custom metric created. The value written + * is a random integer value for demonstration purposes. It's a GAUGE metric, + * which means its a measure of a value at a point in time, and thus the start + * window and end window times are the same. + * + * @throws IOException On network error. + */ + void writeCustomMetricTimeseriesValue() throws IOException { + Map metricLabel = ImmutableMap.of( + "environment", "STAGING" + ); + Map resourceLabel = ImmutableMap.of( + "instance_id", "test-instance", + "zone", "us-central1-f" + ); + + CreateTimeSeriesRequest timeSeriesRequest = new CreateTimeSeriesRequest(); + TimeSeries timeSeries = new TimeSeries(); + + Metric metric = new Metric(); + metric.setType(metricType); + + metric.setLabels(metricLabel); + timeSeries.setMetric(metric); + MonitoredResource monitoredResource = new MonitoredResource(); + monitoredResource.setType("gce_instance"); + monitoredResource.setLabels(resourceLabel); + timeSeries.setResource(monitoredResource); + timeSeries.setMetricKind(METRIC_KIND); + timeSeries.setValueType("INT64"); + Point point = new Point(); + TimeInterval ti = new TimeInterval(); + String now = getNow(); + ti.setStartTime(now); + ti.setEndTime(now); + + point.setInterval(ti); + point.setValue(new TypedValue().setInt64Value(getRandomPoint())); + + timeSeries.setPoints(Lists.newArrayList(point)); + + timeSeriesRequest.setTimeSeries(Lists.newArrayList(timeSeries)); + monitoringService.projects().timeSeries().create(projectResource, timeSeriesRequest).execute(); + } + + /** + * Read the TimeSeries value for the custom metrics created within a window of the + * last 5 minutes. + * + * @return The TimeSeries response object reflecting the Timeseries of the custom metrics + * for the last 5 minutes. + * @throws IOException On network error. + */ + ListTimeSeriesResponse readTimeseriesValue() throws IOException { + ListTimeSeriesResponse response = + monitoringService.projects().timeSeries().list(projectResource) + .setFilter("metric.type=\"" + metricType + "\"") + .setPageSize(3) + .setIntervalStartTime(getStartTime()) + .setIntervalEndTime(getNow()) + .execute(); + return response; + } + + /** + * Use the Google Cloud Monitoring API to create a custom metric. + * + * @param args The first arg should be the project name you'd like to inspect. + * @throws Exception if something goes wrong. + */ + public static void main(final String[] args) throws Exception { + if (args.length != 1) { + System.err.println(String.format("Usage: %s ", + CreateCustomMetric.class.getSimpleName())); + return; + } + + String project = args[0]; + String projectResource = "projects/" + project; + + + // Create an authorized API client + Monitoring monitoringService = ListResources.authenticate(); + + CreateCustomMetric metricWriter = new CreateCustomMetric( + monitoringService, projectResource); + + MetricDescriptor metricDescriptor = metricWriter.createCustomMetric(); + + System.out.println("listMetricDescriptors response"); + System.out.println(metricDescriptor.toPrettyString()); + + // wait until custom metric can be read back + while (metricWriter.getCustomMetric() == null) { + Thread.sleep(2000); + } + metricWriter.writeCustomMetricTimeseriesValue(); + Thread.sleep(3000); + ListTimeSeriesResponse response = metricWriter.readTimeseriesValue(); + System.out.println("reading custom metric timeseries"); + System.out.println(response.toPrettyString()); + + } +} diff --git a/monitoring/v3/src/main/java/ListResources.java b/monitoring/v3/src/main/java/ListResources.java new file mode 100644 index 00000000000..1eeeec28ffa --- /dev/null +++ b/monitoring/v3/src/main/java/ListResources.java @@ -0,0 +1,211 @@ +/** + * Copyright (c) 2015 Google Inc. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +// [START all] + +import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.services.monitoring.v3.Monitoring; +import com.google.api.services.monitoring.v3.MonitoringScopes; +import com.google.api.services.monitoring.v3.model.ListMetricDescriptorsResponse; +import com.google.api.services.monitoring.v3.model.ListMonitoredResourceDescriptorsResponse; +import com.google.api.services.monitoring.v3.model.ListTimeSeriesResponse; + +import org.joda.time.DateTime; + +import java.io.IOException; +import java.io.PrintStream; +import java.security.GeneralSecurityException; +import java.text.SimpleDateFormat; +import java.util.TimeZone; + + + +/** + * Simple command-line program to demonstrate connecting to and retrieving data + * from the Google Cloud Monitoring API v3 using application default credentials. + */ +public class ListResources { + + /** + * The metric that we want to fetch. + */ + private static final String METRIC = + "compute.googleapis.com/instance/cpu/usage_time"; + + /** + * This test program prints to standard output, but the integration tests verify + * the output with a custom output stream. + */ + private PrintStream outputStream; + + /** + * Cloud Monitoring v3 REST client. + */ + private Monitoring monitoringService; + + /** + * Identifier for project resource, in format 'projects/your-project-id'. + */ + private String projectResource; + + /** + * Utility class doesn't need to be instantiated. + */ + private ListResources(Monitoring monitoringService, String projectResource) { + this.monitoringService = monitoringService; + this.projectResource = projectResource; + this.outputStream = System.out; + } + + /** + * Package private that accepts output stream for integration test. + */ + ListResources(Monitoring monitoringService, String projectResource, PrintStream os) { + this.monitoringService = monitoringService; + this.projectResource = projectResource; + this.outputStream = os; + } + + private static SimpleDateFormat rfc3339 = + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"); + + static { + rfc3339.setTimeZone(TimeZone.getTimeZone("UTC")); + } + + /** + * Query the projects.monitoredResourceDescriptors.list API method. + * This lists all the resources available to be monitored in the API. + *

+ * Package-private to be accessible to tests. + */ + void listMonitoredResourceDescriptors() throws IOException { + ListMonitoredResourceDescriptorsResponse monitoredResources = + this.monitoringService.projects() + .monitoredResourceDescriptors().list(this.projectResource).execute(); + this.outputStream.println("listMonitoredResourceDescriptors response"); + this.outputStream.println(monitoredResources.toPrettyString()); + } + + /** + * Query to MetricDescriptors.list + * This lists all the current metrics. + *

+ * Package-private to be accessible to tests. + */ + void listMetricDescriptors() throws IOException { + ListMetricDescriptorsResponse metricsResponse = + this.monitoringService.projects().metricDescriptors() + .list(this.projectResource).execute(); + this.outputStream.println("listMetricDescriptors response"); + this.outputStream.println(metricsResponse.toPrettyString()); + } + + /** + * Returns start time for listTimeSeries. + * + * @return An hour ago - 5 minutes + */ + private static String getStartTime() { + // Return an hour ago - 5 minutes + DateTime dt = new DateTime().minusHours(1).minusMinutes(5); + rfc3339.format(dt.toDate()); + return rfc3339.format(dt.toDate()); + } + + /** + * Returns end time for listTimeSeries. + * + * @return An hour ago + */ + private static String getEndTime() { + // Return an hour ago + DateTime dt = new DateTime().minusHours(1); + return rfc3339.format(dt.toDate()); + } + + + /** + * Query to MetricDescriptors.list + * This lists all the current metrics. + */ + void listTimeseries() throws IOException { + ListTimeSeriesResponse timeSeriesList = this.monitoringService.projects().timeSeries() + .list(this.projectResource) + .setFilter("metric.type=\"" + METRIC + "\"") + .setPageSize(3) + .setIntervalStartTime(getStartTime()) + .setIntervalEndTime(getEndTime()) + .execute(); + this.outputStream.println("listTimeseries response"); + this.outputStream.println(timeSeriesList.toPrettyString()); + } + + /** + * Builds and returns a CloudMonitoring service object authorized with the + * application default credentials. + * + * @return CloudMonitoring service object that is ready to make requests. + * @throws GeneralSecurityException if authentication fails. + * @throws IOException if authentication fails. + */ + static Monitoring authenticate() throws GeneralSecurityException, IOException { + // Grab the Application Default Credentials from the environment. + GoogleCredential credential = GoogleCredential.getApplicationDefault() + .createScoped(MonitoringScopes.all()); + + // Create and return the CloudMonitoring service object + HttpTransport httpTransport = new NetHttpTransport(); + JsonFactory jsonFactory = new JacksonFactory(); + Monitoring service = new Monitoring.Builder(httpTransport, + jsonFactory, credential) + .setApplicationName("Monitoring Sample") + .build(); + return service; + } + + /** + * Query the Google Cloud Monitoring API using a service account and print the + * result to the console. + * + * @param args The first arg should be the project name you'd like to inspect. + * @throws Exception if something goes wrong. + */ + public static void main(final String[] args) throws Exception { + if (args.length != 1) { + System.err.println(String.format("Usage: %s ", + ListResources.class.getSimpleName())); + return; + } + + String project = args[0]; + String projectResource = "projects/" + project; + + + // Create an authorized API client + Monitoring monitoringService = authenticate(); + + ListResources example = new ListResources( + monitoringService, projectResource); + + example.listMonitoredResourceDescriptors(); + example.listMetricDescriptors(); + example.listTimeseries(); + } +} diff --git a/monitoring/v3/src/test/java/CreateCustomMetricTest.java b/monitoring/v3/src/test/java/CreateCustomMetricTest.java new file mode 100644 index 00000000000..c18b34c492f --- /dev/null +++ b/monitoring/v3/src/test/java/CreateCustomMetricTest.java @@ -0,0 +1,91 @@ +/** + * Copyright (c) 2015 Google Inc. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +import com.google.api.services.monitoring.v3.Monitoring; +import com.google.api.services.monitoring.v3.model.Point; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; +import java.util.Random; + +/** + * Integration tests for the basic Cloud Monitoring v3 examples. Running + * these tests requires that GOOGLE_APPLICATION_CREDENTIALS points to a + * valid JSON Service Account downloaded from a project with the Cloud + * Monitoring API enabled. + */ +public class CreateCustomMetricTest { + + /** + * Overrides the Random number generator so our tests get a predictable result. + */ + private static class MockRandom extends Random { + + public int nextInt(int bound) { + return 4; + } + } + + /** + * Google Cloud Monitoring client to integration test. + */ + private CreateCustomMetric underTest; + + /** + * Creates the monitoring service client. + * + * @throws Exception + */ + @Before + public void setUp() throws Exception { + Monitoring monitoringService = ListResources.authenticate(); + String projectResource = "projects/" + ListResourcesTest.TEST_PROJECT_ID; + String name = RandomStringUtils.randomAlphanumeric(20).toUpperCase(); + underTest = new CreateCustomMetric(monitoringService, projectResource, name, 1); + } + + /** + * Tests that the value written for a custom metric can be read back correctly. + * + * @throws Exception + */ + @Test + public void testValueRead() throws Exception { + underTest.createCustomMetric(); + + while (underTest.getCustomMetric() == null) { + Thread.sleep(2000); + } + underTest.writeCustomMetricTimeseriesValue(); + // give time for write to register + Thread.sleep(2000); + List response = underTest.readTimeseriesValue() + .getTimeSeries().get(0).getPoints(); + + boolean found = false; + for (Point p : response) { + System.out.println("found a response " + p.getValue().getInt64Value()); + if (p.getValue().getInt64Value() == 0) { + found = true; + } + } + Assert.assertTrue(found); + } + +} diff --git a/monitoring/v3/src/test/java/ListResourcesTest.java b/monitoring/v3/src/test/java/ListResourcesTest.java new file mode 100644 index 00000000000..f31b12eb04b --- /dev/null +++ b/monitoring/v3/src/test/java/ListResourcesTest.java @@ -0,0 +1,91 @@ +/** + * Copyright (c) 2015 Google Inc. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + + +import com.google.api.services.monitoring.v3.Monitoring; +import junit.framework.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +/** + * Integration tests for the basic Cloud Monitoring v3 examples. Running + * these tests requires that GOOGLE_APPLICATION_CREDENTIALS points to a + * valid JSON Service Account downloaded from a project with the Cloud + * Monitoring API enabled. + */ +public class ListResourcesTest { + + /** + * The project ID of the project created for the integration tests. + */ + public static final String TEST_PROJECT_ID = "cloud-monitoring-dev"; + + /** + * Google Cloud Monitoring client to integration test. + */ + private ListResources underTest; + + /** + * Output stream to capture output and verify expected output. + */ + private ByteArrayOutputStream os; + + @Before + public void setUp() throws Exception { + Monitoring monitoringService = ListResources.authenticate(); + os = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(os); + String projectResource = "projects/" + TEST_PROJECT_ID; + underTest = new ListResources(monitoringService, projectResource, ps); + } + + /** + * Integration tests that tests that getting the monitored resource returns + * the expected strings. + */ + @Test + public void testListMonitoredResourceDescriptors() throws Exception { + this.underTest.listMonitoredResourceDescriptors(); + String result = new String(os.toByteArray()); + Assert.assertTrue(result.contains("An application running in Google App Engine")); + } + + /** + * Integration tests that tests that getting the metric returns + * the expected strings. + */ + @Test + public void testListMetrics() throws Exception { + this.underTest.listMetricDescriptors(); + String result = new String(os.toByteArray()); + Assert.assertTrue(result.contains("Delta CPU usage time. Units are second")); + } + + /** + * Integration tests that tests that getting time series returns + * the expected strings. + */ + @Test + public void testListTimeseries() throws Exception { + this.underTest.listTimeseries(); + String result = new String(os.toByteArray()); + Assert.assertTrue(result.contains("listTimeseries response")); + } + +} diff --git a/pom.xml b/pom.xml index e4b87ab680d..9bc94b812dd 100644 --- a/pom.xml +++ b/pom.xml @@ -42,7 +42,8 @@ managed_vms/sparkjava managed_vms/static-files managed_vms/twilio - monitoring + monitoring/v2 + monitoring/v3 storage/json-api storage/storage-transfer storage/xml-api/cmdline-sample