Skip to content

Commit 967cd58

Browse files
committed
Create compute shared reservation file with updated test
1 parent ccc97b4 commit 967cd58

File tree

2 files changed

+178
-0
lines changed

2 files changed

+178
-0
lines changed
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: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@
2727
from ..compute_reservations.delete_compute_reservation import delete_compute_reservation
2828
from ..compute_reservations.get_compute_reservation import get_compute_reservation
2929
from ..compute_reservations.list_compute_reservation import list_compute_reservation
30+
from ..compute_reservations.create_compute_shared_reservation import (
31+
create_compute_shared_reservation,
32+
)
3033

3134

3235
from ..instances.create import create_instance
@@ -38,6 +41,7 @@
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()
@@ -128,3 +132,27 @@ def test_list_compute_reservation(reservation):
128132
def test_delete_compute_reservation(reservation):
129133
response = delete_compute_reservation(PROJECT_ID, ZONE, reservation.name)
130134
assert response.status == Operation.Status.DONE
135+
136+
137+
def test_create_shared_reservation():
138+
""" Test for creating a shared reservation.
139+
140+
The reservation will be created in PROJECT_ID and shared with the project specified
141+
by SHARED_PROJECT_ID.
142+
143+
Make sure to set the SHARED_PROJECT_ID environment variable before running this test,
144+
and ensure that the project is allowlisted in the organization policy for shared reservations.
145+
146+
If the SHARED_PROJECT_ID environment variable is not set, the test will be skipped.
147+
"""
148+
if not SHARED_PROJECT_ID:
149+
pytest.skip(
150+
"Skipping test because SHARED_PROJECT_ID environment variable is not set."
151+
)
152+
try:
153+
response = create_compute_shared_reservation(
154+
PROJECT_ID, ZONE, RESERVATION_NAME, SHARED_PROJECT_ID
155+
)
156+
assert response.share_settings.project_map.values()
157+
finally:
158+
delete_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)

0 commit comments

Comments
 (0)