Menangguhkan atau melanjutkan VM


Dokumen ini menjelaskan cara menangguhkan atau melanjutkan instance virtual machine (VM).

Jika ingin mempertahankan instance VM tetapi tidak ingin dikenai biaya saat tidak digunakan, Anda dapat menangguhkan VM tersebut. Saat Anda menangguhkan VM, Google akan mempertahankan VM tersebut di project Anda dan memindahkan konten memori VM ke penyimpanan. Saat VM ditangguhkan, Google hanya mengenakan biaya untuk penyimpanan yang digunakan untuk mempertahankan memori VM. Atribut seperti alamat IP statis tetap ada sehingga fungsi jaringan akan berfungsi seperti yang diharapkan saat Anda melanjutkan VM. Setelah melanjutkan, Google akan memindahkan kembali memori VM dari penyimpanan ke instance, dan mulai menagih Anda untuk instance VM yang sedang berjalan.

Menangguhkan instance ideal untuk:

  • Lingkungan pengembangan dan pengujian yang tidak sepenuhnya dimanfaatkan selama periode nonaktif, seperti malam hari atau akhir pekan, untuk menghemat biaya atau melakukan inisialisasi yang lebih cepat daripada membuat instance VM baru.
  • Aplikasi yang memerlukan inisialisasi dalam waktu lama setelah instance selesai booting, tetapi sebelum aplikasi siap melayani permintaan pertamanya, seperti workstation developer virtual atau aplikasi Java yang kompleks.

Cara kerja penangguhan

Jika instance ditangguhkan, sinyal penangguhan ACPI S3 akan dikirimkan ke sistem operasi instance. Menangguhkan instance sama dengan menutup penutup laptop Anda, yang menempatkan instance ke dalam status SUSPENDED.

Menangguhkan instance berbeda dengan menghentikan instance dalam cara berikut:

Semua resource yang terpasang ke instance tersebut akan tetap terhubung ke instance tersebut dan akan dikenai biaya, termasuk persistent disk dan alamat IP eksternal statis atau yang dicadangkan. Semua resource ini dikenai biaya sesuai dengan lembar harga, meskipun jika sebuah instance sedang ditangguhkan.

Anda tidak dapat menangguhkan instance menggunakan proses standar yang terintegrasi ke dalam lingkungan tamu. Perintah, seperti perintah systemctl suspend di Ubuntu 16.04 dan yang lebih baru, tidak tersedia. Anda hanya dapat menggunakan Google Cloud CLI atau REST untuk menangguhkan instance.

Jika Anda tidak ingin memulihkan memori dan status perangkat instance saat Anda melanjutkan instance tersebut nanti, Anda dapat menghentikan instance tersebut, yang tidak akan menimbulkan biaya penyimpanan tambahan.

