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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! An [Azure Application Insights] exporter implementation for [OpenTelemetry Rust].
//!
//! [Azure Application Insights]: https://docs.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview
//! [OpenTelemetry Rust]: https://github.com/open-telemetry/opentelemetry-rust
//!
//! **Disclaimer**: This is not an official Microsoft product.
//!
//! # Usage
//!
//! Configure a OpenTelemetry pipeline using the Application Insights exporter and start creating
//! spans (this example requires the **reqwest-client-blocking** feature):
//!
//! ```no_run
//! use opentelemetry::{api::trace::Tracer as _, sdk::trace::Tracer};
//! use opentelemetry_application_insights::Uninstall;
//!
//! fn init_tracer() -> (Tracer, Uninstall)  {
//!     let instrumentation_key = std::env::var("INSTRUMENTATION_KEY").unwrap();
//!     opentelemetry_application_insights::new_pipeline(instrumentation_key)
//!         .with_client(reqwest::blocking::Client::new())
//!         .install()
//! }
//!
//! fn main() {
//!     let (tracer, _uninstall) = init_tracer();
//!     tracer.in_span("main", |_cx| {});
//! }
//! ```
//!
//! ## Features
//!
//! The functions `build` and `install` automatically configure an asynchronous batch exporter if
//! you enable either the **async-std** or **tokio** feature for the `opentelemetry` crate.
//! Otherwise spans will be exported synchronously.
//!
//! In order to support different async runtimes, the exporter requires you to specify an HTTP
//! client that works with your chosen runtime. This crate comes with support for:
//!
//! - [`surf`] for [`async-std`]: enable the **surf-client** and **opentelemetry/async-std**
//!   features and configure the exporter with `with_client(surf::Client::new())`.
//! - [`reqwest`] for [`tokio`]: enable the **reqwest-client** and **opentelemetry/tokio** features
//!   and configure the exporter with `with_client(reqwest::Client::new())`.
//! - [`reqwest`] for synchronous exports: enable the **reqwest-blocking-client** feature and
//!   configure the exporter with `with_client(reqwest::blocking::Client::new())`.
//!
//! [`async-std`]: https://crates.io/crates/async-std
//! [`reqwest`]: https://crates.io/crates/reqwest
//! [`surf`]: https://crates.io/crates/surf
//! [`tokio`]: https://crates.io/crates/tokio
//!
//! Alternatively you can bring any other HTTP client by implementing the `HttpClient` trait.
//!
//! # Attribute mapping
//!
//! OpenTelemetry and Application Insights are using different terminology. This crate tries it's
//! best to map OpenTelemetry fields to their correct Application Insights pendant.
//!
//! - [OpenTelemetry specification: Span](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/api.md#span)
//! - [Application Insights data model](https://docs.microsoft.com/en-us/azure/azure-monitor/app/data-model)
//!
//! ## Spans
//!
//! The OpenTelemetry SpanKind determines the Application Insights telemetry type:
//!
//! | OpenTelemetry SpanKind           | Application Insights telemetry type |
//! | -------------------------------- | ----------------------------------- |
//! | `CLIENT`, `PRODUCER`, `INTERNAL` | Dependency                          |
//! | `SERVER`, `CONSUMER`             | Request                             |
//!
//! The Span's status determines the Success field of a Dependency or Request. Success is `true` if
//! the status is `OK`; otherwise `false`.
//!
//! For `INTERNAL` Spans the Dependency Type is always `"InProc"` and Success is `true`.
//!
//! The following of the Span's attributes map to special fields in Application Insights (the
//! mapping tries to follow the OpenTelemetry semantic conventions for [trace] and [resource]).
//!
//! [trace]: https://github.com/open-telemetry/opentelemetry-specification/tree/master/specification/trace/semantic_conventions
//! [resource]: https://github.com/open-telemetry/opentelemetry-specification/tree/master/specification/resource/semantic_conventions
//!
//! | OpenTelemetry attribute key                    | Application Insights field     |
//! | ---------------------------------------------- | ------------------------------ |
//! | `service.version`                              | Context: Application version   |
//! | `enduser.id`                                   | Context: Authenticated user id |
//! | `service.namespace` + `service.name`           | Context: Cloud role            |
//! | `service.instance.id`                          | Context: Cloud role instance   |
//! | `telemetry.sdk.name` + `telemetry.sdk.version` | Context: Internal SDK version  |
//! | `http.url`                                     | Dependency Data                |
//! | `db.statement`                                 | Dependency Data                |
//! | `http.host`                                    | Dependency Target              |
//! | `net.peer.name` + `net.peer.port`              | Dependency Target              |
//! | `net.peer.ip` + `net.peer.port`                | Dependency Target              |
//! | `db.name`                                      | Dependency Target              |
//! | `http.status_code`                             | Dependency Result code         |
//! | `db.system`                                    | Dependency Type                |
//! | `messaging.system`                             | Dependency Type                |
//! | `rpc.system`                                   | Dependency Type                |
//! | `"HTTP"` if any `http.` attribute exists       | Dependency Type                |
//! | `"DB"` if any `db.` attribute exists           | Dependency Type                |
//! | `http.url`                                     | Request Url                    |
//! | `http.scheme` + `http.host` + `http.target`    | Request Url                    |
//! | `http.client_ip`                               | Request Source                 |
//! | `net.peer.ip`                                  | Request Source                 |
//! | `http.status_code`                             | Request Response code          |
//!
//! All other attributes are directly converted to custom properties.
//!
//! For Requests the attributes `http.method` and `http.route` override the Name.
//!
//! ## Events
//!
//! Events are converted into Exception telemetry if the event name equals `"exception"` (see
//! OpenTelemetry semantic conventions for [exceptions]) with the following mapping:
//!
//! | OpenTelemetry attribute key | Application Insights field |
//! | --------------------------- | -------------------------- |
//! | `exception.type`            | Exception type             |
//! | `exception.message`         | Exception message          |
//! | `exception.stacktrace`      | Exception call stack       |
//!
//! All other events are converted into Trace telemetry.
//!
//! All other attributes are directly converted to custom properties.
//!
//! [exceptions]: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/exceptions.md
#![doc(html_root_url = "https://docs.rs/opentelemetry-application-insights/0.5.0")]
#![deny(missing_docs, unreachable_pub, missing_debug_implementations)]
#![cfg_attr(test, deny(warnings))]

