Skip to content

Commit 9f14195

Browse files
Implemented consume reservation samples, created tests
1 parent dd24a49 commit 9f14195

File tree

4 files changed

+695
-0
lines changed

4 files changed

+695
-0
lines changed
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
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_consume_any_matching_reservation]
20+
21+
import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.ANY_RESERVATION;
22+
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.AttachedDiskInitializeParams;
27+
import com.google.cloud.compute.v1.Instance;
28+
import com.google.cloud.compute.v1.InstancesClient;
29+
import com.google.cloud.compute.v1.NetworkInterface;
30+
import com.google.cloud.compute.v1.Operation;
31+
import com.google.cloud.compute.v1.Reservation;
32+
import com.google.cloud.compute.v1.ReservationAffinity;
33+
import com.google.cloud.compute.v1.ReservationsClient;
34+
import java.io.IOException;
35+
import java.util.concurrent.ExecutionException;
36+
import java.util.concurrent.TimeUnit;
37+
import java.util.concurrent.TimeoutException;
38+
39+
public class ConsumeAnyMatchingReservation {
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 projectId = "YOUR_PROJECT_ID";
46+
// Name of the zone where the reservation is located.
47+
String zone = "us-central1-a";
48+
// Name of the reservation you want to query.
49+
String reservationName = "YOUR_RESERVATION_NAME";
50+
// Name of the VM instance you want to query.
51+
String instanceName = "YOUR_INSTANCE_NAME";
52+
// Number of the instances.
53+
int numberOfVms = 2;
54+
// Machine type of the instances.
55+
String machineType = "n2-standard-32";
56+
// Minimum CPU platform of the instances.
57+
String minCpuPlatform = "Intel Cascade Lake";
58+
59+
createReservation(projectId, reservationName, numberOfVms, zone, machineType, minCpuPlatform);
60+
createInstance(projectId, zone, instanceName, machineType, minCpuPlatform);
61+
}
62+
63+
// Creates reservation with properties that match the VM properties.
64+
public static void createReservation(String projectId, String reservationName,
65+
int numberOfVms, String zone, String machineType, String minCpuPlatform)
66+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
67+
// Initialize client that will be used to send requests. This client only needs to be created
68+
// once, and can be reused for multiple requests.
69+
try (ReservationsClient reservationsClient = ReservationsClient.create()) {
70+
71+
Reservation reservation =
72+
Reservation.newBuilder()
73+
.setName(reservationName)
74+
.setZone(zone)
75+
.setSpecificReservation(
76+
AllocationSpecificSKUReservation.newBuilder()
77+
.setCount(numberOfVms)
78+
.setInstanceProperties(
79+
AllocationSpecificSKUAllocationReservedInstanceProperties.newBuilder()
80+
.setMachineType(machineType)
81+
.setMinCpuPlatform(minCpuPlatform)
82+
.build())
83+
.build())
84+
.build();
85+
86+
// Wait for the create reservation operation to complete.
87+
Operation response =
88+
reservationsClient.insertAsync(projectId, zone, reservation)
89+
.get(3, TimeUnit.MINUTES);
90+
91+
if (response.hasError()) {
92+
System.out.println("Reservation creation failed!" + response);
93+
return;
94+
}
95+
System.out.println("Reservation created. Operation Status: " + response.getStatus());
96+
}
97+
}
98+
99+
// Create a new instance with the provided "instanceName" value in the specified project and zone.
100+
// In this consumption model, existing and new VMs automatically consume a reservation
101+
// if their properties match the VM properties specified in the reservation.
102+
public static void createInstance(String project, String zone, String instanceName,
103+
String machineType, String minCpuPlatform)
104+
throws IOException, InterruptedException, ExecutionException, TimeoutException {
105+
// Below are sample values that can be replaced.
106+
// sourceImage: path to the operating system image to mount.
107+
// * For details about images you can mount, see https://cloud.google.com/compute/docs/images
108+
// diskSizeGb: storage size of the boot disk to attach to the instance.
109+
// networkName: network interface to associate with the instance.
110+
String sourceImage = String
111+
.format("projects/debian-cloud/global/images/family/%s", "debian-11");
112+
long diskSizeGb = 10L;
113+
String networkName = "default";
114+
115+
// Initialize client that will be used to send requests. This client only needs to be created
116+
// once, and can be reused for multiple requests.
117+
try (InstancesClient instancesClient = InstancesClient.create()) {
118+
// Instance creation requires at least one persistent disk and one network interface.
119+
AttachedDisk disk =
120+
AttachedDisk.newBuilder()
121+
.setBoot(true)
122+
.setAutoDelete(true)
123+
.setType(AttachedDisk.Type.PERSISTENT.toString())
124+
.setDeviceName("disk-1")
125+
.setInitializeParams(
126+
AttachedDiskInitializeParams.newBuilder()
127+
.setSourceImage(sourceImage)
128+
.setDiskSizeGb(diskSizeGb)
129+
.build())
130+
.build();
131+
132+
// Use the network interface provided in the networkName argument.
133+
NetworkInterface networkInterface = NetworkInterface.newBuilder()
134+
.setName(networkName)
135+
.build();
136+
137+
// Bind `instanceName`, `machineType`, `disk`, and `networkInterface` to an instance.
138+
Instance instanceResource =
139+
Instance.newBuilder()
140+
.setName(instanceName)
141+
.setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType))
142+
.addDisks(disk)
143+
.addNetworkInterfaces(networkInterface)
144+
.setMinCpuPlatform(minCpuPlatform)
145+
// Set Reservation Affinity to "ANY"
146+
.setReservationAffinity(
147+
ReservationAffinity.newBuilder()
148+
.setConsumeReservationType(
149+
ANY_RESERVATION.toString())
150+
.build())
151+
.build();
152+
153+
System.out.printf("Creating instance: %s at %s %n", instanceName, zone);
154+
155+
// Wait for the operation to complete.
156+
Operation response = instancesClient.insertAsync(project, zone, instanceResource)
157+
.get(3, TimeUnit.MINUTES);
158+
if (response.hasError()) {
159+
System.out.println("Instance creation failed ! ! " + response);
160+
return;
161+
}
162+
System.out.println("Operation Status: " + response.getStatus());
163+
}
164+
}
165+
}
166+
// [END compute_consume_any_matching_reservation]
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
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_consume_single_project_reservation]
20+
21+
import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.SPECIFIC_RESERVATION;
22+
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.AttachedDiskInitializeParams;
27+
import com.google.cloud.compute.v1.Instance;
28+
import com.google.cloud.compute.v1.InstancesClient;
29+
import com.google.cloud.compute.v1.NetworkInterface;
30+
import com.google.cloud.compute.v1.Operation;
31+
import com.google.cloud.compute.v1.Reservation;
32+
import com.google.cloud.compute.v1.ReservationAffinity;
33+
import com.google.cloud.compute.v1.ReservationsClient;
34+
import java.io.IOException;
35+
import java.util.concurrent.ExecutionException;
36+
import java.util.concurrent.TimeUnit;
37+
import java.util.concurrent.TimeoutException;
38+
39+
public class ConsumeSingleProjectReservation {
40+
public static void main(String[] args)
41+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
42+
// TODO(developer): Replace these variables before running the sample.
43+
// Project ID or project number of the Cloud project you want to use.
44+
String projectId = "YOUR_PROJECT_ID";
45+
// Name of the zone where the reservation is located.
46+
String zone = "us-central1-a";
47+
// Name of the reservation you want to query.
48+
String reservationName = "YOUR_RESERVATION_NAME";
49+
// Name of the VM instance you want to query.
50+
String instanceName = "YOUR_INSTANCE_NAME";
51+
// Number of the instances.
52+
int numberOfVms = 10;
53+
// Machine type of the instances.
54+
String machineType = "n2-standard-32";
55+
// Minimum CPU platform of the instances.
56+
String minCpuPlatform = "Intel Cascade Lake";
57+
boolean specificReservationRequired = true;
58+
59+
createReservation(projectId, reservationName, numberOfVms,
60+
zone, machineType, minCpuPlatform, specificReservationRequired);
61+
createInstance(projectId, zone, instanceName, machineType, minCpuPlatform, reservationName);
62+
}
63+
64+
// Creates reservation with the given parameters.
65+
public static void createReservation(
66+
String projectId, String reservationName, int numberOfVms, String zone,
67+
String machineType, String minCpuPlatform, boolean specificReservationRequired)
68+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
69+
// Initialize client that will be used to send requests. This client only needs to be created
70+
// once, and can be reused for multiple requests.
71+
try (ReservationsClient reservationsClient = ReservationsClient.create()) {
72+
73+
Reservation reservation =
74+
Reservation.newBuilder()
75+
.setName(reservationName)
76+
.setZone(zone)
77+
.setSpecificReservationRequired(specificReservationRequired)
78+
.setSpecificReservation(
79+
AllocationSpecificSKUReservation.newBuilder()
80+
.setCount(numberOfVms)
81+
.setInstanceProperties(
82+
AllocationSpecificSKUAllocationReservedInstanceProperties.newBuilder()
83+
.setMachineType(machineType)
84+
.setMinCpuPlatform(minCpuPlatform)
85+
.build())
86+
.build())
87+
.build();
88+
89+
// Wait for the create reservation operation to complete.
90+
Operation response =
91+
reservationsClient.insertAsync(projectId, zone, reservation).get(3, TimeUnit.MINUTES);
92+
93+
if (response.hasError()) {
94+
System.out.println("Reservation creation failed!" + response);
95+
return;
96+
}
97+
System.out.println("Reservation created. Operation Status: " + response.getStatus());
98+
}
99+
}
100+
101+
// Create a new instance with the provided "instanceName" value in the specified project and zone.
102+
public static void createInstance(String project, String zone,
103+
String instanceName, String machineType, String minCpuPlatform, String reservationName)
104+
throws IOException, InterruptedException, ExecutionException, TimeoutException {
105+
// Below are sample values that can be replaced.
106+
// sourceImage: path to the operating system image to mount.
107+
// * For details about images you can mount, see https://cloud.google.com/compute/docs/images
108+
// diskSizeGb: storage size of the boot disk to attach to the instance.
109+
// networkName: network interface to associate with the instance.
110+
String sourceImage = String
111+
.format("projects/debian-cloud/global/images/family/%s", "debian-11");
112+
long diskSizeGb = 10L;
113+
String networkName = "default";
114+
115+
// Initialize client that will be used to send requests. This client only needs to be created
116+
// once, and can be reused for multiple requests.
117+
try (InstancesClient instancesClient = InstancesClient.create()) {
118+
// Instance creation requires at least one persistent disk and one network interface.
119+
AttachedDisk disk =
120+
AttachedDisk.newBuilder()
121+
.setBoot(true)
122+
.setAutoDelete(true)
123+
.setType(AttachedDisk.Type.PERSISTENT.toString())
124+
.setDeviceName("disk-1")
125+
.setInitializeParams(
126+
AttachedDiskInitializeParams.newBuilder()
127+
.setSourceImage(sourceImage)
128+
.setDiskSizeGb(diskSizeGb)
129+
.build())
130+
.build();
131+
132+
// Use the network interface provided in the networkName argument.
133+
NetworkInterface networkInterface = NetworkInterface.newBuilder()
134+
.setName(networkName)
135+
.build();
136+
137+
// Bind `instanceName`, `machineType`, `disk`, and `networkInterface` to an instance.
138+
Instance instanceResource =
139+
Instance.newBuilder()
140+
.setName(instanceName)
141+
.setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType))
142+
.addDisks(disk)
143+
.addNetworkInterfaces(networkInterface)
144+
.setMinCpuPlatform(minCpuPlatform)
145+
// Set Reservation Affinity
146+
.setReservationAffinity(
147+
ReservationAffinity.newBuilder()
148+
.setConsumeReservationType(
149+
SPECIFIC_RESERVATION.name())
150+
.setKey("compute.googleapis.com/reservation-name")
151+
// Set specific reservation
152+
.addValues(reservationName)
153+
.build())
154+
.build();
155+
156+
System.out.printf("Creating instance: %s at %s %n", instanceName, zone);
157+
158+
// Wait for the operation to complete.
159+
Operation response = instancesClient.insertAsync(project, zone, instanceResource)
160+
.get(3, TimeUnit.MINUTES);
161+
162+
if (response.hasError()) {
163+
System.out.println("Instance creation failed ! ! " + response);
164+
return;
165+
}
166+
System.out.println("Operation Status: " + response.getStatus());
167+
}
168+
}
169+
}
170+
// [END compute_consume_single_project_reservation]

0 commit comments

Comments
 (0)