사용량 보고서 보기


Compute Engine에서는 사용량 내보내기 기능을 사용하여 Compute Engine 사용량의 세부 보고서를 Cloud Storage 버킷으로 내보낼 수 있습니다. 사용량 보고서에는 리소스 수명에 대한 정보도 나와 있습니다. 예를 들어 프로젝트에서 n2-standard-4 머신 유형을 실행 중인 VM 인스턴스 수와 각 인스턴스가 실행되고 있는 시간을 확인할 수 있습니다. 영구 디스크의 저장공간과 기타 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 버킷에 다음과 같은 두 가지 보고서를 전달합니다.

  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 버킷에 대한 읽기 액세스 권한이 있는 모든 사용자는 버킷에 있는 사용량 보고서를 볼 수 있습니다. 버킷에 대한 쓰기 액세스 권한이 있는 모든 사용자는 버킷에 파일을 만들고 기존 파일을 보고 수정할 수 있습니다. 자세한 내용은 액세스 제어 섹션을 참조하세요.

  2. 파일의 보고서 프리픽스

    사용량 보고서에 사용할 보고서 프리픽스를 지정할 수 있습니다. 이 프리픽스는 사용량 보고서의 파일 이름에 포함됩니다. 예를 들어 보고서 프리픽스로 'my-cool-project-report'를 지정하면 my-cool-project-report_1234567890_20131230.csv와 유사한 형식의 파일 이름이 생성됩니다. 보고서 프리픽스를 지정하지 않으면 기본 프리픽스 usage_gce가 사용됩니다.

이 두 가지 속성을 결정했으면 다음과 같은 방법으로 사용량 내보내기 기능을 사용 설정할 수 있습니다.

Console

  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 주소
  • 부하 분산기
  • 예약

각 리소스의 사용량은 다음과 같은 측정항목을 사용하여 기술됩니다.

측정항목 이름 측정항목 속성
보고서 작성일
  • 측정항목 유형: 문자열
  • 설명: 사용 날짜
  • 예: 2019-08-15
측정 ID
  • 측정항목 유형: 문자열
  • 설명: 측정 대상 리소스 유형의 ID.
    예를 들어 us-west2 머신 유형n2-standard를 나타내는 VmimageN2StandardCore_Uswest2입니다.
  • 예: 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/<project‑id>/zones/<zone>/instances/<instance>
리소스 ID
  • 측정항목 유형: 정수
  • 설명: 특정 리소스를 식별하는 숫자 ID
  • 예: 16557630484925648021
위치
  • 측정항목 유형: 문자열
  • 설명: 리소스의 위치. 영역 또는 리전 이름이나 GLOBAL(전역 리소스의 경우).
  • 예: us-central1-a

다음은 이 보고서의 예시 항목입니다.

보고서 작성일 측정 ID 수량 단위 리소스 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에서 --no-bucket 플래그로 gcloud compute project-info set-usage-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")

다음 단계