Crea e utilizza VM spot

In questa pagina viene spiegato come creare e gestire VM spot, tra cui:

  • Come creare, avviare e identificare le VM spot
  • Come rilevare, gestire e testare il prerilascio delle VM spot
  • Best practice per le VM spot

Le VM spot sono istanze di macchine virtuali (VM) con modello di provisioning spot. Le VM spot sono disponibili con uno sconto fino al 60-91% rispetto il prezzo delle VM standard. Tuttavia, Compute Engine potrebbe recuperare le risorse prerilasciando le VM spot in qualsiasi momento. Le VM spot sono consigliate solo per le applicazioni a tolleranza di errore che il prerilascio delle VM. Assicurati che la tua applicazione possa gestire il prerilascio prima di decidere per creare VM spot.

Prima di iniziare

  • Leggi la documentazione concettuale per le VM spot:
    • Esamina il limitazioni e i prezzi di Spot VM.
    • Per evitare che le VM spot consumino le tue quote per delle VM standard CPU, GPU e dischi, valuta la possibilità di richiedere quota prerilasciabile per Spot VM.
  • Se non l'hai già fatto, configura l'autenticazione. Autenticazione è la procedura di verifica dell'identità per l'accesso ai servizi e alle API di Google Cloud. Per eseguire codice o esempi da un ambiente di sviluppo locale, puoi eseguire l'autenticazione Compute Engine come segue.

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    1. Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init
    2. Set a default region and zone.
    3. Terraform

      Per utilizzare gli esempi di Terraform in questa pagina in un ambiente dell'ambiente di sviluppo, installare e inizializzare gcloud CLI quindi configura Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. Create local authentication credentials for your user account:

        gcloud auth application-default login

      Per ulteriori informazioni, vedi Set up authentication for a local development environment.

      REST

      Per utilizzare gli esempi di API REST in questa pagina in un ambiente di sviluppo locale, utilizzi le credenziali che fornisci a gcloud CLI.

        Install the Google Cloud CLI, then initialize it by running the following command:

        gcloud init

      Per ulteriori informazioni, vedi Esegui l'autenticazione per l'utilizzo di REST nella documentazione sull'autenticazione di Google Cloud.

Crea una VM spot

Creare una VM spot utilizzando la console Google Cloud gcloud CLI o l'API Compute Engine. Una VM spot è qualsiasi VM configurata per utilizzare lo spot di provisioning predefinito:

  • Modello di provisioning delle VM impostato su Spot nella console Google Cloud
  • --provisioning-model=SPOT nell'interfaccia alla gcloud CLI
  • "provisioningModel": "SPOT" nell'API Compute Engine
di Gemini Advanced.

Console

  1. Nella console Google Cloud, vai alla pagina Crea un'istanza.

    Vai a Crea un'istanza

  2. Poi segui questi passaggi:

    1. Nella sezione Criteri di disponibilità, seleziona Spot. dall'elenco Modello di provisioning delle VM. Questa impostazione disattiva le opzioni di riavvio automatico e manutenzione dell'host per la VM consente di attivare l'opzione di azione di chiusura.
    2. (Facoltativo) Nell'elenco Alla terminazione della VM, seleziona cosa succede quando Compute Engine prerilascia la VM:
      • Per arrestare la VM durante il prerilascio, seleziona Arresta (impostazione predefinita).
      • Per eliminare la VM durante il prerilascio, seleziona Elimina.
  3. (Facoltativo) Specifica altre opzioni della VM. Per ulteriori informazioni, consulta Creazione e avvio di un'istanza VM.

  4. Per creare e avviare la VM, fai clic su Crea.

gcloud

Per creare una VM da gcloud CLI, utilizza Comando gcloud compute instances create. Per creare VM spot, devi includere --provisioning-model=SPOT flag. Se vuoi, puoi anche specificare di terminazione per le VM spot includendo anche --instance-termination-action flag.

gcloud compute instances create VM_NAME \
    --provisioning-model=SPOT \
    --instance-termination-action=TERMINATION_ACTION

Sostituisci quanto segue:

  • VM_NAME: nome del una nuova VM.
  • TERMINATION_ACTION: facoltativo, specifica quale l'azione da intraprendere quando Compute Engine prerilasa VM, STOP (comportamento predefinito) o DELETE.

Per ulteriori informazioni sulle opzioni che puoi specificare durante la creazione di una VM, consulta Creazione e avvio di un'istanza VM. Ad esempio, per creare VM spot con un'immagine e un tipo di macchina specificati, utilizza questo comando:

gcloud compute instances create VM_NAME \
    --provisioning-model=SPOT \
    [--image=IMAGE | --image-family=IMAGE_FAMILY] \
    --image-project=IMAGE_PROJECT \
    --machine-type=MACHINE_TYPE \
    --instance-termination-action=TERMINATION_ACTION

