使用和锁定保留政策

转到概念

本页面介绍了如何使用存储分区锁定功能,包括使用保留政策以及将其永久地锁定在存储分区上。

前提条件

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

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

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

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

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

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

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

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

控制台

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

    转到浏览器

  2. 在存储分区列表中,点击要为其添加保留政策的存储分区的名称。

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

  4. 保留政策部分,点击 + 设置保留政策链接。

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

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

    如需了解 Console 如何在不同时间单位之间进行转换的详情,请参阅保留期限

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

  7. 点击保存

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

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://my-bucket/...

代码示例

C++

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

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


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

public class SetRetentionPolicySample
{
    /// <summary>
    /// Sets the bucket's retention policy.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <param name="retentionPeriod">The duration in seconds that objects need to be retained. The retention policy enforces a minimum retention
    /// time for all objects contained in the bucket, based on their creation time. Any
    /// attempt to overwrite or delete objects younger than the retention period will
    /// result in a PERMISSION_DENIED error. An unlocked retention policy can be modified
    /// or removed from the bucket via a storage.buckets.update operation. A locked retention
    /// policy cannot be removed or shortened in duration for the lifetime of the bucket.
    /// Attempting to remove or decrease the period of a locked retention policy will result
    /// in a PERMISSION_DENIED error.</param>
    public RetentionPolicyData SetRetentionPolicy(
        string bucketName = "your-unique-bucket-name",
        long retentionPeriod = 10)
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.RetentionPolicy = new RetentionPolicyData { RetentionPeriod = retentionPeriod };

        bucket = storage.UpdateBucket(bucket);

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

Go

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

ctx := context.Background()

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

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

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

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

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

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

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

setRetentionPolicy().catch(console.error);

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 int $retentionPeriod The retention period for objects in bucket, in seconds.
 */
function set_retention_policy($bucketName, $retentionPeriod)
{
    // $bucketName = 'my-bucket';
    // $retentionPeriod = 3600;

    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'retentionPolicy' => [
            'retentionPeriod' => $retentionPeriod
        ]]);
    printf('Bucket %s retention period set to %s seconds' . PHP_EOL, $bucketName,
        $retentionPeriod);
}

Python

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

from google.cloud import storage

def set_retention_policy(bucket_name, retention_period):
    """Defines a retention policy on a given bucket"""
    # 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 参考文档

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

  # The retention period for objects in bucket
  # retention_period = 3600 # 1 hour in seconds

  require "google/cloud/storage"

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

  bucket.retention_period = retention_period

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

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。 如需了解相关说明,请参阅 API 身份验证
  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://storage.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 Console 中,转到 Cloud Storage 浏览器页面。

    转到浏览器

  2. 在存储分区列表中,点击要从中移除保留政策的存储分区的名称。

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

  4. 保留政策部分,点击删除按钮。

    此时将出现删除保留政策吗?对话框。

  5. 点击删除

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

gsutil

使用 gsutil retention clear 命令:

gsutil retention clear gs://BUCKET_NAME

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

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

Clearing retention policy on gs://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().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 参考文档


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

public class RemoveRetentionPolicySample
{
    public void RemoveRetentionPolicy(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        if (bucket.RetentionPolicy != null)
        {
            bool isLocked = bucket.RetentionPolicy.IsLocked ?? false;
            if (isLocked)
            {
                throw new Exception("Retention Policy is locked.");
            }

            bucket.RetentionPolicy.RetentionPeriod = null;
            storage.UpdateBucket(bucket);

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

Go

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

ctx := context.Background()
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{},
}
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.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 参考文档

/**
 * 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 removeRetentionPolicy() {
  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;
  }
}

removeRetentionPolicy().catch(console.error);

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)
{
    // $bucketName = 'my-bucket';

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

from google.cloud import storage

def remove_retention_policy(bucket_name):
    """Removes the retention policy on a given bucket"""
    # 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 参考文档

def remove_retention_policy 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.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
end

REST API

JSON API

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

    {
      "retentionPolicy": 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://storage.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 Console 中,转到 Cloud Storage 浏览器页面。

    转到浏览器

  2. 在存储分区列表中,点击要锁定其保留政策的存储分区的名称。

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

  4. 保留政策部分,点击锁定按钮。

    此时将出现锁定保留政策吗?对话框。

  5. 阅读永久说明。

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

  7. 点击锁定政策

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

gsutil

  1. 使用 gsutil retention lock 命令:

    gsutil retention lock gs://BUCKET_NAME

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

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

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

Locking retention policy on gs://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> 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 参考文档


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

public class LockRetentionPolicySample
{
    /// <summary>
    /// Locks the retention policy of a bucket. This is a one-way process: once a retention
    /// policy is locked, it cannot be shortened, removed or unlocked, although it can
    /// be increased in duration. The lock persists until the bucket is deleted.
    /// </summary>
    /// <param name="bucketName">The name of the bucket whose retention policy should be locked.</param>
    public bool? LockRetentionPolicy(string bucketName = "your-unique-bucket-name")
    {
        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}");

        return bucket.RetentionPolicy.IsLocked;
    }
}

Go

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

ctx := context.Background()
bucket := c.Bucket(bucketName)

ctx, cancel := context.WithTimeout(ctx, time.Second*50)
defer cancel()
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 参考文档

/**
 * 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 lockRetentionPolicy() {
  // 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. The
  // 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;
}

lockRetentionPolicy().catch(console.error);

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)
{
    // $bucketName = 'my-bucket';

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

from google.cloud import storage

def lock_retention_policy(bucket_name):
    """Locks the retention policy on a given bucket"""
    # 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 参考文档

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

  # 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}."
end

REST API

JSON API

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

    curl -X POST \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.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 Console 中,转到 Cloud Storage 浏览器页面。

    转到浏览器

  2. 列显示选项菜单 (列选项图标。) 中,确保已选中保留政策

  3. 在存储桶列表中,如果存储桶具有保留政策,则保留期限会显示在该存储桶的保护列中。如果保留政策被锁定,则锁定图片将直接显示在保留期限的左侧。

gsutil

使用 gsutil retention get 命令:

gsutil retention get gs://BUCKET_NAME

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

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

gs://my-bucket/ 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 const& 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 参考文档


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

public class GetRetentionPolicySample
{
    public RetentionPolicyData GetRetentionPolicy(string bucketName = "your-unique-bucket-name")
    {
        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 isLocked = bucket.RetentionPolicy.IsLocked ?? false;
            Console.WriteLine($"Policy locked: {isLocked}");
        }
        return bucket.RetentionPolicy;
    }
}

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

/**
 * 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 getRetentionPolicy() {
  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');
    }
  }
}

getRetentionPolicy().catch(console.error);

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)
{
    // $bucketName = 'my-bucket';

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

from google.cloud import storage

def get_retention_policy(bucket_name):
    """Gets the retention policy on a given bucket"""
    # 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 参考文档

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

  require "google/cloud/storage"

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

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

REST API

JSON API

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

    curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.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。

后续步骤