From 7aeec2cdb13e3e2e4421f98249cd6dbd5d43bc27 Mon Sep 17 00:00:00 2001 From: Jason Dobry Date: Wed, 25 Jan 2017 16:44:58 -0800 Subject: [PATCH 01/45] samples: Add Monitoring quickstart sample. --- .../example/monitoring/QuickstartSample.java | 107 ++++++++++++++++++ .../monitoring/QuickstartSampleIT.java | 72 ++++++++++++ 2 files changed, 179 insertions(+) create mode 100644 samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java create mode 100644 samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java diff --git a/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java new file mode 100644 index 00000000..e90b0899 --- /dev/null +++ b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java @@ -0,0 +1,107 @@ +/* + Copyright 2017, 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. +*/ + +package com.example.monitoring; + +// [START monitoring_quickstart] +import com.google.api.Metric; +import com.google.api.MonitoredResource; + +// Imports the Google Cloud client library +import com.google.cloud.monitoring.spi.v3.MetricServiceClient; + +import com.google.monitoring.v3.CreateTimeSeriesRequest; +import com.google.monitoring.v3.Point; +import com.google.monitoring.v3.ProjectName; +import com.google.monitoring.v3.TimeInterval; +import com.google.monitoring.v3.TimeSeries; +import com.google.monitoring.v3.TypedValue; +import com.google.protobuf.util.Timestamps; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class QuickstartSample { + 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(123.45) + .build(); + Point point = Point.newBuilder() + .setInterval(interval) + .setValue(value) + .build(); + + List pointList = new ArrayList<>(); + pointList.add(point); + + ProjectName name = ProjectName.create(projectId); + + // Prepares the metric descriptor + Map metricLabels = new HashMap(); + metricLabels.put("store_id", "Pittsburg"); + Metric metric = Metric.newBuilder() + .setType("custom.googleapis.com/stores/daily_sales") + .putAllLabels(metricLabels) + .build(); + + // Prepares the monitored resource descriptor + Map resourceLabels = new HashMap(); + resourceLabels.put("project_id", projectId); + MonitoredResource resource = MonitoredResource.newBuilder() + .setType("global") + .putAllLabels(resourceLabels) + .build(); + + // Prepares the time series request + TimeSeries timeSeries = TimeSeries.newBuilder() + .setMetric(metric) + .setResource(resource) + .addAllPoints(pointList) + .build(); + List timeSeriesList = new ArrayList<>(); + timeSeriesList.add(timeSeries); + + CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder() + .setNameWithProjectName(name) + .addAllTimeSeries(timeSeriesList) + .build(); + + // Writes time series data + metricServiceClient.createTimeSeries(request); + + System.out.printf("Done writing time series data.%n"); + + metricServiceClient.close(); + } +} +// [END monitoring_quickstart] diff --git a/samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java b/samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java new file mode 100644 index 00000000..dbc8000c --- /dev/null +++ b/samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java @@ -0,0 +1,72 @@ +/* + 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. +*/ + +package com.example.monitoring; + +import static com.google.common.truth.Truth.assertThat; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +/** + * Tests for quickstart sample. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class QuickstartSampleIT { + private ByteArrayOutputStream bout; + private PrintStream out; + private static final String LEGACY_PROJECT_ENV_NAME = "GCLOUD_PROJECT"; + private static final String PROJECT_ENV_NAME = "GOOGLE_CLOUD_PROJECT"; + + private static String getProjectId() { + String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME)); + if (projectId == null) { + projectId = System.getProperty(LEGACY_PROJECT_ENV_NAME, + System.getenv(LEGACY_PROJECT_ENV_NAME)); + } + return projectId; + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testQuickstart() throws Exception { + // Act + System.setProperty("projectId", QuickstartSampleIT.getProjectId()); + QuickstartSample.main(); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Done writing time series data."); + } +} From 1322bb11bc9ab90e080b5e6d5bc9b97f45670920 Mon Sep 17 00:00:00 2001 From: Bill Prin Date: Wed, 8 Mar 2017 13:55:07 -0800 Subject: [PATCH 02/45] samples: Finish snippets --- .../java/com/example/monitoring/Snippets.java | 592 ++++++++++++++++++ .../com/example/monitoring/SnippetsIT.java | 153 +++++ 2 files changed, 745 insertions(+) create mode 100644 samples/snippets/src/main/java/com/example/monitoring/Snippets.java create mode 100644 samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java diff --git a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java new file mode 100644 index 00000000..217f9fa9 --- /dev/null +++ b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java @@ -0,0 +1,592 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + */ + +package com.example.monitoring; + +import com.google.api.Metric; +import com.google.api.MetricDescriptor; +import com.google.api.MonitoredResource; +import com.google.api.MonitoredResourceDescriptor; +import com.google.cloud.monitoring.spi.v3.MetricServiceClient; +import com.google.cloud.monitoring.spi.v3.PagedResponseWrappers; +import com.google.monitoring.v3.Aggregation; +import com.google.monitoring.v3.CreateMetricDescriptorRequest; +import com.google.monitoring.v3.CreateTimeSeriesRequest; +import com.google.monitoring.v3.ListMetricDescriptorsRequest; +import com.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest; +import com.google.monitoring.v3.ListTimeSeriesRequest; +import com.google.monitoring.v3.MetricDescriptorName; +import com.google.monitoring.v3.MonitoredResourceDescriptorName; +import com.google.monitoring.v3.Point; +import com.google.monitoring.v3.ProjectName; +import com.google.monitoring.v3.TimeInterval; +import com.google.monitoring.v3.TimeSeries; +import com.google.monitoring.v3.TypedValue; +import com.google.protobuf.Duration; +import com.google.protobuf.util.Timestamps; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +// Imports the Google Cloud client library + + +public class Snippets { + + private static final String CUSTOM_METRIC_DOMAIN = "custom.googleapis.com"; + + /** + * Exercises the methods defined in this class. + * + *

