查看使用報告

Compute Engine 的用量匯出功能可讓您將 Compute Engine 用量的詳細報表匯出至 Cloud Storage bucket。

用量報表提供的資訊與資源的生命週期相關。舉例來說,您可以查看專案中有多少 VM 執行個體正在執行 n2-standard-4 機型,以及每個執行個體已執行的時間長度。您也可以查看永久磁碟的儲存空間,以及其他 Compute Engine 功能的相關資訊。

用量報表不會提供帳單或活動資訊,例如 API 要求的相關資訊。如需帳單資訊,請參閱「將 Cloud Billing 資料匯出至 BigQuery」。如要查看Google Cloud 資源中的管理活動和存取記錄,請參閱「稽核記錄」。

事前準備

  • 如果尚未設定驗證,請先完成設定。 驗證可確認您的身分,以便存取 Google Cloud 服務和 API。如要從本機開發環境執行程式碼或範例,請選取下列其中一個選項,向 Compute Engine 進行驗證:

    如要在本機開發環境中使用本頁的 Python 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用 Cloud Shell,則不需要執行這項操作。

      如果系統傳回驗證錯誤,且您使用外部識別資訊提供者 (IdP),請確認您已 使用聯合身分登入 gcloud CLI。

    詳情請參閱「 設定本機開發環境的驗證機制」。

總覽

啟用用量報表後,Compute Engine 會將兩種類型的報表傳送至您指定的 Cloud Storage bucket:

  1. 每日用量報表

    系統每天都會發送這種報表,提供您前一天使用情形的資料。每個報表均為單獨的檔案,內容包含上一段期間的資料。這些報表中的資料不可變更,也就是說,如果資料不正確,Compute Engine 不會更新或重寫記錄檔。但會在下一份傳送到值區的新報表中修正資料。

    每日用量報表的名稱格式如下:

     <bucket>/<reportprefix><numeric_projectid><YYYYMMDD>.csv
     

  2. 每月總計報表

    系統每天會發送單一的每月總計報表,裡面會包含該專案截至當天的每月用量資料 (當天的用量不包含在內)。系統每天均會使用新資料覆寫每月用量報表,顯示資源到該日為止每個月的使用情況。每項專案每月只會產生一個每月用量資料檔案。

    每月總計報表的名稱格式如下:

     <bucket>/<reportprefix><numeric_projectid><YYYYMM>.csv
     

    每日報表與每月報表檔案的名稱十分相似,差別僅在於日期格式。每月總計報表的日期格式為年度與月份 (YYYYMM);每日使用情況報表則是使用年度、月份、日期 (YYYYMMDD)。

所有用量報表都採用逗號分隔值 (CSV) 格式,且用量報表檔案會加上 <report_prefix> 前置字元。<report_prefix> 是使用者選擇的可自訂值。如未指定報表前置字串,系統預設會使用 usage_gce 前置字串。所有時間均以太平洋標準時間 (PST) 為準。

必要條件

開始使用 Compute Engine 用量匯出功能前,請先完成下列步驟:

設定用量報表

首次啟用用量匯出功能時,系統會在隔天傳送第一份報表,詳細列出前一天的用量。之後,您會每隔 24 小時收到報告。

啟用這項功能時,您必須定義兩個屬性:

  1. 要接收報表的 Cloud Storage bucket。

    您可以選取任何您是擁有者的 Cloud Storage bucket,包括來自不同專案的 bucket。該值區必須在您開始匯出報表前便已經存在,而且您還需要有值區的擁有者權限。Cloud Storage 會依用量收費,因此請參閱 Cloud Storage 定價,瞭解這項服務的收費方式。

    只要使用者有 Cloud Storage bucket 的讀取權限,就能查看 bucket 中的用量報表。只要使用者具備 bucket 的寫入權限,就能在 bucket 中建立、查看及修改現有檔案。詳情請參閱「存取控管」一節。

  2. 檔案的報表前置字串

    您可以指定用量報表所用的報表前置字串,使用量報告的檔案名稱會包含這個前置字串。舉例來說,如果將「my-cool-project-report」指定為報表前置字串,產生的檔案名稱會類似於 my-cool-project-report_1234567890_20131230.csv 格式。如未指定報表前置字元,系統會使用預設前置字元 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 的 REST 參考文件。

下載使用情形匯出報表

開始在 bucket 中收到使用量報表後,請下載報表,就像從 Cloud Storage 下載其他物件一樣。詳情請參閱「下載物件」。

支援的指標

每日用量報表會提供下列資源的使用資訊:

  • 虛擬機器
  • 永久磁碟
  • 映像檔
  • 快照
  • 靜態 IP 位址
  • 負載平衡器
  • 預留項目

每個資源的相關資訊均以下列指標呈現:

指標名稱 指標屬性
報表日期
  • 指標類型:字串
  • 說明:使用情況的日期。
  • 範例: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
單位
  • 指標類型:字串
  • 說明:單位類型,例如次數、秒或小時。
  • 範例:秒數
資源 URI
  • 指標類型:字串
  • 說明:指定資源的 URI。
  • 例如:https://compute.googleapis.com/compute/v1/projects/my-project/zones/us-central1-a/instances/my-n2-vm
ResourceId
  • 指標類型:整數
  • 說明:識別特定資源的數字 ID。
  • 範例:16557630484925648021
位置
  • 指標類型:字串
  • 說明:資源的位置,可用區或區域名稱,或是全域資源的 GLOBAL。
  • 例如:us-central1-a

報表中各項目的範例如下:

報表日期 MeasurementId 數量 單位 資源 URI ResourceId 位置
2019/02/13 com.google.cloud/services/compute-engine/VmimageE2Standard_2 86400 秒 https://compute.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/instances/my-instance 16557630484 us-central1-a

存取控管

為 Cloud Storage bucket 啟用用量匯出功能後,Compute Engine 會自動將自己新增至 bucket,並取得寫入存取權,以便提供用量報表。只要 Compute Engine 可以存取 bucket,且已啟用使用量匯出功能,Compute Engine 就會繼續將用量報表匯出至指定的 Cloud Storage bucket。

如果看到下列身分新增至 bucket IAM 政策,即表示 Compute Engine 有權存取 bucket:

cloud-cluster-analytics-export@google.com

專案擁有者可完整存取 Cloud Storage bucket。其他使用者 (例如寫入者和讀取者) 對儲存空間的存取程度不同。如要瞭解 bucket 的 IAM,請參閱「Cloud Storage 的 IAM」。

停用使用量匯出功能後,Compute Engine 會自動移除 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 會自動移除 Compute Engine 對 Cloud Storage 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")

後續步驟