From 13d899a41511650114469b99dd03b973d506b834 Mon Sep 17 00:00:00 2001 From: averikitsch Date: Mon, 22 Nov 2021 12:01:43 -0800 Subject: [PATCH 1/4] Draft sample --- .../v2/cloudevent/log-cloudevent/pom.xml | 5 + .../java/functions/AutoLabelInstance.java | 99 ++++++++++++++++ .../java/functions/AutoLabelInstanceTest.java | 112 ++++++++++++++++++ 3 files changed, 216 insertions(+) create mode 100644 functions/v2/cloudevent/log-cloudevent/src/main/java/functions/AutoLabelInstance.java create mode 100644 functions/v2/cloudevent/log-cloudevent/src/test/java/functions/AutoLabelInstanceTest.java diff --git a/functions/v2/cloudevent/log-cloudevent/pom.xml b/functions/v2/cloudevent/log-cloudevent/pom.xml index d66b679a203..6f54307a99d 100644 --- a/functions/v2/cloudevent/log-cloudevent/pom.xml +++ b/functions/v2/cloudevent/log-cloudevent/pom.xml @@ -44,6 +44,11 @@ 1.0.4 provided + + com.google.cloud + google-cloud-compute + 1.5.0-alpha + com.google.code.gson gson diff --git a/functions/v2/cloudevent/log-cloudevent/src/main/java/functions/AutoLabelInstance.java b/functions/v2/cloudevent/log-cloudevent/src/main/java/functions/AutoLabelInstance.java new file mode 100644 index 00000000000..04e137a9a02 --- /dev/null +++ b/functions/v2/cloudevent/log-cloudevent/src/main/java/functions/AutoLabelInstance.java @@ -0,0 +1,99 @@ +/* + * Copyright 2021 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 functions; + +// [START functions_log_cloudevent] +import com.google.cloud.compute.v1.GetInstanceRequest; +import com.google.cloud.compute.v1.Instance; +import com.google.cloud.compute.v1.InstancesClient; +import com.google.cloud.compute.v1.InstancesSetLabelsRequest; +import com.google.cloud.compute.v1.Operation; +import com.google.cloud.compute.v1.SetLabelsInstanceRequest; +import com.google.cloud.functions.CloudEventsFunction; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import io.cloudevents.CloudEvent; +import java.nio.charset.StandardCharsets; +import java.util.logging.Logger; + +public class AutoLabelInstance implements CloudEventsFunction { + private static final Logger logger = Logger.getLogger(LogCloudEvent.class.getName()); + + @Override + public void accept(CloudEvent event) throws Exception { + + if (event.getData() != null) { + // Extract data and convert to JSON object + String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8); + Gson gson = new Gson(); + JsonObject eventData = gson.fromJson(cloudEventData, JsonObject.class); + + // Extract the Cloud Audit Logging entry from the protoPayload + JsonObject payload = eventData.getAsJsonObject("protoPayload"); + JsonObject auth = payload.getAsJsonObject("authenticationInfo"); + + if (auth == null) throw new Exception("Creator not specified"); + // The email address of the authenticated user + // (or service account on behalf of third party principal) making the request + String creator = auth.get("principleEmail").getAsString(); + // Format the 'creator' parameter to match GCE label validation requirements + creator = creator.toLowerCase().replaceAll("/\\W/g", "-"); + + // Get relevant VM instance details from the cloudevent's `subject` property + // Example value: + // compute.googleapis.com/projects//zones//instances/ + String subject = event.getSubject(); + String[] params = subject.split("/"); + + // Validate data + if (params.length < 7) throw new Exception("Params not right"); + + try (InstancesClient instancesClient = InstancesClient.create()) { + String project = params[2]; + String zone = params[4]; + String instanceName = params[6]; + + // Get the newly-created VM instance's label fingerprint + // This is required by the Compute Engine API to prevent duplicate labels + GetInstanceRequest getInstanceRequest = + GetInstanceRequest.newBuilder() + .setInstance(instanceName) + .setProject(project) + .setZone(zone) + .build(); + Instance instance = instancesClient.get(getInstanceRequest); + String fingerPrint = instance.getFingerprint(); + + // Label the instance with its creator + SetLabelsInstanceRequest setLabelRequest = + SetLabelsInstanceRequest.newBuilder() + .setInstance(instanceName) + .setProject(project) + .setZone(zone) + .setInstancesSetLabelsRequestResource( + InstancesSetLabelsRequest.newBuilder() + .putLabels("creator", creator) + .setLabelFingerprint(fingerPrint)) + .build(); + + Operation response = + instancesClient.setLabels(setLabelRequest); + } + } + } +} +// [END functions_log_cloudevent] diff --git a/functions/v2/cloudevent/log-cloudevent/src/test/java/functions/AutoLabelInstanceTest.java b/functions/v2/cloudevent/log-cloudevent/src/test/java/functions/AutoLabelInstanceTest.java new file mode 100644 index 00000000000..fcf0202d2c8 --- /dev/null +++ b/functions/v2/cloudevent/log-cloudevent/src/test/java/functions/AutoLabelInstanceTest.java @@ -0,0 +1,112 @@ +/* + * Copyright 2021 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 functions; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.common.testing.TestLogHandler; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import io.cloudevents.CloudEvent; +import io.cloudevents.core.builder.CloudEventBuilder; +import java.net.URI; +import java.util.Base64; +import java.util.logging.Logger; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class AutoLabelInstanceTest { + private static final Logger logger = Logger.getLogger(LogCloudEvent.class.getName()); + private static final TestLogHandler logHandler = new TestLogHandler(); + + @BeforeClass + public static void beforeClass() { + logger.addHandler(logHandler); + } + + @Test + public void functionsAutoLabelInstance() throws Exception { + // Build a CloudEvent Log Entry + JsonObject protoPayload = new JsonObject(); + + JsonObject auth = new JsonObject(); + metadata.addProperty("callerIp", "0.0.0.0"); + metadata.addProperty("callerSuppliedUserAgent", "test useragent"); + + protoPayload.add("requestMetadata", metadata); + protoPayload.addProperty("resourceName", "test resource"); + protoPayload.addProperty("methodName", "test method"); + + JsonObject encodedData = new JsonObject(); + encodedData.add("protoPayload", protoPayload); + + + CloudEvent event = + CloudEventBuilder.v1() + .withId("0") + .withSubject("test subject") + .withType("google.cloud.audit.log.v1.written") + .withSource(URI.create("https://example.com")) + .withData(new Gson().toJson(encodedData).getBytes()) + .build(); + + new LogCloudEvent().accept(event); + + assertThat("Event Subject: " + event.getSubject()).isEqualTo( + logHandler.getStoredLogRecords().get(1).getMessage()); + } +} + +// { +// "protoPayload": { +// "@type": "type.googleapis.com/google.cloud.audit.AuditLog", +// "authenticationInfo": { +// "principalEmail": "akitsch@google.com" +// }, +// "requestMetadata": { +// "callerIp": "2601:601:1100:2350:e8b5:f86f:8406:4692", +// "callerSuppliedUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36,gzip(gfe),gzip(gfe)" +// }, +// "serviceName": "compute.googleapis.com", +// "methodName": "beta.compute.instances.insert", +// "resourceName": "projects/starter-akitsch/zones/us-central1-a/instances/instance-1", +// "request": { +// "@type": "type.googleapis.com/compute.instances.insert" +// } +// }, +// "insertId": "p9fn8ie1fn8w", +// "resource": { +// "type": "gce_instance", +// "labels": { +// "project_id": "starter-akitsch", +// "zone": "us-central1-a", +// "instance_id": "3212917591118034299" +// } +// }, +// "timestamp": "2021-11-22T21:29:01.980019Z", +// "severity": "NOTICE", +// "logName": "projects/starter-akitsch/logs/cloudaudit.googleapis.com%2Factivity", +// "operation": { +// "id": "operation-1637616532093-5d1674fac7a19-e355d053-5a13b52b", +// "producer": "compute.googleapis.com", +// "last": true +// }, +// "receiveTimestamp": "2021-11-22T21:29:02.440154971Z" +// } \ No newline at end of file From 920d0a2039a6fa714ff6f7b920e01184b5dbdcea Mon Sep 17 00:00:00 2001 From: averikitsch Date: Wed, 24 Nov 2021 10:57:25 -0800 Subject: [PATCH 2/4] Update tests --- .../v2/cloudevent/log-cloudevent/pom.xml | 12 ++- .../java/functions/AutoLabelInstance.java | 93 +++++++++++-------- .../java/functions/AutoLabelInstanceTest.java | 82 ++++++---------- 3 files changed, 89 insertions(+), 98 deletions(-) diff --git a/functions/v2/cloudevent/log-cloudevent/pom.xml b/functions/v2/cloudevent/log-cloudevent/pom.xml index 6f54307a99d..9972b1b60d1 100644 --- a/functions/v2/cloudevent/log-cloudevent/pom.xml +++ b/functions/v2/cloudevent/log-cloudevent/pom.xml @@ -16,9 +16,7 @@ limitations under the License. --> - + 4.0.0 com.example.cloud.functions @@ -55,6 +53,12 @@ 2.8.8 compile + + com.google.protobuf + protobuf-java-util + 4.0.0-rc-2 + + com.google.truth @@ -112,4 +116,4 @@ - + \ No newline at end of file diff --git a/functions/v2/cloudevent/log-cloudevent/src/main/java/functions/AutoLabelInstance.java b/functions/v2/cloudevent/log-cloudevent/src/main/java/functions/AutoLabelInstance.java index 04e137a9a02..3fe8f22e4c7 100644 --- a/functions/v2/cloudevent/log-cloudevent/src/main/java/functions/AutoLabelInstance.java +++ b/functions/v2/cloudevent/log-cloudevent/src/main/java/functions/AutoLabelInstance.java @@ -16,84 +16,99 @@ package functions; -// [START functions_log_cloudevent] import com.google.cloud.compute.v1.GetInstanceRequest; import com.google.cloud.compute.v1.Instance; import com.google.cloud.compute.v1.InstancesClient; import com.google.cloud.compute.v1.InstancesSetLabelsRequest; -import com.google.cloud.compute.v1.Operation; import com.google.cloud.compute.v1.SetLabelsInstanceRequest; import com.google.cloud.functions.CloudEventsFunction; import com.google.gson.Gson; import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; import io.cloudevents.CloudEvent; import java.nio.charset.StandardCharsets; import java.util.logging.Logger; public class AutoLabelInstance implements CloudEventsFunction { - private static final Logger logger = Logger.getLogger(LogCloudEvent.class.getName()); + private static final Logger logger = Logger.getLogger(AutoLabelInstance.class.getName()); @Override public void accept(CloudEvent event) throws Exception { - + // Extract CloudEvent data if (event.getData() != null) { - // Extract data and convert to JSON object String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8); - Gson gson = new Gson(); - JsonObject eventData = gson.fromJson(cloudEventData, JsonObject.class); - // Extract the Cloud Audit Logging entry from the protoPayload + // Convert data to JSON + JsonObject eventData; + try { + Gson gson = new Gson(); + eventData = gson.fromJson(cloudEventData, JsonObject.class); + } catch (JsonSyntaxException error) { + throw new RuntimeException("CloudEvent data is not valid JSON: " + error.getMessage()); + } + + // Extract the Cloud Audit Logging entry from the data's protoPayload JsonObject payload = eventData.getAsJsonObject("protoPayload"); JsonObject auth = payload.getAsJsonObject("authenticationInfo"); - if (auth == null) throw new Exception("Creator not specified"); - // The email address of the authenticated user + // Extract the email address of the authenticated user // (or service account on behalf of third party principal) making the request - String creator = auth.get("principleEmail").getAsString(); + String creator = auth.get("principalEmail").getAsString(); + if (creator == null) + throw new RuntimeException("`principalEmail` not found in protoPayload."); // Format the 'creator' parameter to match GCE label validation requirements - creator = creator.toLowerCase().replaceAll("/\\W/g", "-"); + creator = creator.toLowerCase().replaceAll("\\W", "-"); - // Get relevant VM instance details from the cloudevent's `subject` property - // Example value: - // compute.googleapis.com/projects//zones//instances/ + // Get relevant VM instance details from the CloudEvent `subject` property + // Example: compute.googleapis.com/projects//zones//instances/ String subject = event.getSubject(); + if (subject == null || subject == "") + throw new RuntimeException("Missing CloudEvent `subject`."); String[] params = subject.split("/"); // Validate data - if (params.length < 7) throw new Exception("Params not right"); + if (params.length < 7) + throw new RuntimeException("Can not parse resource from CloudEvent `subject`: " + subject); + String project = params[2]; + String zone = params[4]; + String instanceName = params[6]; + // Instantiate the Compute Instances client try (InstancesClient instancesClient = InstancesClient.create()) { - String project = params[2]; - String zone = params[4]; - String instanceName = params[6]; - // Get the newly-created VM instance's label fingerprint // This is required by the Compute Engine API to prevent duplicate labels GetInstanceRequest getInstanceRequest = - GetInstanceRequest.newBuilder() - .setInstance(instanceName) - .setProject(project) - .setZone(zone) - .build(); + GetInstanceRequest.newBuilder() + .setInstance(instanceName) + .setProject(project) + .setZone(zone) + .build(); Instance instance = instancesClient.get(getInstanceRequest); - String fingerPrint = instance.getFingerprint(); + String fingerPrint = instance.getLabelFingerprint(); // Label the instance with its creator - SetLabelsInstanceRequest setLabelRequest = - SetLabelsInstanceRequest.newBuilder() - .setInstance(instanceName) - .setProject(project) - .setZone(zone) - .setInstancesSetLabelsRequestResource( - InstancesSetLabelsRequest.newBuilder() - .putLabels("creator", creator) - .setLabelFingerprint(fingerPrint)) - .build(); + SetLabelsInstanceRequest setLabelRequest = + SetLabelsInstanceRequest.newBuilder() + .setInstance(instanceName) + .setProject(project) + .setZone(zone) + .setInstancesSetLabelsRequestResource( + InstancesSetLabelsRequest.newBuilder() + .putLabels("creator", creator) + .setLabelFingerprint(fingerPrint) + .build()) + .build(); - Operation response = - instancesClient.setLabels(setLabelRequest); + instancesClient.setLabels(setLabelRequest); + logger.info( + String.format( + "Adding label, \"{'creator': '%s'}\", to instance, \"%s\".", + creator, instanceName)); + } catch (Exception error) { + throw new RuntimeException( + String.format( + "Error trying to label VM instance, %s: %s", instanceName, error.toString())); } } } } -// [END functions_log_cloudevent] diff --git a/functions/v2/cloudevent/log-cloudevent/src/test/java/functions/AutoLabelInstanceTest.java b/functions/v2/cloudevent/log-cloudevent/src/test/java/functions/AutoLabelInstanceTest.java index fcf0202d2c8..986e381e67e 100644 --- a/functions/v2/cloudevent/log-cloudevent/src/test/java/functions/AutoLabelInstanceTest.java +++ b/functions/v2/cloudevent/log-cloudevent/src/test/java/functions/AutoLabelInstanceTest.java @@ -24,7 +24,6 @@ import io.cloudevents.CloudEvent; import io.cloudevents.core.builder.CloudEventBuilder; import java.net.URI; -import java.util.Base64; import java.util.logging.Logger; import org.junit.BeforeClass; import org.junit.Test; @@ -33,9 +32,13 @@ @RunWith(JUnit4.class) public class AutoLabelInstanceTest { - private static final Logger logger = Logger.getLogger(LogCloudEvent.class.getName()); + private static final Logger logger = Logger.getLogger(AutoLabelInstance.class.getName()); private static final TestLogHandler logHandler = new TestLogHandler(); + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String ZONE = "us-central1-a"; + private static final String INSTANCE = "lite1"; + @BeforeClass public static void beforeClass() { logger.addHandler(logHandler); @@ -45,68 +48,37 @@ public static void beforeClass() { public void functionsAutoLabelInstance() throws Exception { // Build a CloudEvent Log Entry JsonObject protoPayload = new JsonObject(); + JsonObject authInfo = new JsonObject(); + String email = "test@gmail.com"; + authInfo.addProperty("principalEmail", email); - JsonObject auth = new JsonObject(); - metadata.addProperty("callerIp", "0.0.0.0"); - metadata.addProperty("callerSuppliedUserAgent", "test useragent"); + protoPayload.add("authenticationInfo", authInfo); - protoPayload.add("requestMetadata", metadata); - protoPayload.addProperty("resourceName", "test resource"); - protoPayload.addProperty("methodName", "test method"); + String resource = + String.format( + "compute.googleapis.com/projects/%s/zones/%s/instances/%s", PROJECT_ID, ZONE, INSTANCE); + protoPayload.addProperty("resourceName", resource); + protoPayload.addProperty("methodName", "beta.compute.instances.insert"); JsonObject encodedData = new JsonObject(); encodedData.add("protoPayload", protoPayload); - + encodedData.addProperty("name", "test name"); CloudEvent event = CloudEventBuilder.v1() - .withId("0") - .withSubject("test subject") - .withType("google.cloud.audit.log.v1.written") - .withSource(URI.create("https://example.com")) - .withData(new Gson().toJson(encodedData).getBytes()) - .build(); + .withId("0") + .withSubject(resource) + .withType("google.cloud.audit.log.v1.written") + .withSource(URI.create("https://example.com")) + .withData(new Gson().toJson(encodedData).getBytes()) + .build(); - new LogCloudEvent().accept(event); + new AutoLabelInstance().accept(event); - assertThat("Event Subject: " + event.getSubject()).isEqualTo( - logHandler.getStoredLogRecords().get(1).getMessage()); + assertThat( + String.format( + "Adding label, \"{'creator': '%s'}\", to instance, \"%s\".", + "test-gmail-com", INSTANCE)) + .isEqualTo(logHandler.getStoredLogRecords().get(0).getMessage()); } } - -// { -// "protoPayload": { -// "@type": "type.googleapis.com/google.cloud.audit.AuditLog", -// "authenticationInfo": { -// "principalEmail": "akitsch@google.com" -// }, -// "requestMetadata": { -// "callerIp": "2601:601:1100:2350:e8b5:f86f:8406:4692", -// "callerSuppliedUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36,gzip(gfe),gzip(gfe)" -// }, -// "serviceName": "compute.googleapis.com", -// "methodName": "beta.compute.instances.insert", -// "resourceName": "projects/starter-akitsch/zones/us-central1-a/instances/instance-1", -// "request": { -// "@type": "type.googleapis.com/compute.instances.insert" -// } -// }, -// "insertId": "p9fn8ie1fn8w", -// "resource": { -// "type": "gce_instance", -// "labels": { -// "project_id": "starter-akitsch", -// "zone": "us-central1-a", -// "instance_id": "3212917591118034299" -// } -// }, -// "timestamp": "2021-11-22T21:29:01.980019Z", -// "severity": "NOTICE", -// "logName": "projects/starter-akitsch/logs/cloudaudit.googleapis.com%2Factivity", -// "operation": { -// "id": "operation-1637616532093-5d1674fac7a19-e355d053-5a13b52b", -// "producer": "compute.googleapis.com", -// "last": true -// }, -// "receiveTimestamp": "2021-11-22T21:29:02.440154971Z" -// } \ No newline at end of file From 217806a9d6b2026e766d5ed341c379c64292fcae Mon Sep 17 00:00:00 2001 From: averikitsch Date: Wed, 24 Nov 2021 15:08:12 -0800 Subject: [PATCH 3/4] update directory --- .../v2/cloudevent/log-cloudevent/pom.xml | 17 +-- functions/v2/label-compute-instance/pom.xml | 121 ++++++++++++++++++ .../java/functions/AutoLabelInstance.java | 0 .../java/functions/AutoLabelInstanceTest.java | 0 4 files changed, 125 insertions(+), 13 deletions(-) create mode 100644 functions/v2/label-compute-instance/pom.xml rename functions/v2/{cloudevent/log-cloudevent => label-compute-instance}/src/main/java/functions/AutoLabelInstance.java (100%) rename functions/v2/{cloudevent/log-cloudevent => label-compute-instance}/src/test/java/functions/AutoLabelInstanceTest.java (100%) diff --git a/functions/v2/cloudevent/log-cloudevent/pom.xml b/functions/v2/cloudevent/log-cloudevent/pom.xml index 9972b1b60d1..d66b679a203 100644 --- a/functions/v2/cloudevent/log-cloudevent/pom.xml +++ b/functions/v2/cloudevent/log-cloudevent/pom.xml @@ -16,7 +16,9 @@ limitations under the License. --> - + 4.0.0 com.example.cloud.functions @@ -42,23 +44,12 @@ 1.0.4 provided - - com.google.cloud - google-cloud-compute - 1.5.0-alpha - com.google.code.gson gson 2.8.8 compile - - com.google.protobuf - protobuf-java-util - 4.0.0-rc-2 - - com.google.truth @@ -116,4 +107,4 @@ - \ No newline at end of file + diff --git a/functions/v2/label-compute-instance/pom.xml b/functions/v2/label-compute-instance/pom.xml new file mode 100644 index 00000000000..cb574889593 --- /dev/null +++ b/functions/v2/label-compute-instance/pom.xml @@ -0,0 +1,121 @@ + + + + + + 4.0.0 + + com.example.cloud.functions + label-compute-instance + + + com.google.cloud.samples + shared-configuration + 1.0.23 + + + + 11 + 11 + UTF-8 + + + + + + com.google.cloud.functions + functions-framework-api + 1.0.4 + provided + + + com.google.cloud + google-cloud-compute + 1.5.0-alpha + + + com.google.code.gson + gson + 2.8.8 + compile + + + com.google.protobuf + protobuf-java-util + 4.0.0-rc-2 + + + + + com.google.truth + truth + 1.1.3 + test + + + com.google.guava + guava-testlib + 31.0-jre + test + + + io.cloudevents + cloudevents-core + 2.2.0 + test + + + + + + + + com.google.cloud.functions + function-maven-plugin + 0.10.0 + + functions.AutoLabelInstance + + + + org.apache.maven.plugins + maven-surefire-plugin + + + 3.0.0-M5 + + + **/*Test.java + + ${skipTests} + sponge_log + false + + + + + \ No newline at end of file diff --git a/functions/v2/cloudevent/log-cloudevent/src/main/java/functions/AutoLabelInstance.java b/functions/v2/label-compute-instance/src/main/java/functions/AutoLabelInstance.java similarity index 100% rename from functions/v2/cloudevent/log-cloudevent/src/main/java/functions/AutoLabelInstance.java rename to functions/v2/label-compute-instance/src/main/java/functions/AutoLabelInstance.java diff --git a/functions/v2/cloudevent/log-cloudevent/src/test/java/functions/AutoLabelInstanceTest.java b/functions/v2/label-compute-instance/src/test/java/functions/AutoLabelInstanceTest.java similarity index 100% rename from functions/v2/cloudevent/log-cloudevent/src/test/java/functions/AutoLabelInstanceTest.java rename to functions/v2/label-compute-instance/src/test/java/functions/AutoLabelInstanceTest.java From 8e5e5a78b1b2e18d22ecdb993181db1b534cedea Mon Sep 17 00:00:00 2001 From: averikitsch Date: Wed, 24 Nov 2021 15:15:52 -0800 Subject: [PATCH 4/4] lint --- .../src/main/java/functions/AutoLabelInstance.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/functions/v2/label-compute-instance/src/main/java/functions/AutoLabelInstance.java b/functions/v2/label-compute-instance/src/main/java/functions/AutoLabelInstance.java index 3fe8f22e4c7..6fe51bc95dc 100644 --- a/functions/v2/label-compute-instance/src/main/java/functions/AutoLabelInstance.java +++ b/functions/v2/label-compute-instance/src/main/java/functions/AutoLabelInstance.java @@ -54,21 +54,24 @@ public void accept(CloudEvent event) throws Exception { // Extract the email address of the authenticated user // (or service account on behalf of third party principal) making the request String creator = auth.get("principalEmail").getAsString(); - if (creator == null) + if (creator == null) { throw new RuntimeException("`principalEmail` not found in protoPayload."); + } // Format the 'creator' parameter to match GCE label validation requirements creator = creator.toLowerCase().replaceAll("\\W", "-"); // Get relevant VM instance details from the CloudEvent `subject` property // Example: compute.googleapis.com/projects//zones//instances/ String subject = event.getSubject(); - if (subject == null || subject == "") + if (subject == null || subject == "") { throw new RuntimeException("Missing CloudEvent `subject`."); + } String[] params = subject.split("/"); // Validate data - if (params.length < 7) + if (params.length < 7) { throw new RuntimeException("Can not parse resource from CloudEvent `subject`: " + subject); + } String project = params[2]; String zone = params[4]; String instanceName = params[6];