1
// @@ begin lint list maintained by maint/add_warning @@
2
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
3
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
4
#![warn(missing_docs)]
5
#![warn(noop_method_call)]
6
#![warn(unreachable_pub)]
7
#![warn(clippy::all)]
8
#![deny(clippy::await_holding_lock)]
9
#![deny(clippy::cargo_common_metadata)]
10
#![deny(clippy::cast_lossless)]
11
#![deny(clippy::checked_conversions)]
12
#![allow(clippy::cognitive_complexity)] // See arti#2556
13
#![deny(clippy::debug_assert_with_mut_call)]
14
#![deny(clippy::exhaustive_enums)]
15
#![deny(clippy::exhaustive_structs)]
16
#![deny(clippy::expl_impl_clone_on_copy)]
17
#![deny(clippy::fallible_impl_from)]
18
#![deny(clippy::implicit_clone)]
19
#![deny(clippy::large_stack_arrays)]
20
#![warn(clippy::manual_ok_or)]
21
#![deny(clippy::missing_docs_in_private_items)]
22
#![warn(clippy::needless_borrow)]
23
#![warn(clippy::needless_pass_by_value)]
24
#![warn(clippy::option_option)]
25
#![deny(clippy::print_stderr)]
26
#![deny(clippy::print_stdout)]
27
#![warn(clippy::rc_buffer)]
28
#![deny(clippy::ref_option_ref)]
29
#![warn(clippy::semicolon_if_nothing_returned)]
30
#![warn(clippy::trait_duplication_in_bounds)]
31
#![deny(clippy::unchecked_time_subtraction)]
32
#![deny(clippy::unnecessary_wraps)]
33
#![warn(clippy::unseparated_literal_suffix)]
34
#![deny(clippy::unwrap_used)]
35
#![deny(clippy::mod_module_files)]
36
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
37
#![allow(clippy::uninlined_format_args)]
38
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
39
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
40
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
41
#![allow(clippy::needless_lifetimes)] // See arti#1765
42
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
43
#![allow(clippy::collapsible_if)] // See arti#2342
44
#![deny(clippy::unused_async)]
45
#![deny(clippy::string_slice)] // See arti#2571
46
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
47
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
48

            
49
//! Tracing exporter to write spans to a file in the OTLP JSON format.
50

            
51
// TODO: If https://github.com/open-telemetry/opentelemetry-rust/issues/2602 gets fixed, we can
52
// replace this entire file with whatever upstream has for doing this.
53

            
54
use opentelemetry_proto::transform::common::tonic::ResourceAttributesWithSchema;
55
use opentelemetry_proto::transform::trace::tonic::group_spans_by_resource_and_scope;
56
use opentelemetry_sdk::{
57
    Resource,
58
    error::{OTelSdkError, OTelSdkResult},
59
    trace::SpanExporter,
60
};
61
use std::{
62
    fmt::Debug,
63
    io::{LineWriter, Write},
64
    sync::{Arc, Mutex},
65
};
66

            
67
/// Tracing exporter to write OTLP JSON to a file (or anything else that implements [`LineWriter`].
68
#[derive(Debug)]
69
pub struct FileExporter<W: Write + Send + Debug> {
70
    /// The [`LineWriter`] to write to.
71
    writer: Arc<Mutex<LineWriter<W>>>,
72
    /// The [`Resource`] to associate spans with.
73
    resource: Resource,
74
}
75

            
76
impl<W: Write + Send + Debug> FileExporter<W> {
77
    /// Create a new [`FileExporter`]
78
    pub fn new(writer: W, resource: Resource) -> Self {
79
        Self {
80
            writer: Arc::new(Mutex::new(LineWriter::new(writer))),
81
            resource,
82
        }
83
    }
84
}
85

            
86
// Note that OpenTelemetry can only represent events as children of spans, so this exporter only
87
// works on spans. If you want a event to be exported, you need to make sure it exists within some
88
// span.
89
impl<W: Write + Send + Debug> SpanExporter for FileExporter<W> {
90
    fn export(
91
        &self,
92
        batch: Vec<opentelemetry_sdk::trace::SpanData>,
93
    ) -> impl futures::Future<
94
        Output = std::result::Result<(), opentelemetry_sdk::error::OTelSdkError>,
95
    > + std::marker::Send {
96
        let resource = ResourceAttributesWithSchema::from(&self.resource);
97
        let data = group_spans_by_resource_and_scope(batch, &resource);
98
        let mut writer = self.writer.lock().expect("Lock poisoned");
99
        Box::pin(std::future::ready('write: {
100
            // See https://opentelemetry.io/docs/specs/otel/protocol/file-exporter/ for format
101

            
102
            if let Err(err) = serde_json::to_writer(
103
                writer.get_mut(),
104
                &serde_json::json!({"resourceSpans": data}),
105
            ) {
106
                break 'write Err(OTelSdkError::InternalFailure(err.to_string()));
107
            }
108

            
109
            if let Err(err) = writer.write(b"\n") {
110
                break 'write Err(OTelSdkError::InternalFailure(err.to_string()));
111
            }
112

            
113
            Ok(())
114
        }))
115
    }
116

            
117
    fn force_flush(&self) -> OTelSdkResult {
118
        let mut writer = self
119
            .writer
120
            .lock()
121
            .map_err(|e| OTelSdkError::InternalFailure(e.to_string()))?;
122

            
123
        writer
124
            .flush()
125
            .map_err(|e| OTelSdkError::InternalFailure(e.to_string()))
126
    }
127

            
128
    fn set_resource(&mut self, res: &opentelemetry_sdk::Resource) {
129
        self.resource = res.clone();
130
    }
131
}