Search in sources :

Example 46 with Instance

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

the class CreateWindowsOsImage method createWindowsOsImage.

// Creates a new Windows image from the specified source disk.
public static void createWindowsOsImage(String project, String zone, String sourceDiskName, String imageName, String storageLocation, boolean forceCreate) throws IOException, ExecutionException, InterruptedException, TimeoutException {
    try (ImagesClient imagesClient = ImagesClient.create();
        InstancesClient instancesClient = InstancesClient.create();
        DisksClient disksClient = DisksClient.create()) {
        Disk disk = disksClient.get(project, zone, sourceDiskName);
        // Getting instances where source disk is attached.
        for (String fullInstanceName : disk.getUsersList()) {
            Map<String, String> instanceInfo = parseInstanceName(fullInstanceName);
            Instance instance = instancesClient.get(instanceInfo.get("instanceProjectId"), instanceInfo.get("instanceZone"), instanceInfo.get("instanceName"));
            // Сhecking whether the instances is stopped.
            if (!Arrays.asList("TERMINATED", "STOPPED").contains(instance.getStatus()) && !forceCreate) {
                throw new IllegalStateException(String.format("Instance %s should be stopped. Please stop the instance using GCESysprep command or set forceCreate parameter to true (not recommended). More information here: https://cloud.google.com/compute/docs/instances/windows/creating-windows-os-image#api.", instanceInfo.get("instanceName")));
            }
        }
        if (forceCreate) {
            System.out.println("Warning: forceCreate option compromise the integrity of your image. " + "Stop the instance before you create the image if possible.");
        }
        // Create Image.
        Image image = Image.newBuilder().setName(imageName).setSourceDisk(String.format("/zones/%s/disks/%s", zone, sourceDiskName)).addStorageLocations(storageLocation.isEmpty() ? "" : storageLocation).build();
        InsertImageRequest insertImageRequest = InsertImageRequest.newBuilder().setProject(project).setForceCreate(forceCreate).setImageResource(image).build();
        Operation response = imagesClient.insertAsync(insertImageRequest).get(3, TimeUnit.MINUTES);
        if (response.hasError()) {
            System.out.println("Windows OS Image creation failed ! ! " + response);
            return;
        }
        System.out.println("Image created.");
    }
}
Also used : Instance(com.google.cloud.compute.v1.Instance) InstancesClient(com.google.cloud.compute.v1.InstancesClient) InsertImageRequest(com.google.cloud.compute.v1.InsertImageRequest) Operation(com.google.cloud.compute.v1.Operation) ImagesClient(com.google.cloud.compute.v1.ImagesClient) Image(com.google.cloud.compute.v1.Image) Disk(com.google.cloud.compute.v1.Disk) DisksClient(com.google.cloud.compute.v1.DisksClient)

Example 47 with Instance

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

the class ListInstanceTemplates method listInstanceTemplates.

// Get a list of InstanceTemplate objects available in a project.
public static ListPagedResponse listInstanceTemplates(String projectId) throws IOException {
    try (InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create()) {
        int count = 0;
        System.out.println("Listing instance templates...");
        ListPagedResponse templates = instanceTemplatesClient.list(projectId);
        for (InstanceTemplate instanceTemplate : templates.iterateAll()) {
            System.out.printf("%s. %s%n", ++count, instanceTemplate.getName());
        }
        return templates;
    }
}
Also used : ListPagedResponse(com.google.cloud.compute.v1.InstanceTemplatesClient.ListPagedResponse) InstanceTemplatesClient(com.google.cloud.compute.v1.InstanceTemplatesClient) InstanceTemplate(com.google.cloud.compute.v1.InstanceTemplate)

Example 48 with Instance

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

the class ResumeInstance method resumeInstance.

// Resume a suspended Google Compute Engine instance (with unencrypted disks).
// Instance state changes to RUNNING, if successfully resumed.
public static void resumeInstance(String project, String zone, String instanceName) throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Instantiates a client.
    try (InstancesClient instancesClient = InstancesClient.create()) {
        String currentInstanceState = instancesClient.get(project, zone, instanceName).getStatus();
        // Check if the instance is currently suspended.
        if (!currentInstanceState.equalsIgnoreCase(Status.SUSPENDED.toString())) {
            throw new RuntimeException(String.format("Only suspended instances can be resumed. Instance %s is in %s state.", instanceName, currentInstanceState));
        }
        Operation operation = instancesClient.resumeAsync(project, zone, instanceName).get(300, TimeUnit.SECONDS);
        if (operation.hasError() || !instancesClient.get(project, zone, instanceName).getStatus().equalsIgnoreCase(Status.RUNNING.toString())) {
            System.out.println("Cannot resume instance. Try again!");
            return;
        }
        System.out.printf("Instance resumed successfully ! %s", instanceName);
    }
}
Also used : InstancesClient(com.google.cloud.compute.v1.InstancesClient) Operation(com.google.cloud.compute.v1.Operation)

Example 49 with Instance

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

the class SuspendInstance method suspendInstance.

// Suspend a running Google Compute Engine instance.
// For limitations and compatibility on which instances can be suspended,
// see: https://cloud.google.com/compute/docs/instances/suspend-resume-instance#limitations
public static void suspendInstance(String project, String zone, String instanceName) throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Instantiates a client.
    try (InstancesClient instancesClient = InstancesClient.create()) {
        Operation operation = instancesClient.suspendAsync(project, zone, instanceName).get(300, TimeUnit.SECONDS);
        if (operation.hasError() || !instancesClient.get(project, zone, instanceName).getStatus().equalsIgnoreCase(Status.SUSPENDED.toString())) {
            System.out.println("Cannot suspend instance. Try again!");
            return;
        }
        System.out.printf("Instance suspended successfully ! %s", instanceName);
    }
}
Also used : InstancesClient(com.google.cloud.compute.v1.InstancesClient) Operation(com.google.cloud.compute.v1.Operation)

Example 50 with Instance

use of com.google.cloud.compute.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)

Aggregations

Test (org.junit.Test)41 Instance (com.google.cloud.redis.v1beta1.Instance)34 CloudRedisClient (com.google.cloud.redis.v1beta1.CloudRedisClient)30 InstancesClient (com.google.cloud.compute.v1.InstancesClient)29 Operation (com.google.cloud.compute.v1.Operation)29 Instance (com.google.cloud.compute.v1.Instance)25 ByteString (com.google.protobuf.ByteString)17 AttachedDisk (com.google.cloud.compute.v1.AttachedDisk)16 AbstractMessage (com.google.protobuf.AbstractMessage)13 InsertInstanceRequest (com.google.cloud.compute.v1.InsertInstanceRequest)11 Instance (com.google.spanner.admin.instance.v1.Instance)11 Instance (com.google.bigtable.admin.v2.Instance)10 InstanceTemplatesClient (com.google.cloud.compute.v1.InstanceTemplatesClient)9 Instance (com.google.cloud.notebooks.v1beta1.Instance)9 ArrayList (java.util.ArrayList)8 InvalidArgumentException (com.google.api.gax.rpc.InvalidArgumentException)7 InstanceTemplate (com.google.cloud.compute.v1.InstanceTemplate)7 NetworkInterface (com.google.cloud.compute.v1.NetworkInterface)7 Any (com.google.protobuf.Any)7 FieldMask (com.google.protobuf.FieldMask)7