ניהול קבוצות עקביות

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

מידע נוסף על קבוצות עקביות זמין במאמר מידע על שכפול אסינכרוני.

מגבלות

  • דיסק יכול להשתייך רק לקבוצת עקביות אחת בכל פעם.
  • אין תמיכה בקבוצות עקביות לדיסקים בצמתים של דייר יחיד.
  • בקבוצות עקביות יכולים להיות עד 128 דיסקים.
  • כל הדיסקים בקבוצת אפליקציות עקביות צריכים להיות באותו פרויקט כמו מדיניות המשאבים של קבוצת אפליקציות עקביות.
  • קבוצת עקביות יכולה להכיל דיסקים ראשיים או דיסקים משניים, אבל לא את שניהם.
  • כדי להפעיל שכפול אסינכרוני לדיסקים בקבוצת אפליקציות עקביות, כל הדיסקים צריכים להיות באותו תחום (zone), אם מדובר בדיסקים אזוריים, או באותו זוג תחומים (zone), אם מדובר בדיסקים אזוריים.
  • אי אפשר להוסיף או להסיר דיסק ראשי מקבוצת עקביות או ממנה בזמן שהדיסק משוכפל. אם רוצים להוסיף או להסיר דיסק ראשי מקבוצת עקביות, צריך קודם להפסיק את השכפול. אפשר להוסיף או להסיר דיסקים משניים לקבוצות עקביות או מהן בכל שלב.
  • אפשר לחבר למכונה וירטואלית עד 16 דיסקים שנמצאים בקבוצות אפליקציות עקביות שונות, או דיסקים שלא נמצאים בקבוצת אפליקציות עקביות. דיסקים שנמצאים באותה קבוצת אפליקציות עקביות נספרים כדיסק אחד מתוך מגבלת 16 הדיסקים.

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

  • אם עדיין לא עשיתם את זה, תצטרכו להגדיר אימות. אימות הוא תהליך שבו מאמתים את הזהות שלכם כדי לקבל גישה לממשקי API ולשירותים של Google Cloud . כדי להריץ קוד או דוגמאות מסביבת פיתוח מקומית, אפשר לבצע אימות ל-Compute Engine באחת מהדרכים הבאות:

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

    המסוף

    כשמשתמשים במסוף Google Cloud כדי לגשת לשירותים ולממשקי ה-API, לא צריך להגדיר אימות. Google Cloud

    gcloud

    1. התקינו את ה-CLI של Google Cloud. אחר כך, אתחלו את ה-CLI של Google Cloud באמצעות הפקודה הבאה:

      gcloud init

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

  • הגדרת אזור ותחום כברירת מחדל
  • Terraform

    כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של Terraform שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

    1. התקינו את ה-CLI של Google Cloud.

    2. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

    3. אם אתם משתמשים במעטפת מקומית, אתם צריכים ליצור פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

      gcloud auth application-default login

      אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

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

    מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

    REST

    כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של API בארכיטקטורת REST שבדף הזה, צריך להשתמש בפרטי הכניסה שאתם נותנים ל-CLI של gcloud.

      התקינו את ה-CLI של Google Cloud.

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

    מידע נוסף מופיע במאמר אימות לשימוש ב-REST במסמכי האימות של Google Cloud .

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

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

להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

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

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

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

  • compute.disks.create
  • compute.disks.useReadOnly בדיסק המקור

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

יצירת קבוצת עקביות

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

יוצרים קבוצת עקביות באמצעות מסוף Google Cloud , Google Cloud CLI,‏ REST או Terraform.

המסוף

כדי ליצור קבוצת עקביות:

  1. נכנסים לדף Consistency Groups במסוף Google Cloud .

    כניסה לדף Consistency Groups

  2. לוחצים על הכרטיסייה קבוצות עקביות של דיסקים.

  3. לוחצים על יצירת קבוצת עקביות.

  4. בשדה Name, מזינים שם לקבוצת העקביות.

  5. בשדה Region, בוחרים את האזור שבו נמצאים הדיסקים. אם רוצים להוסיף דיסקים ראשיים לקבוצת עקביות, בוחרים את האזור הראשי. אם רוצים להוסיף דיסקים משניים לקבוצת העקביות, בוחרים את האזור המשני.

  6. לוחצים על יצירה.

gcloud

יוצרים קבוצת אפליקציות עקביות באמצעות הפקודה gcloud compute resource-policies create disk-consistency-group:

gcloud compute resource-policies create disk-consistency-group CONSISTENCY_GROUP_NAME \
    --region=REGION

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

  • CONSISTENCY_GROUP_NAME: השם של קבוצת אפליקציות עקביות.
  • REGION: האזור של קבוצת העקביות. אם רוצים להוסיף דיסקים ראשיים לקבוצת עקביות, צריך להשתמש באזור הראשי. אם רוצים להוסיף דיסקים משניים לקבוצת העקביות, צריך להשתמש באזור המשני.

המשך

