Skip to content

Commit

Permalink
Fixed code as requested in the comments
Browse files Browse the repository at this point in the history
  • Loading branch information
TetyanaYahodska committed Dec 30, 2024
2 parents 1f80e08 + 673b387 commit 9e093f4
Show file tree
Hide file tree
Showing 15 changed files with 839 additions and 43 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package compute.disks;

// [START compute_instance_attach_regional_disk_force]
import com.google.cloud.compute.v1.AttachDiskInstanceRequest;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class AttachRegionalDiskForce {
public static void main(String[] args)
throws IOException, InterruptedException, ExecutionException, TimeoutException {
// TODO(developer): Replace these variables before running the sample.
// Project ID or project number of the Cloud project you want to use.
String projectId = "YOUR_PROJECT_ID";
// Name of the zone of your compute instance.
String zone = "us-central1-a";
// The name of the compute instance where you are adding the replicated disk.
String instanceName = "YOUR_INSTANCE_NAME";
// The region where your replicated disk is located.
String region = "us-central1";
// The name of the replicated disk.
String diskName = "YOUR_DISK_NAME";

attachRegionalDiskForce(projectId, zone, instanceName, region, diskName);
}

// Attaches a regional disk to the instance,
// forcing the attachment even if other VMs are using the disk.
public static Status attachRegionalDiskForce(String projectId,
String zone, String instanceName, String region, String diskName)
throws IOException, InterruptedException, ExecutionException, TimeoutException {
String diskLink = String.format("projects/%s/regions/%s/disks/%s",
projectId, region, diskName);
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests.
try (InstancesClient instancesClient = InstancesClient.create()) {
AttachedDisk attachedDisk = AttachedDisk.newBuilder()
.setSource(diskLink)
.setMode(AttachedDisk.Mode.READ_WRITE.toString())
.build();

AttachDiskInstanceRequest attachDiskRequest = AttachDiskInstanceRequest.newBuilder()
.setProject(projectId)
.setZone(zone)
.setInstance(instanceName)
.setAttachedDiskResource(attachedDisk)
.setForceAttach(true) // Force the attachment
.build();

Operation response = instancesClient.attachDiskAsync(attachDiskRequest)
.get(3, TimeUnit.MINUTES);

if (response.hasError()) {
throw new Error("Error attaching regional disk! " + response);
}
return response.getStatus();
}
}
}
// [END compute_instance_attach_regional_disk_force]
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package compute.disks;

// [START compute_disk_create_secondary]
import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DiskAsyncReplication;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateDiskSecondaryZonal {
public static void main(String[] args)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
// TODO(developer): Replace these variables before running the sample.
// The project that contains the primary disk.
String primaryProjectId = "PRIMARY_PROJECT_ID";
// The project that contains the secondary disk.
String secondaryProjectId = "SECONDARY_PROJECT_ID";
// Name of the primary disk you want to use.
String primaryDiskName = "PRIMARY_DISK_NAME";
// Name of the zone in which your primary disk is located.
// Learn more about zones and regions:
// https://cloud.google.com/compute/docs/disks/async-pd/about#supported_region_pairs
String primaryDiskZone = "us-central1-a";
// Name of the disk you want to create.
String secondaryDiskName = "SECONDARY_DISK_NAME";
// Name of the zone in which you want to create the secondary disk.
String secondaryDiskZone = "us-east1-c";
// Size of the new disk in gigabytes.
long diskSizeGb = 30L;
// The type of the disk you want to create. This value uses the following format:
// "projects/{projectId}/zones/{zone}/diskTypes/
// (pd-standard|pd-ssd|pd-balanced|pd-extreme)".
String diskType = String.format(
"projects/%s/zones/%s/diskTypes/pd-balanced", secondaryProjectId, secondaryDiskZone);

createDiskSecondaryZonal(primaryProjectId, secondaryProjectId, primaryDiskName,
secondaryDiskName, primaryDiskZone, secondaryDiskZone, diskSizeGb, diskType);
}

// Creates a secondary disk in a specified zone.
public static Operation.Status createDiskSecondaryZonal(String primaryProjectId,
String secondaryProjectId, String primaryDiskName, String secondaryDiskName,
String primaryDiskZone, String secondaryDiskZone, long diskSizeGb, String diskType)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests.
try (DisksClient disksClient = DisksClient.create()) {
String primaryDiskSource = String.format("projects/%s/zones/%s/disks/%s",
primaryProjectId, primaryDiskZone, primaryDiskName);

DiskAsyncReplication asyncReplication = DiskAsyncReplication.newBuilder()
.setDisk(primaryDiskSource)
.build();
Disk disk = Disk.newBuilder()
.setName(secondaryDiskName)
.setZone(secondaryDiskZone)
.setSizeGb(diskSizeGb)
.setType(diskType)
.setAsyncPrimaryDisk(asyncReplication)
.build();

Operation response = disksClient.insertAsync(secondaryProjectId, secondaryDiskZone, disk)
.get(3, TimeUnit.MINUTES);

if (response.hasError()) {
throw new Error("Error creating secondary disks! " + response.getError());
}
return response.getStatus();
}
}
}
// [END compute_disk_create_secondary]

Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package compute.disks;

