Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 108 additions & 3 deletions crates/devstack-daemon/src/external.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,62 @@ impl ExternalGroup {
}
}

/// A container port and its protocol, as the agent's file keys them: `5432`
/// for TCP (as every agent wrote a port), `53/udp` for another protocol, so
/// a service's `53/tcp` and `53/udp` are two entries (#192).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PortKey {
pub port: u16,
/// Lower case; `tcp` sorts before `udp`, so a port's TCP entry comes
/// first.
pub protocol: String,
}

impl PortKey {
/// devstack forwards TCP only (#192).
pub fn is_tcp(&self) -> bool {
self.protocol == "tcp"
}
}

impl std::str::FromStr for PortKey {
type Err = String;

fn from_str(s: &str) -> Result<Self, String> {
let (port, protocol) = s.split_once('/').unwrap_or((s, "tcp"));
let port = port
.trim()
.parse()
.map_err(|_| format!("`{s}` is no port"))?;
let protocol = match protocol.trim().to_ascii_lowercase() {
p if p.is_empty() => "tcp".to_string(),
p => p,
};
Ok(Self { port, protocol })
}
}

impl<'de> Deserialize<'de> for PortKey {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
String::deserialize(d)?
.parse()
.map_err(serde::de::Error::custom)
}
}

#[derive(Debug, Clone, Deserialize, Default)]
pub struct ExternalService {
#[serde(default)]
pub environment: BTreeMap<String, Option<String>>,
/// Container port -> address the lane container reaches it at.
#[serde(default)]
pub ports: BTreeMap<u16, String>,
pub ports: BTreeMap<PortKey, String>,
/// Container port -> the port it is on at the lane's developer's machine
/// (what a local lane would publish it on): its links point there, and
/// the developer's tunnels to it come in on that port (ADR-0029 point 4).
/// A port of another protocol than TCP is listed, but not forwarded.
#[serde(default)]
pub published: BTreeMap<u16, u16>,
pub published: BTreeMap<PortKey, u16>,
/// Empty: not started (a parked service that is only an environment source).
#[serde(default)]
pub state: String,
Expand All @@ -94,6 +138,43 @@ pub struct ExternalService {
pub memory: Option<u64>,
}

impl ExternalService {
/// Its TCP ports where the developer reaches them, `(container port,
/// port there)`: what is forwarded, and linked.
pub fn forwarded(&self) -> impl Iterator<Item = (u16, u16)> + '_ {
self.published
.iter()
.filter(|(k, _)| k.is_tcp())
.map(|(k, h)| (k.port, *h))
}

/// Its published ports of another protocol, as the developer would
/// reach them (`5353/udp`): not forwarded, devstack forwards TCP only
/// (#192).
pub fn not_forwarded(&self) -> Vec<String> {
self.published
.iter()
.filter(|(k, _)| !k.is_tcp())
.map(|(k, h)| format!("{h}/{}", k.protocol))
.collect()
}

/// Its ports as the view shows them, as the developer reaches them
/// (`15432->db:5432`, `5353/udp->dns:53`).
pub fn shown_ports(&self) -> Vec<String> {
self.ports
.iter()
.map(|(k, a)| {
let at = self.published.get(k).copied().unwrap_or(k.port);
match k.is_tcp() {
true => format!("{at}->{a}"),
false => format!("{at}/{}->{a}", k.protocol),
}
})
.collect()
}
}

