otelite 0.1.60

Otelite: OTLP receiver, dashboard, and CLI for local OpenTelemetry observability
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! Service management commands for running otelite as a background daemon

use crate::error::{Error, Result};
use otelite_storage::StorageConfig;
use std::fs;
use std::io::Write;
#[cfg(target_os = "macos")]
use std::path::Path;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use tracing::{info, warn};

#[cfg(target_os = "macos")]
const LAUNCHD_SERVICE_LABEL: &str = "dev.otelite.daemon";

#[cfg(target_os = "macos")]
#[derive(Debug, PartialEq, Eq)]
enum LaunchdServiceState {
    Loaded,
    Running(u32),
}

/// Get the directory for otelite runtime files (PID, logs, database).
/// Delegates to StorageConfig so the path is always consistent with the server.
fn get_runtime_dir() -> Result<PathBuf> {
    let runtime_dir = StorageConfig::default_data_dir();

    if !runtime_dir.exists() {
        fs::create_dir_all(&runtime_dir).map_err(|e| {
            Error::ConfigError(format!("Failed to create runtime directory: {}", e))
        })?;
    }

    Ok(runtime_dir)
}

/// Get the path to the PID file
fn get_pid_file() -> Result<PathBuf> {
    Ok(get_runtime_dir()?.join("otelite.pid"))
}

/// Get the path to the log file
fn get_log_file() -> Result<PathBuf> {
    Ok(get_runtime_dir()?.join("otelite.log"))
}

/// Read the PID from the PID file
fn read_pid() -> Result<Option<u32>> {
    let pid_file = get_pid_file()?;

    if !pid_file.exists() {
        return Ok(None);
    }

    let content = fs::read_to_string(&pid_file)
        .map_err(|e| Error::ConfigError(format!("Failed to read PID file: {}", e)))?;

    let pid = content
        .trim()
        .parse::<u32>()
        .map_err(|e| Error::ConfigError(format!("Invalid PID in file: {}", e)))?;

    Ok(Some(pid))
}

/// Write the PID to the PID file
fn write_pid(pid: u32) -> Result<()> {
    let pid_file = get_pid_file()?;

    let mut file = fs::File::create(&pid_file)
        .map_err(|e| Error::ConfigError(format!("Failed to create PID file: {}", e)))?;

    file.write_all(pid.to_string().as_bytes())
        .map_err(|e| Error::ConfigError(format!("Failed to write PID file: {}", e)))?;

    Ok(())
}

/// Remove the PID file
fn remove_pid_file() -> Result<()> {
    let pid_file = get_pid_file()?;

    if pid_file.exists() {
        fs::remove_file(&pid_file)
            .map_err(|e| Error::ConfigError(format!("Failed to remove PID file: {}", e)))?;
    }

    Ok(())
}

#[cfg(target_os = "macos")]
fn parse_launchd_service_state(output: &str) -> LaunchdServiceState {
    let is_running = output.lines().any(|line| line.trim() == "state = running");
    let pid = output.lines().find_map(|line| {
        line.trim()
            .strip_prefix("pid = ")
            .and_then(|value| value.parse::<u32>().ok())
    });

    match (is_running, pid) {
        (true, Some(pid)) => LaunchdServiceState::Running(pid),
        _ => LaunchdServiceState::Loaded,
    }
}

#[cfg(target_os = "macos")]
fn launchd_service_target() -> String {
    use nix::unistd::getuid;

    format!("gui/{}/{}", getuid().as_raw(), LAUNCHD_SERVICE_LABEL)
}

#[cfg(target_os = "macos")]
fn launchd_service_state() -> Result<Option<LaunchdServiceState>> {
    let service_target = launchd_service_target();
    let output = Command::new("launchctl")
        .args(["print", &service_target])
        .output()
        .map_err(|e| Error::ConfigError(format!("Failed to query launchd service: {}", e)))?;

    if !output.status.success() {
        return Ok(None);
    }

    Ok(Some(parse_launchd_service_state(&String::from_utf8_lossy(
        &output.stdout,
    ))))
}

