使用对象保全

转到概念

本页面介绍了如何使用对象保全,包括默认情况下将保全放置在新对象上,以及将保全放置在个别对象上。

前提条件

在 Cloud Storage 中使用此功能之前,您应该:

  1. 拥有足够的权限来查看和更新 Cloud Storage 中的存储分区和对象:

    • 如果您拥有存储分区所属的项目,则您很可能具备所需的权限。

    • 如果您使用了 IAM,您应在相关存储分区上具有 storage.buckets.updatestorage.buckets.getstorage.objects.updatestorage.objects.get 权限。如需了解如何获取具有这些权限的角色(例如 Storage Admin),请参阅使用 IAM 权限

    • 如果使用 ACL,您应对相关存储分区及其中的对象具有 OWNER 权限。有关如何执行此操作的说明,请参阅设置 ACL

使用默认的基于事件的保全属性

以下任务介绍了如何在存储分区上启用、查看和停用默认的基于事件的保全属性。启用此属性后,系统会自动在添加到存储分区的新对象上放置基于事件的保全。

启用默认的基于事件的保全属性

要自动在添加到存储分区的每个新对象上放置基于事件的保全,请执行以下操作:

控制台

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

    转到浏览器

  2. 在存储分区列表中,找到要为其启用默认的基于事件的保全属性的存储分区,并点击其名称。

  3. 选择页面顶部附近的保留标签页。

  4. 在“基于事件的默认保全选项”部分中,点击已停用按钮。

    如果成功,该按钮的相应文字将变为已启用

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

gsutil

使用 gsutil retention event-default set 命令:

gsutil retention event-default set gs://BUCKET_NAME

其中 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) {
  StatusOr<gcs::BucketMetadata> original =
      client.GetBucketMetadata(bucket_name);

  if (!original) throw std::runtime_error(original.status().message());
  StatusOr<gcs::BucketMetadata> patched_metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetDefaultEventBasedHold(true),
      gcs::IfMetagenerationMatch(original->metageneration()));

  if (!patched_metadata) {
    throw std::runtime_error(patched_metadata.status().message());
  }

  std::cout << "The default event-based hold for objects in bucket "
            << bucket_name << " is "
            << (patched_metadata->default_event_based_hold() ? "enabled"
                                                             : "disabled")
            << "\n";
}

C#

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


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

public class EnableBucketDefaultEventBasedHoldSample
{
    public Bucket EnableBucketDefaultEventBasedHold(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.DefaultEventBasedHold = true;
        bucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Default event-based hold was enabled for {bucketName}");
        return bucket;
    }
}

Go

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

ctx := context.Background()

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	DefaultEventBasedHold: true,
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Java

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

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

Bucket bucket =
    storage.update(BucketInfo.newBuilder(bucketName).setDefaultEventBasedHold(true).build());

System.out.println("Default event-based hold was enabled for " + bucketName);

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

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

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

async function enableDefaultEventBasedHold() {
  // Enables a default event-based hold for the bucket.
  await storage.bucket(bucketName).setMetadata({
    defaultEventBasedHold: true,
  });

  console.log(`Default event-based hold was enabled for ${bucketName}.`);
}

enableDefaultEventBasedHold().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Enables a default event-based hold for a bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function enable_default_event_based_hold($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update(['defaultEventBasedHold' => true]);
    printf('Default event-based hold was enabled for %s' . PHP_EOL, $bucketName);
}

Python

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

from google.cloud import storage

