אחזור נתונים של פעולות על ציר הזמן

במאמר הזה מוסבר איך לקרוא נתוני מדדים, שנקראים גם נתונים של סדרות זמן, באמצעות השיטה timeSeries.list ב-Monitoring API. יש כמה דרכים לקרוא לשיטה timeSeries.list:

  • אתם יכולים להשתמש בכרטיסיות Protocol בדף הזה כדי להשתמש ב-APIs Explorer מבוסס-טפסים.
  • אפשר להשתמש בספריית לקוח ספציפית לשפה.
  • אפשר להשתמש ב-Metrics Explorer.

דרך נוספת לקרוא את נתוני המדדים היא לשלוח פקודה ל-method‏ timeSeries.query, שנדרשת בה שפת שאילתת מעקב (MQL). במסמך הזה לא מתוארים MQL או השיטה timeSeries.query. מידע על הנושאים האלה זמין במאמר אחזור נתונים באמצעות timeSeries.query.

סקירה כללית

כל קריאה לשיטה timeSeries.list יכולה להחזיר כל מספר של סדרות זמן מסוג מדד יחיד. לדוגמה, אם אתם משתמשים ב-Compute Engine, למדד compute.googleapis.com/instance/cpu/usage_time יש סדרת זמן נפרדת לכל אחד מהמופעים של המכונות הווירטואליות. במאמר מדדים, סדרות זמנים ומשאבים מופיע מבוא למדדים ולסדרות זמנים.

כדי לציין את נתוני הסדרות העיתיות שרוצים, צריך לספק את הפרטים הבאים לשיטה timeSeries.list:

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

מסננים של נתונים כרונולוגיים

כדי לציין אילו סדרות זמנים לאחזר, מעבירים מסנן סדרות זמנים לשיטה timeSeries.list. הרשימה הבאה מפרטת את רכיבי המסנן הנפוצים:

  • המסנן חייב לציין סוג מדד יחיד. לדוגמה:

    metric.type = "compute.googleapis.com/instance/cpu/usage_time"
    

    כדי לאחזר מדדים שהוגדרו על ידי המשתמש, צריך לשנות את הקידומת metric.type במסנן ל-custom.googleapis.com או לקידומת אחרת אם נעשה בה שימוש. external.googleapis.com היא קידומת נפוצה.

  • במסנן אפשר לציין ערכים לתוויות המאפיינים של המדד. סוג המדד קובע אילו תוויות מוצגות. לדוגמה:

    (metric.label.instance_name = "your-instance-id" OR
    metric.label.instance_name = "your-other-instance-id")
    

    בביטוי הקודם, label הוא הערך הנכון למרות שאובייקט המדד בפועל משתמש ב-labels כמפתח שלו.

  • המסנן יכול לבחור רק את סדרות הזמן שמכילות סוג ספציפי של משאב שנמצא במעקב:

    resource.type = "gce_instance"
    

אפשר לשלב את רכיבי המסנן במסנן יחיד של סדרת זמן, כמו בדוגמה הבאה:

metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND
(metric.label.instance_name = "your-instance-id" OR
metric.label.instance_name = "your-other-instance-id")

אם לא מציינים ערכים לכל תוויות המדדים, השיטה list מחזירה סדרת זמנים לכל שילוב של ערכים בתוויות שלא צוינו. השיטה מחזירה רק סדרות זמן שיש בהן נתונים.

מרווחי זמן

כשמשתמשים ב-API כדי לקרוא נתונים, צריך לציין את מרווח הזמן שרוצים לאחזר עבורו נתונים על ידי הגדרת שעת התחלה ושעת סיום. ה-API מאחזר נתונים מהמרווח (start, end], כלומר, מהזמן שאחרי שעת ההתחלה ועד שעת הסיום.

שעת ההתחלה לא יכולה להיות מאוחרת משעת הסיום. אם מציינים שעת התחלה שמאוחרת משעת הסיום, ה-API מחזיר שגיאה.

אם רוצים לאחזר רק נתונים עם חותמת זמן ספציפית, צריך להגדיר את שעת ההתחלה כשווה לשעת הסיום, או לחלופין לא להגדיר את שעת ההתחלה.

פורמט השעה

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

2024-03-01T12:34:56+04:00
2024-03-01T12:34:56.992Z

הפקודה date -Iseconds ב-Linux שימושית ליצירת חותמות זמן.

פעולות בסיסיות ברשימה

אפשר להשתמש בשיטה timeSeries.list כדי להחזיר נתונים גולמיים פשוטים, או כדי להחזיר נתונים שעברו עיבוד מורכב. בקטע הזה מוסבר איך מציגים את סדרות הזמן הזמינות ואיך מקבלים את הערכים בסדרת זמן ספציפית.

דוגמה: הצגת סדרות זמנים זמינות

בדוגמה הזו מוצגות רק השמות והתיאורים של סדרות הזמן שתואמות למסנן, במקום להחזיר את כל הנתונים הזמינים:

פרוטוקול

  1. פותחים את דף העזר של timeSeries.list.

  2. בחלונית עם התווית Try this method (אפשר לנסות את השיטה הזו), מזינים את הפרטים הבאים:

    • name: מזינים את הנתיב לפרויקט.

      projects/PROJECT_ID
      
    • filter: מציינים את סוג המדד.

      metric.type = "compute.googleapis.com/instance/cpu/utilization"
      
    • interval.endTime: מזינים את שעת הסיום.
    • interval.startTime: מזינים את שעת ההתחלה ומוודאים שהיא מוקדמת ב-20 דקות משעת הסיום.
    • לוחצים על הצגת פרמטרים רגילים, ובשדות מזינים את הפרטים הבאים:

      timeSeries.metric
      
  3. לוחצים על Execute.

פלט הדוגמה מציג סדרות זמן של שתי מכונות VM שונות:

{
  "timeSeries": [
    {
      "metric": {
        "labels": {
          "instance_name": "your-first-instance"
        },
        "type": "compute.googleapis.com/instance/cpu/utilization"
      },
    },
    {
      "metric": {
        "labels": {
          "instance_name": "your-second-instance"
        },
        "type": "compute.googleapis.com/instance/cpu/utilization"
      },
    }
  ]
}