mod convert;
mod http_client;
mod models;
mod tags;
mod uploader;

use async_trait::async_trait;
use convert::{attrs_to_properties, duration_to_string, span_id_to_string, time_to_string};
pub use http_client::HttpClient;
use models::{
    Data, Envelope, ExceptionData, ExceptionDetails, MessageData, RemoteDependencyData,
    RequestData, Sanitize,
};
use opentelemetry::api::{
    trace::{Event, SpanKind, StatusCode, TracerProvider},
    Key, Value,
};
use opentelemetry::exporter::trace::{ExportResult, SpanData, SpanExporter};
use opentelemetry::global;
use opentelemetry::sdk;
use opentelemetry_semantic_conventions as semcov;
use std::collections::{BTreeMap, HashMap};
use tags::{get_tags_for_event, get_tags_for_span};

/// Create a new Application Insights exporter pipeline builder
pub fn new_pipeline(instrumentation_key: String) -> PipelineBuilder<()> {
    PipelineBuilder {
        client: (),
        config: None,
        instrumentation_key,
        sample_rate: 100.0,
    }
}

/// Application Insights exporter pipeline builder
#[derive(Debug)]
pub struct PipelineBuilder<C> {
    client: C,
    config: Option<sdk::trace::Config>,
    instrumentation_key: String,
    sample_rate: f64,
}

impl<C> PipelineBuilder<C> {
    /// Set HTTP client, which the exporter will use to send telemetry to Application Insights.
    ///
    /// Use this to set an HTTP client which fits your async runtime.
    pub fn with_client<NC>(self, client: NC) -> PipelineBuilder<NC> {
        PipelineBuilder {
            client,
            config: self.config,
            instrumentation_key: self.instrumentation_key,
            sample_rate: self.sample_rate,
        }
    }

    /// Set sample rate, which is passed through to Application Insights. It should be a value
    /// between 0 and 1 and match the rate given to the sampler.
    ///
    /// Default: 1.0
    ///
    /// Note: This example requires [`reqwest`] and the **reqwest-client-blocking** feature.
    ///
    /// [`reqwest`]: https://crates.io/crates/reqwest
    ///
    /// ```no_run
    /// let sample_rate = 0.3;
    /// let (tracer, _uninstall) = opentelemetry_application_insights::new_pipeline("...".into())
    ///     .with_client(reqwest::blocking::Client::new())
    ///     .with_sample_rate(sample_rate)
    ///     .install();
    /// ```
    pub fn with_sample_rate(mut self, sample_rate: f64) -> Self {
        // Application Insights expects the sample rate as a percentage.
        self.sample_rate = sample_rate * 100.0;
        self
    }

