使用保留政策和存储分区锁定

本页介绍如何使用存储分区锁定功能,包括使用保留政策和锁定存储分区。有关此功能的详细信息,请参阅保留政策和存储分区锁定

前提条件

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

  1. 具备足够的权限来查看和更新 Cloud Storage 中的存储分区:

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

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

    • 如果您使用了 ACL,您应在相关存储分区上具有 OWNER 权限。 如需了解如何执行此操作,请参阅设置 ACL

  2. 针对该存储分区,检查是否已禁用对象版本控制

在存储分区上设置保留政策

要在存储分区上设置保留政策,请执行以下操作:

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,点击要为其添加保留政策的存储分区的名称。

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

  4. 保留政策条目中,点击添加政策链接。

    此时将出现“设置保留政策”对话框。

  5. 在下拉列表中,选择保留期限的时间单位。

    如需了解控制台如何在不同时间单位之间进行转换,请参阅保留期限

  6. 在值框中,输入保留期限的时间长度。

  7. 点击保存政策

gsutil

使用 gsutil retention set 命令:

gsutil retention set [TIME_DURATION] gs://[BUCKET_NAME]

其中:

  • [TIME_DURATION] 是存储分区中的对象必须保留的时长,例如 2678400s。如需了解 gsutil 如何在不同时间单位之间进行转换,请参阅保留期限
  • [BUCKET_NAME] 是相关存储分区的名称,例如 my-bucket

如果成功,响应将如下所示:

Setting retention policy on gs://[BUCKET_NAME]/...

代码示例

C++

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::chrono::seconds period) {
  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().SetRetentionPolicy(period),
      gcs::IfMetagenerationMatch(original->metageneration()));

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

  if (!patched_metadata->has_retention_policy()) {
    std::cout << "The bucket " << patched_metadata->name()
              << " does not have a retention policy set.\n";
    return;
  }

  std::cout << "The bucket " << patched_metadata->name()
            << " retention policy is set to "
            << patched_metadata->retention_policy() << "\n";
}

C#

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

        private void SetBucketRetentionPolicy(string bucketName,
            long retentionPeriod)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            bucket.RetentionPolicy = new Bucket.RetentionPolicyData();
            bucket.RetentionPolicy.RetentionPeriod = retentionPeriod;
            bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
            {
                IfMetagenerationMatch = bucket.Metageneration
            });

            Console.WriteLine($"Retention policy for {bucketName} was set to {retentionPeriod}");
        }

Go

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

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	RetentionPolicy: &storage.RetentionPolicy{
		RetentionPeriod: retentionPeriod,
	},
}
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";

// The retention period for objects in bucket
// Long retentionPeriod = 3600L; // 1 hour in seconds

Bucket bucketWithRetentionPolicy =
    storage.update(
        BucketInfo.newBuilder(bucketName).setRetentionPeriod(retentionPeriod).build());

System.out.println(
    "Retention period for "
        + bucketName
        + " is now "
        + bucketWithRetentionPolicy.getRetentionPeriod());

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();

const [metadata] = await storage
  .bucket(bucketName)
  .setRetentionPeriod(retentionPeriod);
console.log(
  `Bucket ${bucketName} retention period set for ${metadata.retentionPolicy.retentionPeriod} seconds.`
);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Sets a bucket's retention policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $retentionPeriod the number of seconds for your retention period.
 */
function set_retention_policy($bucketName, $retentionPeriod)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'retentionPolicy' => [
            'retentionPeriod' => $retentionPeriod
        ]]);
    printf('Bucket %s retention period set for %s seconds' . PHP_EOL, $bucketName,
        $retentionPeriod);
}

Python

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

# bucket_name = "my-bucket"
# retention_period = 10

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

bucket.retention_period = retention_period
bucket.patch()

print('Bucket {} retention period set for {} seconds'.format(
    bucket.name,
    bucket.retention_period))

Ruby

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

# project_id       = "Your Google Cloud project ID"
# bucket_name      = "Name of your Google Cloud Storage bucket"
# retention_period = "Object retention period defined in seconds"

require "google/cloud/storage"

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

bucket.retention_period = retention_period

puts "Retention period for #{bucket_name} is now #{bucket.retention_period} seconds."

REST API

JSON API

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

    {
      "retentionPolicy": {
        "retentionPeriod": "[TIME_IN_SECONDS]"
      }
    }

    其中 [TIME_IN_SECONDS] 是存储分区中的对象必须保留的时长(以秒为单位),例如 2678400。如需了解系统如何以秒为单位来计量不同的时间单位,请参阅保留期限

  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://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=retentionPolicy"

    其中:

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

XML API