Sebelum memulai

  • Siapkan autentikasi, jika Anda belum melakukannya. Autentikasi adalah proses verifikasi identitas Anda untuk akses ke layanan dan API Google Cloud. Untuk menjalankan kode atau contoh dari lingkungan pengembangan lokal, Anda dapat melakukan autentikasi ke Compute Engine sebagai berikut.

    Pilih tab untuk melihat bagaimana Anda berencana menggunakan contoh di halaman ini:

    Konsol

    Saat menggunakan Konsol Google Cloud untuk mengakses API dan layanan Google Cloud, Anda tidak perlu menyiapkan autentikasi.

    gcloud

    1. Instal Google Cloud CLI, lalu initialize dengan menjalankan perintah berikut:

      gcloud init
    2. Menetapkan region dan zona default.

    Go

    Untuk menggunakan contoh Go di halaman ini dari lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

    1. Menginstal Google Cloud CLI.
    2. Untuk initialize gcloud CLI, jalankan perintah berikut:

      gcloud init
    3. Buat kredensial autentikasi lokal untuk Akun Google Anda:

      gcloud auth application-default login

    Untuk informasi selengkapnya, lihat Siapkan autentikasi untuk lingkungan pengembangan lokal.

    Java

    Untuk menggunakan contoh Java di halaman ini dari lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

    1. Menginstal Google Cloud CLI.
    2. Untuk initialize gcloud CLI, jalankan perintah berikut:

      gcloud init
    3. Buat kredensial autentikasi lokal untuk Akun Google Anda:

      gcloud auth application-default login

    Untuk informasi selengkapnya, lihat Siapkan autentikasi untuk lingkungan pengembangan lokal.

    Node.js

    Untuk menggunakan contoh Node.js di halaman ini dari lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

    1. Menginstal Google Cloud CLI.
    2. Untuk initialize gcloud CLI, jalankan perintah berikut:

      gcloud init
    3. Buat kredensial autentikasi lokal untuk Akun Google Anda:

      gcloud auth application-default login

    Untuk informasi selengkapnya, lihat Siapkan autentikasi untuk lingkungan pengembangan lokal.

    PHP

    Untuk menggunakan contoh PHP di halaman ini dari lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

    1. Menginstal Google Cloud CLI.
    2. Untuk initialize gcloud CLI, jalankan perintah berikut:

      gcloud init
    3. Buat kredensial autentikasi lokal untuk Akun Google Anda:

      gcloud auth application-default login

    Untuk informasi selengkapnya, lihat Siapkan autentikasi untuk lingkungan pengembangan lokal.

    Python

    Untuk menggunakan contoh Python di halaman ini dari lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

    1. Menginstal Google Cloud CLI.
    2. Untuk initialize gcloud CLI, jalankan perintah berikut:

      gcloud init
    3. Buat kredensial autentikasi lokal untuk Akun Google Anda:

      gcloud auth application-default login

    Untuk informasi selengkapnya, lihat Siapkan autentikasi untuk lingkungan pengembangan lokal.

    REST

    Untuk menggunakan contoh REST API di halaman ini dalam lingkungan pengembangan lokal, gunakan kredensial yang Anda berikan ke gcloud CLI.

      Instal Google Cloud CLI, lalu initialize dengan menjalankan perintah berikut:

      gcloud init

Batasan

Batasan berikut berlaku pada rilis ini:

  • Anda tidak dapat menangguhkan instance yang menggunakan GPU.
  • Anda tidak dapat menangguhkan instance menggunakan proses standar yang terintegrasi ke dalam lingkungan tamu. Perintah, seperti perintah systemctl suspend di Ubuntu 16.04 dan yang lebih baru, tidak tersedia. Sinyal dalam tamu akan diabaikan.
  • Anda hanya dapat menangguhkan instance hingga 60 hari sebelum VM dihentikan secara otomatis.
  • Anda tidak dapat menangguhkan instance yang memiliki memori lebih dari 208 GB.
  • Anda dapat menangguhkan preemptible instance, tetapi preemptible instance mungkin akan dihentikan sebelum berhasil ditangguhkan.
  • Anda tidak dapat menangguhkan Confidential VM.
  • Anda tidak dapat menangguhkan VM yang memiliki disk yang dilindungi CSEK.

SSD lokal

Biasanya, menangguhkan instance VM yang menggunakan SSD Lokal akan menghapus semua data di drive SSD Lokal - perilaku yang sama seperti menghentikan instance.

Lihat Dokumentasi SSD lokal untuk detail selengkapnya.

Preemptible VM

Anda dapat menangguhkan preemptible VM, tetapi jika preemption (bukan peringatan awal yang mendahului preemption) terjadi sebelum operasi penangguhan selesai, penangguhan akan keluar dan instance akan di-preempt.

Kompatibilitas OS

Sebagian besar sistem operasi (OS) yang ditawarkan di Compute Engine mendukung fungsi penangguhan dan pelanjutan, tetapi ada beberapa OS yang tidak. Tinjau halaman detail OS untuk mengetahui daftar lengkapnya.

Harga

Saat menangguhkan instance, Anda akan dikenai biaya untuk:

  • Memori instance (lihat harga untuk instance Ditangguhkan VM).
  • Setiap penggunaan persistent disk untuk boot disk dan disk tambahan yang terpasang ke instance (lihat Harga persistent disk).
  • Semua IP statis yang terpasang pada instance.
  • Menangguhkan VM dapat menghemat biaya lisensi software Anda. Misalnya, jika Anda menangguhkan VM Windows, Anda tidak dikenai biaya lisensi Windows. Biaya lisensi untuk image lain mungkin memiliki persyaratan dan ketentuan yang berbeda, dan dapat menyebabkan tagihan bahkan saat ditangguhkan.

