Skip to content

Commit c2e84ff

Browse files
Implemented compute_reservation_create_from_vm sample. created test
1 parent c6e4279 commit c2e84ff

File tree

3 files changed

+181
-3
lines changed

3 files changed

+181
-3
lines changed

compute/cloud-client/src/main/java/compute/reservation/CreateReservation.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ public static void createReservation(
107107

108108
// Wait for the create reservation operation to complete.
109109
Operation response =
110-
reservationsClient.insertAsync(projectId, zone, reservation).get(5, TimeUnit.MINUTES);
110+
reservationsClient.insertAsync(projectId, zone, reservation).get(7, TimeUnit.MINUTES);
111111

112112
if (response.hasError()) {
113113
System.out.println("Reservation creation failed!" + response);
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 a : existingVm.getGuestAcceleratorsList()) {
70+
guestAccelerators.add(
71+
AcceleratorConfig.newBuilder()
72+
.setAcceleratorCount(a.getAcceleratorCount())
73+
.setAcceleratorType(a.getAcceleratorType()
74+
.substring(a.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]

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

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,12 @@
2121
import static org.junit.jupiter.api.Assertions.assertNotNull;
2222

2323
import com.google.api.gax.rpc.NotFoundException;
24+
import com.google.cloud.compute.v1.Instance;
25+
import com.google.cloud.compute.v1.InstancesClient;
2426
import com.google.cloud.compute.v1.Reservation;
27+
import com.google.cloud.compute.v1.ReservationsClient;
28+
import compute.CreateInstance;
29+
import compute.DeleteInstance;
2530
import compute.Util;
2631
import java.io.IOException;
2732
import java.util.List;
@@ -44,7 +49,11 @@ public class CrudOperationsReservationIT {
4449

4550
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
4651
private static final String ZONE = "us-central1-a";
52+
private static ReservationsClient reservationsClient;
53+
private static InstancesClient instancesClient;
4754
private static String RESERVATION_NAME;
55+
private static String RESERVATION_NAME_FROM_VM;
56+
private static String INSTANCE_FOR_RESERVATION;
4857
private static final int NUMBER_OF_VMS = 3;
4958
static String javaVersion = System.getProperty("java.version").substring(0, 2);
5059

@@ -59,26 +68,44 @@ public static void setUp()
5968
throws IOException, ExecutionException, InterruptedException, TimeoutException {
6069
requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS");
6170
requireEnvVar("GOOGLE_CLOUD_PROJECT");
71+
reservationsClient = ReservationsClient.create();
72+
instancesClient = InstancesClient.create();
73+
6274
RESERVATION_NAME = "test-reservation-" + javaVersion + "-"
6375
+ UUID.randomUUID().toString().substring(0, 8);
76+
RESERVATION_NAME_FROM_VM = "test-reservation-from-vm-" + javaVersion + "-"
77+
+ UUID.randomUUID().toString().substring(0, 8);
78+
INSTANCE_FOR_RESERVATION = "test-instance-for-reserv-" + javaVersion + "-"
79+
+ UUID.randomUUID().toString().substring(0, 8);
6480

6581
// Cleanup existing stale resources.
82+
Util.cleanUpExistingInstances("test-instance-for-reserv-" + javaVersion, PROJECT_ID, ZONE);
6683
Util.cleanUpExistingReservations("test-reservation-" + javaVersion, PROJECT_ID, ZONE);
84+
Util.cleanUpExistingReservations("test-reservation-from-vm-" + javaVersion, PROJECT_ID, ZONE);
6785

86+
CreateInstance.createInstance(PROJECT_ID, ZONE, INSTANCE_FOR_RESERVATION);
6887
CreateReservation.createReservation(
6988
PROJECT_ID, RESERVATION_NAME, NUMBER_OF_VMS, ZONE);
7089
}
7190

7291
@AfterAll
7392
public static void cleanup()
7493
throws IOException, ExecutionException, InterruptedException, TimeoutException {
75-
// Delete all reservations created for testing.
94+
// Delete resources created for testing.
95+
DeleteInstance.deleteInstance(PROJECT_ID, ZONE, INSTANCE_FOR_RESERVATION);
7696
DeleteReservation.deleteReservation(PROJECT_ID, ZONE, RESERVATION_NAME);
97+
DeleteReservation.deleteReservation(PROJECT_ID, ZONE, RESERVATION_NAME_FROM_VM);
7798

7899
// Test that reservations are deleted
79100
Assertions.assertThrows(
80101
NotFoundException.class,
81102
() -> GetReservation.getReservation(PROJECT_ID, RESERVATION_NAME, ZONE));
103+
Assertions.assertThrows(
104+
NotFoundException.class,
105+
() -> GetReservation.getReservation(PROJECT_ID, RESERVATION_NAME_FROM_VM, ZONE));
106+
107+
reservationsClient.close();
108+
instancesClient.close();
82109
}
83110

84111
@Test
@@ -97,6 +124,25 @@ public void testListReservation() throws IOException {
97124
ListReservations.listReservations(PROJECT_ID, ZONE);
98125

99126
assertThat(reservations).isNotNull();
100-
Assert.assertTrue(reservations.get(0).getName().contains("test-"));
127+
Assert.assertTrue(reservations.get(0).getName().contains("test-reservation-"));
128+
Assert.assertTrue(reservations.get(1).getName().contains("test-reservation-"));
129+
}
130+
131+
@Test
132+
public void testCreateComputeReservationFromVm()
133+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
134+
CreateReservationFromVm.createComputeReservationFromVm(
135+
PROJECT_ID, ZONE, RESERVATION_NAME_FROM_VM, INSTANCE_FOR_RESERVATION);
136+
137+
Instance instance = instancesClient.get(PROJECT_ID, ZONE, INSTANCE_FOR_RESERVATION);
138+
Reservation reservation =
139+
reservationsClient.get(PROJECT_ID, ZONE, RESERVATION_NAME_FROM_VM);
140+
141+
Assert.assertNotNull(reservation);
142+
assertThat(reservation.getName()).isEqualTo(RESERVATION_NAME_FROM_VM);
143+
Assert.assertEquals(instance.getMinCpuPlatform(),
144+
reservation.getSpecificReservation().getInstanceProperties().getMinCpuPlatform());
145+
Assert.assertEquals(instance.getGuestAcceleratorsList(),
146+
reservation.getSpecificReservation().getInstanceProperties().getGuestAcceleratorsList());
101147
}
102148
}

0 commit comments

Comments
 (0)