k8s.io/perf-tests/clusterloader2@v0.0.0-20240304094227-64bdb12da87e/pkg/prometheus/clients/gcp_managed.go (about)

     1  /*
     2  Copyright 2022 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package prom
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"io/ioutil"
    23  	"net/http"
    24  	"net/url"
    25  	"os"
    26  	"time"
    27  
    28  	"golang.org/x/oauth2/google"
    29  )
    30  
    31  // gcpManagedPrometheusClient talks to the Google Cloud Managed Service for Prometheus.
    32  // This only works if the cluster is hosted in GCP.
    33  // Details: https://cloud.google.com/stackdriver/docs/managed-prometheus.
    34  type gcpManagedPrometheusClient struct {
    35  	client *http.Client
    36  	uri    string
    37  }
    38  
    39  func (mpc *gcpManagedPrometheusClient) Query(query string, queryTime time.Time) ([]byte, error) {
    40  	params := url.Values{}
    41  	params.Add("query", query)
    42  	params.Add("time", queryTime.Format(time.RFC3339))
    43  	res, err := mpc.client.Get(mpc.uri + "?" + params.Encode())
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	defer res.Body.Close()
    48  	resBody, err := ioutil.ReadAll(res.Body)
    49  	if statusCode := res.StatusCode; statusCode > 299 {
    50  		return resBody, fmt.Errorf("response failed with status code %d", statusCode)
    51  	}
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  	return resBody, nil
    56  }
    57  
    58  // NewGCPManagedPrometheusClient returns an HTTP client for talking to
    59  // the Google Cloud Managed Service for Prometheus.
    60  func NewGCPManagedPrometheusClient() (Client, error) {
    61  	client, err := google.DefaultClient(context.TODO(), "https://www.googleapis.com/auth/monitoring.read")
    62  	if err != nil {
    63  		return nil, err
    64  	}
    65  	return &gcpManagedPrometheusClient{
    66  		client: client,
    67  		uri:    fmt.Sprintf("https://monitoring.googleapis.com/v1/projects/%s/location/global/prometheus/api/v1/query", os.Getenv("PROJECT")),
    68  	}, nil
    69  }
    70  
    71  var _ Client = &gcpManagedPrometheusClient{}