השעיה או הפעלה מחדש של מכונה של Compute Engine

במאמר הזה נסביר איך להשהות או להפעיל מחדש מכונות של Compute Engine. מידע נוסף על השהיה, עצירה או איפוס של מכונות זמין במאמר השהיה, עצירה או איפוס של מכונות Compute Engine.

אם אתם רוצים להשאיר את המכונה של Compute Engine, אבל לא רוצים לשלם עליה כשהיא לא בשימוש, אתם יכולים להשהות אותה. השעיה של מופע שומרת את המופע ומעבירה את התוכן של הזיכרון של המופע לאחסון. אחרי שממשיכים את הפעולה של המכונה, Compute Engine מעביר את הזיכרון של המכונה מהאחסון בחזרה למכונה, והמכונה מתחילה לפעול שוב.

השעיית מכונה של Compute Engine יכולה להיות שימושית במקרים הבאים:

  • סביבות פיתוח ובדיקה שלא נמצאות בשימוש מלא בתקופות של חוסר פעילות, כמו בערבים או בסופי שבוע, ושאתם רוצים לשמור כדי לחסוך בעלויות או כדי לאתחל מהר יותר מאשר ליצור מכונות חדשות.

  • אפליקציות שנדרש להן פרק זמן ארוך לאתחול אחרי שהמופע סיים את האתחול, אבל לפני שהאפליקציה מוכנה לטפל בבקשה הראשונה שלה, כמו תחנות עבודה וירטואליות למפתחים או אפליקציות מורכבות של Java.

מגבלות

כשמשעים מכונת חישוב, חלות המגבלות הבאות:

  • אפשר להשעות מכונה רק אם מערכת ההפעלה של האורח תומכת בכך. פרטים על מערכת ההפעלה

  • אפשר להשעות מכונה שמשתמשת בקובצי האימג' הבאים של מערכת ההפעלה רק אם מגדירים את מערכת ההפעלה שלה, כפי שמתואר במסמך הזה:

    • ‫Debian 8 או 9

    • כל מערכת הפעלה של Windows

  • אפשר להשהות מכונה למשך 60 ימים בלבד לפני שמערכת Compute Engine מעבירה את המצב שלה באופן אוטומטי לTERMINATED.

  • אפשר להשעות מכונות וירטואליות מסוג VM במודל Spot או מופעים זמניים של מכונות וירטואליות – אבל אם Compute Engine מפסיק את הפעולה של המכונה לפני שהפעולה של ההשעיה מסתיימת, הוא מסיים את פעולת ההשעיה ומפסיק את הפעולה של המכונה.

  • אי אפשר להשעות מכונות באמצעות התהליכים הרגילים שמובנים בסביבת האורח שלהן. פקודות כמו systemctl suspend ב-Ubuntu 16.04 ואילך לא נתמכות. אם נשלחת קריאה, Compute Engine מתעלם מהאות בתוך האורח.

  • אי אפשר להשעות את סוגי המקרים הבאים:

    • מופעי Bare Metal.

    • Confidential VMs

    • מכונות וירטואליות עם יחידות GPU או TPU שמצורפות אליהן.

    • מכונות עם זיכרון בנפח של יותר מ-208GB.

    • מקרים שבהם מצורפים דיסקים שמוגנים באמצעות CSEK‏ (הוצא משימוש).

לפני שמתחילים

התפקידים הנדרשים

כדי לקבל את ההרשאות שנדרשות להשהיה או להפעלה מחדש של מכונת Compute, צריך לבקש מהאדמין להקצות לכם ב-IAM את התפקיד Compute Instance Admin ‏ (v1) (roles/compute.instanceAdmin.v1) במכונה. כדי לקרוא הסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

זהו תפקיד שמוגדר מראש וכולל את ההרשאות שנדרשות להשעיה או להפעלה מחדש של מכונת Compute. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

ההרשאות הנדרשות

כדי להשהות או להפעיל מחדש מכונת וירטואלית, צריך את ההרשאות הבאות:

  • כדי להשעות מופע: compute.instances.suspend
  • כדי להפעיל מחדש מופע: compute.instances.resume

