Lee datos de métricas

En esta página, se explica cómo leer datos de métricas, también llamados datos de series temporales, con el método timeSeries.list en la API de Monitoring.

En esta página, no se analiza el lenguaje de consulta de supervisión (MQL) ni el método timeSeries.query. Para obtener esa información, consulta Cómo usar MQL desde la API de Monitoring.

Hay varias formas de usar el método timeSeries.list:

  • Para ejecutar el método list sin escribir ningún código, en los ejemplos de las pestañas PROTOCOLO de esta página, se usa el Explorador de API basado en formularios. (Consulta Explorador de API para obtener más información sobre esta herramienta).

  • Para aprender a usar el método list de los lenguajes de programación seleccionados, consulta las muestras de códigos ejecutables en esta página. No hay compatibilidad con el SDK de Cloud para usar la herramienta de línea de comandos de gcloud a fin de leer datos de métricas.

  • Para consultar las métricas de un recurso supervisado con el Explorador de métricas, haz lo siguiente:

    1. En Google Cloud Console, ve a Monitoring o usa el siguiente botón:
      Ir a Monitoring
    2. En el panel de navegación de Monitoring, haz clic en  Explorador de métricas.
    3. Ingresa el nombre del recurso supervisado en el cuadro de texto Buscar tipo de recurso y métrica.

Para obtener una introducción a las métricas y las series temporales, consulta Métricas, series temporales y recursos.

Resumen

Cada llamada al método timeSeries.list puede mostrar cualquier cantidad de series temporales de un único tipo de métrica. Por ejemplo, si usas Compute Engine, el tipo de métrica compute.googleapis.com/instance/cpu/usage_time tiene una serie temporal separada para cada una de tus instancias de VM.

Puedes especificar qué datos de series temporales deseas si proporcionas lo siguiente:

  • Una expresión de filtro que especifica el tipo de métrica. Opcionalmente, el filtro selecciona un subconjunto de las series temporales de la métrica si especificas los recursos que producen las series temporales o los valores para ciertas etiquetas en las series temporales.
  • Un intervalo que limita la cantidad de datos que se muestran
  • De manera opcional, una especificación de cómo combinar varias series temporales para producir un resumen agregado de los datos. Si necesitas más información, consulta Agrega datos para ver algunos ejemplos.

Filtros de series temporales

Puedes especificar qué series temporales deseas recuperar si pasas un filtro de serie temporal al método list. A continuación, se indican los componentes de filtros que se suelen proporcionar:

  • El filtro debe especificar un solo tipo de métrica. Por ejemplo:

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

    Para recuperar métricas personalizadas, cambia el prefijo metric.type en el filtro a custom.googleapis.com o a otro prefijo si se usa; external.googleapis.com se usa con frecuencia.

  • El filtro puede especificar valores para las etiquetas de dimensión de la métrica. El tipo de métrica determina qué etiquetas están presentes. Por ejemplo:

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

    Ten en cuenta que label es correcto, aunque el objeto de la métrica real usa labels como su clave.

  • El filtro puede limitar las series temporales a aquellas que contienen un tipo de recurso supervisado específico:

    resource.type = "gae_app"
    

Los componentes del filtro se pueden combinar en un solo filtro de series temporales, como el siguiente:

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

Si no especificas valores para todas las etiquetas de métrica, el método list mostrará una serie temporal para cada combinación de valores en las etiquetas no especificadas. El método muestra solo series temporales que tienen datos.

Intervalos

Debes especificar interval.startTime y interval.endTime cuando llames al método timeSeries.list. El período resultante incluye la hora de finalización, pero no la hora de inicio, a menos que ambas coincidan. Esto puede ser confuso. Por ejemplo, considera estos ejemplos de intervalos (start, end]:

(T, T+1]
Este intervalo no contiene T.
(T-1, T]
Este intervalo contiene T.
(T, T]
Como un caso inusual y especial, este intervalo incluye solo la hora T. Si omites la hora de inicio, este es el intervalo que obtienes.

Valores en intervalos de tiempo

Las horas de inicio y finalización deben especificarse como strings en formato RFC 3339. Por ejemplo:

2018-05-11T12:34:56+04:00
2018-05-11T12:34:56.992Z

El comando date -Iseconds en Linux es útil para generar marcas de tiempo.

Rangos en intervalos

Un intervalo se especifica mediante una hora de inicio y de finalización, pero la API no requiere la hora de inicio. Si no se especifica una hora de inicio, la hora de finalización será la predeterminada. Esto tiene sentido semántico solo para las métricas GAUGE, que miden puntos en el tiempo.

