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
15 changed files with 174 additions and 599 deletions

View file

@ -66,7 +66,7 @@ swarm-level operator CLI
* `--users-file <PATH>` — Host-side path of authelia's users database — that is, the path inside the container, prefixed with the container's root. * `--users-file <PATH>` — Host-side path of authelia's users database — that is, the path inside the container, prefixed with the container's root.
This is the only user store: it's read before every change and written in place, and `swarm-authelia-bridge` writes the same file. This is the only user store: it's read before every change and written in place, and `swarm-authelia-bridge` writes the same file.
* `--swarm <URL>` — The swarm's domain, as `https://<domain>` or the bare domain. Given, the `agent`, `schedule` and `forge` verbs, and the agent checks and steps of `setup`, go through its gateway as the account `swarmctl login` logged in, instead of over the controller's socket. Falls back to `SWARMCTL_SWARM`; `login` then falls back to `SWARMCTL_LOGIN_DEFAULT_SWARM`. The swarm-controller nix module sets both to its host's own swarm, so there the verbs use the gateway and need `swarmctl login` once. With no swarm, they use the socket that `--controller-socket` or `SWARM_CONTROLLER_SOCKET` names; the module sets neither * `--swarm <URL>` — The swarm's domain, as `https://<domain>` or the bare domain. Given, the `agent`, `schedule` and `forge` verbs, and the agent checks and steps of `setup`, go through its gateway as the account `swarmctl login` logged in. Falls back to `SWARMCTL_SWARM`; `login` then falls back to `SWARMCTL_LOGIN_DEFAULT_SWARM`. The swarm-controller nix module sets both to its host's own swarm, so there the verbs use the gateway and need `swarmctl login` once. The controller runs as a pod and has no socket on the host, so a verb that reaches it needs a swarm
* `--ca-file <PATH>` — A PEM CA certificate to trust beside the system roots, for a swarm whose gateway serves a certificate from the swarm's own CA. Falls back to `SWARMCTL_CA_FILE` * `--ca-file <PATH>` — A PEM CA certificate to trust beside the system roots, for a swarm whose gateway serves a certificate from the swarm's own CA. Falls back to `SWARMCTL_CA_FILE`
@ -115,9 +115,6 @@ No approval gate guards this: the caller is root on the controller's host, or lo
* `--agents-md <FILE>` — A text file the agent's `AGENTS.md` starts with. * `--agents-md <FILE>` — A text file the agent's `AGENTS.md` starts with.
The agent writes it on its first start, and only when it has no `AGENTS.md` yet: re-creating an agent never replaces an existing file. The controller refuses a file over 64 KiB. The agent writes it on its first start, and only when it has no `AGENTS.md` yet: re-creating an agent never replaces an existing file. The controller refuses a file over 64 KiB.
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
@ -129,18 +126,12 @@ swarm-controller does this for every agent with a store identity at start and ev
Queues and returns, the same way `agent create` does — watch the swarm UI's job view for the outcome. Queues and returns, the same way `agent create` does — watch the swarm UI's job view for the outcome.
**Usage:** `swarmctl agent mint-forge-token [OPTIONS] <NAME>` **Usage:** `swarmctl agent mint-forge-token <NAME>`
###### **Arguments:** ###### **Arguments:**
* `<NAME>` — Name of an agent that already exists * `<NAME>` — Name of an agent that already exists
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl agent set-state` ## `swarmctl agent set-state`
@ -164,9 +155,6 @@ No approval gate guards this: the caller is root on the controller's host, or lo
* `--hive <HIVE>` — The hive that runs the agent * `--hive <HIVE>` — The hive that runs the agent
* `--yes` — Confirm `destroyed`, which can't be undone * `--yes` — Confirm `destroyed`, which can't be undone
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
@ -176,18 +164,12 @@ Follow an agent's terminal rows live: the newest retained rows, then each new on
The swarm-level counterpart of `hivectl agent watch`, read from the swarm-controller rather than from the agent's own web UI, so it works from any machine with `--swarm` and doesn't need the agent running to show what it last did. Fails when the swarm has never heard from the agent. The swarm-level counterpart of `hivectl agent watch`, read from the swarm-controller rather than from the agent's own web UI, so it works from any machine with `--swarm` and doesn't need the agent running to show what it last did. Fails when the swarm has never heard from the agent.
**Usage:** `swarmctl agent watch [OPTIONS] <AGENT>` **Usage:** `swarmctl agent watch <AGENT>`
###### **Arguments:** ###### **Arguments:**
* `<AGENT>` — Agent name * `<AGENT>` — Agent name
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl agent inference` ## `swarmctl agent inference`
@ -212,18 +194,12 @@ A field the swarm sets wins over the agent's own value (its agent.nix or a `hype
Show what the swarm sets for an agent, naming the fields it doesn't set, and the model and effort the agent runs on, each with where it comes from Show what the swarm sets for an agent, naming the fields it doesn't set, and the model and effort the agent runs on, each with where it comes from
**Usage:** `swarmctl agent inference get [OPTIONS] <AGENT>` **Usage:** `swarmctl agent inference get <AGENT>`
###### **Arguments:** ###### **Arguments:**
* `<AGENT>` — Agent name * `<AGENT>` — Agent name
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl agent inference set` ## `swarmctl agent inference set`
@ -244,9 +220,6 @@ Set fields for an agent. Only the flags given change; the others keep what's sto
Possible values: `low`, `medium`, `high`, `xhigh`, `max` Possible values: `low`, `medium`, `high`, `xhigh`, `max`
* `--subagent-models <MODELS>` — The models it may start subagents on, comma-separated. Stored and shown; the agent doesn't apply it yet * `--subagent-models <MODELS>` — The models it may start subagents on, comma-separated. Stored and shown; the agent doesn't apply it yet
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
@ -254,18 +227,12 @@ Set fields for an agent. Only the flags given change; the others keep what's sto
Clear every field for an agent, so it goes back to its own values Clear every field for an agent, so it goes back to its own values
**Usage:** `swarmctl agent inference clear [OPTIONS] <AGENT>` **Usage:** `swarmctl agent inference clear <AGENT>`
###### **Arguments:** ###### **Arguments:**
* `<AGENT>` — Agent name * `<AGENT>` — Agent name
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl agent permissions` ## `swarmctl agent permissions`
@ -288,18 +255,12 @@ The agent applies its tool permissions at its next turn; the hive running it res
Show the permissions the swarm grants an agent, or that it sets none Show the permissions the swarm grants an agent, or that it sets none
**Usage:** `swarmctl agent permissions get [OPTIONS] <AGENT>` **Usage:** `swarmctl agent permissions get <AGENT>`
###### **Arguments:** ###### **Arguments:**
* `<AGENT>` — Agent name * `<AGENT>` — Agent name
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl agent permissions set` ## `swarmctl agent permissions set`
@ -319,9 +280,6 @@ Replace the permissions the swarm grants an agent; the internet flag stays unles
Possible values: `true`, `false` Possible values: `true`, `false`
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
@ -329,18 +287,12 @@ Replace the permissions the swarm grants an agent; the internet flag stays unles
Clear the agent's permissions, so the default applies again Clear the agent's permissions, so the default applies again
**Usage:** `swarmctl agent permissions clear [OPTIONS] <AGENT>` **Usage:** `swarmctl agent permissions clear <AGENT>`
###### **Arguments:** ###### **Arguments:**
* `<AGENT>` — Agent name * `<AGENT>` — Agent name
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl agent agents-md` ## `swarmctl agent agents-md`
@ -362,18 +314,12 @@ Show an agent's AGENTS.md, or edit it with a diff.
Print an agent's AGENTS.md on stdout, and its revision on stderr Print an agent's AGENTS.md on stdout, and its revision on stderr
**Usage:** `swarmctl agent agents-md get [OPTIONS] <AGENT>` **Usage:** `swarmctl agent agents-md get <AGENT>`
###### **Arguments:** ###### **Arguments:**
* `<AGENT>` — Agent name * `<AGENT>` — Agent name
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl agent agents-md apply` ## `swarmctl agent agents-md apply`
@ -382,7 +328,7 @@ Apply a unified diff to an agent's AGENTS.md.
The diff names `a/AGENTS.md` and `b/AGENTS.md`, as `diff -u a/AGENTS.md b/AGENTS.md` writes it. The agent refuses it when the file is no longer at `--base`, or when it doesn't apply, and leaves the file as it was. The diff names `a/AGENTS.md` and `b/AGENTS.md`, as `diff -u a/AGENTS.md b/AGENTS.md` writes it. The agent refuses it when the file is no longer at `--base`, or when it doesn't apply, and leaves the file as it was.
**Usage:** `swarmctl agent agents-md apply [OPTIONS] --base <REVISION> <AGENT> <DIFF_FILE>` **Usage:** `swarmctl agent agents-md apply --base <REVISION> <AGENT> <DIFF_FILE>`
###### **Arguments:** ###### **Arguments:**
@ -392,9 +338,6 @@ The diff names `a/AGENTS.md` and `b/AGENTS.md`, as `diff -u a/AGENTS.md b/AGENTS
###### **Options:** ###### **Options:**
* `--base <REVISION>` — The revision you made the diff against, as `get` printed it. It's the git blob id of that text, so `git hash-object` of the unedited file prints it too * `--base <REVISION>` — The revision you made the diff against, as `get` printed it. It's the git blob id of that text, so `git hash-object` of the unedited file prints it too
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
@ -433,9 +376,6 @@ Without `--every` it fires once. Without `--at` its first fire is now.
* `--at <TIME>` — First fire time: an RFC 3339 time with its offset, such as `2026-10-05T09:00:00+02:00`, or unix seconds. Defaults to now * `--at <TIME>` — First fire time: an RFC 3339 time with its offset, such as `2026-10-05T09:00:00+02:00`, or unix seconds. Defaults to now
* `--every <DURATION>` — Time between fires: a count with a unit of `s`, `m`, `h` or `d`, such as `1h` or `7d`. Leave out for a one-shot * `--every <DURATION>` — Time between fires: a count with a unit of `s`, `m`, `h` or `d`, such as `1h` or `7d`. Leave out for a one-shot
* `--paused` — Add it paused * `--paused` — Add it paused
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
@ -448,9 +388,6 @@ List scheduled prompts, one row each, with their agents and next fire time
###### **Options:** ###### **Options:**
* `--agent <AGENT>` — Show only the prompts that fire in this agent * `--agent <AGENT>` — Show only the prompts that fire in this agent
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
@ -475,9 +412,6 @@ Only the flags given change, and the id stays. `--at` and `--every` move the fir
* `--once` — Make it a one-shot * `--once` — Make it a one-shot
* `--add-agent <AGENT>` — Agent to start firing it in. Repeatable * `--add-agent <AGENT>` — Agent to start firing it in. Repeatable
* `--remove-agent <AGENT>` — Agent to stop firing it in. Repeatable. Fails if the agent isn't a target, or if no agent would remain * `--remove-agent <AGENT>` — Agent to stop firing it in. Repeatable. Fails if the agent isn't a target, or if no agent would remain
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
@ -485,54 +419,36 @@ Only the flags given change, and the id stays. `--at` and `--every` move the fir
Stop a scheduled prompt firing. Times that pass while it's paused aren't fired when it resumes Stop a scheduled prompt firing. Times that pass while it's paused aren't fired when it resumes
**Usage:** `swarmctl schedule pause [OPTIONS] <ID>` **Usage:** `swarmctl schedule pause <ID>`
###### **Arguments:** ###### **Arguments:**
* `<ID>` — The prompt's id, as `schedule list` shows it * `<ID>` — The prompt's id, as `schedule list` shows it
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl schedule resume` ## `swarmctl schedule resume`
Let a paused scheduled prompt fire again, from its next time on Let a paused scheduled prompt fire again, from its next time on
**Usage:** `swarmctl schedule resume [OPTIONS] <ID>` **Usage:** `swarmctl schedule resume <ID>`
###### **Arguments:** ###### **Arguments:**
* `<ID>` — The prompt's id, as `schedule list` shows it * `<ID>` — The prompt's id, as `schedule list` shows it
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl schedule rm` ## `swarmctl schedule rm`
Remove a scheduled prompt from every agent it names Remove a scheduled prompt from every agent it names
**Usage:** `swarmctl schedule rm [OPTIONS] <ID>` **Usage:** `swarmctl schedule rm <ID>`
###### **Arguments:** ###### **Arguments:**
* `<ID>` — The prompt's id, as `schedule list` shows it * `<ID>` — The prompt's id, as `schedule list` shows it
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl user` ## `swarmctl user`
@ -631,18 +547,12 @@ Make an existing forge user a site admin.
The forge creates a human's account on their first SSO login, and this fails until that login has happened. Running it on a site admin changes nothing. Refused for an agent. The forge creates a human's account on their first SSO login, and this fails until that login has happened. Running it on a site admin changes nothing. Refused for an agent.
**Usage:** `swarmctl forge make-admin [OPTIONS] <NAME>` **Usage:** `swarmctl forge make-admin <NAME>`
###### **Arguments:** ###### **Arguments:**
* `<NAME>` — Forge username, the same as the user's SSO username * `<NAME>` — Forge username, the same as the user's SSO username
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl setup` ## `swarmctl setup`
@ -653,19 +563,13 @@ Run it as root, in a terminal. It checks `docs/1-getting-started/setup.md` first
For scripts, use `setup status` and the individual verbs. For scripts, use `setup status` and the individual verbs.
**Usage:** `swarmctl setup [OPTIONS] **Usage:** `swarmctl setup
setup <COMMAND>` setup <COMMAND>`
###### **Subcommands:** ###### **Subcommands:**
* `status` — Print the first-run setup as a progress report: a count and a bar, then each step as done, not done or unknown, and what to do next * `status` — Print the first-run setup as a progress report: a count and a bar, then each step as done, not done or unknown, and what to do next
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.
## `swarmctl setup status` ## `swarmctl setup status`
@ -676,13 +580,7 @@ Read-only, and needs no token. The secret store's steps come from `bao status` a
Exits 0 when every step it can see has finished, and 1 otherwise, including when a check failed to run. Step 10, another agent, is optional and never changes the exit code. The steps are those of `docs/1-getting-started/setup.md`. Exits 0 when every step it can see has finished, and 1 otherwise, including when a check failed to run. Step 10, another agent, is optional and never changes the exit code. The steps are those of `docs/1-getting-started/setup.md`.
**Usage:** `swarmctl setup status [OPTIONS]` **Usage:** `swarmctl setup status`
###### **Options:**
* `--controller-socket <PATH>` — swarm-controller's unix socket.
Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to `SWARM_CONTROLLER_SOCKET`. The controller runs as a pod and has no socket on the host, so name the swarm instead.