Sostituisci quanto segue:

  • VM_NAME: nome del una nuova VM.
  • IMAGE: specifica una delle seguenti opzioni:
    • IMAGE: una versione specifica di un un'immagine pubblica o la famiglia di immagini. Ad esempio, un'immagine specifica viene --image=debian-10-buster-v20200309.
    • Una famiglia di immagini. Questa operazione crea la VM dall'immagine del sistema operativo più recente e non deprecata. Ad esempio, se specifichi --image-family=debian-10, Compute Engine crea una VM dall'ultima versione Immagine sistema operativo nella famiglia di immagini Debian 10.
  • IMAGE_PROJECT: il valore progetto contenente l'immagine. Ad esempio, se specifichi debian-10 come famiglia di immagini, specifica debian-cloud come progetto immagine.
  • MACHINE_TYPE: il valore predefinita o personalizzato, per la nuova VM.
  • TERMINATION_ACTION: facoltativo, specifica quale l'azione da intraprendere quando Compute Engine prerilasa VM, STOP (comportamento predefinito) o DELETE.

    Per ottenere un elenco dei tipi di macchina disponibili in una zona, utilizza Comando gcloud compute machine-types list con il flag --zones.

Terraform

Puoi utilizzare un modello Terraform risorsa per creare un'istanza spot utilizzando il blocco di pianificazione


resource "google_compute_instance" "spot_vm_instance" {
  name         = "spot-instance-name"
  machine_type = "f1-micro"
  zone         = "us-central1-c"

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
    }
  }

  scheduling {
    preemptible                 = true
    automatic_restart           = false
    provisioning_model          = "SPOT"
    instance_termination_action = "STOP"
  }

  network_interface {
    # A default network is created for all GCP projects
    network = "default"
    access_config {
    }
  }
}

REST

Per creare una VM dall'API Compute Engine, utilizza Metodo instances.insert. Devi specificare un tipo di macchina e un nome per la VM. Facoltativamente, puoi e specificare anche un'immagine per il disco di avvio.

Per creare VM spot, devi includere il campo "provisioningModel": spot. Se vuoi, puoi anche specificare un'azione di terminazione per le VM spot incluso il campo "instanceTerminationAction".

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances
{
 "machineType": "zones/ZONE/machineTypes/MACHINE_TYPE",
 "name": "VM_NAME",
 "disks": [
   {
     "initializeParams": {
       "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"
     },
     "boot": true
   }
 ]
 "scheduling":
 {
     "provisioningModel": "SPOT",
     "instanceTerminationAction": "TERMINATION_ACTION"
 },
 ...
}

Sostituisci quanto segue:

  • PROJECT_ID: il valore ID progetto del progetto in cui creare la VM.
  • ZONE: la zona in cui creare la VM. La zona deve supportare anche tipo di macchina utilizzare per la nuova VM.
  • MACHINE_TYPE: il valore predefinita o personalizzato, per la nuova VM.
  • VM_NAME: il valore nome del una nuova VM.
  • IMAGE_PROJECT: il valore project contenente l'immagine. Ad esempio, se specifichi family/debian-10 come famiglia di immagini, specifica debian-cloud come progetto immagine.
  • IMAGE: specifica una delle seguenti opzioni:
    • Una versione specifica di un'immagine pubblica. Ad esempio, un'immagine specifica viene "sourceImage": "projects/debian-cloud/global/images/debian-10-buster-v20200309" dove debian-cloud è il IMAGE_PROJECT.
    • Una famiglia di immagini. Questa operazione crea la VM dall'immagine del sistema operativo più recente e non deprecata. Ad esempio, se specifichi "sourceImage": "projects/debian-cloud/global/images/family/debian-10" dove debian-cloud è il IMAGE_PROJECT, Compute Engine crea una VM dall'ultima versione Immagine sistema operativo nella famiglia di immagini Debian 10.
  • TERMINATION_ACTION: facoltativo, specifica quale l'azione da intraprendere quando Compute Engine prerilasa VM, STOP (comportamento predefinito) o DELETE.

Per ulteriori informazioni sulle opzioni che puoi specificare durante la creazione di una VM, consulta Creazione e avvio di un'istanza VM.

Vai


import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	"cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/protobuf/proto"
)

