Repository navigation
fleet: record CLI invocations for quota analytics (#9373) #11817
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| //! Best-effort local record of fleet CLI invocations for quota analytics. | ||
|
|
||
| use fleet_config::Config; | ||
| use serde_json::json; | ||
| use std::io::Write; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::time::{SystemTime, UNIX_EPOCH}; | ||
|
|
||
| pub const SCHEMA: &str = "fleet-invocation/v1"; | ||
| const FILE: &str = "invocations.jsonl"; | ||
| const MAX_BYTES: u64 = 4 * 1024 * 1024; | ||
| const KEEP: usize = 4; | ||
|
|
||
| pub fn path() -> PathBuf { | ||
| std::env::var_os("FLEET_INVOCATION_LEDGER") | ||
| .map(PathBuf::from) | ||
| .unwrap_or_else(|| Config::state_dir().join(FILE)) | ||
| } | ||
|
|
||
| pub fn record( | ||
| invoked_as: &str, | ||
| args: &[String], | ||
| code: i32, | ||
| duration_ms: u128, | ||
| ) -> serde_json::Value { | ||
| let host = std::env::var("HOSTNAME").ok().filter(|s| !s.is_empty()); | ||
| let caller = [ | ||
| "FLEET_CALLER", | ||
| "OPENCODE_SESSION_ID", | ||
| "MCPX_SESSION_ID", | ||
| "FLEET_SESSION_ID", | ||
| "SYSTEMD_UNIT", | ||
| "CRON_JOB", | ||
| ] | ||
| .iter() | ||
| .find_map(|key| std::env::var(key).ok().filter(|s| !s.is_empty())); | ||
| // Only the leading positional words are recorded: the first flag | ||
| // ends them, so a flag's value (a token, a title, a path) never | ||
| // reaches the ledger. | ||
| let words: Vec<&str> = args | ||
| .iter() | ||
| .map(String::as_str) | ||
| .take_while(|arg| !arg.starts_with('-')) | ||
| .take(3) | ||
| .collect(); | ||
| let (command, subcommand, sub_subcommand) = match invoked_as { | ||
| "fleet" | "fleet-serve" | "fleet-connect" => ( | ||
| words.first().copied(), | ||
| words.get(1).copied(), | ||
| words.get(2).copied(), | ||
| ), | ||
| "repo-queue" => (Some("queue"), words.first().copied(), words.get(1).copied()), | ||
| other => (Some(other), words.get(1).copied(), words.get(2).copied()), | ||
| }; | ||
| json!({ | ||
| "schema": SCHEMA, | ||
| "at_unix_ms": SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0), | ||
| "invoked_as": invoked_as, | ||
| "command": command, | ||
| "subcommand": subcommand, | ||
| "sub_subcommand": sub_subcommand, | ||
| "exit_code": code, | ||
| "duration_ms": duration_ms, | ||
| "host": host, | ||
| "caller": caller, | ||
| }) | ||
| } | ||
|
|
||
| pub fn append(path: &Path, value: &serde_json::Value) -> std::io::Result<()> { | ||
| if let Some(parent) = path.parent() { | ||
| std::fs::create_dir_all(parent)?; | ||
| } | ||
| if path | ||
| .metadata() | ||
| .map(|m| m.len() >= MAX_BYTES) | ||
| .unwrap_or(false) | ||
| { | ||
| for i in (1..KEEP).rev() { | ||
| let from = rotated(path, i); | ||
| let to = rotated(path, i + 1); | ||
| if from.exists() { | ||
| let _ = std::fs::remove_file(&to); | ||
| if let Err(error) = std::fs::rename(from, to) { | ||
| if error.kind() != std::io::ErrorKind::NotFound { | ||
| return Err(error); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| let _ = std::fs::remove_file(rotated(path, 1)); | ||
| std::fs::rename(path, rotated(path, 1))?; | ||
| } | ||
| let mut file = std::fs::OpenOptions::new() | ||
| .create(true) | ||
| .append(true) | ||
| .open(path)?; | ||
| writeln!(file, "{value}") | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When multiple fleet processes finish concurrently, formatting Useful? React with 👍 / 👎. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Prevent a failed write from consuming the next record. If a write leaves an unterminated JSON prefix on disk, the next successful append extends the same line. The reader then discards both records as malformed. A write can make partial progress before returning an error. (doc.rust-lang.org) Under the writer lock, repair an unterminated tail before appending. Leave complete lines unchanged, and test an append that succeeds after a partial write.
|
||
| } | ||
|
|
||
| fn rotated(path: &Path, index: usize) -> PathBuf { | ||
| let mut name = path.file_name().unwrap_or_default().to_os_string(); | ||
| name.push(format!(".{index}")); | ||
| path.with_file_name(name) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn appends_versioned_records_and_rotates() { | ||
| let dir = std::env::temp_dir().join(format!("fleet-ledger-{}", std::process::id())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
|
Comment on lines
+112
to
+113
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use a unique temporary directory with automatic cleanup. The directory name depends only on the process ID. If an assertion fails, the test leaves the ledger and its rotated file behind. A later process that reuses the ID deletes that directory before the test. Use an exclusively created temporary directory with a cleanup guard. Based on learnings, isolate Rust filesystem fixtures and clean them up on failure.
|
||
| let path = dir.join(FILE); | ||
| append( | ||
| &path, | ||
| &record("fleet", &["queue".into(), "list".into()], 0, 4), | ||
| ) | ||
| .unwrap(); | ||
| assert_eq!( | ||
| serde_json::from_str::<serde_json::Value>(&std::fs::read_to_string(&path).unwrap()) | ||
| .unwrap()["schema"], | ||
| SCHEMA | ||
| ); | ||
| let flagged = record( | ||
| "fleet", | ||
| &["queue".into(), "--token".into(), "secret-value".into()], | ||
| 0, | ||
| 1, | ||
| ); | ||
| assert_eq!(flagged["command"], "queue"); | ||
| assert!(flagged["subcommand"].is_null()); | ||
| assert!(!flagged.to_string().contains("secret-value")); | ||
| std::fs::write(&path, vec![b'x'; MAX_BYTES as usize]).unwrap(); | ||
| append(&path, &record("fleet", &[], 2, 1)).unwrap(); | ||
| assert!(rotated(&path, 1).exists()); | ||
| assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 1); | ||
| let _ = std::fs::remove_dir_all(dir); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -51,6 +51,7 @@ mod gh; | |
| #[cfg(feature = "gh")] | ||
| mod gh_cache; | ||
| mod gh_closure; | ||
| mod invocation_ledger; | ||
|
|
||
| #[allow(dead_code)] | ||
| // the derivation runs in build.rs (which includes this module by path); the binary itself consumes only the baked FLEET_DERIVED_VERSION value, plus these unit tests | ||
|
|
@@ -1391,6 +1392,7 @@ fn restore_default_sigpipe() { | |
| fn restore_default_sigpipe() {} | ||
|
|
||
| fn main() { | ||
| let started = std::time::Instant::now(); | ||
| restore_default_sigpipe(); | ||
| let argv: Vec<String> = std::env::args().collect(); | ||
| let invoked_as = argv | ||
|
|
@@ -1407,40 +1409,46 @@ fn main() { | |
| // Config decides the disable table; a malformed config is a loud | ||
| // error on every path (a silently ignored disable would defeat | ||
| // the §7 incident lever). | ||
| let config = match fleet_config::Config::load() { | ||
| Ok(c) => c, | ||
| let code = match fleet_config::Config::load() { | ||
| Ok(config) => { | ||
| if invoked_as == "fleet" { | ||
| let surface = Surface::new(None, config); | ||
| run_root(&surface, &args, &invoked_as) | ||
| } else if let Some(variant) = Variant::from_invocation_name(&invoked_as) { | ||
| // Refinement A: the hyphenated name narrows (never widens). | ||
| let surface = Surface::new(Some(variant), config); | ||
| run_root(&surface, &args, &invoked_as) | ||
| } else if let Some(route) = alias_route(&invoked_as) { | ||
| let surface = Surface::new(None, config); | ||
| let d = domain(route.domain).expect("registry aliases route to real domains"); | ||
| let mut routed: Vec<String> = Vec::new(); | ||
| if let Some(implied) = route.implied_arg { | ||
| routed.push(implied.to_string()); | ||
| } | ||
| routed.extend(args.iter().cloned()); | ||
| run_domain(&surface, d, &routed, &invoked_as) | ||
| } else if is_known_invocation_name(&invoked_as) { | ||
| unreachable!("known names are handled above"); | ||
| } else { | ||
| eprintln!( | ||
| "fleet: invoked under unknown name '{invoked_as}'; expected 'fleet', a variant \ | ||
| name ('fleet-serve', 'fleet-connect'), or a known alias (repo-queue, queue-broker, \ | ||
| secrets-broker, laptop-agent, laptop-agent-broker, atlas-search)" | ||
| ); | ||
| EXIT_USAGE | ||
| } | ||
| } | ||
| Err(e) => { | ||
| eprintln!("{e}"); | ||
| std::process::exit(EXIT_USAGE); | ||
| } | ||
| }; | ||
|
|
||
| let code = if invoked_as == "fleet" { | ||
| let surface = Surface::new(None, config); | ||
| run_root(&surface, &args, &invoked_as) | ||
| } else if let Some(variant) = Variant::from_invocation_name(&invoked_as) { | ||
| // Refinement A: the hyphenated name narrows (never widens). | ||
| let surface = Surface::new(Some(variant), config); | ||
| run_root(&surface, &args, &invoked_as) | ||
| } else if let Some(route) = alias_route(&invoked_as) { | ||
| let surface = Surface::new(None, config); | ||
| let d = domain(route.domain).expect("registry aliases route to real domains"); | ||
| let mut routed: Vec<String> = Vec::new(); | ||
| if let Some(implied) = route.implied_arg { | ||
| routed.push(implied.to_string()); | ||
| EXIT_USAGE | ||
| } | ||
| routed.extend(args); | ||
| run_domain(&surface, d, &routed, &invoked_as) | ||
| } else if is_known_invocation_name(&invoked_as) { | ||
| unreachable!("known names are handled above"); | ||
| } else { | ||
| eprintln!( | ||
| "fleet: invoked under unknown name '{invoked_as}'; expected 'fleet', a variant \ | ||
| name ('fleet-serve', 'fleet-connect'), or a known alias (repo-queue, queue-broker, \ | ||
| secrets-broker, laptop-agent, laptop-agent-broker, atlas-search)" | ||
| ); | ||
| EXIT_USAGE | ||
| }; | ||
| // Telemetry is local, payload-free and best-effort: failure to write | ||
| // the ledger must never alter the command's result. | ||
| let _ = invocation_ledger::append( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Record Unix SSH invocations that replace the Fleet process. When If the ledger must report the final SSH status, collect it from a supervising process that preserves terminal and signal behavior. If a handoff record is sufficient for quota counts, record it before
|
||
| &invocation_ledger::path(), | ||
| &invocation_ledger::record(&invoked_as, &args, code, started.elapsed().as_millis()), | ||
| ); | ||
|
Comment on lines
+1448
to
+1451
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
For queue commands that terminate directly, this append is never reached: Useful? React with 👍 / 👎. |
||
| std::process::exit(code); | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| use std::fs; | ||
| use std::process::Command; | ||
|
|
||
| fn run_case(name: &str, args: &[&str], config: Option<&str>) -> (i32, serde_json::Value) { | ||
| let dir = | ||
| std::env::temp_dir().join(format!("fleet-entry-ledger-{}-{name}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
|
Comment on lines
+5
to
+8
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Clean up the subprocess fixtures when a test fails. If Fleet stops writing the ledger,
|
||
| let ledger = dir.join("invocations.jsonl"); | ||
| let mut command = Command::new(env!("CARGO_BIN_EXE_fleet")); | ||
| command.args(args).env("FLEET_INVOCATION_LEDGER", &ledger); | ||
| if let Some(config) = config { | ||
| let config_path = dir.join("config.toml"); | ||
| fs::write(&config_path, config).unwrap(); | ||
| command.env("FLEET_CONFIG", config_path); | ||
| } | ||
|
Comment on lines
+12
to
+16
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Set a known config for every test subprocess. The success and usage cases inherit
|
||
| let output = command.output().unwrap(); | ||
| let text = fs::read_to_string(&ledger).unwrap(); | ||
| let rows: Vec<serde_json::Value> = text | ||
| .lines() | ||
| .map(|line| serde_json::from_str(line).unwrap()) | ||
| .collect(); | ||
| let _ = fs::remove_dir_all(dir); | ||
| assert_eq!(rows.len(), 1, "one record for {name}"); | ||
| ( | ||
| output.status.code().unwrap_or(1), | ||
| rows.into_iter().next().unwrap(), | ||
| ) | ||
| } | ||
|
|
||
| #[test] | ||
| fn entry_path_records_success_usage_error_and_config_failure_once() { | ||
| let (code, row) = run_case("success", &["version"], None); | ||
| assert_eq!(code, 0); | ||
| assert_eq!(row["exit_code"], 0); | ||
|
|
||
| let (code, row) = run_case("usage", &["--not-a-fleet-command"], None); | ||
| assert_eq!(code, 2); | ||
| assert_eq!(row["exit_code"], 2); | ||
|
|
||
| let (code, row) = run_case("config-error", &["version"], Some("not = [valid toml")); | ||
| assert_eq!(code, 2); | ||
| assert_eq!(row["exit_code"], 2); | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Keep raw arguments and caller metadata out of payload-free telemetry.
recordcopies positional arguments without checking whether they are command names. Iffleet versionreceives an extra argument containing a credential-bearing URL, the command rejects it, but the ledger stores it assubcommand. If that label ranks in the top 12,/api/quota-analytics.jsonalso returns it.Record only recognized command labels. Use a fixed label for invalid input, and omit raw caller and session values unless the analytics needs a defined, non-sensitive classification. Based on learnings, check raw arguments for embedded credentials before writing them to a persistent sink.
Source: Learnings