    /// Assign the SDK config for the exporter pipeline.
    ///
    /// Note: This example requires [`reqwest`] and the **reqwest-client-blocking** feature.
    ///
    /// [`reqwest`]: https://crates.io/crates/reqwest
    ///
    /// ```no_run
    /// # use opentelemetry::{api::KeyValue, sdk};
    /// # use std::sync::Arc;
    /// let (tracer, _uninstall) = opentelemetry_application_insights::new_pipeline("...".into())
    ///     .with_client(reqwest::blocking::Client::new())
    ///     .with_trace_config(sdk::trace::Config {
    ///         resource: Arc::new(sdk::Resource::new(vec![
    ///             KeyValue::new("service.name", "my-application"),
    ///         ])),
    ///         ..Default::default()
    ///     })
    ///     .install();
    /// ```
    pub fn with_trace_config(self, config: sdk::trace::Config) -> Self {
        PipelineBuilder {
            config: Some(config),
            ..self
        }
    }
}

impl<C> PipelineBuilder<C>
where
    C: HttpClient + 'static,
{
    /// Build a configured `TracerProvider` with the recommended defaults.
    ///
    /// This will automatically configure an asynchronous batch exporter if you enable either the
    /// **async-std** or **tokio** feature for the `opentelemetry` crate. Otherwise spans will be
    /// exported synchronously.
    pub fn build(mut self) -> sdk::trace::TracerProvider {
        let config = self.config.take();
        let exporter =
            Exporter::new(self.instrumentation_key, self.client).with_sample_rate(self.sample_rate);

        let mut builder = sdk::trace::TracerProvider::builder().with_exporter(exporter);
        if let Some(config) = config {
            builder = builder.with_config(config);
        }

        builder.build()
    }

    /// Install an Application Insights pipeline with the recommended defaults.
    ///
    /// This registers a global `TracerProvider`. See the `build` function for details about how
    /// this provider is configured.
    pub fn install(self) -> (sdk::trace::Tracer, Uninstall) {
        let trace_provider = self.build();
        let tracer = trace_provider.get_tracer(
            "opentelemetry-application-insights",
            Some(env!("CARGO_PKG_VERSION")),
        );

        let provider_guard = global::set_tracer_provider(trace_provider);

        (tracer, Uninstall(provider_guard))
    }
}

/// Guard that uninstalls the Application Insights trace pipeline when dropped
#[derive(Debug)]
pub struct Uninstall(global::TracerProviderGuard);

/// Application Insights span exporter
#[derive(Debug)]
pub struct Exporter<C> {
    client: C,
    instrumentation_key: String,
    sample_rate: f64,
}

impl<C> Exporter<C> {
    /// Create a new exporter.
    pub fn new(instrumentation_key: String, client: C) -> Self {
        Self {
            client,
            instrumentation_key,
            sample_rate: 100.0,
        }
    }

    /// Set sample rate, which is passed through to Application Insights. It should be a value
    /// between 0 and 1 and match the rate given to the sampler.
    ///
    /// Default: 1.0
    pub fn with_sample_rate(mut self, sample_rate: f64) -> Self {
        // Application Insights expects the sample rate as a percentage.
        self.sample_rate = sample_rate * 100.0;
        self
    }

