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
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
47

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

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

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

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

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

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

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

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

            
112
            Ok(())
113
        }))
114
    }
115

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

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

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