-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathmetrics.go
311 lines (261 loc) · 8.43 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
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
/*
Copyright 2019 The Tekton 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 pipelinerunmetrics
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/tektoncd/pipeline/pkg/apis/config"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
listers "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/labels"
"knative.dev/pkg/apis"
"knative.dev/pkg/logging"
"knative.dev/pkg/metrics"
)
var (
pipelinerunTag = tag.MustNewKey("pipelinerun")
pipelineTag = tag.MustNewKey("pipeline")
namespaceTag = tag.MustNewKey("namespace")
statusTag = tag.MustNewKey("status")
prDuration = stats.Float64(
"pipelinerun_duration_seconds",
"The pipelinerun execution time in seconds",
stats.UnitDimensionless)
prDurationView *view.View
prCount = stats.Float64("pipelinerun_count",
"number of pipelineruns",
stats.UnitDimensionless)
prCountView *view.View
runningPRsCount = stats.Float64("running_pipelineruns_count",
"Number of pipelineruns executing currently",
stats.UnitDimensionless)
runningPRsCountView *view.View
)
const (
// ReasonCancelled indicates that a PipelineRun was cancelled.
ReasonCancelled = "Cancelled"
// ReasonCancelledDeprecated Deprecated: "PipelineRunCancelled" indicates that a PipelineRun was cancelled.
ReasonCancelledDeprecated = "PipelineRunCancelled"
)
// Recorder holds keys for Tekton metrics
type Recorder struct {
mutex sync.Mutex
initialized bool
insertTag func(pipeline,
pipelinerun string) []tag.Mutator
ReportingPeriod time.Duration
}
// We cannot register the view multiple times, so NewRecorder lazily
// initializes this singleton and returns the same recorder across any
// subsequent invocations.
var (
once sync.Once
r *Recorder
recorderErr error
)
// NewRecorder creates a new metrics recorder instance
// to log the PipelineRun related metrics
func NewRecorder(ctx context.Context) (*Recorder, error) {
once.Do(func() {
r = &Recorder{
initialized: true,
// Default to 30s intervals.
ReportingPeriod: 30 * time.Second,
}
cfg := config.FromContextOrDefaults(ctx)
recorderErr = viewRegister(cfg.Metrics)
if recorderErr != nil {
r.initialized = false
return
}
})
return r, recorderErr
}
func viewRegister(cfg *config.Metrics) error {
r.mutex.Lock()
defer r.mutex.Unlock()
prunTag := []tag.Key{}
switch cfg.PipelinerunLevel {
case config.PipelinerunLevelAtPipelinerun:
prunTag = []tag.Key{pipelinerunTag, pipelineTag}
r.insertTag = pipelinerunInsertTag
case config.PipelinerunLevelAtPipeline:
prunTag = []tag.Key{pipelineTag}
r.insertTag = pipelineInsertTag
case config.PipelinerunLevelAtNS:
prunTag = []tag.Key{}
r.insertTag = nilInsertTag
default:
return errors.New("invalid config for PipelinerunLevel: " + cfg.PipelinerunLevel)
}
distribution := view.Distribution(10, 30, 60, 300, 900, 1800, 3600, 5400, 10800, 21600, 43200, 86400)
if cfg.PipelinerunLevel == config.PipelinerunLevelAtPipelinerun {
distribution = view.LastValue()
} else {
switch cfg.DurationPipelinerunType {
case config.DurationTaskrunTypeHistogram:
case config.DurationTaskrunTypeLastValue:
distribution = view.LastValue()
default:
return errors.New("invalid config for DurationTaskrunType: " + cfg.DurationTaskrunType)
}
}
prDurationView = &view.View{
Description: prDuration.Description(),
Measure: prDuration,
Aggregation: distribution,
TagKeys: append([]tag.Key{statusTag, namespaceTag}, prunTag...),
}
prCountView = &view.View{
Description: prCount.Description(),
Measure: prCount,
Aggregation: view.Count(),
TagKeys: []tag.Key{statusTag},
}
runningPRsCountView = &view.View{
Description: runningPRsCount.Description(),
Measure: runningPRsCount,
Aggregation: view.LastValue(),
}
return view.Register(
prDurationView,
prCountView,
runningPRsCountView,
)
}
func viewUnregister() {
view.Unregister(prDurationView, prCountView, runningPRsCountView)
}
// MetricsOnStore returns a function that checks if metrics are configured for a config.Store, and registers it if so
func MetricsOnStore(logger *zap.SugaredLogger) func(name string,
value interface{}) {
return func(name string, value interface{}) {
if name == config.GetMetricsConfigName() {
cfg, ok := value.(*config.Metrics)
if !ok {
logger.Error("Failed to do type insertion for extracting metrics config")
return
}
viewUnregister()
err := viewRegister(cfg)
if err != nil {
logger.Errorf("Failed to register View %v ", err)
return
}
}
}
}
func pipelinerunInsertTag(pipeline, pipelinerun string) []tag.Mutator {
return []tag.Mutator{tag.Insert(pipelineTag, pipeline),
tag.Insert(pipelinerunTag, pipelinerun)}
}
func pipelineInsertTag(pipeline, pipelinerun string) []tag.Mutator {
return []tag.Mutator{tag.Insert(pipelineTag, pipeline)}
}
func nilInsertTag(task, taskrun string) []tag.Mutator {
return []tag.Mutator{}
}
// DurationAndCount logs the duration of PipelineRun execution and
// count for number of PipelineRuns succeed or failed
// returns an error if its failed to log the metrics
func (r *Recorder) DurationAndCount(pr *v1beta1.PipelineRun, beforeCondition *apis.Condition) error {
if !r.initialized {
return fmt.Errorf("ignoring the metrics recording for %s , failed to initialize the metrics recorder", pr.Name)
}
afterCondition := pr.Status.GetCondition(apis.ConditionSucceeded)
// To avoid recount
if equality.Semantic.DeepEqual(beforeCondition, afterCondition) {
return nil
}
r.mutex.Lock()
defer r.mutex.Unlock()
duration := time.Duration(0)
if pr.Status.StartTime != nil {
duration = time.Since(pr.Status.StartTime.Time)
if pr.Status.CompletionTime != nil {
duration = pr.Status.CompletionTime.Sub(pr.Status.StartTime.Time)
}
}
status := "success"
if cond := pr.Status.GetCondition(apis.ConditionSucceeded); cond.Status == corev1.ConditionFalse {
status = "failed"
if cond.Reason == ReasonCancelled || cond.Reason == ReasonCancelledDeprecated {
status = "cancelled"
}
}
pipelineName := "anonymous"
if pr.Spec.PipelineRef != nil && pr.Spec.PipelineRef.Name != "" {
pipelineName = pr.Spec.PipelineRef.Name
}
ctx, err := tag.New(
context.Background(),
append([]tag.Mutator{tag.Insert(namespaceTag, pr.Namespace),
tag.Insert(statusTag, status)}, r.insertTag(pipelineName, pr.Name)...)...)
if err != nil {
return err
}
metrics.Record(ctx, prDuration.M(float64(duration/time.Second)))
metrics.Record(ctx, prCount.M(1))
return nil
}
// RunningPipelineRuns logs the number of PipelineRuns running right now
// returns an error if its failed to log the metrics
func (r *Recorder) RunningPipelineRuns(lister listers.PipelineRunLister) error {
r.mutex.Lock()
r.mutex.Unlock()
if !r.initialized {
return errors.New("ignoring the metrics recording, failed to initialize the metrics recorder")
}
prs, err := lister.List(labels.Everything())
if err != nil {
return fmt.Errorf("failed to list pipelineruns while generating metrics : %v", err)
}
var runningPRs int
for _, pr := range prs {
if !pr.IsDone() {
runningPRs++
}
}
ctx, err := tag.New(context.Background())
if err != nil {
return err
}
metrics.Record(ctx, runningPRsCount.M(float64(runningPRs)))
return nil
}
// ReportRunningPipelineRuns invokes RunningPipelineRuns on our configured PeriodSeconds
// until the context is cancelled.
func (r *Recorder) ReportRunningPipelineRuns(ctx context.Context, lister listers.PipelineRunLister) {
logger := logging.FromContext(ctx)
for {
select {
case <-ctx.Done():
// When the context is cancelled, stop reporting.
return
case <-time.After(r.ReportingPeriod):
// Every 30s surface a metric for the number of running pipelines.
if err := r.RunningPipelineRuns(lister); err != nil {
logger.Warnf("Failed to log the metrics : %v", err)
}
}
}
}