troll 0.4.0

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use std::{
    fs::{self, File, OpenOptions, TryLockError},
    io,
    path::Path,
    sync::atomic::{AtomicU64, Ordering},
};

use serde::Serialize;
use time::OffsetDateTime;
use troll_core::{
    Config, ConfigError, DriftCounts, StoreError, drift_with_protocols, duplicate_ports,
};
use troll_probe::ListenerProbe;

use crate::{
    error::CliError,
    output::{self, SCHEMA},
    platform,
    serve::status::{FILE_NAME, ServiceStatus},
};

use super::read_config;

#[derive(Serialize)]
struct Row {
    name: &'static str,
    status: &'static str,
    detail: String,
}
impl Row {
    fn new(name: &'static str, status: &'static str, detail: impl Into<String>) -> Self {
        Self {
            name,
            status,
            detail: detail.into().replace(['\n', '\r'], " "),
        }
    }
}
#[derive(Serialize)]
struct DoctorOutput {
    schema: u32,
    checks: Vec<Row>,
    counts: Option<DriftCounts>,
}

fn build_report() -> (DoctorOutput, i32) {
    let mut checks = Vec::new();
    let ephemeral = platform::proc_probe().ephemeral_range();
    let mut overlap = None;
    let config = (|| {
        let home = platform::config_home().map_err(|e| e.to_string())?;
        let path = home.join("config.toml");
        let text = read_config(&path).map_err(|e| e.to_string())?;
        let range = ephemeral.as_ref().ok().and_then(|range| range.clone());
        match Config::parse(&home, &text, range) {
            Err(
                error @ (ConfigError::EphemeralOverlap { .. }
                | ConfigError::AppEphemeralOverlap { .. }),
            ) => {
                // Diagnose kernel range conflicts separately so the registry
                // can still be inspected with the configured location.
                overlap = Some(error);
                Config::parse(&home, &text, None)
            }
            result => result,
        }
        .map_err(|e| e.to_string())
    })();
    checks.push(match &config {
        Ok(c) => match c
            .app_range_notice()
            .filter(|_| ephemeral.is_ok() && overlap.is_none())
        {
            Some(notice) => {
                eprintln!("{notice}");
                Row::new("config", "warning", notice)
            }
            None => Row::new("config", "ok", "configuration and policy valid"),
        },
        Err(e) => Row::new("config", "failed", e),
    });
    checks.push(match (&config, ephemeral, overlap) {
        (_, Err(e), _) => Row::new(
            "ranges sane",
            "failed",
            CliError::EphemeralRange(e).to_string(),
        ),
        (_, _, Some(error)) => Row::new("ranges sane", "failed", error.to_string()),
        (Err(_), _, _) => Row::new(
            "ranges sane",
            "warning",
            "configuration unavailable; overlap not checked",
        ),
        (Ok(_), Ok(None), None) => Row::new(
            "ranges sane",
            "warning",
            "ephemeral range probing unsupported on this platform; overlap not checked",
        ),
        (Ok(_), Ok(Some(_)), None) => Row::new(
            "ranges sane",
            "ok",
            "app, lease and ephemeral ranges do not overlap",
        ),
    });
    let mut registry = None;
    let mut lock_timed_out = false;
    if let Ok(c) = &config {
        let home = &c.registry_home;
        if matches!(home.components().as_path().symlink_metadata(), Err(ref e) if e.kind() == io::ErrorKind::NotFound)
        {
            checks.push(Row::new(
                "registry readable",
                "ok",
                "empty, created on first write",
            ));
            registry = Some(Default::default());
            checks.push(Row::new(
                "locking self-test",
                "warning",
                "registry home does not exist yet",
            ));
            checks.push(Row::new(
                "hard links",
                "warning",
                "registry home does not exist yet",
            ));
        } else {
            match platform::open_store(home).load() {
                Ok(r) => {
                    let detail = if home.join("registry.toml").exists() {
                        "registry loaded and validated"
                    } else {
                        "empty, created on first write"
                    };
                    checks.push(Row::new("registry readable", "ok", detail));
                    registry = Some(r);
                }
                Err(e) => {
                    lock_timed_out = matches!(e, StoreError::Locked { .. });
                    checks.push(Row::new(
                        "registry readable",
                        "failed",
                        CliError::from(e).to_string(),
                    ));
                }
            }
            checks.push(match locking(home) {
                Ok(true) => Row::new(
                    "locking self-test",
                    "ok",
                    "independent handles exclude each other",
                ),
                Ok(false) => Row::new(
                    "locking self-test",
                    "warning",
                    "registry lock is held by another troll process; self-test skipped",
                ),
                Err(e) => Row::new("locking self-test", "failed", e),
            });
            checks.push(match hard_links(home) {
                Ok(()) => Row::new("hard links", "ok", "hard links work"),
                Err(e) => Row::new(
                    "hard links",
                    "failed",
                    format!("first registry write needs hard links: {e}"),
                ),
            });
        }
    } else {
        for name in ["registry readable", "locking self-test", "hard links"] {
            checks.push(Row::new(
                name,
                "warning",
                "configuration unavailable; check skipped",
            ));
        }
    }
    if let Some(registry) = &registry {
        for port in duplicate_ports(registry) {
            checks.push(Row::new(
                "duplicate ports",
                "warning",
                format!(
                    "port {port} is held by more than one entry, and troll refuses to choose. The maintainer decides which entry moves and repairs the registry with other troll writers stopped. Agents report the duplicate and stop."
                ),
            ));
        }
    }
    let scan = platform::probe().and_then(|p| p.report());
    checks.push(match &scan {
        Ok(r) if r.skipped_rows == 0 => Row::new("probe", "ok", "listener probe succeeded"),
        Ok(r) => Row::new(
            "probe",
            "warning",
            format!("{} malformed rows in socket tables", r.skipped_rows),
        ),
        Err(e) => Row::new("probe", "failed", e.to_string()),
    });
    checks.push(service_row());
    let ephemeral_range = platform::proc_probe().ephemeral_range().ok().flatten();
    let counts = match (&registry, &scan) {
        (Some(r), Ok(scan)) => {
            let sockets: Vec<_> = scan
                .listeners
                .iter()
                .map(|s| (s.port, s.protocol, s.addr))
                .collect();
            let report = drift_with_protocols(r, &sockets, OffsetDateTime::now_utc());
            let mut counts = report.counts();
            counts.listening_unclaimed = report
                .listening_unclaimed_sockets
                .iter()
                .filter(|&&(port, proto, _)| {
                    !super::inspect::hide_ephemeral_udp(
                        port,
                        proto,
                        ephemeral_range.as_ref(),
                        false,
                    )
                })
                .count();
            Some(counts)
        }
        _ => None,
    };
    let summary = counts.as_ref().map(|c| {
        format!(
            "{} listening unclaimed, {} claimed silent, {} leases expiring",
            c.listening_unclaimed, c.claimed_silent, c.leases_expiring
        )
    });
    let skipped_rows = scan.as_ref().map_or(0, |scan| scan.skipped_rows);
    checks.push(match (summary, skipped_rows) {
        (Some(summary), 0) => Row::new(
            "drift counts",
            "ok",
            format!("{summary}; see troll list --drift"),
        ),
        (None, 0) => Row::new("drift counts", "warning", "unavailable; see earlier checks"),
        (summary, skipped_rows) => {
            let summary = summary.as_deref().unwrap_or("counts unavailable");
            Row::new(
                "drift counts",
                "warning",
                format!("{summary}; listener scan skipped {skipped_rows} malformed rows"),
            )
        }
    });
    let zone_conflicts = counts
        .as_ref()
        .map(|counts| counts.zone_conflicts)
        .or_else(|| registry.as_ref().map(|r| r.zone_conflicts().len()));
    checks.push(zone_conflicts_row(zone_conflicts));
    for (label, proto_name, excluded) in [
        (
            "os excluded ranges",
            "TCP",
            troll_probe::excluded_ranges().unwrap_or_default(),
        ),
        (
            "os excluded udp ranges",
            "UDP",
            troll_probe::excluded_udp_ranges().unwrap_or_default(),
        ),
    ] {
        if !excluded.is_empty() {
            let summary = excluded
                .iter()
                .take(8)
                .map(|r| {
                    if r.start() == r.end() {
                        r.start().to_string()
                    } else {
                        format!("{}–{}", r.start(), r.end())
                    }
                })
                .collect::<Vec<_>>()
                .join(", ");
            let suffix = if excluded.len() > 8 {
                format!(" (+{} more)", excluded.len() - 8)
            } else {
                String::new()
            };
            checks.push(Row::new(
                label,
                "ok",
                format!(
                    "{} reserved {proto_name} ranges: {summary}{suffix}",
                    excluded.len()
                ),
            ));
        }
    }
    let failed = checks.iter().any(|r| r.status == "failed");
    let result = DoctorOutput {
        schema: SCHEMA,
        checks,
        counts,
    };
    (result, if lock_timed_out { 4 } else { i32::from(failed) })
}

