Crea e utilizza VM prerilasciabili

Questa pagina spiega come creare e utilizzare un'istanza di macchina virtuale (VM) prerilasciabile. Le VM prerilasciabili sono disponibili con uno sconto fino al 60-91% rispetto al prezzo delle VM standard. Tuttavia, Compute Engine potrebbe arrestare (prerilasciare) queste VM se ha bisogno di recuperare risorse per altre attività. Le VM prerilasciabili si arrestano sempre dopo 24 ore. Le VM prerilasciabili sono consigliate solo per le applicazioni a tolleranza di errore in grado di sopportare il prerilascio delle VM. Assicurati che la tua applicazione possa gestire i prerilascio prima di decidere di creare una VM prerilasciabile. Per comprendere i rischi e il valore delle VM prerilasciabili, leggi la documentazione sulle istanze VM prerilasciabili.

Prima di iniziare

  • Leggi la documentazione sulle istanze VM prerilasciabili.
  • Se non l'hai già fatto, configura l'autenticazione. L'autenticazione è il processo mediante il quale viene verificata l'identità dell'utente per ottenere l'accesso ai servizi e alle API Google Cloud. Per eseguire codice o esempi da un ambiente di sviluppo locale, puoi eseguire l'autenticazione in 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. Installa Google Cloud CLI, quindi initialize eseguendo questo comando:

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

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

      1. Installa Google Cloud CLI.
      2. Per initialize gcloud CLI, esegui questo comando:

        gcloud init
      3. Crea credenziali di autenticazione locali per il tuo Account Google:

        gcloud auth application-default login

      Per maggiori informazioni, consulta Set up authentication for a local development environment.

      Java

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

      1. Installa Google Cloud CLI.
      2. Per initialize gcloud CLI, esegui questo comando:

        gcloud init
      3. Crea credenziali di autenticazione locali per il tuo Account Google:

        gcloud auth application-default login

      Per maggiori informazioni, consulta Set up authentication for a local development environment.

      Node.js

      Per utilizzare gli Node.js esempi in questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Installa Google Cloud CLI.
      2. Per initialize gcloud CLI, esegui questo comando:

        gcloud init
      3. Crea credenziali di autenticazione locali per il tuo Account Google:

        gcloud auth application-default login

      Per maggiori informazioni, consulta Set up authentication for a local development environment.

      Python

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

      1. Installa Google Cloud CLI.
      2. Per initialize gcloud CLI, esegui questo comando:

        gcloud init
      3. Crea credenziali di autenticazione locali per il tuo Account Google:

        gcloud auth application-default login

      Per maggiori informazioni, consulta 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.

        Installa Google Cloud CLI, quindi initialize eseguendo questo comando:

        gcloud init

      Per maggiori informazioni, consulta Autenticazione per l'utilizzo di REST nella documentazione sull'autenticazione di Google Cloud.

Crea una VM prerilasciabile

Crea una VM prerilasciabile usando gcloud CLI o l'API Compute Engine. Per utilizzare la console Google Cloud, crea una VM spot.

gcloud

Con gcloud compute, utilizza lo stesso comando instances create che useresti per creare una VM normale, ma aggiungi il flag --preemptible.

gcloud compute instances create [VM_NAME] --preemptible

dove [VM_NAME] è il nome della VM.

Go

import (
	"context"
	"fmt"
	"io"

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

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

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

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

	// List of public operating system (OS) images:
	// https://cloud.google.com/compute/docs/images/os-details.
	newestDebianReq := &computepb.GetFromFamilyImageRequest{
		Project: "debian-cloud",
		Family:  "debian-11",
	}
	newestDebian, err := imagesClient.GetFromFamily(ctx, newestDebianReq)
	if err != nil {
		return fmt.Errorf("unable to get image from family: %w", err)
	}

	inst := &computepb.Instance{
		Name: proto.String(instanceName),
		Disks: []*computepb.AttachedDisk{
			{
				InitializeParams: &computepb.AttachedDiskInitializeParams{
					DiskSizeGb:  proto.Int64(10),
					SourceImage: newestDebian.SelfLink,
					DiskType:    proto.String(fmt.Sprintf("zones/%s/diskTypes/pd-standard", zone)),
				},
				AutoDelete: proto.Bool(true),
				Boot:       proto.Bool(true),
			},
		},
		Scheduling: &computepb.Scheduling{
			// Set the preemptible setting
			Preemptible: proto.Bool(true),
		},
		MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/n1-standard-1", zone)),
		NetworkInterfaces: []*computepb.NetworkInterface{
			{
				Name: proto.String("global/networks/default"),
			},
		},
	}

	req := &computepb.InsertInstanceRequest{
		Project:          projectID,
		Zone:             zone,
		InstanceResource: inst,
	}

	op, err := instancesClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create instance: %w", err)
	}

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

	fmt.Fprintf(w, "Instance created\n")

	return nil
}

