Skip to content

Commit a458bc8

Browse files
feat : Create compute shared reservation Sample (#12678)
* Create compute shared reservation file with updated test * Refactored tests for all reservations
1 parent 98d8ab5 commit a458bc8

File tree

4 files changed

+303
-14
lines changed

4 files changed

+303
-14
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Copyright 2024 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# This is an ingredient file. It is not meant to be run directly. Check the samples/snippets
16+
# folder for complete code samples that are ready to be used.
17+
# Disabling flake8 for the ingredients file, as it would fail F821 - undefined name check.
18+
# flake8: noqa
19+
20+
from google.cloud import compute_v1
21+
22+
23+
# <INGREDIENT create_compute_shared_reservation>
24+
def create_compute_shared_reservation(
25+
project_id: str,
26+
zone: str = "us-central1-a",
27+
reservation_name="your-reservation-name",
28+
shared_project_id: str = "shared-project-id",
29+
) -> compute_v1.Reservation:
30+
"""Creates a compute reservation in GCP.
31+
Args:
32+
project_id (str): The ID of the Google Cloud project.
33+
zone (str): The zone to create the reservation.
34+
reservation_name (str): The name of the reservation to create.
35+
shared_project_id (str): The ID of the project that the reservation is shared with.
36+
Returns:
37+
Reservation object that represents the new reservation.
38+
"""
39+
40+
instance_properties = compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
41+
machine_type="n1-standard-1",
42+
# Optional. Specifies amount of local ssd to reserve with each instance.
43+
local_ssds=[
44+
compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(
45+
disk_size_gb=375, interface="NVME"
46+
),
47+
],
48+
)
49+
50+
reservation = compute_v1.Reservation(
51+
name=reservation_name,
52+
specific_reservation=compute_v1.AllocationSpecificSKUReservation(
53+
count=3, # Number of resources that are allocated.
54+
# If you use source_instance_template, you must exclude the instance_properties field.
55+
# It can be a full or partial URL.
56+
# source_instance_template="projects/[PROJECT_ID]/global/instanceTemplates/my-instance-template",
57+
instance_properties=instance_properties,
58+
),
59+
share_settings=compute_v1.ShareSettings(
60+
share_type="SPECIFIC_PROJECTS",
61+
project_map={
62+
shared_project_id: compute_v1.ShareSettingsProjectConfig(
63+
project_id=shared_project_id
64+
)
65+
},
66+
),
67+
)
68+
69+
# Create a client
70+
client = compute_v1.ReservationsClient()
71+
72+
operation = client.insert(
73+
project=project_id,
74+
zone=zone,
75+
reservation_resource=reservation,
76+
)
77+
wait_for_extended_operation(operation, "Reservation creation")
78+
79+
reservation = client.get(
80+
project=project_id, zone=zone, reservation=reservation_name
81+
)
82+
shared_project = next(iter(reservation.share_settings.project_map.values()))
83+
84+
print("Name: ", reservation.name)
85+
print("STATUS: ", reservation.status)
86+
print("SHARED PROJECT: ", shared_project)
87+
# Example response:
88+
# Name: your-reservation-name
89+
# STATUS: READY
90+
# SHARED PROJECT: project_id: "123456789012"
91+
92+
return reservation
93+
94+
95+
# </INGREDIENT>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Copyright 2024 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# <REGION compute_reservation_create_shared>
16+
# <IMPORTS/>
17+
18+
# <INGREDIENT wait_for_extended_operation />
19+
20+
# <INGREDIENT create_compute_shared_reservation />
21+
# </REGION compute_reservation_create_shared>
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
# Copyright 2024 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
# This file is automatically generated. Please do not modify it directly.
17+
# Find the relevant recipe file in the samples/recipes or samples/ingredients
18+
# directory and apply your changes there.
19+
20+
21+
# [START compute_reservation_create_shared]
22+
from __future__ import annotations
23+
24+
import sys
25+
from typing import Any
26+
27+
from google.api_core.extended_operation import ExtendedOperation
28+
from google.cloud import compute_v1
29+
30+
31+
def wait_for_extended_operation(
32+
operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
33+
) -> Any:
34+
"""
35+
Waits for the extended (long-running) operation to complete.
36+
37+
If the operation is successful, it will return its result.
38+
If the operation ends with an error, an exception will be raised.
39+
If there were any warnings during the execution of the operation
40+
they will be printed to sys.stderr.
41+
42+
Args:
43+
operation: a long-running operation you want to wait on.
44+
verbose_name: (optional) a more verbose name of the operation,
45+
used only during error and warning reporting.
46+
timeout: how long (in seconds) to wait for operation to finish.
47+
If None, wait indefinitely.
48+
49+
Returns:
50+
Whatever the operation.result() returns.
51+
52+
Raises:
53+
This method will raise the exception received from `operation.exception()`
54+
or RuntimeError if there is no exception set, but there is an `error_code`
55+
set for the `operation`.
56+
57+
In case of an operation taking longer than `timeout` seconds to complete,
58+
a `concurrent.futures.TimeoutError` will be raised.
59+
"""
60+
result = operation.result(timeout=timeout)
61+
62+
if operation.error_code:
63+
print(
64+
f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
65+
file=sys.stderr,
66+
flush=True,
67+
)
68+
print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
69+
raise operation.exception() or RuntimeError(operation.error_message)
70+
71+
if operation.warnings:
72+
print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
73+
for warning in operation.warnings:
74+
print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
75+
76+
return result
77+
78+
79+
def create_compute_shared_reservation(
80+
project_id: str,
81+
zone: str = "us-central1-a",
82+
reservation_name="your-reservation-name",
83+
shared_project_id: str = "shared-project-id",
84+
) -> compute_v1.Reservation:
85+
"""Creates a compute reservation in GCP.
86+
Args:
87+
project_id (str): The ID of the Google Cloud project.
88+
zone (str): The zone to create the reservation.
89+
reservation_name (str): The name of the reservation to create.
90+
shared_project_id (str): The ID of the project that the reservation is shared with.
91+
Returns:
92+
Reservation object that represents the new reservation.
93+
"""
94+
95+
instance_properties = compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
96+
machine_type="n1-standard-1",
97+
# Optional. Specifies amount of local ssd to reserve with each instance.
98+
local_ssds=[
99+
compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(
100+
disk_size_gb=375, interface="NVME"
101+
),
102+
],
103+
)
104+
105+
reservation = compute_v1.Reservation(
106+
name=reservation_name,
107+
specific_reservation=compute_v1.AllocationSpecificSKUReservation(
108+
count=3, # Number of resources that are allocated.
109+
# If you use source_instance_template, you must exclude the instance_properties field.
110+
# It can be a full or partial URL.
111+
# source_instance_template="projects/[PROJECT_ID]/global/instanceTemplates/my-instance-template",
112+
instance_properties=instance_properties,
113+
),
114+
share_settings=compute_v1.ShareSettings(
115+
share_type="SPECIFIC_PROJECTS",
116+
project_map={
117+
shared_project_id: compute_v1.ShareSettingsProjectConfig(
118+
project_id=shared_project_id
119+
)
120+
},
121+
),
122+
)
123+
124+
# Create a client
125+
client = compute_v1.ReservationsClient()
126+
127+
operation = client.insert(
128+
project=project_id,
129+
zone=zone,
130+
reservation_resource=reservation,
131+
)
132+
wait_for_extended_operation(operation, "Reservation creation")
133+
134+
reservation = client.get(
135+
project=project_id, zone=zone, reservation=reservation_name
136+
)
137+
shared_project = next(iter(reservation.share_settings.project_map.values()))
138+
139+
print("Name: ", reservation.name)
140+
print("STATUS: ", reservation.status)
141+
print("SHARED PROJECT: ", shared_project)
142+
# Example response:
143+
# Name: your-reservation-name
144+
# STATUS: READY
145+
# SHARED PROJECT: project_id: "123456789012"
146+
147+
return reservation
148+
149+
150+
# [END compute_reservation_create_shared]