fn zone_conflicts_row(count: Option<usize>) -> Row {
    match count {
        Some(0) => Row::new("zone conflicts", "ok", "no allocations in enabled zones"),
        Some(count) => Row::new(
            "zone conflicts",
            "warning",
            format!("{count} conflicting allocations; see troll list --drift"),
        ),
        None => Row::new(
            "zone conflicts",
            "warning",
            "registry unavailable; check skipped",
        ),
    }
}

pub(super) fn run(json: bool, style: crate::style::Style) -> Result<i32, CliError> {
    let (result, exit_code) = build_report();
    output::write(json, &result, |out| {
        if style.is_human() {
            let mut table = crate::style::Table::new(&["CHECK", "STATUS", "DETAIL"]);
            for row in &result.checks {
                table.row(vec![
                    crate::style::Cell::plain(row.name),
                    style.status_cell(row.status),
                    crate::style::Cell::plain(crate::style::display(&row.detail)),
                ]);
            }
            write!(out, "{}", table.render(style, ""))?;
        } else {
            for row in &result.checks {
                writeln!(out, "{}: {} — {}", row.name, row.status, row.detail)?;
            }
        }
        Ok(())
    })?;
    Ok(exit_code)
}

fn service_row() -> Row {
    let state_dir = match platform::state_home() {
        Ok(state_dir) => state_dir,
        Err(error) => return Row::new("service", "warning", error.to_string()),
    };
    let path = state_dir.join(FILE_NAME);
    let status = match ServiceStatus::read(&path) {
        Ok(Some(status)) => status,
        Ok(None) => return Row::new("service", "ok", "not running"),
        Err(error) => {
            return Row::new(
                "service",
                "warning",
                format!("could not read {}: {error}", path.display()),
            );
        }
    };
    match status.live_port(&platform::proc_probe()) {
        Ok(Some(port)) => Row::new("service", "ok", format!("running on port {port}")),
        Ok(None) => Row::new("service", "ok", "not running (stale status file)"),
        Err(error) => Row::new(
            "service",
            "warning",
            format!("could not verify {}: {error}", path.display()),
        ),
    }
}

