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
use std::fs::{File, Permissions};
use std::io::Write as _;
use std::os::unix::fs::PermissionsExt as _;
use std::path::PathBuf;
use std::process::exit;
use std::time::Duration;

use daemonize::{Daemonize, Stdio};
use futures::Future;
use tempfile::TempDir;
use tokio::io::AsyncWriteExt as _;
use tokio::net::{UnixListener, UnixStream};
use tokio::process::Command;
use tokio::runtime::Builder as RuntimeBuilder;
use tokio::select;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, trace, warn};
use url::Url;

use crate::daemon_trait::LlmConfig;
use crate::mlc_daemon::bootstrap::{PYPROJECT, SCRIPT};
use crate::LlmDaemon;

pub struct DaemonConfig {
    pub sock_file: String,
    pub pid_file: String,
    pub stdout: String,
    pub stderr: String,
    // default: 127.0.0.1
    pub host: String,
    // default: 8000
    pub port: u16,
    // default: HF://mlc-ai/gemma-2b-it-q4f16_1-MLC
    pub model: String,
}

impl Default for DaemonConfig {
    fn default() -> Self {
        Self {
            sock_file: "/tmp/mlc-daemon2.sock".to_string(),
            pid_file: "/tmp/mlc-daemon2.pid".to_string(),
            stdout: "/tmp/mlc-daemon2.stdout".to_string(),
            stderr: "/tmp/mlc-daemon2.stderr".to_string(),
            host: "127.0.0.1".to_string(),
            port: 8000,
            model: "HF://mlc-ai/gemma-2b-it-q4f16_1-MLC".to_string(),
        }
    }
}

impl LlmConfig for DaemonConfig {
    fn endpoint(&self) -> Url {
        url::Url::parse(&format!(
            "http://{}:{}/v1/completions",
            self.host, self.port
        ))
        .expect("failed to parse url")
    }
}

pub struct Daemon {
    config: DaemonConfig,
}

impl Daemon {
    pub fn new(config: DaemonConfig) -> Self {
        Self { config }
    }
}

impl LlmDaemon for Daemon {
    type Config = DaemonConfig;

