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

### Added

- **Stop stack can take the containers down too**: the dashboard's stop
dialog (header and sidebar) offers "Stop its containers too", as
`devstack down --infra` does; their volumes stay. Checked when the stack
runs nothing but containers, where a stop without them changed nothing
but the daemon. Not offered while lanes run: they keep the containers
they share (ADR-0030).
- **Links to a stack's or a lane's dashboard page, for agents to hand on**:
`devstack status`, `devstack up` and `devstack lane start` end with
`dashboard: http://127.0.0.1:4250/#/s/<id>?lane=<lane>`; the MCP tools
Expand Down Expand Up @@ -114,6 +120,8 @@ and listed with their assets on the
the lanes when their counts change (a lane on a node is read every 5 s),
and the shown lane counts from its own stream. Before, a lane started on
a node stayed yellow until the page switched to another tree.
- A daemon's last telemetry is sent as it exits (2 s at most): what it said
in its last minute, its stop included, was dropped before (ADR-0037).
- A lane on a node no longer stops syncing when a file goes while it is
sent (a package manager rewriting `node_modules`): the file is left out
and the next sync sends what is there then.
Expand Down
4 changes: 4 additions & 0 deletions crates/devstack-daemon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ fn cgroup_root(stack: &str) -> Option<PathBuf> {
/// How long a stopping daemon waits for open requests before it stops anyway.
const SHUTDOWN_GRACE: std::time::Duration = std::time::Duration::from_secs(2);

/// How long an exiting daemon waits to send its last telemetry (ADR-0037).
const TELEMETRY_FLUSH: std::time::Duration = std::time::Duration::from_secs(2);

/// How long a stopping daemon waits for its services to stop. What still
/// runs then dies with the daemon (ADR-0009); a second Ctrl-C ends the wait.
const SHUTDOWN_STOP: std::time::Duration = std::time::Duration::from_secs(90);
Expand Down Expand Up @@ -413,6 +416,7 @@ pub fn serve(stack_file: &Path) -> Result<(), String> {
}
let _ = std::fs::remove_file(info_path(&state_dir));
diag::info("daemon_stop", serde_json::json!({}));
telemetry::flush(TELEMETRY_FLUSH);
served
});
// A stop still under way must not keep the process (dropping the
Expand Down
122 changes: 104 additions & 18 deletions crates/devstack-daemon/src/telemetry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ static TUNNELS_OPEN: AtomicU64 = AtomicU64::new(0);
static REPOSITORY: OnceLock<String> = OnceLock::new();
type GaugeFn = Box<dyn Fn() -> Vec<Gauge> + Send + Sync>;
static GAUGES: OnceLock<GaugeFn> = OnceLock::new();
/// The process's name as a sender (`devstack-daemon`), once started.
static SERVICE: OnceLock<&'static str> = OnceLock::new();
/// The pools the last round sent to: where [`flush`] sends.
static TARGETS: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());

/// Whether diagnostic lines are kept now: a pool takes them, or none was
/// asked yet.
Expand Down Expand Up @@ -143,6 +147,7 @@ pub fn start(service: &'static str) {
return;
}
STATE.store(UNDECIDED, Ordering::Relaxed);
let _ = SERVICE.set(service);
let spawned = std::thread::Builder::new()
.name("telemetry".into())
.spawn(move || run(service));
Expand Down Expand Up @@ -234,30 +239,76 @@ fn run(service: &str) {
}
Round::Send => {}
}
let lines = std::mem::take(&mut *BUFFER.lock().unwrap());
let tunnels = std::mem::take(&mut *TUNNELS.lock().unwrap());
let repo = repository();
let logs = (!lines.is_empty()).then(|| crate::diag::otlp_body(service, repo, &lines));
let mut gauges = GAUGES.get().map(|f| f()).unwrap_or_default();
gauges.extend(tunnel_gauges(repo, &tunnels));
let mut durations = durations(repo, &lines);
durations.extend(tunnel_durations(repo, &tunnels));
let metrics = metrics_body(service, &gauges, &durations);
for (dir, t) in &targets {
let sent = match &logs {
Some(l) => t.telemetry_send("logs", l),
None => Ok(()),
}
.and_then(|()| t.telemetry_send("metrics", &metrics));
*TARGETS.lock().unwrap() = targets.iter().map(|(dir, _)| dir.clone()).collect();
for dir in send(service, &targets, true) {
// A coordinator that stopped collecting answers 404 (ADR-0037):
// stop sending to it now, not when it is asked again.
if stopped_collecting(&sent) {
collects.insert(dir.clone(), (Instant::now(), false));
}
collects.insert(dir, (Instant::now(), false));
}
}
}

