Search in sources :

Example 1 with GetInstanceRequest

use of com.google.bigtable.admin.v2.GetInstanceRequest 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 2 with GetInstanceRequest

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

the class BigtableInstanceAdminClientTest method testGetInstance.

@Test
public void testGetInstance() {
    // Setup
    Mockito.when(mockStub.getInstanceCallable()).thenReturn(mockGetInstanceCallable);
    com.google.bigtable.admin.v2.GetInstanceRequest expectedRequest = com.google.bigtable.admin.v2.GetInstanceRequest.newBuilder().setName(INSTANCE_NAME).build();
    com.google.bigtable.admin.v2.Instance expectedResponse = com.google.bigtable.admin.v2.Instance.newBuilder().setName(INSTANCE_NAME).build();
    Mockito.when(mockGetInstanceCallable.futureCall(expectedRequest)).thenReturn(ApiFutures.immediateFuture(expectedResponse));
    // Execute
    Instance actualResult = adminClient.getInstance(INSTANCE_ID);
    // Verify
    assertThat(actualResult).isEqualTo(Instance.fromProto(expectedResponse));
}
Also used : GetInstanceRequest(com.google.bigtable.admin.v2.GetInstanceRequest) Instance(com.google.cloud.bigtable.admin.v2.models.Instance) Test(org.junit.Test)

Example 3 with GetInstanceRequest

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

the class BaseBigtableInstanceAdminClientTest method getInstanceTest.

