AdSense

網頁

2024/3/12

Golang 取得GCP Monitoring Metric aggregated time series data

Go以Google API Client Libraries來取得CloudWatch metric的聚合時間序列資料。


聚合(Aggregation)是指將原始時間序列資料(Raw time-series data),以某種時間區間和方式重新安排或群組為新的時間序列。本範例是將原本每分鐘取樣一次的time series資料,改以每10分鐘加總的方式呈現。


事前要求

參考「Golang 取得GCP Monitoring Metric time series data」。


取得aggreated time series data

請求參數monitoringpb.ListTimeSeriesRequestAggregation欄位可設定time series的聚合(aggregate)條件。

monitoringpb.Aggregation欄位如下:

  • AlignmentPeriod - 將原始time series資料重對齊(alignment)的時間區間。這邊設定區間為10分鐘。
  • PerSeriesAligner - 依照alignment period區間將一條原始time series資料聚合的方式。這邊設定的alignermonitoringpb.Aggregation_ALIGN_SUM,也就是將alignment period中的資料相加。

main.go

package main

import (
    "context"
    "fmt"
    "time"

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

func main() {
    ctx := context.Background()
    c, err := monitoring.NewMetricClient(ctx)
    if err != nil {
        panic(err)
    }
    defer c.Close()

    projectId := "project-id-1"

    now := time.Now().UTC()
    startTime := now.Add(time.Minute * -10).Unix()
    endTime := now.Unix()

    req := &monitoringpb.ListTimeSeriesRequest{
        Name: "projects/" + projectId,
        Filter: `
    resource.type="gce_instance"
    metric.type="compute.googleapis.com/instance/cpu/utilization" AND
    metric.labels.instance_name = "instance-1"
    `,
        Interval: &monitoringpb.TimeInterval{
            StartTime: &timestamp.Timestamp{Seconds: startTime},
            EndTime:   &timestamp.Timestamp{Seconds: endTime},
        },
        Aggregation: &monitoringpb.Aggregation{
            AlignmentPeriod:  durationpb.New(time.Minute * 10),
            PerSeriesAligner: monitoringpb.Aggregation_ALIGN_SUM,
        },
    }
    it := c.ListTimeSeries(ctx, req)
    for {
        resp, err := it.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            panic(err)
        }

        for _, p := range resp.Points {
            fmt.Println(p.GetInterval().GetEndTime().AsTime())
            fmt.Println(p.GetValue().GetDoubleValue())
        }
    }

}
github

測試

執行Go應用程式印出以下。

2024-03-12 07:29:15 +0000 UTC
0.05103667964705588


沒有留言:

AdSense