/// Send what was kept since the last round to `targets`, with the gauges
/// when `gauges`; the pools whose coordinator no longer collects.
fn send(service: &str, targets: &[(PathBuf, Local)], gauges: bool) -> Vec<PathBuf> {
let lines = std::mem::take(&mut *BUFFER.lock().unwrap());
let tunnels = std::mem::take(&mut *TUNNELS.lock().unwrap());
let repo = repository();
let logs = (!lines.is_empty()).then(|| crate::diag::otlp_body(service, repo, &lines));
let mut measured = if gauges {
GAUGES.get().map(|f| f()).unwrap_or_default()
} else {
Vec::new()
};
measured.extend(tunnel_gauges(repo, &tunnels));
let mut durations = durations(repo, &lines);
durations.extend(tunnel_durations(repo, &tunnels));
let metrics = metrics_body(service, &measured, &durations);
let mut stopped = Vec::new();
for (dir, t) in targets {
let sent = match &logs {
Some(l) => t.telemetry_send("logs", l),
None => Ok(()),
}
.and_then(|()| t.telemetry_send("metrics", &metrics));
if stopped_collecting(&sent) {
stopped.push(dir.clone());
}
}
stopped
}

/// The process is about to exit: send what was kept since the last round
/// to the pools that took it, waiting `within` at most. Without it, a
/// daemon's stop (and whatever went wrong while it stopped) never left.
pub fn flush(within: Duration) {
if STATE.load(Ordering::Relaxed) != ON || BUFFER.lock().unwrap().is_empty() {
return;
}
let Some(service) = SERVICE.get().copied() else {
return;
};
let dirs = TARGETS.lock().unwrap().clone();
let (tx, rx) = std::sync::mpsc::channel();
let spawned = std::thread::Builder::new()
.name("telemetry-flush".into())
.spawn(move || {
let targets: Vec<(PathBuf, Local)> = dirs
.into_iter()
.map(|dir| {
let local = Local::new(&dir);
(dir, local)
})
.collect();
// The gauges read the process's state, which is being torn down.
send(service, &targets, false);
let _ = tx.send(());
});
if spawned.is_ok() {
let _ = rx.recv_timeout(within);
}
}

