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
60 changes: 60 additions & 0 deletions bt-daemon/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,29 @@ pub(crate) async fn status_over(
.await
}

/// Request shutdown directly, without waiting for a status snapshot.
/// Missing and stale endpoints mean there is no daemon to stop.
pub(crate) async fn stop_daemon(socket: &Path) -> anyhow::Result<bool> {
let stream = match connect(socket).await {
Ok(stream) => stream,
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused
) =>
{
return Ok(false)
}
Err(error) => return Err(error.into()),
};
let mut conn = Conn::new(stream);
let response: wire::ShutdownResult = conn
.call(method::DAEMON_SHUTDOWN, serde_json::json!({}))
.await?;
anyhow::ensure!(response.ok, "tracing daemon refused shutdown");
Ok(true)
}

/// Request a graceful daemon shutdown. Primarily useful for lifecycle
/// management and transport integration tests.
pub async fn shutdown_daemon(socket: &std::path::Path) -> anyhow::Result<()> {
Expand All @@ -533,3 +556,40 @@ pub async fn shutdown_daemon(socket: &std::path::Path) -> anyhow::Result<()> {
.await?;
Ok(())
}

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

#[tokio::test]
async fn stop_preserves_shutdown_failures() {
for refused in [true, false] {
let temp = tempfile::tempdir().unwrap();
let socket = temp.path().join("daemon.sock");
let listener = tokio::net::UnixListener::bind(&socket).unwrap();
let peer = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let (read, mut write) = stream.into_split();
let line = BufReader::new(read)
.lines()
.next_line()
.await
.unwrap()
.unwrap();
let request: Request = serde_json::from_str(&line).unwrap();
if refused {
let response =
Response::serialized(request.id, wire::ShutdownResult { ok: false });
write
.write_all(
format!("{}\n", serde_json::to_string(&response).unwrap()).as_bytes(),
)
.await
.unwrap();
}
});
assert!(stop_daemon(&socket).await.is_err());
peer.await.unwrap();
}
}
}
83 changes: 70 additions & 13 deletions bt-daemon/src/trace_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ use crate::trace_command::{DoctorAgent, DoctorArgs, SettingsScope, SetupAgent, T
use crate::wire::{AuthSelection, AuthSource, SessionConfig, SessionRoute, TraceDestination};
use crate::{
braintrust_serve_options, paths, run_disable, run_enable, run_import, run_serve, run_status,
run_traced_with_host, shutdown_daemon, AuthDiagnostic, AuthLease, AuthProvider,
AuthResolveReason, BraintrustSinkConfig, DaemonDiagnostic, DaemonStatus, DoctorCommandOutput,
HostInfo, ImportTarget, OutputFormat, Registry, RunHookCommand, ServeOptions, StatusArgs,
TraceArgs, TraceCommandOutput,
run_traced_with_host, AuthDiagnostic, AuthLease, AuthProvider, AuthResolveReason,
BraintrustSinkConfig, DaemonDiagnostic, DaemonStatus, DoctorCommandOutput, HostInfo,
ImportTarget, OutputFormat, Registry, RunHookCommand, ServeOptions, TraceArgs,
TraceCommandOutput,
};
use async_trait::async_trait;
use std::ffi::OsString;
Expand Down Expand Up @@ -926,15 +926,11 @@ pub async fn run_trace_with_matches(
),
TraceCommand::Stop(stop_args) => {
let socket = paths::socket_path(stop_args.socket.as_deref());
let status_args = StatusArgs {
socket: Some(socket.clone()),
session_id: None,
};
if run_status(status_args).await?.is_none() {
return print_output(TraceCommandOutput::stop(false, false), host.output_format);
}
shutdown_daemon(&socket).await?;
print_output(TraceCommandOutput::stop(true, true), host.output_format)
let stopped = crate::client::stop_daemon(&socket).await?;
print_output(
TraceCommandOutput::stop(stopped, stopped),
host.output_format,
)
}
TraceCommand::Import(import_args) => {
let mut route = resolve_host_route(
Expand Down Expand Up @@ -2230,4 +2226,65 @@ mod tests {
.unwrap();
}
}
#[cfg(unix)]
#[tokio::test]
async fn stop_requests_shutdown_without_status() {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
let temp = tempfile::tempdir().unwrap();
let socket = temp.path().join("daemon.sock");
let listener = tokio::net::UnixListener::bind(&socket).unwrap();
let peer = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let (read, mut write) = stream.into_split();
let line = BufReader::new(read)
.lines()
.next_line()
.await
.unwrap()
.unwrap();
let request: crate::wire::Request = serde_json::from_str(&line).unwrap();
assert_eq!(request.method, crate::wire::method::DAEMON_SHUTDOWN);
let response = crate::wire::Response::serialized(
request.id,
crate::wire::ShutdownResult { ok: true },
);
write
.write_all(format!("{}\n", serde_json::to_string(&response).unwrap()).as_bytes())
.await
.unwrap();
});
tokio::time::timeout(
Duration::from_secs(2),
run_trace(
TraceArgs {
command: TraceCommand::Stop(StopArgs {
socket: Some(socket),
}),
},
test_host(Arc::new(PanicHost)),
),
)
.await
.unwrap()
.unwrap();
peer.await.unwrap();
}

#[cfg(unix)]
#[tokio::test]
async fn stop_accepts_stale_socket() {
let temp = tempfile::tempdir().unwrap();
let socket = temp.path().join("stale.sock");
drop(tokio::net::UnixListener::bind(&socket).unwrap());
run_trace(
TraceArgs {
command: TraceCommand::Stop(StopArgs {
socket: Some(socket),
}),
},
test_host(Arc::new(PanicHost)),
)
.await
.unwrap();
}
}
Loading