使用对象保全

本页面介绍了如何使用对象保全,包括默认情况下将保全放置在新对象上,以及将保全放置在个别对象上。如需详细了解此功能(包括可放置在对象上的保全类型),请参阅对象保全

前提条件

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

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

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

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

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

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

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

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

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

Console

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,找到要为其启用默认的基于事件的保全属性的存储分区,并点击其名称。

  3. 选择页面顶部附近的存储分区锁定标签。

  4. 在“默认采用基于事件的保全”条目中,点击已停用按钮。

gsutil

使用 gsutil retention event-default set 命令,将 [VALUES_IN_BRACKETS] 替换为适当的值:

gsutil retention event-default set gs://[BUCKET_NAME]

代码示例

C++

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string 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 参考文档

private void EnableBucketDefaultEventBasedHold(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName);
    bucket.DefaultEventBasedHold = true;
    bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration
    });
    Console.WriteLine($"Default event-based hold was enabled for {bucketName}");
}

Go

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

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	DefaultEventBasedHold: true,
}
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 参考文档

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

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

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

// 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}.`);

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 参考文档

# 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 参考文档

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id
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}."

REST API

JSON API

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

    {
      "defaultEventBasedHold": true
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

XML API

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

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

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

Console

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,找到要为其检查默认的基于事件的状态的存储分区,并点击其名称。

  3. 选择页面顶部附近的存储分区锁定标签。

  4. 状态会显示在“默认采用基于事件的保全”条目中。

gsutil

使用以下 gsutil ls 命令,将 [VALUES_IN_BRACKETS] 替换为适当的值:

gsutil ls -L -b gs://[BUCKET_NAME]/

响应类似于如下示例:

gs://[BUCKET_NAME]/ :
  Storage class:         MULTI_REGIONAL
  ...
  ...
  Default Event-Based Hold: On
  ...

代码示例

C++

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string 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 参考文档

private bool GetBucketDefaultEventBasedHold(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName);
    bool? defaultEventBasedHoldOrNull = bucket?.DefaultEventBasedHold;
    bool defaultEventBasedHold =
        defaultEventBasedHoldOrNull.HasValue ? defaultEventBasedHoldOrNull.Value : false;
    Console.WriteLine("Default event-based hold: {0}", defaultEventBasedHold);
    return defaultEventBasedHold;
}

Go

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

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 参考文档

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

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

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

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

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 参考文档

# bucket_name = "my-bucket"

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

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 参考文档

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id
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

REST API

JSON API

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

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

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

    {
      "retentionPolicy": true
    }

XML API

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

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

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

Console

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,找到要为其停用默认的基于事件的保全的存储分区,并点击其名称。

  3. 选择页面顶部附近的存储分区锁定标签。

  4. 在“默认采用基于事件的保全”条目中,点击已启用按钮。

gsutil

使用 gsutil retention event-default release 命令,将 [VALUES_IN_BRACKETS] 替换为适当的值:

gsutil retention event-default release gs://[BUCKET_NAME]

代码示例

C++

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string 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 参考文档

private void DisableBucketDefaultEventBasedHold(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName);
    bucket.DefaultEventBasedHold = false;
    bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration
    });
    Console.WriteLine($"Default event-based hold was disabled for {bucketName}");
}

Go

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

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	DefaultEventBasedHold: false,
}
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 参考文档

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

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

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

// 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}.`);

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 参考文档

# bucket_name = "my-bucket"

storage_client = storage.Client()
bucket = storage_client.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 参考文档

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id
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}."

REST API

JSON API

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

    {
      "defaultEventBasedHold": false
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

XML API

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

使用对象保全

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

放置对象保全

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

Console

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,找到包含要在其上放置保全的对象的存储分区,并点击其名称。

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

  4. 点击管理保全按钮。

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

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

  6. 点击保存保全设置

gsutil

使用 [HOLD_TYPE]tempeventgsutil retention 命令,将其他 [VALUES_IN_BRACKETS] 替换为适当的值:

gsutil retention [HOLD_TYPE] set gs://[BUCKET_NAME]/[OBJECT_NAME]

代码示例

C++

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

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string 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 bucket_name, std::string 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 参考文档

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

private void SetObjectEventBasedHold(string bucketName,
    string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    storageObject.EventBasedHold = true;
    storageObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration
    });
}

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

private void SetObjectTemporaryHold(string bucketName,
    string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    storageObject.TemporaryHold = true;
    storageObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration,
    });
}

Go

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

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

o := client.Bucket(bucket).Object(object)
objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
	EventBasedHold: true,
}
if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
	return err
}

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

o := client.Bucket(bucket).Object(object)
objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
	TemporaryHold: true,
}
if _, err := o.Update(ctx, objectAttrsToUpdate); 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";

// 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 参考文档

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

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

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

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

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

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

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 参考文档

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

# 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))

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

# 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 参考文档

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file in the Cloud Storage bucket"

require "google/cloud/storage"

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

file.set_event_based_hold!

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

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file in the Cloud Storage bucket"

require "google/cloud/storage"

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

file.set_temporary_hold!

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

REST API

JSON API

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

    {
      "[HOLD_TYPE]": true
    }
  3. 使用 cURL,通过 PATCH Object 请求调用 JSON API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

XML API

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

获取对象的保全状态

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

撤消对象保全

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

Console

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,找到包含要移除其保全的对象的存储分区,并点击其名称。

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

  4. 点击管理保全按钮。

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

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

  6. 点击保存保全设置

gsutil

使用 [HOLD_TYPE]tempeventgsutil retention 命令,将其他 [VALUES_IN_BRACKETS] 替换为适当的值:

gsutil retention [HOLD_TYPE] release gs://[BUCKET_NAME]/[OBJECT_NAME]

代码示例

C++

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

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string 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 bucket_name, std::string 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 参考文档

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

private void ReleaseObjectEventBasedHold(string bucketName,
    string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    storageObject.EventBasedHold = false;
    storageObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration,
    });
}

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

private void ReleaseObjectTemporaryHold(string bucketName,
    string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    storageObject.TemporaryHold = false;
    storageObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration,
    });
}

Go

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

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

o := client.Bucket(bucket).Object(object)
objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
	EventBasedHold: false,
}
if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
	return err
}

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

o := client.Bucket(bucket).Object(object)
objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
	TemporaryHold: false,
}
if _, err := o.Update(ctx, objectAttrsToUpdate); 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";

// 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 参考文档

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

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

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

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

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

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

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 参考文档

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

# 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))

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

# 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 参考文档

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file in the Cloud Storage bucket"

require "google/cloud/storage"

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

file.release_event_based_hold!

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

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file in the Cloud Storage bucket"

require "google/cloud/storage"

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

file.release_temporary_hold!

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

REST API

JSON API

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

    {
      "[HOLD_TYPE]": false
    }
  3. 使用 cURL,通过 PATCH Object 请求调用 JSON API,将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

XML API

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

后续步骤

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Cloud Storage
需要帮助?请访问我们的支持页面