// createSpotInstance creates a new Spot VM instance with Debian 10 operating system.
func createSpotInstance(w io.Writer, projectID, zone, instanceName string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"

	ctx := context.Background()
	imagesClient, err := compute.NewImagesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewImagesRESTClient: %w", err)
	}
	defer imagesClient.Close()

	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	req := &computepb.GetFromFamilyImageRequest{
		Project: "debian-cloud",
		Family:  "debian-11",
	}

	image, err := imagesClient.GetFromFamily(ctx, req)
	if err != nil {
		return fmt.Errorf("getImageFromFamily: %w", err)
	}

	diskType := fmt.Sprintf("zones/%s/diskTypes/pd-standard", zone)
	disks := []*computepb.AttachedDisk{
		{
			AutoDelete: proto.Bool(true),
			Boot:       proto.Bool(true),
			InitializeParams: &computepb.AttachedDiskInitializeParams{
				DiskSizeGb:  proto.Int64(10),
				DiskType:    proto.String(diskType),
				SourceImage: proto.String(image.GetSelfLink()),
			},
			Type: proto.String(computepb.AttachedDisk_PERSISTENT.String()),
		},
	}

	req2 := &computepb.InsertInstanceRequest{
		Project: projectID,
		Zone:    zone,
		InstanceResource: &computepb.Instance{
			Name:        proto.String(instanceName),
			Disks:       disks,
			MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/%s", zone, "n1-standard-1")),
			NetworkInterfaces: []*computepb.NetworkInterface{
				{
					Name: proto.String("global/networks/default"),
				},
			},
			Scheduling: &computepb.Scheduling{
				ProvisioningModel: proto.String(computepb.Scheduling_SPOT.String()),
			},
		},
	}
	op, err := instancesClient.Insert(ctx, req2)
	if err != nil {
		return fmt.Errorf("insert: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	instance, err := instancesClient.Get(ctx, &computepb.GetInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	})

	if err != nil {
		return fmt.Errorf("createInstance: %w", err)
	}

	fmt.Fprintf(w, "Instance created: %v\n", instance)
	return nil
}

Java


import com.google.cloud.compute.v1.AccessConfig;
import com.google.cloud.compute.v1.AccessConfig.Type;
import com.google.cloud.compute.v1.Address.NetworkTier;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.ImagesClient;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import com.google.cloud.compute.v1.Scheduling;
import com.google.cloud.compute.v1.Scheduling.ProvisioningModel;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateSpotVm {
  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Name of the virtual machine to check.
    String instanceName = "your-instance-name";
    // Name of the zone you want to use. For example: "us-west3-b"
    String zone = "your-zone";

    createSpotInstance(projectId, instanceName, zone);
  }

  // Create a new Spot VM instance with Debian 11 operating system.
  public static Instance createSpotInstance(String projectId, String instanceName, String zone)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    String image;
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (ImagesClient imagesClient = ImagesClient.create()) {
      image = imagesClient.getFromFamily("debian-cloud", "debian-11").getSelfLink();
    }
    AttachedDisk attachedDisk = buildAttachedDisk(image, zone);
    String machineTypes = String.format("zones/%s/machineTypes/%s", zone, "n1-standard-1");

    // Send an instance creation request to the Compute Engine API and wait for it to complete.
    Instance instance =
            createInstance(projectId, zone, instanceName, attachedDisk, true, machineTypes, false);

    System.out.printf("Spot instance '%s' has been created successfully", instance.getName());

    return instance;
  }

  // disks: a list of compute_v1.AttachedDisk objects describing the disks
  //     you want to attach to your new instance.
  // machine_type: machine type of the VM being created. This value uses the
  //     following format: "zones/{zone}/machineTypes/{type_name}".
  //     For example: "zones/europe-west3-c/machineTypes/f1-micro"
  // external_access: boolean flag indicating if the instance should have an external IPv4
  //     address assigned.
  // spot: boolean value indicating if the new instance should be a Spot VM or not.
  private static Instance createInstance(String projectId, String zone, String instanceName,
                                         AttachedDisk disk, boolean isSpot, String machineType,
                                         boolean externalAccess)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (InstancesClient client = InstancesClient.create()) {
      Instance instanceResource =
              buildInstanceResource(instanceName, disk, machineType, externalAccess, isSpot);

      InsertInstanceRequest build = InsertInstanceRequest.newBuilder()
              .setProject(projectId)
              .setRequestId(UUID.randomUUID().toString())
              .setZone(zone)
              .setInstanceResource(instanceResource)
              .build();
      client.insertCallable().futureCall(build).get(60, TimeUnit.SECONDS);

      return client.get(projectId, zone, instanceName);
    }
  }

  private static Instance buildInstanceResource(String instanceName, AttachedDisk disk,
                                                String machineType, boolean externalAccess,
                                                boolean isSpot) {
    NetworkInterface networkInterface =
            networkInterface(externalAccess);
    Instance.Builder builder = Instance.newBuilder()
            .setName(instanceName)
            .addDisks(disk)
            .setMachineType(machineType)
            .addNetworkInterfaces(networkInterface);

    if (isSpot) {
      // Set the Spot VM setting
      Scheduling.Builder scheduling = builder.getScheduling()
              .toBuilder()
              .setProvisioningModel(ProvisioningModel.SPOT.name())
              .setInstanceTerminationAction("STOP");
      builder.setScheduling(scheduling);
    }

    return builder.build();
  }

  private static NetworkInterface networkInterface(boolean externalAccess) {
    NetworkInterface.Builder build = NetworkInterface.newBuilder()
            .setNetwork("global/networks/default");

    if (externalAccess) {
      AccessConfig.Builder accessConfig = AccessConfig.newBuilder()
              .setType(Type.ONE_TO_ONE_NAT.name())
              .setName("External NAT")
              .setNetworkTier(NetworkTier.PREMIUM.name());
      build.addAccessConfigs(accessConfig.build());
    }

    return build.build();
  }

  private static AttachedDisk buildAttachedDisk(String sourceImage, String zone) {
    AttachedDiskInitializeParams initializeParams = AttachedDiskInitializeParams.newBuilder()
            .setSourceImage(sourceImage)
            .setDiskSizeGb(10)
            .setDiskType(String.format("zones/%s/diskTypes/pd-standard", zone))
            .build();
    return AttachedDisk.newBuilder()
            .setInitializeParams(initializeParams)
            // Remember to set auto_delete to True if you want the disk to be deleted
            // when you delete your VM instance.
            .setAutoDelete(true)
            .setBoot(true)
            .build();
  }
}

Python

from __future__ import annotations

import re
import sys
from typing import Any
import warnings

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


def get_image_from_family(project: str, family: str) -> compute_v1.Image:
    """
    Retrieve the newest image that is part of a given family in a project.

    Args:
        project: project ID or project number of the Cloud project you want to get image from.
        family: name of the image family you want to get image from.

    Returns:
        An Image object.
    """
    image_client = compute_v1.ImagesClient()
    # List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
    newest_image = image_client.get_from_family(project=project, family=family)
    return newest_image


