-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathquery_cache.go
More file actions
273 lines (239 loc) · 7.54 KB
/
Copy pathquery_cache.go
File metadata and controls
273 lines (239 loc) · 7.54 KB
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT
package otelmetrics
import (
"context"
"fmt"
"log/slog"
"strings"
"sync"
)
// DefaultMaxConcurrency is the default number of concurrent in-flight queries.
const DefaultMaxConcurrency = 3
// promqlEscaper is the shared escaper for PromQL label values.
var promqlEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`)
func promqlMetricSelector(metricName string) string {
if strings.Contains(metricName, ".") {
return fmt.Sprintf(`{"__name__"="%s",`, metricName)
}
return metricName + "{"
}
type cacheEntry struct {
results []MetricResult
err error
}
// QueryCache provides session-scoped caching of PromQL queries.
// Each unique metric name is queried exactly once; subsequent calls return cached data.
// Concurrent requests for the same metric are deduplicated via singleflight.
type QueryCache struct {
mu sync.RWMutex
filtered map[string]cacheEntry
unfiltered map[string]cacheEntry
client *OtelMetricsClient
cluster string
hostTypes []string
registry *SourceRegistry
sem chan struct{}
inflight map[string]chan struct{} // dedup concurrent fetches for same key
}
// QueryCacheOption configures optional QueryCache behavior.
type QueryCacheOption func(*QueryCache)
func WithHostTypes(hostTypes []string) QueryCacheOption {
return func(qc *QueryCache) { qc.hostTypes = hostTypes }
}
func WithSourceRegistry(registry *SourceRegistry) QueryCacheOption {
return func(qc *QueryCache) { qc.registry = registry }
}
func WithMaxConcurrency(n int) QueryCacheOption {
return func(qc *QueryCache) { qc.sem = make(chan struct{}, n) }
}
func NewQueryCache(client *OtelMetricsClient, clusterName string, opts ...QueryCacheOption) *QueryCache {
qc := &QueryCache{
filtered: make(map[string]cacheEntry),
unfiltered: make(map[string]cacheEntry),
inflight: make(map[string]chan struct{}),
client: client,
cluster: clusterName,
}
for _, opt := range opts {
opt(qc)
}
if qc.sem == nil {
qc.sem = make(chan struct{}, DefaultMaxConcurrency)
}
return qc
}
// Get returns cached results for a metric filtered by cluster name.
// Concurrent calls for the same metric are deduplicated.
func (qc *QueryCache) Get(ctx context.Context, metricName string) ([]MetricResult, error) {
// Fast path: cache hit
qc.mu.RLock()
if entry, ok := qc.filtered[metricName]; ok {
qc.mu.RUnlock()
return entry.results, entry.err
}
// Check if another goroutine is already fetching this metric
if ch, ok := qc.inflight[metricName]; ok {
qc.mu.RUnlock()
<-ch // wait for the fetch to complete
qc.mu.RLock()
entry, ok := qc.filtered[metricName]
qc.mu.RUnlock()
if !ok {
// Empty result was not cached; caller should retry.
return nil, nil
}
return entry.results, entry.err
}
qc.mu.RUnlock()
// Claim this metric fetch
qc.mu.Lock()
// Double-check after acquiring write lock
if entry, ok := qc.filtered[metricName]; ok {
qc.mu.Unlock()
return entry.results, entry.err
}
if ch, ok := qc.inflight[metricName]; ok {
qc.mu.Unlock()
<-ch
qc.mu.RLock()
entry, ok := qc.filtered[metricName]
qc.mu.RUnlock()
if !ok {
// Empty result was not cached; caller should retry.
return nil, nil
}
return entry.results, entry.err
}
ch := make(chan struct{})
qc.inflight[metricName] = ch
qc.mu.Unlock()
// Fetch without holding any lock
entry := qc.fetchFiltered(ctx, metricName)
// Store and signal waiters.
// Do not cache empty successful results; a transient miss would poison
// all later lookups for this metric within the same test binary run.
qc.mu.Lock()
if len(entry.results) > 0 || entry.err != nil {
qc.filtered[metricName] = entry
}
delete(qc.inflight, metricName)
qc.mu.Unlock()
close(ch)
return entry.results, entry.err
}
// fetchFiltered performs the actual HTTP query for a filtered metric.
func (qc *QueryCache) fetchFiltered(ctx context.Context, metricName string) cacheEntry {
escaped := promqlEscaper.Replace(qc.cluster)
sel := promqlMetricSelector(metricName)
var results []MetricResult
var firstErr error
var targetHosts []string
clusterScopedOnly := false
if qc.registry != nil {
if qc.registry.IsClusterScoped(metricName) {
clusterScopedOnly = true
} else {
targetHosts = qc.registry.HostTypesFor(metricName)
}
} else if len(qc.hostTypes) > 0 {
targetHosts = qc.hostTypes
}
if clusterScopedOnly {
promql := fmt.Sprintf(`%s"@resource.k8s.cluster.name"="%s","@resource.host.type"=""}`, sel, escaped)
r, err := qc.client.Query(ctx, promql)
if err != nil {
firstErr = err
} else {
results = append(results, r...)
}
} else if len(targetHosts) > 0 {
type queryResult struct {
results []MetricResult
err error
}
ch := make(chan queryResult, len(targetHosts))
var wg sync.WaitGroup
for _, ht := range targetHosts {
wg.Add(1)
go func(hostType string) {
defer wg.Done()
select {
case qc.sem <- struct{}{}:
defer func() { <-qc.sem }()
case <-ctx.Done():
ch <- queryResult{err: ctx.Err()}
return
}
promql := fmt.Sprintf(`%s"@resource.k8s.cluster.name"="%s","@resource.host.type"="%s"}`, sel, escaped, hostType)
r, err := qc.client.Query(ctx, promql)
ch <- queryResult{results: r, err: err}
}(ht)
}
go func() { wg.Wait(); close(ch) }()
for qr := range ch {
if qr.err != nil {
if firstErr == nil {
firstErr = qr.err
}
continue
}
results = append(results, qr.results...)
}
} else {
promql := fmt.Sprintf(`%s"@resource.k8s.cluster.name"="%s"}`, sel, escaped)
r, err := qc.client.Query(ctx, promql)
results = r
firstErr = err
}
if len(results) == 0 && firstErr != nil {
slog.Debug("query failed", "metric", metricName, "error", firstErr)
return cacheEntry{err: firstErr}
}
return cacheEntry{results: results}
}
// GetWithFilter returns results with additional PromQL label filters. Not cached.
func (qc *QueryCache) GetWithFilter(ctx context.Context, metricName string, extraFilters map[string]string) ([]MetricResult, error) {
escaped := promqlEscaper.Replace(qc.cluster)
sel := promqlMetricSelector(metricName)
filters := fmt.Sprintf(`"@resource.k8s.cluster.name"="%s"`, escaped)
for key, value := range extraFilters {
escapedVal := promqlEscaper.Replace(value)
switch {
case strings.HasPrefix(key, "~@resource."):
filters += fmt.Sprintf(`,"%s"=~"%s"`, strings.TrimPrefix(key, "~"), escapedVal)
case strings.HasPrefix(key, "@resource."):
filters += fmt.Sprintf(`,"%s"="%s"`, key, escapedVal)
case strings.HasPrefix(key, "~"):
filters += fmt.Sprintf(`,%s=~"%s"`, strings.TrimPrefix(key, "~"), escapedVal)
default:
filters += fmt.Sprintf(`,%s="%s"`, key, escapedVal)
}
}
return qc.client.Query(ctx, sel+filters+"}")
}
// GetUnfiltered returns results without cluster filtering. Cached separately.
func (qc *QueryCache) GetUnfiltered(ctx context.Context, metricName string) ([]MetricResult, error) {
qc.mu.RLock()
if entry, ok := qc.unfiltered[metricName]; ok {
qc.mu.RUnlock()
return entry.results, entry.err
}
qc.mu.RUnlock()
qc.mu.Lock()
if entry, ok := qc.unfiltered[metricName]; ok {
qc.mu.Unlock()
return entry.results, entry.err
}
qc.mu.Unlock()
results, queryErr := qc.client.Query(ctx, metricName)
entry := cacheEntry{results: results, err: queryErr}
// Do not cache empty successful results; a transient miss would poison
// all later lookups for this metric within the same test binary run.
qc.mu.Lock()
if len(entry.results) > 0 || entry.err != nil {
qc.unfiltered[metricName] = entry
}
qc.mu.Unlock()
return entry.results, entry.err
}