ping-rust 0.2.2

Menu-driven installer and manager for the shoes proxy server
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use std::{collections::BTreeSet, fs, path::Path, process::Command, thread, time::Duration};

use anyhow::{bail, Context, Result};
use clap::ValueEnum;

use crate::{installer, performance, utils};

pub const SERVICE_NAME: &str = "shoes.service";
const RESET_FAILED_COMMAND: &[&str] = &["reset-failed", SERVICE_NAME];
const ENABLE_NOW_COMMAND: &[&str] = &["enable", "--now", SERVICE_NAME];
const START_COMMAND: &[&str] = &["start", SERVICE_NAME];
const RESTART_COMMAND: &[&str] = &["restart", SERVICE_NAME];

pub struct ServiceSnapshot {
    unit_contents: Option<Vec<u8>>,
    was_active: bool,
    was_enabled: bool,
    main_pid: Option<u32>,
}

impl ServiceSnapshot {
    pub fn was_active(&self) -> bool {
        self.was_active
    }
}

pub struct HotReloadSnapshot {
    pub main_pid: u32,
    pub listening_ports: BTreeSet<u16>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HotReloadReason {
    ServiceNotRunning,
    UnitModified,
    ShoesSourceUnsupported(installer::ShoesProvenance),
    DropInPresent,
    AnchorNotReady,
    ListenerSnapshotMismatch,
    InspectionFailed(String),
}

impl HotReloadReason {
    pub fn restart_notice(&self) -> String {
        let reason = match self {
            Self::ServiceNotRunning => "shoes 服务未运行".to_owned(),
            Self::UnitModified => "shoes unit 内容或加载路径已被修改".to_owned(),
            Self::ShoesSourceUnsupported(shoes) if shoes.source == "github-release" => format!(
                "当前 shoes 来源为 GitHub Release {},热重载需要固定 pin 构建",
                shoes.release_tag.as_deref().unwrap_or("(版本未知)")
            ),
            Self::ShoesSourceUnsupported(_) => {
                "shoes 来源或 revision 不满足固定 pin 验证要求".to_owned()
            }
            Self::DropInPresent => "shoes unit 存在 drop-in".to_owned(),
            Self::AnchorNotReady => "热重载文件锚点未就绪".to_owned(),
            Self::ListenerSnapshotMismatch => {
                "当前监听与受管配置不一致,无法验证监听变更".to_owned()
            }
            Self::InspectionFailed(error) => format!("热重载前置检查失败:{error}"),
        };
        let switch = if matches!(self, Self::ShoesSourceUnsupported(_)) {
            "可在 Update Center 中切换到固定 pin,或运行 sudo ping-rust update --method cargo;需要源码编译时间和足够内存。"
        } else {
            "请检查服务、unit 和日志中的热重载前置条件。"
        };
        format!("{reason};本次使用受控重启。{switch}")
    }
}

pub enum HotReloadReadiness {
    Ready(HotReloadSnapshot),
    Unavailable(HotReloadReason),
}

impl HotReloadReadiness {
    pub fn is_ready(&self) -> bool {
        matches!(self, Self::Ready(_))
    }

    pub fn filter(self, predicate: impl FnOnce(&HotReloadSnapshot) -> bool) -> Self {
        match self {
            Self::Ready(snapshot) if !predicate(&snapshot) => {
                Self::Unavailable(HotReloadReason::ListenerSnapshotMismatch)
            }
            other => other,
        }
    }

    pub fn into_snapshot(self) -> Option<HotReloadSnapshot> {
        match self {
            Self::Ready(snapshot) => Some(snapshot),
            Self::Unavailable(_) => None,
        }
    }