def disk_from_image(
    disk_type: str,
    disk_size_gb: int,
    boot: bool,
    source_image: str,
    auto_delete: bool = True,
) -> compute_v1.AttachedDisk:
    """
    Create an AttachedDisk object to be used in VM instance creation. Uses an image as the
    source for the new disk.

    Args:
         disk_type: the type of disk you want to create. This value uses the following format:
            "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
            For example: "zones/us-west3-b/diskTypes/pd-ssd"
        disk_size_gb: size of the new disk in gigabytes
        boot: boolean flag indicating whether this disk should be used as a boot disk of an instance
        source_image: source image to use when creating this disk. You must have read access to this disk. This can be one
            of the publicly available images or an image from one of your projects.
            This value uses the following format: "projects/{project_name}/global/images/{image_name}"
        auto_delete: boolean flag indicating whether this disk should be deleted with the VM that uses it

    Returns:
        AttachedDisk object configured to be created using the specified image.
    """
    boot_disk = compute_v1.AttachedDisk()
    initialize_params = compute_v1.AttachedDiskInitializeParams()
    initialize_params.source_image = source_image
    initialize_params.disk_size_gb = disk_size_gb
    initialize_params.disk_type = disk_type
    boot_disk.initialize_params = initialize_params
    # Remember to set auto_delete to True if you want the disk to be deleted when you delete
    # your VM instance.
    boot_disk.auto_delete = auto_delete
    boot_disk.boot = boot
    return boot_disk


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_instance(
    project_id: str,
    zone: str,
    instance_name: str,
    disks: list[compute_v1.AttachedDisk],
    machine_type: str = "n1-standard-1",
    network_link: str = "global/networks/default",
    subnetwork_link: str = None,
    internal_ip: str = None,
    external_access: bool = False,
    external_ipv4: str = None,
    accelerators: list[compute_v1.AcceleratorConfig] = None,
    preemptible: bool = False,
    spot: bool = False,
    instance_termination_action: str = "STOP",
    custom_hostname: str = None,
    delete_protection: bool = False,
) -> compute_v1.Instance:
    """
    Send an instance creation request to the Compute Engine API and wait for it to complete.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone to create the instance in. For example: "us-west3-b"
        instance_name: name of the new virtual machine (VM) instance.
        disks: a list of compute_v1.AttachedDisk objects describing the disks
            you want to attach to your new instance.
        machine_type: machine type of the VM being created. This value uses the
            following format: "zones/{zone}/machineTypes/{type_name}".
            For example: "zones/europe-west3-c/machineTypes/f1-micro"
        network_link: name of the network you want the new instance to use.
            For example: "global/networks/default" represents the network
            named "default", which is created automatically for each project.
        subnetwork_link: name of the subnetwork you want the new instance to use.
            This value uses the following format:
            "regions/{region}/subnetworks/{subnetwork_name}"
        internal_ip: internal IP address you want to assign to the new instance.
            By default, a free address from the pool of available internal IP addresses of
            used subnet will be used.
        external_access: boolean flag indicating if the instance should have an external IPv4
            address assigned.
        external_ipv4: external IPv4 address to be assigned to this instance. If you specify
            an external IP address, it must live in the same region as the zone of the instance.
            This setting requires `external_access` to be set to True to work.
        accelerators: a list of AcceleratorConfig objects describing the accelerators that will
            be attached to the new instance.
        preemptible: boolean value indicating if the new instance should be preemptible
            or not. Preemptible VMs have been deprecated and you should now use Spot VMs.
        spot: boolean value indicating if the new instance should be a Spot VM or not.
        instance_termination_action: What action should be taken once a Spot VM is terminated.
            Possible values: "STOP", "DELETE"
        custom_hostname: Custom hostname of the new VM instance.
            Custom hostnames must conform to RFC 1035 requirements for valid hostnames.
        delete_protection: boolean value indicating if the new virtual machine should be
            protected against deletion or not.
    Returns:
        Instance object.
    """
    instance_client = compute_v1.InstancesClient()

    # Use the network interface provided in the network_link argument.
    network_interface = compute_v1.NetworkInterface()
    network_interface.network = network_link
    if subnetwork_link:
        network_interface.subnetwork = subnetwork_link

    if internal_ip:
        network_interface.network_i_p = internal_ip

    if external_access:
        access = compute_v1.AccessConfig()
        access.type_ = compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT.name
        access.name = "External NAT"
        access.network_tier = access.NetworkTier.PREMIUM.name
        if external_ipv4:
            access.nat_i_p = external_ipv4
        network_interface.access_configs = [access]

    # Collect information into the Instance object.
    instance = compute_v1.Instance()
    instance.network_interfaces = [network_interface]
    instance.name = instance_name
    instance.disks = disks
    if re.match(r"^zones/[a-z\d\-]+/machineTypes/[a-z\d\-]+$", machine_type):
        instance.machine_type = machine_type
    else:
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"

    instance.scheduling = compute_v1.Scheduling()
    if accelerators:
        instance.guest_accelerators = accelerators
        instance.scheduling.on_host_maintenance = (
            compute_v1.Scheduling.OnHostMaintenance.TERMINATE.name
        )

    if preemptible:
        # Set the preemptible setting
        warnings.warn(
            "Preemptible VMs are being replaced by Spot VMs.", DeprecationWarning
        )
        instance.scheduling = compute_v1.Scheduling()
        instance.scheduling.preemptible = True

    if spot:
        # Set the Spot VM setting
        instance.scheduling.provisioning_model = (
            compute_v1.Scheduling.ProvisioningModel.SPOT.name
        )
        instance.scheduling.instance_termination_action = instance_termination_action

    if custom_hostname is not None:
        # Set the custom hostname for the instance
        instance.hostname = custom_hostname

    if delete_protection:
        # Set the delete protection bit
        instance.deletion_protection = True

    # Prepare the request to insert an instance.
    request = compute_v1.InsertInstanceRequest()
    request.zone = zone
    request.project = project_id
    request.instance_resource = instance

    # Wait for the create operation to complete.
    print(f"Creating the {instance_name} instance in {zone}...")

    operation = instance_client.insert(request=request)

    wait_for_extended_operation(operation, "instance creation")

    print(f"Instance {instance_name} created.")
    return instance_client.get(project=project_id, zone=zone, instance=instance_name)