#[cfg(target_os = "macos")]
fn stop_launchd_service() -> Result<()> {
    let service_target = launchd_service_target();
    let output = Command::new("launchctl")
        .args(["bootout", &service_target])
        .output()
        .map_err(|e| Error::ConfigError(format!("Failed to stop launchd service: {}", e)))?;

    if output.status.success() {
        return Ok(());
    }

    Err(Error::ConfigError(format!(
        "Failed to stop launchd service {}: {}",
        LAUNCHD_SERVICE_LABEL,
        String::from_utf8_lossy(&output.stderr).trim()
    )))
}

#[cfg(target_os = "macos")]
fn restart_launchd_service() -> Result<()> {
    let service_target = launchd_service_target();
    let output = Command::new("launchctl")
        .args(["kickstart", "-k", &service_target])
        .output()
        .map_err(|e| Error::ConfigError(format!("Failed to restart launchd service: {}", e)))?;

    if output.status.success() {
        return Ok(());
    }

    Err(Error::ConfigError(format!(
        "Failed to restart launchd service {}: {}",
        LAUNCHD_SERVICE_LABEL,
        String::from_utf8_lossy(&output.stderr).trim()
    )))
}

#[cfg(target_os = "macos")]
fn is_otelite_command(command: &str) -> bool {
    Path::new(command.trim())
        .file_name()
        .is_some_and(|name| name == "otelite")
}

#[cfg(target_os = "macos")]
fn is_otelite_process(pid: u32) -> Result<bool> {
    let output = Command::new("ps")
        .args(["-p", &pid.to_string(), "-o", "comm="])
        .output()
        .map_err(|e| Error::ConfigError(format!("Failed to inspect local process: {}", e)))?;

    Ok(output.status.success() && is_otelite_command(&String::from_utf8_lossy(&output.stdout)))
}

#[cfg(target_os = "macos")]
fn ensure_otelite_process(pid: u32) -> Result<()> {
    if is_otelite_process(pid)? {
        return Ok(());
    }

    Err(Error::ConfigError(format!(
        "Otelite process {} exited or was replaced; refusing to signal it",
        pid
    )))
}

#[cfg(target_os = "macos")]
fn pid_file_otelite_pid() -> Result<Option<u32>> {
    let Some(pid) = read_pid()? else {
        return Ok(None);
    };

    if is_process_running(pid) && is_otelite_process(pid)? {
        Ok(Some(pid))
    } else {
        Ok(None)
    }
}

#[cfg(target_os = "macos")]
fn local_otelite_pid() -> Result<Option<u32>> {
    let output = Command::new("lsof")
        .args(["-nP", "-t", "-iTCP:4317", "-sTCP:LISTEN"])
        .output()
        .map_err(|e| {
            Error::ConfigError(format!("Failed to discover local otelite process: {}", e))
        })?;

    if !output.status.success() {
        return Ok(None);
    }

    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let Ok(pid) = line.parse::<u32>() else {
            continue;
        };

        if is_otelite_process(pid)? {
            return Ok(Some(pid));
        }
    }

    Ok(None)
}

/// Check if a process with the given PID is running
fn is_process_running(pid: u32) -> bool {
    #[cfg(unix)]
    {
        use nix::sys::signal::kill;
        use nix::unistd::Pid;

        // Send signal 0 to check if process exists without delivering a signal
        match kill(Pid::from_raw(pid as i32), None) {
            Ok(_) => true,
            Err(nix::errno::Errno::ESRCH) => false, // No such process
            Err(_) => true, // Process exists but we can't signal it (permission issue)
        }
    }

    #[cfg(not(unix))]
    {
        // On non-Unix systems, just check if PID file exists
        // This is a fallback and not as reliable
        warn!("Process check not fully supported on this platform");
        true
    }
}