כדי לראות את הבקשה כפקודת curl, כבקשת HTTP או ב-JavaScript, לוחצים על מסך מלא ב-APIs Explorer.

C#

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

public static object ReadTimeSeriesFields(string projectId,
    string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
    Console.WriteLine($"metricType{ metricType}");
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    string filter = $"metric.type=\"{metricType}\"";
    ListTimeSeriesRequest request = new ListTimeSeriesRequest
    {
        ProjectName = new ProjectName(projectId),
        Filter = filter,
        Interval = new TimeInterval(),
        View = ListTimeSeriesRequest.Types.TimeSeriesView.Headers,
    };
    // Create timestamp for current time formatted in seconds.
    long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
    Timestamp startTimeStamp = new Timestamp();
    // Set startTime to limit results to the last 20 minutes.
    startTimeStamp.Seconds = timeStamp - (60 * 20);
    Timestamp endTimeStamp = new Timestamp();
    // Set endTime to current time.
    endTimeStamp.Seconds = timeStamp;
    TimeInterval interval = new TimeInterval();
    interval.StartTime = startTimeStamp;
    interval.EndTime = endTimeStamp;
    request.Interval = interval;
    // Make the request.
    PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
        metricServiceClient.ListTimeSeries(request);
    // Iterate over all response items, lazily performing RPCs as required.
    Console.Write("Found data points for the following instances:");
    foreach (var item in response)
    {
        Console.WriteLine(JObject.Parse($"{item}").ToString());
    }
    return 0;
}

Go

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"
	"time"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
	"github.com/golang/protobuf/ptypes/timestamp"
	"google.golang.org/api/iterator"
)

// readTimeSeriesFields reads the last 20 minutes of the given metric, aligns
// everything on 10 minute intervals, and combines values from different
// instances.
func readTimeSeriesFields(w io.Writer, projectID string) error {
	ctx := context.Background()
	client, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricClient: %w", err)
	}
	defer client.Close()
	startTime := time.Now().UTC().Add(time.Minute * -20)
	endTime := time.Now().UTC()
	req := &monitoringpb.ListTimeSeriesRequest{
		Name:   "projects/" + projectID,
		Filter: `metric.type="compute.googleapis.com/instance/cpu/utilization"`,
		Interval: &monitoringpb.TimeInterval{
			StartTime: &timestamp.Timestamp{
				Seconds: startTime.Unix(),
			},
			EndTime: &timestamp.Timestamp{
				Seconds: endTime.Unix(),
			},
		},
		View: monitoringpb.ListTimeSeriesRequest_HEADERS,
	}
	fmt.Fprintln(w, "Found data points for the following instances:")
	it := client.ListTimeSeries(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("could not read time series value: %w", err)
		}
		fmt.Fprintf(w, "\t%v\n", resp.GetMetric().GetLabels()["instance_name"])
	}
	fmt.Fprintln(w, "Done")
	return nil
}

Java

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

String projectId = System.getProperty("projectId");
ProjectName name = ProjectName.of(projectId);

// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
TimeInterval interval =
    TimeInterval.newBuilder()
        .setStartTime(Timestamps.fromMillis(startMillis))
        .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
        .build();

ListTimeSeriesRequest.Builder requestBuilder =
    ListTimeSeriesRequest.newBuilder()
        .setName(name.toString())
        .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
        .setInterval(interval)
        .setView(ListTimeSeriesRequest.TimeSeriesView.HEADERS);

ListTimeSeriesRequest request = requestBuilder.build();

