|
| 1 | +/* |
| 2 | + * Copyright 2021 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 | +package functions; |
| 18 | + |
| 19 | +import com.google.cloud.compute.v1.GetInstanceRequest; |
| 20 | +import com.google.cloud.compute.v1.Instance; |
| 21 | +import com.google.cloud.compute.v1.InstancesClient; |
| 22 | +import com.google.cloud.compute.v1.InstancesSetLabelsRequest; |
| 23 | +import com.google.cloud.compute.v1.SetLabelsInstanceRequest; |
| 24 | +import com.google.cloud.functions.CloudEventsFunction; |
| 25 | +import com.google.gson.Gson; |
| 26 | +import com.google.gson.JsonObject; |
| 27 | +import com.google.gson.JsonSyntaxException; |
| 28 | +import io.cloudevents.CloudEvent; |
| 29 | +import java.nio.charset.StandardCharsets; |
| 30 | +import java.util.logging.Logger; |
| 31 | + |
| 32 | +public class AutoLabelInstance implements CloudEventsFunction { |
| 33 | + private static final Logger logger = Logger.getLogger(AutoLabelInstance.class.getName()); |
| 34 | + |
| 35 | + @Override |
| 36 | + public void accept(CloudEvent event) throws Exception { |
| 37 | + // Extract CloudEvent data |
| 38 | + if (event.getData() != null) { |
| 39 | + String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8); |
| 40 | + |
| 41 | + // Convert data to JSON |
| 42 | + JsonObject eventData; |
| 43 | + try { |
| 44 | + Gson gson = new Gson(); |
| 45 | + eventData = gson.fromJson(cloudEventData, JsonObject.class); |
| 46 | + } catch (JsonSyntaxException error) { |
| 47 | + throw new RuntimeException("CloudEvent data is not valid JSON: " + error.getMessage()); |
| 48 | + } |
| 49 | + |
| 50 | + // Extract the Cloud Audit Logging entry from the data's protoPayload |
| 51 | + JsonObject payload = eventData.getAsJsonObject("protoPayload"); |
| 52 | + JsonObject auth = payload.getAsJsonObject("authenticationInfo"); |
| 53 | + |
| 54 | + // Extract the email address of the authenticated user |
| 55 | + // (or service account on behalf of third party principal) making the request |
| 56 | + String creator = auth.get("principalEmail").getAsString(); |
| 57 | + if (creator == null) { |
| 58 | + throw new RuntimeException("`principalEmail` not found in protoPayload."); |
| 59 | + } |
| 60 | + // Format the 'creator' parameter to match GCE label validation requirements |
| 61 | + creator = creator.toLowerCase().replaceAll("\\W", "-"); |
| 62 | + |
| 63 | + // Get relevant VM instance details from the CloudEvent `subject` property |
| 64 | + // Example: compute.googleapis.com/projects/<PROJECT>/zones/<ZONE>/instances/<INSTANCE> |
| 65 | + String subject = event.getSubject(); |
| 66 | + if (subject == null || subject == "") { |
| 67 | + throw new RuntimeException("Missing CloudEvent `subject`."); |
| 68 | + } |
| 69 | + String[] params = subject.split("/"); |
| 70 | + |
| 71 | + // Validate data |
| 72 | + if (params.length < 7) { |
| 73 | + throw new RuntimeException("Can not parse resource from CloudEvent `subject`: " + subject); |
| 74 | + } |
| 75 | + String project = params[2]; |
| 76 | + String zone = params[4]; |
| 77 | + String instanceName = params[6]; |
| 78 | + |
| 79 | + // Instantiate the Compute Instances client |
| 80 | + try (InstancesClient instancesClient = InstancesClient.create()) { |
| 81 | + // Get the newly-created VM instance's label fingerprint |
| 82 | + // This is required by the Compute Engine API to prevent duplicate labels |
| 83 | + GetInstanceRequest getInstanceRequest = |
| 84 | + GetInstanceRequest.newBuilder() |
| 85 | + .setInstance(instanceName) |
| 86 | + .setProject(project) |
| 87 | + .setZone(zone) |
| 88 | + .build(); |
| 89 | + Instance instance = instancesClient.get(getInstanceRequest); |
| 90 | + String fingerPrint = instance.getLabelFingerprint(); |
| 91 | + |
| 92 | + // Label the instance with its creator |
| 93 | + SetLabelsInstanceRequest setLabelRequest = |
| 94 | + SetLabelsInstanceRequest.newBuilder() |
| 95 | + .setInstance(instanceName) |
| 96 | + .setProject(project) |
| 97 | + .setZone(zone) |
| 98 | + .setInstancesSetLabelsRequestResource( |
| 99 | + InstancesSetLabelsRequest.newBuilder() |
| 100 | + .putLabels("creator", creator) |
| 101 | + .setLabelFingerprint(fingerPrint) |
| 102 | + .build()) |
| 103 | + .build(); |
| 104 | + |
| 105 | + instancesClient.setLabels(setLabelRequest); |
| 106 | + logger.info( |
| 107 | + String.format( |
| 108 | + "Adding label, \"{'creator': '%s'}\", to instance, \"%s\".", |
| 109 | + creator, instanceName)); |
| 110 | + } catch (Exception error) { |
| 111 | + throw new RuntimeException( |
| 112 | + String.format( |
| 113 | + "Error trying to label VM instance, %s: %s", instanceName, error.toString())); |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | +} |
0 commit comments