def create_spot_instance(
    project_id: str, zone: str, instance_name: str
) -> compute_v1.Instance:
    """
    Create a new Spot VM instance with Debian 10 operating system.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone to create the instance in. For example: "us-west3-b"
        instance_name: name of the new virtual machine (VM) instance.

    Returns:
        Instance object.
    """
    newest_debian = get_image_from_family(project="debian-cloud", family="debian-11")
    disk_type = f"zones/{zone}/diskTypes/pd-standard"
    disks = [disk_from_image(disk_type, 10, True, newest_debian.self_link)]
    instance = create_instance(project_id, zone, instance_name, disks, spot=True)
    return instance

Per creare più VM spot con le stesse proprietà, puoi crea un modello di istanza, e utilizzare il modello per creare gruppo di istanze gestite. Per saperne di più, consulta le best practice.

Avvia VM spot

Come le altre VM, le VM spot iniziano al momento della creazione. Analogamente, se Le VM spot vengono arrestate, puoi riavvia le VM per ripristinare lo stato RUNNING. Puoi arrestare e riavviare le VM spot prerilasciate tutte le volte che vuoi, purché ci sia capacità. Per ulteriori informazioni, vedi Ciclo di vita delle istanze VM.

Se Compute Engine arresta una o più VM spot in una scalabilità automatica gruppo di istanze gestite (MIG) o cluster Google Kubernetes Engine (GKE), riavvia le VM quando le risorse diventano di nuovo disponibili.

Identifica il modello di provisioning di una VM e l'azione di terminazione

l'identificazione delle VM modello di provisioning per vedere se si tratta di una VM standard, una VM spot VM prerilasciabile. Per una VM Spot, puoi anche identificare azione di chiusura. Puoi identificare il modello di provisioning e l'azione di terminazione di una VM utilizzando Console Google Cloud, gcloud CLI o l'API Compute Engine.

Console

  1. Vai alla pagina Istanze VM.

    Vai alla pagina Istanze VM

  2. Fai clic sul nome della VM che vuoi identificare. La Si apre la pagina Dettagli istanza VM.

  3. Vai alla sezione Gestione nella parte inferiore della pagina. Nella sottosezione Criteri di disponibilità, controlla le seguenti opzioni:

    • Se il modello di provisioning delle VM è impostato su Spot, la VM è una VM spot.
      • Alla terminazione della VM indica quale azione intraprendere quando Compute Engine prerilascia la VM tramite Arresta o Elimina la VM.
    • In caso contrario, se il modello di provisioning delle VM è impostato su Standard. o :
      • Se l'opzione Prerilasciabilità è impostata su On, la VM è una VM prerilasciabile.
      • In caso contrario, si tratta di una VM standard.

gcloud

Per descrivere una VM da gcloud CLI, utilizza Comando gcloud compute instances describe:

gcloud compute instances describe VM_NAME

dove VM_NAME è il name della VM che desideri controllare.

Nell'output, controlla il campo scheduling per identificare la VM:

  • Se l'output include il campo provisioningModel impostato su SPOT, in modo simile alla seguente, la VM è una VM spot.

    ...
    scheduling:
    ...
    provisioningModel: SPOT
    instanceTerminationAction: TERMINATION_ACTION
    ...
    

    dove TERMINATION_ACTION indica quale l'azione da intraprendere quando Compute Engine prerilasa Arresta (STOP) o elimina (DELETE) la VM. Se Campo instanceTerminationAction mancante. Il valore predefinito è STOP.

  • In caso contrario, se l'output include il campo provisioningModel impostato su standard oppure se nell'output il campo provisioningModel viene omesso:

    • Se l'output include il campo preemptible impostato su true, il valore La VM è una VM prerilasciabile.
    • In caso contrario, si tratta di una VM standard.

REST

Per descrivere una VM dall'API Compute Engine, utilizza Metodo instances.get:

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME

Sostituisci quanto segue:

  • PROJECT_ID: il valore ID progetto del progetto in cui si trova la VM.
  • ZONE: la zona in cui si trova la VM.
  • VM_NAME: il valore name della VM che desideri controllare.