import (
	"context"
	"fmt"
	"io"

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

// createConsistencyGroup creates a new consistency group for a project in a given region.
func createConsistencyGroup(w io.Writer, projectID, region, groupName string) error {
	// projectID := "your_project_id"
	// region := "europe-west4"
	// groupName := "your_group_name"

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

	req := &computepb.InsertResourcePolicyRequest{
		Project: projectID,
		ResourcePolicyResource: &computepb.ResourcePolicy{
			Name:                       proto.String(groupName),
			DiskConsistencyGroupPolicy: &computepb.ResourcePolicyDiskConsistencyGroupPolicy{},
		},
		Region: region,
	}

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

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

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

	return nil
}

Java

import com.google.cloud.compute.v1.InsertResourcePolicyRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.ResourcePoliciesClient;
import com.google.cloud.compute.v1.ResourcePolicy;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateConsistencyGroup {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String project = "YOUR_PROJECT_ID";
    // Name of the region in which you want to create the consistency group.
    String region = "us-central1";
    // Name of the consistency group you want to create.
    String consistencyGroupName = "YOUR_CONSISTENCY_GROUP_NAME";

    createConsistencyGroup(project, region, consistencyGroupName);
  }

  // Creates a new consistency group resource policy in the specified project and region.
  public static Status createConsistencyGroup(
      String project, String region, String consistencyGroupName)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (ResourcePoliciesClient  regionResourcePoliciesClient = ResourcePoliciesClient.create()) {
      ResourcePolicy resourcePolicy =
          ResourcePolicy.newBuilder()
              .setName(consistencyGroupName)
              .setRegion(region)
              .setDiskConsistencyGroupPolicy(
                  ResourcePolicy.newBuilder().getDiskConsistencyGroupPolicy())
              .build();

      InsertResourcePolicyRequest request = InsertResourcePolicyRequest.newBuilder()
              .setProject(project)
              .setRegion(region)
              .setResourcePolicyResource(resourcePolicy)
              .build();

      Operation response =
          regionResourcePoliciesClient.insertAsync(request).get(1, TimeUnit.MINUTES);

      if (response.hasError()) {
        throw new Error("Error creating consistency group! " + response.getError());
      }
      return response.getStatus();
    }
  }
}

Node.js

// Import the Compute library
const computeLib = require('@google-cloud/compute');
const compute = computeLib.protos.google.cloud.compute.v1;

// Instantiate a resourcePoliciesClient
const resourcePoliciesClient = new computeLib.ResourcePoliciesClient();
// Instantiate a regionOperationsClient
const regionOperationsClient = new computeLib.RegionOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The project that contains the consistency group.
const projectId = await resourcePoliciesClient.getProjectId();

// The region for the consistency group.
// If you want to add primary disks to consistency group, use the same region as the primary disks.
// If you want to add secondary disks to the consistency group, use the same region as the secondary disks.
// region = 'europe-central2';

// The name for consistency group.
// consistencyGroupName = 'consistency-group-name';

async function callCreateConsistencyGroup() {
  // Create a resourcePolicyResource
  const resourcePolicyResource = new compute.ResourcePolicy({
    diskConsistencyGroupPolicy:
      new compute.ResourcePolicyDiskConsistencyGroupPolicy({}),
    name: consistencyGroupName,
  });

  const [response] = await resourcePoliciesClient.insert({
    project: projectId,
    region,
    resourcePolicyResource,
  });

  let operation = response.latestResponse;

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

  console.log(`Consistency group: ${consistencyGroupName} created.`);
}

await callCreateConsistencyGroup();

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 create_consistency_group(
    project_id: str, region: str, group_name: str, group_description: str
) -> compute_v1.ResourcePolicy:
    """
    Creates a consistency group in Google Cloud Compute Engine.
    Args:
        project_id (str): The ID of the Google Cloud project.
        region (str): The region where the consistency group will be created.
        group_name (str): The name of the consistency group.
        group_description (str): The description of the consistency group.
    Returns:
        compute_v1.ResourcePolicy: The consistency group object
    """

    # Initialize the ResourcePoliciesClient
    client = compute_v1.ResourcePoliciesClient()

    # Create the ResourcePolicy object with the provided name, description, and policy
    resource_policy_resource = compute_v1.ResourcePolicy(
        name=group_name,
        description=group_description,
        disk_consistency_group_policy=compute_v1.ResourcePolicyDiskConsistencyGroupPolicy(),
    )

    operation = client.insert(
        project=project_id,
        region=region,
        resource_policy_resource=resource_policy_resource,
    )
    wait_for_extended_operation(operation, "Consistency group creation")

    return client.get(project=project_id, region=region, resource_policy=group_name)

REST

כדי ליצור קבוצת אפליקציות עקביות באמצעות השיטה resourcePolicies.insert:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT/regions/REGION/resourcePolicies
{
 "name": "CONSISTENCY_GROUP_NAME",
 "diskConsistencyGroupPolicy": {
  }
}

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

  • PROJECT: הפרויקט שמכיל את קבוצת העקביות.
  • REGION: האזור של קבוצת העקביות. אם רוצים להוסיף דיסקים ראשיים לקבוצת אפליקציות עקביות, צריך להשתמש באותו אזור כמו הדיסקים הראשיים. אם רוצים להוסיף דיסקים משניים לקבוצת העקביות, צריך להשתמש באותו אזור כמו הדיסקים המשניים.
  • CONSISTENCY_GROUP_NAME: השם של קבוצת אפליקציות עקביות.

Terraform

כדי ליצור קבוצת עקביות, משתמשים במשאב compute_resource_policy.

resource "google_compute_resource_policy" "default" {
  name   = "test-consistency-group"
  region = "us-central1"
  disk_consistency_group_policy {
    enabled = true
  }
}

כדי ללמוד איך להחיל הגדרות ב-Terraform או להסיר אותן, ראו פקודות בסיסיות ב-Terraform.

הצגת הדיסקים בקבוצת עקביות

אפשר לראות את הדיסקים בקבוצת עקביות באמצעות מסוף Google Cloud , Google Cloud CLI או REST.

המסוף

כדי לראות את הדיסקים שנכללים בקבוצת עקביות:

  1. נכנסים לדף Consistency Groups במסוף Google Cloud .

    כניסה לדף Consistency Groups

  2. לוחצים על הכרטיסייה קבוצות עקביות של דיסקים.

  3. לוחצים על השם של קבוצת העקביות שרוצים להציג את הדיסקים שלה. ייפתח הדף ניהול קבוצת עקביות.

  4. בקטע חברים בקבוצת העקביות אפשר לראות את כל הדיסקים שנכללים בקבוצת העקביות.

