查看使用情况报告


Compute Engine 可让您利用使用情况导出功能将 Compute Engine 使用情况的详细报告导出到 Cloud Storage 存储桶。使用情况报告会提供有关资源生命周期的信息。例如,您可以查看项目中运行 n2-standard-4 机器类型的虚拟机实例数量以及每个实例的运行时长。您还可以查看永久性磁盘的存储空间以及有关其他 Compute Engine 功能的信息。

不过,用量报告并不会提供账单或活动信息(例如有关 API 请求的信息)。如需了解账单信息,请参阅账单导出功能。如需了解活动日志,请参阅活动日志

准备工作

  • 设置身份验证(如果尚未设置)。身份验证是通过其进行身份验证以访问 Google Cloud 服务和 API 的过程。如需从本地开发环境运行代码或示例,您可以按如下方式向 Compute Engine 进行身份验证。

    选择标签页以了解您打算如何使用本页面上的示例:

    控制台

    当您使用 Google Cloud 控制台访问 Google Cloud 服务和 API 时,无需设置身份验证。

    gcloud

    1. 安装 Google Cloud CLI,然后通过运行以下命令初始化 Google Cloud CLI:

      gcloud init
    2. 设置默认区域和可用区

    Python

    如需从本地开发环境使用本页面上的 Python 示例,请安装并初始化 gcloud CLI,然后使用用户凭据设置应用默认凭据。

    1. 安装 Google Cloud CLI。
    2. 如需初始化 gcloud CLI,请运行以下命令:

      gcloud init
    3. 为您的 Google 账号创建本地身份验证凭据:

      gcloud auth application-default login

    如需了解详情,请参阅 为本地开发环境设置身份验证

概览

当您启用使用情况报告时,Compute Engine 会向您指定的 Cloud Storage 存储桶传送两种类型的报告:

  1. 每日使用情况报告

    这些报告每日传送,其中包含前一天的使用情况数据。每份报告都是一个单独的文件,包含上一时间范围的数据。这些报告中的数据都是不可变的,这意味着如果数据不准确,Compute Engine 不会更新或重写日志文件。不过,系统会在传送到存储桶的下一份新报告中更正这些数据。

    每日使用情况报告的名称格式如下:

    <bucket>/<report_prefix>_<numeric_project_id>_<YYYYMMDD>.csv
    
  2. 每月汇总报告

    每月汇总报告每日都会传送一份,这些报告包含截至当日(但不包括当日)为止该项目的每月使用情况数据。每月使用情况报告每天都会被新数据覆盖,这些新数据反映了截至此日期为止资源的每月使用情况。每个项目每个月只有一个每月使用情况数据文件。

    每月汇总报告的名称格式如下:

    <bucket>/<report_prefix>_<numeric_project_id>_<YYYYMM>.csv
    

    每日报告文件与每月报告文件非常相似,差别仅在于日期格式。每月汇总报告的日期采用年月格式 (YYYYMM),而每日使用情况报告的日期采用年月日格式 (YYYYMMDD)。

所有用量报告均以英文逗号分隔值 (CSV) 格式传送,并使用 <report_prefix> 作为前缀。用户可以自定义 <report_prefix> 的值。如果您未指定报告前缀,系统会默认使用前缀 usage_gce。所有时间均采用太平洋时间 (PST)。

前提条件

在开始使用 Compute Engine 使用情况导出功能之前,请先完成以下步骤:

设置使用情况导出功能

当您首次启用使用情况导出功能时,第一份报告会在第二天发出,其中详细说明了前一天的使用情况。此后,您每隔 24 小时就会收到一份报告。

如需设置使用情况导出功能,请使用 gcloud compute 工具启用该功能。启用该功能时,您必须定义以下两个属性:

  1. 将接收报告的 Cloud Storage 存储桶

    您可以选择自己拥有的任何 Cloud Storage 存储桶(包括不同项目中的存储桶)。在开始导出报告之前,此存储桶必须已存在,并且您必须拥有对此存储桶的所有者权限。Cloud Storage 会针对使用情况收费,因此,您应查看 Cloud Storage 价格,以了解使用该服务可能产生的费用。

    对 Cloud Storage 存储桶有读取权限的用户可以查看存储桶中的使用情况报告。对 Cloud Storage 存储桶有写入权限的用户可以创建、查看和修改存储桶中的现有文件。如需了解详情,请参阅访问权限控制部分。

  2. 您的文件的报告前缀

    您可以指定要用于使用情况报告的报告前缀。您的使用情况报告的文件名将会包含此前缀。例如,如果将“my-cool-project-report”指定为报告前缀,则系统会生成类似于 my-cool-project-report_1234567890_20131230.csv 格式的文件名。如果您没有指定报告前缀,则系统会默认使用 usage_gce 前缀。