try (final MetricServiceClient client = MetricServiceClient.create();) {
  ListTimeSeriesPagedResponse response = client.listTimeSeries(request);
  System.out.println("Got timeseries headers: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
}

Node.js

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

async function readTimeSeriesFields() {
  /**
   * TODO(developer): Uncomment and edit the following lines of code.
   */
  // const projectId = 'YOUR_PROJECT_ID';

  const request = {
    name: client.projectPath(projectId),
    filter: 'metric.type="compute.googleapis.com/instance/cpu/utilization"',
    interval: {
      startTime: {
        // Limit results to the last 20 minutes
        seconds: Date.now() / 1000 - 60 * 20,
      },
      endTime: {
        seconds: Date.now() / 1000,
      },
    },
    // Don't return time series data, instead just return information about
    // the metrics that match the filter
    view: 'HEADERS',
  };

  // Writes time series data
  const [timeSeries] = await client.listTimeSeries(request);
  console.log('Found data points for the following instances:');
  timeSeries.forEach(data => {
    console.log(data.metric.labels.instance_name);
  });
}
readTimeSeriesFields();

PHP

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest\TimeSeriesView;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Protobuf\Timestamp;

/**
 * Example:
 * ```
 * read_timeseries_fields($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function read_timeseries_fields(string $projectId, int $minutesAgo = 20): void
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = 'projects/' . $projectId;
    $filter = 'metric.type="compute.googleapis.com/instance/cpu/utilization"';

    $startTime = new Timestamp();
    $startTime->setSeconds(time() - (60 * $minutesAgo));
    $endTime = new Timestamp();
    $endTime->setSeconds(time());

    $interval = new TimeInterval();
    $interval->setStartTime($startTime);
    $interval->setEndTime($endTime);

    $view = TimeSeriesView::HEADERS;
    $listTimeSeriesRequest = (new ListTimeSeriesRequest())
        ->setName($projectName)
        ->setFilter($filter)
        ->setInterval($interval)
        ->setView($view);

    $result = $metrics->listTimeSeries($listTimeSeriesRequest);

    printf('Found data points for the following instances:' . PHP_EOL);
    foreach ($result->iterateAllElements() as $timeSeries) {
        printf($timeSeries->getMetric()->getLabels()['instance_name'] . PHP_EOL);
    }
}

Python

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"
now = time.time()
seconds = int(now)
nanos = int((now - seconds) * 10**9)
interval = monitoring_v3.TimeInterval(
    {
        "end_time": {"seconds": seconds, "nanos": nanos},
        "start_time": {"seconds": (seconds - 1200), "nanos": nanos},
    }
)
results = client.list_time_series(
    request={
        "name": project_name,
        "filter": 'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
        "interval": interval,
        "view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.HEADERS,
    }
)
for result in results:
    print(result)

Ruby

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

gem "google-cloud-monitoring"
require "google/cloud/monitoring"

# Your Google Cloud Platform project ID
# project_id = "YOUR_PROJECT_ID"

client = Google::Cloud::Monitoring.metric_service
project_name = client.project_path project: project_id

interval = Google::Cloud::Monitoring::V3::TimeInterval.new
now = Time.now
interval.end_time = Google::Protobuf::Timestamp.new seconds: now.to_i,
                                                    nanos:   now.nsec
interval.start_time = Google::Protobuf::Timestamp.new seconds: now.to_i - 1200,
                                                      nanos:   now.nsec
filter = 'metric.type = "compute.googleapis.com/instance/cpu/utilization"'
view = Google::Cloud::Monitoring::V3::ListTimeSeriesRequest::TimeSeriesView::HEADERS

results = client.list_time_series name:     project_name,
                                  filter:   filter,
                                  interval: interval,
                                  view:     view
results.each do |result|
  p result
end

אם נתקלתם בבעיות, תוכלו להיעזר במאמר פתרון בעיות ב-Monitoring API.

דוגמה: קבלת נתונים של סדרות עיתיות

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

פרוטוקול

דוגמת הפרוטוקול מגבילה עוד יותר את הפלט, כדי שהנתונים שמוחזרים יהיו קלים יותר לניהול בתיבת התגובה:

  • הערך של filter מגביל את סדרת הזמן למכונת VM אחת.
  • הערך של fields מציין רק את השעה והערך של המדידות.

ההגדרות האלה מגבילות את כמות הנתונים של סדרות הזמן שמוחזרות בתוצאה.

  1. פותחים את דף העזר של timeSeries.list.

  2. בחלונית עם התווית Try this method (אפשר לנסות את השיטה הזו), מזינים את הפרטים הבאים:

    • name: מזינים את הנתיב לפרויקט.

      projects/PROJECT_ID
      
    • filter: מציינים את סוג המדד.

      metric.type = "compute.googleapis.com/instance/cpu/utilization" AND metric.label.instance_name = "INSTANCE_NAME"
      
    • interval.endTime: מזינים את שעת הסיום.

    • interval.startTime: מזינים את שעת ההתחלה ומוודאים שהיא מוקדמת ב-20 דקות משעת הסיום.

    • לוחצים על הצגת פרמטרים רגילים, ובשדות מזינים את הפרטים הבאים:

      timeSeries.points.interval.endTime,timeSeries.points.value
      
  3. לוחצים על Execute.

הבקשה מחזירה תוצאה כמו בדוגמה הבאה:

{
 "timeSeries": [
  {
   "points": [
    {
     "interval": {
      "endTime": "2024-03-01T00:19:01Z"
     },
     "value": {
      "doubleValue": 0.06763074536575005
     }
    },
    {
     "interval": {
      "endTime": "2024-03-01T00:18:01Z"
     },
     "value": {
      "doubleValue": 0.06886174467702706
     }
    },
    ...
    {
     "interval": {
      "endTime": "2024-03-01T00:17:01Z"
     },
     "value": {
      "doubleValue": 0.06929610064253211
     }
    }
   ]
  }
 ]
}

כדי לראות את הבקשה כפקודת curl, כבקשת HTTP או ב-JavaScript, לוחצים על מסך מלא ב-APIs Explorer.

C#

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

public static object ReadTimeSeriesData(string projectId,
    string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    string filter = $"metric.type=\"{metricType}\"";
    ListTimeSeriesRequest request = new ListTimeSeriesRequest
    {
        ProjectName = new ProjectName(projectId),
        Filter = filter,
        Interval = new TimeInterval(),
        View = ListTimeSeriesRequest.Types.TimeSeriesView.Full,
    };
    // Create timestamp for current time formatted in seconds.
    long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
    Timestamp startTimeStamp = new Timestamp();
    // Set startTime to limit results to the last 20 minutes.
    startTimeStamp.Seconds = timeStamp - (60 * 20);
    Timestamp endTimeStamp = new Timestamp();
    // Set endTime to current time.
    endTimeStamp.Seconds = timeStamp;
    TimeInterval interval = new TimeInterval();
    interval.StartTime = startTimeStamp;
    interval.EndTime = endTimeStamp;
    request.Interval = interval;
    // Make the request.
    PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
        metricServiceClient.ListTimeSeries(request);
    // Iterate over all response items, lazily performing RPCs as required.
    foreach (TimeSeries item in response)
    {
        Console.WriteLine(JObject.Parse($"{item}").ToString());
    }
    return 0;
}

Go

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


// readTimeSeriesValue reads the TimeSeries for the value specified by metric type in a time window from the last 20 minutes.
func readTimeSeriesValue(projectID, metricType string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return err
	}
	defer c.Close()
	startTime := time.Now().UTC().Add(time.Minute * -20).Unix()
	endTime := time.Now().UTC().Unix()

	req := &monitoringpb.ListTimeSeriesRequest{
		Name:   "projects/" + projectID,
		Filter: fmt.Sprintf("metric.type=\"%s\"", metricType),
		Interval: &monitoringpb.TimeInterval{
			StartTime: &timestamp.Timestamp{Seconds: startTime},
			EndTime:   &timestamp.Timestamp{Seconds: endTime},
		},
	}
	iter := c.ListTimeSeries(ctx, req)

	for {
		resp, err := iter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("could not read time series value, %w ", err)
		}
		log.Printf("%+v\n", resp)
	}

	return nil
}

Java

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

String projectId = System.getProperty("projectId");
ProjectName name = ProjectName.of(projectId);

// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
TimeInterval interval =
    TimeInterval.newBuilder()
        .setStartTime(Timestamps.fromMillis(startMillis))
        .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
        .build();

ListTimeSeriesRequest.Builder requestBuilder =
    ListTimeSeriesRequest.newBuilder()
        .setName(name.toString())
        .setFilter(filter)
        .setInterval(interval);

ListTimeSeriesRequest request = requestBuilder.build();

try (final MetricServiceClient client = MetricServiceClient.create();) {
  ListTimeSeriesPagedResponse response = client.listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
}

Node.js

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

async function readTimeSeriesData() {
  /**
   * TODO(developer): Uncomment and edit the following lines of code.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const filter = 'metric.type="compute.googleapis.com/instance/cpu/utilization"';

  const request = {
    name: client.projectPath(projectId),
    filter: filter,
    interval: {
      startTime: {
        // Limit results to the last 20 minutes
        seconds: Date.now() / 1000 - 60 * 20,
      },
      endTime: {
        seconds: Date.now() / 1000,
      },
    },
  };

  // Writes time series data
  const [timeSeries] = await client.listTimeSeries(request);
  timeSeries.forEach(data => {
    console.log(`${data.metric.labels.instance_name}:`);
    data.points.forEach(point => {
      console.log(JSON.stringify(point.value));
    });
  });
}
readTimeSeriesData();

PHP

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest\TimeSeriesView;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Protobuf\Timestamp;

/**
 * Example:
 * ```
 * read_timeseries_simple($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function read_timeseries_simple(string $projectId, int $minutesAgo = 20): void
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = 'projects/' . $projectId;
    $filter = 'metric.type="compute.googleapis.com/instance/cpu/utilization"';

    // Limit results to the last 20 minutes
    $startTime = new Timestamp();
    $startTime->setSeconds(time() - (60 * $minutesAgo));
    $endTime = new Timestamp();
    $endTime->setSeconds(time());

    $interval = new TimeInterval();
    $interval->setStartTime($startTime);
    $interval->setEndTime($endTime);

    $view = TimeSeriesView::FULL;
    $listTimeSeriesRequest = (new ListTimeSeriesRequest())
        ->setName($projectName)
        ->setFilter($filter)
        ->setInterval($interval)
        ->setView($view);

    $result = $metrics->listTimeSeries($listTimeSeriesRequest);

    printf('CPU utilization:' . PHP_EOL);
    foreach ($result->iterateAllElements() as $timeSeries) {
        $instanceName = $timeSeries->getMetric()->getLabels()['instance_name'];
        printf($instanceName . ':' . PHP_EOL);
        foreach ($timeSeries->getPoints() as $point) {
            printf('  ' . $point->getValue()->getDoubleValue() . PHP_EOL);
        }
    }
}

Python

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"

now = time.time()
seconds = int(now)
nanos = int((now - seconds) * 10**9)
interval = monitoring_v3.TimeInterval(
    {
        "end_time": {"seconds": seconds, "nanos": nanos},
        "start_time": {"seconds": (seconds - 1200), "nanos": nanos},
    }
)

results = client.list_time_series(
    request={
        "name": project_name,
        "filter": 'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
        "interval": interval,
        "view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL,
    }
)
for result in results:
    print(result)

Ruby

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

gem "google-cloud-monitoring"
require "google/cloud/monitoring"

# Your Google Cloud Platform project ID
# project_id = "YOUR_PROJECT_ID"

client = Google::Cloud::Monitoring.metric_service
project_name = client.project_path project: project_id

interval = Google::Cloud::Monitoring::V3::TimeInterval.new
now = Time.now
interval.end_time = Google::Protobuf::Timestamp.new seconds: now.to_i,
                                                    nanos:   now.nsec
interval.start_time = Google::Protobuf::Timestamp.new seconds: now.to_i - 1200,
                                                      nanos:   now.nsec
filter = 'metric.type = "compute.googleapis.com/instance/cpu/utilization"'
view = Google::Cloud::Monitoring::V3::ListTimeSeriesRequest::TimeSeriesView::FULL

results = client.list_time_series name:     project_name,
                                  filter:   filter,
                                  interval: interval,
                                  view:     view
results.each do |result|
  p result
end

אם נתקלתם בבעיות, תוכלו להיעזר במאמר פתרון בעיות ב-Monitoring API.

צבירת נתונים

שיטת timeSeries.list יכולה לבצע צבירות סטטיסטיות וצמצומים בנתוני סדרת הזמן שמוחזרים. בקטעים הבאים מוצגות שתי דוגמאות. מידע נוסף על סינון וצבירה: שינוי של סדרות זמן

דוגמה: יישור של סדרות זמן

בדוגמה הזו, 20 מדידות השימוש הנפרדות בכל סדרת זמן מצטמצמות ל-2 מדידות: השימוש הממוצע בשני פרקי הזמן של 10 דקות בתוך פרק הזמן של 20 דקות. הנתונים מכל סדרת זמן מיושרים קודם לתקופות של 10 דקות, ואז מחושב ממוצע של הערכים בכל תקופה של 10 דקות.

לפעולת ההתאמה יש שני יתרונות: היא מחליקה את הנתונים ומתאימה את הנתונים מכל נתוני הסדרות העיתיות לגבולות מדויקים של 10 דקות. לאחר מכן אפשר לעבד את הנתונים המתאימים.

פרוטוקול

  1. פותחים את דף העזר של timeSeries.list.

  2. בחלונית עם התווית Try this method (אפשר לנסות את השיטה הזו), מזינים את הפרטים הבאים:

    • name: מזינים את הנתיב לפרויקט.

      projects/PROJECT_ID
      
    • aggregation.alignmentPeriod: מזינים 600s
    • aggregation.perSeriesAligner: בוחרים באפשרות ALIGN_MEAN
    • filter: מציינים את סוג המדד.

      metric.type = "compute.googleapis.com/instance/cpu/utilization"
      
    • interval.endTime: מזינים את שעת הסיום.
    • interval.startTime: מזינים את שעת ההתחלה ומוודאים שהיא מוקדמת ב-20 דקות משעת הסיום.
    • לוחצים על הצגת פרמטרים רגילים, ובשדות מזינים את הפרטים הבאים:

      timeSeries.metric,timeSeries.points
      
  3. לוחצים על Execute.

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

בתוצאה לדוגמה הבאה יש סדרת זמנים לכל אחת משלוש מכונות וירטואליות. לכל סדרת זמנים יש שתי נקודות נתונים, הממוצע של השימוש בתקופות ההתאמה של 10 דקות:

{
 "timeSeries": [
  {
   "metric": {
    "labels": {"instance_name": "your-first-instance"},
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2024-03-01T00:20:00.000Z",
      "endTime": "2024-03-01T00:20:00.000Z"
     },
     "value": { "doubleValue": 0.06688481346044381 }
    },
    {
     "interval": {
      "startTime": "2024-03-01T00:10:00.000Z",
      "endTime": "2024-03-01T00:10:00.000Z"
     },
     "value": {"doubleValue": 0.06786652821310177 }
    }
   ]
  },
  {
   "metric": {
    "labels": { "instance_name": "your-second-instance" },
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2024-03-01T00:20:00.000Z",
      "endTime": "2024-03-01T00:20:00.000Z"
     },
     "value": { "doubleValue": 0.04144239874207415 }
    },
    {
     "interval": {
      "startTime": "2024-03-01T00:10:00.000Z",
      "endTime": "2024-03-01T00:10:00.000Z"
     },
     "value": { "doubleValue": 0.04045793689050091 }
    }
   ]
  },
  {
   "metric": {
    "labels": { "instance_name": "your-third-instance" },
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2024-03-01T00:20:00.000Z",
      "endTime": "2024-03-01T00:20:00.000Z"
     },
     "value": { "doubleValue": 0.029650046587339607 }
    },
    {
     "interval": {
      "startTime": "2024-03-01T00:10:00.000Z",
      "endTime": "2024-03-01T00:10:00.000Z"
     },
     "value": { "doubleValue": 0.03053874224715402 }
    }
   ]
  }
 ]
}

כדי לראות את הבקשה כפקודת curl, כבקשת HTTP או ב-JavaScript, לוחצים על מסך מלא ב-APIs Explorer.

C#

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

public static object ReadTimeSeriesAggregate(string projectId,
    string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    string filter = $"metric.type=\"{metricType}\"";
    ListTimeSeriesRequest request = new ListTimeSeriesRequest
    {
        ProjectName = new ProjectName(projectId),
        Filter = filter,
        Interval = new TimeInterval(),
    };
    // Create timestamp for current time formatted in seconds.
    long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
    Timestamp startTimeStamp = new Timestamp();
    // Set startTime to limit results to the last 20 minutes.
    startTimeStamp.Seconds = timeStamp - (60 * 20);
    Timestamp endTimeStamp = new Timestamp();
    // Set endTime to current time.
    endTimeStamp.Seconds = timeStamp;
    TimeInterval interval = new TimeInterval();
    interval.StartTime = startTimeStamp;
    interval.EndTime = endTimeStamp;
    request.Interval = interval;
    // Aggregate results per matching instance
    Aggregation aggregation = new Aggregation();
    Duration alignmentPeriod = new Duration();
    alignmentPeriod.Seconds = 600;
    aggregation.AlignmentPeriod = alignmentPeriod;
    aggregation.PerSeriesAligner = Aggregation.Types.Aligner.AlignMean;
    // Add the aggregation to the request.
    request.Aggregation = aggregation;
    // Make the request.
    PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
        metricServiceClient.ListTimeSeries(request);
    // Iterate over all response items, lazily performing RPCs as required.
    Console.WriteLine($"{projectId} CPU utilization:");
    foreach (var item in response)
    {
        var points = item.Points;
        var labels = item.Metric.Labels;
        Console.WriteLine($"{labels.Values.FirstOrDefault()}");
        if (points.Count > 0)
        {
            Console.WriteLine($"  Now: {points[0].Value.DoubleValue}");
        }
        if (points.Count > 1)
        {
            Console.WriteLine($"  10 min ago: {points[1].Value.DoubleValue}");
        }
    }
    return 0;
}

Go

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"
	"time"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
	"github.com/golang/protobuf/ptypes/duration"
	"github.com/golang/protobuf/ptypes/timestamp"
	"google.golang.org/api/iterator"
)

// readTimeSeriesAlign reads the last 20 minutes of the given metric and aligns
// everything on 10 minute intervals.
func readTimeSeriesAlign(w io.Writer, projectID string) error {
	ctx := context.Background()
	client, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricClient: %w", err)
	}
	defer client.Close()
	startTime := time.Now().UTC().Add(time.Minute * -20)
	endTime := time.Now().UTC()
	req := &monitoringpb.ListTimeSeriesRequest{
		Name:   "projects/" + projectID,
		Filter: `metric.type="compute.googleapis.com/instance/cpu/utilization"`,
		Interval: &monitoringpb.TimeInterval{
			StartTime: &timestamp.Timestamp{
				Seconds: startTime.Unix(),
			},
			EndTime: &timestamp.Timestamp{
				Seconds: endTime.Unix(),
			},
		},
		Aggregation: &monitoringpb.Aggregation{
			PerSeriesAligner: monitoringpb.Aggregation_ALIGN_MEAN,
			AlignmentPeriod: &duration.Duration{
				Seconds: 600,
			},
		},
	}
	it := client.ListTimeSeries(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("could not read time series value: %w", err)
		}
		fmt.Fprintln(w, resp.GetMetric().GetLabels()["instance_name"])
		fmt.Fprintf(w, "\tNow: %.4f\n", resp.GetPoints()[0].GetValue().GetDoubleValue())
		if len(resp.GetPoints()) > 1 {
			fmt.Fprintf(w, "\t10 minutes ago: %.4f\n", resp.GetPoints()[1].GetValue().GetDoubleValue())
		}
	}
	fmt.Fprintln(w, "Done")
	return nil
}

Java

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

String projectId = System.getProperty("projectId");
ProjectName name = ProjectName.of(projectId);

// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
TimeInterval interval =
    TimeInterval.newBuilder()
        .setStartTime(Timestamps.fromMillis(startMillis))
        .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
        .build();

Aggregation aggregation =
    Aggregation.newBuilder()
        .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
        .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
        .build();

ListTimeSeriesRequest.Builder requestBuilder =
    ListTimeSeriesRequest.newBuilder()
        .setName(name.toString())
        .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
        .setInterval(interval)
        .setAggregation(aggregation);

ListTimeSeriesRequest request = requestBuilder.build();

try (final MetricServiceClient client = MetricServiceClient.create();) {
  ListTimeSeriesPagedResponse response = client.listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
}

Node.js

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

async function readTimeSeriesAggregate() {
  /**
   * TODO(developer): Uncomment and edit the following lines of code.
   */
  // const projectId = 'YOUR_PROJECT_ID';

  const request = {
    name: client.projectPath(projectId),
    filter: 'metric.type="compute.googleapis.com/instance/cpu/utilization"',
    interval: {
      startTime: {
        // Limit results to the last 20 minutes
        seconds: Date.now() / 1000 - 60 * 20,
      },
      endTime: {
        seconds: Date.now() / 1000,
      },
    },
    // Aggregate results per matching instance
    aggregation: {
      alignmentPeriod: {
        seconds: 600,
      },
      perSeriesAligner: 'ALIGN_MEAN',
    },
  };

  // Writes time series data
  const [timeSeries] = await client.listTimeSeries(request);
  console.log('CPU utilization:');
  timeSeries.forEach(data => {
    console.log(data.metric.labels.instance_name);
    console.log(`  Now: ${data.points[0].value.doubleValue}`);
    if (data.points.length > 1) {
      console.log(`  10 min ago: ${data.points[1].value.doubleValue}`);
    }
    console.log('=====');
  });
}
readTimeSeriesAggregate();