gcloud

כדי להציג את הדיסקים שנכללים בקבוצת עקביות, משתמשים בפקודה gcloud compute disks list:

gcloud compute disks list \
    --LOCATION_FLAG=LOCATION \
    --filter=resourcePolicies=CONSISTENCY_GROUP_NAME

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

  • LOCATION_FLAG: דגל המיקום של הדיסקים בקבוצת העקביות. אם הדיסקים בקבוצת העקביות הם אזוריים, משתמשים ב---region. אם הדיסקים בקבוצת העקביות הם אזוריים, משתמשים ב---zone.
  • LOCATION: האזור או התחום (zone) של הדיסקים בקבוצת אפליקציות עקביות. לדיסקים אזוריים, משתמשים באזור. בדיסקים אזוריים, משתמשים באזור.
  • CONSISTENCY_GROUP_NAME: השם של קבוצת אפליקציות עקביות.

המשך

import (
	"context"
	"fmt"
	"io"
	"strings"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/api/iterator"
)

// listRegionalConsistencyGroup get list of disks in consistency group for a project in a given region.
func listRegionalConsistencyGroup(w io.Writer, projectID, region, groupName string) error {
	// projectID := "your_project_id"
	// region := "europe-west4"
	// groupName := "your_group_name"

	if groupName == "" {
		return fmt.Errorf("group name cannot be empty")
	}

	ctx := context.Background()
	// To check for zonal disks in consistency group use compute.NewDisksRESTClient
	disksClient, err := compute.NewRegionDisksRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewRegionDisksRESTClient: %w", err)
	}
	defer disksClient.Close()

	// If using zonal disk client, use computepb.ListDisksRequest
	req := &computepb.ListRegionDisksRequest{
		Project: projectID,
		Region:  region,
	}

	it := disksClient.List(ctx, req)
	for {
		disk, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}

		for _, diskPolicy := range disk.GetResourcePolicies() {
			if strings.Contains(diskPolicy, groupName) {
				fmt.Fprintf(w, "- %s\n", disk.GetName())
			}
		}
	}

	return nil
}

Java

הצגת רשימה של דיסקים אזוריים בקבוצת עקביות

import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.ListDisksRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class ListZonalDisksInConsistencyGroup {
  public static void main(String[] args)
          throws IOException, InterruptedException, ExecutionException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String project = "YOUR_PROJECT_ID";
    // Name of the consistency group.
    String consistencyGroupName = "CONSISTENCY_GROUP_ID";
    // Zone of the disk.
    String disksLocation = "us-central1-a";
    // Region of the consistency group.
    String consistencyGroupLocation = "us-central1";

    listZonalDisksInConsistencyGroup(
            project, consistencyGroupName, consistencyGroupLocation, disksLocation);
  }

  // Lists disks in a consistency group.
  public static List<Disk> listZonalDisksInConsistencyGroup(String project,
      String consistencyGroupName, String consistencyGroupLocation, String disksLocation)
          throws IOException {
    String filter = String
            .format("https://www.googleapis.com/compute/v1/projects/%s/regions/%s/resourcePolicies/%s",
                    project, consistencyGroupLocation, consistencyGroupName);
    List<Disk> disksList = new ArrayList<>();
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (DisksClient disksClient = DisksClient.create()) {
      ListDisksRequest request =
              ListDisksRequest.newBuilder()
                      .setProject(project)
                      .setZone(disksLocation)
                      .build();
      DisksClient.ListPagedResponse response = disksClient.list(request);

      for (Disk disk : response.iterateAll()) {
        if (disk.getResourcePoliciesList().contains(filter)) {
          disksList.add(disk);
        }
      }
    }
    System.out.println(disksList.size());
    return disksList;
  }
}

הצגת דיסקים אזוריים בקבוצת עקביות

import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.ListRegionDisksRequest;
import com.google.cloud.compute.v1.RegionDisksClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class ListRegionalDisksInConsistencyGroup {
  public static void main(String[] args)
          throws IOException, InterruptedException, ExecutionException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String project = "YOUR_PROJECT_ID";
    // Name of the consistency group.
    String consistencyGroupName = "CONSISTENCY_GROUP_ID";
    // Region of the disk.
    String disksLocation = "us-central1";
    // Region of the consistency group.
    String consistencyGroupLocation = "us-central1";

    listRegionalDisksInConsistencyGroup(
            project, consistencyGroupName, consistencyGroupLocation, disksLocation);
  }

  // Lists disks in a consistency group.
  public static List<Disk> listRegionalDisksInConsistencyGroup(String project,
      String consistencyGroupName, String consistencyGroupLocation, String disksLocation)
          throws IOException {
    String filter = String
            .format("https://www.googleapis.com/compute/v1/projects/%s/regions/%s/resourcePolicies/%s",
                    project, consistencyGroupLocation, consistencyGroupName);
    List<Disk> disksList = new ArrayList<>();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (RegionDisksClient disksClient = RegionDisksClient.create()) {
      ListRegionDisksRequest request =
              ListRegionDisksRequest.newBuilder()
                      .setProject(project)
                      .setRegion(disksLocation)
                      .build();

      RegionDisksClient.ListPagedResponse response = disksClient.list(request);
      for (Disk disk : response.iterateAll()) {
        if (disk.getResourcePoliciesList().contains(filter)) {
          disksList.add(disk);
        }
      }
    }
    System.out.println(disksList.size());
    return disksList;
  }
}

Node.js

// Import the Compute library
const computeLib = require('@google-cloud/compute');

// If you want to get regional disks, you should use: RegionDisksClient.
// Instantiate a disksClient
const disksClient = new computeLib.DisksClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The project that contains the disks.
const projectId = await disksClient.getProjectId();