Si tu métrica es CUMULATIVE o DELTA, entonces mide una acumulación o cambio en el tiempo. Para las métricas del tipo “a lo largo del tiempo”, se deben proporcionar las horas de inicio y finalización del intervalo y la hora de inicio debe ser menor que la de finalización.

Consulta Tipos de métricas para obtener más información.

Operaciones de enumeración básicas

El método timeSeries.list se puede usar con el fin de mostrar datos simples y sin procesar o para mostrar datos muy procesados. En esta sección, se ilustran algunos usos básicos.

Ejemplo: Listado de series temporales disponibles

Este ejemplo muestra cómo listar solo los nombres y descripciones de las series temporales que coincide con un filtro, en lugar de mostrar todos los datos disponibles:

Protocolo

Estos son los parámetros de muestra para timeSeries.list:

  • name: projects/[PROJECT_ID]
  • filter: metric.type = "compute.googleapis.com/instance/cpu/utilization"
  • interval.start_time: 2018-05-11T00:00:00Z
  • interval.end_time: 2018-05-11T00:20:00Z
  • fields: timeSeries.metric

Probar

Antes de hacer clic en el botón Ejecutar, cambia [PROJECT_ID] por el ID de tu proyecto.

El resultado de muestra presenta series temporales para dos instancias de VM diferentes:

{
  "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"
      },
    }
  ]
}

C#

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

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

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

// 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: %v", err)
	}
	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: %v", err)
		}
		fmt.Fprintf(w, "\t%v\n", resp.GetMetric().GetLabels()["instance_name"])
	}
	fmt.Fprintln(w, "Done")
	return nil
}

Java

MetricServiceClient metricServiceClient = MetricServiceClient.create();
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();

ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

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

Node.js

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

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

