forked from open-telemetry/opentelemetry-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
562 lines (488 loc) · 19.7 KB
/
mod.rs
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! # OpenTelemetry Trace SDK
//!
//! The tracing SDK consist of a few main structs:
//!
//! * The [`SdkTracer`] struct which performs all tracing operations.
//! * The [`Span`] struct with is a mutable object storing information about the
//! current operation execution.
//! * The [`SdkTracerProvider`] struct which configures and produces [`SdkTracer`]s.
mod config;
mod error;
mod events;
mod export;
mod id_generator;
mod links;
mod provider;
mod sampler;
mod span;
mod span_limit;
mod span_processor;
#[cfg(feature = "experimental_trace_batch_span_processor_with_async_runtime")]
/// Experimental feature to use async runtime with batch span processor.
pub mod span_processor_with_async_runtime;
mod tracer;
pub use config::Config;
pub use error::{TraceError, TraceResult};
pub use events::SpanEvents;
pub use export::{SpanData, SpanExporter};
/// In-Memory span exporter for testing purpose.
#[cfg(any(feature = "testing", test))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "testing", test))))]
pub mod in_memory_exporter;
#[cfg(any(feature = "testing", test))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "testing", test))))]
pub use in_memory_exporter::{InMemorySpanExporter, InMemorySpanExporterBuilder};
pub use id_generator::{IdGenerator, RandomIdGenerator};
pub use links::SpanLinks;
pub use provider::{SdkTracerProvider, TracerProviderBuilder};
pub use sampler::{Sampler, ShouldSample};
pub use span::Span;
pub use span_limit::SpanLimits;
pub use span_processor::{
BatchConfig, BatchConfigBuilder, BatchSpanProcessor, BatchSpanProcessorBuilder,
SimpleSpanProcessor, SpanProcessor,
};
pub use tracer::SdkTracer;
pub use tracer::SdkTracer as Tracer; // for back-compat else tracing-opentelemetry won't build
#[cfg(feature = "jaeger_remote_sampler")]
pub use sampler::{JaegerRemoteSampler, JaegerRemoteSamplerBuilder};
#[cfg(feature = "experimental_trace_batch_span_processor_with_async_runtime")]
#[cfg(test)]
mod runtime_tests;
#[cfg(all(test, feature = "testing"))]
mod tests {
use super::*;
use crate::{
trace::span_limit::{DEFAULT_MAX_EVENT_PER_SPAN, DEFAULT_MAX_LINKS_PER_SPAN},
trace::{InMemorySpanExporter, InMemorySpanExporterBuilder},
};
use opentelemetry::{
baggage::BaggageExt,
trace::{SamplingDecision, SamplingResult, SpanKind, Status, TraceContextExt, TraceState},
};
use opentelemetry::{testing::trace::TestSpan, InstrumentationScope};
use opentelemetry::{
trace::{
Event, Link, Span, SpanBuilder, SpanContext, SpanId, TraceFlags, TraceId, Tracer,
TracerProvider,
},
Context, KeyValue,
};
#[test]
fn span_modification_via_context() {
let exporter = InMemorySpanExporterBuilder::new().build();
let provider = SdkTracerProvider::builder()
.with_span_processor(SimpleSpanProcessor::new(exporter.clone()))
.build();
let tracer = provider.tracer("test_tracer");
#[derive(Debug, PartialEq)]
struct ValueA(u64);
let span = tracer.start("span-name");
// start with Current, which should have no span
let cx = Context::current();
assert!(!cx.has_active_span());
// add span to context
let cx_with_span = cx.with_span(span);
assert!(cx_with_span.has_active_span());
assert!(!cx.has_active_span());
// modify the span by using span_ref from the context
// this is the only way to modify the span as span
// is moved to context.
let span_ref = cx_with_span.span();
span_ref.set_attribute(KeyValue::new("attribute1", "value1"));
// create a new context, which should not affect the original
let cx_with_span_and_more = cx_with_span.with_value(ValueA(1));
// modify the span again using the new context.
// this should still be using the original span itself.
let span_ref_new = cx_with_span_and_more.span();
span_ref_new.set_attribute(KeyValue::new("attribute2", "value2"));
span_ref_new.end();
let exported_spans = exporter
.get_finished_spans()
.expect("Spans are expected to be exported.");
// There should be a single span, with attributes from both modifications.
assert_eq!(exported_spans.len(), 1);
let span = &exported_spans[0];
assert_eq!(span.attributes.len(), 2);
}
#[derive(Debug)]
struct BaggageInspectingSpanProcessor;
impl SpanProcessor for BaggageInspectingSpanProcessor {
fn on_start(&self, span: &mut crate::trace::Span, cx: &Context) {
let baggage = cx.baggage();
if let Some(baggage_value) = baggage.get("bag-key") {
span.set_attribute(KeyValue::new("bag-key", baggage_value.to_string()));
} else {
unreachable!("Baggage should be present in the context");
}
}
fn on_end(&self, _span: SpanData) {}
fn force_flush(&self) -> crate::error::OTelSdkResult {
Ok(())
}
fn shutdown(&self) -> crate::error::OTelSdkResult {
Ok(())
}
}
#[test]
fn span_and_baggage() {
let provider = SdkTracerProvider::builder()
.with_span_processor(BaggageInspectingSpanProcessor)
.build();
let cx_with_baggage =
Context::current_with_baggage(vec![KeyValue::new("bag-key", "bag-value")]);
// assert baggage is in the context
assert_eq!(
cx_with_baggage
.baggage()
.get("bag-key")
.unwrap()
.to_string(),
"bag-value"
);
// Attach context to current
let _cx_guard1 = cx_with_baggage.attach();
// now Current should have the baggage
assert_eq!(
Context::current()
.baggage()
.get("bag-key")
.unwrap()
.to_string(),
"bag-value"
);
let tracer = provider.tracer("test_tracer");
let mut span = tracer
.span_builder("span-name")
.start_with_context(&tracer, &Context::current());
span.set_attribute(KeyValue::new("attribute1", "value1"));
// We have not added span to the context yet
// so the current context should not have any span.
let cx = Context::current();
assert!(!cx.has_active_span());
// Now add span to context which already has baggage.
let cx_with_baggage_and_span = cx.with_span(span);
assert!(cx_with_baggage_and_span.has_active_span());
assert_eq!(
cx_with_baggage_and_span
.baggage()
.get("bag-key")
.unwrap()
.to_string(),
"bag-value"
);
let _cx_guard2 = cx_with_baggage_and_span.attach();
// Now current context should have both baggage and span.
assert!(Context::current().has_active_span());
assert_eq!(
Context::current()
.baggage()
.get("bag-key")
.unwrap()
.to_string(),
"bag-value"
);
}
#[test]
fn tracer_in_span() {
// Arrange
let exporter = InMemorySpanExporterBuilder::new().build();
let provider = SdkTracerProvider::builder()
.with_span_processor(SimpleSpanProcessor::new(exporter.clone()))
.build();
// Act
let tracer = provider.tracer("test_tracer");
tracer.in_span("span_name", |cx| {
let span = cx.span();
assert!(span.is_recording());
span.update_name("span_name_updated");
span.set_attribute(KeyValue::new("attribute1", "value1"));
span.add_event("test-event".to_string(), vec![]);
});
// Assert
let exported_spans = exporter
.get_finished_spans()
.expect("Spans are expected to be exported.");
assert_eq!(exported_spans.len(), 1);
let span = &exported_spans[0];
assert_eq!(span.name, "span_name_updated");
assert_eq!(span.instrumentation_scope.name(), "test_tracer");
assert_eq!(span.attributes.len(), 1);
assert_eq!(span.events.len(), 1);
assert_eq!(span.events[0].name, "test-event");
assert_eq!(span.span_context.trace_flags(), TraceFlags::SAMPLED);
assert!(!span.span_context.is_remote());
assert_eq!(span.status, Status::Unset);
}
#[test]
fn tracer_start() {
// Arrange
let exporter = InMemorySpanExporterBuilder::new().build();
let provider = SdkTracerProvider::builder()
.with_span_processor(SimpleSpanProcessor::new(exporter.clone()))
.build();
// Act
let tracer = provider.tracer("test_tracer");
let mut span = tracer.start("span_name");
span.set_attribute(KeyValue::new("attribute1", "value1"));
span.add_event("test-event".to_string(), vec![]);
span.set_status(Status::error("cancelled"));
span.end();
// After span end, further operations should not have any effect
span.update_name("span_name_updated");
// Assert
let exported_spans = exporter
.get_finished_spans()
.expect("Spans are expected to be exported.");
assert_eq!(exported_spans.len(), 1);
let span = &exported_spans[0];
assert_eq!(span.name, "span_name");
assert_eq!(span.instrumentation_scope.name(), "test_tracer");
assert_eq!(span.attributes.len(), 1);
assert_eq!(span.events.len(), 1);
assert_eq!(span.events[0].name, "test-event");
assert_eq!(span.span_context.trace_flags(), TraceFlags::SAMPLED);
assert!(!span.span_context.is_remote());
let status_expected = Status::error("cancelled");
assert_eq!(span.status, status_expected);
}
#[test]
fn tracer_span_builder() {
// Arrange
let exporter = InMemorySpanExporterBuilder::new().build();
let provider = SdkTracerProvider::builder()
.with_span_processor(SimpleSpanProcessor::new(exporter.clone()))
.build();
// Act
let tracer = provider.tracer("test_tracer");
let mut span = tracer
.span_builder("span_name")
.with_kind(SpanKind::Server)
.start(&tracer);
span.set_attribute(KeyValue::new("attribute1", "value1"));
span.add_event("test-event".to_string(), vec![]);
span.set_status(Status::Ok);
drop(span);
// Assert
let exported_spans = exporter
.get_finished_spans()
.expect("Spans are expected to be exported.");
assert_eq!(exported_spans.len(), 1);
let span = &exported_spans[0];
assert_eq!(span.name, "span_name");
assert_eq!(span.span_kind, SpanKind::Server);
assert_eq!(span.instrumentation_scope.name(), "test_tracer");
assert_eq!(span.attributes.len(), 1);
assert_eq!(span.events.len(), 1);
assert_eq!(span.events[0].name, "test-event");
assert_eq!(span.span_context.trace_flags(), TraceFlags::SAMPLED);
assert!(!span.span_context.is_remote());
assert_eq!(span.status, Status::Ok);
}
#[test]
fn exceed_span_links_limit() {
// Arrange
let exporter = InMemorySpanExporterBuilder::new().build();
let provider = SdkTracerProvider::builder()
.with_span_processor(SimpleSpanProcessor::new(exporter.clone()))
.build();
// Act
let tracer = provider.tracer("test_tracer");
let mut links = Vec::new();
for _i in 0..(DEFAULT_MAX_LINKS_PER_SPAN * 2) {
links.push(Link::with_context(SpanContext::new(
TraceId::from_u128(12),
SpanId::from_u64(12),
TraceFlags::default(),
false,
Default::default(),
)))
}
let span_builder = SpanBuilder::from_name("span_name").with_links(links);
let mut span = tracer.build(span_builder);
span.end();
// Assert
let exported_spans = exporter
.get_finished_spans()
.expect("Spans are expected to be exported.");
assert_eq!(exported_spans.len(), 1);
let span = &exported_spans[0];
assert_eq!(span.name, "span_name");
assert_eq!(span.links.len(), DEFAULT_MAX_LINKS_PER_SPAN as usize);
}
#[test]
fn exceed_span_events_limit() {
// Arrange
let exporter = InMemorySpanExporterBuilder::new().build();
let provider = SdkTracerProvider::builder()
.with_span_processor(SimpleSpanProcessor::new(exporter.clone()))
.build();
// Act
let tracer = provider.tracer("test_tracer");
let mut events = Vec::new();
for _i in 0..(DEFAULT_MAX_EVENT_PER_SPAN * 2) {
events.push(Event::with_name("test event"))
}
// add events via span builder
let span_builder = SpanBuilder::from_name("span_name").with_events(events);
let mut span = tracer.build(span_builder);
// add events using span api after building the span
span.add_event("test event again, after span builder", Vec::new());
span.add_event("test event once again, after span builder", Vec::new());
span.end();
// Assert
let exported_spans = exporter
.get_finished_spans()
.expect("Spans are expected to be exported.");
assert_eq!(exported_spans.len(), 1);
let span = &exported_spans[0];
assert_eq!(span.name, "span_name");
assert_eq!(span.events.len(), DEFAULT_MAX_EVENT_PER_SPAN as usize);
assert_eq!(span.events.dropped_count, DEFAULT_MAX_EVENT_PER_SPAN + 2);
}
#[test]
fn trace_state_for_dropped_sampler() {
let exporter = InMemorySpanExporterBuilder::new().build();
let provider = SdkTracerProvider::builder()
.with_sampler(Sampler::AlwaysOff)
.with_span_processor(SimpleSpanProcessor::new(exporter.clone()))
.build();
let tracer = provider.tracer("test");
let trace_state = TraceState::from_key_value(vec![("foo", "bar")]).unwrap();
let parent_context = Context::new().with_span(TestSpan(SpanContext::new(
TraceId::from_u128(10000),
SpanId::from_u64(20),
TraceFlags::SAMPLED,
true,
trace_state.clone(),
)));
let span = tracer.start_with_context("span", &parent_context);
assert_eq!(
span.span_context().trace_state().get("foo"),
trace_state.get("foo")
)
}
#[derive(Clone, Debug, Default)]
struct TestRecordOnlySampler {}
impl ShouldSample for TestRecordOnlySampler {
fn should_sample(
&self,
parent_context: Option<&Context>,
_trace_id: TraceId,
_name: &str,
_span_kind: &SpanKind,
_attributes: &[KeyValue],
_links: &[Link],
) -> SamplingResult {
let trace_state = parent_context
.unwrap()
.span()
.span_context()
.trace_state()
.clone();
SamplingResult {
decision: SamplingDecision::RecordOnly,
attributes: vec![KeyValue::new("record_only_key", "record_only_value")],
trace_state,
}
}
}
#[test]
fn trace_state_for_record_only_sampler() {
let exporter = InMemorySpanExporterBuilder::new().build();
let provider = SdkTracerProvider::builder()
.with_sampler(TestRecordOnlySampler::default())
.with_span_processor(SimpleSpanProcessor::new(exporter.clone()))
.build();
let tracer = provider.tracer("test");
let trace_state = TraceState::from_key_value(vec![("foo", "bar")]).unwrap();
let parent_context = Context::new().with_span(TestSpan(SpanContext::new(
TraceId::from_u128(10000),
SpanId::from_u64(20),
TraceFlags::SAMPLED,
true,
trace_state.clone(),
)));
let span = tracer.build_with_context(
SpanBuilder::from_name("span")
.with_attributes(vec![KeyValue::new("extra_attr_key", "extra_attr_value")]),
&parent_context,
);
assert!(!span.span_context().trace_flags().is_sampled());
assert_eq!(
span.exported_data().unwrap().attributes,
vec![
KeyValue::new("extra_attr_key", "extra_attr_value"),
KeyValue::new("record_only_key", "record_only_value")
]
);
assert_eq!(span.span_context().trace_state().get("foo"), Some("bar"));
}
#[test]
fn tracer_attributes() {
let provider = SdkTracerProvider::builder().build();
let scope = InstrumentationScope::builder("basic")
.with_attributes(vec![KeyValue::new("test_k", "test_v")])
.build();
let tracer = provider.tracer_with_scope(scope);
let instrumentation_scope = tracer.instrumentation_scope();
assert!(instrumentation_scope
.attributes()
.eq(&[KeyValue::new("test_k", "test_v")]));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn empty_tracer_name_retained() {
async fn tracer_name_retained_helper(
tracer: super::SdkTracer,
provider: SdkTracerProvider,
exporter: InMemorySpanExporter,
) {
// Act
tracer.start("my_span").end();
// Force flush to ensure spans are exported
assert!(provider.force_flush().is_ok());
// Assert
let finished_spans = exporter
.get_finished_spans()
.expect("spans are expected to be exported.");
assert_eq!(finished_spans.len(), 1, "There should be a single span");
let tracer_name = finished_spans[0].instrumentation_scope.name();
assert_eq!(tracer_name, "", "The tracer name should be an empty string");
exporter.reset();
}
let exporter = InMemorySpanExporter::default();
let span_processor = SimpleSpanProcessor::new(exporter.clone());
let tracer_provider = SdkTracerProvider::builder()
.with_span_processor(span_processor)
.build();
// Test Tracer creation in 2 ways, both with empty string as tracer name
let tracer1 = tracer_provider.tracer("");
tracer_name_retained_helper(tracer1, tracer_provider.clone(), exporter.clone()).await;
let tracer_scope = InstrumentationScope::builder("").build();
let tracer2 = tracer_provider.tracer_with_scope(tracer_scope);
tracer_name_retained_helper(tracer2, tracer_provider, exporter).await;
}
#[test]
fn trace_suppression() {
// Arrange
let exporter = InMemorySpanExporter::default();
let span_processor = SimpleSpanProcessor::new(exporter.clone());
let tracer_provider = SdkTracerProvider::builder()
.with_span_processor(span_processor)
.build();
// Act
let tracer = tracer_provider.tracer("test");
{
let _suppressed_context = Context::enter_telemetry_suppressed_scope();
let span = tracer.span_builder("span_name").start(&tracer);
drop(span);
}
// Assert
let finished_spans = exporter.get_finished_spans().expect("this should not fail");
assert_eq!(
finished_spans.len(),
0,
"There should be a no spans as span emission is done inside a suppressed context"
);
}
}