From c7e1d919332144162f20e0920691c54d0692c047 Mon Sep 17 00:00:00 2001 From: Jisha Abubaker Date: Thu, 31 Aug 2017 13:21:38 -0700 Subject: [PATCH] Deleting monitoring apiary samples (#835) --- monitoring/v2/pom.xml | 91 ----- .../main/java/CloudMonitoringAuthSample.java | 104 ------ .../java/CloudMonitoringAuthSampleTest.java | 68 ---- monitoring/v3/README.md | 62 ---- monitoring/v3/list_resources_example.sh | 2 - monitoring/v3/pom.xml | 127 ------- monitoring/v3/run_custom_metrics.sh | 2 - .../v3/src/main/java/CreateCustomMetric.java | 328 ------------------ .../v3/src/main/java/ListResources.java | 210 ----------- .../src/test/java/CreateCustomMetricTest.java | 78 ----- .../v3/src/test/java/ListResourcesTest.java | 96 ----- pom.xml | 2 - 12 files changed, 1170 deletions(-) delete mode 100644 monitoring/v2/pom.xml delete mode 100644 monitoring/v2/src/main/java/CloudMonitoringAuthSample.java delete mode 100644 monitoring/v2/src/test/java/CloudMonitoringAuthSampleTest.java delete mode 100644 monitoring/v3/README.md delete mode 100755 monitoring/v3/list_resources_example.sh delete mode 100644 monitoring/v3/pom.xml delete mode 100755 monitoring/v3/run_custom_metrics.sh delete mode 100644 monitoring/v3/src/main/java/CreateCustomMetric.java delete mode 100644 monitoring/v3/src/main/java/ListResources.java delete mode 100644 monitoring/v3/src/test/java/CreateCustomMetricTest.java delete mode 100644 monitoring/v3/src/test/java/ListResourcesTest.java diff --git a/monitoring/v2/pom.xml b/monitoring/v2/pom.xml deleted file mode 100644 index 720f05a144e..00000000000 --- a/monitoring/v2/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - 4.0.0 - com.google.cloud.monitoring.samples - cloud-monitoring-samples - jar - - - doc-samples - com.google.cloud - 1.0.0 - ../.. - - - - - - googleapis - https://google-api-client-libraries.appspot.com/mavenrepo - - - - - 1.8 - 1.8 - - - - - com.google.apis - google-api-services-cloudmonitoring - v2beta2-rev71-1.22.0 - - - com.google.guava - guava-jdk5 - - - - - com.google.guava - guava - 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} - - - junit - junit - - - com.jcabi - jcabi-matchers - - - com.google.truth - truth - 0.34 - test - - - - diff --git a/monitoring/v2/src/main/java/CloudMonitoringAuthSample.java b/monitoring/v2/src/main/java/CloudMonitoringAuthSample.java deleted file mode 100644 index 537c074ed34..00000000000 --- a/monitoring/v2/src/main/java/CloudMonitoringAuthSample.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * 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.cloudmonitoring.CloudMonitoring; -import com.google.api.services.cloudmonitoring.CloudMonitoringScopes; - -import java.io.IOException; -import java.security.GeneralSecurityException; - -/** - * 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 { - - /** - * The metric that we want to fetch. - */ - private static final String METRIC = - "compute.googleapis.com/instance/disk/read_ops_count"; - - /** - * The end of the time interval to fetch. - */ - private static final String YOUNGEST = "2015-01-01T00:00:00Z"; - - /** - * Utility class doesn't need to be instantiated. - */ - private CloudMonitoringAuthSample() { } - - - /** - * 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. - */ - private static CloudMonitoring authenticate() - throws GeneralSecurityException, IOException { - // Grab the Application Default Credentials from the environment. - GoogleCredential credential = GoogleCredential.getApplicationDefault() - .createScoped(CloudMonitoringScopes.all()); - - // Create and return the CloudMonitoring service object - HttpTransport httpTransport = new NetHttpTransport(); - JsonFactory jsonFactory = new JacksonFactory(); - CloudMonitoring service = new CloudMonitoring.Builder(httpTransport, - jsonFactory, credential) - .setApplicationName("Demo") - .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 ", - CloudMonitoringAuthSample.class.getSimpleName())); - return; - } - - String project = args[0]; - - // Create an authorized API client - CloudMonitoring cloudmonitoring = authenticate(); - - CloudMonitoring.Timeseries.List timeseriesListRequest = - cloudmonitoring.timeseries().list(project, METRIC, YOUNGEST); - - System.out.println("Timeseries.list raw response:"); - System.out.println(timeseriesListRequest.execute().toPrettyString()); - - - } -} -// [END all] diff --git a/monitoring/v2/src/test/java/CloudMonitoringAuthSampleTest.java b/monitoring/v2/src/test/java/CloudMonitoringAuthSampleTest.java deleted file mode 100644 index c1bdadc4d55..00000000000 --- a/monitoring/v2/src/test/java/CloudMonitoringAuthSampleTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 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 static com.google.common.truth.Truth.assertThat; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -/** - * Tests the Cloud Monitoring auth sample. - */ -public class CloudMonitoringAuthSampleTest { - private final ByteArrayOutputStream stdout = - new ByteArrayOutputStream(); - private final ByteArrayOutputStream stderr = - new ByteArrayOutputStream(); - private static final PrintStream REAL_OUT = System.out; - private static final PrintStream REAL_ERR = System.err; - private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); - - @Before - public void setUp() { - System.setOut(new PrintStream(stdout)); - System.setErr(new PrintStream(stderr)); - } - - @After - public void tearDown() { - System.setOut(this.REAL_OUT); - System.setErr(this.REAL_ERR); - } - - @Test - public void testUsage() throws Exception { - CloudMonitoringAuthSample.main(new String[] { }); - assertThat(stderr.toString()) - .named("stderr") - .isEqualTo("Usage: CloudMonitoringAuthSample \n"); - } - - @Test - public void testListTimeSeries() throws Exception { - CloudMonitoringAuthSample.main(new String[] { PROJECT_ID }); - String out = stdout.toString(); - assertThat(out).named("stdout").contains("Timeseries.list raw response:"); - assertThat(out) - .named("stdout") - .containsMatch("\\{\\s*\"kind\" *: *\"cloudmonitoring#listTimeseriesResponse\","); - assertThat(out).named("stdout").containsMatch(".*oldest.*"); - } -} diff --git a/monitoring/v3/README.md b/monitoring/v3/README.md deleted file mode 100644 index ea3940663a7..00000000000 --- a/monitoring/v3/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# 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) - * [GCloud CLI](https://cloud.google.com/sdk/gcloud/) - * Create a Cloud project - -# Set Up Your Local Dev Environment - -Create local credentials by running the following command and following the oauth2 flow: - - gcloud beta auth application-default login - -To run: - - * `mvn clean install` - * `./list_resources_example.sh ` - * `./run_custom_metrics.sh ` - -## Running on GCE, GAE, or other environments - -On Google App Engine, the credentials should be found automatically. - -On Google Compute Engine, the credentials should be found automatically, but require that -you create the instance with the correct scopes. - - gcloud compute instances create --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/compute,https://www.googleapis.com/auth/compute.readonly" test-instance - -If you did not create the instance with the right scopes, you can still upload a JSON service -account and set `GOOGLE_APPLICATION_CREDENTIALS` as described below. - -## Using a Service Account - -In non-Google Cloud environments, GCE instances created without the correct scopes, or local -workstations if the `gcloud beta auth application-default login` command fails, use a Service -Account by doing the following: - -* Go to API Manager -> Credentials -* Click 'New Credentials', and create a Service Account or [click here](https://console.cloud.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 - -## 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`](src/test/java/ListResourcesTest.java) -to the appropriate project ID that matches the Service Account pointed to by -`GOOGLE_APPLICATION_CREDENTIALS`, then run: - - mvn test -DskipTests=false diff --git a/monitoring/v3/list_resources_example.sh b/monitoring/v3/list_resources_example.sh deleted file mode 100755 index 7b0f63cbe0a..00000000000 --- a/monitoring/v3/list_resources_example.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/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 deleted file mode 100644 index 90c2ad1c42d..00000000000 --- a/monitoring/v3/pom.xml +++ /dev/null @@ -1,127 +0,0 @@ - - - 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.7 - 1.7 - 1.22.0 - 1.22.0 - UTF-8 - true - - - - - com.google.api-client - google-api-client - 1.22.0 - - - com.google.guava - guava-jdk5 - - - - - com.google.guava - guava - 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} - - - joda-time - joda-time - 2.9.9 - - - org.apache.commons - commons-lang3 - 3.6 - - - com.google.apis - google-api-services-monitoring - v3-rev411-1.22.0 - - - com.google.code.gson - gson - 2.8.1 - - - - - junit - junit - 4.12 - test - - - com.jcabi - jcabi-matchers - 1.4 - test - - - com.google.truth - truth - 0.34 - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin-version} - - ${skipTests} - - - - - - - diff --git a/monitoring/v3/run_custom_metrics.sh b/monitoring/v3/run_custom_metrics.sh deleted file mode 100755 index 6c2652cfe4d..00000000000 --- a/monitoring/v3/run_custom_metrics.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/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 deleted file mode 100644 index fa7dfd2bfb7..00000000000 --- a/monitoring/v3/src/main/java/CreateCustomMetric.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Copyright 2016 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. - */ - // [START write_timeseries] - 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); - 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(); - } - // [END write_timeseries] - - /** - * 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 deleted file mode 100644 index 818b95a9a24..00000000000 --- a/monitoring/v3/src/main/java/ListResources.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright 2016 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 deleted file mode 100644 index 26dc57e5b97..00000000000 --- a/monitoring/v3/src/test/java/CreateCustomMetricTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2016 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 static com.google.common.truth.Truth.assertThat; - -import com.google.api.services.monitoring.v3.Monitoring; -import com.google.api.services.monitoring.v3.model.Point; -import com.google.common.collect.ImmutableList; - -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - - -/** - * 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 { - - /** - * Google Cloud Monitoring client to integration test. - */ - private CreateCustomMetric underTest; - - /** - * Creates the monitoring service client. - */ - @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. - */ - @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(); - - ImmutableList.Builder timeSeries = ImmutableList.builder(); - for (Point p : response) { - timeSeries.add(p.getValue().getInt64Value()); - } - assertThat(timeSeries.build()).contains(0L); - } - -} diff --git a/monitoring/v3/src/test/java/ListResourcesTest.java b/monitoring/v3/src/test/java/ListResourcesTest.java deleted file mode 100644 index 211dbd80837..00000000000 --- a/monitoring/v3/src/test/java/ListResourcesTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2016 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 static com.google.common.truth.Truth.assertThat; - -import com.google.api.services.monitoring.v3.Monitoring; - -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 = System.getenv("GOOGLE_CLOUD_PROJECT"); - - /** - * 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()); - assertThat(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()); - assertThat(result) - .contains("agent.googleapis.com/cpu/usage_time"); - } - - /** - * 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()); - assertThat(result) - .contains("listTimeseries response"); - } -} diff --git a/pom.xml b/pom.xml index fe7f9e86aa0..7c2e85970d8 100644 --- a/pom.xml +++ b/pom.xml @@ -67,8 +67,6 @@ logging/cloud-client monitoring/cloud-client - monitoring/v2 - monitoring/v3 pubsub/cloud-client