@Test
public void getInstanceTest() throws Exception {
    Instance expectedResponse = Instance.newBuilder().setName(InstanceName.of("[PROJECT]", "[INSTANCE]").toString()).setDisplayName("displayName1714148973").putAllLabels(new HashMap<String, String>()).setCreateTime(Timestamp.newBuilder().build()).build();
    mockBigtableInstanceAdmin.addResponse(expectedResponse);
    InstanceName name = InstanceName.of("[PROJECT]", "[INSTANCE]");
    Instance actualResponse = client.getInstance(name);
    Assert.assertEquals(expectedResponse, actualResponse);
    List<AbstractMessage> actualRequests = mockBigtableInstanceAdmin.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    GetInstanceRequest actualRequest = ((GetInstanceRequest) actualRequests.get(0));
    Assert.assertEquals(name.toString(), actualRequest.getName());
    Assert.assertTrue(channelProvider.isHeaderSent(ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
Also used : InstanceName(com.google.bigtable.admin.v2.InstanceName) AbstractMessage(com.google.protobuf.AbstractMessage) GetInstanceRequest(com.google.bigtable.admin.v2.GetInstanceRequest) Instance(com.google.bigtable.admin.v2.Instance) ByteString(com.google.protobuf.ByteString) Test(org.junit.Test)

Example 4 with GetInstanceRequest

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

the class StartEncryptedInstance method startEncryptedInstance.

// Starts a stopped Google Compute Engine instance (with encrypted disks).
public static void startEncryptedInstance(String project, String zone, String instanceName, String key) throws IOException, ExecutionException, InterruptedException {
    /* Initialize client that will be used to send requests. This client only needs to be created
       once, and can be reused for multiple requests. After completing all of your requests, call
       the `instancesClient.close()` method on the client to safely
       clean up any remaining background resources. */
    try (InstancesClient instancesClient = InstancesClient.create()) {
        GetInstanceRequest getInstanceRequest = GetInstanceRequest.newBuilder().setProject(project).setZone(zone).setInstance(instanceName).build();
        Instance instance = instancesClient.get(getInstanceRequest);
        // Prepare the information about disk encryption.
        CustomerEncryptionKeyProtectedDisk protectedDisk = CustomerEncryptionKeyProtectedDisk.newBuilder().setDiskEncryptionKey(CustomerEncryptionKey.newBuilder().setRawKey(key).build()).setSource(instance.getDisks(0).getSource()).build();
        InstancesStartWithEncryptionKeyRequest startWithEncryptionKeyRequest = InstancesStartWithEncryptionKeyRequest.newBuilder().addDisks(protectedDisk).build();
        StartWithEncryptionKeyInstanceRequest encryptionKeyInstanceRequest = StartWithEncryptionKeyInstanceRequest.newBuilder().setProject(project).setZone(zone).setInstance(instanceName).setInstancesStartWithEncryptionKeyRequestResource(startWithEncryptionKeyRequest).build();
        OperationFuture<Operation, Operation> operation = instancesClient.startWithEncryptionKeyAsync(encryptionKeyInstanceRequest);
        Operation response = operation.get();
        if (response.getStatus() == Status.DONE) {
            System.out.println("Encrypted instance started successfully ! ");
        }
    }
}
Also used : GetInstanceRequest(com.google.cloud.compute.v1.GetInstanceRequest) Instance(com.google.cloud.compute.v1.Instance) StartWithEncryptionKeyInstanceRequest(com.google.cloud.compute.v1.StartWithEncryptionKeyInstanceRequest) InstancesClient(com.google.cloud.compute.v1.InstancesClient) InstancesStartWithEncryptionKeyRequest(com.google.cloud.compute.v1.InstancesStartWithEncryptionKeyRequest) Operation(com.google.cloud.compute.v1.Operation) CustomerEncryptionKeyProtectedDisk(com.google.cloud.compute.v1.CustomerEncryptionKeyProtectedDisk)

Example 5 with GetInstanceRequest

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

the class BaseBigtableInstanceAdminClientTest method getInstanceTest2.

@Test
public void getInstanceTest2() throws Exception {
    Instance expectedResponse = Instance.newBuilder().setName(InstanceName.of("[PROJECT]", "[INSTANCE]").toString()).setDisplayName("displayName1714148973").putAllLabels(new HashMap<String, String>()).setCreateTime(Timestamp.newBuilder().build()).build();
    mockBigtableInstanceAdmin.addResponse(expectedResponse);
    String name = "name3373707";
    Instance actualResponse = client.getInstance(name);
    Assert.assertEquals(expectedResponse, actualResponse);
    List<AbstractMessage> actualRequests = mockBigtableInstanceAdmin.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    GetInstanceRequest actualRequest = ((GetInstanceRequest) actualRequests.get(0));
    Assert.assertEquals(name, actualRequest.getName());
    Assert.assertTrue(channelProvider.isHeaderSent(ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
Also used : AbstractMessage(com.google.protobuf.AbstractMessage) GetInstanceRequest(com.google.bigtable.admin.v2.GetInstanceRequest) Instance(com.google.bigtable.admin.v2.Instance) ByteString(com.google.protobuf.ByteString) Test(org.junit.Test)

Aggregations

GetInstanceRequest (com.google.bigtable.admin.v2.GetInstanceRequest)3 Test (org.junit.Test)3 Instance (com.google.bigtable.admin.v2.Instance)2 GetInstanceRequest (com.google.cloud.compute.v1.GetInstanceRequest)2 Instance (com.google.cloud.compute.v1.Instance)2 InstancesClient (com.google.cloud.compute.v1.InstancesClient)2 AbstractMessage (com.google.protobuf.AbstractMessage)2 ByteString (com.google.protobuf.ByteString)2 InstanceName (com.google.bigtable.admin.v2.InstanceName)1 Instance (com.google.cloud.bigtable.admin.v2.models.Instance)1 CustomerEncryptionKeyProtectedDisk (com.google.cloud.compute.v1.CustomerEncryptionKeyProtectedDisk)1 InstancesStartWithEncryptionKeyRequest (com.google.cloud.compute.v1.InstancesStartWithEncryptionKeyRequest)1 Operation (com.google.cloud.compute.v1.Operation)1 SetLabelsInstanceRequest (com.google.cloud.compute.v1.SetLabelsInstanceRequest)1 StartWithEncryptionKeyInstanceRequest (com.google.cloud.compute.v1.StartWithEncryptionKeyInstanceRequest)1 Gson (com.google.gson.Gson)1 JsonObject (com.google.gson.JsonObject)1 JsonSyntaxException (com.google.gson.JsonSyntaxException)1