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 create with snapshot schedule #9788

Merged
merged 16 commits into from
Dec 31, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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,71 @@
/*
* 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_with_snapshot_schedule]
import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateDiskWithSnapshotSchedule {
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 projectId = "YOUR_PROJECT_ID";
// Name of the zone in which you want to create the disk.
String zone = "us-central1-a";
// Name of the disk you want to create.
String diskName = "YOUR_DISK_NAME";
// Name of the schedule you want to link to the disk.
String snapshotScheduleName = "YOUR_SCHEDULE_NAME";

createDiskWithSnapshotSchedule(projectId, zone, diskName, snapshotScheduleName);
}

// Creates disk with linked snapshot schedule.
public static Status createDiskWithSnapshotSchedule(
String projectId, String zone, String diskName, String snapshotScheduleName)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
try (DisksClient disksClient = DisksClient.create()) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Add the client initializer comment here.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you! Added comment


// Get the resource policy to link to the disk
String resourcePolicyLink = String.format("projects/%s/regions/%s/resourcePolicies/%s",
projectId, zone.substring(0, zone.lastIndexOf('-')), snapshotScheduleName);
Copy link
Contributor

Choose a reason for hiding this comment

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

Please get the snapshot schedule region as a separate parameter. The snapshot schedule doesn't have to be in the same region as the disk, iiuc?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you! Created region variable.
ZONE: the location where you are creating the disk. The disk must be in a zone that is in the same region as the snapshot schedule.


Disk disk = Disk.newBuilder()
.setName(diskName)
.setZone(zone)
.addAllResourcePolicies(List.of(resourcePolicyLink))
.build();

Operation response = disksClient.insertAsync(projectId, zone, disk).get(3, TimeUnit.MINUTES);

if (response.hasError()) {
throw new Error("Disk creation failed! " + response.getError());
}
return response.getStatus();
}
}
}
// [END compute_disk_create_with_snapshot_schedule]
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
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.Operation.Status;
import com.google.cloud.compute.v1.RegionDisksClient;
import java.io.IOException;
import java.util.ArrayList;
Expand Down Expand Up @@ -55,7 +56,7 @@ public static void main(String[] args)
}

// Create a disk for synchronous data replication between two zones in the same region
public static Operation.Status createReplicatedDisk(String projectId, String region,
public static 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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
* 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.snapshotschedule;

// [START compute_snapshot_schedule_create]
Copy link
Contributor

Choose a reason for hiding this comment

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

Why is this sample duplicated?
It is already present in: #9742

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I need this classes for testing.

Copy link
Contributor

Choose a reason for hiding this comment

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

Once the other PR is merged, you can utilize those classes. Kindly remove the Create and Delete samples from this PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you! Deleted

import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.ResourcePoliciesClient;
import com.google.cloud.compute.v1.ResourcePolicy;
import com.google.cloud.compute.v1.ResourcePolicyHourlyCycle;
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicy;
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicyRetentionPolicy;
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicySchedule;
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicySnapshotProperties;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateSnapshotSchedule {
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 projectId = "YOUR_PROJECT_ID";
// Name of the region in which you want to create the snapshot schedule.
String region = "us-central1";
// Name of the snapshot schedule you want to create.
String snapshotScheduleName = "YOUR_SCHEDULE_NAME";
// Description of the snapshot schedule.
String scheduleDescription = "YOUR_SCHEDULE_DESCRIPTION";
// Maximum number of days to retain snapshots.
int maxRetentionDays = 10;
// Storage location for the snapshots.
// More about storage locations:
// https://cloud.google.com/compute/docs/disks/snapshots?authuser=0#selecting_a_storage_location
String storageLocation = "US";
// Determines what happens to your snapshots if the source disk is deleted.
String onSourceDiskDelete = "KEEP_AUTO_SNAPSHOTS";

createSnapshotSchedule(projectId, region, snapshotScheduleName, scheduleDescription,
maxRetentionDays, storageLocation, onSourceDiskDelete);
}

// Creates a snapshot schedule policy.
public static Operation.Status createSnapshotSchedule(String projectId, String region,
String snapshotScheduleName, String scheduleDescription, int maxRetentionDays,
String storageLocation, String onSourceDiskDelete)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
String startTime = "08:00";
ResourcePolicySnapshotSchedulePolicySnapshotProperties snapshotProperties =
ResourcePolicySnapshotSchedulePolicySnapshotProperties.newBuilder()
.addStorageLocations(storageLocation)
.build();

// Define the hourly schedule:
int snapshotInterval = 10; // Create a snapshot every 10 hours
ResourcePolicyHourlyCycle hourlyCycle = ResourcePolicyHourlyCycle.newBuilder()
.setHoursInCycle(snapshotInterval)
.setStartTime(startTime)
.build();

// Define the daily schedule.
// ResourcePolicyDailyCycle dailySchedule =
// ResourcePolicyDailyCycle.newBuilder()
// .setDaysInCycle(1) // Every day
// .setStartTime(startTime)
// .build();

// Define the weekly schedule.
// List<ResourcePolicyWeeklyCycleDayOfWeek> dayOfWeeks = new ArrayList<>();
// ResourcePolicyWeeklyCycleDayOfWeek tuesdaySchedule =
// ResourcePolicyWeeklyCycleDayOfWeek.newBuilder()
// .setDay(ResourcePolicyWeeklyCycleDayOfWeek.Day.TUESDAY.toString())
// .setStartTime(startTime)
// .build();
// dayOfWeeks.add(tuesdaySchedule);
//
// ResourcePolicyWeeklyCycle weeklyCycle = ResourcePolicyWeeklyCycle.newBuilder()
// .addAllDayOfWeeks(dayOfWeeks)
// .build();

ResourcePolicySnapshotSchedulePolicyRetentionPolicy retentionPolicy =
ResourcePolicySnapshotSchedulePolicyRetentionPolicy.newBuilder()
.setMaxRetentionDays(maxRetentionDays)
.setOnSourceDiskDelete(onSourceDiskDelete)
.build();

ResourcePolicySnapshotSchedulePolicy snapshotSchedulePolicy =
ResourcePolicySnapshotSchedulePolicy.newBuilder()
.setRetentionPolicy(retentionPolicy)
.setSchedule(ResourcePolicySnapshotSchedulePolicySchedule.newBuilder()
// You can set only one of the following options:
.setHourlySchedule(hourlyCycle) //Set Hourly Schedule
// .setDailySchedule(dailySchedule) //Set Daily Schedule
// .setWeeklySchedule(weeklyCycle) // Set Weekly Schedule
.build())
.setSnapshotProperties(snapshotProperties)
.build();

ResourcePolicy resourcePolicy = ResourcePolicy.newBuilder()
.setName(snapshotScheduleName)
.setDescription(scheduleDescription)
.setSnapshotSchedulePolicy(snapshotSchedulePolicy)
.build();

// 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 (ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.create()) {

Operation response = resourcePoliciesClient.insertAsync(projectId, region, resourcePolicy)
.get(3, TimeUnit.MINUTES);

if (response.hasError()) {
throw new Error("Snapshot schedule creation failed! " + response.getError());
}
return response.getStatus();
}
}
}
// [END compute_snapshot_schedule_create]
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* 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.snapshotschedule;

// [START compute_snapshot_schedule_delete]
Copy link
Contributor

Choose a reason for hiding this comment

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

Why is this sample duplicated?
It is already present in: #9742

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I need this classes for testing.

Copy link
Contributor

Choose a reason for hiding this comment

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

ditto. Once the other PR is merged, you can utilize those classes. Kindly remove the Create and Delete samples from this PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you! Deleted

import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.ResourcePoliciesClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteSnapshotSchedule {
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 projectId = "YOUR_PROJECT_ID";
// Name of the region where your snapshot schedule is located.
String region = "us-central1";
// Name of the snapshot schedule you want to delete.
String snapshotScheduleName = "YOUR_SCHEDULE_NAME";

deleteSnapshotSchedule(projectId, region, snapshotScheduleName);
}

// Deletes a snapshot schedule policy.
public static Operation.Status deleteSnapshotSchedule(
String projectId, String region, String snapshotScheduleName)
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 (ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.create()) {
Operation response = resourcePoliciesClient
.deleteAsync(projectId, region, snapshotScheduleName)
.get(3, TimeUnit.MINUTES);

if (response.hasError()) {
throw new Error("Snapshot schedule deletion failed! " + response.getError());
}
return response.getStatus();
}
}
}
// [END compute_snapshot_schedule_delete]
24 changes: 24 additions & 0 deletions compute/cloud-client/src/test/java/compute/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
import com.google.cloud.compute.v1.RegionInstanceTemplatesClient;
import com.google.cloud.compute.v1.Reservation;
import com.google.cloud.compute.v1.ReservationsClient;
import com.google.cloud.compute.v1.ResourcePoliciesClient;
import com.google.cloud.compute.v1.ResourcePolicy;
import com.google.cloud.compute.v1.Snapshot;
import com.google.cloud.compute.v1.SnapshotsClient;
import com.google.cloud.compute.v1.StoragePool;
Expand All @@ -39,7 +41,9 @@
import compute.disks.DeleteSnapshot;
import compute.disks.RegionalDelete;
import compute.reservation.DeleteReservation;
import compute.snapshotschedule.DeleteSnapshotSchedule;
import java.io.IOException;
import java.lang.Error;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Instant;
Expand Down Expand Up @@ -283,6 +287,21 @@ public static void deleteStoragePool(String project, String zone, String storage
}
}

// Delete storagePools which starts with the given prefixToDelete and
// has creation timestamp >24 hours.
public static void cleanUpExistingSnapshotSchedule(
String prefixToDelete, String projectId, String region)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
try (ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.create()) {
for (ResourcePolicy resource : resourcePoliciesClient.list(projectId, region).iterateAll()) {
if (containPrefixToDeleteAndZone(resource, prefixToDelete, region)
&& isCreatedBeforeThresholdTime(resource.getCreationTimestamp())) {
DeleteSnapshotSchedule.deleteSnapshotSchedule(projectId, region, resource.getName());
}
}
}
}

public static boolean containPrefixToDeleteAndZone(
Object resource, String prefixToDelete, String zone) {
boolean containPrefixAndZone = false;
Expand All @@ -308,6 +327,11 @@ public static boolean containPrefixToDeleteAndZone(
containPrefixAndZone = ((StoragePool) resource).getName().contains(prefixToDelete)
&& ((StoragePool) resource).getZone().contains(zone);
}
if (resource instanceof ResourcePolicy) {
containPrefixAndZone = ((ResourcePolicy) resource).getName().contains(prefixToDelete)
&& ((ResourcePolicy) resource).getRegion()
.contains(zone.substring(0, zone.lastIndexOf('-')));
}
} catch (NullPointerException e) {
System.out.println("Resource not found, skipping deletion:");
}
Expand Down
Loading
Loading