compute/client_library/snippets/tests/test_compute_reservation.py

Lines changed: 37 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@
2424
from ..compute_reservations.create_compute_reservation_from_vm import (
2525
create_compute_reservation_from_vm,
2626
)
27+
from ..compute_reservations.create_compute_shared_reservation import (
28+
create_compute_shared_reservation,
29+
)
2730
from ..compute_reservations.delete_compute_reservation import delete_compute_reservation
2831
from ..compute_reservations.get_compute_reservation import get_compute_reservation
2932
from ..compute_reservations.list_compute_reservation import list_compute_reservation
@@ -38,22 +41,17 @@
3841
PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
3942
ZONE = "us-central1-a"
4043
MACHINE_TYPE = "n2-standard-2"
44+
SHARED_PROJECT_ID = os.getenv("GOOGLE_CLOUD_SHARED_PROJECT")
4145

4246

4347
@pytest.fixture()
44-
def reservation(request) -> str:
48+
def reservation() -> str:
4549
create_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
46-
47-
def cleanup():
48-
try:
49-
delete_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
50-
except Exception as e:
51-
print(f"Error during cleanup: {e}")
52-
53-
request.addfinalizer(cleanup)
54-
55-
reservation = get_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
56-
return reservation
50+
yield get_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
51+
try:
52+
delete_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
53+
except Exception as e:
54+
print(f"Error during cleanup: {e}")
5755

5856

5957
@pytest.fixture(scope="session")
@@ -88,8 +86,6 @@ def vm_instance():
8886
except Exception as e:
8987
print(f"Error during cleanup: {e}")
9088

91-
return instance
92-
9389

9490
def test_create_compute_reservation_from_vm(vm_instance):
9591
try:
@@ -128,3 +124,30 @@ def test_list_compute_reservation(reservation):
128124
def test_delete_compute_reservation(reservation):
129125
response = delete_compute_reservation(PROJECT_ID, ZONE, reservation.name)
130126
assert response.status == Operation.Status.DONE
127+
128+
129+
def test_create_shared_reservation():
130+
"""Test for creating a shared reservation.
131+
132+
The reservation will be created in PROJECT_ID and shared with the project specified
133+
by SHARED_PROJECT_ID.
134+
135+
Make sure to set the GOOGLE_CLOUD_SHARED_PROJECT environment variable before running this test,
136+
and ensure that the project is allowlisted in the organization policy for shared reservations.
137+
138+
If the GOOGLE_CLOUD_SHARED_PROJECT environment variable is not set, the test will be skipped.
139+
"""
140+
if not SHARED_PROJECT_ID:
141+
pytest.skip(
142+
"Skipping test because SHARED_PROJECT_ID environment variable is not set."
143+
)
144+
try:
145+
response = create_compute_shared_reservation(
146+
PROJECT_ID, ZONE, RESERVATION_NAME, SHARED_PROJECT_ID
147+
)
148+
assert response.share_settings.project_map.values()
149+
finally:
150+
try:
151+
delete_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
152+
except Exception as e:
153+
print(f"Failed to delete reservation: {e}")

0 commit comments

Comments
 (0)