查看使用報告


在 Compute Engine 中,您可以透過用量匯出功能,將 Compute Engine 使用情形的詳細報表匯出至 Cloud Storage 值區。用量報表提供的資訊與資源的生命週期相關。舉例來說,您可以查看專案中執行 n2-standard-4 機器類型的 VM 執行個體數量,以及每個執行個體已執行多久時間。您也可以查看永久磁碟的儲存空間,以及其他 Compute Engine 功能的相關資訊。

不過報表並不會提供帳單資訊或活動資訊 (如 API 要求等)。如需查看帳單資訊,請使用將 Cloud Billing 資料匯出至 BigQuery 功能。如要查看Google Cloud 資源中的管理活動和存取權記錄,請參閱「稽核記錄」。

事前準備

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

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    1. After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    2. Set a default region and zone.

    Python

    To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    For more information, see Set up authentication for a local development environment.

總覽

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

  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 值區

    您可以選擇擁有的任何 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. 勾選「Enable usage export」方塊。

  3. 填入要求提供「Bucket name」的欄位。您可以選擇提供報表前置字串。如果您沒有填入報表的前置字串,系統會使用前置字串的預設值 usage_gce。所有傳送至這個值區的用量報表都會加上這個前置字串。

  4. 按一下 [儲存]

gcloud

使用 gcloud compute project-info set-usage-bucket 指令啟用這項功能:

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

更改下列內容:

  • BUCKET_NAME 是接收使用情形報表的現有值區名稱。名稱的格式必須為 gs://bucket-namehttps://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 的 REST 參考說明文件

下載使用量匯出報表

開始在值區中收到用量報表後,請按照從 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 年 2 月 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 值區的用量匯出功能後,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. 清除「Enable usage export」方塊,即可停用用量匯出功能。

gcloud

請使用帶有 --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")

後續步驟