יכול להיות שתקבלו את ההרשאות האלה באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש אחרים.

הפעלת פעולות השעיה במערכת הפעלה של אורח

אם במכונה שלכם מותקנת מערכת ההפעלה Debian 8 או 9, או כל מערכת הפעלה של Windows, תצטרכו להגדיר את מערכת ההפעלה לפני שתוכלו להשהות ולהמשיך את המכונות. אם המופע שלכם משתמש במערכת הפעלה אחרת לאורח, אפשר לדלג על הקטע הזה.

הפעלת השעיה של פעולות ב-Debian 8 או 9

כדי להשעות או להמשיך מכונות Compute שמשתמשות ב-Debian 8 או 9 כמערכת הפעלה של אורח, צריך להגדיר את מערכת ההפעלה של האורח באחת מהשיטות הבאות:

הגדרת ACPID

כדי להפעיל את הפעולות של השהיה והמשך ב-Debian 8 או 9, אפשר להגדיר את הדמון של אירועי Advanced Configuration and Power Interface (ממשק מתקדם להגדרת תצורה וניהול צריכת חשמל, ACPID) כדי לטפל באירוע של לחצן השינה. אחרי שמפעילים את אירוע הלחצן של שינה עמוקה, אפשר להוסיף סקריפט מעטפת לטיפול באירוע השינה, כמו שמתואר בקטע הזה.

כדי להגדיר את ACPID כך שיתמוך בפעולות השהיה והמשך, מבצעים את הפעולות הבאות:

  1. אם עדיין לא עשיתם זאת, מתחברים למופע Linux.

  2. יוצרים את התיקייה events בתיקייה acpi:

    sudo mkdir -p /etc/acpi/events/
    
  3. מגדירים את ה-ACPID לטיפול באירוע של כפתור ההשהיה:

    cat <<EOF | sudo tee /etc/acpi/events/sleepbtn-acpi-support
    event=button[ /]sleep
    action=/etc/acpi/sleepbtn-acpi-support.sh
    EOF
    
  4. יוצרים את הסקריפט לטיפול באירוע השינה:

    cat <<EOF | sudo tee /etc/acpi/sleepbtn-acpi-support.sh
    #!/bin/sh
    echo mem > /sys/power/state
    EOF
    
  5. מגדירים את ההרשאות לסקריפט:

    sudo chmod 755 /etc/acpi/sleepbtn-acpi-support.sh
    
  6. כדי שהשינויים ייכנסו לתוקף, מפעילים מחדש את ה-ACPID:

    sudo systemctl restart acpid.service
    

התקנה של D-Bus

כדי להפעיל את הפעולה של השהיה והמשך ב-Debian 8 או 9, אפשר להתקין את D-Bus.

כדי להתקין את D-Bus במערכת ההפעלה האורחת של מופע החישוב כשמערכת ההפעלה משתמשת ב-Debian 8 או 9, צריך לבצע את הפעולות הבאות:

  1. אם עדיין לא עשיתם זאת, מתחברים למכונה של Linux.

  2. מתקינים את D-Bus:

    sudo apt-get install dbus
    
  3. כדי שהשינויים ייכנסו לתוקף, צריך להפעיל מחדש את logind:

    sudo systemctl restart systemd-logind.service
    

הפעלת השעיה של פעולות ב-Windows

כדי להשעות מופע שמשתמש במערכת הפעלה אורחת של Windows, צריך להשבית את מצב השינה במערכת ההפעלה. אם ייבאתם קובץ אימג' של Windows, יכול להיות שמצב השינה מופעל כברירת מחדל, ותצטרכו להשבית אותו כדי להשעות את המכונה.

כדי להשבית את מצב השינה ב-Windows, פועלים לפי השלבים הבאים:

  1. אם עדיין לא עשיתם זאת, מתחברים למכונה של Windows.

  2. פותחים את PowerShell כאדמין.

  3. השבתת מצב שינה:

    powercfg -h off
    
  4. מוודאים שמצב השינה מושבת:

    powercfg -a
    