Assumes that you are authenticated using the Google Cloud SDK (using + * {@code gcloud auth application-default-login}). + */ + public static void main(String[] args) throws Exception { + + Snippets snippets = new Snippets(); + System.out.println("Stackdriver Monitoring snippets"); + System.out.println(); + printUsage(); + while (true) { + String commandLine = System.console().readLine("> "); + if (commandLine.trim().isEmpty()) { + break; + } + try { + snippets.handleCommandLine(commandLine); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + printUsage(); + } + } + System.out.println("exiting"); + System.exit(0); + } + + /** + * Creates a metric descriptor. + * + * See: https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create + * @param type The metric type + */ + void createMetricDescriptor(String type) throws IOException { + // [START monitoring_create_metric] + // Your Google Cloud Platform project ID + String projectId = System.getProperty("projectId"); + String metricType = CUSTOM_METRIC_DOMAIN + "/" + type; + + final MetricServiceClient client = MetricServiceClient.create(); + ProjectName name = ProjectName.create(projectId); + + MetricDescriptor descriptor = MetricDescriptor.newBuilder() + .setType(metricType) + .setDescription("This is a simple example of a custom metric.") + .setMetricKind(MetricDescriptor.MetricKind.GAUGE) + .setValueType(MetricDescriptor.ValueType.DOUBLE) + .build(); + + CreateMetricDescriptorRequest request = CreateMetricDescriptorRequest.newBuilder() + .setNameWithProjectName(name) + .setMetricDescriptor(descriptor) + .build(); + + client.createMetricDescriptor(request); + // [END monitoring_create_metric] + } + + /** + * Delete a metric descriptor. + * @param name Name of metric descriptor to delete + */ + void deleteMetricDescriptor(String name) throws IOException { + String projectId = System.getProperty("projectId"); + final MetricServiceClient client = MetricServiceClient.create(); + MetricDescriptorName metricName = MetricDescriptorName.create(projectId, name); + client.deleteMetricDescriptor(metricName); + System.out.println("Deleted descriptor " + name); + } + + /** + * Demonstrates writing a time series value for the metric type + * 'custom.google.apis.com/my_metric'. + * + * 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. + * + */ + 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 pointList = new ArrayList<>(); + pointList.add(point); + + ProjectName name = ProjectName.create(projectId); + + // Prepares the metric descriptor + Map metricLabels = new HashMap(); + Metric metric = Metric.newBuilder() + .setType("custom.googleapis.com/my_metric") + .putAllLabels(metricLabels) + .build(); + + // Prepares the monitored resource descriptor + Map 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 timeSeriesList = new ArrayList<>(); + timeSeriesList.add(timeSeries); + + CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder() + .setNameWithProjectName(name) + .addAllTimeSeries(timeSeriesList) + .build(); + + // Writes time series data + metricServiceClient.createTimeSeries(request); + System.out.println("Done writing time series value."); + // [END monitoring_write_timeseries] + } + + /** + * 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.create(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() + .setNameWithProjectName(name) + .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"") + .setInterval(interval) + .setView(ListTimeSeriesRequest.TimeSeriesView.HEADERS); + + String nextToken = ""; + + do { + if (nextToken != null) { + requestBuilder.setPageToken(nextToken); + } + ListTimeSeriesRequest request = requestBuilder.build(); + + PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient + .listTimeSeries(request); + List timeseries = response.getPage() + .getResponseObject() + .getTimeSeriesList(); + + System.out.println("Got timeseries headers: "); + for (TimeSeries ts : timeseries) { + System.out.println(ts); + } + Object nextObjectToken = response.getNextPageToken(); + nextToken = (String)nextObjectToken; + } while (nextToken != ""); + // [END monitoring_read_timeseries_fields] + } + + /** + * 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.create(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() + .setNameWithProjectName(name) + .setFilter(filter) + .setInterval(interval); + + String nextToken = ""; + + do { + if (nextToken != null) { + requestBuilder.setPageToken(nextToken); + } + ListTimeSeriesRequest request = requestBuilder.build(); + + PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient + .listTimeSeries(request); + List timeseries = response.getPage() + .getResponseObject() + .getTimeSeriesList(); + + System.out.println("Got timeseries: "); + for (TimeSeries ts : timeseries) { + System.out.println(ts); + } + Object nextObjectToken = response.getNextPageToken(); + nextToken = (String)nextObjectToken; + } while (nextToken != ""); + // [END monitoring_read_timeseries_simple] + } + + /** + * 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.create(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() + .setNameWithProjectName(name) + .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"") + .setInterval(interval) + .setAggregation(aggregation); + + String nextToken = ""; + do { + if (nextToken != null) { + requestBuilder.setPageToken(nextToken); + } + ListTimeSeriesRequest request = requestBuilder.build(); + + PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient + .listTimeSeries(request); + List timeseries = response.getPage() + .getResponseObject() + .getTimeSeriesList(); + + System.out.println("Got timeseries: "); + for (TimeSeries ts : timeseries) { + System.out.println(ts); + } + Object nextObjectToken = response.getNextPageToken(); + nextToken = (String)nextObjectToken; + } while (nextToken != ""); + // [END monitoring_read_timeseries_align] + } + + /** + * 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.create(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() + .setNameWithProjectName(name) + .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"") + .setInterval(interval) + .setAggregation(aggregation); + + String nextToken = ""; + + do { + if (nextToken != null) { + requestBuilder.setPageToken(nextToken); + } + ListTimeSeriesRequest request = requestBuilder.build(); + + PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient + .listTimeSeries(request); + List timeseries = response.getPage() + .getResponseObject() + .getTimeSeriesList(); + + System.out.println("Got timeseries: "); + for (TimeSeries ts : timeseries) { + System.out.println(ts); + } + Object nextObjectToken = response.getNextPageToken(); + nextToken = (String)nextObjectToken; + } while (nextToken != ""); + // [END monitoring_read_timeseries_reduce] + } + + /** + * Returns the first page of all metric descriptors. + */ + void listMetricDescriptors() throws IOException { + // [START monitoring_list_descriptors] + // Your Google Cloud Platform project ID + String projectId = System.getProperty("projectId"); + + final MetricServiceClient client = MetricServiceClient.create(); + ProjectName name = ProjectName.create(projectId); + + ListMetricDescriptorsRequest request = ListMetricDescriptorsRequest + .newBuilder() + .setNameWithProjectName(name) + .build(); + PagedResponseWrappers.ListMetricDescriptorsPagedResponse response = + client.listMetricDescriptors(request); + + System.out.println("Listing descriptors: "); + + List descriptors = response.getPage() + .getResponseObject().getMetricDescriptorsList(); + for (MetricDescriptor d : descriptors) { + System.out.println(d.getName() + " " + d.getDisplayName()); + } + // [END monitoring_list_descriptors] + } + + /** + * Gets all monitored resource descriptors. + */ + void listMonitoredResources() throws IOException { + // [START monitoring_list_resources] + // Your Google Cloud Platform project ID + String projectId = System.getProperty("projectId"); + + final MetricServiceClient client = MetricServiceClient.create(); + ProjectName name = ProjectName.create(projectId); + + ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest + .newBuilder() + .setNameWithProjectName(name) + .build(); + + System.out.println("Listing monitored resource descriptors: "); + + PagedResponseWrappers.ListMonitoredResourceDescriptorsPagedResponse response = client + .listMonitoredResourceDescriptors(request); + + List descriptors = response.getPage() + .getResponseObject().getResourceDescriptorsList(); + + for (MonitoredResourceDescriptor d : descriptors) { + System.out.println(d.getType()); + } + // [START monitoring_list_resources] + } + + /** + * Gets full information for a monitored resource. + * @param The resource type + */ + void describeMonitoredResources(String type) throws IOException { + // [START monitoring_list_resources] + // Your Google Cloud Platform project ID + String projectId = System.getProperty("projectId"); + + final MetricServiceClient client = MetricServiceClient.create(); + MonitoredResourceDescriptorName name = MonitoredResourceDescriptorName.create(projectId, type); + MonitoredResourceDescriptor response = client.getMonitoredResourceDescriptor(name); + + System.out.println("Printing monitored resource descriptor: "); + System.out.println(response); + + // [END monitoring_list_resources] + } + + + /** + * Handles a single command. + * + * @param commandLine A line of input provided by the user + */ + void handleCommandLine(String commandLine) throws IOException { + String[] args = commandLine.split("\\s+"); + + if (args.length < 1) { + throw new IllegalArgumentException("not enough args"); + } + + String command = args[0]; + switch (command) { + case "new-metric-descriptor": + // Everything after the first whitespace token is interpreted to be the description. + args = commandLine.split("\\s+", 2); + if (args.length != 2) { + throw new IllegalArgumentException("usage: "); + } + // Set created to now() and done to false. + createMetricDescriptor(args[1]); + System.out.println("Metric descriptor created"); + break; + case "list-metric-descriptors": + args = commandLine.split("\\s+", 2); + if (args.length != 1) { + throw new IllegalArgumentException("usage: no arguments"); + } + listMetricDescriptors(); + break; + case "list-monitored-resources": + args = commandLine.split("\\s+", 2); + if (args.length != 1) { + throw new IllegalArgumentException("usage: no arguments"); + } + listMonitoredResources(); + break; + case "get-resource": + args = commandLine.split("\\s+", 2); + if (args.length != 2) { + throw new IllegalArgumentException("usage: "); + } + describeMonitoredResources(args[1]); + break; + case "delete-metric-descriptor": + args = commandLine.split("\\s+", 2); + if (args.length != 1) { + throw new IllegalArgumentException("usage: "); + } + deleteMetricDescriptor(args[1]); + break; + case "write-time-series": + args = commandLine.split("\\s+", 2); + if (args.length != 1) { + throw new IllegalArgumentException("usage: no arguments"); + } + writeTimeSeries(); + break; + case "list-time-series-header": + args = commandLine.split("\\s+", 2); + if (args.length != 1) { + throw new IllegalArgumentException("usage: no arguments"); + } + listTimeSeriesHeaders(); + break; + case "list-time-series": + args = commandLine.split("\\s+", 2); + if (args.length != 2) { + throw new IllegalArgumentException("usage: "); + } + listTimeSeries(args[1]); + break; + case "list-aggregate": + args = commandLine.split("\\s+", 2); + if (args.length != 1) { + throw new IllegalArgumentException("usage: no arguments"); + } + listTimeSeriesAggregrate(); + break; + case "list-reduce": + args = commandLine.split("\\s+", 2); + if (args.length != 1) { + throw new IllegalArgumentException("usage: no arguments"); + } + listTimeSeriesReduce(); + break; + default: + throw new IllegalArgumentException("unrecognized command: " + command); + } + } + + private void assertArgsLength(String[] args, int expectedLength) { + if (args.length != expectedLength) { + throw new IllegalArgumentException( + String.format("expected exactly %d arg(s), found %d", expectedLength, args.length)); + } + } + + private static void printUsage() { + System.out.println("Usage:"); + System.out.println(); + System.out.println(" new-metric-descriptor Creates a metric descriptor"); + System.out.println(" list-metric-descriptors Lists first page of metric descriptors"); + System.out.println(" list-monitored-resources Lists the monitored resources"); + System.out.println(" get-resource Describes a monitored resource"); + System.out.println(" delete-metric-descriptors Deletes a metric descriptor"); + System.out.println(" write-time-series Writes a time series value to a metric"); + System.out.println(" list-headers List time series header of " + + " 'compute.googleapis.com/instance/cpu/utilization'"); + System.out.println(" list-time-series-header List time series data that matches a " + + "given filter"); + System.out.println(" list-aggregate `Aggregates time series data that matches" + + "'compute.googleapis.com/instance/cpu/utilization"); + System.out.println(" list-reduce `Reduces time series data that matches" + + " 'compute.googleapis.com/instance/cpu/utilization"); + System.out.println(); + } + +} diff --git a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java new file mode 100644 index 00000000..29dab31f --- /dev/null +++ b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java @@ -0,0 +1,153 @@ +/* + 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. +*/ + +package com.example.monitoring; + +import static com.google.common.truth.Truth.assertThat; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +/** + * Tests for quickstart sample. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class SnippetsIT { + private ByteArrayOutputStream bout; + private PrintStream out; + private static final String LEGACY_PROJECT_ENV_NAME = "GCLOUD_PROJECT"; + private static final String PROJECT_ENV_NAME = "GOOGLE_CLOUD_PROJECT"; + + private static String getProjectId() { + String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME)); + if (projectId == null) { + projectId = System.getProperty(LEGACY_PROJECT_ENV_NAME, + System.getenv(LEGACY_PROJECT_ENV_NAME)); + } + return projectId; + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testListMetricsDescriptor() throws Exception { + // Act + System.setProperty("projectId", SnippetsIT.getProjectId()); + Snippets snippets = new Snippets(); + + snippets.listMetricDescriptors(); + // Assert + String got = bout.toString(); + assertThat(got).contains("metricDescriptors/bigquery.googleapis.com/query/count"); + } + + @Test + public void testListTimeSeries() throws Exception { + // Act + System.setProperty("projectId", SnippetsIT.getProjectId()); + Snippets snippets = new Snippets(); + + snippets.listTimeSeries("metric.type=\"custom.googleapis.com/my_metric\""); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Got timeseries:"); + } + + @Test + public void testListTimeSeriesHeader() throws Exception { + // Act + System.setProperty("projectId", SnippetsIT.getProjectId()); + Snippets snippets = new Snippets(); + + snippets.listTimeSeriesHeaders(); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Got timeseries headers:"); + } + + @Test + public void testListTimeSeriesAggregate() throws Exception { + // Act + System.setProperty("projectId", SnippetsIT.getProjectId()); + Snippets snippets = new Snippets(); + + snippets.listTimeSeriesAggregrate(); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Got timeseries:"); + assertThat(got).contains("compute.googleapis.com/instance/cpu/utilizatio"); + } + + @Test + public void testListTimeSeriesReduce() throws Exception { + // Act + System.setProperty("projectId", SnippetsIT.getProjectId()); + Snippets snippets = new Snippets(); + + snippets.listTimeSeriesReduce(); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Got timeseries:"); + assertThat(got).contains("compute.googleapis.com/instance/cpu/utilizatio"); + } + + @Test + public void testGetResource() throws Exception { + // Act + System.setProperty("projectId", SnippetsIT.getProjectId()); + Snippets snippets = new Snippets(); + + snippets.describeMonitoredResources("cloudsql_database"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("\"A database hosted in Google Cloud SQL"); + } + + @Test + public void testListResources() throws Exception { + // Act + System.setProperty("projectId", SnippetsIT.getProjectId()); + Snippets snippets = new Snippets(); + + snippets.listMonitoredResources(); + + // Assert + String got = bout.toString(); + assertThat(got).contains("gce_instance"); + } +} From 18131ba9ec96df8e07cdcd00c2b3d7782e87293e Mon Sep 17 00:00:00 2001 From: Bill Prin Date: Fri, 17 Mar 2017 15:20:19 -0700 Subject: [PATCH 03/45] samples: Fix typo --- .../src/test/java/com/example/monitoring/SnippetsIT.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java index 29dab31f..a1b35395 100644 --- a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java +++ b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java @@ -108,7 +108,7 @@ public void testListTimeSeriesAggregate() throws Exception { // Assert String got = bout.toString(); assertThat(got).contains("Got timeseries:"); - assertThat(got).contains("compute.googleapis.com/instance/cpu/utilizatio"); + assertThat(got).contains("compute.googleapis.com/instance/cpu/utilization"); } @Test @@ -122,7 +122,7 @@ public void testListTimeSeriesReduce() throws Exception { // Assert String got = bout.toString(); assertThat(got).contains("Got timeseries:"); - assertThat(got).contains("compute.googleapis.com/instance/cpu/utilizatio"); + assertThat(got).contains("compute.googleapis.com/instance/cpu/utilization"); } @Test From 011d94b56d820bdf98510a5cc7b4e33419aa63d5 Mon Sep 17 00:00:00 2001 From: Bill Prin Date: Fri, 17 Mar 2017 15:47:55 -0700 Subject: [PATCH 04/45] samples: Make tests less specific --- .../src/test/java/com/example/monitoring/SnippetsIT.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java index a1b35395..7f16da6f 100644 --- a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java +++ b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java @@ -108,7 +108,6 @@ public void testListTimeSeriesAggregate() throws Exception { // Assert String got = bout.toString(); assertThat(got).contains("Got timeseries:"); - assertThat(got).contains("compute.googleapis.com/instance/cpu/utilization"); } @Test @@ -122,7 +121,6 @@ public void testListTimeSeriesReduce() throws Exception { // Assert String got = bout.toString(); assertThat(got).contains("Got timeseries:"); - assertThat(got).contains("compute.googleapis.com/instance/cpu/utilization"); } @Test From 2fd7609b4be3cfd1b96d7d8baa3aaa96d9d2ea11 Mon Sep 17 00:00:00 2001 From: Bill Prin Date: Fri, 17 Mar 2017 15:55:23 -0700 Subject: [PATCH 05/45] samples: Switch custom metric to cpu --- .../src/test/java/com/example/monitoring/SnippetsIT.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java index 7f16da6f..bb06947f 100644 --- a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java +++ b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java @@ -77,7 +77,7 @@ public void testListTimeSeries() throws Exception { System.setProperty("projectId", SnippetsIT.getProjectId()); Snippets snippets = new Snippets(); - snippets.listTimeSeries("metric.type=\"custom.googleapis.com/my_metric\""); + snippets.listTimeSeries("metric.type=\"compute.googleapis.com/instance/cpu/utilization\""); // Assert String got = bout.toString(); From f52b087f049947729284c17d6b9e8a1d26920213 Mon Sep 17 00:00:00 2001 From: Bill Prin Date: Mon, 27 Mar 2017 14:00:11 -0700 Subject: [PATCH 06/45] samples: Fix region tags --- .../src/main/java/com/example/monitoring/Snippets.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java index 217f9fa9..07df8fe7 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java +++ b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java @@ -115,11 +115,13 @@ void createMetricDescriptor(String type) throws IOException { * @param name Name of metric descriptor to delete */ void deleteMetricDescriptor(String name) throws IOException { + // [START monitoring_delete_metric] String projectId = System.getProperty("projectId"); final MetricServiceClient client = MetricServiceClient.create(); MetricDescriptorName metricName = MetricDescriptorName.create(projectId, name); client.deleteMetricDescriptor(metricName); System.out.println("Deleted descriptor " + name); + // [END monitoring_delete_metric] } /** @@ -447,7 +449,7 @@ void listMonitoredResources() throws IOException { for (MonitoredResourceDescriptor d : descriptors) { System.out.println(d.getType()); } - // [START monitoring_list_resources] + // [END monitoring_list_resources] } /** @@ -455,7 +457,7 @@ void listMonitoredResources() throws IOException { * @param The resource type */ void describeMonitoredResources(String type) throws IOException { - // [START monitoring_list_resources] + // [START monitoring_get_descriptor] // Your Google Cloud Platform project ID String projectId = System.getProperty("projectId"); @@ -465,8 +467,7 @@ void describeMonitoredResources(String type) throws IOException { System.out.println("Printing monitored resource descriptor: "); System.out.println(response); - - // [END monitoring_list_resources] + // [END monitoring_get_descriptor] } From e5a87725d2c37647b4acd96088b5599a70a53e60 Mon Sep 17 00:00:00 2001 From: DPE bot Date: Tue, 18 Apr 2017 20:28:06 -0700 Subject: [PATCH 07/45] samples: Auto-update dependencies. (#614) * Auto-update dependencies. * Update to new gax 1. Update for new tax 2. Lots of trivial formatting changes --- .../java/com/example/monitoring/Snippets.java | 131 +++++------------- 1 file changed, 37 insertions(+), 94 deletions(-) diff --git a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java index 07df8fe7..66fcb481 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java +++ b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java @@ -53,7 +53,7 @@ public class Snippets { /** * Exercises the methods defined in this class. - * + *

*

Assumes that you are authenticated using the Google Cloud SDK (using * {@code gcloud auth application-default-login}). */ @@ -81,8 +81,9 @@ public static void main(String[] args) throws Exception { /** * Creates a metric descriptor. - * + *

* See: https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create + * * @param type The metric type */ void createMetricDescriptor(String type) throws IOException { @@ -112,6 +113,7 @@ void createMetricDescriptor(String type) throws IOException { /** * Delete a metric descriptor. + * * @param name Name of metric descriptor to delete */ void deleteMetricDescriptor(String name) throws IOException { @@ -127,11 +129,10 @@ void deleteMetricDescriptor(String name) throws IOException { /** * Demonstrates writing a time series value for the metric type * 'custom.google.apis.com/my_metric'. - * + *

* 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. - * */ void writeTimeSeries() throws IOException { // [START monitoring_write_timeseries] @@ -203,7 +204,6 @@ void listTimeSeriesHeaders() throws IOException { String projectId = System.getProperty("projectId"); ProjectName name = ProjectName.create(projectId); - // Restrict time to last 20 minutes long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000); TimeInterval interval = TimeInterval.newBuilder() @@ -217,33 +217,20 @@ void listTimeSeriesHeaders() throws IOException { .setInterval(interval) .setView(ListTimeSeriesRequest.TimeSeriesView.HEADERS); - String nextToken = ""; + ListTimeSeriesRequest request = requestBuilder.build(); - do { - if (nextToken != null) { - requestBuilder.setPageToken(nextToken); - } - ListTimeSeriesRequest request = requestBuilder.build(); + PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient + .listTimeSeries(request); - PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient - .listTimeSeries(request); - List timeseries = response.getPage() - .getResponseObject() - .getTimeSeriesList(); - - System.out.println("Got timeseries headers: "); - for (TimeSeries ts : timeseries) { - System.out.println(ts); - } - Object nextObjectToken = response.getNextPageToken(); - nextToken = (String)nextObjectToken; - } while (nextToken != ""); + System.out.println("Got timeseries headers: "); + for (TimeSeries ts : response.iterateAll()) { + System.out.println(ts); + } // [END monitoring_read_timeseries_fields] } /** * Demonstrates listing time series using a filter. - * */ void listTimeSeries(String filter) throws IOException { // [START monitoring_read_timeseries_simple] @@ -251,7 +238,6 @@ void listTimeSeries(String filter) throws IOException { String projectId = System.getProperty("projectId"); ProjectName name = ProjectName.create(projectId); - // Restrict time to last 20 minutes long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000); TimeInterval interval = TimeInterval.newBuilder() @@ -264,33 +250,20 @@ void listTimeSeries(String filter) throws IOException { .setFilter(filter) .setInterval(interval); - String nextToken = ""; - - do { - if (nextToken != null) { - requestBuilder.setPageToken(nextToken); - } - ListTimeSeriesRequest request = requestBuilder.build(); + ListTimeSeriesRequest request = requestBuilder.build(); - PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient - .listTimeSeries(request); - List timeseries = response.getPage() - .getResponseObject() - .getTimeSeriesList(); + PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient + .listTimeSeries(request); - System.out.println("Got timeseries: "); - for (TimeSeries ts : timeseries) { - System.out.println(ts); - } - Object nextObjectToken = response.getNextPageToken(); - nextToken = (String)nextObjectToken; - } while (nextToken != ""); + System.out.println("Got timeseries: "); + for (TimeSeries ts : response.iterateAll()) { + System.out.println(ts); + } // [END monitoring_read_timeseries_simple] } /** * Demonstrates listing time series and aggregating them. - * */ void listTimeSeriesAggregrate() throws IOException { // [START monitoring_read_timeseries_align] @@ -298,7 +271,6 @@ void listTimeSeriesAggregrate() throws IOException { String projectId = System.getProperty("projectId"); ProjectName name = ProjectName.create(projectId); - // Restrict time to last 20 minutes long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000); TimeInterval interval = TimeInterval.newBuilder() @@ -317,32 +289,20 @@ void listTimeSeriesAggregrate() throws IOException { .setInterval(interval) .setAggregation(aggregation); - String nextToken = ""; - do { - if (nextToken != null) { - requestBuilder.setPageToken(nextToken); - } - ListTimeSeriesRequest request = requestBuilder.build(); + ListTimeSeriesRequest request = requestBuilder.build(); - PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient - .listTimeSeries(request); - List timeseries = response.getPage() - .getResponseObject() - .getTimeSeriesList(); + PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient + .listTimeSeries(request); - System.out.println("Got timeseries: "); - for (TimeSeries ts : timeseries) { - System.out.println(ts); - } - Object nextObjectToken = response.getNextPageToken(); - nextToken = (String)nextObjectToken; - } while (nextToken != ""); + System.out.println("Got timeseries: "); + for (TimeSeries ts : response.iterateAll()) { + System.out.println(ts); + } // [END monitoring_read_timeseries_align] } /** * Demonstrates listing time series and aggregating and reducing them. - * */ void listTimeSeriesReduce() throws IOException { // [START monitoring_read_timeseries_reduce] @@ -350,7 +310,6 @@ void listTimeSeriesReduce() throws IOException { String projectId = System.getProperty("projectId"); ProjectName name = ProjectName.create(projectId); - // Restrict time to last 20 minutes long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000); TimeInterval interval = TimeInterval.newBuilder() @@ -370,27 +329,15 @@ void listTimeSeriesReduce() throws IOException { .setInterval(interval) .setAggregation(aggregation); - String nextToken = ""; - - do { - if (nextToken != null) { - requestBuilder.setPageToken(nextToken); - } - ListTimeSeriesRequest request = requestBuilder.build(); + ListTimeSeriesRequest request = requestBuilder.build(); - PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient - .listTimeSeries(request); - List timeseries = response.getPage() - .getResponseObject() - .getTimeSeriesList(); + PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient + .listTimeSeries(request); - System.out.println("Got timeseries: "); - for (TimeSeries ts : timeseries) { - System.out.println(ts); - } - Object nextObjectToken = response.getNextPageToken(); - nextToken = (String)nextObjectToken; - } while (nextToken != ""); + System.out.println("Got timeseries: "); + for (TimeSeries ts : response.iterateAll()) { + System.out.println(ts); + } // [END monitoring_read_timeseries_reduce] } @@ -414,9 +361,7 @@ void listMetricDescriptors() throws IOException { System.out.println("Listing descriptors: "); - List descriptors = response.getPage() - .getResponseObject().getMetricDescriptorsList(); - for (MetricDescriptor d : descriptors) { + for (MetricDescriptor d : response.iterateAll()) { System.out.println(d.getName() + " " + d.getDisplayName()); } // [END monitoring_list_descriptors] @@ -443,10 +388,7 @@ void listMonitoredResources() throws IOException { PagedResponseWrappers.ListMonitoredResourceDescriptorsPagedResponse response = client .listMonitoredResourceDescriptors(request); - List descriptors = response.getPage() - .getResponseObject().getResourceDescriptorsList(); - - for (MonitoredResourceDescriptor d : descriptors) { + for (MonitoredResourceDescriptor d : response.iterateAll()) { System.out.println(d.getType()); } // [END monitoring_list_resources] @@ -454,7 +396,8 @@ void listMonitoredResources() throws IOException { /** * Gets full information for a monitored resource. - * @param The resource type + * + * @param type The resource type */ void describeMonitoredResources(String type) throws IOException { // [START monitoring_get_descriptor] From 13aaf2a5ab7fed5d06cbd47040955eb725ba2479 Mon Sep 17 00:00:00 2001 From: Jisha Abubaker Date: Wed, 19 Apr 2017 13:04:13 -0700 Subject: [PATCH 08/45] samples: updating license header to remove ARR (#621) --- .../snippets/src/main/java/com/example/monitoring/Snippets.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java index 66fcb481..b02aca06 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java +++ b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 Google Inc. All Rights Reserved. + * 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. From 5c4fc39098c667140eacd7c68c53d810616c0da4 Mon Sep 17 00:00:00 2001 From: Jisha Abubaker Date: Mon, 19 Jun 2017 16:22:12 -0700 Subject: [PATCH 09/45] samples: updating to latest google-cloud-* dependencies (#723) --- .../main/java/com/example/monitoring/QuickstartSample.java | 2 +- .../src/main/java/com/example/monitoring/Snippets.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java index e90b0899..dfd6ae89 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java +++ b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java @@ -21,7 +21,7 @@ import com.google.api.MonitoredResource; // Imports the Google Cloud client library -import com.google.cloud.monitoring.spi.v3.MetricServiceClient; +import com.google.cloud.monitoring.v3.MetricServiceClient; import com.google.monitoring.v3.CreateTimeSeriesRequest; import com.google.monitoring.v3.Point; diff --git a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java index b02aca06..40492605 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java +++ b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java @@ -20,8 +20,8 @@ import com.google.api.MetricDescriptor; import com.google.api.MonitoredResource; import com.google.api.MonitoredResourceDescriptor; -import com.google.cloud.monitoring.spi.v3.MetricServiceClient; -import com.google.cloud.monitoring.spi.v3.PagedResponseWrappers; +import com.google.cloud.monitoring.v3.MetricServiceClient; +import com.google.cloud.monitoring.v3.PagedResponseWrappers; import com.google.monitoring.v3.Aggregation; import com.google.monitoring.v3.CreateMetricDescriptorRequest; import com.google.monitoring.v3.CreateTimeSeriesRequest; From 919b9fb1b22aeabdc7c08e372e757faa531fc609 Mon Sep 17 00:00:00 2001 From: Kurtis Van Gent <31518063+kurtisvg@users.noreply.github.com> Date: Thu, 18 Jan 2018 08:18:34 -0800 Subject: [PATCH 10/45] samples: Updated mlengine, monitoring, pubsub, spanner, and speech. (#993) * Updated mlengine/online-prediction. * Updated monitoring/ * Updated pubsub/ * Updated spanner/ * Updated speech/ * Fixed spanner mistakes. --- .../example/monitoring/QuickstartSample.java | 38 ++++++++++--------- .../java/com/example/monitoring/Snippets.java | 5 ++- .../monitoring/QuickstartSampleIT.java | 33 ++++++++-------- .../com/example/monitoring/SnippetsIT.java | 33 ++++++++-------- 4 files changed, 55 insertions(+), 54 deletions(-) diff --git a/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java index dfd6ae89..c777b6d6 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java +++ b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java @@ -1,28 +1,27 @@ /* - Copyright 2017, 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. -*/ + * Copyright 2017 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. + */ package com.example.monitoring; +//CHECKSTYLE OFF: VariableDeclarationUsageDistance // [START monitoring_quickstart] + import com.google.api.Metric; import com.google.api.MonitoredResource; - -// Imports the Google Cloud client library import com.google.cloud.monitoring.v3.MetricServiceClient; - import com.google.monitoring.v3.CreateTimeSeriesRequest; import com.google.monitoring.v3.Point; import com.google.monitoring.v3.ProjectName; @@ -30,13 +29,15 @@ import com.google.monitoring.v3.TimeSeries; import com.google.monitoring.v3.TypedValue; import com.google.protobuf.util.Timestamps; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +// Imports the Google Cloud client library + public class QuickstartSample { + public static void main(String... args) throws Exception { // Your Google Cloud Platform project ID String projectId = System.getProperty("projectId"); @@ -105,3 +106,4 @@ public static void main(String... args) throws Exception { } } // [END monitoring_quickstart] +//CHECKSTYLE ON: VariableDeclarationUsageDistance diff --git a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java index 40492605..0781c86c 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java +++ b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -37,7 +37,6 @@ import com.google.monitoring.v3.TypedValue; import com.google.protobuf.Duration; import com.google.protobuf.util.Timestamps; - import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -134,6 +133,7 @@ void deleteMetricDescriptor(String name) throws IOException { * 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"); @@ -194,6 +194,7 @@ void writeTimeSeries() throws IOException { System.out.println("Done writing time series value."); // [END monitoring_write_timeseries] } + //CHECKSTYLE ON: VariableDeclarationUsageDistance /** * Demonstrates listing time series headers. diff --git a/samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java b/samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java index dbc8000c..e118067e 100644 --- a/samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java +++ b/samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java @@ -1,32 +1,31 @@ /* - 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. -*/ + * 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. + */ package com.example.monitoring; import static com.google.common.truth.Truth.assertThat; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - /** * Tests for quickstart sample. */ diff --git a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java index bb06947f..ebc6e1d6 100644 --- a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java +++ b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java @@ -1,32 +1,31 @@ /* - 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. -*/ + * 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. + */ package com.example.monitoring; import static com.google.common.truth.Truth.assertThat; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - /** * Tests for quickstart sample. */ From b8295a42a40d0fd36f88c9ffe492f85bc450e6e4 Mon Sep 17 00:00:00 2001 From: Dane Zeke Liergaard Date: Mon, 26 Mar 2018 14:23:15 -0700 Subject: [PATCH 11/45] samples: Fixing build issues caused by dependency update. (#1055) * Auto-update dependencies. * Fix build errors caused by dependency updates. --- .../example/monitoring/QuickstartSample.java | 4 +- .../java/com/example/monitoring/Snippets.java | 70 ++++++++----------- 2 files changed, 32 insertions(+), 42 deletions(-) diff --git a/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java index c777b6d6..151594b8 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java +++ b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java @@ -65,7 +65,7 @@ public static void main(String... args) throws Exception { List pointList = new ArrayList<>(); pointList.add(point); - ProjectName name = ProjectName.create(projectId); + ProjectName name = ProjectName.of(projectId); // Prepares the metric descriptor Map metricLabels = new HashMap(); @@ -93,7 +93,7 @@ public static void main(String... args) throws Exception { timeSeriesList.add(timeSeries); CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder() - .setNameWithProjectName(name) + .setName(name.toString()) .addAllTimeSeries(timeSeriesList) .build(); diff --git a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java index 0781c86c..be60908a 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java +++ b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java @@ -21,7 +21,9 @@ import com.google.api.MonitoredResource; import com.google.api.MonitoredResourceDescriptor; import com.google.cloud.monitoring.v3.MetricServiceClient; -import com.google.cloud.monitoring.v3.PagedResponseWrappers; +import com.google.cloud.monitoring.v3.MetricServiceClient.ListMetricDescriptorsPagedResponse; +import com.google.cloud.monitoring.v3.MetricServiceClient.ListMonitoredResourceDescriptorsPagedResponse; +import com.google.cloud.monitoring.v3.MetricServiceClient.ListTimeSeriesPagedResponse; import com.google.monitoring.v3.Aggregation; import com.google.monitoring.v3.CreateMetricDescriptorRequest; import com.google.monitoring.v3.CreateTimeSeriesRequest; @@ -92,7 +94,7 @@ void createMetricDescriptor(String type) throws IOException { String metricType = CUSTOM_METRIC_DOMAIN + "/" + type; final MetricServiceClient client = MetricServiceClient.create(); - ProjectName name = ProjectName.create(projectId); + ProjectName name = ProjectName.of(projectId); MetricDescriptor descriptor = MetricDescriptor.newBuilder() .setType(metricType) @@ -102,7 +104,7 @@ void createMetricDescriptor(String type) throws IOException { .build(); CreateMetricDescriptorRequest request = CreateMetricDescriptorRequest.newBuilder() - .setNameWithProjectName(name) + .setName(name.toString()) .setMetricDescriptor(descriptor) .build(); @@ -119,7 +121,7 @@ void deleteMetricDescriptor(String name) throws IOException { // [START monitoring_delete_metric] String projectId = System.getProperty("projectId"); final MetricServiceClient client = MetricServiceClient.create(); - MetricDescriptorName metricName = MetricDescriptorName.create(projectId, name); + MetricDescriptorName metricName = MetricDescriptorName.of(projectId, name); client.deleteMetricDescriptor(metricName); System.out.println("Deleted descriptor " + name); // [END monitoring_delete_metric] @@ -155,17 +157,17 @@ void writeTimeSeries() throws IOException { List pointList = new ArrayList<>(); pointList.add(point); - ProjectName name = ProjectName.create(projectId); + ProjectName name = ProjectName.of(projectId); // Prepares the metric descriptor - Map metricLabels = new HashMap(); + Map metricLabels = new HashMap<>(); Metric metric = Metric.newBuilder() .setType("custom.googleapis.com/my_metric") .putAllLabels(metricLabels) .build(); // Prepares the monitored resource descriptor - Map resourceLabels = new HashMap(); + Map resourceLabels = new HashMap<>(); resourceLabels.put("instance_id", "1234567890123456789"); resourceLabels.put("zone", "us-central1-f"); @@ -185,7 +187,7 @@ void writeTimeSeries() throws IOException { timeSeriesList.add(timeSeries); CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder() - .setNameWithProjectName(name) + .setName(name.toString()) .addAllTimeSeries(timeSeriesList) .build(); @@ -203,7 +205,7 @@ void listTimeSeriesHeaders() throws IOException { // [START monitoring_read_timeseries_fields] MetricServiceClient metricServiceClient = MetricServiceClient.create(); String projectId = System.getProperty("projectId"); - ProjectName name = ProjectName.create(projectId); + ProjectName name = ProjectName.of(projectId); // Restrict time to last 20 minutes long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000); @@ -213,15 +215,14 @@ void listTimeSeriesHeaders() throws IOException { .build(); ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder() - .setNameWithProjectName(name) + .setName(name.toString()) .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"") .setInterval(interval) .setView(ListTimeSeriesRequest.TimeSeriesView.HEADERS); ListTimeSeriesRequest request = requestBuilder.build(); - PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient - .listTimeSeries(request); + ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request); System.out.println("Got timeseries headers: "); for (TimeSeries ts : response.iterateAll()) { @@ -237,7 +238,7 @@ void listTimeSeries(String filter) throws IOException { // [START monitoring_read_timeseries_simple] MetricServiceClient metricServiceClient = MetricServiceClient.create(); String projectId = System.getProperty("projectId"); - ProjectName name = ProjectName.create(projectId); + ProjectName name = ProjectName.of(projectId); // Restrict time to last 20 minutes long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000); @@ -247,14 +248,13 @@ void listTimeSeries(String filter) throws IOException { .build(); ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder() - .setNameWithProjectName(name) + .setName(name.toString()) .setFilter(filter) .setInterval(interval); ListTimeSeriesRequest request = requestBuilder.build(); - PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient - .listTimeSeries(request); + ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request); System.out.println("Got timeseries: "); for (TimeSeries ts : response.iterateAll()) { @@ -270,7 +270,7 @@ void listTimeSeriesAggregrate() throws IOException { // [START monitoring_read_timeseries_align] MetricServiceClient metricServiceClient = MetricServiceClient.create(); String projectId = System.getProperty("projectId"); - ProjectName name = ProjectName.create(projectId); + ProjectName name = ProjectName.of(projectId); // Restrict time to last 20 minutes long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000); @@ -285,15 +285,14 @@ void listTimeSeriesAggregrate() throws IOException { .build(); ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder() - .setNameWithProjectName(name) + .setName(name.toString()) .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"") .setInterval(interval) .setAggregation(aggregation); ListTimeSeriesRequest request = requestBuilder.build(); - PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient - .listTimeSeries(request); + ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request); System.out.println("Got timeseries: "); for (TimeSeries ts : response.iterateAll()) { @@ -309,7 +308,7 @@ void listTimeSeriesReduce() throws IOException { // [START monitoring_read_timeseries_reduce] MetricServiceClient metricServiceClient = MetricServiceClient.create(); String projectId = System.getProperty("projectId"); - ProjectName name = ProjectName.create(projectId); + ProjectName name = ProjectName.of(projectId); // Restrict time to last 20 minutes long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000); @@ -325,15 +324,14 @@ void listTimeSeriesReduce() throws IOException { .build(); ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder() - .setNameWithProjectName(name) + .setName(name.toString()) .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"") .setInterval(interval) .setAggregation(aggregation); ListTimeSeriesRequest request = requestBuilder.build(); - PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient - .listTimeSeries(request); + ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request); System.out.println("Got timeseries: "); for (TimeSeries ts : response.iterateAll()) { @@ -351,14 +349,13 @@ void listMetricDescriptors() throws IOException { String projectId = System.getProperty("projectId"); final MetricServiceClient client = MetricServiceClient.create(); - ProjectName name = ProjectName.create(projectId); + ProjectName name = ProjectName.of(projectId); ListMetricDescriptorsRequest request = ListMetricDescriptorsRequest .newBuilder() - .setNameWithProjectName(name) + .setName(name.toString()) .build(); - PagedResponseWrappers.ListMetricDescriptorsPagedResponse response = - client.listMetricDescriptors(request); + ListMetricDescriptorsPagedResponse response = client.listMetricDescriptors(request); System.out.println("Listing descriptors: "); @@ -377,16 +374,16 @@ void listMonitoredResources() throws IOException { String projectId = System.getProperty("projectId"); final MetricServiceClient client = MetricServiceClient.create(); - ProjectName name = ProjectName.create(projectId); + ProjectName name = ProjectName.of(projectId); ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest .newBuilder() - .setNameWithProjectName(name) + .setName(name.toString()) .build(); System.out.println("Listing monitored resource descriptors: "); - PagedResponseWrappers.ListMonitoredResourceDescriptorsPagedResponse response = client + ListMonitoredResourceDescriptorsPagedResponse response = client .listMonitoredResourceDescriptors(request); for (MonitoredResourceDescriptor d : response.iterateAll()) { @@ -406,7 +403,7 @@ void describeMonitoredResources(String type) throws IOException { String projectId = System.getProperty("projectId"); final MetricServiceClient client = MetricServiceClient.create(); - MonitoredResourceDescriptorName name = MonitoredResourceDescriptorName.create(projectId, type); + MonitoredResourceDescriptorName name = MonitoredResourceDescriptorName.of(projectId, type); MonitoredResourceDescriptor response = client.getMonitoredResourceDescriptor(name); System.out.println("Printing monitored resource descriptor: "); @@ -462,7 +459,7 @@ void handleCommandLine(String commandLine) throws IOException { break; case "delete-metric-descriptor": args = commandLine.split("\\s+", 2); - if (args.length != 1) { + if (args.length != 2) { throw new IllegalArgumentException("usage: "); } deleteMetricDescriptor(args[1]); @@ -507,13 +504,6 @@ void handleCommandLine(String commandLine) throws IOException { } } - private void assertArgsLength(String[] args, int expectedLength) { - if (args.length != expectedLength) { - throw new IllegalArgumentException( - String.format("expected exactly %d arg(s), found %d", expectedLength, args.length)); - } - } - private static void printUsage() { System.out.println("Usage:"); System.out.println(); From 10740dd0709e22626a1d4071cb4c3bc618bdfef1 Mon Sep 17 00:00:00 2001 From: Dane Zeke Liergaard Date: Thu, 3 Jan 2019 10:02:45 -0800 Subject: [PATCH 12/45] samples: Add monitoring_get_resource tag/code sample to monitoring snippets. (#1306) * Add monitoring_get_resource tag/code sample to monitoring snippets. * Add monitoring_alert_delete_channel code, tag, and test. --- .../java/com/example/monitoring/Snippets.java | 15 ++++++++++++++- .../java/com/example/monitoring/SnippetsIT.java | 14 ++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java index be60908a..81d5c875 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java +++ b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java @@ -24,6 +24,7 @@ import com.google.cloud.monitoring.v3.MetricServiceClient.ListMetricDescriptorsPagedResponse; import com.google.cloud.monitoring.v3.MetricServiceClient.ListMonitoredResourceDescriptorsPagedResponse; import com.google.cloud.monitoring.v3.MetricServiceClient.ListTimeSeriesPagedResponse; +import com.google.gson.Gson; import com.google.monitoring.v3.Aggregation; import com.google.monitoring.v3.CreateMetricDescriptorRequest; import com.google.monitoring.v3.CreateTimeSeriesRequest; @@ -39,6 +40,7 @@ import com.google.monitoring.v3.TypedValue; import com.google.protobuf.Duration; import com.google.protobuf.util.Timestamps; + import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -49,8 +51,8 @@ public class Snippets { - private static final String CUSTOM_METRIC_DOMAIN = "custom.googleapis.com"; + private static final Gson gson = new Gson(); /** * Exercises the methods defined in this class. @@ -392,6 +394,17 @@ void listMonitoredResources() throws IOException { // [END monitoring_list_resources] } + // [START monitoring_get_resource] + void getMonitoredResource(String resourceId) throws IOException { + String projectId = System.getProperty("projectId"); + MetricServiceClient client = MetricServiceClient.create(); + MonitoredResourceDescriptorName name = + MonitoredResourceDescriptorName.of(projectId, resourceId); + MonitoredResourceDescriptor response = client.getMonitoredResourceDescriptor(name); + System.out.println("Retrieved Monitored Resource: " + gson.toJson(response)); + } + // [END monitoring_get_resource] + /** * Gets full information for a monitored resource. * diff --git a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java index ebc6e1d6..5b4eb9be 100644 --- a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java +++ b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java @@ -20,6 +20,7 @@ import java.io.ByteArrayOutputStream; import java.io.PrintStream; + import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -70,6 +71,19 @@ public void testListMetricsDescriptor() throws Exception { assertThat(got).contains("metricDescriptors/bigquery.googleapis.com/query/count"); } + @Test + public void testGetMetricsDescriptor() throws Exception { + // Act + System.setProperty("projectId", SnippetsIT.getProjectId()); + Snippets snippets = new Snippets(); + + snippets.getMonitoredResource("api"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Produced API"); + } + @Test public void testListTimeSeries() throws Exception { // Act From 2c480000111c2acf72d04c14b4dfc0a17699fa29 Mon Sep 17 00:00:00 2001 From: Dane Zeke Liergaard Date: Mon, 10 Jun 2019 11:54:22 -0700 Subject: [PATCH 13/45] samples: Add store_id label to monitoring snippets. (#1450) --- .../src/main/java/com/example/monitoring/Snippets.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java index 81d5c875..a84d3df2 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java +++ b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java @@ -16,6 +16,7 @@ package com.example.monitoring; +import com.google.api.LabelDescriptor; import com.google.api.Metric; import com.google.api.MetricDescriptor; import com.google.api.MonitoredResource; @@ -100,6 +101,10 @@ void createMetricDescriptor(String type) throws IOException { MetricDescriptor descriptor = MetricDescriptor.newBuilder() .setType(metricType) + .addLabels(LabelDescriptor + .newBuilder() + .setKey("store_id") + .setValueType(LabelDescriptor.ValueType.STRING)) .setDescription("This is a simple example of a custom metric.") .setMetricKind(MetricDescriptor.MetricKind.GAUGE) .setValueType(MetricDescriptor.ValueType.DOUBLE) From b1f82493e3e7e48076c3873ca0dd60881eec51d6 Mon Sep 17 00:00:00 2001 From: Averi Kitsch Date: Fri, 27 Mar 2020 12:00:25 -0700 Subject: [PATCH 14/45] samples: update shared config (#2443) * update shared config * Update to 1.0.13 * lint * Fix linting * lint * fix imports Co-authored-by: Les Vogel --- .../example/monitoring/QuickstartSample.java | 55 ++-- .../java/com/example/monitoring/Snippets.java | 279 +++++++++--------- .../monitoring/QuickstartSampleIT.java | 8 +- .../com/example/monitoring/SnippetsIT.java | 9 +- 4 files changed, 169 insertions(+), 182 deletions(-) diff --git a/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java index 151594b8..fcfd392a 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java +++ b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java @@ -16,7 +16,7 @@ package com.example.monitoring; -//CHECKSTYLE OFF: VariableDeclarationUsageDistance +// CHECKSTYLE OFF: VariableDeclarationUsageDistance // [START monitoring_quickstart] import com.google.api.Metric; @@ -51,16 +51,12 @@ public static void main(String... args) throws Exception { 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(); + 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 pointList = new ArrayList<>(); pointList.add(point); @@ -70,32 +66,33 @@ public static void main(String... args) throws Exception { // Prepares the metric descriptor Map metricLabels = new HashMap(); metricLabels.put("store_id", "Pittsburg"); - Metric metric = Metric.newBuilder() - .setType("custom.googleapis.com/stores/daily_sales") - .putAllLabels(metricLabels) - .build(); + Metric metric = + Metric.newBuilder() + .setType("custom.googleapis.com/stores/daily_sales") + .putAllLabels(metricLabels) + .build(); // Prepares the monitored resource descriptor Map resourceLabels = new HashMap(); resourceLabels.put("project_id", projectId); - MonitoredResource resource = MonitoredResource.newBuilder() - .setType("global") - .putAllLabels(resourceLabels) - .build(); + MonitoredResource resource = + MonitoredResource.newBuilder().setType("global").putAllLabels(resourceLabels).build(); // Prepares the time series request - TimeSeries timeSeries = TimeSeries.newBuilder() - .setMetric(metric) - .setResource(resource) - .addAllPoints(pointList) - .build(); + TimeSeries timeSeries = + TimeSeries.newBuilder() + .setMetric(metric) + .setResource(resource) + .addAllPoints(pointList) + .build(); List timeSeriesList = new ArrayList<>(); timeSeriesList.add(timeSeries); - CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder() - .setName(name.toString()) - .addAllTimeSeries(timeSeriesList) - .build(); + CreateTimeSeriesRequest request = + CreateTimeSeriesRequest.newBuilder() + .setName(name.toString()) + .addAllTimeSeries(timeSeriesList) + .build(); // Writes time series data metricServiceClient.createTimeSeries(request); @@ -106,4 +103,4 @@ public static void main(String... args) throws Exception { } } // [END monitoring_quickstart] -//CHECKSTYLE ON: VariableDeclarationUsageDistance +// CHECKSTYLE ON: VariableDeclarationUsageDistance diff --git a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java index a84d3df2..b2967ccd 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/Snippets.java +++ b/samples/snippets/src/main/java/com/example/monitoring/Snippets.java @@ -41,7 +41,6 @@ import com.google.monitoring.v3.TypedValue; import com.google.protobuf.Duration; import com.google.protobuf.util.Timestamps; - import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -50,16 +49,17 @@ // Imports the Google Cloud client library - public class Snippets { private static final String CUSTOM_METRIC_DOMAIN = "custom.googleapis.com"; private static final Gson gson = new Gson(); /** * Exercises the methods defined in this class. + * *

- *

Assumes that you are authenticated using the Google Cloud SDK (using - * {@code gcloud auth application-default-login}). + * + *

Assumes that you are authenticated using the Google Cloud SDK (using {@code gcloud auth + * application-default-login}). */ public static void main(String[] args) throws Exception { @@ -85,8 +85,9 @@ public static void main(String[] args) throws Exception { /** * Creates a metric descriptor. - *

- * See: https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create + * + *

See: + * https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create * * @param type The metric type */ @@ -99,21 +100,23 @@ void createMetricDescriptor(String type) throws IOException { final MetricServiceClient client = MetricServiceClient.create(); ProjectName name = ProjectName.of(projectId); - MetricDescriptor descriptor = MetricDescriptor.newBuilder() - .setType(metricType) - .addLabels(LabelDescriptor - .newBuilder() - .setKey("store_id") - .setValueType(LabelDescriptor.ValueType.STRING)) - .setDescription("This is a simple example of a custom metric.") - .setMetricKind(MetricDescriptor.MetricKind.GAUGE) - .setValueType(MetricDescriptor.ValueType.DOUBLE) - .build(); - - CreateMetricDescriptorRequest request = CreateMetricDescriptorRequest.newBuilder() - .setName(name.toString()) - .setMetricDescriptor(descriptor) - .build(); + MetricDescriptor descriptor = + MetricDescriptor.newBuilder() + .setType(metricType) + .addLabels( + LabelDescriptor.newBuilder() + .setKey("store_id") + .setValueType(LabelDescriptor.ValueType.STRING)) + .setDescription("This is a simple example of a custom metric.") + .setMetricKind(MetricDescriptor.MetricKind.GAUGE) + .setValueType(MetricDescriptor.ValueType.DOUBLE) + .build(); + + CreateMetricDescriptorRequest request = + CreateMetricDescriptorRequest.newBuilder() + .setName(name.toString()) + .setMetricDescriptor(descriptor) + .build(); client.createMetricDescriptor(request); // [END monitoring_create_metric] @@ -137,12 +140,11 @@ void deleteMetricDescriptor(String name) throws IOException { /** * Demonstrates writing a time series value for the metric type * 'custom.google.apis.com/my_metric'. - *

- * 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. + * + *

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 + // CHECKSTYLE OFF: VariableDeclarationUsageDistance void writeTimeSeries() throws IOException { // [START monitoring_write_timeseries] String projectId = System.getProperty("projectId"); @@ -150,16 +152,12 @@ void writeTimeSeries() throws IOException { 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(); + 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 pointList = new ArrayList<>(); pointList.add(point); @@ -168,46 +166,45 @@ void writeTimeSeries() throws IOException { // Prepares the metric descriptor Map metricLabels = new HashMap<>(); - Metric metric = Metric.newBuilder() - .setType("custom.googleapis.com/my_metric") - .putAllLabels(metricLabels) - .build(); + Metric metric = + Metric.newBuilder() + .setType("custom.googleapis.com/my_metric") + .putAllLabels(metricLabels) + .build(); // Prepares the monitored resource descriptor Map resourceLabels = new HashMap<>(); resourceLabels.put("instance_id", "1234567890123456789"); resourceLabels.put("zone", "us-central1-f"); - MonitoredResource resource = MonitoredResource.newBuilder() - .setType("gce_instance") - .putAllLabels(resourceLabels) - .build(); + 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(); + TimeSeries timeSeries = + TimeSeries.newBuilder() + .setMetric(metric) + .setResource(resource) + .addAllPoints(pointList) + .build(); List timeSeriesList = new ArrayList<>(); timeSeriesList.add(timeSeries); - CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder() - .setName(name.toString()) - .addAllTimeSeries(timeSeriesList) - .build(); + 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] } - //CHECKSTYLE ON: VariableDeclarationUsageDistance + // CHECKSTYLE ON: VariableDeclarationUsageDistance - /** - * Demonstrates listing time series headers. - */ + /** Demonstrates listing time series headers. */ void listTimeSeriesHeaders() throws IOException { // [START monitoring_read_timeseries_fields] MetricServiceClient metricServiceClient = MetricServiceClient.create(); @@ -216,16 +213,18 @@ void listTimeSeriesHeaders() throws IOException { // 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); + 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(); @@ -238,9 +237,7 @@ void listTimeSeriesHeaders() throws IOException { // [END monitoring_read_timeseries_fields] } - /** - * Demonstrates listing time series using a filter. - */ + /** Demonstrates listing time series using a filter. */ void listTimeSeries(String filter) throws IOException { // [START monitoring_read_timeseries_simple] MetricServiceClient metricServiceClient = MetricServiceClient.create(); @@ -249,15 +246,17 @@ void listTimeSeries(String filter) throws IOException { // 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); + 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(); @@ -270,9 +269,7 @@ void listTimeSeries(String filter) throws IOException { // [END monitoring_read_timeseries_simple] } - /** - * Demonstrates listing time series and aggregating them. - */ + /** Demonstrates listing time series and aggregating them. */ void listTimeSeriesAggregrate() throws IOException { // [START monitoring_read_timeseries_align] MetricServiceClient metricServiceClient = MetricServiceClient.create(); @@ -281,21 +278,24 @@ void listTimeSeriesAggregrate() throws IOException { // 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); + 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(); @@ -308,9 +308,7 @@ void listTimeSeriesAggregrate() throws IOException { // [END monitoring_read_timeseries_align] } - /** - * Demonstrates listing time series and aggregating and reducing them. - */ + /** Demonstrates listing time series and aggregating and reducing them. */ void listTimeSeriesReduce() throws IOException { // [START monitoring_read_timeseries_reduce] MetricServiceClient metricServiceClient = MetricServiceClient.create(); @@ -319,22 +317,25 @@ void listTimeSeriesReduce() throws IOException { // 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); + 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(); @@ -347,9 +348,7 @@ void listTimeSeriesReduce() throws IOException { // [END monitoring_read_timeseries_reduce] } - /** - * Returns the first page of all metric descriptors. - */ + /** Returns the first page of all metric descriptors. */ void listMetricDescriptors() throws IOException { // [START monitoring_list_descriptors] // Your Google Cloud Platform project ID @@ -358,10 +357,8 @@ void listMetricDescriptors() throws IOException { final MetricServiceClient client = MetricServiceClient.create(); ProjectName name = ProjectName.of(projectId); - ListMetricDescriptorsRequest request = ListMetricDescriptorsRequest - .newBuilder() - .setName(name.toString()) - .build(); + ListMetricDescriptorsRequest request = + ListMetricDescriptorsRequest.newBuilder().setName(name.toString()).build(); ListMetricDescriptorsPagedResponse response = client.listMetricDescriptors(request); System.out.println("Listing descriptors: "); @@ -372,9 +369,7 @@ void listMetricDescriptors() throws IOException { // [END monitoring_list_descriptors] } - /** - * Gets all monitored resource descriptors. - */ + /** Gets all monitored resource descriptors. */ void listMonitoredResources() throws IOException { // [START monitoring_list_resources] // Your Google Cloud Platform project ID @@ -383,15 +378,13 @@ void listMonitoredResources() throws IOException { final MetricServiceClient client = MetricServiceClient.create(); ProjectName name = ProjectName.of(projectId); - ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest - .newBuilder() - .setName(name.toString()) - .build(); + ListMonitoredResourceDescriptorsRequest request = + ListMonitoredResourceDescriptorsRequest.newBuilder().setName(name.toString()).build(); System.out.println("Listing monitored resource descriptors: "); - ListMonitoredResourceDescriptorsPagedResponse response = client - .listMonitoredResourceDescriptors(request); + ListMonitoredResourceDescriptorsPagedResponse response = + client.listMonitoredResourceDescriptors(request); for (MonitoredResourceDescriptor d : response.iterateAll()) { System.out.println(d.getType()); @@ -429,7 +422,6 @@ void describeMonitoredResources(String type) throws IOException { // [END monitoring_get_descriptor] } - /** * Handles a single command. * @@ -531,15 +523,18 @@ private static void printUsage() { System.out.println(" get-resource Describes a monitored resource"); System.out.println(" delete-metric-descriptors Deletes a metric descriptor"); System.out.println(" write-time-series Writes a time series value to a metric"); - System.out.println(" list-headers List time series header of " - + " 'compute.googleapis.com/instance/cpu/utilization'"); - System.out.println(" list-time-series-header List time series data that matches a " - + "given filter"); - System.out.println(" list-aggregate `Aggregates time series data that matches" - + "'compute.googleapis.com/instance/cpu/utilization"); - System.out.println(" list-reduce `Reduces time series data that matches" - + " 'compute.googleapis.com/instance/cpu/utilization"); + System.out.println( + " list-headers List time series header of " + + " 'compute.googleapis.com/instance/cpu/utilization'"); + System.out.println( + " list-time-series-header List time series data that matches a " + + "given filter"); + System.out.println( + " list-aggregate `Aggregates time series data that matches" + + "'compute.googleapis.com/instance/cpu/utilization"); + System.out.println( + " list-reduce `Reduces time series data that matches" + + " 'compute.googleapis.com/instance/cpu/utilization"); System.out.println(); } - } diff --git a/samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java b/samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java index e118067e..d4bd52c5 100644 --- a/samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java +++ b/samples/snippets/src/test/java/com/example/monitoring/QuickstartSampleIT.java @@ -26,9 +26,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** - * Tests for quickstart sample. - */ +/** Tests for quickstart sample. */ @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class QuickstartSampleIT { @@ -40,8 +38,8 @@ public class QuickstartSampleIT { private static String getProjectId() { String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME)); if (projectId == null) { - projectId = System.getProperty(LEGACY_PROJECT_ENV_NAME, - System.getenv(LEGACY_PROJECT_ENV_NAME)); + projectId = + System.getProperty(LEGACY_PROJECT_ENV_NAME, System.getenv(LEGACY_PROJECT_ENV_NAME)); } return projectId; } diff --git a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java index 5b4eb9be..9685926b 100644 --- a/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java +++ b/samples/snippets/src/test/java/com/example/monitoring/SnippetsIT.java @@ -20,16 +20,13 @@ import java.io.ByteArrayOutputStream; import java.io.PrintStream; - import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** - * Tests for quickstart sample. - */ +/** Tests for quickstart sample. */ @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class SnippetsIT { @@ -41,8 +38,8 @@ public class SnippetsIT { private static String getProjectId() { String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME)); if (projectId == null) { - projectId = System.getProperty(LEGACY_PROJECT_ENV_NAME, - System.getenv(LEGACY_PROJECT_ENV_NAME)); + projectId = + System.getProperty(LEGACY_PROJECT_ENV_NAME, System.getenv(LEGACY_PROJECT_ENV_NAME)); } return projectId; } From 0cbcd736b9ebb08f320225732b168de882f21724 Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 11 Jun 2020 16:32:05 -0400 Subject: [PATCH 15/45] samples: fix-it(Cloud Monitoring Api): Change the quick start documentation. (#3150) - Change the quick start metric to `custom.googleapis.com/my_metric` - Change the type to "gce_instance". Justification: Cloud monitoring api team discourage using "global" resource type for custom metric, and to align the sample, I change the metric type also. --- .../java/com/example/monitoring/QuickstartSample.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java index fcfd392a..6b6e2579 100644 --- a/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java +++ b/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java @@ -55,7 +55,7 @@ public static void main(String... args) throws Exception { TimeInterval.newBuilder() .setEndTime(Timestamps.fromMillis(System.currentTimeMillis())) .build(); - TypedValue value = TypedValue.newBuilder().setDoubleValue(123.45).build(); + TypedValue value = TypedValue.newBuilder().setDoubleValue(3.14).build(); Point point = Point.newBuilder().setInterval(interval).setValue(value).build(); List pointList = new ArrayList<>(); @@ -68,15 +68,16 @@ public static void main(String... args) throws Exception { metricLabels.put("store_id", "Pittsburg"); Metric metric = Metric.newBuilder() - .setType("custom.googleapis.com/stores/daily_sales") + .setType("custom.googleapis.com/my_metric") .putAllLabels(metricLabels) .build(); // Prepares the monitored resource descriptor Map resourceLabels = new HashMap(); - resourceLabels.put("project_id", projectId); + resourceLabels.put("instance_id", "1234567890123456789"); + resourceLabels.put("zone", "us-central1-f"); MonitoredResource resource = - MonitoredResource.newBuilder().setType("global").putAllLabels(resourceLabels).build(); + MonitoredResource.newBuilder().setType("gce_instance").putAllLabels(resourceLabels).build(); // Prepares the time series request TimeSeries timeSeries = From a6e49d8f6e697f736d31b635ad6a7a22f6c1c41f Mon Sep 17 00:00:00 2001 From: Bill Prin Date: Wed, 16 Mar 2016 12:16:20 -0700 Subject: [PATCH 16/45] samples: 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.) --- .../src/main/java/CreateCustomMetric.java | 324 ++++++++++++++++++ .../snippets/src/main/java/ListResources.java | 211 ++++++++++++ .../src/test/java/CreateCustomMetricTest.java | 91 +++++ .../src/test/java/ListResourcesTest.java | 91 +++++ 4 files changed, 717 insertions(+) create mode 100644 samples/snippets/src/main/java/CreateCustomMetric.java create mode 100644 samples/snippets/src/main/java/ListResources.java create mode 100644 samples/snippets/src/test/java/CreateCustomMetricTest.java create mode 100644 samples/snippets/src/test/java/ListResourcesTest.java diff --git a/samples/snippets/src/main/java/CreateCustomMetric.java b/samples/snippets/src/main/java/CreateCustomMetric.java new file mode 100644 index 00000000..18cdc4b5 --- /dev/null +++ b/samples/snippets/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/samples/snippets/src/main/java/ListResources.java b/samples/snippets/src/main/java/ListResources.java new file mode 100644 index 00000000..1eeeec28 --- /dev/null +++ b/samples/snippets/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/samples/snippets/src/test/java/CreateCustomMetricTest.java b/samples/snippets/src/test/java/CreateCustomMetricTest.java new file mode 100644 index 00000000..c18b34c4 --- /dev/null +++ b/samples/snippets/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/samples/snippets/src/test/java/ListResourcesTest.java b/samples/snippets/src/test/java/ListResourcesTest.java new file mode 100644 index 00000000..f31b12eb --- /dev/null +++ b/samples/snippets/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")); + } + +} From 8739256efb99813c7799181d6fc263826927486a Mon Sep 17 00:00:00 2001 From: Tim Swast Date: Wed, 16 Mar 2016 16:35:22 -0700 Subject: [PATCH 17/45] samples: Fix checkstyle in monitoring v3 sample. Also, start applying checkstyles on test classes so that new samples with out-of-spec test classes won't get added. --- .../src/test/java/CreateCustomMetricTest.java | 31 +++++++++---------- .../src/test/java/ListResourcesTest.java | 26 ++++++++++------ 2 files changed, 30 insertions(+), 27 deletions(-) diff --git a/samples/snippets/src/test/java/CreateCustomMetricTest.java b/samples/snippets/src/test/java/CreateCustomMetricTest.java index c18b34c4..f4c2aae8 100644 --- a/samples/snippets/src/test/java/CreateCustomMetricTest.java +++ b/samples/snippets/src/test/java/CreateCustomMetricTest.java @@ -1,12 +1,12 @@ -/** +/* * 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 @@ -14,10 +14,14 @@ * 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.Assert; + import org.junit.Before; import org.junit.Test; @@ -49,8 +53,6 @@ public int nextInt(int bound) { /** * Creates the monitoring service client. - * - * @throws Exception */ @Before public void setUp() throws Exception { @@ -62,8 +64,6 @@ public void setUp() throws Exception { /** * Tests that the value written for a custom metric can be read back correctly. - * - * @throws Exception */ @Test public void testValueRead() throws Exception { @@ -75,17 +75,14 @@ public void testValueRead() throws Exception { underTest.writeCustomMetricTimeseriesValue(); // give time for write to register Thread.sleep(2000); - List response = underTest.readTimeseriesValue() - .getTimeSeries().get(0).getPoints(); + List response = + underTest.readTimeseriesValue().getTimeSeries().get(0).getPoints(); - boolean found = false; + ImmutableList.Builder timeSeries = ImmutableList.builder(); for (Point p : response) { - System.out.println("found a response " + p.getValue().getInt64Value()); - if (p.getValue().getInt64Value() == 0) { - found = true; - } + timeSeries.add(p.getValue().getInt64Value()); } - Assert.assertTrue(found); + assertThat(timeSeries.build()).contains(0L); } } diff --git a/samples/snippets/src/test/java/ListResourcesTest.java b/samples/snippets/src/test/java/ListResourcesTest.java index f31b12eb..234ee858 100644 --- a/samples/snippets/src/test/java/ListResourcesTest.java +++ b/samples/snippets/src/test/java/ListResourcesTest.java @@ -1,12 +1,12 @@ -/** +/* * 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 @@ -14,9 +14,10 @@ * the License. */ +import static com.google.common.truth.Truth.assertThat; import com.google.api.services.monitoring.v3.Monitoring; -import junit.framework.Assert; + import org.junit.Before; import org.junit.Test; @@ -34,7 +35,7 @@ public class ListResourcesTest { /** * The project ID of the project created for the integration tests. */ - public static final String TEST_PROJECT_ID = "cloud-monitoring-dev"; + public static final String TEST_PROJECT_ID = "cloud-samples-tests"; /** * Google Cloud Monitoring client to integration test. @@ -63,7 +64,9 @@ public void setUp() throws Exception { 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")); + assertThat(result) + .named("output text stream") + .contains("An application running in Google App Engine"); } /** @@ -74,7 +77,9 @@ public void testListMonitoredResourceDescriptors() throws Exception { 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")); + assertThat(result) + .named("output text stream") + .contains("Delta CPU usage time. Units are second"); } /** @@ -85,7 +90,8 @@ public void testListMetrics() throws Exception { public void testListTimeseries() throws Exception { this.underTest.listTimeseries(); String result = new String(os.toByteArray()); - Assert.assertTrue(result.contains("listTimeseries response")); + assertThat(result) + .named("output text stream") + .contains("listTimeseries response"); } - } From 37aa171b4bdc0a3bb96c3a5bb1853eafa98c9f69 Mon Sep 17 00:00:00 2001 From: Bill Prin Date: Wed, 30 Mar 2016 13:42:53 -0700 Subject: [PATCH 18/45] samples: Fix style, Use Same Test Project Also fix error in README and change test project to this repo's project. --- .../src/main/java/CreateCustomMetric.java | 66 ++++++++++--------- .../snippets/src/main/java/ListResources.java | 39 ++++++----- .../src/test/java/CreateCustomMetricTest.java | 34 ++++------ .../src/test/java/ListResourcesTest.java | 22 ++++--- 4 files changed, 78 insertions(+), 83 deletions(-) diff --git a/samples/snippets/src/main/java/CreateCustomMetric.java b/samples/snippets/src/main/java/CreateCustomMetric.java index 18cdc4b5..86047357 100644 --- a/samples/snippets/src/main/java/CreateCustomMetric.java +++ b/samples/snippets/src/main/java/CreateCustomMetric.java @@ -1,17 +1,17 @@ -/** - * 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 - *

+/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + * 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; @@ -40,12 +40,12 @@ 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. + * 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 { @@ -111,7 +111,8 @@ public CreateCustomMetric(Monitoring monitoringService, String projectResource) /** * 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. + *

+ *

Package-private to be accessible to tests. */ CreateCustomMetric(Monitoring monitoringService, String projectResource, String metricName, int bound) { @@ -162,7 +163,8 @@ private long getRandomPoint() { /** * This method creates a custom metric with arbitrary names, description, * and units. - * Package-private to be accessible to tests. + *

+ *

Package-private to be accessible to tests. */ MetricDescriptor createCustomMetric() throws IOException { MetricDescriptor metricDescriptor = new MetricDescriptor(); @@ -196,8 +198,10 @@ MetricDescriptor createCustomMetric() throws IOException { } /** - * 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 + * 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 { @@ -218,8 +222,8 @@ public MetricDescriptor getCustomMetric() throws IOException { } /** - * 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, + * 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. * @@ -268,17 +272,17 @@ void writeCustomMetricTimeseriesValue() throws IOException { * last 5 minutes. * * @return The TimeSeries response object reflecting the Timeseries of the custom metrics - * for the last 5 minutes. + * 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(); + .setFilter("metric.type=\"" + metricType + "\"") + .setPageSize(3) + .setIntervalStartTime(getStartTime()) + .setIntervalEndTime(getNow()) + .execute(); return response; } @@ -302,8 +306,8 @@ public static void main(final String[] args) throws Exception { // Create an authorized API client Monitoring monitoringService = ListResources.authenticate(); - CreateCustomMetric metricWriter = new CreateCustomMetric( - monitoringService, projectResource); + CreateCustomMetric metricWriter = + new CreateCustomMetric(monitoringService, projectResource); MetricDescriptor metricDescriptor = metricWriter.createCustomMetric(); diff --git a/samples/snippets/src/main/java/ListResources.java b/samples/snippets/src/main/java/ListResources.java index 1eeeec28..859e635f 100644 --- a/samples/snippets/src/main/java/ListResources.java +++ b/samples/snippets/src/main/java/ListResources.java @@ -1,17 +1,17 @@ -/** - * 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 - *

+/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + * 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] @@ -35,7 +35,6 @@ 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. @@ -91,9 +90,10 @@ private ListResources(Monitoring monitoringService, String projectResource) { /** * 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. + *

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 = @@ -105,14 +105,12 @@ void listMonitoredResourceDescriptors() throws IOException { /** * Query to MetricDescriptors.list - * This lists all the current metrics. - *

- * Package-private to be accessible to tests. + *

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(); + .list(this.projectResource).execute(); this.outputStream.println("listMetricDescriptors response"); this.outputStream.println(metricsResponse.toPrettyString()); } @@ -143,7 +141,8 @@ private static String getEndTime() { /** * Query to MetricDescriptors.list - * This lists all the current metrics. + * + *

This lists all the current metrics. */ void listTimeseries() throws IOException { ListTimeSeriesResponse timeSeriesList = this.monitoringService.projects().timeSeries() diff --git a/samples/snippets/src/test/java/CreateCustomMetricTest.java b/samples/snippets/src/test/java/CreateCustomMetricTest.java index f4c2aae8..301d08ed 100644 --- a/samples/snippets/src/test/java/CreateCustomMetricTest.java +++ b/samples/snippets/src/test/java/CreateCustomMetricTest.java @@ -1,17 +1,17 @@ /* - * Copyright (c) 2015 Google Inc. + * Copyright 2016 Google Inc. All Rights Reserved. * - * 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 + * 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. + * 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; @@ -21,31 +21,21 @@ import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.RandomStringUtils; - 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 + * 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. */ diff --git a/samples/snippets/src/test/java/ListResourcesTest.java b/samples/snippets/src/test/java/ListResourcesTest.java index 234ee858..e8415d76 100644 --- a/samples/snippets/src/test/java/ListResourcesTest.java +++ b/samples/snippets/src/test/java/ListResourcesTest.java @@ -1,17 +1,17 @@ /* - * Copyright (c) 2015 Google Inc. + * Copyright 2016 Google Inc. All Rights Reserved. * - * 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 + * 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. + * 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; @@ -24,9 +24,11 @@ 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 + * 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. */ From 0373897d505992dd6fa5fb4c5910369568e56506 Mon Sep 17 00:00:00 2001 From: Bill Prin Date: Mon, 15 Aug 2016 17:56:33 -0700 Subject: [PATCH 19/45] samples: Remove output only fields --- samples/snippets/src/main/java/CreateCustomMetric.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/samples/snippets/src/main/java/CreateCustomMetric.java b/samples/snippets/src/main/java/CreateCustomMetric.java index 86047357..76225bec 100644 --- a/samples/snippets/src/main/java/CreateCustomMetric.java +++ b/samples/snippets/src/main/java/CreateCustomMetric.java @@ -250,8 +250,6 @@ void writeCustomMetricTimeseriesValue() throws IOException { 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(); From 8a06cd25bdb8a0a88ce65a548fcfdca728bfb708 Mon Sep 17 00:00:00 2001 From: Tim Swast Date: Tue, 11 Oct 2016 12:43:26 -0700 Subject: [PATCH 20/45] samples: Fix monitoring tests. Look for a type instead of description, since that should be less likely to change. --- samples/snippets/src/test/java/ListResourcesTest.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/samples/snippets/src/test/java/ListResourcesTest.java b/samples/snippets/src/test/java/ListResourcesTest.java index e8415d76..46ecfd33 100644 --- a/samples/snippets/src/test/java/ListResourcesTest.java +++ b/samples/snippets/src/test/java/ListResourcesTest.java @@ -67,7 +67,6 @@ public void testListMonitoredResourceDescriptors() throws Exception { this.underTest.listMonitoredResourceDescriptors(); String result = new String(os.toByteArray()); assertThat(result) - .named("output text stream") .contains("An application running in Google App Engine"); } @@ -80,8 +79,7 @@ public void testListMetrics() throws Exception { this.underTest.listMetricDescriptors(); String result = new String(os.toByteArray()); assertThat(result) - .named("output text stream") - .contains("Delta CPU usage time. Units are second"); + .contains("agent.googleapis.com/cpu/usage_time"); } /** @@ -93,7 +91,6 @@ public void testListTimeseries() throws Exception { this.underTest.listTimeseries(); String result = new String(os.toByteArray()); assertThat(result) - .named("output text stream") .contains("listTimeseries response"); } } From f033ef30d7f4c707c3905fe9ed2df69e70ef287b Mon Sep 17 00:00:00 2001 From: Bill Prin Date: Thu, 12 Jan 2017 13:58:43 -0800 Subject: [PATCH 21/45] samples: Add region tags for writing timeseries --- samples/snippets/src/main/java/CreateCustomMetric.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/samples/snippets/src/main/java/CreateCustomMetric.java b/samples/snippets/src/main/java/CreateCustomMetric.java index 76225bec..5b0def17 100644 --- a/samples/snippets/src/main/java/CreateCustomMetric.java +++ b/samples/snippets/src/main/java/CreateCustomMetric.java @@ -229,6 +229,7 @@ public MetricDescriptor getCustomMetric() throws IOException { * * @throws IOException On network error. */ + // [START write_timeseries] void writeCustomMetricTimeseriesValue() throws IOException { Map metricLabel = ImmutableMap.of( "environment", "STAGING" @@ -264,6 +265,7 @@ void writeCustomMetricTimeseriesValue() throws IOException { 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 From 2a0ebc12be565d380016d3787d40122dcac66fc8 Mon Sep 17 00:00:00 2001 From: Jerjou Cheng Date: Mon, 20 Mar 2017 17:43:42 -0700 Subject: [PATCH 22/45] samples: Infer project from env --- samples/snippets/src/test/java/ListResourcesTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/src/test/java/ListResourcesTest.java b/samples/snippets/src/test/java/ListResourcesTest.java index 46ecfd33..7a03548b 100644 --- a/samples/snippets/src/test/java/ListResourcesTest.java +++ b/samples/snippets/src/test/java/ListResourcesTest.java @@ -37,7 +37,7 @@ public class ListResourcesTest { /** * The project ID of the project created for the integration tests. */ - public static final String TEST_PROJECT_ID = "cloud-samples-tests"; + public static final String TEST_PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); /** * Google Cloud Monitoring client to integration test. From 755f8be6ac5a0584cfa9d03b42dc17698c803da9 Mon Sep 17 00:00:00 2001 From: Jisha Abubaker Date: Wed, 19 Apr 2017 13:04:13 -0700 Subject: [PATCH 23/45] samples: updating license header to remove ARR (#621) --- samples/snippets/src/main/java/CreateCustomMetric.java | 2 +- samples/snippets/src/main/java/ListResources.java | 2 +- samples/snippets/src/test/java/CreateCustomMetricTest.java | 2 +- samples/snippets/src/test/java/ListResourcesTest.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/snippets/src/main/java/CreateCustomMetric.java b/samples/snippets/src/main/java/CreateCustomMetric.java index 5b0def17..fa7dfd2b 100644 --- a/samples/snippets/src/main/java/CreateCustomMetric.java +++ b/samples/snippets/src/main/java/CreateCustomMetric.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 Google Inc. All Rights Reserved. + * 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. diff --git a/samples/snippets/src/main/java/ListResources.java b/samples/snippets/src/main/java/ListResources.java index 859e635f..818b95a9 100644 --- a/samples/snippets/src/main/java/ListResources.java +++ b/samples/snippets/src/main/java/ListResources.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 Google Inc. All Rights Reserved. + * 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. diff --git a/samples/snippets/src/test/java/CreateCustomMetricTest.java b/samples/snippets/src/test/java/CreateCustomMetricTest.java index 301d08ed..26dc57e5 100644 --- a/samples/snippets/src/test/java/CreateCustomMetricTest.java +++ b/samples/snippets/src/test/java/CreateCustomMetricTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 Google Inc. All Rights Reserved. + * 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. diff --git a/samples/snippets/src/test/java/ListResourcesTest.java b/samples/snippets/src/test/java/ListResourcesTest.java index 7a03548b..211dbd80 100644 --- a/samples/snippets/src/test/java/ListResourcesTest.java +++ b/samples/snippets/src/test/java/ListResourcesTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 Google Inc. All Rights Reserved. + * 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. From e59244258a3b61498cb697e751f439a4a41deb7f Mon Sep 17 00:00:00 2001 From: Jisha Abubaker Date: Thu, 31 Aug 2017 13:21:38 -0700 Subject: [PATCH 24/45] samples: Deleting monitoring apiary samples (#835) --- .../src/main/java/CreateCustomMetric.java | 328 ------------------ .../snippets/src/main/java/ListResources.java | 210 ----------- .../src/test/java/CreateCustomMetricTest.java | 78 ----- .../src/test/java/ListResourcesTest.java | 96 ----- 4 files changed, 712 deletions(-) delete mode 100644 samples/snippets/src/main/java/CreateCustomMetric.java delete mode 100644 samples/snippets/src/main/java/ListResources.java delete mode 100644 samples/snippets/src/test/java/CreateCustomMetricTest.java delete mode 100644 samples/snippets/src/test/java/ListResourcesTest.java diff --git a/samples/snippets/src/main/java/CreateCustomMetric.java b/samples/snippets/src/main/java/CreateCustomMetric.java deleted file mode 100644 index fa7dfd2b..00000000 --- a/samples/snippets/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/samples/snippets/src/main/java/ListResources.java b/samples/snippets/src/main/java/ListResources.java deleted file mode 100644 index 818b95a9..00000000 --- a/samples/snippets/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/samples/snippets/src/test/java/CreateCustomMetricTest.java b/samples/snippets/src/test/java/CreateCustomMetricTest.java deleted file mode 100644 index 26dc57e5..00000000 --- a/samples/snippets/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/samples/snippets/src/test/java/ListResourcesTest.java b/samples/snippets/src/test/java/ListResourcesTest.java deleted file mode 100644 index 211dbd80..00000000 --- a/samples/snippets/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"); - } -} From d2fafd7de1e39a5d485ac0d24eee2c63925af4ec Mon Sep 17 00:00:00 2001 From: Dane Zeke Liergaard Date: Mon, 26 Mar 2018 09:34:03 -0700 Subject: [PATCH 25/45] samples: Creating sample for StackDriver Alerts. (#1063) --- .../snippets/src/main/java/AlertSample.java | 500 ++++++++++++++++++ 1 file changed, 500 insertions(+) create mode 100644 samples/snippets/src/main/java/AlertSample.java diff --git a/samples/snippets/src/main/java/AlertSample.java b/samples/snippets/src/main/java/AlertSample.java new file mode 100644 index 00000000..9a9323d2 --- /dev/null +++ b/samples/snippets/src/main/java/AlertSample.java @@ -0,0 +1,500 @@ +/* + * Copyright 2018 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.base.Preconditions.checkNotNull; + +import com.google.cloud.monitoring.v3.AlertPolicyServiceClient; +import com.google.cloud.monitoring.v3.AlertPolicyServiceClient.ListAlertPoliciesPagedResponse; +import com.google.cloud.monitoring.v3.NotificationChannelServiceClient; +import com.google.cloud.monitoring.v3.NotificationChannelServiceClient.ListNotificationChannelsPagedResponse; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSyntaxException; +import com.google.monitoring.v3.AlertPolicy; +import com.google.monitoring.v3.AlertPolicyName; +import com.google.monitoring.v3.ListAlertPoliciesRequest; +import com.google.monitoring.v3.NotificationChannel; +import com.google.monitoring.v3.NotificationChannelName; +import com.google.monitoring.v3.ProjectName; +import com.google.protobuf.BoolValue; +import com.google.protobuf.FieldMask; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintStream; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; + +public class AlertSample { + + private static final Option PROJECT_ID_OPTION = Option.builder("p") + .longOpt("projectid") + .desc("Your Google project id.") + .hasArg() + .argName("PROJECT_ID") + .build(); + private static final Option FILE_PATH_OPTION = Option.builder("j") + .longOpt("jsonPath") + .desc("Path to json file where alert polices are saved and restored.") + .hasArg() + .argName("JSON_PATH") + .build(); + private static final Option ALERT_ID_OPTION = Option.builder("a") + .required() + .longOpt("alert-id") + .desc("The id of the alert policy whose channels will be replaced.") + .hasArg() + .argName("ALERT_ID") + .build(); + private static final Option CHANNEL_ID_OPTION = Option.builder("c") + .longOpt("channel-id") + .desc("A channel id. Repeat this option to set multiple channel ids.") + .hasArg() + .argName("CHANNEL_ID") + .build(); + private static final Option FILTER_OPTION = Option.builder("d") + .longOpt("filter") + .desc("See https://cloud.google.com/monitoring/api/v3/filters.") + .hasArg() + .argName("FILTER") + .build(); + + private static final Options BASE_OPTIONS = new Options() + .addOption(PROJECT_ID_OPTION); + private static final Options BACKUP_OPTIONS = new Options() + .addOption(PROJECT_ID_OPTION) + .addOption(FILE_PATH_OPTION); + private static final Options REPLACE_CHANNELS_OPTIONS = new Options() + .addOption(PROJECT_ID_OPTION) + .addOption(ALERT_ID_OPTION) + .addOption(CHANNEL_ID_OPTION); + private static final Options ENABLE_OPTIONS = new Options() + .addOption(PROJECT_ID_OPTION) + .addOption(FILTER_OPTION); + + private static Map COMMAND_OPTIONS = ImmutableMap.of( + "backup", BACKUP_OPTIONS, + "restore", BACKUP_OPTIONS, + "replace-channels", REPLACE_CHANNELS_OPTIONS, + "enable", ENABLE_OPTIONS + ); + + private static final CommandLineParser PARSER = new DefaultParser(); + + private static final FieldMask NOTIFICATION_CHANNEL_UPDATE_MASK = FieldMask + .newBuilder() + .addPaths("type") + .addPaths("name") + .addPaths("displayName") + .addPaths("description") + .addPaths("labels") + .addPaths("userLabels") + .build(); + + private AlertPolicyServiceClient alertPolicyClient; + private NotificationChannelServiceClient notificationChannelClient; + private PrintStream outputStream; + private Gson gson = new Gson(); + + private AlertSample() throws IOException { + this(AlertPolicyServiceClient.create(), NotificationChannelServiceClient.create(), System.out); + } + + AlertSample(AlertPolicyServiceClient alertPolicyClient, + NotificationChannelServiceClient notificationChannelClient, + PrintStream os) { + this.alertPolicyClient = checkNotNull(alertPolicyClient); + this.notificationChannelClient = notificationChannelClient; + outputStream = checkNotNull(os); + } + + public static void main(String[] args) throws IOException { + AlertSample sample = createAlertSample(); + + if (args.length == 0) { + usage(System.out, null); + return; + } + String command = args[0]; + Options expectedOptions = COMMAND_OPTIONS.getOrDefault(command, BASE_OPTIONS); + + CommandLine cl = parseCommandLine(args, expectedOptions); + + String projectId = cl.hasOption(PROJECT_ID_OPTION.getOpt()) + ? cl.getOptionValue(PROJECT_ID_OPTION.getOpt()) + : System.getenv("GOOGLE_PROJECT_ID"); + + if (Strings.isNullOrEmpty(projectId)) { + projectId = System.getenv("DEVSHELL_PROJECT_ID"); + } + + if (Strings.isNullOrEmpty(projectId)) { + usage(sample.outputStream, + "Error: --project-id arg required unless provided by the GOOGLE_PROJECT_ID " + + "or DEVSHELL_PROJECT_ID environment variables."); + return; + } + + switch (command) { + case "list": + sample.listAlertPolicies(projectId); + break; + case "backup": + sample.backupPolicies(projectId, + cl.getOptionValue(FILE_PATH_OPTION.getOpt())); + break; + case "restore": + sample.restorePolicies(projectId, + cl.getOptionValue(FILE_PATH_OPTION.getOpt())); + break; + case "replace-channels": + sample.replaceChannels(projectId, + cl.getOptionValue(ALERT_ID_OPTION.getOpt()), + cl.getOptionValues(CHANNEL_ID_OPTION.getOpt())); + break; + case "enable": + sample.enablePolicies(projectId, + cl.getOptionValue(FILTER_OPTION.getOpt()), true); + break; + case "disable": + sample.enablePolicies(projectId, + cl.getOptionValue(FILTER_OPTION.getOpt()), false); + break; + default: + usage(sample.outputStream, null); + } + } + + private static CommandLine parseCommandLine(String[] args, Options expectedOptions) { + CommandLine cl; + try { + cl = PARSER.parse(expectedOptions, args); + } catch (ParseException pe) { + usage(System.out, "Exception parsing command line arguments."); + throw new RuntimeException("Exception parsing command line arguments.", pe); + } + return cl; + } + + private static AlertSample createAlertSample() throws IOException { + AlertSample sample; + try { + sample = new AlertSample(); + } catch (Exception e) { + usage(System.out, "Exception creating alert sample."); + throw e; + } + return sample; + } + + // [START monitoring_alert_list_policies] + void listAlertPolicies(String projectId) { + ListAlertPoliciesPagedResponse response = alertPolicyClient.listAlertPolicies(ProjectName.of( + projectId)); + + for (AlertPolicy policy : response.iterateAll()) { + outputStream.println(policy.getDisplayName()); + if (policy.hasDocumentation() && policy.getDocumentation().getContent() != null) { + outputStream.println(policy.getDocumentation().getContent()); + } + } + } + // [END monitoring_alert_list_policies] + + // [START monitoring_alert_backup_policies] + void backupPolicies(String projectId, String filePath) throws IOException { + List alertPolicies = getAlertPolicies(projectId); + List notificationChannels = getNotificationChannels(projectId); + writePoliciesBackupFile(projectId, filePath, alertPolicies, notificationChannels); + outputStream.println(String.format("Saved policies to %s", filePath)); + } + + private List getAlertPolicies(String projectId) { + List alertPolicies = Lists.newArrayList(); + ListAlertPoliciesPagedResponse response = + alertPolicyClient.listAlertPolicies(ProjectName.of(projectId)); + + for (AlertPolicy policy : response.iterateAll()) { + alertPolicies.add(policy); + } + return alertPolicies; + } + + private List getNotificationChannels(String projectId) { + List notificationChannels = Lists.newArrayList(); + ListNotificationChannelsPagedResponse listNotificationChannelsResponse = + notificationChannelClient.listNotificationChannels(ProjectName.of(projectId)); + for (NotificationChannel channel : listNotificationChannelsResponse.iterateAll()) { + notificationChannels.add(channel); + } + return notificationChannels; + } + + private void writePoliciesBackupFile(String projectId, + String filePath, + List alertPolicies, + List notificationChannels) + throws IOException { + JsonObject backupContents = new JsonObject(); + backupContents.add("project_id", new JsonPrimitive(projectId)); + JsonArray policiesJson = new JsonArray(); + for (AlertPolicy policy : alertPolicies) { + policiesJson.add(gson.toJsonTree(policy)); + } + backupContents.add("policies", policiesJson); + + JsonArray notificationsJson = new JsonArray(); + for (NotificationChannel channel : notificationChannels) { + notificationsJson.add(gson.toJsonTree(channel)); + } + backupContents.add("notification_channels", notificationsJson); + + FileWriter writer = new FileWriter(filePath); + writer.write(backupContents.toString()); + writer.close(); + } + // [END monitoring_alert_backup_policies] + + // [START monitoring_alert_restore_policies] + void restorePolicies(String projectId, String filePath) throws IOException { + FileReader reader = new FileReader(filePath); + BufferedReader bufferedReader = new BufferedReader(reader); + + JsonObject backupContent = getPolicyJsonContents(filePath, bufferedReader, gson); + String backupProjectId = backupContent.get("project_id").getAsString(); + boolean isSameProject = projectId.equals(backupProjectId); + + AlertPolicy[] policies = gson.fromJson(backupContent.get("policies"), AlertPolicy[].class); + List notificationChannels = readNotificationChannelsJson(backupContent); + Map restoredChannelIds = restoreNotificationChannels(projectId, + notificationChannels, + isSameProject); + List policiesToRestore = reviseRestoredPolicies(policies, + isSameProject, + restoredChannelIds); + + restoreRevisedPolicies(projectId, isSameProject, policiesToRestore); + } + + private List reviseRestoredPolicies(AlertPolicy[] policies, + boolean isSameProject, + Map restoredChannelIds) { + List newPolicies = Lists.newArrayListWithCapacity(policies.length); + for (AlertPolicy policy : policies) { + AlertPolicy.Builder policyBuilder = policy + .toBuilder() + .clearNotificationChannels() + .clearMutationRecord() + .clearCreationRecord(); + // Update restored notification channel names. + for (String channelName : policy.getNotificationChannelsList()) { + String newChannelName = restoredChannelIds.get(channelName); + if (!Strings.isNullOrEmpty(newChannelName)) { + policyBuilder.addNotificationChannels(newChannelName); + } + } + if (!isSameProject) { + policyBuilder.clearName(); + policyBuilder.clearConditions(); + for (AlertPolicy.Condition condition : policy.getConditionsList()) { + policyBuilder.addConditions(condition.toBuilder().clearName()); + } + } + newPolicies.add(policyBuilder.build()); + } + return newPolicies; + } + + private void restoreRevisedPolicies(String projectId, + boolean isSameProject, + List policies) { + for (AlertPolicy policy : policies) { + if (!isSameProject) { + policy = alertPolicyClient.createAlertPolicy(ProjectName.of(projectId), policy); + } else { + try { + alertPolicyClient.updateAlertPolicy(null, policy); + } catch (Exception e) { + policy = alertPolicyClient.createAlertPolicy(ProjectName.of(projectId), + policy.toBuilder().clearName().build()); + } + } + outputStream.println(String.format("Restored %s", policy.getName())); + } + } + + private List readNotificationChannelsJson(JsonObject backupContent) { + if (backupContent.has("notification_channels")) { + NotificationChannel[] channels = gson.fromJson(backupContent.get("notification_channels"), + NotificationChannel[].class); + return Lists.newArrayList(channels); + } + return Lists.newArrayList(); + } + + private Map restoreNotificationChannels(String projectId, + List channels, + boolean isSameProject) { + Map newChannelNames = Maps.newHashMap(); + for (NotificationChannel channel : channels) { + // Update channel name if project ID is different. + boolean channelUpdated = false; + if (isSameProject) { + try { + NotificationChannel updatedChannel = notificationChannelClient.updateNotificationChannel( + NOTIFICATION_CHANNEL_UPDATE_MASK, + channel); + newChannelNames.put(channel.getName(), updatedChannel.getName()); + channelUpdated = true; + } catch (Exception e) { + channelUpdated = false; + } + } + if (!channelUpdated) { + NotificationChannel newChannel = notificationChannelClient.createNotificationChannel( + ProjectName.of(projectId), + channel + .toBuilder() + .clearName() + .clearVerificationStatus() + .build()); + newChannelNames.put(channel.getName(), newChannel.getName()); + } + } + return newChannelNames; + } + + private JsonObject getPolicyJsonContents(String filePath, BufferedReader content, Gson gson) { + try { + return gson.fromJson(content, JsonObject.class); + } catch (JsonSyntaxException jse) { + throw new RuntimeException(String.format("Could not parse policies file %s", filePath), jse); + } + } + // [END monitoring_alert_restore_policies] + + // [START monitoring_alert_replace_channels] + void replaceChannels(String projectId, String alertPolicyId, String[] channelIds) { + AlertPolicy.Builder policyBuilder = AlertPolicy + .newBuilder() + .setName(AlertPolicyName.of(projectId, alertPolicyId).toString()); + for (String channelId : channelIds) { + policyBuilder.addNotificationChannels( + NotificationChannelName.of(projectId, channelId).toString()); + } + AlertPolicy result = alertPolicyClient.updateAlertPolicy( + FieldMask.newBuilder().addPaths("notification_channels").build(), policyBuilder.build()); + outputStream.println(String.format("Updated %s", result.getName())); + } + // [END monitoring_alert_replace_channels] + + // [START monitoring_alert_enable_policies] + // [START monitoring_alert_disable_policies] + void enablePolicies(String projectId, + String filter, + boolean enable) { + ListAlertPoliciesPagedResponse response = alertPolicyClient + .listAlertPolicies(ListAlertPoliciesRequest.newBuilder() + .setName(projectId) + .setFilter(filter) + .build()); + + for (AlertPolicy policy : response.iterateAll()) { + if (policy.getEnabled().getValue() == enable) { + outputStream.println(String.format("Policy %s is already %b.", policy.getName(), enable)); + continue; + } + AlertPolicy updatedPolicy = AlertPolicy + .newBuilder() + .setName(AlertPolicyName.of(projectId, policy.getName()).toString()) + .setEnabled(BoolValue.newBuilder().setValue(enable)) + .build(); + AlertPolicy result = alertPolicyClient.updateAlertPolicy( + FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy); + outputStream.println(String.format( + "%s %s", result.getName(), result.getEnabled().getValue() ? "Enabled" : "Disabled")); + } + + } + // [END monitoring_alert_enable_policies] + // [END monitoring_alert_disable_policies] + + private static void usage(PrintStream ps) { + usage(ps, null); + } + + private static void usage(PrintStream ps, String message) { + Optional.ofNullable(message).ifPresent(ps::println); + ps.println("Usage:"); + ps.printf( + "\tjava %s \"\" \"\"\n" + + "Args:\n" + + "\t%s\n" + + "Commands:\n" + + "\tlist:\t\t\t\tList existing alert policies for project.\n" + + "\tbackup:\t\t\t\tBackup existing alert policies & notification channels to a file.\n" + + "\t\t\t\t\t\t\tArgs:\n" + + "\t\t\t\t\t\t\t\t%s\n" + + "\t\t\t\t\t\t\t\t%s\n" + + "\trestore:\t\t\tRestore alerts and notification channels from a backed-up file.\n" + + "\t\t\t\t\t\t\tArgs:\n" + + "\t\t\t\t\t\t\t\t%s\n" + + "\t\t\t\t\t\t\t\t%s\n" + + "\treplace-channels:\tReplace the notification channels for an alert.\n" + + "\t\t\t\t\t\t\tArgs:\n" + + "\t\t\t\t\t\t\t\t%s\n" + + "\t\t\t\t\t\t\t\t%s\n" + + "\tenable:\t\t\t\tEnable alert policies in project.\n" + + "\t\t\t\t\t\t\tArgs:\n" + + "\t\t\t\t\t\t\t\t%s\n" + + "\tdisable:\t\t\tDisable alert policies in project.\n" + + "\t\t\t\t\t\t\tArgs:\n" + + "\t\t\t\t\t\t\t\t%s\n", + AlertSample.class.getCanonicalName(), + formatArgString(PROJECT_ID_OPTION), + formatArgString(FILE_PATH_OPTION), + formatArgString(CHANNEL_ID_OPTION), + formatArgString(FILE_PATH_OPTION), + formatArgString(CHANNEL_ID_OPTION), + formatArgString(ALERT_ID_OPTION), + formatArgString(CHANNEL_ID_OPTION), + formatArgString(FILTER_OPTION), + formatArgString(FILTER_OPTION)); + } + + private static String formatArgString(Option option) { + return String.format("--%s (%s):\t%s", + option.getLongOpt(), + option.getOpt(), + option.getDescription()); + } +} From 100387903f0592d58abd483838789dc28c12cf39 Mon Sep 17 00:00:00 2001 From: mtabasko <34554386+mtabasko@users.noreply.github.com> Date: Wed, 11 Apr 2018 17:54:14 -0400 Subject: [PATCH 26/45] samples: Adds region tags to Java alerting sample (#1087) Adds region tags to AlertSample.java, for extraction of doc samples without resorting to regexps. --- samples/snippets/src/main/java/AlertSample.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/samples/snippets/src/main/java/AlertSample.java b/samples/snippets/src/main/java/AlertSample.java index 9a9323d2..d5bacbe9 100644 --- a/samples/snippets/src/main/java/AlertSample.java +++ b/samples/snippets/src/main/java/AlertSample.java @@ -249,6 +249,7 @@ private List getAlertPolicies(String projectId) { return alertPolicies; } + // [START monitoring_alert_list_channels] private List getNotificationChannels(String projectId) { List notificationChannels = Lists.newArrayList(); ListNotificationChannelsPagedResponse listNotificationChannelsResponse = @@ -258,6 +259,7 @@ private List getNotificationChannels(String projectId) { } return notificationChannels; } + // [END monitoring_alert_list_channels] private void writePoliciesBackupFile(String projectId, String filePath, @@ -334,6 +336,7 @@ private List reviseRestoredPolicies(AlertPolicy[] policies, return newPolicies; } + // [START monitoring_alert_create_policy] private void restoreRevisedPolicies(String projectId, boolean isSameProject, List policies) { @@ -351,6 +354,7 @@ private void restoreRevisedPolicies(String projectId, outputStream.println(String.format("Restored %s", policy.getName())); } } + // [END monitoring_alert_create_policy] private List readNotificationChannelsJson(JsonObject backupContent) { if (backupContent.has("notification_channels")) { @@ -361,6 +365,8 @@ private List readNotificationChannelsJson(JsonObject backup return Lists.newArrayList(); } + // [START monitoring_alert_create_channel] + // [START monitoring_alert_update_channel] private Map restoreNotificationChannels(String projectId, List channels, boolean isSameProject) { @@ -392,7 +398,9 @@ private Map restoreNotificationChannels(String projectId, } return newChannelNames; } - + // [END monitoring_alert_create_channel] + // [END monitoring_alert_update_channel] + private JsonObject getPolicyJsonContents(String filePath, BufferedReader content, Gson gson) { try { return gson.fromJson(content, JsonObject.class); From 84b5b5eb6c788c5269600485f266527bddb26a81 Mon Sep 17 00:00:00 2001 From: Dane Zeke Liergaard Date: Wed, 6 Jun 2018 13:31:52 -0700 Subject: [PATCH 27/45] samples: Add stackdriver alert v3 integration tests. (#1119) --- .../snippets/src/main/java/AlertSample.java | 72 ++++++------ samples/snippets/src/test/java/AlertIT.java | 107 ++++++++++++++++++ 2 files changed, 145 insertions(+), 34 deletions(-) create mode 100644 samples/snippets/src/test/java/AlertIT.java diff --git a/samples/snippets/src/main/java/AlertSample.java b/samples/snippets/src/main/java/AlertSample.java index d5bacbe9..e0167469 100644 --- a/samples/snippets/src/main/java/AlertSample.java +++ b/samples/snippets/src/main/java/AlertSample.java @@ -42,7 +42,6 @@ import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; -import java.io.PrintStream; import java.util.List; import java.util.Map; import java.util.Optional; @@ -105,7 +104,8 @@ public class AlertSample { "backup", BACKUP_OPTIONS, "restore", BACKUP_OPTIONS, "replace-channels", REPLACE_CHANNELS_OPTIONS, - "enable", ENABLE_OPTIONS + "enable", ENABLE_OPTIONS, + "disable", ENABLE_OPTIONS ); private static final CommandLineParser PARSER = new DefaultParser(); @@ -122,26 +122,23 @@ public class AlertSample { private AlertPolicyServiceClient alertPolicyClient; private NotificationChannelServiceClient notificationChannelClient; - private PrintStream outputStream; private Gson gson = new Gson(); private AlertSample() throws IOException { - this(AlertPolicyServiceClient.create(), NotificationChannelServiceClient.create(), System.out); + this(AlertPolicyServiceClient.create(), NotificationChannelServiceClient.create()); } AlertSample(AlertPolicyServiceClient alertPolicyClient, - NotificationChannelServiceClient notificationChannelClient, - PrintStream os) { + NotificationChannelServiceClient notificationChannelClient) { this.alertPolicyClient = checkNotNull(alertPolicyClient); this.notificationChannelClient = notificationChannelClient; - outputStream = checkNotNull(os); } public static void main(String[] args) throws IOException { AlertSample sample = createAlertSample(); if (args.length == 0) { - usage(System.out, null); + usage(null); return; } String command = args[0]; @@ -151,16 +148,15 @@ public static void main(String[] args) throws IOException { String projectId = cl.hasOption(PROJECT_ID_OPTION.getOpt()) ? cl.getOptionValue(PROJECT_ID_OPTION.getOpt()) - : System.getenv("GOOGLE_PROJECT_ID"); + : System.getenv("GOOGLE_CLOUD_PROJECT"); if (Strings.isNullOrEmpty(projectId)) { projectId = System.getenv("DEVSHELL_PROJECT_ID"); } if (Strings.isNullOrEmpty(projectId)) { - usage(sample.outputStream, - "Error: --project-id arg required unless provided by the GOOGLE_PROJECT_ID " - + "or DEVSHELL_PROJECT_ID environment variables."); + usage("Error: --project-id arg required unless provided by the GOOGLE_CLOUD_PROJECT " + + "or DEVSHELL_PROJECT_ID environment variables."); return; } @@ -190,7 +186,7 @@ public static void main(String[] args) throws IOException { cl.getOptionValue(FILTER_OPTION.getOpt()), false); break; default: - usage(sample.outputStream, null); + usage(null); } } @@ -199,7 +195,7 @@ private static CommandLine parseCommandLine(String[] args, Options expectedOptio try { cl = PARSER.parse(expectedOptions, args); } catch (ParseException pe) { - usage(System.out, "Exception parsing command line arguments."); + usage("Exception parsing command line arguments."); throw new RuntimeException("Exception parsing command line arguments.", pe); } return cl; @@ -210,7 +206,7 @@ private static AlertSample createAlertSample() throws IOException { try { sample = new AlertSample(); } catch (Exception e) { - usage(System.out, "Exception creating alert sample."); + usage("Exception creating alert sample."); throw e; } return sample; @@ -221,10 +217,19 @@ void listAlertPolicies(String projectId) { ListAlertPoliciesPagedResponse response = alertPolicyClient.listAlertPolicies(ProjectName.of( projectId)); + System.out.println("Alert Policies:"); for (AlertPolicy policy : response.iterateAll()) { - outputStream.println(policy.getDisplayName()); + System.out.println( + String.format("\nPolicy %s\nalert-id: %s", policy.getDisplayName(), policy.getName())); + int channels = policy.getNotificationChannelsCount(); + if (channels > 0) { + System.out.println("notification-channels:"); + for (int i = 0; i < channels; i++) { + System.out.println("\t" + policy.getNotificationChannels(i)); + } + } if (policy.hasDocumentation() && policy.getDocumentation().getContent() != null) { - outputStream.println(policy.getDocumentation().getContent()); + System.out.println(policy.getDocumentation().getContent()); } } } @@ -235,7 +240,7 @@ void backupPolicies(String projectId, String filePath) throws IOException { List alertPolicies = getAlertPolicies(projectId); List notificationChannels = getNotificationChannels(projectId); writePoliciesBackupFile(projectId, filePath, alertPolicies, notificationChannels); - outputStream.println(String.format("Saved policies to %s", filePath)); + System.out.println(String.format("Saved policies to %s", filePath)); } private List getAlertPolicies(String projectId) { @@ -351,7 +356,7 @@ private void restoreRevisedPolicies(String projectId, policy.toBuilder().clearName().build()); } } - outputStream.println(String.format("Restored %s", policy.getName())); + System.out.println(String.format("Restored %s", policy.getName())); } } // [END monitoring_alert_create_policy] @@ -400,7 +405,7 @@ private Map restoreNotificationChannels(String projectId, } // [END monitoring_alert_create_channel] // [END monitoring_alert_update_channel] - + private JsonObject getPolicyJsonContents(String filePath, BufferedReader content, Gson gson) { try { return gson.fromJson(content, JsonObject.class); @@ -421,7 +426,7 @@ void replaceChannels(String projectId, String alertPolicyId, String[] channelIds } AlertPolicy result = alertPolicyClient.updateAlertPolicy( FieldMask.newBuilder().addPaths("notification_channels").build(), policyBuilder.build()); - outputStream.println(String.format("Updated %s", result.getName())); + System.out.println(String.format("Updated %s", result.getName())); } // [END monitoring_alert_replace_channels] @@ -432,38 +437,37 @@ void enablePolicies(String projectId, boolean enable) { ListAlertPoliciesPagedResponse response = alertPolicyClient .listAlertPolicies(ListAlertPoliciesRequest.newBuilder() - .setName(projectId) + .setName(ProjectName.of(projectId).toString()) .setFilter(filter) .build()); for (AlertPolicy policy : response.iterateAll()) { if (policy.getEnabled().getValue() == enable) { - outputStream.println(String.format("Policy %s is already %b.", policy.getName(), enable)); + System.out.println(String.format( + "Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled")); continue; } AlertPolicy updatedPolicy = AlertPolicy .newBuilder() - .setName(AlertPolicyName.of(projectId, policy.getName()).toString()) + .setName(policy.getName()) .setEnabled(BoolValue.newBuilder().setValue(enable)) .build(); AlertPolicy result = alertPolicyClient.updateAlertPolicy( FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy); - outputStream.println(String.format( - "%s %s", result.getName(), result.getEnabled().getValue() ? "Enabled" : "Disabled")); + System.out.println(String.format( + "%s %s", + result.getDisplayName(), + result.getEnabled().getValue() ? "enabled" : "disabled")); } } // [END monitoring_alert_enable_policies] // [END monitoring_alert_disable_policies] - private static void usage(PrintStream ps) { - usage(ps, null); - } - - private static void usage(PrintStream ps, String message) { - Optional.ofNullable(message).ifPresent(ps::println); - ps.println("Usage:"); - ps.printf( + private static void usage(String message) { + Optional.ofNullable(message).ifPresent(System.out::println); + System.out.println("Usage:"); + System.out.printf( "\tjava %s \"\" \"\"\n" + "Args:\n" + "\t%s\n" diff --git a/samples/snippets/src/test/java/AlertIT.java b/samples/snippets/src/test/java/AlertIT.java new file mode 100644 index 00000000..d98eb61e --- /dev/null +++ b/samples/snippets/src/test/java/AlertIT.java @@ -0,0 +1,107 @@ +/* + * Copyright 2018 Google LLC + * + * 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 org.junit.Assert.assertTrue; + +import com.google.common.base.Strings; +import com.google.common.io.Files; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for monitoring "AlertSample" sample. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class AlertIT { + private static String testPolicyName = "test-policy"; + private static String policyFileName = "target/policyBackup.json"; + private static Pattern policyNameRegex = Pattern.compile( + "alertPolicies/(?.*)(?s).*(?!s)notificationChannels/(?[a-zA-Z0-9]*)$"); + private ByteArrayOutputStream bout; + private PrintStream out; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testListPolicies() throws IOException { + AlertSample.main(new String[]{"list"}); + assertTrue(bout.toString().contains(testPolicyName)); + } + + @Test + public void testBackupPolicies() throws IOException { + AlertSample.main(new String[]{"backup", "-j", policyFileName}); + File backupFile = new File(policyFileName); + assertTrue(backupFile.exists()); + String fileContents = + String.join("\n", Files.readLines(backupFile, StandardCharsets.UTF_8)); + assertTrue(fileContents.contains("test-policy")); + } + + // TODO(b/78293034): Complete restore backup test when parse/unparse issue is figured out. + @Test + @Ignore + public void testRestoreBackup() throws IOException { + } + + @Test + public void testReplaceChannels() throws IOException { + // Get a test policy name for the project. + AlertSample.main(new String[]{"list"}); + Matcher matcher = policyNameRegex.matcher(bout.toString()); + assertTrue(matcher.find()); + String alertId = matcher.group("alertid"); + String channel = matcher.group("channel"); + Assert.assertFalse(Strings.isNullOrEmpty(alertId)); + AlertSample.main(new String[]{"replace-channels", "-a", alertId, "-c", channel}); + Pattern resultPattern = Pattern.compile("(?s).*Updated .*/alertPolicies/" + alertId); + assertTrue(resultPattern.matcher(bout.toString()).find()); + } + + @Test + public void testDisableEnablePolicies() throws IOException { + AlertSample.main(new String[]{"disable", "-d", "display_name='test-policy'"}); + assertTrue(bout.toString().contains("disabled")); + AlertSample.main(new String[]{"enable", "-d", "display_name='test-policy'"}); + assertTrue(bout.toString().contains("enabled")); + + } +} From f4af8f72b497d039a3b11ed13e8b83f51cb8bf2e Mon Sep 17 00:00:00 2001 From: Dane Zeke Liergaard Date: Thu, 2 Aug 2018 09:36:09 -0700 Subject: [PATCH 28/45] samples: Create monitoring uptime check config samples. (#1169) * Move monitoring Alert samples into com.example directory. * Add monitoring uptime check samples. --- .../java/{ => com/example}/AlertSample.java | 349 ++++++++---------- .../main/java/com/example/UptimeSample.java | 226 ++++++++++++ .../test/java/{ => com/example}/AlertIT.java | 2 + .../src/test/java/com/example/UptimeIT.java | 98 +++++ 4 files changed, 485 insertions(+), 190 deletions(-) rename samples/snippets/src/main/java/{ => com/example}/AlertSample.java (55%) create mode 100644 samples/snippets/src/main/java/com/example/UptimeSample.java rename samples/snippets/src/test/java/{ => com/example}/AlertIT.java (99%) create mode 100644 samples/snippets/src/test/java/com/example/UptimeIT.java diff --git a/samples/snippets/src/main/java/AlertSample.java b/samples/snippets/src/main/java/com/example/AlertSample.java similarity index 55% rename from samples/snippets/src/main/java/AlertSample.java rename to samples/snippets/src/main/java/com/example/AlertSample.java index e0167469..163903a4 100644 --- a/samples/snippets/src/main/java/AlertSample.java +++ b/samples/snippets/src/main/java/com/example/AlertSample.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 Google Inc. + * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ * limitations under the License. */ -import static com.google.common.base.Preconditions.checkNotNull; +package com.example; import com.google.cloud.monitoring.v3.AlertPolicyServiceClient; import com.google.cloud.monitoring.v3.AlertPolicyServiceClient.ListAlertPoliciesPagedResponse; @@ -49,6 +49,7 @@ import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; @@ -120,23 +121,9 @@ public class AlertSample { .addPaths("userLabels") .build(); - private AlertPolicyServiceClient alertPolicyClient; - private NotificationChannelServiceClient notificationChannelClient; - private Gson gson = new Gson(); - - private AlertSample() throws IOException { - this(AlertPolicyServiceClient.create(), NotificationChannelServiceClient.create()); - } - - AlertSample(AlertPolicyServiceClient alertPolicyClient, - NotificationChannelServiceClient notificationChannelClient) { - this.alertPolicyClient = checkNotNull(alertPolicyClient); - this.notificationChannelClient = notificationChannelClient; - } - - public static void main(String[] args) throws IOException { - AlertSample sample = createAlertSample(); + private static Gson gson = new Gson(); + public static void main(String... args) throws IOException { if (args.length == 0) { usage(null); return; @@ -162,28 +149,25 @@ public static void main(String[] args) throws IOException { switch (command) { case "list": - sample.listAlertPolicies(projectId); + listAlertPolicies(projectId); break; case "backup": - sample.backupPolicies(projectId, - cl.getOptionValue(FILE_PATH_OPTION.getOpt())); + backupPolicies(projectId, cl.getOptionValue(FILE_PATH_OPTION.getOpt())); break; case "restore": - sample.restorePolicies(projectId, - cl.getOptionValue(FILE_PATH_OPTION.getOpt())); + restorePolicies(projectId, cl.getOptionValue(FILE_PATH_OPTION.getOpt())); break; case "replace-channels": - sample.replaceChannels(projectId, + replaceChannels( + projectId, cl.getOptionValue(ALERT_ID_OPTION.getOpt()), cl.getOptionValues(CHANNEL_ID_OPTION.getOpt())); break; case "enable": - sample.enablePolicies(projectId, - cl.getOptionValue(FILTER_OPTION.getOpt()), true); + enablePolicies(projectId, cl.getOptionValue(FILTER_OPTION.getOpt()), true); break; case "disable": - sample.enablePolicies(projectId, - cl.getOptionValue(FILTER_OPTION.getOpt()), false); + enablePolicies(projectId, cl.getOptionValue(FILTER_OPTION.getOpt()), false); break; default: usage(null); @@ -201,76 +185,70 @@ private static CommandLine parseCommandLine(String[] args, Options expectedOptio return cl; } - private static AlertSample createAlertSample() throws IOException { - AlertSample sample; - try { - sample = new AlertSample(); - } catch (Exception e) { - usage("Exception creating alert sample."); - throw e; - } - return sample; - } - // [START monitoring_alert_list_policies] - void listAlertPolicies(String projectId) { - ListAlertPoliciesPagedResponse response = alertPolicyClient.listAlertPolicies(ProjectName.of( - projectId)); - - System.out.println("Alert Policies:"); - for (AlertPolicy policy : response.iterateAll()) { - System.out.println( - String.format("\nPolicy %s\nalert-id: %s", policy.getDisplayName(), policy.getName())); - int channels = policy.getNotificationChannelsCount(); - if (channels > 0) { - System.out.println("notification-channels:"); - for (int i = 0; i < channels; i++) { - System.out.println("\t" + policy.getNotificationChannels(i)); + private static void listAlertPolicies(String projectId) throws IOException { + try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) { + ListAlertPoliciesPagedResponse response = client.listAlertPolicies(ProjectName.of(projectId)); + + System.out.println("Alert Policies:"); + for (AlertPolicy policy : response.iterateAll()) { + System.out.println( + String.format("\nPolicy %s\nalert-id: %s", policy.getDisplayName(), policy.getName())); + int channels = policy.getNotificationChannelsCount(); + if (channels > 0) { + System.out.println("notification-channels:"); + for (int i = 0; i < channels; i++) { + System.out.println("\t" + policy.getNotificationChannels(i)); + } + } + if (policy.hasDocumentation() && policy.getDocumentation().getContent() != null) { + System.out.println(policy.getDocumentation().getContent()); } - } - if (policy.hasDocumentation() && policy.getDocumentation().getContent() != null) { - System.out.println(policy.getDocumentation().getContent()); } } } // [END monitoring_alert_list_policies] // [START monitoring_alert_backup_policies] - void backupPolicies(String projectId, String filePath) throws IOException { + private static void backupPolicies(String projectId, String filePath) throws IOException { List alertPolicies = getAlertPolicies(projectId); List notificationChannels = getNotificationChannels(projectId); writePoliciesBackupFile(projectId, filePath, alertPolicies, notificationChannels); System.out.println(String.format("Saved policies to %s", filePath)); } - private List getAlertPolicies(String projectId) { + private static List getAlertPolicies(String projectId) throws IOException { List alertPolicies = Lists.newArrayList(); - ListAlertPoliciesPagedResponse response = - alertPolicyClient.listAlertPolicies(ProjectName.of(projectId)); + try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) { + ListAlertPoliciesPagedResponse response = client.listAlertPolicies(ProjectName.of(projectId)); - for (AlertPolicy policy : response.iterateAll()) { - alertPolicies.add(policy); + for (AlertPolicy policy : response.iterateAll()) { + alertPolicies.add(policy); + } } return alertPolicies; } // [START monitoring_alert_list_channels] - private List getNotificationChannels(String projectId) { + private static List getNotificationChannels(String projectId) + throws IOException { List notificationChannels = Lists.newArrayList(); - ListNotificationChannelsPagedResponse listNotificationChannelsResponse = - notificationChannelClient.listNotificationChannels(ProjectName.of(projectId)); - for (NotificationChannel channel : listNotificationChannelsResponse.iterateAll()) { - notificationChannels.add(channel); + try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) { + ListNotificationChannelsPagedResponse listNotificationChannelsResponse = + client.listNotificationChannels(ProjectName.of(projectId)); + for (NotificationChannel channel : listNotificationChannelsResponse.iterateAll()) { + notificationChannels.add(channel); + } } return notificationChannels; } // [END monitoring_alert_list_channels] - private void writePoliciesBackupFile(String projectId, - String filePath, - List alertPolicies, - List notificationChannels) - throws IOException { + private static void writePoliciesBackupFile( + String projectId, + String filePath, + List alertPolicies, + List notificationChannels) throws IOException { JsonObject backupContents = new JsonObject(); backupContents.add("project_id", new JsonPrimitive(projectId)); JsonArray policiesJson = new JsonArray(); @@ -292,11 +270,11 @@ private void writePoliciesBackupFile(String projectId, // [END monitoring_alert_backup_policies] // [START monitoring_alert_restore_policies] - void restorePolicies(String projectId, String filePath) throws IOException { + private static void restorePolicies(String projectId, String filePath) throws IOException { FileReader reader = new FileReader(filePath); BufferedReader bufferedReader = new BufferedReader(reader); - JsonObject backupContent = getPolicyJsonContents(filePath, bufferedReader, gson); + JsonObject backupContent = getPolicyJsonContents(filePath, bufferedReader); String backupProjectId = backupContent.get("project_id").getAsString(); boolean isSameProject = projectId.equals(backupProjectId); @@ -305,16 +283,16 @@ void restorePolicies(String projectId, String filePath) throws IOException { Map restoredChannelIds = restoreNotificationChannels(projectId, notificationChannels, isSameProject); - List policiesToRestore = reviseRestoredPolicies(policies, - isSameProject, - restoredChannelIds); + List policiesToRestore = + reviseRestoredPolicies(policies, isSameProject, restoredChannelIds); restoreRevisedPolicies(projectId, isSameProject, policiesToRestore); } - private List reviseRestoredPolicies(AlertPolicy[] policies, - boolean isSameProject, - Map restoredChannelIds) { + private static List reviseRestoredPolicies( + AlertPolicy[] policies, + boolean isSameProject, + Map restoredChannelIds) { List newPolicies = Lists.newArrayListWithCapacity(policies.length); for (AlertPolicy policy : policies) { AlertPolicy.Builder policyBuilder = policy @@ -342,26 +320,30 @@ private List reviseRestoredPolicies(AlertPolicy[] policies, } // [START monitoring_alert_create_policy] - private void restoreRevisedPolicies(String projectId, - boolean isSameProject, - List policies) { - for (AlertPolicy policy : policies) { - if (!isSameProject) { - policy = alertPolicyClient.createAlertPolicy(ProjectName.of(projectId), policy); - } else { - try { - alertPolicyClient.updateAlertPolicy(null, policy); - } catch (Exception e) { - policy = alertPolicyClient.createAlertPolicy(ProjectName.of(projectId), - policy.toBuilder().clearName().build()); + private static void restoreRevisedPolicies( + String projectId, + boolean isSameProject, + List policies) throws IOException { + try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) { + for (AlertPolicy policy : policies) { + if (!isSameProject) { + policy = client.createAlertPolicy(ProjectName.of(projectId), policy); + } else { + try { + client.updateAlertPolicy(null, policy); + } catch (Exception e) { + policy = client.createAlertPolicy( + ProjectName.of(projectId), + policy.toBuilder().clearName().build()); + } } + System.out.println(String.format("Restored %s", policy.getName())); } - System.out.println(String.format("Restored %s", policy.getName())); } } // [END monitoring_alert_create_policy] - private List readNotificationChannelsJson(JsonObject backupContent) { + private static List readNotificationChannelsJson(JsonObject backupContent) { if (backupContent.has("notification_channels")) { NotificationChannel[] channels = gson.fromJson(backupContent.get("notification_channels"), NotificationChannel[].class); @@ -372,33 +354,35 @@ private List readNotificationChannelsJson(JsonObject backup // [START monitoring_alert_create_channel] // [START monitoring_alert_update_channel] - private Map restoreNotificationChannels(String projectId, - List channels, - boolean isSameProject) { + private static Map restoreNotificationChannels( + String projectId, + List channels, + boolean isSameProject) throws IOException { Map newChannelNames = Maps.newHashMap(); - for (NotificationChannel channel : channels) { - // Update channel name if project ID is different. - boolean channelUpdated = false; - if (isSameProject) { - try { - NotificationChannel updatedChannel = notificationChannelClient.updateNotificationChannel( - NOTIFICATION_CHANNEL_UPDATE_MASK, - channel); - newChannelNames.put(channel.getName(), updatedChannel.getName()); - channelUpdated = true; - } catch (Exception e) { - channelUpdated = false; + try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) { + for (NotificationChannel channel : channels) { + // Update channel name if project ID is different. + boolean channelUpdated = false; + if (isSameProject) { + try { + NotificationChannel updatedChannel = + client.updateNotificationChannel(NOTIFICATION_CHANNEL_UPDATE_MASK, channel); + newChannelNames.put(channel.getName(), updatedChannel.getName()); + channelUpdated = true; + } catch (Exception e) { + channelUpdated = false; + } + } + if (!channelUpdated) { + NotificationChannel newChannel = client.createNotificationChannel( + ProjectName.of(projectId), + channel + .toBuilder() + .clearName() + .clearVerificationStatus() + .build()); + newChannelNames.put(channel.getName(), newChannel.getName()); } - } - if (!channelUpdated) { - NotificationChannel newChannel = notificationChannelClient.createNotificationChannel( - ProjectName.of(projectId), - channel - .toBuilder() - .clearName() - .clearVerificationStatus() - .build()); - newChannelNames.put(channel.getName(), newChannel.getName()); } } return newChannelNames; @@ -406,7 +390,7 @@ private Map restoreNotificationChannels(String projectId, // [END monitoring_alert_create_channel] // [END monitoring_alert_update_channel] - private JsonObject getPolicyJsonContents(String filePath, BufferedReader content, Gson gson) { + private static JsonObject getPolicyJsonContents(String filePath, BufferedReader content) { try { return gson.fromJson(content, JsonObject.class); } catch (JsonSyntaxException jse) { @@ -416,7 +400,8 @@ private JsonObject getPolicyJsonContents(String filePath, BufferedReader content // [END monitoring_alert_restore_policies] // [START monitoring_alert_replace_channels] - void replaceChannels(String projectId, String alertPolicyId, String[] channelIds) { + private static void replaceChannels(String projectId, String alertPolicyId, String[] channelIds) + throws IOException { AlertPolicy.Builder policyBuilder = AlertPolicy .newBuilder() .setName(AlertPolicyName.of(projectId, alertPolicyId).toString()); @@ -424,89 +409,73 @@ void replaceChannels(String projectId, String alertPolicyId, String[] channelIds policyBuilder.addNotificationChannels( NotificationChannelName.of(projectId, channelId).toString()); } - AlertPolicy result = alertPolicyClient.updateAlertPolicy( - FieldMask.newBuilder().addPaths("notification_channels").build(), policyBuilder.build()); - System.out.println(String.format("Updated %s", result.getName())); + try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) { + AlertPolicy result = client.updateAlertPolicy( + FieldMask.newBuilder().addPaths("notification_channels").build(), policyBuilder.build()); + System.out.println(String.format("Updated %s", result.getName())); + } } // [END monitoring_alert_replace_channels] // [START monitoring_alert_enable_policies] // [START monitoring_alert_disable_policies] - void enablePolicies(String projectId, - String filter, - boolean enable) { - ListAlertPoliciesPagedResponse response = alertPolicyClient - .listAlertPolicies(ListAlertPoliciesRequest.newBuilder() - .setName(ProjectName.of(projectId).toString()) - .setFilter(filter) - .build()); - - for (AlertPolicy policy : response.iterateAll()) { - if (policy.getEnabled().getValue() == enable) { + private static void enablePolicies(String projectId, String filter, boolean enable) + throws IOException { + try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) { + ListAlertPoliciesPagedResponse response = client + .listAlertPolicies(ListAlertPoliciesRequest.newBuilder() + .setName(ProjectName.of(projectId).toString()) + .setFilter(filter) + .build()); + + for (AlertPolicy policy : response.iterateAll()) { + if (policy.getEnabled().getValue() == enable) { + System.out.println(String.format( + "Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled")); + continue; + } + AlertPolicy updatedPolicy = AlertPolicy + .newBuilder() + .setName(policy.getName()) + .setEnabled(BoolValue.newBuilder().setValue(enable)) + .build(); + AlertPolicy result = client.updateAlertPolicy( + FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy); System.out.println(String.format( - "Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled")); - continue; + "%s %s", + result.getDisplayName(), + result.getEnabled().getValue() ? "enabled" : "disabled")); } - AlertPolicy updatedPolicy = AlertPolicy - .newBuilder() - .setName(policy.getName()) - .setEnabled(BoolValue.newBuilder().setValue(enable)) - .build(); - AlertPolicy result = alertPolicyClient.updateAlertPolicy( - FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy); - System.out.println(String.format( - "%s %s", - result.getDisplayName(), - result.getEnabled().getValue() ? "enabled" : "disabled")); } - } // [END monitoring_alert_enable_policies] // [END monitoring_alert_disable_policies] private static void usage(String message) { Optional.ofNullable(message).ifPresent(System.out::println); - System.out.println("Usage:"); - System.out.printf( - "\tjava %s \"\" \"\"\n" - + "Args:\n" - + "\t%s\n" - + "Commands:\n" - + "\tlist:\t\t\t\tList existing alert policies for project.\n" - + "\tbackup:\t\t\t\tBackup existing alert policies & notification channels to a file.\n" - + "\t\t\t\t\t\t\tArgs:\n" - + "\t\t\t\t\t\t\t\t%s\n" - + "\t\t\t\t\t\t\t\t%s\n" - + "\trestore:\t\t\tRestore alerts and notification channels from a backed-up file.\n" - + "\t\t\t\t\t\t\tArgs:\n" - + "\t\t\t\t\t\t\t\t%s\n" - + "\t\t\t\t\t\t\t\t%s\n" - + "\treplace-channels:\tReplace the notification channels for an alert.\n" - + "\t\t\t\t\t\t\tArgs:\n" - + "\t\t\t\t\t\t\t\t%s\n" - + "\t\t\t\t\t\t\t\t%s\n" - + "\tenable:\t\t\t\tEnable alert policies in project.\n" - + "\t\t\t\t\t\t\tArgs:\n" - + "\t\t\t\t\t\t\t\t%s\n" - + "\tdisable:\t\t\tDisable alert policies in project.\n" - + "\t\t\t\t\t\t\tArgs:\n" - + "\t\t\t\t\t\t\t\t%s\n", - AlertSample.class.getCanonicalName(), - formatArgString(PROJECT_ID_OPTION), - formatArgString(FILE_PATH_OPTION), - formatArgString(CHANNEL_ID_OPTION), - formatArgString(FILE_PATH_OPTION), - formatArgString(CHANNEL_ID_OPTION), - formatArgString(ALERT_ID_OPTION), - formatArgString(CHANNEL_ID_OPTION), - formatArgString(FILTER_OPTION), - formatArgString(FILTER_OPTION)); - } - - private static String formatArgString(Option option) { - return String.format("--%s (%s):\t%s", - option.getLongOpt(), - option.getOpt(), - option.getDescription()); + System.out.println(); + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp("list", "Lists alert policies.", BASE_OPTIONS, "", true); + System.out.println(); + formatter.printHelp( + "[backup|restore]", + "Backs up or restores alert policies.", + BACKUP_OPTIONS, + "", + true); + System.out.println(); + formatter.printHelp( + "replace-channels", + "Replaces alert policy notification channels.", + REPLACE_CHANNELS_OPTIONS, + "", + true); + System.out.println(); + formatter.printHelp( + "[enable|disable]", + "Enables/disables alert policies.", + ENABLE_OPTIONS, + "", + true); } } diff --git a/samples/snippets/src/main/java/com/example/UptimeSample.java b/samples/snippets/src/main/java/com/example/UptimeSample.java new file mode 100644 index 00000000..a0a427fa --- /dev/null +++ b/samples/snippets/src/main/java/com/example/UptimeSample.java @@ -0,0 +1,226 @@ +/* + * Copyright 2018 Google LLC + * + * 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. + */ + +package com.example; + +import com.google.api.MonitoredResource; +import com.google.cloud.monitoring.v3.UptimeCheckServiceClient; +import com.google.cloud.monitoring.v3.UptimeCheckServiceClient.ListUptimeCheckConfigsPagedResponse; +import com.google.cloud.monitoring.v3.UptimeCheckServiceClient.ListUptimeCheckIpsPagedResponse; +import com.google.common.base.Strings; +import com.google.monitoring.v3.CreateUptimeCheckConfigRequest; +import com.google.monitoring.v3.ListUptimeCheckConfigsRequest; +import com.google.monitoring.v3.ListUptimeCheckIpsRequest; +import com.google.monitoring.v3.ProjectName; +import com.google.monitoring.v3.UptimeCheckConfig; +import com.google.monitoring.v3.UptimeCheckConfig.HttpCheck; +import com.google.monitoring.v3.UptimeCheckConfigName; +import com.google.monitoring.v3.UptimeCheckIp; +import com.google.protobuf.Duration; + +import java.io.IOException; +import java.util.Optional; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; + +public class UptimeSample { + + private static final Option PROJECT_ID_OPTION = Option.builder("p") + .longOpt("projectid") + .desc("Your Google project id.") + .hasArg() + .argName("PROJECT_ID") + .build(); + private static final Option DISPLAY_NAME_OPTION = Option.builder("n") + .longOpt("name") + .desc("[create/get/delete]: Display name of uptime check.") + .hasArg() + .argName("DISPLAY_NAME") + .required(false) + .build(); + private static final Option HOST_NAME_OPTION = Option.builder("o") + .longOpt("hostname") + .desc("[create]: Host name of uptime check to create.") + .hasArg() + .argName("HOST_NAME") + .required(false) + .build(); + + private static final Options OPTIONS = new Options() + .addOption(PROJECT_ID_OPTION) + .addOption(DISPLAY_NAME_OPTION) + .addOption(HOST_NAME_OPTION); + + private static final CommandLineParser PARSER = new DefaultParser(); + + public static void main(String... args) throws IOException { + CommandLine cl; + try { + cl = PARSER.parse(OPTIONS, args); + } catch (ParseException pe) { + usage("Exception parsing command line arguments."); + throw new RuntimeException("Exception parsing command line arguments.", pe); + } + + String projectId = cl.getOptionValue( + PROJECT_ID_OPTION.getOpt(), + System.getenv("GOOGLE_CLOUD_PROJECT")); + + String command = Optional + .of(cl.getArgList()) + .filter(l -> l.size() > 0) + .map(l -> Strings.emptyToNull(l.get(0))) + .orElse(null); + if (command == null) { + usage(null); + return; + } + + switch (command.toLowerCase()) { + case "create": + createUptimeCheck( + projectId, + cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check"), + cl.getOptionValue(HOST_NAME_OPTION.getOpt(), "example.com") + ); + break; + case "list": + listUptimeChecks(projectId); + break; + case "listips": + listUptimeCheckIPs(); + break; + case "get": + getUptimeCheckConfig( + projectId, + cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check")); + break; + case "delete": + deleteUptimeCheckConfig( + projectId, + cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check")); + break; + default: + usage(null); + } + } + + // [START monitoring_uptime_check_create]] + private static void createUptimeCheck(String projectId, String displayName, String hostName) + throws IOException { + CreateUptimeCheckConfigRequest request = CreateUptimeCheckConfigRequest + .newBuilder() + .setParent(ProjectName.format(projectId)) + .setUptimeCheckConfig(UptimeCheckConfig + .newBuilder() + .setDisplayName(displayName) + .setMonitoredResource(MonitoredResource + .newBuilder() + .setType("uptime_url") + .putLabels("host", hostName)) + .setHttpCheck(HttpCheck + .newBuilder() + .setPath("/") + .setPort(80)) + .setTimeout(Duration.newBuilder().setSeconds(10)) + .setPeriod(Duration.newBuilder().setSeconds(300))) + .build(); + try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) { + UptimeCheckConfig config = client.createUptimeCheckConfig(request); + System.out.println("Uptime check created: " + config.getDisplayName()); + } catch (Exception e) { + usage("Exception creating uptime check: " + e.toString()); + throw e; + } + } + // [END monitoring_uptime_check_create]] + + // [START monitoring_uptime_check_list_configs]] + private static void listUptimeChecks(String projectId) throws IOException { + ListUptimeCheckConfigsRequest request = ListUptimeCheckConfigsRequest + .newBuilder() + .setParent(ProjectName.format(projectId)) + .build(); + try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) { + ListUptimeCheckConfigsPagedResponse response = client.listUptimeCheckConfigs(request); + for (UptimeCheckConfig config : response.iterateAll()) { + System.out.println(config.getDisplayName()); + } + } catch (Exception e) { + usage("Exception listing uptime checks: " + e.toString()); + throw e; + } + } + // [END monitoring_uptime_check_list_configs]] + + // [START monitoring_uptime_check_list_ips]] + private static void listUptimeCheckIPs() throws IOException { + try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) { + ListUptimeCheckIpsPagedResponse response = + client.listUptimeCheckIps(ListUptimeCheckIpsRequest.newBuilder().build()); + for (UptimeCheckIp config : response.iterateAll()) { + System.out.println(config.getRegion() + " - " + config.getIpAddress()); + } + } catch (Exception e) { + usage("Exception listing uptime IPs: " + e.toString()); + throw e; + } + } + // [END monitoring_uptime_check_list_ips]] + + // [START monitoring_uptime_check_get]] + private static void getUptimeCheckConfig(String projectId, String checkName) throws IOException { + try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) { + String fullCheckName = UptimeCheckConfigName.format(projectId, checkName); + UptimeCheckConfig config = client.getUptimeCheckConfig(fullCheckName); + if (config != null) { + System.out.println(config.toString()); + } else { + System.out.println( + "No uptime check config found with name " + checkName + " in project " + projectId); + } + } catch (Exception e) { + usage("Exception getting uptime check: " + e.toString()); + throw e; + } + } + // [END monitoring_uptime_check_get]] + + // [START monitoring_uptime_check_delete]] + private static void deleteUptimeCheckConfig(String projectId, String checkName) + throws IOException { + try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) { + client.deleteUptimeCheckConfig(UptimeCheckConfigName.format(projectId, checkName)); + } catch (Exception e) { + usage("Exception deleting uptime check: " + e.toString()); + throw e; + } + } + // [END monitoring_uptime_check_delete]] + + private static void usage(String message) { + Optional.ofNullable(message).ifPresent(System.out::println); + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp("[create|list|listIPs|get|delete]", + "Performs operations on monitoring uptime checks.", OPTIONS, "", true); + } +} diff --git a/samples/snippets/src/test/java/AlertIT.java b/samples/snippets/src/test/java/com/example/AlertIT.java similarity index 99% rename from samples/snippets/src/test/java/AlertIT.java rename to samples/snippets/src/test/java/com/example/AlertIT.java index d98eb61e..55015ff2 100644 --- a/samples/snippets/src/test/java/AlertIT.java +++ b/samples/snippets/src/test/java/com/example/AlertIT.java @@ -14,6 +14,8 @@ * limitations under the License. */ +package com.example; + import static org.junit.Assert.assertTrue; import com.google.common.base.Strings; diff --git a/samples/snippets/src/test/java/com/example/UptimeIT.java b/samples/snippets/src/test/java/com/example/UptimeIT.java new file mode 100644 index 00000000..9fdb82d7 --- /dev/null +++ b/samples/snippets/src/test/java/com/example/UptimeIT.java @@ -0,0 +1,98 @@ +/* + * Copyright 2018 Google LLC + * + * 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. + */ + +package com.example; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.monitoring.v3.UptimeCheckConfig; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.UUID; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.junit.runners.MethodSorters; + +/** + * Integration (system) tests for {@link UptimeSample}. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class UptimeIT { + private ByteArrayOutputStream bout; + private PrintStream out; + + private static UptimeCheckConfig config = UptimeCheckConfig + .newBuilder() + .setDisplayName("check-" + UUID.randomUUID().toString().substring(0, 6)) + .build(); + + @BeforeClass + public static void setUpClass() { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(bout); + System.setOut(out); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @Test + public void test1_CreateUptimeCheck() throws Exception { + UptimeSample.main("create", "-n", config.getDisplayName()); + assertThat(bout.toString()).contains("Uptime check created: " + config.getDisplayName()); + } + + @Test + public void test2_GetUptimeCheck() throws Exception { + UptimeSample.main("get", "-n", config.getDisplayName()); + assertThat(bout.toString()).contains(config.getDisplayName()); + } + + @Test + public void test2_ListUptimeChecks() throws Exception { + // Create a few uptime check configs to list. + UptimeSample.main("list"); + assertThat(bout.toString()).contains(config.getDisplayName()); + } + + @Test + public void test2_ListUptimeIps() throws Exception { + // Create a few uptime check configs to list. + UptimeSample.main("listIPs"); + String output = bout.toString(); + assertThat(output).contains("USA - "); + assertThat(output).contains("EUROPE - "); + assertThat(output).contains("SOUTH_AMERICA - "); + assertThat(output).contains("ASIA_PACIFIC - "); + } + + @Test + public void test3_DeleteUptimeCheck() throws Exception { + UptimeSample.main("delete", "-n", config.getDisplayName()); + } +} From 51d2a4e5915fe1319447bb327aef85ad7542a70b Mon Sep 17 00:00:00 2001 From: Dane Zeke Liergaard Date: Tue, 14 Aug 2018 10:14:59 -0700 Subject: [PATCH 29/45] samples: Add final Monitoring Uptime Check sample (update). (#1180) --- .../main/java/com/example/UptimeSample.java | 63 +++++++++++++++++-- .../src/test/java/com/example/UptimeIT.java | 11 +++- 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/samples/snippets/src/main/java/com/example/UptimeSample.java b/samples/snippets/src/main/java/com/example/UptimeSample.java index a0a427fa..77bd0769 100644 --- a/samples/snippets/src/main/java/com/example/UptimeSample.java +++ b/samples/snippets/src/main/java/com/example/UptimeSample.java @@ -25,11 +25,13 @@ import com.google.monitoring.v3.ListUptimeCheckConfigsRequest; import com.google.monitoring.v3.ListUptimeCheckIpsRequest; import com.google.monitoring.v3.ProjectName; +import com.google.monitoring.v3.UpdateUptimeCheckConfigRequest; import com.google.monitoring.v3.UptimeCheckConfig; import com.google.monitoring.v3.UptimeCheckConfig.HttpCheck; import com.google.monitoring.v3.UptimeCheckConfigName; import com.google.monitoring.v3.UptimeCheckIp; import com.google.protobuf.Duration; +import com.google.protobuf.FieldMask; import java.io.IOException; import java.util.Optional; @@ -64,11 +66,19 @@ public class UptimeSample { .argName("HOST_NAME") .required(false) .build(); + private static final Option PATH_NAME_OPTION = Option.builder("a") + .longOpt("pathname") + .desc("[create/update]: Path name of uptime check to create/update.") + .hasArg() + .argName("HOST_NAME") + .required(false) + .build(); private static final Options OPTIONS = new Options() .addOption(PROJECT_ID_OPTION) .addOption(DISPLAY_NAME_OPTION) - .addOption(HOST_NAME_OPTION); + .addOption(HOST_NAME_OPTION) + .addOption(PATH_NAME_OPTION); private static final CommandLineParser PARSER = new DefaultParser(); @@ -100,7 +110,16 @@ public static void main(String... args) throws IOException { createUptimeCheck( projectId, cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check"), - cl.getOptionValue(HOST_NAME_OPTION.getOpt(), "example.com") + cl.getOptionValue(HOST_NAME_OPTION.getOpt(), "example.com"), + cl.getOptionValue(PATH_NAME_OPTION.getOpt(), "/") + ); + break; + case "update": + updateUptimeCheck( + projectId, + cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check"), + cl.getOptionValue(HOST_NAME_OPTION.getOpt(), "example.com"), + cl.getOptionValue(PATH_NAME_OPTION.getOpt(), "/") ); break; case "list": @@ -125,8 +144,8 @@ public static void main(String... args) throws IOException { } // [START monitoring_uptime_check_create]] - private static void createUptimeCheck(String projectId, String displayName, String hostName) - throws IOException { + private static void createUptimeCheck( + String projectId, String displayName, String hostName, String pathName) throws IOException { CreateUptimeCheckConfigRequest request = CreateUptimeCheckConfigRequest .newBuilder() .setParent(ProjectName.format(projectId)) @@ -139,7 +158,7 @@ private static void createUptimeCheck(String projectId, String displayName, Stri .putLabels("host", hostName)) .setHttpCheck(HttpCheck .newBuilder() - .setPath("/") + .setPath(pathName) .setPort(80)) .setTimeout(Duration.newBuilder().setSeconds(10)) .setPeriod(Duration.newBuilder().setSeconds(300))) @@ -154,6 +173,40 @@ private static void createUptimeCheck(String projectId, String displayName, Stri } // [END monitoring_uptime_check_create]] + // [START monitoring_uptime_check_update]] + private static void updateUptimeCheck( + String projectId, String displayName, String hostName, String pathName) throws IOException { + String fullCheckName = UptimeCheckConfigName.format(projectId, displayName); + + UpdateUptimeCheckConfigRequest request = UpdateUptimeCheckConfigRequest + .newBuilder() + .setUpdateMask(FieldMask + .newBuilder() + .addPaths("http_check.path")) + .setUptimeCheckConfig(UptimeCheckConfig + .newBuilder() + .setName(fullCheckName) + .setMonitoredResource(MonitoredResource + .newBuilder() + .setType("uptime_url") + .putLabels("host", hostName)) + .setHttpCheck(HttpCheck + .newBuilder() + .setPath(pathName) + .setPort(80)) + .setTimeout(Duration.newBuilder().setSeconds(10)) + .setPeriod(Duration.newBuilder().setSeconds(300))) + .build(); + try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) { + UptimeCheckConfig config = client.updateUptimeCheckConfig(request); + System.out.println("Uptime check updated: \n" + config.toString()); + } catch (Exception e) { + usage("Exception updating uptime check: " + e.toString()); + throw e; + } + } + // [END monitoring_uptime_check_update]] + // [START monitoring_uptime_check_list_configs]] private static void listUptimeChecks(String projectId) throws IOException { ListUptimeCheckConfigsRequest request = ListUptimeCheckConfigsRequest diff --git a/samples/snippets/src/test/java/com/example/UptimeIT.java b/samples/snippets/src/test/java/com/example/UptimeIT.java index 9fdb82d7..3bed7dac 100644 --- a/samples/snippets/src/test/java/com/example/UptimeIT.java +++ b/samples/snippets/src/test/java/com/example/UptimeIT.java @@ -63,8 +63,16 @@ public void setUp() { @Test public void test1_CreateUptimeCheck() throws Exception { - UptimeSample.main("create", "-n", config.getDisplayName()); + UptimeSample.main( + "create", "-n", config.getDisplayName(), "-o", "test.example.com", "-a", "/"); assertThat(bout.toString()).contains("Uptime check created: " + config.getDisplayName()); + + } + + @Test + public void test2_UpdateUptimeCheck() throws Exception { + UptimeSample.main("update", "-n", config.getDisplayName(), "-a", "/updated"); + assertThat(bout.toString()).contains("/updated"); } @Test @@ -75,7 +83,6 @@ public void test2_GetUptimeCheck() throws Exception { @Test public void test2_ListUptimeChecks() throws Exception { - // Create a few uptime check configs to list. UptimeSample.main("list"); assertThat(bout.toString()).contains(config.getDisplayName()); } From 1f5da6a6fd4b7c79769a481a717a89f500bd9cef Mon Sep 17 00:00:00 2001 From: Dane Zeke Liergaard Date: Thu, 3 Jan 2019 10:02:45 -0800 Subject: [PATCH 30/45] samples: Add monitoring_get_resource tag/code sample to monitoring snippets. (#1306) * Add monitoring_get_resource tag/code sample to monitoring snippets. * Add monitoring_alert_delete_channel code, tag, and test. --- .../example/DeleteNotificationChannel.java | 39 ++++++++ .../example/DeleteNotificationChannelIT.java | 93 +++++++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 samples/snippets/src/main/java/com/example/DeleteNotificationChannel.java create mode 100644 samples/snippets/src/test/java/com/example/DeleteNotificationChannelIT.java diff --git a/samples/snippets/src/main/java/com/example/DeleteNotificationChannel.java b/samples/snippets/src/main/java/com/example/DeleteNotificationChannel.java new file mode 100644 index 00000000..4cad86ff --- /dev/null +++ b/samples/snippets/src/main/java/com/example/DeleteNotificationChannel.java @@ -0,0 +1,39 @@ +/* + * Copyright 2018 Google LLC + * + * 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. + */ + +package com.example; + +import com.google.cloud.monitoring.v3.NotificationChannelServiceClient; +import com.google.monitoring.v3.NotificationChannelName; + +import java.io.IOException; + +public class DeleteNotificationChannel { + /** + * Demonstrates deleting a notification channel by name. + * @param channelName Name of the notification channel to delete. + */ + // [START monitoring_alert_delete_channel] + static void deleteNotificationChannel(String channelName) throws IOException { + String projectId = System.getProperty("projectId"); + try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) { + NotificationChannelName name = NotificationChannelName.of(projectId, channelName); + client.deleteNotificationChannel(channelName, false); + System.out.println("Deleted notification channel " + channelName); + } + } + // [END monitoring_alert_delete_channel] +} diff --git a/samples/snippets/src/test/java/com/example/DeleteNotificationChannelIT.java b/samples/snippets/src/test/java/com/example/DeleteNotificationChannelIT.java new file mode 100644 index 00000000..d3f0dad3 --- /dev/null +++ b/samples/snippets/src/test/java/com/example/DeleteNotificationChannelIT.java @@ -0,0 +1,93 @@ +/* + * Copyright 2018 Google LLC + * + * 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. + */ + +package com.example; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.cloud.monitoring.v3.NotificationChannelServiceClient; +import com.google.monitoring.v3.NotificationChannel; +import com.google.monitoring.v3.ProjectName; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for delete notification channel sample. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DeleteNotificationChannelIT { + private ByteArrayOutputStream bout; + private PrintStream out; + private static final String LEGACY_PROJECT_ENV_NAME = "GCLOUD_PROJECT"; + private static final String PROJECT_ENV_NAME = "GOOGLE_CLOUD_PROJECT"; + private static String NOTIFICATION_CHANNEL_NAME = "channelname"; + private static NotificationChannel NOTIFICATION_CHANNEL; + + private static String getProjectId() { + String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME)); + if (projectId == null) { + projectId = System.getProperty(LEGACY_PROJECT_ENV_NAME, + System.getenv(LEGACY_PROJECT_ENV_NAME)); + } + return projectId; + } + + @BeforeClass + public static void setupClass() throws IOException { + try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) { + String projectId = getProjectId(); + NOTIFICATION_CHANNEL = NotificationChannel.newBuilder() + .setType("email") + .putLabels("email_address", "java-docs-samples-testing@google.com") + .build(); + NotificationChannel channel = client.createNotificationChannel(ProjectName.of(projectId), + NOTIFICATION_CHANNEL); + NOTIFICATION_CHANNEL_NAME = channel.getName(); + } + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + System.setProperty("projectId", DeleteNotificationChannelIT.getProjectId()); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testDeleteNotificationChannel() throws Exception { + // Act + DeleteNotificationChannel.deleteNotificationChannel(NOTIFICATION_CHANNEL_NAME); + // Assert + String got = bout.toString(); + assertThat(got).contains(NOTIFICATION_CHANNEL_NAME); + } +} From 0c651d2d70ae87d5f9acc7b3e4ea9dc958afd82d Mon Sep 17 00:00:00 2001 From: Averi Kitsch Date: Fri, 27 Mar 2020 12:00:25 -0700 Subject: [PATCH 31/45] samples: update shared config (#2443) * update shared config * Update to 1.0.13 * lint * Fix linting * lint * fix imports Co-authored-by: Les Vogel --- .../main/java/com/example/AlertSample.java | 254 +++++++++--------- .../example/DeleteNotificationChannel.java | 2 +- .../main/java/com/example/UptimeSample.java | 176 ++++++------ .../src/test/java/com/example/AlertIT.java | 30 +-- .../example/DeleteNotificationChannelIT.java | 23 +- .../src/test/java/com/example/UptimeIT.java | 18 +- 6 files changed, 236 insertions(+), 267 deletions(-) diff --git a/samples/snippets/src/main/java/com/example/AlertSample.java b/samples/snippets/src/main/java/com/example/AlertSample.java index 163903a4..538d595f 100644 --- a/samples/snippets/src/main/java/com/example/AlertSample.java +++ b/samples/snippets/src/main/java/com/example/AlertSample.java @@ -37,7 +37,6 @@ import com.google.monitoring.v3.ProjectName; import com.google.protobuf.BoolValue; import com.google.protobuf.FieldMask; - import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; @@ -45,7 +44,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; - import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; @@ -56,70 +54,73 @@ public class AlertSample { - private static final Option PROJECT_ID_OPTION = Option.builder("p") - .longOpt("projectid") - .desc("Your Google project id.") - .hasArg() - .argName("PROJECT_ID") - .build(); - private static final Option FILE_PATH_OPTION = Option.builder("j") - .longOpt("jsonPath") - .desc("Path to json file where alert polices are saved and restored.") - .hasArg() - .argName("JSON_PATH") - .build(); - private static final Option ALERT_ID_OPTION = Option.builder("a") - .required() - .longOpt("alert-id") - .desc("The id of the alert policy whose channels will be replaced.") - .hasArg() - .argName("ALERT_ID") - .build(); - private static final Option CHANNEL_ID_OPTION = Option.builder("c") - .longOpt("channel-id") - .desc("A channel id. Repeat this option to set multiple channel ids.") - .hasArg() - .argName("CHANNEL_ID") - .build(); - private static final Option FILTER_OPTION = Option.builder("d") - .longOpt("filter") - .desc("See https://cloud.google.com/monitoring/api/v3/filters.") - .hasArg() - .argName("FILTER") - .build(); - - private static final Options BASE_OPTIONS = new Options() - .addOption(PROJECT_ID_OPTION); - private static final Options BACKUP_OPTIONS = new Options() - .addOption(PROJECT_ID_OPTION) - .addOption(FILE_PATH_OPTION); - private static final Options REPLACE_CHANNELS_OPTIONS = new Options() - .addOption(PROJECT_ID_OPTION) - .addOption(ALERT_ID_OPTION) - .addOption(CHANNEL_ID_OPTION); - private static final Options ENABLE_OPTIONS = new Options() - .addOption(PROJECT_ID_OPTION) - .addOption(FILTER_OPTION); - - private static Map COMMAND_OPTIONS = ImmutableMap.of( - "backup", BACKUP_OPTIONS, - "restore", BACKUP_OPTIONS, - "replace-channels", REPLACE_CHANNELS_OPTIONS, - "enable", ENABLE_OPTIONS, - "disable", ENABLE_OPTIONS - ); + private static final Option PROJECT_ID_OPTION = + Option.builder("p") + .longOpt("projectid") + .desc("Your Google project id.") + .hasArg() + .argName("PROJECT_ID") + .build(); + private static final Option FILE_PATH_OPTION = + Option.builder("j") + .longOpt("jsonPath") + .desc("Path to json file where alert polices are saved and restored.") + .hasArg() + .argName("JSON_PATH") + .build(); + private static final Option ALERT_ID_OPTION = + Option.builder("a") + .required() + .longOpt("alert-id") + .desc("The id of the alert policy whose channels will be replaced.") + .hasArg() + .argName("ALERT_ID") + .build(); + private static final Option CHANNEL_ID_OPTION = + Option.builder("c") + .longOpt("channel-id") + .desc("A channel id. Repeat this option to set multiple channel ids.") + .hasArg() + .argName("CHANNEL_ID") + .build(); + private static final Option FILTER_OPTION = + Option.builder("d") + .longOpt("filter") + .desc("See https://cloud.google.com/monitoring/api/v3/filters.") + .hasArg() + .argName("FILTER") + .build(); + + private static final Options BASE_OPTIONS = new Options().addOption(PROJECT_ID_OPTION); + private static final Options BACKUP_OPTIONS = + new Options().addOption(PROJECT_ID_OPTION).addOption(FILE_PATH_OPTION); + private static final Options REPLACE_CHANNELS_OPTIONS = + new Options() + .addOption(PROJECT_ID_OPTION) + .addOption(ALERT_ID_OPTION) + .addOption(CHANNEL_ID_OPTION); + private static final Options ENABLE_OPTIONS = + new Options().addOption(PROJECT_ID_OPTION).addOption(FILTER_OPTION); + + private static Map COMMAND_OPTIONS = + ImmutableMap.of( + "backup", BACKUP_OPTIONS, + "restore", BACKUP_OPTIONS, + "replace-channels", REPLACE_CHANNELS_OPTIONS, + "enable", ENABLE_OPTIONS, + "disable", ENABLE_OPTIONS); private static final CommandLineParser PARSER = new DefaultParser(); - private static final FieldMask NOTIFICATION_CHANNEL_UPDATE_MASK = FieldMask - .newBuilder() - .addPaths("type") - .addPaths("name") - .addPaths("displayName") - .addPaths("description") - .addPaths("labels") - .addPaths("userLabels") - .build(); + private static final FieldMask NOTIFICATION_CHANNEL_UPDATE_MASK = + FieldMask.newBuilder() + .addPaths("type") + .addPaths("name") + .addPaths("displayName") + .addPaths("description") + .addPaths("labels") + .addPaths("userLabels") + .build(); private static Gson gson = new Gson(); @@ -133,17 +134,19 @@ public static void main(String... args) throws IOException { CommandLine cl = parseCommandLine(args, expectedOptions); - String projectId = cl.hasOption(PROJECT_ID_OPTION.getOpt()) - ? cl.getOptionValue(PROJECT_ID_OPTION.getOpt()) - : System.getenv("GOOGLE_CLOUD_PROJECT"); + String projectId = + cl.hasOption(PROJECT_ID_OPTION.getOpt()) + ? cl.getOptionValue(PROJECT_ID_OPTION.getOpt()) + : System.getenv("GOOGLE_CLOUD_PROJECT"); if (Strings.isNullOrEmpty(projectId)) { projectId = System.getenv("DEVSHELL_PROJECT_ID"); } if (Strings.isNullOrEmpty(projectId)) { - usage("Error: --project-id arg required unless provided by the GOOGLE_CLOUD_PROJECT " - + "or DEVSHELL_PROJECT_ID environment variables."); + usage( + "Error: --project-id arg required unless provided by the GOOGLE_CLOUD_PROJECT " + + "or DEVSHELL_PROJECT_ID environment variables."); return; } @@ -248,7 +251,8 @@ private static void writePoliciesBackupFile( String projectId, String filePath, List alertPolicies, - List notificationChannels) throws IOException { + List notificationChannels) + throws IOException { JsonObject backupContents = new JsonObject(); backupContents.add("project_id", new JsonPrimitive(projectId)); JsonArray policiesJson = new JsonArray(); @@ -280,9 +284,8 @@ private static void restorePolicies(String projectId, String filePath) throws IO AlertPolicy[] policies = gson.fromJson(backupContent.get("policies"), AlertPolicy[].class); List notificationChannels = readNotificationChannelsJson(backupContent); - Map restoredChannelIds = restoreNotificationChannels(projectId, - notificationChannels, - isSameProject); + Map restoredChannelIds = + restoreNotificationChannels(projectId, notificationChannels, isSameProject); List policiesToRestore = reviseRestoredPolicies(policies, isSameProject, restoredChannelIds); @@ -290,16 +293,15 @@ private static void restorePolicies(String projectId, String filePath) throws IO } private static List reviseRestoredPolicies( - AlertPolicy[] policies, - boolean isSameProject, - Map restoredChannelIds) { + AlertPolicy[] policies, boolean isSameProject, Map restoredChannelIds) { List newPolicies = Lists.newArrayListWithCapacity(policies.length); for (AlertPolicy policy : policies) { - AlertPolicy.Builder policyBuilder = policy - .toBuilder() - .clearNotificationChannels() - .clearMutationRecord() - .clearCreationRecord(); + AlertPolicy.Builder policyBuilder = + policy + .toBuilder() + .clearNotificationChannels() + .clearMutationRecord() + .clearCreationRecord(); // Update restored notification channel names. for (String channelName : policy.getNotificationChannelsList()) { String newChannelName = restoredChannelIds.get(channelName); @@ -321,9 +323,7 @@ private static List reviseRestoredPolicies( // [START monitoring_alert_create_policy] private static void restoreRevisedPolicies( - String projectId, - boolean isSameProject, - List policies) throws IOException { + String projectId, boolean isSameProject, List policies) throws IOException { try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) { for (AlertPolicy policy : policies) { if (!isSameProject) { @@ -332,9 +332,9 @@ private static void restoreRevisedPolicies( try { client.updateAlertPolicy(null, policy); } catch (Exception e) { - policy = client.createAlertPolicy( - ProjectName.of(projectId), - policy.toBuilder().clearName().build()); + policy = + client.createAlertPolicy( + ProjectName.of(projectId), policy.toBuilder().clearName().build()); } } System.out.println(String.format("Restored %s", policy.getName())); @@ -345,8 +345,8 @@ private static void restoreRevisedPolicies( private static List readNotificationChannelsJson(JsonObject backupContent) { if (backupContent.has("notification_channels")) { - NotificationChannel[] channels = gson.fromJson(backupContent.get("notification_channels"), - NotificationChannel[].class); + NotificationChannel[] channels = + gson.fromJson(backupContent.get("notification_channels"), NotificationChannel[].class); return Lists.newArrayList(channels); } return Lists.newArrayList(); @@ -355,9 +355,8 @@ private static List readNotificationChannelsJson(JsonObject // [START monitoring_alert_create_channel] // [START monitoring_alert_update_channel] private static Map restoreNotificationChannels( - String projectId, - List channels, - boolean isSameProject) throws IOException { + String projectId, List channels, boolean isSameProject) + throws IOException { Map newChannelNames = Maps.newHashMap(); try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) { for (NotificationChannel channel : channels) { @@ -374,13 +373,10 @@ private static Map restoreNotificationChannels( } } if (!channelUpdated) { - NotificationChannel newChannel = client.createNotificationChannel( - ProjectName.of(projectId), - channel - .toBuilder() - .clearName() - .clearVerificationStatus() - .build()); + NotificationChannel newChannel = + client.createNotificationChannel( + ProjectName.of(projectId), + channel.toBuilder().clearName().clearVerificationStatus().build()); newChannelNames.put(channel.getName(), newChannel.getName()); } } @@ -402,16 +398,17 @@ private static JsonObject getPolicyJsonContents(String filePath, BufferedReader // [START monitoring_alert_replace_channels] private static void replaceChannels(String projectId, String alertPolicyId, String[] channelIds) throws IOException { - AlertPolicy.Builder policyBuilder = AlertPolicy - .newBuilder() - .setName(AlertPolicyName.of(projectId, alertPolicyId).toString()); + AlertPolicy.Builder policyBuilder = + AlertPolicy.newBuilder().setName(AlertPolicyName.of(projectId, alertPolicyId).toString()); for (String channelId : channelIds) { policyBuilder.addNotificationChannels( NotificationChannelName.of(projectId, channelId).toString()); } try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) { - AlertPolicy result = client.updateAlertPolicy( - FieldMask.newBuilder().addPaths("notification_channels").build(), policyBuilder.build()); + AlertPolicy result = + client.updateAlertPolicy( + FieldMask.newBuilder().addPaths("notification_channels").build(), + policyBuilder.build()); System.out.println(String.format("Updated %s", result.getName())); } } @@ -422,29 +419,32 @@ private static void replaceChannels(String projectId, String alertPolicyId, Stri private static void enablePolicies(String projectId, String filter, boolean enable) throws IOException { try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) { - ListAlertPoliciesPagedResponse response = client - .listAlertPolicies(ListAlertPoliciesRequest.newBuilder() - .setName(ProjectName.of(projectId).toString()) - .setFilter(filter) - .build()); + ListAlertPoliciesPagedResponse response = + client.listAlertPolicies( + ListAlertPoliciesRequest.newBuilder() + .setName(ProjectName.of(projectId).toString()) + .setFilter(filter) + .build()); for (AlertPolicy policy : response.iterateAll()) { if (policy.getEnabled().getValue() == enable) { - System.out.println(String.format( - "Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled")); + System.out.println( + String.format( + "Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled")); continue; } - AlertPolicy updatedPolicy = AlertPolicy - .newBuilder() - .setName(policy.getName()) - .setEnabled(BoolValue.newBuilder().setValue(enable)) - .build(); - AlertPolicy result = client.updateAlertPolicy( - FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy); - System.out.println(String.format( - "%s %s", - result.getDisplayName(), - result.getEnabled().getValue() ? "enabled" : "disabled")); + AlertPolicy updatedPolicy = + AlertPolicy.newBuilder() + .setName(policy.getName()) + .setEnabled(BoolValue.newBuilder().setValue(enable)) + .build(); + AlertPolicy result = + client.updateAlertPolicy( + FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy); + System.out.println( + String.format( + "%s %s", + result.getDisplayName(), result.getEnabled().getValue() ? "enabled" : "disabled")); } } } @@ -458,11 +458,7 @@ private static void usage(String message) { formatter.printHelp("list", "Lists alert policies.", BASE_OPTIONS, "", true); System.out.println(); formatter.printHelp( - "[backup|restore]", - "Backs up or restores alert policies.", - BACKUP_OPTIONS, - "", - true); + "[backup|restore]", "Backs up or restores alert policies.", BACKUP_OPTIONS, "", true); System.out.println(); formatter.printHelp( "replace-channels", @@ -472,10 +468,6 @@ private static void usage(String message) { true); System.out.println(); formatter.printHelp( - "[enable|disable]", - "Enables/disables alert policies.", - ENABLE_OPTIONS, - "", - true); + "[enable|disable]", "Enables/disables alert policies.", ENABLE_OPTIONS, "", true); } } diff --git a/samples/snippets/src/main/java/com/example/DeleteNotificationChannel.java b/samples/snippets/src/main/java/com/example/DeleteNotificationChannel.java index 4cad86ff..751f8d2d 100644 --- a/samples/snippets/src/main/java/com/example/DeleteNotificationChannel.java +++ b/samples/snippets/src/main/java/com/example/DeleteNotificationChannel.java @@ -18,12 +18,12 @@ import com.google.cloud.monitoring.v3.NotificationChannelServiceClient; import com.google.monitoring.v3.NotificationChannelName; - import java.io.IOException; public class DeleteNotificationChannel { /** * Demonstrates deleting a notification channel by name. + * * @param channelName Name of the notification channel to delete. */ // [START monitoring_alert_delete_channel] diff --git a/samples/snippets/src/main/java/com/example/UptimeSample.java b/samples/snippets/src/main/java/com/example/UptimeSample.java index 77bd0769..bc1c5bfd 100644 --- a/samples/snippets/src/main/java/com/example/UptimeSample.java +++ b/samples/snippets/src/main/java/com/example/UptimeSample.java @@ -32,10 +32,8 @@ import com.google.monitoring.v3.UptimeCheckIp; import com.google.protobuf.Duration; import com.google.protobuf.FieldMask; - import java.io.IOException; import java.util.Optional; - import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; @@ -46,39 +44,44 @@ public class UptimeSample { - private static final Option PROJECT_ID_OPTION = Option.builder("p") - .longOpt("projectid") - .desc("Your Google project id.") - .hasArg() - .argName("PROJECT_ID") - .build(); - private static final Option DISPLAY_NAME_OPTION = Option.builder("n") - .longOpt("name") - .desc("[create/get/delete]: Display name of uptime check.") - .hasArg() - .argName("DISPLAY_NAME") - .required(false) - .build(); - private static final Option HOST_NAME_OPTION = Option.builder("o") - .longOpt("hostname") - .desc("[create]: Host name of uptime check to create.") - .hasArg() - .argName("HOST_NAME") - .required(false) - .build(); - private static final Option PATH_NAME_OPTION = Option.builder("a") - .longOpt("pathname") - .desc("[create/update]: Path name of uptime check to create/update.") - .hasArg() - .argName("HOST_NAME") - .required(false) - .build(); + private static final Option PROJECT_ID_OPTION = + Option.builder("p") + .longOpt("projectid") + .desc("Your Google project id.") + .hasArg() + .argName("PROJECT_ID") + .build(); + private static final Option DISPLAY_NAME_OPTION = + Option.builder("n") + .longOpt("name") + .desc("[create/get/delete]: Display name of uptime check.") + .hasArg() + .argName("DISPLAY_NAME") + .required(false) + .build(); + private static final Option HOST_NAME_OPTION = + Option.builder("o") + .longOpt("hostname") + .desc("[create]: Host name of uptime check to create.") + .hasArg() + .argName("HOST_NAME") + .required(false) + .build(); + private static final Option PATH_NAME_OPTION = + Option.builder("a") + .longOpt("pathname") + .desc("[create/update]: Path name of uptime check to create/update.") + .hasArg() + .argName("HOST_NAME") + .required(false) + .build(); - private static final Options OPTIONS = new Options() - .addOption(PROJECT_ID_OPTION) - .addOption(DISPLAY_NAME_OPTION) - .addOption(HOST_NAME_OPTION) - .addOption(PATH_NAME_OPTION); + private static final Options OPTIONS = + new Options() + .addOption(PROJECT_ID_OPTION) + .addOption(DISPLAY_NAME_OPTION) + .addOption(HOST_NAME_OPTION) + .addOption(PATH_NAME_OPTION); private static final CommandLineParser PARSER = new DefaultParser(); @@ -91,15 +94,14 @@ public static void main(String... args) throws IOException { throw new RuntimeException("Exception parsing command line arguments.", pe); } - String projectId = cl.getOptionValue( - PROJECT_ID_OPTION.getOpt(), - System.getenv("GOOGLE_CLOUD_PROJECT")); + String projectId = + cl.getOptionValue(PROJECT_ID_OPTION.getOpt(), System.getenv("GOOGLE_CLOUD_PROJECT")); - String command = Optional - .of(cl.getArgList()) - .filter(l -> l.size() > 0) - .map(l -> Strings.emptyToNull(l.get(0))) - .orElse(null); + String command = + Optional.of(cl.getArgList()) + .filter(l -> l.size() > 0) + .map(l -> Strings.emptyToNull(l.get(0))) + .orElse(null); if (command == null) { usage(null); return; @@ -111,16 +113,14 @@ public static void main(String... args) throws IOException { projectId, cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check"), cl.getOptionValue(HOST_NAME_OPTION.getOpt(), "example.com"), - cl.getOptionValue(PATH_NAME_OPTION.getOpt(), "/") - ); + cl.getOptionValue(PATH_NAME_OPTION.getOpt(), "/")); break; case "update": updateUptimeCheck( projectId, cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check"), cl.getOptionValue(HOST_NAME_OPTION.getOpt(), "example.com"), - cl.getOptionValue(PATH_NAME_OPTION.getOpt(), "/") - ); + cl.getOptionValue(PATH_NAME_OPTION.getOpt(), "/")); break; case "list": listUptimeChecks(projectId); @@ -130,13 +130,11 @@ public static void main(String... args) throws IOException { break; case "get": getUptimeCheckConfig( - projectId, - cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check")); + projectId, cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check")); break; case "delete": deleteUptimeCheckConfig( - projectId, - cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check")); + projectId, cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check")); break; default: usage(null); @@ -146,23 +144,20 @@ public static void main(String... args) throws IOException { // [START monitoring_uptime_check_create]] private static void createUptimeCheck( String projectId, String displayName, String hostName, String pathName) throws IOException { - CreateUptimeCheckConfigRequest request = CreateUptimeCheckConfigRequest - .newBuilder() - .setParent(ProjectName.format(projectId)) - .setUptimeCheckConfig(UptimeCheckConfig - .newBuilder() - .setDisplayName(displayName) - .setMonitoredResource(MonitoredResource - .newBuilder() - .setType("uptime_url") - .putLabels("host", hostName)) - .setHttpCheck(HttpCheck - .newBuilder() - .setPath(pathName) - .setPort(80)) - .setTimeout(Duration.newBuilder().setSeconds(10)) - .setPeriod(Duration.newBuilder().setSeconds(300))) - .build(); + CreateUptimeCheckConfigRequest request = + CreateUptimeCheckConfigRequest.newBuilder() + .setParent(ProjectName.format(projectId)) + .setUptimeCheckConfig( + UptimeCheckConfig.newBuilder() + .setDisplayName(displayName) + .setMonitoredResource( + MonitoredResource.newBuilder() + .setType("uptime_url") + .putLabels("host", hostName)) + .setHttpCheck(HttpCheck.newBuilder().setPath(pathName).setPort(80)) + .setTimeout(Duration.newBuilder().setSeconds(10)) + .setPeriod(Duration.newBuilder().setSeconds(300))) + .build(); try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) { UptimeCheckConfig config = client.createUptimeCheckConfig(request); System.out.println("Uptime check created: " + config.getDisplayName()); @@ -178,25 +173,20 @@ private static void updateUptimeCheck( String projectId, String displayName, String hostName, String pathName) throws IOException { String fullCheckName = UptimeCheckConfigName.format(projectId, displayName); - UpdateUptimeCheckConfigRequest request = UpdateUptimeCheckConfigRequest - .newBuilder() - .setUpdateMask(FieldMask - .newBuilder() - .addPaths("http_check.path")) - .setUptimeCheckConfig(UptimeCheckConfig - .newBuilder() - .setName(fullCheckName) - .setMonitoredResource(MonitoredResource - .newBuilder() - .setType("uptime_url") - .putLabels("host", hostName)) - .setHttpCheck(HttpCheck - .newBuilder() - .setPath(pathName) - .setPort(80)) - .setTimeout(Duration.newBuilder().setSeconds(10)) - .setPeriod(Duration.newBuilder().setSeconds(300))) - .build(); + UpdateUptimeCheckConfigRequest request = + UpdateUptimeCheckConfigRequest.newBuilder() + .setUpdateMask(FieldMask.newBuilder().addPaths("http_check.path")) + .setUptimeCheckConfig( + UptimeCheckConfig.newBuilder() + .setName(fullCheckName) + .setMonitoredResource( + MonitoredResource.newBuilder() + .setType("uptime_url") + .putLabels("host", hostName)) + .setHttpCheck(HttpCheck.newBuilder().setPath(pathName).setPort(80)) + .setTimeout(Duration.newBuilder().setSeconds(10)) + .setPeriod(Duration.newBuilder().setSeconds(300))) + .build(); try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) { UptimeCheckConfig config = client.updateUptimeCheckConfig(request); System.out.println("Uptime check updated: \n" + config.toString()); @@ -209,10 +199,8 @@ private static void updateUptimeCheck( // [START monitoring_uptime_check_list_configs]] private static void listUptimeChecks(String projectId) throws IOException { - ListUptimeCheckConfigsRequest request = ListUptimeCheckConfigsRequest - .newBuilder() - .setParent(ProjectName.format(projectId)) - .build(); + ListUptimeCheckConfigsRequest request = + ListUptimeCheckConfigsRequest.newBuilder().setParent(ProjectName.format(projectId)).build(); try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) { ListUptimeCheckConfigsPagedResponse response = client.listUptimeCheckConfigs(request); for (UptimeCheckConfig config : response.iterateAll()) { @@ -273,7 +261,11 @@ private static void deleteUptimeCheckConfig(String projectId, String checkName) private static void usage(String message) { Optional.ofNullable(message).ifPresent(System.out::println); HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp("[create|list|listIPs|get|delete]", - "Performs operations on monitoring uptime checks.", OPTIONS, "", true); + formatter.printHelp( + "[create|list|listIPs|get|delete]", + "Performs operations on monitoring uptime checks.", + OPTIONS, + "", + true); } } diff --git a/samples/snippets/src/test/java/com/example/AlertIT.java b/samples/snippets/src/test/java/com/example/AlertIT.java index 55015ff2..bd648cd1 100644 --- a/samples/snippets/src/test/java/com/example/AlertIT.java +++ b/samples/snippets/src/test/java/com/example/AlertIT.java @@ -20,7 +20,6 @@ import com.google.common.base.Strings; import com.google.common.io.Files; - import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -28,7 +27,6 @@ import java.nio.charset.StandardCharsets; import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -37,16 +35,15 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** - * Tests for monitoring "AlertSample" sample. - */ +/** Tests for monitoring "AlertSample" sample. */ @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class AlertIT { private static String testPolicyName = "test-policy"; private static String policyFileName = "target/policyBackup.json"; - private static Pattern policyNameRegex = Pattern.compile( - "alertPolicies/(?.*)(?s).*(?!s)notificationChannels/(?[a-zA-Z0-9]*)$"); + private static Pattern policyNameRegex = + Pattern.compile( + "alertPolicies/(?.*)(?s).*(?!s)notificationChannels/(?[a-zA-Z0-9]*)$"); private ByteArrayOutputStream bout; private PrintStream out; @@ -64,46 +61,43 @@ public void tearDown() { @Test public void testListPolicies() throws IOException { - AlertSample.main(new String[]{"list"}); + AlertSample.main(new String[] {"list"}); assertTrue(bout.toString().contains(testPolicyName)); } @Test public void testBackupPolicies() throws IOException { - AlertSample.main(new String[]{"backup", "-j", policyFileName}); + AlertSample.main(new String[] {"backup", "-j", policyFileName}); File backupFile = new File(policyFileName); assertTrue(backupFile.exists()); - String fileContents = - String.join("\n", Files.readLines(backupFile, StandardCharsets.UTF_8)); + String fileContents = String.join("\n", Files.readLines(backupFile, StandardCharsets.UTF_8)); assertTrue(fileContents.contains("test-policy")); } // TODO(b/78293034): Complete restore backup test when parse/unparse issue is figured out. @Test @Ignore - public void testRestoreBackup() throws IOException { - } + public void testRestoreBackup() throws IOException {} @Test public void testReplaceChannels() throws IOException { // Get a test policy name for the project. - AlertSample.main(new String[]{"list"}); + AlertSample.main(new String[] {"list"}); Matcher matcher = policyNameRegex.matcher(bout.toString()); assertTrue(matcher.find()); String alertId = matcher.group("alertid"); String channel = matcher.group("channel"); Assert.assertFalse(Strings.isNullOrEmpty(alertId)); - AlertSample.main(new String[]{"replace-channels", "-a", alertId, "-c", channel}); + AlertSample.main(new String[] {"replace-channels", "-a", alertId, "-c", channel}); Pattern resultPattern = Pattern.compile("(?s).*Updated .*/alertPolicies/" + alertId); assertTrue(resultPattern.matcher(bout.toString()).find()); } @Test public void testDisableEnablePolicies() throws IOException { - AlertSample.main(new String[]{"disable", "-d", "display_name='test-policy'"}); + AlertSample.main(new String[] {"disable", "-d", "display_name='test-policy'"}); assertTrue(bout.toString().contains("disabled")); - AlertSample.main(new String[]{"enable", "-d", "display_name='test-policy'"}); + AlertSample.main(new String[] {"enable", "-d", "display_name='test-policy'"}); assertTrue(bout.toString().contains("enabled")); - } } diff --git a/samples/snippets/src/test/java/com/example/DeleteNotificationChannelIT.java b/samples/snippets/src/test/java/com/example/DeleteNotificationChannelIT.java index d3f0dad3..5228b131 100644 --- a/samples/snippets/src/test/java/com/example/DeleteNotificationChannelIT.java +++ b/samples/snippets/src/test/java/com/example/DeleteNotificationChannelIT.java @@ -21,11 +21,9 @@ import com.google.cloud.monitoring.v3.NotificationChannelServiceClient; import com.google.monitoring.v3.NotificationChannel; import com.google.monitoring.v3.ProjectName; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; - import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -33,9 +31,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** - * Tests for delete notification channel sample. - */ +/** Tests for delete notification channel sample. */ @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class DeleteNotificationChannelIT { @@ -49,8 +45,8 @@ public class DeleteNotificationChannelIT { private static String getProjectId() { String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME)); if (projectId == null) { - projectId = System.getProperty(LEGACY_PROJECT_ENV_NAME, - System.getenv(LEGACY_PROJECT_ENV_NAME)); + projectId = + System.getProperty(LEGACY_PROJECT_ENV_NAME, System.getenv(LEGACY_PROJECT_ENV_NAME)); } return projectId; } @@ -59,12 +55,13 @@ private static String getProjectId() { public static void setupClass() throws IOException { try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) { String projectId = getProjectId(); - NOTIFICATION_CHANNEL = NotificationChannel.newBuilder() - .setType("email") - .putLabels("email_address", "java-docs-samples-testing@google.com") - .build(); - NotificationChannel channel = client.createNotificationChannel(ProjectName.of(projectId), - NOTIFICATION_CHANNEL); + NOTIFICATION_CHANNEL = + NotificationChannel.newBuilder() + .setType("email") + .putLabels("email_address", "java-docs-samples-testing@google.com") + .build(); + NotificationChannel channel = + client.createNotificationChannel(ProjectName.of(projectId), NOTIFICATION_CHANNEL); NOTIFICATION_CHANNEL_NAME = channel.getName(); } } diff --git a/samples/snippets/src/test/java/com/example/UptimeIT.java b/samples/snippets/src/test/java/com/example/UptimeIT.java index 3bed7dac..41d59650 100644 --- a/samples/snippets/src/test/java/com/example/UptimeIT.java +++ b/samples/snippets/src/test/java/com/example/UptimeIT.java @@ -19,11 +19,9 @@ import static com.google.common.truth.Truth.assertThat; import com.google.monitoring.v3.UptimeCheckConfig; - import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.UUID; - import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; @@ -32,9 +30,7 @@ import org.junit.runners.JUnit4; import org.junit.runners.MethodSorters; -/** - * Integration (system) tests for {@link UptimeSample}. - */ +/** Integration (system) tests for {@link UptimeSample}. */ @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") @FixMethodOrder(MethodSorters.NAME_ASCENDING) @@ -42,10 +38,10 @@ public class UptimeIT { private ByteArrayOutputStream bout; private PrintStream out; - private static UptimeCheckConfig config = UptimeCheckConfig - .newBuilder() - .setDisplayName("check-" + UUID.randomUUID().toString().substring(0, 6)) - .build(); + private static UptimeCheckConfig config = + UptimeCheckConfig.newBuilder() + .setDisplayName("check-" + UUID.randomUUID().toString().substring(0, 6)) + .build(); @BeforeClass public static void setUpClass() { @@ -63,10 +59,8 @@ public void setUp() { @Test public void test1_CreateUptimeCheck() throws Exception { - UptimeSample.main( - "create", "-n", config.getDisplayName(), "-o", "test.example.com", "-a", "/"); + UptimeSample.main("create", "-n", config.getDisplayName(), "-o", "test.example.com", "-a", "/"); assertThat(bout.toString()).contains("Uptime check created: " + config.getDisplayName()); - } @Test From 8a1f9576d0099e46f0cf22b13ea25e47dbee7360 Mon Sep 17 00:00:00 2001 From: Mike <45373284+munkhuushmgl@users.noreply.github.com> Date: Wed, 15 Apr 2020 12:56:44 -0700 Subject: [PATCH 32/45] samples: Fix flaky tests (#2668) * Fixed flaky tests * reverted back --- samples/snippets/src/test/java/com/example/AlertIT.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/snippets/src/test/java/com/example/AlertIT.java b/samples/snippets/src/test/java/com/example/AlertIT.java index bd648cd1..e34d2fd6 100644 --- a/samples/snippets/src/test/java/com/example/AlertIT.java +++ b/samples/snippets/src/test/java/com/example/AlertIT.java @@ -95,9 +95,9 @@ public void testReplaceChannels() throws IOException { @Test public void testDisableEnablePolicies() throws IOException { - AlertSample.main(new String[] {"disable", "-d", "display_name='test-policy'"}); - assertTrue(bout.toString().contains("disabled")); AlertSample.main(new String[] {"enable", "-d", "display_name='test-policy'"}); assertTrue(bout.toString().contains("enabled")); + AlertSample.main(new String[] {"disable", "-d", "display_name='test-policy'"}); + assertTrue(bout.toString().contains("disabled")); } } From 8bb87babefc247e89879e6df4fd049ee64d2a99e Mon Sep 17 00:00:00 2001 From: Mike <45373284+munkhuushmgl@users.noreply.github.com> Date: Wed, 15 Apr 2020 15:46:44 -0700 Subject: [PATCH 33/45] samples: Fix monitor test (#2669) * Fixed flaky tests * reverted back * added condition for disable/enable testing --- .../src/test/java/com/example/AlertIT.java | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/samples/snippets/src/test/java/com/example/AlertIT.java b/samples/snippets/src/test/java/com/example/AlertIT.java index e34d2fd6..d611c873 100644 --- a/samples/snippets/src/test/java/com/example/AlertIT.java +++ b/samples/snippets/src/test/java/com/example/AlertIT.java @@ -96,8 +96,22 @@ public void testReplaceChannels() throws IOException { @Test public void testDisableEnablePolicies() throws IOException { AlertSample.main(new String[] {"enable", "-d", "display_name='test-policy'"}); - assertTrue(bout.toString().contains("enabled")); - AlertSample.main(new String[] {"disable", "-d", "display_name='test-policy'"}); - assertTrue(bout.toString().contains("disabled")); + + // check the current state of policy to make sure + // not to enable the policy that is already enabled. + boolean isEnabled = bout.toString().contains("already"); + if (isEnabled) { + AlertSample.main(new String[] {"disable", "-d", "display_name='test-policy'"}); + assertTrue(bout.toString().contains("disabled")); + + AlertSample.main(new String[] {"enable", "-d", "display_name='test-policy'"}); + assertTrue(bout.toString().contains("enabled")); + } else { + AlertSample.main(new String[] {"enable", "-d", "display_name='test-policy'"}); + assertTrue(bout.toString().contains("enabled")); + + AlertSample.main(new String[] {"disable", "-d", "display_name='test-policy'"}); + assertTrue(bout.toString().contains("disabled")); + } } } From b1f7c2c049eb6d8a47c9a622b5c550ad4112dd96 Mon Sep 17 00:00:00 2001 From: Jeff Ching Date: Fri, 14 Aug 2020 14:17:37 -0700 Subject: [PATCH 34/45] samples: fix dependency declarations --- samples/install-without-bom/pom.xml | 12 ++++++++++++ samples/snapshot/pom.xml | 12 +++++++++++- samples/snippets/pom.xml | 11 ++++++++++- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/samples/install-without-bom/pom.xml b/samples/install-without-bom/pom.xml index 473f1171..11b6c696 100644 --- a/samples/install-without-bom/pom.xml +++ b/samples/install-without-bom/pom.xml @@ -33,6 +33,18 @@ + + + + com.google.auth + google-auth-library-oauth2-http + 0.21.1 + + + commons-cli + commons-cli + 1.4 + com.google.protobuf protobuf-java-util diff --git a/samples/snapshot/pom.xml b/samples/snapshot/pom.xml index b5e2dfe1..c4efebf2 100644 --- a/samples/snapshot/pom.xml +++ b/samples/snapshot/pom.xml @@ -31,12 +31,22 @@ 2.0.1 + + + com.google.auth + google-auth-library-oauth2-http + 0.21.1 + + + commons-cli + commons-cli + 1.4 + com.google.protobuf protobuf-java-util 3.12.4 - junit junit diff --git a/samples/snippets/pom.xml b/samples/snippets/pom.xml index 7e599af5..8629c84c 100644 --- a/samples/snippets/pom.xml +++ b/samples/snippets/pom.xml @@ -43,10 +43,19 @@ google-cloud-monitoring + + + com.google.auth + google-auth-library-oauth2-http + + + commons-cli + commons-cli + 1.4 + com.google.protobuf protobuf-java-util - 3.12.4 junit From 4f00cb5c448718402abe41afd4a50017514a61ea Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Fri, 14 Aug 2020 15:48:55 -0700 Subject: [PATCH 35/45] chore: regenerate samples list (#234) autosynth cannot find the source of changes triggered by earlier changes in this repository, or by version upgrades to tools such as linters. --- README.md | 6 +++++- synth.metadata | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c0724400..69e57f5c 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ If you are using Maven without BOM, add this to your dependencies: com.google.cloud google-cloud-monitoring - 2.0.0 + 2.0.1 ``` @@ -94,7 +94,11 @@ has instructions for running the samples. | Sample | Source Code | Try it | | --------------------------- | --------------------------------- | ------ | +| Alert Sample | [source code](https://github.com/googleapis/java-monitoring/blob/master/samples/snippets/src/main/java/com/example/AlertSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-monitoring&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/AlertSample.java) | +| Delete Notification Channel | [source code](https://github.com/googleapis/java-monitoring/blob/master/samples/snippets/src/main/java/com/example/DeleteNotificationChannel.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-monitoring&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/DeleteNotificationChannel.java) | +| Uptime Sample | [source code](https://github.com/googleapis/java-monitoring/blob/master/samples/snippets/src/main/java/com/example/UptimeSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-monitoring&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/UptimeSample.java) | | Quickstart Sample | [source code](https://github.com/googleapis/java-monitoring/blob/master/samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-monitoring&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/monitoring/QuickstartSample.java) | +| Snippets | [source code](https://github.com/googleapis/java-monitoring/blob/master/samples/snippets/src/main/java/com/example/monitoring/Snippets.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-monitoring&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/monitoring/Snippets.java) | diff --git a/synth.metadata b/synth.metadata index 4210f29d..513c6254 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/java-monitoring.git", - "sha": "802393532d8bcaf9fc78313f35eedadd1779a686" + "sha": "aa7579406070baaa3aeea55ccd5bf73e1342f059" } }, { From 46e0f83caa40aa3f8e8c625abe763caa467083f7 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Fri, 14 Aug 2020 22:54:03 +0000 Subject: [PATCH 36/45] chore: release 2.0.2-SNAPSHOT (#233) :robot: I have created a release \*beep\* \*boop\* --- ### Updating meta-information for bleeding-edge SNAPSHOT release. --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). --- google-cloud-monitoring-bom/pom.xml | 8 ++++---- google-cloud-monitoring/pom.xml | 4 ++-- grpc-google-cloud-monitoring-v3/pom.xml | 4 ++-- pom.xml | 8 ++++---- proto-google-cloud-monitoring-v3/pom.xml | 4 ++-- samples/install-without-bom/pom.xml | 2 +- samples/snapshot/pom.xml | 2 +- versions.txt | 6 +++--- 8 files changed, 19 insertions(+), 19 deletions(-) diff --git a/google-cloud-monitoring-bom/pom.xml b/google-cloud-monitoring-bom/pom.xml index 6959bb6b..3e8a9a10 100644 --- a/google-cloud-monitoring-bom/pom.xml +++ b/google-cloud-monitoring-bom/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.google.cloud google-cloud-monitoring-bom - 2.0.1 + 2.0.2-SNAPSHOT pom com.google.cloud @@ -64,17 +64,17 @@ com.google.cloud google-cloud-monitoring - 2.0.1 + 2.0.2-SNAPSHOT com.google.api.grpc grpc-google-cloud-monitoring-v3 - 2.0.1 + 2.0.2-SNAPSHOT com.google.api.grpc proto-google-cloud-monitoring-v3 - 2.0.1 + 2.0.2-SNAPSHOT diff --git a/google-cloud-monitoring/pom.xml b/google-cloud-monitoring/pom.xml index c1f0bfd6..27fedd91 100644 --- a/google-cloud-monitoring/pom.xml +++ b/google-cloud-monitoring/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.google.cloud google-cloud-monitoring - 2.0.1 + 2.0.2-SNAPSHOT jar Google Cloud Monitoring https://github.com/googleapis/java-monitoring @@ -11,7 +11,7 @@ com.google.cloud google-cloud-monitoring-parent - 2.0.1 + 2.0.2-SNAPSHOT google-cloud-monitoring diff --git a/grpc-google-cloud-monitoring-v3/pom.xml b/grpc-google-cloud-monitoring-v3/pom.xml index 1680ac30..6be624a9 100644 --- a/grpc-google-cloud-monitoring-v3/pom.xml +++ b/grpc-google-cloud-monitoring-v3/pom.xml @@ -4,13 +4,13 @@ 4.0.0 com.google.api.grpc grpc-google-cloud-monitoring-v3 - 2.0.1 + 2.0.2-SNAPSHOT grpc-google-cloud-monitoring-v3 GRPC library for grpc-google-cloud-monitoring-v3 com.google.cloud google-cloud-monitoring-parent - 2.0.1 + 2.0.2-SNAPSHOT diff --git a/pom.xml b/pom.xml index 402a05b2..23ba9089 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.google.cloud google-cloud-monitoring-parent pom - 2.0.1 + 2.0.2-SNAPSHOT Google Cloud Monitoring Parent https://github.com/googleapis/java-monitoring @@ -70,17 +70,17 @@ com.google.api.grpc proto-google-cloud-monitoring-v3 - 2.0.1 + 2.0.2-SNAPSHOT com.google.api.grpc grpc-google-cloud-monitoring-v3 - 2.0.1 + 2.0.2-SNAPSHOT com.google.cloud google-cloud-monitoring - 2.0.1 + 2.0.2-SNAPSHOT diff --git a/proto-google-cloud-monitoring-v3/pom.xml b/proto-google-cloud-monitoring-v3/pom.xml index 05009fa5..5c7028cd 100644 --- a/proto-google-cloud-monitoring-v3/pom.xml +++ b/proto-google-cloud-monitoring-v3/pom.xml @@ -4,13 +4,13 @@ 4.0.0 com.google.api.grpc proto-google-cloud-monitoring-v3 - 2.0.1 + 2.0.2-SNAPSHOT proto-google-cloud-monitoring-v3 PROTO library for proto-google-cloud-monitoring-v3 com.google.cloud google-cloud-monitoring-parent - 2.0.1 + 2.0.2-SNAPSHOT diff --git a/samples/install-without-bom/pom.xml b/samples/install-without-bom/pom.xml index 11b6c696..ee757d81 100644 --- a/samples/install-without-bom/pom.xml +++ b/samples/install-without-bom/pom.xml @@ -29,7 +29,7 @@ com.google.cloud google-cloud-monitoring - 2.0.1 + 2.0.2-SNAPSHOT diff --git a/samples/snapshot/pom.xml b/samples/snapshot/pom.xml index c4efebf2..78a31a6e 100644 --- a/samples/snapshot/pom.xml +++ b/samples/snapshot/pom.xml @@ -28,7 +28,7 @@ com.google.cloud google-cloud-monitoring - 2.0.1 + 2.0.2-SNAPSHOT diff --git a/versions.txt b/versions.txt index 4933a4cb..e683c38b 100644 --- a/versions.txt +++ b/versions.txt @@ -1,6 +1,6 @@ # Format: # module:released-version:current-version -proto-google-cloud-monitoring-v3:2.0.1:2.0.1 -grpc-google-cloud-monitoring-v3:2.0.1:2.0.1 -google-cloud-monitoring:2.0.1:2.0.1 \ No newline at end of file +proto-google-cloud-monitoring-v3:2.0.1:2.0.2-SNAPSHOT +grpc-google-cloud-monitoring-v3:2.0.1:2.0.2-SNAPSHOT +google-cloud-monitoring:2.0.1:2.0.2-SNAPSHOT \ No newline at end of file From 1264529d9e7130b8c4f1d0290deb74ae08039c59 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 18 Aug 2020 00:04:15 +0200 Subject: [PATCH 37/45] chore(deps): update dependency com.google.cloud:libraries-bom to v9.1.0 --- samples/snippets/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/pom.xml b/samples/snippets/pom.xml index 8629c84c..afbefad6 100644 --- a/samples/snippets/pom.xml +++ b/samples/snippets/pom.xml @@ -30,7 +30,7 @@ com.google.cloud libraries-bom - 9.0.0 + 9.1.0 pom import From 5b09dfc50ef6df3b5e232cea2661b514c30ce145 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 18 Aug 2020 20:11:00 +0200 Subject: [PATCH 38/45] deps: update dependency com.google.protobuf:protobuf-java-util to v3.13.0 (#235) --- samples/install-without-bom/pom.xml | 2 +- samples/snapshot/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/install-without-bom/pom.xml b/samples/install-without-bom/pom.xml index ee757d81..c4c8d93d 100644 --- a/samples/install-without-bom/pom.xml +++ b/samples/install-without-bom/pom.xml @@ -48,7 +48,7 @@ com.google.protobuf protobuf-java-util - 3.12.4 + 3.13.0 diff --git a/samples/snapshot/pom.xml b/samples/snapshot/pom.xml index 78a31a6e..4d3b1816 100644 --- a/samples/snapshot/pom.xml +++ b/samples/snapshot/pom.xml @@ -45,7 +45,7 @@ com.google.protobuf protobuf-java-util - 3.12.4 + 3.13.0 junit From a1a1edb83386ed9ae65ac097664cb53802e9be18 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Thu, 20 Aug 2020 15:38:24 -0700 Subject: [PATCH 39/45] samples: add presubmit lint check (#242) This PR was generated using Autosynth. :rainbow: Synth log will be available here: https://source.cloud.google.com/results/invocations/a79f8a17-dbb5-42d4-99e9-73d2b5ffda4d/targets - [ ] To automatically regenerate this PR, check this box. Source-Link: https://github.com/googleapis/synthtool/commit/9602086c6c5b05db77950c7f7495a2a3868f3537 Source-Link: https://github.com/googleapis/synthtool/commit/c3caf0704f25a0c365f1c315e804a30b87c62a75 --- .github/workflows/samples.yaml | 14 ++++++++++++++ README.md | 4 ++-- synth.metadata | 5 +++-- 3 files changed, 19 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/samples.yaml diff --git a/.github/workflows/samples.yaml b/.github/workflows/samples.yaml new file mode 100644 index 00000000..a1d50073 --- /dev/null +++ b/.github/workflows/samples.yaml @@ -0,0 +1,14 @@ +on: + pull_request: +name: samples +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: 8 + - name: Run checkstyle + run: mvn -P lint --quiet --batch-mode checkstyle:check + working-directory: samples/snippets diff --git a/README.md b/README.md index 69e57f5c..4733db6e 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ If you are using Maven with [BOM][libraries-bom], add this to your pom.xml file com.google.cloud libraries-bom - 9.0.0 + 9.1.0 pom import @@ -39,7 +39,7 @@ If you are using Maven without BOM, add this to your dependencies: com.google.cloud google-cloud-monitoring - 2.0.1 + 2.0.2-SNAPSHOT ``` diff --git a/synth.metadata b/synth.metadata index 513c6254..956abf50 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/java-monitoring.git", - "sha": "aa7579406070baaa3aeea55ccd5bf73e1342f059" + "sha": "5b09dfc50ef6df3b5e232cea2661b514c30ce145" } }, { @@ -19,7 +19,7 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "f8823dec98277a9516f2fb6fae9f58b3a59a23e1" + "sha": "9602086c6c5b05db77950c7f7495a2a3868f3537" } } ], @@ -43,6 +43,7 @@ ".github/release-please.yml", ".github/trusted-contribution.yml", ".github/workflows/ci.yaml", + ".github/workflows/samples.yaml", ".kokoro/build.bat", ".kokoro/build.sh", ".kokoro/coerce_logs.sh", From 5c4f9a8c2fb9aa1f187337dfdae670d06816742e Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Wed, 26 Aug 2020 09:31:56 -0700 Subject: [PATCH 40/45] build: temporarily disable reporting to unblock releases Source-Author: Stephanie Wang Source-Date: Tue Aug 25 13:05:26 2020 -0400 Source-Repo: googleapis/synthtool Source-Sha: 968465a1cad496e1292ef4584a054a35f756ff94 Source-Link: https://github.com/googleapis/synthtool/commit/968465a1cad496e1292ef4584a054a35f756ff94 --- .kokoro/release/stage.sh | 5 +++-- synth.metadata | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.kokoro/release/stage.sh b/.kokoro/release/stage.sh index 3c482cbc..d19191fc 100755 --- a/.kokoro/release/stage.sh +++ b/.kokoro/release/stage.sh @@ -16,8 +16,9 @@ set -eo pipefail # Start the releasetool reporter -python3 -m pip install gcp-releasetool -python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script +# Disable reporting due to issue observed with Kokoro blocking releases +# python3 -m pip install gcp-releasetool +# python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script source $(dirname "$0")/common.sh MAVEN_SETTINGS_FILE=$(realpath $(dirname "$0")/../../)/settings.xml diff --git a/synth.metadata b/synth.metadata index 956abf50..e077cbd6 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/java-monitoring.git", - "sha": "5b09dfc50ef6df3b5e232cea2661b514c30ce145" + "sha": "a1a1edb83386ed9ae65ac097664cb53802e9be18" } }, { @@ -19,7 +19,7 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "9602086c6c5b05db77950c7f7495a2a3868f3537" + "sha": "968465a1cad496e1292ef4584a054a35f756ff94" } } ], From a9936b61c3dc4c79d1d3c1fd02749637d4ca080a Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Thu, 27 Aug 2020 09:27:15 -0700 Subject: [PATCH 41/45] build(java): switch to release-publish app for notifying GitHub of release status Source-Author: Jeff Ching Source-Date: Wed Aug 26 21:48:06 2020 -0700 Source-Repo: googleapis/synthtool Source-Sha: 019c7168faa0e56619f792693a8acdb30d6de19b Source-Link: https://github.com/googleapis/synthtool/commit/019c7168faa0e56619f792693a8acdb30d6de19b --- .kokoro/release/stage.cfg | 31 +++---------------------------- .kokoro/release/stage.sh | 5 ++--- synth.metadata | 4 ++-- 3 files changed, 7 insertions(+), 33 deletions(-) diff --git a/.kokoro/release/stage.cfg b/.kokoro/release/stage.cfg index d92a905d..ac1f6e5a 100644 --- a/.kokoro/release/stage.cfg +++ b/.kokoro/release/stage.cfg @@ -13,32 +13,7 @@ action { } } -# Fetch the token needed for reporting release status to GitHub -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "yoshi-automation-github-key" - } - } -} - -# Fetch magictoken to use with Magic Github Proxy -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "releasetool-magictoken" - } - } -} - -# Fetch api key to use with Magic Github Proxy -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "magic-github-proxy-api-key" - } - } +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" } diff --git a/.kokoro/release/stage.sh b/.kokoro/release/stage.sh index d19191fc..3c482cbc 100755 --- a/.kokoro/release/stage.sh +++ b/.kokoro/release/stage.sh @@ -16,9 +16,8 @@ set -eo pipefail # Start the releasetool reporter -# Disable reporting due to issue observed with Kokoro blocking releases -# python3 -m pip install gcp-releasetool -# python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script +python3 -m pip install gcp-releasetool +python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script source $(dirname "$0")/common.sh MAVEN_SETTINGS_FILE=$(realpath $(dirname "$0")/../../)/settings.xml diff --git a/synth.metadata b/synth.metadata index e077cbd6..de27b508 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/java-monitoring.git", - "sha": "a1a1edb83386ed9ae65ac097664cb53802e9be18" + "sha": "5c4f9a8c2fb9aa1f187337dfdae670d06816742e" } }, { @@ -19,7 +19,7 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "968465a1cad496e1292ef4584a054a35f756ff94" + "sha": "019c7168faa0e56619f792693a8acdb30d6de19b" } } ], From 3dbf19dc0d6c4a36ba4b41c651ff404b07941959 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 8 Sep 2020 21:26:32 +0200 Subject: [PATCH 42/45] deps: update dependency com.google.cloud:google-cloud-shared-dependencies to v0.9.0 (#248) This PR contains the following updates: | Package | Update | Change | |---|---|---| | [com.google.cloud:google-cloud-shared-dependencies](https://togithub.com/googleapis/java-shared-dependencies) | minor | `0.8.6` -> `0.9.0` | --- ### Release Notes

googleapis/java-shared-dependencies ### [`v0.9.0`](https://togithub.com/googleapis/java-shared-dependencies/blob/master/CHANGELOG.md#​090-httpswwwgithubcomgoogleapisjava-shared-dependenciescompare086v090-2020-08-31) [Compare Source](https://togithub.com/googleapis/java-shared-dependencies/compare/v0.8.6...v0.9.0) ##### Bug Fixes - temporarily disable reporting to unblock releases ([#​129](https://www.github.com/googleapis/java-shared-dependencies/issues/129)) ([7fff6f2](https://www.github.com/googleapis/java-shared-dependencies/commit/7fff6f2c94a19ba998d8cd47e8be5a6333808df8)) ##### Dependencies - update dependency com.google.protobuf:protobuf-bom to v3.13.0 ([#​126](https://www.github.com/googleapis/java-shared-dependencies/issues/126)) ([908063f](https://www.github.com/googleapis/java-shared-dependencies/commit/908063f9b820dd3195b15537189e45be0d4acbbb)) - update dependency io.grpc:grpc-bom to v1.31.1 ([#​124](https://www.github.com/googleapis/java-shared-dependencies/issues/124)) ([553a339](https://www.github.com/googleapis/java-shared-dependencies/commit/553a3393f5bede0e90e16e2d0d87daa2b936ab32)) - update google.common-protos.version to v1.18.1 ([#​119](https://www.github.com/googleapis/java-shared-dependencies/issues/119)) ([05ad27e](https://www.github.com/googleapis/java-shared-dependencies/commit/05ad27e35fe082e148d377315b10943b187b5670)) - update google.core.version to v1.93.8 ([f72cef3](https://www.github.com/googleapis/java-shared-dependencies/commit/f72cef3d78a036e2b2434bf08b0a75d57b2fa139)) - update iam.version to v0.15.0 ([#​118](https://www.github.com/googleapis/java-shared-dependencies/issues/118)) ([1409a16](https://www.github.com/googleapis/java-shared-dependencies/commit/1409a16826d3fd4a5d9cbcbe46ea4b4af8687a5c)) - update iam.version to v1 (major) ([#​120](https://www.github.com/googleapis/java-shared-dependencies/issues/120)) ([a6243a0](https://www.github.com/googleapis/java-shared-dependencies/commit/a6243a02129e42fec804b5769fb8e3f334ba84ce)) ##### [0.8.6](https://www.github.com/googleapis/java-shared-dependencies/compare/v0.8.5...v0.8.6) (2020-08-07) ##### Dependencies - update gax to v1.58.2 ([#​115](https://www.github.com/googleapis/java-shared-dependencies/issues/115)) ([84b48b4](https://www.github.com/googleapis/java-shared-dependencies/commit/84b48b4e77a4b5b4a2db6030609abe241d5ee2e1)) ##### [0.8.5](https://www.github.com/googleapis/java-shared-dependencies/compare/v0.8.4...v0.8.5) (2020-08-07) ##### Dependencies - update gax to v1.58.1 ([#​111](https://www.github.com/googleapis/java-shared-dependencies/issues/111)) ([93a1691](https://www.github.com/googleapis/java-shared-dependencies/commit/93a16915b863a610ffdabe0e23aec58c4ae5f4f1)) ##### [0.8.4](https://www.github.com/googleapis/java-shared-dependencies/compare/v0.8.3...v0.8.4) (2020-08-04) ##### Dependencies - update core dependencies ([#​104](https://www.github.com/googleapis/java-shared-dependencies/issues/104)) ([5046818](https://www.github.com/googleapis/java-shared-dependencies/commit/504681803d2bba888404acffe9a8853746501358)) - update dependency com.google.api:api-common to v1.10.0 ([#​101](https://www.github.com/googleapis/java-shared-dependencies/issues/101)) ([6472fac](https://www.github.com/googleapis/java-shared-dependencies/commit/6472face89700e3f2f982c04a5e88801876580be)) - update dependency com.google.protobuf:protobuf-bom to v3.12.4 ([#​103](https://www.github.com/googleapis/java-shared-dependencies/issues/103)) ([885bd0e](https://www.github.com/googleapis/java-shared-dependencies/commit/885bd0ef3c9e344bd1fc60e0f3264995064001d9)) ##### [0.8.3](https://www.github.com/googleapis/java-shared-dependencies/compare/v0.8.2...v0.8.3) (2020-07-09) ##### Dependencies - update core dependencies ([#​96](https://www.github.com/googleapis/java-shared-dependencies/issues/96)) ([978e69e](https://www.github.com/googleapis/java-shared-dependencies/commit/978e69e9b5999630354ea204c034be2d6b8a2d80)) - update dependency com.google.api-client:google-api-client-bom to v1.30.10 ([#​99](https://www.github.com/googleapis/java-shared-dependencies/issues/99)) ([65c9cce](https://www.github.com/googleapis/java-shared-dependencies/commit/65c9ccea34275fa6f9599043d6e06df169bc433a)) - update dependency com.google.api:api-common to v1.9.3 ([#​91](https://www.github.com/googleapis/java-shared-dependencies/issues/91)) ([2a23a50](https://www.github.com/googleapis/java-shared-dependencies/commit/2a23a50ee5c73b581a02171048e20b14f999949f)) ##### [0.8.2](https://www.github.com/googleapis/java-shared-dependencies/compare/v0.8.1...v0.8.2) (2020-07-01) ##### Dependencies - update dependency com.google.auth:google-auth-library-bom to v0.21.0 ([#​86](https://www.github.com/googleapis/java-shared-dependencies/issues/86)) ([dc9d717](https://www.github.com/googleapis/java-shared-dependencies/commit/dc9d717fdec4f0962141ba34e98f5737ec3bc57a)) - update dependency com.google.http-client:google-http-client-bom to v1.36.0 ([#​89](https://www.github.com/googleapis/java-shared-dependencies/issues/89)) ([12437d7](https://www.github.com/googleapis/java-shared-dependencies/commit/12437d7392a430299c3372d18d2650b62be60eaf)) - update dependency io.grpc:grpc-bom to v1.30.1 ([#​82](https://www.github.com/googleapis/java-shared-dependencies/issues/82)) ([a5199a0](https://www.github.com/googleapis/java-shared-dependencies/commit/a5199a02d5bde75e86349b37c1efae64a6379a40)) - update dependency io.grpc:grpc-bom to v1.30.2 ([#​85](https://www.github.com/googleapis/java-shared-dependencies/issues/85)) ([084d18d](https://www.github.com/googleapis/java-shared-dependencies/commit/084d18daab010c6b0be04e67b42ca8ab8ba5f3d5)) ##### [0.8.1](https://www.github.com/googleapis/java-shared-dependencies/compare/v0.8.0...v0.8.1) (2020-06-13) ##### Reverts - Revert "feat: mark javax annotations scope as provided ([#​70](https://togithub.com/googleapis/java-shared-dependencies/issues/70))" ([#​75](https://togithub.com/googleapis/java-shared-dependencies/issues/75)) ([d2f23ec](https://www.github.com/googleapis/java-shared-dependencies/commit/d2f23ecae56a1ec07b1217f0fca5347dd0f0406b)), closes [#​70](https://www.github.com/googleapis/java-shared-dependencies/issues/70) [#​75](https://www.github.com/googleapis/java-shared-dependencies/issues/75)
--- ### Renovate configuration :date: **Schedule**: At any time (no schedule defined). :vertical_traffic_light: **Automerge**: Disabled by config. Please merge this manually once you are satisfied. :recycle: **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. :no_bell: **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/java-monitoring). --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 23ba9089..8cb01692 100644 --- a/pom.xml +++ b/pom.xml @@ -86,7 +86,7 @@ com.google.cloud google-cloud-shared-dependencies - 0.8.6 + 0.9.0 pom import From 2661e1126823159dc73cbf6a32a69f103891c68c Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Thu, 10 Sep 2020 22:02:07 +0200 Subject: [PATCH 43/45] build(deps): update dependency org.apache.maven.plugins:maven-project-info-reports-plugin to v3.1.1 (#249) This PR contains the following updates: | Package | Update | Change | |---|---|---| | org.apache.maven.plugins:maven-project-info-reports-plugin | patch | `3.1.0` -> `3.1.1` | --- ### Renovate configuration :date: **Schedule**: At any time (no schedule defined). :vertical_traffic_light: **Automerge**: Disabled by config. Please merge this manually once you are satisfied. :recycle: **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. :no_bell: **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/java-monitoring). --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 8cb01692..dc5707d2 100644 --- a/pom.xml +++ b/pom.xml @@ -129,7 +129,7 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 3.1.0 + 3.1.1 From cd90b3f97a381f5434a5bb39db5a43355513f6a5 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Mon, 21 Sep 2020 14:45:48 -0700 Subject: [PATCH 44/45] build(ci): enable auto-release for dependency-update-only releases Automatically perform a Java client library release when: 1. Only dependency updates are going out in the release since any releases containing bug fixes, build changes or new features should be supervised; 2. There are no outstanding/open dependency update pull requests in the repo. This is to avoid multiple/redundant releases; 3. It is a SNAPSHOT release which is automatically generated post regular release -- this requires no human supervision. Testing done in 5 java-bigquery* client library repos. Example: [chore: release 0.3.4 ](https://github.com/googleapis/java-bigqueryconnection/pull/130) [chore: release 0.3.5-SNAPSHOT](https://github.com/googleapis/java-bigqueryconnection/pull/131) Source-Author: Stephanie Wang Source-Date: Thu Sep 17 15:30:02 2020 -0400 Source-Repo: googleapis/synthtool Source-Sha: 538a68019eb4a36a0cdfa4021f324dd01b784395 Source-Link: https://github.com/googleapis/synthtool/commit/538a68019eb4a36a0cdfa4021f324dd01b784395 --- .github/workflows/auto-release.yaml | 69 +++++++++++++++++++++++++++++ synth.metadata | 5 ++- 2 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/auto-release.yaml diff --git a/.github/workflows/auto-release.yaml b/.github/workflows/auto-release.yaml new file mode 100644 index 00000000..d26427e4 --- /dev/null +++ b/.github/workflows/auto-release.yaml @@ -0,0 +1,69 @@ +on: + pull_request: +name: auto-release +jobs: + approve: + runs-on: ubuntu-latest + steps: + - uses: actions/github-script@v3.0.0 + with: + github-token: ${{secrets.GITHUB_TOKEN}} + debug: true + script: | + // only approve PRs from release-please[bot] + if (context.payload.pull_request.user.login !== "release-please[bot]") { + return; + } + + // only approve PRs like "chore: release " + if ( !context.payload.pull_request.title.startsWith("chore: release") ) { + return; + } + + // trigger auto-release when + // 1) it is a SNAPSHOT release (auto-generated post regular release) + // 2) there are dependency updates only + // 3) there are no open dependency update PRs in this repo (to avoid multiple releases) + if ( + context.payload.pull_request.body.includes("Fix") || + context.payload.pull_request.body.includes("Build") || + context.payload.pull_request.body.includes("Documentation") || + context.payload.pull_request.body.includes("BREAKING CHANGES") || + context.payload.pull_request.body.includes("Features") + ) { + console.log( "Not auto-releasing since it is not a dependency-update-only release." ); + return; + } + + const promise = github.pulls.list.endpoint({ + owner: context.repo.owner, + repo: context.repo.repo, + state: 'open' + }); + const open_pulls = await github.paginate(promise) + + if ( open_pulls.length > 1 && !context.payload.pull_request.title.includes("SNAPSHOT") ) { + for ( const pull of open_pulls ) { + if ( pull.title.startsWith("deps: update dependency") ) { + console.log( "Not auto-releasing yet since there are dependency update PRs open in this repo." ); + return; + } + } + } + + // approve release PR + await github.pulls.createReview({ + owner: context.repo.owner, + repo: context.repo.repo, + body: 'Rubber stamped release!', + pull_number: context.payload.pull_request.number, + event: 'APPROVE' + }); + + // attach kokoro:force-run and automerge labels + await github.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + labels: ['kokoro:force-run', 'automerge'] + }); \ No newline at end of file diff --git a/synth.metadata b/synth.metadata index de27b508..36a6cfd5 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/java-monitoring.git", - "sha": "5c4f9a8c2fb9aa1f187337dfdae670d06816742e" + "sha": "2661e1126823159dc73cbf6a32a69f103891c68c" } }, { @@ -19,7 +19,7 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "019c7168faa0e56619f792693a8acdb30d6de19b" + "sha": "538a68019eb4a36a0cdfa4021f324dd01b784395" } } ], @@ -42,6 +42,7 @@ ".github/PULL_REQUEST_TEMPLATE.md", ".github/release-please.yml", ".github/trusted-contribution.yml", + ".github/workflows/auto-release.yaml", ".github/workflows/ci.yaml", ".github/workflows/samples.yaml", ".kokoro/build.bat", From 76bddedeacb96cfcf4e8d474d4a5826d664320d1 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 21 Sep 2020 22:06:06 +0000 Subject: [PATCH 45/45] chore: release 2.0.2 (#240) :robot: I have created a release \*beep\* \*boop\* --- ### [2.0.2](https://www.github.com/googleapis/java-monitoring/compare/v2.0.1...v2.0.2) (2020-09-21) ### Dependencies * update dependency com.google.cloud:google-cloud-shared-dependencies to v0.9.0 ([#248](https://www.github.com/googleapis/java-monitoring/issues/248)) ([3dbf19d](https://www.github.com/googleapis/java-monitoring/commit/3dbf19dc0d6c4a36ba4b41c651ff404b07941959)) * update dependency com.google.protobuf:protobuf-java-util to v3.13.0 ([#235](https://www.github.com/googleapis/java-monitoring/issues/235)) ([5b09dfc](https://www.github.com/googleapis/java-monitoring/commit/5b09dfc50ef6df3b5e232cea2661b514c30ce145)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). --- CHANGELOG.md | 8 ++++++++ README.md | 4 ++-- google-cloud-monitoring-bom/pom.xml | 8 ++++---- google-cloud-monitoring/pom.xml | 4 ++-- grpc-google-cloud-monitoring-v3/pom.xml | 4 ++-- pom.xml | 8 ++++---- proto-google-cloud-monitoring-v3/pom.xml | 4 ++-- samples/install-without-bom/pom.xml | 2 +- samples/snapshot/pom.xml | 2 +- versions.txt | 6 +++--- 10 files changed, 29 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6f489db..9fcd02ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +### [2.0.2](https://www.github.com/googleapis/java-monitoring/compare/v2.0.1...v2.0.2) (2020-09-21) + + +### Dependencies + +* update dependency com.google.cloud:google-cloud-shared-dependencies to v0.9.0 ([#248](https://www.github.com/googleapis/java-monitoring/issues/248)) ([3dbf19d](https://www.github.com/googleapis/java-monitoring/commit/3dbf19dc0d6c4a36ba4b41c651ff404b07941959)) +* update dependency com.google.protobuf:protobuf-java-util to v3.13.0 ([#235](https://www.github.com/googleapis/java-monitoring/issues/235)) ([5b09dfc](https://www.github.com/googleapis/java-monitoring/commit/5b09dfc50ef6df3b5e232cea2661b514c30ce145)) + ### [2.0.1](https://www.github.com/googleapis/java-monitoring/compare/v2.0.0...v2.0.1) (2020-08-14) diff --git a/README.md b/README.md index 4733db6e..e2c1ba54 100644 --- a/README.md +++ b/README.md @@ -48,11 +48,11 @@ If you are using Maven without BOM, add this to your dependencies: If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-monitoring:2.0.1' +compile 'com.google.cloud:google-cloud-monitoring:2.0.2' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-monitoring" % "2.0.1" +libraryDependencies += "com.google.cloud" % "google-cloud-monitoring" % "2.0.2" ``` [//]: # ({x-version-update-end}) diff --git a/google-cloud-monitoring-bom/pom.xml b/google-cloud-monitoring-bom/pom.xml index 3e8a9a10..16e11492 100644 --- a/google-cloud-monitoring-bom/pom.xml +++ b/google-cloud-monitoring-bom/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.google.cloud google-cloud-monitoring-bom - 2.0.2-SNAPSHOT + 2.0.2 pom com.google.cloud @@ -64,17 +64,17 @@ com.google.cloud google-cloud-monitoring - 2.0.2-SNAPSHOT + 2.0.2 com.google.api.grpc grpc-google-cloud-monitoring-v3 - 2.0.2-SNAPSHOT + 2.0.2 com.google.api.grpc proto-google-cloud-monitoring-v3 - 2.0.2-SNAPSHOT + 2.0.2 diff --git a/google-cloud-monitoring/pom.xml b/google-cloud-monitoring/pom.xml index 27fedd91..c2858dbe 100644 --- a/google-cloud-monitoring/pom.xml +++ b/google-cloud-monitoring/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.google.cloud google-cloud-monitoring - 2.0.2-SNAPSHOT + 2.0.2 jar Google Cloud Monitoring https://github.com/googleapis/java-monitoring @@ -11,7 +11,7 @@ com.google.cloud google-cloud-monitoring-parent - 2.0.2-SNAPSHOT + 2.0.2 google-cloud-monitoring diff --git a/grpc-google-cloud-monitoring-v3/pom.xml b/grpc-google-cloud-monitoring-v3/pom.xml index 6be624a9..3c7004bd 100644 --- a/grpc-google-cloud-monitoring-v3/pom.xml +++ b/grpc-google-cloud-monitoring-v3/pom.xml @@ -4,13 +4,13 @@ 4.0.0 com.google.api.grpc grpc-google-cloud-monitoring-v3 - 2.0.2-SNAPSHOT + 2.0.2 grpc-google-cloud-monitoring-v3 GRPC library for grpc-google-cloud-monitoring-v3 com.google.cloud google-cloud-monitoring-parent - 2.0.2-SNAPSHOT + 2.0.2 diff --git a/pom.xml b/pom.xml index dc5707d2..c5c1f733 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.google.cloud google-cloud-monitoring-parent pom - 2.0.2-SNAPSHOT + 2.0.2 Google Cloud Monitoring Parent https://github.com/googleapis/java-monitoring @@ -70,17 +70,17 @@ com.google.api.grpc proto-google-cloud-monitoring-v3 - 2.0.2-SNAPSHOT + 2.0.2 com.google.api.grpc grpc-google-cloud-monitoring-v3 - 2.0.2-SNAPSHOT + 2.0.2 com.google.cloud google-cloud-monitoring - 2.0.2-SNAPSHOT + 2.0.2 diff --git a/proto-google-cloud-monitoring-v3/pom.xml b/proto-google-cloud-monitoring-v3/pom.xml index 5c7028cd..e2ed8292 100644 --- a/proto-google-cloud-monitoring-v3/pom.xml +++ b/proto-google-cloud-monitoring-v3/pom.xml @@ -4,13 +4,13 @@ 4.0.0 com.google.api.grpc proto-google-cloud-monitoring-v3 - 2.0.2-SNAPSHOT + 2.0.2 proto-google-cloud-monitoring-v3 PROTO library for proto-google-cloud-monitoring-v3 com.google.cloud google-cloud-monitoring-parent - 2.0.2-SNAPSHOT + 2.0.2 diff --git a/samples/install-without-bom/pom.xml b/samples/install-without-bom/pom.xml index c4c8d93d..b7a423b8 100644 --- a/samples/install-without-bom/pom.xml +++ b/samples/install-without-bom/pom.xml @@ -29,7 +29,7 @@ com.google.cloud google-cloud-monitoring - 2.0.2-SNAPSHOT + 2.0.2 diff --git a/samples/snapshot/pom.xml b/samples/snapshot/pom.xml index 4d3b1816..ae70ed4a 100644 --- a/samples/snapshot/pom.xml +++ b/samples/snapshot/pom.xml @@ -28,7 +28,7 @@ com.google.cloud google-cloud-monitoring - 2.0.2-SNAPSHOT + 2.0.2 diff --git a/versions.txt b/versions.txt index e683c38b..60fb0173 100644 --- a/versions.txt +++ b/versions.txt @@ -1,6 +1,6 @@ # Format: # module:released-version:current-version -proto-google-cloud-monitoring-v3:2.0.1:2.0.2-SNAPSHOT -grpc-google-cloud-monitoring-v3:2.0.1:2.0.2-SNAPSHOT -google-cloud-monitoring:2.0.1:2.0.2-SNAPSHOT \ No newline at end of file +proto-google-cloud-monitoring-v3:2.0.2:2.0.2 +grpc-google-cloud-monitoring-v3:2.0.2:2.0.2 +google-cloud-monitoring:2.0.2:2.0.2 \ No newline at end of file