|
| 1 | +// Copyright 2024 Google Inc. All Rights Reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package framework |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + "io" |
| 20 | + "net/http" |
| 21 | + "strings" |
| 22 | + "time" |
| 23 | + |
| 24 | + dto "github.com/prometheus/client_model/go" |
| 25 | + "github.com/prometheus/common/expfmt" |
| 26 | +) |
| 27 | + |
| 28 | +// MetricsClient provides methods for fetching and parsing Prometheus metrics |
| 29 | +// from cAdvisor's /metrics endpoint. |
| 30 | +type MetricsClient struct { |
| 31 | + baseURL string |
| 32 | + httpClient *http.Client |
| 33 | +} |
| 34 | + |
| 35 | +// NewMetricsClient creates a new client for the /metrics endpoint. |
| 36 | +func NewMetricsClient(hostname HostnameInfo) *MetricsClient { |
| 37 | + return &MetricsClient{ |
| 38 | + baseURL: hostname.FullHostname(), |
| 39 | + httpClient: &http.Client{ |
| 40 | + Timeout: 30 * time.Second, |
| 41 | + }, |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// Fetch retrieves raw metrics text from the /metrics endpoint. |
| 46 | +func (m *MetricsClient) Fetch() (string, error) { |
| 47 | + return m.FetchWithParams("") |
| 48 | +} |
| 49 | + |
| 50 | +// FetchWithParams retrieves metrics with optional query parameters. |
| 51 | +// Parameters can be "type=docker" or "type=name" to filter containers. |
| 52 | +func (m *MetricsClient) FetchWithParams(params string) (string, error) { |
| 53 | + url := m.baseURL + "metrics" |
| 54 | + if params != "" { |
| 55 | + url += "?" + params |
| 56 | + } |
| 57 | + |
| 58 | + resp, err := m.httpClient.Get(url) |
| 59 | + if err != nil { |
| 60 | + return "", fmt.Errorf("failed to fetch metrics: %w", err) |
| 61 | + } |
| 62 | + defer resp.Body.Close() |
| 63 | + |
| 64 | + if resp.StatusCode != http.StatusOK { |
| 65 | + body, _ := io.ReadAll(resp.Body) |
| 66 | + return "", fmt.Errorf("metrics endpoint returned %d: %s", resp.StatusCode, string(body)) |
| 67 | + } |
| 68 | + |
| 69 | + body, err := io.ReadAll(resp.Body) |
| 70 | + if err != nil { |
| 71 | + return "", fmt.Errorf("failed to read response: %w", err) |
| 72 | + } |
| 73 | + |
| 74 | + return string(body), nil |
| 75 | +} |
| 76 | + |
| 77 | +// Parse converts Prometheus text format to metric families. |
| 78 | +func (m *MetricsClient) Parse(metricsText string) (map[string]*dto.MetricFamily, error) { |
| 79 | + parser := expfmt.TextParser{} |
| 80 | + return parser.TextToMetricFamilies(strings.NewReader(metricsText)) |
| 81 | +} |
| 82 | + |
| 83 | +// FetchAndParse combines Fetch and Parse into one call. |
| 84 | +func (m *MetricsClient) FetchAndParse() (map[string]*dto.MetricFamily, error) { |
| 85 | + text, err := m.Fetch() |
| 86 | + if err != nil { |
| 87 | + return nil, err |
| 88 | + } |
| 89 | + return m.Parse(text) |
| 90 | +} |
| 91 | + |
| 92 | +// HasMetric checks if a metric family exists by name. |
| 93 | +func HasMetric(families map[string]*dto.MetricFamily, name string) bool { |
| 94 | + _, ok := families[name] |
| 95 | + return ok |
| 96 | +} |
| 97 | + |
| 98 | +// GetMetricFamily returns a specific metric family by name. |
| 99 | +func GetMetricFamily(families map[string]*dto.MetricFamily, name string) (*dto.MetricFamily, bool) { |
| 100 | + mf, ok := families[name] |
| 101 | + return mf, ok |
| 102 | +} |
| 103 | + |
| 104 | +// FindMetricWithLabels finds a metric matching all specified labels. |
| 105 | +// Returns nil if no matching metric is found. |
| 106 | +func FindMetricWithLabels(mf *dto.MetricFamily, labels map[string]string) *dto.Metric { |
| 107 | + if mf == nil { |
| 108 | + return nil |
| 109 | + } |
| 110 | + for _, metric := range mf.GetMetric() { |
| 111 | + if matchesLabels(metric, labels) { |
| 112 | + return metric |
| 113 | + } |
| 114 | + } |
| 115 | + return nil |
| 116 | +} |
| 117 | + |
| 118 | +// FindMetricsWithLabelSubstring finds all metrics where the specified label |
| 119 | +// contains the given substring. |
| 120 | +func FindMetricsWithLabelSubstring(mf *dto.MetricFamily, labelName, substring string) []*dto.Metric { |
| 121 | + if mf == nil { |
| 122 | + return nil |
| 123 | + } |
| 124 | + var result []*dto.Metric |
| 125 | + for _, metric := range mf.GetMetric() { |
| 126 | + for _, lp := range metric.GetLabel() { |
| 127 | + if lp.GetName() == labelName && strings.Contains(lp.GetValue(), substring) { |
| 128 | + result = append(result, metric) |
| 129 | + break |
| 130 | + } |
| 131 | + } |
| 132 | + } |
| 133 | + return result |
| 134 | +} |
| 135 | + |
| 136 | +// GetGaugeValue extracts the value from a gauge metric. |
| 137 | +func GetGaugeValue(metric *dto.Metric) float64 { |
| 138 | + if metric == nil || metric.GetGauge() == nil { |
| 139 | + return 0 |
| 140 | + } |
| 141 | + return metric.GetGauge().GetValue() |
| 142 | +} |
| 143 | + |
| 144 | +// GetCounterValue extracts the value from a counter metric. |
| 145 | +func GetCounterValue(metric *dto.Metric) float64 { |
| 146 | + if metric == nil || metric.GetCounter() == nil { |
| 147 | + return 0 |
| 148 | + } |
| 149 | + return metric.GetCounter().GetValue() |
| 150 | +} |
| 151 | + |
| 152 | +// GetLabelValue returns the value of a specific label from a metric. |
| 153 | +// Returns empty string if label is not found. |
| 154 | +func GetLabelValue(metric *dto.Metric, labelName string) string { |
| 155 | + if metric == nil { |
| 156 | + return "" |
| 157 | + } |
| 158 | + for _, lp := range metric.GetLabel() { |
| 159 | + if lp.GetName() == labelName { |
| 160 | + return lp.GetValue() |
| 161 | + } |
| 162 | + } |
| 163 | + return "" |
| 164 | +} |
| 165 | + |
| 166 | +// ContainsLabelValue checks if any metric in the family has the label |
| 167 | +// containing the given substring. |
| 168 | +func ContainsLabelValue(mf *dto.MetricFamily, labelName, substring string) bool { |
| 169 | + if mf == nil { |
| 170 | + return false |
| 171 | + } |
| 172 | + for _, metric := range mf.GetMetric() { |
| 173 | + for _, lp := range metric.GetLabel() { |
| 174 | + if lp.GetName() == labelName && strings.Contains(lp.GetValue(), substring) { |
| 175 | + return true |
| 176 | + } |
| 177 | + } |
| 178 | + } |
| 179 | + return false |
| 180 | +} |
| 181 | + |
| 182 | +// GetMetricType returns the type of a metric family as a string. |
| 183 | +func GetMetricType(mf *dto.MetricFamily) string { |
| 184 | + if mf == nil { |
| 185 | + return "unknown" |
| 186 | + } |
| 187 | + return mf.GetType().String() |
| 188 | +} |
| 189 | + |
| 190 | +// matchesLabels checks if a metric has all the specified labels with exact values. |
| 191 | +func matchesLabels(metric *dto.Metric, targetLabels map[string]string) bool { |
| 192 | + if metric == nil { |
| 193 | + return false |
| 194 | + } |
| 195 | + labelMap := make(map[string]string) |
| 196 | + for _, lp := range metric.GetLabel() { |
| 197 | + labelMap[lp.GetName()] = lp.GetValue() |
| 198 | + } |
| 199 | + for k, v := range targetLabels { |
| 200 | + if labelMap[k] != v { |
| 201 | + return false |
| 202 | + } |
| 203 | + } |
| 204 | + return true |
| 205 | +} |
| 206 | + |
| 207 | +// CountMetrics returns the number of metric samples in a metric family. |
| 208 | +func CountMetrics(mf *dto.MetricFamily) int { |
| 209 | + if mf == nil { |
| 210 | + return 0 |
| 211 | + } |
| 212 | + return len(mf.GetMetric()) |
| 213 | +} |
| 214 | + |
| 215 | +// GetAllLabelValues returns all unique values for a given label name across |
| 216 | +// all metrics in the family. |
| 217 | +func GetAllLabelValues(mf *dto.MetricFamily, labelName string) []string { |
| 218 | + if mf == nil { |
| 219 | + return nil |
| 220 | + } |
| 221 | + seen := make(map[string]bool) |
| 222 | + var values []string |
| 223 | + for _, metric := range mf.GetMetric() { |
| 224 | + for _, lp := range metric.GetLabel() { |
| 225 | + if lp.GetName() == labelName { |
| 226 | + val := lp.GetValue() |
| 227 | + if !seen[val] { |
| 228 | + seen[val] = true |
| 229 | + values = append(values, val) |
| 230 | + } |
| 231 | + } |
| 232 | + } |
| 233 | + } |
| 234 | + return values |
| 235 | +} |
0 commit comments