确定这两个属性后,您可以通过以下方法启用使用情况导出功能:

控制台

  1. 转到 Compute Engine“设置”页面

    转到 Compute Engine“设置”

  2. 选中启用使用情况导出功能复选框。

  3. 填写要求输入存储桶名称的字段。(可选)根据需要提供报告前缀。如果您将报告前缀留空,则系统会默认使用 usage_gce 前缀。传送到该存储桶的所有使用情况报告都会使用此前缀命名。

  4. 点击保存

gcloud

gcloud compute 中,使用 gcloud compute project-info set-usage-bucket 命令启用此功能。

 gcloud compute project-info set-usage-bucket --bucket [BUCKET_NAME] [--prefix [PREFIX]]

其中:

  • [BUCKET_NAME] 是接收使用情况报告的现有存储桶的名称。必须采用 gs://<bucket-name>https://storage.googleapis.com/<bucket-name> 格式。运行此命令的用户必须是该存储桶的所有者。
  • [PREFIX] 是使用情况报告名称的可选前缀。如果未指定,则使用默认前缀 usage_gce

Python

如需启用使用情况导出功能,请使用 Projects 集合中的 set_usage_export_bucket() 方法。以下示例使用 Python 版 Cloud 客户端库:

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1

def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result

def set_usage_export_bucket(
    project_id: str, bucket_name: str, report_name_prefix: str = ""
) -> None:
    """
    Set Compute Engine usage export bucket for the Cloud project.
    This sample presents how to interpret the default value for the
    report name prefix parameter.

    Args:
        project_id: project ID or project number of the project to update.
        bucket_name: Google Cloud Storage bucket used to store Compute Engine
            usage reports. An existing Google Cloud Storage bucket is required.
        report_name_prefix: Prefix of the usage report name which defaults to an empty string
            to showcase default values behaviour.
    """
    usage_export_location = compute_v1.UsageExportLocation()
    usage_export_location.bucket_name = bucket_name
    usage_export_location.report_name_prefix = report_name_prefix

    if not report_name_prefix:
        # Sending an empty value for report_name_prefix results in the
        # next usage report being generated with the default prefix value
        # "usage_gce". (ref: https://cloud.google.com/compute/docs/reference/rest/v1/projects/setUsageExportBucket)
        print(
            "Setting report_name_prefix to empty value causes the report "
            "to have the default prefix of `usage_gce`."
        )

    projects_client = compute_v1.ProjectsClient()
    operation = projects_client.set_usage_export_bucket(
        project=project_id, usage_export_location_resource=usage_export_location
    )

    wait_for_extended_operation(operation, "setting GCE usage bucket")

如需了解详情,请参阅 projects.setUsageExportBucket 的 API 参考文档。

下载使用情况导出报告

开始在您的存储桶中接收使用情况报告后,请像从 Cloud Storage 中下载其他对象一样下载报告。如需了解详情,请参阅下载对象

支持的指标

每日使用情况报告提供以下资源的使用情况信息:

  • 虚拟机
  • 永久性磁盘
  • 映像
  • 快照
  • 静态 IP 地址
  • 负载均衡器
  • 预留

系统使用以下指标描述每个资源:

指标名称 指标属性
Report Date
  • 指标类型:字符串
  • 说明:使用情况的日期。
  • 示例:2019-08-15
MeasurementId
  • 指标类型:字符串
  • 说明:受测资源的类型 ID。
    例如,VmimageN2StandardCore_Uswest2 表示 us-west2 机器类型中的 n2-standard
  • 示例:com.google.cloud/services/compute‑engine/VmimageN2StandardCore_Uswest2
  • 示例:com.google.cloud/services/compute‑engine/VmimageN2StandardRam_Uswest2
