Search in sources :

Example 41 with Instance

use of com.google.bigtable.admin.v2.Instance in project java-docs-samples by GoogleCloudPlatform.

the class AutoLabelInstance method accept.

@Override
public void accept(CloudEvent event) throws Exception {
    // Extract CloudEvent data
    if (event.getData() != null) {
        String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
        // 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");
        // 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) {
            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/<PROJECT>/zones/<ZONE>/instances/<INSTANCE>
        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 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()) {
            // 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.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()).build();
            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()));
        }
    }
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) GetInstanceRequest(com.google.cloud.compute.v1.GetInstanceRequest) Instance(com.google.cloud.compute.v1.Instance) InstancesClient(com.google.cloud.compute.v1.InstancesClient) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) SetLabelsInstanceRequest(com.google.cloud.compute.v1.SetLabelsInstanceRequest) JsonSyntaxException(com.google.gson.JsonSyntaxException)

Example 42 with Instance

use of com.google.bigtable.admin.v2.Instance in project java-redis by googleapis.

the class ITSystemTest method setUp.

@BeforeClass
public static void setUp() throws Exception {
    CloudRedisSettings.Builder cloudRedisSettingsBuilder = CloudRedisSettings.newBuilder();
    cloudRedisSettingsBuilder.getInstanceSettings().setRetrySettings(cloudRedisSettingsBuilder.getInstanceSettings().getRetrySettings().toBuilder().setTotalTimeout(Duration.ofSeconds(900)).build());
    CloudRedisSettings cloudRedisSettings = cloudRedisSettingsBuilder.build();
    client = CloudRedisClient.create(cloudRedisSettings);
    /* Creates a Redis instance based on the specified tier and memory size. */
    Instance instance = Instance.newBuilder().setTier(TIER).setMemorySizeGb(1).setAuthorizedNetwork(AUTHORIZED_NETWORK).build();
    client.createInstanceAsync(PARENT, INSTANCE, instance).get();
    LOG.info("redis instance created successfully.");
}
Also used : Instance(com.google.cloud.redis.v1beta1.Instance) CloudRedisSettings(com.google.cloud.redis.v1beta1.CloudRedisSettings) BeforeClass(org.junit.BeforeClass)

Example 43 with Instance

use of com.google.bigtable.admin.v2.Instance in project java-redis by googleapis.

the class ITSystemTest method testUpdateInstance.

@Test
public void testUpdateInstance() throws ExecutionException, InterruptedException {
    int memorySizeGb = 4;
    FieldMask updateMask = FieldMask.newBuilder().addAllPaths(Arrays.asList("memory_size_gb")).build();
    Instance instance = Instance.newBuilder().setName(INSTANCE_NAME.toString()).setMemorySizeGb(memorySizeGb).build();
    UpdateInstanceRequest updateInstanceRequest = UpdateInstanceRequest.newBuilder().setInstance(instance).setUpdateMask(updateMask).build();
    Instance actualInstance = client.updateInstanceAsync(updateInstanceRequest).get();
    assertEquals(memorySizeGb, actualInstance.getMemorySizeGb());
}
Also used : UpdateInstanceRequest(com.google.cloud.redis.v1beta1.UpdateInstanceRequest) Instance(com.google.cloud.redis.v1beta1.Instance) FieldMask(com.google.protobuf.FieldMask) Test(org.junit.Test)

Example 44 with Instance

use of com.google.bigtable.admin.v2.Instance in project java-redis by googleapis.

the class ITSystemTest method testListInstances.

@Test
public void testListInstances() {
    List<Instance> instances = Lists.newArrayList(client.listInstances(PARENT).iterateAll());
    for (Instance instance : instances) {
        if (INSTANCE_NAME.toString().equals(instance.getName())) {
            assertEquals(TIER, instance.getTier());
            assertEquals(INSTANCE_NAME.toString(), instance.getName());
        }
    }
}
Also used : Instance(com.google.cloud.redis.v1.Instance) Test(org.junit.Test)

Example 45 with Instance

use of com.google.bigtable.admin.v2.Instance in project java-redis by googleapis.

the class ITSystemTest method testUpdateInstance.

@Test
public void testUpdateInstance() throws ExecutionException, InterruptedException {
    int memorySizeGb = 4;
    FieldMask updateMask = FieldMask.newBuilder().addAllPaths(Arrays.asList("memory_size_gb")).build();
    Instance instance = Instance.newBuilder().setName(INSTANCE_NAME.toString()).setMemorySizeGb(memorySizeGb).build();
    UpdateInstanceRequest updateInstanceRequest = UpdateInstanceRequest.newBuilder().setInstance(instance).setUpdateMask(updateMask).build();
    Instance actualInstance = client.updateInstanceAsync(updateInstanceRequest).get();
    assertEquals(memorySizeGb, actualInstance.getMemorySizeGb());
}
Also used : UpdateInstanceRequest(com.google.cloud.redis.v1.UpdateInstanceRequest) Instance(com.google.cloud.redis.v1.Instance) FieldMask(com.google.protobuf.FieldMask) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)137 AbstractMessage (com.google.protobuf.AbstractMessage)63 ByteString (com.google.protobuf.ByteString)57 InvalidArgumentException (com.google.api.gax.rpc.InvalidArgumentException)41 StatusRuntimeException (io.grpc.StatusRuntimeException)41 Instance (com.google.cloud.redis.v1beta1.Instance)34 CloudRedisClient (com.google.cloud.redis.v1beta1.CloudRedisClient)30 Instance (com.google.cloud.compute.v1.Instance)25 Operation (com.google.longrunning.Operation)22 InstanceName (com.google.bigtable.admin.v2.InstanceName)20 InstancesClient (com.google.cloud.compute.v1.InstancesClient)19 ExecutionException (java.util.concurrent.ExecutionException)17 ClusterName (com.google.bigtable.admin.v2.ClusterName)16 Table (com.google.bigtable.admin.v2.Table)16 HashMap (java.util.HashMap)16 TableName (com.google.bigtable.admin.v2.TableName)15 Cluster (com.google.bigtable.admin.v2.Cluster)13 ColumnFamily (com.google.bigtable.admin.v2.ColumnFamily)13 Operation (com.google.cloud.compute.v1.Operation)13 ArrayList (java.util.ArrayList)13