XML API 不能用于在现有存储分区上设置保留政策。它只能用于为新存储分区设置保留政策

从存储分区中移除保留政策

要从存储分区中移除保留政策,请执行以下操作:

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,点击要从中移除保留政策的存储分区的名称。

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

  4. 保留政策条目中,点击垃圾桶图标

    此时将出现“是否删除保留政策?”对话框。

  5. 点击删除

gsutil

使用 gsutil retention clear 命令:

gsutil retention clear gs://[BUCKET_NAME]

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

如果成功,响应将如下所示:

Clearing retention policy on 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().ResetRetentionPolicy(),
      gcs::IfMetagenerationMatch(original->metageneration()));

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

  if (!patched_metadata->has_retention_policy()) {
    std::cout << "The bucket " << patched_metadata->name()
              << " does not have a retention policy set.\n";
    return;
  }

  std::cout << "The bucket " << patched_metadata->name()
            << " retention policy is set to "
            << patched_metadata->retention_policy()
            << ". This is unexpected, maybe a concurrent change by another"
            << " application?\n";
}

C#

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

        private void RemoveBucketRetentionPolicy(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            if (bucket.RetentionPolicy != null)
            {
                bool? isLockedOrNull = bucket?.RetentionPolicy.IsLocked;
                bool isLocked =
                    isLockedOrNull.HasValue ? isLockedOrNull.Value : false;
                if (isLocked)
                {
                    throw new Exception("Retention Policy is locked.");
                }

                bucket.RetentionPolicy.RetentionPeriod = null;
                bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
                {
                    IfMetagenerationMatch = bucket.Metageneration
                });

                Console.WriteLine($"Retention period for {bucketName} has been removed.");
            }
        }

Go

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

bucket := c.Bucket(bucketName)

attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}
if attrs.RetentionPolicy.IsLocked {
	return errors.New("retention policy is locked")
}

bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	RetentionPolicy: &storage.RetentionPolicy{},
}
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.get(bucketName, BucketGetOption.fields(BucketField.RETENTION_POLICY));
if (bucket.retentionPolicyIsLocked() != null && bucket.retentionPolicyIsLocked()) {
  throw new IllegalArgumentException(
      "Unable to remove retention period as retention policy is locked.");
}

Bucket bucketWithoutRetentionPolicy =
    bucket.toBuilder().setRetentionPeriod(null).build().update();

System.out.println("Retention period for " + bucketName + " has been removed");

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();
const [metadata] = await storage.bucket(bucketName).getMetadata();
if (metadata.retentionPolicy && metadata.retentionPolicy.isLocked) {
  console.log(
    'Unable to remove retention period as retention policy is locked.'
  );
  return null;
} else {
  const results = await storage.bucket(bucketName).removeRetentionPeriod();
  console.log(`Removed bucket ${bucketName} retention policy.`);
  return results;
}

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Removes a bucket's retention policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function remove_retention_policy($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();

    if (array_key_exists('isLocked', $bucket->info()['retentionPolicy']) &&
        $bucket->info()['retentionPolicy']['isLocked']) {
        printf('Unable to remove retention period as retention policy is locked.' . PHP_EOL);
        return;
    }

    $bucket->update([
        'retentionPolicy' => []
    ]);
    printf('Removed bucket %s retention policy' . PHP_EOL, $bucketName);
}

Python

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

# bucket_name = "my-bucket"

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

if bucket.retention_policy_locked:
    print(
        'Unable to remove retention period as retention policy is locked.')
    return

bucket.retention_period = None
bucket.patch()

print('Removed bucket {} retention policy'.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.retention_policy_locked?
  bucket.retention_period = nil
  puts "Retention policy for #{bucket_name} has been removed."
else
  puts "Policy is locked and retention policy can't be removed."
end

REST API

JSON API

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

    {
      "retentionPolicy": {
        "retentionPeriod": null
      }
    }
  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://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=retentionPolicy"

    其中:

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

XML API

XML API 不能用于从存储分区中移除保留政策。请使用其他 Cloud Storage 工具,例如 gsutil。

锁定存储分区

要锁定存储分区并永久限制对存储分区保留政策的修改,请执行以下操作:

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,点击要锁定其保留政策的存储分区的名称。

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

  4. “已锁定”条目中,点击锁定图标

    此时将出现“是否锁定此存储分区的保留政策?”对话框。

  5. 阅读永久说明。

  6. “存储分区名称”文本框中,键入存储分区的名称。

  7. 点击锁定政策

gsutil

  1. 使用 gsutil retention lock 命令:

    gsutil retention lock gs://[BUCKET_NAME]

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

  2. 当系统提示您继续时,请按 y 键。

如果成功,响应将如下所示:

Locking retention policy on 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> updated_metadata =
      client.LockBucketRetentionPolicy(bucket_name,
                                       original->metageneration());

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

  if (!updated_metadata->has_retention_policy()) {
    std::cerr << "The bucket " << updated_metadata->name()
              << " does not have a retention policy, even though the"
              << " operation to set it was successful.\n"
              << "This is unexpected, and may indicate that another"
              << " application has modified the bucket concurrently.\n";
    return;
  }

  std::cout << "Retention policy successfully locked for bucket "
            << updated_metadata->name() << "\nNew retention policy is: "
            << updated_metadata->retention_policy()
            << "\nFull metadata: " << *updated_metadata << "\n";
}