/**
 * 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);
});

PHP

use Google\Cloud\Monitoring\V3\MetricServiceClient;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView;
use Google\Protobuf\Timestamp;

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

    $projectName = $metrics->projectName($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 = ListTimeSeriesRequest_TimeSeriesView::HEADERS;

    $result = $metrics->listTimeSeries(
        $projectName,
        $filter,
        $interval,
        $view);

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

Python

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

Ruby

# 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

Consulta Soluciona problemas de llamadas a la API si tienes dificultades.

Ejemplo: Obtén datos de series temporales

En este ejemplo, se muestra toda la información disponible para la solicitud timeSeries.list, incluidos los datos de métricas, de las instancias de Compute Engine de los últimos 20 minutos.

Protocolo

El ejemplo del protocolo limita aún más la salida para que los datos mostrados sean más manejables en el cuadro de respuesta. Este ejemplo usa diferentes valores de campo:

  • El valor del filtro ahora limita las series temporales a una sola instancia de VM.
  • El valor de los campos ahora especifica solo el tiempo y el valor de las mediciones.

Estos limitan la cantidad de datos de series temporales que se muestran en el resultado.

Estos son los parámetros de muestra para timeSeries.list:

  • name: projects/[PROJECT_ID]
  • filter: metric.type = "compute.googleapis.com/instance/cpu/utilization" AND metric.label.instance_name = "[YOUR_INSTANCE_NAME]"
  • interval.start_time: 2018-05-11T00:00:00Z
  • interval.end_time: 2018-05-11T00:20:00Z
  • fields: timeSeries.points.interval.endTime,timeSeries.points.value

Probar

Antes de hacer clic en el botón Ejecutar, cambia [PROJECT_ID] y [YOUR_INSTANCE_NAME] por los valores de tu proyecto y establece la hora de finalización en una hora reciente y la hora de inicio en 20 minutos antes.

La solicitud muestra un resultado como el siguiente:

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

C#

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


// 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
	}
	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, %v ", err)
		}
		log.Printf("%+v\n", resp)
	}

	return nil
}

Java

MetricServiceClient metricServiceClient = MetricServiceClient.create();
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();

ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

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

Node.js

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

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

/**
 * 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));
  });
});

PHP

use Google\Cloud\Monitoring\V3\MetricServiceClient;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView;
use Google\Protobuf\Timestamp;

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

    $projectName = $metrics->projectName($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 = ListTimeSeriesRequest_TimeSeriesView::FULL;

    $result = $metrics->listTimeSeries(
        $projectName,
        $filter,
        $interval,
        $view);

    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

client = monitoring_v3.MetricServiceClient()
project_name = client.project_path(project_id)
interval = monitoring_v3.types.TimeInterval()
now = time.time()
interval.end_time.seconds = int(now)
interval.end_time.nanos = int(
    (now - interval.end_time.seconds) * 10**9)
interval.start_time.seconds = int(now - 1200)
interval.start_time.nanos = interval.end_time.nanos
results = client.list_time_series(
    project_name,
    'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
    interval,
    monitoring_v3.enums.ListTimeSeriesRequest.TimeSeriesView.FULL)
for result in results:
    print(result)

Ruby

# 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

Los datos mostrados incluyen 20 datos en cada serie temporal durante el período de 20 minutos, ya que las métricas de Compute Engine se recopilan cada minuto. Para obtener más información, consulta Retención y latencia de datos de métricas. La API muestra los datos en cada serie temporal en orden inverso; no hay anulación para este orden de puntos.

Consulta Soluciona problemas de llamadas a la API si tienes dificultades.

Agrega datos

El método timeSeries.list puede realizar agregaciones y reducciones estadísticas en los datos de series temporales que se muestran. Las siguientes secciones muestran dos ejemplos. Consulta la documentación del método para obtener más opciones.

Ejemplo: Alineación de series temporales

En este ejemplo, se reducen las 20 mediciones de uso individuales en cada serie temporal a solo dos mediciones: El uso medio para los dos períodos de 10 minutos dentro del intervalo de 20 minutos. Los datos de cada serie temporal se alinean primero en períodos de 10 minutos (600 segundos) y luego se promedian los valores de cada período de 10 minutos.

En este ejemplo, se convierten las veinte medidas por series temporales en dos por serie de tiempo. Esta operación tiene dos ventajas: Suaviza los datos y alinea los datos de todas las series temporales en límites exactos de 10 minutos. Los datos se pueden procesar aún más.

Protocolo

Estos son los parámetros de muestra para timeSeries.list:

  • name: projects/[PROJECT_ID]
  • aggregation.alignmentPeriod: 600s
  • aggregation.perSeriesAligner: ALIGN_MEAN
  • filter: metric.type = "compute.googleapis.com/instance/cpu/utilization"
  • interval.start_time: 2018-05-11T00:00:00Z
  • interval.end_time: 2018-05-11T00:20:00Z
  • fields: timeSeries.metric,timeSeries.points

Se quita el filtro para una sola instancia que se muestra en el ejemplo anterior: esta consulta muestra muchos menos datos, por lo tanto, hay menos necesidad de restringirlo a una instancia de VM.

Probar

Antes de hacer clic en el botón Ejecutar, cambia [PROJECT_ID] por el ID de tu proyecto y establece la hora de finalización en una hora reciente y la hora de inicio en 20 minutos antes.

El siguiente resultado de muestra tiene una serie temporal para cada una de las tres instancias de VM. Cada serie temporal tiene dos datos, el uso medio para los períodos de alineación de 10 minutos:

{
 "timeSeries": [
  {
   "metric": {
    "labels": {"instance_name": "your-first-instance"},
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2018-05-04T14:00:00.000Z",
      "endTime": "2018-05-04T14:00:00.000Z"
     },
     "value": { "doubleValue": 0.06688481346044381 }
    },
    {
     "interval": {
      "startTime": "2018-05-04T13:50:00.000Z",
      "endTime": "2018-05-04T13:50:00.000Z"
     },
     "value": {"doubleValue": 0.06786652821310177 }
    }
   ]
  },
  {
   "metric": {
    "labels": { "instance_name": "your-second-instance" },
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2018-05-04T14:00:00.000Z",
      "endTime": "2018-05-04T14:00:00.000Z"
     },
     "value": { "doubleValue": 0.04144239874207415 }
    },
    {
     "interval": {
      "startTime": "2018-05-04T13:50:00.000Z",
      "endTime": "2018-05-04T13:50:00.000Z"
     },
     "value": { "doubleValue": 0.04045793689050091 }
    }
   ]
  },
  {
   "metric": {
    "labels": { "instance_name": "your-third-instance" },
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2018-05-04T14:00:00.000Z",
      "endTime": "2018-05-04T14:00:00.000Z"
     },
     "value": { "doubleValue": 0.029650046587339607 }
    },
    {
     "interval": {
      "startTime": "2018-05-04T13:50:00.000Z",
      "endTime": "2018-05-04T13:50:00.000Z"
     },
     "value": { "doubleValue": 0.03053874224715402 }
    }
   ]
  }
 ]
}

C#

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

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

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

// 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: %v", err)
	}
	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: %v", 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

MetricServiceClient metricServiceClient = MetricServiceClient.create();
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();

ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

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

Node.js

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

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

/**
 * 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('=====');
});

PHP

use Google\Cloud\Monitoring\V3\MetricServiceClient;
use Google\Cloud\Monitoring\V3\Aggregation_Aligner;
use Google\Cloud\Monitoring\V3\Aggregation;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView;
use Google\Protobuf\Duration;
use Google\Protobuf\Timestamp;

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

    $projectName = $metrics->projectName($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(Aggregation_Aligner::ALIGN_MEAN);

    $view = ListTimeSeriesRequest_TimeSeriesView::FULL;

    $result = $metrics->listTimeSeries(
        $projectName,
        $filter,
        $interval,
        $view,
        ['aggregation' => $aggregation]);

    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

client = monitoring_v3.MetricServiceClient()
project_name = client.project_path(project_id)
interval = monitoring_v3.types.TimeInterval()
now = time.time()
interval.end_time.seconds = int(now)
interval.end_time.nanos = int(
    (now - interval.end_time.seconds) * 10**9)
interval.start_time.seconds = int(now - 3600)
interval.start_time.nanos = interval.end_time.nanos
aggregation = monitoring_v3.types.Aggregation()
aggregation.alignment_period.seconds = 1200  # 20 minutes
aggregation.per_series_aligner = (
    monitoring_v3.enums.Aggregation.Aligner.ALIGN_MEAN)

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

Ruby

# 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

Consulta Soluciona problemas de llamadas a la API si tienes dificultades.

Ejemplo: Reducción a través de series temporales

En este ejemplo, se extiende el ejemplo anterior cuando combina las series temporales alineadas de las tres instancias de VM en una sola serie temporal que mide el uso promedio de todas las instancias.

Protocolo

A continuación, se muestran los parámetros de muestra para timeSeries.list, aggregation.crossSeriesReducer:

  • name: projects/[PROJECT_ID]
  • aggregation.alignmentPeriod: 600s
  • aggregation.crossSeriesReducer: REDUCE_MEAN
  • aggregation.perSeriesAligner: ALIGN_MEAN
  • filter: metric.type = "compute.googleapis.com/instance/cpu/utilization"
  • interval.start_time: 2018-05-11T00:00:00Z
  • interval.end_time: 2018-05-11T00:20:00Z
  • fields: timeSeries.metric,timeSeries.points

Probar

Antes de hacer clic en el botón Ejecutar, cambia [PROJECT_ID] por el ID de tu proyecto y establece la hora de finalización en una hora reciente y la hora de inicio en 20 minutos antes.

El siguiente resultado de muestra tiene solo una serie temporal y dos datos. Cada punto es el promedio del uso entre las tres instancias de VM durante el período:

{
 "timeSeries": [
  {
   "metric": {
    "type": "compute.googleapis.com/instance/cpu/utilization"
   },
   "points": [
    {
     "interval": {
      "startTime": "2018-05-04T14:00:00.000Z",
      "endTime": "2018-05-04T14:00:00.000Z"
     },
     "value": {
      "doubleValue": 0.045992419596619184
     }
    },
    {
     "interval": {
      "startTime": "2018-05-04T13:50:00.000Z",
      "endTime": "2018-05-04T13:50:00.000Z"
     },
     "value": {
      "doubleValue": 0.04628773578358556
     }
    }
   ]
  }
 ]
}

C#

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

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

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

// 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: %v", err)
	}
	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: %v", 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

MetricServiceClient metricServiceClient = MetricServiceClient.create();
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();

ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

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

Node.js

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

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

/**
 * 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}`);

PHP

use Google\Cloud\Monitoring\V3\MetricServiceClient;
use Google\Cloud\Monitoring\V3\Aggregation_Aligner;
use Google\Cloud\Monitoring\V3\Aggregation_Reducer;
use Google\Cloud\Monitoring\V3\Aggregation;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Cloud\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView;
use Google\Protobuf\Duration;
use Google\Protobuf\Timestamp;

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

    $projectName = $metrics->projectName($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 = ListTimeSeriesRequest_TimeSeriesView::FULL;

    $result = $metrics->listTimeSeries(
        $projectName,
        $filter,
        $interval,
        $view,
        ['aggregation' => $aggregation]);

    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

client = monitoring_v3.MetricServiceClient()
project_name = client.project_path(project_id)
interval = monitoring_v3.types.TimeInterval()
now = time.time()
interval.end_time.seconds = int(now)
interval.end_time.nanos = int(
    (now - interval.end_time.seconds) * 10**9)
interval.start_time.seconds = int(now - 3600)
interval.start_time.nanos = interval.end_time.nanos
aggregation = monitoring_v3.types.Aggregation()
aggregation.alignment_period.seconds = 1200  # 20 minutes
aggregation.per_series_aligner = (
    monitoring_v3.enums.Aggregation.Aligner.ALIGN_MEAN)
aggregation.cross_series_reducer = (
    monitoring_v3.enums.Aggregation.Reducer.REDUCE_MEAN)
aggregation.group_by_fields.append('resource.zone')

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

Ruby

# 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

Consulta Soluciona problemas de llamadas a la API si tienes dificultades.