    fn create_envelopes(&self, span: SpanData) -> Vec<Envelope> {
        let mut result = Vec::with_capacity(1 + span.message_events.len());

        let (data, tags, name) = match span.span_kind {
            SpanKind::Server | SpanKind::Consumer => {
                let data: RequestData = (&span).into();
                let tags = get_tags_for_span(&span);
                (
                    Data::Request(data),
                    tags,
                    "Microsoft.ApplicationInsights.Request",
                )
            }
            SpanKind::Client | SpanKind::Producer | SpanKind::Internal => {
                let data: RemoteDependencyData = (&span).into();
                let tags = get_tags_for_span(&span);
                (
                    Data::RemoteDependency(data),
                    tags,
                    "Microsoft.ApplicationInsights.RemoteDependency",
                )
            }
        };
        result.push(Envelope {
            name: name.into(),
            time: time_to_string(span.start_time),
            sample_rate: Some(self.sample_rate),
            i_key: Some(self.instrumentation_key.clone()),
            tags: Some(tags),
            data: Some(data),
        });

        for event in span.message_events.iter() {
            let (data, name) = match event.name.as_ref() {
                "exception" => (
                    Data::Exception(event.into()),
                    "Microsoft.ApplicationInsights.Exception",
                ),
                _ => (
                    Data::Message(event.into()),
                    "Microsoft.ApplicationInsights.Message",
                ),
            };
            result.push(Envelope {
                name: name.into(),
                time: time_to_string(event.timestamp),
                sample_rate: Some(self.sample_rate),
                i_key: Some(self.instrumentation_key.clone()),
                tags: Some(get_tags_for_event(&span)),
                data: Some(data),
            });
        }

        result
    }
}

#[async_trait]
impl<C> SpanExporter for Exporter<C>
where
    C: HttpClient,
{
    /// Export spans to Application Insights
    async fn export(&self, batch: Vec<SpanData>) -> ExportResult {
        let mut envelopes: Vec<_> = batch
            .into_iter()
            .flat_map(|span| self.create_envelopes(span))
            .collect();
        for envelope in envelopes.iter_mut() {
            envelope.sanitize();
        }

        uploader::send(&self.client, envelopes).await
    }
}

impl From<&SpanData> for RequestData {
    fn from(span: &SpanData) -> RequestData {
        let mut data = RequestData {
            ver: 2,
            id: span_id_to_string(span.span_reference.span_id()),
            name: Some(span.name.clone()).filter(|x| !x.is_empty()),
            duration: duration_to_string(
                span.end_time
                    .duration_since(span.start_time)
                    .unwrap_or_default(),
            ),
            response_code: (span.status_code.clone() as i32).to_string(),
            success: span.status_code == StatusCode::OK,
            source: None,
            url: None,
            properties: attrs_to_properties(&span.attributes, span.resource.as_ref()),
        };

        if let Some(method) = span.attributes.get(&semcov::trace::HTTP_METHOD) {
            data.name = Some(
                if let Some(route) = span.attributes.get(&semcov::trace::HTTP_ROUTE) {
                    format!("{} {}", String::from(method), String::from(route))
                } else {
                    String::from(method)
                },
            );
        }

        if let Some(status_code) = span.attributes.get(&semcov::trace::HTTP_STATUS_CODE) {
            data.response_code = String::from(status_code);
        }

        if let Some(url) = span.attributes.get(&semcov::trace::HTTP_URL) {
            data.url = Some(String::from(url));
        } else if let Some(target) = span.attributes.get(&semcov::trace::HTTP_TARGET) {
            let mut target = String::from(target);
            if !target.starts_with('/') {
                target.insert(0, '/');
            }

            if let Some((scheme, host)) = opt_zip(
                span.attributes.get(&semcov::trace::HTTP_SCHEME),
                span.attributes.get(&semcov::trace::HTTP_HOST),
            ) {
                data.url = Some(format!(
                    "{}://{}{}",
                    String::from(scheme),
                    String::from(host),
                    target
                ));
            } else {
                data.url = Some(target);
            }
        }

        if let Some(client_ip) = span.attributes.get(&semcov::trace::HTTP_CLIENT_IP) {
            data.source = Some(String::from(client_ip));
        } else if let Some(peer_ip) = span.attributes.get(&semcov::trace::NET_PEER_IP) {
            data.source = Some(String::from(peer_ip));
        }

        data
    }
}

