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

feat : Create compute shared reservation Sample #12678

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This is an ingredient file. It is not meant to be run directly. Check the samples/snippets
# folder for complete code samples that are ready to be used.
# Disabling flake8 for the ingredients file, as it would fail F821 - undefined name check.
# flake8: noqa

from google.cloud import compute_v1


# <INGREDIENT create_compute_shared_reservation>
def create_compute_shared_reservation(
project_id: str,
zone: str = "us-central1-a",
reservation_name="your-reservation-name",
shared_project_id: str = "shared-project-id",
) -> compute_v1.Reservation:
"""Creates a compute reservation in GCP.
Args:
project_id (str): The ID of the Google Cloud project.
zone (str): The zone to create the reservation.
reservation_name (str): The name of the reservation to create.
shared_project_id (str): The ID of the project that the reservation is shared with.
Returns:
Reservation object that represents the new reservation.
"""

instance_properties = compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
machine_type="n1-standard-1",
# Optional. Specifies amount of local ssd to reserve with each instance.
local_ssds=[
compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That class name is ridiculous 🤣

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But I don't know what I could do with that 🤷‍♂️
Maybe we could make a request to update the library. Then I could use more readable names here! 😄

disk_size_gb=375, interface="NVME"
),
],
)

reservation = compute_v1.Reservation(
name=reservation_name,
specific_reservation=compute_v1.AllocationSpecificSKUReservation(
count=3, # Number of resources that are allocated.
# If you use source_instance_template, you must exclude the instance_properties field.
# It can be a full or partial URL.
# source_instance_template="projects/[PROJECT_ID]/global/instanceTemplates/my-instance-template",
instance_properties=instance_properties,
),
share_settings=compute_v1.ShareSettings(
share_type="SPECIFIC_PROJECTS",
project_map={
shared_project_id: compute_v1.ShareSettingsProjectConfig(
project_id=shared_project_id
)
},
),
)

# Create a client
client = compute_v1.ReservationsClient()

operation = client.insert(
project=project_id,
zone=zone,
reservation_resource=reservation,
)
wait_for_extended_operation(operation, "Reservation creation")

reservation = client.get(
project=project_id, zone=zone, reservation=reservation_name
)
shared_project = next(iter(reservation.share_settings.project_map.values()))

print("Name: ", reservation.name)
print("STATUS: ", reservation.status)
print("SHARED PROJECT: ", shared_project)
# Example response:
# Name: your-reservation-name
# STATUS: READY
# SHARED PROJECT: project_id: "123456789012"

return reservation


# </INGREDIENT>
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# <REGION compute_reservation_create_shared>
# <IMPORTS/>

# <INGREDIENT wait_for_extended_operation />

# <INGREDIENT create_compute_shared_reservation />
# </REGION compute_reservation_create_shared>
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


# This file is automatically generated. Please do not modify it directly.
# Find the relevant recipe file in the samples/recipes or samples/ingredients
# directory and apply your changes there.


# [START compute_reservation_create_shared]
from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
"""
Waits for the extended (long-running) operation to complete.

If the operation is successful, it will return its result.
If the operation ends with an error, an exception will be raised.
If there were any warnings during the execution of the operation
they will be printed to sys.stderr.

Args:
operation: a long-running operation you want to wait on.
verbose_name: (optional) a more verbose name of the operation,
used only during error and warning reporting.
timeout: how long (in seconds) to wait for operation to finish.
If None, wait indefinitely.

Returns:
Whatever the operation.result() returns.

Raises:
This method will raise the exception received from `operation.exception()`
or RuntimeError if there is no exception set, but there is an `error_code`
set for the `operation`.

In case of an operation taking longer than `timeout` seconds to complete,
a `concurrent.futures.TimeoutError` will be raised.
"""
result = operation.result(timeout=timeout)

if operation.error_code:
print(
f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
file=sys.stderr,
flush=True,
)
print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
raise operation.exception() or RuntimeError(operation.error_message)

if operation.warnings:
print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
for warning in operation.warnings:
print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

return result


def create_compute_shared_reservation(
project_id: str,
zone: str = "us-central1-a",
reservation_name="your-reservation-name",
shared_project_id: str = "shared-project-id",
) -> compute_v1.Reservation:
"""Creates a compute reservation in GCP.
Args:
project_id (str): The ID of the Google Cloud project.
zone (str): The zone to create the reservation.
reservation_name (str): The name of the reservation to create.
shared_project_id (str): The ID of the project that the reservation is shared with.
Returns:
Reservation object that represents the new reservation.
"""

