forked from linkerd/linkerd2
/
server.go
470 lines (406 loc) · 12.9 KB
/
server.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
package telemetry
import (
"errors"
"fmt"
"net"
"net/http"
"strconv"
"time"
"github.com/golang/protobuf/ptypes/duration"
"github.com/prometheus/client_golang/api"
"github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
common "github.com/runconduit/conduit/controller/gen/common"
read "github.com/runconduit/conduit/controller/gen/controller/telemetry"
write "github.com/runconduit/conduit/controller/gen/proxy/telemetry"
public "github.com/runconduit/conduit/controller/gen/public"
"github.com/runconduit/conduit/controller/k8s"
"github.com/runconduit/conduit/controller/util"
pkgK8s "github.com/runconduit/conduit/pkg/k8s"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
k8sV1 "k8s.io/api/core/v1"
)
const (
reportsMetric = "reports_total"
)
var (
requestLabels = []string{"source_deployment", "target_deployment"}
requestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "requests_total",
Help: "Total number of requests",
},
requestLabels,
)
responseLabels = append(requestLabels, []string{"http_status_code", "classification"}...)
responsesTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "responses_total",
Help: "Total number of responses",
},
responseLabels,
)
responseLatencyBuckets = append(append(append(append(append(
prometheus.LinearBuckets(1, 1, 5),
prometheus.LinearBuckets(10, 10, 5)...),
prometheus.LinearBuckets(100, 100, 5)...),
prometheus.LinearBuckets(1000, 1000, 5)...),
prometheus.LinearBuckets(10000, 10000, 5)...),
)
responseLatency = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "response_latency_ms",
Help: "Response latency in milliseconds",
Buckets: responseLatencyBuckets,
},
requestLabels,
)
reportsLabels = []string{"pod"}
reportsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: reportsMetric,
Help: "Total number of telemetry reports received",
},
reportsLabels,
)
)
func init() {
prometheus.MustRegister(requestsTotal)
prometheus.MustRegister(responsesTotal)
prometheus.MustRegister(responseLatency)
prometheus.MustRegister(reportsTotal)
}
type (
server struct {
prometheusAPI v1.API
pods *k8s.PodIndex
replicaSets *k8s.ReplicaSetStore
ignoredNamespaces []string
}
)
func podIPKeyFunc(obj interface{}) ([]string, error) {
if pod, ok := obj.(*k8sV1.Pod); ok {
return []string{pod.Status.PodIP}, nil
}
return nil, fmt.Errorf("Object is not a Pod")
}
func NewServer(addr, prometheusUrl string, ignoredNamespaces []string, kubeconfig string) (*grpc.Server, net.Listener, error) {
prometheusClient, err := api.NewClient(api.Config{Address: prometheusUrl})
if err != nil {
return nil, nil, err
}
clientSet, err := k8s.NewClientSet(kubeconfig)
if err != nil {
return nil, nil, err
}
pods, err := k8s.NewPodIndex(clientSet, podIPKeyFunc)
if err != nil {
return nil, nil, err
}
err = pods.Run()
if err != nil {
return nil, nil, err
}
replicaSets, err := k8s.NewReplicaSetStore(clientSet)
if err != nil {
return nil, nil, err
}
err = replicaSets.Run()
if err != nil {
return nil, nil, err
}
srv := &server{
prometheusAPI: v1.NewAPI(prometheusClient),
pods: pods,
replicaSets: replicaSets,
ignoredNamespaces: ignoredNamespaces,
}
lis, err := net.Listen("tcp", addr)
if err != nil {
return nil, nil, err
}
s := util.NewGrpcServer()
read.RegisterTelemetryServer(s, srv)
write.RegisterTelemetryServer(s, srv)
// TODO: register shutdown hook to call pods.Stop() and replicatSets.Stop()
return s, lis, nil
}
func (s *server) Query(ctx context.Context, req *read.QueryRequest) (*read.QueryResponse, error) {
log.Debugf("Query request: %+v", req)
samples := make([]*read.Sample, 0)
if req.EndMs == 0 {
err := fmt.Errorf("EndMs timestamp missing from request: %+v", req)
log.Errorf("%s", err)
return nil, err
}
end := time.Unix(0, req.EndMs*int64(time.Millisecond))
if req.StartMs != 0 && req.EndMs != 0 && req.Step != "" {
// timeseries query
start := time.Unix(0, req.StartMs*int64(time.Millisecond))
step, err := time.ParseDuration(req.Step)
if err != nil {
log.Errorf("ParseDuration(%+v) failed with: %+v", req.Step, err)
return nil, err
}
queryRange := v1.Range{
Start: start,
End: end,
Step: step,
}
res, err := s.prometheusAPI.QueryRange(ctx, req.Query, queryRange)
if err != nil {
log.Errorf("QueryRange(%+v, %+v) failed with: %+v", req.Query, queryRange, err)
return nil, err
}
log.Debugf("Query response: %+v", res)
if res.Type() != model.ValMatrix {
err = fmt.Errorf("Unexpected query result type (expected Matrix): %s", res.Type())
log.Error(err)
return nil, err
}
for _, s := range res.(model.Matrix) {
samples = append(samples, convertSampleStream(s))
}
} else {
// single data point (aka summary) query
res, err := s.prometheusAPI.Query(ctx, req.Query, end)
if err != nil {
log.Errorf("Query(%+v, %+v) failed with: %+v", req.Query, end, err)
return nil, err
}
log.Debugf("Query response: %+v", res)
if res.Type() != model.ValVector {
err = fmt.Errorf("Unexpected query result type (expected Vector): %s", res.Type())
log.Error(err)
return nil, err
}
for _, s := range res.(model.Vector) {
samples = append(samples, convertSample(s))
}
}
return &read.QueryResponse{Metrics: samples}, nil
}
func (s *server) ListPods(ctx context.Context, req *read.ListPodsRequest) (*public.ListPodsResponse, error) {
log.Debugf("ListPods request: %+v", req)
pods, err := s.pods.List()
if err != nil {
return nil, err
}
// Reports is a map from instance name to the absolute time of the most recent
// report from that instance.
reports := make(map[string]time.Time)
// Query Prometheus for reports in the last 30 seconds.
res, err := s.prometheusAPI.Query(ctx, reportsMetric + "[30s]", time.Time{})
if err != nil {
return nil, err
}
if res.Type() != model.ValMatrix {
err = fmt.Errorf("Unexpected query result type (expected Matrix): %s", res.Type())
log.Error(err)
return nil, err
}
for _, s := range res.(model.Matrix) {
labels := metricToMap(s.Metric)
timestamp := s.Values[len(s.Values)-1].Timestamp
reports[labels["pod"]] = time.Unix(0, int64(timestamp)*int64(time.Millisecond))
}
podList := make([]*public.Pod, 0)
for _, pod := range pods {
if s.shouldIngore(pod) {
continue
}
deployment, err := s.replicaSets.GetDeploymentForPod(pod)
if err != nil {
log.Debugf("Cannot get deployment for pod %s: %s", pod.Name, err)
deployment = ""
}
name := pod.Namespace + "/" + pod.Name
updated, added := reports[name]
status := string(pod.Status.Phase)
if pod.DeletionTimestamp != nil {
status = "Terminating"
}
controllerComponent := pod.Labels[pkgK8s.ControllerComponentLabel]
controllerNS := pod.Labels[pkgK8s.ControllerNSLabel]
item := &public.Pod{
Name: pod.Namespace + "/" + pod.Name,
Deployment: deployment,
Status: status,
PodIP: pod.Status.PodIP,
Added: added,
ControllerNamespace: controllerNS,
ControlPlane: controllerComponent != "",
}
if added {
since := time.Since(updated)
item.SinceLastReport = &duration.Duration{
Seconds: int64(since / time.Second),
Nanos: int32(since % time.Second),
}
}
podList = append(podList, item)
}
return &public.ListPodsResponse{Pods: podList}, nil
}
func (s *server) Report(ctx context.Context, req *write.ReportRequest) (*write.ReportResponse, error) {
log.Debugf("Report request: %+v", req)
id := "unknown"
if req.Process != nil {
id = req.Process.ScheduledNamespace + "/" + req.Process.ScheduledInstance
}
logCtx := log.WithFields(log.Fields{"id": id})
logCtx.Debugf("Received report with %d requests", len(req.Requests))
reportsTotal.With(prometheus.Labels{"pod": id}).Inc()
for _, requestScope := range req.Requests {
if requestScope.Ctx == nil {
return nil, errors.New("RequestCtx is required")
}
requestLabels := s.requestLabelsFor(requestScope)
requestsTotal.With(requestLabels).Add(float64(requestScope.Count))
latencyStat := responseLatency.With(requestLabels)
for _, responseScope := range requestScope.Responses {
if responseScope.Ctx == nil {
return nil, errors.New("ResponseCtx is required")
}
// Validate this ResponseScope's latency histogram.
numBuckets := len(responseScope.ResponseLatencyCounts)
expectedNumBuckets := len(req.HistogramBucketBoundsTenthMs)
if numBuckets != expectedNumBuckets {
err := errors.New(
"received report with incorrect number of latency buckets")
logCtx.WithFields(log.Fields{
"numBuckets": numBuckets,
"expected": expectedNumBuckets,
"scope": responseScope,
}).WithError(err).Error()
return nil, err
}
for bucketNum, count := range responseScope.ResponseLatencyCounts {
// Look up the bucket max value corresponding to this position
// in the report's latency histogram.
latencyTenthsMs := req.HistogramBucketBoundsTenthMs[bucketNum]
latencyMs := float64(latencyTenthsMs) / 10
for i := uint32(0); i < count; i++ {
// Then, report that latency value to Prometheus a number
// of times equal to the count reported by the proxy.
latencyStat.Observe(latencyMs)
}
}
for _, eosScope := range responseScope.Ends {
if eosScope.Ctx == nil {
return nil, errors.New("EosCtx is required")
}
responseLabels := s.requestLabelsFor(requestScope)
for k, v := range responseLabelsFor(responseScope, eosScope) {
responseLabels[k] = v
}
responsesTotal.With(responseLabels).Add(float64(eosScope.Streams))
}
}
}
return &write.ReportResponse{}, nil
}
func (s *server) shouldIngore(pod *k8sV1.Pod) bool {
for _, namespace := range s.ignoredNamespaces {
if pod.Namespace == namespace {
return true
}
}
return false
}
// getDeployment returns the name of the deployment associated with a pod.
// If the name of the deployment could not be found, then a message will be
// logged, and getDeployment will return an emtpy string.
func (s *server) getDeployment(ip *common.IPAddress) string {
ipStr := util.IPToString(ip)
pods, err := s.pods.GetPodsByIndex(ipStr)
if err != nil {
log.Debugf("Cannot get pod for IP %s: %s", ipStr, err)
return ""
}
if len(pods) == 0 {
log.Debugf("No pod exists for IP %s", ipStr)
return ""
}
if len(pods) > 1 {
log.Debugf("Multiple pods found for IP %s", ipStr)
return ""
}
pod := pods[0]
deployment, err := (*s.replicaSets).GetDeploymentForPod(pod)
if err != nil {
log.WithError(err).Debugf("Cannot get deployment for pod %s", pod.Name)
return ""
}
return deployment
}
func methodString(method *common.HttpMethod) string {
switch method.Type.(type) {
case *common.HttpMethod_Registered_:
return method.GetRegistered().String()
case *common.HttpMethod_Unregistered:
return method.GetUnregistered()
}
return ""
}
func metricToMap(metric model.Metric) map[string]string {
labels := make(map[string]string)
for k, v := range metric {
labels[string(k)] = string(v)
}
return labels
}
func convertSampleStream(sample *model.SampleStream) *read.Sample {
values := make([]*read.SampleValue, 0)
for _, s := range sample.Values {
v := read.SampleValue{
Value: float64(s.Value),
TimestampMs: int64(s.Timestamp),
}
values = append(values, &v)
}
return &read.Sample{Values: values, Labels: metricToMap(sample.Metric)}
}
func convertSample(sample *model.Sample) *read.Sample {
values := []*read.SampleValue{
&read.SampleValue{
Value: float64(sample.Value),
TimestampMs: int64(sample.Timestamp),
},
}
return &read.Sample{Values: values, Labels: metricToMap(sample.Metric)}
}
func (s *server) requestLabelsFor(requestScope *write.RequestScope) prometheus.Labels {
sourceDeployment := s.getDeployment(requestScope.Ctx.SourceIp)
targetDeployment := s.getDeployment(requestScope.Ctx.TargetAddr.Ip)
return prometheus.Labels{
"source_deployment": sourceDeployment,
"target_deployment": targetDeployment,
}
}
func responseLabelsFor(responseScope *write.ResponseScope, eosScope *write.EosScope) prometheus.Labels {
httpStatusCode := strconv.Itoa(int(responseScope.Ctx.HttpStatusCode))
classification := "failure"
switch x := eosScope.Ctx.End.(type) {
case *write.EosCtx_GrpcStatusCode:
// The stream ended with a `grpc-status` trailer.
// Classify based on the gRPC status code.
if x.GrpcStatusCode == uint32(codes.OK) {
classification = "success"
}
case *write.EosCtx_Other:
// The stream did not end with a `grpc-status` trailer (i.e., it was
// not a gRPC message). Classify based on the response's HTTP status.
if responseScope.Ctx.HttpStatusCode < http.StatusInternalServerError {
classification = "success"
}
}
return prometheus.Labels{
"http_status_code": httpStatusCode,
"classification": classification,
}
}