Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit fac8cd2

Browse filesBrowse files
feat: Create Compute reservation create from VM Sample (GoogleCloudPlatform#12668)
* Added compute_reservation_from_vm Sample
1 parent 80c3048 commit fac8cd2
Copy full SHA for fac8cd2

File tree

Expand file treeCollapse file tree

4 files changed

+357
-0
lines changed
Filter options
Expand file treeCollapse file tree

4 files changed

+357
-0
lines changed
+108Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
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_reservation_from_vm>
24+
def create_compute_reservation_from_vm(
25+
project_id: str,
26+
zone: str = "us-central1-a",
27+
reservation_name="your-reservation-name",
28+
vm_name="your-vm-name",
29+
) -> compute_v1.Reservation:
30+
"""Creates a compute reservation in GCP from an existing VM.
31+
Args:
32+
project_id (str): The ID of the Google Cloud project.
33+
zone (str): The zone of the VM. In this zone the reservation will be created.
34+
reservation_name (str): The name of the reservation to create.
35+
vm_name: The name of the VM to create the reservation from.
36+
Returns:
37+
Reservation object that represents the new reservation with the same properties as the VM.
38+
"""
39+
instance_client = compute_v1.InstancesClient()
40+
existing_vm = instance_client.get(project=project_id, zone=zone, instance=vm_name)
41+
42+
guest_accelerators = [
43+
compute_v1.AcceleratorConfig(
44+
accelerator_count=a.accelerator_count,
45+
accelerator_type=a.accelerator_type.split("/")[-1],
46+
)
47+
for a in existing_vm.guest_accelerators
48+
]
49+
50+
local_ssds = [
51+
compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(
52+
disk_size_gb=disk.disk_size_gb, interface=disk.interface
53+
)
54+
for disk in existing_vm.disks
55+
if disk.disk_size_gb >= 375
56+
]
57+
58+
instance_properties = (
59+
compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
60+
machine_type=existing_vm.machine_type.split("/")[-1],
61+
min_cpu_platform=existing_vm.min_cpu_platform,
62+
local_ssds=local_ssds,
63+
guest_accelerators=guest_accelerators,
64+
)
65+
)
66+
67+
reservation = compute_v1.Reservation(
68+
name=reservation_name,
69+
specific_reservation=compute_v1.AllocationSpecificSKUReservation(
70+
count=3, # Number of resources that are allocated.
71+
instance_properties=instance_properties,
72+
),
73+
specific_reservation_required=True,
74+
)
75+
76+
# Create a client
77+
client = compute_v1.ReservationsClient()
78+
79+
operation = client.insert(
80+
project=project_id,
81+
zone=zone,
82+
reservation_resource=reservation,
83+
)
84+
wait_for_extended_operation(operation, "Reservation creation")
85+
86+
reservation = client.get(
87+
project=project_id, zone=zone, reservation=reservation_name
88+
)
89+
90+
print("Name: ", reservation.name)
91+
print("STATUS: ", reservation.status)
92+
print(reservation.specific_reservation)
93+
# Example response:
94+
# Name: your-reservation-name
95+
# STATUS: READY
96+
# count: 3
97+
# instance_properties {
98+
# machine_type: "n2-standard-2"
99+
# local_ssds {
100+
# disk_size_gb: 375
101+
# interface: "SCSI"
102+
# }
103+
# ...
104+
105+
return reservation
106+
107+
108+
# </INGREDIENT>
+21Lines 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_from_vm>
16+
# <IMPORTS/>
17+
18+
# <INGREDIENT wait_for_extended_operation />
19+
20+
# <INGREDIENT create_compute_reservation_from_vm />
21+
# </REGION compute_reservation_create_from_vm>
+163Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
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_from_vm]
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_reservation_from_vm(
80+
project_id: str,
81+
zone: str = "us-central1-a",
82+
reservation_name="your-reservation-name",
83+
vm_name="your-vm-name",
84+
) -> compute_v1.Reservation:
85+
"""Creates a compute reservation in GCP from an existing VM.
86+
Args:
87+
project_id (str): The ID of the Google Cloud project.
88+
zone (str): The zone of the VM. In this zone the reservation will be created.
89+
reservation_name (str): The name of the reservation to create.
90+
vm_name: The name of the VM to create the reservation from.
91+
Returns:
92+
Reservation object that represents the new reservation with the same properties as the VM.
93+
"""
94+
instance_client = compute_v1.InstancesClient()
95+
existing_vm = instance_client.get(project=project_id, zone=zone, instance=vm_name)
96+
97+
guest_accelerators = [
98+
compute_v1.AcceleratorConfig(
99+
accelerator_count=a.accelerator_count,
100+
accelerator_type=a.accelerator_type.split("/")[-1],
101+
)
102+
for a in existing_vm.guest_accelerators
103+
]
104+
105+
local_ssds = [
106+
compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(
107+
disk_size_gb=disk.disk_size_gb, interface=disk.interface
108+
)
109+
for disk in existing_vm.disks
110+
if disk.disk_size_gb >= 375
111+
]
112+
113+
instance_properties = (
114+
compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
115+
machine_type=existing_vm.machine_type.split("/")[-1],
116+
min_cpu_platform=existing_vm.min_cpu_platform,
117+
local_ssds=local_ssds,
118+
guest_accelerators=guest_accelerators,
119+
)
120+
)
121+
122+
reservation = compute_v1.Reservation(
123+
name=reservation_name,
124+
specific_reservation=compute_v1.AllocationSpecificSKUReservation(
125+
count=3, # Number of resources that are allocated.
126+
instance_properties=instance_properties,
127+
),
128+
specific_reservation_required=True,
129+
)
130+
131+
# Create a client
132+
client = compute_v1.ReservationsClient()
133+
134+
operation = client.insert(
135+
project=project_id,
136+
zone=zone,
137+
reservation_resource=reservation,
138+
)
139+
wait_for_extended_operation(operation, "Reservation creation")
140+
141+
reservation = client.get(
142+
project=project_id, zone=zone, reservation=reservation_name
143+
)
144+
145+
print("Name: ", reservation.name)
146+
print("STATUS: ", reservation.status)
147+
print(reservation.specific_reservation)
148+
# Example response:
149+
# Name: your-reservation-name
150+
# STATUS: READY
151+
# count: 3
152+
# instance_properties {
153+
# machine_type: "n2-standard-2"
154+
# local_ssds {
155+
# disk_size_gb: 375
156+
# interface: "SCSI"
157+
# }
158+
# ...
159+
160+
return reservation
161+
162+
163+
# [END compute_reservation_create_from_vm]

