main
Colby Knox 0.2.94: keep serving when tiny_http's accept loop stops; self-check ticker (#30) ed6e3ec
//! A step trace that outlives the process (adom/altium-bridge#30).
//!
//! On one machine the bridge died during `altium_agent_start` 266 times with nothing left behind: no panic (the hook
//! never ran), and ab rewrites the bridge's console log on every respawn. So every request and every step of the
//! agent lifecycle is appended here, beside the exe, as it happens. When the next process starts it reads the trace:
//! a request that began and never ended is where the last process died, and that goes into the crash log with the
//! steps before it.
use std::io::Write;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

const CAP: u64 = 1024 * 1024;
static NEXT_ID: AtomicU64 = AtomicU64::new(1);

pub fn path() -> std::path::PathBuf {
    std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_path_buf()))
        .unwrap_or_else(std::env::temp_dir).join("altium-bridge-trace.log")
}

fn now_ms() -> u128 {
    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0)
}

/// The address of a local: how deep this thread's stack is, to within a frame. Steps that walk down by megabytes are
/// recursion.
#[inline(never)]
fn stack_addr() -> usize {
    let x = 0u8;
    std::hint::black_box(&x) as *const u8 as usize
}

fn write_line(line: &str) {
    let p = path();
    if std::fs::metadata(&p).map(|m| m.len() > CAP).unwrap_or(false) {
        let _ = std::fs::rename(&p, p.with_extension("log.1"));
    }
    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&p) {
        let _ = f.write_all(line.as_bytes());
    }
}

/// One step: time, pid, thread, heal depth, stack address, what.
pub fn step(what: &str) {
    let t = std::thread::current();
    let line = format!("{} pid={} thread={}:{:?} heal={} sp={:#x} {}\n", now_ms(), std::process::id(),
        t.name().unwrap_or("?"), t.id(), crate::agent::heal_depth(), stack_addr(), what.replace('\n', " "));
    write_line(&line);
}

/// A request began: its id, to pair with `end`.
pub fn begin(verb: &str) -> u64 {
    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
    step(&format!("BEGIN #{id} {verb}"));
    id
}

pub fn end(id: u64, verb: &str, ms: u128, ok: Option<bool>) {
    step(&format!("END #{id} {verb} {ms}ms success={}", ok.map(|b| b.to_string()).unwrap_or_else(|| "?".into())));
}

/// What the previous process was doing when it ended, if it ended inside a request. Pure over the trace text.
pub fn unfinished(text: &str, this_pid: u32) -> Option<String> {
    let lines: Vec<&str> = text.lines().collect();
    let pid_of = |l: &str| l.split_whitespace().nth(1).and_then(|f| f.strip_prefix("pid=")).and_then(|p| p.parse::<u32>().ok());
    let last_pid = lines.iter().rev().filter_map(|l| pid_of(l)).find(|p| *p != this_pid)?;
    let mine: Vec<&str> = lines.iter().copied().filter(|l| pid_of(l) == Some(last_pid)).collect();
    let mut open: Vec<(String, String)> = Vec::new();
    for l in &mine {
        if let Some(i) = l.find("BEGIN #") {
            let rest = &l[i + 7..];
            let id = rest.split_whitespace().next().unwrap_or("").to_string();
            let verb = rest.split_whitespace().nth(1).unwrap_or("?").to_string();
            open.push((id, verb));
        } else if let Some(i) = l.find("END #") {
            let id = l[i + 5..].split_whitespace().next().unwrap_or("");
            open.retain(|(o, _)| o != id);
        }
    }
    if open.is_empty() {
        return None;
    }
    let verbs: Vec<String> = open.iter().map(|(id, v)| format!("#{id} {v}")).collect();
    let tail: Vec<&str> = mine.iter().rev().take(25).rev().copied().collect();
    Some(format!("the previous bridge process (pid {last_pid}) ended while running {}; its last steps:\n  {}",
        verbs.join(", "), tail.join("\n  ")))
}

/// At startup: name the request the previous process died in, if any.
pub fn previous_run_report() -> Option<String> {
    let p = path();
    let len = std::fs::metadata(&p).ok()?.len();
    let mut f = std::fs::File::open(&p).ok()?;
    use std::io::{Read, Seek, SeekFrom};
    let from = len.saturating_sub(256 * 1024);
    f.seek(SeekFrom::Start(from)).ok()?;
    let mut buf = Vec::new();
    f.read_to_end(&mut buf).ok()?;
    let text = String::from_utf8_lossy(&buf);
    unfinished(&text, std::process::id())
}

