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
mod agent;
#[cfg(any(feature = "collector_client", feature = "wasm_collector_client"))]
mod collector;
pub(crate) mod runtime;
#[allow(clippy::all, unreachable_pub, dead_code)]
#[rustfmt::skip] mod thrift;
pub mod config;
pub(crate) mod transport;
mod uploader;
#[allow(unused_imports)]
#[cfg(feature = "surf_collector_client")]
use std::convert::TryFrom;
use self::runtime::JaegerTraceRuntime;
use self::thrift::jaeger;
use futures::future::BoxFuture;
use std::convert::TryInto;
use std::sync::Arc;
#[cfg(feature = "isahc_collector_client")]
#[allow(unused_imports)] use isahc::prelude::Configurable;
use opentelemetry::sdk::export::ExportError;
use opentelemetry::{
sdk,
sdk::export::trace,
trace::{Event, Link, SpanKind, Status},
Key, KeyValue,
};
use crate::exporter::uploader::Uploader;
use std::time::{Duration, SystemTime};
const INSTRUMENTATION_LIBRARY_NAME: &str = "otel.library.name";
const INSTRUMENTATION_LIBRARY_VERSION: &str = "otel.library.version";
#[derive(Debug)]
pub struct Exporter {
export_instrumentation_lib: bool,
uploader: Arc<dyn Uploader>,
process: jaeger::Process,
}
impl Exporter {
fn new(
process: jaeger::Process,
export_instrumentation_lib: bool,
uploader: Arc<dyn Uploader>,
) -> Exporter {
Exporter {
export_instrumentation_lib,
uploader,
process,
}
}
}
#[derive(Debug, Default)]
pub struct Process {
pub service_name: String,
pub tags: Vec<KeyValue>,
}
impl trace::SpanExporter for Exporter {
fn export(&mut self, batch: Vec<trace::SpanData>) -> BoxFuture<'static, trace::ExportResult> {
let mut jaeger_spans: Vec<jaeger::Span> = Vec::with_capacity(batch.len());
let process = self.process.clone();
for span in batch.into_iter() {
jaeger_spans.push(convert_otel_span_into_jaeger_span(
span,
self.export_instrumentation_lib,
));
}
let uploader = self.uploader.clone();
Box::pin(async move {
uploader
.upload(jaeger::Batch::new(process, jaeger_spans))
.await
})
}
}
fn links_to_references(links: sdk::trace::EvictedQueue<Link>) -> Option<Vec<jaeger::SpanRef>> {
if !links.is_empty() {
let refs = links
.iter()
.map(|link| {
let span_context = &link.span_context;
let trace_id_bytes = span_context.trace_id().to_bytes();
let (high, low) = trace_id_bytes.split_at(8);
let trace_id_high = i64::from_be_bytes(high.try_into().unwrap());
let trace_id_low = i64::from_be_bytes(low.try_into().unwrap());
jaeger::SpanRef::new(
jaeger::SpanRefType::FollowsFrom,
trace_id_low,
trace_id_high,
i64::from_be_bytes(span_context.span_id().to_bytes()),
)
})
.collect();
Some(refs)
} else {
None
}
}
fn convert_otel_span_into_jaeger_span(
span: trace::SpanData,
export_instrument_lib: bool,
) -> jaeger::Span {
let trace_id_bytes = span.span_context.trace_id().to_bytes();
let (high, low) = trace_id_bytes.split_at(8);
let trace_id_high = i64::from_be_bytes(high.try_into().unwrap());
let trace_id_low = i64::from_be_bytes(low.try_into().unwrap());
jaeger::Span {
trace_id_low,
trace_id_high,
span_id: i64::from_be_bytes(span.span_context.span_id().to_bytes()),
parent_span_id: i64::from_be_bytes(span.parent_span_id.to_bytes()),
operation_name: span.name.into_owned(),
references: links_to_references(span.links),
flags: span.span_context.trace_flags().to_u8() as i32,
start_time: span
.start_time
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_else(|_| Duration::from_secs(0))
.as_micros() as i64,
duration: span
.end_time
.duration_since(span.start_time)
.unwrap_or_else(|_| Duration::from_secs(0))
.as_micros() as i64,
tags: Some(build_span_tags(
span.attributes,
if export_instrument_lib {
Some(span.instrumentation_lib)
} else {
None
},
span.status,
span.span_kind,
)),
logs: events_to_logs(span.events),
}
}
fn build_span_tags(
attrs: sdk::trace::EvictedHashMap,
instrumentation_lib: Option<sdk::InstrumentationLibrary>,
status: Status,
kind: SpanKind,
) -> Vec<jaeger::Tag> {
let mut user_overrides = UserOverrides::default();
let mut tags = attrs
.into_iter()
.map(|(k, v)| {
user_overrides.record_attr(k.as_str());
KeyValue::new(k, v).into()
})
.collect::<Vec<_>>();
if let Some(instrumentation_lib) = instrumentation_lib {
tags.push(KeyValue::new(INSTRUMENTATION_LIBRARY_NAME, instrumentation_lib.name).into());
if let Some(version) = instrumentation_lib.version {
tags.push(KeyValue::new(INSTRUMENTATION_LIBRARY_VERSION, version).into())
}
}
if !user_overrides.span_kind && kind != SpanKind::Internal {
tags.push(Key::new(SPAN_KIND).string(format_span_kind(kind)).into());
}
match status {
Status::Unset => {}
Status::Ok => {
if !user_overrides.status_code {
tags.push(KeyValue::new(OTEL_STATUS_CODE, "OK").into());
}
}
Status::Error {
description: message,
} => {
if !user_overrides.error {
tags.push(Key::new(ERROR).bool(true).into());
}
if !user_overrides.status_code {
tags.push(KeyValue::new(OTEL_STATUS_CODE, "ERROR").into());
}
if !message.is_empty() && !user_overrides.status_description {
tags.push(Key::new(OTEL_STATUS_DESCRIPTION).string(message).into());
}
}
}
tags
}
fn format_span_kind(kind: SpanKind) -> &'static str {
match kind {
SpanKind::Client => "client",
SpanKind::Server => "server",
SpanKind::Producer => "producer",
SpanKind::Consumer => "consumer",
SpanKind::Internal => "internal",
}
}
const ERROR: &str = "error";
const SPAN_KIND: &str = "span.kind";
const OTEL_STATUS_CODE: &str = "otel.status_code";
const OTEL_STATUS_DESCRIPTION: &str = "otel.status_description";
#[derive(Default)]
struct UserOverrides {
error: bool,
span_kind: bool,
status_code: bool,
status_description: bool,
}
impl UserOverrides {
fn record_attr(&mut self, attr: &str) {
match attr {
ERROR => self.error = true,
SPAN_KIND => self.span_kind = true,
OTEL_STATUS_CODE => self.status_code = true,
OTEL_STATUS_DESCRIPTION => self.status_description = true,
_ => (),
}
}
}
fn events_to_logs(events: sdk::trace::EvictedQueue<Event>) -> Option<Vec<jaeger::Log>> {
if events.is_empty() {
None
} else {
Some(events.into_iter().map(Into::into).collect())
}
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("thrift agent failed with {0}")]
ThriftAgentError(#[from] ::thrift::Error),
#[error("{pipeline_name} pipeline fails because one of the configuration {config_name} is invalid. {reason}")]
ConfigError {
pipeline_name: &'static str,
config_name: &'static str,
reason: String,
},
}
impl ExportError for Error {
fn exporter_name(&self) -> &'static str {
"jaeger"
}
}
#[cfg(test)]
mod tests {
use super::SPAN_KIND;
use crate::exporter::thrift::jaeger::Tag;
use crate::exporter::{build_span_tags, OTEL_STATUS_CODE, OTEL_STATUS_DESCRIPTION};
use opentelemetry::sdk::trace::EvictedHashMap;
use opentelemetry::trace::{SpanKind, Status};
use opentelemetry::KeyValue;
fn assert_tag_contains(tags: Vec<Tag>, key: &'static str, expect_val: &'static str) {
assert_eq!(
tags.into_iter()
.filter(|tag| tag.key.as_str() == key
&& tag.v_str.as_deref().unwrap_or("") == expect_val)
.count(),
1,
"Expect a tag {} with value {} but found nothing",
key,
expect_val
);
}
fn assert_tag_not_contains(tags: Vec<Tag>, key: &'static str) {
assert_eq!(
tags.into_iter()
.filter(|tag| tag.key.as_str() == key)
.count(),
0,
"Not expect tag {}, but found something",
key
);
}
#[rustfmt::skip]
fn get_error_tag_test_data() -> Vec<(Status, Option<&'static str>, Option<&'static str>)>
{
vec![
(Status::error(""), Some("ERROR"), None),
(Status::Unset, None, None),
(Status::Ok, Some("OK"), None),
(Status::error("have message"), Some("ERROR"), Some("have message")),
(Status::Unset, None, None),
]
}
#[test]
fn test_set_status() {
for (status, status_tag_val, msg_tag_val) in get_error_tag_test_data() {
let tags = build_span_tags(EvictedHashMap::new(20, 20), None, status, SpanKind::Client);
if let Some(val) = status_tag_val {
assert_tag_contains(tags.clone(), OTEL_STATUS_CODE, val);
} else {
assert_tag_not_contains(tags.clone(), OTEL_STATUS_CODE);
}
if let Some(val) = msg_tag_val {
assert_tag_contains(tags.clone(), OTEL_STATUS_DESCRIPTION, val);
} else {
assert_tag_not_contains(tags.clone(), OTEL_STATUS_DESCRIPTION);
}
}
}
#[test]
fn ignores_user_set_values() {
let mut attributes = EvictedHashMap::new(20, 20);
let user_error = true;
let user_kind = "server";
let user_status_description = "Something bad happened";
let user_status = Status::Error {
description: user_status_description.into(),
};
attributes.insert(KeyValue::new("error", user_error));
attributes.insert(KeyValue::new(SPAN_KIND, user_kind));
attributes.insert(KeyValue::new(OTEL_STATUS_CODE, "ERROR"));
attributes.insert(KeyValue::new(
OTEL_STATUS_DESCRIPTION,
user_status_description,
));
let tags = build_span_tags(attributes, None, user_status, SpanKind::Client);
assert!(tags
.iter()
.filter(|tag| tag.key.as_str() == "error")
.all(|tag| tag.v_bool.unwrap()));
assert_tag_contains(tags.clone(), SPAN_KIND, user_kind);
assert_tag_contains(tags.clone(), OTEL_STATUS_CODE, "ERROR");
assert_tag_contains(tags, OTEL_STATUS_DESCRIPTION, user_status_description);
}
}