Skip to content

Commit 77d892e

Browse files
Implemented compute_snapshot_schedule_delete and compute_snapshot_schedule_create samples, created test
1 parent b7781fd commit 77d892e

File tree

3 files changed

+272
-0
lines changed

3 files changed

+272
-0
lines changed
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: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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.ResourcePoliciesClient;
21+
import java.io.IOException;
22+
import java.util.concurrent.ExecutionException;
23+
import java.util.concurrent.TimeUnit;
24+
import java.util.concurrent.TimeoutException;
25+
26+
public class DeleteSnapshotSchedule {
27+
public static void main(String[] args)
28+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
29+
// TODO(developer): Replace these variables before running the sample.
30+
// Project ID or project number of the Cloud project you want to use.
31+
String projectId = "YOUR_PROJECT_ID";
32+
// Name of the region where your snapshot schedule is located.
33+
String region = "us-central1";
34+
// Name of the snapshot schedule you want to delete.
35+
String scheduleName = "YOUR_SCHEDULE_NAME";
36+
37+
deleteSnapshotSchedule(projectId, region, scheduleName);
38+
}
39+
40+
// Deletes a snapshot schedule policy.
41+
public static void deleteSnapshotSchedule(String projectId, String region, String scheduleName)
42+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
43+
44+
try (ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.create()) {
45+
resourcePoliciesClient.deleteAsync(projectId, region, scheduleName).get(3, TimeUnit.MINUTES);
46+
47+
System.out.println("Snapshot schedule deleted successfully: " + scheduleName);
48+
}
49+
}
50+
}
51+
// [END compute_snapshot_schedule_delete]
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
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+
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 java.io.ByteArrayOutputStream;
24+
import java.io.IOException;
25+
import java.io.PrintStream;
26+
import java.util.UUID;
27+
import java.util.concurrent.ExecutionException;
28+
import java.util.concurrent.TimeUnit;
29+
import java.util.concurrent.TimeoutException;
30+
import org.junit.jupiter.api.AfterAll;
31+
import org.junit.jupiter.api.BeforeAll;
32+
import org.junit.jupiter.api.Test;
33+
import org.junit.jupiter.api.Timeout;
34+
import org.junit.runner.RunWith;
35+
import org.junit.runners.JUnit4;
36+
37+
@RunWith(JUnit4.class)
38+
@Timeout(value = 6, unit = TimeUnit.MINUTES)
39+
public class SnapshotIT {
40+
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
41+
private static final String ZONE = "asia-south1-a";
42+
private static final String REGION = ZONE.substring(0, ZONE.lastIndexOf('-'));
43+
static String templateUUID = UUID.randomUUID().toString();
44+
private static final String SCHEDULE_NAME = "test-schedule-" + templateUUID;
45+
private static final String SCHEDULE_DESCRIPTION = "Test hourly snapshot schedule";
46+
private static final int MAX_RETENTION_DAYS = 2;
47+
private static final String STORAGE_LOCATION = "US";
48+
private static final String ON_SOURCE_DISK_DELETE = "KEEP_AUTO_SNAPSHOTS";
49+
50+
// Check if the required environment variables are set.
51+
public static void requireEnvVar(String envVarName) {
52+
assertWithMessage(String.format("Missing environment variable '%s' ", envVarName))
53+
.that(System.getenv(envVarName)).isNotEmpty();
54+
}
55+
56+
@BeforeAll
57+
public static void setUp()
58+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
59+
requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS");
60+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
61+
}
62+
63+
@AfterAll
64+
public static void cleanup()
65+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
66+
ByteArrayOutputStream stdOut = new ByteArrayOutputStream();
67+
System.setOut(new PrintStream(stdOut));
68+
69+
// Delete snapshot schedule created for testing.
70+
DeleteSnapshotSchedule.deleteSnapshotSchedule(PROJECT_ID, REGION, SCHEDULE_NAME);
71+
72+
assertThat(stdOut.toString())
73+
.contains("Snapshot schedule deleted successfully: " + SCHEDULE_NAME);
74+
75+
stdOut.close();
76+
}
77+
78+
@Test
79+
public void testCreateSnapshotScheduleHourly()
80+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
81+
Operation.Status status = CreateSnapshotSchedule.createSnapshotSchedule(
82+
PROJECT_ID, REGION, SCHEDULE_NAME, SCHEDULE_DESCRIPTION,
83+
MAX_RETENTION_DAYS, STORAGE_LOCATION, ON_SOURCE_DISK_DELETE);
84+
assertThat(status).isEqualTo(Operation.Status.DONE);
85+
}
86+
}

0 commit comments

Comments
 (0)