-
Notifications
You must be signed in to change notification settings - Fork 419
/
metrics.go
182 lines (155 loc) · 4.59 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
package sink
import (
"context"
"encoding/json"
"log"
"net/http"
"time"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"knative.dev/pkg/metrics"
)
var (
elDuration = stats.Float64(
"http_duration_seconds",
"The eventlistener HTTP request duration",
stats.UnitDimensionless)
elDistribution = view.Distribution(metrics.BucketsNBy10(0.001, 5)...)
eventCount = stats.Float64("event_count",
"number of events received by sink",
stats.UnitDimensionless)
triggeredResources = stats.Int64("triggered_resources", "Count of the number of triggered eventlistener resources", stats.UnitDimensionless)
)
const (
failTag = "failed"
successTag = "succeeded"
)
// NewRecorder creates a new metrics recorder instance
// to log the TaskRun related metrics
func NewRecorder() (*Recorder, error) {
r := &Recorder{
initialized: true,
// Default to reporting metrics every 30s.
ReportingPeriod: 30 * time.Second,
}
status, err := tag.NewKey("status")
if err != nil {
return nil, err
}
r.status = status
kind, err := tag.NewKey("kind")
if err != nil {
return nil, err
}
r.kind = kind
err = view.Register(
&view.View{
Description: elDuration.Description(),
Measure: elDuration,
Aggregation: elDistribution,
},
&view.View{
Description: triggeredResources.Description(),
Measure: triggeredResources,
Aggregation: view.Count(),
TagKeys: []tag.Key{r.kind},
},
&view.View{
Description: eventCount.Description(),
Measure: eventCount,
Aggregation: view.Count(),
TagKeys: []tag.Key{r.status},
},
)
if err != nil {
log.Fatalf("unable to register eventlistener metrics: %s", err)
}
return r, nil
}
func (s *Sink) NewMetricsRecorderInterceptor() MetricsInterceptor {
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
recorder := &StatusRecorder{
ResponseWriter: w,
Status: 200,
}
startTime := time.Now()
defer func() {
endTime := time.Now()
elapsed := endTime.Sub(startTime)
// Log the consumed time
go s.recordDurationMetrics(recorder, elapsed)
}()
next(recorder, r)
}
}
func (s *Sink) recordDurationMetrics(w *StatusRecorder, elapsed time.Duration) {
duration := elapsed.Seconds()
s.Logger.Debugw("event listener request completed", "status", w.Status, "duration", duration)
ctx, err := tag.New(
context.Background(),
)
if err != nil {
s.Logger.Warnf("failed to create tag for http metric request: %w", err)
return
}
metrics.Record(ctx, elDuration.M(duration))
}
func (s *Sink) recordCountMetrics(status string) {
s.Logger.Debugw("event listener request", "status", status)
ctx, err := tag.New(
context.Background(),
tag.Insert(s.Recorder.status, status),
)
if err != nil {
s.Logger.Warnf("failed to create tag for metric event_count: %w", err)
return
}
metrics.Record(ctx, eventCount.M(1))
}
func (s *Sink) recordResourceCreation(resources []json.RawMessage) {
for _, rt := range resources {
// Assume the TriggerResourceTemplate is valid (it has an apiVersion and Kind)
data := new(unstructured.Unstructured)
if err := data.UnmarshalJSON(rt); err != nil {
s.Logger.Warnf("couldn't unmarshal json from the TriggerTemplate: %v", err)
continue
}
ctx, err := tag.New(context.Background(), tag.Insert(s.Recorder.kind, data.GetKind()))
if err != nil {
s.Logger.Warnf("failed to create tag for resource creation: %w", err)
continue
}
metrics.Record(ctx, triggeredResources.M(1))
}
}
type Recorder struct {
initialized bool
status tag.Key
kind tag.Key
ReportingPeriod time.Duration
}
type StatusRecorder struct {
http.ResponseWriter
Status int
}
func (r *StatusRecorder) WriteHeader(status int) {
r.Status = status
r.ResponseWriter.WriteHeader(status)
}
// MetricsInterceptor intercepts an HTTP handler invocation, it is passed both response writer and request
// which after interception can be passed onto the handler function.
type MetricsInterceptor func(http.ResponseWriter, *http.Request, http.HandlerFunc)
// MetricsHandlerFunc builds on top of http.Handler, and exposes API to intercept with MetricsInterceptor.
// This allows building complex long chains without complicated struct manipulation
type MetricsHandler struct {
Handler http.Handler
}
// Intercept returns back a continuation that will call the handler func to intercept
// the continuation call.
func (cont *MetricsHandler) Intercept(mw MetricsInterceptor) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
mw(writer, request, cont.Handler.ServeHTTP)
}
}