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

### Fixed

- **A running job shows what it uses, and that it runs** (#544). A
`kind = "job"` stayed "starting" with no CPU or memory for its whole run
(hours for a training job), because only a started instance was measured.
It now shows "running" from its launch until it ends, with its process
tree's usage in the dashboard, the lane card and `/v1/usage`; a service
waiting for its health check is measured too. A command that `requires` a
job still waits until the job completed.
- **A lane started here no longer lands on ports another stack claims for
its lane on a node** (#535). Its start checked only whether one of its
ports was in use at that moment; a lane on a node forwards its ports here
Expand Down
11 changes: 6 additions & 5 deletions crates/devstack-daemon/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,12 @@ pub fn start(
}
let view = sup.view();
for r in &cmd.requires {
if !view
.services
.iter()
.any(|s| &s.name == r && s.status.is_ready())
{
// A job is ready once it completed, not while it runs (#544).
let ready = |s: &crate::state::ServiceView| match s.kind.as_str() {
"job" => s.status == crate::state::Status::Completed { exit_code: 0 },
_ => s.status.is_ready(),
};
if !view.services.iter().any(|s| &s.name == r && ready(s)) {
return Err(RunError::NotReady(r.clone()));
}
}
Expand Down
6 changes: 4 additions & 2 deletions crates/devstack-daemon/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@ pub enum Status {
Building {
build_id: Option<String>,
},
/// Process started, waiting for health (or for a job to finish).
/// Process started, waiting for health.
Starting,
/// Running without a health check (tools, services without `health`).
/// Running without a health check (tools, services without `health`),
/// or a job running until it ends (#544; ready for its dependants only
/// once `Completed`).
Running,
Healthy,
Unhealthy {
Expand Down
93 changes: 92 additions & 1 deletion crates/devstack-daemon/src/supervisor/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,14 @@ impl Supervisor {
v.instance_port = inst.port;
}
self.set_status(name, Status::Starting);
let ready = match self.wait_instance(svc, &mut inst, &cancel) {
// A job runs from here until it ends (#544): `starting` for its
// whole run read as stuck.
if svc.kind == Kind::Job {
self.set_status(name, Status::Running);
}
let waited = self.wait_instance(svc, &mut inst, &cancel, Some(name));
self.set_starting_usage(name, None);
let ready = match waited {
Ok(s) => s,
Err(e) => {
self.end(&mut inst, None);
Expand Down Expand Up @@ -1087,17 +1094,34 @@ impl Supervisor {
/// the proxy: ADR-0010 condition 1), else a moment to fail fast. Returns the
/// status to show. A job runs for its `timeout` at most; `cancel` (a
/// stop) ends the wait at once. The caller kills the instance on an error.
/// `record`: the service whose start this is; what the instance uses is
/// noted for it while the wait lasts (#544), every [`NATIVE_EVERY`] as
/// the usage sampler asks. A candidate's wait notes nothing: its
/// service's main instance is measured meanwhile.
///
/// [`NATIVE_EVERY`]: crate::usage::NATIVE_EVERY
pub(super) fn wait_instance(
&self,
svc: &Service,
inst: &mut Instance,
cancel: &dyn Fn() -> bool,
record: Option<&str>,
) -> Result<Status, String> {
let mut sampled: Option<Instant> = None;
let mut sample = |inst: &mut Instance| {
if let Some(name) = record
&& sampled.is_none_or(|t| t.elapsed() >= crate::usage::NATIVE_EVERY)
{
self.set_starting_usage(name, Some(inst.tree.usage()));
sampled = Some(Instant::now());
}
};
match svc.kind {
Kind::Job => {
let limit = svc.timeout.unwrap_or(JOB_TIMEOUT);
let t0 = Instant::now();
loop {
sample(inst);
if let Some(code) = inst.tree.try_exit_code() {
if code == 0 {
return Ok(Status::Completed { exit_code: 0 });
Expand Down Expand Up @@ -1126,6 +1150,7 @@ impl Supervisor {
let t0 = Instant::now();
let mut last = String::new();
while t0.elapsed() < h.timeout {
sample(inst);
if cancel() {
return Err(STOPPED.into());
}
Expand Down Expand Up @@ -1585,3 +1610,69 @@ fn port_freed(port: u16) -> bool {
}
true
}

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

/// #544: a job that runs shows `running` and its process tree's usage
/// while it runs, not `starting` with nothing; once done, `completed`,
/// and its usage is gone with it. Windows only: elsewhere a process is
/// started through devstack's shim, a binary a unit test does not have;
/// the daemon's integration test sees the same on every platform.
#[test]
fn a_running_job_shows_running_and_what_it_uses() {
let d = tempfile::tempdir().unwrap();
let file = d.path().join("devstack.toml");
let run = if cfg!(windows) {
"ping -n 4 127.0.0.1 > NUL"
} else {
"sleep 3"
};
let text = format!(
"version = 1\n[stack]\nname = \"s\"\n[services.burn]\nkind = \"job\"\nrun = '{run}'\n"
);
let stack = devstack_config::from_str(&text, &file).unwrap();
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
let sup = Supervisor::new(
stack,
file,
d.path().to_path_buf(),
d.path().join(".devstack"),
devstack_proc::Options::default(),
rt.handle().clone(),
)
.unwrap();
let status = |sup: &Supervisor| {
sup.view()
.services
.into_iter()
.find(|s| s.name == "burn")
.unwrap()
.status
};
let measured = |sup: &Supervisor| {
sup.tree_usage()
.iter()
.any(|(n, u)| n == "burn" && u.processes > 0)
};
let s = sup.clone();
let start = std::thread::spawn(move || s.start("burn"));
let (mut running, mut used) = (false, false);
let t0 = Instant::now();
while t0.elapsed() < Duration::from_millis(2500) && !(running && used) {
running |= status(&sup) == Status::Running;
used |= measured(&sup);
std::thread::sleep(Duration::from_millis(50));
}
let started = start.join().unwrap();
assert!(started.is_ok(), "{started:?}");
assert!(running, "running while it ran");
assert!(used, "measured while it ran");
assert_eq!(status(&sup), Status::Completed { exit_code: 0 });
assert!(!measured(&sup), "no usage once done");
}
}
24 changes: 23 additions & 1 deletion crates/devstack-daemon/src/supervisor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ pub(crate) struct Slot {
/// A job: when its last successful run was asked for (Unix ms). A
/// candidate built after that needs no run of its own.
ran_since: Option<u128>,
/// What the instance being started uses, sampled while its start waits:
/// a job for its whole run, a service for its health check (#544). Its
/// tree is the start's own until then, so `main` has none to measure.
starting_usage: Option<devstack_proc::Usage>,
}

/// A built candidate a promotion gate holds (ADR-0013). The gate stays until
Expand Down Expand Up @@ -483,6 +487,7 @@ impl Supervisor {
exits: 0,
without_workers: None,
ran_since: None,
starting_usage: None,
},
);
op_locks.insert(name.clone(), Mutex::new(()));
Expand Down Expand Up @@ -824,6 +829,9 @@ impl Supervisor {
slot.starts += 1;
None
}
// A job runs once launched (#544): its start is over when it
// ends, so the start's duration is its run, as before.
Status::Running if slot.view.kind == "job" => None,
_ => slot
.spawned
.take()
Expand Down Expand Up @@ -1058,10 +1066,24 @@ impl Supervisor {
.lock()
.unwrap()
.iter_mut()
.filter_map(|(name, slot)| slot.main.as_mut().map(|i| (name.clone(), i.tree.usage())))
.filter_map(|(name, slot)| {
let usage = match slot.main.as_mut() {
Some(i) => i.tree.usage(),
None => slot.starting_usage?,
};
Some((name.clone(), usage))
})
.collect()
}

/// Note what the instance of `name` that is being started uses now
/// ([`Slot::starting_usage`]); `None` clears it once the start is over.
pub(super) fn set_starting_usage(&self, name: &str, usage: Option<devstack_proc::Usage>) {
if let Some(slot) = self.slots.lock().unwrap().get_mut(name) {
slot.starting_usage = usage;
}
}

pub(crate) fn build_usage(&self) -> devstack_proc::Usage {
self.builder.usage()
}
Expand Down
4 changes: 2 additions & 2 deletions crates/devstack-daemon/src/supervisor/replace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ The running instance was left as it was."
Ok(i) => i,
Err(e) => return fail(e),
};
if let Err(e) = self.wait_instance(svc, &mut candidate, &cancel) {
if let Err(e) = self.wait_instance(svc, &mut candidate, &cancel, None) {
self.end(&mut candidate, None);
return fail(e);
}
Expand All @@ -250,7 +250,7 @@ The running instance was left as it was."
Ok(i) => i,
Err(e) => return self.running_without_workers(name, svc, e),
};
if let Err(e) = self.wait_instance(svc, &mut fin, &cancel) {
if let Err(e) = self.wait_instance(svc, &mut fin, &cancel, None) {
self.end(&mut fin, None);
return self.running_without_workers(name, svc, e);
}
Expand Down
2 changes: 2 additions & 0 deletions crates/devstack/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1321,6 +1321,8 @@ pub fn start_and_wait(
if expected.contains(&name) {
let state = s["status"]["state"].as_str().unwrap_or("");
match state {
// A job runs until it ends (#544): `up` waits for it.
"running" if s["kind"] == "job" => done = false,
"healthy" | "running" => {}
"stopped" if served_elsewhere => {}
"completed" if s["status"]["exit_code"] == 0 => {}
Expand Down
24 changes: 21 additions & 3 deletions crates/devstack/tests/daemon_lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1423,7 +1423,25 @@ steps = [{{ exec = "{hang}", timeout = "1s" }}]
});
assert!(
wait_for(
|| s.service_view("seed")["status"]["state"] == "starting",
// A job runs from its launch (#544).
|| s.service_view("seed")["status"]["state"] == "running",
Duration::from_secs(20)
),
"{}",
s.diag()
);
// And is measured while it runs (#544).
assert!(
wait_for(
|| {
s.daemon_get("/v1/usage")["services"]
.as_array()
.is_some_and(|a| {
a.iter().any(|e| {
e["name"] == "seed" && e["processes"].as_u64().unwrap_or(0) >= 1
})
})
},
Duration::from_secs(20)
),
"{}",
Expand Down Expand Up @@ -2514,7 +2532,7 @@ fn a_stop_while_the_migrator_runs_holds() {
assert_eq!(s.state("app"), "running", "{}", s.diag());
s.edit_site("<p>a change with a migration</p>");
assert!(
wait_for(|| s.state("migrate") == "starting", Duration::from_secs(60)),
wait_for(|| s.state("migrate") == "running", Duration::from_secs(60)),
"the candidate runs the migrator\n{}",
s.diag()
);
Expand Down Expand Up @@ -2571,7 +2589,7 @@ fn a_stop_while_a_restart_migrates_leaves_no_candidate() {
.unwrap()
});
assert!(
wait_for(|| s.state("migrate") == "starting", Duration::from_secs(60)),
wait_for(|| s.state("migrate") == "running", Duration::from_secs(60)),
"the restart runs the migrator\n{}",
s.diag()
);
Expand Down
2 changes: 1 addition & 1 deletion docs/dashboard-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ type PrepareView = {
stored?: true; // `run`: what it made went into the store
};
type Status =
| { state: "stopped" | "starting" | "running" | "healthy" }
| { state: "stopped" | "starting" | "running" | "healthy" } // a job: "running" from its launch until it ends (since 0.48.0; "starting" before)
| { state: "building"; build_id: string | null }
| { state: "unhealthy" | "failed"; reason: string }
| { state: "completed" | "exited"; exit_code: number };
Expand Down
Loading