C#

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

private void LockBucketRetentionPolicy(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName);
    storage.LockBucketRetentionPolicy(bucketName,
        bucket.Metageneration.Value);
    bucket = storage.GetBucket(bucketName);
    Console.WriteLine($"Retention policy for {bucketName} is now locked");
    Console.WriteLine($"Retention policy effective as of {bucket.RetentionPolicy.EffectiveTime}");
}

Go

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

bucket := c.Bucket(bucketName)
attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}

conditions := storage.BucketConditions{
	MetagenerationMatch: attrs.MetaGeneration,
}
if err := bucket.If(conditions).LockRetentionPolicy(ctx); err != nil {
	return err
}

lockedAttrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}
log.Printf("Retention policy for %v is now locked\n", bucketName)
log.Printf("Retention policy effective as of %v\n",
	lockedAttrs.RetentionPolicy.EffectiveTime)

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, Storage.BucketGetOption.fields(BucketField.METAGENERATION));
Bucket lockedBucket =
    bucket.lockRetentionPolicy(Storage.BucketTargetOption.metagenerationMatch());

System.out.println("Retention period for " + bucketName + " is now locked");
System.out.println(
    "Retention policy effective as of " + new Date(lockedBucket.getRetentionEffectiveTime()));

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();
// get_bucket gets the current metageneration value for the bucket,
// required by lock_retention_policy.
const [unlockedMetadata] = await storage.bucket(bucketName).getMetadata();
// Warning: Once a retention policy is locked it cannot be unlocked
// and retention period can only be increased.
const [lockedMetadata] = await storage
  .bucket(bucketName)
  .lock(unlockedMetadata.metageneration);
console.log(`Retention policy for ${bucketName} is now locked.`);
console.log(
  `Retention policy effective as of ${lockedMetadata.retentionPolicy.effectiveTime}`
);

return lockedMetadata;

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Locks a bucket's retention policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function lock_retention_policy($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();
    $bucket->lockRetentionPolicy();
    printf('Bucket %s retention policy locked' . PHP_EOL, $bucketName);
}

Python

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

# bucket_name = "my-bucket"

storage_client = storage.Client()
# get_bucket gets the current metageneration value for the bucket,
# required by lock_retention_policy.
bucket = storage_client.get_bucket(bucket_name)

# Warning: Once a retention policy is locked it cannot be unlocked
# and retention period can only be increased.
bucket.lock_retention_policy()

print('Retention policy for {} is now locked'.format(bucket_name))
print('Retention policy effective as of {}'.format(
    bucket.retention_policy_effective_time))

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

# Warning: Once a retention policy is locked it cannot be unlocked
# and retention period can only be increased.
# Uses Bucket#metageneration as a precondition.
bucket.lock_retention_policy!

puts "Retention policy for #{bucket_name} is now locked."
puts "Retention policy effective as of #{bucket.retention_effective_at}."

REST API

JSON API

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

    curl -X POST \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/lockRetentionPolicy?ifMetagenerationMatch=[BUCKET_METAGENERATION_NUMBER]"

    其中:

    • [OAUTH2_TOKEN] 是您在第 1 步中生成的访问令牌的名称。
    • [BUCKET_NAME] 是相关存储分区的名称,例如 my-bucket
    • [BUCKET_METAGENERATION_NUMBER] 是存储分区的 metageneration 值,例如 8。通过 GET Bucket 请求调用 JSON API,您可以找到存储分区的 metageneration 值。

XML API

您不能使用 XML API 来锁定存储分区。 请使用其他 Cloud Storage 工具,例如 gsutil。

查看存储分区的保留政策和锁定状态

如需查看存储分区上设置了什么保留政策(若有)以及该保留政策是否已锁定,请执行以下操作:

控制台

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. “列”下拉菜单中,请务必勾选保留政策

  3. 在存储分区列表中,每个存储分区的保留期限可在保留政策列中找到。如果保留政策被锁定,则锁定图片将直接显示在保留期限的左侧。