impl From<&SpanData> for RemoteDependencyData {
    fn from(span: &SpanData) -> RemoteDependencyData {
        let mut data = RemoteDependencyData {
            ver: 2,
            id: Some(span_id_to_string(span.span_reference.span_id())),
            name: span.name.clone(),
            duration: duration_to_string(
                span.end_time
                    .duration_since(span.start_time)
                    .unwrap_or_default(),
            ),
            result_code: Some((span.status_code.clone() as i32).to_string()),
            success: Some(span.status_code == StatusCode::OK),
            data: None,
            target: None,
            type_: None,
            properties: attrs_to_properties(&span.attributes, span.resource.as_ref()),
        };

        if let Some(status_code) = span.attributes.get(&semcov::trace::HTTP_STATUS_CODE) {
            data.result_code = Some(String::from(status_code));
        }

        if let Some(url) = span.attributes.get(&semcov::trace::HTTP_URL) {
            data.data = Some(String::from(url));
        } else if let Some(statement) = span.attributes.get(&semcov::trace::DB_STATEMENT) {
            data.data = Some(String::from(statement));
        }

        if let Some(host) = span.attributes.get(&semcov::trace::HTTP_HOST) {
            data.target = Some(String::from(host));
        } else if let Some(peer_name) = span.attributes.get(&semcov::trace::NET_PEER_NAME) {
            if let Some(peer_port) = span.attributes.get(&semcov::trace::NET_PEER_PORT) {
                data.target = Some(format!(
                    "{}:{}",
                    String::from(peer_name),
                    String::from(peer_port)
                ));
            } else {
                data.target = Some(String::from(peer_name));
            }
        } else if let Some(peer_ip) = span.attributes.get(&semcov::trace::NET_PEER_IP) {
            if let Some(peer_port) = span.attributes.get(&semcov::trace::NET_PEER_PORT) {
                data.target = Some(format!(
                    "{}:{}",
                    String::from(peer_ip),
                    String::from(peer_port)
                ));
            } else {
                data.target = Some(String::from(peer_ip));
            }
        } else if let Some(db_name) = span.attributes.get(&semcov::trace::DB_NAME) {
            data.target = Some(String::from(db_name));
        }

        if span.span_kind == SpanKind::Internal {
            data.type_ = Some("InProc".into());
            data.success = Some(true);
        } else if let Some(db_system) = span.attributes.get(&semcov::trace::DB_SYSTEM) {
            data.type_ = Some(String::from(db_system));
        } else if let Some(messaging_system) = span.attributes.get(&semcov::trace::MESSAGING_SYSTEM)
        {
            data.type_ = Some(String::from(messaging_system));
        } else if let Some(rpc_system) = span.attributes.get(&semcov::trace::RPC_SYSTEM) {
            data.type_ = Some(String::from(rpc_system));
        } else if let Some(ref properties) = data.properties {
            if properties.keys().any(|x| x.starts_with("http.")) {
                data.type_ = Some("HTTP".into());
            } else if properties.keys().any(|x| x.starts_with("db.")) {
                data.type_ = Some("DB".into());
            }
        }

        data
    }
}

impl From<&Event> for ExceptionData {
    fn from(event: &Event) -> ExceptionData {
        let mut attrs: HashMap<&Key, &Value> = event
            .attributes
            .iter()
            .map(|kv| (&kv.key, &kv.value))
            .collect();
        let exception = ExceptionDetails {
            type_name: attrs
                .remove(&semcov::trace::EXCEPTION_TYPE)
                .map(String::from)
                .unwrap_or_else(|| "<no type>".into()),
            message: attrs
                .remove(&semcov::trace::EXCEPTION_MESSAGE)
                .map(String::from)
                .unwrap_or_else(|| "<no message>".into()),
            stack: attrs
                .remove(&semcov::trace::EXCEPTION_STACKTRACE)
                .map(String::from),
        };
        ExceptionData {
            ver: 2,
            exceptions: vec![exception],
            properties: Some(
                attrs
                    .iter()
                    .map(|(k, v)| (k.as_str().to_string(), String::from(*v)))
                    .collect(),
            )
            .filter(|x: &BTreeMap<String, String>| !x.is_empty()),
        }
    }
}

impl From<&Event> for MessageData {
    fn from(event: &Event) -> MessageData {
        MessageData {
            ver: 2,
            message: if event.name.is_empty() {
                "<no message>".into()
            } else {
                event.name.clone()
            },
            properties: Some(
                event
                    .attributes
                    .iter()
                    .map(|kv| (kv.key.as_str().to_string(), String::from(&kv.value)))
                    .collect(),
            )
            .filter(|x: &BTreeMap<String, String>| !x.is_empty()),
        }
    }
}

fn opt_zip<T1, T2>(o1: Option<T1>, o2: Option<T2>) -> Option<(T1, T2)> {
    match (o1, o2) {
        (Some(v1), Some(v2)) => Some((v1, v2)),
        _ => None,
    }
}