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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ and listed with their assets on the

## [Unreleased]

### Removed

- **The share switch is gone from the dashboard** (sidebar and pool area):
it reported capacity but never started a node agent, so no member could
start a lane on a machine that only switched it on; on Windows none can
run at all (#168). The hub reports the machine (online, what it has, its
devstack) and offers nothing; `PUT /hub/pool/share` is gone, `GET` says why
(`unavailable`). A machine runs other members' lanes with `devstack node
agent`, granted by an admin; a switch that starts it is #171.

### Changed

- **A lane started on a node opens its pages as soon as its daemon runs
Expand Down
5 changes: 3 additions & 2 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,9 @@ browsers as well.
(local certificates, an ignored env file), from the worktree or else the
main tree. The node's owner can read all of it, and the lane's output and
containers run there.
- Your machine reports to the coordinator what it shares (CPU, memory, GPUs,
load) when the share switch is on, and a node reports its lanes.
- Your machine reports to the coordinator what it has (CPU, memory, GPUs,
load) and which devstack it runs; a node reports what it offers and its
lanes.
- **Telemetry** to the pool's collector only with your consent, per pool,
off by default (`devstack join --telemetry`, `devstack pool telemetry
on|off`, the pool area): devstack's diagnostic log, cut to first lines as
Expand Down
2 changes: 1 addition & 1 deletion crates/devstack-hub/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ fn router(state: AppState) -> axum::Router {
.route("/hub/stacks/{id}", delete(forget))
.route("/hub/stacks/{id}/api/{*rest}", any(forward))
.route("/hub/pool", get(pool::overview))
.route("/hub/pool/share", get(share::get).put(share::put))
.route("/hub/pool/share", get(share::get))
.route("/hub/pool/shared", get(shared::list))
.route("/hub/pool/shared/{lease}/open", post(shared::open))
.route("/hub/pool/shared/{lease}/api/{*rest}", get(shared::view))
Expand Down
130 changes: 39 additions & 91 deletions crates/devstack-hub/src/share.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,42 @@
//! This machine's share of the pool (ADR-0031 point 3): the hub measures what
//! is free, offers half of it (capped, only with the switch on) and reports it
//! to the coordinator every 15 s, which also tells the pool the machine is
//! online. A machine in no pool, or not approved yet, reports nothing.
//! This machine in the pool (ADR-0031): the hub measures what the machine has
//! and what is free and reports it to the coordinator every 15 s, which also
//! tells the pool the machine is online and which devstack it runs. A machine
//! in no pool, or not approved yet, reports nothing.
//!
//! - `GET /hub/pool/share`: the switch, the caps, what is free and offered now,
//! the last report
//! - `PUT /hub/pool/share` `{enabled, max_cpus?, max_memory?}`: change them;
//! reports at once
//! The hub offers nothing to the pool. A machine runs other members' lanes
//! with a node agent (`devstack node agent`, granted by an admin), and the
//! dashboard's share switch never started one: it only reported capacity
//! nobody could use, and is gone until it does (#171; on Windows, which
//! cannot run the Linux lanes, #168).
//!
//! Both per pool (`?pool=<name>`, ADR-0034): each pool has its own switch
//! and caps, and gets its own report.
//! - `GET /hub/pool/share?pool=`: what is measured, the last report, the
//! coordinator's devstack, and why nothing is offered (`unavailable`)

use axum::Json;
use axum::extract::Query;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use devstack_node::coordinator::Report;
use devstack_node::share::{Amount, Settings, idle_cpus};
use devstack_node::share::{Amount, idle_cpus};
use devstack_node::store::State;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::mpsc;
use std::sync::{Mutex, OnceLock};
use std::time::Duration;

const EVERY: Duration = Duration::from_secs(15);

/// Why the hub offers nothing to the pool.
const NOT_SHARED: &str = "A machine runs other members' lanes with a node agent \
(`devstack node agent`, granted by an admin); the dashboard does not start one yet \
(#171, on Windows #168).";

#[derive(Debug, Clone, Default, Serialize)]
pub struct Status {
pub settings: Settings,
/// What the machine has in all.
pub total: Amount,
/// What is free now.
pub free: Amount,
/// What it offers now.
pub offer: Amount,
/// Whether it belongs to a pool as an approved member (else nothing is
/// reported).
pub member: bool,
Expand All @@ -46,12 +48,8 @@ pub struct Status {
/// report; `None` before one, or from an older coordinator.
#[serde(skip_serializing_if = "Option::is_none")]
pub coordinator: Option<devstack_node::version::Release>,
}

struct Sharing {
/// Per pool.
status: Mutex<BTreeMap<String, Status>>,
poke: Mutex<mpsc::Sender<()>>,
/// Why this machine offers the pool nothing.
pub unavailable: &'static str,
}

#[derive(Deserialize, Default)]
Expand All @@ -72,7 +70,8 @@ impl PoolQuery {
}
}

static SHARING: OnceLock<Sharing> = OnceLock::new();
/// Per pool.
static STATUS: OnceLock<Mutex<BTreeMap<String, Status>>> = OnceLock::new();

fn state() -> std::path::PathBuf {
devstack_daemon::token::token_path()
Expand All @@ -85,10 +84,9 @@ fn dir(pool: &str) -> std::path::PathBuf {
devstack_node::member::pool_dir(&state(), pool)
}

/// A pool's status, its settings read from its directory the first time.
fn entry<'a>(map: &'a mut BTreeMap<String, Status>, pool: &str) -> &'a mut Status {
map.entry(pool.to_string()).or_insert_with(|| Status {
settings: Settings::load(&dir(pool)),
unavailable: NOT_SHARED,
..Status::default()
})
}
Expand All @@ -101,28 +99,19 @@ fn now_ms() -> u128 {

/// Start measuring and reporting, once per hub.
pub fn start() {
let (tx, rx) = mpsc::channel();
if SHARING
.set(Sharing {
status: Mutex::new(BTreeMap::new()),
poke: Mutex::new(tx),
})
.is_err()
{
if STATUS.set(Mutex::new(BTreeMap::new())).is_err() {
return;
}
std::thread::spawn(move || run(&rx));
std::thread::spawn(run);
}

fn run(poked: &mpsc::Receiver<()>) {
fn run() {
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
let mut before = devstack_proc::cpu_times();
// The first CPU reading needs a second one to say anything.
let mut wait = Duration::from_secs(2);
loop {
if let Err(mpsc::RecvTimeoutError::Disconnected) = poked.recv_timeout(wait) {
return;
}
std::thread::sleep(wait);
wait = EVERY;
let after = devstack_proc::cpu_times();
let free = Amount {
Expand All @@ -139,17 +128,14 @@ fn run(poked: &mpsc::Receiver<()>) {
cpus: cores as f64,
memory: devstack_proc::memory_total().unwrap_or(0),
};
let Some(s) = SHARING.get() else { return };
let Some(status) = STATUS.get() else { return };
let gpus = devstack_node::share::gpus();
for (pool, _) in devstack_node::member::pools(&state()) {
let settings = entry(&mut s.status.lock().unwrap(), &pool).settings.clone();
let offer = settings.offer(free);
let result = report(&pool, &settings, offer, total, &gpus);
let mut map = s.status.lock().unwrap();
let result = report(&pool, total, &gpus);
let mut map = status.lock().unwrap();
let st = entry(&mut map, &pool);
st.total = total;
st.free = free;
st.offer = offer;
match result {
Ok(answer) => {
st.member = answer.is_some();
Expand Down Expand Up @@ -185,12 +171,10 @@ fn guests(pool: &str) -> Option<Vec<crate::guests::Guest>> {
Some(crate::guests::of(pool, &m.id, &leases, &nodes))
}

/// Report to the coordinator: what it says it runs; `Ok(None)` when this
/// machine is no approved member (nothing to report to).
/// Report to the coordinator, offering nothing: what it says it runs;
/// `Ok(None)` when this machine is no approved member (nothing to report to).
fn report(
pool: &str,
settings: &Settings,
offer: Amount,
total: Amount,
gpus: &[devstack_node::share::Gpu],
) -> Result<Option<Option<devstack_node::version::Release>>, String> {
Expand All @@ -202,9 +186,9 @@ fn report(
}
local
.report(&Report {
sharing: settings.enabled,
cpus: offer.cpus,
memory: offer.memory,
sharing: false,
cpus: 0.0,
memory: 0,
api: None,
dedicated: false,
devstack: Some(devstack_node::version::Release::this()),
Expand All @@ -219,7 +203,7 @@ fn report(
gpus: gpus
.iter()
.map(|g| devstack_node::share::Gpu {
offered: settings.enabled,
offered: false,
..g.clone()
})
.collect(),
Expand All @@ -236,58 +220,22 @@ pub async fn get(Query(q): Query<PoolQuery>) -> Response {
)
.into_response();
};
match SHARING.get() {
Some(s) => {
let mut map = s.status.lock().unwrap();
match STATUS.get() {
Some(status) => {
let mut map = status.lock().unwrap();
// A pool not reported yet still shows what is measured.
let any = map.values().next().cloned();
let st = entry(&mut map, &pool);
if let Some(a) = any.filter(|_| st.reported_at.is_none() && st.total.cpus == 0.0) {
st.total = a.total;
st.free = a.free;
st.offer = st.settings.offer(a.free);
}
Json(st.clone()).into_response()
}
None => (
StatusCode::SERVICE_UNAVAILABLE,
Json(serde_json::json!({ "error": "sharing has not started" })),
Json(serde_json::json!({ "error": "reporting has not started" })),
)
.into_response(),
}
}

pub async fn put(Query(q): Query<PoolQuery>, Json(new): Json<Settings>) -> Response {
let bad = |m: &str| {
(
StatusCode::BAD_REQUEST,
Json(serde_json::json!({ "error": m })),
)
.into_response()
};
if new.max_cpus.is_some_and(|c| !c.is_finite() || c < 0.0) {
return bad("max_cpus: a number of cores, 0 or more");
}
let Some(pool) = q.name() else {
return bad("pool: a-z, 0-9, `-` and `_`, at most 32");
};
let Some(s) = SHARING.get() else {
return bad("sharing has not started");
};
if let Err(e) = new.save(&dir(&pool)) {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ "error": e.to_string() })),
)
.into_response();
}
let status = {
let mut map = s.status.lock().unwrap();
let st = entry(&mut map, &pool);
st.settings = new;
st.offer = st.settings.offer(st.free);
st.clone()
};
let _ = s.poke.lock().unwrap().send(());
Json(status).into_response()
}
27 changes: 27 additions & 0 deletions crates/devstack/tests/hub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,33 @@ fn down_then_up_at_once_runs_again() {
}
}

/// #169: the hub offers the pool nothing and says why; the share switch is
/// gone until it starts a node agent (#171).
#[test]
fn the_hub_offers_the_pool_nothing_and_says_why() {
let h = start();
let p = h.port;
let bearer = format!("Authorization: Bearer {}\r\n", token(&h));
let (s, _, body) = get(p, "/hub/pool/share", &bearer);
assert_eq!(s, 200, "{body}");
let v: serde_json::Value = serde_json::from_str(&body).unwrap();
let why = v["unavailable"].as_str().unwrap_or("");
assert!(why.contains("#171") && !why.contains(" "), "{v}");
assert!(
v.get("settings").is_none() && v.get("offer").is_none(),
"{v}"
);
let body = r#"{"enabled":true}"#;
let (s, _, _) = http(
p,
&format!(
"PUT /hub/pool/share HTTP/1.1\r\nHost: 127.0.0.1:{p}\r\n{bearer}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
),
);
assert_eq!(s, 405, "no switch to turn on");
}

/// ADR-0045: the settings over the API, and a link from a notification
/// (`/auth?next=`) that lands on the stack, without a second session for a
/// browser that is paired already.
Expand Down
9 changes: 8 additions & 1 deletion docs/adr/0031-a-coordinator-places-lanes.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# ADR-0031: A coordinator places lanes and admits members; nodes admit leases; data goes directly

- **Status:** Accepted (2026-10-16), amended 2026-10-16 (one binary: `devstack node`), amended 2026-10-19 (point 8: which devstack each party runs)
- **Status:** Accepted (2026-10-16), amended 2026-10-16 (one binary: `devstack node`), amended 2026-10-19 (point 8: which devstack each party runs), amended 2026-10-21 (point 3: no share switch)
- **Date:** 2026-10-16
- **Deciders:** project owner
- **Related:** [ADR-0025](0025-a-lane-can-run-on-another-node.md), [ADR-0026](0026-placement-by-the-requester-admission-by-the-node.md) (points 1 and 3 replaced here), [ADR-0027](0027-trust-between-nodes.md) (points 1 and 2 replaced here), [ADR-0029](0029-source-sync-and-port-forwarding-for-remote-lanes.md), [ADR-0015](0015-devstack-is-optional.md), [ADR-0032](0032-the-pool-is-administered-in-the-dashboard.md) (point 2 extended there: admins in the dashboard, nodes granted)
Expand Down Expand Up @@ -144,3 +144,10 @@ with a slot of this lane (its kept data, ADR-0038), then one with a slot of
the repository (its images and builds), then free capacity for the need.
Nodes report their slots and their free disk; the lease offer says `why`;
`GET /v1/placement` gives the order to the dashboard.

*Amended 2026-10-21.* Point 3's share switch is removed from the dashboard.
It reported capacity but never started a node agent, so no lane ever ran on
a machine that only switched it on (on Windows none can, #168). A machine
shares by running a node agent an admin granted (ADR-0032); the hub reports
the machine and offers nothing (`crates/devstack-hub/src/share.rs`). A
switch that starts the agent is #171, and comes with its own ADR.
2 changes: 1 addition & 1 deletion docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ stay.
| [0028](0028-lane-images.md) | A remote lane runs in a stack-provided toolchain image; the node supplies devstack | Accepted, amended (a Dockerfile the node builds) |
| [0029](0029-source-sync-and-port-forwarding-for-remote-lanes.md) | A remote lane works on a mirror of the requester's tree; ports and API come back over one connection | Accepted; point 2 amended (`[lanes] sync`); Consequences built by ADR-0038 |
| [0030](0030-each-lane-has-its-own-infrastructure.md) | Each lane has its own infrastructure | Accepted |
| [0031](0031-a-coordinator-places-lanes.md) | A coordinator places lanes and admits members; nodes admit leases; data goes directly | Accepted, amended (one binary: `devstack node`), amended 2026-10-19 (versions in the pool) |
| [0031](0031-a-coordinator-places-lanes.md) | A coordinator places lanes and admits members; nodes admit leases; data goes directly | Accepted, amended (one binary: `devstack node`), amended 2026-10-19 (versions in the pool), amended 2026-10-21 (no share switch) |
| [0032](0032-the-pool-is-administered-in-the-dashboard.md) | The pool is administered in the dashboard, by members with the admin role | Accepted, amended (admins grant nodes); extended by ADR-0039 (updating a server) |
| [0033](0033-a-node-decides-what-runs-on-it.md) | A node decides who runs lanes on it, and what a lane there may do | Accepted, amended (what Compose files may ask; limits; the node's own policy; amended 2026-10-20: the node runs the model it checked, known keys only, a lane's projects end with it; noted 2026-10-21: what holds while a lane's containers start under its running daemon) |
| [0034](0034-a-machine-can-belong-to-several-pools.md) | A machine can belong to several pools; pools do not trust each other | Accepted; noted 2026-10-20 (several agents on one Docker engine) |
Expand Down
2 changes: 1 addition & 1 deletion docs/dashboard-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script.
| `POST /hub/pool/nodes/{id}/policy` (a `NodePolicy` or `null`) | cookie + Origin | admins only: what the node lets run on it, `{allow, repos, memory_headroom?, max_cpus?, network: "lan"\|"internet"\|"none"}`; `null` lifts it |
| `POST /hub/pool/join {"coordinator", "fingerprint", "name"?}` | cookie + Origin | ask a pool to admit this machine (`devstack join` without waiting); `GET /hub/pool` shows it pending until an admin approves. `coordinator` is `https://<host>[:<port>]` and nothing more (`400` otherwise). Errors of every `/hub/pool...` route pass on the coordinator's own `{"error"}` only, never the body of whatever else answered |
| `POST /hub/pool/members/{id}/role {"role"}` | cookie + Origin | admins only: `member` or `admin`; `409 {"error"}` for the last admin. A member who is no admin gets `403` from all three |
| `GET /hub/pool/share`, `PUT /hub/pool/share {enabled, max_cpus?, max_memory?}` | cookie (+ Origin for `PUT`) | this machine's share of the pool (ADR-0031 point 3), per pool: the switch, the caps, what is free and offered now, the last report (`ShareStatus`, with `coordinator?`: the `PoolRelease` the coordinator answered the last report with, absent from an older one); `PUT` changes them and reports at once |
| `GET /hub/pool/share?pool=` | cookie | this machine in the pool, per pool: what it has and what is free (`total`, `free`), whether it is an approved member, the last report (`reported_at`, `error`), the `PoolRelease` the coordinator answered it with (`coordinator?`), and why it offers nothing (`unavailable`: a node agent runs lanes, the dashboard does not start one yet, [#171](https://github.com/nuetzliches/devstack/issues/171)). The share switch and its `PUT` are gone (#169) |
| `POST /hub/shutdown` | `Authorization: Bearer <user token>` | `202`; the hub exits (`devstack hub stop`) |
| `POST /hub/pair` | `Authorization: Bearer <user token>` | `{"code": "...", "url": "http://127.0.0.1:4250/auth?code=..."}` (CLI only) |

Expand Down
11 changes: 8 additions & 3 deletions docs/pool.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,14 @@ The dashboard's **Pool** area does the same with a
form. `devstack pool` then lists the machines, what each offers, and which
lanes run where.

A member that only asks for lanes needs nothing else. The **share switch**
(sidebar, pool area) lets the pool run other members' lanes on your machine:
half of what is free, never more than the caps you set; off by default.
A member that only asks for lanes needs nothing else. A machine runs other
members' lanes only with a node agent, below. The dashboard has no switch for
that: the share switch it had only reported capacity, never started an agent,
and is gone until it does
([#171](https://github.com/nuetzliches/devstack/issues/171); on Windows,
which cannot run the Linux lanes yet,
[#168](https://github.com/nuetzliches/devstack/issues/168)). The hub reports
the machine (online, what it has, its devstack) and offers nothing.

Lanes of other members on your machine always show: a banner below the
dashboard's top bar (it can be hidden until a lane comes or goes), a tile in
Expand Down
Loading