View file

@ -13,9 +13,8 @@ anyhow.workspace = true
# PKCE verifier, state and S256 challenge for `swarmctl login`. # PKCE verifier, state and S256 challenge for `swarmctl login`.
base64.workspace = true base64.workspace = true
chrono.workspace = true chrono.workspace = true
# `agent create` — bare HTTP/1.1 client over swarm-controller's unix # Request and response bodies of the gateway calls; `http-body-util`,
# socket. No new workspace dependency: `bytes`, `http-body-util`, # `hyper` and `hyper-util` also serve the loopback listener of `swarmctl login`.
# `hyper` and `hyper-util` are all already pinned in the root manifest.
bytes = "1" bytes = "1"
clap.workspace = true clap.workspace = true
clap-markdown = "0.1" clap-markdown = "0.1"

View file

@ -61,7 +61,6 @@ an error.
| `SWARMCTL_AUTHELIA_UNIT` | authelia's unit inside that container | | `SWARMCTL_AUTHELIA_UNIT` | authelia's unit inside that container |
| `SWARMCTL_BAO_BOOTSTRAP_TOKEN_FILE` | where `bao grant-bootstrap` places the 24h grant token | | `SWARMCTL_BAO_BOOTSTRAP_TOKEN_FILE` | where `bao grant-bootstrap` places the 24h grant token |
| `SWARMCTL_BAO_BOOTSTRAP_POLICY` | the `bao-bootstrap` policy file `bao grant-bootstrap` writes | | `SWARMCTL_BAO_BOOTSTRAP_POLICY` | the `bao-bootstrap` policy file `bao grant-bootstrap` writes |
| `SWARM_CONTROLLER_SOCKET` | a controller socket to use when no swarm is named; the module sets none, as the controller is a pod |
| `SWARMCTL_LOGIN_DEFAULT_SWARM` | `https://<swarm domain>` of this host's swarm, for `login` | | `SWARMCTL_LOGIN_DEFAULT_SWARM` | `https://<swarm domain>` of this host's swarm, for `login` |
| `SWARMCTL_SWARM` | the swarm's domain, bare or `https://`: reach the controller there; the module defaults it to this host's swarm | | `SWARMCTL_SWARM` | the swarm's domain, bare or `https://`: reach the controller there; the module defaults it to this host's swarm |
| `SWARMCTL_CA_FILE` | a PEM CA to trust beside the system roots, for `SWARMCTL_SWARM` | | `SWARMCTL_CA_FILE` | a PEM CA to trust beside the system roots, for `SWARMCTL_SWARM` |
@ -299,8 +298,7 @@ too and needs one `swarmctl login`. The gateway names the sender from the SSO se
The controller runs as a pod and has no socket on the host, so the gateway is the only way in. `swarmctl user add` The controller runs as a pod and has no socket on the host, so the gateway is the only way in. `swarmctl user add`
writes authelia's users file and needs no controller, so `swarmctl login` needs only authelia and your SSO account, both there by step 2. writes authelia's users file and needs no controller, so `swarmctl login` needs only authelia and your SSO account, both there by step 2.
`--controller-socket` and `SWARM_CONTROLLER_SOCKET` still name a unix socket for a controller reached that way A verb that reaches the controller with no swarm named stops and says to name one.
(none the module sets); with neither a swarm nor a socket the verb stops and says to name the swarm.
`login` finds the swarm's SSO provider itself: the gateway's 401 at `/api/` `login` finds the swarm's SSO provider itself: the gateway's 401 at `/api/`
names a public metadata document (RFC 9728) that names authelia, so `--swarm` names a public metadata document (RFC 9728) that names authelia, so `--swarm`

View file