fn locking(home: &Path) -> Result<bool, String> {
    let path = home.join("registry.lock");
    let metadata = fs::symlink_metadata(&path).map_err(|e| e.to_string())?;
    if !metadata.is_file() {
        return Err("registry lock is not a regular file".into());
    }
    let first = OpenOptions::new()
        .read(true)
        .write(true)
        .open(&path)
        .map_err(|e| e.to_string())?;
    match first.try_lock() {
        Ok(()) => {}
        Err(TryLockError::WouldBlock) => return Ok(false),
        Err(TryLockError::Error(e)) => {
            return Err(format!(
                "could not acquire registry lock for self-test: {e}"
            ));
        }
    }
    let second = OpenOptions::new()
        .read(true)
        .write(true)
        .open(&path)
        .map_err(|e| e.to_string())?;
    match second.try_lock() {
        Err(TryLockError::WouldBlock) => Ok(true),
        Ok(()) => Err(
            "file locking does not work on this filesystem; do not keep the registry here".into(),
        ),
        Err(TryLockError::Error(e)) => Err(format!("could not test registry lock: {e}")),
    }
}

static SEQUENCE: AtomicU64 = AtomicU64::new(0);
fn hard_links(home: &Path) -> io::Result<()> {
    loop {
        let id = SEQUENCE.fetch_add(1, Ordering::Relaxed);
        let source = home.join(format!(".troll-doctor-{}-{id}", std::process::id()));
        let target = home.join(format!(".troll-doctor-{}-{id}.link", std::process::id()));
        let file = match File::create_new(&source) {
            Ok(f) => f,
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(e),
        };
        drop(file);
        let linked = fs::hard_link(&source, &target);
        let remove_target = if linked.is_ok() {
            fs::remove_file(&target)
        } else {
            Ok(())
        };
        let remove_source = fs::remove_file(&source);
        linked.and(remove_target).and(remove_source)?;
        return Ok(());
    }
}

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

    #[test]
    fn zone_check_warns_with_count_and_is_ok_when_clean() {
        let clean = zone_conflicts_row(Some(0));
        assert_eq!(clean.name, "zone conflicts");
        assert_eq!(clean.status, "ok");

        let conflicts = zone_conflicts_row(Some(2));
        assert_eq!(conflicts.status, "warning");
        assert!(conflicts.detail.contains("2 conflicting allocations"));
        assert!(conflicts.detail.contains("troll list --drift"));
    }
}