gsutil

使用 gsutil retention get 命令:

gsutil retention get gs://[BUCKET_NAME]

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

如果成功,响应将如下所示:

gs://[BUCKET_NAME]/ has no retention policy.

或者:

gs://retention-test/:
    Retention policy [LOCK_STATUS]:
    Duration: [TIME_LENGTH]
    Effective Time: [SET_DATE]

代码示例

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());
  }

  if (!bucket_metadata->has_retention_policy()) {
    std::cout << "The bucket " << bucket_metadata->name()
              << " does not have a retention policy set.\n";
    return;
  }

  std::cout << "The bucket " << bucket_metadata->name()
            << " retention policy is set to "
            << bucket_metadata->retention_policy() << "\n";
}

C#

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

        private void GetBucketRetentionPolicy(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);

            if (bucket.RetentionPolicy != null)
            {
                Console.WriteLine("Retention policy:");
                Console.WriteLine($"period: {bucket.RetentionPolicy.RetentionPeriod}");
                Console.WriteLine($"effective time: {bucket.RetentionPolicy.EffectiveTime}");
                bool? isLockedOrNull = bucket?.RetentionPolicy.IsLocked;
                bool isLocked =
                    isLockedOrNull.HasValue ? isLockedOrNull.Value : false;
                Console.WriteLine("policy locked: {0}", isLocked);
            }
        }

Go

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

attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return nil, err
}
if attrs.RetentionPolicy != nil {
	log.Print("Retention Policy\n")
	log.Printf("period: %v\n", attrs.RetentionPolicy.RetentionPeriod)
	log.Printf("effective time: %v\n", attrs.RetentionPolicy.EffectiveTime)
	log.Printf("policy locked: %v\n", attrs.RetentionPolicy.IsLocked)
}

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.RETENTION_POLICY));

System.out.println("Retention Policy for " + bucketName);
System.out.println("Retention Period: " + bucket.getRetentionPeriod());
if (bucket.retentionPolicyIsLocked() != null && bucket.retentionPolicyIsLocked()) {
  System.out.println("Retention Policy is locked");
}
if (bucket.getRetentionEffectiveTime() != null) {
  System.out.println("Effective Time: " + new Date(bucket.getRetentionEffectiveTime()));
}

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();
const [metadata] = await storage.bucket(bucketName).getMetadata();
if (metadata.retentionPolicy) {
  const retentionPolicy = metadata.retentionPolicy;
  console.log('A retention policy exists!');
  console.log(`Period: ${retentionPolicy.retentionPeriod}`);
  console.log(`Effective time: ${retentionPolicy.effectiveTime}`);
  if (retentionPolicy.isLocked) {
    console.log('Policy is locked');
  } else {
    console.log('Policy is unlocked');
  }
}

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Gets a bucket's retention policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function get_retention_policy($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();

    printf('Retention Policy for ' . $bucketName . PHP_EOL);
    printf('Retention Period: ' . $bucket->info()['retentionPolicy']['retentionPeriod'] . PHP_EOL);
    if (array_key_exists('isLocked', $bucket->info()['retentionPolicy']) &&
        $bucket->info()['retentionPolicy']['isLocked']) {
        printf('Retention Policy is locked' . PHP_EOL);
    }
    if ($bucket->info()['retentionPolicy']['effectiveTime']) {
        printf('Effective Time: ' . $bucket->info()['retentionPolicy']['effectiveTime'] . PHP_EOL);
    }
}

Python

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

# bucket_name = "my-bucket"

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

print('Retention Policy for {}'.format(bucket_name))
print('Retention Period: {}'.format(bucket.retention_period))
if bucket.retention_policy_locked:
    print('Retention Policy is locked')

if bucket.retention_policy_effective_time:
    print('Effective Time: {}'
          .format(bucket.retention_policy_effective_time))

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

puts "Retention policy:"
puts "period: #{bucket.retention_period}"
puts "effective time: #{bucket.retention_effective_at}"
puts "policy locked: #{bucket.retention_policy_locked?}"

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://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=retentionPolicy"

    其中:

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

    如果存储分区上设置了保留政策,则响应类似于以下示例:

    {
      "retentionPolicy": {
          "retentionPeriod": "[TIME_IN_SECONDS]",
          "effectiveTime": "[DATETIME]",
          "isLocked": "[BOOLEAN]"
       },
    }

XML API

XML API 不能用于查看存储分区上的保留政策。请使用其他 Cloud Storage 工具,例如 gsutil。

后续步骤

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

发送以下问题的反馈:

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