The best way to control Claude Code, Codex and more from any computer or phone
| 1 | use serde::{Deserialize, Serialize}; |
| 2 | use std::collections::{HashMap, HashSet, VecDeque}; |
| 3 | use std::io::{self, BufRead, BufWriter, Write}; |
| 4 | use std::sync::mpsc::{self, Receiver, RecvTimeoutError}; |
| 5 | use std::thread; |
| 6 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; |
| 7 | use sysinfo::{ |
| 8 | MINIMUM_CPU_UPDATE_INTERVAL, Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind, |
| 9 | }; |
| 10 | |
| 11 | const PROTOCOL_VERSION: u32 = 3; |
| 12 | const MIN_SAMPLE_INTERVAL_MS: u64 = 250; |
| 13 | const MAX_SAMPLE_INTERVAL_MS: u64 = 60_000; |
| 14 | const PROCESS_START_TIME_PRECISION_MS: u64 = 1_000; |
| 15 | const HISTORY_RETENTION_MS: u64 = 60 * 60_000; |
| 16 | const MAX_HISTORY_SNAPSHOTS: usize = 3_600; |
| 17 | const INPUT_QUEUE_CAPACITY: usize = 64; |
| 18 | const MAX_HISTORY_RETAINED_ENTRIES: usize = 20_000; |
| 19 | const MAX_HISTORY_RETAINED_BYTES: usize = 64 * 1024 * 1024; |
| 20 | const MAX_PROCESS_NAME_BYTES: usize = 1_024; |
| 21 | const MAX_PROCESS_COMMAND_BYTES: usize = 16 * 1_024; |
| 22 | const MAX_PROCESS_STATUS_BYTES: usize = 256; |
| 23 | const HISTORY_CHUNK_SNAPSHOTS: usize = 32; |
| 24 | const TWO_STAGE_PROCESS_REFRESH: bool = cfg!(any(target_os = "linux", target_os = "macos")); |
| 25 | |
| 26 | #[derive(Debug, Clone, Deserialize, Serialize)] |
| 27 | #[serde(rename_all = "camelCase")] |
| 28 | struct ExternalProcess { |
| 29 | pid: u32, |
| 30 | #[serde(default)] |
| 31 | start_time_ms: Option<u64>, |
| 32 | } |
| 33 | |
| 34 | impl ExternalProcess { |
| 35 | fn estimated_history_bytes(&self) -> usize { |
| 36 | std::mem::size_of::<Self>() |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | #[derive(Debug, Deserialize)] |
| 41 | #[serde( |
| 42 | tag = "type", |
| 43 | rename_all = "camelCase", |
| 44 | rename_all_fields = "camelCase" |
| 45 | )] |
| 46 | enum Command { |
| 47 | Configure { |
| 48 | version: u32, |
| 49 | root_pid: u32, |
| 50 | sample_interval_ms: u64, |
| 51 | #[serde(default)] |
| 52 | external_processes: Vec<ExternalProcess>, |
| 53 | }, |
| 54 | SetExternalProcesses { |
| 55 | version: u32, |
| 56 | processes: Vec<ExternalProcess>, |
| 57 | }, |
| 58 | SetSampleInterval { |
| 59 | version: u32, |
| 60 | sample_interval_ms: u64, |
| 61 | }, |
| 62 | SetStreaming { |
| 63 | version: u32, |
| 64 | enabled: bool, |
| 65 | }, |
| 66 | SampleNow { |
| 67 | version: u32, |
| 68 | request_id: String, |
| 69 | }, |
| 70 | ProcessTable { |
| 71 | version: u32, |
| 72 | request_id: String, |
| 73 | }, |
| 74 | ReadHistory { |
| 75 | version: u32, |
| 76 | request_id: String, |
| 77 | window_ms: u64, |
| 78 | }, |
| 79 | Shutdown { |
| 80 | version: u32, |
| 81 | }, |
| 82 | } |
| 83 | |
| 84 | impl Command { |
| 85 | fn version(&self) -> u32 { |
| 86 | match self { |
| 87 | Self::Configure { version, .. } |
| 88 | | Self::SetExternalProcesses { version, .. } |
| 89 | | Self::SetSampleInterval { version, .. } |
| 90 | | Self::SetStreaming { version, .. } |
| 91 | | Self::SampleNow { version, .. } |
| 92 | | Self::ProcessTable { version, .. } |
| 93 | | Self::ReadHistory { version, .. } |
| 94 | | Self::Shutdown { version } => *version, |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | enum Input { |
| 100 | Command(Command), |
| 101 | Invalid(String), |
| 102 | } |
| 103 | |
| 104 | #[derive(Debug, Serialize)] |
| 105 | #[serde(rename_all = "camelCase")] |
| 106 | struct Capabilities { |
| 107 | cumulative_cpu_time: bool, |
| 108 | current_cpu_percent: bool, |
| 109 | resident_memory: bool, |
| 110 | virtual_memory: bool, |
| 111 | io_bytes: bool, |
| 112 | process_start_time: bool, |
| 113 | process_tree: bool, |
| 114 | } |
| 115 | |
| 116 | #[derive(Debug, Serialize)] |
| 117 | #[serde(rename_all = "camelCase")] |
| 118 | struct HelloEvent { |
| 119 | version: u32, |
| 120 | #[serde(rename = "type")] |
| 121 | event_type: &'static str, |
| 122 | sidecar_version: &'static str, |
| 123 | sidecar_pid: u32, |
| 124 | platform: &'static str, |
| 125 | arch: &'static str, |
| 126 | capabilities: Capabilities, |
| 127 | } |
| 128 | |
| 129 | #[derive(Debug, Clone, Copy, Serialize)] |
| 130 | #[serde(rename_all = "kebab-case")] |
| 131 | enum IoSemantics { |
| 132 | Storage, |
| 133 | AllIo, |
| 134 | } |
| 135 | |
| 136 | #[derive(Debug, Clone, Serialize)] |
| 137 | #[serde(rename_all = "camelCase")] |
| 138 | struct ProcessSample { |
| 139 | pid: u32, |
| 140 | ppid: u32, |
| 141 | start_time_ms: u64, |
| 142 | run_time_ms: u64, |
| 143 | name: String, |
| 144 | command: String, |
| 145 | status: String, |
| 146 | cpu_percent: f32, |
| 147 | cpu_time_ms: u64, |
| 148 | resident_bytes: u64, |
| 149 | virtual_bytes: u64, |
| 150 | io_read_bytes: u64, |
| 151 | io_write_bytes: u64, |
| 152 | io_semantics: IoSemantics, |
| 153 | } |
| 154 | |
| 155 | #[derive(Debug, Serialize)] |
| 156 | #[serde(rename_all = "camelCase")] |
| 157 | struct ProcessTableEntry { |
| 158 | pid: u32, |
| 159 | ppid: u32, |
| 160 | name: String, |
| 161 | } |
| 162 | |
| 163 | #[derive(Debug, Serialize)] |
| 164 | #[serde(rename_all = "camelCase")] |
| 165 | struct ProcessTableEvent<'a> { |
| 166 | version: u32, |
| 167 | #[serde(rename = "type")] |
| 168 | event_type: &'static str, |
| 169 | request_id: &'a str, |
| 170 | processes: Vec<ProcessTableEntry>, |
| 171 | } |
| 172 | |
| 173 | impl ProcessSample { |
| 174 | fn estimated_history_bytes(&self) -> usize { |
| 175 | std::mem::size_of::<Self>() |
| 176 | .saturating_add(self.name.len()) |
| 177 | .saturating_add(self.command.len()) |
| 178 | .saturating_add(self.status.len()) |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | #[derive(Debug, Clone, Serialize)] |
| 183 | #[serde(rename_all = "camelCase")] |
| 184 | struct SnapshotEvent { |
| 185 | version: u32, |
| 186 | #[serde(rename = "type")] |
| 187 | event_type: &'static str, |
| 188 | sequence: u64, |
| 189 | sampled_at_unix_ms: u64, |
| 190 | collection_duration_micros: u64, |
| 191 | scanned_process_count: usize, |
| 192 | retained_process_count: usize, |
| 193 | inaccessible_process_count: usize, |
| 194 | #[serde(skip_serializing_if = "Option::is_none")] |
| 195 | request_id: Option<String>, |
| 196 | external_processes: Vec<ExternalProcess>, |
| 197 | processes: Vec<ProcessSample>, |
| 198 | } |
| 199 | |
| 200 | impl SnapshotEvent { |
| 201 | fn retained_entry_count(&self) -> usize { |
| 202 | self.processes |
| 203 | .len() |
| 204 | .saturating_add(self.external_processes.len()) |
| 205 | } |
| 206 | |
| 207 | fn estimated_history_bytes(&self) -> usize { |
| 208 | std::mem::size_of::<Self>() |
| 209 | .saturating_add( |
| 210 | self.processes |
| 211 | .iter() |
| 212 | .map(ProcessSample::estimated_history_bytes) |
| 213 | .sum::<usize>(), |
| 214 | ) |
| 215 | .saturating_add( |
| 216 | self.external_processes |
| 217 | .iter() |
| 218 | .map(ExternalProcess::estimated_history_bytes) |
| 219 | .sum::<usize>(), |
| 220 | ) |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | #[derive(Debug, Serialize)] |
| 225 | #[serde(rename_all = "camelCase")] |
| 226 | struct HistoryChunkEvent<'a> { |
| 227 | version: u32, |
| 228 | #[serde(rename = "type")] |
| 229 | event_type: &'static str, |
| 230 | request_id: &'a str, |
| 231 | done: bool, |
| 232 | snapshots: &'a [SnapshotEvent], |
| 233 | } |
| 234 | |
| 235 | #[derive(Debug, Serialize)] |
| 236 | #[serde(rename_all = "camelCase")] |
| 237 | struct ErrorEvent { |
| 238 | version: u32, |
| 239 | #[serde(rename = "type")] |
| 240 | event_type: &'static str, |
| 241 | code: &'static str, |
| 242 | message: String, |
| 243 | recoverable: bool, |
| 244 | } |
| 245 | |
| 246 | #[derive(Debug, Clone)] |
| 247 | struct CollectorConfig { |
| 248 | root_pid: u32, |
| 249 | sample_interval: Option<Duration>, |
| 250 | external_processes: HashMap<u32, Option<u64>>, |
| 251 | } |
| 252 | |
| 253 | #[derive(Default)] |
| 254 | struct HistoryRecorder { |
| 255 | snapshots: VecDeque<SnapshotEvent>, |
| 256 | retained_entry_count: usize, |
| 257 | retained_bytes: usize, |
| 258 | } |
| 259 | |
| 260 | impl HistoryRecorder { |
| 261 | fn record(&mut self, snapshot: &SnapshotEvent) { |
| 262 | self.record_with_limits( |
| 263 | snapshot, |
| 264 | MAX_HISTORY_SNAPSHOTS, |
| 265 | MAX_HISTORY_RETAINED_ENTRIES, |
| 266 | MAX_HISTORY_RETAINED_BYTES, |
| 267 | ); |
| 268 | } |
| 269 | |
| 270 | fn record_with_limits( |
| 271 | &mut self, |
| 272 | snapshot: &SnapshotEvent, |
| 273 | max_snapshots: usize, |
| 274 | max_retained_entries: usize, |
| 275 | max_retained_bytes: usize, |
| 276 | ) { |
| 277 | let clock_moved_backward = self |
| 278 | .snapshots |
| 279 | .back() |
| 280 | .is_some_and(|previous| previous.sampled_at_unix_ms > snapshot.sampled_at_unix_ms); |
| 281 | let mut retained = snapshot.clone(); |
| 282 | retained.request_id = None; |
| 283 | self.retained_entry_count = self |
| 284 | .retained_entry_count |
| 285 | .saturating_add(retained.retained_entry_count()); |
| 286 | self.retained_bytes = self |
| 287 | .retained_bytes |
| 288 | .saturating_add(retained.estimated_history_bytes()); |
| 289 | self.snapshots.push_back(retained); |
| 290 | self.trim_to_limits( |
| 291 | snapshot.sampled_at_unix_ms, |
| 292 | max_snapshots, |
| 293 | max_retained_entries, |
| 294 | max_retained_bytes, |
| 295 | clock_moved_backward, |
| 296 | ); |
| 297 | } |
| 298 | |
| 299 | fn trim_to_limits( |
| 300 | &mut self, |
| 301 | now_ms: u64, |
| 302 | max_snapshots: usize, |
| 303 | max_retained_entries: usize, |
| 304 | max_retained_bytes: usize, |
| 305 | clock_moved_backward: bool, |
| 306 | ) { |
| 307 | if clock_moved_backward { |
| 308 | let mut future_entry_count = 0usize; |
| 309 | let mut future_bytes = 0usize; |
| 310 | self.snapshots.retain(|snapshot| { |
| 311 | let keep = snapshot.sampled_at_unix_ms <= now_ms; |
| 312 | if !keep { |
| 313 | future_entry_count = |
| 314 | future_entry_count.saturating_add(snapshot.retained_entry_count()); |
| 315 | future_bytes = future_bytes.saturating_add(snapshot.estimated_history_bytes()); |
| 316 | } |
| 317 | keep |
| 318 | }); |
| 319 | self.retained_entry_count = |
| 320 | self.retained_entry_count.saturating_sub(future_entry_count); |
| 321 | self.retained_bytes = self.retained_bytes.saturating_sub(future_bytes); |
| 322 | } |
| 323 | |
| 324 | while self.snapshots.front().is_some_and(|snapshot| { |
| 325 | snapshot.sampled_at_unix_ms < now_ms.saturating_sub(HISTORY_RETENTION_MS) |
| 326 | || self.snapshots.len() > max_snapshots |
| 327 | || self.retained_entry_count > max_retained_entries |
| 328 | || self.retained_bytes > max_retained_bytes |
| 329 | }) { |
| 330 | if let Some(removed) = self.snapshots.pop_front() { |
| 331 | self.retained_entry_count = self |
| 332 | .retained_entry_count |
| 333 | .saturating_sub(removed.retained_entry_count()); |
| 334 | self.retained_bytes = self |
| 335 | .retained_bytes |
| 336 | .saturating_sub(removed.estimated_history_bytes()); |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | fn read(&self, window_ms: u64, now_ms: u64) -> Vec<SnapshotEvent> { |
| 342 | let started_at_ms = now_ms.saturating_sub(window_ms.min(HISTORY_RETENTION_MS)); |
| 343 | self.snapshots |
| 344 | .iter() |
| 345 | .filter(|snapshot| { |
| 346 | snapshot.sampled_at_unix_ms >= started_at_ms |
| 347 | && snapshot.sampled_at_unix_ms <= now_ms |
| 348 | }) |
| 349 | .cloned() |
| 350 | .collect() |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | struct Collector { |
| 355 | system: System, |
| 356 | sequence: u64, |
| 357 | cpu_baseline_refreshed_at: Option<Instant>, |
| 358 | } |
| 359 | |
| 360 | impl Collector { |
| 361 | fn new() -> Self { |
| 362 | Self { |
| 363 | system: System::new(), |
| 364 | sequence: 0, |
| 365 | cpu_baseline_refreshed_at: None, |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | fn prime_cpu_usage(&mut self) { |
| 370 | self.system.refresh_processes_specifics( |
| 371 | ProcessesToUpdate::All, |
| 372 | true, |
| 373 | process_discovery_refresh_kind(), |
| 374 | ); |
| 375 | self.cpu_baseline_refreshed_at = Some(Instant::now()); |
| 376 | } |
| 377 | |
| 378 | // Terminal polling asks for this every second while a shell is open. On |
| 379 | // Linux one read of /proc/<pid>/stat has everything; sysinfo also opens |
| 380 | // /proc/<pid>/status and builds a full record per process, ~3x the CPU. |
| 381 | #[cfg(target_os = "linux")] |
| 382 | fn process_table(&self) -> Vec<ProcessTableEntry> { |
| 383 | use std::io::Read; |
| 384 | |
| 385 | let Ok(entries) = std::fs::read_dir("/proc") else { |
| 386 | return Vec::new(); |
| 387 | }; |
| 388 | let mut buffer = Vec::with_capacity(512); |
| 389 | let mut processes = entries |
| 390 | .filter_map(|entry| { |
| 391 | let entry = entry.ok()?; |
| 392 | let pid = entry.file_name().to_str()?.parse::<u32>().ok()?; |
| 393 | buffer.clear(); |
| 394 | std::fs::File::open(entry.path().join("stat")) |
| 395 | .ok()? |
| 396 | .read_to_end(&mut buffer) |
| 397 | .ok()?; |
| 398 | let (name, ppid) = parse_proc_stat(&buffer)?; |
| 399 | Some(ProcessTableEntry { pid, ppid, name }) |
| 400 | }) |
| 401 | .collect::<Vec<_>>(); |
| 402 | processes.sort_by_key(|process| process.pid); |
| 403 | processes |
| 404 | } |
| 405 | |
| 406 | #[cfg(not(target_os = "linux"))] |
| 407 | fn process_table(&self) -> Vec<ProcessTableEntry> { |
| 408 | // A separate System preserves snapshot CPU baselines. |
| 409 | let mut process_table_system = System::new(); |
| 410 | process_table_system.refresh_processes_specifics( |
| 411 | ProcessesToUpdate::All, |
| 412 | true, |
| 413 | ProcessRefreshKind::nothing().without_tasks(), |
| 414 | ); |
| 415 | let mut processes = process_table_system |
| 416 | .processes() |
| 417 | .iter() |
| 418 | .filter_map(|(pid, process)| { |
| 419 | let pid = pid.as_u32(); |
| 420 | // Kernel idle PID 0 would fail the server's positive-PID event schema. |
| 421 | if pid == 0 { |
| 422 | return None; |
| 423 | } |
| 424 | Some(ProcessTableEntry { |
| 425 | pid, |
| 426 | ppid: process.parent().map(Pid::as_u32).unwrap_or(0), |
| 427 | name: truncate_utf8( |
| 428 | process.name().to_string_lossy().into_owned(), |
| 429 | MAX_PROCESS_NAME_BYTES, |
| 430 | ), |
| 431 | }) |
| 432 | }) |
| 433 | .collect::<Vec<_>>(); |
| 434 | processes.sort_by_key(|process| process.pid); |
| 435 | processes |
| 436 | } |
| 437 | |
| 438 | fn sample(&mut self, config: &CollectorConfig, request_id: Option<String>) -> SnapshotEvent { |
| 439 | if let Some(delay) = |
| 440 | remaining_cpu_measurement_delay(self.cpu_baseline_refreshed_at.take(), Instant::now()) |
| 441 | { |
| 442 | thread::sleep(delay); |
| 443 | } |
| 444 | let collection_started = Instant::now(); |
| 445 | self.system.refresh_processes_specifics( |
| 446 | ProcessesToUpdate::All, |
| 447 | true, |
| 448 | process_discovery_refresh_kind(), |
| 449 | ); |
| 450 | self.cpu_baseline_refreshed_at = Some(Instant::now()); |
| 451 | |
| 452 | let rows = self |
| 453 | .system |
| 454 | .processes() |
| 455 | .iter() |
| 456 | .map(|(pid, process)| { |
| 457 | let pid = pid.as_u32(); |
| 458 | let ppid = process.parent().map(Pid::as_u32).unwrap_or(0); |
| 459 | (pid, ppid, process.start_time().saturating_mul(1_000)) |
| 460 | }) |
| 461 | .collect::<Vec<_>>(); |
| 462 | let external_processes = config |
| 463 | .external_processes |
| 464 | .iter() |
| 465 | .filter_map(|(pid, expected_start_time_ms)| { |
| 466 | let process = self.system.process(Pid::from_u32(*pid))?; |
| 467 | let actual_start_time_ms = process.start_time().saturating_mul(1_000); |
| 468 | matches_external_identity(actual_start_time_ms, *expected_start_time_ms).then_some( |
| 469 | ExternalProcess { |
| 470 | pid: *pid, |
| 471 | start_time_ms: Some(actual_start_time_ms), |
| 472 | }, |
| 473 | ) |
| 474 | }) |
| 475 | .collect::<Vec<_>>(); |
| 476 | let mut roots = external_processes |
| 477 | .iter() |
| 478 | .map(|process| process.pid) |
| 479 | .collect::<HashSet<_>>(); |
| 480 | roots.insert(config.root_pid); |
| 481 | let tracked = select_tracked_pids(&rows, &roots); |
| 482 | let tracked_process_count = tracked.len(); |
| 483 | let process_details = if TWO_STAGE_PROCESS_REFRESH && !tracked.is_empty() { |
| 484 | let monitor_pid = Pid::from_u32(std::process::id()); |
| 485 | let mut detail_pids = tracked |
| 486 | .iter() |
| 487 | .copied() |
| 488 | .map(Pid::from_u32) |
| 489 | .collect::<Vec<_>>(); |
| 490 | if !tracked.contains(&monitor_pid.as_u32()) { |
| 491 | detail_pids.push(monitor_pid); |
| 492 | } |
| 493 | // Detail fields need no baseline. Drop command data and OS handles after each sample. |
| 494 | let mut details = System::new(); |
| 495 | details.refresh_processes_specifics( |
| 496 | ProcessesToUpdate::Some(&detail_pids), |
| 497 | true, |
| 498 | process_refresh_kind().without_cpu(), |
| 499 | ); |
| 500 | // This process cannot be replaced during collection. Its start time |
| 501 | // exposes any boot-epoch shift between the two System instances. |
| 502 | let start_time_offset = self.system.process(monitor_pid).and_then(|process| { |
| 503 | details.process(monitor_pid).map(|detail| { |
| 504 | i128::from(detail.start_time()) - i128::from(process.start_time()) |
| 505 | }) |
| 506 | }); |
| 507 | Some((details, start_time_offset)) |
| 508 | } else { |
| 509 | None |
| 510 | }; |
| 511 | let sample_details = process_details |
| 512 | .as_ref() |
| 513 | .map_or(&self.system, |(details, _)| details); |
| 514 | let start_time_offset = process_details |
| 515 | .as_ref() |
| 516 | .map_or(Some(0), |(_, offset)| *offset); |
| 517 | let mut processes = tracked |
| 518 | .into_iter() |
| 519 | .filter_map(|pid| { |
| 520 | let process = self.system.process(Pid::from_u32(pid))?; |
| 521 | let details = sample_details.process(Pid::from_u32(pid))?; |
| 522 | if !matches_process_start_time( |
| 523 | process.start_time(), |
| 524 | details.start_time(), |
| 525 | start_time_offset?, |
| 526 | ) { |
| 527 | return None; |
| 528 | } |
| 529 | let disk_usage = details.disk_usage(); |
| 530 | let command = if details.cmd().is_empty() { |
| 531 | process.name().to_string_lossy().into_owned() |
| 532 | } else { |
| 533 | details |
| 534 | .cmd() |
| 535 | .iter() |
| 536 | .map(|part| part.to_string_lossy()) |
| 537 | .collect::<Vec<_>>() |
| 538 | .join(" ") |
| 539 | }; |
| 540 | |
| 541 | Some(ProcessSample { |
| 542 | pid, |
| 543 | ppid: process.parent().map(Pid::as_u32).unwrap_or(0), |
| 544 | start_time_ms: process.start_time().saturating_mul(1_000), |
| 545 | run_time_ms: process.run_time().saturating_mul(1_000), |
| 546 | name: truncate_utf8( |
| 547 | process.name().to_string_lossy().into_owned(), |
| 548 | MAX_PROCESS_NAME_BYTES, |
| 549 | ), |
| 550 | command: truncate_utf8(command, MAX_PROCESS_COMMAND_BYTES), |
| 551 | status: truncate_utf8( |
| 552 | format!("{:?}", process.status()), |
| 553 | MAX_PROCESS_STATUS_BYTES, |
| 554 | ), |
| 555 | cpu_percent: process.cpu_usage(), |
| 556 | cpu_time_ms: process.accumulated_cpu_time(), |
| 557 | resident_bytes: details.memory(), |
| 558 | virtual_bytes: details.virtual_memory(), |
| 559 | io_read_bytes: disk_usage.total_read_bytes, |
| 560 | io_write_bytes: disk_usage.total_written_bytes, |
| 561 | io_semantics: io_semantics(), |
| 562 | }) |
| 563 | }) |
| 564 | .collect::<Vec<_>>(); |
| 565 | drop(process_details); |
| 566 | processes.sort_by_key(|process| process.pid); |
| 567 | self.sequence = self.sequence.saturating_add(1); |
| 568 | |
| 569 | SnapshotEvent { |
| 570 | version: PROTOCOL_VERSION, |
| 571 | event_type: "snapshot", |
| 572 | sequence: self.sequence, |
| 573 | sampled_at_unix_ms: unix_time_ms(), |
| 574 | collection_duration_micros: collection_started.elapsed().as_micros() as u64, |
| 575 | scanned_process_count: self.system.processes().len(), |
| 576 | retained_process_count: processes.len(), |
| 577 | inaccessible_process_count: inaccessible_process_count( |
| 578 | tracked_process_count, |
| 579 | processes.len(), |
| 580 | ), |
| 581 | request_id, |
| 582 | external_processes, |
| 583 | processes, |
| 584 | } |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | // Keep CPU baselines separate. Even a metadata refresh resets Linux process times. |
| 589 | fn process_discovery_refresh_kind() -> ProcessRefreshKind { |
| 590 | if TWO_STAGE_PROCESS_REFRESH { |
| 591 | ProcessRefreshKind::nothing().with_cpu().without_tasks() |
| 592 | } else { |
| 593 | process_refresh_kind() |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | fn process_refresh_kind() -> ProcessRefreshKind { |
| 598 | ProcessRefreshKind::nothing() |
| 599 | .with_memory() |
| 600 | .with_cpu() |
| 601 | .with_disk_usage() |
| 602 | .with_cmd(UpdateKind::Always) |
| 603 | .without_tasks() |
| 604 | } |
| 605 | |
| 606 | /// Name and parent pid from `/proc/<pid>/stat`: `pid (comm) state ppid ...`. |
| 607 | /// The name may itself contain spaces and parentheses, so it ends at the last `)`. |
| 608 | #[cfg(any(target_os = "linux", test))] |
| 609 | fn parse_proc_stat(stat: &[u8]) -> Option<(String, u32)> { |
| 610 | let open = stat.iter().position(|&byte| byte == b'(')?; |
| 611 | let close = stat.iter().rposition(|&byte| byte == b')')?; |
| 612 | let name = stat.get(open + 1..close)?; |
| 613 | let mut fields = stat.get(close + 1..)?.split(|&byte| byte == b' '); |
| 614 | fields.next()?; |
| 615 | fields.next()?; |
| 616 | let ppid = std::str::from_utf8(fields.next()?).ok()?.parse().ok()?; |
| 617 | let name = truncate_utf8( |
| 618 | String::from_utf8_lossy(name).into_owned(), |
| 619 | MAX_PROCESS_NAME_BYTES, |
| 620 | ); |
| 621 | Some((name, ppid)) |
| 622 | } |
| 623 | |
| 624 | fn inaccessible_process_count(selected: usize, materialized: usize) -> usize { |
| 625 | selected.saturating_sub(materialized) |
| 626 | } |
| 627 | |
| 628 | fn matches_process_start_time(discovered: u64, detail: u64, epoch_offset: i128) -> bool { |
| 629 | i128::from(detail) - epoch_offset == i128::from(discovered) |
| 630 | } |
| 631 | |
| 632 | fn remaining_cpu_measurement_delay( |
| 633 | baseline_refreshed_at: Option<Instant>, |
| 634 | now: Instant, |
| 635 | ) -> Option<Duration> { |
| 636 | baseline_refreshed_at |
| 637 | .and_then(|baseline| MINIMUM_CPU_UPDATE_INTERVAL.checked_sub(now.duration_since(baseline))) |
| 638 | .filter(|delay| !delay.is_zero()) |
| 639 | } |
| 640 | |
| 641 | fn matches_external_identity( |
| 642 | actual_start_time_ms: u64, |
| 643 | expected_start_time_ms: Option<u64>, |
| 644 | ) -> bool { |
| 645 | // Match sysinfo's whole-second precision without admitting reused PIDs from adjacent seconds. |
| 646 | expected_start_time_ms.is_none_or(|expected| { |
| 647 | actual_start_time_ms == expected - (expected % PROCESS_START_TIME_PRECISION_MS) |
| 648 | }) |
| 649 | } |
| 650 | |
| 651 | fn select_tracked_pids(rows: &[(u32, u32, u64)], roots: &HashSet<u32>) -> HashSet<u32> { |
| 652 | let mut children_by_parent = HashMap::<u32, Vec<(u32, u64)>>::new(); |
| 653 | let mut start_time_by_pid = HashMap::<u32, u64>::new(); |
| 654 | for (pid, ppid, start_time_ms) in rows { |
| 655 | children_by_parent |
| 656 | .entry(*ppid) |
| 657 | .or_default() |
| 658 | .push((*pid, *start_time_ms)); |
| 659 | start_time_by_pid.insert(*pid, *start_time_ms); |
| 660 | } |
| 661 | |
| 662 | let mut tracked = HashSet::new(); |
| 663 | let mut visited_identities = HashSet::new(); |
| 664 | let mut queue = roots |
| 665 | .iter() |
| 666 | .filter_map(|pid| { |
| 667 | start_time_by_pid |
| 668 | .get(pid) |
| 669 | .map(|start_time_ms| (*pid, *start_time_ms)) |
| 670 | }) |
| 671 | .collect::<VecDeque<_>>(); |
| 672 | |
| 673 | while let Some((pid, start_time_ms)) = queue.pop_front() { |
| 674 | if !visited_identities.insert((pid, start_time_ms)) { |
| 675 | continue; |
| 676 | } |
| 677 | tracked.insert(pid); |
| 678 | if let Some(children) = children_by_parent.get(&pid) { |
| 679 | queue.extend( |
| 680 | children |
| 681 | .iter() |
| 682 | .copied() |
| 683 | .filter(|(_, child_start_time_ms)| *child_start_time_ms >= start_time_ms), |
| 684 | ); |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | tracked |
| 689 | } |
| 690 | |
| 691 | fn truncate_utf8(mut value: String, max_bytes: usize) -> String { |
| 692 | if value.len() <= max_bytes { |
| 693 | return value; |
| 694 | } |
| 695 | let mut boundary = max_bytes; |
| 696 | while !value.is_char_boundary(boundary) { |
| 697 | boundary = boundary.saturating_sub(1); |
| 698 | } |
| 699 | value.truncate(boundary); |
| 700 | value |
| 701 | } |
| 702 | |
| 703 | fn io_semantics() -> IoSemantics { |
| 704 | if cfg!(target_os = "windows") { |
| 705 | IoSemantics::AllIo |
| 706 | } else { |
| 707 | IoSemantics::Storage |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | fn unix_time_ms() -> u64 { |
| 712 | SystemTime::now() |
| 713 | .duration_since(UNIX_EPOCH) |
| 714 | .unwrap_or_default() |
| 715 | .as_millis() as u64 |
| 716 | } |
| 717 | |
| 718 | fn clamp_sample_interval(sample_interval_ms: u64) -> Option<Duration> { |
| 719 | (sample_interval_ms > 0).then(|| { |
| 720 | Duration::from_millis( |
| 721 | sample_interval_ms.clamp(MIN_SAMPLE_INTERVAL_MS, MAX_SAMPLE_INTERVAL_MS), |
| 722 | ) |
| 723 | }) |
| 724 | } |
| 725 | |
| 726 | fn spawn_input_reader() -> Receiver<Input> { |
| 727 | let (sender, receiver) = mpsc::sync_channel(INPUT_QUEUE_CAPACITY); |
| 728 | thread::spawn(move || { |
| 729 | let stdin = io::stdin(); |
| 730 | for line in stdin.lock().lines() { |
| 731 | let line = match line { |
| 732 | Ok(line) => line, |
| 733 | Err(error) => { |
| 734 | let _ = sender.send(Input::Invalid(format!( |
| 735 | "failed reading command stream: {error}" |
| 736 | ))); |
| 737 | return; |
| 738 | } |
| 739 | }; |
| 740 | if line.trim().is_empty() { |
| 741 | continue; |
| 742 | } |
| 743 | match serde_json::from_str::<Command>(&line) { |
| 744 | Ok(command) => { |
| 745 | if sender.send(Input::Command(command)).is_err() { |
| 746 | return; |
| 747 | } |
| 748 | } |
| 749 | Err(error) => { |
| 750 | if sender |
| 751 | .send(Input::Invalid(format!("invalid command: {error}"))) |
| 752 | .is_err() |
| 753 | { |
| 754 | return; |
| 755 | } |
| 756 | } |
| 757 | } |
| 758 | } |
| 759 | }); |
| 760 | receiver |
| 761 | } |
| 762 | |
| 763 | fn sample_now_deadline( |
| 764 | current: Option<Instant>, |
| 765 | interval: Option<Duration>, |
| 766 | now: Instant, |
| 767 | ) -> Option<Instant> { |
| 768 | current.or_else(|| interval.map(|duration| now + duration)) |
| 769 | } |
| 770 | |
| 771 | fn write_event<T: Serialize>(writer: &mut impl Write, event: &T) -> io::Result<()> { |
| 772 | serde_json::to_writer(&mut *writer, event)?; |
| 773 | writer.write_all(b"\n")?; |
| 774 | writer.flush() |
| 775 | } |
| 776 | |
| 777 | fn write_error( |
| 778 | writer: &mut impl Write, |
| 779 | code: &'static str, |
| 780 | message: impl Into<String>, |
| 781 | recoverable: bool, |
| 782 | ) -> io::Result<()> { |
| 783 | write_event( |
| 784 | writer, |
| 785 | &ErrorEvent { |
| 786 | version: PROTOCOL_VERSION, |
| 787 | event_type: "error", |
| 788 | code, |
| 789 | message: message.into(), |
| 790 | recoverable, |
| 791 | }, |
| 792 | ) |
| 793 | } |
| 794 | |
| 795 | fn write_history( |
| 796 | writer: &mut impl Write, |
| 797 | request_id: &str, |
| 798 | snapshots: &[SnapshotEvent], |
| 799 | ) -> io::Result<()> { |
| 800 | if snapshots.is_empty() { |
| 801 | return write_event( |
| 802 | writer, |
| 803 | &HistoryChunkEvent { |
| 804 | version: PROTOCOL_VERSION, |
| 805 | event_type: "historyChunk", |
| 806 | request_id, |
| 807 | done: true, |
| 808 | snapshots, |
| 809 | }, |
| 810 | ); |
| 811 | } |
| 812 | |
| 813 | let chunk_count = snapshots.len().div_ceil(HISTORY_CHUNK_SNAPSHOTS); |
| 814 | for (index, chunk) in snapshots.chunks(HISTORY_CHUNK_SNAPSHOTS).enumerate() { |
| 815 | write_event( |
| 816 | writer, |
| 817 | &HistoryChunkEvent { |
| 818 | version: PROTOCOL_VERSION, |
| 819 | event_type: "historyChunk", |
| 820 | request_id, |
| 821 | done: index + 1 == chunk_count, |
| 822 | snapshots: chunk, |
| 823 | }, |
| 824 | )?; |
| 825 | } |
| 826 | Ok(()) |
| 827 | } |
| 828 | |
| 829 | fn main() -> io::Result<()> { |
| 830 | let mut writer = BufWriter::new(io::stdout().lock()); |
| 831 | write_event( |
| 832 | &mut writer, |
| 833 | &HelloEvent { |
| 834 | version: PROTOCOL_VERSION, |
| 835 | event_type: "hello", |
| 836 | sidecar_version: env!("CARGO_PKG_VERSION"), |
| 837 | sidecar_pid: std::process::id(), |
| 838 | platform: std::env::consts::OS, |
| 839 | arch: std::env::consts::ARCH, |
| 840 | capabilities: Capabilities { |
| 841 | cumulative_cpu_time: true, |
| 842 | current_cpu_percent: true, |
| 843 | resident_memory: true, |
| 844 | virtual_memory: true, |
| 845 | io_bytes: true, |
| 846 | process_start_time: true, |
| 847 | process_tree: true, |
| 848 | }, |
| 849 | }, |
| 850 | )?; |
| 851 | |
| 852 | let receiver = spawn_input_reader(); |
| 853 | let mut collector = Collector::new(); |
| 854 | let mut history = HistoryRecorder::default(); |
| 855 | let mut config: Option<CollectorConfig> = None; |
| 856 | let mut next_sample_at: Option<Instant> = None; |
| 857 | let mut streaming_enabled = false; |
| 858 | |
| 859 | loop { |
| 860 | if next_sample_at.is_some_and(|deadline| deadline <= Instant::now()) { |
| 861 | if let Some(current) = config.as_ref() { |
| 862 | if let Some(interval) = current.sample_interval { |
| 863 | let event = collector.sample(current, None); |
| 864 | history.record(&event); |
| 865 | if streaming_enabled { |
| 866 | write_event(&mut writer, &event)?; |
| 867 | } |
| 868 | next_sample_at = Some(Instant::now() + interval); |
| 869 | } else { |
| 870 | next_sample_at = None; |
| 871 | } |
| 872 | } else { |
| 873 | next_sample_at = None; |
| 874 | } |
| 875 | continue; |
| 876 | } |
| 877 | |
| 878 | let timeout = next_sample_at |
| 879 | .map(|deadline| deadline.saturating_duration_since(Instant::now())) |
| 880 | .unwrap_or(Duration::from_secs(60)); |
| 881 | |
| 882 | match receiver.recv_timeout(timeout) { |
| 883 | Ok(Input::Invalid(message)) => { |
| 884 | write_error(&mut writer, "invalid-command", message, true)?; |
| 885 | } |
| 886 | Ok(Input::Command(command)) => { |
| 887 | if command.version() != PROTOCOL_VERSION { |
| 888 | write_error( |
| 889 | &mut writer, |
| 890 | "protocol-mismatch", |
| 891 | format!( |
| 892 | "unsupported protocol version {}; expected {PROTOCOL_VERSION}", |
| 893 | command.version() |
| 894 | ), |
| 895 | false, |
| 896 | )?; |
| 897 | continue; |
| 898 | } |
| 899 | |
| 900 | match command { |
| 901 | Command::Configure { |
| 902 | root_pid, |
| 903 | sample_interval_ms, |
| 904 | external_processes, |
| 905 | .. |
| 906 | } => { |
| 907 | let sample_interval = clamp_sample_interval(sample_interval_ms); |
| 908 | config = Some(CollectorConfig { |
| 909 | root_pid, |
| 910 | sample_interval, |
| 911 | external_processes: external_processes |
| 912 | .into_iter() |
| 913 | .map(|process| (process.pid, process.start_time_ms)) |
| 914 | .collect(), |
| 915 | }); |
| 916 | collector.prime_cpu_usage(); |
| 917 | next_sample_at = sample_interval.map(|_| Instant::now()); |
| 918 | } |
| 919 | Command::SetExternalProcesses { processes, .. } => { |
| 920 | if let Some(current) = config.as_mut() { |
| 921 | current.external_processes = processes |
| 922 | .into_iter() |
| 923 | .map(|process| (process.pid, process.start_time_ms)) |
| 924 | .collect(); |
| 925 | } else { |
| 926 | write_error( |
| 927 | &mut writer, |
| 928 | "not-configured", |
| 929 | "configure must be sent before external processes", |
| 930 | true, |
| 931 | )?; |
| 932 | } |
| 933 | } |
| 934 | Command::SetSampleInterval { |
| 935 | sample_interval_ms, .. |
| 936 | } => { |
| 937 | if let Some(current) = config.as_mut() { |
| 938 | current.sample_interval = clamp_sample_interval(sample_interval_ms); |
| 939 | next_sample_at = current |
| 940 | .sample_interval |
| 941 | .map(|interval| Instant::now() + interval); |
| 942 | } else { |
| 943 | write_error( |
| 944 | &mut writer, |
| 945 | "not-configured", |
| 946 | "configure must be sent before changing the sample interval", |
| 947 | true, |
| 948 | )?; |
| 949 | } |
| 950 | } |
| 951 | Command::SetStreaming { enabled, .. } => { |
| 952 | streaming_enabled = enabled; |
| 953 | } |
| 954 | Command::SampleNow { request_id, .. } => { |
| 955 | if let Some(current) = config.as_ref() { |
| 956 | let event = collector.sample(current, Some(request_id)); |
| 957 | history.record(&event); |
| 958 | write_event(&mut writer, &event)?; |
| 959 | next_sample_at = sample_now_deadline( |
| 960 | next_sample_at, |
| 961 | current.sample_interval, |
| 962 | Instant::now(), |
| 963 | ); |
| 964 | } else { |
| 965 | write_error( |
| 966 | &mut writer, |
| 967 | "not-configured", |
| 968 | "configure must be sent before sampling", |
| 969 | true, |
| 970 | )?; |
| 971 | } |
| 972 | } |
| 973 | Command::ProcessTable { request_id, .. } => { |
| 974 | let event = ProcessTableEvent { |
| 975 | version: PROTOCOL_VERSION, |
| 976 | event_type: "processTable", |
| 977 | request_id: &request_id, |
| 978 | processes: collector.process_table(), |
| 979 | }; |
| 980 | write_event(&mut writer, &event)?; |
| 981 | } |
| 982 | Command::ReadHistory { |
| 983 | request_id, |
| 984 | window_ms, |
| 985 | .. |
| 986 | } => { |
| 987 | if config.is_some() { |
| 988 | let snapshots = history.read(window_ms, unix_time_ms()); |
| 989 | write_history(&mut writer, &request_id, &snapshots)?; |
| 990 | } else { |
| 991 | write_error( |
| 992 | &mut writer, |
| 993 | "not-configured", |
| 994 | "configure must be sent before reading history", |
| 995 | true, |
| 996 | )?; |
| 997 | } |
| 998 | } |
| 999 | Command::Shutdown { .. } => return Ok(()), |
| 1000 | } |
| 1001 | } |
| 1002 | Err(RecvTimeoutError::Timeout) => {} |
| 1003 | Err(RecvTimeoutError::Disconnected) => return Ok(()), |
| 1004 | } |
| 1005 | } |
| 1006 | } |
| 1007 | |
| 1008 | #[cfg(test)] |
| 1009 | mod tests { |
| 1010 | use super::*; |
| 1011 | |
| 1012 | #[test] |
| 1013 | fn selects_roots_and_all_descendants() { |
| 1014 | let rows = vec![ |
| 1015 | (10, 1, 1_000), |
| 1016 | (11, 10, 1_100), |
| 1017 | (12, 11, 1_200), |
| 1018 | (20, 1, 2_000), |
| 1019 | (21, 20, 2_100), |
| 1020 | (30, 99, 3_000), |
| 1021 | ]; |
| 1022 | let tracked = select_tracked_pids(&rows, &HashSet::from([10, 20])); |
| 1023 | |
| 1024 | assert_eq!(tracked, HashSet::from([10, 11, 12, 20, 21])); |
| 1025 | } |
| 1026 | |
| 1027 | #[test] |
| 1028 | fn rejects_descendants_older_than_a_reused_parent_pid() { |
| 1029 | let rows = vec![ |
| 1030 | (20, 1, 5_000), |
| 1031 | (21, 20, 4_000), |
| 1032 | (22, 20, 5_100), |
| 1033 | (23, 21, 5_200), |
| 1034 | ]; |
| 1035 | let tracked = select_tracked_pids(&rows, &HashSet::from([20])); |
| 1036 | |
| 1037 | assert_eq!(tracked, HashSet::from([20, 22])); |
| 1038 | } |
| 1039 | |
| 1040 | #[test] |
| 1041 | fn ignores_missing_roots() { |
| 1042 | let rows = vec![(10, 1, 1_000), (11, 10, 1_100)]; |
| 1043 | let tracked = select_tracked_pids(&rows, &HashSet::from([99])); |
| 1044 | |
| 1045 | assert!(tracked.is_empty()); |
| 1046 | } |
| 1047 | |
| 1048 | #[test] |
| 1049 | fn validates_external_process_start_identity() { |
| 1050 | for (actual, expected, matches) in [ |
| 1051 | (10_000, None, true), |
| 1052 | (10_000, Some(10_000), true), |
| 1053 | (10_000, Some(10_999), true), |
| 1054 | (10_000, Some(11_000), false), |
| 1055 | (10_000, Some(9_999), false), |
| 1056 | (0, Some(999), true), |
| 1057 | (0, Some(1_000), false), |
| 1058 | (u64::MAX, None, true), |
| 1059 | (u64::MAX, Some(u64::MAX), false), |
| 1060 | ] { |
| 1061 | assert_eq!(matches_external_identity(actual, expected), matches); |
| 1062 | } |
| 1063 | } |
| 1064 | |
| 1065 | #[test] |
| 1066 | fn loads_details_when_an_existing_process_becomes_selected() { |
| 1067 | let mut collector = Collector::new(); |
| 1068 | let mut config = CollectorConfig { |
| 1069 | root_pid: u32::MAX, |
| 1070 | sample_interval: None, |
| 1071 | external_processes: HashMap::new(), |
| 1072 | }; |
| 1073 | assert!(collector.sample(&config, None).processes.is_empty()); |
| 1074 | |
| 1075 | config.root_pid = std::process::id(); |
| 1076 | let snapshot = collector.sample(&config, None); |
| 1077 | let process = snapshot |
| 1078 | .processes |
| 1079 | .iter() |
| 1080 | .find(|process| process.pid == config.root_pid) |
| 1081 | .expect("selected process"); |
| 1082 | |
| 1083 | assert!(!process.command.is_empty()); |
| 1084 | assert!(process.resident_bytes > 0); |
| 1085 | assert!(process.cpu_percent.is_finite()); |
| 1086 | } |
| 1087 | |
| 1088 | #[cfg(any(target_os = "linux", target_os = "macos"))] |
| 1089 | #[test] |
| 1090 | fn keeps_command_lines_and_memory_out_of_the_discovery_table() { |
| 1091 | let mut collector = Collector::new(); |
| 1092 | let mut config = CollectorConfig { |
| 1093 | root_pid: u32::MAX, |
| 1094 | sample_interval: None, |
| 1095 | external_processes: HashMap::new(), |
| 1096 | }; |
| 1097 | assert!(collector.sample(&config, None).processes.is_empty()); |
| 1098 | |
| 1099 | let pid = Pid::from_u32(std::process::id()); |
| 1100 | let unselected = collector.system.process(pid).expect("discovered process"); |
| 1101 | assert!(unselected.cmd().is_empty()); |
| 1102 | assert_eq!(unselected.memory(), 0); |
| 1103 | assert_eq!(unselected.virtual_memory(), 0); |
| 1104 | |
| 1105 | config.external_processes = [ |
| 1106 | (pid.as_u32(), Some(0)), |
| 1107 | (u32::MAX, None), |
| 1108 | (pid.as_u32(), None), |
| 1109 | ] |
| 1110 | .into_iter() |
| 1111 | .collect(); |
| 1112 | let snapshot = collector.sample(&config, None); |
| 1113 | let selected = snapshot |
| 1114 | .processes |
| 1115 | .iter() |
| 1116 | .find(|process| process.pid == pid.as_u32()) |
| 1117 | .expect("external process details"); |
| 1118 | assert!(!selected.command.is_empty()); |
| 1119 | assert!(selected.resident_bytes > 0); |
| 1120 | assert!(selected.start_time_ms > 0); |
| 1121 | assert_eq!( |
| 1122 | snapshot |
| 1123 | .external_processes |
| 1124 | .iter() |
| 1125 | .map(|process| (process.pid, process.start_time_ms)) |
| 1126 | .collect::<Vec<_>>(), |
| 1127 | vec![(pid.as_u32(), Some(selected.start_time_ms))], |
| 1128 | ); |
| 1129 | |
| 1130 | config.root_pid = pid.as_u32(); |
| 1131 | config.external_processes.insert(pid.as_u32(), Some(0)); |
| 1132 | let snapshot = collector.sample(&config, None); |
| 1133 | assert!(snapshot.external_processes.is_empty()); |
| 1134 | assert_eq!( |
| 1135 | snapshot |
| 1136 | .processes |
| 1137 | .iter() |
| 1138 | .filter(|process| process.pid == pid.as_u32()) |
| 1139 | .count(), |
| 1140 | 1, |
| 1141 | ); |
| 1142 | |
| 1143 | let retained = collector |
| 1144 | .system |
| 1145 | .process(pid) |
| 1146 | .expect("retained CPU baseline"); |
| 1147 | assert!(retained.cmd().is_empty()); |
| 1148 | assert_eq!(retained.memory(), 0); |
| 1149 | assert_eq!(retained.virtual_memory(), 0); |
| 1150 | } |
| 1151 | |
| 1152 | #[test] |
| 1153 | fn accepts_clock_shifts_without_accepting_reused_process_starts() { |
| 1154 | assert!(matches_process_start_time(10_000, 13_600, 3_600)); |
| 1155 | assert!(!matches_process_start_time(10_000, 13_601, 3_600)); |
| 1156 | assert!(matches_process_start_time(10_000, 6_400, -3_600)); |
| 1157 | assert!(!matches_process_start_time(10_000, 6_401, -3_600)); |
| 1158 | assert!(matches_process_start_time(10_000, 10_000, 0)); |
| 1159 | assert!(!matches_process_start_time(10_000, 10_001, 0)); |
| 1160 | } |
| 1161 | |
| 1162 | #[test] |
| 1163 | fn decodes_protocol_commands() { |
| 1164 | let configure = serde_json::from_str::<Command>( |
| 1165 | r#"{"version":3,"type":"configure","rootPid":42,"sampleIntervalMs":1000,"externalProcesses":[{"pid":7}]}"#, |
| 1166 | ) |
| 1167 | .expect("configure command"); |
| 1168 | |
| 1169 | match configure { |
| 1170 | Command::Configure { |
| 1171 | root_pid, |
| 1172 | sample_interval_ms, |
| 1173 | external_processes, |
| 1174 | .. |
| 1175 | } => { |
| 1176 | assert_eq!(root_pid, 42); |
| 1177 | assert_eq!(sample_interval_ms, 1_000); |
| 1178 | assert_eq!(external_processes[0].pid, 7); |
| 1179 | assert_eq!(external_processes[0].start_time_ms, None); |
| 1180 | } |
| 1181 | _ => panic!("unexpected command"), |
| 1182 | } |
| 1183 | |
| 1184 | let read_history = serde_json::from_str::<Command>( |
| 1185 | r#"{"version":3,"type":"readHistory","requestId":"history-1","windowMs":60000}"#, |
| 1186 | ) |
| 1187 | .expect("read history command"); |
| 1188 | assert!(matches!( |
| 1189 | read_history, |
| 1190 | Command::ReadHistory { |
| 1191 | request_id, |
| 1192 | window_ms: 60_000, |
| 1193 | .. |
| 1194 | } if request_id == "history-1" |
| 1195 | )); |
| 1196 | |
| 1197 | let process_table = serde_json::from_str::<Command>( |
| 1198 | r#"{"version":3,"type":"processTable","requestId":"processes-1"}"#, |
| 1199 | ) |
| 1200 | .expect("process table command"); |
| 1201 | assert!(matches!( |
| 1202 | process_table, |
| 1203 | Command::ProcessTable { request_id, .. } if request_id == "processes-1" |
| 1204 | )); |
| 1205 | } |
| 1206 | |
| 1207 | #[test] |
| 1208 | fn clamps_sample_interval() { |
| 1209 | assert_eq!(clamp_sample_interval(0), None); |
| 1210 | assert_eq!(clamp_sample_interval(1), Some(Duration::from_millis(250))); |
| 1211 | assert_eq!( |
| 1212 | clamp_sample_interval(100_000), |
| 1213 | Some(Duration::from_millis(60_000)) |
| 1214 | ); |
| 1215 | } |
| 1216 | |
| 1217 | #[test] |
| 1218 | fn counts_selected_processes_that_could_not_be_materialized() { |
| 1219 | assert_eq!(inaccessible_process_count(5, 3), 2); |
| 1220 | assert_eq!(inaccessible_process_count(3, 5), 0); |
| 1221 | } |
| 1222 | |
| 1223 | #[test] |
| 1224 | fn waits_for_a_cpu_measurement_window_after_priming() { |
| 1225 | let baseline = Instant::now(); |
| 1226 | |
| 1227 | assert_eq!( |
| 1228 | remaining_cpu_measurement_delay(Some(baseline), baseline), |
| 1229 | Some(MINIMUM_CPU_UPDATE_INTERVAL) |
| 1230 | ); |
| 1231 | assert_eq!( |
| 1232 | remaining_cpu_measurement_delay(Some(baseline), baseline + MINIMUM_CPU_UPDATE_INTERVAL), |
| 1233 | None |
| 1234 | ); |
| 1235 | assert_eq!(remaining_cpu_measurement_delay(None, baseline), None); |
| 1236 | } |
| 1237 | |
| 1238 | #[test] |
| 1239 | fn retains_bounded_history_without_request_ids() { |
| 1240 | let mut history = HistoryRecorder::default(); |
| 1241 | for sequence in 0..=MAX_HISTORY_SNAPSHOTS { |
| 1242 | history.record(&SnapshotEvent { |
| 1243 | version: PROTOCOL_VERSION, |
| 1244 | event_type: "snapshot", |
| 1245 | sequence: sequence as u64, |
| 1246 | sampled_at_unix_ms: sequence as u64 * 1_000, |
| 1247 | collection_duration_micros: 1, |
| 1248 | scanned_process_count: 0, |
| 1249 | retained_process_count: 0, |
| 1250 | inaccessible_process_count: 0, |
| 1251 | request_id: Some("request".to_owned()), |
| 1252 | external_processes: vec![ExternalProcess { |
| 1253 | pid: 7, |
| 1254 | start_time_ms: Some(1_000), |
| 1255 | }], |
| 1256 | processes: Vec::new(), |
| 1257 | }); |
| 1258 | } |
| 1259 | |
| 1260 | assert_eq!(history.snapshots.len(), MAX_HISTORY_SNAPSHOTS); |
| 1261 | assert!( |
| 1262 | history |
| 1263 | .snapshots |
| 1264 | .iter() |
| 1265 | .all(|snapshot| snapshot.request_id.is_none()) |
| 1266 | ); |
| 1267 | assert!(history.snapshots.iter().all(|snapshot| { |
| 1268 | snapshot.external_processes.len() == 1 |
| 1269 | && snapshot.external_processes[0].pid == 7 |
| 1270 | && snapshot.external_processes[0].start_time_ms == Some(1_000) |
| 1271 | })); |
| 1272 | assert_eq!( |
| 1273 | history |
| 1274 | .read(10_000, MAX_HISTORY_SNAPSHOTS as u64 * 1_000) |
| 1275 | .len(), |
| 1276 | 11 |
| 1277 | ); |
| 1278 | } |
| 1279 | |
| 1280 | #[test] |
| 1281 | fn excludes_and_trims_future_history_after_the_clock_moves_backward() { |
| 1282 | let mut history = HistoryRecorder::default(); |
| 1283 | let snapshot = SnapshotEvent { |
| 1284 | version: PROTOCOL_VERSION, |
| 1285 | event_type: "snapshot", |
| 1286 | sequence: 1, |
| 1287 | sampled_at_unix_ms: 2_000, |
| 1288 | collection_duration_micros: 1, |
| 1289 | scanned_process_count: 0, |
| 1290 | retained_process_count: 0, |
| 1291 | inaccessible_process_count: 0, |
| 1292 | request_id: None, |
| 1293 | external_processes: Vec::new(), |
| 1294 | processes: Vec::new(), |
| 1295 | }; |
| 1296 | history.record(&snapshot); |
| 1297 | |
| 1298 | assert!(history.read(0, 1_000).is_empty()); |
| 1299 | |
| 1300 | history.record(&SnapshotEvent { |
| 1301 | sequence: 2, |
| 1302 | sampled_at_unix_ms: 1_000, |
| 1303 | ..snapshot |
| 1304 | }); |
| 1305 | assert_eq!(history.snapshots.len(), 1); |
| 1306 | assert_eq!( |
| 1307 | history.snapshots.front().map(|entry| entry.sequence), |
| 1308 | Some(2) |
| 1309 | ); |
| 1310 | } |
| 1311 | |
| 1312 | #[test] |
| 1313 | fn bounds_history_by_estimated_process_bytes() { |
| 1314 | let mut history = HistoryRecorder::default(); |
| 1315 | let command = "x".repeat(128); |
| 1316 | let process = ProcessSample { |
| 1317 | pid: 1, |
| 1318 | ppid: 0, |
| 1319 | start_time_ms: 0, |
| 1320 | run_time_ms: 0, |
| 1321 | name: "process".to_owned(), |
| 1322 | command, |
| 1323 | status: "Run".to_owned(), |
| 1324 | cpu_percent: 0.0, |
| 1325 | cpu_time_ms: 0, |
| 1326 | resident_bytes: 0, |
| 1327 | virtual_bytes: 0, |
| 1328 | io_read_bytes: 0, |
| 1329 | io_write_bytes: 0, |
| 1330 | io_semantics: IoSemantics::Storage, |
| 1331 | }; |
| 1332 | let snapshot_bytes = |
| 1333 | std::mem::size_of::<SnapshotEvent>() + process.estimated_history_bytes(); |
| 1334 | for sequence in 0..3 { |
| 1335 | history.record_with_limits( |
| 1336 | &SnapshotEvent { |
| 1337 | version: PROTOCOL_VERSION, |
| 1338 | event_type: "snapshot", |
| 1339 | sequence, |
| 1340 | sampled_at_unix_ms: sequence * 1_000, |
| 1341 | collection_duration_micros: 1, |
| 1342 | scanned_process_count: 1, |
| 1343 | retained_process_count: 1, |
| 1344 | inaccessible_process_count: 0, |
| 1345 | request_id: None, |
| 1346 | external_processes: Vec::new(), |
| 1347 | processes: vec![ProcessSample { |
| 1348 | pid: sequence as u32 + 1, |
| 1349 | start_time_ms: sequence * 1_000, |
| 1350 | ..process.clone() |
| 1351 | }], |
| 1352 | }, |
| 1353 | 3, |
| 1354 | 3, |
| 1355 | snapshot_bytes * 2, |
| 1356 | ); |
| 1357 | } |
| 1358 | |
| 1359 | assert!(history.retained_bytes <= snapshot_bytes * 2); |
| 1360 | assert_eq!(history.snapshots.len(), 2); |
| 1361 | assert_eq!( |
| 1362 | history.snapshots.front().map(|snapshot| snapshot.sequence), |
| 1363 | Some(1) |
| 1364 | ); |
| 1365 | } |
| 1366 | |
| 1367 | #[test] |
| 1368 | fn counts_external_processes_toward_history_limits() { |
| 1369 | let mut history = HistoryRecorder::default(); |
| 1370 | let external_processes = (1..=128) |
| 1371 | .map(|pid| ExternalProcess { |
| 1372 | pid, |
| 1373 | start_time_ms: Some(u64::from(pid) * 1_000), |
| 1374 | }) |
| 1375 | .collect::<Vec<_>>(); |
| 1376 | let snapshot = SnapshotEvent { |
| 1377 | version: PROTOCOL_VERSION, |
| 1378 | event_type: "snapshot", |
| 1379 | sequence: 0, |
| 1380 | sampled_at_unix_ms: 0, |
| 1381 | collection_duration_micros: 1, |
| 1382 | scanned_process_count: 0, |
| 1383 | retained_process_count: 0, |
| 1384 | inaccessible_process_count: 0, |
| 1385 | request_id: None, |
| 1386 | external_processes, |
| 1387 | processes: Vec::new(), |
| 1388 | }; |
| 1389 | let snapshot_bytes = snapshot.estimated_history_bytes(); |
| 1390 | let snapshot_entries = snapshot.retained_entry_count(); |
| 1391 | |
| 1392 | for sequence in 0..3 { |
| 1393 | history.record_with_limits( |
| 1394 | &SnapshotEvent { |
| 1395 | sequence, |
| 1396 | sampled_at_unix_ms: sequence * 1_000, |
| 1397 | ..snapshot.clone() |
| 1398 | }, |
| 1399 | 3, |
| 1400 | snapshot_entries * 2, |
| 1401 | snapshot_bytes * 2, |
| 1402 | ); |
| 1403 | } |
| 1404 | |
| 1405 | assert_eq!(history.retained_entry_count, snapshot_entries * 2); |
| 1406 | assert!(history.retained_bytes <= snapshot_bytes * 2); |
| 1407 | assert_eq!(history.snapshots.len(), 2); |
| 1408 | assert_eq!( |
| 1409 | history.snapshots.front().map(|snapshot| snapshot.sequence), |
| 1410 | Some(1) |
| 1411 | ); |
| 1412 | } |
| 1413 | |
| 1414 | #[test] |
| 1415 | fn truncates_process_strings_at_utf8_boundaries() { |
| 1416 | let value = "é".repeat(MAX_PROCESS_NAME_BYTES); |
| 1417 | let truncated = truncate_utf8(value, MAX_PROCESS_NAME_BYTES - 1); |
| 1418 | |
| 1419 | assert!(truncated.len() < MAX_PROCESS_NAME_BYTES); |
| 1420 | assert!(truncated.is_char_boundary(truncated.len())); |
| 1421 | } |
| 1422 | |
| 1423 | #[test] |
| 1424 | fn parses_proc_stat_names_with_spaces_and_parentheses() { |
| 1425 | assert_eq!( |
| 1426 | parse_proc_stat(b"4242 (tmux: server) S 1 4242 4242 0 -1 4194560 3101"), |
| 1427 | Some(("tmux: server".to_owned(), 1)) |
| 1428 | ); |
| 1429 | assert_eq!( |
| 1430 | parse_proc_stat(b"77 (a) b (c)) R 4242 77 77 34816 77 4194304"), |
| 1431 | Some(("a) b (c)".to_owned(), 4242)) |
| 1432 | ); |
| 1433 | assert_eq!(parse_proc_stat(b"77 (truncated"), None); |
| 1434 | } |
| 1435 | |
| 1436 | #[cfg(target_os = "linux")] |
| 1437 | #[test] |
| 1438 | fn linux_process_table_reports_own_process_like_sysinfo() { |
| 1439 | let collector = Collector::new(); |
| 1440 | let mut system = System::new(); |
| 1441 | system.refresh_processes_specifics( |
| 1442 | ProcessesToUpdate::All, |
| 1443 | true, |
| 1444 | ProcessRefreshKind::nothing().without_tasks(), |
| 1445 | ); |
| 1446 | let own_pid = std::process::id(); |
| 1447 | let table = collector.process_table(); |
| 1448 | let own = table |
| 1449 | .iter() |
| 1450 | .find(|process| process.pid == own_pid) |
| 1451 | .expect("own process"); |
| 1452 | let expected = system |
| 1453 | .process(Pid::from_u32(own_pid)) |
| 1454 | .expect("sysinfo own process"); |
| 1455 | assert_eq!(own.ppid, expected.parent().map(Pid::as_u32).unwrap_or(0)); |
| 1456 | assert_eq!(own.name, expected.name().to_string_lossy()); |
| 1457 | assert!(table.windows(2).all(|pair| pair[0].pid < pair[1].pid)); |
| 1458 | } |
| 1459 | |
| 1460 | #[test] |
| 1461 | fn refreshes_commands_without_enumerating_linux_tasks() { |
| 1462 | let refresh_kind = process_refresh_kind(); |
| 1463 | |
| 1464 | assert_eq!(refresh_kind.cmd(), UpdateKind::Always); |
| 1465 | assert!(!refresh_kind.tasks()); |
| 1466 | assert!(refresh_kind.cpu()); |
| 1467 | assert!(refresh_kind.memory()); |
| 1468 | assert!(refresh_kind.disk_usage()); |
| 1469 | } |
| 1470 | |
| 1471 | #[test] |
| 1472 | fn sample_now_does_not_postpone_an_existing_periodic_deadline() { |
| 1473 | let now = Instant::now(); |
| 1474 | let deadline = now + Duration::from_secs(1); |
| 1475 | |
| 1476 | assert_eq!( |
| 1477 | sample_now_deadline( |
| 1478 | Some(deadline), |
| 1479 | Some(Duration::from_secs(5)), |
| 1480 | now + Duration::from_millis(100) |
| 1481 | ), |
| 1482 | Some(deadline) |
| 1483 | ); |
| 1484 | } |
| 1485 | } |