צפייה בדוחות שימוש

באמצעות התכונה לייצוא נתוני שימוש ב-Compute Engine, אפשר לייצא דוחות מפורטים של השימוש ב-Compute Engine לקטגוריה של Cloud Storage.

דוחות השימוש מספקים מידע על משך החיים של המשאבים. לדוגמה, אפשר לראות כמה מופעים של מכונות וירטואליות בפרויקט מריצים סוג מכונה n2-standard-4 וכמה זמן כל מופע פועל. אפשר גם לבדוק את נפח האחסון של דיסק מתמשך ומידע על תכונות אחרות של Compute Engine.

דוחות השימוש לא מספקים מידע על חיוב או על פעילות, כמו מידע על בקשות API. מידע על חיוב זמין במאמר ייצוא נתוני החיוב ב-Cloud ל-BigQuery. כדי לראות תיעוד של פעילויות הניהול והגישה במשאביGoogle Cloud , קראו את המאמר יומני ביקורת.

לפני שמתחילים

  • אם עדיין לא עשיתם את זה, תצטרכו להגדיר אימות. אימות הוא תהליך שבו מאמתים את הזהות שלכם כדי לקבל גישה לממשקי API ולשירותים של Google Cloud . כדי להריץ קוד או דוגמאות מסביבת פיתוח מקומית, אפשר לבצע אימות ל-Compute Engine באחת מהדרכים הבאות:

    כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של Python שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

    1. התקינו את ה-CLI של Google Cloud.

    2. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

    3. אם אתם משתמשים במעטפת מקומית, צרו פרטי כניסה לאימות מקומי בחשבון המשתמש:

      gcloud auth application-default login

      אם אתם משתמשים ב-Cloud Shell, אתם לא צריכים לעשות את זה.

      אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

    למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

סקירה כללית

כשמפעילים דוחות שימוש, 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.

אחרי שתבחרו את שני הנכסים האלה, תוכלו להפעיל את התכונה של ייצוא נתוני השימוש באחת מהדרכים הבאות:

Python

כדי להפעיל ייצוא של נתוני שימוש, משתמשים ב-method ‏set_usage_export_bucket() באוסף Projects. בדוגמה הבאה נעשה שימוש בספריות הלקוח של Cloud ל-Python:

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")

למידע נוסף, קראו את מאמרי העזרה של REST בנושא projects.setUsageExportBucket.

הורדה של דוחות ייצוא של נתוני שימוש

אחרי שתתחילו לקבל דוחות שימוש בקטגוריה, תוכלו להוריד את הדוחות כמו שמורידים אובייקטים אחרים מ-Cloud Storage. מידע נוסף זמין במאמר הורדת אובייקטים.

מדדים נתמכים

דוחות שימוש יומיים מספקים נתוני שימוש על המשאבים הבאים:

  • מכונות וירטואליות
  • דיסקים לאחסון מתמיד (persistent disks)
  • תמונות
  • תמונות מצב
  • כתובות IP סטטיות
  • מאזני עומסים
  • הזמנות

כל משאב מתואר באמצעות המדדים הבאים:

שם המדד מאפייני המדד
תאריך הדוח
  • סוג המדד: מחרוזת
  • תיאור: תאריך השימוש.
  • דוגמה: 2019-08-15
MeasurementId
  • סוג המדד: מחרוזת
  • תיאור: המזהה של סוג המשאב שנמדד.
    לדוגמה, VmimageN2StandardCore_Uswest2 כדי לייצג n2-standard סוג מכונה ב-us-west2.
  • לדוגמה: com.google.cloud/services/compute‑engine/VmimageN2StandardCore_Uswest2
  • לדוגמה: com.google.cloud/services/compute‑engine/VmimageN2StandardRam_Uswest2
כמות
  • סוג המדד: מספר שלם
  • תיאור: כמות השימוש בתאריך שצוין.
  • דוגמה: 86400
יחידה
  • סוג המדד: מחרוזת
  • תיאור: סוג היחידה, כמו count,‏ seconds או hours.
  • דוגמה: שניות
‫URI של המשאב
  • סוג המדד: מחרוזת
  • תיאור: ה-URI של המשאב שצוין.
  • לדוגמה: https://compute.googleapis.com/compute/v1/projects/my-project/zones/us-central1-a/instances/my-n2-vm
ResourceId
  • סוג המדד: מספר שלם
  • תיאור: מזהה מספרי שמזהה את המשאב הספציפי.
  • דוגמה: 16557630484925648021
מיקום
  • סוג המדד: מחרוזת
  • תיאור: המיקום של המשאב. שם של אזור או תחום (zone), או GLOBAL למשאבים גלובליים.
  • לדוגמה: us-central1-a

דוגמה לרשומה בדוח:

תאריך הדוח MeasurementId כמות יחידה ‫URI של המשאב מזהה המשאב מיקום
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 יש גישה לקטגוריה והתכונה של ייצוא נתוני השימוש מופעלת, המערכת ממשיכה לייצא דוחות שימוש לקטגוריה שצוינה ב-Cloud Storage.

אפשר לראות של-Compute Engine יש גישה לקטגוריה אם הזהות הבאה מתווספת למדיניות ה-IAM של הקטגוריה:

cloud-cluster-analytics-export@google.com

לכל משתמש שהוא בעלים של הפרויקט יש גישה מלאה לקטגוריה של Cloud Storage. למשתמשים אחרים, כמו כותבים וקוראים, יש רמות גישה שונות לקטגוריה. מידע על IAM לקטגוריות זמין במאמר IAM ל-Cloud Storage.

אם משביתים את התכונה של ייצוא נתוני השימוש, 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, ומפסיקה לשלוח דוחות חדשים.

Python

כדי להשבית את הייצוא של נתוני השימוש, משתמשים ב-method‏ set_usage_export_bucket() באוסף Projects, ומגדירים את usage_export_location_resource לערך None. בדוגמה הבאה נעשה שימוש בספריות הלקוח של Cloud ל-Python:

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")

המאמרים הבאים