-
Notifications
You must be signed in to change notification settings - Fork 415
/
prometheus_recorder.go
290 lines (263 loc) · 6.5 KB
/
prometheus_recorder.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*
* Copyright 2018- The Pixie 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package metrics
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"sync"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/gogo/protobuf/types"
io_prometheus_client "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/transport/spdy"
"px.dev/pixie/src/e2e_test/perf_tool/experimentpb"
"px.dev/pixie/src/e2e_test/perf_tool/pkg/cluster"
)
type prometheusRecorderImpl struct {
clusterCtx *cluster.Context
spec *experimentpb.PrometheusScrapeSpec
eg *errgroup.Group
resultCh chan<- *ResultRow
wg sync.WaitGroup
stopCh chan struct{}
fws []*forwarder
}
func (r *prometheusRecorderImpl) Start(ctx context.Context) error {
if err := r.startPortForward(ctx); err != nil {
return err
}
r.stopCh = make(chan struct{})
r.wg.Add(1)
r.eg.Go(func() error {
defer r.wg.Done()
err := r.run()
if err != nil {
err = fmt.Errorf("error recording prometheus metrics: %w", err)
}
return err
})
return nil
}
func (r *prometheusRecorderImpl) Close() {
if r.stopCh != nil {
close(r.stopCh)
r.wg.Wait()
r.stopCh = nil
}
for _, fw := range r.fws {
fw.Close()
}
}
func (r *prometheusRecorderImpl) run() error {
d, err := types.DurationFromProto(r.spec.ScrapePeriod)
if err != nil {
return err
}
t := time.NewTicker(d)
defer t.Stop()
for {
select {
case <-r.stopCh:
return nil
case <-t.C:
if err := r.scrape(); err != nil {
return err
}
}
}
}
func (r *prometheusRecorderImpl) scrape() error {
eg := errgroup.Group{}
for _, fw := range r.fws {
eg.Go(r.scrapeFunc(fw))
}
return eg.Wait()
}
func (r *prometheusRecorderImpl) scrapeFunc(fw *forwarder) func() error {
op := func() error {
resp, err := http.Get(fmt.Sprintf("http://localhost:%d/metrics", fw.localPort))
if err != nil {
return err
}
ts := time.Now()
metrics, err := (&expfmt.TextParser{}).TextToMetricFamilies(resp.Body)
if err != nil {
return backoff.Permanent(err)
}
for _, mf := range metrics {
name, ok := r.spec.MetricNames[mf.GetName()]
if !ok {
// Only collect metrics named in the spec.
continue
}
// Only collect counters and gauges for now.
if !(mf.GetType() == io_prometheus_client.MetricType_COUNTER || mf.GetType() == io_prometheus_client.MetricType_GAUGE) {
continue
}
for _, m := range mf.GetMetric() {
row := newResultRow()
row.Name = name
row.Timestamp = ts
for _, lp := range m.GetLabel() {
row.Tags[lp.GetName()] = lp.GetValue()
}
row.Tags["pod"] = fw.podName
switch mf.GetType() {
case io_prometheus_client.MetricType_COUNTER:
row.Value = m.GetCounter().GetValue()
case io_prometheus_client.MetricType_GAUGE:
row.Value = m.GetGauge().GetValue()
}
r.resultCh <- row
}
}
return nil
}
bo := backoff.NewExponentialBackOff()
bo.MaxElapsedTime = 20 * time.Second
return func() error { return backoff.Retry(op, bo) }
}
func (r *prometheusRecorderImpl) startPortForward(ctx context.Context) error {
pl, err := r.clusterCtx.Clientset().CoreV1().Pods(r.spec.Namespace).List(ctx, metav1.ListOptions{
LabelSelector: metav1.FormatLabelSelector(&metav1.LabelSelector{
MatchLabels: map[string]string{
r.spec.MatchLabelKey: r.spec.MatchLabelValue,
},
}),
})
if err != nil {
return err
}
fws := make(chan *forwarder, len(pl.Items))
eg := errgroup.Group{}
for _, pod := range pl.Items {
name := pod.Name
eg.Go(func() error {
fw, err := newForwarder(ctx, r.clusterCtx, r.spec.Namespace, name, uint16(r.spec.Port))
if err != nil {
return err
}
if err := fw.Start(); err != nil {
return err
}
fws <- fw
return nil
})
}
if err := eg.Wait(); err != nil {
log.WithError(err).Error("error starting port forwarders for prometheus scraping")
close(fws)
for fw := range fws {
fw.Close()
}
return err
}
close(fws)
r.fws = make([]*forwarder, 0)
for fw := range fws {
r.fws = append(r.fws, fw)
}
return nil
}
type forwarder struct {
localPort uint16
pf *portforward.PortForwarder
stopCh chan struct{}
readyCh chan struct{}
errCh chan error
podName string
wg sync.WaitGroup
}
func newForwarder(ctx context.Context, clusterCtx *cluster.Context, ns string, pod string, remotePort uint16) (*forwarder, error) {
p, err := clusterCtx.Clientset().CoreV1().Pods(ns).Get(ctx, pod, metav1.GetOptions{})
if err != nil {
return nil, err
}
req := clusterCtx.Clientset().CoreV1().RESTClient().
Post().
Resource("pods").
Namespace(ns).
Name(p.Name).
SubResource("portforward")
transport, upgrader, err := spdy.RoundTripperFor(clusterCtx.RestConfig())
if err != nil {
return nil, err
}
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, "POST", req.URL())
fw := &forwarder{
podName: pod,
stopCh: make(chan struct{}),
errCh: make(chan error),
readyCh: make(chan struct{}),
}
ports := []string{fmt.Sprintf("0:%d", remotePort)}
pf, err := portforward.New(dialer, ports, fw.stopCh, fw.readyCh, io.Discard, os.Stderr)
if err != nil {
return nil, err
}
fw.pf = pf
return fw, nil
}
func (fw *forwarder) Start() error {
fw.wg.Add(1)
go fw.run()
select {
case err := <-fw.errCh:
return err
case <-fw.readyCh:
}
fwPorts, err := fw.pf.GetPorts()
if err != nil {
fw.pf.Close()
close(fw.stopCh)
return err
}
if len(fwPorts) != 1 {
fw.pf.Close()
close(fw.stopCh)
return errors.New("couldn't get local port from port forwarder")
}
fw.localPort = fwPorts[0].Local
return nil
}
func (fw *forwarder) run() {
defer fw.wg.Done()
err := fw.pf.ForwardPorts()
if err != nil {
fw.errCh <- err
}
close(fw.errCh)
}
func (fw *forwarder) Close() {
if fw.stopCh == nil {
return
}
fw.pf.Close()
close(fw.stopCh)
defer func() { fw.stopCh = nil }()
fw.wg.Wait()
}