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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ windows = { version = "0.62", features = ["Data_Xml_Dom", "Foundation", "UI_Noti
zbus = { version = "6", default-features = false, features = ["tokio", "proxy"] }
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_NetworkManagement_IpHelper",
"Win32_Security",
"Win32_Storage_FileSystem",
"Win32_System_ProcessStatus",
Expand Down
12 changes: 6 additions & 6 deletions crates/devstack-daemon/src/supervisor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1030,6 +1030,8 @@ fn topo(deps: BTreeMap<String, Vec<String>>) -> Vec<String> {
/// Taken on IPv4 or IPv6 loopback. A dev server bound to `localhost` may hold
/// only `::1` (Node on Windows); binding `127.0.0.1` would still succeed. A host
/// without IPv6 fails the `::1` bind with another error, which is not "in use".
/// A port held on every address (`0.0.0.0`) is told on Windows by the table
/// of listeners, on macOS by a connect (#226).
pub fn port_in_use(port: u16) -> bool {
// Windows reports a port held exclusively by another process as access denied.
let taken = |r: std::io::Result<std::net::TcpListener>| {
Expand All @@ -1042,6 +1044,7 @@ pub fn port_in_use(port: u16) -> bool {
};
taken(std::net::TcpListener::bind(("127.0.0.1", port)))
|| taken(std::net::TcpListener::bind(("::1", port)))
|| (cfg!(windows) && devstack_proc::tcp_listening(port))
|| (cfg!(target_os = "macos") && answers_locally(port))
}

Expand Down Expand Up @@ -1233,14 +1236,11 @@ mod port_tests {
assert!(!super::port_in_use(port));
}

// Not on Windows: there a bind on 127.0.0.1 succeeds too while the same
// user listens on 0.0.0.0, and a connect probe would take seconds per
// closed port; not covered yet.
#[cfg(not(windows))]
#[test]
fn a_port_held_on_every_address_is_in_use() {
// Docker's published ports, a dev server on 0.0.0.0. With BSD sockets
// (macOS) a bind on 127.0.0.1 still succeeds; the connect tells.
// Docker's published ports, a dev server on 0.0.0.0. On Windows and
// with BSD sockets (macOS) a bind on 127.0.0.1 still succeeds; the
// table of listeners tells (Windows), or a connect (macOS).
let l = std::net::TcpListener::bind(("0.0.0.0", 0)).unwrap();
let port = l.local_addr().unwrap().port();
assert!(super::port_in_use(port));
Expand Down
244 changes: 228 additions & 16 deletions crates/devstack-hub/src/share.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
//! 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.
//! in no pool, or not approved yet, reports nothing. Nor does the hub for a
//! pool while a node agent of the same membership runs here: the agent
//! reports the machine then, with its API and its leases, which a report of
//! the hub's would drop (#170).
//!
//! 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
Expand Down Expand Up @@ -44,6 +47,9 @@ pub struct Status {
pub reported_at: Option<u128>,
/// Why the last report failed.
pub error: Option<String>,
/// A node agent of this membership runs here and reports the machine;
/// the hub does not (#170).
pub agent: bool,
/// The devstack the coordinator runs, from its answer to the last
/// report; `None` before one, or from an older coordinator.
#[serde(skip_serializing_if = "Option::is_none")]
Expand Down Expand Up @@ -131,19 +137,26 @@ fn run() {
let Some(status) = STATUS.get() else { return };
let gpus = devstack_node::share::gpus();
for (pool, _) in devstack_node::member::pools(&state()) {
let result = report(&pool, total, &gpus);
let result = round(&dir(&pool), total, &gpus);
let mut map = status.lock().unwrap();
let st = entry(&mut map, &pool);
st.total = total;
st.free = free;
st.agent = matches!(result, Ok(Round::Agent));
match result {
Ok(answer) => {
st.member = answer.is_some();
Ok(Round::NoMember) => {
st.member = false;
st.error = None;
if let Some(coordinator) = answer {
st.reported_at = Some(now_ms());
st.coordinator = coordinator;
}
}
Ok(Round::Agent) => {
st.member = true;
st.error = None;
}
Ok(Round::Reported(coordinator)) => {
st.member = true;
st.error = None;
st.reported_at = Some(now_ms());
st.coordinator = coordinator;
}
Err(e) => st.error = Some(e),
}
Expand Down Expand Up @@ -171,19 +184,36 @@ fn guests(pool: &str) -> Option<Vec<crate::guests::Guest>> {
Some(crate::guests::of(pool, &m.id, &leases, &nodes))
}

/// 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,
/// What one round did for a pool.
#[derive(Debug, PartialEq)]
enum Round {
/// This machine is no approved member: nothing to report to.
NoMember,
/// A node agent of the membership runs here and reports (#170).
Agent,
/// Reported; what the coordinator says it runs.
Reported(Option<devstack_node::version::Release>),
}

/// Report the membership in `dir` to the coordinator, offering nothing,
/// unless a node agent of it runs here. Its report carries no API and no
/// leases: sent while the agent runs, the coordinator would take the node
/// for one without an agent and drop its leases until the agent's next
/// report, which brings them back new, without their sharing.
fn round(
dir: &std::path::Path,
total: Amount,
gpus: &[devstack_node::share::Gpu],
) -> Result<Option<Option<devstack_node::version::Release>>, String> {
let local = devstack_node::member::Local::new(&dir(pool));
) -> Result<Round, String> {
let local = devstack_node::member::Local::new(dir);
match local.membership() {
Ok(Some(m)) if m.state == State::Approved => {}
Ok(_) => return Ok(None),
Ok(_) => return Ok(Round::NoMember),
Err(e) => return Err(e.to_string()),
}
if devstack_node::node::agent_runs(dir) {
return Ok(Round::Agent);
}
local
.report(&Report {
sharing: false,
Expand All @@ -210,7 +240,7 @@ fn report(
})
.collect(),
})
.map(|a| Some(a.coordinator))
.map(|a| Round::Reported(a.coordinator))
.map_err(|e| e.to_string())
}

Expand Down Expand Up @@ -241,3 +271,185 @@ pub async fn get(Query(q): Query<PoolQuery>) -> Response {
.into_response(),
}
}

#[cfg(test)]
mod tests {
use super::{Round, round};
use devstack_node::coordinator::{self, LeaseRequest, SharedService, Sharing};
use devstack_node::member::Local;
use devstack_node::node::{self, NodeConfig};
use devstack_node::nodeclient::NodeClient;
use devstack_node::share::{Amount, Need, Settings};
use devstack_node::store::{SHELL, Store};
use std::path::Path;
use std::time::{Duration, Instant};

fn rt() -> tokio::runtime::Runtime {
tokio::runtime::Runtime::new().unwrap()
}

fn wait_for(secs: u64, what: &str, mut f: impl FnMut() -> bool) {
let until = Instant::now() + Duration::from_secs(secs);
while !f() {
assert!(Instant::now() < until, "{what}");
std::thread::sleep(Duration::from_millis(200));
}
}

/// A machine in `dir` that joined and was approved.
fn member(coord: &Path, url: &str, fp: &str, dir: &Path, name: &str) -> Local {
let l = Local::new(dir);
let m = l.join(url, fp, name).unwrap();
Store::new(coord)
.approve(&m.id, &coordinator::ca(coord).unwrap(), None, SHELL)
.unwrap();
l.refresh().unwrap();
l
}

/// A machine that runs the hub and a node agent of the same membership
/// (#170): while the agent runs, the hub does not report, so the node
/// keeps its API, and a running lease its `created` and its sharing,
/// across the hub's rounds. Once the agent is gone, the hub reports.
#[test]
fn the_hub_does_not_report_over_a_node_agent_of_the_same_member() {
let c = tempfile::tempdir().unwrap();
let fp = coordinator::init(c.path(), &["127.0.0.1".into()]).unwrap();
let rt_coord = rt();
let listener = rt_coord
.block_on(tokio::net::TcpListener::bind(("127.0.0.1", 0)))
.unwrap();
let url = format!(
"https://127.0.0.1:{}",
listener.local_addr().unwrap().port()
);
let cdir = c.path().to_path_buf();
std::thread::spawn(move || {
rt_coord
.block_on(coordinator::serve(&cdir, listener, std::future::pending()))
.unwrap();
});
let (md, rd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let machine = member(c.path(), &url, &fp, md.path(), "dev-box");
let requester = member(c.path(), &url, &fp, rd.path(), "laptop");
let id = machine.membership().unwrap().unwrap().id;
Store::new(c.path()).set_node(&id, true, SHELL).unwrap();
let total = Amount {
cpus: 8.0,
memory: 16 << 30,
};

// No agent yet: the hub reports the machine.
assert!(matches!(
round(md.path(), total, &[]),
Ok(Round::Reported(_))
));

// The agent of the same membership, until `stop`.
let rt_node = rt();
let listener = rt_node
.block_on(tokio::net::TcpListener::bind(("127.0.0.1", 0)))
.unwrap();
let api = format!(
"https://127.0.0.1:{}",
listener.local_addr().unwrap().port()
);
let config = NodeConfig {
on_update: None,
dir: md.path().to_path_buf(),
api: api.clone(),
share: Settings {
enabled: true,
max_cpus: Some(4.0),
max_memory: Some(4 << 30),
},
dedicated: false,
};
let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
let agent = std::thread::spawn(move || {
rt_node
.block_on(node::serve(config, listener, async {
let _ = stopped.await;
}))
.unwrap();
});
let node_api = || {
requester
.nodes()
.unwrap()
.into_iter()
.find(|n| n.id == id)
.and_then(|n| n.report.and_then(|r| r.api))
};
wait_for(20, "the agent reports its API", || {
node_api().as_deref() == Some(api.as_str())
});

// A running lease on it, shared.
let offer = requester
.lease(&LeaseRequest {
node: "dev-box".into(),
repo: "shop".into(),
lane: "fix".into(),
need: Need {
cpus: 0.1,
memory: 64 << 20,
..Need::default()
},
need_from: None,
floor: None,
profile: None,
devstack: None,
})
.unwrap();
let rt = rt();
let client = NodeClient::new(&requester, offer.node.clone()).unwrap();
rt.block_on(client.admit(&offer)).unwrap();
let sharing = Sharing::new(
vec!["*".into()],
vec![SharedService {
name: "web".into(),
port: 5173,
scheme: "http".into(),
here: 5273,
}],
);
requester.share_lease(&offer.id, Some(&sharing)).unwrap();
let lease = || {
requester
.leases()
.unwrap()
.into_iter()
.find(|l| l.node == id && l.lane == "fix")
};
wait_for(20, "the agent reports the lease running", || {
lease().is_some_and(|l| l.state == "running")
});
let before = lease().unwrap();
assert_eq!(before.shared.as_ref(), Some(&sharing));
// A lease the coordinator took for new would have a later `created`.
std::thread::sleep(Duration::from_millis(1100));

// The hub's rounds leave the node to its agent.
for _ in 0..3 {
assert_eq!(round(md.path(), total, &[]), Ok(Round::Agent));
assert_eq!(node_api().as_deref(), Some(api.as_str()), "the API stays");
let now = lease().expect("the lease stays");
assert_eq!(
(now.id.as_str(), now.created, now.shared.as_ref()),
(before.id.as_str(), before.created, Some(&sharing))
);
std::thread::sleep(Duration::from_millis(300));
}

// The agent stops: the hub reports the machine again.
let _ = stop.send(());
agent.join().unwrap();
assert!(!node::agent_runs(md.path()));
assert!(matches!(
round(md.path(), total, &[]),
Ok(Round::Reported(_))
));
assert_eq!(node_api(), None, "a hub's report has no API");
}
}
34 changes: 34 additions & 0 deletions crates/devstack-node/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3601,6 +3601,37 @@ fn restart_on(binary: &Path) -> String {
}
}

/// Whether a node agent runs for the membership in `dir` (`pool/` or
/// `pools/<name>/` in devstack's per-user state): it holds `node/lock`
/// while it runs. The hub on the same machine then does not report for that
/// pool; the agent reports the machine (#170).
pub fn agent_runs(dir: &Path) -> bool {
devstack_proc::StateLock::held(&dir.join("node"))
}

/// The agent's lock in `root` (its `node/` directory). Held a moment longer
/// by the agent it replaces (a restart after an update, on Windows a new
/// process) or by a hub that looks whether it is held: tried again for a few
/// seconds.
async fn agent_lock(root: &Path) -> Result<devstack_proc::StateLock, NodeError> {
let t0 = Instant::now();
loop {
match devstack_proc::StateLock::acquire(root) {
Ok(l) => return Ok(l),
Err(devstack_proc::LockError::Held(_)) if t0.elapsed() < Duration::from_secs(10) => {
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(devstack_proc::LockError::Held(p)) => {
return Err(NodeError::Other(format!(
"a node agent of this member runs already ({} is held)",
p.display()
)));
}
Err(e) => return Err(NodeError::Other(e.to_string())),
}
}
}

/// Run the node agent of the member in `config.dir` on `listener` until
/// `stop` resolves.
pub async fn serve(
Expand Down Expand Up @@ -3629,6 +3660,9 @@ pub async fn serve(
)
.map_err(|e| NodeError::Other(e.to_string()))?;
let root = config.dir.join("node");
// One reporter per machine and pool (#170): while it is held, the hub
// does not report for this membership.
let _lock = agent_lock(&root).await?;
std::fs::create_dir_all(root.join("lanes")).map_err(|e| NodeError::Io(root.clone(), e))?;
let leases: HashMap<String, NodeLease> = std::fs::read(root.join("leases.json"))
.ok()
Expand Down
Loading
Loading