#[cfg(test)]
mod tests {
    use super::unfinished;

    #[test]
    fn self_probe_tells_answering_from_deaf() {
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let addr = server.server_addr().to_ip().unwrap();
        let t = std::thread::spawn(move || {
            let rq = server.recv().unwrap();
            let _ = rq.respond(tiny_http::Response::from_string("{}"));
            // the listener is dropped here, as when tiny_http's accept thread ends
        });
        assert!(super::self_probe(addr).is_ok());
        t.join().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(200));
        let e = super::self_probe(addr).unwrap_err();
        assert!(e.starts_with("connect") || e.starts_with("read") || e.starts_with("no HTTP"), "{e}");
        // and the same port can be listened on again (main does this when the accept loop stops)
        assert!(tiny_http::Server::http(addr).is_ok());
    }

    #[test]
    fn names_the_request_the_last_process_died_in() {
        let t = "1 pid=10 thread=a:ThreadId(2) heal=0 sp=0x1 BEGIN #1 altium_status\n\
                 2 pid=10 thread=a:ThreadId(2) heal=0 sp=0x1 END #1 altium_status 3ms success=true\n\
                 3 pid=10 thread=a:ThreadId(3) heal=0 sp=0x1 BEGIN #2 altium_agent_start\n\
                 4 pid=10 thread=a:ThreadId(3) heal=1 sp=0x1 start: enter\n";
        let r = unfinished(t, 99).unwrap();
        assert!(r.contains("pid 10") && r.contains("#2 altium_agent_start") && r.contains("start: enter"), "{r}");
        // every request finished: nothing to say
        let done = "1 pid=10 thread=a heal=0 sp=0x1 BEGIN #1 x\n2 pid=10 thread=a heal=0 sp=0x1 END #1 x 1ms success=true\n";
        assert!(unfinished(done, 99).is_none());
        // this process's own lines are not the previous one's
        assert!(unfinished("1 pid=99 thread=a heal=0 sp=0x1 BEGIN #1 x\n", 99).is_none());
    }
}

/// Ask our own port for /ping, the way ab reaches us. `Err` names what failed: a bridge that is alive but no longer
/// answers is a different fault from one that died, and only this can tell them apart from inside (#30).
pub fn self_probe(addr: std::net::SocketAddr) -> Result<u128, String> {
    use std::io::Read;
    use std::time::Duration;
    let t0 = std::time::Instant::now();
    let mut s = std::net::TcpStream::connect_timeout(&addr, Duration::from_secs(3)).map_err(|e| format!("connect: {e}"))?;
    let _ = s.set_read_timeout(Some(Duration::from_secs(5)));
    let _ = s.set_write_timeout(Some(Duration::from_secs(3)));
    s.write_all(b"GET /ping HTTP/1.0\r\nHost: localhost\r\n\r\n").map_err(|e| format!("write: {e}"))?;
    let mut buf = [0u8; 64];
    let n = s.read(&mut buf).map_err(|e| format!("read: {e}"))?;
    if n == 0 || !buf[..n].starts_with(b"HTTP/1.") { return Err(format!("no HTTP answer ({n} bytes)")); }
    Ok(t0.elapsed().as_millis())
}

/// Record that the process is alive, and whether it still answers on its own port: every 5 s for the first 5 minutes
/// (one machine lost its bridge 30 to 60 s after every start), then every minute. A failed probe is always written.
pub fn start_ticker(addr: std::net::SocketAddr) {
    let _ = std::thread::Builder::new().name("altium-trace-ticker".into()).spawn(move || {
        let born = std::time::Instant::now();
        let mut last_written = std::time::Instant::now();
        loop {
            let early = born.elapsed() < std::time::Duration::from_secs(300);
            std::thread::sleep(std::time::Duration::from_secs(if early { 5 } else { 60 }));
            let probe = self_probe(addr);
            let due = early || last_written.elapsed() >= std::time::Duration::from_secs(600);
            match probe {
                Ok(ms) if due => { step(&format!("tick {}s: answering on {addr} ({ms} ms)", born.elapsed().as_secs())); last_written = std::time::Instant::now(); }
                Ok(_) => {}
                Err(e) => {
                    let msg = format!("tick {}s: NOT answering on {addr}: {e}", born.elapsed().as_secs());
                    step(&msg);
                    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true)
                        .open(path().with_file_name("altium-bridge-crash.log")) {
                        let _ = f.write_all(format!("[{}] bridge pid {}: {msg}\n", now_ms() / 1000, std::process::id()).as_bytes());
                    }
                    last_written = std::time::Instant::now();
                }
            }
        }
    });
}