השעיית מכונה

אם מערכת ההפעלה האורחת של מכונת החישוב שלכם היא Debian 8 או 9, לפני השהיית המכונה, אתם צריכים להגדיר את מערכת ההפעלה האורחת כך שתתמוך בפעולות השהיה והפעלה מחדש, כמו שמתואר במסמך הזה.

כדי להשעות מכונה, משתמשים באחת מהשיטות הבאות, בהתאם לשאלה אם למכונה מצורפים דיסקים מסוג Local SSD:

השהיית מכונה ללא דיסקים מקומיים מסוג SSD

אפשר להשעות כמה מופעי מחשוב בו-זמנית או מופעים בודדים. אם יש כמה מכונות, אפשר להשתמש במסוף Google Cloud או ב-Google Cloud CLI (אם המכונות נמצאות באותו אזור). למופעים ספציפיים, בוחרים באחת מהאפשרויות הבאות:

המסוף

  1. נכנסים לדף VM instances במסוף Google Cloud .

    כניסה לדף VM instances

  2. בוחרים מכונה אחת או יותר שרוצים להשעות.

  3. לוחצים על השעיה ואז על השעיה כדי לאשר.

gcloud

כדי להשהות מכונה אחת או יותר באזור יחיד, משתמשים בפקודה gcloud compute instances suspend:

gcloud compute instances suspend INSTANCE_NAMES \
    --zone=ZONE

מחליפים את מה שכתוב בשדות הבאים:

  • ‫INSTANCE_NAMES: רשימה של שמות מכונות שמופרדים ברווחים, לדוגמה instance-01 instance-02 instance-03.

  • ‫ZONE: האזור שבו נמצאים המופעים.

המשך

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

כדי להשהות מכונה, שולחים בקשת POST אל ה-method‏ instances.suspend:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend

מחליפים את מה שכתוב בשדות הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט שבו נמצא המופע.

  • ‫ZONE: האזור שבו נמצאת המכונה.

  • ‫INSTANCE_NAME: השם של המכונה.

השהיית מכונה עם דיסקים מסוג SSD מקומי

בהתאם למספר מופעי המחשוב שרוצים להשהות בו-זמנית ולצורך לשמור את הנתונים של דיסקי ה-SSD המקומיים שמצורפים אליהם, מבצעים את הפעולות הבאות:

  • כדי לשמור את הנתונים של דיסקי ה-SSD המקומיים שמחוברים למכונה (לא כולל מכונות עם דיסקי Titanium SSD), צריך להשעות את המכונה באמצעות ה-CLI של gcloud או ה-API בארכיטקטורת REST.

  • כדי להשהות כמה מכונות בו-זמנית, משתמשים במסוף Google Cloud או ב-CLI של gcloud (למכונות שנמצאות באותו אזור).

כדי להשעות מכונה אחת או יותר שמחוברים אליה דיסקים מסוג SSD מקומי, בוחרים באחת מהאפשרויות הבאות:

המסוף

  1. נכנסים לדף VM instances במסוף Google Cloud .

    כניסה לדף VM instances

  2. בוחרים מכונה אחת או יותר להשעיה.

  3. לוחצים על השעיה ואז על השעיה כדי לאשר.

gcloud

כשמשעים מכונה אחת או יותר באזור יחיד עם דיסקים מסוג Local SSD שמחוברים אליהן, צריך לציין אם לבטל את הנתונים של Local SSD או לשמור אותם, באופן הבא:

  • כדי למחוק את הנתונים ב-SSD המקומי, משתמשים בפקודה gcloud compute instances suspend עם הדגל --discard-local-ssd=true:

    gcloud compute instances suspend INSTANCE_NAMES \
        --discard-local-ssd=true \
        --zone=ZONE
    
  • כדי לשמור את הנתונים של ה-SSD המקומי, משתמשים בפקודה gcloud beta compute instances suspend עם הדגל --discard-local-ssd=false:

    gcloud beta compute instances suspend INSTANCE_NAMES \
        --discard-local-ssd=false \
        --zone=ZONE
    

