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::fleet::update::Behind;
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 control_plane: Box<dyn Fn() -> Option<ControlPlaneOf> + Send + Sync>,
pub routed: Box<dyn Fn() -> Vec<(String, Result<String, String>)> + Send + Sync>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ControlPlaneOf {
pub control_plane: String,
pub me: String,
}
pub type Hold = Arc<dyn Fn(&Entry, &Held) -> String + Send + Sync>;
pub struct ControlPlane {
pub remotes: PathBuf,
pub is_control_plane: Arc<dyn Fn() -> bool + Send + Sync>,
}
pub struct Machines {
inner: Arc<Inner>,
saver: Option<JoinHandle<()>>,
}
struct ControlPlaneSave {
path: PathBuf,
is_control_plane: 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,
control_plane: Option<ControlPlaneSave>,
}
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>,
behind: Behind,
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 behind(&self, behind: Behind) {
lock(&self.ctl.carrier).behind = behind;
}
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,
Relist,
}
struct Call {
method: String,
params: Value,
wait: Duration,
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,
control_plane: Option<ControlPlane>,
log: fn(&str),
) -> Machines {
let control_plane = control_plane.map(|h| ControlPlaneSave { path: h.remotes, is_control_plane: h.is_control_plane, 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),
control_plane,
});
let saver = inner.control_plane.as_ref().and_then(|h| {
if (h.is_control_plane)() {
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(control_plane) = &self.inner.control_plane {
lock(&control_plane.state).stop = true;
control_plane.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(control_plane) = &inner.control_plane else { return };
let mut last: Option<Instant> = None;
loop {
{
let mut s = lock(&control_plane.state);
while !s.dirty && !s.stop {
s = control_plane.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(control_plane.cv.wait_timeout(s, wait));
continue;
}
s.dirty = false;
}
if !(control_plane.is_control_plane)() {
continue;
}
if let Err(e) = saved::save(&control_plane.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(control_plane) = &self.control_plane {
lock(&control_plane.state).dirty = true;
control_plane.cv.notify_all();
}
}
}
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));
}
}
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 gone: Vec<LinkThread> = {
let mut links = inner.lock_links();
let stale: Vec<String> =
links.iter().filter(|(name, l)| !entries.iter().any(|e| e.name == **name && *e == l.entry)).map(|(name, _)| name.clone()).collect();
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 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 cycle_one(&self, name: &str) -> bool {
match self.inner.lock_links().get(name) {
Some(l) if carried(&l.entry) => {
l.ctl.cycle();
true
}
_ => false,
}
}
pub fn wake(&self) {
for l in self.inner.lock_links().values() {
let _ = l.tx.send(Cmd::Wake);
}
}
pub fn entries(&self) -> Vec<Entry> {
let links = self.inner.lock_links();
links.values().map(|l| Entry { roots: self.inner.remotes.roots(&l.entry.name), ..l.entry.clone() }).collect()
}
pub fn relist(&self, name: &str) {
if let Some(l) = self.inner.lock_links().get(name) {
let _ = l.tx.send(Cmd::Relist);
}
}
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> {
self.forward_within(machine, method, params, self.inner.timing.call)
}
pub fn forward_within(&self, machine: &str, method: &str, params: Value, wait: Duration) -> 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, wait),
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, wait, reply })).map_err(|_| stopping())?;
let t = &self.inner.timing;
let bound = t.handshake * 2 + wait + 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, self.inner.timing.call).map_err(|e| format!("{direct}; over a route: {}", e.message))
}
}
}
fn call_routed(&self, machine: &str, method: &str, params: Value, wait: Duration) -> 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, wait) {
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 control plane changed: redialing".into();
}
{
let mut c = lock(&ctl.carrier);
c.up = false;
c.why = Some(why.clone());
c.behind = Behind::default();
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,
listing: Vec<crate::serve::api::RootCandidate>,
relist: bool,
}
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, listing: Vec::new(), relist: false }
}
fn take(&mut self, cmd: Cmd) {
match cmd {
Cmd::Call(call) => self.pending.push_back(call),
Cmd::Relist => self.relist = true,
Cmd::Wake => {}
}
}
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_up();
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) => self.take(cmd),
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 set_up(&self) {
let behind = if carried(&self.entry) { lock(&self.ctl.carrier).behind.clone() } else { self.inner.inbound.behind(&self.entry.name) };
let mut moved = false;
self.inner.remotes.update(&self.entry.name, |m| moved = m.set_up(behind));
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", "roots"] })) {
return End::Lost(why);
}
self.relist = true;
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) => self.take(cmd),
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => return End::Stopped,
}
}
if std::mem::take(&mut self.relist)
&& let Err(why) = self.list_roots(link)
{
return End::Lost(why);
}
let roots = (self.inner.hooks.watching)();
let control_plane = (self.inner.hooks.control_plane)().filter(|h| h.control_plane == name);
if control_plane.is_none() {
self.drop_fleet();
}
let want = Want { roots, fleet: roots && control_plane.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, call.wait);
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 == "roots.changed" => self.relist = true,
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 list_roots(&mut self, link: &mut Link) -> Result<(), String> {
let name = self.entry.name.clone();
let r = link
.conn
.call_within("roots.list", json!({}), self.inner.timing.call)
.map_err(|e| format!("{name}: {e:#}"))?
.ok_or_else(|| format!("{name}: `roots.list` timed out"))?;
let mut rows = match (r.error, r.result.map(serde_json::from_value::<Vec<crate::serve::api::RootCandidate>>)) {
(None, Some(Ok(rows))) => rows,
(Some(e), _) => {
(self.inner.log)(&format!("machine {name}: roots.list: {}", e.message));
return Ok(());
}
(None, _) => {
(self.inner.log)(&format!("machine {name}: bad roots.list answer"));
return Ok(());
}
};
rows.retain(|c| c.error.is_none() || c.fleet);
let listed: Vec<PathBuf> = rows.iter().map(|c| c.root.clone()).collect();
let default = super::default_root(&rows);
self.listing = rows;
self.apply_roots(listed, default);
Ok(())
}
fn apply_roots(&mut self, listed: Vec<PathBuf>, default: Option<PathBuf>) {
let name = self.entry.name.clone();
let inner = self.inner;
let mut moved = false;
self.entry.roots = listed;
{
let links = inner.lock_links();
if links.contains_key(&name) {
let roots = &self.entry.roots;
inner.remotes.update(&name, |m| {
moved = m.roots != *roots || m.default_root != default;
m.roots.clone_from(roots);
m.default_root = default;
m.listed = true;
m.rows.retain(|root, _| roots.contains(root));
});
}
}
if moved {
self.inner.rows_changed();
(self.inner.hooks.changed)();
}
}
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 {
match crate::serve::fleet::placed::fleet_root(&self.listing) {
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.control_plane)().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}}),
Some("roots.list") => json!({"id": req["id"], "result": []}),
_ => 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(|| {}), control_plane: 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 CONTROL_PLANE_LOGGED: Mutex<Vec<String>> = Mutex::new(Vec::new());
#[allow(clippy::type_complexity)]
fn inbound_and_ssh(
base: &Path,
control_plane: Option<ControlPlane>,
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, Default::default());
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(), control_plane, 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| CONTROL_PLANE_LOGGED.lock().unwrap().push(l.into()));
let h = machines.handle();
wait_for("the inbound link retrying", Duration::from_secs(5), || {
ran(&dials, "w") >= 3 && h.remotes().get("w").unwrap().state == LinkState::Unreachable
});
let logged: Vec<_> = CONTROL_PLANE_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);
wait_for("the ssh machine's carrier failed", Duration::from_secs(5), || {
ran(&runs, "s") >= 1 && h.remotes().get("s").unwrap().state == LinkState::Unreachable
});
assert_eq!(ran(&runs, "w"), 0, "no carrier for an inbound machine");
assert_eq!(ran(&dials, "s"), 0, "nothing dialed over a down carrier");
assert!(!base.join("remotes.json").exists(), "only a control plane saves");
drop(machines);
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn a_control_plane_restores_and_saves_remotes() {
let base = short_scratch("cp-save");
let path = base.join("remotes.json");
let rows = json!({"dir": "/r", "instances": [{"name": "web-1"}]});
let row = |name: &str| Machine {
name: name.into(),
roots: vec![PathBuf::from("/r")],
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("w"), row("gone")], 0)).unwrap();
let control_plane = ControlPlane { remotes: path.clone(), is_control_plane: Arc::new(|| true) };
let (machines, _w, up, _, runs) = inbound_and_ssh(&base, Some(control_plane), |_| {});
let h = machines.handle();
assert!(h.remotes().get("gone").is_none(), "not registered: dropped");
let s = h.remotes().get("s").unwrap();
assert!(s.restored && s.rows.contains_key(Path::new("/r")));
assert_eq!(h.entries().iter().map(|e| e.roots.clone()).collect::<Vec<_>>(), vec![vec![PathBuf::from("/r")], vec![PathBuf::from("/r")]]);
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 listed", Duration::from_secs(5), || h.remotes().get("w").unwrap().roots.is_empty());
let w = h.remotes().get("w").unwrap();
assert!(w.rows.is_empty() && h.remotes().get("s").unwrap().rows.contains_key(Path::new("/r")));
drop(machines);
let saved = saved::load(&path).unwrap();
assert_eq!(saved.machines.keys().collect::<Vec<_>>(), ["s", "w"], "gone dropped");
assert_eq!(saved.machines["s"].roots, [PathBuf::from("/r")], "s never listed: as restored");
assert!(saved.machines["w"].rows.is_empty() && saved.machines["w"].roots.is_empty());
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_control_plane_are_remotes_saved() {
let base = short_scratch("cp-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_control_plane = {
let flag = Arc::clone(&flag);
Arc::new(move || flag.load(Ordering::SeqCst))
};
let (machines, _w, up, _, _) = inbound_and_ssh(&base, Some(ControlPlane { remotes: path.clone(), is_control_plane }), |_| {});
let h = machines.handle();
assert!(!h.remotes().get("s").unwrap().restored, "not the control plane: 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 control plane: nothing saved");
flag.store(true, Ordering::SeqCst);
h.reload();
drop(machines);
assert_eq!(saved::load(&path).unwrap().machines.keys().collect::<Vec<_>>(), ["w"], "the control plane now: saved");
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn a_control_plane_no_longer_the_control_plane_stops_saving_remotes() {
let base = short_scratch("cp-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_control_plane = {
let flag = Arc::clone(&flag);
Arc::new(move || flag.load(Ordering::SeqCst))
};
let (machines, _w, up, _, _) = inbound_and_ssh(&base, Some(ControlPlane { remotes: path.clone(), is_control_plane }), |_| {});
let h = machines.handle();
assert!(h.remotes().get("s").unwrap().restored, "the control plane: 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 control plane: nothing saved");
assert!(!saved::load(&path).unwrap().machines.contains_key("w"));
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn an_inbound_neighbors_roots_are_its_links_listing() {
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, Default::default());
let (dials, calls) = (Arc::new(AtomicUsize::new(0)), Arc::new(Mutex::new(Vec::new())));
let listed = Arc::new(Mutex::new(vec!["/r".to_string()]));
let dial: Dial = {
let (dials, calls) = (Arc::clone(&dials), Arc::clone(&calls));
Arc::new(move |_| {
dials.fetch_add(1, Ordering::SeqCst);
Ok(listing_peer(&calls, &listed))
})
};
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("/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);
}
fn listing_peer(calls: &Arc<Mutex<Vec<String>>>, listed: &Arc<Mutex<Vec<String>>>) -> Duplex {
let (ours, theirs) = UnixStream::pair().unwrap();
let (calls, listed) = (Arc::clone(calls), Arc::clone(listed));
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();
let at = req["params"]["dir"].as_str().or(req["params"]["root"].as_str()).unwrap_or_default().to_string();
calls.lock().unwrap().push(format!("{method} {at}"));
let gone = |r: &str| listed.lock().unwrap().iter().any(|l| l.strip_prefix('!') == Some(r));
let answer = match method {
"hello" => json!({"id": req["id"], "result": {"version": "0.6.0", "build": 1, "protocol": 1}}),
"roots.list" => {
let rows: Vec<Value> = listed
.lock()
.unwrap()
.iter()
.map(|r| match r.strip_prefix('!') {
Some(r) => json!({"root": r, "sandboxes": [], "error": "no such directory"}),
None => json!({"root": r, "sandboxes": [], "error": null}),
})
.collect();
json!({"id": req["id"], "result": rows})
}
"sandboxes.list" => json!({"id": req["id"], "result": [{"name": "s", "root": at}]}),
"instances.watch" if gone(&at) => {
json!({"id": req["id"], "error": {"code": "not-found", "message": format!("no config root at {at}")}})
}
_ => json!({"id": req["id"], "result": {"ok": true}}),
};
if writeln!(&theirs, "{answer}").is_err() {
break;
}
if method == "instances.watch" && answer["error"].is_null() {
let push = json!({"method": "instances.snapshot", "params": {"dir": at, "instances": []}});
if writeln!(&theirs, "{push}").is_err() {
break;
}
}
if method == "test.rootsChanged" && writeln!(&theirs, "{}", json!({"method": "roots.changed", "params": {}})).is_err() {
break;
}
line.clear();
}
});
Duplex::socket(ours)
}
#[test]
fn a_root_listed_later_is_watched_and_listed() {
let base = short_scratch("live-roots");
let registry = base.join("machines.toml");
crate::serve::machines::update(®istry, |e| e.push(Entry::ssh("b", "me@b"))).unwrap();
let calls = Arc::new(Mutex::new(Vec::new()));
let listed = Arc::new(Mutex::new(vec!["/a".to_string()]));
let dial: Dial = {
let (calls, listed) = (Arc::clone(&calls), Arc::clone(&listed));
Arc::new(move |_| Ok(listing_peer(&calls, &listed)))
};
let hooks = Hooks { watching: Box::new(|| true), ..no_hooks() };
let hold = fake_hold(&Arc::new(AtomicBool::new(true)), &Arc::default());
let machines = Machines::spawn(registry.clone(), Arc::default(), dial, no_route(), hold, opts(1, 0).machine_timing, hooks, None, |_| {});
let h = machines.handle();
let called = |c: &str| calls.lock().unwrap().iter().any(|x| x == c);
wait_for("/a watched", Duration::from_secs(5), || called("instances.watch /a"));
assert_eq!(h.entries()[0].roots, [PathBuf::from("/a")]);
listed.lock().unwrap().push("/data/mesh/tree/bolt".into());
h.relist("b");
wait_for("the new root watched", Duration::from_secs(5), || called("instances.watch /data/mesh/tree/bolt"));
let live = [PathBuf::from("/a"), PathBuf::from("/data/mesh/tree/bolt")];
assert_eq!(h.entries()[0].roots, live);
assert_eq!(h.remotes().get("b").unwrap().roots, live, "its pushes are stored");
let all = super::super::forward::sandboxes_everywhere(Ok(json!([])), Some(&h)).unwrap();
assert_eq!(
all,
json!([
{"name": "s", "machine": "b", "root": "/a"},
{"name": "s", "machine": "b", "root": "/data/mesh/tree/bolt"},
])
);
drop(machines);
let _ = std::fs::remove_dir_all(&base);
}
fn listing_machine(tag: &str, listed: Vec<String>) -> (PathBuf, Machines, Arc<Mutex<Vec<String>>>, Arc<Mutex<Vec<String>>>) {
let base = short_scratch(tag);
let registry = base.join("machines.toml");
crate::serve::machines::update(®istry, |e| e.push(Entry::ssh("b", "me@b"))).unwrap();
let calls = Arc::new(Mutex::new(Vec::new()));
let listed = Arc::new(Mutex::new(listed));
let dial: Dial = {
let (calls, listed) = (Arc::clone(&calls), Arc::clone(&listed));
Arc::new(move |_| Ok(listing_peer(&calls, &listed)))
};
let hooks = Hooks { watching: Box::new(|| true), ..no_hooks() };
let hold = fake_hold(&Arc::new(AtomicBool::new(true)), &Arc::default());
let machines = Machines::spawn(registry, Arc::default(), dial, no_route(), hold, opts(1, 0).machine_timing, hooks, None, |_| {});
wait_for("/a watched", Duration::from_secs(5), || calls.lock().unwrap().iter().any(|c| c == "instances.watch /a"));
(base, machines, calls, listed)
}
#[test]
fn roots_changed_relists() {
let (base, machines, calls, listed) = listing_machine("roots-changed", vec!["/a".into(), "/b".into()]);
let h = machines.handle();
listed.lock().unwrap().retain(|r| r != "/b");
assert!(h.forward("b", "test.rootsChanged", json!({})).unwrap().error.is_none());
wait_for("/b gone", Duration::from_secs(5), || h.entries()[0].roots == [PathBuf::from("/a")]);
assert_eq!(h.remotes().get("b").unwrap().roots, [PathBuf::from("/a")]);
assert!(!h.remotes().get("b").unwrap().rows.contains_key(Path::new("/b")));
assert_eq!(calls.lock().unwrap().iter().filter(|c| c.starts_with("roots.list")).count(), 2);
drop(machines);
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn a_listed_root_with_an_error_is_not_watched() {
let (base, machines, calls, _) = listing_machine("dead-root", vec!["/a".into(), "!/gone".into()]);
let h = machines.handle();
assert!(h.forward("b", "ping", json!({})).unwrap().error.is_none());
assert!(!calls.lock().unwrap().iter().any(|c| c == "instances.watch /gone"), "{:?}", calls.lock().unwrap());
let b = h.remotes().get("b").unwrap();
assert_eq!((b.state, b.error), (LinkState::Connected, None));
assert_eq!(h.entries()[0].roots, [PathBuf::from("/a")]);
drop(machines);
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn a_reload_keeps_the_listed_roots() {
let (base, machines, calls, _) = listing_machine("reload-keeps", vec!["/a".into()]);
let h = machines.handle();
let a = PathBuf::from("/a");
wait_for("/a's push stored", Duration::from_secs(5), || h.remotes().get("b").unwrap().rows.contains_key(&a));
h.reload();
let b = h.remotes().get("b").unwrap();
assert_eq!((b.roots, b.rows.contains_key(&a)), (vec![a.clone()], true));
assert_eq!(h.entries()[0].roots, [a]);
assert!(h.forward("b", "ping", json!({})).unwrap().error.is_none());
assert_eq!(calls.lock().unwrap().iter().filter(|c| c.starts_with("roots.list")).count(), 1);
drop(machines);
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);
wait_for("up again", Duration::from_secs(5), || lock(&h.inner.lock_links()["c"].ctl.carrier).up);
assert!(h.cycle_one("c"));
wait_for("redialed by name", Duration::from_secs(5), || runs.load(Ordering::SeqCst) == 5);
assert!(!h.cycle_one("nope"));
drop(machines);
let _ = std::fs::remove_dir_all(&base);
}
}