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
#![warn(clippy::or_fun_call)]
26
#![deny(clippy::print_stderr)]
27
#![deny(clippy::print_stdout)]
28
#![warn(clippy::rc_buffer)]
29
#![deny(clippy::ref_option_ref)]
30
#![warn(clippy::semicolon_if_nothing_returned)]
31
#![warn(clippy::trait_duplication_in_bounds)]
32
#![deny(clippy::unchecked_time_subtraction)]
33
#![deny(clippy::unnecessary_wraps)]
34
#![warn(clippy::unseparated_literal_suffix)]
35
#![deny(clippy::unwrap_used)]
36
#![deny(clippy::mod_module_files)]
37
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
38
#![allow(clippy::uninlined_format_args)]
39
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
40
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
41
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
42
#![allow(clippy::needless_lifetimes)] // See arti#1765
43
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
44
#![allow(clippy::collapsible_if)] // See arti#2342
45
#![deny(clippy::unused_async)]
46
#![deny(clippy::string_slice)] // See arti#2571
47
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
48
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
49

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

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

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

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

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

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

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

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

            
114
            Ok(())
115
        }))
116
    }
117

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

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

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