// If you use RegionDisksClient- define region, if DisksClient- define zone.
// The zone or region of the disks.
// disksLocation = 'europe-central2-a';

// The name of the consistency group.
// consistencyGroupName = 'consistency-group-name';

// The region of the consistency group.
// consistencyGroupLocation = 'europe-central2';

async function callConsistencyGroupDisksList() {
  const filter = `https://www.googleapis.com/compute/v1/projects/${projectId}/regions/${consistencyGroupLocation}/resourcePolicies/${consistencyGroupName}`;

  const [response] = await disksClient.list({
    project: projectId,
    // If you use RegionDisksClient, pass region as an argument instead of zone.
    zone: disksLocation,
  });

  // Filtering must be done manually for now, since list filtering inside disksClient.list is not supported yet.
  const filteredDisks = response.filter(disk =>
    disk.resourcePolicies.includes(filter)
  );

  console.log(JSON.stringify(filteredDisks));
}

await callConsistencyGroupDisksList();

Python

from google.cloud import compute_v1


def list_disks_consistency_group(
    project_id: str,
    disk_location: str,
    consistency_group_name: str,
    consistency_group_region: str,
) -> list:
    """
    Lists disks that are part of a specified consistency group.
    Args:
        project_id (str): The ID of the Google Cloud project.
        disk_location (str): The region or zone of the disk
        disk_region_flag (bool): Flag indicating if the disk is regional.
        consistency_group_name (str): The name of the consistency group.
        consistency_group_region (str): The region of the consistency group.
    Returns:
        list: A list of disks that are part of the specified consistency group.
    """
    consistency_group_link = (
        f"https://www.googleapis.com/compute/v1/projects/{project_id}/regions/"
        f"{consistency_group_region}/resourcePolicies/{consistency_group_name}"
    )
    # If the final character of the disk_location is a digit, it is a regional disk
    if disk_location[-1].isdigit():
        region_client = compute_v1.RegionDisksClient()
        disks = region_client.list(project=project_id, region=disk_location)
    # For zonal disks we use DisksClient
    else:
        client = compute_v1.DisksClient()
        disks = client.list(project=project_id, zone=disk_location)
    return [disk for disk in disks if consistency_group_link in disk.resource_policies]

REST

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

  • כדי להציג דיסקים אזוריים בקבוצת עקביות באמצעות השיטה disks.get:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT/zones/ZONE/disks?filter=resourcePolicies%3DCONSISTENCY_GROUP_NAME
    
  • כדי להציג דיסקים אזוריים בקבוצת אפליקציות עקביות באמצעות השיטה regionDisks.get:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT/regions/REGION/disks?filter=resourcePolicies%3DCONSISTENCY_GROUP_NAME
    

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

  • PROJECT: הפרויקט שמכיל את קבוצת העקביות
  • ZONE: האזור של הדיסקים בקבוצת העקביות
  • REGION: האזור של הדיסקים בקבוצת העקביות
  • CONSISTENCY_GROUP_NAME: השם של קבוצת העקביות

הוספת דיסק לקבוצת עקביות

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

מוסיפים דיסק לקבוצת אפליקציות עקביות באמצעות מסוף Google Cloud , Google Cloud CLI,‏ REST או Terraform.

המסוף

כדי להוסיף דיסקים לקבוצת עקביות:

  1. נכנסים לדף Consistency Groups במסוף Google Cloud .

    כניסה לדף Consistency Groups

  2. לוחצים על הכרטיסייה קבוצות עקביות של דיסקים.

  3. לוחצים על השם של קבוצת העקביות שאליה רוצים להוסיף דיסקים. ייפתח הדף ניהול קבוצת עקביות.

  4. לוחצים על הקצאת דיסקים. ייפתח הדף הקצאת דיסקים.

  5. בוחרים את הדיסקים שרוצים להוסיף לקבוצת העקביות.

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

gcloud

מוסיפים דיסק לקבוצת עקביות באמצעות הפקודה gcloud compute disks add-resource-policies:

gcloud compute disks add-resource-policies DISK_NAME \
    --LOCATION_FLAG=LOCATION \
    --resource-policies=CONSISTENCY_GROUP

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

  • DISK_NAME: השם של הדיסק שרוצים להוסיף לקבוצת העקביות.
  • LOCATION_FLAG: דגל המיקום של הדיסק. לדיסק אזורי, משתמשים ב---region. לדיסק אזורי, משתמשים ב---zone.
  • LOCATION: האזור או התחום של הדיסק. לדיסקים אזוריים, משתמשים באזור. לדיסקים אזוריים, משתמשים באזור.
  • CONSISTENCY_GROUP: כתובת ה-URL של קבוצת העקביות. לדוגמה, projects/PROJECT/regions/REGION/resourcePolicies/CONSISTENCY_GROUP_NAME.

המשך