def enable_default_event_based_hold(bucket_name):
    """Enables the default event based hold on a given bucket"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    bucket.default_event_based_hold = True
    bucket.patch()

    print("Default event based hold was enabled for {}".format(bucket_name))

Ruby

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

def enable_default_event_based_hold 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.update do |b|
    b.default_event_based_hold = true
  end

  puts "Default event-based hold was enabled for #{bucket_name}."
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件:

    {
      "defaultEventBasedHold": true
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API:

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

    其中:

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

XML API

XML API 不能用于处理对象保全。请改用其他 Cloud Storage 工具,例如 gsutil。

获取存储分区的默认保全状态

要查看默认情况下存储分区是否在新对象上放置基于事件的保全,请执行以下操作:

控制台

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

    转到浏览器

  2. 在存储分区列表中,找到要为其检查默认的基于事件的状态的存储分区,并点击其名称。

  3. 选择页面顶部附近的保留标签页。

  4. 状态会显示在“基于事件的默认保全选项”部分中。

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

gsutil

使用以下 gsutil ls 命令:

gsutil ls -L -b gs://BUCKET_NAME

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

响应如下例所示:

gs://my-bucket/ :
  Storage class:         STANDARD
  ...
  ...
  Default Event-Based Hold: True
  ...

默认情况下,如果存储分区没有在新对象上放置基于事件的保全,则 gsutil 会完全省略输出中的 Default Event-Based Hold

代码示例

C++

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name);

  if (!bucket_metadata) {
    throw std::runtime_error(bucket_metadata.status().message());
  }

  std::cout << "The default event-based hold for objects in bucket "
            << bucket_metadata->name() << " is "
            << (bucket_metadata->default_event_based_hold() ? "enabled"
                                                            : "disabled")
            << "\n";
}

C#

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


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

public class GetDefaultEventBasedHoldSample
{
    public bool GetDefaultEventBasedHold(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bool defaultEventBasedHold = bucket.DefaultEventBasedHold ?? false;
        Console.WriteLine($"Default event-based hold: {defaultEventBasedHold}");
        return defaultEventBasedHold;
    }
}

Go

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

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return nil, err
}
log.Printf("Default event-based hold enabled? %t\n",
	attrs.DefaultEventBasedHold)

Java

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

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

Bucket bucket =
    storage.get(bucketName, BucketGetOption.fields(BucketField.DEFAULT_EVENT_BASED_HOLD));

if (bucket.getDefaultEventBasedHold() != null && bucket.getDefaultEventBasedHold()) {
  System.out.println("Default event-based hold is enabled for " + bucketName);
} else {
  System.out.println("Default event-based hold is not enabled for " + bucketName);
}

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

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

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

async function getDefaultEventBasedHold() {
  const [metadata] = await storage.bucket(bucketName).getMetadata();
  console.log(`Default event-based hold: ${metadata.defaultEventBasedHold}.`);
}

getDefaultEventBasedHold().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Enables a default event-based hold for a bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function get_default_event_based_hold($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    if ($bucket->info()['defaultEventBasedHold']) {
        printf('Default event-based hold is enabled for ' . $bucketName . PHP_EOL);
    } else {
        printf('Default event-based hold is not enabled for ' . $bucketName . PHP_EOL);
    }
}

Python

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

from google.cloud import storage

def get_default_event_based_hold(bucket_name):
    """Gets the default event based hold on a given bucket"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)

    if bucket.default_event_based_hold:
        print("Default event-based hold is enabled for {}".format(bucket_name))
    else:
        print(
            "Default event-based hold is not enabled for {}".format(
                bucket_name
            )
        )

Ruby

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

def get_default_event_based_hold 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

  if bucket.default_event_based_hold?
    puts "Default event-based hold is enabled for #{bucket_name}."
  else
    puts "Default event-based hold is not enabled for #{bucket_name}."
  end
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过包含所需 fieldsGET Bucket 请求调用 JSON API:

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

    其中

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

    如果为存储分区启用了默认的基于事件的保全,则响应类似于以下示例:

    {
      "retentionPolicy": true
    }

XML API

XML API 不能用于处理对象保全。请改用其他 Cloud Storage 工具,例如 gsutil。

停用默认的基于事件的保全

要停用存储分区上默认的基于事件的保全,请执行以下操作:

控制台

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

    转到浏览器

  2. 在存储分区列表中,找到要为其停用默认的基于事件的保全的存储分区,并点击其名称。

  3. 选择页面顶部附近的保留标签页。

  4. 在“基于事件的默认保全选项”部分中,点击已启用按钮。

    如果成功,该按钮的相应文字将变为已停用

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

gsutil

使用 gsutil retention event-default release 命令:

gsutil retention event-default release gs://BUCKET_NAME

其中 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) {
  StatusOr<gcs::BucketMetadata> original =
      client.GetBucketMetadata(bucket_name);

  if (!original) throw std::runtime_error(original.status().message());
  StatusOr<gcs::BucketMetadata> patched_metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetDefaultEventBasedHold(false),
      gcs::IfMetagenerationMatch(original->metageneration()));

  if (!patched_metadata) {
    throw std::runtime_error(patched_metadata.status().message());
  }

  std::cout << "The default event-based hold for objects in bucket "
            << bucket_name << " is "
            << (patched_metadata->default_event_based_hold() ? "enabled"
                                                             : "disabled")
            << "\n";
}

