Skip to content

Commit 2b77274

Browse files
committed
Created Schedule attach disk sample
1 parent b65dfd6 commit 2b77274

File tree

4 files changed

+209
-0
lines changed

4 files changed

+209
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
# http://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 attach_disk_schedule_snapshots>
24+
def snapshot_schedule_attach(
25+
project_id: str, zone: str, region: str, disk_name: str, schedule_name: str
26+
) -> None:
27+
"""
28+
Attaches a snapshot schedule to a specified disk.
29+
Args:
30+
project_id (str): The ID of the Google Cloud project.
31+
zone (str): The zone where the disk is located.
32+
region (str): The region where the snapshot schedule was created
33+
disk_name (str): The name of the disk to which the snapshot schedule will be attached.
34+
schedule_name (str): The name of the snapshot schedule that you are applying to this disk
35+
Returns:
36+
None
37+
"""
38+
disks_add_request = compute_v1.DisksAddResourcePoliciesRequest(
39+
resource_policies=[f"regions/{region}/resourcePolicies/{schedule_name}"]
40+
)
41+
42+
client = compute_v1.DisksClient()
43+
operation = client.add_resource_policies(
44+
project=project_id,
45+
zone=zone,
46+
disk=disk_name,
47+
disks_add_resource_policies_request_resource=disks_add_request,
48+
)
49+
wait_for_extended_operation(operation, "Attaching snapshot schedule to disk")
50+
51+
52+
# </INGREDIENT>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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+
# http://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+
# flake8: noqa
15+
16+
# <REGION compute_snapshot_schedule_attach>
17+
# <IMPORTS/>
18+
19+
# <INGREDIENT wait_for_extended_operation />
20+
21+
# <INGREDIENT attach_disk_schedule_snapshots />
22+
23+
# </REGION compute_snapshot_schedule_attach>
Lines 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+
# http://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+
# flake8: noqa
15+
16+
17+
# This file is automatically generated. Please do not modify it directly.
18+
# Find the relevant recipe file in the samples/recipes or samples/ingredients
19+
# directory and apply your changes there.
20+
21+
22+
# [START compute_snapshot_schedule_attach]
23+
from __future__ import annotations
24+
25+
import sys
26+
from typing import Any
27+
28+
from google.api_core.extended_operation import ExtendedOperation
29+
from google.cloud import compute_v1
30+
31+
32+
def wait_for_extended_operation(
33+
operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
34+
) -> Any:
35+
"""
36+
Waits for the extended (long-running) operation to complete.
37+
38+
If the operation is successful, it will return its result.
39+
If the operation ends with an error, an exception will be raised.
40+
If there were any warnings during the execution of the operation
41+
they will be printed to sys.stderr.
42+
43+
Args:
44+
operation: a long-running operation you want to wait on.
45+
verbose_name: (optional) a more verbose name of the operation,
46+
used only during error and warning reporting.
47+
timeout: how long (in seconds) to wait for operation to finish.
48+
If None, wait indefinitely.
49+
50+
Returns:
51+
Whatever the operation.result() returns.
52+
53+
Raises:
54+
This method will raise the exception received from `operation.exception()`
55+
or RuntimeError if there is no exception set, but there is an `error_code`
56+
set for the `operation`.
57+
58+
In case of an operation taking longer than `timeout` seconds to complete,
59+
a `concurrent.futures.TimeoutError` will be raised.
60+
"""
61+
result = operation.result(timeout=timeout)
62+
63+
if operation.error_code:
64+
print(
65+
f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
66+
file=sys.stderr,
67+
flush=True,
68+
)
69+
print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
70+
raise operation.exception() or RuntimeError(operation.error_message)
71+
72+
if operation.warnings:
73+
print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
74+
for warning in operation.warnings:
75+
print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
76+
77+
return result
78+
79+
80+
def snapshot_schedule_attach(
81+
project_id: str, zone: str, region: str, disk_name: str, schedule_name: str
82+
) -> None:
83+
"""
84+
Attaches a snapshot schedule to a specified disk.
85+
Args:
86+
project_id (str): The ID of the Google Cloud project.
87+
zone (str): The zone where the disk is located.
88+
region (str): The region where the snapshot schedule was created
89+
disk_name (str): The name of the disk to which the snapshot schedule will be attached.
90+
schedule_name (str): The name of the snapshot schedule that you are applying to this disk
91+
Returns:
92+
None
93+
"""
94+
disks_add_request = compute_v1.DisksAddResourcePoliciesRequest(
95+
resource_policies=[f"regions/{region}/resourcePolicies/{schedule_name}"]
96+
)
97+
98+
client = compute_v1.DisksClient()
99+
operation = client.add_resource_policies(
100+
project=project_id,
101+
zone=zone,
102+
disk=disk_name,
103+
disks_add_resource_policies_request_resource=disks_add_request,
104+
)
105+
wait_for_extended_operation(operation, "Attaching snapshot schedule to disk")
106+
107+
108+
# [END compute_snapshot_schedule_attach]

compute/client_library/snippets/tests/test_snapshots.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
import uuid
1515

1616
import google.auth
17+
from google.cloud import compute_v1
18+
1719
import pytest
1820

1921
from ..disks.create_from_image import create_disk_from_image
@@ -23,6 +25,7 @@
2325
from ..snapshots.delete import delete_snapshot
2426
from ..snapshots.get import get_snapshot
2527
from ..snapshots.list import list_snapshots
28+
from ..snapshots.schedule_attach_disk import snapshot_schedule_attach
2629
from ..snapshots.schedule_create import snapshot_schedule_create
2730
from ..snapshots.schedule_delete import snapshot_schedule_delete
2831
from ..snapshots.schedule_get import snapshot_schedule_get
@@ -50,6 +53,20 @@ def test_disk():
5053
delete_disk(PROJECT, ZONE, test_disk_name)
5154

5255

56+
@pytest.fixture
57+
def test_schedule_snapshot():
58+
test_schedule_snapshot_name = "test-snapshot-" + uuid.uuid4().hex[:5]
59+
schedule_snapshot = snapshot_schedule_create(
60+
PROJECT,
61+
REGION,
62+
test_schedule_snapshot_name,
63+
"test description",
64+
{"env": "dev", "media": "images"},
65+
)
66+
yield schedule_snapshot
67+
snapshot_schedule_delete(PROJECT, REGION, test_schedule_snapshot_name)
68+
69+
5370
def test_snapshot_create_delete(test_disk):
5471
snapshot_name = "test-snapshot-" + uuid.uuid4().hex[:10]
5572
snapshot = create_snapshot(PROJECT, test_disk.name, snapshot_name, zone=ZONE)
@@ -93,3 +110,12 @@ def test_create_get_list_delete_schedule_snapshot():
93110
finally:
94111
snapshot_schedule_delete(PROJECT, REGION, test_snapshot_name)
95112
assert len(list(snapshot_schedule_list(PROJECT, REGION))) == 0
113+
114+
115+
def test_attach_disk_to_snapshot(test_schedule_snapshot, test_disk):
116+
assert not test_disk.resource_policies
117+
snapshot_schedule_attach(
118+
PROJECT, ZONE, REGION, test_disk.name, test_schedule_snapshot.name
119+
)
120+
disk = compute_v1.DisksClient().get(project=PROJECT, zone=ZONE, disk=test_disk.name)
121+
assert test_schedule_snapshot.name in disk.resource_policies[0]

0 commit comments

Comments
 (0)