import (
	"context"
	"fmt"
	"io"

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

// addDiskConsistencyGroup adds a disk to a consistency group for a project in a given region.
func addDiskConsistencyGroup(w io.Writer, projectID, region, groupName, diskName string) error {
	// projectID := "your_project_id"
	// region := "europe-west4"
	// diskName := "your_disk_name"
	// groupName := "your_group_name"

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

	consistencyGroupUrl := fmt.Sprintf("projects/%s/regions/%s/resourcePolicies/%s", projectID, region, groupName)

	req := &computepb.AddResourcePoliciesRegionDiskRequest{
		Project: projectID,
		Disk:    diskName,
		RegionDisksAddResourcePoliciesRequestResource: &computepb.RegionDisksAddResourcePoliciesRequest{
			ResourcePolicies: []string{consistencyGroupUrl},
		},
		Region: region,
	}

	op, err := disksClient.AddResourcePolicies(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to add disk: %w", err)
	}

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

	fmt.Fprintf(w, "Disk added\n")

	return nil
}

Java

import com.google.cloud.compute.v1.AddResourcePoliciesDiskRequest;
import com.google.cloud.compute.v1.AddResourcePoliciesRegionDiskRequest;
import com.google.cloud.compute.v1.DisksAddResourcePoliciesRequest;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.RegionDisksAddResourcePoliciesRequest;
import com.google.cloud.compute.v1.RegionDisksClient;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class AddDiskToConsistencyGroup {
  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project that contains the disk.
    String project = "YOUR_PROJECT_ID";
    // Zone or region of the disk.
    String location = "us-central1";
    // Name of the disk.
    String diskName = "DISK_NAME";
    // Name of the consistency group.
    String consistencyGroupName = "CONSISTENCY_GROUP";
    // Region of the consistency group.
    String consistencyGroupLocation = "us-central1";

    addDiskToConsistencyGroup(
        project, location, diskName, consistencyGroupName, consistencyGroupLocation);
  }

  // Adds a disk to a consistency group.
  public static Status addDiskToConsistencyGroup(
      String project, String location, String diskName,
      String consistencyGroupName, String consistencyGroupLocation)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    String consistencyGroupUrl = String.format(
        "https://www.googleapis.com/compute/v1/projects/%s/regions/%s/resourcePolicies/%s",
        project, consistencyGroupLocation, consistencyGroupName);
    Operation response;
    if (Character.isDigit(location.charAt(location.length() - 1))) {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (RegionDisksClient disksClient = RegionDisksClient.create()) {
        AddResourcePoliciesRegionDiskRequest request =
                AddResourcePoliciesRegionDiskRequest.newBuilder()
                    .setDisk(diskName)
                    .setRegion(location)
                    .setProject(project)
                    .setRegionDisksAddResourcePoliciesRequestResource(
                            RegionDisksAddResourcePoliciesRequest.newBuilder()
                                .addAllResourcePolicies(Arrays.asList(consistencyGroupUrl))
                                .build())
                    .build();
        response = disksClient.addResourcePoliciesAsync(request).get(1, TimeUnit.MINUTES);
      }
    } else {
      try (DisksClient disksClient = DisksClient.create()) {
        AddResourcePoliciesDiskRequest request =
                AddResourcePoliciesDiskRequest.newBuilder()
                    .setDisk(diskName)
                    .setZone(location)
                    .setProject(project)
                    .setDisksAddResourcePoliciesRequestResource(
                            DisksAddResourcePoliciesRequest.newBuilder()
                                .addAllResourcePolicies(Arrays.asList(consistencyGroupUrl))
                                .build())
                    .build();
        response = disksClient.addResourcePoliciesAsync(request).get(1, TimeUnit.MINUTES);
      }
    }
    if (response.hasError()) {
      throw new Error("Error adding disk to consistency group! " + response.getError());
    }
    return response.getStatus();
  }
}

Node.js

// Import the Compute library
const computeLib = require('@google-cloud/compute');
const compute = computeLib.protos.google.cloud.compute.v1;

// If you want to add regional disk,
// you should use: RegionDisksClient and RegionOperationsClient.
// Instantiate a disksClient
const disksClient = new computeLib.DisksClient();
// Instantiate a zone
const zoneOperationsClient = new computeLib.ZoneOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The project that contains the disk.
const projectId = await disksClient.getProjectId();

// The name of the disk.
// diskName = 'disk-name';

// If you use RegionDisksClient- define region, if DisksClient- define zone.
// The zone or region of the disk.
// diskLocation = 'europe-central2-a';

// The name of the consistency group.
// consistencyGroupName = 'consistency-group-name';

// The region of the consistency group.
// consistencyGroupLocation = 'europe-central2';

async function callAddDiskToConsistencyGroup() {
  const [response] = await disksClient.addResourcePolicies({
    disk: diskName,
    project: projectId,
    // If you use RegionDisksClient, pass region as an argument instead of zone.
    zone: diskLocation,
    disksAddResourcePoliciesRequestResource:
      new compute.DisksAddResourcePoliciesRequest({
        resourcePolicies: [
          `https://www.googleapis.com/compute/v1/projects/${projectId}/regions/${consistencyGroupLocation}/resourcePolicies/${consistencyGroupName}`,
        ],
      }),
  });

  let operation = response.latestResponse;

  // Wait for the add disk operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await zoneOperationsClient.wait({
      operation: operation.name,
      project: projectId,
      // If you use RegionDisksClient, pass region as an argument instead of zone.
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log(
    `Disk: ${diskName} added to consistency group: ${consistencyGroupName}.`
  );
}

await callAddDiskToConsistencyGroup();

Python

from google.cloud import compute_v1


def add_disk_consistency_group(
    project_id: str,
    disk_name: str,
    disk_location: str,
    consistency_group_name: str,
    consistency_group_region: str,
) -> None:
    """Adds a disk to a specified consistency group.
    Args:
        project_id (str): The ID of the Google Cloud project.
        disk_name (str): The name of the disk to be added.
        disk_location (str): The region or zone of the disk
        consistency_group_name (str): The name of the consistency group.
        consistency_group_region (str): The region of the consistency group.
    Returns:
        None
    """
    consistency_group_link = (
        f"regions/{consistency_group_region}/resourcePolicies/{consistency_group_name}"
    )

    # Checking if the disk is zonal or regional
    # If the final character of the disk_location is a digit, it is a regional disk
    if disk_location[-1].isdigit():
        policy = compute_v1.RegionDisksAddResourcePoliciesRequest(
            resource_policies=[consistency_group_link]
        )
        disk_client = compute_v1.RegionDisksClient()
        disk_client.add_resource_policies(
            project=project_id,
            region=disk_location,
            disk=disk_name,
            region_disks_add_resource_policies_request_resource=policy,
        )
    # For zonal disks we use DisksClient
    else:
        print("Using DisksClient")
        policy = compute_v1.DisksAddResourcePoliciesRequest(
            resource_policies=[consistency_group_link]
        )
        disk_client = compute_v1.DisksClient()
        disk_client.add_resource_policies(
            project=project_id,
            zone=disk_location,
            disk=disk_name,
            disks_add_resource_policies_request_resource=policy,
        )

    print(f"Disk {disk_name} added to consistency group {consistency_group_name}")

