-
Notifications
You must be signed in to change notification settings - Fork 474
/
metrics.go
251 lines (225 loc) · 8.84 KB
/
metrics.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package prometheus
import (
"context"
"fmt"
"strings"
"sync"
"time"
prom_v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
"github.com/kiali/kiali/prometheus/internalmetrics"
)
func getMetrics(api prom_v1.API, q *IstioMetricsQuery) Metrics {
labels, labelsError := buildLabelStrings(q)
grouping := strings.Join(q.ByLabels, ",")
metrics := fetchAllMetrics(api, q, labels, labelsError, grouping)
return metrics
}
func buildLabelStrings(q *IstioMetricsQuery) (string, string) {
labels := []string{fmt.Sprintf(`reporter="%s"`, q.Reporter)}
ref := "destination"
if q.Direction == "outbound" {
ref = "source"
}
if q.Service != "" {
// inbound only
labels = append(labels, fmt.Sprintf(`destination_service_name="%s"`, q.Service))
if q.Namespace != "" {
labels = append(labels, fmt.Sprintf(`destination_service_namespace="%s"`, q.Namespace))
}
} else if q.Namespace != "" {
labels = append(labels, fmt.Sprintf(`%s_workload_namespace="%s"`, ref, q.Namespace))
}
if q.Workload != "" {
labels = append(labels, fmt.Sprintf(`%s_workload="%s"`, ref, q.Workload))
}
if q.App != "" {
labels = append(labels, fmt.Sprintf(`%s_app="%s"`, ref, q.App))
}
if q.RequestProtocol != "" {
labels = append(labels, fmt.Sprintf(`request_protocol="%s"`, q.RequestProtocol))
}
full := "{" + strings.Join(labels, ",") + "}"
labels = append(labels, `response_code=~"[5|4].*"`)
errors := "{" + strings.Join(labels, ",") + "}"
return full, errors
}
func fetchAllMetrics(api prom_v1.API, q *IstioMetricsQuery, labels, labelsError, grouping string) Metrics {
var wg sync.WaitGroup
fetchRate := func(p8sFamilyName string, metric **Metric, lbl string) {
defer wg.Done()
m := fetchRateRange(api, p8sFamilyName, lbl, grouping, &q.BaseMetricsQuery)
*metric = m
}
fetchHisto := func(p8sFamilyName string, histo *Histogram) {
defer wg.Done()
h := fetchHistogramRange(api, p8sFamilyName, labels, grouping, &q.BaseMetricsQuery)
*histo = h
}
type resultHolder struct {
metric *Metric
histo Histogram
definition istioMetric
}
maxResults := len(istioMetrics)
if len(q.Filters) != 0 {
maxResults = len(q.Filters)
}
results := make([]*resultHolder, maxResults)
for _, istioMetric := range istioMetrics {
// if filters is empty, fetch all anyway
doFetch := len(q.Filters) == 0
if !doFetch {
for _, filter := range q.Filters {
if filter == istioMetric.kialiName {
doFetch = true
break
}
}
}
if doFetch {
wg.Add(1)
result := resultHolder{definition: istioMetric}
results = append(results, &result)
if istioMetric.isHisto {
go fetchHisto(istioMetric.istioName, &result.histo)
} else {
labelsToUse := istioMetric.labelsToUse(labels, labelsError)
go fetchRate(istioMetric.istioName, &result.metric, labelsToUse)
}
}
}
wg.Wait()
// Return results as two maps per reporter
metrics := make(map[string]*Metric)
histograms := make(map[string]Histogram)
for _, result := range results {
if result != nil {
if result.definition.isHisto {
histograms[result.definition.kialiName] = result.histo
} else {
metrics[result.definition.kialiName] = result.metric
}
}
}
return Metrics{
Metrics: metrics,
Histograms: histograms,
}
}
func fetchRateRange(api prom_v1.API, metricName, labels, grouping string, q *BaseMetricsQuery) *Metric {
var query string
// Example: round(sum(rate(my_counter{foo=bar}[5m])) by (baz), 0.001)
if grouping == "" {
query = fmt.Sprintf("sum(%s(%s%s[%s]))", q.RateFunc, metricName, labels, q.RateInterval)
} else {
query = fmt.Sprintf("sum(%s(%s%s[%s])) by (%s)", q.RateFunc, metricName, labels, q.RateInterval, grouping)
}
query = roundSignificant(query, 0.001)
return fetchRange(api, query, q.Range)
}
func fetchHistogramRange(api prom_v1.API, metricName, labels, grouping string, q *BaseMetricsQuery) Histogram {
histogram := make(Histogram)
// Note: the p8s queries are not run in parallel here, but they are at the caller's place.
// This is because we may not want to create too many threads in the lowest layer
if q.Avg {
groupingAvg := ""
if grouping != "" {
groupingAvg = fmt.Sprintf(" by (%s)", grouping)
}
// Average
// Example: sum(rate(my_histogram_sum{foo=bar}[5m])) by (baz) / sum(rate(my_histogram_count{foo=bar}[5m])) by (baz)
query := fmt.Sprintf("sum(rate(%s_sum%s[%s]))%s / sum(rate(%s_count%s[%s]))%s",
metricName, labels, q.RateInterval, groupingAvg, metricName, labels, q.RateInterval, groupingAvg)
query = roundSignificant(query, 0.001)
histogram["avg"] = fetchRange(api, query, q.Range)
}
groupingQuantile := ""
if grouping != "" {
groupingQuantile = fmt.Sprintf(",%s", grouping)
}
for _, quantile := range q.Quantiles {
// Example: round(histogram_quantile(0.5, sum(rate(my_histogram_bucket{foo=bar}[5m])) by (le,baz)), 0.001)
query := fmt.Sprintf("histogram_quantile(%s, sum(rate(%s_bucket%s[%s])) by (le%s))",
quantile, metricName, labels, q.RateInterval, groupingQuantile)
query = roundSignificant(query, 0.001)
histogram[quantile] = fetchRange(api, query, q.Range)
}
return histogram
}
func fetchRange(api prom_v1.API, query string, bounds prom_v1.Range) *Metric {
result, err := api.QueryRange(context.Background(), query, bounds)
if err != nil {
return &Metric{err: err}
}
switch result.Type() {
case model.ValMatrix:
return &Metric{Matrix: result.(model.Matrix)}
}
return &Metric{err: fmt.Errorf("invalid query, matrix expected: %s", query)}
}
// getAllRequestRates retrieves traffic rates for requests entering, internal to, or exiting the namespace.
// Uses source telemetry unless working on the Istio namespace.
func getAllRequestRates(api prom_v1.API, namespace string, queryTime time.Time, ratesInterval string) (model.Vector, error) {
// traffic originating outside the namespace to destinations inside the namespace
lbl := fmt.Sprintf(`destination_service_namespace="%s",source_workload_namespace!="%s"`, namespace, namespace)
fromOutside, err := getRequestRatesForLabel(api, queryTime, lbl, ratesInterval)
if err != nil {
return model.Vector{}, err
}
// traffic originating inside the namespace to destinations inside or outside the namespace
lbl = fmt.Sprintf(`source_workload_namespace="%s"`, namespace)
fromInside, err := getRequestRatesForLabel(api, queryTime, lbl, ratesInterval)
if err != nil {
return model.Vector{}, err
}
// Merge results
all := append(fromOutside, fromInside...)
return all, nil
}
// getNamespaceServicesRequestRates retrieves traffic rates for requests entering or internal to the namespace.
// Uses source telemetry unless working on the Istio namespace.
func getNamespaceServicesRequestRates(api prom_v1.API, namespace string, queryTime time.Time, ratesInterval string) (model.Vector, error) {
// traffic for the namespace services
lblNs := fmt.Sprintf(`destination_service_namespace="%s"`, namespace)
ns, err := getRequestRatesForLabel(api, queryTime, lblNs, ratesInterval)
if err != nil {
return model.Vector{}, err
}
return ns, nil
}
func getServiceRequestRates(api prom_v1.API, namespace, service string, queryTime time.Time, ratesInterval string) (model.Vector, error) {
lbl := fmt.Sprintf(`destination_service_name="%s",destination_service_namespace="%s"`, service, namespace)
in, err := getRequestRatesForLabel(api, queryTime, lbl, ratesInterval)
if err != nil {
return model.Vector{}, err
}
return in, nil
}
func getItemRequestRates(api prom_v1.API, namespace, item, itemLabelSuffix string, queryTime time.Time, ratesInterval string) (model.Vector, model.Vector, error) {
lblIn := fmt.Sprintf(`destination_workload_namespace="%s",destination_%s="%s"`, namespace, itemLabelSuffix, item)
lblOut := fmt.Sprintf(`source_workload_namespace="%s",source_%s="%s"`, namespace, itemLabelSuffix, item)
in, err := getRequestRatesForLabel(api, queryTime, lblIn, ratesInterval)
if err != nil {
return model.Vector{}, model.Vector{}, err
}
out, err := getRequestRatesForLabel(api, queryTime, lblOut, ratesInterval)
if err != nil {
return model.Vector{}, model.Vector{}, err
}
return in, out, nil
}
func getRequestRatesForLabel(api prom_v1.API, time time.Time, labels, ratesInterval string) (model.Vector, error) {
query := fmt.Sprintf("rate(istio_requests_total{%s}[%s])", labels, ratesInterval)
promtimer := internalmetrics.GetPrometheusProcessingTimePrometheusTimer("Metrics-GetRequestRates")
result, err := api.Query(context.Background(), query, time)
if err != nil {
return model.Vector{}, err
}
promtimer.ObserveDuration() // notice we only collect metrics for successful prom queries
return result.(model.Vector), nil
}
// roundSignificant will output promQL that performs rounding only if the resulting value is significant, that is, higher than the requested precision
func roundSignificant(innerQuery string, precision float64) string {
return fmt.Sprintf("round(%s, %f) > %f or %s", innerQuery, precision, precision, innerQuery)
}