C#

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


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

public class DisableDefaultEventBasedHoldSample
{
    public Bucket DisableDefaultEventBasedHold(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.DefaultEventBasedHold = false;
        bucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Default event-based hold was disabled for {bucketName}");
        return bucket;
    }
}

Go

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

ctx := context.Background()

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	DefaultEventBasedHold: false,
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Java

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

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

Bucket bucket =
    storage.update(BucketInfo.newBuilder(bucketName).setDefaultEventBasedHold(false).build());

System.out.println("Default event-based hold was disabled for " + bucketName);

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

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

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

async function disableDefaultEventBasedHold() {
  // Disables a default event-based hold for a bucket.
  await storage.bucket(bucketName).setMetadata({
    defaultEventBasedHold: false,
  });
  console.log(`Default event-based hold was disabled for ${bucketName}.`);
}

disableDefaultEventBasedHold().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Disables a default event-based hold for a bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function disable_default_event_based_hold($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update(['defaultEventBasedHold' => false]);
    printf('Default event-based hold was disabled for %s' . PHP_EOL, $bucketName);
}

Python

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

from google.cloud import storage

def disable_default_event_based_hold(bucket_name):
    """Disables the default event based hold on a given bucket"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.default_event_based_hold = False
    bucket.patch()

    print("Default event based hold was disabled for {}".format(bucket_name))

Ruby

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

def disable_default_event_based_hold 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.update do |b|
    b.default_event_based_hold = false
  end

  puts "Default event-based hold was disabled for #{bucket_name}."
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件:

    {
      "defaultEventBasedHold": false
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API:

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

    其中:

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

XML API

XML API 不能用于处理对象保全。请改用其他 Cloud Storage 工具,例如 gsutil。

使用对象保全

以下任务说明如何在对象上放置、查看和撤消保全

放置对象保全

要在存储分区中的对象上放置保全,请执行以下操作:

控制台

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

    转到浏览器

  2. 在存储分区列表中,找到包含要在其上放置保全的对象的存储分区,并点击其名称。

  3. 选中要在其上放置保全的对象名称旁边的复选框。

  4. 点击管理保全按钮。

    随即会显示“管理保全”窗口。

  5. 选中要在所选对象上放置的保全类型旁边的复选框

  6. 点击保存保全设置

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

gsutil

使用 gsutil retention 命令:

gsutil retention HOLD_TYPE set gs://BUCKET_NAME/OBJECT_NAME

其中:

  • HOLD_TYPE 是您要应用到对象的保全类型,例如 tempevent。如需详细了解保全类型,请参阅对象保全
  • BUCKET_NAME 是相关存储分区的名称, 例如 my-bucket
  • OBJECT_NAME 是相关对象的名称, 例如 pets/dog.png

代码示例

C++

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

以下示例在对象上设置基于事件的保全:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  StatusOr<gcs::ObjectMetadata> original =
      client.GetObjectMetadata(bucket_name, object_name);
  if (!original) throw std::runtime_error(original.status().message());

  StatusOr<gcs::ObjectMetadata> updated = client.PatchObject(
      bucket_name, object_name,
      gcs::ObjectMetadataPatchBuilder().SetEventBasedHold(true),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!updated) throw std::runtime_error(updated.status().message());

  std::cout << "The event hold for object " << updated->name()
            << " in bucket " << updated->bucket() << " is "
            << (updated->event_based_hold() ? "enabled" : "disabled") << "\n";
}

以下示例在对象上设置临时保全:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  StatusOr<gcs::ObjectMetadata> original =
      client.GetObjectMetadata(bucket_name, object_name);
  if (!original) throw std::runtime_error(original.status().message());

  StatusOr<gcs::ObjectMetadata> updated = client.PatchObject(
      bucket_name, object_name,
      gcs::ObjectMetadataPatchBuilder().SetTemporaryHold(true),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!updated) throw std::runtime_error(updated.status().message());

  std::cout << "The temporary hold for object " << updated->name()
            << " in bucket " << updated->bucket() << " is "
            << (updated->temporary_hold() ? "enabled" : "disabled") << "\n";
}

C#

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

以下示例在对象上设置基于事件的保全:


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

public class SetEventBasedHoldSample
{
    public void SetEventBasedHold(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName);
        storageObject.EventBasedHold = true;
        storage.UpdateObject(storageObject);
        Console.WriteLine($"Event-based hold was set for {objectName}.");
    }
}

以下示例在对象上设置临时保全:


using Google.Cloud.Storage.V1;

public class SetTemporaryHoldSample
{
    public void SetTemporaryHold(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName);
        storageObject.TemporaryHold = true;
        storage.UpdateObject(storageObject);
        System.Console.WriteLine($"Temporary hold was set for {objectName}.");
    }
}

Go

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

以下示例在对象上设置基于事件的保全:

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

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

// setEventBasedHold sets EventBasedHold flag of an object to true.
func setEventBasedHold(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-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()

	o := client.Bucket(bucket).Object(object)
	objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
		EventBasedHold: true,
	}
	if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
		return fmt.Errorf("Object(%q).Update: %v", object, err)
	}
	fmt.Fprintf(w, "Default event based hold was enabled for %v.\n", object)
	return nil
}

以下示例在对象上设置临时保全:

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

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

// setTemporaryHold sets TemporaryHold flag of an object to true.
func setTemporaryHold(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-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()

	o := client.Bucket(bucket).Object(object)
	objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
		TemporaryHold: true,
	}
	if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
		return fmt.Errorf("Object(%q).Update: %v", object, err)
	}
	fmt.Fprintf(w, "Temporary hold was enabled for %v.\n", object)
	return nil
}

Java

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

以下示例在对象上设置基于事件的保全:

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

// The name of a blob, e.g. "my-blob"
// String blobName = "my-blob";

BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage.update(BlobInfo.newBuilder(blobId).setEventBasedHold(true).build());

System.out.println("Event-based hold was set for " + blobName);

以下示例在对象上设置临时保全:

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

// The name of a blob, e.g. "my-blob"
// String blobName = "my-blob";

BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage.update(BlobInfo.newBuilder(blobId).setTemporaryHold(true).build());

System.out.println("Temporary hold was set for " + blobName);

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 ID of your GCS file
// const fileName = 'your-file-name';

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

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

async function setEventBasedHold() {
  // Set event-based hold
  await storage.bucket(bucketName).file(fileName).setMetadata({
    eventBasedHold: true,
  });
  console.log(`Event-based hold was set for ${fileName}.`);
}

setEventBasedHold().catch(console.error);

以下示例在对象上设置临时保全:

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

// The ID of your GCS file
// const fileName = 'your-file-name';

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

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

async function setTemporaryHold() {
  await storage.bucket(bucketName).file(fileName).setMetadata({
    temporaryHold: true,
  });
  console.log(`Temporary hold was set for ${fileName}.`);
}

setTemporaryHold().catch(console.error);

PHP

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

以下示例在对象上设置基于事件的保全:

use Google\Cloud\Storage\StorageClient;

/**
 * Sets an event-based hold for an object.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 */
function set_event_based_hold($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['eventBasedHold' => true]);
    printf('Event-based hold was set for %s' . PHP_EOL, $objectName);
}

以下示例在对象上设置临时保全:

use Google\Cloud\Storage\StorageClient;

/**
 * Sets a temporary hold for an object.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 */
function set_temporary_hold($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['temporaryHold' => true]);
    printf('Temporary hold was set for %s' . PHP_EOL, $objectName);
}

Python

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

以下示例在对象上设置基于事件的保全:

from google.cloud import storage

def set_event_based_hold(bucket_name, blob_name):
    """Sets a event based hold on a given blob"""
    # bucket_name = "my-bucket"
    # blob_name = "my-blob"

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

    blob.event_based_hold = True
    blob.patch()

    print("Event based hold was set for {}".format(blob_name))

以下示例在对象上设置临时保全:

from google.cloud import storage

def set_temporary_hold(bucket_name, blob_name):
    """Sets a temporary hold on a given blob"""
    # bucket_name = "my-bucket"
    # blob_name = "my-blob"

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

    blob.temporary_hold = True
    blob.patch()

    print("Temporary hold was set for #{blob_name}")

Ruby

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

以下示例在对象上设置基于事件的保全:

def set_event_based_hold bucket_name:, file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  require "google/cloud/storage"

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

  file.set_event_based_hold!

  puts "Event-based hold was set for #{file_name}."
end

以下示例在对象上设置临时保全:

def set_temporary_hold bucket_name:, file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  require "google/cloud/storage"

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

  file.set_temporary_hold!

  puts "Temporary hold was set for #{file_name}."
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件:

    {
      "HOLD_TYPE": true
    }

    其中 HOLD_TYPE 是您要应用到对象的保全类型,例如 temporaryHoldeventBasedHold。如需详细了解保全类型,请参阅对象保全

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

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

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket
    • OBJECT_NAME 是相关对象的名称,例如 pets/dog.png

XML API

XML API 不能用于处理对象保全。请改用其他 Cloud Storage 工具,例如 gsutil。

获取对象的保全状态

要查看对象上存在的保全(如果有),请按照查看对象元数据的一般说明进行操作。

撤消对象保全

要撤消存储分区中对象的保全,请执行以下操作:

控制台

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

    转到浏览器

  2. 在存储分区列表中,找到包含要移除其保全的对象的存储分区,并点击其名称。

  3. 选中要从中移除其保全的对象名称旁边的复选框。

  4. 点击管理保全按钮。

    随即会显示“管理保全”窗口。

  5. 取消选中要移除的保全旁边的复选框。

  6. 点击保存保全设置

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

gsutil

使用 gsutil retention 命令:

gsutil retention HOLD_TYPE release gs://BUCKET_NAME/OBJECT_NAME

其中:

  • HOLD_TYPE 是您要从对象中撤消的保全类型,例如 tempevent。如需详细了解保全类型,请参阅对象保全
  • BUCKET_NAME 是相关存储分区的名称, 例如 my-bucket
  • OBJECT_NAME 是相关对象的名称, 例如 pets/dog.png

代码示例

C++

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

以下示例在对象上设置基于事件的保全:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  StatusOr<gcs::ObjectMetadata> original =
      client.GetObjectMetadata(bucket_name, object_name);
  if (!original) throw std::runtime_error(original.status().message());

  StatusOr<gcs::ObjectMetadata> updated = client.PatchObject(
      bucket_name, object_name,
      gcs::ObjectMetadataPatchBuilder().SetEventBasedHold(false),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!updated) throw std::runtime_error(updated.status().message());

  std::cout << "The event hold for object " << updated->name()
            << " in bucket " << updated->bucket() << " is "
            << (updated->event_based_hold() ? "enabled" : "disabled") << "\n";
}

以下示例在对象上设置临时保全:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  StatusOr<gcs::ObjectMetadata> original =
      client.GetObjectMetadata(bucket_name, object_name);

  if (!original) throw std::runtime_error(original.status().message());
  StatusOr<gcs::ObjectMetadata> updated = client.PatchObject(
      bucket_name, object_name,
      gcs::ObjectMetadataPatchBuilder().SetTemporaryHold(false),
      gcs::IfMetagenerationMatch(original->metageneration()));

  if (!updated) throw std::runtime_error(updated.status().message());
  std::cout << "The temporary hold for object " << updated->name()
            << " in bucket " << updated->bucket() << " is "
            << (updated->temporary_hold() ? "enabled" : "disabled") << "\n";
}

C#

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

以下示例撤消对象上基于事件的保全:


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

public class ReleaseEventBasedHoldSample
{
    public void ReleaseEventBasedHold(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName);
        storageObject.EventBasedHold = false;
        storage.UpdateObject(storageObject);
        Console.WriteLine($"Event-based hold was released for {objectName}.");
    }
}

以下示例撤消对象上的临时保全:


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

public class ReleaseTemporaryHoldSample
{
    public void ReleaseTemporaryHold(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName);
        storageObject.TemporaryHold = false;
        storage.UpdateObject(storageObject);
        Console.WriteLine($"Temporary hold was released for {objectName}.");
    }
}

Go

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

以下示例撤消对象上基于事件的保全:

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

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

// releaseEventBasedHold releases an object with event-based hold.
func releaseEventBasedHold(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-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()

	o := client.Bucket(bucket).Object(object)
	objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
		EventBasedHold: false,
	}
	if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
		return fmt.Errorf("Object(%q).Update: %v", object, err)
	}
	fmt.Fprintf(w, "Event based hold was released for %v.\n", object)
	return nil
}

以下示例撤消对象上的临时保全:

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

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

// releaseTemporaryHold releases an object with temporary hold.
func releaseTemporaryHold(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-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()

	o := client.Bucket(bucket).Object(object)
	objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
		TemporaryHold: false,
	}
	if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
		return fmt.Errorf("Object(%q).Update: %v", object, err)
	}
	fmt.Fprintf(w, "Temporary hold was released for %v.\n", object)
	return nil
}

Java

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

以下示例撤消对象上基于事件的保全:

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

// The name of a blob, e.g. "my-blob"
// String blobName = "my-blob";

BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage.update(BlobInfo.newBuilder(blobId).setEventBasedHold(false).build());

System.out.println("Event-based hold was released for " + blobName);

以下示例撤消对象上的临时保全:

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

// The name of a blob, e.g. "my-blob"
// String blobName = "my-blob";

BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage.update(BlobInfo.newBuilder(blobId).setTemporaryHold(false).build());

System.out.println("Temporary hold was released for " + blobName);

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 ID of your GCS file
// const fileName = 'your-file-name';

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

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

async function releaseEventBasedHold() {
  await storage.bucket(bucketName).file(fileName).setMetadata({
    eventBasedHold: false,
  });
  console.log(`Event-based hold was released for ${fileName}.`);
}

releaseEventBasedHold().catch(console.error);

以下示例撤消对象上的临时保全:

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

// The ID of your GCS file
// const fileName = 'your-file-name';

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

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

async function releaseTemporaryHold() {
  await storage.bucket(bucketName).file(fileName).setMetadata({
    temporaryHold: false,
  });
  console.log(`Temporary hold was released for ${fileName}.`);
}

releaseTemporaryHold().catch(console.error);

PHP

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

以下示例撤消对象上基于事件的保全:

use Google\Cloud\Storage\StorageClient;

/**
 * Releases an event-based hold for an object.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 */
function release_event_based_hold($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['eventBasedHold' => false]);
    printf('Event-based hold was released for %s' . PHP_EOL, $objectName);
}

以下示例撤消对象上的临时保全:

use Google\Cloud\Storage\StorageClient;

/**
 * Releases a temporary hold for an object.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 */
function release_temporary_hold($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['temporaryHold' => false]);
    printf('Temporary hold was released for %s' . PHP_EOL, $objectName);
}

Python

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

以下示例撤消对象上基于事件的保全:

from google.cloud import storage

def release_event_based_hold(bucket_name, blob_name):
    """Releases the event based hold on a given blob"""

    # bucket_name = "my-bucket"
    # blob_name = "my-blob"

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

    blob.event_based_hold = False
    blob.patch()

    print("Event based hold was released for {}".format(blob_name))

以下示例撤消对象上的临时保全:

from google.cloud import storage

def release_temporary_hold(bucket_name, blob_name):
    """Releases the temporary hold on a given blob"""

    # bucket_name = "my-bucket"
    # blob_name = "my-blob"

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

    blob.temporary_hold = False
    blob.patch()

    print("Temporary hold was release for #{blob_name}")

Ruby

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

以下示例撤消对象上基于事件的保全:

def release_event_based_hold bucket_name:, file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  require "google/cloud/storage"

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

  file.release_event_based_hold!

  puts "Event-based hold was released for #{file_name}."
end

以下示例撤消对象上的临时保全:

def release_temporary_hold bucket_name:, file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  require "google/cloud/storage"

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

  file.release_temporary_hold!

  puts "Temporary hold was released for #{file_name}."
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件:

    {
      "HOLD_TYPE": false
    }

    其中 HOLD_TYPE 是您要从对象中撤消的保全类型,例如 temporaryHoldeventBasedHold。如需详细了解保全类型,请参阅对象保全

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

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

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket
    • OBJECT_NAME 是相关对象的名称,例如 pets/dog.png

XML API

XML API 不能用于处理对象保全。请改用其他 Cloud Storage 工具,例如 gsutil。

后续步骤