REST

מוסיפים דיסקים לקבוצת עקביות באחת מהשיטות הבאות:

  • מוסיפים דיסקים אזוריים לקבוצת עקביות באמצעות השיטה disks.addResourcePolicies:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT/zones/LOCATION/disks/DISK_NAME/addResourcePolicies
    
    {
    "resourcePolicies": "CONSISTENCY_GROUP"
    }
    
  • כדי להוסיף דיסקים אזוריים לקבוצת אפליקציות עקביות באמצעות השיטה regionDisks.addResourcePolicies:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT/regions/LOCATION/disks/DISK_NAME/addResourcePolicies
    
    {
    "resourcePolicies": "CONSISTENCY_GROUP"
    }
    

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

  • PROJECT: הפרויקט שמכיל את הדיסק.
  • LOCATION: האזור או האזור של הדיסק. בדיסקים אזוריים, משתמשים באזור. לדיסקים אזוריים, משתמשים באזור.
  • DISK_NAME: השם של הדיסק שרוצים להוסיף לקבוצת העקביות.
  • CONSISTENCY_GROUP: כתובת ה-URL של קבוצת העקביות. לדוגמה, projects/PROJECT/regions/REGION/resourcePolicies/CONSISTENCY_GROUP_NAME.

Terraform

כדי להוסיף את הדיסק לקבוצת העקביות, משתמשים במשאב compute_disk_resource_policy_attachment.

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

    resource "google_compute_disk_resource_policy_attachment" "default" {
      name = google_compute_resource_policy.default.name
      disk = google_compute_disk.default.name
      zone = "us-central1-a"
    }

    כדי ללמוד איך להחיל הגדרות ב-Terraform או להסיר אותן, ראו פקודות בסיסיות ב-Terraform.

הסרת דיסק מקבוצת עקביות

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

אפשר להסיר דיסק מקבוצת עקביות באמצעות מסוף Google Cloud , Google Cloud CLI או REST.

המסוף

כדי להסיר דיסקים ראשיים מקבוצת עקביות:

  1. נכנסים לדף Consistency Groups במסוף Google Cloud .

    כניסה לדף Consistency Groups

  2. לוחצים על הכרטיסייה קבוצות עקביות של דיסקים.

  3. לוחצים על השם של קבוצת העקביות שאליה רוצים להוסיף דיסקים. ייפתח הדף ניהול קבוצת עקביות.

  4. בקטע Consistency group members (חברים בקבוצת העקביות), בוחרים את הדיסקים שרוצים להסיר מקבוצת העקביות.

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

gcloud

כדי להסיר דיסק מקבוצת אפליקציות עקביות, משתמשים בפקודה gcloud compute disks remove-resource-policies:

gcloud compute disks remove-resource-policies DISK_NAME \
    --LOCATION_FLAG=LOCATION \
    --resource-policies=CONSISTENCY_GROUP

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

  • DISK_NAME: השם של הדיסק שרוצים להסיר מקבוצת האפליקציות העקביות.
  • LOCATION_FLAG: דגל המיקום של הדיסק. לדיסק אזורי, משתמשים ב---region. לדיסק אזורי, משתמשים ב---zone.
  • LOCATION: האזור או התחום של הדיסק. לדיסקים אזוריים, משתמשים באזור. לדיסקים אזוריים, משתמשים באזור.
  • CONSISTENCY_GROUP: כתובת ה-URL של קבוצת העקביות. לדוגמה, projects/PROJECT/regions/REGION/resourcePolicies/CONSISTENCY_GROUP_NAME.

המשך

