Repository navigation
Expand file tree
/
Copy pathtelemetry.rs
More file actions
158 lines (143 loc) · 4.62 KB
/
Copy pathtelemetry.rs
File metadata and controls
158 lines (143 loc) · 4.62 KB
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
use super::logger::{error, log};
use anyhow::Result;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::skip_serializing_none;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use tempfile::Builder as TempfileBuilder;
pub struct Telemetry {
diagnostics_directory: PathBuf,
collected_messages: Mutex<Vec<TelemetryMessage>>,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Note,
Warning,
Error,
}
#[skip_serializing_none]
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TelemetryMessage {
timestamp: String,
source: TelemetrySource,
severity: Severity,
visibility: TelemetryVisibility,
plaintext_message: Option<String>,
attributes: Option<Value>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct TelemetrySource {
id: &'static str,
name: String,
extractor_name: &'static str,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TelemetryVisibility {
status_page: bool,
cli_summary_table: bool,
telemetry: bool,
}
impl TelemetryMessage {
pub fn new(severity: Severity, id: &'static str, name: impl Into<String>) -> TelemetryMessage {
TelemetryMessage {
timestamp: Utc::now().to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true),
source: TelemetrySource {
id,
name: name.into(),
extractor_name: "cpp",
},
severity,
visibility: TelemetryVisibility {
status_page: false,
cli_summary_table: false,
telemetry: true,
},
plaintext_message: None,
attributes: None,
}
}
#[must_use]
pub fn plaintext_message(mut self, plaintext_message: &str) -> TelemetryMessage {
self.plaintext_message = Some(plaintext_message.to_string());
self
}
#[must_use]
pub fn attributes(mut self, attributes: Value) -> TelemetryMessage {
self.attributes = Some(attributes);
self
}
}
impl Telemetry {
pub fn new(diagnostics_directory: String) -> Result<Telemetry> {
fs::create_dir_all(&diagnostics_directory)?;
Ok(Telemetry {
diagnostics_directory: PathBuf::from(diagnostics_directory),
collected_messages: Mutex::new(Vec::new()),
})
}
fn write_message_worker(&self, telemetry_message: &TelemetryMessage) -> std::io::Result<()> {
let time = Utc::now();
let time_usecs = time.timestamp_micros();
let pid = std::process::id();
let prefix = "standalone-extraction";
let mut tempfile = TempfileBuilder::new()
.prefix(prefix)
.suffix(".json.tmp")
.tempfile_in(&self.diagnostics_directory)?;
tempfile.write_all(serde_json::to_string(telemetry_message)?.as_bytes())?;
tempfile.flush()?;
let mut file_num = 0;
let mut file_path;
loop {
file_path = self
.diagnostics_directory
.join(format!("{prefix}.{pid}.{time_usecs}.{file_num}.json"));
if let Ok(false) = fs::exists(&file_path) {
break;
}
file_num += 1;
}
tempfile.persist_noclobber(file_path)?;
Ok(())
}
pub fn write_message(&self, telemetry_message: TelemetryMessage) {
// Write to individual file
let _ = self
.write_message_worker(&telemetry_message)
.inspect_err(|e| {
error!("Failed to write telemetry message: {e}");
});
// Collect the message for potential combined output
if let Ok(mut messages) = self.collected_messages.lock() {
messages.push(telemetry_message);
}
}
/// Writes all collected telemetry messages to a combined JSON file.
pub fn write_combined_to_file(&self, path: &Path) {
let messages = match self.collected_messages.lock() {
Ok(guard) => guard.clone(),
Err(e) => {
error!("Failed to lock telemetry messages: {e}");
return;
}
};
let json_str = match serde_json::to_string_pretty(&messages) {
Ok(s) => s,
Err(e) => {
error!("Failed to serialize telemetry messages: {e}");
return;
}
};
if let Err(e) = fs::write(path, json_str) {
error!("Failed to write combined telemetry file: {e}");
}
}
}