管理增强型复制

转到概念

本页面介绍如何在双区域存储桶上使用增强型复制功能。

前提条件

前提条件因所使用的工具而异:

控制台

如需使用 Google Cloud Console 完成本指南,您必须拥有适当的 IAM 权限。如需使用此功能,您必须在双区域位置拥有或打算创建一个存储桶。如果您要访问的存储桶在不是由您创建的项目中,则可能需要项目所有者为您提供具有必要权限的角色。

如需查看特定操作所需权限的列表,请参阅 Google Cloud Console 的 IAM 权限

如需查看相关角色的列表,请参阅 Cloud Storage 角色。或者,您也可以创建一个自定义角色,并为其提供具体受限的权限。

命令行

为使用命令行实用程序完成本指南,您必须拥有适当的 IAM 权限。如需使用此功能,您必须在双区域位置拥有或打算创建一个存储桶。如果您要访问的存储桶在不是由您创建的项目中,则可能需要项目所有者为您提供具有必要权限的角色。

如需查看特定操作所需权限的列表,请参阅 gsutil 命令的 IAM 权限

如需查看相关角色的列表,请参阅 Cloud Storage 角色。或者,您也可以创建一个自定义角色,并为其提供具体受限的权限。

代码示例

如需使用 Cloud Storage 客户端库完成本指南,您必须拥有适当的 IAM 权限。如需使用此功能,您必须在双区域位置拥有或打算创建一个存储桶。如果您要访问的存储桶在不是由您创建的项目中,则可能需要项目所有者为您提供具有必要权限的角色。除非另有说明,否则客户端库请求通过 JSON API 发出。

如需查看特定操作所需的权限列表,请参阅 JSON 方法的 IAM 权限

如需查看相关角色的列表,请参阅 Cloud Storage 角色。或者,您也可以创建一个自定义角色,并为其提供具体受限的权限。

REST API

JSON API

如需使用 JSON API 完成本指南,您必须拥有适当的 IAM 权限。如需使用此功能,您必须在双区域位置拥有或打算创建一个存储桶。如果您要访问的存储桶在不是由您创建的项目中,则可能需要项目所有者为您提供具有必要权限的角色。

如需查看特定操作所需的权限列表,请参阅 JSON 方法的 IAM 权限

如需查看相关角色的列表,请参阅 Cloud Storage 角色。或者,您也可以创建一个自定义角色,并为其提供具体受限的权限。

XML API

此功能无法通过 XML API 进行管理。请改用 JSON API。

检查存储桶的复制状态

如需检查存储桶的恢复点目标 (RPO) 或复制状态,请按照以下说明操作:

控制台

  1. 在 Google Cloud Console 中,转到 Cloud Storage 的浏览器页面。

    转到浏览器

  2. 在存储桶列表中,点击要验证的存储桶的名称。

  3. 点击配置标签页。

  4. 如果该存储桶启用了增强型复制,则复制会设置为增强型

命令行

使用 gsutil rpo get 命令:

gsutil rpo get gs://BUCKET_NAME/

其中:

  • BUCKET_NAME 是相关存储分区的名称, 例如 my-bucket

如果成功,则响应类似如下示例:

gs://my-bucket: ASYNC_TURBO

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto metadata = client.GetBucketMetadata(bucket_name);
  if (!metadata) throw std::runtime_error(metadata.status().message());

  std::cout << "RPO is " << metadata->rpo() << " for bucket "
            << metadata->name() << "\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档


using System;
using Google.Cloud.Storage.V1;

public class GetRpoSample
{
    public string GetRpo(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var rpo = storage.GetBucket(bucketName).Rpo;
        Console.WriteLine($"The RPO Setting of bucket {bucketName} is {rpo}.");

        return rpo;
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// getRPO gets the current RPO (Recovery Point Objective) setting
// for the bucket, either "DEFAULT" or "ASYNC_TURBO".
func getRPO(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Attrs: %v", bucketName, err)
	}
	fmt.Fprintf(w, "RPO is %s for %v", attrs.RPO, bucketName)
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class GetBucketRpo {
  public static void getBucketRpo(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    String rpo = bucket.getRpo().toString();

    System.out.println("The RPO setting of bucket " + bucketName + " is " + rpo);
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The name of your GCS bucket in a dual-region
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getRPO() {
  // Gets Bucket Metadata and prints RPO value (either 'default' or 'async_turbo').
  // If RPO is undefined, the bucket is a single region bucket
  const [metadata] = await storage.bucket(bucketName).getMetadata();
  console.log(`RPO is ${metadata.rpo} for ${bucketName}.`);
}

getRPO();

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Get the bucket's recovery point objective (RPO) setting.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function get_rpo($bucketName)
{
    // $bucketName = 'my-bucket';

    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    printf(
        'The bucket\'s RPO value is: %s.' . PHP_EOL,
        $bucket->info()['rpo']
    );
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档


from google.cloud import storage
from google.cloud.storage.constants import RPO_DEFAULT

def get_rpo(bucket_name):
    """Gets the RPO of the bucket"""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    bucket.rpo = RPO_DEFAULT
    rpo = bucket.rpo

    print(f"RPO for {bucket.name} is {rpo}.")

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

def get_rpo bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  puts "The RPO setting of bucket '#{bucket_name}' is #{bucket.rpo}."
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。 如需了解相关说明,请参阅 API 身份验证
  2. 使用 cURL,通过 GET Bucket 请求调用 JSON API

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=rpo"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

    响应如下例所示:

    {
      "name": "my-bucket",
      "projectNumber": "234...",
      ...
      "rpo": "ASYNC_TURBO"
    }

    请注意 rpo 键。值 ASYNC_TURBO 表示已启用增强型复制。DEFAULT 表示已应用默认复制。双区域和多区域存储桶中始终存在 rpo 字段,但单区域存储桶中不存在该字段。

XML API

此功能无法通过 XML API 进行管理。请改用 JSON API。

设置增强型复制

如需在现有存储桶上启用或停用增强型复制,请按照以下说明操作:

控制台

  1. 在 Google Cloud Console 中,转到 Cloud Storage 的浏览器页面。

    转到浏览器

  2. 在存储桶列表中,点击所需存储桶的名称。

  3. 点击配置标签页。

  4. 复制行中,点击 修改

    随即显示的窗口表示您要启用增强型复制还是停用增强型复制

  5. 点击保存以确认新设置。

命令行

使用 gsutil rpo set 命令:

gsutil rpo set STATE gs://BUCKET_NAME/

其中:

  • STATEASYNC_TURBO(用于启用 Turbo 复制)或 DEFAULT(用于停用 Turbo 复制)。

  • BUCKET_NAME 是相关存储分区的名称, 例如 my-bucket

如果成功,则不会返回响应。更改会立即生效。

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

以下示例会在存储桶上启用增强型复制:

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto updated = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetRpo(gcs::RpoAsyncTurbo()));
  if (!updated) throw std::runtime_error(updated.status().message());

  std::cout << "RPO is set to 'ASYNC_TURBO' for " << updated->name() << "\n";
}

以下示例会在存储桶上启用默认复制:

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto updated = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetRpo(gcs::RpoDefault()));
  if (!updated) throw std::runtime_error(updated.status().message());

  std::cout << "RPO is set to 'default' for " << updated->name() << "\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

以下示例会在存储桶上启用增强型复制:

// Copyright 2021 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using Google.Cloud.Storage.V1;

public class SetRpoAsyncTurboSample
{
    public void SetRpoAsyncTurbo(string bucketName = "your-unique-bucket-name")
    {
        // Enabling turbo replication requires a bucket with dual-region configuration
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.Rpo = "ASYNC_TURBO";
        storage.UpdateBucket(bucket);

        Console.WriteLine($"Turbo replication enabled for bucket {bucketName}");
    }
}

以下示例会在存储桶上启用默认复制:

// Copyright 2021 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using Google.Cloud.Storage.V1;

public class SetRpoDefaultSample
{
    public void SetRpoDefault(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.Rpo = "DEFAULT";
        storage.UpdateBucket(bucket);

        Console.WriteLine($"Turbo replication disabled for bucket {bucketName}");
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

以下示例会在存储桶上启用增强型复制:

// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package buckets

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// setRPOAsyncTurbo enables turbo replication for the bucket by setting RPO to
// "ASYNC_TURBO". The bucket must be dual-region to use this feature.
func setRPOAsyncTurbo(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	setRPO := storage.BucketAttrsToUpdate{
		RPO: storage.RPOAsyncTurbo,
	}
	if _, err := bucket.Update(ctx, setRPO); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Turbo replication enabled for %v", bucketName)
	return nil
}

以下示例会在存储桶上启用默认复制:

// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package buckets

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// setRPODefault disables turbo replication for the bucket by setting RPO to
// "DEFAULT".
func setRPODefault(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	setRPO := storage.BucketAttrsToUpdate{
		RPO: storage.RPODefault,
	}
	if _, err := bucket.Update(ctx, setRPO); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Turbo replication disabled for %v", bucketName)
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

以下示例会在存储桶上启用增强型复制:

/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.storage.bucket;

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Rpo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetAsyncTurboRpo {
  public static void setAsyncTurboRpo(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);

    bucket.toBuilder().setRpo(Rpo.ASYNC_TURBO).build().update();

    System.out.println("Turbo replication was enabled for " + bucketName);
  }
}

以下示例会在存储桶上启用默认复制:

/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.storage.bucket;

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Rpo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetDefaultRpo {
  public static void setDefaultRpo(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);

    bucket.toBuilder().setRpo(Rpo.DEFAULT).build().update();

    System.out.println("Replication was set to default for " + bucketName);
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

以下示例会在存储桶上启用增强型复制:

// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * This application demonstrates how to perform basic operations on buckets with
 * the Google Cloud Storage API.
 *
 * For more information, see the README.md under /storage and the documentation
 * at https://cloud.google.com/storage/docs.
 */

function main(bucketName = 'my-bucket') {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // The name of your GCS bucket in a dual-region
  // const bucketName = 'Name of a bucket, e.g. my-bucket';

  // Imports the Google Cloud client library
  const {Storage} = require('@google-cloud/storage');

  // Creates a client
  const storage = new Storage();

  // Enable turbo replication for the bucket by setting rpo to ASYNC_TURBO.
  // The bucket must be a dual-region bucket.
  async function setRPOAsyncTurbo() {
    await storage.bucket(bucketName).setMetadata({
      rpo: 'ASYNC_TURBO',
    });

    console.log(`Turbo replication enabled for ${bucketName}.`);
  }

  setRPOAsyncTurbo();
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));

以下示例会在存储桶上启用默认复制:

// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * This application demonstrates how to perform basic operations on buckets with
 * the Google Cloud Storage API.
 *
 * For more information, see the README.md under /storage and the documentation
 * at https://cloud.google.com/storage/docs.
 */

function main(bucketName = 'my-bucket') {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // The name of your GCS bucket in a dual-region
  // const bucketName = 'Name of a bucket, e.g. my-bucket';

  // Imports the Google Cloud client library
  const {Storage} = require('@google-cloud/storage');

  // Creates a client
  const storage = new Storage();

  // Disable turbo replication for the bucket by setting RPO to default.
  // The bucket must be a dual-region bucket.
  async function setRPODefault() {
    await storage.bucket(bucketName).setMetadata({
      rpo: 'DEFAULT',
    });

    console.log(`Turbo replication disabled for ${bucketName}.`);
  }

  setRPODefault();
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

以下示例会在存储桶上启用增强型复制:

<?php
/**
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * For instructions on how to run the full sample:
 *
 * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/storage/README.md
 */

namespace Google\Cloud\Samples\Storage;

use Google\Cloud\Storage\StorageClient;

/**
 * Set the bucket's Turbo Replication(rpo) setting to `ASYNC_TURBO`.
 * The bucket must be a dual-region bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function set_rpo_async_turbo($bucketName)
{
    // $bucketName = 'my-bucket';

    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $rpo = 'ASYNC_TURBO';

    $bucket->update([
        'rpo' => $rpo
    ]);

    printf(
        'The replication behavior or recovery point objective (RPO) has been set to ASYNC_TURBO for %s.' . PHP_EOL,
        $bucketName
    );
}

// The following 2 lines are only needed to run the samples
require_once __DIR__ . '/../../testing/sample_helpers.php';
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

以下示例会在存储桶上启用默认复制:

<?php
/**
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * For instructions on how to run the full sample:
 *
 * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/storage/README.md
 */

namespace Google\Cloud\Samples\Storage;

use Google\Cloud\Storage\StorageClient;

/**
 * Set the bucket's replication behavior or recovery point objective (RPO) to `DEFAULT`.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function set_rpo_default($bucketName)
{
    // $bucketName = 'my-bucket';

    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $rpo = 'DEFAULT';

    // Updating the rpo value of a multi-region bucket to DEFAULT has no effect
    // and updating the rpo value of a regional bucket will throw an exception.
    $bucket->update([
        'rpo' => $rpo
    ]);

    printf(
        'The replication behavior or recovery point objective (RPO) has been set to DEFAULT for %s.' . PHP_EOL,
        $bucketName
    );
}

// The following 2 lines are only needed to run the samples
require_once __DIR__ . '/../../testing/sample_helpers.php';
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

以下示例会在存储桶上启用增强型复制:

#!/usr/bin/env python

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

"""Sample that sets RPO (Recovery Point Objective) to ASYNC_TURBO
This sample is used on this page:
    https://cloud.google.com/storage/docs/managing-turbo-replication
For more information, see README.md.
"""

from google.cloud import storage
from google.cloud.storage.constants import RPO_ASYNC_TURBO

def set_rpo_async_turbo(bucket_name):
    """Sets the RPO to ASYNC_TURBO, enabling the turbo replication feature"""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    bucket.rpo = RPO_ASYNC_TURBO
    bucket.patch()

    print(f"RPO is set to ASYNC_TURBO for {bucket.name}.")

if __name__ == "__main__":
    set_rpo_async_turbo(bucket_name=sys.argv[1])

以下示例会在存储桶上启用默认复制:

#!/usr/bin/env python

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

"""Sample that sets the replication behavior or recovery point objective (RPO) to default.
This sample is used on this page:
    https://cloud.google.com/storage/docs/managing-turbo-replication
For more information, see README.md.
"""

from google.cloud import storage
from google.cloud.storage.constants import RPO_DEFAULT

def set_rpo_default(bucket_name):
    """Sets the RPO to DEFAULT, disabling the turbo replication feature"""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    bucket.rpo = RPO_DEFAULT
    bucket.patch()

    print(f"RPO is set to DEFAULT for {bucket.name}.")

if __name__ == "__main__":
    set_rpo_default(bucket_name=sys.argv[1])

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

以下示例会在存储桶上启用增强型复制:

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

def set_rpo_async_turbo bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name,
                           location: "ASIA"

  bucket.rpo = :ASYNC_TURBO

  puts "Turbo replication is enabled for #{bucket_name}."
end

set_rpo_async_turbo bucket_name: ARGV.shift if $PROGRAM_NAME == __FILE__

以下示例会在存储桶上启用默认复制:

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

def set_rpo_default bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.rpo = :DEFAULT

  puts "The replication behavior or recovery point objective (RPO) for #{bucket_name} is set to default."
end

set_rpo_default bucket_name: ARGV.shift if $PROGRAM_NAME == __FILE__

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。 如需了解相关说明,请参阅 API 身份验证
  2. 创建一个包含以下信息的 JSON 文件:

    {
      "rpo": "STATE"
    }

    其中,STATEASYNC_TURBO(用于启用 Turbo 复制)或 DEFAULT(用于停用 Turbo 复制)。

  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API

    curl -X PATCH --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=rpo"

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的 JSON 文件的路径。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

    如果请求成功,则不会返回任何响应。

XML API

此功能无法通过 XML API 进行管理。请改用 JSON API。

创建具有增强型复制功能的双区域存储桶

如需创建启用了增强型复制的新双区域存储桶,请按照以下说明操作:

控制台

  1. 在 Google Cloud Console 中,转到 Cloud Storage 的浏览器页面。

    转到浏览器

  2. 点击创建存储分区

  3. 创建存储分区页面上,输入您的存储分区信息。如需转到下一步,请点击继续

    1. 指定存储桶的名称部分,输入符合存储桶命名要求的名称。

    2. 选择数据存储位置部分,选择位置类型旁边的双区域,然后选中添加增强型复制功能复选框。

    3. 位置部分,选择一个可用的双区域。

    4. 为数据选择一个默认存储类别部分,为存储桶选择一个存储类别。默认情况下,系统会为上传到存储桶的所有对象分配该默认存储类别。

    5. 选择如何控制对对象的访问权限部分,选择访问权限控制选项。访问权限控制模型决定了如何控制对存储桶对象的访问权限

    6. 高级设置(可选)部分,添加存储桶标签,设置保留政策并选择 加密方法

  4. 点击创建

    如需了解如何获取有关 Cloud Storage 浏览器中失败操作的详细错误信息,请参阅问题排查

命令行

使用 gsutil mb --rpo 命令:

gsutil mb -l LOCATION -c CLASS --rpo REPLICATION_TYPE gs://BUCKET_NAME/

其中:

  • LOCATION 指定存储桶的地理位置。如果未指定位置,则默认为 US 多区域。在此示例中,请指定双区域位置。例如 nam4

  • CLASS 指定存储类别。例如 NEARLINE

  • REPLICATION_TYPE 指定双区域和多区域存储桶的复制设置。DEFAULT 值表示默认复制,是双区域或多区域存储桶的有效选项。ASYNC_TURBO 表示增强型复制,是许多双区域存储桶的有效选项。如果未指定,则默认复制设置为默认复制。在此示例中,请使用 ASYNC_TURBO

  • BUCKET_NAME 是相关存储分区的名称, 例如 my-bucket

    如果请求成功,该命令将返回以下消息:

    Creating gs://BUCKET_NAME/...

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto bucket =
      client.CreateBucket(bucket_name, gcs::BucketMetadata()
                                           .set_rpo(gcs::RpoAsyncTurbo())
                                           .set_location("NAM4"));
  if (!bucket) throw std::runtime_error(bucket.status().message());

  std::cout << "Created bucket " << bucket->name() << " with RPO set to "
            << bucket->rpo() << " in " << bucket->location() << ".\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class CreateBucketWithTurboReplicationSample
{
    public Bucket CreateBucketWithTurboReplication(
        string projectId = "your-project-id",
        string location = "your-bucket-location",
        string bucketName = "bucket-name")
    {
        var storage = StorageClient.Create();
        // Enabling turbo replication requires a bucket with dual-region configuration
        var bucket = storage.CreateBucket(projectId, new Bucket { Name = bucketName , Location = location, Rpo = "ASYNC_TURBO" });

        Console.WriteLine($"Created {bucket.Name} in {bucket.Location} with RPO Setting {bucket.Rpo}.");
        return bucket;
    }

}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// createBucketTurboReplication creates a new dual-region bucket with
// turbo replication enabled.
func createBucketTurboReplication(w io.Writer, projectID, bucketName, location string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	// location := "NAM4" // the name of a dual-region location
	// See this documentation for other valid locations:
	// https://cloud.google.com/storage/docs/locations#location-dr

	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	storageLocationAndRPO := &storage.BucketAttrs{
		Location: location,
		RPO:      storage.RPOAsyncTurbo,
	}
	bucket := client.Bucket(bucketName)
	if err := bucket.Create(ctx, projectID, storageLocationAndRPO); err != nil {
		return fmt.Errorf("Bucket(%q).Create: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Created bucket %v with turbo replication in %v\n", bucketName, storageLocationAndRPO.Location)
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Rpo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class CreateBucketWithTurboReplication {
  public static void createBucketWithTurboReplication(
      String projectId, String bucketName, String location) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The dual-region location to create your bucket in
    // String location = "NAM4"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Bucket bucket =
        storage.create(
            BucketInfo.newBuilder(bucketName)
                .setLocation(location)
                .setRpo(Rpo.ASYNC_TURBO)
                .build());

    System.out.println(
        "Created bucket "
            + bucket.getName()
            + " in "
            + bucket.getLocation()
            + " with RPO setting"
            + bucket.getRpo());
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The name of a dual-region location
// See this documentation for other valid locations:
// https://cloud.google.com/storage/docs/locations#location-dr
// const location = 'NAM4';

// Flag to enable turbo replication for this bucket
const rpo = 'ASYNC_TURBO';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
// The bucket in the sample below will be created in the project associated with this client.
// For more information, please see https://cloud.google.com/docs/authentication/production or https://googleapis.dev/nodejs/storage/latest/Storage.html
const storage = new Storage();

async function createBucketWithTurboReplication() {
  // For default values see: https://cloud.google.com/storage/docs/locations and
  // https://cloud.google.com/storage/docs/storage-classes
  const [bucket] = await storage.createBucket(bucketName, {
    location,
    rpo,
  });

  console.log(
    `${bucket.name} created with the recovery point objective (RPO) set to ${rpo} in ${location}.`
  );
}

createBucketWithTurboReplication();

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Create a Cloud Storage bucket with the recovery point objective (RPO) set to `ASYNC_TURBO`.
 * The bucket must be a dual-region bucket for this setting to take effect.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * @param string $location The Dual-Region location where you want your bucket to reside (e.g. "US-CENTRAL1+US-WEST1").
                                           Read more at https://cloud.google.com/storage/docs/locations#location-dr
 */
function create_bucket_turbo_replication($bucketName, $location = 'nam4')
{
    // $bucketName = 'my-bucket';

    $storage = new StorageClient();
    $rpo = 'ASYNC_TURBO';

    // providing a location which is a dual-region location
    // makes sure the locationType is set to 'dual-region' implicitly
    // we can pass 'locationType' => 'dual-region'
    // to make it explicit
    $bucket = $storage->createBucket($bucketName, [
        'location' => $location,
        'rpo' => $rpo
    ]);
    printf('Bucket with recovery point objective (RPO) set to \'ASYNC_TURBO\' created: %s' . PHP_EOL, $bucket->name());
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档


from google.cloud import storage
from google.cloud.storage.constants import RPO_ASYNC_TURBO

def create_bucket_turbo_replication(bucket_name):
    """Creates dual-region bucket with turbo replication enabled."""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    bucket.location = "NAM4"
    bucket.rpo = RPO_ASYNC_TURBO
    bucket.create()

    print(f"{bucket.name} created with the recovery point objective (RPO) set to {bucket.rpo} in {bucket.location}.")

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

def create_bucket_turbo_replication bucket_name:
  # The ID to give your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.create_bucket bucket_name,
                                  location: "ASIA1",
                                  rpo:      "ASYNC_TURBO"

  puts "Created bucket #{bucket.name} in #{bucket.location} with "
  + "the recovery point objective (RPO) set to #{bucket.rpo}."
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。 如需了解相关说明,请参阅 API 身份验证
  2. 创建一个包含存储桶的设置的 JSON 文件,其中必须包含存储桶的 name。如需查看完整的设置列表,请参阅 Buckets:Insert 文档。以下是一些常用的设置,包括:

    {
      "name": "BUCKET_NAME",
      "rpo": "REPLICATION_TYPE",
      "location": "BUCKET_LOCATION",
      "storageClass": "STORAGE_CLASS",
      "iamConfiguration": {
        "uniformBucketLevelAccess": {
          "enabled": true
        },
      }
    }

    其中:

    • BUCKET_NAME 是您要为自己的存储桶指定的名称(须遵循命名要求),例如 my-bucket
    • REPLICATION_TYPE 指定双区域和多区域存储桶的复制设置。DEFAULT 值表示默认复制,是双区域或多区域存储桶的有效选项。ASYNC_TURBO 表示增强型复制,是大多数双区域存储桶的有效选项。如果未指定,则默认复制设置为默认复制。在此示例中,请使用 ASYNC_TURBO
    • BUCKET_LOCATION 是您要用于存储自己的存储桶对象数据位置。由于您要创建启用了增强型复制的存储桶,并且存储桶的地理位置一旦创建便无法更改,因此请指定双区域。例如 NAM4
    • STORAGE_CLASS 是您的存储桶的默认存储类别,例如 NEARLINE
  3. 使用 cURL 调用 JSON API

    curl -X POST --data-binary @JSON_FILE_NAME \
     -H "Authorization: Bearer OAUTH2_TOKEN" \
     -H "Content-Type: application/json" \
     "https://storage.googleapis.com/storage/v1/b?project=PROJECT_ID"

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的 JSON 文件的路径。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • PROJECT_ID 是将与您的存储桶相关联的项目的 ID,例如 my-project

XML API

此功能无法通过 XML API 进行管理。请改用 JSON API。

监控存储桶的增强型复制性能

  1. 在 Google Cloud Console 中,转到 Cloud Storage 的浏览器页面。

    转到浏览器

  2. 在存储桶列表中,点击所需存储桶的名称。

  3. 点击配置标签页。

  4. 复制行中,点击查看复制指标

    如果复制对象用时超过 15 分钟,则系统会汇总额外的分钟数并在 Cloud Console 中显示为缺少 RPO 的分钟数。Cloud Console 还会跟踪已完成的对象复制的数量,显示为使用增强型功能复制对象的次数

    如需了解详情,请参阅了解 RTO 和 RPO

后续步骤