use std::collections::{BTreeMap, VecDeque};
use std::net::Shutdown;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread::JoinHandle;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde_json::{Value, json};
use super::inbound::Neighbors;
use super::link::{self, Link};
use super::{Entry, Kind};
use super::saved;
use super::ssh::{Dial, Duplex, RouteDial};
use crate::serve::api::ApiError;
use crate::serve::endpoint::Stream;
use crate::serve::proto::Response;
use crate::serve::snapshots::{self, LinkState, Remotes};
#[derive(Debug, Clone, Copy)]
pub struct Timing {
pub backoff: Duration,
pub backoff_cap: Duration,
pub call: Duration,
pub handshake: Duration,
pub tick: Duration,
}
impl Default for Timing {
fn default() -> Self {
Self {
backoff: Duration::from_secs(1),
backoff_cap: Duration::from_secs(30),
call: Duration::from_secs(15),
handshake: Duration::from_secs(20),
tick: Duration::from_millis(100),
}
}
}
pub struct Hooks {
pub watching: Box<dyn Fn() -> bool + Send + Sync>,
pub changed: Box<dyn Fn() + Send + Sync>,
pub hub: Box<dyn Fn() -> Option<HubOf> + Send + Sync>,
pub routed: Box<dyn Fn() -> Vec<(String, Result<String, String>)> + Send + Sync>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HubOf {
pub hub: String,
pub me: String,
}
pub type Hold = Arc<dyn Fn(&Entry, &Held) -> String + Send + Sync>;
pub struct Hub {
pub remotes: PathBuf,
pub is_hub: Arc<dyn Fn() -> bool + Send + Sync>,
}
pub struct Machines {
inner: Arc<Inner>,
saver: Option<JoinHandle<()>>,
}
struct HubSave {
path: PathBuf,
is_hub: Arc<dyn Fn() -> bool + Send + Sync>,
state: Mutex<SaveState>,
cv: Condvar,
}
#[derive(Default)]
struct SaveState {
dirty: bool,
stop: bool,
}
#[derive(Clone)]
pub struct Handle {
inner: Arc<Inner>,
}
struct Inner {
registry: PathBuf,
inbound: Arc<Neighbors>,
reloading: Mutex<()>,
dial: Dial,
route: RouteDial,
hold: Hold,
timing: Timing,
hooks: Hooks,
log: fn(&str),
remotes: Arc<Remotes>,
links: Mutex<BTreeMap<String, LinkThread>>,
stopped: AtomicBool,
hub: Option<HubSave>,
}
struct LinkThread {
entry: Entry,
tx: Sender<Cmd>,
ctl: Arc<Ctl>,
thread: Option<JoinHandle<()>>,
carrier: Option<JoinHandle<()>>,
}
fn carried(entry: &Entry) -> bool {
matches!(entry.kind, Kind::Ssh { .. })
}
#[derive(Default)]
struct Ctl {
stop: AtomicBool,
cycled: AtomicBool,
stream: Mutex<Option<Stream>>,
carrier: Mutex<Carrier>,
carrier_cv: Condvar,
}
#[derive(Default)]
struct Carrier {
up: bool,
generation: u64,
why: Option<String>,
stream: Option<Stream>,
}
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
impl Ctl {
fn stopped(&self) -> bool {
self.stop.load(Ordering::SeqCst)
}
fn cut(&self) {
self.stop.store(true, Ordering::SeqCst);
if let Some(s) = lock(&self.stream).as_ref() {
let _ = s.shutdown(Shutdown::Both);
}
if let Some(s) = lock(&self.carrier).stream.as_ref() {
let _ = s.shutdown(Shutdown::Both);
}
self.carrier_cv.notify_all();
}
fn hold(&self, stream: Option<Stream>) {
*lock(&self.stream) = stream;
}
fn cycle(&self) {
self.cycled.store(true, Ordering::SeqCst);
if let Some(s) = lock(&self.carrier).stream.as_ref() {
let _ = s.shutdown(Shutdown::Both);
}
self.carrier_cv.notify_all();
}
fn sleep(&self, wait: Duration) {
let c = lock(&self.carrier);
let _ = self.carrier_cv.wait_timeout_while(c, wait, |_| !self.stopped() && !self.cycled.load(Ordering::SeqCst));
}
}
pub struct Held<'a> {
ctl: &'a Ctl,
tx: &'a Sender<Cmd>,
came_up: AtomicBool,
}
impl Held<'_> {
pub fn stopped(&self) -> bool {
self.ctl.stopped()
}
pub fn hold(&self, stream: Option<Stream>) -> bool {
let mut c = lock(&self.ctl.carrier);
if self.ctl.stopped() {
return false;
}
c.stream = stream;
true
}
pub fn up(&self) {
self.came_up.store(true, Ordering::SeqCst);
self.set(true, None);
}
pub fn note(&self, why: String) {
self.set(false, Some(why));
}
fn set(&self, up: bool, why: Option<String>) {
{
let mut c = lock(&self.ctl.carrier);
if up && !c.up {
c.generation += 1;
}
c.up = up;
if why.is_some() || up {
c.why = why;
}
}
let _ = self.tx.send(Cmd::Wake);
}
}
enum Cmd {
Call(Call),
Wake,
Roots(Vec<PathBuf>),
}
struct Call {
method: String,
params: Value,
reply: Sender<Response>,
}
impl Machines {
#[allow(clippy::too_many_arguments)]
pub fn spawn(
registry: PathBuf,
inbound: Arc<Neighbors>,
dial: Dial,
route: RouteDial,
hold: Hold,
timing: Timing,
hooks: Hooks,
hub: Option<Hub>,
log: fn(&str),
) -> Machines {
let hub = hub.map(|h| HubSave { path: h.remotes, is_hub: h.is_hub, state: Mutex::default(), cv: Condvar::new() });
let inner = Arc::new(Inner {
registry,
inbound,
reloading: Mutex::new(()),
dial,
route,
hold,
timing,
hooks,
log,
remotes: Arc::default(),
links: Mutex::new(BTreeMap::new()),
stopped: AtomicBool::new(false),
hub,
});
let saver = inner.hub.as_ref().and_then(|h| {
if (h.is_hub)() {
match saved::load(&h.path) {
Ok(s) => inner.remotes.restore(saved::machines(s)),
Err(e) => log(&format!("machines: {e:#}")),
}
}
let inner = Arc::clone(&inner);
std::thread::Builder::new()
.name("serve-remotes".into())
.spawn(move || save_loop(&inner))
.map_err(|e| log(&format!("cannot start saving remotes.json: {e}")))
.ok()
});
let weak = Arc::downgrade(&inner);
inner.inbound.on_change(Arc::new(move || {
if let Some(inner) = weak.upgrade() {
Handle { inner }.reload();
}
}));
let machines = Machines { inner, saver };
machines.handle().reload();
machines
}
pub fn handle(&self) -> Handle {
Handle { inner: Arc::clone(&self.inner) }
}
}
impl Drop for Machines {
fn drop(&mut self) {
self.inner.stopped.store(true, Ordering::SeqCst);
let links = std::mem::take(&mut *self.inner.lock_links());
stop_all(links.into_values().collect());
if let Some(hub) = &self.inner.hub {
lock(&hub.state).stop = true;
hub.cv.notify_all();
}
if let Some(saver) = self.saver.take() {
let _ = saver.join();
}
}
}
fn now_unix() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
}
fn save_loop(inner: &Inner) {
let Some(hub) = &inner.hub else { return };
let mut last: Option<Instant> = None;
loop {
{
let mut s = lock(&hub.state);
while !s.dirty && !s.stop {
s = hub.cv.wait(s).unwrap_or_else(|e| e.into_inner());
}
if !s.dirty {
return;
}
let wait = saved::save_wait(last, Instant::now());
if !wait.is_zero() && !s.stop {
drop(hub.cv.wait_timeout(s, wait));
continue;
}
s.dirty = false;
}
if !(hub.is_hub)() {
continue;
}
if let Err(e) = saved::save(&hub.path, &saved::of(&inner.remotes.all(), now_unix())) {
(inner.log)(&format!("machines: cannot save remotes: {e:#}"));
}
last = Some(Instant::now());
}
}
fn stop_all(links: Vec<LinkThread>) {
for l in &links {
l.ctl.cut();
let _ = l.tx.send(Cmd::Wake);
}
for mut l in links {
for t in [l.thread.take(), l.carrier.take()].into_iter().flatten() {
let _ = t.join();
}
}
}
impl Inner {
fn lock_links(&self) -> MutexGuard<'_, BTreeMap<String, LinkThread>> {
lock(&self.links)
}
fn rows_changed(&self) {
if let Some(hub) = &self.hub {
lock(&hub.state).dirty = true;
hub.cv.notify_all();
}
}
}
fn same_but_roots(a: &Entry, b: &Entry) -> bool {
*a == Entry { roots: a.roots.clone(), ..b.clone() }
}
fn with_inbound(mut entries: Vec<Entry>, inbound: &Neighbors) -> Vec<Entry> {
for n in inbound.list() {
if !entries.iter().any(|e| e.name == n.name) {
entries.push(Entry::inbound(n.name, n.roots));
}
}
entries.sort_by(|a, b| a.name.cmp(&b.name));
entries
}
impl Handle {
pub fn reload(&self) {
let inner = &self.inner;
let _one = lock(&inner.reloading);
let entries = match super::load(&inner.registry) {
Ok(entries) => with_inbound(entries, &inner.inbound),
Err(e) => {
(inner.log)(&format!("machines: {e:#}"));
return;
}
};
let mut moved = Vec::new();
let gone: Vec<LinkThread> = {
let mut links = inner.lock_links();
let mut stale = Vec::new();
for (name, l) in links.iter_mut() {
match entries.iter().find(|e| e.name == *name) {
Some(e) if *e == l.entry => {}
Some(e) if same_but_roots(e, &l.entry) => {
l.entry.roots.clone_from(&e.roots);
moved.push(name.clone());
}
_ => stale.push(name.clone()),
}
}
stale.iter().filter_map(|name| links.remove(name)).collect()
};
stop_all(gone);
let mut links = inner.lock_links();
if inner.stopped.load(Ordering::SeqCst) {
return;
}
inner.remotes.sync(&entries);
inner.rows_changed();
for name in &moved {
if let Some(l) = links.get(name) {
let _ = l.tx.send(Cmd::Roots(l.entry.roots.clone()));
}
}
for e in &entries {
if !links.contains_key(&e.name) {
let link = spawn_link(e.clone(), Arc::clone(inner));
links.insert(e.name.clone(), link);
}
}
drop(links);
(inner.hooks.changed)();
}
pub fn cycle(&self) {
for l in self.inner.lock_links().values() {
if carried(&l.entry) {
l.ctl.cycle();
}
}
}
pub fn wake(&self) {
for l in self.inner.lock_links().values() {
let _ = l.tx.send(Cmd::Wake);
}
}
pub fn entries(&self) -> Vec<Entry> {
self.inner.lock_links().values().map(|l| l.entry.clone()).collect()
}
pub fn remotes(&self) -> &Arc<Remotes> {
&self.inner.remotes
}
pub fn unknown(&self, machine: &str) -> ApiError {
ApiError::not_found(format!("no machine named `{machine}`"))
}
pub fn routed(&self) -> Vec<snapshots::Routed> {
self.inner.remotes.routed((self.inner.hooks.routed)())
}
pub fn routed_one(&self, name: &str) -> Option<snapshots::Routed> {
if self.inner.lock_links().contains_key(name) {
return None;
}
self.routed().into_iter().find(|r| r.name == name)
}
pub fn dial(&self, machine: &str) -> Option<anyhow::Result<Duplex>> {
let entry = self.inner.lock_links().get(machine).map(|l| l.entry.clone());
match entry {
Some(entry) => Some((self.inner.dial)(&entry)),
None => self.routed_one(machine).map(|_| (self.inner.route)(machine)),
}
}
pub fn forward(&self, machine: &str, method: &str, params: Value) -> Result<Response, ApiError> {
let tx = self.inner.lock_links().get(machine).map(|l| l.tx.clone());
let tx = match tx {
Some(tx) => tx,
None if self.routed_one(machine).is_some() => return self.call_routed(machine, method, params),
None => return Err(self.unknown(machine)),
};
let (reply, rx) = mpsc::channel();
let stopping = || ApiError::internal(anyhow::anyhow!("{machine}: the link is stopping"));
tx.send(Cmd::Call(Call { method: method.into(), params, reply })).map_err(|_| stopping())?;
let t = &self.inner.timing;
let bound = t.handshake * 2 + t.call + t.backoff_cap + Duration::from_secs(5);
rx.recv_timeout(bound).map_err(|e| match e {
RecvTimeoutError::Timeout => ApiError::internal(anyhow::anyhow!("{machine}: no answer")),
RecvTimeoutError::Disconnected => stopping(),
})
}
fn direct_up(&self, machine: &str) -> Result<(), String> {
match self.inner.remotes.get(machine) {
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 route_worth(&self, machine: &str, direct: &str) -> Result<(), String> {
if self.inner.lock_links().contains_key(machine) {
return Ok(());
}
match self.routed_one(machine) {
Some(r) if r.state == LinkState::Connected => Ok(()),
Some(r) => Err(format!("{direct}, and {}", r.error.unwrap_or_else(|| "no route to it is up".into()))),
None => Err(format!("{direct}, and no path to it in this host's link graph")),
}
}
pub fn open_member(&self, machine: &str) -> Result<Duplex, String> {
let direct = match self.direct_up(machine) {
Ok(()) => {
let entry = self.inner.lock_links().get(machine).map(|l| l.entry.clone());
if let Some(entry) = entry {
return (self.inner.dial)(&entry).map_err(|e| format!("{e:#}"));
}
"no link to it".to_string()
}
Err(why) => why,
};
self.route_worth(machine, &direct)?;
(self.inner.route)(machine).map_err(|e| format!("{direct}; over a route: {e:#}"))
}
pub fn call_member(&self, machine: &str, method: &str, params: Value) -> Result<Response, String> {
match self.direct_up(machine) {
Ok(()) => self.forward(machine, method, params).map_err(|e| e.message),
Err(direct) => {
self.route_worth(machine, &direct)?;
self.call_routed(machine, method, params).map_err(|e| format!("{direct}; over a route: {}", e.message))
}
}
}
fn call_routed(&self, machine: &str, method: &str, params: Value) -> Result<Response, ApiError> {
let t = &self.inner.timing;
let duplex = (self.inner.route)(machine).map_err(|e| ApiError::failed(format!("{machine}: unreachable: {e:#}")))?;
let mut link = link::handshake(machine, duplex, t.handshake, link::Over::Link).map_err(|e| ApiError::failed(e.to_string()))?;
match link.conn.call_within(method, params, t.call) {
Ok(Some(r)) => Ok(r),
Ok(None) => Err(ApiError::internal(anyhow::anyhow!("{machine}: timed out"))),
Err(e) => Err(ApiError::failed(format!("{machine}: {e:#}"))),
}
}
}
fn spawn_link(entry: Entry, inner: Arc<Inner>) -> LinkThread {
let (tx, rx) = mpsc::channel();
let ctl = Arc::new(Ctl::default());
let log = inner.log;
let thread = {
let (entry, ctl, inner) = (entry.clone(), Arc::clone(&ctl), Arc::clone(&inner));
std::thread::Builder::new()
.name(format!("serve-machine-{}", entry.name))
.spawn(move || LinkLoop::new(entry, &inner, &ctl).run(&rx))
};
let thread = thread.map_err(|e| log(&format!("cannot start machine {}'s link: {e}", entry.name))).ok();
let carrier = carried(&entry).then(|| {
let (entry, ctl, tx) = (entry.clone(), Arc::clone(&ctl), tx.clone());
std::thread::Builder::new()
.name(format!("serve-machine-{}-link", entry.name))
.spawn(move || carry(&entry, &inner, &ctl, &tx))
});
let carrier = carrier.and_then(|c| c.map_err(|e| log(&format!("cannot start machine {}'s carrier: {e}", entry.name))).ok());
LinkThread { entry, tx, ctl, thread, carrier }
}
pub(crate) fn backoff(t: &Timing, failures: &mut u32) -> Duration {
let delay = t.backoff.saturating_mul(1u32 << (*failures).min(16)).min(t.backoff_cap);
*failures = failures.saturating_add(1);
delay
}
fn carry(entry: &Entry, inner: &Inner, ctl: &Ctl, tx: &Sender<Cmd>) {
let mut failures = 0;
let mut logged = None;
while !ctl.stopped() {
ctl.cycled.store(false, Ordering::SeqCst);
let held = Held { ctl, tx, came_up: AtomicBool::new(false) };
let mut why = (inner.hold)(entry, &held);
let cycled = ctl.cycled.swap(false, Ordering::SeqCst);
if cycled {
why = "this host's hub changed: redialing".into();
}
{
let mut c = lock(&ctl.carrier);
c.up = false;
c.why = Some(why.clone());
c.stream = None;
}
let _ = tx.send(Cmd::Wake);
if ctl.stopped() {
break;
}
if held.came_up.load(Ordering::SeqCst) {
failures = 0;
logged = None;
}
if cycled {
continue;
}
if log_failure(&mut logged, &why) {
(inner.log)(&format!("machine {}: {why}", entry.name));
}
ctl.sleep(backoff(&inner.timing, &mut failures));
}
}
enum End {
Stopped,
Lost(String),
}
struct LinkLoop<'a> {
entry: Entry,
inner: &'a Inner,
ctl: &'a Ctl,
pending: VecDeque<Call>,
failures: u32,
logged: Option<String>,
generation: u64,
}
impl<'a> LinkLoop<'a> {
fn new(entry: Entry, inner: &'a Inner, ctl: &'a Ctl) -> Self {
Self { entry, inner, ctl, pending: VecDeque::new(), failures: 0, logged: None, generation: 0 }
}
fn run(&mut self, rx: &Receiver<Cmd>) {
let tick = self.inner.timing.tick;
while !self.ctl.stopped() {
if let Some(why) = self.carrier_down() {
match why {
Some(why) => {
self.set(LinkState::Unreachable, Some(why.clone()));
self.fail_pending(&why);
}
None => self.set(LinkState::Connecting, None),
}
if !self.recv(rx, tick) {
break;
}
continue;
}
self.set(LinkState::Connecting, None);
let failed = match self.connect() {
Ok(mut link) => {
self.failures = 0;
self.logged = None;
let remote = link.remote().version.clone();
self.inner.remotes.update(&self.entry.name, |m| m.version = Some(remote));
self.inner.rows_changed();
self.set(LinkState::Connected, None);
let end = self.serve(&mut link, rx);
self.ctl.hold(None);
drop(link);
match end {
End::Stopped => break,
End::Lost(why) => why,
}
}
Err(why) => why,
};
if self.ctl.stopped() {
break;
}
if self.carrier_moved() {
continue;
}
if log_failure(&mut self.logged, &failed) {
(self.inner.log)(&format!("machine {}: {failed}", self.entry.name));
}
self.set(LinkState::Unreachable, Some(failed.clone()));
self.fail_pending(&failed);
let delay = self.backoff();
let until = Instant::now() + delay;
while self.pending.is_empty() && !self.ctl.stopped() && !self.carrier_moved() {
let left = until.saturating_duration_since(Instant::now());
if left.is_zero() || !self.recv(rx, left.min(tick)) {
break;
}
}
}
for call in self.pending.drain(..) {
let _ = call.reply.send(Response::err(None, "internal", format!("{}: the link is stopping", self.entry.name)));
}
self.ctl.hold(None);
}
fn carrier_down(&mut self) -> Option<Option<String>> {
if !carried(&self.entry) {
return None;
}
let c = lock(&self.ctl.carrier);
if !c.up {
return Some(c.why.clone());
}
if c.generation != self.generation {
self.generation = c.generation;
self.failures = 0;
self.logged = None;
}
None
}
fn carrier_moved(&self) -> bool {
if !carried(&self.entry) {
return false;
}
let c = lock(&self.ctl.carrier);
!c.up || c.generation != self.generation
}
fn fail_pending(&mut self, why: &str) {
for call in self.pending.drain(..) {
let _ = call.reply.send(Response::err(None, "failed", format!("{}: unreachable: {why}", self.entry.name)));
}
}
fn backoff(&mut self) -> Duration {
backoff(&self.inner.timing, &mut self.failures)
}
fn recv(&mut self, rx: &Receiver<Cmd>, wait: Duration) -> bool {
match rx.recv_timeout(wait) {
Ok(Cmd::Call(call)) => self.pending.push_back(call),
Ok(Cmd::Roots(roots)) => self.entry.roots = roots,
Ok(Cmd::Wake) | Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => return false,
}
true
}
fn set(&self, state: LinkState, error: Option<String>) {
let mut moved = false;
self.inner.remotes.update(&self.entry.name, |m| moved = m.set_link(state, error));
if moved {
(self.inner.hooks.changed)();
}
}
fn connect(&self) -> Result<Link, String> {
let duplex = (self.inner.dial)(&self.entry).map_err(|e| format!("{}: {e:#}", self.entry.name))?;
self.ctl.hold(duplex.stream.try_clone().ok());
if self.ctl.stopped() {
return Err("stopping".into());
}
link::handshake(&self.entry.name, duplex, self.inner.timing.handshake, link::Over::Link).map_err(|e| e.to_string())
}
fn serve(&mut self, link: &mut Link, rx: &Receiver<Cmd>) -> End {
let name = self.entry.name.clone();
let t = self.inner.timing;
if let Err(why) = self.quick(link, "subscribe", json!({ "topics": ["instances"] })) {
return End::Lost(why);
}
let mut watched = Watched::default();
loop {
if self.ctl.stopped() {
return End::Stopped;
}
if self.carrier_moved() {
return End::Lost(format!("{name}: its link went down"));
}
loop {
match rx.try_recv() {
Ok(Cmd::Call(call)) => self.pending.push_back(call),
Ok(Cmd::Roots(roots)) => self.entry.roots = roots,
Ok(Cmd::Wake) => {}
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => return End::Stopped,
}
}
let roots = (self.inner.hooks.watching)();
let hub = (self.inner.hooks.hub)().filter(|h| h.hub == name);
if hub.is_none() {
self.drop_fleet();
}
let want = Want { roots, fleet: roots && hub.is_some() };
if want != watched.asked || (want.roots && watched.roots != self.entry.roots) {
if let Err(why) = self.watch(link, &mut watched, want) {
return End::Lost(why);
}
}
if let Some(call) = self.pending.pop_front() {
let answer = link.conn.call_within(&call.method, call.params, t.call);
match answer {
Ok(Some(r)) => {
let _ = call.reply.send(r);
}
Ok(None) => {
let _ = call.reply.send(Response::err(None, "internal", format!("{name}: timed out")));
return End::Lost(format!("{name}: `{}` timed out", call.method));
}
Err(e) => {
let _ = call.reply.send(Response::err(None, "failed", format!("{name}: {e:#}")));
return End::Lost(format!("{name}: {e:#}"));
}
}
continue;
}
match link.conn.next_notification(t.tick) {
Ok(Some(n)) if n.method == "instances.snapshot" => self.store(n.params, watched.fleet.as_deref()),
Ok(Some(n)) if n.method == "closing" => {
let reason = n.params.get("reason").and_then(Value::as_str).unwrap_or("closing");
return End::Lost(format!("{name}: its devsandbox serve is exiting ({reason})"));
}
Ok(_) => {}
Err(e) => return End::Lost(format!("{name}: {e:#}")),
}
}
}
fn watch(&self, link: &mut Link, watched: &mut Watched, want: Want) -> Result<(), String> {
let name = &self.entry.name;
let t = self.inner.timing;
let call = |link: &mut Link, method: &str, params: Value| {
link.conn
.call_within(method, params, t.call)
.map_err(|e| format!("{name}: {e:#}"))?
.ok_or_else(|| format!("{name}: `{method}` timed out"))
};
for root in std::mem::take(&mut watched.roots) {
call(link, "instances.unwatch", json!({ "dir": root }))?;
}
if let Some(dir) = watched.fleet.take() {
call(link, "instances.unwatch", json!({ "dir": dir }))?;
}
watched.asked = want;
let mut refused = Vec::new();
if want.fleet {
let r = call(link, "roots.list", json!({}))?;
let rows: Option<Vec<crate::serve::api::RootCandidate>> = r.result.and_then(|v| serde_json::from_value(v).ok());
match rows.as_deref().and_then(crate::serve::fleet::placed::fleet_root) {
Some(dir) => {
let r = call(link, "instances.watch", json!({ "dir": dir, "machines": true }))?;
match r.error {
Some(e) => refused.push(format!("the fleet through it: {}", e.message)),
None => watched.fleet = Some(dir),
}
}
None => refused.push("the fleet through it: it lists no fleet root for this host".to_string()),
}
}
if want.roots {
watched.roots.clone_from(&self.entry.roots);
for root in &self.entry.roots {
if watched.fleet.as_ref() == Some(root) {
continue;
}
let r = call(link, "instances.watch", json!({ "dir": root }))?;
if let Some(e) = r.error {
refused.push(format!("{}: {}", root.display(), e.message));
}
}
}
let error = (!refused.is_empty()).then(|| refused.join("; "));
self.set(LinkState::Connected, error);
Ok(())
}
fn drop_fleet(&self) {
let mut had = false;
self.inner.remotes.update(&self.entry.name, |m| had = m.fleet.take().is_some());
if had {
(self.inner.hooks.changed)();
}
}
fn quick(&self, link: &mut Link, method: &str, params: Value) -> Result<(), String> {
let name = &self.entry.name;
match link.conn.call_within(method, params, self.inner.timing.call) {
Ok(Some(r)) => match r.error {
Some(e) => Err(format!("{name}: {method}: {} ({})", e.message, e.code)),
None => Ok(()),
},
Ok(None) => Err(format!("{name}: `{method}` timed out")),
Err(e) => Err(format!("{name}: {e:#}")),
}
}
fn store(&self, mut params: Value, fleet: Option<&std::path::Path>) {
let Some(dir) = params.get("dir").and_then(Value::as_str).map(PathBuf::from) else { return };
if fleet == Some(dir.as_path()) {
let me = (self.inner.hooks.hub)().map(|h| h.me);
let view = Arc::new(snapshots::fleet_view(&mut params, me.as_deref()));
self.inner.remotes.update(&self.entry.name, |m| m.fleet = Some(view));
if !self.entry.roots.contains(&dir) {
(self.inner.hooks.changed)();
return;
}
}
if !self.entry.roots.contains(&dir) {
return;
}
let mut stored = false;
self.inner.remotes.update(&self.entry.name, |m| {
if !m.roots.contains(&dir) {
return;
}
if let Some(prev) = m.rows.get(&dir) {
snapshots::carry_remote_status(prev, &mut params);
}
m.rows.insert(dir, Arc::new(params));
m.seen = Some(now_unix());
stored = true;
});
if !stored {
return;
}
self.inner.rows_changed();
(self.inner.hooks.changed)();
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct Want {
roots: bool,
fleet: bool,
}
#[derive(Debug, Default)]
struct Watched {
asked: Want,
fleet: Option<PathBuf>,
roots: Vec<PathBuf>,
}
fn log_failure(logged: &mut Option<String>, failed: &str) -> bool {
if logged.as_deref() == Some(failed) {
return false;
}
*logged = Some(failed.to_string());
true
}
#[cfg(test)]
mod tests {
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
use std::path::Path;
use std::sync::atomic::AtomicUsize;
use super::*;
use crate::serve::daemon::tests::opts;
use crate::serve::machines::inbound;
use crate::serve::machines::ssh::Duplex;
use crate::serve::snapshots::Machine;
fn mute_peer() -> Duplex {
let (ours, theirs) = UnixStream::pair().unwrap();
std::thread::spawn(move || {
let mut r = BufReader::new(theirs.try_clone().unwrap());
let mut line = String::new();
while r.read_line(&mut line).is_ok_and(|n| n > 0) {
let req: Value = serde_json::from_str(&line).unwrap();
let answer = match req["method"].as_str() {
Some("hello") => json!({"id": req["id"], "result": {"version": "0.6.0", "build": 1, "protocol": 1}}),
Some("subscribe") => json!({"id": req["id"], "result": {"ok": true}}),
_ => Value::Null,
};
if !answer.is_null() && writeln!(&theirs, "{answer}").is_err() {
break;
}
line.clear();
}
});
Duplex::socket(ours)
}
fn short_scratch(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("dsv-ms-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn wait_for(what: &str, within: Duration, mut cond: impl FnMut() -> bool) {
let deadline = Instant::now() + within;
while !cond() {
assert!(Instant::now() < deadline, "timed out waiting: {what}");
std::thread::sleep(Duration::from_millis(10));
}
}
fn fake_hold(up: &Arc<AtomicBool>, runs: &Arc<Mutex<Vec<String>>>) -> Hold {
let (up, runs) = (Arc::clone(up), Arc::clone(runs));
Arc::new(move |e: &Entry, held: &Held| {
runs.lock().unwrap().push(e.name.clone());
if !up.load(Ordering::SeqCst) {
return "ssh: no route".into();
}
held.up();
while !held.stopped() && up.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(5));
}
"link closed".into()
})
}
fn ran(runs: &Mutex<Vec<String>>, name: &str) -> usize {
runs.lock().unwrap().iter().filter(|n| *n == name).count()
}
fn no_hooks() -> Hooks {
Hooks { watching: Box::new(|| false), changed: Box::new(|| {}), hub: Box::new(|| None), routed: Box::new(Vec::new) }
}
fn no_route() -> RouteDial {
Arc::new(|name: &str| anyhow::bail!("no route to `{name}`"))
}
fn counting_dial(dials: &Arc<AtomicUsize>) -> Dial {
let dials = Arc::clone(dials);
Arc::new(move |_| {
dials.fetch_add(1, Ordering::SeqCst);
Ok(mute_peer())
})
}
#[test]
fn a_timed_out_call_drops_the_link() {
let base = short_scratch("link-timeout");
let registry = base.join("machines.toml");
crate::serve::machines::update(®istry, |e| e.push(Entry::ssh("m", "m"))).unwrap();
let dials = Arc::new(AtomicUsize::new(0));
let (up, runs) = (Arc::new(AtomicBool::new(true)), Arc::default());
let timing = Timing { call: Duration::from_millis(200), ..opts(1, 0).machine_timing };
let machines = Machines::spawn(registry, Arc::default(), counting_dial(&dials), no_route(), fake_hold(&up, &runs), timing, no_hooks(), None, |_| {});
let h = machines.handle();
for round in 1..=2 {
let r = h.forward("m", "instances.list", json!({"dir": "/x"})).unwrap();
let e = r.error.unwrap();
assert_eq!((e.code.as_str(), e.message.as_str()), ("internal", "m: timed out"));
assert_eq!(dials.load(Ordering::SeqCst), round);
}
assert_eq!(ran(&runs, "m"), 1, "the carrier stayed up");
assert_eq!(h.forward("n", "instances.list", json!({})).unwrap_err().code, "not-found");
let started = Instant::now();
drop(machines);
assert!(started.elapsed() < Duration::from_secs(2), "the stop waited");
assert!(h.forward("m", "instances.list", json!({})).is_err(), "stopped");
let _ = std::fs::remove_dir_all(&base);
}
static LOGGED: Mutex<Vec<String>> = Mutex::new(Vec::new());
#[test]
fn a_machine_follows_its_carrier() {
let base = short_scratch("carrier");
let registry = base.join("machines.toml");
crate::serve::machines::update(®istry, |e| e.push(Entry::ssh("c", "me@c"))).unwrap();
let dials = Arc::new(AtomicUsize::new(0));
let (up, runs) = (Arc::new(AtomicBool::new(false)), Arc::default());
let timing = opts(1, 0).machine_timing;
let log = |line: &str| LOGGED.lock().unwrap().push(line.into());
let machines = Machines::spawn(registry, Arc::default(), counting_dial(&dials), no_route(), fake_hold(&up, &runs), timing, no_hooks(), None, log);
let h = machines.handle();
let state = || h.remotes().get("c").unwrap();
wait_for("the carrier retried", Duration::from_secs(5), || ran(&runs, "c") >= 3);
let s = state();
assert_eq!((s.state, s.error.as_deref()), (LinkState::Unreachable, Some("ssh: no route")));
let logged: Vec<_> = LOGGED.lock().unwrap().iter().filter(|l| l.starts_with("machine c: ")).cloned().collect();
assert_eq!(logged, ["machine c: ssh: no route"], "one line for one way of failing");
let started = Instant::now();
let e = h.forward("c", "instances.list", json!({})).unwrap().error.unwrap();
assert_eq!((e.code.as_str(), e.message.as_str()), ("failed", "c: unreachable: ssh: no route"));
assert!(started.elapsed() < Duration::from_secs(1), "no wait for a down carrier");
assert_eq!(dials.load(Ordering::SeqCst), 0, "nothing dialed over a down carrier");
up.store(true, Ordering::SeqCst);
wait_for("connected", Duration::from_secs(5), || state().state == LinkState::Connected);
assert_eq!((dials.load(Ordering::SeqCst), state().version.as_deref()), (1, Some("0.6.0")));
up.store(false, Ordering::SeqCst);
wait_for("unreachable again", Duration::from_secs(5), || state().state == LinkState::Unreachable);
up.store(true, Ordering::SeqCst);
wait_for("connected again", Duration::from_secs(5), || state().state == LinkState::Connected);
assert_eq!(dials.load(Ordering::SeqCst), 2, "one dial per carrier");
drop(machines);
let _ = std::fs::remove_dir_all(&base);
}
static HUB_LOGGED: Mutex<Vec<String>> = Mutex::new(Vec::new());
#[allow(clippy::type_complexity)]
fn inbound_and_ssh(
base: &Path,
hub: Option<Hub>,
log: fn(&str),
) -> (Machines, inbound::Guard, Arc<AtomicBool>, Arc<Mutex<Vec<String>>>, Arc<Mutex<Vec<String>>>) {
let registry = base.join("machines.toml");
crate::serve::machines::update(®istry, |e| e.push(Entry::ssh("s", "me@s"))).unwrap();
let neighbors: Arc<inbound::Neighbors> = Arc::default();
let guard = neighbors.announce("w", "0.6.0 abc dev x/y member", false);
let up = Arc::new(AtomicBool::new(false));
let dials = Arc::new(Mutex::new(Vec::new()));
let dial: Dial = {
let (up, dials) = (Arc::clone(&up), Arc::clone(&dials));
Arc::new(move |e: &Entry| {
dials.lock().unwrap().push(e.name.clone());
if e.kind == Kind::Inbound && up.load(Ordering::SeqCst) {
return Ok(mute_peer());
}
anyhow::bail!("its link isn't up (fleet-{}.sock: No such file or directory)", e.name)
})
};
let runs = Arc::new(Mutex::new(Vec::new()));
let hold = fake_hold(&Arc::new(AtomicBool::new(false)), &runs);
let machines = Machines::spawn(registry, neighbors, dial, no_route(), hold, opts(1, 0).machine_timing, no_hooks(), hub, log);
(machines, guard, up, dials, runs)
}
#[test]
fn every_link_is_held() {
let base = short_scratch("held");
let (machines, _w, up, dials, runs) = inbound_and_ssh(&base, None, |l| HUB_LOGGED.lock().unwrap().push(l.into()));
let h = machines.handle();
wait_for("the inbound link retrying", Duration::from_secs(5), || ran(&dials, "w") >= 3);
assert_eq!(h.remotes().get("w").unwrap().state, LinkState::Unreachable);
let logged: Vec<_> = HUB_LOGGED.lock().unwrap().iter().filter(|l| l.starts_with("machine w: ")).cloned().collect();
assert_eq!(logged.len(), 1, "one line for one way of failing: {logged:?}");
assert!(logged[0].contains("its link isn't up"), "{}", logged[0]);
up.store(true, Ordering::SeqCst);
wait_for("the inbound link up", Duration::from_secs(5), || h.remotes().get("w").unwrap().state == LinkState::Connected);
assert_eq!(ran(&runs, "w"), 0, "no carrier for an inbound machine");
assert!(ran(&runs, "s") >= 1, "the ssh machine's carrier runs");
assert_eq!(ran(&dials, "s"), 0, "nothing dialed over a down carrier");
assert_eq!(h.remotes().get("s").unwrap().state, LinkState::Unreachable);
assert!(!base.join("remotes.json").exists(), "only a hub saves");
drop(machines);
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn a_hub_restores_and_saves_remotes() {
let base = short_scratch("hub-save");
let path = base.join("remotes.json");
let rows = json!({"dir": "/r", "instances": [{"name": "web-1"}]});
let row = |name: &str| Machine {
name: name.into(),
rows: [(PathBuf::from("/r"), Arc::new(rows.clone()))].into(),
seen: Some(1_761_566_400),
..Machine::default()
};
saved::save(&path, &saved::of(&[row("s"), row("gone")], 0)).unwrap();
let hub = Hub { remotes: path.clone(), is_hub: Arc::new(|| true) };
let (machines, _w, up, _, runs) = inbound_and_ssh(&base, Some(hub), |_| {});
let h = machines.handle();
assert!(h.remotes().get("gone").is_none(), "not registered: dropped");
let s = h.remotes().get("s").unwrap();
assert!(s.rows.is_empty() && s.restored);
wait_for("s's carrier failed", Duration::from_secs(5), || ran(&runs, "s") >= 1);
wait_for("s unreachable", Duration::from_secs(5), || h.remotes().get("s").unwrap().error.is_some());
let s = h.remotes().get("s").unwrap();
assert_eq!(s.state, LinkState::Unreachable, "restored: unreachable");
assert!(s.error.as_deref().unwrap().ends_with("(rows from Oct 27 12:00 UTC)"), "{:?}", s.error);
up.store(true, Ordering::SeqCst);
wait_for("w connected", Duration::from_secs(5), || h.remotes().get("w").unwrap().state == LinkState::Connected);
drop(machines);
let saved = saved::load(&path).unwrap();
assert_eq!(saved.machines.keys().collect::<Vec<_>>(), ["w"], "gone dropped; s has nothing left to save");
assert_eq!(saved.machines["w"].version.as_deref(), Some("0.6.0"), "w's hello");
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn only_while_the_hub_are_remotes_saved() {
let base = short_scratch("hub-flip");
let path = base.join("remotes.json");
let rows = json!({"dir": "/r", "instances": []});
let saved_s = Machine { name: "s".into(), rows: [(PathBuf::from("/r"), Arc::new(rows))].into(), seen: Some(1), ..Machine::default() };
saved::save(&path, &saved::of(&[saved_s], 0)).unwrap();
let before = std::fs::read(&path).unwrap();
let flag = Arc::new(AtomicBool::new(false));
let is_hub = {
let flag = Arc::clone(&flag);
Arc::new(move || flag.load(Ordering::SeqCst))
};
let (machines, _w, up, _, _) = inbound_and_ssh(&base, Some(Hub { remotes: path.clone(), is_hub }), |_| {});
let h = machines.handle();
assert!(!h.remotes().get("s").unwrap().restored, "not the hub: nothing restored");
up.store(true, Ordering::SeqCst);
wait_for("w connected", Duration::from_secs(5), || h.remotes().get("w").unwrap().state == LinkState::Connected);
std::thread::sleep(Duration::from_millis(100));
assert_eq!(std::fs::read(&path).unwrap(), before, "not the hub: nothing saved");
flag.store(true, Ordering::SeqCst);
h.reload();
drop(machines);
assert_eq!(saved::load(&path).unwrap().machines.keys().collect::<Vec<_>>(), ["w"], "the hub now: saved");
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn a_hub_no_longer_the_hub_stops_saving_remotes() {
let base = short_scratch("hub-unflip");
let path = base.join("remotes.json");
let rows = json!({"dir": "/r", "instances": []});
let saved_s = Machine { name: "s".into(), rows: [(PathBuf::from("/r"), Arc::new(rows))].into(), seen: Some(1), ..Machine::default() };
saved::save(&path, &saved::of(&[saved_s], 0)).unwrap();
let flag = Arc::new(AtomicBool::new(true));
let is_hub = {
let flag = Arc::clone(&flag);
Arc::new(move || flag.load(Ordering::SeqCst))
};
let (machines, _w, up, _, _) = inbound_and_ssh(&base, Some(Hub { remotes: path.clone(), is_hub }), |_| {});
let h = machines.handle();
assert!(h.remotes().get("s").unwrap().restored, "the hub: restored");
flag.store(false, Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(100));
let before = std::fs::read(&path).unwrap();
up.store(true, Ordering::SeqCst);
wait_for("w connected", Duration::from_secs(5), || h.remotes().get("w").unwrap().state == LinkState::Connected);
h.reload();
drop(machines);
assert_eq!(std::fs::read(&path).unwrap(), before, "no longer the hub: nothing saved");
assert!(!saved::load(&path).unwrap().machines.contains_key("w"));
let _ = std::fs::remove_dir_all(&base);
}
fn recording_peer(calls: &Arc<Mutex<Vec<String>>>) -> Duplex {
let (ours, theirs) = UnixStream::pair().unwrap();
let calls = Arc::clone(calls);
std::thread::spawn(move || {
let mut r = BufReader::new(theirs.try_clone().unwrap());
let mut line = String::new();
while r.read_line(&mut line).is_ok_and(|n| n > 0) {
let req: Value = serde_json::from_str(&line).unwrap();
let method = req["method"].as_str().unwrap_or_default();
calls.lock().unwrap().push(format!("{method} {}", req["params"]["dir"].as_str().unwrap_or_default()));
let result = match method {
"hello" => json!({"version": "0.6.0", "build": 1, "protocol": 1}),
_ => json!({"ok": true}),
};
if writeln!(&theirs, "{}", json!({"id": req["id"], "result": result})).is_err() {
break;
}
line.clear();
}
});
Duplex::socket(ours)
}
#[test]
fn a_change_of_roots_keeps_the_link() {
let base = short_scratch("roots");
let neighbors: Arc<inbound::Neighbors> = Arc::default();
let guard = neighbors.announce("w", "0.6.0 abc dev x/y member", false);
let (dials, calls) = (Arc::new(AtomicUsize::new(0)), Arc::new(Mutex::new(Vec::new())));
let dial: Dial = {
let (dials, calls) = (Arc::clone(&dials), Arc::clone(&calls));
Arc::new(move |_| {
dials.fetch_add(1, Ordering::SeqCst);
Ok(recording_peer(&calls))
})
};
let hooks = Hooks { watching: Box::new(|| true), ..no_hooks() };
let hold = fake_hold(&Arc::new(AtomicBool::new(false)), &Arc::default());
let timing = opts(1, 0).machine_timing;
let machines = Machines::spawn(base.join("machines.toml"), neighbors, dial, no_route(), hold, timing, hooks, None, |_| {});
let h = machines.handle();
wait_for("w connected", Duration::from_secs(5), || h.remotes().get("w").unwrap().state == LinkState::Connected);
guard.roots_setter()(vec![PathBuf::from("/r")]);
wait_for("/r watched", Duration::from_secs(5), || calls.lock().unwrap().iter().any(|c| c == "instances.watch /r"));
assert_eq!(dials.load(Ordering::SeqCst), 1, "no redial");
assert_eq!(h.remotes().get("w").unwrap().state, LinkState::Connected);
assert_eq!(h.entries()[0].roots, [PathBuf::from("/r")]);
drop(machines);
drop(guard);
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn a_cycle_redials_the_carrier_at_once() {
let base = short_scratch("cycle");
let registry = base.join("machines.toml");
crate::serve::machines::update(®istry, |e| e.push(Entry::ssh("c", "me@c"))).unwrap();
let runs = Arc::new(AtomicUsize::new(0));
let fail = Arc::new(AtomicBool::new(false));
let hold: Hold = {
let (runs, fail) = (Arc::clone(&runs), Arc::clone(&fail));
Arc::new(move |_: &Entry, held: &Held| {
runs.fetch_add(1, Ordering::SeqCst);
if fail.load(Ordering::SeqCst) {
return "ssh: no route".into();
}
let (ours, mut theirs) = UnixStream::pair().unwrap();
if !held.hold(Some(ours)) {
return "stopping".into();
}
held.up();
let _ = std::io::Read::read(&mut theirs, &mut [0u8; 1]);
"link closed".into()
})
};
let timing = Timing { backoff: Duration::from_secs(60), backoff_cap: Duration::from_secs(60), ..opts(1, 0).machine_timing };
let no_dial: Dial = Arc::new(|_| anyhow::bail!("no link here"));
let machines = Machines::spawn(registry, Arc::default(), no_dial, no_route(), hold, timing, no_hooks(), None, |_| {});
let h = machines.handle();
wait_for("up", Duration::from_secs(5), || runs.load(Ordering::SeqCst) == 1 && lock(&h.inner.lock_links()["c"].ctl.carrier).up);
h.cycle();
wait_for("redialed at once", Duration::from_secs(5), || runs.load(Ordering::SeqCst) == 2);
fail.store(true, Ordering::SeqCst);
h.cycle();
wait_for("failed", Duration::from_secs(5), || runs.load(Ordering::SeqCst) == 3);
std::thread::sleep(Duration::from_millis(100));
assert_eq!(runs.load(Ordering::SeqCst), 3, "in its backoff");
fail.store(false, Ordering::SeqCst);
h.cycle();
wait_for("redialed out of the backoff", Duration::from_secs(5), || runs.load(Ordering::SeqCst) == 4);
drop(machines);
let _ = std::fs::remove_dir_all(&base);
}
}