Skip to content

Commit 07c0c57

Browse files
Implemented compute_snapshot_schedule_attach sample, created test
1 parent fc31f6b commit 07c0c57

File tree

4 files changed

+383
-0
lines changed

4 files changed

+383
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
* Copyright 2024 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package compute.snapshot;
18+
19+
// [START compute_snapshot_schedule_attach]
20+
import com.google.cloud.compute.v1.AddResourcePoliciesDiskRequest;
21+
import com.google.cloud.compute.v1.DisksAddResourcePoliciesRequest;
22+
import com.google.cloud.compute.v1.DisksClient;
23+
import com.google.cloud.compute.v1.Operation;
24+
import java.io.IOException;
25+
import java.util.concurrent.ExecutionException;
26+
import java.util.concurrent.TimeUnit;
27+
import java.util.concurrent.TimeoutException;
28+
29+
public class AttachSnapshotScheduleToDisk {
30+
public static void main(String[] args) throws Exception {
31+
// TODO(developer): Replace these variables before running the sample.
32+
// Project ID or project number of the Cloud project you want to use.
33+
String projectId = "YOUR_PROJECT_ID";
34+
// Name of the zone where your disk is located.
35+
String zone = "us-central1-a";
36+
// Name of the disk you want to attach the snapshot schedule to.
37+
String diskName = "YOUR_DISK_NAME";
38+
// Name of the snapshot schedule you want to attach.
39+
String snapshotScheduleName = "YOUR_SNAPSHOT_SCHEDULE_NAME";
40+
// Name of the region where your snapshot schedule is located.
41+
String region = "us-central1";
42+
43+
attachSnapshotScheduleToDisk(projectId, zone, diskName, snapshotScheduleName, region);
44+
}
45+
46+
// Attaches a snapshot schedule to a disk.
47+
public static Operation.Status attachSnapshotScheduleToDisk(
48+
String projectId, String zone, String diskName, String snapshotScheduleName, String region)
49+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
50+
51+
String resourcePolicyLink = String.format(
52+
"projects/%s/regions/%s/resourcePolicies/%s", projectId, region, snapshotScheduleName);
53+
try (DisksClient disksClient = DisksClient.create()) {
54+
55+
AddResourcePoliciesDiskRequest request = AddResourcePoliciesDiskRequest.newBuilder()
56+
.setDisk(diskName)
57+
.setDisksAddResourcePoliciesRequestResource(
58+
DisksAddResourcePoliciesRequest.newBuilder()
59+
.addResourcePolicies(resourcePolicyLink)
60+
.build())
61+
.setProject(projectId)
62+
.setZone(zone)
63+
.build();
64+
65+
Operation response = disksClient.addResourcePoliciesAsync(request).get(1, TimeUnit.MINUTES);
66+
67+
if (response.hasError()) {
68+
throw new Error("Error attaching snapshot schedule to disk: " + response.getError());
69+
}
70+
return response.getStatus();
71+
}
72+
}
73+
}
74+
// [END compute_snapshot_schedule_attach]
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
/*
2+
* Copyright 2024 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package compute.snapshot;
18+
19+
// [START compute_snapshot_schedule_create]
20+
import com.google.cloud.compute.v1.Operation;
21+
import com.google.cloud.compute.v1.ResourcePoliciesClient;
22+
import com.google.cloud.compute.v1.ResourcePolicy;
23+
import com.google.cloud.compute.v1.ResourcePolicyHourlyCycle;
24+
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicy;
25+
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicyRetentionPolicy;
26+
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicySchedule;
27+
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicySnapshotProperties;
28+
import java.io.IOException;
29+
import java.util.concurrent.ExecutionException;
30+
import java.util.concurrent.TimeUnit;
31+
import java.util.concurrent.TimeoutException;
32+
33+
public class CreateSnapshotSchedule {
34+
public static void main(String[] args)
35+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
36+
// TODO(developer): Replace these variables before running the sample.
37+
// Project ID or project number of the Cloud project you want to use.
38+
String projectId = "YOUR_PROJECT_ID";
39+
// Name of the region in which you want to create the snapshot schedule.
40+
String region = "us-central1";
41+
// Name of the snapshot schedule you want to create.
42+
String scheduleName = "YOUR_SCHEDULE_NAME";
43+
// Description of the snapshot schedule.
44+
String scheduleDescription = "YOUR_SCHEDULE_DESCRIPTION";
45+
// Maximum number of days to retain snapshots.
46+
int maxRetentionDays = 10;
47+
// Storage location for the snapshots.
48+
// More about storage locations:
49+
// https://cloud.google.com/compute/docs/disks/snapshots?authuser=0#selecting_a_storage_location
50+
String storageLocation = "US";
51+
// Determines what happens to your snapshots if the source disk is deleted.
52+
String onSourceDiskDelete = "KEEP_AUTO_SNAPSHOTS";
53+
54+
createSnapshotSchedule(projectId, region, scheduleName, scheduleDescription, maxRetentionDays,
55+
storageLocation, onSourceDiskDelete);
56+
}
57+
58+
// Creates a snapshot schedule policy.
59+
public static Operation.Status createSnapshotSchedule(String projectId, String region,
60+
String scheduleName, String scheduleDescription, int maxRetentionDays,
61+
String storageLocation, String onSourceDiskDelete)
62+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
63+
String startTime = "08:00";
64+
ResourcePolicySnapshotSchedulePolicySnapshotProperties snapshotProperties =
65+
ResourcePolicySnapshotSchedulePolicySnapshotProperties.newBuilder()
66+
.addStorageLocations(storageLocation)
67+
.build();
68+
69+
// Define the hourly schedule:
70+
int snapshotInterval = 10; // Create a snapshot every 10 hours
71+
ResourcePolicyHourlyCycle hourlyCycle = ResourcePolicyHourlyCycle.newBuilder()
72+
.setHoursInCycle(snapshotInterval)
73+
.setStartTime(startTime)
74+
.build();
75+
76+
// Define the daily schedule.
77+
// ResourcePolicyDailyCycle dailySchedule =
78+
// ResourcePolicyDailyCycle.newBuilder()
79+
// .setDaysInCycle(1) // Every day
80+
// .setStartTime(startTime)
81+
// .build();
82+
83+
// Define the weekly schedule.
84+
// List<ResourcePolicyWeeklyCycleDayOfWeek> dayOfWeeks = new ArrayList<>();
85+
// ResourcePolicyWeeklyCycleDayOfWeek tuesdaySchedule =
86+
// ResourcePolicyWeeklyCycleDayOfWeek.newBuilder()
87+
// .setDay(ResourcePolicyWeeklyCycleDayOfWeek.Day.TUESDAY.toString())
88+
// .setStartTime(startTime)
89+
// .build();
90+
// dayOfWeeks.add(tuesdaySchedule);
91+
//
92+
// ResourcePolicyWeeklyCycle weeklyCycle = ResourcePolicyWeeklyCycle.newBuilder()
93+
// .addAllDayOfWeeks(dayOfWeeks)
94+
// .build();
95+
96+
ResourcePolicySnapshotSchedulePolicyRetentionPolicy retentionPolicy =
97+
ResourcePolicySnapshotSchedulePolicyRetentionPolicy.newBuilder()
98+
.setMaxRetentionDays(maxRetentionDays)
99+
.setOnSourceDiskDelete(onSourceDiskDelete)
100+
.build();
101+
102+
ResourcePolicySnapshotSchedulePolicy snapshotSchedulePolicy =
103+
ResourcePolicySnapshotSchedulePolicy.newBuilder()
104+
.setRetentionPolicy(retentionPolicy)
105+
.setSchedule(ResourcePolicySnapshotSchedulePolicySchedule.newBuilder()
106+
// You can set only one of the following options:
107+
.setHourlySchedule(hourlyCycle) //Set Hourly Schedule
108+
// .setDailySchedule(dailySchedule) //Set Daily Schedule
109+
// .setWeeklySchedule(weeklyCycle) // Set Weekly Schedule
110+
.build())
111+
.setSnapshotProperties(snapshotProperties)
112+
.build();
113+
114+
ResourcePolicy resourcePolicy = ResourcePolicy.newBuilder()
115+
.setName(scheduleName)
116+
.setDescription(scheduleDescription)
117+
.setSnapshotSchedulePolicy(snapshotSchedulePolicy)
118+
.build();
119+
120+
// Initialize client that will be used to send requests. This client only needs to be created
121+
// once, and can be reused for multiple requests.
122+
try (ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.create()) {
123+
124+
Operation response = resourcePoliciesClient.insertAsync(projectId, region, resourcePolicy)
125+
.get(3, TimeUnit.MINUTES);
126+
127+
if (response.hasError()) {
128+
System.out.printf("Snapshot schedule creation failed: %s%n", response.getError());
129+
return null;
130+
}
131+
return response.getStatus();
132+
}
133+
}
134+
}
135+
// [END compute_snapshot_schedule_create]
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Copyright 2024 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package compute.snapshot;
18+
19+
// [START compute_snapshot_schedule_delete]
20+
import com.google.cloud.compute.v1.Operation;
21+
import com.google.cloud.compute.v1.ResourcePoliciesClient;
22+
import java.io.IOException;
23+
import java.util.concurrent.ExecutionException;
24+
import java.util.concurrent.TimeUnit;
25+
import java.util.concurrent.TimeoutException;
26+
27+
public class DeleteSnapshotSchedule {
28+
public static void main(String[] args)
29+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
30+
// TODO(developer): Replace these variables before running the sample.
31+
// Project ID or project number of the Cloud project you want to use.
32+
String projectId = "YOUR_PROJECT_ID";
33+
// Name of the region where your snapshot schedule is located.
34+
String region = "us-central1";
35+
// Name of the snapshot schedule you want to delete.
36+
String scheduleName = "YOUR_SCHEDULE_NAME";
37+
38+
deleteSnapshotSchedule(projectId, region, scheduleName);
39+
}
40+
41+
// Deletes a snapshot schedule policy.
42+
public static Operation.Status deleteSnapshotSchedule(
43+
String projectId, String region, String scheduleName)
44+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
45+
// Initialize client that will be used to send requests. This client only needs to be created
46+
// once, and can be reused for multiple requests.
47+
try (ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.create()) {
48+
Operation response = resourcePoliciesClient.deleteAsync(projectId, region, scheduleName)
49+
.get(3, TimeUnit.MINUTES);
50+
51+
if (response.hasError()) {
52+
System.out.printf("Snapshot schedule deletion failed: %s%n", response.getError());
53+
return null;
54+
}
55+
return response.getStatus();
56+
}
57+
}
58+
}
59+
// [END compute_snapshot_schedule_delete]
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
/*
2+
* Copyright 2024 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package compute.snapshotschedule;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
import static com.google.common.truth.Truth.assertWithMessage;
21+
22+
import com.google.cloud.compute.v1.Operation;
23+
import compute.disks.CreateEmptyDisk;
24+
import compute.disks.DeleteDisk;
25+
import compute.snapshot.AttachSnapshotScheduleToDisk;
26+
import compute.snapshot.CreateSnapshotSchedule;
27+
import compute.snapshot.DeleteSnapshotSchedule;
28+
import java.io.IOException;
29+
import java.util.UUID;
30+
import java.util.concurrent.ExecutionException;
31+
import java.util.concurrent.TimeUnit;
32+
import java.util.concurrent.TimeoutException;
33+
import org.junit.jupiter.api.AfterAll;
34+
import org.junit.jupiter.api.BeforeAll;
35+
import org.junit.jupiter.api.MethodOrderer;
36+
import org.junit.jupiter.api.Order;
37+
import org.junit.jupiter.api.Test;
38+
import org.junit.jupiter.api.TestMethodOrder;
39+
import org.junit.jupiter.api.Timeout;
40+
import org.junit.runner.RunWith;
41+
import org.junit.runners.JUnit4;
42+
43+
@RunWith(JUnit4.class)
44+
@Timeout(value = 6, unit = TimeUnit.MINUTES)
45+
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
46+
public class SnapshotScheduleIT {
47+
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
48+
private static final String ZONE = "asia-south1-a";
49+
private static final String REGION = ZONE.substring(0, ZONE.lastIndexOf('-'));
50+
static String templateUUID = UUID.randomUUID().toString();
51+
private static final String SCHEDULE_NAME = "test-schedule-" + templateUUID;
52+
private static final String SCHEDULE_FOR_DISK = "test-schedule-for-disk-" + templateUUID;
53+
private static final String SCHEDULE_DESCRIPTION = "Test hourly snapshot schedule";
54+
private static final int MAX_RETENTION_DAYS = 2;
55+
private static final String STORAGE_LOCATION = "US";
56+
private static final String ON_SOURCE_DISK_DELETE = "KEEP_AUTO_SNAPSHOTS";
57+
private static final String DISK_NAME = "gcloud-test-disk-" + templateUUID;
58+
59+
// Check if the required environment variables are set.
60+
public static void requireEnvVar(String envVarName) {
61+
assertWithMessage(String.format("Missing environment variable '%s' ", envVarName))
62+
.that(System.getenv(envVarName)).isNotEmpty();
63+
}
64+
65+
@BeforeAll
66+
public static void setUp()
67+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
68+
requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS");
69+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
70+
71+
String diskType = String.format("zones/%s/diskTypes/pd-standard", ZONE);
72+
CreateEmptyDisk.createEmptyDisk(PROJECT_ID, ZONE, DISK_NAME, diskType, 12);
73+
CreateSnapshotSchedule.createSnapshotSchedule(
74+
PROJECT_ID, REGION, SCHEDULE_FOR_DISK, SCHEDULE_DESCRIPTION,
75+
MAX_RETENTION_DAYS, STORAGE_LOCATION, ON_SOURCE_DISK_DELETE);
76+
}
77+
78+
@AfterAll
79+
public static void cleanUp()
80+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
81+
DeleteDisk.deleteDisk(PROJECT_ID, ZONE, DISK_NAME);
82+
DeleteSnapshotSchedule.deleteSnapshotSchedule(PROJECT_ID, REGION, SCHEDULE_FOR_DISK);
83+
}
84+
85+
@Test
86+
@Order(1)
87+
public void testCreateSnapshotScheduleHourly()
88+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
89+
Operation.Status status = CreateSnapshotSchedule.createSnapshotSchedule(
90+
PROJECT_ID, REGION, SCHEDULE_NAME, SCHEDULE_DESCRIPTION,
91+
MAX_RETENTION_DAYS, STORAGE_LOCATION, ON_SOURCE_DISK_DELETE);
92+
93+
assertThat(status).isEqualTo(Operation.Status.DONE);
94+
}
95+
96+
@Test
97+
@Order(2)
98+
public void testAttachSnapshotScheduleToDisk()
99+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
100+
Operation.Status status = AttachSnapshotScheduleToDisk.attachSnapshotScheduleToDisk(
101+
PROJECT_ID, ZONE, DISK_NAME, SCHEDULE_FOR_DISK, REGION);
102+
103+
assertThat(status).isEqualTo(Operation.Status.DONE);
104+
}
105+
106+
@Test
107+
@Order(3)
108+
public void testDeleteSnapshotSchedule()
109+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
110+
Operation.Status status = DeleteSnapshotSchedule
111+
.deleteSnapshotSchedule(PROJECT_ID, REGION, SCHEDULE_NAME);
112+
113+
assertThat(status).isEqualTo(Operation.Status.DONE);
114+
}
115+
}

0 commit comments

Comments
 (0)