@ -7,11 +7,8 @@
//! settled graph would not mean the agent is up and there is nothing here //! settled graph would not mean the agent is up and there is nothing here
//! that could be waited on honestly. //! that could be waited on honestly.
//! //!
//! Transport is a bare `hyper` HTTP/1.1 client handshaked onto a //! Transport is the swarm's gateway: [`crate::remote::Swarm::request`] sends the
//! [`tokio::net::UnixStream`] via [`hyper_util::rt::TokioIo`] — the //! request with the cached login.
//! 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.
//! //!
//! The request and response bodies come from `swarm-controller-api`, which //! The request and response bodies come from `swarm-controller-api`, which
//! the controller imports too. //! the controller imports too.
@ -21,15 +18,12 @@
use std::path::Path; use std::path::Path;
use anyhow::{Context as _, Result, bail}; use anyhow::{Context as _, Result, bail};
use http_body_util::{BodyExt as _, Full};
use hyper_util::rt::TokioIo;
use serde::Serialize; use serde::Serialize;
use swarm_controller_api::agents::{ use swarm_controller_api::agents::{
CreateAgentRequest, CreateAgentResponse, MintAgentForgeTokenResponse, CreateAgentRequest, CreateAgentResponse, MintAgentForgeTokenResponse,
}; };
use tokio::net::UnixStream;
use crate::remote::Target; use crate::remote::Swarm;
/// Run `swarmctl agent create`. /// Run `swarmctl agent create`.
/// ///
@ -39,7 +33,7 @@ use crate::remote::Target;
/// way `PathArgs::resolve` is called only in the arms that need the /// way `PathArgs::resolve` is called only in the arms that need the
/// deployment's env vars. /// deployment's env vars.
pub(crate) fn create( pub(crate) fn create(
target: &Target, target: &Swarm,
name: &str, name: &str,
hive: &str, hive: &str,
agents_md: Option<&Path>, agents_md: Option<&Path>,
@ -75,7 +69,7 @@ pub(crate) fn create(
/// The round trip of [`create`] for an already validated `name` and `hive`, /// The round trip of [`create`] for an already validated `name` and `hive`,
/// printing nothing. /// printing nothing.
pub(crate) fn request_create( pub(crate) fn request_create(
target: &Target, target: &Swarm,
name: &str, name: &str,
hive: &str, hive: &str,
agents_md: Option<&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 /// 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. /// 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 name = parse_ident(name, "agent name")?;
let rt = tokio::runtime::Builder::new_current_thread() 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`. /// Run `swarmctl agent set-state`: `PUT /api/hives/{hive}/agents/{agent}/state`.
pub(crate) fn set_state( pub(crate) fn set_state(
target: &Target, target: &Swarm,
agent: &str, agent: &str,
hive: &str, hive: &str,
state: swarm_wire::wanted::AgentState, 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`, /// The round trip of [`set_state`] for an already validated `agent` and `hive`,
/// printing nothing. Returns the state as the wire spells it. /// printing nothing. Returns the state as the wire spells it.
pub(crate) fn request_state( pub(crate) fn request_state(
target: &Target, target: &Swarm,
agent: &str, agent: &str,
hive: &str, hive: &str,
state: swarm_wire::wanted::AgentState, state: swarm_wire::wanted::AgentState,
@ -181,7 +175,7 @@ pub(crate) fn request_state(
/// One `POST /api/agents` round trip at the controller. /// One `POST /api/agents` round trip at the controller.
async fn post_create( async fn post_create(
target: &Target, target: &Swarm,
name: &str, name: &str,
hive: &str, hive: &str,
agents_md: Option<&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 /// which call failed, and every other part of this function is identical
/// between the two verbs. /// between the two verbs.
pub(crate) async fn post<Req: Serialize, Resp: serde::de::DeserializeOwned>( pub(crate) async fn post<Req: Serialize, Resp: serde::de::DeserializeOwned>(
target: &Target, target: &Swarm,
uri: &str, uri: &str,
request: &Req, request: &Req,
what: &str, 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 /// when there is one. A `204` decodes as JSON `null`, so a caller expecting no
/// body asks for `()`. /// body asks for `()`.
pub(crate) async fn send<Req: Serialize, Resp: serde::de::DeserializeOwned>( pub(crate) async fn send<Req: Serialize, Resp: serde::de::DeserializeOwned>(
target: &Target, target: &Swarm,
method: hyper::Method, method: hyper::Method,
uri: &str, uri: &str,
request: Option<&Req>, request: Option<&Req>,
@ -233,10 +227,7 @@ pub(crate) async fn send<Req: Serialize, Resp: serde::de::DeserializeOwned>(
.transpose() .transpose()
.with_context(|| format!("serialising the {what} request"))?; .with_context(|| format!("serialising the {what} request"))?;
let (status, body) = match target { let (status, body) = target.request(method, uri, body, what).await?;
Target::Socket(socket) => over_socket(socket, method, uri, body, what).await?,
Target::Swarm(swarm) => swarm.request(method, uri, body, what).await?,
};
if !status.is_success() { if !status.is_success() {
bail!("{}", describe_error(status, &body)); 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. /// Turn a failed response into one line the operator can act on.
/// ///
/// The controller answers errors as RFC 9457 `application/problem+json`, /// 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)] #[cfg(test)]
mod tests { 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; 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 /// The accepted values are the wire enum's: each spelling it writes
/// parses back, and an unknown one names the valid ones. /// parses back, and an unknown one names the valid ones.
#[test] #[test]

View file

@ -11,7 +11,7 @@ use anyhow::{Context as _, Result};
use swarm_controller_api::agents_md::{AgentsMdEdit, AgentsMdSaved, AgentsMdView}; use swarm_controller_api::agents_md::{AgentsMdEdit, AgentsMdSaved, AgentsMdView};
use crate::agent::{parse_ident, send}; use crate::agent::{parse_ident, send};
use crate::remote::Target; use crate::remote::Swarm;
fn runtime() -> Result<tokio::runtime::Runtime> { fn runtime() -> Result<tokio::runtime::Runtime> {
tokio::runtime::Builder::new_current_thread() tokio::runtime::Builder::new_current_thread()
@ -29,7 +29,7 @@ fn member(agent: &str) -> Result<String> {
/// Run `swarmctl agent agents-md get`: the text on stdout, unchanged, and its /// Run `swarmctl agent agents-md get`: the text on stdout, unchanged, and its
/// revision on stderr, so stdout redirected to a file is the file. /// revision on stderr, so stdout redirected to a file is the file.
pub(crate) fn get(target: &Target, agent: &str) -> Result<()> { pub(crate) fn get(target: &Swarm, agent: &str) -> Result<()> {
let uri = member(agent)?; let uri = member(agent)?;
let view: AgentsMdView = runtime()?.block_on(send( let view: AgentsMdView = runtime()?.block_on(send(
target, target,
@ -45,7 +45,7 @@ pub(crate) fn get(target: &Target, agent: &str) -> Result<()> {
/// Run `swarmctl agent agents-md apply`: send the diff in `diff_file`, made /// Run `swarmctl agent agents-md apply`: send the diff in `diff_file`, made
/// against `base`, and print the file's new revision. /// against `base`, and print the file's new revision.
pub(crate) fn apply(target: &Target, agent: &str, base: &str, diff_file: &Path) -> Result<()> { pub(crate) fn apply(target: &Swarm, agent: &str, base: &str, diff_file: &Path) -> Result<()> {
let uri = member(agent)?; let uri = member(agent)?;
let diff = std::fs::read_to_string(diff_file) let diff = std::fs::read_to_string(diff_file)
.with_context(|| format!("reading the diff {}", diff_file.display()))?; .with_context(|| format!("reading the diff {}", diff_file.display()))?;

View file

@ -2,25 +2,24 @@
//! admin, through the swarm-controller over the forge's admin API. //! admin, through the swarm-controller over the forge's admin API.
//! //!
//! Unlike the `agent` verbs this one waits: the controller answers with what //! Unlike the `agent` verbs this one waits: the controller answers with what
//! it found. Same round trip as [`crate::agent`], over the controller's unix //! it found. Same round trip as [`crate::agent`], through the gateway.
//! socket.
use anyhow::{Context as _, Result}; use anyhow::{Context as _, Result};
use swarm_controller_api::forge::{ForgeAdminChange, MakeForgeAdminResponse}; use swarm_controller_api::forge::{ForgeAdminChange, MakeForgeAdminResponse};
use crate::agent::{parse_ident, post}; use crate::agent::{parse_ident, post};
use crate::remote::Target; use crate::remote::Swarm;
/// Run `swarmctl forge make-admin`. /// Run `swarmctl forge make-admin`.
/// ///
/// Synchronous for the same reason `agent create` is. /// Synchronous for the same reason `agent create` is.
pub(crate) fn make_admin(target: &Target, name: &str) -> Result<()> { pub(crate) fn make_admin(target: &Swarm, name: &str) -> Result<()> {
println!("{}", request_admin(target, name)?); println!("{}", request_admin(target, name)?);
Ok(()) Ok(())
} }
/// The round trip of [`make_admin`]: the sentence it prints, not printed. /// The round trip of [`make_admin`]: the sentence it prints, not printed.
pub(crate) fn request_admin(target: &Target, name: &str) -> Result<String> { pub(crate) fn request_admin(target: &Swarm, name: &str) -> Result<String> {
let name = parse_ident(name, "user name")?; let name = parse_ident(name, "user name")?;
let rt = tokio::runtime::Builder::new_current_thread() let rt = tokio::runtime::Builder::new_current_thread()

View file

@ -15,7 +15,7 @@ use swarm_controller_api::inference::{
}; };
use crate::agent::{parse_ident, send}; use crate::agent::{parse_ident, send};
use crate::remote::Target; use crate::remote::Swarm;
/// What `agent inference set` was asked to change. /// What `agent inference set` was asked to change.
pub(crate) struct SetFlags { pub(crate) struct SetFlags {
@ -65,7 +65,7 @@ fn member(agent: &str) -> Result<String> {
} }
/// Run `swarmctl agent inference get`. /// Run `swarmctl agent inference get`.
pub(crate) fn get(target: &Target, agent: &str) -> Result<()> { pub(crate) fn get(target: &Swarm, agent: &str) -> Result<()> {
let uri = member(agent)?; let uri = member(agent)?;
let view: AgentInferenceView = runtime()?.block_on(send( let view: AgentInferenceView = runtime()?.block_on(send(
target, target,
@ -84,7 +84,7 @@ pub(crate) fn get(target: &Target, agent: &str) -> Result<()> {
/// Run `swarmctl agent inference set`: read the agent's settings, write the /// Run `swarmctl agent inference set`: read the agent's settings, write the
/// flags over them, and store the result. /// flags over them, and store the result.
pub(crate) fn set(target: &Target, agent: &str, flags: SetFlags) -> Result<()> { pub(crate) fn set(target: &Swarm, agent: &str, flags: SetFlags) -> Result<()> {
let uri = member(agent)?; let uri = member(agent)?;
let rt = runtime()?; let rt = runtime()?;
let current: AgentInferenceView = rt.block_on(send( let current: AgentInferenceView = rt.block_on(send(
@ -107,7 +107,7 @@ pub(crate) fn set(target: &Target, agent: &str, flags: SetFlags) -> Result<()> {
} }
/// Run `swarmctl agent inference clear`. /// Run `swarmctl agent inference clear`.
pub(crate) fn clear(target: &Target, agent: &str) -> Result<()> { pub(crate) fn clear(target: &Swarm, agent: &str) -> Result<()> {
let uri = member(agent)?; let uri = member(agent)?;
runtime()?.block_on(send::<(), ()>( runtime()?.block_on(send::<(), ()>(
target, target,

View file

@ -38,7 +38,7 @@ pub(crate) struct HostFacts {
pub(crate) store: StoreHost, pub(crate) store: StoreHost,
/// The nix module gave `swarmctl` authelia's binary and users file. /// The nix module gave `swarmctl` authelia's binary and users file.
pub(crate) sso: bool, pub(crate) sso: bool,
/// The controller's socket, or a `--swarm`, is known. /// A `--swarm` is known.
pub(crate) controller: bool, pub(crate) controller: bool,
} }

View file

@ -17,9 +17,8 @@
//! Acting directly is not the same as acting *alone*, though: the `agent`, //! Acting directly is not the same as acting *alone*, though: the `agent`,
//! `schedule` and `forge` verbs are clients of the controller, because the //! `schedule` and `forge` verbs are clients of the controller, because the
//! work they ask for is only the controller's to do (see [`agent`]). They //! work they ask for is only the controller's to do (see [`agent`]). They
//! reach it over its unix socket on its host, or, with `--swarm`, through //! reach it through the swarm domain's gateway as the operator's own SSO
//! the swarm domain's gateway as the operator's own SSO account //! account ([`remote`]). The `user` verbs act on the local users file only; the `bao`
//! ([`remote`]). The `user` verbs act on the local users file only; the `bao`
//! verbs run the `bao` CLI against the secret store. `setup` walks the first-run //! verbs run the `bao` CLI against the secret store. `setup` walks the first-run
//! ceremony interactively by calling the code of those verbs ([`interactive`], //! ceremony interactively by calling the code of those verbs ([`interactive`],
//! [`terminal`]). //! [`terminal`]).
@ -53,7 +52,7 @@ use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use clap::{Args, Parser, Subcommand}; use clap::{Args, Parser, Subcommand};
use remote::Target; use remote::Swarm;
use users::{User, UserStore}; use users::{User, UserStore};
#[derive(Parser)] #[derive(Parser)]
@ -83,18 +82,16 @@ struct LoginArgs {
callback_port: u16, callback_port: u16,
} }
/// Which swarm to reach through its domain rather than the local socket. /// Which swarm to reach through its domain.
#[derive(Args)] #[derive(Args)]
struct RemoteArgs { struct RemoteArgs {
/// The swarm's domain, as `https://<domain>` or the bare domain. Given, /// The swarm's domain, as `https://<domain>` or the bare domain. Given,
/// the `agent`, `schedule` and `forge` verbs, and the agent checks and steps of `setup`, go through its gateway as the /// the `agent`, `schedule` and `forge` verbs, and the agent checks and steps of `setup`, go through its gateway as the
/// account `swarmctl login` logged in, instead of over the controller's /// account `swarmctl login` logged in. Falls back to `SWARMCTL_SWARM`; `login` then falls back to
/// socket. Falls back to `SWARMCTL_SWARM`; `login` then falls back to
/// `SWARMCTL_LOGIN_DEFAULT_SWARM`. The swarm-controller nix module sets both /// `SWARMCTL_LOGIN_DEFAULT_SWARM`. The swarm-controller nix module sets both
/// to its host's own swarm, so there the verbs use the gateway and need /// to its host's own swarm, so there the verbs use the gateway and need
/// `swarmctl login` once. With no swarm, they use the socket that /// `swarmctl login` once. The controller runs as a pod and has no socket on the
/// `--controller-socket` or `SWARM_CONTROLLER_SOCKET` names; the module sets /// host, so a verb that reaches it needs a swarm.
/// neither.
#[arg(long, value_name = "URL", global = true)] #[arg(long, value_name = "URL", global = true)]
swarm: Option<String>, swarm: Option<String>,
/// A PEM CA certificate to trust beside the system roots, for a swarm /// A PEM CA certificate to trust beside the system roots, for a swarm
@ -135,18 +132,12 @@ impl RemoteArgs {
.transpose() .transpose()
} }
/// The swarm when one is named, else the controller socket the flag or /// The swarm the verb reaches the controller through. The controller runs as a
/// `SWARM_CONTROLLER_SOCKET` names. The controller runs as a pod and has no /// pod and has no socket on the host, so a host that names no swarm is told to.
/// socket on the host, so a host with neither is told to name the swarm. fn target(&self) -> Result<Swarm> {
fn target(&self, socket: Option<PathBuf>) -> Result<Target> { self.swarm()?.context(
if let Some(swarm) = self.swarm()? { "no swarm is named — name it with `--swarm <domain>` or `SWARMCTL_SWARM` \
return Ok(Target::Swarm(swarm)); and run `swarmctl login`",
}
let socket =
socket.or_else(|| std::env::var_os("SWARM_CONTROLLER_SOCKET").map(PathBuf::from));
socket.map(Target::Socket).context(
"no swarm is named and no controller socket is given — name the swarm with \
`--swarm <domain>` or `SWARMCTL_SWARM` and run `swarmctl login`",
) )
} }
} }
@ -314,8 +305,6 @@ enum Verb {
struct SetupArgs { struct SetupArgs {
#[command(subcommand)] #[command(subcommand)]
command: Option<SetupVerb>, command: Option<SetupVerb>,
#[command(flatten)]
socket: ControllerSocketArg,
} }
#[derive(Subcommand)] #[derive(Subcommand)]
@ -335,13 +324,7 @@ enum SetupVerb {
/// when a check failed to run. Step 10, another agent, is optional and never /// when a check failed to run. Step 10, another agent, is optional and never
/// changes the exit code. The steps are those of /// changes the exit code. The steps are those of
/// `docs/1-getting-started/setup.md`. /// `docs/1-getting-started/setup.md`.
Status(SetupStatusArgs), Status,
}
#[derive(Args)]
struct SetupStatusArgs {
#[command(flatten)]
socket: ControllerSocketArg,
} }
#[derive(Subcommand)] #[derive(Subcommand)]
@ -479,8 +462,6 @@ struct AgentsMdApplyArgs {
/// file prints it too. /// file prints it too.
#[arg(long, value_name = "REVISION")] #[arg(long, value_name = "REVISION")]
base: String, base: String,
#[command(flatten)]
socket: ControllerSocketArg,
} }
#[derive(Subcommand)] #[derive(Subcommand)]
@ -513,8 +494,6 @@ struct PermissionsSetArgs {
/// the stored value stays. /// the stored value stays.
#[arg(long, value_name = "BOOL")] #[arg(long, value_name = "BOOL")]
unrestricted_internet: Option<bool>, unrestricted_internet: Option<bool>,
#[command(flatten)]
socket: ControllerSocketArg,
} }
#[derive(Subcommand)] #[derive(Subcommand)]
@ -534,8 +513,6 @@ enum InferenceVerb {
struct InferenceAgentArgs { struct InferenceAgentArgs {
/// Agent name. /// Agent name.
agent: String, agent: String,
#[command(flatten)]
socket: ControllerSocketArg,
} }
#[derive(Args)] #[derive(Args)]
@ -552,8 +529,6 @@ struct InferenceSetArgs {
/// shown; the agent doesn't apply it yet. /// shown; the agent doesn't apply it yet.
#[arg(long, value_name = "MODELS", value_delimiter = ',')] #[arg(long, value_name = "MODELS", value_delimiter = ',')]
subagent_models: Option<Vec<String>>, subagent_models: Option<Vec<String>>,
#[command(flatten)]
socket: ControllerSocketArg,
} }
#[derive(Args)] #[derive(Args)]
@ -569,16 +544,12 @@ struct AgentSetStateArgs {
/// Confirm `destroyed`, which can't be undone. /// Confirm `destroyed`, which can't be undone.
#[arg(long)] #[arg(long)]
yes: bool, yes: bool,
#[command(flatten)]
socket: ControllerSocketArg,
} }
#[derive(Args)] #[derive(Args)]
struct AgentWatchArgs { struct AgentWatchArgs {
/// Agent name. /// Agent name.
agent: String, agent: String,
#[command(flatten)]
socket: ControllerSocketArg,
} }
#[derive(Args)] #[derive(Args)]
@ -605,28 +576,12 @@ struct AgentCreateArgs {
/// The controller refuses a file over 64 KiB. /// The controller refuses a file over 64 KiB.
#[arg(long, value_name = "FILE")] #[arg(long, value_name = "FILE")]
agents_md: Option<PathBuf>, agents_md: Option<PathBuf>,
/// swarm-controller's unix socket.
///
/// Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to
/// `SWARM_CONTROLLER_SOCKET`.
/// The controller runs as a pod and has no socket on the host, so name
/// the swarm instead.
#[arg(long, value_name = "PATH")]
controller_socket: Option<PathBuf>,
} }
#[derive(Args)] #[derive(Args)]
struct AgentMintForgeTokenArgs { struct AgentMintForgeTokenArgs {
/// Name of an agent that already exists. /// Name of an agent that already exists.
name: String, name: String,
/// swarm-controller's unix socket.
///
/// Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to
/// `SWARM_CONTROLLER_SOCKET`.
/// The controller runs as a pod and has no socket on the host, so name
/// the swarm instead.
#[arg(long, value_name = "PATH")]
controller_socket: Option<PathBuf>,
} }
#[derive(Subcommand)] #[derive(Subcommand)]
@ -643,14 +598,6 @@ enum ForgeVerb {
struct ForgeMakeAdminArgs { struct ForgeMakeAdminArgs {
/// Forge username, the same as the user's SSO username. /// Forge username, the same as the user's SSO username.
name: String, name: String,
/// swarm-controller's unix socket.
///
/// Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to
/// `SWARM_CONTROLLER_SOCKET`.
/// The controller runs as a pod and has no socket on the host, so name
/// the swarm instead.
#[arg(long, value_name = "PATH")]
controller_socket: Option<PathBuf>,
} }
#[derive(Subcommand)] #[derive(Subcommand)]
@ -698,8 +645,6 @@ struct ScheduleAddArgs {
/// Add it paused. /// Add it paused.
#[arg(long)] #[arg(long)]
paused: bool, paused: bool,
#[command(flatten)]
socket: ControllerSocketArg,
} }
#[derive(Args)] #[derive(Args)]
@ -707,8 +652,6 @@ struct ScheduleListArgs {
/// Show only the prompts that fire in this agent. /// Show only the prompts that fire in this agent.
#[arg(long, value_name = "AGENT")] #[arg(long, value_name = "AGENT")]
agent: Option<String>, agent: Option<String>,
#[command(flatten)]
socket: ControllerSocketArg,
} }
#[derive(Args)] #[derive(Args)]
@ -737,34 +680,12 @@ struct ScheduleEditArgs {
/// target, or if no agent would remain. /// target, or if no agent would remain.
#[arg(long = "remove-agent", value_name = "AGENT")] #[arg(long = "remove-agent", value_name = "AGENT")]
remove_agents: Vec<String>, remove_agents: Vec<String>,
#[command(flatten)]
socket: ControllerSocketArg,
} }
#[derive(Args)] #[derive(Args)]
struct ScheduleIdArgs { struct ScheduleIdArgs {
/// The prompt's id, as `schedule list` shows it. /// The prompt's id, as `schedule list` shows it.
id: String, id: String,
#[command(flatten)]
socket: ControllerSocketArg,
}
#[derive(Args)]
struct ControllerSocketArg {
/// swarm-controller's unix socket.
///
/// Used when `--swarm` and `SWARMCTL_SWARM` give no swarm; falls back to
/// `SWARM_CONTROLLER_SOCKET`.
/// The controller runs as a pod and has no socket on the host, so name
/// the swarm instead.
#[arg(long, value_name = "PATH")]
controller_socket: Option<PathBuf>,
}
impl ControllerSocketArg {
fn resolve(self, remote: &RemoteArgs) -> Result<Target> {
remote.target(self.controller_socket)
}
} }
#[derive(Subcommand)] #[derive(Subcommand)]
@ -843,33 +764,33 @@ fn main() -> Result<()> {
command, command,
} = Cli::parse(); } = Cli::parse();
match command { match command {
// Resolves its own socket path, not `PathArgs`: this verb needs // Resolves its own swarm, not `PathArgs`: this verb needs
// none of the `SWARMCTL_AUTHELIA_*` values, and requiring them // none of the `SWARMCTL_AUTHELIA_*` values, and requiring them
// would make agent creation fail on a controller host that is not // would make agent creation fail on a controller host that is not
// also the swarm's SSO host. // also the swarm's SSO host.
Verb::Agent { Verb::Agent {
command: AgentVerb::Create(args), command: AgentVerb::Create(args),
} => { } => {
let target = remote.target(args.controller_socket)?; let target = remote.target()?;
agent::create(&target, &args.name, &args.hive, args.agents_md.as_deref()) agent::create(&target, &args.name, &args.hive, args.agents_md.as_deref())
} }
// Same socket-resolution reasoning as `Create` above. // Same swarm-resolution reasoning as `Create` above.
Verb::Agent { Verb::Agent {
command: AgentVerb::MintForgeToken(args), command: AgentVerb::MintForgeToken(args),
} => { } => {
let target = remote.target(args.controller_socket)?; let target = remote.target()?;
agent::mint_forge_token(&target, &args.name) agent::mint_forge_token(&target, &args.name)
} }
Verb::Agent { Verb::Agent {
command: AgentVerb::SetState(args), command: AgentVerb::SetState(args),
} => { } => {
let target = args.socket.resolve(&remote)?; let target = remote.target()?;
agent::set_state(&target, &args.agent, &args.hive, args.state, args.yes) agent::set_state(&target, &args.agent, &args.hive, args.state, args.yes)
} }
Verb::Agent { Verb::Agent {
command: AgentVerb::Watch(args), command: AgentVerb::Watch(args),
} => { } => {
let target = args.socket.resolve(&remote)?; let target = remote.target()?;
watch::watch(&target, &args.agent) watch::watch(&target, &args.agent)
} }
Verb::Agent { Verb::Agent {
@ -881,11 +802,11 @@ fn main() -> Result<()> {
Verb::Agent { Verb::Agent {
command: AgentVerb::AgentsMd { command }, command: AgentVerb::AgentsMd { command },
} => agents_md(&remote, command), } => agents_md(&remote, command),
// Same socket-resolution reasoning as `Create` above. // Same swarm-resolution reasoning as `Create` above.
Verb::Forge { Verb::Forge {
command: ForgeVerb::MakeAdmin(args), command: ForgeVerb::MakeAdmin(args),
} => { } => {
let target = remote.target(args.controller_socket)?; let target = remote.target()?;
forge::make_admin(&target, &args.name) forge::make_admin(&target, &args.name)
} }
// Acts through the `bao` CLI only: none of the `SWARMCTL_AUTHELIA_*` values apply. // Acts through the `bao` CLI only: none of the `SWARMCTL_AUTHELIA_*` values apply.
@ -896,9 +817,9 @@ fn main() -> Result<()> {
command: BaoVerb::GrantBootstrap(args), command: BaoVerb::GrantBootstrap(args),
} => bao::grant_bootstrap(args), } => bao::grant_bootstrap(args),
// Needs none of the `SWARMCTL_AUTHELIA_*` values: it reads the cluster and systemd. // Needs none of the `SWARMCTL_AUTHELIA_*` values: it reads the cluster and systemd.
// Same socket-resolution reasoning as `Create` above. // Same swarm-resolution reasoning as `Create` above.
Verb::Schedule { command } => schedule(&remote, command), Verb::Schedule { command } => schedule(&remote, command),
Verb::Setup(args) => setup_verb(paths, &remote, args), Verb::Setup(args) => setup_verb(paths, &remote, args.command.as_ref()),
Verb::Login(args) => login::login( Verb::Login(args) => login::login(
&remote &remote
.login_swarm()? .login_swarm()?
@ -944,13 +865,13 @@ fn main() -> Result<()> {
} }
} }
/// Neither the controller socket nor the users file is required: a host /// Neither the users file nor a named swarm with a login is required: a host
/// without one still reports, and walks, the steps that need neither. /// without them still reports, and walks, the steps that need neither.
fn setup_verb(paths: PathArgs, remote: &RemoteArgs, args: SetupArgs) -> Result<()> { fn setup_verb(paths: PathArgs, remote: &RemoteArgs, command: Option<&SetupVerb>) -> Result<()> {
let users_file = path_from(paths.users_file, "SWARMCTL_AUTHELIA_USERS_FILE"); let users_file = path_from(paths.users_file, "SWARMCTL_AUTHELIA_USERS_FILE");
match args.command { match command {
Some(SetupVerb::Status(status)) => { Some(&SetupVerb::Status) => {
let target = status.socket.resolve(remote); let target = remote.target();
let complete = setup::status(&target, &users_file); let complete = setup::status(&target, &users_file);
io::stdout().flush().context("writing the report")?; io::stdout().flush().context("writing the report")?;
if !complete { if !complete {
@ -959,7 +880,7 @@ fn setup_verb(paths: PathArgs, remote: &RemoteArgs, args: SetupArgs) -> Result<(
Ok(()) Ok(())
} }
None => { None => {
let target = args.socket.resolve(remote); let target = remote.target();
let authelia_bin = path_from(paths.authelia_bin, "SWARMCTL_AUTHELIA_BIN"); let authelia_bin = path_from(paths.authelia_bin, "SWARMCTL_AUTHELIA_BIN");
terminal::setup(target, users_file, authelia_bin) terminal::setup(target, users_file, authelia_bin)
} }
@ -968,9 +889,9 @@ fn setup_verb(paths: PathArgs, remote: &RemoteArgs, args: SetupArgs) -> Result<(
fn inference(remote: &RemoteArgs, command: InferenceVerb) -> Result<()> { fn inference(remote: &RemoteArgs, command: InferenceVerb) -> Result<()> {
match command { match command {
InferenceVerb::Get(a) => inference::get(&a.socket.resolve(remote)?, &a.agent), InferenceVerb::Get(a) => inference::get(&remote.target()?, &a.agent),
InferenceVerb::Set(a) => inference::set( InferenceVerb::Set(a) => inference::set(
&a.socket.resolve(remote)?, &remote.target()?,
&a.agent, &a.agent,
inference::SetFlags { inference::SetFlags {
model: a.model, model: a.model,
@ -978,28 +899,28 @@ fn inference(remote: &RemoteArgs, command: InferenceVerb) -> Result<()> {
subagent_models: a.subagent_models, subagent_models: a.subagent_models,
}, },
), ),
InferenceVerb::Clear(a) => inference::clear(&a.socket.resolve(remote)?, &a.agent), InferenceVerb::Clear(a) => inference::clear(&remote.target()?, &a.agent),
} }
} }
fn permissions(remote: &RemoteArgs, command: PermissionsVerb) -> Result<()> { fn permissions(remote: &RemoteArgs, command: PermissionsVerb) -> Result<()> {
match command { match command {
PermissionsVerb::Get(a) => permissions::get(&a.socket.resolve(remote)?, &a.agent), PermissionsVerb::Get(a) => permissions::get(&remote.target()?, &a.agent),
PermissionsVerb::Set(a) => permissions::set( PermissionsVerb::Set(a) => permissions::set(
&a.socket.resolve(remote)?, &remote.target()?,
&a.agent, &a.agent,
&a.permissions, &a.permissions,
a.unrestricted_internet, a.unrestricted_internet,
), ),
PermissionsVerb::Clear(a) => permissions::clear(&a.socket.resolve(remote)?, &a.agent), PermissionsVerb::Clear(a) => permissions::clear(&remote.target()?, &a.agent),
} }
} }
fn agents_md(remote: &RemoteArgs, command: AgentsMdVerb) -> Result<()> { fn agents_md(remote: &RemoteArgs, command: AgentsMdVerb) -> Result<()> {
match command { match command {
AgentsMdVerb::Get(a) => agents_md::get(&a.socket.resolve(remote)?, &a.agent), AgentsMdVerb::Get(a) => agents_md::get(&remote.target()?, &a.agent),
AgentsMdVerb::Apply(a) => { AgentsMdVerb::Apply(a) => {
agents_md::apply(&a.socket.resolve(remote)?, &a.agent, &a.base, &a.diff_file) agents_md::apply(&remote.target()?, &a.agent, &a.base, &a.diff_file)
} }
} }
} }
@ -1007,7 +928,7 @@ fn agents_md(remote: &RemoteArgs, command: AgentsMdVerb) -> Result<()> {
fn schedule(remote: &RemoteArgs, command: ScheduleVerb) -> Result<()> { fn schedule(remote: &RemoteArgs, command: ScheduleVerb) -> Result<()> {
match command { match command {
ScheduleVerb::Add(a) => schedule::add( ScheduleVerb::Add(a) => schedule::add(
&a.socket.resolve(remote)?, &remote.target()?,
&schedule::AddFlags { &schedule::AddFlags {
name: &a.name, name: &a.name,
agents: &a.agents, agents: &a.agents,
@ -1017,7 +938,7 @@ fn schedule(remote: &RemoteArgs, command: ScheduleVerb) -> Result<()> {
paused: a.paused, paused: a.paused,
}, },
), ),
ScheduleVerb::List(a) => schedule::list(&a.socket.resolve(remote)?, a.agent.as_deref()), ScheduleVerb::List(a) => schedule::list(&remote.target()?, a.agent.as_deref()),
ScheduleVerb::Edit(a) => { ScheduleVerb::Edit(a) => {
let edit = schedule::edit_request(schedule::EditFlags { let edit = schedule::edit_request(schedule::EditFlags {
name: a.name, name: a.name,
@ -1028,11 +949,11 @@ fn schedule(remote: &RemoteArgs, command: ScheduleVerb) -> Result<()> {
add_agents: a.add_agents, add_agents: a.add_agents,
remove_agents: a.remove_agents, remove_agents: a.remove_agents,
})?; })?;
schedule::edit(&a.socket.resolve(remote)?, &a.id, &edit) schedule::edit(&remote.target()?, &a.id, &edit)
} }
ScheduleVerb::Pause(a) => schedule::set_paused(&a.socket.resolve(remote)?, &a.id, true), ScheduleVerb::Pause(a) => schedule::set_paused(&remote.target()?, &a.id, true),
ScheduleVerb::Resume(a) => schedule::set_paused(&a.socket.resolve(remote)?, &a.id, false), ScheduleVerb::Resume(a) => schedule::set_paused(&remote.target()?, &a.id, false),
ScheduleVerb::Rm(a) => schedule::remove(&a.socket.resolve(remote)?, &a.id), ScheduleVerb::Rm(a) => schedule::remove(&remote.target()?, &a.id),
} }
} }
@ -1535,98 +1456,32 @@ mod tests {
); );
} }
/// A host that names no swarm and gives no socket (the host of a pod-only /// A host that names no swarm (the host of a pod-only controller has no
/// controller) is told to name the swarm, not to look for a unit. /// socket to fall back on) is told to name one, not to look for a unit.
#[test] #[test]
fn with_no_swarm_and_no_socket_the_error_names_the_swarm() { fn with_no_swarm_named_the_error_names_the_swarm() {
assert!( assert!(
std::env::var_os("SWARMCTL_SWARM").is_none() std::env::var_os("SWARMCTL_SWARM").is_none(),
&& std::env::var_os("SWARM_CONTROLLER_SOCKET").is_none(), "this test needs SWARMCTL_SWARM unset"
"this test needs both variables unset"
); );
let cli = Cli::try_parse_from(["swarmctl", "schedule", "list"]).expect("parses"); let cli = Cli::try_parse_from(["swarmctl", "schedule", "list"]).expect("parses");
let Verb::Schedule { let err = cli.remote.target().err().expect("no target");
command: ScheduleVerb::List(args),
} = cli.command
else {
panic!("expected `schedule list`");
};
let err = args.socket.resolve(&cli.remote).err().expect("no target");
let text = format!("{err:#}"); let text = format!("{err:#}");
assert!( assert!(
text.contains("--swarm <domain>") && text.contains("swarmctl login"), text.contains("--swarm <domain>") && text.contains("swarmctl login"),
"{text}" "{text}"
); );
assert!(!text.contains("systemctl"), "{text}"); assert!(!text.contains("systemctl"), "{text}");
} // The control: the same verb with a swarm named resolves.
let named = Cli::try_parse_from([
/// Root on the controller host, with no `--swarm` and no login: the verbs
/// still go over the unix socket, unchanged by the remote path.
#[test]
fn with_no_swarm_named_the_verbs_use_the_controller_socket() {
assert!(
std::env::var_os("SWARMCTL_SWARM").is_none(),
"this test needs SWARMCTL_SWARM unset"
);
let dir = std::env::temp_dir().join(format!("swarmctl-socket-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("dir");
let socket = dir.join("controller.sock");
let listener = std::os::unix::net::UnixListener::bind(&socket).expect("bind");
listener.set_nonblocking(true).expect("nonblocking");
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let server_seen = std::sync::Arc::clone(&seen);
std::thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime");
rt.block_on(async move {
let listener = tokio::net::UnixListener::from_std(listener).expect("listener");
let (stream, _) = listener.accept().await.expect("accept");
let service = hyper::service::service_fn(
move |req: hyper::Request<hyper::body::Incoming>| {
server_seen.lock().expect("seen").push(format!(
"{} {} auth={}",
req.method(),
req.uri(),
req.headers().contains_key(hyper::header::AUTHORIZATION)
));
async {
Ok::<_, std::convert::Infallible>(hyper::Response::new(
http_body_util::Full::new(bytes::Bytes::from_static(b"[]")),
))
}
},
);
let _ = hyper::server::conn::http1::Builder::new()
.serve_connection(hyper_util::rt::TokioIo::new(stream), service)
.await;
});
});
let cli = Cli::try_parse_from([
"swarmctl", "swarmctl",
"--swarm",
"https://swarm.test",
"schedule", "schedule",
"list", "list",
"--controller-socket",
socket.to_str().expect("utf-8"),
]) ])
.expect("parses"); .expect("parses");
let Verb::Schedule { assert!(named.remote.target().is_ok());
command: ScheduleVerb::List(args),
} = cli.command
else {
panic!("parsed as another verb");
};
let target = args.socket.resolve(&cli.remote).expect("resolves");
assert!(matches!(&target, Target::Socket(p) if *p == socket));
schedule::list(&target, None).expect("lists over the socket");
assert_eq!(
*seen.lock().expect("seen"),
["GET /api/schedules auth=false"]
);
fs::remove_dir_all(&dir).expect("cleanup");
} }
/// clap's own consistency checks over the whole tree — a duplicated /// clap's own consistency checks over the whole tree — a duplicated
@ -1741,18 +1596,9 @@ mod tests {
} }
#[test] #[test]
fn agent_create_parses_its_name_hive_and_socket() { fn agent_create_parses_its_name_and_hive() {
let cli = Cli::try_parse_from([ let cli = Cli::try_parse_from(["swarmctl", "agent", "create", "scribe", "--hive", "alpha"])
"swarmctl", .expect("the full form parses");
"agent",
"create",
"scribe",
"--hive",
"alpha",
"--controller-socket",
"/run/elsewhere/controller.sock",
])
.expect("the full form parses");
let Verb::Agent { let Verb::Agent {
command: AgentVerb::Create(args), command: AgentVerb::Create(args),
} = cli.command } = cli.command
@ -1761,26 +1607,6 @@ mod tests {
}; };
assert_eq!(args.name, "scribe"); assert_eq!(args.name, "scribe");
assert_eq!(args.hive, "alpha"); assert_eq!(args.hive, "alpha");
assert_eq!(
args.controller_socket.as_deref(),
Some(Path::new("/run/elsewhere/controller.sock"))
);
}
/// The socket is optional on the command line because the nix wrapper
/// sets `SWARM_CONTROLLER_SOCKET`; `path_from` is what turns an absent
/// pair into an error rather than a guess.
#[test]
fn an_omitted_socket_flag_leaves_the_env_to_supply_it() {
let cli = Cli::try_parse_from(["swarmctl", "agent", "create", "scribe", "--hive", "alpha"])
.expect("the minimal form parses");
let Verb::Agent {
command: AgentVerb::Create(args),
} = cli.command
else {
panic!("expected `agent create`");
};
assert!(args.controller_socket.is_none());
} }
#[test] #[test]
@ -1819,7 +1645,6 @@ mod tests {
panic!("expected `forge make-admin`"); panic!("expected `forge make-admin`");
}; };
assert_eq!(args.name, "mara"); assert_eq!(args.name, "mara");
assert!(args.controller_socket.is_none());
assert!( assert!(
Cli::try_parse_from(["swarmctl", "forge", "make-admin"]).is_err(), Cli::try_parse_from(["swarmctl", "forge", "make-admin"]).is_err(),
"the user must be named" "the user must be named"

View file

@ -13,7 +13,7 @@ use hive_types::Permission;
use swarm_controller_api::permissions::Permissions; use swarm_controller_api::permissions::Permissions;
use crate::agent::{parse_ident, send}; use crate::agent::{parse_ident, send};
use crate::remote::Target; use crate::remote::Swarm;
fn runtime() -> Result<tokio::runtime::Runtime> { fn runtime() -> Result<tokio::runtime::Runtime> {
tokio::runtime::Builder::new_current_thread() tokio::runtime::Builder::new_current_thread()
@ -30,7 +30,7 @@ fn member(agent: &str) -> Result<String> {
} }
/// Run `swarmctl agent permissions get`. /// Run `swarmctl agent permissions get`.
pub(crate) fn get(target: &Target, agent: &str) -> Result<()> { pub(crate) fn get(target: &Swarm, agent: &str) -> Result<()> {
let uri = member(agent)?; let uri = member(agent)?;
let stored: Permissions = runtime()?.block_on(send( let stored: Permissions = runtime()?.block_on(send(
target, target,
@ -44,7 +44,7 @@ pub(crate) fn get(target: &Target, agent: &str) -> Result<()> {
} }
/// The stored record of `agent`, printing nothing. /// The stored record of `agent`, printing nothing.
pub(crate) fn fetch(target: &Target, agent: &str) -> Result<Permissions> { pub(crate) fn fetch(target: &Swarm, agent: &str) -> Result<Permissions> {
let uri = member(agent)?; let uri = member(agent)?;
runtime()?.block_on(send( runtime()?.block_on(send(
target, target,
@ -58,7 +58,7 @@ pub(crate) fn fetch(target: &Target, agent: &str) -> Result<Permissions> {
/// Run `swarmctl agent permissions set`: store the given permissions, which /// Run `swarmctl agent permissions set`: store the given permissions, which
/// replace the agent's record whole. /// replace the agent's record whole.
pub(crate) fn set( pub(crate) fn set(
target: &Target, target: &Swarm,
agent: &str, agent: &str,
permissions: &[String], permissions: &[String],
unrestricted_internet: Option<bool>, unrestricted_internet: Option<bool>,
@ -70,7 +70,7 @@ pub(crate) fn set(
/// The round trip of [`set`], printing nothing. /// The round trip of [`set`], printing nothing.
pub(crate) fn store( pub(crate) fn store(
target: &Target, target: &Swarm,
agent: &str, agent: &str,
permissions: &[String], permissions: &[String],
unrestricted_internet: Option<bool>, unrestricted_internet: Option<bool>,
@ -123,7 +123,7 @@ fn parse_permission(name: &str) -> Result<Permission> {
} }
/// Run `swarmctl agent permissions clear`. /// Run `swarmctl agent permissions clear`.
pub(crate) fn clear(target: &Target, agent: &str) -> Result<()> { pub(crate) fn clear(target: &Swarm, agent: &str) -> Result<()> {
let uri = member(agent)?; let uri = member(agent)?;
runtime()?.block_on(send::<(), ()>( runtime()?.block_on(send::<(), ()>(
target, target,

View file

@ -31,14 +31,6 @@ const HTTP_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Bound on one whole request, body included; a refresh holds the cache lock for that long at most. /// Bound on one whole request, body included; a refresh holds the cache lock for that long at most.
const HTTP_TIMEOUT: Duration = Duration::from_secs(30); const HTTP_TIMEOUT: Duration = Duration::from_secs(30);
/// Where a controller request goes.
pub(crate) enum Target {
/// swarm-controller's unix socket on this host.
Socket(PathBuf),
/// The swarm domain's gateway, with the cached login.
Swarm(Swarm),
}
/// A swarm reached by its domain. /// A swarm reached by its domain.
pub(crate) struct Swarm { pub(crate) struct Swarm {
/// `https://<swarm domain>`, with no path. /// `https://<swarm domain>`, with no path.

View file

@ -11,7 +11,7 @@ use swarm_controller_api::schedules::{
}; };
use crate::agent::{parse_ident, send}; use crate::agent::{parse_ident, send};
use crate::remote::Target; use crate::remote::Swarm;
/// What `schedule edit` was asked to change. /// What `schedule edit` was asked to change.
pub(crate) struct EditFlags<'a> { pub(crate) struct EditFlags<'a> {
@ -94,7 +94,7 @@ pub(crate) struct AddFlags<'a> {
} }
/// Run `swarmctl schedule add`. /// Run `swarmctl schedule add`.
pub(crate) fn add(target: &Target, flags: &AddFlags<'_>) -> Result<()> { pub(crate) fn add(target: &Swarm, flags: &AddFlags<'_>) -> Result<()> {
let request = AddScheduleRequest { let request = AddScheduleRequest {
name: flags.name.to_owned(), name: flags.name.to_owned(),
agents: agents(flags.agents)?, agents: agents(flags.agents)?,
@ -116,7 +116,7 @@ pub(crate) fn add(target: &Target, flags: &AddFlags<'_>) -> Result<()> {
} }
/// Run `swarmctl schedule list`, optionally only the schedules naming `agent`. /// Run `swarmctl schedule list`, optionally only the schedules naming `agent`.
pub(crate) fn list(target: &Target, agent: Option<&str>) -> Result<()> { pub(crate) fn list(target: &Swarm, agent: Option<&str>) -> Result<()> {
let agent = agent.map(|a| parse_ident(a, "agent name")).transpose()?; let agent = agent.map(|a| parse_ident(a, "agent name")).transpose()?;
let schedules: Vec<ScheduleView> = runtime()?.block_on(send( let schedules: Vec<ScheduleView> = runtime()?.block_on(send(
target, target,
@ -139,7 +139,7 @@ pub(crate) fn list(target: &Target, agent: Option<&str>) -> Result<()> {
} }
/// Run `swarmctl schedule edit`. /// Run `swarmctl schedule edit`.
pub(crate) fn edit(target: &Target, id: &str, edit: &EditScheduleRequest) -> Result<()> { pub(crate) fn edit(target: &Swarm, id: &str, edit: &EditScheduleRequest) -> Result<()> {
let edited: ScheduleView = runtime()?.block_on(send( let edited: ScheduleView = runtime()?.block_on(send(
target, target,
hyper::Method::PATCH, hyper::Method::PATCH,
@ -152,12 +152,12 @@ pub(crate) fn edit(target: &Target, id: &str, edit: &EditScheduleRequest) -> Res
} }
/// Run `swarmctl schedule pause` or `resume`. /// Run `swarmctl schedule pause` or `resume`.
pub(crate) fn set_paused(target: &Target, id: &str, paused: bool) -> Result<()> { pub(crate) fn set_paused(target: &Swarm, id: &str, paused: bool) -> Result<()> {
edit(target, id, &paused_edit(paused)) edit(target, id, &paused_edit(paused))
} }
/// Run `swarmctl schedule rm`. /// Run `swarmctl schedule rm`.
pub(crate) fn remove(target: &Target, id: &str) -> Result<()> { pub(crate) fn remove(target: &Swarm, id: &str) -> Result<()> {
let uri = member(id)?; let uri = member(id)?;
runtime()?.block_on(send::<(), ()>( runtime()?.block_on(send::<(), ()>(
target, target,

View file

@ -20,7 +20,7 @@ use serde::Deserialize;
use swarm_controller_api::permissions::Permissions; use swarm_controller_api::permissions::Permissions;
use crate::agent::send; use crate::agent::send;
use crate::remote::Target; use crate::remote::Swarm;
/// The manager agent the ceremony creates. /// The manager agent the ceremony creates.
const RUTH: &str = "ruth"; const RUTH: &str = "ruth";
@ -497,7 +497,7 @@ pub(crate) fn render(steps: &[Step], color: bool) -> String {
/// host that lacks either still reports the steps that need neither. On a /// host that lacks either still reports the steps that need neither. On a
/// terminal, a `checking <what>…` line on stderr names the running check /// terminal, a `checking <what>…` line on stderr names the running check
/// and is erased when the report prints; piped output carries only the report. /// and is erased when the report prints; piped output carries only the report.
pub(crate) fn status(target: &Result<Target>, users_file: &Result<std::path::PathBuf>) -> bool { pub(crate) fn status(target: &Result<Swarm>, users_file: &Result<std::path::PathBuf>) -> bool {
use std::io::{IsTerminal as _, Write as _}; use std::io::{IsTerminal as _, Write as _};
let live = std::io::stderr().is_terminal(); let live = std::io::stderr().is_terminal();
@ -517,16 +517,13 @@ pub(crate) fn status(target: &Result<Target>, users_file: &Result<std::path::Pat
/// Run every check once. The inputs are borrowed so that `swarmctl setup` can /// Run every check once. The inputs are borrowed so that `swarmctl setup` can
/// look again after each step. /// look again after each step.
pub(crate) fn observe( pub(crate) fn observe(target: &Result<Swarm>, users_file: &Result<std::path::PathBuf>) -> Observed {
target: &Result<Target>,
users_file: &Result<std::path::PathBuf>,
) -> Observed {
observe_with(target, users_file, &mut |_| {}) observe_with(target, users_file, &mut |_| {})
} }
/// [`observe`], calling `progress` with a name before each check starts. /// [`observe`], calling `progress` with a name before each check starts.
fn observe_with( fn observe_with(
target: &Result<Target>, target: &Result<Swarm>,
users_file: &Result<std::path::PathBuf>, users_file: &Result<std::path::PathBuf>,
progress: &mut dyn FnMut(&str), progress: &mut dyn FnMut(&str),
) -> Observed { ) -> Observed {
@ -758,7 +755,7 @@ fn has_admin_user(users_file: &Path) -> Result<bool> {
})) }))
} }
fn agents(target: &Target) -> Result<Agents> { fn agents(target: &Swarm) -> Result<Agents> {
let rt = tokio::runtime::Builder::new_current_thread() let rt = tokio::runtime::Builder::new_current_thread()
.enable_all() .enable_all()
.build() .build()
@ -1072,7 +1069,7 @@ mod tests {
granter: down("no unit"), granter: down("no unit"),
policy_units: down("no units"), policy_units: down("no units"),
admin_user: down("no users file"), admin_user: down("no users file"),
agents: down("no socket"), agents: down("not logged in"),
}; };
assert_eq!( assert_eq!(
kinds(&o), kinds(&o),
@ -1144,7 +1141,7 @@ next: step 6, setup.md § 2: `swarmctl user add <name> --email <address> --group
#[test] #[test]
fn the_header_counts_unknown_steps_apart_from_done_ones() { fn the_header_counts_unknown_steps_apart_from_done_ones() {
let mut o = pending(); let mut o = pending();
o.agents = Err("no socket".to_owned()); o.agents = Err("not logged in".to_owned());
let text = render(&classify(&o), false); let text = render(&classify(&o), false);
assert!( assert!(
text.starts_with("🏗️ setup: 5/8 steps done ██████░░░░ ❓ 4 unknown\n"), text.starts_with("🏗️ setup: 5/8 steps done ██████░░░░ ❓ 4 unknown\n"),

View file

@ -21,7 +21,7 @@ use zeroize::Zeroizing;
use crate::bao::Bao; use crate::bao::Bao;
use crate::interactive::{Actions, HostFacts, Initialised, NewUser, StoreHost, Tone, Ui}; use crate::interactive::{Actions, HostFacts, Initialised, NewUser, StoreHost, Tone, Ui};
use crate::remote::Target; use crate::remote::Swarm;
use crate::setup::{Observed, granter_unit_exists, observe}; use crate::setup::{Observed, granter_unit_exists, observe};
use crate::{AddArgs, Paths, agent, forge, permissions}; use crate::{AddArgs, Paths, agent, forge, permissions};
@ -60,7 +60,7 @@ fn use_colour(stdout_tty: bool, no_color: Option<&str>, term: Option<&str>) -> b
/// Run `swarmctl setup`. /// Run `swarmctl setup`.
pub(crate) fn setup( pub(crate) fn setup(
target: Result<Target>, target: Result<Swarm>,
users_file: Result<PathBuf>, users_file: Result<PathBuf>,
authelia_bin: Result<PathBuf>, authelia_bin: Result<PathBuf>,
) -> Result<()> { ) -> Result<()> {
@ -171,14 +171,14 @@ impl Ui for Terminal {
} }
struct Live { struct Live {
target: Result<Target>, target: Result<Swarm>,
users_file: Result<PathBuf>, users_file: Result<PathBuf>,
authelia_bin: Result<PathBuf>, authelia_bin: Result<PathBuf>,
bao: Bao, bao: Bao,
} }
impl Live { impl Live {
fn target(&self) -> Result<&Target> { fn target(&self) -> Result<&Swarm> {
self.target.as_ref().map_err(|e| anyhow!("{e:#}")) self.target.as_ref().map_err(|e| anyhow!("{e:#}"))
} }
} }

View file

@ -7,19 +7,15 @@
//! tool call. //! tool call.
//! //!
//! The ordinary request path in [`crate::agent`] buffers a whole response, so //! The ordinary request path in [`crate::agent`] buffers a whole response, so
//! the stream has its own: a unix-socket `hyper` request, or a bearer- //! the stream has its own: a bearer-authenticated gateway request whose body
//! authenticated gateway request whose body is read chunk by chunk. //! is read chunk by chunk.
use crate::agent::{describe_error, parse_ident};
use crate::remote::Swarm;
use anyhow::{Context as _, Result, bail}; use anyhow::{Context as _, Result, bail};
use http_body_util::{BodyExt as _, Empty};
use hyper_util::rt::TokioIo;
use tokio::net::UnixStream;
use crate::agent::{connect_hint, describe_error, parse_ident};
use crate::remote::Target;
/// Run `swarmctl agent watch`. Returns when the stream ends or on Ctrl-C. /// Run `swarmctl agent watch`. Returns when the stream ends or on Ctrl-C.
pub(crate) fn watch(target: &Target, agent: &str) -> Result<()> { pub(crate) fn watch(target: &Swarm, agent: &str) -> Result<()> {
let agent = parse_ident(agent, "agent name")?; let agent = parse_ident(agent, "agent name")?;
let rt = tokio::runtime::Builder::new_current_thread() let rt = tokio::runtime::Builder::new_current_thread()
.enable_all() .enable_all()
@ -33,7 +29,7 @@ pub(crate) fn watch(target: &Target, agent: &str) -> Result<()> {
}) })
} }
async fn follow(target: &Target, agent: &str) -> Result<()> { async fn follow(target: &Swarm, agent: &str) -> Result<()> {
let uri = format!("/api/agents/{agent}/term/stream"); let uri = format!("/api/agents/{agent}/term/stream");
let mut body = open(target, &uri).await?; let mut body = open(target, &uri).await?;
let mut out = std::io::stdout().lock(); let mut out = std::io::stdout().lock();
@ -41,7 +37,7 @@ async fn follow(target: &Target, agent: &str) -> Result<()> {
return Ok(()); return Ok(());
} }
let mut frames = Frames::default(); let mut frames = Frames::default();
while let Some(chunk) = body.next().await? { while let Some(chunk) = next_chunk(&mut body).await? {
for frame in frames.push(&chunk) { for frame in frames.push(&chunk) {
if let Some(line) = render_frame(&frame) if let Some(line) = render_frame(&frame)
&& !emit(&mut out, &line)? && !emit(&mut out, &line)?
@ -60,80 +56,25 @@ fn emit(out: &mut impl std::io::Write, line: &str) -> Result<bool> {
hive_types::term_out::emit(out, line).context("writing to stdout") hive_types::term_out::emit(out, line).context("writing to stdout")
} }
/// A response body read in pieces, whichever transport carried it. /// The next piece of the response body, or `None` at the end of the stream.
enum Body { async fn next_chunk(resp: &mut reqwest::Response) -> Result<Option<bytes::Bytes>> {
Socket(hyper::body::Incoming), resp.chunk()
Gateway(reqwest::Response), .await
} .context("reading swarm-controller's event stream")
impl Body {
/// The next piece of data, or `None` at the end of the stream.
async fn next(&mut self) -> Result<Option<bytes::Bytes>> {
match self {
Self::Socket(body) => {
while let Some(frame) = body.frame().await {
let frame = frame.context("reading swarm-controller's event stream")?;
if let Ok(data) = frame.into_data() {
return Ok(Some(data));
}
}
Ok(None)
}
Self::Gateway(resp) => resp
.chunk()
.await
.context("reading swarm-controller's event stream"),
}
}
} }
/// Open the stream, failing with the controller's own error on a non-2xx. /// Open the stream, failing with the controller's own error on a non-2xx.
async fn open(target: &Target, uri: &str) -> Result<Body> { async fn open(swarm: &Swarm, uri: &str) -> Result<reqwest::Response> {
match target { let resp = swarm.open_stream(uri, "watch").await?;
Target::Socket(socket) => { let status = resp.status();
let stream = UnixStream::connect(socket) if !status.is_success() {
.await let body = resp
.with_context(|| connect_hint(socket))?; .bytes()
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream)) .await
.await .context("reading the gateway's response")?;
.with_context(|| format!("HTTP handshake with {}", socket.display()))?; bail!("{}", describe_error(status, &body));
tokio::spawn(conn);
let req = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(uri)
.header(hyper::header::HOST, "localhost")
.header(hyper::header::ACCEPT, "text/event-stream")
.body(Empty::<bytes::Bytes>::new())
.context("building the watch request")?;
let resp = sender
.send_request(req)
.await
.context("sending the watch request to swarm-controller")?;
let status = resp.status();
if !status.is_success() {
let body = resp
.into_body()
.collect()
.await
.context("reading swarm-controller's response")?
.to_bytes();
bail!("{}", describe_error(status, &body));
}
Ok(Body::Socket(resp.into_body()))
}
Target::Swarm(swarm) => {
let resp = swarm.open_stream(uri, "watch").await?;
let status = resp.status();
if !status.is_success() {
let body = resp
.bytes()
.await
.context("reading the gateway's response")?;
bail!("{}", describe_error(status, &body));
}
Ok(Body::Gateway(resp))
}
} }
Ok(resp)
} }
/// Splits a byte stream into SSE frames. A chunk boundary has no relation to /// Splits a byte stream into SSE frames. A chunk boundary has no relation to
@ -187,6 +128,7 @@ fn render_raw(frame: &str) -> Option<String> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{Frames, render_frame}; use super::{Frames, render_frame};
use crate::remote::Swarm;
#[test] #[test]
fn a_frame_split_across_chunks_is_emitted_once_whole() { fn a_frame_split_across_chunks_is_emitted_once_whole() {
@ -241,14 +183,15 @@ mod tests {
assert_eq!(raw, "! \u{FFFD}[2J"); assert_eq!(raw, "! \u{FFFD}[2J");
} }
/// Serves one canned response on a fresh unix socket and returns its path. /// Serves one canned response on a loopback port and returns a swarm at it,
fn serve_once(name: &str, response: Vec<&'static [u8]>) -> std::path::PathBuf { /// logged in with a token that does not expire during the test.
fn serve_once(name: &str, response: Vec<&'static [u8]>) -> Swarm {
use std::io::{Read as _, Write as _}; use std::io::{Read as _, Write as _};
let dir = std::env::temp_dir().join(format!("swarmctl-{name}-{}", std::process::id())); let dir = std::env::temp_dir().join(format!("swarmctl-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir); let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("dir"); let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
let path = dir.join("controller.sock"); let origin = url::Url::parse(&format!("http://{}/", listener.local_addr().expect("addr")))
let listener = std::os::unix::net::UnixListener::bind(&path).expect("bind"); .expect("url");
std::thread::spawn(move || { std::thread::spawn(move || {
let (mut conn, _) = listener.accept().expect("accept"); let (mut conn, _) = listener.accept().expect("accept");
let mut seen = Vec::new(); let mut seen = Vec::new();
@ -263,7 +206,19 @@ mod tests {
std::thread::sleep(std::time::Duration::from_millis(50)); std::thread::sleep(std::time::Duration::from_millis(50));
} }
}); });
path let swarm = Swarm {
origin: origin.clone(),
ca_file: None,
state_dir: dir,
};
let cache = crate::remote::Cached {
auth: origin.as_str().trim_end_matches('/').to_owned(),
access_token: "at-0".into(),
refresh_token: "rt-0".into(),
expires_at: chrono::Utc::now().timestamp() + 3600,
};
crate::remote::write_cache(&swarm.cache_path(), &cache).expect("cache");
swarm
} }
fn rt() -> tokio::runtime::Runtime { fn rt() -> tokio::runtime::Runtime {
@ -276,8 +231,8 @@ mod tests {
/// Rows arrive as the server sends them, a frame split across two chunks /// Rows arrive as the server sends them, a frame split across two chunks
/// is rendered once, and the end of the stream ends the loop. /// is rendered once, and the end of the stream ends the loop.
#[test] #[test]
fn rows_stream_over_the_socket_until_it_closes() { fn rows_stream_through_the_gateway_until_it_closes() {
let socket = serve_once( let swarm = serve_once(
"watch-ok", "watch-ok",
vec![ vec![
b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ntransfer-encoding: chunked\r\n\r\n", b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ntransfer-encoding: chunked\r\n\r\n",
@ -287,12 +242,10 @@ mod tests {
], ],
); );
let lines = rt().block_on(async { let lines = rt().block_on(async {
let mut body = super::open(&crate::remote::Target::Socket(socket), "/x") let mut body = super::open(&swarm, "/x").await.expect("opens");
.await
.expect("opens");
let mut frames = Frames::default(); let mut frames = Frames::default();
let mut lines = Vec::new(); let mut lines = Vec::new();
while let Some(chunk) = body.next().await.expect("reads") { while let Some(chunk) = super::next_chunk(&mut body).await.expect("reads") {
lines.extend(frames.push(&chunk).iter().filter_map(|f| render_frame(f))); lines.extend(frames.push(&chunk).iter().filter_map(|f| render_frame(f)));
} }
lines lines
@ -305,7 +258,7 @@ mod tests {
fn a_refusal_surfaces_the_controllers_detail() { fn a_refusal_surfaces_the_controllers_detail() {
let body: &'static [u8] = let body: &'static [u8] =
b"{\"status\":404,\"title\":\"Not Found\",\"detail\":\"\\\"ghost\\\" has never reported\"}"; b"{\"status\":404,\"title\":\"Not Found\",\"detail\":\"\\\"ghost\\\" has never reported\"}";
let socket = serve_once( let swarm = serve_once(
"watch-404", "watch-404",
vec![ vec![
b"HTTP/1.1 404 Not Found\r\ncontent-type: application/problem+json\r\nconnection: close\r\n\r\n", b"HTTP/1.1 404 Not Found\r\ncontent-type: application/problem+json\r\nconnection: close\r\n\r\n",
@ -313,9 +266,8 @@ mod tests {
], ],
); );
let err = rt() let err = rt()
.block_on(super::open(&crate::remote::Target::Socket(socket), "/x")) .block_on(super::open(&swarm, "/x"))
.err() .expect_err("refused");
.expect("refused");
let msg = err.to_string(); let msg = err.to_string();
assert!( assert!(
msg.contains("404") && msg.contains("has never reported"), msg.contains("404") && msg.contains("has never reported"),