//[START compute_disk_create_secondary_custom]
import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DiskAsyncReplication;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.GuestOsFeature;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateSecondaryCustomDisk {
public static void main(String[] args)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
// TODO(developer): Replace these variables before running the sample.
// The project that contains the primary disk.
String primaryProjectId = "PRIMARY_PROJECT_ID";
// The project that contains the secondary disk.
String secondaryProjectId = "SECONDARY_PROJECT_ID";
// Name of the primary disk you want to use.
String primaryDiskName = "PRIMARY_DISK_NAME";
// Name of the zone in which your primary disk is located.
// Learn more about zones and regions:
// https://cloud.google.com/compute/docs/disks/async-pd/about#supported_region_pairs
String primaryDiskZone = "us-central1-a";
// Name of the disk you want to create.
String secondaryDiskName = "SECONDARY_DISK_NAME";
// Name of the zone in which you want to create the secondary disk.
String secondaryDiskZone = "us-east1-c";
// Size of the new disk in gigabytes.
long diskSizeGb = 30L;
// The type of the disk you want to create. This value uses the following format:
// "projects/{projectId}/zones/{zone}/diskTypes/
// (pd-standard|pd-ssd|pd-balanced|pd-extreme)".
String diskType = String.format(
"projects/%s/zones/%s/diskTypes/pd-balanced", secondaryProjectId, secondaryDiskZone);

createSecondaryCustomDisk(primaryProjectId, secondaryProjectId, primaryDiskName,
secondaryDiskName, primaryDiskZone, secondaryDiskZone, diskSizeGb, diskType);
}

// Creates a secondary disk with specified custom parameters.
public static Status createSecondaryCustomDisk(String primaryProjectId, String secondaryProjectId,
String primaryDiskName, String secondaryDiskName, String primaryDiskZone,
String secondaryDiskZone, long diskSizeGb, String diskType)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests.
try (DisksClient disksClient = DisksClient.create()) {
String primaryDiskSource = String.format("projects/%s/zones/%s/disks/%s",
primaryProjectId, primaryDiskZone, primaryDiskName);

DiskAsyncReplication asyncReplication = DiskAsyncReplication.newBuilder()
.setDisk(primaryDiskSource)
.build();

// Define the guest OS features.
List<GuestOsFeature> guestOsFeatures = Arrays.asList(
GuestOsFeature.newBuilder().setType("UEFI_COMPATIBLE").build(),
GuestOsFeature.newBuilder().setType("GVNIC").build(),
GuestOsFeature.newBuilder().setType("MULTI_IP_SUBNET").build());

// Define the labels.
Map<String, String> labels = new HashMap<>();
labels.put("secondary-disk-for-replication", "yes");

Disk disk = Disk.newBuilder()
.setName(secondaryDiskName)
.setSizeGb(diskSizeGb)
.setType(diskType)
.setZone(secondaryDiskZone)
.addAllGuestOsFeatures(guestOsFeatures)
.putAllLabels(labels)
.setAsyncPrimaryDisk(asyncReplication)
.build();

// Wait for the create disk operation to complete.
Operation response = disksClient.insertAsync(secondaryProjectId, secondaryDiskZone, disk)
.get(3, TimeUnit.MINUTES);

if (response.hasError()) {
throw new Error("Error creating secondary custom disks! " + response.getError());
}
return response.getStatus();
}
}
}
// [END compute_disk_create_secondary_custom]
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package compute.disks.consistencygroup;

// [START compute_consistency_group_clone_regional_disk]
import com.google.cloud.compute.v1.BulkInsertDiskResource;
import com.google.cloud.compute.v1.BulkInsertRegionDiskRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.RegionDisksClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CloneRegionalDisksFromConsistencyGroup {

public static void main(String[] args)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
// TODO(developer): Replace these variables before running the sample.
// Project ID or project number of the Cloud project you want to use.
String project = "YOUR_PROJECT_ID";
// Region in which your disks and consistency group are located.
String region = "us-central1";
// Name of the consistency group you want to clone disks from.
String consistencyGroupName = "YOUR_CONSISTENCY_GROUP_NAME";

cloneRegionalDisksFromConsistencyGroup(project, region, consistencyGroupName);
}

// Clones regional disks from a consistency group.
public static Status cloneRegionalDisksFromConsistencyGroup(
String project, String region, String consistencyGroupName)
throws IOException, InterruptedException, ExecutionException, TimeoutException {
String sourceConsistencyGroupPolicy = String.format(
"projects/%s/regions/%s/resourcePolicies/%s", project, region, consistencyGroupName);

// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests.
try (RegionDisksClient disksClient = RegionDisksClient.create()) {
BulkInsertRegionDiskRequest request = BulkInsertRegionDiskRequest.newBuilder()
.setProject(project)
.setRegion(region)
.setBulkInsertDiskResourceResource(
BulkInsertDiskResource.newBuilder()
.setSourceConsistencyGroupPolicy(sourceConsistencyGroupPolicy)
.build())
.build();

Operation response = disksClient.bulkInsertAsync(request).get(3, TimeUnit.MINUTES);

if (response.hasError()) {
throw new Error("Error cloning regional disks! " + response.getError());
}
return response.getStatus();
}
}
}
// [END compute_consistency_group_clone_regional_disk]
Loading

0 comments on commit 9e093f4

Please sign in to comment.