-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInstrumenterBuilder.java
More file actions
491 lines (435 loc) · 18.8 KB
/
InstrumenterBuilder.java
File metadata and controls
491 lines (435 loc) · 18.8 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
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.api.instrumenter;
import static java.util.Objects.requireNonNull;
import static java.util.logging.Level.WARNING;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.api.metrics.MeterBuilder;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.trace.TracerBuilder;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.TextMapGetter;
import io.opentelemetry.context.propagation.TextMapSetter;
import io.opentelemetry.instrumentation.api.internal.ApiConfigProperties;
import io.opentelemetry.instrumentation.api.internal.EmbeddedInstrumentationProperties;
import io.opentelemetry.instrumentation.api.internal.Experimental;
import io.opentelemetry.instrumentation.api.internal.InstrumenterBuilderAccess;
import io.opentelemetry.instrumentation.api.internal.InstrumenterUtil;
import io.opentelemetry.instrumentation.api.internal.InternalInstrumenterCustomizer;
import io.opentelemetry.instrumentation.api.internal.InternalInstrumenterCustomizerProvider;
import io.opentelemetry.instrumentation.api.internal.InternalInstrumenterCustomizerUtil;
import io.opentelemetry.instrumentation.api.internal.SchemaUrlProvider;
import io.opentelemetry.instrumentation.api.internal.SpanKey;
import io.opentelemetry.instrumentation.api.internal.SpanKeyProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.UnaryOperator;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
/**
* A builder of an {@link Instrumenter}.
*
* <p>Instrumentation libraries should generally expose their own builder with controls that are
* appropriate for that library and delegate to this class to create the {@link Instrumenter}.
*/
public final class InstrumenterBuilder<REQUEST, RESPONSE> {
private static final Logger logger = Logger.getLogger(InstrumenterBuilder.class.getName());
final OpenTelemetry openTelemetry;
final String instrumentationName;
SpanNameExtractor<? super REQUEST> spanNameExtractor;
final List<SpanLinksExtractor<? super REQUEST>> spanLinksExtractors = new ArrayList<>();
final List<AttributesExtractor<? super REQUEST, ? super RESPONSE>> attributesExtractors =
new ArrayList<>();
final List<AttributesExtractor<? super REQUEST, ? super RESPONSE>>
operationListenerAttributesExtractors = new ArrayList<>();
final List<ContextCustomizer<? super REQUEST>> contextCustomizers = new ArrayList<>();
private final List<OperationListener> operationListeners = new ArrayList<>();
private final List<OperationMetrics> operationMetrics = new ArrayList<>();
@Nullable private String instrumentationVersion;
@Nullable private String schemaUrl = null;
SpanKindExtractor<? super REQUEST> spanKindExtractor = SpanKindExtractor.alwaysInternal();
SpanStatusExtractor<? super REQUEST, ? super RESPONSE> spanStatusExtractor =
SpanStatusExtractor.getDefault();
ErrorCauseExtractor errorCauseExtractor = ErrorCauseExtractor.getDefault();
boolean propagateOperationListenersToOnEnd = false;
boolean enabled = true;
static {
Experimental.internalAddOperationListenerAttributesExtractor(
(builder, operationListenerAttributesExtractor) ->
builder.operationListenerAttributesExtractors.add(
requireNonNull(
operationListenerAttributesExtractor, "operationListenerAttributesExtractor")));
}
InstrumenterBuilder(
OpenTelemetry openTelemetry,
String instrumentationName,
SpanNameExtractor<? super REQUEST> spanNameExtractor) {
this.openTelemetry = openTelemetry;
this.instrumentationName = instrumentationName;
this.spanNameExtractor = spanNameExtractor;
this.instrumentationVersion =
EmbeddedInstrumentationProperties.findVersion(instrumentationName);
}
/**
* Sets the instrumentation version that will be associated with all telemetry produced by this
* {@link Instrumenter}.
*
* @param instrumentationVersion is the version of the instrumentation library, not the version of
* the instrument<b>ed</b> library.
*/
@CanIgnoreReturnValue
public InstrumenterBuilder<REQUEST, RESPONSE> setInstrumentationVersion(
String instrumentationVersion) {
this.instrumentationVersion = requireNonNull(instrumentationVersion, "instrumentationVersion");
return this;
}
/**
* Sets the OpenTelemetry schema URL that will be associated with all telemetry produced by this
* {@link Instrumenter}.
*/
@CanIgnoreReturnValue
public InstrumenterBuilder<REQUEST, RESPONSE> setSchemaUrl(String schemaUrl) {
this.schemaUrl = requireNonNull(schemaUrl, "schemaUrl");
return this;
}
/**
* Sets the {@link SpanStatusExtractor} that will determine the {@link StatusCode} for a response.
*/
@CanIgnoreReturnValue
public InstrumenterBuilder<REQUEST, RESPONSE> setSpanStatusExtractor(
SpanStatusExtractor<? super REQUEST, ? super RESPONSE> spanStatusExtractor) {
this.spanStatusExtractor = requireNonNull(spanStatusExtractor, "spanStatusExtractor");
return this;
}
/**
* Adds a {@link AttributesExtractor} that will extract attributes from requests and responses.
*/
@CanIgnoreReturnValue
public InstrumenterBuilder<REQUEST, RESPONSE> addAttributesExtractor(
AttributesExtractor<? super REQUEST, ? super RESPONSE> attributesExtractor) {
this.attributesExtractors.add(requireNonNull(attributesExtractor, "attributesExtractor"));
return this;
}
/** Adds {@link AttributesExtractor}s that will extract attributes from requests and responses. */
@CanIgnoreReturnValue
public InstrumenterBuilder<REQUEST, RESPONSE> addAttributesExtractors(
Iterable<? extends AttributesExtractor<? super REQUEST, ? super RESPONSE>>
attributesExtractors) {
attributesExtractors.forEach(this::addAttributesExtractor);
return this;
}
/** Adds a {@link SpanLinksExtractor} that will extract span links from requests. */
@CanIgnoreReturnValue
public InstrumenterBuilder<REQUEST, RESPONSE> addSpanLinksExtractor(
SpanLinksExtractor<REQUEST> spanLinksExtractor) {
spanLinksExtractors.add(requireNonNull(spanLinksExtractor, "spanLinksExtractor"));
return this;
}
/**
* Adds a {@link ContextCustomizer} that will customize the context during {@link
* Instrumenter#start(Context, Object)}.
*/
@CanIgnoreReturnValue
public InstrumenterBuilder<REQUEST, RESPONSE> addContextCustomizer(
ContextCustomizer<? super REQUEST> contextCustomizer) {
contextCustomizers.add(requireNonNull(contextCustomizer, "contextCustomizer"));
return this;
}
/**
* Adds a {@link OperationListener} that will be called when an instrumented operation starts and
* ends.
*/
@CanIgnoreReturnValue
public InstrumenterBuilder<REQUEST, RESPONSE> addOperationListener(OperationListener listener) {
operationListeners.add(requireNonNull(listener, "operationListener"));
return this;
}
/**
* Adds a {@link OperationMetrics} that will produce a {@link OperationListener} capturing the
* requests processing metrics.
*/
@CanIgnoreReturnValue
public InstrumenterBuilder<REQUEST, RESPONSE> addOperationMetrics(OperationMetrics factory) {
operationMetrics.add(requireNonNull(factory, "operationMetrics"));
return this;
}
/**
* Sets the {@link ErrorCauseExtractor} that will extract the root cause of an error thrown during
* request processing.
*/
@CanIgnoreReturnValue
public InstrumenterBuilder<REQUEST, RESPONSE> setErrorCauseExtractor(
ErrorCauseExtractor errorCauseExtractor) {
this.errorCauseExtractor = requireNonNull(errorCauseExtractor, "errorCauseExtractor");
return this;
}
/**
* Allows enabling/disabling the {@link Instrumenter} based on the {@code enabled} value passed as
* parameter. All instrumenters are enabled by default.
*/
@CanIgnoreReturnValue
public InstrumenterBuilder<REQUEST, RESPONSE> setEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Returns a new {@link Instrumenter} which will create {@linkplain SpanKind#CLIENT client} spans
* and inject context into requests with the passed {@link TextMapSetter}.
*/
public Instrumenter<REQUEST, RESPONSE> buildClientInstrumenter(TextMapSetter<REQUEST> setter) {
return buildInstrumenter(
InstrumenterConstructor.propagatingToDownstream(requireNonNull(setter, "setter")),
SpanKindExtractor.alwaysClient());
}
/**
* Returns a new {@link Instrumenter} which will create {@linkplain SpanKind#SERVER server} spans
* and extract context from requests with the passed {@link TextMapGetter}.
*/
public Instrumenter<REQUEST, RESPONSE> buildServerInstrumenter(TextMapGetter<REQUEST> getter) {
return buildInstrumenter(
InstrumenterConstructor.propagatingFromUpstream(requireNonNull(getter, "getter")),
SpanKindExtractor.alwaysServer());
}
/**
* Returns a new {@link Instrumenter} which will create {@linkplain SpanKind#PRODUCER producer}
* spans and inject context into requests with the passed {@link TextMapSetter}.
*/
public Instrumenter<REQUEST, RESPONSE> buildProducerInstrumenter(TextMapSetter<REQUEST> setter) {
return buildInstrumenter(
InstrumenterConstructor.propagatingToDownstream(requireNonNull(setter, "setter")),
SpanKindExtractor.alwaysProducer());
}
/**
* Returns a new {@link Instrumenter} which will create {@linkplain SpanKind#CONSUMER consumer}
* spans and extract context from requests with the passed {@link TextMapGetter}.
*/
public Instrumenter<REQUEST, RESPONSE> buildConsumerInstrumenter(TextMapGetter<REQUEST> getter) {
return buildInstrumenter(
InstrumenterConstructor.propagatingFromUpstream(requireNonNull(getter, "getter")),
SpanKindExtractor.alwaysConsumer());
}
/**
* Returns a new {@link Instrumenter} which will create spans with kind determined by the passed
* {@link SpanKindExtractor} and extract context from requests with the passed {@link
* TextMapGetter}.
*/
// TODO: candidate for public API
Instrumenter<REQUEST, RESPONSE> buildUpstreamInstrumenter(
TextMapGetter<REQUEST> getter, SpanKindExtractor<REQUEST> spanKindExtractor) {
return buildInstrumenter(
InstrumenterConstructor.propagatingFromUpstream(requireNonNull(getter, "getter")),
spanKindExtractor);
}
/**
* Returns a new {@link Instrumenter} which will create spans with kind determined by the passed
* {@link SpanKindExtractor} and inject context into requests with the passed {@link
* TextMapSetter}.
*/
// TODO: candidate for public API
Instrumenter<REQUEST, RESPONSE> buildDownstreamInstrumenter(
TextMapSetter<REQUEST> setter, SpanKindExtractor<REQUEST> spanKindExtractor) {
return buildInstrumenter(
InstrumenterConstructor.propagatingToDownstream(requireNonNull(setter, "setter")),
spanKindExtractor);
}
/**
* Returns a new {@link Instrumenter} which will create {@linkplain SpanKind#INTERNAL internal}
* spans and do no context propagation.
*/
public Instrumenter<REQUEST, RESPONSE> buildInstrumenter() {
return buildInstrumenter(
InstrumenterConstructor.internal(), SpanKindExtractor.alwaysInternal());
}
/**
* Returns a new {@link Instrumenter} which will create spans with kind determined by the passed
* {@link SpanKindExtractor} and do no context propagation.
*/
public Instrumenter<REQUEST, RESPONSE> buildInstrumenter(
SpanKindExtractor<? super REQUEST> spanKindExtractor) {
return buildInstrumenter(
InstrumenterConstructor.internal(), requireNonNull(spanKindExtractor, "spanKindExtractor"));
}
private Instrumenter<REQUEST, RESPONSE> buildInstrumenter(
InstrumenterConstructor<REQUEST, RESPONSE> constructor,
SpanKindExtractor<? super REQUEST> spanKindExtractor) {
applyCustomizers(this);
this.spanKindExtractor = spanKindExtractor;
return constructor.create(this);
}
Tracer buildTracer() {
TracerBuilder tracerBuilder =
openTelemetry.getTracerProvider().tracerBuilder(instrumentationName);
if (instrumentationVersion != null) {
tracerBuilder.setInstrumentationVersion(instrumentationVersion);
}
String schemaUrl = getSchemaUrl();
if (schemaUrl != null) {
tracerBuilder.setSchemaUrl(schemaUrl);
}
return tracerBuilder.build();
}
List<OperationListener> buildOperationListeners() {
// just copy the listeners list if there are no metrics registered
if (operationMetrics.isEmpty()) {
return new ArrayList<>(operationListeners);
}
List<OperationListener> listeners =
new ArrayList<>(operationListeners.size() + operationMetrics.size());
listeners.addAll(operationListeners);
MeterBuilder meterBuilder = openTelemetry.getMeterProvider().meterBuilder(instrumentationName);
if (instrumentationVersion != null) {
meterBuilder.setInstrumentationVersion(instrumentationVersion);
}
String schemaUrl = getSchemaUrl();
if (schemaUrl != null) {
meterBuilder.setSchemaUrl(schemaUrl);
}
Meter meter = meterBuilder.build();
for (OperationMetrics factory : operationMetrics) {
listeners.add(factory.create(meter));
}
return listeners;
}
@Nullable
private String getSchemaUrl() {
// url set explicitly overrides url computed using attributes extractors
if (schemaUrl != null) {
return schemaUrl;
}
Set<String> computedSchemaUrls =
attributesExtractors.stream()
.filter(SchemaUrlProvider.class::isInstance)
.map(SchemaUrlProvider.class::cast)
.flatMap(
provider -> {
String url = provider.internalGetSchemaUrl();
return url == null ? Stream.of() : Stream.of(url);
})
.collect(Collectors.toSet());
switch (computedSchemaUrls.size()) {
case 0:
return null;
case 1:
return computedSchemaUrls.iterator().next();
default:
logger.log(
WARNING,
"Multiple schemaUrls were detected: {0}. The built Instrumenter will have no schemaUrl assigned.",
computedSchemaUrls);
return null;
}
}
SpanSuppressor buildSpanSuppressor() {
return new SpanSuppressors.ByContextKey(
SpanSuppressionStrategy.fromConfig(
new ApiConfigProperties(openTelemetry)
.getString("otel.instrumentation.experimental.span-suppression-strategy"))
.create(getSpanKeysFromAttributesExtractors()));
}
private Set<SpanKey> getSpanKeysFromAttributesExtractors() {
return attributesExtractors.stream()
.filter(SpanKeyProvider.class::isInstance)
.map(SpanKeyProvider.class::cast)
.flatMap(
provider -> {
SpanKey spanKey = provider.internalGetSpanKey();
return spanKey == null ? Stream.of() : Stream.of(spanKey);
})
.collect(Collectors.toSet());
}
private void propagateOperationListenersToOnEnd() {
propagateOperationListenersToOnEnd = true;
}
private static <REQUEST, RESPONSE> void applyCustomizers(
InstrumenterBuilder<REQUEST, RESPONSE> builder) {
List<InternalInstrumenterCustomizerProvider> customizerProviders =
InternalInstrumenterCustomizerUtil.getInstrumenterCustomizerProviders();
if (customizerProviders.isEmpty()) {
return;
}
Set<SpanKey> spanKeys = builder.getSpanKeysFromAttributesExtractors();
for (InternalInstrumenterCustomizerProvider provider : customizerProviders) {
provider.customize(
new InternalInstrumenterCustomizer<REQUEST, RESPONSE>() {
@Override
public String getInstrumentationName() {
return builder.instrumentationName;
}
@Override
public boolean hasType(SpanKey type) {
return spanKeys.contains(type);
}
@Override
public void addAttributesExtractor(AttributesExtractor<REQUEST, RESPONSE> extractor) {
builder.addAttributesExtractor(extractor);
}
@Override
public void addAttributesExtractors(
Iterable<? extends AttributesExtractor<REQUEST, RESPONSE>> extractors) {
builder.addAttributesExtractors(extractors);
}
@Override
public void addOperationMetrics(OperationMetrics operationMetrics) {
builder.addOperationMetrics(operationMetrics);
}
@Override
public void addContextCustomizer(ContextCustomizer<REQUEST> customizer) {
builder.addContextCustomizer(customizer);
}
@Override
public void setSpanNameExtractor(
UnaryOperator<SpanNameExtractor<? super REQUEST>> spanNameExtractorTransformer) {
builder.spanNameExtractor =
spanNameExtractorTransformer.apply(builder.spanNameExtractor);
}
});
}
}
private interface InstrumenterConstructor<RQ, RS> {
Instrumenter<RQ, RS> create(InstrumenterBuilder<RQ, RS> builder);
static <RQ, RS> InstrumenterConstructor<RQ, RS> internal() {
return Instrumenter::new;
}
static <RQ, RS> InstrumenterConstructor<RQ, RS> propagatingToDownstream(
TextMapSetter<RQ> setter) {
return builder -> new PropagatingToDownstreamInstrumenter<>(builder, setter);
}
static <RQ, RS> InstrumenterConstructor<RQ, RS> propagatingFromUpstream(
TextMapGetter<RQ> getter) {
return builder -> new PropagatingFromUpstreamInstrumenter<>(builder, getter);
}
}
static {
InstrumenterUtil.setInstrumenterBuilderAccess(
new InstrumenterBuilderAccess() {
@Override
public <RQ, RS> Instrumenter<RQ, RS> buildUpstreamInstrumenter(
InstrumenterBuilder<RQ, RS> builder,
TextMapGetter<RQ> getter,
SpanKindExtractor<RQ> spanKindExtractor) {
return builder.buildUpstreamInstrumenter(getter, spanKindExtractor);
}
@Override
public <RQ, RS> Instrumenter<RQ, RS> buildDownstreamInstrumenter(
InstrumenterBuilder<RQ, RS> builder,
TextMapSetter<RQ> setter,
SpanKindExtractor<RQ> spanKindExtractor) {
return builder.buildDownstreamInstrumenter(setter, spanKindExtractor);
}
@Override
public <RQ, RS> void propagateOperationListenersToOnEnd(
InstrumenterBuilder<RQ, RS> builder) {
builder.propagateOperationListenersToOnEnd();
}
});
}
}