/// Start otelite as a background daemon
pub async fn handle_start(storage_path: Option<PathBuf>, addr: String) -> Result<()> {
    if let Some(pid) = read_pid()? {
        if is_process_running(pid) {
            return Err(Error::ConfigError(format!(
                "Otelite is already running with PID {}",
                pid
            )));
        } else {
            warn!("Stale PID file found, removing it");
            remove_pid_file()?;
        }
    }

    info!("Starting otelite daemon...");

    let exe_path = std::env::current_exe()
        .map_err(|e| Error::ConfigError(format!("Failed to get executable path: {}", e)))?;

    let log_file = get_log_file()?;

    let log_file_handle = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&log_file)
        .map_err(|e| Error::ConfigError(format!("Failed to open log file: {}", e)))?;

    let mut cmd = Command::new(&exe_path);
    cmd.arg("serve").arg("--addr").arg(&addr);
    if let Some(path) = &storage_path {
        cmd.arg("--storage-path").arg(path);
    }
    let child =
        cmd.stdin(Stdio::null())
            .stdout(log_file_handle.try_clone().map_err(|e| {
                Error::ConfigError(format!("Failed to clone log file handle: {}", e))
            })?)
            .stderr(log_file_handle)
            .spawn()
            .map_err(|e| Error::ConfigError(format!("Failed to spawn daemon process: {}", e)))?;

    let pid = child.id();
    write_pid(pid)?;

    let storage_display = storage_path
        .as_deref()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| StorageConfig::default_data_dir().display().to_string());

    println!("✓ Otelite daemon started with PID {}", pid);
    println!("  Logs: {}", log_file.display());
    println!("  Storage: {}", storage_display);
    println!("  Dashboard: http://{}", addr);
    println!("\nUse 'otelite stop' to stop the daemon");
    println!("Use 'otelite status' to check daemon status");

    Ok(())
}

/// Stop the otelite daemon
pub async fn handle_stop() -> Result<()> {
    #[cfg(target_os = "macos")]
    if launchd_service_state()?.is_some() {
        stop_launchd_service()?;
        println!("✓ Otelite launchd service stopped");
        return Ok(());
    }

    #[cfg(target_os = "macos")]
    let pid = pid_file_otelite_pid()?
        .or(local_otelite_pid()?)
        .ok_or_else(|| Error::ConfigError("Otelite daemon is not running".to_string()))?;

    #[cfg(not(target_os = "macos"))]
    let pid = match read_pid()? {
        Some(pid) if is_process_running(pid) => pid,
        Some(_) => {
            warn!("PID file exists but process is not running, cleaning up");
            remove_pid_file()?;
            return Err(Error::ConfigError(
                "Otelite daemon is not running".to_string(),
            ));
        },
        None => {
            return Err(Error::ConfigError(
                "Otelite daemon is not running (no PID file found)".to_string(),
            ));
        },
    };

    info!("Stopping otelite daemon (PID {})...", pid);

    #[cfg(unix)]
    {
        use nix::sys::signal::{kill, Signal};
        use nix::unistd::Pid;

        // Send SIGTERM for graceful shutdown
        #[cfg(target_os = "macos")]
        ensure_otelite_process(pid)?;
        kill(Pid::from_raw(pid as i32), Signal::SIGTERM)
            .map_err(|e| Error::ConfigError(format!("Failed to send SIGTERM to process: {}", e)))?;

        // Wait for process to exit (with timeout)
        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_secs(10);

        while is_process_running(pid) {
            if start.elapsed() > timeout {
                warn!("Process did not exit gracefully, sending SIGKILL");
                #[cfg(target_os = "macos")]
                ensure_otelite_process(pid)?;
                kill(Pid::from_raw(pid as i32), Signal::SIGKILL).map_err(|e| {
                    Error::ConfigError(format!("Failed to send SIGKILL to process: {}", e))
                })?;
                break;
            }
            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
        }
    }

    #[cfg(not(unix))]
    {
        return Err(Error::ConfigError(
            "Stop command not supported on this platform".to_string(),
        ));
    }

    if read_pid()? == Some(pid) {
        remove_pid_file()?;
    }
    println!("✓ Otelite daemon stopped");

    Ok(())
}