Menangguhkan instance

Untuk menangguhkan instance, gunakan Google Cloud Console, gcloud CLI, API, atau Library Klien Cloud.

Anda tidak dapat menangguhkan instance menggunakan proses standar yang terintegrasi ke dalam lingkungan tamu. Anda dapat menggunakan Google Cloud Console, Google Cloud CLI, atau API untuk menangguhkan instance.

Operasi penangguhan dapat gagal jika dipicu terlalu cepat setelah instance dimulai. Instance harus dimulai sepenuhnya (termasuk proses seperti Agen Tamu) agar operasi penangguhan berhasil.

Konsol

  1. Di Konsol Google Cloud, buka halaman VM instances.

    Buka halaman instance VM

  2. Pilih satu atau beberapa instance untuk ditangguhkan.

  3. Klik Tangguhkan.

  4. Saat diminta, jika Anda ingin menghapus data SSD lokal, pilih Hapus konten SSD. Saat instance Anda dilanjutkan, semua data SSD lokal pada instance tersebut akan dihapus.

gcloud

Untuk menangguhkan instance di Google Cloud CLI:

 gcloud compute instances suspend VM_NAME

Setelah Anda membuat permintaan untuk menangguhkan instance, Compute Engine perlu waktu beberapa saat untuk menyimpan semua data yang diperlukan untuk instance tersebut. Selama jangka waktu ini, Anda akan terus dikenakan biaya untuk instance tersebut selama instance tersebut masih berjalan.

Instance yang ditangguhkan ditandai dengan status SUSPENDED. Periksa status instance dengan membuat permintaan describe:

gcloud compute instances describe VM_NAME

Untuk menangguhkan instance dengan data SSD lokal, Anda harus memberikan flag --discard-local-ssd:

gcloud compute instances suspend VM_NAME --discard-local-ssd

Menggunakan --discard-local-ssd atau --discard-local-ssd=True akan menghapus konten SSD Lokal. Compute Engine --discard-local-ssd=False saat ini berada dalam Pratinjau Publik. Menggunakan tanda ini akan menyimpan konten hingga 16 disk SSD Lokal selama Penangguhan. Lihat Dokumentasi SSD lokal untuk detail selengkapnya.

Go

