|
| 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_windows_image_create] |
| 23 | +# [START compute_images_create] |
| 24 | +import sys |
| 25 | +import time |
| 26 | +from typing import Any |
| 27 | +import warnings |
| 28 | + |
| 29 | +from google.api_core.extended_operation import ExtendedOperation |
| 30 | +from google.cloud import compute_v1 |
| 31 | + |
| 32 | + |
| 33 | +def wait_for_extended_operation( |
| 34 | + operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300 |
| 35 | +) -> Any: |
| 36 | + """ |
| 37 | + This method will wait for the extended (long-running) operation to |
| 38 | + complete. 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 | + ) |
| 68 | + print(f"Operation ID: {operation.name}") |
| 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) |
| 73 | + for warning in operation.warnings: |
| 74 | + print(f" - {warning.code}: {warning.message}", file=sys.stderr) |
| 75 | + |
| 76 | + return result |
| 77 | + |
| 78 | + |
| 79 | +STOPPED_MACHINE_STATUS = ( |
| 80 | + compute_v1.Instance.Status.TERMINATED.name, |
| 81 | + compute_v1.Instance.Status.STOPPED.name, |
| 82 | +) |
| 83 | + |
| 84 | + |
| 85 | +def create_image( |
| 86 | + project_id: str, |
| 87 | + zone: str, |
| 88 | + source_disk_name: str, |
| 89 | + image_name: str, |
| 90 | + storage_location: str = None, |
| 91 | + force_create: bool = False, |
| 92 | +) -> compute_v1.Image: |
| 93 | + """ |
| 94 | + Creates a new disk image. |
| 95 | +
|
| 96 | + Args: |
| 97 | + project_id: project ID or project number of the Cloud project you use. |
| 98 | + zone: zone of the disk you copy from. |
| 99 | + source_disk_name: name of the source disk you copy from. |
| 100 | + image_name: name of the image you want to create. |
| 101 | + storage_location: storage location for the image. If the value is undefined, |
| 102 | + function will store the image in the multi-region closest to your image's |
| 103 | + source location. |
| 104 | + force_create: create the image even if the source disk is attached to a |
| 105 | + running instance. |
| 106 | + """ |
| 107 | + image_client = compute_v1.ImagesClient() |
| 108 | + disk_client = compute_v1.DisksClient() |
| 109 | + instance_client = compute_v1.InstancesClient() |
| 110 | + |
| 111 | + # Get source disk |
| 112 | + disk = disk_client.get(project=project_id, zone=zone, disk=source_disk_name) |
| 113 | + |
| 114 | + for disk_user in disk.users: |
| 115 | + instance = instance_client.get( |
| 116 | + project=project_id, zone=zone, instance=disk_user |
| 117 | + ) |
| 118 | + if instance.status in STOPPED_MACHINE_STATUS: |
| 119 | + continue |
| 120 | + if not force_create: |
| 121 | + raise RuntimeError( |
| 122 | + f"Instance {disk_user} should be stopped. For Windows instances please " |
| 123 | + f"stop the instance using `GCESysprep` command. For Linux instances just " |
| 124 | + f"shut it down normally. You can supress this error and create an image of" |
| 125 | + f"the disk by setting `force_create` parameter to true (not recommended). \n" |
| 126 | + f"More information here: \n" |
| 127 | + f" * https://cloud.google.com/compute/docs/instances/windows/creating-windows-os-image#api \n" |
| 128 | + f" * https://cloud.google.com/compute/docs/images/create-delete-deprecate-private-images#prepare_instance_for_image" |
| 129 | + ) |
| 130 | + else: |
| 131 | + warnings.warn( |
| 132 | + f"Warning: The `force_create` option may compromise the integrity of your image. " |
| 133 | + f"Stop the {disk_user} instance before you create the image if possible." |
| 134 | + ) |
| 135 | + |
| 136 | + # Create image |
| 137 | + image = compute_v1.Image() |
| 138 | + image.source_disk = disk.self_link |
| 139 | + image.name = image_name |
| 140 | + if storage_location: |
| 141 | + image.storage_locations = [storage_location] |
| 142 | + |
| 143 | + operation = image_client.insert(project=project_id, image_resource=image) |
| 144 | + |
| 145 | + wait_for_extended_operation(operation, "image creation") |
| 146 | + |
| 147 | + return image_client.get(project=project_id, image=image_name) |
| 148 | + |
| 149 | + |
| 150 | +# [END compute_images_create] |
| 151 | +# [END compute_windows_image_create] |
0 commit comments