‎compute/client_library/snippets/tests/test_compute_reservation.py

Copy file name to clipboardExpand all lines: compute/client_library/snippets/tests/test_compute_reservation.py
+65Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,29 @@
1515
import time
1616
import uuid
1717

18+
from google.cloud import compute_v1
1819
from google.cloud.compute_v1.types import Operation
1920

2021
import pytest
2122

2223
from ..compute_reservations.create_compute_reservation import create_compute_reservation
24+
from ..compute_reservations.create_compute_reservation_from_vm import (
25+
create_compute_reservation_from_vm,
26+
)
2327
from ..compute_reservations.delete_compute_reservation import delete_compute_reservation
2428
from ..compute_reservations.get_compute_reservation import get_compute_reservation
2529
from ..compute_reservations.list_compute_reservation import list_compute_reservation
2630

31+
32+
from ..instances.create import create_instance
33+
from ..instances.delete import delete_instance
34+
35+
INSTANCE_NAME = "test-instance-" + uuid.uuid4().hex[:10]
2736
RESERVATION_NAME = "test-reservation-" + uuid.uuid4().hex[:10]
2837
TIMEOUT = time.time() + 300 # 5 minutes
2938
PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
3039
ZONE = "us-central1-a"
40+
MACHINE_TYPE = "n2-standard-2"
3141

3242

3343
@pytest.fixture()
@@ -46,6 +56,61 @@ def cleanup():
4656
return reservation
4757

4858

59+
@pytest.fixture(scope="session")
60+
def vm_instance():
61+
"""the fixture should create a VM instance"""
62+
boot_disk = compute_v1.AttachedDisk()
63+
boot_disk.auto_delete = True
64+
boot_disk.boot = True
65+
boot_disk.initialize_params = compute_v1.AttachedDiskInitializeParams(
66+
source_image="projects/debian-cloud/global/images/family/debian-11"
67+
)
68+
69+
additional_disk = compute_v1.AttachedDisk()
70+
additional_disk.auto_delete = True
71+
additional_disk.boot = False
72+
additional_disk.initialize_params = compute_v1.AttachedDiskInitializeParams(
73+
disk_size_gb=375
74+
)
75+
additional_disk.interface = "SCSI"
76+
77+
instance = create_instance(
78+
project_id=PROJECT_ID,
79+
zone=ZONE,
80+
instance_name=INSTANCE_NAME,
81+
disks=[boot_disk, additional_disk],
82+
machine_type=MACHINE_TYPE,
83+
)
84+
yield instance
85+
86+
try:
87+
delete_instance(PROJECT_ID, ZONE, INSTANCE_NAME)
88+
except Exception as e:
89+
print(f"Error during cleanup: {e}")
90+
91+
return instance
92+
93+
94+
def test_create_compute_reservation_from_vm(vm_instance):
95+
try:
96+
res_from_vm = create_compute_reservation_from_vm(
97+
PROJECT_ID, ZONE, RESERVATION_NAME, vm_instance.name
98+
)
99+
assert res_from_vm.status == "READY"
100+
assert (
101+
res_from_vm.specific_reservation.instance_properties.local_ssds[
102+
0
103+
].disk_size_gb
104+
== vm_instance.disks[1].disk_size_gb
105+
)
106+
assert (
107+
res_from_vm.specific_reservation.instance_properties.local_ssds[0].interface
108+
== vm_instance.disks[1].interface
109+
)
110+
finally:
111+
delete_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
112+
113+
49114
def test_create_and_get_compute_reservation(reservation):
50115
assert reservation.name == RESERVATION_NAME
51116
assert reservation.status == "READY"

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.