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
5 changes: 5 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ rfd = { version = "0.17", default-features = false, features = ["xdg-portal"] }
schemars = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# A UDP socket's send buffer: macOS refuses a datagram larger than it,
# 9 KiB by default (ADR-0056).
socket2 = "0.6"
tempfile = "3"
thiserror = "2"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "net", "time", "signal", "io-util"] }
Expand Down
1 change: 1 addition & 0 deletions crates/devstack-daemon/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ ignore.workspace = true
rand.workspace = true
serde.workspace = true
serde_json.workspace = true
socket2.workspace = true
thiserror.workspace = true
tokio.workspace = true
tokio-stream.workspace = true
Expand Down
57 changes: 56 additions & 1 deletion crates/devstack-daemon/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,62 @@ fn memory_fits(
/// listen on its container's loopback, and the requester forwards its
/// local ports through the node agent to here. Only the ports of the stack's
/// services, behind the API's token like every route.
async fn tunnel(State(s): State<AppState>, Path(port): Path<u16>, mut req: Request) -> Response {
///
/// With `Upgrade: devstack-udp` the connection is a UDP session to the
/// container published on `port` as UDP (ADR-0056): datagrams as frames,
/// sent from a socket of the session's own.
async fn tunnel(State(s): State<AppState>, Path(port): Path<u16>, req: Request) -> Response {
let udp = req
.headers()
.get(header::UPGRADE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.eq_ignore_ascii_case(crate::udprelay::PROTOCOL));
if udp {
udp_tunnel(&s, port, req).await
} else {
tcp_tunnel(&s, port, req).await
}
}

/// [`tunnel`] for a UDP session (ADR-0056 point 4).
async fn udp_tunnel(s: &AppState, port: u16, mut req: Request) -> Response {
let Some(addr) = s.sup.infra_udp(port) else {
return err(
StatusCode::FORBIDDEN,
format!(
"port {port} is no container's UDP port in this stack (devstack {} here)",
env!("CARGO_PKG_VERSION")
),
);
};
// The container's name resolves once it runs: before, the datagram is
// dropped on the requester, and the next one tries again (no hold).
let socket = match crate::udprelay::connect(&addr).await {
Ok(x) => x,
Err(e) => {
return err(
StatusCode::BAD_GATEWAY,
format!("nothing answers at {addr}/udp: {e}"),
);
}
};
let upgrade = hyper::upgrade::on(&mut req);
tokio::spawn(async move {
let Ok(up) = upgrade.await else { return };
// A backstop: the requester ends an idle session first.
let idle = crate::udprelay::Limits::default().idle * 2;
crate::udprelay::serve(hyper_util::rt::TokioIo::new(up), socket, idle).await;
});
Response::builder()
.status(StatusCode::SWITCHING_PROTOCOLS)
.header(header::CONNECTION, "upgrade")
.header(header::UPGRADE, crate::udprelay::PROTOCOL)
.body(axum::body::Body::empty())
.expect("a valid response")
}

/// [`tunnel`] for a TCP connection.
async fn tcp_tunnel(s: &AppState, port: u16, mut req: Request) -> Response {
// A service's port on this machine's loopback, or (a lane on a node) a
// container's, at its address on the lane's network.
let container = s.sup.infra_tunnel(port);
Expand Down
44 changes: 36 additions & 8 deletions crates/devstack-daemon/src/external.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ pub struct ExternalInfra {
/// agent from before #101 writes the file once, without it.
#[serde(default)]
pub at: Option<u64>,
/// The lane's requester relays its UDP ports (ADR-0056): it asked for
/// it at the start, and this node's agent passes them on. An older
/// requester or agent leaves it out, and the ports stay not forwarded.
#[serde(default)]
pub udp: bool,
}

#[derive(Debug, Clone, Deserialize, Default)]
Expand Down Expand Up @@ -81,10 +86,13 @@ pub struct PortKey {
}

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

pub fn is_udp(&self) -> bool {
self.protocol == "udp"
}
}

impl std::str::FromStr for PortKey {
Expand Down Expand Up @@ -122,7 +130,8 @@ pub struct ExternalService {
/// 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.
/// A UDP port is relayed when the requester asked for it (ADR-0056); a
/// port of another protocol is listed, but not forwarded.
#[serde(default)]
pub published: BTreeMap<PortKey, u16>,
/// Empty: not started (a parked service that is only an environment source).
Expand All @@ -148,13 +157,13 @@ impl ExternalService {
.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> {
/// Its published ports the developer does not reach, as they would
/// (`5353/udp`): those of another protocol than TCP (#192), UDP ones
/// too unless the requester relays them (`udp`, ADR-0056).
pub fn not_forwarded(&self, udp: bool) -> Vec<String> {
self.published
.iter()
.filter(|(k, _)| !k.is_tcp())
.filter(|(k, _)| !k.is_tcp() && !(udp && k.is_udp()))
.map(|(k, h)| format!("{h}/{}", k.protocol))
.collect()
}
Expand Down Expand Up @@ -262,12 +271,31 @@ mod tests {
dns.forwarded().collect::<Vec<_>>(),
[(53, 5453), (8080, 8180)]
);
assert_eq!(dns.not_forwarded(), ["5453/udp"]);
assert_eq!(dns.not_forwarded(false), ["5453/udp"]);
assert!(dns.not_forwarded(true).is_empty(), "relayed (ADR-0056)");
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");
assert!(
!x.udp,
"an older agent's file, or an older requester's lane"
);
}

#[test]
fn a_relayed_lane_still_names_a_port_of_a_third_protocol() {
let x: super::ExternalInfra = serde_json::from_str(
r#"{"udp":true,"groups":{"app":{"services":{"voice":{
"ports":{"5060/udp":"voice:5060","9000/sctp":"voice:9000"},
"published":{"5060/udp":5160,"9000/sctp":9100},
"state":"running"}}}}}"#,
)
.unwrap();
assert!(x.udp);
let voice = &x.groups["app"].services["voice"];
assert_eq!(voice.not_forwarded(x.udp), ["9100/sctp"]);
}
}
9 changes: 8 additions & 1 deletion crates/devstack-daemon/src/lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,13 @@ pub struct LaneView {
#[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).
/// does not forward (`5353/udp`): another protocol than TCP and UDP
/// (#192), or UDP the node does not relay (ADR-0056).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub not_forwarded: Vec<String>,
/// Why they are not, when there are such ports.
#[serde(skip_serializing_if = "Option::is_none")]
pub not_forwarded_reason: Option<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 Down Expand Up @@ -1698,6 +1702,9 @@ impl Lanes {
.as_ref()
.map(|st| st.not_forwarded.clone())
.unwrap_or_default(),
not_forwarded_reason: node_state
.as_ref()
.and_then(|st| st.not_forwarded_reason.clone()),
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
1 change: 1 addition & 0 deletions crates/devstack-daemon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub mod tcpfwd;
pub mod telemetry;
pub mod timeline;
pub mod token;
pub mod udprelay;
pub mod usage;
pub mod watch;

Expand Down
Loading
Loading