Agrega memoria a una VM existente
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Actualiza una VM con memoria extendida por CPU virtual.
Explora más
Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:
Muestra de código
Go
Antes de probar esta muestra, sigue las instrucciones de configuración de Go en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente.
Si quieres obtener más información, consulta la documentación de referencia de la API de Go de Compute Engine.
Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación.
Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.
import (
"context"
"fmt"
"io"
"strings"
compute "cloud.google.com/go/compute/apiv1"
computepb "cloud.google.com/go/compute/apiv1/computepb"
"google.golang.org/protobuf/proto"
)
// modifyInstanceWithExtendedMemory sends an instance creation request
// to the Compute Engine API and waits for it to complete.
func modifyInstanceWithExtendedMemory(
w io.Writer,
projectID, zone, instanceName string,
newMemory int,
) error {
// projectID := "your_project_id"
// zone := "europe-central2-b"
// instanceName := "your_instance_name"
// newMemory := 256 // the amount of memory for the VM instance, in megabytes.
ctx := context.Background()
instancesClient, err := compute.NewInstancesRESTClient(ctx)
if err != nil {
return fmt.Errorf("NewInstancesRESTClient: %w", err)
}
defer instancesClient.Close()
reqInstance := &computepb.GetInstanceRequest{
Project: projectID,
Zone: zone,
Instance: instanceName,
}
instance, err := instancesClient.Get(ctx, reqInstance)
if err != nil {
return fmt.Errorf("unable to get instance: %w", err)
}
containsString := func(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}
if !(strings.Contains(instance.GetMachineType(), "machineTypes/n1-") ||
strings.Contains(instance.GetMachineType(), "machineTypes/n2-") ||
strings.Contains(instance.GetMachineType(), "machineTypes/n2d-")) {
return fmt.Errorf("extra memory is available only for N1, N2 and N2D CPUs")
}
// Make sure that the machine is turned off
if !containsString([]string{"TERMINATED", "STOPPED"}, instance.GetStatus()) {
reqStop := &computepb.StopInstanceRequest{
Project: projectID,
Zone: zone,
Instance: instanceName,
}
op, err := instancesClient.Stop(ctx, reqStop)
if err != nil {
return fmt.Errorf("unable to stop instance: %w", err)
}
if err = op.Wait(ctx); err != nil {
return fmt.Errorf("unable to wait for the operation: %w", err)
}
}
// Modify the machine definition, remember that extended memory
// is available only for N1, N2 and N2D CPUs
machineType := instance.GetMachineType()
start := machineType[:strings.LastIndex(machineType, "-")]
updateReq := &computepb.SetMachineTypeInstanceRequest{
Project: projectID,
Zone: zone,
Instance: instanceName,
InstancesSetMachineTypeRequestResource: &computepb.InstancesSetMachineTypeRequest{
MachineType: proto.String(fmt.Sprintf("%s-%v-ext", start, newMemory)),
},
}
op, err := instancesClient.SetMachineType(ctx, updateReq)
if err != nil {
return fmt.Errorf("unable to update 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 updated\n")
return nil
}
Python
Antes de probar esta muestra, sigue las instrucciones de configuración de Python en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente.
Si quieres obtener más información, consulta la documentación de referencia de la API de Python de Compute Engine.
Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación.
Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.
from __future__ import annotations
import sys
import time
from typing import Any
from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1
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 add_extended_memory_to_instance(
project_id: str, zone: str, instance_name: str, new_memory: int
):
"""
Modify an existing VM to use extended memory.
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.
new_memory: the amount of memory for the VM instance, in megabytes.
Returns:
Instance object.
"""
instance_client = compute_v1.InstancesClient()
instance = instance_client.get(
project=project_id, zone=zone, instance=instance_name
)
if not (
"n1-" in instance.machine_type
or "n2-" in instance.machine_type
or "n2d-" in instance.machine_type
):
raise RuntimeError("Extra memory is available only for N1, N2 and N2D CPUs.")
# Make sure that the machine is turned off
if instance.status not in (
instance.Status.TERMINATED.name,
instance.Status.STOPPED.name,
):
operation = instance_client.stop(
project=project_id, zone=zone, instance=instance_name
)
wait_for_extended_operation(operation, "instance stopping")
start = time.time()
while instance.status not in (
instance.Status.TERMINATED.name,
instance.Status.STOPPED.name,
):
# Waiting for the instance to be turned off.
instance = instance_client.get(
project=project_id, zone=zone, instance=instance_name
)
time.sleep(2)
if time.time() - start >= 300: # 5 minutes
raise TimeoutError()
# Modify the machine definition, remember that extended memory is available only for N1, N2 and N2D CPUs
start, end = instance.machine_type.rsplit("-", maxsplit=1)
instance.machine_type = start + f"-{new_memory}-ext"
# TODO: If you prefer to use the CustomMachineType helper class, uncomment this code and comment the 2 lines above
# Using CustomMachineType helper
# cmt = CustomMachineType.from_str(instance.machine_type)
# cmt.memory_mb = new_memory
# cmt.extra_memory_used = True
# instance.machine_type = str(cmt)
operation = instance_client.update(
project=project_id,
zone=zone,
instance=instance_name,
instance_resource=instance,
)
wait_for_extended_operation(operation, "instance update")
return instance_client.get(project=project_id, zone=zone, instance=instance_name)
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],[],[],[]]