获取存储分区信息

本页面介绍如何获取 Cloud Storage 存储分区大小和元数据的相关信息。如需查看存储分区的概览,请参阅关键术语。 如需详细了解特定的存储分区属性,请参阅存储类别存储分区位置

确定存储分区的大小

如需确定存储分区的大小,请执行以下操作:

Cloud Monitoring

如需使用 Metrics Explorer 查看受监控资源的指标,请执行以下操作:

  1. 在 Google Cloud Console 中,转到 Monitoring 或使用下面的按钮:
    转到 Monitoring
  2. 在 Monitoring 导航窗格中,点击 Metrics Explorer
  3. 确保所选标签页为指标
  4. 点击标有 Find resource type and metric 的框,然后从菜单中选择或者输入资源和指标的名称。使用以下信息填写此文本框的各个字段:
    1. 对于 Resource,选择或输入 gcs_bucket
    2. 对于 Metric,选择或输入 Total bytes
    此受监控资源的完全限定名称为 storage.googleapis.com/storage/total_bytes
  5. 使用 FilterGroup ByAggregation 菜单修改数据的显示方式。例如,您可以按资源或指标标签进行分组。如需了解详情,请参阅选择指标 - 其他配置

您还可以使用 Metrics Explorer 测量其他存储分区指标,例如 storage.googleapis.com/storage/object_countstorage.googleapis.com/storage/total_byte_seconds,这两个指标分别测量每日使用的对象数量和每日使用的存储空间。请参阅 Google Cloud 指标文档,了解可用指标的完整列表,并参阅指标、时间序列和资源,详细了解如何使用 Metrics Explorer。

gsutil

使用带有 -s 标志的 gsutil du 命令:

gsutil du -s gs://[BUCKET_NAME]/

其中,[BUCKET_NAME] 为相关存储分区的名称。

响应如下例所示:

134620      gs://[BUCKET_NAME]

在此示例中,存储分区的大小为 134620 字节。

显示存储分区的元数据

如需显示与存储分区关联的元数据,请执行以下操作:

控制台

  1. 在 Google Cloud Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. (可选):您可以通过点击列显示选项菜单 (列选项图标。) 来限制 Cloud Console 存储分区列表中显示的列。

  3. 在存储分区列表中,找到您要验证的存储分区,然后检查其列标题以获取要查看的元数据。

gsutil

使用以下 gsutil ls 命令:

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

其中,[BUCKET_NAME] 为相关存储分区的名称。

响应类似如下示例:

gs://[BUCKET_NAME]/ :
  Storage class:         STANDARD
  Location constraint:   US
  ...

代码示例

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 metadata for bucket " << bucket_metadata->name() << " is "
            << *bucket_metadata << "\n";
}

C#

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

private void GetBucketMetadata(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName);
    Console.WriteLine($"Bucket:\t{bucket.Name}");
    Console.WriteLine($"Acl:\t{bucket.Acl}");
    Console.WriteLine($"Billing:\t{bucket.Billing}");
    Console.WriteLine($"Cors:\t{bucket.Cors}");
    Console.WriteLine($"DefaultEventBasedHold:\t{bucket.DefaultEventBasedHold}");
    Console.WriteLine($"DefaultObjectAcl:\t{bucket.DefaultObjectAcl}");
    Console.WriteLine($"Encryption:\t{bucket.Encryption}");
    if (bucket.Encryption != null)
    {
        Console.WriteLine($"KmsKeyName:\t{bucket.Encryption.DefaultKmsKeyName}");
    }
    Console.WriteLine($"Id:\t{bucket.Id}");
    Console.WriteLine($"Kind:\t{bucket.Kind}");
    Console.WriteLine($"Lifecycle:\t{bucket.Lifecycle}");
    Console.WriteLine($"Location:\t{bucket.Location}");
    Console.WriteLine($"LocationType:\t{bucket.LocationType}");
    Console.WriteLine($"Logging:\t{bucket.Logging}");
    Console.WriteLine($"Metageneration:\t{bucket.Metageneration}");
    Console.WriteLine($"Owner:\t{bucket.Owner}");
    Console.WriteLine($"ProjectNumber:\t{bucket.ProjectNumber}");
    Console.WriteLine($"RetentionPolicy:\t{bucket.RetentionPolicy}");
    Console.WriteLine($"SelfLink:\t{bucket.SelfLink}");
    Console.WriteLine($"StorageClass:\t{bucket.StorageClass}");
    Console.WriteLine($"TimeCreated:\t{bucket.TimeCreated}");
    Console.WriteLine($"Updated:\t{bucket.Updated}");
    Console.WriteLine($"Versioning:\t{bucket.Versioning}");
    Console.WriteLine($"Website:\t{bucket.Website}");
}

