Linux: Kiri's networks keep clear of Docker's, whichever engine starts first (#700)

Co-authored-by: Urdemonlord <hasrinata@gmail.com>
This commit is contained in:
Precious OkwuandUrdemonlord authored and GitHub committed 2026-11-21 18:37:46 +01:00
1 parent 68ba680ebd
commit cfb8b5330d
9 files changed
+528 -47

No files matched your search

+4 -1
View File
@@ -8,7 +8,10 @@
[Unit]
Description=Kiri container engine
Documentation=https://kiri.canestack.com
After=network-online.target
# After docker.service, when Docker is installed (ordering only: Kiri starts
# without it): at boot Docker's docker0 and networks are up first, and Kiri
# picks its subnets around them, rather than the two taking the same one.
After=network-online.target docker.service
Wants=network-online.target
[Service]
+1 -1
View File
@@ -13,7 +13,7 @@ if [ -d /run/systemd/system ]; then
cat > /etc/systemd/system/kiri.service <<UNIT
[Unit]
Description=Kiri container engine
After=network-online.target
After=network-online.target docker.service
[Service]
ExecStart=/usr/local/bin/kiri daemon
Environment=HOME=/var/lib/kiri-daemon
+37 -9
View File
@@ -152,9 +152,17 @@ fn send_to(fd: RawFd, data: &[u8], to: &libc::sockaddr_in) {
impl Dns {
/// Starts answering on a bridge's gateway address (once per bridge).
/// A bridge made again with another gateway (its network's subnet moved
/// off one the host took, #489) gets a listener there in place of the
/// old one, which no address of the bridge's reaches any more.
pub fn serve(&mut self, bridge: &str, gateway: [u8; 4]) -> io::Result<()> {
if self.servers.iter().any(|s| s.container.is_none() && s.bridges.iter().any(|b| b == bridge)) {
return Ok(());
let at_gateway = |s: &Server| s.container.is_none() && s.bridges.iter().any(|b| b == bridge);
if let Some(s) = self.servers.iter().find(|s| at_gateway(s)) {
if local_addr(&s.sock) == Some(gateway) {
return Ok(());
}
self.servers.retain(|s| !at_gateway(s));
self.forget_pending();
}
let sock = bound(gateway, 53)?;
self.servers.push(Server { bridges: vec![bridge.to_owned()], sock, container: None });
@@ -215,13 +223,7 @@ impl Dns {
/// Whether the agent answers DNS at `ip` on a bridge (its gateway).
pub fn serves_at(&self, ip: [u8; 4]) -> bool {
self.servers.iter().filter(|s| s.container.is_none()).any(|s| {
// SAFETY: sockaddr_in is plain data; getsockname fills at most `len` bytes.
let mut a: libc::sockaddr_in = unsafe { std::mem::zeroed() };
let mut len = std::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t;
let named = unsafe { libc::getsockname(s.sock.as_raw_fd(), (&mut a as *mut libc::sockaddr_in).cast(), &mut len) } == 0;
named && a.sin_addr.s_addr.to_ne_bytes() == ip
})
self.servers.iter().filter(|s| s.container.is_none()).any(|s| local_addr(&s.sock) == Some(ip))
}
/// Container `pid` is gone: its 127.0.0.11 server goes.
@@ -614,6 +616,16 @@ fn embedded_socket() -> io::Result<OwnedFd> {
}
}
/// The address socket `sock` is bound to.
fn local_addr(sock: &OwnedFd) -> Option<[u8; 4]> {
// SAFETY: sockaddr_in is plain data; getsockname fills at most `len` bytes.
let mut a: libc::sockaddr_in = unsafe { std::mem::zeroed() };
let mut len = std::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t;
// SAFETY: a socket we own and a buffer of `len` bytes.
let named = unsafe { libc::getsockname(sock.as_raw_fd(), (&mut a as *mut libc::sockaddr_in).cast(), &mut len) } == 0;
named.then(|| a.sin_addr.s_addr.to_ne_bytes())
}
/// The port socket `sock` is bound to.
fn local_port(sock: &OwnedFd) -> io::Result<u16> {
// SAFETY: sockaddr_in is plain data; getsockname fills at most `len` bytes.
@@ -888,6 +900,22 @@ mod tests {
}
}
/// The default bridge moved off a subnet the host took (#489): its
/// bridge is made again with another gateway, and the gateway's
/// listener follows it rather than staying on the old address.
#[test]
fn a_gateway_listener_follows_its_bridges_new_gateway() {
let mut dns = Dns::default();
dns.servers.push(Server { bridges: vec!["kiri0".into()], sock: super::bound([127, 0, 0, 2], 0).unwrap(), container: None });
dns.serve("kiri0", [127, 0, 0, 2]).unwrap();
assert_eq!(dns.servers.len(), 1, "the same gateway keeps its listener");
// Port 53 may need privileges this test lacks: either way the old
// listener is gone.
let made = dns.serve("kiri0", [127, 0, 0, 3]).is_ok();
assert!(!dns.serves_at([127, 0, 0, 2]));
assert_eq!(dns.serves_at([127, 0, 0, 3]), made);
}
#[test]
fn one_client_cant_take_every_forwarded_slot() {
let mut dns = Dns::default();
+19 -2
View File
@@ -2796,7 +2796,20 @@ impl Engine {
if spec.pid_mode == "host" {
flags |= run_flags::PID_HOST;
}
let net = self.lock_networks().find(&spec.network_mode).cloned();
// The network's subnet, checked against the host's once more before
// its first container (#489).
let net = {
let mut nets = self.lock_networks();
match nets.settle(&spec.network_mode) {
Ok(()) => nets.find(&spec.network_mode).cloned(),
Err(e) => {
drop(nets);
let e = Error::Conflict(e);
self.fail_start(&id, &spec, &e);
return Err(e);
}
}
};
let links = match net.as_ref().map(|n| self.link_hosts(&id, &spec, n)).transpose() {
Ok(l) => l.unwrap_or_default(),
Err(e) => {
@@ -3664,7 +3677,11 @@ impl Engine {
/// SIGTERM, then SIGKILL after `timeout` if it is still running.
/// Plugs a running container into one more network as `eth{n}`.
fn attach_extra(&self, vm: &VmLink, id: &str, n: u32, extra: &ExtraNetwork) -> Result<(), Error> {
let net = self.lock_networks().find(&extra.name).cloned().ok_or_else(|| Error::NotFound(format!("network {} not found", extra.name)))?;
let net = {
let mut nets = self.lock_networks();
nets.settle(&extra.name).map_err(Error::Conflict)?;
nets.find(&extra.name).cloned().ok_or_else(|| Error::NotFound(format!("network {} not found", extra.name)))?
};
if net.driver != "bridge" {
return Err(Error::BadRequest(format!("only bridge networks can be connected, not {}", net.driver)));
}
+435 -28
View File
@@ -6,6 +6,10 @@
//! `IPAM.Config` (`--subnet`, `--gateway`, `--ip-range`, `--aux-address`)
//! picks them instead, and containers may then ask for fixed addresses.
//!
//! On a Linux host the pool keeps clear of the host's own networks, and of
//! the ones Docker Engine there brings back when it starts; a network whose
//! subnet one of them takes later moves, or is refused (`Network::settle`).
//!
//! `--ipv6` (Compose `enable_ipv6`) adds an IPv6 subnet beside the IPv4 one:
//! an IPv6 `IPAM.Config` entry, or a /64 from Kiri's own ULA pool (a /48
//! under fd00::/8 per engine), as Docker's default address pools hand out.
@@ -583,11 +587,32 @@ impl Networks {
Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
Err(e) => return Err(e),
};
// 172.17.0.0/16 as Docker uses, unless the host already routes it
// (Kiri on a Linux host inside another engine's container) or a
// saved network has it.
// A saved network whose subnet the host has taken since (Docker
// started while Kiri was stopped), or Docker will take back when it
// starts, moves off it; one whose subnet the user gave is refused at
// its next container if the host holds it (#489).
let host = host_networks();
let mut saved = saved;
let mut moved = false;
for i in 0..saved.len() {
let taken: Vec<([u8; 4], u8)> = saved.iter().enumerate().filter(|(j, n)| *j != i && !n.bridge.is_empty()).map(|(_, n)| (n.subnet, n.prefix)).collect();
let n = &mut saved[i];
match n.settle(&taken, &host) {
Ok(Some(was)) => {
crate::diag::warn!("network moved off a subnet the host has taken", network = n.name, from = was, to = n.subnet_str());
moved = true;
}
Ok(None) => {}
Err(e) => crate::diag::warn!("network's subnet is taken on the host", error = e),
}
}
// 172.17.0.0/16 as Docker uses, unless the host is already on it
// (Kiri on a Linux host inside another engine's container), Docker
// here will take it back when it starts, or a saved network has it.
// Chosen afresh at each start: never saved, as Docker's own default
// bridge is not.
let taken: Vec<([u8; 4], u8)> = saved.iter().map(|n| (n.subnet, n.prefix)).collect();
let (subnet, prefix) = free_subnet(&taken, true).unwrap_or(([172, 17, 0, 0], 16));
let (subnet, prefix) = default_bridge_subnet(&taken, &host)?;
let mut bridge = builtin("bridge", "bridge", "kiri0", subnet, [subnet[0], subnet[1], subnet[2], 1]);
bridge.prefix = prefix;
// `KIRI_BRIDGE_IPV6=1`, as Docker's daemon.json `"ipv6": true`: the
@@ -602,7 +627,42 @@ impl Networks {
}
let mut list = vec![bridge, builtin("host", "host", "", [0; 4], [0; 4]), builtin("none", "null", "", [0; 4], [0; 4])];
list.extend(saved);
Ok(Networks { list, path, ula })
let networks = Networks { list, path, ula };
if moved {
networks.save();
}
Ok(networks)
}
/// Before a network's first container: its subnet checked against the
/// host's once more (`Network::settle`), as the host may have taken it
/// since it was chosen. Bridges are made at a network's first container,
/// so Docker started after Kiri, or at boot before Kiri's containers
/// came back, may hold it by then. Nothing to do while containers are
/// on it (their bridge, and its route, came first), off a Linux host
/// (Kiri's VM has its own network), or for host and none.
pub fn settle(&mut self, key: &str) -> Result<(), String> {
if self.find(key).is_none_or(|n| n.bridge.is_empty() || !n.used.is_empty()) {
return Ok(());
}
self.settle_with(key, &host_networks())
}
fn settle_with(&mut self, key: &str, host: &[HostNet]) -> Result<(), String> {
let Some(n) = self.find(key) else { return Ok(()) };
if n.bridge.is_empty() || !n.used.is_empty() || host.is_empty() {
return Ok(());
}
let name = n.name.clone();
let taken: Vec<([u8; 4], u8)> = self.list.iter().filter(|o| !o.bridge.is_empty() && o.name != name).map(|o| (o.subnet, o.prefix)).collect();
let Some(n) = self.find_mut(&name) else { return Ok(()) };
let Some(was) = n.settle(&taken, host)? else { return Ok(()) };
crate::diag::warn!("network moved off a subnet the host has taken", network = name, from = was, to = n.subnet_str());
let saved = !n.builtin();
if saved {
self.save();
}
Ok(())
}
fn save(&self) {
@@ -778,19 +838,249 @@ impl Networks {
}
}
/// The default bridge's subnet, or an error when the whole pool is taken:
/// falling back to 172.17.0.0/16 anyway would hand out a subnet the host
/// already routes (#489), so the daemon fails to start loudly instead.
fn default_bridge_subnet(taken: &[([u8; 4], u8)], host: &[HostNet]) -> io::Result<([u8; 4], u8)> {
free_subnet_with(taken, true, host).ok_or_else(|| io::Error::other(NO_FREE_SUBNET))
}
const NO_FREE_SUBNET: &str = "no free subnet for the default bridge: 172.17.0.0/16 … 172.31.0.0/16 and 10.89.0.0/24 … 10.89.255.0/24 are all routed on this host or used by another network";
/// The first free subnet: 172.17.0.0/16 (only for the default bridge), then
/// 172.18.0.0/16 … 172.31.0.0/16, then 10.89.N.0/24, skipping ones Kiri
/// already uses and ones on the host's own links.
/// already uses and ones on the host's own links and interfaces.
fn free_subnet(taken: &[([u8; 4], u8)], default_bridge: bool) -> Option<([u8; 4], u8)> {
let routes = host_routes();
free_subnet_with(taken, default_bridge, &host_networks())
}
/// The first free subnet against `host`'s networks, as `free_subnet` does
/// against the live host's. Split out so tests can feed it a host.
fn free_subnet_with(taken: &[([u8; 4], u8)], default_bridge: bool, host: &[HostNet]) -> Option<([u8; 4], u8)> {
let first = if default_bridge { 17 } else { 18 };
(first..=31u8)
.map(|b| ([172, b, 0, 0], 16u8))
.chain((0..=255u8).map(|c| ([10, 89, c, 0], 24u8)))
.find(|(s, p)| {
let (net, mask) = (u32::from_be_bytes(*s), u32::MAX << (32 - p));
!taken.iter().any(|t| overlaps(*t, (*s, *p))) && !routes.iter().any(|(rn, rm)| (net & rm) == *rn || (rn & mask) == net)
})
.find(|(s, p)| !taken.iter().any(|t| overlaps(*t, (*s, *p))) && !host.iter().any(|h| h.overlaps(*s, *p)))
}
/// A subnet the host itself is on, outside Kiri's bridges: an on-link route
/// or an interface's address, and the interface it is on. Or one Docker
/// will take back when it starts (`docker_saved`): not on the host now.
#[derive(Debug, Clone, PartialEq, Eq)]
struct HostNet {
net: u32,
mask: u32,
dev: String,
saved: bool,
}
fn mask4(prefix: u8) -> u32 {
if prefix == 0 { 0 } else { u32::MAX << (32 - prefix as u32) }
}
impl HostNet {
fn new(dev: &str, addr: [u8; 4], mask: u32) -> HostNet {
HostNet { net: u32::from_be_bytes(addr) & mask, mask, dev: dev.to_owned(), saved: false }
}
/// Shares any address with `subnet`: a new subnet keeps clear of it.
fn overlaps(&self, subnet: [u8; 4], prefix: u8) -> bool {
let net = u32::from_be_bytes(subnet);
(net & self.mask) == self.net || (self.net & mask4(prefix)) == net
}
/// Lies inside `subnet` (or is it), so the host routes that part of it,
/// `gateway` included when it is in it, to `dev` and not to Kiri's
/// bridge: the kernel picks the more specific route, and of two equal
/// ones the older. A host network around Kiri's leaves it working.
fn inside(&self, subnet: [u8; 4], prefix: u8) -> bool {
self.mask >= mask4(prefix) && (self.net & mask4(prefix)) == u32::from_be_bytes(subnet)
}
fn contains(&self, ip: [u8; 4]) -> bool {
u32::from_be_bytes(ip) & self.mask == self.net
}
fn cidr(&self) -> String {
format!("{}/{}", ip_str(self.net.to_be_bytes()), self.mask.count_ones())
}
}
impl Network {
/// A subnet a host network has taken since it was chosen (#489): Docker
/// started while Kiri was stopped, or before this network's first
/// container, and its docker0 or br-… holds it now. A subnet from the
/// pool (the default bridge's, or one made without `--subnet`) moves to
/// a free one: no container can have asked for an address on it, and
/// each gets a new one when it starts, as its address is handed out
/// then. A subnet the user gave stays (as Docker keeps it), unless the
/// host's network takes its gateway's part: then nothing on it would
/// work, and its containers are refused with the reason. Returns what
/// moved, for the log.
fn settle(&mut self, taken: &[([u8; 4], u8)], host: &[HostNet]) -> Result<Option<String>, String> {
if self.bridge.is_empty() || self.no_ipv4 {
return Ok(None);
}
let inside: Vec<&HostNet> = host.iter().filter(|h| h.inside(self.subnet, self.prefix)).collect();
let Some(h) = inside.first() else { return Ok(None) };
// Only a network on the host now breaks this one now; one Docker
// saved is reason to move a pool subnet before it does, not to
// refuse the user's.
let shadowed = inside.iter().find(|h| !h.saved && h.contains(self.gateway));
let refuse = |h: &HostNet| {
format!(
"network {}'s subnet {} is also on this host's interface {} ({}), another engine's network (Docker's docker0 or br-…, say), so its containers could not reach their gateway {}. Remove that network, or make {} again with another --subnet",
self.name,
self.subnet_str(),
h.dev,
h.cidr(),
ip_str(self.gateway),
self.name
)
};
if self.user_subnet {
return match shadowed {
Some(h) => Err(refuse(h)),
None => Ok(None),
};
}
let Some((s, p)) = free_subnet_with(taken, self.name == "bridge", host) else {
return match shadowed {
Some(h) => Err(refuse(h)),
None => Ok(None),
};
};
let was = format!("{} ({} {} as {})", self.subnet_str(), if h.saved { "Docker keeps" } else { "on" }, h.dev, h.cidr());
self.subnet = s;
self.prefix = p;
self.gateway = [s[0], s[1], s[2], 1];
Ok(Some(was))
}
}
/// The host's own networks: its on-link routes plus the subnets its
/// interfaces have addresses on, outside Kiri's bridges. Only a Linux host
/// shares its routing table and interfaces with Kiri.
#[cfg(target_os = "linux")]
fn host_networks() -> Vec<HostNet> {
let mut out = on_link_routes(&std::fs::read_to_string("/proc/net/route").unwrap_or_default());
out.extend(host_addrs());
out.extend(docker_saved());
out
}
/// The bridges Docker Engine on this host will bring back when it starts
/// (docker0 and its networks), as its store keeps them: dockerd restores
/// each with its saved address and never looks at what else is on the host
/// then (moby daemon/libnetwork/drivers/bridge/bridge_store.go,
/// populateNetworks; for docker0, daemon/daemon_unix.go, selectBIP, takes
/// the address docker0 has). A Kiri network on one of them while Docker is
/// stopped would break Docker's, or Kiri's, when Docker starts. Only its
/// very first start picks a subnet around what the host has.
#[cfg(target_os = "linux")]
fn docker_saved() -> Vec<HostNet> {
// daemon.json's data-root, else /var/lib/docker; the snap's own.
let root = std::fs::read("/etc/docker/daemon.json")
.ok()
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
.and_then(|v| v["data-root"].as_str().map(str::to_owned))
.unwrap_or_else(|| "/var/lib/docker".into());
let mut out = Vec::new();
for dir in [root.as_str(), "/var/snap/docker/common/var-lib-docker"] {
let path = std::path::Path::new(dir).join("network/files/local-kv.db");
match std::fs::File::open(&path) {
Ok(f) => {
use std::io::Read;
let mut b = Vec::new();
// A few dozen KiB for a few networks.
if f.take(16 << 20).read_to_end(&mut b).is_ok() {
out.extend(docker_bridges(&b));
}
}
// A store Kiri can't read (not root): Docker's default.
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => out.push(HostNet { saved: true, ..HostNet::new("docker0", [172, 17, 0, 1], mask4(16)) }),
Err(_) => {}
}
}
out
}
/// Docker's saved bridges in its store's bytes. The store is a bbolt file;
/// each bridge network's configuration is a JSON object in it, written by
/// moby's networkConfiguration.MarshalJSON with sorted keys, so its
/// `"AddressIPv4":"172.17.0.1/16"` comes just before its `"BridgeName"`.
/// A copy bbolt has not reused yet may still be there after the network
/// went: a subnet more to keep clear of, and nothing worse.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn docker_bridges(b: &[u8]) -> Vec<HostNet> {
const ADDR: &[u8] = b"\"AddressIPv4\":\"";
const NAME: &[u8] = b"\"BridgeName\":\"";
let quoted = |at: usize| b.get(at..).and_then(|r| r.iter().position(|c| *c == b'"').map(|end| String::from_utf8_lossy(&r[..end]).into_owned()));
let mut out: Vec<HostNet> = Vec::new();
let mut i = 0;
while let Some(off) = b.get(i..).and_then(|r| r.windows(ADDR.len()).position(|w| w == ADDR)) {
i += off + ADDR.len();
let Some(cidr) = quoted(i) else { break };
let parsed = cidr.split_once('/').and_then(|(a, p)| Some((parse_ip(a)?, p.parse::<u8>().ok().filter(|p| (8..=32).contains(p))?)));
let Some((ip, prefix)) = parsed else { continue };
let window = &b[i..(i + 512).min(b.len())];
let dev = window.windows(NAME.len()).position(|w| w == NAME).and_then(|o| quoted(i + o + NAME.len())).filter(|n| !n.is_empty()).unwrap_or_else(|| "a Docker bridge".into());
let h = HostNet { saved: true, ..HostNet::new(&dev, ip, mask4(prefix)) };
if !out.contains(&h) {
out.push(h);
}
}
out
}
#[cfg(not(target_os = "linux"))]
fn host_networks() -> Vec<HostNet> {
Vec::new()
}
/// The subnets this machine's interfaces have addresses on, outside Kiri's
/// bridges and loopback. An address stays on an interface whose route is
/// gone (a `noprefixroute` one) or not yet there, so this catches what the
/// routing table misses.
#[cfg(target_os = "linux")]
fn host_addrs() -> Vec<HostNet> {
let mut list: *mut libc::ifaddrs = std::ptr::null_mut();
// SAFETY: getifaddrs fills `list`, freed below; entries are read only while it lives.
if unsafe { libc::getifaddrs(&mut list) } != 0 {
return Vec::new();
}
let mut entries = Vec::new();
let mut p = list;
while !p.is_null() {
// SAFETY: `p` is non-null and an entry of the list getifaddrs returned.
let Some(ifa) = (unsafe { p.as_ref() }) else { break };
// SAFETY: ifa_addr is checked non-null before its family is read.
if !ifa.ifa_addr.is_null() && !ifa.ifa_netmask.is_null() && i32::from(unsafe { (*ifa.ifa_addr).sa_family }) == libc::AF_INET {
// SAFETY: an AF_INET address and netmask are sockaddr_in.
let a = unsafe { (*(ifa.ifa_addr as *const libc::sockaddr_in)).sin_addr.s_addr }.to_ne_bytes();
let m = unsafe { (*(ifa.ifa_netmask as *const libc::sockaddr_in)).sin_addr.s_addr }.to_ne_bytes();
// SAFETY: the interface name is NUL-terminated by getifaddrs.
let name = unsafe { std::ffi::CStr::from_ptr(ifa.ifa_name) }.to_string_lossy().into_owned();
entries.push((name, a, m));
}
p = ifa.ifa_next;
}
// SAFETY: the list getifaddrs returned, freed once.
unsafe { libc::freeifaddrs(list) };
interface_networks(entries)
}
/// The network of each interface address, skipping Kiri's own bridges and
/// loopback: a bridge Kiri made earlier is its own business, and
/// 127.0.0.0/8 never overlaps the pool.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn interface_networks(entries: Vec<(String, [u8; 4], [u8; 4])>) -> Vec<HostNet> {
entries
.into_iter()
.filter(|(name, a, _)| !name.starts_with("kiri") && name != "lo" && a[0] != 127)
.map(|(name, a, m)| HostNet::new(&name, a, u32::from_be_bytes(m)))
.collect()
}
/// The host's own IPv6 routes, outside Kiri's bridges, the default route
@@ -819,19 +1109,14 @@ fn host_routes6() -> Vec<([u8; 16], u8)> {
Vec::new()
}
/// The host's on-link routes as (network, mask), outside Kiri's bridges.
/// Only a Linux host shares its routing table with Kiri.
#[cfg(target_os = "linux")]
fn host_routes() -> Vec<(u32, u32)> {
on_link_routes(&std::fs::read_to_string("/proc/net/route").unwrap_or_default())
}
/// The routes in `/proc/net/route`'s text that put the host on a subnet, as
/// Docker reserves them since 23.0 (moby#42598): not one through a gateway
/// (OpenVPN's 0.0.0.0/1 and 128.0.0.0/1), an unreachable or prohibit one, or
/// one to 0.0.0.0 (the default route, a WireGuard 0.0.0.0/1).
/// one to 0.0.0.0 (the default route, a WireGuard 0.0.0.0/1). Kiri's own
/// bridges' routes are left out. A bridge with no carrier (Docker's docker0
/// with no containers) keeps its route, marked linkdown: it is here too.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn on_link_routes(text: &str) -> Vec<(u32, u32)> {
fn on_link_routes(text: &str) -> Vec<HostNet> {
const RTF_GATEWAY: u32 = 0x2;
text.lines()
.skip(1)
@@ -844,16 +1129,11 @@ fn on_link_routes(text: &str) -> Vec<(u32, u32)> {
// Little-endian hex, as the kernel prints them.
let dest = u32::from_str_radix(f[1], 16).ok()?.swap_bytes();
let mask = u32::from_str_radix(f[7], 16).ok()?.swap_bytes();
(dest != 0).then_some((dest & mask, mask))
(dest != 0).then(|| HostNet::new(f[0], dest.to_be_bytes(), mask))
})
.collect()
}
#[cfg(not(target_os = "linux"))]
fn host_routes() -> Vec<(u32, u32)> {
Vec::new()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1031,6 +1311,134 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
fn host(dev: &str, addr: [u8; 4], prefix: u8) -> HostNet {
HostNet::new(dev, addr, mask4(prefix))
}
#[test]
fn default_bridge_skips_a_subnet_an_interface_address_uses() {
// docker0 with 172.17.0.1/16 and no carrier, as in #489: its route
// is linkdown, but the address is still configured.
let host = interface_networks(vec![
("docker0".into(), [172, 17, 0, 1], [255, 255, 0, 0]),
("lo".into(), [127, 0, 0, 1], [255, 0, 0, 0]),
("lo".into(), [10, 255, 255, 254], [255, 255, 255, 255]),
("kiri0".into(), [172, 18, 0, 1], [255, 255, 0, 0]),
]);
assert_eq!(host, [self::host("docker0", [172, 17, 0, 0], 16)]);
assert_eq!(default_bridge_subnet(&[], &host).unwrap(), ([172, 18, 0, 0], 16));
// Nothing on the host: 172.17.0.0/16, as Docker uses.
assert_eq!(default_bridge_subnet(&[], &[]).unwrap(), ([172, 17, 0, 0], 16));
}
/// Docker's store as bbolt keeps it: each bridge network's settings a
/// JSON object among binary pages, stale copies included.
#[test]
fn dockers_saved_bridges_are_read_from_its_store() {
let cfg = |addr: &str, name: &str| format!(r#"{{"AddressIPv4":"{addr}","BridgeIfaceCreator":1,"BridgeName":"{name}","DefaultBridge":false}}"#);
let mut store = vec![0u8, 1, 2, 0xff];
for (a, n) in [("172.17.0.1/16", "docker0"), ("172.18.0.1/16", "br-0123456789ab"), ("172.17.0.1/16", "docker0"), ("nonsense", "x")] {
store.extend(cfg(a, n).bytes());
store.extend([0u8; 7]);
}
store.extend(br#"{"AddressIPv4":"10.5.0.1/24"}"#);
let saved = docker_bridges(&store);
let want = |dev: &str, a: [u8; 4], p: u8| HostNet { saved: true, ..host(dev, a, p) };
assert_eq!(saved, [want("docker0", [172, 17, 0, 0], 16), want("br-0123456789ab", [172, 18, 0, 0], 16), want("a Docker bridge", [10, 5, 0, 0], 24)]);
assert!(docker_bridges(b"").is_empty() && docker_bridges(br#""AddressIPv4":"172.17"#).is_empty());
// The default bridge keeps clear of them, as of a live docker0.
assert_eq!(default_bridge_subnet(&[], &saved).unwrap(), ([172, 19, 0, 0], 16));
}
/// Docker stopped with docker0 and a network saved: a pool network on
/// one moves before Docker takes it back, but a subnet the user gave
/// is not refused for what is not on the host yet.
#[test]
fn a_subnet_docker_will_take_back_moves_but_is_not_refused() {
let (mut n, dir) = nets();
let pool = n.create("pool", Settings::default()).unwrap();
let ipam = parse_ipam(&serde_json::json!({"Config": [{"Subnet": "172.30.0.0/16"}]})).unwrap();
n.create("mine", Settings { ipam, ..Default::default() }).unwrap();
let saved = |a: [u8; 4]| HostNet { saved: true, ..host("br-0123456789ab", a, 16) };
n.settle_with("mine", &[saved([172, 30, 0, 1])]).unwrap();
assert_eq!(n.find("mine").unwrap().subnet_str(), "172.30.0.0/16");
n.settle_with("pool", &[saved(pool.gateway)]).unwrap();
assert_ne!(n.find("pool").unwrap().subnet, pool.subnet);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn default_bridge_errors_when_the_pool_is_full() {
// Every candidate blocked: 172.17-31 by one /12 route, the 10.89
// /24s by one /16. No silent fallback to 172.17.0.0/16 (#489).
let host = [host("eth1", [172, 16, 0, 0], 12), host("eth2", [10, 89, 0, 0], 16)];
assert!(default_bridge_subnet(&[], &host).is_err());
}
/// Docker started after the default bridge was chosen (while Kiri was
/// stopped, or before its first container) and its docker0 holds
/// 172.17.0.0/16 now: the default bridge moves before its first
/// container, and stays while containers are on it (#489).
#[test]
fn the_default_bridge_moves_off_a_subnet_the_host_took() {
// Subnets as this machine's routes left them at load: compared,
// not assumed (a Linux test host may have Docker's networks).
let (mut n, dir) = nets();
let was = n.find("bridge").unwrap().clone();
let docker0 = [host("docker0", was.gateway, was.prefix)];
n.settle_with("bridge", &docker0).unwrap();
let b = n.find("bridge").unwrap().clone();
assert!(!overlaps((b.subnet, b.prefix), (was.subnet, was.prefix)), "{} moved off {}", b.subnet_str(), was.subnet_str());
assert_eq!(b.gateway, [b.subnet[0], b.subnet[1], b.subnet[2], 1]);
let ip = n.allocate_avoiding("bridge", &[]).unwrap();
assert!(b.contains(ip) && ip != b.gateway, "containers get addresses in the new subnet");
// With a container on it, its bridge (and route) came first: kept.
n.settle_with("default", &[host("docker0", b.gateway, b.prefix)]).unwrap();
assert_eq!(n.find("bridge").unwrap().subnet, b.subnet);
// Not saved: chosen afresh at each start, as Docker's.
assert!(!std::fs::read_to_string(dir.join("networks.json")).unwrap_or_default().contains("kiri0"));
let _ = std::fs::remove_dir_all(dir);
}
/// A network made without --subnet moves off a subnet the host took
/// since, and the move is saved; one with a --subnet the user gave is
/// kept, as Docker keeps it, unless the host's network takes its
/// gateway's part: then its containers are refused, saying why.
#[test]
fn saved_networks_move_or_refuse_when_the_host_took_their_subnet() {
let (mut n, dir) = nets();
let pool = n.create("pool", Settings::default()).unwrap();
let ipam = parse_ipam(&serde_json::json!({"Config": [{"Subnet": "172.30.0.0/16"}]})).unwrap();
n.create("mine", Settings { ipam, ..Default::default() }).unwrap();
let br = host("br-0123456789ab", pool.gateway, pool.prefix);
n.settle_with("pool", std::slice::from_ref(&br)).unwrap();
let moved = n.find("pool").unwrap().clone();
assert!(!br.overlaps(moved.subnet, moved.prefix) && moved.subnet != [172, 17, 0, 0], "{}", moved.subnet_str());
assert!(!overlaps((moved.subnet, moved.prefix), (n.find("bridge").unwrap().subnet, 16)) && !overlaps((moved.subnet, moved.prefix), ([172, 30, 0, 0], 16)));
// Saved as it is (a load would check it against this machine again).
let on_disk: Vec<Network> = serde_json::from_slice(&std::fs::read(dir.join("networks.json")).unwrap()).unwrap();
assert_eq!(on_disk.iter().find(|n| n.name == "pool").map(|n| n.subnet), Some(moved.subnet), "saved");
// The user's subnet: an equal one on the host takes the gateway.
let e = n.settle_with("mine", &[host("br-feedfacecafe", [172, 30, 0, 1], 16)]).unwrap_err();
assert!(e.starts_with("network mine's subnet 172.30.0.0/16 is also on this host's interface br-feedfacecafe (172.30.0.0/16)"), "{e}");
assert!(e.contains("another --subnet"), "{e}");
assert_eq!(n.find("mine").unwrap().subnet_str(), "172.30.0.0/16", "never moved");
// A part of it away from the gateway, or a host network around it,
// leaves it working: kept, as is a pool network inside a wider one.
n.settle_with("mine", &[host("eth1", [172, 30, 9, 1], 24)]).unwrap();
let wide = [host("eth1", [moved.subnet[0], 0, 0, 0], 8)];
n.settle_with("mine", &wide).unwrap();
n.settle_with("pool", &wide).unwrap();
assert_eq!((n.find("mine").unwrap().subnet_str(), n.find("pool").unwrap().subnet), ("172.30.0.0/16".to_owned(), moved.subnet));
// Nowhere to move to and the gateway taken: refused, not clashing.
let full = [host("eth1", moved.gateway, moved.prefix), host("eth2", [172, 16, 0, 0], 12), host("eth3", [10, 89, 0, 0], 16)];
let e = n.settle_with("pool", &full).unwrap_err();
assert!(e.contains(&format!("could not reach their gateway {}", ip_str(moved.gateway))), "{e}");
// host and none have no subnet.
n.settle_with("host", &full).unwrap();
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn overlapping_subnets_are_found() {
assert!(overlaps(([172, 18, 0, 0], 16), ([172, 18, 5, 0], 24)));
@@ -1055,8 +1463,7 @@ mod tests {
*\t000010AC\t00000000\t0001\t0\t0\t0\t0000F0FF\t0\t0\t0\n\
eth0\t0001A8C0\t00000000\t0001\t0\t0\t100\t00FFFFFF\t0\t0\t0\n\
kiri1\t000012AC\t00000000\t0001\t0\t0\t0\t0000FFFF\t0\t0\t0\n";
let lan = |a: [u8; 4]| (u32::from_be_bytes(a), u32::MAX << 8);
assert_eq!(on_link_routes(text), [lan([10, 8, 0, 0]), lan([192, 168, 1, 0])]);
assert_eq!(on_link_routes(text), [host("tun0", [10, 8, 0, 0], 24), host("eth0", [192, 168, 1, 0], 24)]);
}
#[test]
+4 -1
View File
@@ -6,7 +6,10 @@
[Unit]
Description=Kiri container engine
Documentation=https://runkiri.com
After=network-online.target
# After docker.service, when Docker is installed (ordering only: Kiri starts
# without it): at boot Docker's docker0 and networks are up first, and Kiri
# picks its subnets around them, rather than the two taking the same one.
After=network-online.target docker.service
Wants=network-online.target
[Service]
+5 -5
View File
@@ -194,11 +194,11 @@ gate() {
# /etc/resolv.conf.
BRIDGE_GW=172.17.0.1 DEFAULT_NS=172.17.0.1 HOSTNET_ADDR=192.168.64. HOSTNET_IF=eth0 HOST_UPS=1024
if [ "$SYS" != mac ]; then
# Docker's 172.17.0.0/16 unless the host already routes it (Kiri in another
# engine's container): then the first free subnet (daemon/network.rs).
if ip -4 route 2>/dev/null | grep -v ' dev kiri0 ' | grep -q '^172\.17\.'; then
BRIDGE_GW=$($D network inspect bridge -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}' 2>/dev/null)
fi
# Docker's 172.17.0.0/16 unless the host is already on it (Docker's
# docker0, Kiri in another engine's container): then the first free
# subnet (daemon/network.rs). As the engine says.
BRIDGE_GW=$($D network inspect bridge -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}' 2>/dev/null)
BRIDGE_GW=${BRIDGE_GW:-172.17.0.1}
# The default bridge names the host's resolvers, as the agent reads them
# (kiri-init transport.rs host_dns): /etc/resolv.conf's but loopback, else
# systemd-resolved's upstreams; a resolver at one of the host's own
+20
View File
@@ -154,6 +154,26 @@ t ss-restarted-start "204" "$POST http://d/kiri/wake"
t ss-restarted-brings-back "ss-us=true ss-al=true ss-user=false ss-no=false" "$BACK"
t ss-restarted-all-always "running: 7" "for i in \$(seq 100); do [ \$(docker ps -q | wc -l) -ge 7 ] && break; sleep 0.2; done; echo running: \$(docker ps -q | wc -l)"
t ss-cleanup "ss-us" "docker rm -f $ALL"
# Docker took a subnet Kiri had chosen while Kiri was stopped (or before a
# network's first container, when Kiri makes its bridge): its docker0 or
# br-… holds the address, with no carrier yet. Kiri's network moves to a
# free subnet, and its containers reach their gateway, DNS and the internet,
# not the other engine's bridge; one whose --subnet the user gave is refused
# with the reason (#489). The default bridge's subnet is read, not assumed:
# this engine's container is itself on a 172.17 bridge.
GW="docker network inspect -f '{{(index .IPAM.Config 0).Gateway}}'"
t taken-setup "ok" "docker network create lh489 >/dev/null && docker network create --subnet 10.89.240.0/24 lh489u >/dev/null && echo ok"
OLD_BRIDGE=$($D exec "$N" sh -c "DOCKER_HOST=unix:///root/.kiri/run/docker.sock $GW bridge")
OLD_POOL=$($D exec "$N" sh -c "DOCKER_HOST=unix:///root/.kiri/run/docker.sock $GW lh489")
t taken-stop "204" "$POST http://d/kiri/stop"
t taken-by-other-bridges "ok" "apk add -q iproute2 >/dev/null 2>&1; for b in docker489:$OLD_BRIDGE/16 br489:$OLD_POOL/16 br489u:10.89.240.1/24; do ip link add \${b%%:*} type bridge && ip addr add \${b#*:} dev \${b%%:*} && ip link set \${b%%:*} up || exit; done; echo ok"
t taken-wake "204" "$POST http://d/kiri/wake"
REACH="gw=\\\$(ip route | awk '/^default/ {print \\\$3}'); ping -c1 -W2 \\\$gw >/dev/null && r=gateway-ok || r=gateway-unreachable; echo \\\$r \\\$gw"
t taken-default-bridge-moves "gateway-ok" "docker run --rm alpine sh -c \"$REACH\" | grep -v ' $OLD_BRIDGE\$'"
t taken-default-bridge-internet "Example Domain" "docker run --rm alpine wget -qO- -T 10 http://example.com"
t taken-pool-network-moves "gateway-ok" "docker run --rm --network lh489 alpine sh -c \"$REACH\" | grep -v ' $OLD_POOL\$'"
t taken-user-subnet-refused "is also on this host's interface br489u" "docker run --rm --network lh489u alpine true"
t taken-cleanup "ok" "docker network rm lh489 lh489u >/dev/null; ip link del docker489; ip link del br489; ip link del br489u; echo ok"
# A command that may not be run is 126, a missing one 127, as with Docker (#183).
t exit-126-not-executable "126" "docker run --rm alpine /etc/passwd; echo \$?"
t not-executable-msg 'exec: "/etc/passwd": permission denied' "docker run --rm alpine /etc/passwd"
+3
View File
@@ -118,3 +118,6 @@ dockerfw-docker-kept-apart #247 letting Kiri's containers through Docker's firew
import-dir-mtime #676 every directory of an image layer had the time Kiri unpacked it, not the layer's
buildx-copy-then-start #83 buildx's bootstrap failed with "connection reset by peer": the engine answered the copy into the new BuildKit container, then closed the connection without saying so, and the start sent next on it was lost
buildx-bootstrap-loop #83 about one buildx docker-container bootstrap in six failed at the BuildKit container's start with "connection reset by peer", leaving it created
taken-default-bridge-moves #489 the default bridge kept a subnet Docker's docker0 had taken while Kiri was stopped, so its containers could not reach their gateway
taken-pool-network-moves #489 a network made without --subnet kept a subnet another engine's bridge had taken since, so its containers could not reach their gateway
taken-user-subnet-refused #489 a network whose --subnet another engine's bridge holds started containers that could not reach their gateway, with no word why
Can't render this file because it contains an unexpected character in line 2 and column 52.