PHP

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Monitoring\V3\Aggregation;
use Google\Cloud\Monitoring\V3\Aggregation\Aligner;
use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest\TimeSeriesView;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Protobuf\Duration;
use Google\Protobuf\Timestamp;

/**
 * Example:
 * ```
 * read_timeseries_align($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function read_timeseries_align(string $projectId, int $minutesAgo = 20): void
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = 'projects/' . $projectId;
    $filter = 'metric.type="compute.googleapis.com/instance/cpu/utilization"';

    $startTime = new Timestamp();
    $startTime->setSeconds(time() - (60 * $minutesAgo));
    $endTime = new Timestamp();
    $endTime->setSeconds(time());

    $interval = new TimeInterval();
    $interval->setStartTime($startTime);
    $interval->setEndTime($endTime);

    $alignmentPeriod = new Duration();
    $alignmentPeriod->setSeconds(600);
    $aggregation = new Aggregation();
    $aggregation->setAlignmentPeriod($alignmentPeriod);
    $aggregation->setPerSeriesAligner(Aligner::ALIGN_MEAN);

    $view = TimeSeriesView::FULL;
    $listTimeSeriesRequest = (new ListTimeSeriesRequest())
        ->setName($projectName)
        ->setFilter($filter)
        ->setInterval($interval)
        ->setView($view)
        ->setAggregation($aggregation);

    $result = $metrics->listTimeSeries($listTimeSeriesRequest);

    printf('CPU utilization:' . PHP_EOL);
    foreach ($result->iterateAllElements() as $timeSeries) {
        printf($timeSeries->getMetric()->getLabels()['instance_name'] . PHP_EOL);
        printf('  Now: ');
        printf($timeSeries->getPoints()[0]->getValue()->getDoubleValue() . PHP_EOL);
        if (count($timeSeries->getPoints()) > 1) {
            printf('  10 minutes ago: ');
            printf($timeSeries->getPoints()[1]->getValue()->getDoubleValue() . PHP_EOL);
        }
    }
}

Python

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"

now = time.time()
seconds = int(now)
nanos = int((now - seconds) * 10**9)
interval = monitoring_v3.TimeInterval(
    {
        "end_time": {"seconds": seconds, "nanos": nanos},
        "start_time": {"seconds": (seconds - 3600), "nanos": nanos},
    }
)
aggregation = monitoring_v3.Aggregation(
    {
        "alignment_period": {"seconds": 1200},  # 20 minutes
        "per_series_aligner": monitoring_v3.Aggregation.Aligner.ALIGN_MEAN,
    }
)

results = client.list_time_series(
    request={
        "name": project_name,
        "filter": 'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
        "interval": interval,
        "view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL,
        "aggregation": aggregation,
    }
)
for result in results:
    print(result)

Ruby

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

gem "google-cloud-monitoring"
require "google/cloud/monitoring"

# Your Google Cloud Platform project ID
# project_id = "YOUR_PROJECT_ID"

client = Google::Cloud::Monitoring.metric_service
project_name = client.project_path project: project_id

interval = Google::Cloud::Monitoring::V3::TimeInterval.new
now = Time.now
interval.end_time = Google::Protobuf::Timestamp.new seconds: now.to_i,
                                                    nanos:   now.nsec
interval.start_time = Google::Protobuf::Timestamp.new seconds: now.to_i - 1200,
                                                      nanos:   now.nsec
filter = 'metric.type = "compute.googleapis.com/instance/cpu/utilization"'
view = Google::Cloud::Monitoring::V3::ListTimeSeriesRequest::TimeSeriesView::FULL
aggregation = Google::Cloud::Monitoring::V3::Aggregation.new(
  alignment_period:   { seconds: 1200 },
  per_series_aligner: Google::Cloud::Monitoring::V3::Aggregation::Aligner::ALIGN_MEAN
)

results = client.list_time_series name:        project_name,
                                  filter:      filter,
                                  interval:    interval,
                                  view:        view,
                                  aggregation: aggregation
results.each do |result|
  p result
end

אם נתקלתם בבעיות, תוכלו להיעזר במאמר פתרון בעיות ב-Monitoring API.

דוגמה: צמצום בסדרות זמן

בדוגמה הזו אנחנו מרחיבים את הדוגמה הקודמת ומשלבים את סדרות הזמנים המיושרות משלושת המכונות הווירטואליות לסדרת זמן אחת שמודדת את ממוצע השימוש בכל המכונות.

פרוטוקול

  1. פותחים את דף העזר של timeSeries.list.

  2. בחלונית עם התווית Try this method (אפשר לנסות את השיטה הזו), מזינים את הפרטים הבאים:

    • name: מזינים את הנתיב לפרויקט.

      projects/PROJECT_ID
      
    • aggregation.alignmentPeriod: מזינים 600s
    • aggregation.perSeriesAligner: בוחרים באפשרות ALIGN_MEAN
    • aggregation.crossSeriesReducer: בוחרים באפשרות REDUCE_MEAN
    • filter: מציינים את סוג המדד.

      metric.type = "compute.googleapis.com/instance/cpu/utilization"
      
    • interval.endTime: מזינים את שעת הסיום.
    • interval.startTime: מזינים את שעת ההתחלה ומוודאים שהיא מוקדמת ב-20 דקות משעת הסיום.
    • לוחצים על הצגת פרמטרים רגילים, ובשדות מזינים את הפרטים הבאים:

      timeSeries.metric,timeSeries.points
      
  3. לוחצים על Execute.

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

{
 "timeSeries": [
  {
   "metric": {
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2024-03-01T00:20:00.000Z",
      "endTime": "2024-03-01T00:20:00.000Z"
     },
     "value": {
      "doubleValue": 0.045992419596619184
     }
    },
    {
     "interval": {
      "startTime": "2024-03-01T00:10:00.000Z",
      "endTime": "2024-03-01T00:10:00.000Z"
     },
     "value": {
      "doubleValue": 0.04628773578358556
     }
    }
   ]
  }
 ]
}

כדי לראות את הבקשה כפקודת curl, כבקשת HTTP או ב-JavaScript, לוחצים על מסך מלא ב-APIs Explorer.

C#

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

public static object ReadTimeSeriesReduce(string projectId,
    string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    string filter = $"metric.type=\"{metricType}\"";
    ListTimeSeriesRequest request = new ListTimeSeriesRequest
    {
        ProjectName = new ProjectName(projectId),
        Filter = filter,
        Interval = new TimeInterval(),
    };
    // Create timestamp for current time formatted in seconds.
    long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
    Timestamp startTimeStamp = new Timestamp();
    // Set startTime to limit results to the last 20 minutes.
    startTimeStamp.Seconds = timeStamp - (60 * 20);
    Timestamp endTimeStamp = new Timestamp();
    // Set endTime to current time.
    endTimeStamp.Seconds = timeStamp;
    TimeInterval interval = new TimeInterval();
    interval.StartTime = startTimeStamp;
    interval.EndTime = endTimeStamp;
    request.Interval = interval;
    // Aggregate results per matching instance.
    Aggregation aggregation = new Aggregation();
    Duration alignmentPeriod = new Duration();
    alignmentPeriod.Seconds = 600;
    aggregation.AlignmentPeriod = alignmentPeriod;
    aggregation.CrossSeriesReducer = Aggregation.Types.Reducer.ReduceMean;
    aggregation.PerSeriesAligner = Aggregation.Types.Aligner.AlignMean;
    // Add the aggregation to the request.
    request.Aggregation = aggregation;
    // Make the request.
    PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
        metricServiceClient.ListTimeSeries(request);
    // Iterate over all response items, lazily performing RPCs as required.
    Console.WriteLine("CPU utilization:");
    foreach (var item in response)
    {
        var points = item.Points;
        Console.WriteLine("Average CPU utilization across all GCE instances:");
        Console.WriteLine($"  Last 10 min: {points[0].Value.DoubleValue}");
        Console.WriteLine($"  Last 10-20 min ago: {points[1].Value.DoubleValue}");
    }
    return 0;
}

Go

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"
	"time"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
	"github.com/golang/protobuf/ptypes/duration"
	"github.com/golang/protobuf/ptypes/timestamp"
	"google.golang.org/api/iterator"
)

// readTimeSeriesReduce reads the last 20 minutes of the given metric, aligns
// everything on 10 minute intervals, and combines values from different
// instances.
func readTimeSeriesReduce(w io.Writer, projectID string) error {
	ctx := context.Background()
	client, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricClient: %w", err)
	}
	defer client.Close()
	startTime := time.Now().UTC().Add(time.Minute * -20)
	endTime := time.Now().UTC()
	req := &monitoringpb.ListTimeSeriesRequest{
		Name:   "projects/" + projectID,
		Filter: `metric.type="compute.googleapis.com/instance/cpu/utilization"`,
		Interval: &monitoringpb.TimeInterval{
			StartTime: &timestamp.Timestamp{
				Seconds: startTime.Unix(),
			},
			EndTime: &timestamp.Timestamp{
				Seconds: endTime.Unix(),
			},
		},
		Aggregation: &monitoringpb.Aggregation{
			CrossSeriesReducer: monitoringpb.Aggregation_REDUCE_MEAN,
			PerSeriesAligner:   monitoringpb.Aggregation_ALIGN_MEAN,
			AlignmentPeriod: &duration.Duration{
				Seconds: 600,
			},
		},
	}
	it := client.ListTimeSeries(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("could not read time series value: %w", err)
		}
		fmt.Fprintln(w, "Average CPU utilization across all GCE instances:")
		fmt.Fprintf(w, "\tNow: %.4f\n", resp.GetPoints()[0].GetValue().GetDoubleValue())
		if len(resp.GetPoints()) > 1 {
			fmt.Fprintf(w, "\t10 minutes ago: %.4f\n", resp.GetPoints()[1].GetValue().GetDoubleValue())
		}
	}
	fmt.Fprintln(w, "Done")
	return nil
}

Java

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

String projectId = System.getProperty("projectId");
ProjectName name = ProjectName.of(projectId);

// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
TimeInterval interval =
    TimeInterval.newBuilder()
        .setStartTime(Timestamps.fromMillis(startMillis))
        .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
        .build();

Aggregation aggregation =
    Aggregation.newBuilder()
        .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
        .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
        .setCrossSeriesReducer(Aggregation.Reducer.REDUCE_MEAN)
        .build();

ListTimeSeriesRequest.Builder requestBuilder =
    ListTimeSeriesRequest.newBuilder()
        .setName(name.toString())
        .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
        .setInterval(interval)
        .setAggregation(aggregation);

ListTimeSeriesRequest request = requestBuilder.build();

try (final MetricServiceClient client = MetricServiceClient.create();) {
  ListTimeSeriesPagedResponse response = client.listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
}

Node.js

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.MetricServiceClient();

async function readTimeSeriesReduce() {
  /**
   * TODO(developer): Uncomment and edit the following lines of code.
   */
  // const projectId = 'YOUR_PROJECT_ID';

  const request = {
    name: client.projectPath(projectId),
    filter: 'metric.type="compute.googleapis.com/instance/cpu/utilization"',
    interval: {
      startTime: {
        // Limit results to the last 20 minutes
        seconds: Date.now() / 1000 - 60 * 20,
      },
      endTime: {
        seconds: Date.now() / 1000,
      },
    },
    // Aggregate results per matching instance
    aggregation: {
      alignmentPeriod: {
        seconds: 600,
      },
      crossSeriesReducer: 'REDUCE_MEAN',
      perSeriesAligner: 'ALIGN_MEAN',
    },
  };

  // Writes time series data
  const [result] = await client.listTimeSeries(request);
  if (result.length === 0) {
    console.log('No data');
    return;
  }
  const reductions = result[0].points;

  console.log('Average CPU utilization across all GCE instances:');
  console.log(`  Last 10 min: ${reductions[0].value.doubleValue}`);
  console.log(`  10-20 min ago: ${reductions[0].value.doubleValue}`);
}
readTimeSeriesReduce();

