Content-Length: 963045 | pFad | https://github.com/googleapis/python-compute/commit/79b26c5dea49717a2774e0b2f89a2669af9ae8c2

0C docs(samples): Bulk insert sample (#299) · googleapis/python-compute@79b26c5 · GitHub
Skip to content
This repository was archived by the owner on Dec 31, 2023. It is now read-only.

Commit 79b26c5

Browse files
m-strzelczykpartheagcf-owl-bot[bot]
authored
docs(samples): Bulk insert sample (#299)
Co-authored-by: Anthonios Partheniou <partheniou@google.com> Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 1baaf5d commit 79b26c5

File tree

4 files changed

+397
-0
lines changed

4 files changed

+397
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Copyright 2022 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+
from typing import Iterable, Optional
16+
import uuid
17+
18+
from google.cloud import compute_v1
19+
20+
21+
# <INGREDIENT bulk_insert_instance>
22+
def bulk_insert_instance(project_id: str, zone: str, template: compute_v1.InstanceTemplate,
23+
count: int, name_pattern: str, min_count: Optional[int] = None,
24+
labels: Optional[dict] = None) -> Iterable[compute_v1.Instance]:
25+
"""
26+
Create multiple VMs based on an Instance Template. The newly created instances will
27+
be returned as a list and will share a label with key `bulk_batch` and a random
28+
value.
29+
30+
If the bulk insert operation fails and the requested number of instances can't be created,
31+
and more than min_count instances are created, then those instances can be found using
32+
the `bulk_batch` label with value attached to the raised exception in bulk_batch_id
33+
attribute. So, you can use the following filter: f"label.bulk_batch={err.bulk_batch_id}"
34+
when listing instances in a zone to get the instances that were successfully created.
35+
36+
Args:
37+
project_id: project ID or project number of the Cloud project you want to use.
38+
zone: name of the zone to create the instance in. For example: "us-west3-b"
39+
template: an Instance Template to be used for creation of the new VMs.
40+
name_pattern: The string pattern used for the names of the VMs. The pattern
41+
must contain one continuous sequence of placeholder hash characters (#)
42+
with each character corresponding to one digit of the generated instance
43+
name. Example: a name_pattern of inst-#### generates instance names such
44+
as inst-0001 and inst-0002. If existing instances in the same project and
45+
zone have names that match the name pattern then the generated instance
46+
numbers start after the biggest existing number. For example, if there
47+
exists an instance with name inst-0050, then instance names generated
48+
using the pattern inst-#### begin with inst-0051. The name pattern
49+
placeholder #...# can contain up to 18 characters.
50+
count: The maximum number of instances to create.
51+
min_count (optional): The minimum number of instances to create. If no min_count is
52+
specified then count is used as the default value. If min_count instances
53+
cannot be created, then no instances will be created and instances already
54+
created will be deleted.
55+
labels (optional): A dictionary with labels to be added to the new VMs.
56+
"""
57+
bulk_insert_resource = compute_v1.BulkInsertInstanceResource()
58+
bulk_insert_resource.source_instance_template = template.self_link
59+
bulk_insert_resource.count = count
60+
bulk_insert_resource.min_count = min_count or count
61+
bulk_insert_resource.name_pattern = name_pattern
62+
63+
if not labels:
64+
labels = {}
65+
66+
labels['bulk_batch'] = uuid.uuid4().hex
67+
instance_prop = compute_v1.InstanceProperties()
68+
instance_prop.labels = labels
69+
bulk_insert_resource.instance_properties = instance_prop
70+
71+
bulk_insert_request = compute_v1.BulkInsertInstanceRequest()
72+
bulk_insert_request.bulk_insert_instance_resource_resource = bulk_insert_resource
73+
bulk_insert_request.project = project_id
74+
bulk_insert_request.zone = zone
75+
76+
client = compute_v1.InstancesClient()
77+
operation = client.bulk_insert(bulk_insert_request)
78+
79+
try:
80+
wait_for_extended_operation(operation, "bulk instance creation")
81+
except Exception as err:
82+
err.bulk_batch_id = labels['bulk_batch']
83+
raise err
84+
85+
list_req = compute_v1.ListInstancesRequest()
86+
list_req.project = project_id
87+
list_req.zone = zone
88+
list_req.filter = " AND ".join(f"labels.{key}:{value}" for key, value in labels.items())
89+
return client.list(list_req)
90+
# </INGREDIENT>
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Copyright 2022 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_instances_bulk_insert>
17+
# <IMPORTS/>
18+
19+
# <INGREDIENT wait_for_extended_operation />
20+
21+
# <INGREDIENT get_instance_template />
22+
23+
# <INGREDIENT bulk_insert_instance />
24+
25+
26+
def create_five_instances(project_id: str, zone: str, template_name: str,
27+
name_pattern: str):
28+
"""
29+
Create five instances of an instance template.
30+
31+
Args:
32+
project_id: project ID or project number of the Cloud project you want to use.
33+
zone: name of the zone to create the instance in. For example: "us-west3-b"
34+
template_name: name of the template that will be used to create new VMs.
35+
name_pattern: The string pattern used for the names of the VMs.
36+
"""
37+
template = get_instance_template(project_id, template_name)
38+
instances = bulk_insert_instance(project_id, zone, template, 5, name_pattern)
39+
return instances
40+
# </REGION compute_instances_bulk_insert>
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
# Copyright 2022 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_instances_bulk_insert]
23+
import sys
24+
from typing import Any, Iterable, Optional
25+
import uuid
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+
This method will wait for the extended (long-running) operation to
36+
complete. If the operation is successful, it will return its result.
37+
If the operation ends with an error, an exception will be raised.
38+
If there were any warnings during the execution of the operation
39+
they will be printed to sys.stderr.
40+
41+
Args:
42+
operation: a long-running operation you want to wait on.
43+
verbose_name: (optional) a more verbose name of the operation,
44+
used only during error and warning reporting.
45+
timeout: how long (in seconds) to wait for operation to finish.
46+
If None, wait indefinitely.
47+
48+
Returns:
49+
Whatever the operation.result() returns.
50+
51+
Raises:
52+
This method will raise the exception received from `operation.exception()`
53+
or RuntimeError if there is no exception set, but there is an `error_code`
54+
set for the `operation`.
55+
56+
In case of an operation taking longer than `timeout` seconds to complete,
57+
a `concurrent.futures.TimeoutError` will be raised.
58+
"""
59+
result = operation.result(timeout=timeout)
60+
61+
if operation.error_code:
62+
print(
63+
f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
64+
file=sys.stderr,
65+
flush=True,
66+
)
67+
print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
68+
raise operation.exception() or RuntimeError(operation.error_message)
69+
70+
if operation.warnings:
71+
print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
72+
for warning in operation.warnings:
73+
print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
74+
75+
return result
76+
77+
78+
def get_instance_template(
79+
project_id: str, template_name: str
80+
) -> compute_v1.InstanceTemplate:
81+
"""
82+
Retrieve an instance template, which you can use to create virtual machine
83+
(VM) instances and managed instance groups (MIGs).
84+
85+
Args:
86+
project_id: project ID or project number of the Cloud project you use.
87+
template_name: name of the template to retrieve.
88+
89+
Returns:
90+
InstanceTemplate object that represents the retrieved template.
91+
"""
92+
template_client = compute_v1.InstanceTemplatesClient()
93+
return template_client.get(project=project_id, instance_template=template_name)
94+
95+
96+
def bulk_insert_instance(
97+
project_id: str,
98+
zone: str,
99+
template: compute_v1.InstanceTemplate,
100+
count: int,
101+
name_pattern: str,
102+
min_count: Optional[int] = None,
103+
labels: Optional[dict] = None,
104+
) -> Iterable[compute_v1.Instance]:
105+
"""
106+
Create multiple VMs based on an Instance Template. The newly created instances will
107+
be returned as a list and will share a label with key `bulk_batch` and a random
108+
value.
109+
110+
If the bulk insert operation fails and the requested number of instances can't be created,
111+
and more than min_count instances are created, then those instances can be found using
112+
the `bulk_batch` label with value attached to the raised exception in bulk_batch_id
113+
attribute. So, you can use the following filter: f"label.bulk_batch={err.bulk_batch_id}"
114+
when listing instances in a zone to get the instances that were successfully created.
115+
116+
Args:
117+
project_id: project ID or project number of the Cloud project you want to use.
118+
zone: name of the zone to create the instance in. For example: "us-west3-b"
119+
template: an Instance Template to be used for creation of the new VMs.
120+
name_pattern: The string pattern used for the names of the VMs. The pattern
121+
must contain one continuous sequence of placeholder hash characters (#)
122+
with each character corresponding to one digit of the generated instance
123+
name. Example: a name_pattern of inst-#### generates instance names such
124+
as inst-0001 and inst-0002. If existing instances in the same project and
125+
zone have names that match the name pattern then the generated instance
126+
numbers start after the biggest existing number. For example, if there
127+
exists an instance with name inst-0050, then instance names generated
128+
using the pattern inst-#### begin with inst-0051. The name pattern
129+
placeholder #...# can contain up to 18 characters.
130+
count: The maximum number of instances to create.
131+
min_count (optional): The minimum number of instances to create. If no min_count is
132+
specified then count is used as the default value. If min_count instances
133+
cannot be created, then no instances will be created and instances already
134+
created will be deleted.
135+
labels (optional): A dictionary with labels to be added to the new VMs.
136+
"""
137+
bulk_insert_resource = compute_v1.BulkInsertInstanceResource()
138+
bulk_insert_resource.source_instance_template = template.self_link
139+
bulk_insert_resource.count = count
140+
bulk_insert_resource.min_count = min_count or count
141+
bulk_insert_resource.name_pattern = name_pattern
142+
143+
if not labels:
144+
labels = {}
145+
146+
labels["bulk_batch"] = uuid.uuid4().hex
147+
instance_prop = compute_v1.InstanceProperties()
148+
instance_prop.labels = labels
149+
bulk_insert_resource.instance_properties = instance_prop
150+
151+
bulk_insert_request = compute_v1.BulkInsertInstanceRequest()
152+
bulk_insert_request.bulk_insert_instance_resource_resource = bulk_insert_resource
153+
bulk_insert_request.project = project_id
154+
bulk_insert_request.zone = zone
155+
156+
client = compute_v1.InstancesClient()
157+
operation = client.bulk_insert(bulk_insert_request)
158+
159+
try:
160+
wait_for_extended_operation(operation, "bulk instance creation")
161+
except Exception as err:
162+
err.bulk_batch_id = labels["bulk_batch"]
163+
raise err
164+
165+
list_req = compute_v1.ListInstancesRequest()
166+
list_req.project = project_id
167+
list_req.zone = zone
168+
list_req.filter = " AND ".join(
169+
f"labels.{key}:{value}" for key, value in labels.items()
170+
)
171+
return client.list(list_req)
172+
173+
174+
def create_five_instances(
175+
project_id: str, zone: str, template_name: str, name_pattern: str
176+
):
177+
"""
178+
Create five instances of an instance template.
179+
180+
Args:
181+
project_id: project ID or project number of the Cloud project you want to use.
182+
zone: name of the zone to create the instance in. For example: "us-west3-b"
183+
template_name: name of the template that will be used to create new VMs.
184+
name_pattern: The string pattern used for the names of the VMs.
185+
"""
186+
template = get_instance_template(project_id, template_name)
187+
instances = bulk_insert_instance(project_id, zone, template, 5, name_pattern)
188+
return instances
189+
190+
191+
# [END compute_instances_bulk_insert]

0 commit comments

Comments
 (0)








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: https://github.com/googleapis/python-compute/commit/79b26c5dea49717a2774e0b2f89a2669af9ae8c2

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy