Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/hive-priv/src/egress_diag.rs
maia 9237948c2c egress-pin: say a vb- veth on the bridge that has no link_index
parse_ports drops a bridge port whose listing has no numeric link_index
without a line, and the unenslaved check cannot see it because it is on
the bridge. A sweep now names such a veth after the usual 60 s grace,
keyed by its ifindex so a restart is a new finding. Diagnostics only: no
binding changes.

Refs #6646
2026-11-23 10:29:37 +01:00

569 lines
19 KiB
Rust

//! What a bridge sweep says about the ports it leaves as they are.
//!
//! `egress-pin` prints a line for each port it binds and none for a port it
//! can't, so a container that stayed unbound for eleven hours left nothing in
//! the journal. A sweep (`egress-pin` with no port, the timer's run) now says
//! what it finds and doesn't fix:
//!
//! - a port that stays unbound, with the links it was matched against;
//! - a `vb-` veth that is not on the bridge, which no pass can see;
//! - a `vb-` veth on the bridge with no usable `link_index`, which the port
//! listing drops, so no pass can see it either;
//! - a registered machine the pass could not read, with the reason.
//!
//! A port is unbound for a moment at every container start, so a finding is
//! said only after it has stood for [`GRACE_SECS`], and once: the pass keeps
//! `<state file>.diag`, one `<first seen> <said 0|1> <key>` line per finding, and
//! drops a finding's line when it clears, so a return is said again. An older
//! binary never reads the file. Nothing here changes what is bound.
use std::fmt::Write as _;
use anyhow::{Context as _, Result, bail};
use crate::egress::{HostPort, Machines, NsLink, PIN, Skip, is_plain_name, owner_of};
/// Seconds a finding stands before a pass says it: two ticks of the timer, and
/// longer than the 30 s a port's own `egress-pin <port>` run waits for its
/// container to register.
pub(crate) const GRACE_SECS: u64 = 60;
/// The prefix of the host end of a container's veth that nspawn makes when the
/// container joins a bridge.
const VETH_PREFIX: &str = "vb-";
/// A `vb-` veth that is not on the bridge.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Unenslaved {
name: String,
/// The bridge it is on instead, if any.
master: Option<String>,
}
/// The `vb-` veths of an `ip -j link show type veth` listing that are not on
/// `bridge`.
pub(crate) fn parse_unenslaved(json: &str, bridge: &str) -> Result<Vec<Unenslaved>> {
let value: serde_json::Value = serde_json::from_str(json).context("parse ip -j link")?;
let Some(items) = value.as_array() else {
bail!("ip -j link did not print a list");
};
Ok(items
.iter()
.filter_map(|item| {
let name = item.get("ifname")?.as_str()?;
let master = item.get("master").and_then(serde_json::Value::as_str);
(name.starts_with(VETH_PREFIX) && is_plain_name(name) && master != Some(bridge)).then(
|| Unenslaved {
name: name.to_string(),
master: master.map(str::to_string),
},
)
})
.collect())
}
/// A `vb-` veth on the bridge whose `link_index`, the index of its peer, the
/// listing lacks or gives as something other than a number. A port like that
/// is not read as a bridge port, so no pass binds it.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Peerless {
name: String,
ifindex: Option<u64>,
}
/// The `vb-` veths of an `ip -j link show type veth` listing that are on
/// `bridge` and have no usable `link_index`.
pub(crate) fn parse_peerless(json: &str, bridge: &str) -> Result<Vec<Peerless>> {
let value: serde_json::Value = serde_json::from_str(json).context("parse ip -j link")?;
let Some(items) = value.as_array() else {
bail!("ip -j link did not print a list");
};
Ok(items
.iter()
.filter_map(|item| {
let name = item.get("ifname")?.as_str()?;
let on_bridge = item.get("master").and_then(serde_json::Value::as_str) == Some(bridge);
let has_peer = item
.get("link_index")
.is_some_and(serde_json::Value::is_u64);
(name.starts_with(VETH_PREFIX) && is_plain_name(name) && on_bridge && !has_peer).then(
|| Peerless {
name: name.to_string(),
ifindex: item.get("ifindex").and_then(serde_json::Value::as_u64),
},
)
})
.collect())
}
/// What a sweep looked at.
pub(crate) struct Pass<'a> {
pub(crate) bridge: &'a str,
pub(crate) ports: &'a [HostPort],
/// Port name and why it stays unbound.
pub(crate) unbound: &'a [(String, String)],
pub(crate) machines: &'a Machines,
pub(crate) unenslaved: &'a [Unenslaved],
pub(crate) peerless: &'a [Peerless],
}
/// One thing a sweep can say.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Finding {
/// What it is about: the same finding has the same key in every pass.
key: String,
line: String,
}
/// The line about a machine a pass could not read.
pub(crate) fn skip_line(skip: &Skip) -> String {
format!("machine {} is skipped: {}", skip.machine, skip.why)
}
/// Each machine with the `<index>/<peer index>` of its veth links, by name.
fn machines_seen(machines: &[(String, Vec<NsLink>)]) -> String {
let mut seen: Vec<String> = machines
.iter()
.map(|(name, links)| {
let pairs: Vec<String> = links
.iter()
.filter_map(|l| Some(format!("{}/{}", l.ifindex, l.peer_index?)))
.collect();
let pairs = if pairs.is_empty() {
"-".to_string()
} else {
pairs.join("+")
};
format!("{name}={pairs}")
})
.collect();
seen.sort();
if seen.is_empty() {
"none".into()
} else {
seen.join(", ")
}
}
/// Everything a sweep has to say about what it left as it is.
pub(crate) fn findings(pass: &Pass<'_>) -> Vec<Finding> {
let mut found = Vec::new();
for (name, why) in pass.unbound {
let Some(port) = pass.ports.iter().find(|p| &p.name == name) else {
continue;
};
let head = format!(
"{name} (ifindex {}, peer {})",
port.ifindex, port.peer_index
);
let line = if owner_of(port, &pass.machines.links).is_none() {
format!(
"{head} has no owner; machines seen: {}",
machines_seen(&pass.machines.links)
)
} else {
format!("{head} stays unbound: {why}")
};
found.push(Finding {
key: format!("port {name} {}", port.ifindex),
line,
});
}
for skip in &pass.machines.skipped {
let leader = skip.leader.map_or("-".to_string(), |pid| pid.to_string());
found.push(Finding {
key: format!("machine {} {leader}", skip.machine),
line: skip_line(skip),
});
}
for veth in pass.unenslaved {
let line = match &veth.master {
Some(master) => format!("{} is on {master}, not {}", veth.name, pass.bridge),
None => format!("{} is not on {}", veth.name, pass.bridge),
};
found.push(Finding {
key: format!("veth {}", veth.name),
line,
});
}
for veth in pass.peerless {
let ifindex = veth.ifindex.map_or("-".to_string(), |i| i.to_string());
found.push(Finding {
key: format!("peerless {} {ifindex}", veth.name),
line: format!("{} is on {} but has no link_index", veth.name, pass.bridge),
});
}
found
}
/// A finding a pass has seen: when it first did and whether it said so.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Seen {
first: u64,
said: bool,
key: String,
}
/// The findings of earlier passes. A line that does not parse is dropped.
pub(crate) fn parse_seen(text: &str) -> Vec<Seen> {
text.lines()
.filter_map(|line| {
let mut cols = line.splitn(3, ' ');
let first = cols.next()?.parse().ok()?;
let said = match cols.next()? {
"1" => true,
"0" => false,
_ => return None,
};
Some(Seen {
first,
said,
key: cols.next()?.to_string(),
})
})
.collect()
}
fn seen_text(seen: &[Seen]) -> String {
let mut text = String::new();
for s in seen {
let _ = writeln!(text, "{} {} {}", s.first, u8::from(s.said), s.key);
}
text
}
/// What this pass keeps for the next one, and the findings it says now: the ones
/// that have stood for [`GRACE_SECS`] and were not said before. A finding that
/// is gone is not kept, so it is said again when it returns.
pub(crate) fn advance<'a>(
findings: &'a [Finding],
earlier: &[Seen],
now: u64,
) -> (Vec<Seen>, Vec<&'a Finding>) {
let mut kept = Vec::new();
let mut due = Vec::new();
for finding in findings {
let before = earlier.iter().find(|s| s.key == finding.key);
let first = before.map_or(now, |s| s.first);
let said = before.is_some_and(|s| s.said);
let say = !said && now.saturating_sub(first) >= GRACE_SECS;
if say {
due.push(finding);
}
kept.push(Seen {
first,
said: said || say,
key: finding.key.clone(),
});
}
(kept, due)
}
/// Print what `findings` has that is due and keep the rest in `path`. A file
/// that can't be written is a warning: without it a finding would never stand
/// long enough to be said.
pub(crate) fn say(findings: &[Finding], path: &str, now: u64) {
let before = std::fs::read_to_string(path).unwrap_or_default();
let (kept, due) = advance(findings, &parse_seen(&before), now);
let text = seen_text(&kept);
if text != before
&& let Err(e) = std::fs::write(path, &text)
{
eprintln!("{PIN}: write {path}: {e}");
}
for finding in due {
eprintln!("{PIN}: {}", finding.line);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::egress::Mac;
fn port(name: &str, ifindex: u64, peer_index: u64) -> HostPort {
HostPort {
name: name.into(),
ifindex,
peer_index,
}
}
fn link(ifindex: u64, peer_index: Option<u64>) -> NsLink {
NsLink {
ifindex,
peer_index,
mac: Mac::parse("02:00:00:00:00:01").unwrap(),
}
}
fn unbound(name: &str, why: &str) -> (String, String) {
(name.into(), why.into())
}
fn lines(found: &[Finding]) -> Vec<&str> {
found.iter().map(|f| f.line.as_str()).collect()
}
#[test]
fn a_port_no_machine_owns_names_every_machine_and_its_links() {
let machines = Machines {
links: vec![
("h-b".into(), vec![link(1, None), link(2, Some(41))]),
("h-a".into(), vec![link(1, None)]),
("h-c".into(), vec![link(2, Some(7)), link(3, Some(8))]),
],
skipped: Vec::new(),
};
let ports = [port("vb-h-x", 40, 3)];
let unbound = [unbound("vb-h-x", "no registered container owns it")];
let found = findings(&Pass {
bridge: "hive-br0",
ports: &ports,
unbound: &unbound,
machines: &machines,
unenslaved: &[],
peerless: &[],
});
assert_eq!(
lines(&found),
["vb-h-x (ifindex 40, peer 3) has no owner; machines seen: \
h-a=-, h-b=2/41, h-c=2/7+3/8"]
);
assert_eq!(found[0].key, "port vb-h-x 40");
}
#[test]
fn with_no_machine_read_the_line_says_none() {
let ports = [port("vb-h-x", 40, 3)];
let unbound = [unbound("vb-h-x", "no registered container owns it")];
let found = findings(&Pass {
bridge: "hive-br0",
ports: &ports,
unbound: &unbound,
machines: &Machines::default(),
unenslaved: &[],
peerless: &[],
});
assert_eq!(
lines(&found),
["vb-h-x (ifindex 40, peer 3) has no owner; machines seen: none"]
);
}
#[test]
fn a_port_with_an_owner_gives_the_reason_it_stays_unbound() {
let machines = Machines {
links: vec![("h-a".into(), vec![link(3, Some(40))])],
skipped: Vec::new(),
};
let ports = [port("vb-h-a", 40, 3)];
let unbound = [unbound(
"vb-h-a",
"h-a has the unusable address 00:00:00:00:00:00",
)];
let found = findings(&Pass {
bridge: "hive-br0",
ports: &ports,
unbound: &unbound,
machines: &machines,
unenslaved: &[],
peerless: &[],
});
assert_eq!(
lines(&found),
["vb-h-a (ifindex 40, peer 3) stays unbound: \
h-a has the unusable address 00:00:00:00:00:00"]
);
}
#[test]
fn a_skipped_machine_names_the_reason() {
let machines = Machines {
links: Vec::new(),
skipped: vec![
Skip {
machine: "h-a".into(),
leader: Some(77),
why: "it is not a container".into(),
},
Skip {
machine: "h-b".into(),
leader: None,
why: "its state file cannot be read: gone".into(),
},
],
};
let found = findings(&Pass {
bridge: "hive-br0",
ports: &[],
unbound: &[],
machines: &machines,
unenslaved: &[],
peerless: &[],
});
assert_eq!(
lines(&found),
[
"machine h-a is skipped: it is not a container",
"machine h-b is skipped: its state file cannot be read: gone"
]
);
assert_eq!(found[0].key, "machine h-a 77");
assert_eq!(found[1].key, "machine h-b -");
}
#[test]
fn a_veth_off_the_bridge_is_named_with_the_bridge_it_is_on() {
let off = parse_unenslaved(
r#"[
{"ifname":"vb-a","master":"hive-br0"},
{"ifname":"vb-b"},
{"ifname":"vb-c","master":"virbr0"},
{"ifname":"ve-d"},
{"ifname":"vb-e\"x"}
]"#,
"hive-br0",
)
.unwrap();
let found = findings(&Pass {
bridge: "hive-br0",
ports: &[],
unbound: &[],
machines: &Machines::default(),
unenslaved: &off,
peerless: &[],
});
assert_eq!(
lines(&found),
["vb-b is not on hive-br0", "vb-c is on virbr0, not hive-br0"]
);
assert_eq!(found[0].key, "veth vb-b");
assert!(parse_unenslaved("{}", "hive-br0").is_err());
}
#[test]
fn a_bridge_port_with_no_peer_index_is_named_and_keyed_by_its_ifindex() {
let listing = r#"[
{"ifindex":10,"ifname":"vb-a","master":"hive-br0","link_index":2},
{"ifindex":11,"ifname":"vb-b","master":"hive-br0"},
{"ifindex":12,"ifname":"vb-c","master":"hive-br0","link_index":"x"},
{"ifindex":13,"ifname":"vb-d","master":"virbr0"},
{"ifindex":14,"ifname":"vb-e"},
{"ifindex":15,"ifname":"ve-f","master":"hive-br0"},
{"ifindex":16,"ifname":"vb-g\"x","master":"hive-br0"},
{"ifname":"vb-h","master":"hive-br0"}
]"#;
let none = parse_peerless(listing, "hive-br0").unwrap();
let found = findings(&Pass {
bridge: "hive-br0",
ports: &[],
unbound: &[],
machines: &Machines::default(),
unenslaved: &[],
peerless: &none,
});
assert_eq!(
lines(&found),
[
"vb-b is on hive-br0 but has no link_index",
"vb-c is on hive-br0 but has no link_index",
"vb-h is on hive-br0 but has no link_index"
]
);
// A restart gives the port a new ifindex, so the new port is a new
// finding that is said again.
assert_eq!(found[0].key, "peerless vb-b 11");
assert_eq!(found[2].key, "peerless vb-h -");
assert!(parse_peerless("{}", "hive-br0").is_err());
}
fn finding(key: &str) -> Finding {
Finding {
key: key.into(),
line: format!("line of {key}"),
}
}
#[test]
fn a_finding_is_said_once_after_the_grace_and_not_before() {
let found = [finding("a")];
let (kept, due) = advance(&found, &[], 1000);
assert!(due.is_empty());
let (kept, due) = advance(&found, &kept, 1000 + GRACE_SECS - 1);
assert!(due.is_empty());
let (kept, due) = advance(&found, &kept, 1000 + GRACE_SECS);
assert_eq!(due, [&found[0]]);
let (kept, due) = advance(&found, &kept, 1000 + 10 * GRACE_SECS);
assert!(due.is_empty());
let (_, due) = advance(&found, &kept, 1000 + 20 * GRACE_SECS);
assert!(due.is_empty());
}
#[test]
fn a_finding_that_cleared_is_said_again_when_it_returns() {
let found = [finding("a")];
let (kept, _) = advance(&found, &[], 0);
let (kept, due) = advance(&found, &kept, GRACE_SECS);
assert_eq!(due.len(), 1);
let (kept, due) = advance(&[], &kept, 2 * GRACE_SECS);
assert!(kept.is_empty() && due.is_empty());
let (kept, due) = advance(&found, &kept, 3 * GRACE_SECS);
assert!(due.is_empty());
let (_, due) = advance(&found, &kept, 4 * GRACE_SECS);
assert_eq!(due.len(), 1);
}
#[test]
fn each_finding_has_its_own_clock() {
let both = [finding("a"), finding("b")];
let (kept, _) = advance(&both[..1], &[], 0);
let (kept, due) = advance(&both, &kept, GRACE_SECS);
assert_eq!(due, [&both[0]]);
let (_, due) = advance(&both, &kept, 2 * GRACE_SECS);
assert_eq!(due, [&both[1]]);
}
#[test]
fn a_clock_that_steps_back_waits() {
let found = [finding("a")];
let (kept, _) = advance(&found, &[], 5000);
let (_, due) = advance(&found, &kept, 100);
assert!(due.is_empty());
}
#[test]
fn the_seen_file_round_trips_and_drops_bad_lines() {
let seen = vec![
Seen {
first: 12,
said: true,
key: "port vb-h-x 40".into(),
},
Seen {
first: 30,
said: false,
key: "veth vb-b".into(),
},
];
let text = seen_text(&seen);
assert_eq!(text, "12 1 port vb-h-x 40\n30 0 veth vb-b\n");
assert_eq!(parse_seen(&text), seen);
assert!(parse_seen("x 1 a\n5 2 a\n5 1\n\n").is_empty());
}
#[test]
fn say_keeps_what_it_has_not_said_in_the_file() {
let path = std::env::temp_dir().join(format!("hive-priv-diag-{}", std::process::id()));
let path = path.to_str().unwrap().to_string();
let _ = std::fs::remove_file(&path);
let found = [finding("a")];
say(&found, &path, 100);
assert_eq!(std::fs::read_to_string(&path).unwrap(), "100 0 a\n");
say(&found, &path, 100 + GRACE_SECS);
assert_eq!(std::fs::read_to_string(&path).unwrap(), "100 1 a\n");
say(&[], &path, 100 + 2 * GRACE_SECS);
assert_eq!(std::fs::read_to_string(&path).unwrap(), "");
let _ = std::fs::remove_file(&path);
}
}