use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::api::{self, Ctx};
use super::changes::{self, Proposed, Signed};
use super::service::Handle;
use crate::serve::api::{ApiError, parse};
use crate::serve::fleet::member::{self, ControlPlane};
use crate::serve::fleet::membership::{self, Stored};
use crate::serve::fleet::membership_api;
use crate::serve::fleet::proposals::Change;
use crate::serve::snapshots::LinkState;
type Answer = Result<Value, ApiError>;
pub const CONTROL_PLANE_HAS_MEMBERS: &str = "the control plane can't leave while it has members: machine rm each first";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Authority<'a> {
None,
This,
Other(&'a str),
}
pub struct Here<'a> {
pub name: &'a str,
pub control_plane: &'a ControlPlane,
pub machines: &'a [String],
pub routed: bool,
pub authority: Authority<'a>,
pub in_log: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Plan {
Remove { name: String, tell: bool },
Revoke { name: String },
Propose { authority: String },
Leave { control_plane: Option<String> },
}
pub fn plan(here: &Here, name: &str, from: Option<&str>) -> Result<Plan, ApiError> {
let known = here.machines.iter().any(|m| m == name) || here.in_log;
if name == here.name {
return match here.control_plane {
ControlPlane::None => Err(ApiError::failed("this host is in no fleet")),
ControlPlane::This if from.is_some() => Err(control_plane_leaves_itself(name)),
ControlPlane::This if !here.machines.is_empty() => Err(ApiError::denied(CONTROL_PLANE_HAS_MEMBERS)),
ControlPlane::This => Ok(Plan::Leave { control_plane: None }),
ControlPlane::Other(control_plane) => Ok(Plan::Leave { control_plane: Some(control_plane.clone()) }),
};
}
if from.is_some() {
return match here.control_plane {
ControlPlane::This if known => Ok(Plan::Remove { name: name.into(), tell: from != Some(name) }),
ControlPlane::This => Err(unknown(name)),
_ => Err(ApiError::denied("`fleet.rm` runs on the control plane only")),
};
}
match here.control_plane {
ControlPlane::None if known => {
return Err(ApiError::failed(format!("this host is in no fleet: `devsandbox machine unlink {name}` drops its link")));
}
ControlPlane::None => return Err(unknown(name)),
ControlPlane::Other(control_plane) if control_plane == name => return Err(control_plane_named(name)),
_ => {}
}
match here.authority {
Authority::None => Err(ApiError::failed(
"this host's fleet has no membership log: make the fleet again with `devsandbox machine add`",
)),
Authority::Other(a) if a == name => Err(ApiError::denied(format!("`{name}` is the fleet's authority: it can't be removed"))),
_ if !(known || here.routed) => Err(unknown(name)),
Authority::This => Ok(Plan::Revoke { name: name.into() }),
Authority::Other(a) => Ok(Plan::Propose { authority: a.into() }),
}
}
fn control_plane_leaves_itself(control_plane: &str) -> ApiError {
ApiError::denied(format!("`{control_plane}` is the control plane: it leaves on its own host"))
}
fn control_plane_named(control_plane: &str) -> ApiError {
ApiError::denied(format!("`{control_plane}` is the control plane: move the role first (`devsandbox machine control-plane <m>`)"))
}
fn unknown(name: &str) -> ApiError {
ApiError::not_found(format!("no machine named `{name}`"))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Heard {
Told,
Leaving,
Unreachable,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Missed {
pub name: String,
pub error: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Removed {
pub name: String,
pub control_plane: String,
pub leave: Heard,
pub error: Option<String>,
pub forgot: Vec<String>,
pub missed: Vec<Missed>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Left {
pub name: String,
pub control_plane: String,
pub removed: Option<Removed>,
pub error: Option<String>,
pub dropped: Vec<String>,
pub proposed: Option<Proposed>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum RmAnswer {
Revoked(Signed),
Proposed(Proposed),
Left(Left),
}
#[derive(Debug, PartialEq, Eq)]
pub enum After {
Left,
Unlinked(String),
Rotated,
ControlPlane(ControlPlane),
}
pub fn apply(after: After, ctx: &Ctx) {
match after {
After::Left => {
(ctx.control_plane_changed)(ControlPlane::None);
if let Some(links) = &ctx.links {
links.reload();
}
}
After::Unlinked(name) => {
if let Some(links) = &ctx.links {
links.reload();
}
if ctx.inbound.contains(&name) {
(ctx.end_inbound)(&name);
}
}
After::Rotated => (ctx.key_rotated)(),
After::ControlPlane(control_plane) => (ctx.control_plane_changed)(control_plane),
}
}
#[derive(Deserialize)]
struct NameParams {
name: String,
}
pub(super) fn member_toml(ctx: &Ctx) -> Result<&std::path::Path, ApiError> {
ctx.member.as_deref().ok_or_else(|| ApiError::failed("this daemon has no member.toml (no data dir)"))
}
pub fn authority_of<'a>(stored: Option<&'a Stored>, me: &str, key: &crate::serve::fleet::identity::PublicKey) -> Authority<'a> {
match stored.and_then(|s| s.log.membership()) {
None => Authority::None,
Some(m) if m.authority.0 == me && m.is_authority(key) => Authority::This,
Some(m) => Authority::Other(&m.authority.0),
}
}
fn in_log(stored: Option<&Stored>, name: &str) -> bool {
stored.is_some_and(|s| s.log.membership().is_some_and(|m| m.members.contains_key(name)) || s.log.revoked_name(name))
}
pub fn rm(params: Value, ctx: &Ctx) -> Answer {
let p: NameParams = parse(params)?;
let (me, control_plane) = api::own_member(ctx)?;
let path = member_toml(ctx)?;
let machines: Vec<String> = api::machines(ctx)?.into_iter().map(|e| e.name).collect();
let routed = ctx.links.as_ref().is_some_and(|l| l.routed_one(&p.name).is_some());
let stored = membership_api::load(path)?;
let (_, key) = membership_api::own(path, &ctx.hostname)?;
let authority = authority_of(stored.as_ref(), &me, &crate::serve::fleet::identity::Signer::public_key(&key));
let here = Here { name: &me, control_plane: &control_plane, machines: &machines, routed, authority, in_log: in_log(stored.as_ref(), &p.name) };
let answer = match plan(&here, &p.name, None)? {
Plan::Revoke { name } => RmAnswer::Revoked(changes::revoke(ctx, &name)?),
Plan::Propose { authority } => {
let id = changes::propose(ctx, &authority, Change::Revoke { name: p.name.clone() })?;
RmAnswer::Proposed(Proposed { name: p.name, authority, id: Some(id), error: None })
}
Plan::Leave { control_plane } => {
let proposed = match authority {
Authority::Other(a) => Some(match changes::propose(ctx, a, Change::Revoke { name: me.clone() }) {
Ok(id) => Proposed { name: me.clone(), authority: a.into(), id: Some(id), error: None },
Err(e) => Proposed { name: me.clone(), authority: a.into(), id: None, error: Some(e.message) },
}),
_ => None,
};
RmAnswer::Left(leave(ctx, &me, control_plane, proposed)?)
}
Plan::Remove { .. } => unreachable!("only `fleet.rm` removes without a revoke here"),
};
serde_json::to_value(answer).map_err(|e| ApiError::internal(e.into()))
}
fn leave(ctx: &Ctx, me: &str, control_plane: Option<String>, proposed: Option<Proposed>) -> Result<Left, ApiError> {
let (removed, error) = match &control_plane {
None => (None, None),
Some(control_plane) => match call(ctx, control_plane, "fleet.rm", json!({ "name": me })) {
Ok(v) => match serde_json::from_value::<Removed>(v) {
Ok(r) => (Some(r), None),
Err(e) => (None, Some(format!("fleet.rm: unexpected answer: {e}"))),
},
Err(why) => (None, Some(why)),
},
};
let dropped = drop_all(ctx)?;
apply(After::Left, ctx);
Ok(Left { name: me.into(), control_plane: control_plane.unwrap_or_else(|| me.into()), removed, error, dropped, proposed })
}
fn drop_all(ctx: &Ctx) -> Result<Vec<String>, ApiError> {
let path = member_toml(ctx)?;
let dropped = super::update(&ctx.registry, |entries| std::mem::take(entries).into_iter().map(|e| e.name).collect());
let dropped: Vec<String> = dropped.map_err(ApiError::internal)?;
member::set_fleet(path, None, &ControlPlane::None).map_err(ApiError::internal)?;
let log = membership::path(path);
match std::fs::remove_file(&log) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(ApiError::internal(anyhow::Error::new(e).context(format!("cannot remove {}", log.display())))),
}
Ok(dropped)
}
pub(super) fn remove(ctx: &Ctx, control_plane: &str, name: &str, tell: bool, machines: &[String]) -> Result<(Removed, After), ApiError> {
let log = membership_api::load(member_toml(ctx)?)?.map(|s| serde_json::to_value(s.to_wire()));
let log = log.transpose().map_err(|e| ApiError::internal(e.into()))?;
let sync = |to: &str| {
if let Some(log) = &log {
let _ = call(ctx, to, "fleet.sync", log.clone());
}
};
let (leave, error) = if !tell {
(Heard::Leaving, None)
} else {
sync(name);
match call(ctx, name, "fleet.leave", json!({})) {
Ok(_) => (Heard::Told, None),
Err(why) => (Heard::Unreachable, Some(why)),
}
};
let (mut forgot, mut missed) = (Vec::new(), Vec::new());
let routed: Vec<String> = ctx.links.as_ref().map(|l| l.routed().into_iter().map(|r| r.name).collect()).unwrap_or_default();
for other in &forget_targets(machines, &routed, control_plane, name) {
sync(other);
match call(ctx, other, "fleet.forget", json!({ "name": name })) {
Ok(_) => forgot.push(other.clone()),
Err(error) => missed.push(Missed { name: other.clone(), error }),
}
}
unregister(ctx, name)?;
let removed = Removed { name: name.into(), control_plane: control_plane.into(), leave, error, forgot, missed };
Ok((removed, After::Unlinked(name.into())))
}
fn forget_targets(machines: &[String], routed: &[String], control_plane: &str, name: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for m in machines.iter().chain(routed) {
if m != name && m != control_plane && !out.contains(m) {
out.push(m.clone());
}
}
out
}
fn unregister(ctx: &Ctx, name: &str) -> Result<(), ApiError> {
super::update(&ctx.registry, |entries| entries.retain(|e| e.name != name)).map_err(ApiError::internal)
}
pub(super) fn call(ctx: &Ctx, name: &str, method: &str, params: Value) -> Result<Value, String> {
match &ctx.links {
Some(links) => answer_of(method, links.call_member(name, method, params)?),
None => Err("no links here".into()),
}
}
pub(crate) fn call_on(links: &Handle, name: &str, method: &str, params: Value) -> Result<Value, String> {
direct_up(links, name)?;
answer_of(method, links.forward(name, method, params).map_err(|e| e.message)?)
}
pub(crate) fn call_on_within(links: &Handle, name: &str, method: &str, params: Value, wait: std::time::Duration) -> Result<Value, String> {
direct_up(links, name)?;
answer_of(method, links.forward_within(name, method, params, wait).map_err(|e| e.message)?)
}
fn direct_up(links: &Handle, name: &str) -> Result<(), String> {
match links.remotes().get(name) {
Some(m) if m.state == LinkState::Connected => Ok(()),
Some(m) => Err(m.error.unwrap_or_else(|| "its link isn't up".into())),
None => Err("no link to it".into()),
}
}
fn answer_of(method: &str, r: crate::serve::proto::Response) -> Result<Value, String> {
if let Some(e) = r.error {
return Err(format!("{method}: {} ({})", e.message, e.code));
}
Ok(r.result.unwrap_or(Value::Null))
}
pub fn fleet_call(method: &str, params: Value, from: &str, ctx: &Ctx) -> (Answer, Option<After>) {
match fleet_call_inner(method, params, from, ctx) {
Ok((value, after)) => (Ok(value), after),
Err(e) => (Err(e), None),
}
}
fn fleet_call_inner(method: &str, params: Value, from: &str, ctx: &Ctx) -> Result<(Value, Option<After>), ApiError> {
let ok = json!({ "ok": true });
match method {
"fleet.leave" => {
drop_all(ctx)?;
Ok((ok, Some(After::Left)))
}
"fleet.forget" => {
let p: NameParams = parse(params)?;
let (me, _) = api::own_member(ctx)?;
if p.name == me || p.name == from {
return Err(ApiError::invalid(format!("`fleet.forget` of `{}`: that's this host or its control plane", p.name)));
}
unregister(ctx, &p.name)?;
apply(After::Unlinked(p.name), ctx);
Ok((ok, None))
}
"fleet.rm" => {
let p: NameParams = parse(params)?;
let (me, control_plane) = api::own_member(ctx)?;
let machines: Vec<String> = api::machines(ctx)?.into_iter().map(|e| e.name).collect();
let stored = membership_api::load(member_toml(ctx)?)?;
let in_log = in_log(stored.as_ref(), &p.name);
let here = Here { name: &me, control_plane: &control_plane, machines: &machines, routed: false, authority: Authority::None, in_log };
let Plan::Remove { name, tell } = plan(&here, &p.name, Some(from))? else {
return Err(ApiError::denied("`fleet.rm` removes another member"));
};
let (removed, after) = remove(ctx, &me, &name, tell, &machines)?;
let value = serde_json::to_value(removed).map_err(|e| ApiError::internal(e.into()))?;
if tell {
apply(after, ctx);
Ok((value, None))
} else {
Ok((value, Some(after)))
}
}
"fleet.propose" | "fleet.sync" => changes::fleet_call(method, params, from, ctx),
m => Err(ApiError::unknown_method(m)),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn names(n: &[&str]) -> Vec<String> {
n.iter().map(|s| s.to_string()).collect()
}
fn plan_on(control_plane: ControlPlane, machines: &[&str], seen: bool, authority: Authority, in_log: bool, name: &str, from: Option<&str>) -> Result<Plan, ApiError> {
let machines = names(machines);
plan(&Here { name: "lap", control_plane: &control_plane, machines: &machines, routed: seen, authority, in_log }, name, from)
}
fn run(control_plane: ControlPlane, machines: &[&str], seen: bool, name: &str, from: Option<&str>) -> Result<Plan, ApiError> {
plan_on(control_plane, machines, seen, Authority::This, false, name, from)
}
fn code(r: Result<Plan, ApiError>) -> (&'static str, String) {
let e = r.unwrap_err();
(e.code, e.message)
}
#[test]
fn the_authority_revokes() {
assert_eq!(run(ControlPlane::This, &["box"], false, "box", None), Ok(Plan::Revoke { name: "box".into() }));
assert_eq!(plan_on(ControlPlane::This, &[], false, Authority::This, true, "pi", None), Ok(Plan::Revoke { name: "pi".into() }));
assert_eq!(run(ControlPlane::Other("k".into()), &["k", "box"], false, "box", None), Ok(Plan::Revoke { name: "box".into() }));
assert_eq!(code(run(ControlPlane::This, &["box"], false, "nope", None)).0, "not-found");
assert_eq!(
code(run(ControlPlane::Other("k".into()), &["k"], false, "k", None)),
("denied", "`k` is the control plane: move the role first (`devsandbox machine control-plane <m>`)".into())
);
}
#[test]
fn the_control_plane_removes_on_fleet_rm() {
assert_eq!(run(ControlPlane::This, &["box", "x"], false, "box", Some("x")), Ok(Plan::Remove { name: "box".into(), tell: true }));
assert_eq!(run(ControlPlane::This, &["box"], false, "box", Some("box")), Ok(Plan::Remove { name: "box".into(), tell: false }));
assert_eq!(
plan_on(ControlPlane::This, &[], false, Authority::None, true, "pi", Some("x")),
Ok(Plan::Remove { name: "pi".into(), tell: true }),
"in the log only"
);
assert_eq!(code(run(ControlPlane::This, &["box"], false, "nope", Some("x"))).0, "not-found");
assert_eq!(code(run(ControlPlane::This, &["box"], false, "lap", Some("box"))), ("denied", "`lap` is the control plane: it leaves on its own host".into()));
assert_eq!(code(run(ControlPlane::Other("k".into()), &["k", "box"], false, "box", Some("k"))).0, "denied", "`fleet.rm` on a member");
}
#[test]
fn a_member_proposes_to_the_authority() {
let k = || ControlPlane::Other("k".into());
let a = Authority::Other("auth");
let propose = Ok(Plan::Propose { authority: "auth".into() });
assert_eq!(plan_on(k(), &["k", "box"], false, a, false, "box", None), propose);
assert_eq!(plan_on(k(), &["k"], true, a, false, "x", None), propose, "seen through the control plane");
assert_eq!(plan_on(k(), &["k"], false, a, true, "x", None), propose, "in the log");
assert_eq!(code(plan_on(k(), &["k"], false, a, false, "x", None)).0, "not-found");
assert_eq!(code(plan_on(k(), &["k", "auth"], false, a, true, "auth", None)), ("denied", "`auth` is the fleet's authority: it can't be removed".into()));
assert_eq!(code(plan_on(k(), &["k"], false, a, true, "k", None)).0, "denied", "the control plane");
assert_eq!(code(plan_on(k(), &["k", "box"], false, Authority::None, false, "box", None)).0, "failed");
}
#[test]
fn leaving() {
assert_eq!(run(ControlPlane::Other("k".into()), &["k", "box"], false, "lap", None), Ok(Plan::Leave { control_plane: Some("k".into()) }));
assert_eq!(plan_on(ControlPlane::Other("k".into()), &["k"], false, Authority::Other("k"), true, "lap", None), Ok(Plan::Leave { control_plane: Some("k".into()) }));
assert_eq!(run(ControlPlane::This, &[], false, "lap", None), Ok(Plan::Leave { control_plane: None }));
assert_eq!(code(run(ControlPlane::This, &["box"], false, "lap", None)), ("denied", CONTROL_PLANE_HAS_MEMBERS.into()));
assert_eq!(code(run(ControlPlane::None, &[], false, "lap", None)), ("failed", "this host is in no fleet".into()));
}
#[test]
fn the_control_plane_forgets_on_direct_and_routed_members() {
assert_eq!(forget_targets(&names(&["box", "x"]), &names(&["lap", "x", "pi"]), "b", "pi"), names(&["box", "x", "lap"]));
assert_eq!(forget_targets(&[], &names(&["b", "lap"]), "b", "zed"), names(&["lap"]), "never the control plane itself");
}
#[test]
fn in_no_fleet() {
let (c, m) = code(run(ControlPlane::None, &["box"], false, "box", None));
assert_eq!((c, m.as_str()), ("failed", "this host is in no fleet: `devsandbox machine unlink box` drops its link"));
assert_eq!(code(run(ControlPlane::None, &[], false, "box", None)).0, "not-found");
}
}