使用状況レポートの表示


Compute Engine では、使用状況データのエクスポート機能を使用して、Compute Engine の使用状況データに関する詳細なレポートを Cloud Storage バケットにエクスポートできます。使用状況レポートには、リソースの使用期間に関する情報が表示されます。たとえば、n2-standard-4 マシンタイプを実行しているプロジェクト内のインスタンスの数や、各インスタンスが実行されている期間を確認できます。永続ディスクの保存容量や、Compute Engine のその他の機能に関する情報も確認できます。

使用状況レポートには、お支払い情報やアクティビティ情報(API リクエストに関する情報など)は表示されません。お支払い情報については、課金データのエクスポート機能をご覧ください。アクティビティ ログについては、アクティビティ ログをご覧ください。

始める前に

  • まだ設定していない場合は、認証を設定します。認証とは、Google Cloud サービスと API にアクセスするために ID を確認するプロセスです。ローカル開発環境からコードまたはサンプルを実行するには、次のように Compute Engine に対する認証を行います。

    このページのサンプルをどのように使うかに応じて、タブを選択してください。

    コンソール

    Google Cloud コンソールを使用して Google Cloud サービスと API にアクセスする場合、認証を設定する必要はありません。

    gcloud

    1. 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 バケットに 2 種類のレポートが配信されます。

  1. 日次使用状況レポート

    このレポートは毎日配信されるもので、前日からの使用状況データが示されています。各レポートは、前回の期間からのデータを示す個別のファイルです。このレポートのデータは変更できません。つまり、誤りがあった場合でも、Compute Engine によってログファイルが更新されたり書き換えられたりすることはありません。代わりに、データは、バケットに次回配信される新しいレポートで修正されます。

    日次使用状況レポートの名前形式は次のとおりです。

    <bucket>/<report_prefix>_<numeric_project_id>_<YYYYMMDD>.csv
    
  2. 月次ロールアップ レポート

    月次ロールアップ レポートは毎日 1 件配信されるもので、その日の前日までのそのプロジェクトに関する月次使用状況データが示されています。月次使用状況レポートは毎日新しいデータで上書きされ、その日までのリソースの月次使用状況が反映されます。月間使用状況データファイルは、プロジェクトごとに、1 か月あたり 1 つだけです。

    月次ロールアップ レポートの名前形式は次のとおりです。

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

    日次レポート ファイルと月次レポート ファイルはよく似ていますが、日付形式が異なります。月次ロールアップ レポートでは年と月(YYYYMM)が使用されますが、日次使用状況レポートでは年、月、日(YYYYMMDD)が使用されます。

使用状況レポートはすべてカンマ区切り値(CSV)形式で配信され、レポートのファイル名には接頭辞 <report_prefix> が付けられます。<report_prefix> はユーザーが選択するカスタマイズ可能な値です。レポート接頭辞を指定しない場合は、デフォルトで接頭辞 usage_gce が使用されます。時間はすべて太平洋時間(PST)で表記されます。

前提条件

Compute Engine の使用状況データのエクスポートを使用する前に、次のことを行います。

使用状況データのエクスポートを設定する

使用状況データのエクスポート機能を初めて有効にしたときは、その翌日に、前日の使用状況の詳細を示す最初のレポートが送信されます。その後、レポートは 24 時間間隔で届きます。

使用状況データのエクスポート機能を設定するには、gcloud compute ツールでこの機能を有効にします。この機能を有効にするときは、2 つのプロパティを定義する必要があります。

  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 が使用されます。

これら 2 つのプロパティを決定したら、使用状況データのエクスポート機能を次の方法で有効にすることができます。

Console

  1. Compute Engine の設定ページに移動します。

    Compute Engine の設定に移動

  2. [使用量データのエクスポートを有効にする] チェックボックスをオンにします。

  3. [バケット名] フィールドに入力します。必要に応じて、[レポート接頭辞] を入力します。レポート接頭辞を指定しなかった場合は、デフォルトの接頭辞 usage_gce が使用されます。バケットに配信されるすべての使用状況レポートには、この接頭辞が付きます。

  4. [保存] をクリックします。

gcloud

この機能を有効にするには、gcloud computegcloud 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 アドレス
  • ロードバランサ
  • 予約

各リソースについては以下の指標を使用して記載されます。

指標名 指標プロパティ
レポート生成日
  • 指標タイプ: string
  • 説明: 使用状況の日付。
  • 例: 2019-08-15
MeasurementId
  • 指標タイプ: string
  • 説明: 測定されているリソースのタイプの ID。
    たとえば、VmimageN2StandardCore_Uswest2us-west2 マシンタイプn2-standard を表します。
  • 例: com.google.cloud/services/compute‑engine/VmimageN2StandardCore_Uswest2
  • 例: com.google.cloud/services/compute‑engine/VmimageN2StandardRam_Uswest2
数量
  • 指標タイプ: integer
  • 説明: 指定した日付の使用量。
  • 例: 86400
単位
  • 指標タイプ: string
  • 説明: 数、秒、時間などの単位のタイプ。
  • 例: 秒
リソースの URI
  • 指標タイプ: string
  • 説明: 指定したリソースの URI。
  • 例: https://compute.googleapis.com/compute/v1/projects/<project‑id>/zones/<zone>/instances/<instance>
ResourceId
  • 指標タイプ: integer
  • 説明: 特定のリソースを識別する数値 ID。
  • 例: 16557630484925648021
ロケーション
  • 指標タイプ: string
  • 説明: リソースのロケーション。ゾーン名またはリージョン名(グローバル リソースの場合は GLOBAL)。
  • 例: us-central1-a

レポート内のエントリの例は次のようになります。

レポート生成日 MeasurementId 数量 単位 リソースの URI リソース ID ロケーション
02/13/2019 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 ポリシーに追加された次の ID から、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 で、gcloud compute project-info set-usage-bucket コマンドと --no-bucket フラグを使用して、使用状況データのエクスポート機能を無効にします。

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

Python

使用状況のエクスポートを無効にするには、usage_export_location_resourceNone に設定して 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 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")

次のステップ