Skip to content

Commit 8843b83

Browse files
authored
Merge branch 'master' into dpebot-repositorygardener
2 parents bfc76e1 + 78406bd commit 8843b83

File tree

3 files changed

+154
-35
lines changed

3 files changed

+154
-35
lines changed

monitoring/v3/pom.xml

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
<parent>
2828
<groupId>com.google.cloud.samples</groupId>
2929
<artifactId>shared-configuration</artifactId>
30-
<version>1.0.9</version>
30+
<version>1.0.10</version>
3131
</parent>
3232

3333
<properties>
@@ -46,5 +46,13 @@
4646
<artifactId>commons-cli</artifactId>
4747
<version>1.4</version>
4848
</dependency>
49+
50+
<!-- Test dependencies -->
51+
<dependency>
52+
<groupId>junit</groupId>
53+
<artifactId>junit</artifactId>
54+
<version>4.12</version>
55+
<scope>test</scope>
56+
</dependency>
4957
</dependencies>
5058
</project>

monitoring/v3/src/main/java/AlertSample.java

Lines changed: 38 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@
4242
import java.io.FileReader;
4343
import java.io.FileWriter;
4444
import java.io.IOException;
45-
import java.io.PrintStream;
4645
import java.util.List;
4746
import java.util.Map;
4847
import java.util.Optional;
@@ -105,7 +104,8 @@ public class AlertSample {
105104
"backup", BACKUP_OPTIONS,
106105
"restore", BACKUP_OPTIONS,
107106
"replace-channels", REPLACE_CHANNELS_OPTIONS,
108-
"enable", ENABLE_OPTIONS
107+
"enable", ENABLE_OPTIONS,
108+
"disable", ENABLE_OPTIONS
109109
);
110110

