Unverified Commit 2ad93490 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

Improve common errors in turbo-trace-server (#100862)

More than once i have been blocked by the the vscode sandbox when
attempting to read a trace file, now we print the PermissionDenied error
so this is easier to diagnose

a client disconnect also gets a simpler error message, these are not a
big deal
parent fc5ebd29
...@@ -8,6 +8,7 @@ use std::{ ...@@ -8,6 +8,7 @@ use std::{
env, env,
fs::{self, File, Metadata}, fs::{self, File, Metadata},
io::{self, BufReader, Read, Seek, SeekFrom, Write}, io::{self, BufReader, Read, Seek, SeekFrom, Write},
ops::ControlFlow,
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::Arc, sync::Arc,
thread::{self, JoinHandle}, thread::{self, JoinHandle},
...@@ -216,12 +217,35 @@ impl TraceReader { ...@@ -216,12 +217,35 @@ impl TraceReader {
} }
pub fn run(&mut self) { pub fn run(&mut self) {
let mut file_warning_printed = false; // Failures are retried every 500ms, so only report when the error changes
let mut last_open_error = None;
let mut last_read_error = None;
loop { loop {
let read_success = self.try_read(); match File::open(&self.path) {
if !file_warning_printed && !read_success { Ok(file) => {
println!("Unable to read trace file at {:?}, waiting...", self.path); last_open_error = None;
file_warning_printed = true; match self.try_read(file) {
Ok(()) => last_read_error = None,
Err(err) => {
if last_read_error != Some(err.kind()) {
println!(
"Unable to read trace file at {:?}: {err}, waiting...",
self.path
);
last_read_error = Some(err.kind());
}
}
}
}
Err(err) => {
if last_open_error != Some(err.kind()) {
println!(
"Unable to open trace file at {:?}: {err}, waiting...",
self.path
);
last_open_error = Some(err.kind());
}
}
} }
thread::sleep(Duration::from_millis(500)); thread::sleep(Duration::from_millis(500));
} }
...@@ -266,10 +290,9 @@ impl TraceReader { ...@@ -266,10 +290,9 @@ impl TraceReader {
}) })
} }
fn try_read(&mut self) -> bool { /// Reads the trace file until it is replaced or removed. Returns an error if the file couldn't
let Ok(mut file) = File::open(&self.path) else { /// be read.
return false; fn try_read(&mut self, mut file: File) -> io::Result<()> {
};
println!("Trace file opened"); println!("Trace file opened");
let stop_at = env::var("STOP_AT") let stop_at = env::var("STOP_AT")
.unwrap_or_default() .unwrap_or_default()
...@@ -291,16 +314,8 @@ impl TraceReader { ...@@ -291,16 +314,8 @@ impl TraceReader {
.seek(SeekFrom::End(0)) .seek(SeekFrom::End(0))
.ok() .ok()
.map(|total| (total, Instant::now())); .map(|total| (total, Instant::now()));
if file.seek(SeekFrom::Start(0)).is_err() { file.seek(SeekFrom::Start(0))?;
return false; let mut file = self.trace_file_from_file(file)?;
}
let mut file = match self.trace_file_from_file(file) {
Ok(f) => f,
Err(err) => {
println!("Error opening trace file for reading: {err}");
return false;
}
};
let mut buffer = Vec::new(); let mut buffer = Vec::new();
let mut index = 0; let mut index = 0;
...@@ -311,12 +326,15 @@ impl TraceReader { ...@@ -311,12 +326,15 @@ impl TraceReader {
Ok(bytes_read) => { Ok(bytes_read) => {
if bytes_read == 0 { if bytes_read == 0 {
self.store.write().optimize(); self.store.write().optimize();
if let Some(value) = self.wait_for_more_data( if self
.wait_for_more_data(
&mut file, &mut file,
&mut initial_read, &mut initial_read,
format.as_ref().map(|(f, _)| f), format.as_ref().map(|(f, _)| f),
) { )
return value; .is_break()
{
return Ok(());
} }
} else { } else {
// If we have partially consumed some data, and we are at buffer capacity, // If we have partially consumed some data, and we are at buffer capacity,
...@@ -332,9 +350,9 @@ impl TraceReader { ...@@ -332,9 +350,9 @@ impl TraceReader {
// Not enough data yet // Not enough data yet
Ok(None) => continue, Ok(None) => continue,
Err(err) => { Err(err) => {
println!("Trace file error: {err}"); println!("Trace file error: {err:?}");
self.wait_for_file_change(&file); self.wait_for_file_change(&file);
return true; return Ok(());
} }
}; };
let erased_format = match kind { let erased_format = match kind {
...@@ -360,9 +378,9 @@ impl TraceReader { ...@@ -360,9 +378,9 @@ impl TraceReader {
index += bytes_read; index += bytes_read;
} }
Err(err) => { Err(err) => {
println!("Trace file error: {err}"); println!("Trace file error: {err:?}");
self.wait_for_file_change(&file); self.wait_for_file_change(&file);
return true; return Ok(());
} }
} }
if self.store.want_to_read() { if self.store.want_to_read() {
...@@ -411,7 +429,7 @@ impl TraceReader { ...@@ -411,7 +429,7 @@ impl TraceReader {
Waiting for new file..." Waiting for new file..."
); );
self.wait_for_new_file(&mut file); self.wait_for_new_file(&mut file);
return true; return Ok(());
} }
} }
} }
...@@ -421,31 +439,35 @@ impl TraceReader { ...@@ -421,31 +439,35 @@ impl TraceReader {
|| err.kind() == io::ErrorKind::InvalidInput || err.kind() == io::ErrorKind::InvalidInput
{ {
self.store.write().optimize(); self.store.write().optimize();
if let Some(value) = self.wait_for_more_data( if self
.wait_for_more_data(
&mut file, &mut file,
&mut initial_read, &mut initial_read,
format.as_ref().map(|(f, _)| f), format.as_ref().map(|(f, _)| f),
) { )
return value; .is_break()
{
return Ok(());
} }
} else { } else {
// Error reading file, maybe it was removed // Error reading file, maybe it was removed
println!("Error reading trace file: {err:?}"); return Err(err);
return true;
} }
} }
} }
} }
} }
/// Waits until the file has more data ([`ControlFlow::Continue`]) or was replaced or removed
/// ([`ControlFlow::Break`]).
fn wait_for_more_data( fn wait_for_more_data(
&mut self, &mut self,
file: &mut TraceFile, file: &mut TraceFile,
initial_read: &mut Option<(u64, Instant)>, initial_read: &mut Option<(u64, Instant)>,
format: Option<&ErasedTraceFormat>, format: Option<&ErasedTraceFormat>,
) -> Option<bool> { ) -> ControlFlow<()> {
let Ok(pos) = file.stream_position() else { let Ok(pos) = file.stream_position() else {
return Some(true); return ControlFlow::Break(());
}; };
if let Some((total, start)) = initial_read.take() { if let Some((total, start)) = initial_read.take() {
// Erase the in-place progress line (printed with a leading `\r` and // Erase the in-place progress line (printed with a leading `\r` and
...@@ -470,17 +492,17 @@ impl TraceReader { ...@@ -470,17 +492,17 @@ impl TraceReader {
// No more data to read, sleep for a while to wait for more data // No more data to read, sleep for a while to wait for more data
thread::sleep(Duration::from_millis(100)); thread::sleep(Duration::from_millis(100));
let Ok(mut real_file) = File::open(&self.path) else { let Ok(mut real_file) = File::open(&self.path) else {
return Some(true); return ControlFlow::Break(());
}; };
let Ok(end) = real_file.seek(SeekFrom::End(0)) else { let Ok(end) = real_file.seek(SeekFrom::End(0)) else {
return Some(true); return ControlFlow::Break(());
}; };
if end < pos { if end < pos {
// new file // new file
return Some(true); return ControlFlow::Break(());
} else if end != pos { } else if end != pos {
// file has more data // file has more data
return None; return ControlFlow::Continue(());
} }
} }
} }
...@@ -600,7 +622,7 @@ mod tests { ...@@ -600,7 +622,7 @@ mod tests {
dir: PathBuf, dir: PathBuf,
path: PathBuf, path: PathBuf,
store: Arc<StoreContainer>, store: Arc<StoreContainer>,
thread: Option<JoinHandle<bool>>, thread: Option<JoinHandle<io::Result<()>>>,
} }
impl ReaderFixture { impl ReaderFixture {
...@@ -615,7 +637,8 @@ mod tests { ...@@ -615,7 +637,8 @@ mod tests {
store: store.clone(), store: store.clone(),
path: path.clone(), path: path.clone(),
}; };
let thread = thread::spawn(move || reader.try_read()); let file = File::open(&path).unwrap();
let thread = thread::spawn(move || reader.try_read(file));
Self { Self {
dir, dir,
path, path,
...@@ -638,12 +661,13 @@ mod tests { ...@@ -638,12 +661,13 @@ mod tests {
assert!(start.elapsed() < TIMEOUT, "reader did not return"); assert!(start.elapsed() < TIMEOUT, "reader did not return");
thread::sleep(Duration::from_millis(20)); thread::sleep(Duration::from_millis(20));
} }
self.thread.take().unwrap().join().unwrap(); self.thread.take().unwrap().join().unwrap().unwrap();
let mut reader = TraceReader { let mut reader = TraceReader {
store: self.store.clone(), store: self.store.clone(),
path: self.path.clone(), path: self.path.clone(),
}; };
self.thread = Some(thread::spawn(move || reader.try_read())); let file = File::open(&self.path).unwrap();
self.thread = Some(thread::spawn(move || reader.try_read(file)));
} }
fn append(&self, data: &[u8]) { fn append(&self, data: &[u8]) {
...@@ -679,7 +703,9 @@ mod tests { ...@@ -679,7 +703,9 @@ mod tests {
if let Some(thread) = self.thread.take() { if let Some(thread) = self.thread.take() {
let result = thread.join(); let result = thread.join();
if !thread::panicking() { if !thread::panicking() {
result.expect("reader thread panicked"); result
.expect("reader thread panicked")
.expect("reader failed");
} }
} }
let _ = std::fs::remove_dir_all(&self.dir); let _ = std::fs::remove_dir_all(&self.dir);
......
use std::{ use std::{
io,
net::{SocketAddr, SocketAddrV4, TcpListener, TcpStream}, net::{SocketAddr, SocketAddrV4, TcpListener, TcpStream},
sync::{Arc, Mutex}, sync::{Arc, Mutex},
thread::spawn, thread::spawn,
...@@ -6,7 +7,7 @@ use std::{ ...@@ -6,7 +7,7 @@ use std::{
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tungstenite::{Message, accept}; use tungstenite::{Message, accept, error::ProtocolError};
use crate::{ use crate::{
store::SpanId, store::SpanId,
...@@ -124,13 +125,39 @@ pub fn serve(store: Arc<StoreContainer>, port: u16) { ...@@ -124,13 +125,39 @@ pub fn serve(store: Arc<StoreContainer>, port: u16) {
spawn(move || { spawn(move || {
let websocket = accept(stream.unwrap()).unwrap(); let websocket = accept(stream.unwrap()).unwrap();
if let Err(err) = handle_connection(websocket, store) { match handle_connection(websocket, store) {
Ok(()) => {}
Err(err) if is_disconnect(&err) => {
println!("Trace viewer disconnected");
}
Err(err) => {
eprintln!("Error: {err:?}"); eprintln!("Error: {err:?}");
} }
}
}); });
} }
} }
/// Whether the error is caused by the client going away without a clean close handshake, e.g.
/// when the trace viewer tab is closed or reloaded while an update is being sent.
fn is_disconnect(err: &anyhow::Error) -> bool {
match err.downcast_ref::<tungstenite::Error>() {
Some(
tungstenite::Error::ConnectionClosed
| tungstenite::Error::AlreadyClosed
| tungstenite::Error::Protocol(ProtocolError::ResetWithoutClosingHandshake),
) => true,
Some(tungstenite::Error::Io(err)) => matches!(
err.kind(),
io::ErrorKind::ConnectionReset
| io::ErrorKind::ConnectionAborted
| io::ErrorKind::BrokenPipe
| io::ErrorKind::UnexpectedEof
),
_ => false,
}
}
fn handle_connection( fn handle_connection(
mut websocket: tungstenite::WebSocket<TcpStream>, mut websocket: tungstenite::WebSocket<TcpStream>,
store: Arc<StoreContainer>, store: Arc<StoreContainer>,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment