aboutsummaryrefslogtreecommitdiffstats
path: root/crates/daemon/src/main.rs
blob: 59d4c7ff51110fd580fd796cc44e932d28845a49 (plain) (blame)
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
#![expect(unused_crate_dependencies)]

use std::{
    fs::{self, File, OpenOptions},
    io::Write,
    path::{Path, PathBuf},
    time::{Duration, Instant},
};

use clap::Parser;
use eyre::WrapErr;
use eyre::{Context, Result, bail, eyre};
use fs4::fs_std::FileExt;
use tokio::time::sleep;

use crate::{
    aclient::{database::ClientSqlite, record::sqlite_store::SqliteStore, settings::Settings},
    api::{control::ControlService, history::HistoryService},
    daemon::Daemon,
};

pub(crate) mod aclient;
pub(crate) mod api;
pub(crate) mod daemon;
pub(crate) mod events;
pub(crate) mod server;

const DAEMON_VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(Parser, Debug)]
#[command(infer_subcommands = true)]
enum Cmd {
    /// Start the daemon server
    Start {
        /// Also write daemon logs to the console (useful for debugging)
        #[arg(long)]
        show_logs: bool,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    let settings = Settings::new().wrap_err("could not load client settings")?;
    let db_path = PathBuf::from(settings.db_path.as_str());
    let record_store_path = PathBuf::from(settings.record_store_path.as_str());

    let history_db = ClientSqlite::new(db_path, settings.local_timeout).await?;
    let sqlite_store = SqliteStore::new(record_store_path, settings.local_timeout).await?;

    match Cmd::parse() {
        Cmd::Start { show_logs, .. } => boot(settings, sqlite_store, history_db).await,
    }
}

/// Boot the daemon.
///
/// This creates a daemon,
/// starts the gRPC server with services, and runs the event loop.
async fn boot(settings: Settings, store: SqliteStore, history_db: ClientSqlite) -> Result<()> {
    let pidfile_path = PathBuf::from(&settings.daemon.pidfile_path);
    let _pidfile_guard = PidfileGuard::acquire(&pidfile_path)?;

    let mut daemon = Daemon::builder(settings.clone())
        .store(store)
        .history_db(history_db.clone())
        .build()?;

    let handle = {
        let handle = daemon.handle();

        // Spawn signal handler to emit ShutdownRequested on Ctrl+C/SIGTERM
        let signal_handle = handle.clone();
        tokio::spawn(async move {
            shutdown_signal().await;
            tracing::info!("received shutdown signal");
            signal_handle.shutdown();
        });

        handle
    };

    let history_service = HistoryService::new(handle.clone(), history_db).await?;
    let control_service = ControlService::new(handle.clone());

    server::run_grpc_server(
        &settings,
        history_service.into_server(),
        control_service.into_server(),
        handle,
    )?;

    daemon.run_event_loop().await?;

    tracing::info!("daemon shut down complete");
    Ok(())
}

/// Wait for a shutdown signal (Ctrl+C or SIGTERM).
#[cfg(unix)]
async fn shutdown_signal() {
    let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
        .expect("failed to register sigterm handler");
    let mut int = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())
        .expect("failed to register sigint handler");

    tokio::select! {
        _ = term.recv() => {},
        _ = int.recv() => {},
    }
}

struct PidfileGuard {
    file: File,
}

impl PidfileGuard {
    fn acquire(path: &Path) -> Result<Self> {
        let mut file = open_lock_file(path)?;

        if !file.try_lock_exclusive()? {
            bail!(
                "daemon already running (pidfile lock busy at {})",
                path.display()
            );
        }

        file.set_len(0)
            .wrap_err_with(|| format!("could not truncate daemon pidfile {}", path.display()))?;
        writeln!(file, "{}", std::process::id())
            .and_then(|()| writeln!(file, "{DAEMON_VERSION}"))
            .wrap_err_with(|| format!("could not write daemon pidfile {}", path.display()))?;

        Ok(Self { file })
    }
}

impl Drop for PidfileGuard {
    fn drop(&mut self) {
        drop(self.file.unlock());
    }
}

fn open_lock_file(path: &Path) -> Result<File> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .wrap_err_with(|| format!("could not create lock directory {}", parent.display()))?;
    }

    OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(path)
        .wrap_err_with(|| format!("could not open lock file {}", path.display()))
}

async fn wait_for_lock(path: &Path, timeout: Duration) -> Result<File> {
    const LOCK_POLL: Duration = Duration::from_millis(20);

    let file = open_lock_file(path)?;
    let start = Instant::now();

    loop {
        match file.try_lock_exclusive() {
            Ok(true) => return Ok(file),
            Ok(false) => {
                if start.elapsed() >= timeout {
                    bail!("timed out waiting for lock at {}", path.display());
                }

                sleep(LOCK_POLL).await;
            }
            Err(err) => {
                return Err(eyre!("could not lock {}: {err}", path.display()));
            }
        }
    }
}

async fn wait_for_pidfile_available(path: &Path, timeout: Duration) -> Result<()> {
    let file = wait_for_lock(path, timeout).await?;
    file.unlock()
        .wrap_err_with(|| format!("failed to unlock {}", path.display()))?;
    Ok(())
}