举例说明如何锁定存储分区的保留政策。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
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;
}
}
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";
}
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 参考文档。
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
import java.util.Date;
public class LockRetentionPolicy {
public static void lockRetentionPolicy(String projectId, String bucketName)
throws StorageException {
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
Bucket bucket =
storage.get(bucketName, Storage.BucketGetOption.fields(Storage.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(f"Retention policy for {bucket_name} is now locked")
print(
f"Retention policy effective as of {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
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。