1use std::{
18 os::unix::ffi::OsStrExt as _,
19 path::{Path, PathBuf},
20};
21
22use kizz_store::{
23 AccessBits, BuildId, Connection, MachinePart, MachineStateRecord, PathState, StepKey,
24 StepPosition, StepRecord, Store, StoreError, TaskId, TaskLabel, TaskRecord, Verdict,
25 path_prefix,
26};
27
28use crate::{explain::RepeatedWarning, render::Render};
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct WhyStep {
33 pub position: u32,
35 pub key: StepKey,
37 pub verdict: Verdict,
39 pub argv: Option<Vec<String>>,
41 pub untracked: Vec<(PathBuf, AccessBits)>,
44 pub ignored: u64,
46 pub unknown_system_calls: Vec<u32>,
49 pub connections: Vec<Connection>,
52 pub machine_names: Vec<String>,
55 pub machine: MachineStateRecord,
58}
59
60impl WhyStep {
61 #[must_use]
64 pub fn command(&self) -> String {
65 self.argv.as_ref().map_or_else(
66 || "(the step record is no longer in the cache)".to_owned(),
67 |argv| argv.join(" "),
68 )
69 }
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct WhyTask {
75 pub id: TaskId,
77 pub record: TaskRecord,
79 pub steps: Vec<WhyStep>,
81}
82
83impl WhyTask {
84 #[must_use]
86 pub fn label(&self) -> TaskLabel {
87 TaskLabel {
88 task: self.id.clone(),
89 line: self.record.line,
90 heading: self.record.heading.clone(),
91 }
92 }
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct WhyReport {
98 pub path: PathBuf,
100 pub build: Option<BuildId>,
103 pub tasks: Vec<WhyTask>,
106}
107
108impl WhyReport {
109 #[must_use]
112 pub fn warnings(&self) -> Vec<RepeatedWarning> {
113 self.tasks
114 .iter()
115 .flat_map(|task| {
116 task.steps.iter().filter_map(|step| {
117 match &step.verdict {
118 Verdict::Ran(explanation) if !explanation.repeated.is_empty() => {
119 Some(RepeatedWarning {
120 task: Some(task.label()),
121 position: step.position,
122 command: step.command(),
123 paths: explanation.repeated.clone(),
124 })
125 },
126 Verdict::Ran(_) | Verdict::Cached => None,
127 }
128 })
129 })
130 .collect()
131 }
132}
133
134pub fn why(
141 store: &Store,
142 path: &Path,
143) -> Result<WhyReport, StoreError> {
144 let txn = store.read()?;
145 let prefix = if path.is_file() {
146 let mut prefix = path.as_os_str().as_bytes().to_vec();
148 prefix.push(0);
149 prefix
150 } else {
151 path_prefix(path)
152 };
153 let records = txn.scan::<TaskRecord>(&prefix)?;
154 let build = records.iter().map(|(_, record)| record.build).max();
155 let mut tasks = Vec::new();
156 for (id, record) in records {
157 if Some(record.build) != build {
158 continue;
159 }
160 let mut steps = Vec::new();
161 for (key, position) in txn.scan::<StepPosition>(&id.key_prefix())? {
162 if key.task != id || key.position >= record.steps {
163 continue;
164 }
165 steps.push(step(
166 txn.get::<StepRecord>(&position.step)?,
167 key.position,
168 position,
169 ));
170 }
171 tasks.push(WhyTask { id, record, steps });
172 }
173 Ok(WhyReport {
174 path: path.to_path_buf(),
175 build,
176 tasks,
177 })
178}
179
180fn step(
183 record: Option<StepRecord>,
184 position: u32,
185 stored: StepPosition,
186) -> WhyStep {
187 let (argv, untracked, ignored, unknown_system_calls, connections, machine_names, machine) =
188 record.map_or_else(
189 || {
190 (
191 None,
192 Vec::new(),
193 0,
194 Vec::new(),
195 Vec::new(),
196 Vec::new(),
197 MachineStateRecord::default(),
198 )
199 },
200 |record| {
201 let untracked = record
202 .observations
203 .iter()
204 .filter(|observation| observation.state == PathState::Untracked)
205 .map(|observation| (observation.path.clone(), observation.access))
206 .collect();
207 (
208 Some(record.spec.argv),
209 untracked,
210 record.ignored,
211 record.unknown_system_calls,
212 record.connections,
213 record.spec.machine,
214 record.machine,
215 )
216 },
217 );
218 WhyStep {
219 position,
220 key: stored.step,
221 verdict: stored.verdict,
222 argv,
223 untracked,
224 ignored,
225 unknown_system_calls,
226 connections,
227 machine_names,
228 machine,
229 }
230}
231
232impl Render {
233 #[must_use]
240 pub fn why(
241 &self,
242 report: &WhyReport,
243 ) -> String {
244 let path = format!("`{}`", self.path(&report.path));
245 if report.tasks.is_empty() {
246 if report.build.is_some() {
247 return format!(
248 "No tasks matched the filter in the most recent build under {path}.\n"
249 );
250 }
251 return format!("No build has recorded a task under {path}.\n");
252 }
253 let tasks = if report.tasks.len() == 1 {
254 "1 task".to_owned()
255 } else {
256 format!("{} tasks", report.tasks.len())
257 };
258 let mut lines = vec![format!("The most recent build ran {tasks} under {path}.")];
259 for task in &report.tasks {
260 let failed = if task.record.succeeded {
261 ""
262 } else {
263 " (failed)"
264 };
265 lines.push(String::new());
266 lines.push(format!(
267 "{} [{}]{failed}",
268 self.task(&task.label()),
269 task.record.targets.join(", ")
270 ));
271 if task.steps.is_empty() {
272 lines.push(" no commands ran".to_owned());
273 }
274 for step in &task.steps {
275 lines.push(format!(
276 " step {}: `{}`",
277 step.position.saturating_add(1),
278 step.command()
279 ));
280 lines.extend(
281 self.full(&step.verdict)
282 .into_iter()
283 .map(|line| format!(" {line}")),
284 );
285 lines.push(format!(" {}", self.untracked(&step.untracked)));
286 lines.push(format!(" {}", self.connections(&step.connections)));
287 if !step.unknown_system_calls.is_empty() {
288 let numbers: Vec<String> = step
289 .unknown_system_calls
290 .iter()
291 .map(ToString::to_string)
292 .collect();
293 lines.push(format!(
294 " system calls that the tracer does not know: {}",
295 numbers.join(", ")
296 ));
297 }
298 if step.argv.is_some() {
299 lines.extend(
300 self.machine(step)
301 .into_iter()
302 .map(|line| format!(" {line}")),
303 );
304 }
305 lines.push(format!(" ignored accesses: {}", step.ignored));
306 }
307 }
308 lines.push(String::new());
309 lines.join("\n")
310 }
311
312 fn machine(
316 &self,
317 step: &WhyStep,
318 ) -> Vec<String> {
319 MachinePart::ALL
320 .into_iter()
321 .filter_map(|part| {
322 let named = step.machine_names.iter().any(|name| name == part.name());
323 let text = step.machine.text(part);
324 match (named, self.verbose) {
325 (true, true) => Some(format!("machine {part} (checked): {text}")),
326 (true, false) | (false, true) => Some(format!("machine {part}: {text}")),
327 (false, false) => None,
328 }
329 })
330 .collect()
331 }
332
333 fn connections(
336 &self,
337 connections: &[Connection],
338 ) -> String {
339 if connections.is_empty() {
340 return "connections: none".to_owned();
341 }
342 let shown: Vec<String> = connections
343 .iter()
344 .map(|connection| connection.text(|path| format!("`{}`", self.path(path))))
345 .collect();
346 format!("connections: {}", shown.join(", "))
347 }
348
349 fn untracked(
351 &self,
352 untracked: &[(PathBuf, AccessBits)],
353 ) -> String {
354 if untracked.is_empty() {
355 return "untracked /proc and /sys accesses: none".to_owned();
356 }
357 let shown: Vec<String> = untracked
358 .iter()
359 .map(|(path, access)| {
360 format!(
361 "`{}` ({})",
362 self.path(path),
363 crate::render::access_kinds(*access)
364 )
365 })
366 .collect();
367 format!("untracked /proc and /sys accesses: {}", shown.join(", "))
368 }
369}