Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ and listed with their assets on the
or off, and a mute per stack or lane, behind the bell in the dashboard's
top bar or with `devstack hub notify [on|off <kind>…|test]`;
`DEVSTACK_NO_NOTIFY` switches them off.
- **Lanes of other members on this machine are shown**: a banner below the
dashboard's top bar (hidden until a lane comes or goes), a tile in the
sidebar, and *On this machine* in the pool area (whose, repository,
since when, what it reserved); a lane that starts running here notifies
(`guest_lane`, on by default). The hub reads them from the pool's leases
every 15 s and sends them on `/hub/events` (`guests`).
- A `devstack://open?stack=…&lane=…&service=…` link opens the dashboard
there, paired; `/auth` takes `next`, a dashboard route, and keeps the
session of a browser that is paired already.
Expand Down
212 changes: 212 additions & 0 deletions crates/devstack-hub/src/guests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
//! Lanes of other members that run on this machine ("guest lanes"): whoever
//! sits at a machine that runs the pool's lanes sees, without asking, that
//! someone else's code runs on it. The coordinator lists every lease of the
//! pool to every member; those whose node is this machine and whose owner is
//! someone else are the guests. The share loop (`share.rs`) asks after each
//! report, every 15 s per pool. The dashboard hears them on `/hub/events`
//! (`guests`), and a guest lane that starts notifies (ADR-0045,
//! `guest_lane`).

use devstack_node::coordinator::{Lease, NodeView};
use serde::Serialize;
use std::collections::{BTreeMap, HashSet};
use std::sync::{Mutex, OnceLock};
use tokio::sync::watch;

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Guest {
pub pool: String,
pub lease: String,
/// The member whose lane it is, and how the pool names them.
pub member: String,
pub owner: String,
pub repo: String,
pub lane: String,
/// `offered` (admitted by the coordinator, not started yet) or `running`.
pub state: String,
/// Unix seconds.
pub since: u64,
/// What it asked for.
pub cpus: f64,
pub memory: u64,
}

type Started = Box<dyn Fn(&Guest) + Send + Sync>;

struct Guests {
tx: watch::Sender<Vec<Guest>>,
/// Per pool, as last read; a pool that could not be asked keeps its last.
by_pool: Mutex<BTreeMap<String, Vec<Guest>>>,
/// Per pool, the running leases already told (or there when the hub
/// first read the pool).
told: Mutex<BTreeMap<String, HashSet<String>>>,
started: OnceLock<Started>,
}

static GUESTS: OnceLock<Guests> = OnceLock::new();

fn guests() -> &'static Guests {
GUESTS.get_or_init(|| Guests {
tx: watch::channel(Vec::new()).0,
by_pool: Mutex::new(BTreeMap::new()),
told: Mutex::new(BTreeMap::new()),
started: OnceLock::new(),
})
}

/// The guest lanes now, and each change.
pub fn subscribe() -> watch::Receiver<Vec<Guest>> {
guests().tx.subscribe()
}

/// What to do when a guest lane starts running here (the hub's notification).
pub fn on_started(f: impl Fn(&Guest) + Send + Sync + 'static) {
let _ = guests().started.set(Box::new(f));
}

/// The guests in `leases` of `pool`, for the member `me`; owners named from
/// `nodes` (every member reports, so every member is listed there).
pub fn of(pool: &str, me: &str, leases: &[Lease], nodes: &[NodeView]) -> Vec<Guest> {
leases
.iter()
.filter(|l| l.node == me && l.member != me)
.map(|l| Guest {
pool: pool.to_string(),
lease: l.id.clone(),
member: l.member.clone(),
owner: nodes
.iter()
.find(|n| n.id == l.member)
.map_or_else(|| l.member.clone(), |n| n.name.clone()),
repo: l.repo.clone(),
lane: l.lane.clone(),
state: l.state.clone(),
since: l.created,
cpus: l.need.cpus,
memory: l.need.memory,
})
.collect()
}

/// The guests of `pool` as just read (`None`: it could not be asked, the
/// last list stands). A pool's first reading is its baseline: guest lanes
/// running then are not told.
pub fn seen(pool: &str, now: Option<Vec<Guest>>) {
let g = guests();
let Some(list) = now else { return };
let running: Vec<&Guest> = list.iter().filter(|x| x.state == "running").collect();
let fresh: Vec<Guest> = {
let mut told = g.told.lock().unwrap();
match told.get_mut(pool) {
None => {
let set = running.iter().map(|x| x.lease.clone()).collect();
told.insert(pool.to_string(), set);
Vec::new()
}
Some(set) => {
// Forget leases that are gone, so the set never only grows.
set.retain(|l| list.iter().any(|x| &x.lease == l));
running
.iter()
.filter(|x| set.insert(x.lease.clone()))
.map(|x| (*x).clone())
.collect()
}
}
};
let all: Vec<Guest> = {
let mut by_pool = g.by_pool.lock().unwrap();
by_pool.insert(pool.to_string(), list);
by_pool.values().flatten().cloned().collect()
};
g.tx.send_if_modified(|cur| {
if *cur == all {
false
} else {
*cur = all;
true
}
});
if let Some(f) = g.started.get() {
for x in &fresh {
f(x);
}
}
}