מחליפים את מה שכתוב בשדות הבאים:

  • ‫INSTANCE_NAMES: רשימה של שמות מכונות שמופרדים ברווחים, לדוגמה instance-01 instance-02 instance-03.

  • ‫ZONE: האזור שבו נמצאים המופעים.

REST

כשמשעים מכונה שמחוברים אליה דיסקים של SSD מקומי, צריך לציין אם למחוק או לשמור את הנתונים ב-SSD המקומי, באופן הבא:

  • כדי לבטל את הנתונים של SSD מקומי, צריך לשלוח בקשת POST ל-method‏ instances.suspend. בכתובת ה-URL של הבקשה, מוסיפים את הפרמטר discardLocalSsd של השאילתה, מוגדר ל-true:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend?discardLocalSsd=true
    
  • כדי לשמור את הנתונים ב-SSD מקומי, צריך לשלוח בקשת POST ל-method‏ beta.instances.suspend. בכתובת ה-URL של הבקשה, מוסיפים את פרמטר השאילתה discardLocalSsd שמוגדר לערך false:

    POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend?discardLocalSsd=false
    

מחליפים את מה שכתוב בשדות הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט שבו נמצא המופע.

  • ‫ZONE: האזור שבו נמצאת המכונה.

  • ‫INSTANCE_NAME: השם של המכונה.

המשך של מכונה מושעית

לפני שממשיכים להשתמש במופע של מכונת חישוב שהושעתה, כדאי לשים לב לנקודות הבאות:

  • אפשר להפעיל מחדש מכונה רק אם יש מספיק קיבולת באזור שבו היא נמצאת. בדרך כלל זה לא מהווה בעיה. אם לא הצלחתם להפעיל מחדש את המכונה, נסו שוב מאוחר יותר.

  • אם חיברתם דיסקים של Local SSD למכונה ובחרתם לשמור את הנתונים של Local SSD כשאתם משעים אותה, יכול להיות שתצטרכו לטעון מחדש את הדיסקים של Local SSD אחרי שתפעילו אותה מחדש. למידע נוסף, קראו איך טוענים מחדש דיסקים שאינם דיסקי אתחול במכונות של Linux או במכונות של Windows.

אפשר להמשיך כמה מופעים בו-זמנית או מופעים בודדים. לכמה מכונות, אפשר להשתמש במסוף Google Cloud או ב-CLI של gcloud (אם המכונות ממוקמות באותו אזור). למופעים ספציפיים, בוחרים באחת מהאפשרויות הבאות:

המסוף

  1. נכנסים לדף VM instances במסוף Google Cloud .

    כניסה לדף VM instances

  2. בוחרים מכונה אחת או יותר שהושעו כדי להפעיל אותן מחדש.

  3. לוחצים על Start / Resume (התחלה / המשך) ואז על Start (התחלה).

gcloud

כדי להפעיל מחדש מכונה אחת או יותר שהושעו באזור אחד, משתמשים בפקודה gcloud compute instances resume:

gcloud compute instances resume INSTANCE_NAMES \
    --zone=ZONE

מחליפים את מה שכתוב בשדות הבאים:

  • ‫INSTANCE_NAMES: רשימה מופרדת ברווחים של שמות של מופעים – לדוגמה, instance-01 instance-02 instance-03.

  • ‫ZONE: האזור שבו נמצאות המכונות המושעות.

המשך

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

כדי להפעיל מחדש מכונה מושעית, שולחים בקשת POST אל ה-method‏ instances.resume:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/resume

מחליפים את מה שכתוב בשדות הבאים:

  • ‫INSTANCE_NAME: השם של המכונה שרוצים להשהות כדי להפעיל אותה מחדש.

  • ‫PROJECT_ID: מזהה הפרויקט שבו נמצא המכונה שהושהתה.

  • ‫ZONE: האזור שבו נמצאת המכונה המושעית.

המאמרים הבאים