/// Stop the running daemon and start a fresh one
pub async fn handle_restart(storage_path: Option<PathBuf>, addr: String) -> Result<()> {
    #[cfg(target_os = "macos")]
    if launchd_service_state()?.is_some() {
        restart_launchd_service()?;
        println!("✓ Otelite launchd service restarted");
        return Ok(());
    }

    // Verify a daemon is actually running before attempting restart
    match read_pid()? {
        None => {
            return Err(Error::ConfigError(
                "No otelite daemon is running. Use 'otelite start' to start one.".to_string(),
            ));
        },
        Some(pid) if !is_process_running(pid) => {
            return Err(Error::ConfigError(
                "No otelite daemon is running. Use 'otelite start' to start one.".to_string(),
            ));
        },
        _ => {},
    }

    println!("Stopping daemon...");
    handle_stop().await?;

    println!("Daemon stopped. Starting fresh...");
    handle_start(storage_path, addr).await
}

fn display_running_status(pid: u32, supervisor: Option<&str>) -> Result<()> {
    match supervisor {
        Some(supervisor) => println!("Status: Running ({})", supervisor),
        None => println!("Status: Running"),
    }
    println!("PID: {}", pid);

    // Try to get process uptime on Unix systems
    #[cfg(unix)]
    {
        if let Ok(output) = Command::new("ps")
            .args(["-p", &pid.to_string(), "-o", "etime="])
            .output()
        {
            if output.status.success() {
                if let Ok(uptime) = String::from_utf8(output.stdout) {
                    println!("Uptime: {}", uptime.trim());
                }
            }
        }
    }

    let log_file = get_log_file()?;
    println!("Logs: {}", log_file.display());

    let runtime_dir = get_runtime_dir()?;
    println!("Runtime directory: {}", runtime_dir.display());

    Ok(())
}

/// Show the status of the otelite daemon
pub async fn handle_status() -> Result<()> {
    #[cfg(target_os = "macos")]
    if let Some(LaunchdServiceState::Running(pid)) = launchd_service_state()? {
        return display_running_status(pid, Some("launchd: dev.otelite.daemon"));
    }

    #[cfg(target_os = "macos")]
    if let Some(pid) = pid_file_otelite_pid()? {
        return display_running_status(pid, Some("local process"));
    }

    #[cfg(target_os = "macos")]
    if let Some(pid) = local_otelite_pid()? {
        return display_running_status(pid, Some("local process"));
    }

    #[cfg(not(target_os = "macos"))]
    match read_pid()? {
        Some(pid) if is_process_running(pid) => return display_running_status(pid, None),
        Some(_) => warn!("PID file exists but process is not running"),
        None => {},
    }

    if read_pid()?.is_some() {
        println!("Status: Not running (stale PID file)");
        warn!("Cleaning up stale PID file");
        remove_pid_file()?;
    } else {
        println!("Status: Not running");
    }

    Ok(())
}

/// Install otelite as a system service
pub async fn handle_service_install() -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        install_launchd_service().await
    }

    #[cfg(target_os = "linux")]
    {
        install_systemd_service().await
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        Err(Error::ConfigError(
            "Service installation not supported on this platform".to_string(),
        ))
    }
}