#[cfg(test)]
mod tests {
use super::*;

fn lease(id: &str, node: &str, member: &str, state: &str) -> Lease {
serde_json::from_value(serde_json::json!({
"id": id, "node": node, "member": member, "repo": "shop", "lane": "feat-cart",
"need": { "cpus": 2.0, "memory": 4_000_000_000u64 }, "state": state, "created": 1_700_000_000u64,
}))
.unwrap()
}

fn node(id: &str, name: &str) -> NodeView {
serde_json::from_value(serde_json::json!({ "id": id, "name": name, "online": true }))
.unwrap()
}

#[test]
fn guests_are_others_lanes_on_this_machine() {
let leases = [
lease("l1", "me", "anna", "running"),
lease("l2", "me", "me", "running"), // my own lane here
lease("l3", "server", "anna", "running"), // anna's lane elsewhere
lease("l4", "me", "ghost", "offered"),
];
let g = of("default", "me", &leases, &[node("anna", "ANNA-LAPTOP")]);
assert_eq!(g.len(), 2);
assert_eq!(
(g[0].lease.as_str(), g[0].owner.as_str()),
("l1", "ANNA-LAPTOP")
);
// An owner the node list does not name is shown by id.
assert_eq!(
(g[1].owner.as_str(), g[1].state.as_str()),
("ghost", "offered")
);
assert_eq!((g[0].cpus, g[0].memory), (2.0, 4_000_000_000));
}

#[test]
fn a_guest_lane_that_starts_is_told_once_and_a_pools_first_reading_is_none() {
static TOLD: Mutex<Vec<String>> = Mutex::new(Vec::new());
on_started(|g| TOLD.lock().unwrap().push(g.lease.clone()));
let rx = subscribe();
let read = |pool: &str, leases: &[Lease]| seen(pool, Some(of(pool, "me", leases, &[])));
// What runs when the hub first reads a pool is the baseline.
read("t-a", &[lease("a1", "me", "anna", "running")]);
read("t-b", &[lease("b1", "me", "ben", "running")]);
assert!(TOLD.lock().unwrap().is_empty());
// Offered, then running: told when it runs, once.
read(
"t-a",
&[
lease("a1", "me", "anna", "running"),
lease("a2", "me", "anna", "offered"),
],
);
read(
"t-a",
&[
lease("a1", "me", "anna", "running"),
lease("a2", "me", "anna", "running"),
],
);
read("t-a", &[lease("a2", "me", "anna", "running")]);
// A pool that could not be asked keeps its guests.
seen("t-b", None);
assert_eq!(*TOLD.lock().unwrap(), ["a2"]);
let now: Vec<String> = rx.borrow().iter().map(|g| g.lease.clone()).collect();
assert!(
now.contains(&"a2".to_string()) && now.contains(&"b1".to_string()),
"{now:?}"
);
assert!(!now.contains(&"a1".to_string()), "{now:?}");
}
}
15 changes: 14 additions & 1 deletion crates/devstack-hub/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ use tokio_stream::StreamExt;
static UI: Dir<'_> = include_dir!("$OUT_DIR/ui");

mod dialog;
mod guests;
mod notify;
mod pool;
pub mod release;
Expand Down Expand Up @@ -372,6 +373,12 @@ pub fn serve() -> Result<(), String> {
Arc::new(move |t: &notify::Target| open_dashboard(port, &codes, &t.path()))
};
let notify = Arc::new(notify::Center::new(&dir, notify::platform_sink(port, open)));
{
let notify = notify.clone();
guests::on_started(move |g| {
notify.guest_started(g);
});
}
let state = AppState {
port,
token: Arc::new(token),
Expand Down Expand Up @@ -1321,7 +1328,13 @@ fn hub_events(s: &AppState) -> impl tokio_stream::Stream<Item = serde_json::Valu
.map(|engine| serde_json::json!({ "type": "docker", "docker": engine }));
let release = tokio_stream::wrappers::WatchStream::new(s.newer.clone())
.map(|newer| serde_json::json!({ "type": "release", "current": VERSION, "newer": newer }));
stacks.merge(docker).merge(release).merge(update)
let guests = tokio_stream::wrappers::WatchStream::new(guests::subscribe())
.map(|guests| serde_json::json!({ "type": "guests", "guests": guests }));
stacks
.merge(docker)
.merge(release)
.merge(update)
.merge(guests)
}

