Watch
0
0
Fork
You've already forked hyperhive
0

swarmctl: drop the controller socket target, the host has no socket to reach

This commit is contained in:
atlas 2026-11-26 15:40:29 +01:00 • committed by maia
commit 279f97e5ca

View file

@ -7,11 +7,8 @@
//! settled graph would not mean the agent is up and there is nothing here
//! that could be waited on honestly.
//!
//! Transport is a bare `hyper` HTTP/1.1 client handshaked onto a
//! [`tokio::net::UnixStream`] via [`hyper_util::rt::TokioIo`] — the
//! controller has no TCP port, so this crate speaks plain HTTP directly
//! over the socket rather than pulling in a full client stack for one
//! POST.
//! Transport is the swarm's gateway: [`crate::remote::Swarm::request`] sends the
//! request with the cached login.
//!
//! The request and response bodies come from `swarm-controller-api`, which
//! the controller imports too.
@ -21,15 +18,12 @@
use std::path::Path;
use anyhow::{Context as _, Result, bail};
use http_body_util::{BodyExt as _, Full};
use hyper_util::rt::TokioIo;
use serde::Serialize;
use swarm_controller_api::agents::{
CreateAgentRequest, CreateAgentResponse, MintAgentForgeTokenResponse,
};
use tokio::net::UnixStream;
use crate::remote::Target;
use crate::remote::Swarm;
/// Run `swarmctl agent create`.
///
@ -39,7 +33,7 @@ use crate::remote::Target;
/// way `PathArgs::resolve` is called only in the arms that need the
/// deployment's env vars.
pub(crate) fn create(
target: &Target,
target: &Swarm,
name: &str,
hive: &str,
agents_md: Option<&Path>,
@ -75,7 +69,7 @@ pub(crate) fn create(
/// The round trip of [`create`] for an already validated `name` and `hive`,
/// printing nothing.
pub(crate) fn request_create(
target: &Target,
target: &Swarm,
name: &str,
hive: &str,
agents_md: Option<&str>,
@ -100,7 +94,7 @@ pub(crate) fn parse_ident(value: &str, what: &str) -> Result<String> {
///
/// Synchronous for the same reason [`create`] is, and built on the same
/// round trip. No `--hive`: the token's store path has no hive in it.
pub(crate) fn mint_forge_token(target: &Target, name: &str) -> Result<()> {
pub(crate) fn mint_forge_token(target: &Swarm, name: &str) -> Result<()> {
let name = parse_ident(name, "agent name")?;
let rt = tokio::runtime::Builder::new_current_thread()
@ -139,7 +133,7 @@ fn check_confirmed(state: swarm_wire::wanted::AgentState, yes: bool) -> Result<(
/// Run `swarmctl agent set-state`: `PUT /api/hives/{hive}/agents/{agent}/state`.
pub(crate) fn set_state(
target: &Target,
target: &Swarm,
agent: &str,
hive: &str,
state: swarm_wire::wanted::AgentState,
@ -159,7 +153,7 @@ pub(crate) fn set_state(
/// The round trip of [`set_state`] for an already validated `agent` and `hive`,
/// printing nothing. Returns the state as the wire spells it.
pub(crate) fn request_state(
target: &Target,
target: &Swarm,
agent: &str,
hive: &str,
state: swarm_wire::wanted::AgentState,
@ -181,7 +175,7 @@ pub(crate) fn request_state(
/// One `POST /api/agents` round trip at the controller.
async fn post_create(
target: &Target,
target: &Swarm,
name: &str,
hive: &str,
agents_md: Option<&str>,
@ -210,7 +204,7 @@ async fn post_create(
/// which call failed, and every other part of this function is identical
/// between the two verbs.
pub(crate) async fn post<Req: Serialize, Resp: serde::de::DeserializeOwned>(
target: &Target,
target: &Swarm,
uri: &str,
request: &Req,
what: &str,
@ -222,7 +216,7 @@ pub(crate) async fn post<Req: Serialize, Resp: serde::de::DeserializeOwned>(
/// when there is one. A `204` decodes as JSON `null`, so a caller expecting no
/// body asks for `()`.
pub(crate) async fn send<Req: Serialize, Resp: serde::de::DeserializeOwned>(
target: &Target,
target: &Swarm,
method: hyper::Method,
uri: &str,
request: Option<&Req>,
@ -233,10 +227,7 @@ pub(crate) async fn send<Req: Serialize, Resp: serde::de::DeserializeOwned>(
.transpose()
.with_context(|| format!("serialising the {what} request"))?;
let (status, body) = match target {
Target::Socket(socket) => over_socket(socket, method, uri, body, what).await?,
Target::Swarm(swarm) => swarm.request(method, uri, body, what).await?,
};
let (status, body) = target.request(method, uri, body, what).await?;
if !status.is_success() {
bail!("{}", describe_error(status, &body));
@ -254,51 +245,6 @@ pub(crate) async fn send<Req: Serialize, Resp: serde::de::DeserializeOwned>(
})
}
async fn over_socket(
socket: &Path,
method: hyper::Method,
uri: &str,
body: Option<Vec<u8>>,
what: &str,
) -> Result<(hyper::StatusCode, bytes::Bytes)> {
let stream = UnixStream::connect(socket)
.await
.with_context(|| connect_hint(socket))?;
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
.await
.with_context(|| format!("HTTP handshake with {}", socket.display()))?;
// Drives the connection's I/O; a one-shot request has nothing to do with
// the join handle, and a connection that dies surfaces as an error on
// `send_request` or on reading the body.
tokio::spawn(conn);
let mut req = hyper::Request::builder()
.method(method)
.uri(uri)
// A unix socket has no authority of its own, but HTTP/1.1 requires
// the header; the controller routes on the path alone.
.header(hyper::header::HOST, "localhost");
if body.is_some() {
req = req.header(hyper::header::CONTENT_TYPE, "application/json");
}
let req = req
.body(Full::new(bytes::Bytes::from(body.unwrap_or_default())))
.with_context(|| format!("building the {what} request"))?;
let resp = sender
.send_request(req)
.await
.with_context(|| format!("sending the {what} request to swarm-controller"))?;
let status = resp.status();
let body = resp
.into_body()
.collect()
.await
.context("reading swarm-controller's response")?
.to_bytes();
Ok((status, body))
}
/// Turn a failed response into one line the operator can act on.
///
/// The controller answers errors as RFC 9457 `application/problem+json`,
@ -328,42 +274,11 @@ pub(crate) fn describe_error(status: hyper::StatusCode, body: &[u8]) -> String {
}
}
/// Message for a socket that could not be dialled.
///
/// The controller runs as a pod, so the host has no socket to dial: the way in
/// is the swarm's gateway.
pub(crate) fn connect_hint(socket: &Path) -> String {
format!(
"could not connect to a swarm-controller socket at {} — the controller runs as a pod \
and has no socket on this host; reach it through the swarm's gateway with \
`--swarm <domain>` (or `SWARMCTL_SWARM`) after `swarmctl login`",
socket.display()
)
}
#[cfg(test)]
mod tests {
use super::{check_confirmed, connect_hint, describe_error, parse_ident, parse_state};
use super::{check_confirmed, describe_error, parse_ident, parse_state};
use swarm_wire::wanted::AgentState;
/// The controller has no socket on the host, so the hint sends the operator to the
/// gateway and the login, not to a unit that is not there.
#[test]
fn the_connect_hint_names_the_gateway_and_the_login() {
let hint = connect_hint(std::path::Path::new(
"/run/swarm-controller/controller.sock",
));
assert!(
hint.contains("/run/swarm-controller/controller.sock"),
"{hint}"
);
assert!(
hint.contains("--swarm <domain>") && hint.contains("swarmctl login"),
"{hint}"
);
assert!(!hint.contains("systemctl"), "{hint}");
}
/// The accepted values are the wire enum's: each spelling it writes
/// parses back, and an unknown one names the valid ones.
#[test]