import (
	"context"
	"fmt"
	"io"

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

// removeDiskConsistencyGroup removes a disk from consistency group for a project in a given region.
func removeDiskConsistencyGroup(w io.Writer, projectID, region, groupName, diskName string) error {
	// projectID := "your_project_id"
	// region := "europe-west4"
	// diskName := "your_disk_name"
	// groupName := "your_group_name"

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

	consistencyGroupUrl := fmt.Sprintf("projects/%s/regions/%s/resourcePolicies/%s", projectID, region, groupName)

	req := &computepb.RemoveResourcePoliciesRegionDiskRequest{
		Project: projectID,
		Disk:    diskName,
		RegionDisksRemoveResourcePoliciesRequestResource: &computepb.RegionDisksRemoveResourcePoliciesRequest{
			ResourcePolicies: []string{consistencyGroupUrl},
		},
		Region: region,
	}

	op, err := disksClient.RemoveResourcePolicies(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to remove disk: %w", err)
	}

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

	fmt.Fprintf(w, "Disk removed\n")

	return nil
}

Java

import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.DisksRemoveResourcePoliciesRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.RegionDisksClient;
import com.google.cloud.compute.v1.RegionDisksRemoveResourcePoliciesRequest;
import com.google.cloud.compute.v1.RemoveResourcePoliciesDiskRequest;
import com.google.cloud.compute.v1.RemoveResourcePoliciesRegionDiskRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RemoveDiskFromConsistencyGroup {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project that contains the disk.
    String project = "YOUR_PROJECT_ID";
    // Zone or region of the disk.
    String location = "us-central1";
    // Name of the disk.
    String diskName = "DISK_NAME";
    // Name of the consistency group.
    String consistencyGroupName = "CONSISTENCY_GROUP";
    // Region of the consistency group.
    String consistencyGroupLocation = "us-central1";

    removeDiskFromConsistencyGroup(
        project, location, diskName, consistencyGroupName, consistencyGroupLocation);
  }

  // Removes a disk from a consistency group.
  public static Status removeDiskFromConsistencyGroup(
      String project, String location, String diskName,
      String consistencyGroupName, String consistencyGroupLocation)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    String consistencyGroupUrl = String.format(
        "https://www.googleapis.com/compute/v1/projects/%s/regions/%s/resourcePolicies/%s",
        project, consistencyGroupLocation, consistencyGroupName);
    Operation response;
    if (Character.isDigit(location.charAt(location.length() - 1))) {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (RegionDisksClient disksClient = RegionDisksClient.create()) {
        RemoveResourcePoliciesRegionDiskRequest request =
            RemoveResourcePoliciesRegionDiskRequest.newBuilder()
                .setDisk(diskName)
                .setRegion(location)
                .setProject(project)
                .setRegionDisksRemoveResourcePoliciesRequestResource(
                    RegionDisksRemoveResourcePoliciesRequest.newBuilder()
                        .addAllResourcePolicies(Arrays.asList(consistencyGroupUrl))
                        .build())
                .build();

        response = disksClient.removeResourcePoliciesAsync(request).get(1, TimeUnit.MINUTES);
      }
    } else {
      try (DisksClient disksClient = DisksClient.create()) {
        RemoveResourcePoliciesDiskRequest request =
            RemoveResourcePoliciesDiskRequest.newBuilder()
                .setDisk(diskName)
                .setZone(location)
                .setProject(project)
                .setDisksRemoveResourcePoliciesRequestResource(
                    DisksRemoveResourcePoliciesRequest.newBuilder()
                        .addAllResourcePolicies(Arrays.asList(consistencyGroupUrl))
                        .build())
                .build();
        response = disksClient.removeResourcePoliciesAsync(request).get(1, TimeUnit.MINUTES);
      }
    }
    if (response.hasError()) {
      throw new Error("Error removing disk from consistency group! " + response.getError());
    }
    return response.getStatus();
  }
}

Node.js

// Import the Compute library
const computeLib = require('@google-cloud/compute');
const compute = computeLib.protos.google.cloud.compute.v1;

// If you want to remove regional disk,
// you should use: RegionDisksClient and RegionOperationsClient.
// Instantiate a disksClient
const disksClient = new computeLib.DisksClient();
// Instantiate a zone
const zoneOperationsClient = new computeLib.ZoneOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The project that contains the disk.
const projectId = await disksClient.getProjectId();

// The name of the disk.
// diskName = 'disk-name';

// If you use RegionDisksClient- define region, if DisksClient- define zone.
// The zone or region of the disk.
// diskLocation = 'europe-central2-a';

// The name of the consistency group.
// consistencyGroupName = 'consistency-group-name';

// The region of the consistency group.
// consistencyGroupLocation = 'europe-central2';

async function callDeleteDiskFromConsistencyGroup() {
  const [response] = await disksClient.removeResourcePolicies({
    disk: diskName,
    project: projectId,
    // If you use RegionDisksClient, pass region as an argument instead of zone.
    zone: diskLocation,
    disksRemoveResourcePoliciesRequestResource:
      new compute.DisksRemoveResourcePoliciesRequest({
        resourcePolicies: [
          `https://www.googleapis.com/compute/v1/projects/${projectId}/regions/${consistencyGroupLocation}/resourcePolicies/${consistencyGroupName}`,
        ],
      }),
  });

  let operation = response.latestResponse;

  // Wait for the delete disk operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await zoneOperationsClient.wait({
      operation: operation.name,
      project: projectId,
      // If you use RegionDisksClient, pass region as an argument instead of zone.
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log(
    `Disk: ${diskName} deleted from consistency group: ${consistencyGroupName}.`
  );
}

await callDeleteDiskFromConsistencyGroup();

Python

from google.cloud import compute_v1


def remove_disk_consistency_group(
    project_id: str,
    disk_name: str,
    disk_location: str,
    consistency_group_name: str,
    consistency_group_region: str,
) -> None:
    """Removes a disk from a specified consistency group.
    Args:
        project_id (str): The ID of the Google Cloud project.
        disk_name (str): The name of the disk to be deleted.
        disk_location (str): The region or zone of the disk
        consistency_group_name (str): The name of the consistency group.
        consistency_group_region (str): The region of the consistency group.
    Returns:
        None
    """
    consistency_group_link = (
        f"regions/{consistency_group_region}/resourcePolicies/{consistency_group_name}"
    )
    # Checking if the disk is zonal or regional
    # If the final character of the disk_location is a digit, it is a regional disk
    if disk_location[-1].isdigit():
        policy = compute_v1.RegionDisksRemoveResourcePoliciesRequest(
            resource_policies=[consistency_group_link]
        )
        disk_client = compute_v1.RegionDisksClient()
        disk_client.remove_resource_policies(
            project=project_id,
            region=disk_location,
            disk=disk_name,
            region_disks_remove_resource_policies_request_resource=policy,
        )
    # For zonal disks we use DisksClient
    else:
        policy = compute_v1.DisksRemoveResourcePoliciesRequest(
            resource_policies=[consistency_group_link]
        )
        disk_client = compute_v1.DisksClient()
        disk_client.remove_resource_policies(
            project=project_id,
            zone=disk_location,
            disk=disk_name,
            disks_remove_resource_policies_request_resource=policy,
        )

    print(f"Disk {disk_name} removed from consistency group {consistency_group_name}")

REST

