Skip to main content

wasi_virt_layer_cli/
fallback_command.rs

1use std::{
2    fs::File,
3    io::{Read as _, Seek as _, Write as _},
4};
5
6use eyre::Context as _;
7use fs2::FileExt as _;
8use tempfile::Builder as TempFileBuilder;
9
10pub(crate) const COMMAND_ALTERNATE_ENV_VAR: &str = "WASI_VIRT_LAYER_FALLBACK_ALTERNATE_COMMAND";
11
12#[allow(unused)]
13pub(crate) fn wasm_opt(args: &[String]) -> i32 {
14    #[cfg(feature = "fallback")]
15    {
16        let mut command = wasm_opt::integration::Command::new("wasm-opt");
17        command.args(args.iter().skip(1));
18
19        match wasm_opt::integration::run_from_command_args(command) {
20            Ok(()) => 0,
21            Err(err) => {
22                eprintln!("wasm-opt fallback failed: {err}");
23                1
24            }
25        }
26    }
27    #[cfg(not(feature = "fallback"))]
28    {
29        eprintln!("wasm-opt fallback is not enabled");
30        1
31    }
32}
33
34fn fake_fallback(args: &[String]) -> i32 {
35    unimplemented!("This is a fake fallback function. It should never be called. Args: {args:?}");
36}
37
38/// Gets a `FallbackCommand` for the specified binary, with a fallback function that will be called if the binary is not found.
39pub fn get_fallback_command(
40    bin: impl AsRef<str>,
41) -> FallbackCommand<impl FnOnce(&[String]) -> i32 + Send + 'static> {
42    match bin.as_ref() {
43        "wasm-opt" => FallbackCommand::new("wasm-opt", fake_fallback),
44        _ => panic!("Unsupported fallback command specified: {}", bin.as_ref()),
45    }
46}
47
48/// A command that can fall back to a Rust function if the binary is not found.
49pub struct FallbackCommand<F>
50where
51    F: FnOnce(&[String]) -> i32 + Send + 'static,
52{
53    /// The binary name.
54    pub bin: String,
55    /// The arguments to the command.
56    pub args: Vec<String>,
57    /// The optional fallback function.
58    pub func: Option<F>,
59}
60
61const DISABLE_FALLBACK: bool = false;
62
63/// A file-based lock to prevent concurrent execution of commands.
64pub struct CommandLock {
65    locks: Vec<(File, String)>,
66}
67
68impl<F> FallbackCommand<F>
69where
70    F: FnOnce(&[String]) -> i32 + Send + 'static,
71{
72    /// Creates a new `FallbackCommand` with the specified binary and fallback function.
73    pub fn new(bin: impl AsRef<str>, func: F) -> Self {
74        Self {
75            bin: bin.as_ref().to_string(),
76            args: Vec::new(),
77            func: Some(func),
78        }
79    }
80
81    /// Adds an argument to the command.
82    pub fn arg(&mut self, arg: impl AsRef<str>) -> &mut Self {
83        self.args.push(arg.as_ref().to_string());
84        self
85    }
86
87    /// Adds multiple arguments to the command.
88    pub fn args<I, S>(&mut self, args: I) -> &mut Self
89    where
90        I: IntoIterator<Item = S>,
91        S: AsRef<str>,
92    {
93        for arg in args {
94            self.arg(arg.as_ref());
95        }
96        self
97    }
98
99    /// Spawns the command, either as a child process or as a fallback thread.
100    pub fn spawn(&mut self) -> std::io::Result<FallbackChild> {
101        let mut cmd = std::process::Command::new(&self.bin);
102        let setter = |cmd: &mut std::process::Command| {
103            cmd.args(&self.args);
104            let piped_out = std::process::Stdio::piped();
105            let piped_err = std::process::Stdio::piped();
106            cmd.stdout(piped_out);
107            cmd.stderr(piped_err);
108        };
109        setter(&mut cmd);
110        match cmd.spawn() {
111            Ok(child) => Ok(FallbackChild::new_process(child)),
112            Err(e) if e.kind() == std::io::ErrorKind::NotFound && DISABLE_FALLBACK => {
113                let _ = self.func.take();
114                Err(e)
115            }
116            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
117                // // Fallback to the provided function
118                // let args = self.args.clone();
119                // let func = self.func.take().expect("Function already taken");
120                // let handle = std::thread::spawn(move || {
121                //     let log = std::fs::OpenOptions::new()
122                //         .truncate(true)
123                //         .read(true)
124                //         .create(true)
125                //         .write(true)
126                //         .open(get_temp_filepath())
127                //         .unwrap();
128
129                //     let print_redirect = gag::Redirect::stdout(log).unwrap();
130
131                //     let result = (func)(&args);
132
133                //     // Extract redirect
134                //     let mut log = print_redirect.into_inner();
135
136                //     let mut buf = String::new();
137                //     log.seek(std::io::SeekFrom::Start(0)).unwrap();
138                //     log.read_to_string(&mut buf).unwrap();
139
140                //     FallbackOutput {
141                //         stdout: buf.into_bytes(),
142                //         stderr: Vec::new(),
143                //         success: result == 0,
144                //     }
145                // });
146                // Ok(FallbackChild::new_thread(handle))
147
148                // Fallback to self call with env var
149                let mut cmd = std::process::Command::new(std::env::current_exe().unwrap());
150                setter(&mut cmd);
151                cmd.env(COMMAND_ALTERNATE_ENV_VAR, &self.bin);
152                let child = cmd.spawn()?;
153                Ok(FallbackChild::new_process(child))
154            }
155            Err(e) => Err(e),
156        }
157    }
158}
159
160/// A handle to a spawned fallback command, which could be a process or a thread.
161pub enum FallbackChild {
162    /// A child process handle.
163    Process(std::process::Child),
164    /// A handle to a thread running the fallback function.
165    Thread(std::thread::JoinHandle<FallbackOutput>),
166}
167
168impl FallbackChild {
169    fn new_process(child: std::process::Child) -> Self {
170        FallbackChild::Process(child)
171    }
172
173    #[allow(unused)]
174    fn new_thread(handle: std::thread::JoinHandle<FallbackOutput>) -> Self {
175        FallbackChild::Thread(handle)
176    }
177
178    /// Waits for the command to finish and returns its output.
179    pub fn wait_with_output(self) -> std::io::Result<FallbackOutput> {
180        match self {
181            FallbackChild::Process(child) => {
182                let output = child.wait_with_output()?;
183                Ok(FallbackOutput {
184                    stdout: output.stdout,
185                    stderr: output.stderr,
186                    success: output.status.success(),
187                })
188            }
189            FallbackChild::Thread(handle) => {
190                let out = handle.join().expect("Thread panicked");
191                Ok(out)
192            }
193        }
194    }
195}
196
197/// The output of a finished fallback command.
198pub struct FallbackOutput {
199    /// The standard output of the command.
200    pub stdout: Vec<u8>,
201    /// The standard error of the command.
202    pub stderr: Vec<u8>,
203    /// Whether the command exited successfully.
204    pub success: bool,
205}
206
207impl CommandLock {
208    /// Acquires the command locks for the specified identifiers using a master-lock strategy to prevent deadlocks.
209    pub fn acquire(ids: &[String]) -> eyre::Result<Self> {
210        let mut sorted_ids = ids.to_vec();
211        sorted_ids.sort();
212        sorted_ids.dedup();
213
214        // 1. Ensure temp dir exists
215        let temp_dir = std::env::temp_dir().join(env!("CARGO_PKG_NAME"));
216        std::fs::create_dir_all(&temp_dir).wrap_err("Failed to create temp lock directory")?;
217
218        // 2. Acquire Master Lock to serialize acquisition phase
219        let master_path = temp_dir.join("master.lock");
220        let master_file = File::options()
221            .read(true)
222            .write(true)
223            .create(true)
224            .open(&master_path)
225            .wrap_err_with(|| {
226                format!("Failed to open master lock file: {}", master_path.display())
227            })?;
228
229        master_file
230            .lock_exclusive()
231            .wrap_err("Failed to acquire master lock")?;
232
233        let mut locks = Vec::new();
234
235        // 3. Acquire individual locks while holding the master lock
236        for id in sorted_ids {
237            let hash = {
238                use std::hash::{Hash, Hasher};
239                let mut hasher = std::collections::hash_map::DefaultHasher::new();
240                id.hash(&mut hasher);
241                format!("{:x}", hasher.finish())
242            };
243
244            let lock_path = get_temp_lock_filepath(&hash);
245            let lock_file = File::options()
246                .read(true)
247                .write(true)
248                .create(true)
249                .open(&lock_path)
250                .wrap_err_with(|| format!("Failed to open lock file: {lock_path}"))?;
251
252            if let Err(_) = lock_file.try_lock_exclusive() {
253                let mut pid_str = String::new();
254                let mut file = &lock_file;
255                let _ = file.read_to_string(&mut pid_str);
256                let pid_info = if pid_str.is_empty() {
257                    String::new()
258                } else {
259                    format!(" (held by PID {})", pid_str.trim())
260                };
261
262                eprintln!("Waiting for command lock for {} {}...", id, pid_info);
263
264                // We are holding the master lock, so we serialize all acquisitions.
265                // If we block here, other processes waiting for DIFFERENT locks will also be blocked
266                // at the master lock. This is acceptable for a CLI tool and prevents deadlock.
267                lock_file
268                    .lock_exclusive()
269                    .wrap_err_with(|| format!("Failed to lock command file: {lock_path}"))?;
270            }
271
272            // Write current PID to the lock file
273            let mut file = &lock_file;
274            let _ = file.set_len(0);
275            let _ = file.seek(std::io::SeekFrom::Start(0));
276            let _ = write!(file, "{}", std::process::id());
277            let _ = file.flush();
278
279            locks.push((lock_file, lock_path));
280        }
281
282        // 4. Release master lock
283        let _ = master_file.unlock();
284
285        Ok(Self { locks })
286    }
287}
288
289impl Drop for CommandLock {
290    fn drop(&mut self) {
291        for (file, _) in &mut self.locks {
292            let _ = file.unlock();
293        }
294    }
295}
296
297fn get_temp_filepath() -> String {
298    let mut builder = TempFileBuilder::new();
299    let prefix = format!("tmp_{}_", env!("CARGO_PKG_NAME"));
300    builder.prefix(&prefix);
301    builder.suffix(".log");
302
303    let builder = builder.tempfile_in(std::env::temp_dir());
304
305    let file = builder.expect("Failed to create temp log file");
306    let (_file, path) = file.keep().expect("Failed to persist temp log file");
307
308    path.to_string_lossy().into_owned()
309}
310
311fn get_temp_lock_filepath(hash: &str) -> String {
312    std::env::temp_dir()
313        .join(env!("CARGO_PKG_NAME"))
314        .join(format!("command_{}.lock", hash))
315        .to_string_lossy()
316        .into_owned()
317}
318
319/// require mutex
320pub fn check_gag() -> bool {
321    pub fn check_gag() -> Option<()> {
322        let gag = gag::Redirect::stdout(
323            std::fs::OpenOptions::new()
324                .truncate(true)
325                .read(true)
326                .create(true)
327                .write(true)
328                .open(get_temp_filepath())
329                .ok()?,
330        )
331        .ok()?;
332
333        const WHITE_SPACE: &str = " \t\n\r";
334
335        print!("{WHITE_SPACE}");
336        std::io::Write::flush(&mut std::io::stdout()).ok()?;
337
338        let mut stdout = gag.into_inner();
339        let mut buf = String::new();
340        stdout.seek(std::io::SeekFrom::Start(0)).ok()?;
341        stdout.read_to_string(&mut buf).ok()?;
342
343        Some(if buf.contains(WHITE_SPACE) {
344            ()
345        } else {
346            return None;
347        })
348    }
349
350    check_gag().is_some()
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356
357    static MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
358
359    #[cfg_attr(not(feature = "fallback"), ignore = "fallback feature disabled")]
360    #[test]
361    /// if not use nocapture arg, skip test.
362    /// because gag crate require it.
363    fn test_fallback_command() {
364        if DISABLE_FALLBACK {
365            return;
366        }
367
368        let _lock = MUTEX.lock().unwrap();
369        if !check_gag() {
370            return;
371        }
372
373        let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
374            println!("Fallback function called with args: {:?}", args);
375            0
376        });
377        cmd.arg("arg1").arg("arg2");
378
379        let child = cmd.spawn().expect("Failed to spawn command");
380        let output = child.wait_with_output().expect("Failed to get output");
381
382        assert!(output.success);
383        let stdout_str = String::from_utf8_lossy(&output.stdout);
384        assert!(stdout_str.contains("Fallback function called with args: [\"arg1\", \"arg2\"]"));
385
386        drop(_lock);
387    }
388}