/// Install otelite as a launchd service on macOS
#[cfg(target_os = "macos")]
async fn install_launchd_service() -> Result<()> {
    let home = std::env::var("HOME")
        .map_err(|_| Error::ConfigError("HOME environment variable not set".to_string()))?;

    let launch_agents_dir = PathBuf::from(&home).join("Library/LaunchAgents");

    if !launch_agents_dir.exists() {
        fs::create_dir_all(&launch_agents_dir).map_err(|e| {
            Error::ConfigError(format!("Failed to create LaunchAgents directory: {}", e))
        })?;
    }

    let plist_path = launch_agents_dir.join("dev.otelite.daemon.plist");
    let exe_path = std::env::current_exe()
        .map_err(|e| Error::ConfigError(format!("Failed to get executable path: {}", e)))?;

    let log_file = get_log_file()?;

    let plist_content = format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>dev.otelite.daemon</string>
    <key>ProgramArguments</key>
    <array>
        <string>{}</string>
        <string>serve</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>{}</string>
    <key>StandardErrorPath</key>
    <string>{}</string>
</dict>
</plist>
"#,
        exe_path.display(),
        log_file.display(),
        log_file.display()
    );

    fs::write(&plist_path, plist_content)
        .map_err(|e| Error::ConfigError(format!("Failed to write plist file: {}", e)))?;

    println!(
        "✓ Service configuration created at {}",
        plist_path.display()
    );
    println!("\nTo enable the service, run:");
    println!("  launchctl load {}", plist_path.display());
    println!("\nTo disable the service, run:");
    println!("  launchctl unload {}", plist_path.display());

    Ok(())
}

/// Install otelite as a systemd service on Linux
#[cfg(target_os = "linux")]
async fn install_systemd_service() -> Result<()> {
    let home = std::env::var("HOME")
        .map_err(|_| Error::ConfigError("HOME environment variable not set".to_string()))?;

    let systemd_user_dir = PathBuf::from(&home).join(".config/systemd/user");

    // Create directory if it doesn't exist
    if !systemd_user_dir.exists() {
        fs::create_dir_all(&systemd_user_dir).map_err(|e| {
            Error::ConfigError(format!("Failed to create systemd user directory: {}", e))
        })?;
    }

    let unit_path = systemd_user_dir.join("otelite.service");
    let exe_path = std::env::current_exe()
        .map_err(|e| Error::ConfigError(format!("Failed to get executable path: {}", e)))?;

    let unit_content = format!(
        r#"[Unit]
Description=Otelite OpenTelemetry Collector
After=network.target

[Service]
Type=simple
ExecStart={} serve
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
"#,
        exe_path.display()
    );

    fs::write(&unit_path, unit_content)
        .map_err(|e| Error::ConfigError(format!("Failed to write systemd unit file: {}", e)))?;

    println!("✓ Service configuration created at {}", unit_path.display());
    println!("\nTo enable and start the service, run:");
    println!("  systemctl --user daemon-reload");
    println!("  systemctl --user enable otelite.service");
    println!("  systemctl --user start otelite.service");
    println!("\nTo check service status:");
    println!("  systemctl --user status otelite.service");
    println!("\nTo disable the service:");
    println!("  systemctl --user stop otelite.service");
    println!("  systemctl --user disable otelite.service");

    Ok(())
}

#[cfg(test)]
#[cfg(target_os = "macos")]
mod tests {
    use super::{parse_launchd_service_state, LaunchdServiceState};

    #[test]
    fn test_parse_launchd_service_state_detects_running_service() {
        let output = r#"
gui/501/dev.otelite.daemon = {
    state = running
    pid = 7351
}
"#;

        assert_eq!(
            parse_launchd_service_state(output),
            LaunchdServiceState::Running(7351)
        );
    }

    #[test]
    fn test_parse_launchd_service_state_detects_loaded_non_running_service() {
        let output = r#"
gui/501/dev.otelite.daemon = {
    state = spawn scheduled
    pid = 7351
}
"#;

        assert_eq!(
            parse_launchd_service_state(output),
            LaunchdServiceState::Loaded
        );
    }

    #[test]
    fn test_is_otelite_command_accepts_only_otelite_executable() {
        assert!(super::is_otelite_command(
            "/Users/jonesn/.local/bin/otelite"
        ));
        assert!(!super::is_otelite_command("/usr/bin/python3"));
    }
}