import (
	"context"
	"fmt"
	"io"

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

// suspendInstance suspends a running Google Compute Engine instance.
func suspendInstance(w io.Writer, projectID, zone, instanceName string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"

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

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

	op, err := instancesClient.Suspend(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to suspend 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 suspended\n")

	return nil
}

Java


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

public class SuspendInstance {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // project: project ID or project number of the Cloud project your instance belongs to.
    // zone: name of the zone your instance belongs to.
    // instanceName: name of the instance your want to suspend.

    String project = "your-project-id";
    String zone = "zone-name";
    String instanceName = "instance-name";

    suspendInstance(project, zone, instanceName);
  }

  // Suspend a running Google Compute Engine instance.
  // For limitations and compatibility on which instances can be suspended,
  // see: https://cloud.google.com/compute/docs/instances/suspend-resume-instance#limitations
  public static void suspendInstance(String project, String zone, String instanceName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Instantiates a client.
    try (InstancesClient instancesClient = InstancesClient.create()) {

      Operation operation = instancesClient.suspendAsync(project, zone, instanceName)
          .get(300, TimeUnit.SECONDS);

      if (operation.hasError() || !instancesClient.get(project, zone, instanceName).getStatus()
          .equalsIgnoreCase(Status.SUSPENDED.toString())) {
        System.out.println("Cannot suspend instance. Try again!");
        return;
      }

      System.out.printf("Instance suspended successfully ! %s", instanceName);
    }
  }
}

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');

// Suspends a running Google Compute Engine instance.
async function suspendInstance() {
  const instancesClient = new compute.InstancesClient();

  const [response] = await instancesClient.suspend({
    project: projectId,
    zone,
    instance: instanceName,
  });
  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 suspended.');
}

suspendInstance();

PHP

use Google\Cloud\Compute\V1\Client\InstancesClient;
use Google\Cloud\Compute\V1\SuspendInstanceRequest;

/**
 * Suspend a running Google Compute Engine instance.
 *
 * @param string $projectId Project ID or project number of the Cloud project your instance belongs to.
 * @param string $zone Name of the zone your instance belongs to.
 * @param string $instanceName Name of the instance you want to suspend.
  *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 * @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
 */
function suspend_instance(
    string $projectId,
    string $zone,
    string $instanceName
) {
    // Suspend the running Compute Engine instance using InstancesClient.
    $instancesClient = new InstancesClient();
    $request = (new SuspendInstanceRequest())
        ->setInstance($instanceName)
        ->setProject($projectId)
        ->setZone($zone);
    $operation = $instancesClient->suspend($request);

    // Wait for the operation to complete.
    $operation->pollUntilComplete();
    if ($operation->operationSucceeded()) {
        printf('Instance %s suspended successfully' . PHP_EOL, $instanceName);
    } else {
        $error = $operation->getError();
        printf('Failed to suspend instance: %s' . PHP_EOL, $error?->getMessage());
    }
}

Python

from __future__ import annotations

import sys
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 suspend_instance(project_id: str, zone: str, instance_name: str) -> None:
    """
    Suspend a running Google Compute Engine instance.
    Args:
        project_id: project ID or project number of the Cloud project your instance belongs to.
        zone: name of the zone your instance belongs to.
        instance_name: name of the instance you want to suspend.
    """
    instance_client = compute_v1.InstancesClient()

    operation = instance_client.suspend(
        project=project_id, zone=zone, instance=instance_name
    )

    wait_for_extended_operation(operation, "suspend instance")

REST

Di API, buat permintaan menggunakan metode instances.suspend:

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

Ganti kode berikut:

  • PROJECT_ID: the project ID
  • ZONE: zona VM
  • VM_NAME: instance yang ingin ditangguhkan

Setelah Anda membuat permintaan untuk menangguhkan instance, Compute Engine perlu waktu beberapa saat untuk menyimpan semua data yang diperlukan untuk instance tersebut. Selama jangka waktu ini, Anda akan terus dikenakan biaya untuk instance tersebut selama instance tersebut masih berjalan.

Compute Engine menandai instance yang ditangguhkan dengan status SUSPENDED. Periksa status instance dengan membuat permintaan GET:

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

Status instance terlihat di kolom status. Contoh:

...
"zone": "https://content.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a",
"status": "SUSPENDED",
"name": "example-vm",
...

Untuk menangguhkan instance dengan lebih dari 16 disk SSD lokal, Anda harus menghapus data SSD lokal dengan memberikan parameter kueri discardLocalSsd seperti berikut:

https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/suspend?discardLocalSsd=true

Untuk informasi selengkapnya, lihat Dokumentasi SSD lokal.

Melanjutkan instance yang ditangguhkan

Anda hanya dapat melanjutkan instance jika memiliki kapasitas yang memadai di zona tempat VM berada. Di sebagian besar kasus, hal ini tidak menjadi masalah, tetapi jika Anda mengalami masalah kapasitas, coba lagi permintaan pelanjutan Anda di lain waktu.

Untuk melanjutkan instance yang ditangguhkan, gunakan Google Cloud Console, gcloud CLI, API, atau Library Klien Cloud.

Konsol

  1. Di Konsol Google Cloud, buka halaman VM instances.

    Buka halaman instance VM

  2. Pilih satu atau beberapa instance untuk dilanjutkan.

  3. Klik Mulai/Lanjutkan.

gcloud

Untuk melanjutkan instance di Google Cloud CLI:

 gcloud compute instances resume VM_NAME

Setelah Anda membuat permintaan untuk melanjutkan instance, perlu waktu beberapa saat agar Compute Engine memulihkan semua data yang diperlukan untuk instance tersebut. Selama jangka waktu ini, Anda akan terus dikenakan biaya untuk instance tersebut saat instance dilanjutkan.

Instance dilanjutkan jika ditandai sebagai RUNNING. Periksa status instance dengan membuat permintaan deskripsi:

gcloud compute instances describe VM_NAME

Go

import (
	"context"
	"fmt"
	"io"

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

// resumeInstance resumes a suspended Google Compute Engine instance
// (with unencrypted disks).
func resumeInstance(w io.Writer, projectID, zone, instanceName string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"

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

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

	instance, err := instancesClient.Get(ctx, getInstanceReq)
	if err != nil {
		return fmt.Errorf("unable to get instance: %w", err)
	}

	if instance.GetStatus() != "SUSPENDED" {
		return fmt.Errorf(
			"only suspended instances can be resumed, instance %s is in %s state",
			instanceName,
			instance.GetStatus(),
		)
	}

	resumeInstanceReq := &computepb.ResumeInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	}

	op, err := instancesClient.Resume(ctx, resumeInstanceReq)
	if err != nil {
		return fmt.Errorf("unable to resume 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 resumed\n")

	return nil
}

Java


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

public class ResumeInstance {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // project: project ID or project number of the Cloud project your instance belongs to.
    // zone: name of the zone your instance belongs to.
    // instanceName: name of the instance your want to resume.

    String project = "your-project-id";
    String zone = "zone-name";
    String instanceName = "instance-name";

    resumeInstance(project, zone, instanceName);
  }

  // Resume a suspended Google Compute Engine instance (with unencrypted disks).
  // Instance state changes to RUNNING, if successfully resumed.
  public static void resumeInstance(String project, String zone, String instanceName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Instantiates a client.
    try (InstancesClient instancesClient = InstancesClient.create()) {

      String currentInstanceState = instancesClient.get(project, zone, instanceName).getStatus();

      // Check if the instance is currently suspended.
      if (!currentInstanceState.equalsIgnoreCase(Status.SUSPENDED.toString())) {
        throw new RuntimeException(
            String.format("Only suspended instances can be resumed. Instance %s is in %s state.",
                instanceName, currentInstanceState));
      }

      Operation operation = instancesClient.resumeAsync(project, zone, instanceName)
          .get(300, TimeUnit.SECONDS);

      if (operation.hasError() || !instancesClient.get(project, zone, instanceName).getStatus()
          .equalsIgnoreCase(
              Status.RUNNING.toString())) {
        System.out.println("Cannot resume instance. Try again!");
        return;
      }

      System.out.printf("Instance resumed successfully ! %s", instanceName);
    }
  }
}

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');

// Resumes a suspended Google Compute Engine instance (with unencrypted disks).
async function resumeInstance() {
  const instancesClient = new compute.InstancesClient();

  const [instance] = await instancesClient.get({
    project: projectId,
    zone,
    instance: instanceName,
  });

  if (instance.status !== 'SUSPENDED') {
    throw new Error(
      'Only suspended instances can be resumed.' +
        `Instance ${instanceName} is in ${instance.status} state.`
    );
  }

  const [response] = await instancesClient.resume({
    project: projectId,
    zone,
    instance: instanceName,
  });
  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 resumed.');
}

resumeInstance();

PHP

use Google\Cloud\Compute\V1\Client\InstancesClient;
use Google\Cloud\Compute\V1\ResumeInstanceRequest;

/**
 * Resume a suspended Google Compute Engine instance (with unencrypted disks).
 *
 * @param string $projectId Project ID or project number of the Cloud project your instance belongs to.
 * @param string $zone Name of the zone your instance belongs to.
 * @param string $instanceName Name of the instance you want to resume.
  *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 * @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
 */
function resume_instance(
    string $projectId,
    string $zone,
    string $instanceName
) {
    // Resume the suspended Compute Engine instance using InstancesClient.
    $instancesClient = new InstancesClient();
    $request = (new ResumeInstanceRequest())
        ->setInstance($instanceName)
        ->setProject($projectId)
        ->setZone($zone);
    $operation = $instancesClient->resume($request);

    // Wait for the operation to complete.
    $operation->pollUntilComplete();
    if ($operation->operationSucceeded()) {
        printf('Instance %s resumed successfully' . PHP_EOL, $instanceName);
    } else {
        $error = $operation->getError();
        printf('Failed to resume instance: %s' . PHP_EOL, $error?->getMessage());
    }
}

Python

from __future__ import annotations

import sys
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 resume_instance(project_id: str, zone: str, instance_name: str) -> None:
    """
    Resume a suspended Google Compute Engine instance (with unencrypted disks).
    Args:
        project_id: project ID or project number of the Cloud project your instance belongs to.
        zone: name of the zone your instance belongs to.
        instance_name: name of the instance you want to resume.
    """
    instance_client = compute_v1.InstancesClient()

    instance = instance_client.get(
        project=project_id, zone=zone, instance=instance_name
    )
    if instance.status != compute_v1.Instance.Status.SUSPENDED.name:
        raise RuntimeError(
            f"Only suspended instances can be resumed. "
            f"Instance {instance_name} is in {instance.status} state."
        )

    operation = instance_client.resume(
        project=project_id, zone=zone, instance=instance_name
    )

    wait_for_extended_operation(operation, "instance resumption")

REST

Buat permintaan ke metode instances.resume:

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

Ganti kode berikut:

  • PROJECT_ID: project ID untuk permintaan ini
  • ZONE: zona VM
  • VM_NAME: instance yang akan dilanjutkan

Setelah Anda membuat permintaan untuk melanjutkan instance, perlu waktu beberapa saat agar Compute Engine memulihkan semua data yang diperlukan untuk instance tersebut. Selama jangka waktu ini, Anda akan terus dikenakan biaya untuk instance tersebut saat instance dilanjutkan.

Compute Engine menandai instance dengan status RUNNING setelah pelanjutan selesai. Periksa status instance dengan membuat permintaan GET:

GET https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/instances/example-instance

Status instance terlihat di kolom status. Contoh:

...
"zone": "https://content.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a",
"status": "RUNNING",
"name": "example-instance",
...

Menangguhkan proses

Saat membuat permintaan penangguhan, Anda mengirim sinyal penangguhan ACPI ke instance VM. Jika VM tidak merespons sinyal penangguhan ACPI S3 dalam beberapa menit, Compute Engine akan membatalkan upaya penangguhan dan mengembalikan VM ke status RUNNING.

Tabel berikut menjelaskan efek penangguhan instance VM pada resource terkaitnya:

Resource Dukungan
Memori Hanya VM dengan memori kurang dari atau sama dengan 208 GB yang dapat ditangguhkan
SSD Lokal Data SSD lokal dihapus
Persistent disk Disk HDD dan SSD persisten dipertahankan
Alamat IP IP efemeral dirilis selama penangguhan, tetapi IP statis tetap terpasang ke instance VM. Jika Anda ingin mempertahankan IP sementara Anda, promosikan IP tersebut.
Konfigurasi VM (seperti jenis mesin, metadata, label, dll.) Semua konfigurasi VM, selain alamat IP sementara, dipertahankan dan dipulihkan saat instance dilanjutkan.

Mengonfigurasi VM Debian untuk mendukung penangguhan dan pelanjutan

VM yang menjalankan Debian 8 dan 9 dapat ditangguhkan dan dilanjutkan, tetapi harus dikonfigurasi terlebih dahulu. Untuk mengonfigurasi instance Debian Anda, selesaikan salah satu rangkaian petunjuk berikut, opsi A atau opsi B. Sebaiknya konfigurasi ACPID jika memungkinkan (opsi A).

Opsi A

Opsi ini mengonfigurasi ACPID untuk menangani peristiwa tombol tidur dan menambahkan skrip shell untuk menangani peristiwa tidur.

  1. Hubungkan ke instance VM Anda menggunakan ssh:

    gcloud compute ssh VM_NAME
    
  2. Pada instance VM, buat direktori di folder acpi:

    sudo mkdir -p /etc/acpi/events/
    
  3. Konfigurasi ACPID untuk menangani peristiwa tombol tidur:

    cat <<EOF | sudo tee /etc/acpi/events/sleepbtn-acpi-support
    event=button[ /]sleep
    action=/etc/acpi/sleepbtn-acpi-support.sh
    EOF
    
  4. Buat skrip penanganan peristiwa tidur:

    cat <<EOF | sudo tee /etc/acpi/sleepbtn-acpi-support.sh
    #!/bin/sh
    echo mem > /sys/power/state
    EOF
    
  5. Siapkan izin untuk skrip:

    sudo chmod 755 /etc/acpi/sleepbtn-acpi-support.sh
    
  6. Mulai ulang ACPID:

    sudo systemctl restart acpid.service
    

Opsi B

  1. Hubungkan ke instance VM Anda menggunakan ssh:

    gcloud compute ssh VM_NAME
    
  2. Pada instance VM, instal dbus:

    sudo apt-get install dbus
    
  3. Mulai ulang logind:

    sudo systemctl restart systemd-logind.service
    

Langkah selanjutnya