    fn fork_daemon(&self) -> anyhow::Result<()> {
        let config = &self.config;
        let port_str = config.port.to_string();
        let args: Vec<&str> =
            vec![&config.model, "--host", &config.host, "--port", &port_str];

        let stdout: Stdio = File::create(&config.stdout)
            .map(|v| v.into())
            .unwrap_or_else(|err| {
                warn!("failed to open stdout: {:?}", err);
                Stdio::keep()
            });
        let stderr: Stdio = File::create(&config.stderr)
            .map(|v| v.into())
            .unwrap_or_else(|err| {
                warn!("failed to open stderr: {:?}", err);
                Stdio::keep()
            });

        let daemon = Daemonize::new()
            .pid_file(&config.pid_file)
            .stdout(stdout)
            .stderr(stderr);

        match daemon.execute() {
            daemonize::Outcome::Child(res) => {
                if res.is_err() {
                    let _ = std::io::stdout().write_all(format!("Failed to spawn a daemon - maybe another daemon is already running?: {:?}\n", res.err()).as_bytes());
                    exit(0)
                }
                let _ = std::io::stdout().write_all(
                    format!("Daemon spawned: {:?}\n", std::env::current_dir())
                        .as_bytes(),
                );
                let runtime = RuntimeBuilder::new_current_thread()
                    .enable_time()
                    .enable_io()
                    .build()
                    .expect("failed to create runtime");
                runtime.block_on(async {
                    let bootstrap: anyhow::Result<(TempDir, PathBuf)> = (|| {
                        let temp_dir = tempfile::tempdir()?;
                        let _ = std::io::stdout().write_all(format!("temp dir: {:?}\n", temp_dir.path()).as_bytes());
                        let file1_path = temp_dir.path().join("pyproject.toml");
                        let mut file1 = File::create(file1_path)?;
                        file1.write_all(PYPROJECT.as_bytes())?;
                        file1.sync_all()?;
                        let file2_path = temp_dir.path().join("script.sh");
                        let mut file2 = File::create(file2_path.clone())?;
                        file2.write_all(SCRIPT.as_bytes())?;
                        file2.sync_all()?;
                        std::fs::set_permissions(file2_path.clone(), Permissions::from_mode(0o755))?;
                        Ok((temp_dir, file2_path))
                    })();

                    let Ok((temp_dir, file2_path)) = bootstrap else {
                        let _ = std::io::stdout().write_all(format!("failed to bootstrap: {:?}\n", bootstrap.err()).as_bytes());
                        panic!("what should I do");
                    };
                    let mut cmd = Command::new(file2_path)
                        .stdout(std::process::Stdio::inherit())
                        .stderr(std::process::Stdio::inherit())
                        .current_dir(temp_dir.path())
                        .args(args)
                        .spawn()
                        .expect("failed to spawn child");

                    let _ = std::io::stdout().write_all(format!("child: {:?}\n", cmd.id()).as_bytes());

                    let listener =
                        UnixListener::bind(&config.sock_file).expect("Failed to open socket");
                    let mut sigterms =
                        signal(SignalKind::terminate()).expect("failed to add SIGTERM handler");
                    let _ = std::io::stdout().write_all("Starting loop\n".as_bytes());
                    let _ = std::io::stdout().flush();
                    loop {
                        select! {
                           _ = sigterms.recv() => {
                               let _ = std::io::stdout().write_all("Got SIGTERM, closing\n".as_bytes());
                               break;
                           },
                           exit_status = cmd.wait() => {
                               let _ = std::io::stdout().write_all(format!("Child got closed: {:?}\n", exit_status).as_bytes());
                               break;
                           },
                           res = listener.accept() => {
                               let Ok((mut stream, _)) = res else {
                                   let _ = std::io::stdout().write_all("Failed to accept a socket, closing\n".as_bytes());
                                   break;
                               };
                               let mut buf = [0u8; 32];
                               loop {
                                   let _ = stream.readable().await;
                                   match stream.try_read(&mut buf) {
                                        Ok(sz) => {
                                            let _ = std::io::stdout().write_all(format!("Got {:?}, continue...\n", sz).as_bytes());
                                            break;
                                        },
                                        Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                                            continue;
                                        },
                                        Err(err) => {
                                            let _ = std::io::stdout().write_all(format!("Error {:?}, exiting...\n", err).as_bytes());
                                            break;
                                        }
                                    }
                               }
                               let _ = stream.shutdown().await;
                           },
                           _ = tokio::time::sleep(Duration::from_secs(2)) => {
                               let _ = std::io::stdout().write_all("No activitiy for 10 seconds, closing...\n".as_bytes());
                               break;
                           },
                        }
                    }
                    // Child might be already killed, so ignore the error
                    let _ = std::io::stdout().write_all(format!("Closing child: {:?}\n", cmd.id()).as_bytes());
                    cmd.kill().await.ok();
                    // To make sure temp_dir is alive until here
                    drop(temp_dir);
                });
                std::fs::remove_file(&config.sock_file).ok();
                let _ = std::io::stdout()
                    .write_all("Server closed\n".as_bytes());
                exit(0)
            },
            daemonize::Outcome::Parent(res) => {
                res.expect("parent should have no problem");
            },
        }
        Ok(())
    }

    fn heartbeat(
        &self,
    ) -> impl Future<Output = anyhow::Result<()>> + Send + 'static {
        let sock_file = self.config.sock_file.clone();
        async move {
            loop {
                tokio::time::sleep(Duration::from_secs(1)).await;
                trace!(sock_file = &sock_file, "Running scheduled loop");
                if std::fs::metadata(&sock_file).is_err() {
                    trace!(
                        sock_file = &sock_file,
                        "Cannot get file metadata, retry later"
                    );
                    continue;
                }
                let stream = UnixStream::connect(&sock_file).await?;
                stream.writable().await?;
                match stream.try_write(&[0]) {
                    Ok(_) => {
                        info!("sent heartbeat");
                    },
                    Err(err) => {
                        warn!("Cannot send heartbeat: {:?}", err);
                    },
                };
            }
        }
    }
    
    fn config(&self) -> &Self::Config {
        &self.config
    }
}

#[cfg(test)]
mod tests {
    use tokio::runtime::Builder as RuntimeBuilder;
    use tracing_test::traced_test;

    use super::{Daemon, DaemonConfig};
    use crate::daemon_trait::LlmConfig as _;
    use crate::test_client::Generator;
    use crate::LlmDaemon as _;

    #[traced_test]
    #[test]
    fn launch_daemon() -> anyhow::Result<()> {
        let conf = DaemonConfig::default();
        let endpoint = conf.endpoint();
        let inst = Daemon::new(conf);

        inst.fork_daemon()?;
        let runtime = RuntimeBuilder::new_current_thread()
            .enable_time()
            .enable_io()
            .build()
            .expect("failed to create runtime");
        runtime.spawn(inst.heartbeat());
        runtime.block_on(async {
            inst.ready().await;
            let gen = Generator::new(endpoint, None);
            let resp = gen
                .generate("<bos>Sum of 7 and 8 is ".to_string())
                .await
                .expect("failed to generate");
            assert!(resp.contains("15"));
        });
        Ok(())
    }
}