111111
private static final CommandLineParser PARSER = new DefaultParser();
@@ -122,26 +122,23 @@ public class AlertSample {
122122

123123
private AlertPolicyServiceClient alertPolicyClient;
124124
private NotificationChannelServiceClient notificationChannelClient;
125-
private PrintStream outputStream;
126125
private Gson gson = new Gson();
127126

128127
private AlertSample() throws IOException {
129-
this(AlertPolicyServiceClient.create(), NotificationChannelServiceClient.create(), System.out);
128+
this(AlertPolicyServiceClient.create(), NotificationChannelServiceClient.create());
130129
}
131130

132131
AlertSample(AlertPolicyServiceClient alertPolicyClient,
133-
NotificationChannelServiceClient notificationChannelClient,
134-
PrintStream os) {
132+
NotificationChannelServiceClient notificationChannelClient) {
135133
this.alertPolicyClient = checkNotNull(alertPolicyClient);
136134
this.notificationChannelClient = notificationChannelClient;
137-
outputStream = checkNotNull(os);
138135
}
139136

140137
public static void main(String[] args) throws IOException {
141138
AlertSample sample = createAlertSample();
142139

143140
if (args.length == 0) {
144-
usage(System.out, null);
141+
usage(null);
145142
return;
146143
}
147144
String command = args[0];
@@ -151,16 +148,15 @@ public static void main(String[] args) throws IOException {
151148

152149
String projectId = cl.hasOption(PROJECT_ID_OPTION.getOpt())
153150
? cl.getOptionValue(PROJECT_ID_OPTION.getOpt())
154-
: System.getenv("GOOGLE_PROJECT_ID");
151+
: System.getenv("GOOGLE_CLOUD_PROJECT");
155152

156153
if (Strings.isNullOrEmpty(projectId)) {
157154
projectId = System.getenv("DEVSHELL_PROJECT_ID");
158155
}
159156

160157
if (Strings.isNullOrEmpty(projectId)) {
161-
usage(sample.outputStream,
162-
"Error: --project-id arg required unless provided by the GOOGLE_PROJECT_ID "
163-
+ "or DEVSHELL_PROJECT_ID environment variables.");
158+
usage("Error: --project-id arg required unless provided by the GOOGLE_CLOUD_PROJECT "
159+
+ "or DEVSHELL_PROJECT_ID environment variables.");
164160
return;
165161
}
166162

@@ -190,7 +186,7 @@ public static void main(String[] args) throws IOException {
190186
cl.getOptionValue(FILTER_OPTION.getOpt()), false);
191187
break;
192188
default:
193-
usage(sample.outputStream, null);
189+
usage(null);
194190
}
195191
}
196192

@@ -199,7 +195,7 @@ private static CommandLine parseCommandLine(String[] args, Options expectedOptio
199195
try {
200196
cl = PARSER.parse(expectedOptions, args);
201197
} catch (ParseException pe) {
202-
usage(System.out, "Exception parsing command line arguments.");
198+
usage("Exception parsing command line arguments.");
203199
throw new RuntimeException("Exception parsing command line arguments.", pe);
204200
}
205201
return cl;
@@ -210,7 +206,7 @@ private static AlertSample createAlertSample() throws IOException {
210206
try {
211207
sample = new AlertSample();
212208
} catch (Exception e) {
213-
usage(System.out, "Exception creating alert sample.");
209+
usage("Exception creating alert sample.");
214210
throw e;
215211
}
216212
return sample;
@@ -221,10 +217,19 @@ void listAlertPolicies(String projectId) {
221217
ListAlertPoliciesPagedResponse response = alertPolicyClient.listAlertPolicies(ProjectName.of(
222218
projectId));
223219

220+
System.out.println("Alert Policies:");
224221
for (AlertPolicy policy : response.iterateAll()) {
225-
outputStream.println(policy.getDisplayName());
222+
System.out.println(
223+
String.format("\nPolicy %s\nalert-id: %s", policy.getDisplayName(), policy.getName()));
224+
int channels = policy.getNotificationChannelsCount();
225+
if (channels > 0) {
226+
System.out.println("notification-channels:");
227+
for (int i = 0; i < channels; i++) {
228+
System.out.println("\t" + policy.getNotificationChannels(i));
229+
}
230+
}
226231
if (policy.hasDocumentation() && policy.getDocumentation().getContent() != null) {
227-
outputStream.println(policy.getDocumentation().getContent());
232+
System.out.println(policy.getDocumentation().getContent());
228233
}
229234
}
230235
}
@@ -235,7 +240,7 @@ void backupPolicies(String projectId, String filePath) throws IOException {
235240
List<AlertPolicy> alertPolicies = getAlertPolicies(projectId);
236241
List<NotificationChannel> notificationChannels = getNotificationChannels(projectId);
237242
writePoliciesBackupFile(projectId, filePath, alertPolicies, notificationChannels);
238-
outputStream.println(String.format("Saved policies to %s", filePath));
243+
System.out.println(String.format("Saved policies to %s", filePath));
239244
}
240245

241246
private List<AlertPolicy> getAlertPolicies(String projectId) {
@@ -351,7 +356,7 @@ private void restoreRevisedPolicies(String projectId,
351356
policy.toBuilder().clearName().build());
352357
}
353358
}
354-
outputStream.println(String.format("Restored %s", policy.getName()));
359+
System.out.println(String.format("Restored %s", policy.getName()));
355360
}
356361
}
357362
// [END monitoring_alert_create_policy]
@@ -400,7 +405,7 @@ private Map<String, String> restoreNotificationChannels(String projectId,
400405
}
401406
// [END monitoring_alert_create_channel]
402407
// [END monitoring_alert_update_channel]
403-
408+
404409
private JsonObject getPolicyJsonContents(String filePath, BufferedReader content, Gson gson) {
405410
try {
406411
return gson.fromJson(content, JsonObject.class);
@@ -421,7 +426,7 @@ void replaceChannels(String projectId, String alertPolicyId, String[] channelIds
421426
}
422427
AlertPolicy result = alertPolicyClient.updateAlertPolicy(
423428
FieldMask.newBuilder().addPaths("notification_channels").build(), policyBuilder.build());
424-
outputStream.println(String.format("Updated %s", result.getName()));
429+
System.out.println(String.format("Updated %s", result.getName()));
425430
}
426431
// [END monitoring_alert_replace_channels]
427432

@@ -432,38 +437,37 @@ void enablePolicies(String projectId,
432437
boolean enable) {
433438
ListAlertPoliciesPagedResponse response = alertPolicyClient
434439
.listAlertPolicies(ListAlertPoliciesRequest.newBuilder()
435-
.setName(projectId)
440+
.setName(ProjectName.of(projectId).toString())
436441
.setFilter(filter)
437442
.build());
438443

439444
for (AlertPolicy policy : response.iterateAll()) {
440445
if (policy.getEnabled().getValue() == enable) {
441-
outputStream.println(String.format("Policy %s is already %b.", policy.getName(), enable));
446+
System.out.println(String.format(
447+
"Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled"));
442448
continue;
443449
}
444450
AlertPolicy updatedPolicy = AlertPolicy
445451
.newBuilder()
446-
.setName(AlertPolicyName.of(projectId, policy.getName()).toString())
452+
.setName(policy.getName())
447453
.setEnabled(BoolValue.newBuilder().setValue(enable))
448454
.build();
449455
AlertPolicy result = alertPolicyClient.updateAlertPolicy(
450456
FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy);
451-
outputStream.println(String.format(
452-
"%s %s", result.getName(), result.getEnabled().getValue() ? "Enabled" : "Disabled"));
457+
System.out.println(String.format(
458+
"%s %s",
459+
result.getDisplayName(),
460+
result.getEnabled().getValue() ? "enabled" : "disabled"));
453461
}
454462

455463
}
456464
// [END monitoring_alert_enable_policies]
457465
// [END monitoring_alert_disable_policies]
458466

459-
private static void usage(PrintStream ps) {
460-
usage(ps, null);
461-
}
462-
463-
private static void usage(PrintStream ps, String message) {
464-
Optional.ofNullable(message).ifPresent(ps::println);
465-
ps.println("Usage:");
466-
ps.printf(
467+
private static void usage(String message) {
468+
Optional.ofNullable(message).ifPresent(System.out::println);
469+
System.out.println("Usage:");
470+
System.out.printf(
467471
"\tjava %s \"<command>\" \"<args>\"\n"
468472
+ "Args:\n"
469473
+ "\t%s\n"
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
/*
2+
* Copyright 2018 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import static org.junit.Assert.assertTrue;
18+
19+
import com.google.common.base.Strings;
20+
import com.google.common.io.Files;
21+
22+
import java.io.ByteArrayOutputStream;
23+
import java.io.File;
24+
import java.io.IOException;
25+
import java.io.PrintStream;
26+
import java.nio.charset.StandardCharsets;
27+
import java.util.regex.Matcher;
28+
import java.util.regex.Pattern;
29+
30+
import org.junit.After;
31+
import org.junit.Assert;
32+
import org.junit.Before;
33+
import org.junit.Ignore;
34+
import org.junit.Test;
35+
import org.junit.runner.RunWith;
36+
import org.junit.runners.JUnit4;
37+
38+
/**
39+
* Tests for monitoring "AlertSample" sample.
40+
*/
41+
@RunWith(JUnit4.class)
42+
@SuppressWarnings("checkstyle:abbreviationaswordinname")
43+
public class AlertIT {
44+
private static String testPolicyName = "test-policy";
45+
private static String policyFileName = "target/policyBackup.json";
46+
private static Pattern policyNameRegex = Pattern.compile(
47+
"alertPolicies/(?<alertid>.*)(?s).*(?!s)notificationChannels/(?<channel>[a-zA-Z0-9]*)$");
48+
private ByteArrayOutputStream bout;
49+
private PrintStream out;
50+
51+
@Before
52+
public void setUp() {
53+
bout = new ByteArrayOutputStream();
54+
out = new PrintStream(bout);
55+
System.setOut(out);
56+
}
57+
58+
@After
59+
public void tearDown() {
60+
System.setOut(null);
61+
}
62+
63+
@Test
64+
public void testListPolicies() throws IOException {
65+
AlertSample.main(new String[]{"list"});
66+
assertTrue(bout.toString().contains(testPolicyName));
67+
}
68+
69+
@Test
70+
public void testBackupPolicies() throws IOException {
71+
AlertSample.main(new String[]{"backup", "-j", policyFileName});
72+
File backupFile = new File(policyFileName);
73+
assertTrue(backupFile.exists());
74+
String fileContents =
75+
String.join("\n", Files.readLines(backupFile, StandardCharsets.UTF_8));
76+
assertTrue(fileContents.contains("test-policy"));
77+
}
78+
79+
// TODO(b/78293034): Complete restore backup test when parse/unparse issue is figured out.
80+
@Test
81+
@Ignore
82+
public void testRestoreBackup() throws IOException {
83+
}
84+
85+
@Test
86+
public void testReplaceChannels() throws IOException {
87+
// Get a test policy name for the project.
88+
AlertSample.main(new String[]{"list"});
89+
Matcher matcher = policyNameRegex.matcher(bout.toString());
90+
assertTrue(matcher.find());
91+
String alertId = matcher.group("alertid");
92+
String channel = matcher.group("channel");
93+
Assert.assertFalse(Strings.isNullOrEmpty(alertId));
94+
AlertSample.main(new String[]{"replace-channels", "-a", alertId, "-c", channel});
95+
Pattern resultPattern = Pattern.compile("(?s).*Updated .*/alertPolicies/" + alertId);
96+
assertTrue(resultPattern.matcher(bout.toString()).find());
97+
}
98+
99+
@Test
100+
public void testDisableEnablePolicies() throws IOException {
101+
AlertSample.main(new String[]{"disable", "-d", "display_name='test-policy'"});
102+
assertTrue(bout.toString().contains("disabled"));
103+
AlertSample.main(new String[]{"enable", "-d", "display_name='test-policy'"});
104+
assertTrue(bout.toString().contains("enabled"));
105+
106+
}
107+
}

0 commit comments

Comments
 (0)