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

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

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

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

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

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

    צריך לבחור את הכרטיסייה הרלוונטית לאופן שבו תכננתם להשתמש בדוגמאות בדף הזה:

    gcloud

    1. התקינו את ה-CLI של Google Cloud. אחר כך, אתחלו את ה-CLI של Google Cloud באמצעות הפקודה הבאה:

      gcloud init

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

  • הגדרת אזור ותחום כברירת מחדל
  • Python

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

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

gcloud

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

כדי להפעיל את הייצוא של נתוני השימוש, משתמשים ב-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. מידע נוסף זמין במאמר הורדת אובייקטים.

מדדים נתמכים

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

  • מכונות וירטואליות
  • דיסקים לאחסון מתמיד
  • תמונות
  • Snapshots
  • כתובות 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 יש גישה לקטגוריה ותכונת ייצוא השימוש מופעלת,‏ 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 ומפסיקה לשלוח דוחות חדשים.

gcloud

כדי להשבית את התכונה של ייצוא נתוני השימוש, משתמשים בפקודה gcloud compute project-info set-usage-bucket עם הדגל --no-bucket:

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

Python

כדי להשבית את ייצוא נתוני השימוש, משתמשים בשיטה 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")

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