wasi_virt_layer_cli/
fallback_command.rs1use 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 if args
17 .iter()
18 .any(|arg| arg.starts_with("--no-inline=__wvl_reactor_initialize"))
19 {
20 eprintln!(
24 "threaded reactor optimization requires native wasm-opt with --no-inline support; install wasm-opt or use --dev"
25 );
26 return 1;
27 }
28 let mut command = wasm_opt::integration::Command::new("wasm-opt");
29 command.args(args.iter().skip(1));
30
31 match wasm_opt::integration::run_from_command_args(command) {
32 Ok(()) => 0,
33 Err(err) => {
34 eprintln!("wasm-opt fallback failed: {err}");
35 1
36 }
37 }
38 }
39 #[cfg(not(feature = "fallback"))]
40 {
41 eprintln!("wasm-opt fallback is not enabled");
42 1
43 }
44}
45
46fn fake_fallback(args: &[String]) -> i32 {
47 unimplemented!("This is a fake fallback function. It should never be called. Args: {args:?}");
48}
49
50pub fn get_fallback_command(
52 bin: impl AsRef<str>,
53) -> FallbackCommand<impl FnOnce(&[String]) -> i32 + Send + 'static> {
54 match bin.as_ref() {
55 "wasm-opt" => FallbackCommand::new("wasm-opt", fake_fallback),
56 _ => panic!("Unsupported fallback command specified: {}", bin.as_ref()),
57 }
58}
59
60pub struct FallbackCommand<F>
62where
63 F: FnOnce(&[String]) -> i32 + Send + 'static,
64{
65 pub bin: String,
67 pub args: Vec<String>,
69 pub func: Option<F>,
71}
72
73const DISABLE_FALLBACK: bool = false;
74
75pub struct CommandLock {
77 locks: Vec<(File, String)>,
78}
79
80impl<F> FallbackCommand<F>
81where
82 F: FnOnce(&[String]) -> i32 + Send + 'static,
83{
84 pub fn new(bin: impl AsRef<str>, func: F) -> Self {
86 Self {
87 bin: bin.as_ref().to_string(),
88 args: Vec::new(),
89 func: Some(func),
90 }
91 }
92
93 pub fn arg(&mut self, arg: impl AsRef<str>) -> &mut Self {
95 self.args.push(arg.as_ref().to_string());
96 self
97 }
98
99 pub fn args<I, S>(&mut self, args: I) -> &mut Self
101 where
102 I: IntoIterator<Item = S>,
103 S: AsRef<str>,
104 {
105 for arg in args {
106 self.arg(arg.as_ref());
107 }
108 self
109 }
110
111 pub fn spawn(&mut self) -> std::io::Result<FallbackChild> {
113 let mut cmd = std::process::Command::new(&self.bin);
114 let setter = |cmd: &mut std::process::Command| {
115 cmd.args(&self.args);
116 let piped_out = std::process::Stdio::piped();
117 let piped_err = std::process::Stdio::piped();
118 cmd.stdout(piped_out);
119 cmd.stderr(piped_err);
120 };
121 setter(&mut cmd);
122 match cmd.spawn() {
123 Ok(child) => Ok(FallbackChild::new_process(child)),
124 Err(e) if e.kind() == std::io::ErrorKind::NotFound && DISABLE_FALLBACK => {
125 let _ = self.func.take();
126 Err(e)
127 }
128 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
129 let mut cmd = std::process::Command::new(std::env::current_exe().unwrap());
162 setter(&mut cmd);
163 cmd.env(COMMAND_ALTERNATE_ENV_VAR, &self.bin);
164 let child = cmd.spawn()?;
165 Ok(FallbackChild::new_process(child))
166 }
167 Err(e) => Err(e),
168 }
169 }
170}
171
172pub enum FallbackChild {
174 Process(std::process::Child),
176 Thread(std::thread::JoinHandle<FallbackOutput>),
178}
179
180impl FallbackChild {
181 fn new_process(child: std::process::Child) -> Self {
182 FallbackChild::Process(child)
183 }
184
185 #[allow(unused)]
186 fn new_thread(handle: std::thread::JoinHandle<FallbackOutput>) -> Self {
187 FallbackChild::Thread(handle)
188 }
189
190 pub fn wait_with_output(self) -> std::io::Result<FallbackOutput> {
192 match self {
193 FallbackChild::Process(child) => {
194 let output = child.wait_with_output()?;
195 Ok(FallbackOutput {
196 stdout: output.stdout,
197 stderr: output.stderr,
198 success: output.status.success(),
199 })
200 }
201 FallbackChild::Thread(handle) => {
202 let out = handle.join().expect("Thread panicked");
203 Ok(out)
204 }
205 }
206 }
207}
208
209pub struct FallbackOutput {
211 pub stdout: Vec<u8>,
213 pub stderr: Vec<u8>,
215 pub success: bool,
217}
218
219impl CommandLock {
220 pub fn acquire(ids: &[String]) -> eyre::Result<Self> {
222 let mut sorted_ids = ids.to_vec();
223 sorted_ids.sort();
224 sorted_ids.dedup();
225
226 let temp_dir = std::env::temp_dir().join(env!("CARGO_PKG_NAME"));
228 std::fs::create_dir_all(&temp_dir).wrap_err("Failed to create temp lock directory")?;
229
230 let master_path = temp_dir.join("master.lock");
232 let master_file = File::options()
233 .read(true)
234 .write(true)
235 .create(true)
236 .open(&master_path)
237 .wrap_err_with(|| {
238 format!("Failed to open master lock file: {}", master_path.display())
239 })?;
240
241 master_file
242 .lock_exclusive()
243 .wrap_err("Failed to acquire master lock")?;
244
245 let mut locks = Vec::new();
246
247 for id in sorted_ids {
249 let hash = {
250 use std::hash::{Hash, Hasher};
251 let mut hasher = std::collections::hash_map::DefaultHasher::new();
252 id.hash(&mut hasher);
253 format!("{:x}", hasher.finish())
254 };
255
256 let lock_path = get_temp_lock_filepath(&hash);
257 let lock_file = File::options()
258 .read(true)
259 .write(true)
260 .create(true)
261 .open(&lock_path)
262 .wrap_err_with(|| format!("Failed to open lock file: {lock_path}"))?;
263
264 if let Err(_) = lock_file.try_lock_exclusive() {
265 let mut pid_str = String::new();
266 let mut file = &lock_file;
267 let _ = file.read_to_string(&mut pid_str);
268 let pid_info = if pid_str.is_empty() {
269 String::new()
270 } else {
271 format!(" (held by PID {})", pid_str.trim())
272 };
273
274 eprintln!("Waiting for command lock for {} {}...", id, pid_info);
275
276 lock_file
280 .lock_exclusive()
281 .wrap_err_with(|| format!("Failed to lock command file: {lock_path}"))?;
282 }
283
284 let mut file = &lock_file;
286 let _ = file.set_len(0);
287 let _ = file.seek(std::io::SeekFrom::Start(0));
288 let _ = write!(file, "{}", std::process::id());
289 let _ = file.flush();
290
291 locks.push((lock_file, lock_path));
292 }
293
294 let _ = master_file.unlock();
296
297 Ok(Self { locks })
298 }
299}
300
301impl Drop for CommandLock {
302 fn drop(&mut self) {
303 for (file, _) in &mut self.locks {
304 let _ = file.unlock();
305 }
306 }
307}
308
309fn get_temp_filepath() -> String {
310 let mut builder = TempFileBuilder::new();
311 let prefix = format!("tmp_{}_", env!("CARGO_PKG_NAME"));
312 builder.prefix(&prefix);
313 builder.suffix(".log");
314
315 let builder = builder.tempfile_in(std::env::temp_dir());
316
317 let file = builder.expect("Failed to create temp log file");
318 let (_file, path) = file.keep().expect("Failed to persist temp log file");
319
320 path.to_string_lossy().into_owned()
321}
322
323fn get_temp_lock_filepath(hash: &str) -> String {
324 std::env::temp_dir()
325 .join(env!("CARGO_PKG_NAME"))
326 .join(format!("command_{}.lock", hash))
327 .to_string_lossy()
328 .into_owned()
329}
330
331pub fn check_gag() -> bool {
333 pub fn check_gag() -> Option<()> {
334 let gag = gag::Redirect::stdout(
335 std::fs::OpenOptions::new()
336 .truncate(true)
337 .read(true)
338 .create(true)
339 .write(true)
340 .open(get_temp_filepath())
341 .ok()?,
342 )
343 .ok()?;
344
345 const WHITE_SPACE: &str = " \t\n\r";
346
347 print!("{WHITE_SPACE}");
348 std::io::Write::flush(&mut std::io::stdout()).ok()?;
349
350 let mut stdout = gag.into_inner();
351 let mut buf = String::new();
352 stdout.seek(std::io::SeekFrom::Start(0)).ok()?;
353 stdout.read_to_string(&mut buf).ok()?;
354
355 Some(if buf.contains(WHITE_SPACE) {
356 ()
357 } else {
358 return None;
359 })
360 }
361
362 check_gag().is_some()
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368
369 static MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
370
371 #[cfg_attr(not(feature = "fallback"), ignore = "fallback feature disabled")]
372 #[test]
373 fn test_fallback_command() {
376 if DISABLE_FALLBACK {
377 return;
378 }
379
380 let _lock = MUTEX.lock().unwrap();
381 if !check_gag() {
382 return;
383 }
384
385 let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
386 println!("Fallback function called with args: {:?}", args);
387 0
388 });
389 cmd.arg("arg1").arg("arg2");
390
391 let child = cmd.spawn().expect("Failed to spawn command");
392 let output = child.wait_with_output().expect("Failed to get output");
393
394 assert!(output.success);
395 let stdout_str = String::from_utf8_lossy(&output.stdout);
396 assert!(stdout_str.contains("Fallback function called with args: [\"arg1\", \"arg2\"]"));
397
398 drop(_lock);
399 }
400}