Debian Codegraph @

tests/framework/metrics.go

raw
1 /*
2 Copyright 2023 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 framework
18
19 import (
20 "fmt"
21 "net/http"
22
23 dto "github.com/prometheus/client_model/go"
24 "github.com/prometheus/common/expfmt"
25 "github.com/prometheus/common/model"
26 )
27
28 func readIntGauge(metricsURL, metricName string) (int, error) {
29 metrics, err := scrapeMetrics(metricsURL)
30 if err != nil {
31 return 0, err
32 }
33
34 metric, found := metrics[metricName]
35 if !found {
36 return 0, fmt.Errorf("missing %s metric", metricName)
37 }
38
39 vals := metric.GetMetric()
40 if len(vals) == 0 {
41 return 0, fmt.Errorf("missing value for %s metric", metricName)
42 }
43
44 return int(vals[0].GetGauge().GetValue()), nil
45 }
46
47 func scrapeMetrics(metricsURL string) (map[string]*dto.MetricFamily, error) {
48 resp, err := http.Get(metricsURL)
49 if err != nil {
50 return nil, fmt.Errorf("failed to scrape metrics from %s: %w", metricsURL, err)
51 }
52 defer resp.Body.Close()
53
54 if resp.StatusCode != http.StatusOK {
55 return nil, fmt.Errorf("unexpected %q status scraping metrics from %s", resp.Status, metricsURL)
56 }
57
58 parser := expfmt.NewTextParser(model.LegacyValidation)
59 mf, err := parser.TextToMetricFamilies(resp.Body)
60 if err != nil {
61 return nil, fmt.Errorf("failed to parse metrics: %w", err)
62 }
63 return mf, nil
64 }