AdSense

網頁

2024/3/18

Golang 取得GCP Monitoring Instance Disk寫入大小統計

Go以Google Cloud Client Libraries for Go來取得GCP Monitoring的instance [Disk write bytes]指標的時間序列資料。



事前要求

參考「GCP 建立Compute Engine VM instance」建立名為"instance-1"的instance和名為"instance-1"的disk。

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


取得Disk write bytes指標

參數monitoringpb.ListTimeSeriesRequest欄位:



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

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/disk/write_bytes_count" AND
    metric.labels.instance_name = "instance-1" AND
    metric.labels.device_name = "instance-1"
    `,
        Interval: &monitoringpb.TimeInterval{
            StartTime: &timestamp.Timestamp{Seconds: startTime},
            EndTime:   &timestamp.Timestamp{Seconds: endTime},
        },
    }
    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().GetInt64Value())
        }
    }

}

github



測試

執行印出以下。

2024-03-18 08:47:00 +0000 UTC
12413
2024-03-18 08:46:00 +0000 UTC
16384
2024-03-18 08:45:00 +0000 UTC
17006
2024-03-18 08:44:00 +0000 UTC
35868
2024-03-18 08:43:00 +0000 UTC
4470
2024-03-18 08:42:00 +0000 UTC
16259
2024-03-18 08:41:00 +0000 UTC
22118
2024-03-18 08:40:00 +0000 UTC
336624

沒有留言:

AdSense