数量
  • 指标类型:整数
  • 说明:指定日期的使用量。
  • 示例:86400
Unit
  • 指标类型:字符串
  • 说明:单位类型,如计数、秒、小时等。
  • 示例:秒
Resource URI
  • 指标类型:字符串
  • 说明:指定资源的 URI。
  • 示例:https://compute.googleapis.com/compute/v1/projects/<project‑id>/zones/<zone>/instances/<instance>
ResourceId
  • 指标类型:整数
  • 说明:标识特定资源的数字 ID。
  • 示例:16557630484925648021
位置
  • 指标类型:字符串
  • 说明:资源的位置。通常为地区或区域名称;如果是全球性资源,则为 GLOBAL
  • 示例:us-central1-a

报告中条目的示例如下:

Report Date MeasurementId 数量 Unit Resource URI Resource ID 位置
02/13/2019 com.google.cloud/services/compute-engine/VmimageE2Standard_2 86400 seconds https://compute.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/instances/my-instance 16557630484 us-central1-a

访问权限控制

当您为 Cloud Storage 存储桶启用使用情况导出功能后,Compute Engine 会自动将自身添加到其拥有写入权限的存储桶,以便传送使用情况报告。只要 Compute Engine 有权访问存储桶,并且使用情况导出功能已启用,Compute Engine 就会继续将使用情况报告导出到指定的 Cloud Storage 存储桶。

如果您看到存储桶 IAM 政策中添加了以下身份,则可以确定 Compute Engine 有权访问该存储桶:

cloud-cluster-analytics-export@google.com

身为项目所有者的所有用户均拥有对 Cloud Storage 存储桶的完整访问权限。其他用户(如写入者和读取者)对存储桶有不同程度的访问权限。如需了解存储桶的 IAM,请参阅 Cloud Storage 的 IAM

如果您停用使用情况导出功能,Compute Engine 会自动将其对存储桶的写入权限移除。如果您修改 cloud-cluster-analytics-export@google.com 账号的权限,然后停用使用情况导出功能,则 Compute Engine 会停用使用情况导出功能,但不会从项目访问权限列表中移除该账号。如果需要,您可以选择手动移除账号。

检查使用情况报告是否已启用

您可以通过获取项目相关信息来检查项目的使用情况导出功能设置:

gcloud compute project-info describe

查找 usageExportLocation 字段:

+-------------------------+----------------------------------------------------+
| name                    | myproject                                          |
| description             |                                                    |
| creation-time           | 2019-10-18T16:31:52.308-07:00                      |
| usage                   |                                                    |
|   snapshots             | 1.0/1000.0                                         |
|   networks              | 2.0/2.0                                            |
|   firewalls             | 3.0/10.0                                           |
|...                      |                                                    |
| usageExportLocation     |                                                    |
|   bucketName            | https://storage.googleapis.com/usage-export-sample |
|   reportNamePrefix      |                                                    |
+-------------------------+----------------------------------------------------+

停用使用情况报告

当您停用使用情况报告时,Compute Engine 会自动移除其对 Cloud Storage 存储桶的写入权限,并停止发送新报告。

控制台

  1. 转到 Compute Engine“设置”页面

    转到 Compute Engine“设置”

  2. 取消选中启用使用情况导出功能复选框即可停用使用情况导出功能。

gcloud

gcloud compute 中,通过运行带有 --no-bucket 标志的 gcloud compute project-info set-usage-bucket 命令来停用使用情况导出功能:

gcloud compute project-info set-usage-bucket --no-bucket

Python

如需停用使用情况导出功能,请使用 Projects 集合中的 set_usage_export_bucket() 方法并将 usage_export_location_resource 设置为 None。以下示例使用 Python 版 Cloud 客户端库:

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1

def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result

def disable_usage_export(project_id: str) -> None:
    """
    Disable Compute Engine usage export bucket for the Cloud Project.

    Args:
        project_id: project ID or project number of the project to update.
    """
    projects_client = compute_v1.ProjectsClient()

    # Setting `usage_export_location_resource` to an
    # empty object will disable the usage report generation.
    operation = projects_client.set_usage_export_bucket(
        project=project_id, usage_export_location_resource={}
    )

    wait_for_extended_operation(operation, "disabling GCE usage bucket")

后续步骤