PHP

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Monitoring\V3\Aggregation;
use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest\TimeSeriesView;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Protobuf\Duration;
use Google\Protobuf\Timestamp;

/**
 * Example:
 * ```
 * read_timeseries_reduce($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function read_timeseries_reduce(string $projectId, int $minutesAgo = 20): void
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = 'projects/' . $projectId;
    $filter = 'metric.type="compute.googleapis.com/instance/cpu/utilization"';

    $startTime = new Timestamp();
    $startTime->setSeconds(time() - (60 * $minutesAgo));
    $endTime = new Timestamp();
    $endTime->setSeconds(time());

    $interval = new TimeInterval();
    $interval->setStartTime($startTime);
    $interval->setEndTime($endTime);

    $alignmentPeriod = new Duration();
    $alignmentPeriod->setSeconds(600);
    $aggregation = new Aggregation();
    $aggregation->setAlignmentPeriod($alignmentPeriod);
    $aggregation->setCrossSeriesReducer(Aggregation\Reducer::REDUCE_MEAN);
    $aggregation->setPerSeriesAligner(Aggregation\Aligner::ALIGN_MEAN);

    $view = TimeSeriesView::FULL;
    $listTimeSeriesRequest = (new ListTimeSeriesRequest())
        ->setName($projectName)
        ->setFilter($filter)
        ->setInterval($interval)
        ->setView($view)
        ->setAggregation($aggregation);

    $result = $metrics->listTimeSeries($listTimeSeriesRequest);

    printf('Average CPU utilization across all GCE instances:' . PHP_EOL);
    if ($timeSeries = $result->iterateAllElements()->current()) {
        $reductions = $timeSeries->getPoints();
        printf('  Last 10 minutes: ');
        printf($reductions[0]->getValue()->getDoubleValue() . PHP_EOL);
        if (count($reductions) > 1) {
            printf('  10-20 minutes ago: ');
            printf($reductions[1]->getValue()->getDoubleValue() . PHP_EOL);
        }
    }
}

Python

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"

now = time.time()
seconds = int(now)
nanos = int((now - seconds) * 10**9)
interval = monitoring_v3.TimeInterval(
    {
        "end_time": {"seconds": seconds, "nanos": nanos},
        "start_time": {"seconds": (seconds - 3600), "nanos": nanos},
    }
)
aggregation = monitoring_v3.Aggregation(
    {
        "alignment_period": {"seconds": 1200},  # 20 minutes
        "per_series_aligner": monitoring_v3.Aggregation.Aligner.ALIGN_MEAN,
        "cross_series_reducer": monitoring_v3.Aggregation.Reducer.REDUCE_MEAN,
        "group_by_fields": ["resource.zone"],
    }
)

results = client.list_time_series(
    request={
        "name": project_name,
        "filter": 'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
        "interval": interval,
        "view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL,
        "aggregation": aggregation,
    }
)
for result in results:
    print(result)

Ruby

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

gem "google-cloud-monitoring"
require "google/cloud/monitoring"

# Your Google Cloud Platform project ID
# project_id = "YOUR_PROJECT_ID"

client = Google::Cloud::Monitoring.metric_service
project_name = client.project_path project: project_id

interval = Google::Cloud::Monitoring::V3::TimeInterval.new
now = Time.now
interval.end_time = Google::Protobuf::Timestamp.new seconds: now.to_i,
                                                    nanos:   now.nsec
interval.start_time = Google::Protobuf::Timestamp.new seconds: now.to_i - 1200,
                                                      nanos:   now.nsec
filter = 'metric.type = "compute.googleapis.com/instance/cpu/utilization"'
view = Google::Cloud::Monitoring::V3::ListTimeSeriesRequest::TimeSeriesView::FULL
aggregation = Google::Cloud::Monitoring::V3::Aggregation.new(
  alignment_period:     { seconds: 1200 },
  per_series_aligner:   Google::Cloud::Monitoring::V3::Aggregation::Aligner::ALIGN_MEAN,
  cross_series_reducer: Google::Cloud::Monitoring::V3::Aggregation::Reducer::REDUCE_MEAN,
  group_by_fields:      ["resource.zone"]
)

results = client.list_time_series name:        project_name,
                                  filter:      filter,
                                  interval:    interval,
                                  view:        view,
                                  aggregation: aggregation
results.each do |result|
  p result
end

אם נתקלתם בבעיות, תוכלו להיעזר במאמר פתרון בעיות ב-Monitoring API.

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