|
| 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