/// Whether a send's answer says the coordinator no longer collects.
fn stopped_collecting(sent: &devstack_node::member::Result<()>) -> bool {
matches!(
Expand Down Expand Up @@ -358,6 +409,9 @@ fn tunnel_gauges(repo: Option<&str>, tunnels: &[TunnelClosed]) -> Vec<Gauge> {
mod tests {
use super::*;

/// Held by the tests that change the module's state and buffer.
static GLOBALS: Mutex<()> = Mutex::new(());

#[test]
fn a_command_run_is_counted_by_its_name_and_result() {
let lines = vec![
Expand Down Expand Up @@ -481,6 +535,7 @@ mod tests {
m
};
let has = |n: &str| BUFFER.lock().unwrap().iter().any(|l| l["event"] == n);
let _g = GLOBALS.lock().unwrap_or_else(|e| e.into_inner());
STATE.store(UNDECIDED, Ordering::Relaxed);
record(&line("telemetry_test_early"));
assert!(has("telemetry_test_early"));
Expand All @@ -496,6 +551,37 @@ mod tests {
.retain(|l| l["event"] != "telemetry_test_early");
}

#[test]
fn an_exit_sends_what_was_kept_and_waits_no_longer_than_it_may() {
let _g = GLOBALS.lock().unwrap_or_else(|e| e.into_inner());
let mut line = serde_json::Map::new();
line.insert("event".into(), Value::String("telemetry_test_exit".into()));
let kept = || {
BUFFER
.lock()
.unwrap()
.iter()
.any(|l| l["event"] == "telemetry_test_exit")
};
// Not sending: kept as it is.
STATE.store(UNDECIDED, Ordering::Relaxed);
record(&line);
flush(Duration::from_secs(2));
assert!(kept());
// Sending: taken and sent to the pools of the last round (one
// without a membership here refuses at once).
let _ = SERVICE.set("devstack-daemon");
let pool = tempfile::tempdir().unwrap();
*TARGETS.lock().unwrap() = vec![pool.path().to_path_buf()];
STATE.store(ON, Ordering::Relaxed);
let t0 = Instant::now();
flush(Duration::from_secs(2));
assert!(!kept());
assert!(t0.elapsed() < Duration::from_secs(3));
STATE.store(IDLE, Ordering::Relaxed);
TARGETS.lock().unwrap().clear();
}

#[test]
fn a_collector_that_answers_404_stopped_collecting() {
use devstack_node::member::MemberError;
Expand Down
21 changes: 21 additions & 0 deletions ui/src/components/GlobalDialogs.vue
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ async function copy(text: string) {
<Icon :name="req?.danger ? 'alert' : 'info'" :size="20" />
</template>
<p class="confirm-text" data-testid="confirm-text">{{ req?.text }}</p>
<label v-if="req?.option" class="confirm-option" data-testid="confirm-option">
<input v-model="req.option.checked" type="checkbox" />
<span>
{{ req.option.label }}
<span v-if="req.option.hint" class="faint small">{{ req.option.hint }}</span>
</span>
</label>
<template #footer>
<button type="button" class="btn" data-testid="confirm-cancel" @click="req?.resolve(false)">Cancel</button>
<button
Expand Down Expand Up @@ -69,4 +76,18 @@ async function copy(text: string) {
line-height: 1.55;
white-space: pre-wrap;
}
.confirm-option {
display: flex;
gap: 8px;
align-items: flex-start;
margin-top: 12px;
font-size: 14px;
cursor: pointer;
}
.confirm-option input {
margin-top: 3px;
}
.confirm-option .faint {
display: block;
}
</style>
6 changes: 4 additions & 2 deletions ui/src/components/Sidebar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -214,13 +214,15 @@ async function stopStack(s: StackEntry) {
closeMenu();
// The shown stack's own stop knows its lanes and says what stays.
if (isCurrent(s)) return void stack.stopStack();
const option = stack.stopContainers(false);
const ok = await ui.confirm({
title: `Stop ${s.name}`,
text: 'Its services stop. Infrastructure containers keep running.',
text: 'Its services stop. Lanes that still run keep its daemon and the containers they share.',
confirmLabel: 'Stop stack',
danger: true,
option,
});
if (ok) await act({ label: `Stop ${s.name}`, path: paths.down(s.id, false), success: 'Stopping the stack…' });
if (ok) await act({ label: `Stop ${s.name}`, path: paths.down(s.id, option.checked), success: 'Stopping the stack…' });
}
async function removeStack(s: StackEntry) {
closeMenu();
Expand Down
17 changes: 14 additions & 3 deletions ui/src/stores/stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { persist } from '@/lib/persist';
import { statusBucket } from '@/lib/status';
import { useHub } from './hub';
import { usePool } from './pool';
import { useUi } from './ui';
import { useUi, type ConfirmOption } from './ui';

const MAX_EVENTS = 500;
const HISTORY_WINDOW_MS = 10 * 60_000;
Expand Down Expand Up @@ -725,28 +725,39 @@ export const useStack = defineStore('stack', () => {
if (!id.value) return;
const name = entry.value?.name ?? 'stack';
const kept = runningLanes.value;
// Lanes that run keep the containers they share (ADR-0030): nothing to choose.
const containers = !kept.length && (view.value?.infra.some((g) => g.containers.length) ?? true);
// Containers only, nothing else to stop: then they are what "stop" means.
const option = containers ? stopContainers(view.value !== null && view.value.services.length === 0) : undefined;
const ok = await ui.confirm({
title: `Stop ${name}`,
text: kept.length
? `The main working tree's services stop. ${laneList(kept)} keep running, and with them the daemon. Infrastructure containers keep running.`
: 'All services of this stack stop and its daemon exits. Infrastructure containers keep running.',
: 'All services of this stack stop and its daemon exits.',
confirmLabel: 'Stop stack',
danger: true,
option,
});
if (!ok) return;
busy.value['stack'] = 'stop';
try {
await act({ label: `Stop ${name}`, path: paths.down(id.value, false), success: 'Stopping the stack…' });
await act({ label: `Stop ${name}`, path: paths.down(id.value, !!option?.checked), success: 'Stopping the stack…' });
} finally {
delete busy.value['stack'];
}
}

/** The choice to take a stack's containers down with it (`devstack down --infra`). */
function stopContainers(checked: boolean): ConfirmOption {
return { label: 'Stop its containers too', hint: 'Docker Compose takes them down; their volumes stay.', checked };
}

function laneList(names: string[]) {
return names.length === 1 ? `Lane ${names[0]} and its ports` : `Lanes ${names.join(', ')} and their ports`;
}

return {
stopContainers,
id,
view,
viewAt,
Expand Down
24 changes: 24 additions & 0 deletions ui/src/stores/stores.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,30 @@ describe('stack store', () => {
expect(stack.view?.services[0].pid).toBeNull();
});

it('a stack of containers only stops them too, unless told otherwise', async () => {
const stack = await shownStack();
const app = { group: 'app', project: 'shop', containers: [{ service: 'db', name: 'shop-db-1', state: 'running', health: '', ports: [] }], error: null };
const view = (services: unknown[]) => ({ name: 'shop', repo: '/src/shop', version: '0.9.8', services, infra: [app], groups: [], commands: [] });
const events = fake.stream('/hub/stacks/shop/api/v1/events');
const ui = useUi();
const stopWith = async (checked?: boolean) => {
const done = stack.stopStack();
await vi.waitFor(() => expect(ui.confirmRequest).not.toBeNull());
const option = ui.confirmRequest!.option!;
const offered = option.checked;
if (checked !== undefined) option.checked = checked;
ui.confirmRequest!.resolve(true);
await done;
return { offered, path: fake.requests.at(-1)?.path };
};
events.handlers.onMessage({ type: 'snapshot', stack: view([]) } as never);
expect(await stopWith()).toEqual({ offered: true, path: '/hub/stacks/shop/down?infra=true' });
expect((await stopWith(false)).path).toBe('/hub/stacks/shop/down?infra=false');
// Services of its own: the containers stay unless asked.
events.handlers.onMessage({ type: 'snapshot', stack: view([{ name: 'api', status: { state: 'running' } }]) } as never);
expect(await stopWith()).toEqual({ offered: false, path: '/hub/stacks/shop/down?infra=false' });
});

it('a lane not started is shown from the main tree', async () => {
const stack = await shownStack();
fake.stream('/hub/stacks/shop/api/v1/events').handlers.onMessage({
Expand Down
7 changes: 6 additions & 1 deletion ui/src/stores/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ export type ConfirmRequest = {
text: string;
confirmLabel: string;
danger: boolean;
/** A choice that goes with it; the dialog sets `checked`. */
option?: ConfirmOption;
resolve(ok: boolean): void;
};

export type ConfirmOption = { label: string; hint?: string; checked: boolean };

export type ProblemRequest = { title: string; message: string; hint?: string };

const THEME_KEY = 'devstack.theme';
Expand Down Expand Up @@ -64,14 +68,15 @@ export const useUi = defineStore('ui', () => {

// ---------------------------------------------------------- dialogs
const confirmRequest = ref<ConfirmRequest | null>(null);
function confirm(opts: { title: string; text: string; confirmLabel?: string; danger?: boolean }): Promise<boolean> {
function confirm(opts: { title: string; text: string; confirmLabel?: string; danger?: boolean; option?: ConfirmOption }): Promise<boolean> {
confirmRequest.value?.resolve(false);
return new Promise((resolve) => {
confirmRequest.value = {
title: opts.title,
text: opts.text,
confirmLabel: opts.confirmLabel ?? 'Continue',
danger: opts.danger ?? false,
option: opts.option,
resolve: (ok) => {
confirmRequest.value = null;
resolve(ok);
Expand Down