-
Notifications
You must be signed in to change notification settings - Fork 67
/
manager.go
264 lines (227 loc) · 7.15 KB
/
manager.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
252
253
254
255
256
257
258
259
260
261
262
263
264
// Copyright 2022-2024 The Parca Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package labels
import (
"context"
"fmt"
"strconv"
"sync"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/relabel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"github.com/parca-dev/parca-agent/pkg/cache"
"github.com/parca-dev/parca-agent/pkg/metadata"
)
type Cache[K comparable, V any] interface {
Add(key K, value V)
Get(key K) (V, bool)
Peek(key K) (V, bool)
Purge()
}
// Manager is responsible for aggregating, mutating, and serving process labels.
type Manager struct {
logger log.Logger
tracer trace.Tracer
providers []metadata.Provider
providerCache Cache[string, model.LabelSet]
labelCache Cache[string, model.LabelSet]
mtx *sync.RWMutex
relabelConfigs []*relabel.Config
}
// New returns an initialized Manager.
func NewManager(
logger log.Logger,
tracer trace.Tracer,
reg prometheus.Registerer,
providers []metadata.Provider,
relabelConfigs []*relabel.Config,
cacheDisabled bool,
profilingDuration time.Duration,
) *Manager {
var (
labelCache Cache[string, model.LabelSet] = cache.NewNoopCache[string, model.LabelSet]()
providerCache Cache[string, model.LabelSet] = cache.NewNoopCache[string, model.LabelSet]()
)
if !cacheDisabled {
labelCache = cache.NewLRUCacheWithTTL[string, model.LabelSet](
prometheus.WrapRegistererWith(prometheus.Labels{"cache": "label"}, reg),
1024,
3*profilingDuration,
)
// Making cache durations shorter than label cache will not make any visible difference.
providerCache = cache.NewLRUCacheWithTTL[string, model.LabelSet](
prometheus.WrapRegistererWith(prometheus.Labels{"cache": "label_provider"}, reg),
1024,
10*6*profilingDuration,
)
}
return &Manager{
logger: logger,
tracer: tracer,
providers: providers,
mtx: &sync.RWMutex{},
relabelConfigs: relabelConfigs,
labelCache: labelCache,
providerCache: providerCache,
}
}
// ApplyConfig updates the Manager's config.
func (m *Manager) ApplyConfig(relabelConfigs []*relabel.Config) error {
m.mtx.Lock()
defer m.mtx.Unlock()
m.relabelConfigs = relabelConfigs
m.labelCache.Purge()
return nil
}
// labelSet fetches process specific labels to the profile.
// Returns nil if set is dropped.
func (m *Manager) labelSet(ctx context.Context, pid int) (model.LabelSet, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
ctx, span := m.tracer.Start(ctx, "LabelManager.labelSet")
defer span.End()
labelSet := model.LabelSet{
"pid": model.LabelValue(strconv.Itoa(pid)),
}
for _, provider := range m.providers {
_, span := m.tracer.Start(ctx, "LabelManager.labelSet/"+provider.Name())
shouldCache := provider.ShouldCache()
if shouldCache {
span.SetAttributes(attribute.Bool("cache", true))
key := providerCacheKey(provider.Name(), pid)
if lbls, ok := m.providerCache.Get(key); ok {
labelSet = labelSet.Merge(lbls)
span.End()
continue
}
}
// Add service discovery metadata, such as the Kubernetes pod where the
// process is running, among others.
lbl, err := provider.Labels(ctx, pid)
if err != nil {
// NOTICE: Can be too noisy. Keeping this for debugging purposes.
level.Debug(m.logger).Log("msg", "failed to get metadata", "provider", provider.Name(), "err", err)
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
if lbl == nil {
span.End()
continue
}
labelSet = labelSet.Merge(lbl)
if shouldCache {
// Stateless providers are cached for a longer period of time.
m.providerCache.Add(providerCacheKey(provider.Name(), pid), labelSet)
}
span.End()
}
return labelSet, nil
}
// Labels returns a labels.Labels with relabel configs applied.
// Returns nil if set is dropped.
// This method is only used by the UI for troubleshooting.
func (m *Manager) Labels(ctx context.Context, pid int) (labels.Labels, error) {
ctx, span := m.tracer.Start(ctx, "LabelManager.Labels")
defer span.End()
labelSet, ok := m.getIfCached(pid)
if ok {
if labelSet == nil {
return nil, nil
}
return labelSetToLabels(labelSet), nil
}
labelSet, err := m.labelSet(ctx, pid)
if err != nil {
return nil, err
}
lbls, keep := labelSetToLabels(labelSet), true
if len(m.relabelConfigs) > 0 {
lbls, keep = m.processRelabel(lbls)
}
// This path is only used by the UI for troubleshooting,
// it is not necessary to cache these labels at the moment
if !keep {
return nil, nil
}
return lbls, nil
}
// Fetch fetches process specific labels to the profile.
// This method is intended to be used by process info manager to fetch certain labels as early as possible.
// It bypasses relabeling and top-level caching.
func (m *Manager) Fetch(ctx context.Context, pid int) error {
_, err := m.labelSet(ctx, pid)
return err
}
// LabelSet returns a model.LabelSet with relabel configs applied.
func (m *Manager) LabelSet(ctx context.Context, pid int) (model.LabelSet, error) {
labelSet, ok := m.getIfCached(pid)
if ok {
return labelSet, nil
}
labelSet, err := m.labelSet(ctx, pid)
if err != nil {
return nil, err
}
if len(m.relabelConfigs) > 0 {
lbls, keep := m.processRelabel(labelSetToLabels(labelSet))
if !keep {
m.labelCache.Add(labelCacheKey(pid), model.LabelSet{})
return nil, nil
}
labelSet = labelsToLabelSet(lbls)
}
m.labelCache.Add(labelCacheKey(pid), labelSet)
return labelSet, nil
}
func (m *Manager) processRelabel(lbls labels.Labels) (labels.Labels, bool) {
m.mtx.RLock()
defer m.mtx.RUnlock()
return relabel.Process(lbls, m.relabelConfigs...)
}
func labelCacheKey(pid int) string {
return strconv.Itoa(pid)
}
func providerCacheKey(provider string, pid int) string {
return fmt.Sprintf("%s:%d", provider, pid)
}
// getIfCached retrieved a labelSet if it has been cached.
func (m *Manager) getIfCached(pid int) (model.LabelSet, bool) {
if labelSet, ok := m.labelCache.Get(labelCacheKey(pid)); ok {
return labelSet, true
}
return nil, false
}
// labelSetToLabels converts a model.LabelSet to labels.Labels.
func labelSetToLabels(labelSet model.LabelSet) labels.Labels {
b := labels.NewScratchBuilder(len(labelSet))
for name, value := range labelSet {
b.Add(string(name), string(value))
}
return b.Labels()
}
// labelsToLabelSet converts a labels.Labels to model.LabelSet.
func labelsToLabelSet(lbls labels.Labels) model.LabelSet {
labelSet := make(model.LabelSet, len(lbls))
for _, l := range lbls {
labelSet[model.LabelName(l.Name)] = model.LabelValue(l.Value)
}
return labelSet
}