github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/pkg/metrics/push.go (about)

     1  /*
     2  Copyright 2019 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  // This file is a copy from upstream where it was removed in
    18  // https://github.com/prometheus/client_golang/pull/600
    19  package metrics
    20  
    21  import (
    22  	"bytes"
    23  	"fmt"
    24  	"io"
    25  	"net/http"
    26  	"net/url"
    27  	"os"
    28  	"strings"
    29  
    30  	"github.com/prometheus/client_golang/prometheus"
    31  	"github.com/prometheus/common/expfmt"
    32  	"github.com/prometheus/common/model"
    33  )
    34  
    35  const contentTypeHeader = "Content-Type"
    36  
    37  func fromGatherer(job string, grouping map[string]string, url string, g prometheus.Gatherer) error {
    38  	return push(job, grouping, url, g, "PUT")
    39  }
    40  
    41  func push(job string, grouping map[string]string, pushURL string, g prometheus.Gatherer, method string) error {
    42  	if !strings.Contains(pushURL, "://") {
    43  		pushURL = "http://" + pushURL
    44  	}
    45  	pushURL = strings.TrimSuffix(pushURL, "/")
    46  
    47  	if strings.Contains(job, "/") {
    48  		return fmt.Errorf("job contains '/': %s", job)
    49  	}
    50  	urlComponents := []string{url.QueryEscape(job)}
    51  	for ln, lv := range grouping {
    52  		if !model.LabelName(ln).IsValid() {
    53  			return fmt.Errorf("grouping label has invalid name: %s", ln)
    54  		}
    55  		if strings.Contains(lv, "/") {
    56  			return fmt.Errorf("value of grouping label %s contains '/': %s", ln, lv)
    57  		}
    58  		urlComponents = append(urlComponents, ln, lv)
    59  	}
    60  	pushURL = fmt.Sprintf("%s/metrics/job/%s", pushURL, strings.Join(urlComponents, "/"))
    61  
    62  	mfs, err := g.Gather()
    63  	if err != nil {
    64  		return err
    65  	}
    66  	buf := &bytes.Buffer{}
    67  	enc := expfmt.NewEncoder(buf, expfmt.FmtProtoDelim)
    68  	// Check for pre-existing grouping labels:
    69  	for _, mf := range mfs {
    70  		for _, m := range mf.GetMetric() {
    71  			for _, l := range m.GetLabel() {
    72  				if l.GetName() == "job" {
    73  					return fmt.Errorf("pushed metric %s (%s) already contains a job label", mf.GetName(), m)
    74  				}
    75  				if _, ok := grouping[l.GetName()]; ok {
    76  					return fmt.Errorf(
    77  						"pushed metric %s (%s) already contains grouping label %s",
    78  						mf.GetName(), m, l.GetName(),
    79  					)
    80  				}
    81  			}
    82  		}
    83  		enc.Encode(mf)
    84  	}
    85  	req, err := http.NewRequest(method, pushURL, buf)
    86  	if err != nil {
    87  		return err
    88  	}
    89  	req.Header.Set(contentTypeHeader, string(expfmt.FmtProtoDelim))
    90  	resp, err := http.DefaultClient.Do(req)
    91  	if err != nil {
    92  		return err
    93  	}
    94  	defer resp.Body.Close()
    95  	if !(resp.StatusCode == 200 || resp.StatusCode == 202) {
    96  		body, _ := io.ReadAll(resp.Body) // Ignore any further error as this is for an error message only.
    97  		return fmt.Errorf("unexpected status code %d while pushing to %s: %s", resp.StatusCode, pushURL, body)
    98  	}
    99  	return nil
   100  }
   101  
   102  func hostnameGroupingKey() map[string]string {
   103  	hostname, err := os.Hostname()
   104  	if err != nil {
   105  		return map[string]string{"instance": "unknown"}
   106  	}
   107  	return map[string]string{"instance": hostname}
   108  }