Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(compute): add compute disk regional replicated sample #9697

Merged
merged 8 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* 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_regional_replicated]
import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.InsertRegionDiskRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.RegionDisksClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateReplicatedDisk {

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";
// The region for the replicated disk to reside in.
// The disk must be in the same region as the VM that you plan to attach it to.
String region = "us-central1";
// The zones within the region where the two disk replicas are located
List<String> replicaZones = new ArrayList<>();
replicaZones.add(String.format("projects/%s/zones/%s", projectId, "us-central1-a"));
replicaZones.add(String.format("projects/%s/zones/%s", projectId, "us-central1-b"));
// Name of the disk you want to create.
String diskName = "YOUR_DISK_NAME";
// Size of the new disk in gigabytes.
int diskSizeGb = 100;
// The type of replicated disk. This value uses the following format:
// "regions/{region}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
// For example: "regions/us-west3/diskTypes/pd-ssd"
String diskType = String.format("regions/%s/diskTypes/%s", region, "pd-standard");

createReplicatedDisk(projectId, region, replicaZones, diskName, diskSizeGb, diskType);
}

// Create a disk for synchronous data replication between two zones in the same region
public static Operation.Status createReplicatedDisk(String projectId, String region,
List<String> replicaZones, String diskName, int diskSizeGb, String diskType)
throws IOException, InterruptedException, ExecutionException, 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 (RegionDisksClient regionDisksClient = RegionDisksClient.create()) {
Disk disk = Disk.newBuilder()
.setSizeGb(diskSizeGb)
.setName(diskName)
.setType(diskType)
.addAllReplicaZones(replicaZones)
.build();

InsertRegionDiskRequest insertRegionDiskRequest = InsertRegionDiskRequest.newBuilder()
.setProject(projectId)
.setRegion(region)
.setDiskResource(disk)
.build();

Operation response = regionDisksClient.insertAsync(insertRegionDiskRequest)
.get(3, TimeUnit.MINUTES);

if (response.hasError()) {
throw new Error("Error creating disk! " + response.getError());
}
return response.getStatus();
}
}
}
// [END compute_disk_regional_replicated]
17 changes: 17 additions & 0 deletions compute/cloud-client/src/test/java/compute/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import compute.deleteprotection.SetDeleteProtection;
import compute.disks.DeleteDisk;
import compute.disks.DeleteSnapshot;
import compute.disks.RegionalDelete;
import compute.reservation.DeleteReservation;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -217,6 +218,22 @@ && isCreatedBeforeThresholdTime(disk.getCreationTimestamp())) {
}
}

// Delete regional disks which starts with the given prefixToDelete and
// has creation timestamp >24 hours.
public static void cleanUpExistingRegionalDisks(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I remember seeing this method in another PR as well. Kindly ensure to resolve merge conflicts in the PRs before merging.

String prefixToDelete, String projectId, String region)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
try (RegionDisksClient disksClient = RegionDisksClient.create()) {
for (Disk disk : disksClient.list(projectId, region).iterateAll()) {
if (disk.getName().contains(prefixToDelete)
&& disk.getRegion().equals(region)
&& isCreatedBeforeThresholdTime(disk.getCreationTimestamp())) {
RegionalDelete.deleteRegionalDisk(projectId, region, disk.getName());
}
}
}
}

// Delete snapshots which starts with the given prefixToDelete and
// has creation timestamp >24 hours.
public static void cleanUpExistingSnapshots(String prefixToDelete, String projectId)
Expand Down
23 changes: 16 additions & 7 deletions compute/cloud-client/src/test/java/compute/disks/DisksIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,12 @@ public class DisksIT {
private static String EMPTY_DISK_NAME;
private static String SNAPSHOT_NAME;
private static String DISK_TYPE;

private static String ZONAL_BLANK_DISK;

private static String REGIONAL_BLANK_DISK;

private static String REGIONAL_REPLICATED_DISK;
private static final List<String> replicaZones = Arrays.asList(
String.format("projects/%s/zones/%s-a", PROJECT_ID, REGION),
String.format("projects/%s/zones/%s-b", PROJECT_ID, REGION));
private ByteArrayOutputStream stdOut;

// Check if the required environment variables are set.
Expand Down Expand Up @@ -101,12 +102,13 @@ public static void setup()
DISK_TYPE = String.format("zones/%s/diskTypes/pd-ssd", ZONE);
ZONAL_BLANK_DISK = "gcloud-test-disk-zattach-" + uuid;
REGIONAL_BLANK_DISK = "gcloud-test-disk-rattach-" + uuid;
REGIONAL_REPLICATED_DISK = "gcloud-test-disk-replicated-" + uuid;

// Cleanup existing stale instances.
Util.cleanUpExistingInstances("test-disks", PROJECT_ID, ZONE);
Util.cleanUpExistingDisks("gcloud-test-", PROJECT_ID, ZONE);
Util.cleanUpExistingSnapshots("gcloud-test-snapshot-", PROJECT_ID);

Util.cleanUpExistingRegionalDisks("gcloud-test-disk-", PROJECT_ID, REGION);
// Create disk from image.
Image debianImage = null;
try (ImagesClient imagesClient = ImagesClient.create()) {
Expand Down Expand Up @@ -170,6 +172,7 @@ public static void cleanUp()
DeleteDisk.deleteDisk(PROJECT_ID, ZONE, EMPTY_DISK_NAME);
DeleteDisk.deleteDisk(PROJECT_ID, ZONE, ZONAL_BLANK_DISK);
RegionalDelete.deleteRegionalDisk(PROJECT_ID, REGION, REGIONAL_BLANK_DISK);
RegionalDelete.deleteRegionalDisk(PROJECT_ID, REGION, REGIONAL_REPLICATED_DISK);

stdOut.close();
System.setOut(out);
Expand Down Expand Up @@ -245,9 +248,7 @@ public static void createZonalDisk()
public static void createRegionalDisk()
throws IOException, ExecutionException, InterruptedException, TimeoutException {
String diskType = String.format("regions/%s/diskTypes/pd-balanced", REGION);
List<String> replicaZones = Arrays.asList(
String.format("projects/%s/zones/%s-a", PROJECT_ID, REGION),
String.format("projects/%s/zones/%s-b", PROJECT_ID, REGION));

RegionalCreateFromSource.createRegionalDisk(PROJECT_ID, REGION, replicaZones,
REGIONAL_BLANK_DISK, diskType, 11, Optional.empty(), Optional.empty());
}
Expand Down Expand Up @@ -301,4 +302,12 @@ public void testDiskAttachResize()
Util.getRegionalDisk(PROJECT_ID, REGION, REGIONAL_BLANK_DISK).getSizeGb());
}

@Test
public void testCreateReplicatedDisk()
throws IOException, ExecutionException, InterruptedException, TimeoutException {
Operation.Status status = CreateReplicatedDisk.createReplicatedDisk(PROJECT_ID, REGION,
replicaZones, REGIONAL_REPLICATED_DISK, 100, DISK_TYPE);

assertThat(status).isEqualTo(Operation.Status.DONE);
}
}
Loading