Go

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

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

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

// getBucketMetadata gets the bucket metadata.
func getBucketMetadata(w io.Writer, bucketName string) (*storage.BucketAttrs, error) {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return nil, fmt.Errorf("Bucket(%q).Attrs: %v", bucketName, err)
	}
	fmt.Fprintf(w, "BucketName: %v\n", attrs.Name)
	fmt.Fprintf(w, "Location: %v\n", attrs.Location)
	fmt.Fprintf(w, "LocationType: %v\n", attrs.LocationType)
	fmt.Fprintf(w, "StorageClass: %v\n", attrs.StorageClass)
	fmt.Fprintf(w, "TimeCreated: %v\n", attrs.Created)
	fmt.Fprintf(w, "Metageneration: %v\n", attrs.MetaGeneration)
	fmt.Fprintf(w, "PredefinedACL: %v\n", attrs.PredefinedACL)
	if attrs.Encryption != nil {
		fmt.Fprintf(w, "DefaultKmsKeyName: %v\n", attrs.Encryption.DefaultKMSKeyName)
	}
	if attrs.Website != nil {
		fmt.Fprintf(w, "IndexPage: %v\n", attrs.Website.MainPageSuffix)
		fmt.Fprintf(w, "NotFoundPage: %v\n", attrs.Website.NotFoundPage)
	}
	fmt.Fprintf(w, "DefaultEventBasedHold: %v\n", attrs.DefaultEventBasedHold)
	if attrs.RetentionPolicy != nil {
		fmt.Fprintf(w, "RetentionEffectiveTime: %v\n", attrs.RetentionPolicy.EffectiveTime)
		fmt.Fprintf(w, "RetentionPeriod: %v\n", attrs.RetentionPolicy.RetentionPeriod)
		fmt.Fprintf(w, "RetentionPolicyIsLocked: %v\n", attrs.RetentionPolicy.IsLocked)
	}
	fmt.Fprintf(w, "RequesterPays: %v\n", attrs.RequesterPays)
	fmt.Fprintf(w, "VersioningEnabled: %v\n", attrs.VersioningEnabled)
	if attrs.Logging != nil {
		fmt.Fprintf(w, "LogBucket: %v\n", attrs.Logging.LogBucket)
		fmt.Fprintf(w, "LogObjectPrefix: %v\n", attrs.Logging.LogObjectPrefix)
	}
	if attrs.Labels != nil {
		fmt.Fprintf(w, "\n\n\nLabels:")
		for key, value := range attrs.Labels {
			fmt.Fprintf(w, "\t%v = %v\n", key, value)
		}
	}
	return attrs, nil
}

Java

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

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;

public class GetBucketMetadata {
  public static void getBucketMetadata(String projectId, String bucketName) {
    // 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();

    // Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAME
    Bucket bucket =
        storage.get(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.values()));

    // Print bucket metadata
    System.out.println("BucketName: " + bucket.getName());
    System.out.println("DefaultEventBasedHold: " + bucket.getDefaultEventBasedHold());
    System.out.println("DefaultKmsKeyName: " + bucket.getDefaultKmsKeyName());
    System.out.println("Id: " + bucket.getGeneratedId());
    System.out.println("IndexPage: " + bucket.getIndexPage());
    System.out.println("Location: " + bucket.getLocation());
    System.out.println("LocationType: " + bucket.getLocationType());
    System.out.println("Metageneration: " + bucket.getMetageneration());
    System.out.println("NotFoundPage: " + bucket.getNotFoundPage());
    System.out.println("RetentionEffectiveTime: " + bucket.getRetentionEffectiveTime());
    System.out.println("RetentionPeriod: " + bucket.getRetentionPeriod());
    System.out.println("RetentionPolicyIsLocked: " + bucket.retentionPolicyIsLocked());
    System.out.println("RequesterPays: " + bucket.requesterPays());
    System.out.println("SelfLink: " + bucket.getSelfLink());
    System.out.println("StorageClass: " + bucket.getStorageClass().name());
    System.out.println("TimeCreated: " + bucket.getCreateTime());
    System.out.println("VersioningEnabled: " + bucket.versioningEnabled());
    if (bucket.getLabels() != null) {
      System.out.println("\n\n\nLabels:");
      for (Map.Entry<String, String> label : bucket.getLabels().entrySet()) {
        System.out.println(label.getKey() + "=" + label.getValue());
      }
    }
    if (bucket.getLifecycleRules() != null) {
      System.out.println("\n\n\nLifecycle Rules:");
      for (BucketInfo.LifecycleRule rule : bucket.getLifecycleRules()) {
        System.out.println(rule);
      }
    }
  }
}

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