/// The file `DEVSTACK_EXTERNAL_INFRA` names, if it is set.
pub fn path() -> Option<PathBuf> {
std::env::var_os("DEVSTACK_EXTERNAL_INFRA")
Expand Down Expand Up @@ -147,7 +228,7 @@ mod tests {
)
.unwrap();
let g = &x.groups["app"];
assert_eq!(g.services["db"].ports[&5432], "db:5432");
assert_eq!(g.services["db"].ports[&"5432".parse().unwrap()], "db:5432");
assert_eq!(g.services["api"].state, "");
assert_eq!(g.services["api"].environment["X"], None);
assert_eq!(
Expand All @@ -165,4 +246,28 @@ mod tests {
(Some(1_760_000_000_000), Some(12.5), Some(1 << 20))
);
}

#[test]
fn a_port_of_another_protocol_is_its_own_and_not_forwarded() {
let x: super::ExternalInfra = serde_json::from_str(
r#"{"groups":{"app":{"services":{"dns":{
"ports":{"53":"dns:53","53/udp":"dns:53","8080/tcp":"dns:8080"},
"published":{"53":5453,"53/udp":5453,"8080/tcp":8180},
"state":"running"}}}}}"#,
)
.unwrap();
let dns = &x.groups["app"].services["dns"];
assert_eq!(dns.ports.len(), 3, "53/tcp and 53/udp are two");
assert_eq!(
dns.forwarded().collect::<Vec<_>>(),
[(53, 5453), (8080, 8180)]
);
assert_eq!(dns.not_forwarded(), ["5453/udp"]);
assert_eq!(
dns.shown_ports(),
["5453->dns:53", "5453/udp->dns:53", "8180->dns:8080"]
);
assert!("x/udp".parse::<super::PortKey>().is_err());
assert_eq!("53/UDP".parse::<super::PortKey>().unwrap().protocol, "udp");
}
}
22 changes: 19 additions & 3 deletions crates/devstack-daemon/src/lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ pub struct LaneView {
/// or does not say which (ADR-0031, amended 2026-10-19).
#[serde(skip_serializing_if = "Option::is_none")]
pub node_warning: Option<String>,
/// Of a lane on a node, its containers' published ports this machine
/// does not forward (`5353/udp`): devstack forwards TCP only (#192).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub not_forwarded: Vec<String>,
/// A start on a node or a move under way, or one that failed lately.
#[serde(skip_serializing_if = "Option::is_none")]
pub moving: Option<LaneMove>,
Expand All @@ -105,8 +109,15 @@ pub struct LaneView {

/// Of a lane, what the lists show that changes on its own: name, services
/// and containers running and all, its node's error, whether it moves, its
/// notices.
type Shown = (String, [usize; 4], Option<String>, bool, Vec<Notice>);
/// notices, its ports not forwarded.
type Shown = (
String,
[usize; 4],
Option<String>,
bool,
Vec<Notice>,
Vec<String>,
);

/// The notice of a lane whose worktree git lists but is not there, missing
/// since `since` (unix ms): the lane goes after [`MISSING_GRACE`].
Expand Down Expand Up @@ -1087,6 +1098,7 @@ impl Lanes {
v.node_error,
v.moving.is_some(),
v.notices,
v.not_forwarded,
)
})
.collect()
Expand Down Expand Up @@ -1660,7 +1672,11 @@ impl Lanes {
pool: on_node.map(|r| r.pool.clone()),
shared_with: self.share_of(&k.entry.name),
profile: self.profiles.lock().unwrap().get(&k.entry.name).cloned(),
node_error: node_state.and_then(|st| st.error()),
node_error: node_state.as_ref().and_then(|st| st.error()),
not_forwarded: node_state
.as_ref()
.map(|st| st.not_forwarded.clone())
.unwrap_or_default(),
node_warning: on_node
.and_then(|r| r.warning.clone())
.or_else(|| moves.get(&k.entry.name).and_then(|m| m.warning.clone())),
Expand Down
36 changes: 36 additions & 0 deletions crates/devstack-daemon/src/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ pub struct RemoteState {
pub ended: bool,
/// Its services that run now (healthy or running), by name.
pub active: Vec<String>,
/// Its containers' published ports this machine does not forward
/// (`5353/udp`): devstack forwards TCP only (#192).
pub not_forwarded: Vec<String>,
}

impl RemoteState {
Expand Down Expand Up @@ -1200,6 +1203,7 @@ impl RemoteLane {
st.containers_running = all.iter().filter(|c| c["state"] == "running").count();
st.containers = all.len();
st.active = active;
st.not_forwarded = not_forwarded(&all);
}
if !self.tick(STATE_EVERY).await {
return;
Expand Down Expand Up @@ -1487,6 +1491,23 @@ fn not_written(failed: &[String]) -> String {
s
}

/// The published ports of a lane's containers (its view's, read as JSON)
/// that this machine does not forward, each once, in order (`5353/udp`).
/// A lane daemon from before #192 does not say.
fn not_forwarded(containers: &[serde_json::Value]) -> Vec<String> {
let mut out: Vec<String> = containers
.iter()
.flat_map(|c| c["not_forwarded"].as_array().cloned().unwrap_or_default())
.filter_map(|p| p.as_str().map(str::to_string))
.collect();
out.sort_by_key(|p| {
let port = p.split('/').next().and_then(|n| n.parse::<u16>().ok());
(port, p.clone())
});
out.dedup();
out
}

/// What a lease offer says of the node's and the coordinator's devstack:
/// `Err` for a node with another pool protocol, a warning for another
/// release or one that does not say.
Expand Down Expand Up @@ -1805,4 +1826,19 @@ members = ["api"]
"not written on the node: f1: denied"
);
}

#[test]
fn a_lanes_ports_not_forwarded_are_listed_once_in_order() {
let containers: Vec<serde_json::Value> = serde_json::from_str(
r#"[{"service":"dns","not_forwarded":["10053/udp","5453/udp"]},
{"service":"voice","not_forwarded":["5453/udp"]},
{"service":"db","ports":["15432->db:5432"]}]"#,
)
.unwrap();
assert_eq!(super::not_forwarded(&containers), ["5453/udp", "10053/udp"]);
assert!(
super::not_forwarded(&containers[2..]).is_empty(),
"an older lane daemon's"
);
}
}
5 changes: 5 additions & 0 deletions crates/devstack-daemon/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ pub struct ContainerView {
/// container may look healthy. A restart of the container fixes it.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub unreachable: Vec<String>,
/// Of a lane on a node, its published ports of another protocol than
/// TCP (`5353/udp`): devstack forwards TCP only, so the developer's
/// machine does not reach them (#192).
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub not_forwarded: Vec<String>,
/// Its fixed ports devstack holds (`main_ports`, ADR-0048): `port` the
/// fixed one, `upstream` where it forwards now (the container's
/// instance port, or a lane's port while that serves the main ports).
Expand Down
39 changes: 21 additions & 18 deletions crates/devstack-daemon/src/supervisor/infra.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,7 @@ impl Supervisor {
urls: self.container_urls(group, &c.service, &ports),
ports,
unreachable: Vec::new(),
not_forwarded: Vec::new(),
held,
}
}
Expand Down Expand Up @@ -1032,7 +1033,7 @@ impl Supervisor {

/// In a lane on a node: the container address a tunnel on `port` goes
/// to, when `port` is where a container of the lane is published for its
/// developer (ADR-0029 point 4).
/// developer (ADR-0029 point 4). A tunnel carries TCP (#192).
pub fn infra_tunnel(&self, port: u16) -> Option<String> {
let ext = crate::external::read(&self.external_infra()?).ok()?;
ext.groups
Expand All @@ -1041,7 +1042,7 @@ impl Supervisor {
.find_map(|s| {
s.published
.iter()
.find(|(_, h)| **h == port)
.find(|(k, h)| k.is_tcp() && **h == port)
.and_then(|(target, _)| s.ports.get(target).cloned())
})
}
Expand Down Expand Up @@ -1073,36 +1074,36 @@ impl Supervisor {
view.error = Some(e);
}
for (svc, s) in eg.services {
for (port, addr) in &s.ports {
for (key, addr) in &s.ports {
// A published container is reached on loopback,
// as on the developer's machine: the same
// addresses for the services (`rewrite_hosts`),
// and loopback where they insist on it.
let at = match s.published.get(port) {
Some(host) if self.loopback_forward(*host, addr) => {
// and loopback where they insist on it. A
// forward carries TCP; a UDP port is reached at
// its container (#192).
let at = match s.published.get(key) {
Some(host)
if key.is_tcp() && self.loopback_forward(*host, addr) =>
{
format!("127.0.0.1:{host}")
}
_ => addr.clone(),
};
cache.published.insert((g.clone(), svc.clone(), *port), at);
// A port's TCP entry comes first, and stays.
cache
.published
.entry((g.clone(), svc.clone(), key.port))
.or_insert(at);
}
cache
.envs
.insert((g.clone(), svc.clone()), s.environment.clone());
if !s.state.is_empty() {
// Shown, and linked, as the developer reaches it.
let ports: Vec<String> = s
.ports
.iter()
.map(|(p, a)| match s.published.get(p) {
Some(h) => format!("{h}->{a}"),
None => format!("{p}->{a}"),
})
.collect();
let ports = s.shown_ports();
let here: Vec<String> = s
.published
.values()
.map(|h| format!("localhost:{h}"))
.forwarded()
.map(|(_, h)| format!("localhost:{h}"))
.collect();
view.containers.push(ContainerView {
service: svc.clone(),
Expand All @@ -1113,6 +1114,7 @@ impl Supervisor {
urls: self.container_urls(&g, &svc, &here),
ports,
unreachable: Vec::new(),
not_forwarded: s.not_forwarded(),
held: Vec::new(),
managed: true,
});
Expand Down Expand Up @@ -1499,6 +1501,7 @@ mod tests {
ports: Vec::new(),
urls: Vec::new(),
unreachable: Vec::new(),
not_forwarded: Vec::new(),
held: Vec::new(),
managed,
}
Expand Down
Loading