Search in sources :

Example 6 with Instance

use of com.google.cloud.redis.v1.Instance in project java-docs-samples by GoogleCloudPlatform.

the class CreateInstanceWithCustomHostname method createInstanceWithCustomHostname.

// Creates an instance with custom hostname.
public static void createInstanceWithCustomHostname(String projectId, String zone, String instanceName, String hostName) throws IOException, ExecutionException, InterruptedException {
    // machineType - Machine type for the VM instance specified in the following format:
    // *    "zones/{zone}/machineTypes/{type_name}". For example:
    // *    "zones/europe-west3-c/machineTypes/f1-micro"
    // *    You can find the list of available machine types by using this gcloud command:
    // *    $ gcloud compute machine-types list
    // sourceImage - Path of the disk image you want to use for your boot
    // *    disk. This image can be one of the public images
    // *    eg: "projects/...
    // *    or a private image you have access to.
    // *    You can check the list of available public images using:
    // *    $ gcloud compute images list
    // networkName - Name of the network you want the new instance to use.
    // *    For example: global/networks/default - if you want to use the default network.
    String machineType = "n1-standard-1";
    String sourceImage = String.format("projects/%s/global/images/family/%s", "debian-cloud", "debian-11");
    String networkName = "global/networks/default";
    try (InstancesClient instancesClient = InstancesClient.create()) {
        System.out.printf("Creating the %s instance in %s with hostname %s...", instanceName, zone, hostName);
        AttachedDisk disk = AttachedDisk.newBuilder().setBoot(true).setAutoDelete(true).setType(AttachedDisk.Type.PERSISTENT.toString()).setInitializeParams(// Describe the size and source image of the boot disk to attach to the instance.
        AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(10).build()).build();
        // Use the network interface provided in the networkName argument.
        NetworkInterface networkInterface = NetworkInterface.newBuilder().setName(networkName).build();
        Instance instanceResource = Instance.newBuilder().setName(instanceName).setHostname(hostName).addDisks(disk).setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType)).addNetworkInterfaces(networkInterface).build();
        InsertInstanceRequest request = InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instanceResource).build();
        // Wait for the create operation to complete.
        Operation response = instancesClient.insertAsync(request).get();
        if (response.hasError()) {
            System.out.printf("Instance creation failed for instance: %s ; Response: %s ! ! ", instanceName, response);
            return;
        }
        System.out.printf("Instance created : %s", instanceName);
        System.out.printf("Operation Status for instance %s is %s: ", instanceName, response.getStatus());
    }
}
Also used : InsertInstanceRequest(com.google.cloud.compute.v1.InsertInstanceRequest) Instance(com.google.cloud.compute.v1.Instance) InstancesClient(com.google.cloud.compute.v1.InstancesClient) AttachedDisk(com.google.cloud.compute.v1.AttachedDisk) NetworkInterface(com.google.cloud.compute.v1.NetworkInterface) Operation(com.google.cloud.compute.v1.Operation)

Example 7 with Instance

use of com.google.cloud.redis.v1.Instance in project java-docs-samples by GoogleCloudPlatform.

the class CreateInstanceDeleteProtection method createInstanceDeleteProtection.