    pub fn report_controlled_restart(&self, was_active: bool) {
        if let Self::Unavailable(reason) = self {
            if was_active {
                // Keep add --plain stdout as one URI line.
                eprintln!("提示:{}", reason.restart_notice());
            }
        }
    }
}

fn hot_reload_unavailable_reason(
    was_active: bool,
    unit_matches: bool,
    shoes: &installer::ShoesProvenance,
    drop_ins: &str,
    anchor_ready: bool,
) -> Option<HotReloadReason> {
    if !was_active {
        Some(HotReloadReason::ServiceNotRunning)
    } else if !unit_matches {
        Some(HotReloadReason::UnitModified)
    } else if shoes.source != "verified-pin"
        || shoes.revision.as_deref() != Some(installer::verified_pin())
    {
        Some(HotReloadReason::ShoesSourceUnsupported(shoes.clone()))
    } else if !drop_ins.is_empty() && drop_ins != "-" {
        Some(HotReloadReason::DropInPresent)
    } else if !anchor_ready {
        Some(HotReloadReason::AnchorNotReady)
    } else {
        None
    }
}

const HOT_RELOAD_TIMEOUT: Duration = Duration::from_secs(6);
const HOT_RELOAD_POLL: Duration = Duration::from_millis(200);

#[derive(Clone, Copy, Debug, ValueEnum)]
pub enum ServiceAction {
    Install,
    Start,
    Stop,
    Restart,
    Status,
    Enable,
    Disable,
}

pub fn unit_contents() -> String {
    format!(
        r#"[Unit]
Description=shoes proxy server managed by ping-rust
Documentation=https://github.com/cfal/shoes
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=root
Group=root
ExecStart={} {}
Restart=on-failure
RestartSec=3s
LimitNOFILE=1048576
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
ProtectControlGroups=true
ProtectKernelModules=true
ProtectKernelTunables=true
ReadOnlyPaths={}
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictSUIDSGID=true
LockPersonality=true
MemoryDenyWriteExecute=true
SystemCallArchitectures=native
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
"#,
        utils::SHOES_BIN,
        utils::CONFIG_FILE,
        utils::CONFIG_DIR
    )
}

pub fn install_unit(enable_now: bool) -> Result<()> {
    utils::require_linux_root()?;
    ensure_systemctl()?;
    let unit_exists = enable_now && Path::new(utils::SERVICE_FILE).exists();
    let was_active = unit_exists && systemctl_is_active()?;
    let was_failed = unit_exists && systemctl_is_failed()?;
    utils::atomic_write(
        Path::new(utils::SERVICE_FILE),
        unit_contents().as_bytes(),
        0o644,
    )?;
    let anchor_prepared = enable_now && prepare_anchor_before_start();
    systemctl(&["daemon-reload"])?;
    if enable_now {
        for command in activation_commands(was_active, was_failed) {
            systemctl(command)?;
        }
        if anchor_prepared {
            mark_anchor_after_start();
        }
    }
    Ok(())
}

pub fn activate_and_verify() -> Result<()> {
    let _timer = performance::stage("systemd_activate");
    install_unit(true)?;
    verify_active_stable(systemctl_is_active, || {
        thread::sleep(Duration::from_millis(750))
    })
}

pub fn restart_and_verify() -> Result<()> {
    utils::require_linux_root()?;
    ensure_systemctl()?;
    let anchor_prepared = prepare_anchor_before_start();
    systemctl_after_reset(RESTART_COMMAND)?;
    verify_active_stable(systemctl_is_active, || {
        thread::sleep(Duration::from_millis(750))
    })?;
    if anchor_prepared {
        mark_anchor_after_start();
    }
    Ok(())
}

fn prepare_anchor_before_start() -> bool {
    utils::refresh_hot_reload_anchor().is_ok()
}

fn mark_anchor_after_start() {
    if let Ok(Some(pid)) = main_pid() {
        let _ = utils::mark_hot_reload_anchor_pid(pid);
    }
}

fn verify_active_stable(
    mut probe: impl FnMut() -> Result<bool>,
    mut pause: impl FnMut(),
) -> Result<()> {
    if !probe()? {
        bail!("systemd 命令已返回成功,但 shoes.service 未处于 active 状态");
    }
    pause();
    if !probe()? {
        bail!("shoes.service 启动后未保持 active,可能已立即退出或进入自动重启");
    }
    Ok(())
}

pub fn capture_snapshot() -> Result<ServiceSnapshot> {
    utils::require_linux_root()?;
    ensure_systemctl()?;
    let path = Path::new(utils::SERVICE_FILE);
    let unit_contents = match fs::read(path) {
        Ok(contents) => Some(contents),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
        Err(error) => return Err(error).context("读取现有 systemd unit 失败"),
    };
    let unit_exists = unit_contents.is_some();
    let was_active = unit_exists && systemctl_is_active()?;
    Ok(ServiceSnapshot {
        unit_contents,
        was_active,
        was_enabled: unit_exists && systemctl_is_enabled()?,
        main_pid: was_active.then(main_pid).transpose()?.flatten(),
    })
}

pub fn capture_hot_reload_snapshot(snapshot: &ServiceSnapshot) -> Result<HotReloadReadiness> {
    if !snapshot.was_active {
        return Ok(HotReloadReadiness::Unavailable(
            HotReloadReason::ServiceNotRunning,
        ));
    }
    if snapshot.unit_contents.as_deref() != Some(unit_contents().as_bytes()) {
        return Ok(HotReloadReadiness::Unavailable(
            HotReloadReason::UnitModified,
        ));
    }
    if systemctl_show_value("FragmentPath")? != utils::SERVICE_FILE {
        return Ok(HotReloadReadiness::Unavailable(
            HotReloadReason::UnitModified,
        ));
    }
    let shoes = installer::load_provenance();
    if shoes.source != "verified-pin"
        || shoes.revision.as_deref() != Some(installer::verified_pin())
    {
        return Ok(HotReloadReadiness::Unavailable(
            HotReloadReason::ShoesSourceUnsupported(shoes),
        ));
    }
    let drop_ins = systemctl_show_value("DropInPaths")?;
    if !drop_ins.is_empty() && drop_ins != "-" {
        return Ok(HotReloadReadiness::Unavailable(
            HotReloadReason::DropInPresent,
        ));
    }
    let main_pid = snapshot
        .main_pid
        .context("shoes.service active but MainPID is unavailable")?;
    if let Some(reason) = hot_reload_unavailable_reason(
        snapshot.was_active,
        true,
        &shoes,
        &drop_ins,
        utils::hot_reload_anchor_ready(main_pid),
    ) {
        return Ok(HotReloadReadiness::Unavailable(reason));
    }
    let snapshot = HotReloadSnapshot {
        main_pid,
        listening_ports: listening_ports(main_pid)?,
    };
    Ok(HotReloadReadiness::Ready(snapshot))
}

pub fn hot_reload_and_verify(
    snapshot: HotReloadSnapshot,
    expected_ports: &BTreeSet<u16>,
    removed_ports: &BTreeSet<u16>,
) -> Result<()> {
    utils::notify_hot_reload_anchor()?;
    let deadline = std::time::Instant::now() + HOT_RELOAD_TIMEOUT;
    loop {
        let active = systemctl_is_active()?;
        let current_pid = main_pid()?.unwrap_or(0);
        let ports = if active && current_pid == snapshot.main_pid {
            listening_ports(current_pid)?
        } else {
            BTreeSet::new()
        };
        if reload_observation(
            snapshot.main_pid,
            current_pid,
            active,
            &ports,
            expected_ports,
            removed_ports,
        )? {
            return Ok(());
        }
        if std::time::Instant::now() >= deadline {
            bail!(
                "shoes 热重载未在 {:?} 内达到预期监听端口;当前={ports:?},期望新增={expected_ports:?},期望删除={removed_ports:?}",
                HOT_RELOAD_TIMEOUT
            );
        }
        thread::sleep(HOT_RELOAD_POLL);
    }
}

fn reload_observation(
    original_pid: u32,
    current_pid: u32,
    active: bool,
    ports: &BTreeSet<u16>,
    expected_ports: &BTreeSet<u16>,
    removed_ports: &BTreeSet<u16>,
) -> Result<bool> {
    if !active || current_pid == 0 {
        bail!("shoes 热重载后服务未保持 active");
    }
    if current_pid != original_pid {
        bail!(
            "shoes 热重载触发了进程重启(旧 MainPID={},新 MainPID={})",
            original_pid,
            current_pid
        );
    }
    Ok(expected_ports.is_subset(ports) && removed_ports.is_disjoint(ports))
}

pub fn main_pid() -> Result<Option<u32>> {
    let value = systemctl_show_value("MainPID")?;
    let pid = value
        .parse::<u32>()
        .with_context(|| format!("systemd 返回了无效 MainPID:{value}"))?;
    Ok((pid != 0).then_some(pid))
}

fn systemctl_show_value(property: &str) -> Result<String> {
    let output = Command::new("systemctl")
        .args([
            "show",
            &format!("--property={property}"),
            "--value",
            SERVICE_NAME,
        ])
        .output()
        .with_context(|| format!("无法查询 shoes.service {property}"))?;
    if !output.status.success() {
        bail!(
            "查询 shoes.service {property} 失败(退出码:{})",
            output.status
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
}

fn listening_ports(pid: u32) -> Result<BTreeSet<u16>> {
    let fd_dir = format!("/proc/{pid}/fd");
    let mut socket_inodes = BTreeSet::new();
    for entry in fs::read_dir(&fd_dir).with_context(|| format!("读取 {fd_dir} 失败"))? {
        let entry = entry?;
        let target = match fs::read_link(entry.path()) {
            Ok(target) => target,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
            Err(error) => return Err(error).context("读取 shoes socket fd 失败"),
        };
        if let Some(inode) = target
            .to_string_lossy()
            .strip_prefix("socket:[")
            .and_then(|value| value.strip_suffix(']'))
            .and_then(|value| value.parse::<u64>().ok())
        {
            socket_inodes.insert(inode);
        }
    }
    let mut ports = BTreeSet::new();
    for (name, tcp) in [
        ("tcp", true),
        ("tcp6", true),
        ("udp", false),
        ("udp6", false),
    ] {
        let path = format!("/proc/{pid}/net/{name}");
        let table = fs::read_to_string(&path).with_context(|| format!("读取 {path} 失败"))?;
        ports.extend(parse_proc_net_ports(&table, &socket_inodes, tcp));
    }
    Ok(ports)
}

fn parse_proc_net_ports(table: &str, socket_inodes: &BTreeSet<u64>, tcp: bool) -> BTreeSet<u16> {
    table
        .lines()
        .skip(1)
        .filter_map(|line| {
            let columns = line.split_whitespace().collect::<Vec<_>>();
            let local = *columns.get(1)?;
            let state = *columns.get(3)?;
            let inode = columns.get(9)?.parse::<u64>().ok()?;
            if !socket_inodes.contains(&inode) || (tcp && state != "0A") {
                return None;
            }
            let port = local.rsplit_once(':')?.1;
            u16::from_str_radix(port, 16).ok()
        })
        .collect()
}

pub fn restore_snapshot(snapshot: ServiceSnapshot) -> Result<()> {
    utils::require_linux_root()?;
    ensure_systemctl()?;
    let path = Path::new(utils::SERVICE_FILE);
    let managed_unit = snapshot.unit_contents.as_deref() == Some(unit_contents().as_bytes());

    if path.exists() {
        let _ = Command::new("systemctl")
            .args(["disable", "--now", SERVICE_NAME])
            .status();
    }
    if let Some(contents) = snapshot.unit_contents {
        utils::atomic_write(path, &contents, 0o644)?;
    } else if path.exists() {
        fs::remove_file(path).context("删除回滚 systemd unit 失败")?;
    }
    systemctl(&["daemon-reload"])?;

    if path.exists() {
        if snapshot.was_enabled {
            systemctl(&["enable", SERVICE_NAME])?;
        } else {
            let _ = Command::new("systemctl")
                .args(["disable", SERVICE_NAME])
                .status();
        }
        if snapshot.was_active {
            let anchor_prepared = managed_unit && prepare_anchor_before_start();
            systemctl_after_reset(START_COMMAND)?;
            verify_active_stable(systemctl_is_active, || {
                thread::sleep(Duration::from_millis(750))
            })?;
            if anchor_prepared {
                mark_anchor_after_start();
            }
        } else {
            let _ = Command::new("systemctl")
                .args(["stop", SERVICE_NAME])
                .status();
        }
    }
    Ok(())
}

fn activation_commands(was_active: bool, was_failed: bool) -> Vec<&'static [&'static str]> {
    let mut commands = Vec::with_capacity(3);
    if was_active || was_failed {
        commands.push(RESET_FAILED_COMMAND);
    }
    commands.push(ENABLE_NOW_COMMAND);
    if was_active {
        commands.push(RESTART_COMMAND);
    }
    commands
}

pub fn execute(action: ServiceAction) -> Result<()> {
    utils::require_linux_root()?;
    ensure_systemctl()?;
    match action {
        ServiceAction::Install => install_unit(false),
        ServiceAction::Start => systemctl_after_reset(START_COMMAND),
        ServiceAction::Stop => systemctl(&["stop", SERVICE_NAME]),
        ServiceAction::Restart => systemctl_after_reset(RESTART_COMMAND),
        ServiceAction::Status => systemctl(&["status", "--no-pager", SERVICE_NAME]),
        ServiceAction::Enable => systemctl_after_reset(ENABLE_NOW_COMMAND),
        ServiceAction::Disable => systemctl(&["disable", "--now", SERVICE_NAME]),
    }
}

fn systemctl_after_reset(command: &[&str]) -> Result<()> {
    if systemctl_is_active()? || systemctl_is_failed()? {
        systemctl(RESET_FAILED_COMMAND)?;
    }
    systemctl(command)
}

pub fn logs(lines: usize) -> Result<()> {
    utils::require_linux()?;
    let status = Command::new("journalctl")
        .args(["-u", SERVICE_NAME, "--no-pager", "-n", &lines.to_string()])
        .status()
        .context("无法执行 journalctl")?;
    if !status.success() {
        bail!("journalctl 执行失败(退出码:{status})");
    }
    Ok(())
}

pub fn uninstall_unit() -> Result<bool> {
    utils::require_linux_root()?;
    ensure_systemctl()?;
    let path = Path::new(utils::SERVICE_FILE);
    if !path.exists() {
        return Ok(false);
    }

    systemctl(&["disable", "--now", SERVICE_NAME])?;
    fs::remove_file(path).context("删除 systemd unit 失败")?;
    systemctl(&["daemon-reload"])?;
    Ok(true)
}

pub fn is_active() -> Result<bool> {
    utils::require_linux()?;
    ensure_systemctl()?;
    systemctl_is_active()
}

fn systemctl_is_active() -> Result<bool> {
    Ok(Command::new("systemctl")
        .args(["is-active", "--quiet", SERVICE_NAME])
        .status()
        .context("无法查询 systemd 服务状态")?
        .success())
}

fn systemctl_is_failed() -> Result<bool> {
    Ok(Command::new("systemctl")
        .args(["is-failed", "--quiet", SERVICE_NAME])
        .status()
        .context("无法查询 systemd 服务失败状态")?
        .success())
}

fn systemctl_is_enabled() -> Result<bool> {
    Ok(Command::new("systemctl")
        .args(["is-enabled", "--quiet", SERVICE_NAME])
        .status()
        .context("无法查询 systemd 服务启用状态")?
        .success())
}

fn systemctl(args: &[&str]) -> Result<()> {
    let status = Command::new("systemctl")
        .args(args)
        .status()
        .with_context(|| format!("无法执行 systemctl {}", args.join(" ")))?;
    if !status.success() {
        bail!("systemctl {} 失败(退出码:{status})", args.join(" "));
    }
    Ok(())
}

fn ensure_systemctl() -> Result<()> {
    if !utils::command_exists("systemctl") {
        bail!("未找到 systemctl;当前系统可能未使用 systemd");
    }
    Ok(())
}

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

    fn pin_provenance() -> installer::ShoesProvenance {
        installer::ShoesProvenance {
            source: "verified-pin".into(),
            revision: Some(installer::verified_pin().into()),
            ..Default::default()
        }
    }

    #[test]
    fn hot_reload_reason_service_not_running() {
        assert_eq!(
            hot_reload_unavailable_reason(false, true, &pin_provenance(), "", true),
            Some(HotReloadReason::ServiceNotRunning)
        );
    }

    #[test]
    fn hot_reload_reason_modified_unit() {
        assert_eq!(
            hot_reload_unavailable_reason(true, false, &pin_provenance(), "", true),
            Some(HotReloadReason::UnitModified)
        );
    }

    #[test]
    fn hot_reload_reason_release_and_wrong_pin_remain_ineligible() {
        let release = installer::ShoesProvenance {
            source: "github-release".into(),
            release_tag: Some("v0.2.7".into()),
            ..Default::default()
        };
        assert_eq!(
            hot_reload_unavailable_reason(true, true, &release, "", true),
            Some(HotReloadReason::ShoesSourceUnsupported(release))
        );
        let mut wrong_pin = pin_provenance();
        wrong_pin.revision = Some("different-revision".into());
        assert!(matches!(
            hot_reload_unavailable_reason(true, true, &wrong_pin, "", true),
            Some(HotReloadReason::ShoesSourceUnsupported(_))
        ));
    }

    #[test]
    fn hot_reload_reason_drop_in() {
        assert_eq!(
            hot_reload_unavailable_reason(true, true, &pin_provenance(), "override.conf", true),
            Some(HotReloadReason::DropInPresent)
        );
    }

    #[test]
    fn hot_reload_reason_anchor_not_ready() {
        assert_eq!(
            hot_reload_unavailable_reason(true, true, &pin_provenance(), "", false),
            Some(HotReloadReason::AnchorNotReady)
        );
        assert!(hot_reload_unavailable_reason(true, true, &pin_provenance(), "-", true).is_none());
    }

    #[test]
    fn hot_reload_release_fallback_explains_source_and_switch() {
        let reason = HotReloadReason::ShoesSourceUnsupported(installer::ShoesProvenance {
            source: "github-release".into(),
            release_tag: Some("v0.2.7".into()),
            ..Default::default()
        });
        let message = reason.restart_notice();
        for expected in [
            "GitHub Release v0.2.7",
            "固定 pin",
            "受控重启",
            "Update Center",
            "update --method cargo",
        ] {
            assert!(message.contains(expected), "missing {expected}: {message}");
        }
    }

    #[test]
    fn unit_uses_expected_paths_and_hardening() {
        let unit = unit_contents();
        assert_eq!(
            unit,
            include_str!("../systemd/ping-rust.service").replace("\r\n", "\n")
        );
        assert!(unit.contains("ExecStart=/usr/local/bin/shoes /etc/shoes/config.yaml"));
        assert!(unit.contains("Restart=on-failure"));
        assert!(unit.contains("NoNewPrivileges=true"));
        assert!(unit.contains("ProtectControlGroups=true"));
        assert!(unit.contains("ProtectKernelModules=true"));
        assert!(unit.contains("ProtectKernelTunables=true"));
        assert!(unit.contains("RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6"));
        assert!(unit.contains("RestrictSUIDSGID=true"));
        assert!(unit.contains("LockPersonality=true"));
        assert!(unit.contains("MemoryDenyWriteExecute=true"));
        assert!(unit.contains("SystemCallArchitectures=native"));
        assert!(unit.contains("WantedBy=multi-user.target"));
    }

    #[test]
    fn activation_commands_cover_new_active_and_failed_units() {
        assert_eq!(activation_commands(false, false), vec![ENABLE_NOW_COMMAND]);
        assert_eq!(
            activation_commands(true, false),
            vec![RESET_FAILED_COMMAND, ENABLE_NOW_COMMAND, RESTART_COMMAND]
        );
        assert_eq!(
            activation_commands(false, true),
            vec![RESET_FAILED_COMMAND, ENABLE_NOW_COMMAND]
        );
    }

    #[test]
    fn stable_activation_requires_two_successful_probes() {
        let mut samples = [true, true].into_iter();
        verify_active_stable(|| Ok(samples.next().unwrap()), || {}).unwrap();

        let mut samples = [true, false].into_iter();
        assert!(verify_active_stable(|| Ok(samples.next().unwrap()), || {}).is_err());
    }

    #[test]
    fn hot_reload_requires_same_pid_and_exact_listener_delta() {
        let expected = BTreeSet::from([1001, 1003]);
        let removed = BTreeSet::from([1002]);
        assert!(reload_observation(42, 42, true, &expected, &expected, &removed).unwrap());
        assert!(!reload_observation(
            42,
            42,
            true,
            &BTreeSet::from([1001, 1002]),
            &expected,
            &removed
        )
        .unwrap());
        assert!(!reload_observation(
            42,
            42,
            true,
            &BTreeSet::from([1001, 1002, 1003]),
            &expected,
            &removed
        )
        .unwrap());
        assert!(reload_observation(42, 43, true, &expected, &expected, &removed).is_err());
        assert!(reload_observation(42, 0, false, &expected, &expected, &removed).is_err());
    }

    #[test]
    fn proc_net_parser_filters_pid_sockets_and_tcp_state() {
        let table = "  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode\n  0: 0100007F:1F90 00000000:0000 0A 00000000:0000 00:00000000 00000000   0        0 7001 1 0000000000000000 100 0 0 10 0\n  1: 0100007F:1F91 00000000:0000 01 00000000:0000 00:00000000 00000000   0        0 7002 1 0000000000000000 100 0 0 10 0\n";
        let ports = parse_proc_net_ports(table, &BTreeSet::from([7001, 7002]), true);
        assert_eq!(ports, BTreeSet::from([8080]));
    }
}