Java


import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
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.Operation;
import com.google.cloud.compute.v1.Scheduling;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreatePreemptibleInstance {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // projectId: 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”
    // instanceName: name of the new virtual machine.
    String projectId = "your-project-id-or-number";
    String zone = "zone-name";
    String instanceName = "instance-name";

    createPremptibleInstance(projectId, zone, instanceName);
  }

  // Send an instance creation request with preemptible settings to the Compute Engine API
  // and wait for it to complete.
  public static void createPremptibleInstance(String projectId, String zone, String instanceName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    String machineType = String.format("zones/%s/machineTypes/e2-small", zone);
    String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
    long diskSizeGb = 10L;
    String networkName = "default";

    try (InstancesClient instancesClient = InstancesClient.create()) {

      AttachedDisk disk =
          AttachedDisk.newBuilder()
              .setBoot(true)
              .setAutoDelete(true)
              .setType(AttachedDisk.Type.PERSISTENT.toString())
              .setInitializeParams(
                  // Describe the size and source image of the boot disk to attach to the instance.
                  AttachedDiskInitializeParams.newBuilder()
                      .setSourceImage(sourceImage)
                      .setDiskSizeGb(diskSizeGb)
                      .build())
              .build();

      // Use the default VPC network.
      NetworkInterface networkInterface = NetworkInterface.newBuilder()
          .setName(networkName)
          .build();

      // Collect information into the Instance object.
      Instance instanceResource =
          Instance.newBuilder()
              .setName(instanceName)
              .setMachineType(machineType)
              .addDisks(disk)
              .addNetworkInterfaces(networkInterface)
              // Set the preemptible setting.
              .setScheduling(Scheduling.newBuilder()
                  .setPreemptible(true)
                  .build())
              .build();

      System.out.printf("Creating instance: %s at %s %n", instanceName, zone);

      // Prepare the request to insert an instance.
      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setInstanceResource(instanceResource)
          .build();

      // Wait for the create operation to complete.
      Operation response = instancesClient.insertAsync(insertInstanceRequest)
          .get(3, TimeUnit.MINUTES);
      ;

      if (response.hasError()) {
        System.out.println("Instance creation failed ! ! " + response);
        return;
      }

      System.out.printf("Instance created : %s\n", instanceName);
      System.out.println("Operation Status: " + response.getStatus());
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'europe-central2-b';
// const instanceName = 'YOUR_INSTANCE_NAME';

const compute = require('@google-cloud/compute');

async function createPreemptible() {
  const instancesClient = new compute.InstancesClient();

  const [response] = await instancesClient.insert({
    instanceResource: {
      name: instanceName,
      disks: [
        {
          initializeParams: {
            diskSizeGb: '64',
            sourceImage:
              'projects/debian-cloud/global/images/family/debian-11/',
          },
          autoDelete: true,
          boot: true,
        },
      ],
      scheduling: {
        // Set the preemptible setting
        preemptible: true,
      },
      machineType: `zones/${zone}/machineTypes/e2-small`,
      networkInterfaces: [
        {
          name: 'global/networks/default',
        },
      ],
    },
    project: projectId,
    zone,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

  // Wait for the create operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log('Instance created.');
}

createPreemptible();

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_preemptible_instance(
    project_id: str, zone: str, instance_name: str
) -> compute_v1.Instance:
    """
    Create a new preemptible 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, preemptible=True)
    return instance

REST

Nell'API, crea una normale richiesta per creare una VM, ma includi la proprietà preemptible in scheduling e impostala su true. Ad esempio:

POST https://compute.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/instances

{
  'machineType': 'zones/[ZONE]/machineTypes/[MACHINE_TYPE]',
  'name': '[INSTANCE_NAME]',
  'scheduling':
  {
    'preemptible': true
  },
  ...
}

Quote di CPU prerilasciabili

Le VM prerilasciabili richiedono quote per le CPU disponibili come le VM standard. Per evitare che le VM prerilasciabili consumino le quote per le CPU delle VM standard, puoi richiedere una quota speciale di "CPU prerilasciabile". Quando Compute Engine ti concede la quota di CPU prerilasciabile in quella regione, tutte le VM prerilasciabili verranno conteggiate nella quota e tutte le VM standard continueranno a essere conteggiate nella quota di CPU standard.

Nelle regioni in cui non disponi di questa quota, puoi utilizzare la quota CPU standard per avviare le VM prerilasciabili. Hai anche bisogno di una quota IP e disco sufficiente, come di consueto. La quota di CPU prerilasciabili non è visibile nelle pagine delle quote di gcloud CLI o Google Cloud Console, a meno che Compute Engine non abbia concesso la quota.

Per saperne di più sulle quote, visita la pagina Quote delle risorse.

Avvia una VM prerilasciata

Come per qualsiasi altra VM, se una VM prerilasciabile viene arrestata o prerilasciata, puoi riavviarla e riportarla allo stato RUNNING. L'avvio di una VM prerilasciabile reimposta il contatore delle 24 ore, ma poiché è ancora una VM prerilasciabile, Compute Engine può prerilasciare prima di 24 ore. Non è possibile convertire una VM prerilasciabile in una VM standard mentre è in esecuzione.

Se Compute Engine interrompe una VM prerilasciabile in un gruppo di istanze gestite con scalabilità automatica o in un cluster Google Kubernetes Engine (GKE), il gruppo riavvia la VM quando le risorse diventano nuovamente disponibili.

Gestire il prerilascio con uno script di chiusura

Quando Compute Engine prerilascia una VM, puoi utilizzare uno script di arresto per provare a eseguire azioni di pulizia prima che la VM venga prerilasciata. Ad esempio, puoi arrestare rapidamente un processo in esecuzione e copiare un file di checkpoint in Cloud Storage. In particolare, la durata massima del periodo di chiusura è più breve per un avviso di prerilascio rispetto a un arresto avviato dall'utente. Per ulteriori informazioni sul periodo di arresto per un avviso di prerilascio, consulta Procedura di prerilascio nella documentazione concettuale.

Di seguito è riportato uno script di chiusura che puoi aggiungere a una VM prerilasciabile in esecuzione o a una nuova VM prerilasciabile quando la crei. Questo script viene eseguito all'avvio dell'arresto della VM, prima che il normale comando kill del sistema operativo arresti tutti i processi rimanenti. Dopo aver interrotto correttamente 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_USERNAME]"
CHECKPOINT="/home/$MY_USER/checkpoint.out"
GSUTIL_OPTS="-m -o GSUtil:parallel_composite_upload_threshold=32M"
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 "gsutil $GSUTIL_OPTS cp $CHECKPOINT gs://${BUCKET_NAME}/"

echo "Done uploading, shutting down."

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

  1. Copia o scarica lo script di arresto sulla workstation locale.
  2. Apri il file da modificare e cambia le seguenti variabili:
    • [PROGRAM_NAME] è il nome del processo o del programma che vuoi arrestare. 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 del checkpoint del programma. Tieni presente che in questo caso il nome del bucket non inizia con gs://.
  3. Salva le modifiche.
  4. Aggiungi lo script di chiusura a una nuova VM o a una VM esistente.

Questo script presuppone quanto segue:

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

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

Identifica le VM prerilasciabili

Per verificare se una VM è prerilasciabile, segui i passaggi per identificare il modello di provisioning e l'azione di terminazione di una VM.

Determina se una VM è stata prerilasciata

Determina se una VM è stata prerilasciata con la console Google Cloud, gcloud CLI o l'API.

Console

Puoi verificare se una VM è stata prerilasciata controllando i 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 al campo di filtro per etichetta o ricerca testuale.

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

  5. Premi Invio per applicare i filtri specificati. La console Google Cloud aggiorna l'elenco dei log per mostrare solo le operazioni in cui una VM è stata prerilasciata.

  6. Seleziona un'operazione nell'elenco per visualizzare i dettagli della VM prerilasciata.

gcloud


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

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

Puoi utilizzare il parametro di filtro per definire ulteriormente l'ambito dei risultati. Ad esempio, per visualizzare gli eventi di prerilascio solo per le VM all'interno di un gruppo di istanze gestite:

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

gcloud restituisce una risposta simile a:

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

Un tipo di operazione compute.instances.preempted indica che la VM è stata prerilasciata. Puoi utilizzare il comando operations describe per ottenere ulteriori informazioni su un'operazione di prerilascio specifica.

gcloud compute operations describe \
    systemevent-xxxxxxxx

gcloud restituisce una risposta simile a:

...
operationType: compute.instances.preempted
progress: 100
selfLink: https://compute.googleapis.com/compute/v1/projects/[PROJECT_ID]/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, invia una richiesta GET all'URI delle operazioni di zona.

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

La risposta contiene un elenco di operazioni recenti.

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

Per definire l'ambito della risposta in modo che mostri solo le operazioni di prerilascio, puoi aggiungere un filtro alla richiesta API: operationType="compute.instances.preempted". 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]".

In alternativa, puoi determinare se una VM è stata prerilasciata all'interno della VM stessa. Questo è utile se vuoi gestire un arresto dovuto a un prerilascio di Compute Engine in modo diverso rispetto a un normale arresto in uno script di arresto. Per farlo, è sufficiente verificare se sul server dei metadati è presente il valore preempted nei metadati predefiniti dell'istanza della VM.

Ad esempio, utilizza 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. Questo esegue una richiesta GET HTTP inutilizzata, che restituisce solo quando 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

Testa le impostazioni di prerilascio

Puoi eseguire eventi di manutenzione simulati sulle VM per prerilasciarli. Usa questa funzionalità per verificare in che modo le tue app gestiscono le VM prerilasciabili. Leggi la pagina relativa al test dei criteri di disponibilità per scoprire come testare gli eventi di manutenzione sulle VM.

Puoi anche simulare il prerilascio di una VM arrestandola. Questa operazione può essere utilizzata invece di simulare un evento di manutenzione ed evita i limiti di quota.

Best practice

Ecco alcune best practice per aiutarti a ottenere il massimo dalle istanze VM prerilasciabili.

Utilizzo dell'API per istanze collettive

Anziché creare singole VM, puoi utilizzare l'API per istanze in blocco.

Scegli forme di macchina più piccole

Le risorse per le VM prerilasciabili provengono dalla capacità in eccesso e di backup di Google Cloud. La capacità è spesso più facile da ottenere per i tipi di macchine più piccoli, ovvero tipi di macchina con meno risorse come vCPU e memoria. Se selezioni un tipo di macchina personalizzata più piccolo, la capacità delle VM prerilasciabili potrebbe essere maggiore, ma la capacità è ancor più probabile per i tipi di macchine predefinite più piccoli. Ad esempio, rispetto alla capacità per il tipo di macchina predefinita n2-standard-32, la capacità per il tipo di macchina personalizzata n2-custom-24-96 è più probabile, ma è ancora più probabile per il tipo di macchina predefinita n2-standard-16.

Esegui cluster di VM prerilasciabile di grandi dimensioni durante le ore di punta

Il carico nei data center di Google Cloud varia a seconda della località e dell'ora del giorno, ma in genere è più basso di notte e nei fine settimana. Pertanto, la notte e i fine settimana sono i momenti migliori per eseguire grandi cluster di VM prerilasciabile.

Progetta le tue applicazioni in modo che siano a tolleranza di errore e di prerilascio

È importante prepararsi al fatto che si stanno verificando cambiamenti nei modelli di prerilascio in diversi momenti. Ad esempio, se una zona subisce un'interruzione parziale, un numero elevato di VM prerilasciabili potrebbe essere prerilasciato per fare spazio alle VM standard che devono essere spostate nell'ambito del ripristino. In un lasso di tempo così breve, il tasso di prerilascio avrebbe avuto un aspetto molto diverso rispetto a quello di qualsiasi altro giorno. Se la tua applicazione presuppone che i prerilascio vengano sempre eseguiti in piccoli gruppi, potresti non essere pronto per un evento di questo tipo. Puoi testare il comportamento della tua applicazione in un evento di prerilascio, arrestando l'istanza VM.

Riprova a creare VM prerilasciate

Se la tua istanza VM è stata prerilasciata, prova a creare nuove VM prerilasciabili una o due volte prima di utilizzare le VM standard. A seconda dei requisiti, potrebbe essere una buona idea combinare VM standard e prerilasciabili nei tuoi cluster per assicurarti che il lavoro proceda a un ritmo adeguato.

Utilizzare gli script di chiusura

Gestisci gli avvisi di arresto e prerilascio con uno script di arresto che può salvare i progressi di un job in modo che possa riprendere da dove era stato interrotto, anziché ricominciare da zero.

Che cosa succede dopo?