Nell'output, controlla il campo scheduling per identificare la VM:

  • Se l'output include il campo provisioningModel impostato su SPOT, in modo simile alla seguente, la VM è una VM spot.

    {
      ...
      "scheduling":
      {
         ...
         "provisioningModel": "SPOT",
         "instanceTerminationAction": "TERMINATION_ACTION"
         ...
      },
      ...
    }
    

    dove TERMINATION_ACTION indica quale l'azione da intraprendere quando Compute Engine prerilasa Arresta (STOP) o elimina (DELETE) la VM. Se Campo instanceTerminationAction mancante. Il valore predefinito è STOP.

  • In caso contrario, se l'output include il campo provisioningModel impostato su standard oppure se nell'output il campo provisioningModel viene omesso:

    • Se l'output include il campo preemptible impostato su true, il valore La VM è una VM prerilasciabile.
    • In caso contrario, si tratta di una VM standard.

Vai


import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	"cloud.google.com/go/compute/apiv1/computepb"
)

// isSpotVM checks if a given instance is a Spot VM or not.
func isSpotVM(w io.Writer, projectID, zone, instanceName string) (bool, error) {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	ctx := context.Background()
	client, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return false, fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer client.Close()

	req := &computepb.GetInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	}

	instance, err := client.Get(ctx, req)
	if err != nil {
		return false, fmt.Errorf("GetInstance: %w", err)
	}

	isSpot := instance.GetScheduling().GetProvisioningModel() == computepb.Scheduling_SPOT.String()

	var isSpotMessage string
	if !isSpot {
		isSpotMessage = " not"
	}
	fmt.Fprintf(w, "Instance %s is%s spot\n", instanceName, isSpotMessage)

	return instance.GetScheduling().GetProvisioningModel() == computepb.Scheduling_SPOT.String(), nil
}

Java


import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.Scheduling;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class CheckIsSpotVm {
  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Name of the virtual machine to check.
    String instanceName = "your-route-name";
    // Name of the zone you want to use. For example: "us-west3-b"
    String zone = "your-zone";

    boolean isSpotVm = isSpotVm(projectId, instanceName, zone);
    System.out.printf("Is %s spot VM instance - %s", instanceName, isSpotVm);
  }

  // Check if a given instance is Spot VM or not.
  public static boolean isSpotVm(String projectId, String instanceName, String zone)
          throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (InstancesClient client = InstancesClient.create()) {
      Instance instance = client.get(projectId, zone, instanceName);

      return instance.getScheduling().getProvisioningModel()
              .equals(Scheduling.ProvisioningModel.SPOT.name());
    }
  }
}

Python

from google.cloud import compute_v1


def is_spot_vm(project_id: str, zone: str, instance_name: str) -> bool:
    """
    Check if a given instance is Spot VM or not.
    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone you want to use. For example: "us-west3-b"
        instance_name: name of the virtual machine to check.
    Returns:
        The Spot VM status of the instance.
    """
    instance_client = compute_v1.InstancesClient()
    instance = instance_client.get(
        project=project_id, zone=zone, instance=instance_name
    )
    return (
        instance.scheduling.provisioning_model
        == compute_v1.Scheduling.ProvisioningModel.SPOT.name
    )

Gestire il prerilascio con uno script di chiusura

Quando Compute Engine prerilascia una VM spot, puoi usare un script di arresto per provare a eseguire la pulizia prima che la VM venga prerilasciata. Ad esempio, puoi interrompere delicatamente su un processo in esecuzione e copia un file di checkpoint Cloud Storage. In particolare, la durata massima del periodo di arresto è più breve per un prerilascio piuttosto che a un arresto avviato dall'utente. Per ulteriori informazioni periodo di chiusura per un avviso di prerilascio, consulta Procedura di prerilascio nella documentazione concettuale per le VM spot.

Di seguito è riportato un esempio di script di chiusura che puoi aggiungere a una eseguire una VM Spot o aggiungerla durante la creazione di VM spot. Questo script viene eseguito quando la VM inizia ad arrestarsi, prima che il normale comando kill del sistema operativo interrompa tutti i rimanenti i processi di machine learning. Dopo aver interrotto con grazia il programma desiderato, lo script esegue un caricamento parallelo di un file di checkpoint in un bucket Cloud Storage.

#!/bin/bash

MY_PROGRAM="PROGRAM_NAME" # For example, "apache2" or "nginx"
MY_USER="LOCAL_USER"
CHECKPOINT="/home/$MY_USER/checkpoint.out"
BUCKET_NAME="BUCKET_NAME" # For example, "my-checkpoint-files" (without gs://)

echo "Shutting down!  Seeing if ${MY_PROGRAM} is running."

# Find the newest copy of $MY_PROGRAM
PID="$(pgrep -n "$MY_PROGRAM")"

if [[ "$?" -ne 0 ]]; then
  echo "${MY_PROGRAM} not running, shutting down immediately."
  exit 0
fi

echo "Sending SIGINT to $PID"
kill -2 "$PID"

# Portable waitpid equivalent
while kill -0 "$PID"; do
   sleep 1
done

echo "$PID is done, copying ${CHECKPOINT} to gs://${BUCKET_NAME} as ${MY_USER}"

su "${MY_USER}" -c "gcloud storage cp $CHECKPOINT gs://${BUCKET_NAME}/"

echo "Done uploading, shutting down."