// Send an instance creation request to the Compute Engine API and wait for it to complete.
public static void createInstanceDeleteProtection(String projectId, String zone, String instanceName, boolean deleteProtection) throws IOException, ExecutionException, InterruptedException {
    String machineType = String.format("zones/%s/machineTypes/e2-small", zone);
    String sourceImage = String.format("projects/debian-cloud/global/images/family/%s", "debian-11");
    long diskSizeGb = 10L;
    String networkName = "default";
    // Instance creation requires at least one persistent disk and one network interface.
    try (InstancesClient instancesClient = InstancesClient.create()) {
        AttachedDisk disk = AttachedDisk.newBuilder().setBoot(true).setAutoDelete(true).setType(AttachedDisk.Type.PERSISTENT.toString()).setInitializeParams(// Describe the size and source image of the boot disk to attach to the instance.
        AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(diskSizeGb).build()).build();
        // Use the default VPC network.
        NetworkInterface networkInterface = NetworkInterface.newBuilder().setName(networkName).build();
        // Collect information into the Instance object.
        Instance instanceResource = Instance.newBuilder().setName(instanceName).setMachineType(machineType).addDisks(disk).addNetworkInterfaces(networkInterface).setDeletionProtection(deleteProtection).build();
        System.out.printf("Creating instance: %s at %s %n", instanceName, zone);
        // Prepare the request to insert an instance.
        InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instanceResource).build();
        // Wait for the create operation to complete.
        Operation response = instancesClient.insertAsync(insertInstanceRequest).get();
        if (response.hasError()) {
            System.out.println("Instance creation failed ! ! " + response);
            return;
        }
        System.out.printf("Instance created : %s", instanceName);
        System.out.println("Operation Status: " + response.getStatus());
    }
}
Also used : InsertInstanceRequest(com.google.cloud.compute.v1.InsertInstanceRequest) Instance(com.google.cloud.compute.v1.Instance) InstancesClient(com.google.cloud.compute.v1.InstancesClient) AttachedDisk(com.google.cloud.compute.v1.AttachedDisk) NetworkInterface(com.google.cloud.compute.v1.NetworkInterface) Operation(com.google.cloud.compute.v1.Operation)

Example 8 with Instance

use of com.google.cloud.redis.v1.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 9 with Instance

use of com.google.cloud.redis.v1.Instance 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 10 with Instance

use of com.google.cloud.redis.v1.Instance in project java-bigtable by googleapis.

the class BaseBigtableInstanceAdminClientTest method createInstanceExceptionTest2.

@Test
public void createInstanceExceptionTest2() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockBigtableInstanceAdmin.addException(exception);
    try {
        String parent = "parent-995424086";
        String instanceId = "instanceId902024336";
        Instance instance = Instance.newBuilder().build();
        Map<String, Cluster> clusters = new HashMap<>();
        client.createInstanceAsync(parent, instanceId, instance, clusters).get();
        Assert.fail("No exception raised");
    } catch (ExecutionException e) {
        Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass());
        InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause());
        Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode());
    }
}
Also used : InvalidArgumentException(com.google.api.gax.rpc.InvalidArgumentException) Instance(com.google.bigtable.admin.v2.Instance) HashMap(java.util.HashMap) StatusRuntimeException(io.grpc.StatusRuntimeException) Cluster(com.google.bigtable.admin.v2.Cluster) ByteString(com.google.protobuf.ByteString) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)18 Instance (com.google.cloud.compute.v1.Instance)11 InstancesClient (com.google.cloud.compute.v1.InstancesClient)11 Instance (com.google.bigtable.admin.v2.Instance)10 ByteString (com.google.protobuf.ByteString)9 AbstractMessage (com.google.protobuf.AbstractMessage)8 Operation (com.google.cloud.compute.v1.Operation)7 InsertInstanceRequest (com.google.cloud.compute.v1.InsertInstanceRequest)6 AttachedDisk (com.google.cloud.compute.v1.AttachedDisk)5 NetworkInterface (com.google.cloud.compute.v1.NetworkInterface)5 Instance (com.google.cloud.redis.v1.Instance)5 HashMap (java.util.HashMap)5 InvalidArgumentException (com.google.api.gax.rpc.InvalidArgumentException)4 Cluster (com.google.bigtable.admin.v2.Cluster)4 Instance (com.google.cloud.redis.v1beta1.Instance)4 FieldMask (com.google.protobuf.FieldMask)4 Instance (com.scaleset.cfbuilder.ec2.Instance)4 StatusRuntimeException (io.grpc.StatusRuntimeException)4 Operation (com.google.longrunning.Operation)3 CreateInstanceRequest (com.google.bigtable.admin.v2.CreateInstanceRequest)2