-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathoutput.go
More file actions
253 lines (213 loc) · 6.26 KB
/
output.go
File metadata and controls
253 lines (213 loc) · 6.26 KB
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
// Package opentelemetry performs output operations for the opentelemetry extension
package opentelemetry
import (
"context"
"fmt"
"time"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel/attribute"
otelMetric "go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
"go.k6.io/k6/metrics"
"go.k6.io/k6/output"
)
// Output implements the lib.Output interface
type Output struct {
output.SampleBuffer
config Config
periodicFlusher *output.PeriodicFlusher
logger logrus.FieldLogger
meterProvider *metric.MeterProvider
metricsRegistry *registry
}
var _ output.WithStopWithTestError = new(Output)
// New creates an instance of the collector
func New(p output.Params) (*Output, error) {
conf, err := GetConsolidatedConfig(p.JSONConfig, p.Environment, p.Logger)
if err != nil {
return nil, err
}
if conf.ExporterType.Valid {
p.Logger.Warn("Exporter type is deprecated, please migrate to exporter protocol")
}
return &Output{
config: conf,
logger: p.Logger,
}, nil
}
// Description returns a human-readable description of the output that will be shown in `k6 run`
func (o *Output) Description() string {
return fmt.Sprintf("opentelemetry (%s)", o.config)
}
// StopWithTestError flushes all remaining metrics and finalizes the test run
func (o *Output) StopWithTestError(_ error) error {
o.logger.Debug("Stopping...")
defer o.logger.Debug("Stopped!")
o.periodicFlusher.Stop()
if err := o.meterProvider.Shutdown(context.Background()); err != nil {
o.logger.WithError(err).Error("can't shutdown OpenTelemetry metric provider")
}
return nil
}
// Stop just implements an old interface (output.Output)
func (o *Output) Stop() error {
return o.StopWithTestError(nil)
}
// Start performs initialization tasks prior to Engine using the output
func (o *Output) Start() error {
o.logger.Debug("Starting output...")
if !o.config.SingleCounterForRate.Bool {
o.logger.Warn("Exporting rate metrics as a pair of counters is deprecated" +
" and will be removed in future releases. Please migrate to the new format.")
}
exp, err := getExporter(o.config)
if err != nil {
return fmt.Errorf("failed to create OpenTelemetry exporter: %w", err)
}
res, err := resource.Merge(resource.Default(),
resource.NewSchemaless(
semconv.ServiceName(o.config.ServiceName.String),
semconv.ServiceVersion(o.config.ServiceVersion.String),
))
if err != nil {
return fmt.Errorf("failed to create OpenTelemetry resource: %w", err)
}
meterProvider := metric.NewMeterProvider(
metric.WithResource(res),
metric.WithReader(
metric.NewPeriodicReader(
exp,
metric.WithInterval(o.config.ExportInterval.TimeDuration()),
),
),
)
pf, err := output.NewPeriodicFlusher(o.config.FlushInterval.TimeDuration(), o.flushMetrics)
if err != nil {
return err
}
o.logger.Debug("Started!")
o.periodicFlusher = pf
o.meterProvider = meterProvider
o.metricsRegistry = newRegistry(meterProvider.Meter("k6"), o.logger)
return nil
}
func (o *Output) flushMetrics() {
samples := o.GetBufferedSamples()
start := time.Now()
var count, errCount int
for _, sc := range samples {
samples := sc.GetSamples()
for _, sample := range samples {
if err := o.dispatch(sample); err != nil {
o.logger.WithError(err).Error("Error dispatching sample")
errCount++
continue
}
count++
}
}
if count > 0 {
o.logger.
WithField("t", time.Since(start)).
WithField("count", count).
Debug("registered metrics in OpenTelemetry metric provider")
}
if errCount > 0 {
o.logger.
WithField("t", time.Since(start)).
WithField("count", errCount).
Warn("can't flush some metrics")
}
}
func (o *Output) dispatch(entry metrics.Sample) error {
ctx := context.Background()
name := normalizeMetricName(o.config, entry.Metric.Name)
attributeSet := newAttributeSet(entry.Tags)
attributeSetOpt := otelMetric.WithAttributeSet(attributeSet)
unit := normalizeUnit(entry.Metric.Contains)
switch entry.Metric.Type {
case metrics.Counter:
counter, err := o.metricsRegistry.getOrCreateCounter(name, unit)
if err != nil {
return err
}
counter.Add(ctx, entry.Value, attributeSetOpt)
case metrics.Gauge:
gauge, err := o.metricsRegistry.getOrCreateGauge(name, unit)
if err != nil {
return err
}
gauge.Record(ctx, entry.Value, attributeSetOpt)
case metrics.Trend:
trend, err := o.metricsRegistry.getOrCreateHistogram(name, unit)
if err != nil {
return err
}
trend.Record(ctx, entry.Value, attributeSetOpt)
case metrics.Rate:
var err error
if o.config.SingleCounterForRate.Bool {
err = o.singleCounterForRate(ctx, name, attributeSetOpt, entry)
} else {
// Deprecated path, remove with https://github.com/grafana/k6/issues/5185
err = o.pairOfCountersForRate(ctx, name, attributeSetOpt, entry)
}
if err != nil {
return err
}
default:
return fmt.Errorf("metric %q has unsupported metric type", entry.Metric.Name)
}
return nil
}
func (o *Output) pairOfCountersForRate(
ctx context.Context,
metricName string,
attributeSetOpt otelMetric.MeasurementOption,
entry metrics.Sample,
) error {
nonZero, total, err := o.metricsRegistry.getOrCreateCountersForRate(metricName)
if err != nil {
return fmt.Errorf("get or create counter for Rate metric %q: %w", metricName, err)
}
if entry.Value != 0 {
nonZero.Add(ctx, 1, attributeSetOpt)
}
total.Add(ctx, 1, attributeSetOpt)
return nil
}
func (o *Output) singleCounterForRate(
ctx context.Context,
metricName string,
attributeSetOpt otelMetric.MeasurementOption,
entry metrics.Sample,
) error {
rate, err := o.metricsRegistry.getOrCreateCounterForRate(metricName)
if err != nil {
return fmt.Errorf("get or create counter for Rate metric %q: %w", metricName, err)
}
var valueType string
if entry.Value != 0 {
valueType = "nonzero"
} else {
valueType = "zero"
}
valset := attribute.NewSet(attribute.String("condition", valueType))
rate.Add(ctx, 1, attributeSetOpt, otelMetric.WithAttributeSet(valset))
return nil
}
func normalizeMetricName(cfg Config, name string) string {
return cfg.MetricPrefix.String + name
}
func normalizeUnit(vt metrics.ValueType) string {
switch vt {
case metrics.Time:
return "ms"
case metrics.Data:
return "By"
default:
return ""
}
}