Questo script presuppone quanto segue:

  • La VM è stata creata con almeno accesso in lettura/scrittura a Cloud Storage. Per istruzioni su come creare una VM con gli ambiti appropriati, vedi il documentazione sull'autenticazione.

  • Disponi già di un bucket Cloud Storage e dell'autorizzazione per scrivere li annotino.

Per aggiungere questo script a una VM, configura lo script in modo che funzioni con un sulla tua VM e aggiungerla ai metadati della VM.

  1. Copia o scarica lo script di chiusura:

    • Copia lo script di chiusura precedente dopo aver sostituito quanto segue:

      • PROGRAM_NAME è il nome del processo o che vuoi chiudere. Ad esempio, apache2 o nginx.
      • LOCAL_USER è il nome utente che hai registrato nella macchina virtuale.
      • BUCKET_NAME è il nome del Bucket Cloud Storage in cui vuoi salvare i dati del programma di controllo. Tieni presente che il nome del bucket non inizia con gs:// in questo caso.
    • Scarica lo script di chiusura alla workstation locale e sostituisci le seguenti variabili nel file:

      • [PROGRAM_NAME] è il nome del processo o del programma che vuoi chiudere verso il basso. Ad esempio, apache2 o nginx.
      • [LOCAL_USER] è il nome utente con cui hai eseguito l'accesso alla macchina virtuale.
      • [BUCKET_NAME] è il nome del bucket Cloud Storage in cui vuoi salvare il file dei checkpoint del programma. Tieni presente che il nome del bucket iniziano con gs:// in questo caso.
  2. Aggiungi lo script di chiusura a un nuova VM o un VM esistente.

Rileva il prerilascio delle VM spot

Determinare se le VM spot sono state prerilasciate da Compute Engine utilizzando la console Google Cloud. gcloud CLI API Compute Engine.

Console

Per verificare se una VM è stata prerilasciata, controlla log delle attività di sistema.

  1. Nella console Google Cloud, vai alla pagina Log.

    Vai a Log

  2. Seleziona il progetto e fai clic su Continua.

  3. Aggiungi compute.instances.preempted a campo filtra per etichetta o ricerca testuale.

  4. Se vuoi, puoi anche inserire il nome di una VM se vuoi visualizzare le operazioni di prerilascio per una VM.

  5. Premi Invio per applicare i filtri specificati. Console Google Cloud aggiorna l'elenco dei log per mostrare solo le operazioni in cui una VM è stato prerilasciato.

  6. Seleziona un'operazione nell'elenco per visualizzare i dettagli della VM che è stato prerilasciato.

gcloud

Usa il comando gcloud compute operations list con un parametro filter per un elenco di eventi di prerilascio nel progetto.

gcloud compute operations list \
    --filter="operationType=compute.instances.preempted"

Facoltativamente, puoi utilizzare parametri di filtro aggiuntivi per ampliare l'ambito i risultati. Ad esempio, per visualizzare gli eventi di prerilascio solo per le istanze all'interno di un gruppo di istanze gestite, utilizza il comando seguente:

gcloud compute operations list \
    --filter="operationType=compute.instances.preempted AND targetLink:instances/BASE_INSTANCE_NAME"

dove BASE_INSTANCE_NAME è il nome di base specificato come prefisso per i nomi di tutte le VM in questo gruppo di istanze gestite.

L'output è simile al seguente:

NAME                  TYPE                         TARGET                                        HTTP_STATUS STATUS TIMESTAMP
systemevent-xxxxxxxx  compute.instances.preempted  us-central1-f/instances/example-instance-xxx  200         DONE   2015-04-02T12:12:10.881-07:00

Un'operazione di tipo compute.instances.preempted indica che L'istanza VM è stata prerilasciata. Puoi utilizzare lo Comando gcloud compute operations describe per ottenere ulteriori informazioni su una specifica operazione di prerilascio.

gcloud compute operations describe SYSTEM_EVENT \
    --zone=ZONE

Sostituisci quanto segue:

  • SYSTEM_EVENT: l'evento di sistema dal dell'output del comando gcloud compute operations list, ad esempio systemevent-xxxxxxxx.
  • ZONE: la zona del evento di sistema, ad esempio us-central1-f.

L'output è simile al seguente:

...
operationType: compute.instances.preempted
progress: 100
selfLink: https://compute.googleapis.com/compute/v1/projects/my-project/zones/us-central1-f/operations/systemevent-xxxxxxxx
startTime: '2015-04-02T12:12:10.881-07:00'
status: DONE
statusMessage: Instance was preempted.
...

REST

Per ottenere un elenco delle operazioni di sistema recenti per un progetto e una zona specifici, utilizza il metodo zoneOperations.get.

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/operations

Sostituisci quanto segue:

Facoltativamente, per limitare la risposta in modo da mostrare solo le operazioni di prerilascio, puoi aggiungere un filtro alla richiesta API:

operationType="compute.instances.preempted"

In alternativa, per visualizzare le operazioni di prerilascio per una VM specifica, aggiungi un parametro targetLink al filtro:

operationType="compute.instances.preempted" AND
targetLink="https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME

Sostituisci quanto segue: + PROJECT_ID: il ID progetto. + ZONE: la zona. + VM_NAME: il nome di una VM specifica in questo la zona e il progetto.

La risposta contiene un elenco di operazioni recenti. Ad esempio, un il prerilascio è simile al seguente:

