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

## [Unreleased]

### Added

- **Restart, Rebuild, Cold** ([ADR-0072](docs/adr/0072-a-restart-is-warm-a-rebuild-or-cold.md)):
every restart button in the dashboard (a service row, a group's head, a
lane's header) is a split button. A click restarts warm, from the build
there is for the inputs, the data kept; its arrow offers Rebuild (built
again even for inputs built before, the data kept) and, for a lane,
Cold (built again and seeded again; asks first). The command palette has
them too.
- **A lane restarts where it runs**: `POST /v1/lanes/{lane}/restart` with
`{"mode": "warm" | "rebuild" | "cold"}`. On a node a warm restart and a
rebuild go through the lane's own API, so its lease, node and ports
stay; a cold restart stops it, throws its data away and starts it again
at the same place. A group has `rebuild` too
(`POST /v1/groups/{name}/rebuild`, `devstack restart --rebuild <group>`).
- **A lane's actions in one menu**: the header's Restart (Start for a
stopped lane) has Rebuild, Cold…, Stop, Discard data… and Remove
worktree… in its menu; the same menu opens from a lane's "…" button or a
right click on its row in the branch picker. The separate "Stop
worktree" and "Discard data" buttons are gone.

### Changed

- **A group's start and stop take its containers along**, as its restart
did: `devstack start|stop <group>` and the group's buttons start its
containers before its services and stop them after (a lane leaves the
main tree's `shared` ones alone). A group of containers only gets its
buttons in the overview now. A lane on a node needs a node with devstack
0.28.0 or later for this.

### Fixed

- **A lane on a node keeps its journal** (#287): the requester's take of
Expand Down
50 changes: 47 additions & 3 deletions crates/devstack-daemon/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub fn router(state: AppState) -> axum::Router {
.route("/v1/lanes", get(lanes_list).post(lanes_start))
.route("/v1/lanes/{lane}/stop", post(lanes_stop))
.route("/v1/lanes/{lane}/reset", post(lanes_reset))
.route("/v1/lanes/{lane}/restart", post(lanes_restart))
.route("/v1/lanes/prune", post(lanes_prune))
.route("/v1/lanes/{lane}/move", post(lanes_move))
.route("/v1/lanes/{lane}/share", post(lanes_share))
Expand Down Expand Up @@ -878,6 +879,49 @@ async fn lanes_reset(State(s): State<AppState>, Path(lane): Path<String>) -> Res
}
}

#[derive(Deserialize, Default)]
struct LaneRestart {
/// `warm` (absent), `rebuild` or `cold`.
#[serde(default)]
mode: Option<String>,
}

/// `POST /v1/lanes/{lane}/restart` with `{"mode"}`: restart a started lane
/// where it runs (`warm`: its running services, from the artifacts there
/// are; `rebuild`: built again; `cold`: stopped, its data thrown away and
/// started again at the same place). `warm` and `rebuild` answer when the
/// services ran, `cold` once the lane is started again (its services start
/// after, on a node its `moving` shows the start). The lanes after it.
async fn lanes_restart(
State(s): State<AppState>,
Path(lane): Path<String>,
body: Option<Json<LaneRestart>>,
) -> Response {
let lanes = match lanes_of(&s) {
Ok(l) => l.clone(),
Err(r) => return r,
};
let mode = body.and_then(|b| b.0.mode).unwrap_or_else(|| "warm".into());
if !matches!(mode.as_str(), "warm" | "rebuild" | "cold") {
return err(
StatusCode::BAD_REQUEST,
format!("mode `{mode}`: `warm`, `rebuild` or `cold`"),
);
}
let main = s.sup.clone();
let usage = s.usage.clone();
let res = tokio::task::spawn_blocking(move || {
let need = lane_estimate(&main, &usage);
lanes.restart(&lane, &mode, need).map(|()| lanes.list())
})
.await;
match res {
Ok(Ok(v)) => Json(v).into_response(),
Ok(Err(e)) => err(StatusCode::CONFLICT, e),
Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
}
}

#[derive(Deserialize, Default)]
struct Prune {
/// Also kept lanes on nodes not used for this long (`7d`, `36h`).
Expand Down Expand Up @@ -1117,8 +1161,8 @@ async fn service_env(
}
}

/// `POST /v1/groups/{name}/{start|stop|restart}`: every member; `409` names
/// the members that failed (the others ran).
/// `POST /v1/groups/{name}/{start|stop|restart|rebuild}`: every member,
/// its containers too; `409` names the members that failed (the others ran).
/// The node's agent acted on the containers this request names already
/// (a lane on a node, #128): its daemon, which has no Docker, leaves them.
fn node_acted(headers: &axum::http::HeaderMap) -> bool {
Expand All @@ -1134,7 +1178,7 @@ async fn group_action(
if !s.sup.stack.groups.contains_key(&name) {
return err(StatusCode::NOT_FOUND, format!("no group `{name}`"));
}
if !matches!(action.as_str(), "start" | "stop" | "restart") {
if !matches!(action.as_str(), "start" | "stop" | "restart" | "rebuild") {
return err(
StatusCode::NOT_FOUND,
format!("unknown group action `{action}`"),
Expand Down
117 changes: 117 additions & 0 deletions crates/devstack-daemon/src/lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2137,6 +2137,123 @@ impl Lanes {
result
}

/// Restart a started lane where it runs (`POST /v1/lanes/{lane}/restart`):
/// `warm` restarts its running services in place, from the artifacts
/// there are for their inputs, its data kept; `rebuild` builds them
/// again even so. On a node through the lane's own API: the lease, the
/// node and the ports stay. `cold` stops it, throws its data away
/// ([`Self::reset`]) and starts it again at the same place, with the
/// same profile and workers: built again and seeded again, as a lane
/// that moves is (ADR-0038). Its containers stay up on `warm` and
/// `rebuild`. `need`: what a start on a node is expected to take.
pub fn restart(
self: &Arc<Self>,
name: &str,
mode: &str,
need: crate::remote::Expected,
) -> Result<(), String> {
let t0 = std::time::Instant::now();
let remote = self.remote(name);
if mode != "cold" {
let rebuild = mode == "rebuild";
let r = match &remote {
Some(r) => r.restart_services(&self.rt, rebuild),
None => self.started(name)?.sup.restart_running(rebuild),
};
crate::diag::info(
"lane_restarted",
serde_json::json!({ "lane": name, "mode": mode,
"place": if remote.is_some() { "remote" } else { "local" },
"ms": t0.elapsed().as_millis() as u64, "ok": r.is_ok() }),
);
return r;
}
// Cold: where it runs, and how, before the stop forgets it.
let on = remote.as_ref().map(|r| r.node.name.clone());
let (path, workers) = match &remote {
Some(_) => (
self.known
.lock()
.unwrap()
.get(name)
.map(|k| k.entry.path.clone())
.ok_or_else(|| format!("no lane `{name}` (see `devstack lane list`)"))?,
self.workers.lock().unwrap().contains(name),
),
None => {
let l = self.started(name)?;
(l.entry.path.clone(), l.sup.lane_workers())
}
};
let profile = self.profiles.lock().unwrap().get(name).cloned();
self.stop(name)?;
let failed: Vec<String> = self
.reset(name)?
.into_iter()
.filter(|p| !p.removed)
.map(|p| {
format!(
"{}: {}",
p.place,
p.error.unwrap_or_else(|| "not removed".into())
)
})
.collect();
if !failed.is_empty() {
return Err(format!(
"lane `{name}` is stopped, but not all of its data went ({}): it was not started again",
failed.join("; ")
));
}
crate::diag::info(
"lane_restarted",
serde_json::json!({ "lane": name, "mode": mode,
"place": if on.is_some() { "remote" } else { "local" } }),
);
match on {
Some(node) => {
self.activate_remote(&path, &node, need, profile.as_deref(), workers)?;
// Its services start once it runs there; `moving` shows the
// start meanwhile, and its error if it fails.
let lanes = self.clone();
let lane = name.to_string();
std::thread::Builder::new()
.name(format!("lane-cold-{name}"))
.spawn(move || {
while lanes.pending.lock().unwrap().contains(&lane) {
std::thread::sleep(std::time::Duration::from_secs(1));
}
if let Some(r) = lanes.remote(&lane)
&& let Err(e) = r.up(&lanes.rt)
{
crate::diag::warn(
"lane_restart_failed",
serde_json::json!({ "lane": lane, "mode": "cold", "error": e }),
);
}
})
.map_err(|e| format!("lane `{name}`: {e}"))?;
}
None => {
let lane = self.activate(&path, profile.as_deref())?;
lane.sup.set_lane_workers(workers);
let sup = lane.sup.clone();
std::thread::Builder::new()
.name(format!("lane-cold-{name}"))
.spawn(move || {
if let Err(e) = sup.up() {
sup.emit(crate::state::EventBody::Infra {
group: "*".into(),
message: format!("up stopped: {e}"),
});
}
})
.map_err(|e| format!("lane `{name}`: {e}"))?;
}
}
Ok(())
}

/// `devstack lane stop`: the lane's services stop and it is no longer
/// started; its snapshot and builds stay for the next start. The worktree
/// is git's business and stays as it is.
Expand Down
107 changes: 104 additions & 3 deletions crates/devstack-daemon/src/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1223,6 +1223,89 @@ impl RemoteLane {
}
}

/// Restart the services that run on the node now, in place, at the same
/// time, through the lane's own API: `restart`, with `rebuild` a
/// `rebuild` of those that run a build. The lease, the node and the
/// ports stay. Errors name the services that failed. Blocking.
pub fn restart_services(
&self,
rt: &tokio::runtime::Handle,
rebuild: bool,
) -> Result<(), String> {
let (status, body) = rt
.block_on(self.client.api(&self.lease, "GET", "/v1/stack", None))
.map_err(|e| format!("lane `{}` on {}: {e}", self.name, self.node.name))?;
if status != 200 {
return Err(format!(
"lane `{}` on {} answered {status}: {body}",
self.name, self.node.name
));
}
let v: serde_json::Value = serde_json::from_str(&body).map_err(|e| e.to_string())?;
let running: Vec<(String, bool)> = v["services"]
.as_array()
.cloned()
.unwrap_or_default()
.iter()
.filter(|s| matches!(s["status"]["state"].as_str(), Some("healthy" | "running")))
.filter_map(|s| {
let name = s["name"].as_str()?.to_string();
// A service that runs a build has its id; one without a
// `build` cannot be rebuilt, only restarted.
Some((name, s["build_id"].as_str().is_some()))
})
.collect();
let failed: Vec<String> = std::thread::scope(|scope| {
let handles: Vec<_> = running
.iter()
.map(|(name, built)| {
let action = if rebuild && *built {
"rebuild"
} else {
"restart"
};
let path = format!("/v1/services/{name}/{action}");
(
name,
scope.spawn(move || {
rt.block_on(self.client.api(&self.lease, "POST", &path, None))
}),
)
})
.collect();
handles
.into_iter()
.filter_map(|(name, h)| match h.join() {
Ok(Ok((200, _))) => None,
Ok(Ok((_, body))) => Some(format!(
"{name}: {}",
serde_json::from_str::<serde_json::Value>(&body)
.ok()
.and_then(|v| v["error"].as_str().map(str::to_string))
.unwrap_or(body)
)),
Ok(Err(e)) => Some(format!("{name}: {e}")),
Err(_) => Some(format!("{name}: panicked")),
})
.collect()
});
if failed.is_empty() {
Ok(())
} else {
Err(failed.join("\n"))
}
}

/// Start the lane's services on the node (`POST /v1/up` there), as a
/// client does after the lane was started. Blocking.
pub fn up(&self, rt: &tokio::runtime::Handle) -> Result<(), String> {
match rt.block_on(self.client.api(&self.lease, "POST", "/v1/up", None)) {
Ok((s, _)) if s < 300 => Ok(()),
Ok((s, body)) => Err(format!("starting its services: {s} {body}")),
Err(e) => Err(e.to_string()),
}
}

/// Its services that run now (healthy or running), read from the lane
/// at once rather than from the last poll. Blocking.
pub fn active_now(&self, rt: &tokio::runtime::Handle) -> Vec<String> {
Expand Down Expand Up @@ -1923,7 +2006,8 @@ impl RemoteLane {
/// The release a node needs to act on the containers `method path` names
/// (`/v1/...` of the lane daemon's API): `/v1/infra/{group}/{service}/…`
/// since #101, a service route that names containers (a group's restart,
/// a Compose service by its name) since #128. `None`: it names none.
/// a Compose service by its name) since #128, a group's start, stop and
/// rebuild that name containers since 0.28.0. `None`: it names none.
fn containers_need(
stack: &devstack_config::Stack,
method: &axum::http::Method,
Expand All @@ -1943,7 +2027,17 @@ fn containers_need(
} else {
Named::Groups
};
(!named(stack, route, name, action).is_empty()).then_some("0.12.0")
if named(stack, route, name, action).is_empty() {
return None;
}
// A group's start and stop took its containers along from
// 0.28.0 on, and its rebuild was new then.
let group = stack.groups.contains_key(*name);
Some(if group && *action != "restart" {
"0.28.0"
} else {
"0.12.0"
})
}
_ => None,
}
Expand Down Expand Up @@ -2390,9 +2484,16 @@ members = ["api"]
] {
assert_eq!(need(&Method::POST, p), Some("0.12.0"), "{p}");
}
for p in [
"/v1/groups/server/start",
"/v1/groups/server/stop",
"/v1/groups/server/rebuild",
"/v1/services/server/stop",
] {
assert_eq!(need(&Method::POST, p), Some("0.28.0"), "{p}");
}
for (m, p) in [
(Method::POST, "/v1/services/api/restart"),
(Method::POST, "/v1/services/server/stop"),
(Method::POST, "/v1/groups/front/restart"),
(Method::GET, "/v1/infra/app/db/logs"),
(Method::GET, "/v1/services/web/restart"),
Expand Down
2 changes: 1 addition & 1 deletion crates/devstack-daemon/src/supervisor/infra.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1201,7 +1201,7 @@ impl Supervisor {
}

/// A Compose service a lane uses from the main tree (`shared`, ADR-0030).
fn is_shared(&self, group: &str, service: &str) -> bool {
pub(super) fn is_shared(&self, group: &str, service: &str) -> bool {
!self.lane.is_empty()
&& self
.stack
Expand Down
Loading
Loading