fn entry(s: &AppState, id: &str) -> Option<StackEntry> {
Expand Down
51 changes: 51 additions & 0 deletions crates/devstack-hub/src/notify/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,17 @@ pub(crate) struct Target {
pub stack: Option<String>,
pub lane: Option<String>,
pub service: Option<String>,
/// The pool area instead (guest lanes).
pub pool: bool,
}

impl Target {
/// The dashboard's route for it (hash history). `lane=` (empty) shows
/// the main working tree, whichever lane was shown last.
pub fn path(&self) -> String {
if self.pool {
return "/#/pool".into();
}
let Some(stack) = &self.stack else {
return "/#/".into();
};
Expand All @@ -76,6 +81,9 @@ impl Target {
/// The `devstack://open` link that opens it (`devstack open-url`).
#[cfg_attr(not(windows), allow(dead_code))]
pub fn link(&self) -> String {
if self.pool {
return "devstack://open?page=pool".into();
}
let mut q = Vec::new();
for (k, v) in [
("stack", &self.stack),
Expand Down Expand Up @@ -258,6 +266,39 @@ impl Center {
stack: Some(stack.to_string()),
lane: lane.map(str::to_string),
service: n.service,
pool: false,
},
tag: blake3::hash(key.as_bytes()).to_hex()[..16].to_string(),
});
true
}

/// A lane of another member started running on this machine
/// (`guests.rs`). Once per lease; whether it was told.
pub fn guest_started(&self, g: &crate::guests::Guest) -> bool {
if !self.settings.lock().unwrap().on(Kind::GuestLane) {
return false;
}
let key = format!("guest/{}/{}", g.pool, g.lease);
diag::info(
"notice",
serde_json::json!({
"kind": Kind::GuestLane.key(), "pool": g.pool, "owner": g.owner,
"repo": g.repo, "lane": g.lane, "shown": self.sink.status().is_ok(),
}),
);
let pool = if g.pool == devstack_node::member::DEFAULT_POOL {
String::new()
} else {
format!(" · pool {}", g.pool)
};
self.sink.show(Shown {
title: format!("{}'s lane {} runs on this machine", g.owner, g.lane),
context: format!("{}{pool}", g.repo),
body: "The pool area shows it; pausing the node there takes no new lanes.".into(),
target: Target {
pool: true,
..Target::default()
},
tag: blake3::hash(key.as_bytes()).to_hex()[..16].to_string(),
});
Expand Down Expand Up @@ -582,6 +623,7 @@ mod tests {
stack: Some("ab12".into()),
lane: Some("feat-x".into()),
service: Some("api".into()),
pool: false,
}
);
}
Expand Down Expand Up @@ -668,6 +710,7 @@ mod tests {
stack: Some("ab12".into()),
lane: Some("feat x".into()),
service: Some("api".into()),
pool: false,
};
assert_eq!(t.path(), "/#/s/ab12/services/api?lane=feat%20x");
assert_eq!(
Expand All @@ -682,5 +725,13 @@ mod tests {
assert_eq!(main.link(), "devstack://open?stack=ab12");
assert_eq!(Target::default().path(), "/#/");
assert_eq!(Target::default().link(), "devstack://open");
let pool = Target {
pool: true,
..Target::default()
};
assert_eq!(
(pool.path().as_str(), pool.link().as_str()),
("/#/pool", "devstack://open?page=pool")
);
}
}
6 changes: 5 additions & 1 deletion crates/devstack-hub/src/notify/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,18 @@ pub enum Kind {
LaneFailed,
MainPorts,
Live,
GuestLane,
}

impl Kind {
pub const ALL: [Kind; 6] = [
pub const ALL: [Kind; 7] = [
Kind::BuildFailed,
Kind::Held,
Kind::ServiceFailed,
Kind::LaneFailed,
Kind::MainPorts,
Kind::Live,
Kind::GuestLane,
];

pub fn key(self) -> &'static str {
Expand All @@ -38,6 +40,7 @@ impl Kind {
Kind::LaneFailed => "lane_failed",
Kind::MainPorts => "main_ports",
Kind::Live => "live",
Kind::GuestLane => "guest_lane",
}
}

Expand All @@ -53,6 +56,7 @@ impl Kind {
Kind::LaneFailed => "A lane's start or move on a node failed",
Kind::MainPorts => "A lane took or gave back the main ports",
Kind::Live => "A candidate went live",
Kind::GuestLane => "A lane of another member started on this machine",
}
}

Expand Down
Loading