instance_properties = compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
machine_type="n1-standard-1",
# Optional. Specifies amount of local ssd to reserve with each instance.
local_ssds=[
compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(
disk_size_gb=375, interface="NVME"
),
],
)

reservation = compute_v1.Reservation(
name=reservation_name,
specific_reservation=compute_v1.AllocationSpecificSKUReservation(
count=3, # Number of resources that are allocated.
# If you use source_instance_template, you must exclude the instance_properties field.
# It can be a full or partial URL.
# source_instance_template="projects/[PROJECT_ID]/global/instanceTemplates/my-instance-template",
instance_properties=instance_properties,
),
share_settings=compute_v1.ShareSettings(
share_type="SPECIFIC_PROJECTS",
project_map={
shared_project_id: compute_v1.ShareSettingsProjectConfig(
project_id=shared_project_id
)
},
),
)

# Create a client
client = compute_v1.ReservationsClient()

operation = client.insert(
project=project_id,
zone=zone,
reservation_resource=reservation,
)
wait_for_extended_operation(operation, "Reservation creation")

reservation = client.get(
project=project_id, zone=zone, reservation=reservation_name
)
shared_project = next(iter(reservation.share_settings.project_map.values()))

print("Name: ", reservation.name)
print("STATUS: ", reservation.status)
print("SHARED PROJECT: ", shared_project)
# Example response:
# Name: your-reservation-name
# STATUS: READY
# SHARED PROJECT: project_id: "123456789012"

return reservation


# [END compute_reservation_create_shared]
51 changes: 37 additions & 14 deletions 51 compute/client_library/snippets/tests/test_compute_reservation.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
from ..compute_reservations.create_compute_reservation_from_vm import (
create_compute_reservation_from_vm,
)
from ..compute_reservations.create_compute_shared_reservation import (
create_compute_shared_reservation,
)
from ..compute_reservations.delete_compute_reservation import delete_compute_reservation
from ..compute_reservations.get_compute_reservation import get_compute_reservation
from ..compute_reservations.list_compute_reservation import list_compute_reservation
Expand All @@ -38,22 +41,17 @@
PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
ZONE = "us-central1-a"
MACHINE_TYPE = "n2-standard-2"
SHARED_PROJECT_ID = os.getenv("GOOGLE_CLOUD_SHARED_PROJECT")


@pytest.fixture()
def reservation(request) -> str:
def reservation() -> str:
create_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)

def cleanup():
try:
delete_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
except Exception as e:
print(f"Error during cleanup: {e}")

request.addfinalizer(cleanup)

reservation = get_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
return reservation
yield get_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
try:
delete_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
except Exception as e:
print(f"Error during cleanup: {e}")


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

return instance


def test_create_compute_reservation_from_vm(vm_instance):
try:
Expand Down Expand Up @@ -128,3 +124,30 @@ def test_list_compute_reservation(reservation):
def test_delete_compute_reservation(reservation):
response = delete_compute_reservation(PROJECT_ID, ZONE, reservation.name)
assert response.status == Operation.Status.DONE


def test_create_shared_reservation():
"""Test for creating a shared reservation.

The reservation will be created in PROJECT_ID and shared with the project specified
by SHARED_PROJECT_ID.

Make sure to set the GOOGLE_CLOUD_SHARED_PROJECT environment variable before running this test,
and ensure that the project is allowlisted in the organization policy for shared reservations.

If the GOOGLE_CLOUD_SHARED_PROJECT environment variable is not set, the test will be skipped.
"""
if not SHARED_PROJECT_ID:
pytest.skip(
"Skipping test because SHARED_PROJECT_ID environment variable is not set."
Thoughtseize1 marked this conversation as resolved.
Show resolved Hide resolved
)
try:
response = create_compute_shared_reservation(
PROJECT_ID, ZONE, RESERVATION_NAME, SHARED_PROJECT_ID
)
assert response.share_settings.project_map.values()
finally:
try:
delete_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
except Exception as e:
print(f"Failed to delete reservation: {e}")
Morty Proxy This is a proxified and sanitized view of the page, visit original site.