forked from spacedriveapp/spacebot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaemon.rs
More file actions
464 lines (405 loc) · 15.4 KB
/
daemon.rs
File metadata and controls
464 lines (405 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Process daemonization and IPC for background operation.
use crate::config::{Config, TelemetryConfig};
use anyhow::{Context as _, anyhow};
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_otlp::WithHttpConfig;
use opentelemetry_sdk::trace::SdkTracerProvider;
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
use tokio::net::{UnixListener, UnixStream};
use tokio::sync::watch;
use tracing_subscriber::fmt::format;
use tracing_subscriber::layer::SubscriberExt as _;
use tracing_subscriber::util::SubscriberInitExt as _;
use std::path::PathBuf;
use std::time::Instant;
/// Commands sent from CLI client to the running daemon.
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "command", rename_all = "snake_case")]
pub enum IpcCommand {
Shutdown,
Status,
}
/// Responses from the daemon back to the CLI client.
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "result", rename_all = "snake_case")]
pub enum IpcResponse {
Ok,
Status { pid: u32, uptime_seconds: u64 },
Error { message: String },
}
/// Paths for daemon runtime files, all derived from the instance directory.
pub struct DaemonPaths {
pub pid_file: PathBuf,
pub socket: PathBuf,
pub log_dir: PathBuf,
}
impl DaemonPaths {
pub fn new(instance_dir: &std::path::Path) -> Self {
Self {
pid_file: instance_dir.join("spacebot.pid"),
socket: instance_dir.join("spacebot.sock"),
log_dir: instance_dir.join("logs"),
}
}
pub fn from_default() -> Self {
Self::new(&Config::default_instance_dir())
}
}
/// Check whether a daemon is already running by testing PID file liveness
/// and socket connectivity.
pub fn is_running(paths: &DaemonPaths) -> Option<u32> {
let pid = read_pid_file(&paths.pid_file)?;
// Verify the process is actually alive
if !is_process_alive(pid) {
cleanup_stale_files(paths);
return None;
}
// Double-check by trying to connect to the socket
if paths.socket.exists() {
if let Ok(stream) = std::os::unix::net::UnixStream::connect(&paths.socket) {
drop(stream);
return Some(pid);
}
// Socket exists but can't connect — stale
cleanup_stale_files(paths);
return None;
}
// PID alive but no socket — process may be starting up or crashed
// without cleanup. Trust the PID.
Some(pid)
}
/// Daemonize the current process. Returns in the child; the parent prints
/// a message and exits.
pub fn daemonize(paths: &DaemonPaths) -> anyhow::Result<()> {
std::fs::create_dir_all(&paths.log_dir).with_context(|| {
format!(
"failed to create log directory: {}",
paths.log_dir.display()
)
})?;
let stdout = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(paths.log_dir.join("spacebot.out"))
.context("failed to open stdout log")?;
let stderr = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(paths.log_dir.join("spacebot.err"))
.context("failed to open stderr log")?;
let daemonize = daemonize::Daemonize::new()
.pid_file(&paths.pid_file)
.chown_pid_file(true)
.stdout(stdout)
.stderr(stderr);
daemonize
.start()
.map_err(|error| anyhow!("failed to daemonize: {error}"))?;
Ok(())
}
/// Initialize tracing for background (daemon) mode.
///
/// Returns an `SdkTracerProvider` if OTLP export is configured. The caller must
/// hold onto it for the process lifetime and call `.shutdown()` before exit so
/// the batch exporter flushes buffered spans.
pub fn init_background_tracing(
paths: &DaemonPaths,
debug: bool,
telemetry: &TelemetryConfig,
) -> Option<SdkTracerProvider> {
let file_appender = tracing_appender::rolling::daily(&paths.log_dir, "spacebot.log");
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
let field_formatter = format::debug_fn(|writer, field, value| {
let field_name = field.name();
if field_name == "gen_ai.system_instructions"
|| field_name == "gen_ai.tool.call.arguments"
|| field_name == "gen_ai.tool.call.result"
{
Ok(())
} else if field_name == "message" {
let formatted = format!("{value:?}");
const MAX_MESSAGE_CHARS: usize = 280;
if formatted.len() > MAX_MESSAGE_CHARS {
let boundary = formatted.floor_char_boundary(MAX_MESSAGE_CHARS);
write!(writer, "{}={}", field_name, &formatted[..boundary])?;
write!(writer, "...")
} else {
write!(writer, "{}={formatted}", field_name)
}
} else {
write!(writer, "{}={value:?}", field_name)
}
});
// Leak the guard so the non-blocking writer lives for the entire process.
// The process owns this — it's cleaned up on exit.
std::mem::forget(_guard);
let filter = build_env_filter(debug);
let fmt_layer = tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_ansi(false)
.fmt_fields(field_formatter)
.compact();
match build_otlp_provider(telemetry) {
Some(provider) => {
let tracer = provider.tracer("spacebot");
tracing_subscriber::registry()
.with(filter)
.with(fmt_layer)
.with(tracing_opentelemetry::layer().with_tracer(tracer))
.init();
Some(provider)
}
None => {
tracing_subscriber::registry()
.with(filter)
.with(fmt_layer)
.init();
None
}
}
}
/// Initialize tracing for foreground (terminal) mode.
///
/// Returns an `SdkTracerProvider` if OTLP export is configured.
pub fn init_foreground_tracing(
debug: bool,
telemetry: &TelemetryConfig,
) -> Option<SdkTracerProvider> {
let field_formatter = format::debug_fn(|writer, field, value| {
let field_name = field.name();
if field_name == "gen_ai.system_instructions"
|| field_name == "gen_ai.tool.call.arguments"
|| field_name == "gen_ai.tool.call.result"
{
Ok(())
} else if field_name == "message" {
let formatted = format!("{value:?}");
const MAX_MESSAGE_CHARS: usize = 280;
if formatted.len() > MAX_MESSAGE_CHARS {
let boundary = formatted.floor_char_boundary(MAX_MESSAGE_CHARS);
write!(writer, "{}={}", field_name, &formatted[..boundary])?;
write!(writer, "...")
} else {
write!(writer, "{}={formatted}", field_name)
}
} else {
write!(writer, "{}={value:?}", field_name)
}
});
let filter = build_env_filter(debug);
let fmt_layer = tracing_subscriber::fmt::layer()
.fmt_fields(field_formatter)
.compact();
match build_otlp_provider(telemetry) {
Some(provider) => {
let tracer = provider.tracer("spacebot");
tracing_subscriber::registry()
.with(filter)
.with(fmt_layer)
.with(tracing_opentelemetry::layer().with_tracer(tracer))
.init();
Some(provider)
}
None => {
tracing_subscriber::registry()
.with(filter)
.with(fmt_layer)
.init();
None
}
}
}
fn build_env_filter(debug: bool) -> tracing_subscriber::EnvFilter {
if debug {
tracing_subscriber::EnvFilter::new("debug")
} else {
tracing_subscriber::EnvFilter::new("info")
}
}
/// Build an OTLP `SdkTracerProvider` when an endpoint is configured.
///
/// Returns `None` if neither the config field nor the `OTEL_EXPORTER_OTLP_ENDPOINT`
/// environment variable is set, allowing the OTel layer to be omitted entirely.
fn build_otlp_provider(telemetry: &TelemetryConfig) -> Option<SdkTracerProvider> {
use opentelemetry_otlp::WithExportConfig as _;
let endpoint = telemetry.otlp_endpoint.as_deref()?;
// The HTTP/protobuf endpoint path is /v1/traces by default. Append it only
// when the caller provided a bare host:port so both forms work.
let endpoint = if endpoint.ends_with("/v1/traces") {
endpoint.to_owned()
} else {
format!("{}/v1/traces", endpoint.trim_end_matches('/'))
};
let mut exporter_builder = opentelemetry_otlp::SpanExporter::builder()
.with_http()
.with_endpoint(endpoint);
if !telemetry.otlp_headers.is_empty() {
exporter_builder = exporter_builder.with_headers(telemetry.otlp_headers.clone());
}
let exporter = exporter_builder
.build()
.map_err(|error| eprintln!("failed to build OTLP exporter: {error}"))
.ok()?;
let resource = opentelemetry_sdk::Resource::builder()
.with_service_name(telemetry.service_name.clone())
.build();
let sampler: opentelemetry_sdk::trace::Sampler =
if (telemetry.sample_rate - 1.0).abs() < f64::EPSILON {
opentelemetry_sdk::trace::Sampler::AlwaysOn
} else {
opentelemetry_sdk::trace::Sampler::ParentBased(Box::new(
opentelemetry_sdk::trace::Sampler::TraceIdRatioBased(telemetry.sample_rate),
))
};
// Use the async-runtime-aware BatchSpanProcessor so the export future is
// driven by tokio::spawn rather than a plain OS thread using
// futures_executor::block_on. The sync variant panics because reqwest
// calls tokio::time::sleep internally, which requires an active Tokio
// runtime on the calling thread — something the plain thread never has.
let batch_processor =
opentelemetry_sdk::trace::span_processor_with_async_runtime::BatchSpanProcessor::builder(
exporter,
opentelemetry_sdk::runtime::Tokio,
)
.build();
let provider = SdkTracerProvider::builder()
.with_span_processor(batch_processor)
.with_resource(resource)
.with_sampler(sampler)
.build();
Some(provider)
}
/// Start the IPC server. Returns a shutdown receiver that the main event
/// loop should select on.
pub async fn start_ipc_server(
paths: &DaemonPaths,
) -> anyhow::Result<(watch::Receiver<bool>, tokio::task::JoinHandle<()>)> {
// Ensure the instance directory exists (e.g. on first run)
if let Some(parent) = paths.socket.parent() {
std::fs::create_dir_all(parent).with_context(|| {
format!("failed to create instance directory: {}", parent.display())
})?;
}
// Clean up any stale socket file
if paths.socket.exists() {
std::fs::remove_file(&paths.socket).with_context(|| {
format!("failed to remove stale socket: {}", paths.socket.display())
})?;
}
let listener = UnixListener::bind(&paths.socket)
.with_context(|| format!("failed to bind IPC socket: {}", paths.socket.display()))?;
let (shutdown_tx, shutdown_rx) = watch::channel(false);
let start_time = Instant::now();
let socket_path = paths.socket.clone();
let handle = tokio::spawn(async move {
loop {
match listener.accept().await {
Ok((stream, _address)) => {
let shutdown_tx = shutdown_tx.clone();
let uptime = start_time.elapsed();
tokio::spawn(async move {
if let Err(error) =
handle_ipc_connection(stream, &shutdown_tx, uptime).await
{
tracing::warn!(%error, "IPC connection handler failed");
}
});
}
Err(error) => {
tracing::warn!(%error, "failed to accept IPC connection");
}
}
}
});
// Spawn a cleanup task that removes the socket file when the server shuts down
let cleanup_socket = socket_path.clone();
let mut cleanup_rx = shutdown_rx.clone();
tokio::spawn(async move {
let _ = cleanup_rx.wait_for(|shutdown| *shutdown).await;
let _ = std::fs::remove_file(&cleanup_socket);
});
Ok((shutdown_rx, handle))
}
/// Handle a single IPC client connection.
async fn handle_ipc_connection(
stream: UnixStream,
shutdown_tx: &watch::Sender<bool>,
uptime: std::time::Duration,
) -> anyhow::Result<()> {
let (reader, mut writer) = stream.into_split();
let mut reader = tokio::io::BufReader::new(reader);
let mut line = String::new();
reader.read_line(&mut line).await?;
let command: IpcCommand = serde_json::from_str(line.trim())
.with_context(|| format!("invalid IPC command: {line}"))?;
let response = match command {
IpcCommand::Shutdown => {
tracing::info!("shutdown requested via IPC");
shutdown_tx.send(true).ok();
IpcResponse::Ok
}
IpcCommand::Status => IpcResponse::Status {
pid: std::process::id(),
uptime_seconds: uptime.as_secs(),
},
};
let mut response_bytes = serde_json::to_vec(&response)?;
response_bytes.push(b'\n');
writer.write_all(&response_bytes).await?;
writer.flush().await?;
Ok(())
}
/// Send a command to the running daemon and return the response.
pub async fn send_command(paths: &DaemonPaths, command: IpcCommand) -> anyhow::Result<IpcResponse> {
let stream = UnixStream::connect(&paths.socket)
.await
.with_context(|| "failed to connect to spacebot daemon. is it running?")?;
let (reader, mut writer) = stream.into_split();
let mut command_bytes = serde_json::to_vec(&command)?;
command_bytes.push(b'\n');
writer.write_all(&command_bytes).await?;
writer.flush().await?;
let mut reader = tokio::io::BufReader::new(reader);
let mut line = String::new();
reader.read_line(&mut line).await?;
let response: IpcResponse = serde_json::from_str(line.trim())
.with_context(|| format!("invalid IPC response: {line}"))?;
Ok(response)
}
/// Clean up PID and socket files on shutdown.
pub fn cleanup(paths: &DaemonPaths) {
if let Err(error) = std::fs::remove_file(&paths.pid_file)
&& error.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!(%error, "failed to remove PID file");
}
if let Err(error) = std::fs::remove_file(&paths.socket)
&& error.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!(%error, "failed to remove socket file");
}
}
fn read_pid_file(path: &std::path::Path) -> Option<u32> {
let content = std::fs::read_to_string(path).ok()?;
content.trim().parse::<u32>().ok()
}
fn is_process_alive(pid: u32) -> bool {
// kill(pid, 0) checks if the process exists without sending a signal
unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
}
fn cleanup_stale_files(paths: &DaemonPaths) {
let _ = std::fs::remove_file(&paths.pid_file);
let _ = std::fs::remove_file(&paths.socket);
}
/// Wait for the daemon process to exit after sending a shutdown command.
/// Polls the PID with a short interval, times out after 10 seconds.
pub fn wait_for_exit(pid: u32) -> bool {
for _ in 0..100 {
if !is_process_alive(pid) {
return true;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
false
}