| 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 | ) |
| 26 | |
| 27 | func readIntGauge(metricsURL, metricName string) (int, error) { |
| 28 | metrics, err := scrapeMetrics(metricsURL) |
| 29 | if err != nil { |
| 30 | return 0, err |
| 31 | } |
| 32 | |
| 33 | metric, found := metrics[metricName] |
| 34 | if !found { |
| 35 | return 0, fmt.Errorf("missing %s metric", metricName) |
| 36 | } |
| 37 | |
| 38 | vals := metric.GetMetric() |
| 39 | if len(vals) == 0 { |
| 40 | return 0, fmt.Errorf("missing value for %s metric", metricName) |
| 41 | } |
| 42 | |
| 43 | return int(vals[0].GetGauge().GetValue()), nil |
| 44 | } |
| 45 | |
| 46 | func scrapeMetrics(metricsURL string) (map[string]*dto.MetricFamily, error) { |
| 47 | resp, err := http.Get(metricsURL) |
| 48 | if err != nil { |
| 49 | return nil, fmt.Errorf("failed to scrape metrics from %s: %w", metricsURL, err) |
| 50 | } |
| 51 | defer resp.Body.Close() |
| 52 | |
| 53 | if resp.StatusCode != http.StatusOK { |
| 54 | return nil, fmt.Errorf("unexpected %q status scraping metrics from %s", resp.Status, metricsURL) |
| 55 | } |
| 56 | |
| 57 | var parser expfmt.TextParser |
| 58 | mf, err := parser.TextToMetricFamilies(resp.Body) |
| 59 | if err != nil { |
| 60 | return nil, fmt.Errorf("failed to parse metrics: %w", err) |
| 61 | } |
| 62 | return mf, nil |
| 63 | } |