async function getBucketMetadata() {
  // Get bucket metadata.
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const bucketName = 'Name of a bucket, e.g. my-bucket';

  // Get Bucket Metadata
  const [metadata] = await storage.bucket(bucketName).getMetadata();

  for (const [key, value] of Object.entries(metadata)) {
    console.log(`${key}: ${value}`);
  }
}

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Get bucket metadata.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *
 * @return void
 */
function get_bucket_metadata($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $info = $bucket->info();

    printf("Bucket Metadata: %s" . PHP_EOL, print_r($info));
}

Python

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

from google.cloud import storage
import pprint

def bucket_metadata(bucket_name):
    """Prints out a bucket's metadata."""
    # bucket_name = 'your-bucket-name'

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

    print("ID: {}".format(bucket.id))
    print("Name: {}".format(bucket.name))
    print("Storage Class: {}".format(bucket.storage_class))
    print("Location: {}".format(bucket.location))
    print("Location Type: {}".format(bucket.location_type))
    print("Cors: {}".format(bucket.cors))
    print(
        "Default Event Based Hold: {}".format(bucket.default_event_based_hold)
    )
    print("Default KMS Key Name: {}".format(bucket.default_kms_key_name))
    print("Metageneration: {}".format(bucket.metageneration))
    print(
        "Retention Effective Time: {}".format(
            bucket.retention_policy_effective_time
        )
    )
    print("Retention Period: {}".format(bucket.retention_period))
    print("Retention Policy Locked: {}".format(bucket.retention_policy_locked))
    print("Requester Pays: {}".format(bucket.requester_pays))
    print("Self Link: {}".format(bucket.self_link))
    print("Time Created: {}".format(bucket.time_created))
    print("Versioning Enabled: {}".format(bucket.versioning_enabled))
    print("Labels:")
    pprint.pprint(bucket.labels)

Ruby

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

# bucket_name = "Your Google Cloud Storage bucket name"

require "google/cloud/storage"

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

puts "ID:                       #{bucket.id}"
puts "Name:                     #{bucket.name}"
puts "Storage Class:            #{bucket.storage_class}"
puts "Location:                 #{bucket.location}"
puts "Location Type:            #{bucket.location_type}"
puts "Cors:                     #{bucket.cors}"
puts "Default Event Based Hold: #{bucket.default_event_based_hold?}"
puts "Default KMS Key Name:     #{bucket.default_kms_key}"
puts "Logging Bucket:           #{bucket.logging_bucket}"
puts "Logging Prefix:           #{bucket.logging_prefix}"
puts "Metageneration:           #{bucket.metageneration}"
puts "Retention Effective Time: #{bucket.retention_effective_at}"
puts "Retention Period:         #{bucket.retention_period}"
puts "Retention Policy Locked:  #{bucket.retention_policy_locked?}"
puts "Requester Pays:           #{bucket.requester_pays}"
puts "Self Link:                #{bucket.api_url}"
puts "Time Created:             #{bucket.created_at}"
puts "Versioning Enabled:       #{bucket.versioning?}"
puts "Index Page:               #{bucket.website_main}"
puts "Not Found Page:           #{bucket.website_404}"
puts "Labels:"
bucket.labels.each do |key, value|
  puts " - #{key} = #{value}"
end

REST API

JSON API

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

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

    其中:

    • [OAUTH2_TOKEN] 是您在第 1 步中生成的访问令牌的名称。
    • [BUCKET_NAME] 是相关存储分区的名称,例如 my-bucket
  3. 使用查询参数将搜索结果范围缩小至所需字段:

    curl -X GET \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=[FIELD1]%2C[FIELD2]"

    其中 [FIELD#] 是要包含在搜索结果中的存储分区属性。例如 locationstorageClass

响应类似如下示例:

{
  "location": "US",
  "storageClass": "STANDARD"
}

XML API

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

    curl -X GET \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    "https://storage.googleapis.com/[BUCKET_NAME]?[QUERY_PARAMETER]"

    其中:

    • [OAUTH2_TOKEN] 是您在第 1 步中生成的访问令牌的名称。
    • [BUCKET_NAME] 是相关存储分区的名称,例如 my-bucket
    • [QUERY_PARAMETER] 是要返回的元数据字段。例如,location(用于获取存储分区的位置)。一次只能对 XML API 使用一个查询参数。

    响应类似如下示例:<LocationConstraint>US</LocationConstraint>

后续步骤