Skip to content

Commit 5f65217

Browse files
feat(compute): add compute reservation create from vm sample. (#9573)
* Implemented compute_reservation_create_from_vm sample. created test * Cleaned reservations * Fixed lint issue * Revert "Fixed lint issue" This reverts commit c758b03. * Reverted changes * Fixed naming * Fixed naming * Fixed naming * Fixed naming * Created new test class for CreateReservationFromVm * Changed zone * Cleaned unused code * Fixed test and naming
1 parent 002b4ae commit 5f65217

File tree

3 files changed

+249
-2
lines changed

3 files changed

+249
-2
lines changed
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
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.reservation;
18+
19+
// [START compute_reservation_create_from_vm]
20+
21+
import com.google.cloud.compute.v1.AcceleratorConfig;
22+
import com.google.cloud.compute.v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk;
23+
import com.google.cloud.compute.v1.AllocationSpecificSKUAllocationReservedInstanceProperties;
24+
import com.google.cloud.compute.v1.AllocationSpecificSKUReservation;
25+
import com.google.cloud.compute.v1.AttachedDisk;
26+
import com.google.cloud.compute.v1.InsertReservationRequest;
27+
import com.google.cloud.compute.v1.Instance;
28+
import com.google.cloud.compute.v1.InstancesClient;
29+
import com.google.cloud.compute.v1.Operation;
30+
import com.google.cloud.compute.v1.Reservation;
31+
import com.google.cloud.compute.v1.ReservationsClient;
32+
import java.io.IOException;
33+
import java.util.ArrayList;
34+
import java.util.List;
35+
import java.util.concurrent.ExecutionException;
36+
import java.util.concurrent.TimeUnit;
37+
import java.util.concurrent.TimeoutException;
38+
39+
public class CreateReservationFromVm {
40+
41+
public static void main(String[] args)
42+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
43+
// TODO(developer): Replace these variables before running the sample.
44+
// Project ID or project number of the Cloud project you want to use.
45+
String project = "YOUR_PROJECT_ID";
46+
// The zone of the VM. In this zone the reservation will be created.
47+
String zone = "us-central1-a";
48+
// The name of the reservation to create.
49+
String reservationName = "YOUR_RESERVATION_NAME";
50+
// The name of the VM to create the reservation from.
51+
String vmName = "YOUR_VM_NAME";
52+
53+
createComputeReservationFromVm(project, zone, reservationName, vmName);
54+
}
55+
56+
// Creates a compute reservation from an existing VM.
57+
public static void createComputeReservationFromVm(
58+
String project, String zone, String reservationName, String vmName)
59+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
60+
// Initialize client that will be used to send requests. This client only needs to be created
61+
// once, and can be reused for multiple requests.
62+
try (InstancesClient instancesClient = InstancesClient.create();
63+
ReservationsClient reservationsClient = ReservationsClient.create()) {
64+
Instance existingVm = instancesClient.get(project, zone, vmName);
65+
66+
// Extract properties from the existing VM
67+
List<AcceleratorConfig> guestAccelerators = new ArrayList<>();
68+
if (!existingVm.getGuestAcceleratorsList().isEmpty()) {
69+
for (AcceleratorConfig accelatorConfig : existingVm.getGuestAcceleratorsList()) {
70+
guestAccelerators.add(
71+
AcceleratorConfig.newBuilder()
72+
.setAcceleratorCount(accelatorConfig.getAcceleratorCount())
73+
.setAcceleratorType(accelatorConfig.getAcceleratorType()
74+
.substring(accelatorConfig.getAcceleratorType().lastIndexOf('/') + 1))
75+
.build());
76+
}
77+
}
78+
79+
List<AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk> localSsds =
80+
new ArrayList<>();
81+
if (!existingVm.getDisksList().isEmpty()) {
82+
for (AttachedDisk disk : existingVm.getDisksList()) {
83+
if (disk.getDiskSizeGb() >= 375) {
84+
localSsds.add(
85+
AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk.newBuilder()
86+
.setDiskSizeGb(disk.getDiskSizeGb())
87+
.setInterface(disk.getInterface())
88+
.build());
89+
}
90+
}
91+
}
92+
93+
AllocationSpecificSKUAllocationReservedInstanceProperties instanceProperties =
94+
AllocationSpecificSKUAllocationReservedInstanceProperties.newBuilder()
95+
.setMachineType(
96+
existingVm.getMachineType()
97+
.substring(existingVm.getMachineType().lastIndexOf('/') + 1))
98+
.setMinCpuPlatform(existingVm.getMinCpuPlatform())
99+
.addAllLocalSsds(localSsds)
100+
.addAllGuestAccelerators(guestAccelerators)
101+
.build();
102+
103+
Reservation reservation =
104+
Reservation.newBuilder()
105+
.setName(reservationName)
106+
.setSpecificReservation(
107+
AllocationSpecificSKUReservation.newBuilder()
108+
.setCount(3)
109+
.setInstanceProperties(instanceProperties)
110+
.build())
111+
.setSpecificReservationRequired(true)
112+
.build();
113+
114+
InsertReservationRequest insertReservationRequest =
115+
InsertReservationRequest.newBuilder()
116+
.setProject(project)
117+
.setZone(zone)
118+
.setReservationResource(reservation)
119+
.build();
120+
121+
Operation response = reservationsClient
122+
.insertAsync(insertReservationRequest).get(3, TimeUnit.MINUTES);
123+
124+
if (response.hasError()) {
125+
System.out.println("Reservation creation failed ! ! " + response);
126+
return;
127+
}
128+
System.out.println("Operation completed successfully.");
129+
}
130+
}
131+
}
132+
// [END compute_reservation_create_from_vm]
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.reservation;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
import static com.google.common.truth.Truth.assertWithMessage;
21+
22+
import com.google.api.gax.rpc.NotFoundException;
23+
import com.google.cloud.compute.v1.Instance;
24+
import com.google.cloud.compute.v1.InstancesClient;
25+
import com.google.cloud.compute.v1.Reservation;
26+
import com.google.cloud.compute.v1.ReservationsClient;
27+
import compute.CreateInstance;
28+
import compute.DeleteInstance;
29+
import compute.Util;
30+
import java.io.IOException;
31+
import java.util.UUID;
32+
import java.util.concurrent.ExecutionException;
33+
import java.util.concurrent.TimeUnit;
34+
import java.util.concurrent.TimeoutException;
35+
import org.junit.jupiter.api.AfterAll;
36+
import org.junit.jupiter.api.Assertions;
37+
import org.junit.jupiter.api.BeforeAll;
38+
import org.junit.jupiter.api.Test;
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 = 3, unit = TimeUnit.MINUTES)
45+
public class CreateReservationFromVmIT {
46+
47+
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
48+
private static final String ZONE = "us-east4-c";
49+
private static ReservationsClient reservationsClient;
50+
private static InstancesClient instancesClient;
51+
private static String reservationName;
52+
private static String instanceForReservation;
53+
static String javaVersion = System.getProperty("java.version").substring(0, 2);
54+
55+
// Check if the required environment variables are set.
56+
public static void requireEnvVar(String envVarName) {
57+
assertWithMessage(String.format("Missing environment variable '%s' ", envVarName))
58+
.that(System.getenv(envVarName)).isNotEmpty();
59+
}
60+
61+
@BeforeAll
62+
public static void setUp()
63+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
64+
requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS");
65+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
66+
reservationsClient = ReservationsClient.create();
67+
instancesClient = InstancesClient.create();
68+
69+
reservationName = "test-reservation-from-vm-" + javaVersion + "-"
70+
+ UUID.randomUUID().toString().substring(0, 8);
71+
instanceForReservation = "test-instance-for-reserv-" + javaVersion + "-"
72+
+ UUID.randomUUID().toString().substring(0, 8);
73+
74+
// Cleanup existing stale resources.
75+
Util.cleanUpExistingInstances("test-instance-for-reserv-" + javaVersion, PROJECT_ID, ZONE);
76+
Util.cleanUpExistingReservations("test-reservation-from-vm-" + javaVersion, PROJECT_ID, ZONE);
77+
78+
CreateInstance.createInstance(PROJECT_ID, ZONE, instanceForReservation);
79+
}
80+
81+
@AfterAll
82+
public static void cleanup()
83+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
84+
// Delete resources created for testing.
85+
DeleteInstance.deleteInstance(PROJECT_ID, ZONE, instanceForReservation);
86+
87+
reservationsClient.close();
88+
instancesClient.close();
89+
}
90+
91+
@Test
92+
public void testCreateComputeReservationFromVm()
93+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
94+
CreateReservationFromVm.createComputeReservationFromVm(
95+
PROJECT_ID, ZONE, reservationName, instanceForReservation);
96+
97+
Instance instance = instancesClient.get(PROJECT_ID, ZONE, instanceForReservation);
98+
Reservation reservation =
99+
reservationsClient.get(PROJECT_ID, ZONE, reservationName);
100+
101+
Assertions.assertNotNull(reservation);
102+
assertThat(reservation.getName()).isEqualTo(reservationName);
103+
Assertions.assertEquals(instance.getMinCpuPlatform(),
104+
reservation.getSpecificReservation().getInstanceProperties().getMinCpuPlatform());
105+
Assertions.assertEquals(instance.getGuestAcceleratorsList(),
106+
reservation.getSpecificReservation().getInstanceProperties().getGuestAcceleratorsList());
107+
108+
DeleteReservation.deleteReservation(PROJECT_ID, ZONE, reservationName);
109+
110+
// Test that reservation is deleted
111+
Assertions.assertThrows(
112+
NotFoundException.class,
113+
() -> GetReservation.getReservation(PROJECT_ID, reservationName, ZONE));
114+
}
115+
}

compute/cloud-client/src/test/java/compute/reservation/CrudOperationsReservationIT.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,10 @@ public static void setUp()
7474
@AfterAll
7575
public static void cleanup()
7676
throws IOException, ExecutionException, InterruptedException, TimeoutException {
77-
// Delete all reservations created for testing.
77+
// Delete resources created for testing.
7878
DeleteReservation.deleteReservation(PROJECT_ID, ZONE, RESERVATION_NAME);
7979

80-
// Test that reservations are deleted
80+
// Test that reservation is deleted
8181
Assertions.assertThrows(
8282
NotFoundException.class,
8383
() -> GetReservation.getReservation(PROJECT_ID, RESERVATION_NAME, ZONE));

0 commit comments

Comments
 (0)