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

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

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

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

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

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

מגבלות

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

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

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

    • ‫Debian 8 או 9

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

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

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

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

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

    • מופעים של שרתים פיזיים.

    • מכונות וירטואליות סודיות (Confidential VMs).

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

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

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

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

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

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

כדי להשהות או להפעיל מחדש מכונות וירטואליות שמשתמשות ב-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 במערכת ההפעלה האורחת של מופע Compute כשמערכת ההפעלה משתמשת ב-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
    

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

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

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

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

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

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

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

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

השעיית מכונה

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

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

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

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

המסוף

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

    כניסה לדף 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.s3nsapis.fr/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.

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

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

המסוף

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

    כניסה לדף VM instances

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

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

gcloud

כשמשעים מכונה אחת או יותר באזור יחיד עם דיסקים מסוג 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.s3nsapis.fr/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.s3nsapis.fr/compute/beta/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/suspend?discardLocalSsd=false
    

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

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

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

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

המשך של מופע מושעה

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

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

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

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

המסוף

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

    כניסה לדף 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.s3nsapis.fr/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/resume

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

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

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

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

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