{
  "kind": "compute#operation",
  "id": "15041793718812375371",
  "name": "systemevent-xxxxxxxx",
  "zone": "https://www.googleapis.com/compute/v1/projects/my-project/zones/us-central1-f",
  "operationType": "compute.instances.preempted",
  "targetLink": "https://www.googleapis.com/compute/v1/projects/my-project/zones/us-central1-f/instances/example-instance",
  "targetId": "12820389800990687210",
  "status": "DONE",
  "statusMessage": "Instance was preempted.",
  ...
}

In alternativa, puoi determinare se una VM è stata prerilasciata all'interno della VM stessa. Questa opzione è utile se vuoi gestire un arresto a causa di il prerilascio di Compute Engine è diverso da quello la chiusura in uno script di arresto. A questo scopo, è sufficiente selezionare il server di metadati per il valore preempted nella macchina virtuale metadati predefiniti.

Ad esempio, usa curl dall'interno della VM per ottenere il valore di preempted:

curl "http://metadata.google.internal/computeMetadata/v1/instance/preempted" -H "Metadata-Flavor: Google"
TRUE

Se questo valore è TRUE, la VM è stata prerilasciata da Compute Engine altrimenti è FALSE.

Se vuoi utilizzarlo al di fuori di uno script di chiusura, puoi aggiungere ?wait_for_change=true all'URL. Questa operazione esegue una richiesta GET HTTP in attesa che restituisce solo se i metadati sono stati modificati e la VM è stata prerilasciata.

curl "http://metadata.google.internal/computeMetadata/v1/instance/preempted?wait_for_change=true" -H "Metadata-Flavor: Google"
TRUE

Come testare le impostazioni di prerilascio

Puoi eseguire eventi di manutenzione simulati sulle tue VM per forzarle a farlo prerilascio. Utilizza questa funzionalità per testare il modo in cui le tue app gestiscono le VM spot. Letto Simula un evento di manutenzione dell'host per scoprire come testare gli eventi di manutenzione sulle tue istanze.

Puoi anche simulare il prerilascio di una VM arresto dell'istanza VM, che può essere utilizzato invece di simulare un evento di manutenzione, evitando così limiti di quota.

Best practice

Di seguito sono riportate alcune best practice per aiutarti a ottenere il massimo dalle VM spot.

  • Utilizzare i modelli di istanza. Invece di creare Spot VM una alla volta puoi utilizzare i modelli di istanze per creare più VM spot con le stesse proprietà. Istanza sono necessari modelli per usare i gruppi di istanze gestite. In alternativa, puoi anche Creare più VM spot utilizzando l'API per le istanze collettive.

  • Utilizza i gruppi di istanze gestite per distribuire e ricreare automaticamente a livello di regione VM spot. Utilizza MIG per rendere più flessibili e resilienti i carichi di lavoro sulle VM spot. Ad esempio, utilizza MIG regionali per distribuire VM in più zone, il che aiuta a mitigare gli errori di disponibilità delle risorse. Puoi anche usare la riparazione automatica per ricreare automaticamente le VM spot dopo che sono state prerilasciate.

  • Scegli tipi di macchine più piccoli. Le risorse per le VM spot provengono della capacità in eccesso e di backup di Google Cloud. Capacità per VM spot è spesso più facile da ottenere per i tipi di macchine più piccoli, nel senso che con meno risorse, come vCPU e memoria. Potresti trovare più capacità per le VM spot selezionando un tipo di macchina personalizzata più piccolo, è ancora più probabile per i tipi di macchina predefinita più piccoli. Per rispetto alla capacità dell'intervallo predefinito n2-standard-32 tipo di macchina personalizzata, la capacità per il tipo di macchina personalizzata n2-custom-24-96 è ma la capacità per il tipo di macchina predefinita n2-standard-16 è ancora più probabile.

  • Esegui grandi cluster di VM spot durante le ore di punta. Il carico sui data center Google Cloud varia a seconda posizione e ora del giorno, ma generalmente i valori più bassi di notte e nei fine settimana. Di conseguenza, le notti e i fine settimana sono i momenti migliori per eseguire grandi cluster di VM spot.

  • Progetta le tue applicazioni in modo che siano a tolleranza di errore e di prerilascio. È importante prepararsi ai cambiamenti schemi di prerilascio in diversi momenti. Ad esempio: Se una zona subisce un'interruzione parziale, un numero elevato di VM spot potrebbe essere prerilasciata per fare spazio alle VM standard che devono spostati nell'ambito del ripristino. In quel piccolo lasso di tempo, il tasso di prerilascio sarebbe molto diverso rispetto a qualsiasi altro giorno. Se le tue il prerilascio viene sempre effettuato in piccoli gruppi, potresti non essere pronto per un evento del genere.

  • Riprova a creare VM spot che sono state prerilasciate. Se le tue VM spot sono state prerilasciate, prova a creare nuove VM spot una o due volte prima di ricorrere alle VM standard. In base potrebbe essere una buona idea combinare VM standard e VM spot nei tuoi cluster per assicurarti che il lavoro proceda a un ritmo adeguato.

  • Utilizza gli script di chiusura. Gestisci gli avvisi di chiusura e prerilascio con un script di arresto che può salvare l'avanzamento di un job in modo che possa riprendere da dove era stato interrotto, anziché ricominciare da zero.

Passaggi successivi