כדי להסיר דיסק מקבוצת עקביות, משתמשים בשיטה disks.removeResourcePolicies לדיסקים אזוריים או בשיטה regionDisks.removeResourcePolicies לדיסקים אזוריים.

  • כדי להסיר דיסק אזורי מקבוצת עקביות:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT/zones/LOCATION/disks/DISK_NAME/removeResourcePolicies
    
    {
    "resourcePolicies": "CONSISTENCY_GROUP"
    }
    
  • כדי להסיר דיסק אזורי מקבוצת עקביות:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT/regions/LOCATION/disks/DISK_NAME/removeResourcePolicies
    
    {
    "resourcePolicies": "CONSISTENCY_GROUP"
    }
    

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

  • PROJECT: הפרויקט שמכיל את הדיסק.
  • LOCATION: האזור או האזור של הדיסק. בדיסקים אזוריים, משתמשים באזור. לדיסקים אזוריים, משתמשים באזור.
  • DISK_NAME: השם של הדיסק שרוצים להסיר מקבוצת האפליקציות העקביות.
  • CONSISTENCY_GROUP: כתובת ה-URL של קבוצת העקביות. לדוגמה, projects/PROJECT/regions/REGION/resourcePolicies/CONSISTENCY_GROUP_NAME.

מחיקת קבוצת עקביות

מחיקת קבוצת אפליקציות עקביות באמצעות Google Cloud המסוף, Google Cloud CLI או REST.

המסוף

כדי למחוק עקביות:

  1. נכנסים לדף Consistency Groups במסוף Google Cloud .

    כניסה לדף Consistency Groups

  2. לוחצים על הכרטיסייה קבוצות עקביות של דיסקים.

  3. בוחרים את קבוצת העקביות שרוצים למחוק.

  4. לוחצים על Delete. ייפתח החלון מחיקת קבוצת עקביות.

  5. לוחצים על Delete.

gcloud

מוחקים את מדיניות המשאבים באמצעות הפקודה gcloud compute resource-policies delete:

gcloud compute resource-policies delete CONSISTENCY_GROUP \
    --region=REGION

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

  • CONSISTENCY_GROUP: השם של קבוצת העקביות
  • REGION: האזור של קבוצת אפליקציות עקביות

המשך

import (
	"context"
	"fmt"
	"io"

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

// deleteConsistencyGroup deletes consistency group for a project in a given region.
func deleteConsistencyGroup(w io.Writer, projectID, region, groupName string) error {
	// projectID := "your_project_id"
	// region := "europe-west4"
	// groupName := "your_group_name"

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

	req := &computepb.DeleteResourcePolicyRequest{
		Project:        projectID,
		ResourcePolicy: groupName,
		Region:         region,
	}

	op, err := disksClient.Delete(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to delete group: %w", err)
	}

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

	fmt.Fprintf(w, "Group deleted\n")

	return nil
}

Java

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

public class DeleteConsistencyGroup {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String project = "YOUR_PROJECT_ID";
    // Region in which your consistency group is located.
    String region = "us-central1";
    // Name of the consistency group you want to delete.
    String consistencyGroupName = "YOUR_CONSISTENCY_GROUP_NAME";

    deleteConsistencyGroup(project, region, consistencyGroupName);
  }

  // Deletes a consistency group resource policy in the specified project and region.
  public static Status deleteConsistencyGroup(
      String project, String region, String consistencyGroupName)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.create()) {
      Operation response = resourcePoliciesClient
          .deleteAsync(project, region, consistencyGroupName).get(1, TimeUnit.MINUTES);

      if (response.hasError()) {
        throw new Error("Error deleting disk! " + response.getError());
      }
      return response.getStatus();
    }
  }
}

Node.js


// Import the Compute library
const computeLib = require('@google-cloud/compute');

// Instantiate a resourcePoliciesClient
const resourcePoliciesClient = new computeLib.ResourcePoliciesClient();
// Instantiate a regionOperationsClient
const regionOperationsClient = new computeLib.RegionOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The project that contains the consistency group.
const projectId = await resourcePoliciesClient.getProjectId();

// The region of the consistency group.
// region = 'europe-central2';

// The name of the consistency group.
// consistencyGroupName = 'consistency-group-name';

async function callDeleteConsistencyGroup() {
  // Delete a resourcePolicyResource
  const [response] = await resourcePoliciesClient.delete({
    project: projectId,
    region,
    resourcePolicy: consistencyGroupName,
  });

  let operation = response.latestResponse;

  // Wait for the delete group operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await regionOperationsClient.wait({
      operation: operation.name,
      project: projectId,
      region,
    });
  }

  console.log(`Consistency group: ${consistencyGroupName} deleted.`);
}

await callDeleteConsistencyGroup();

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 delete_consistency_group(project_id: str, region: str, group_name: str) -> None:
    """
    Deletes a consistency group in Google Cloud Compute Engine.
    Args:
        project_id (str): The ID of the Google Cloud project.
        region (str): The region where the consistency group is located.
        group_name (str): The name of the consistency group to delete.
    Returns:
        None
    """

    # Initialize the ResourcePoliciesClient
    client = compute_v1.ResourcePoliciesClient()

    # Delete the (consistency group) from the specified project and region
    operation = client.delete(
        project=project_id,
        region=region,
        resource_policy=group_name,
    )
    wait_for_extended_operation(operation, "Consistency group deletion")

REST

כדי למחוק עקביות, משתמשים בשיטה resourcePolicies.delete:

DELETE https://compute.googleapis.com/compute/v1/projects/PROJECT/regions/REGION/resourcePolicies/CONSISTENCY_GROUP_NAME

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

  • PROJECT: הפרויקט שמכיל את קבוצת העקביות
  • REGION: האזור של קבוצת אפליקציות עקביות
  • CONSISTENCY_GROUP: השם של קבוצת העקביות

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