Skip to main content

chainguard_sandbox/
blocking.rs

1//! The same API for programs without an async runtime.
2//!
3//! Every call blocks until it is done. The calls run on a small runtime this module starts on
4//! first use and shares between threads. Calling them from inside an async runtime is refused
5//! (use the async API there).
6//!
7//! Unlike the async [`crate::Sandbox`], a blocking [`Sandbox`] deletes its sandbox when it is
8//! dropped, like Python's `with Sandbox.create() as sbx:`. Call [`Sandbox::detach`] to keep it.
9//!
10//! ```no_run
11//! use chainguard_sandbox::blocking::Sandbox;
12//! use chainguard_sandbox::CreateOptions;
13//!
14//! fn main() -> chainguard_sandbox::Result<()> {
15//!     let sbx = Sandbox::create(CreateOptions::default())?; // deleted when sbx is dropped
16//!     println!("{}", sbx.commands.run("echo hello")?.stdout);
17//!     Ok(())
18//! }
19//! ```
20
21use std::future::Future;
22use std::path::Path;
23use std::sync::OnceLock;
24use std::time::Duration;
25
26use crate::{
27    CommandResult, ConnectOptions, CreateOptions, EntryInfo, Error, Info, Organization,
28    ProcessInfo, Result, RunOptions, SetupOptions, StartOptions, WaitOptions, WorkspacesStatus,
29    WriteEntry, WriteInfo,
30};
31
32crate::opaque_debug!(Commands, CommandHandle, Files);
33
34fn runtime() -> &'static tokio::runtime::Runtime {
35    static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
36    RT.get_or_init(|| {
37        tokio::runtime::Builder::new_multi_thread()
38            .worker_threads(2)
39            .thread_name("chainguard-sandbox")
40            .enable_all()
41            .build()
42            .expect("starting the chainguard-sandbox runtime")
43    })
44}
45
46fn block_on<F: Future<Output = Result<T>>, T>(f: F) -> Result<T> {
47    if tokio::runtime::Handle::try_current().is_ok() {
48        return Err(Error::other(
49            "chainguard_sandbox::blocking was called from inside an async runtime; use the async API (chainguard_sandbox::Sandbox) there",
50        ));
51    }
52    runtime().block_on(f)
53}
54
55/// A handle to one sandbox, deleted when dropped (see [`Sandbox::detach`]).
56pub struct Sandbox {
57    /// The short ID (8 hex characters).
58    pub id: String,
59    /// The full resource name.
60    pub name: String,
61    /// Runs commands in the sandbox.
62    pub commands: Commands,
63    /// Reads and writes the sandbox's filesystem.
64    pub files: Files,
65    inner: Option<crate::Sandbox>,
66    kill_on_drop: bool,
67}
68
69impl std::fmt::Debug for Sandbox {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        f.debug_struct("Sandbox")
72            .field("id", &self.id)
73            .field("name", &self.name)
74            .finish_non_exhaustive()
75    }
76}
77
78impl Sandbox {
79    fn wrap(s: crate::Sandbox, kill_on_drop: bool) -> Sandbox {
80        Sandbox {
81            id: s.id.clone(),
82            name: s.name.clone(),
83            commands: Commands(s.commands.clone()),
84            files: Files(s.files.clone()),
85            inner: Some(s),
86            kill_on_drop,
87        }
88    }
89
90    fn sbx(&self) -> &crate::Sandbox {
91        self.inner.as_ref().expect("sandbox handle")
92    }
93
94    /// See [`crate::Sandbox::create`]. The sandbox is deleted when the handle is dropped.
95    pub fn create(o: CreateOptions) -> Result<Sandbox> {
96        block_on(crate::Sandbox::create(o)).map(|s| Sandbox::wrap(s, true))
97    }
98
99    /// See [`crate::Sandbox::connect`]. A connected sandbox is not deleted on drop.
100    pub fn connect(id: &str, o: ConnectOptions) -> Result<Sandbox> {
101        block_on(crate::Sandbox::connect(id, o)).map(|s| Sandbox::wrap(s, false))
102    }
103
104    /// Keeps the sandbox running after the handle is dropped. Returns the async handle.
105    pub fn detach(mut self) -> crate::Sandbox {
106        self.kill_on_drop = false;
107        self.inner.take().expect("sandbox handle")
108    }
109
110    /// See [`crate::Sandbox::kill`].
111    pub fn kill(&self) -> Result<bool> {
112        block_on(self.sbx().kill())
113    }
114
115    /// See [`crate::Sandbox::pause`].
116    pub fn pause(&self) -> Result<()> {
117        block_on(self.sbx().pause())
118    }
119
120    /// See [`crate::Sandbox::keep_alive`].
121    pub fn keep_alive(&self, d: Duration) -> Result<()> {
122        block_on(self.sbx().keep_alive(d))
123    }
124
125    /// See [`crate::Sandbox::get_info`].
126    pub fn get_info(&self) -> Result<Info> {
127        block_on(self.sbx().get_info())
128    }
129
130    /// See [`crate::Sandbox::is_running`].
131    pub fn is_running(&self) -> Result<bool> {
132        block_on(self.sbx().is_running())
133    }
134
135    /// The async handle, for anything else.
136    pub fn as_async(&self) -> &crate::Sandbox {
137        self.sbx()
138    }
139}
140
141impl Drop for Sandbox {
142    fn drop(&mut self) {
143        if self.kill_on_drop
144            && let Some(s) = self.inner.take()
145            && tokio::runtime::Handle::try_current().is_err()
146        {
147            let _ = runtime().block_on(s.kill());
148        }
149    }
150}
151
152/// Blocking [`crate::Commands`].
153pub struct Commands(crate::Commands);
154
155impl Commands {
156    pub fn run(&self, cmd: &str) -> Result<CommandResult> {
157        block_on(self.0.run(cmd))
158    }
159    pub fn run_with(&self, cmd: &str, o: RunOptions) -> Result<CommandResult> {
160        block_on(self.0.run_with(cmd, o))
161    }
162    pub fn run_args<I>(&self, argv: I) -> Result<CommandResult>
163    where
164        I: IntoIterator,
165        I::Item: Into<String>,
166    {
167        let argv: Vec<String> = argv.into_iter().map(Into::into).collect();
168        block_on(self.0.run_args(argv))
169    }
170    pub fn run_args_with<I>(&self, argv: I, o: RunOptions) -> Result<CommandResult>
171    where
172        I: IntoIterator,
173        I::Item: Into<String>,
174    {
175        let argv: Vec<String> = argv.into_iter().map(Into::into).collect();
176        block_on(self.0.run_args_with(argv, o))
177    }
178    pub fn start(&self, cmd: &str) -> Result<CommandHandle> {
179        block_on(self.0.start(cmd)).map(CommandHandle)
180    }
181    pub fn start_with(&self, cmd: &str, o: StartOptions) -> Result<CommandHandle> {
182        block_on(self.0.start_with(cmd, o)).map(CommandHandle)
183    }
184    pub fn start_args_with<I>(&self, argv: I, o: StartOptions) -> Result<CommandHandle>
185    where
186        I: IntoIterator,
187        I::Item: Into<String>,
188    {
189        let argv: Vec<String> = argv.into_iter().map(Into::into).collect();
190        block_on(self.0.start_args_with(argv, o)).map(CommandHandle)
191    }
192    pub fn list(&self) -> Result<Vec<ProcessInfo>> {
193        block_on(self.0.list())
194    }
195    pub fn connect(&self, pid: i64) -> Result<CommandHandle> {
196        block_on(self.0.connect(pid)).map(CommandHandle)
197    }
198    pub fn kill(&self, pid: i64) -> Result<bool> {
199        block_on(self.0.kill(pid))
200    }
201}
202
203/// Blocking [`crate::CommandHandle`].
204pub struct CommandHandle(crate::CommandHandle);
205
206impl CommandHandle {
207    pub fn pid(&self) -> i64 {
208        self.0.pid
209    }
210    pub fn id(&self) -> &str {
211        &self.0.id
212    }
213    pub fn stdout(&self) -> String {
214        self.0.stdout()
215    }
216    pub fn stderr(&self) -> String {
217        self.0.stderr()
218    }
219    pub fn exit_code(&self) -> Option<i32> {
220        self.0.exit_code()
221    }
222    pub fn poll(&self) -> Result<Option<i32>> {
223        block_on(self.0.poll())
224    }
225    pub fn wait(&self) -> Result<CommandResult> {
226        block_on(self.0.wait())
227    }
228    pub fn wait_with(&self, o: WaitOptions) -> Result<CommandResult> {
229        block_on(self.0.wait_with(o))
230    }
231    pub fn kill(&self) -> Result<bool> {
232        block_on(self.0.kill())
233    }
234}
235
236/// Blocking [`crate::Files`].
237pub struct Files(crate::Files);
238
239impl Files {
240    pub fn read(&self, p: &str) -> Result<Vec<u8>> {
241        block_on(self.0.read(p))
242    }
243    pub fn read_text(&self, p: &str) -> Result<String> {
244        block_on(self.0.read_text(p))
245    }
246    pub fn write(&self, p: &str, data: impl Into<Vec<u8>>) -> Result<WriteInfo> {
247        block_on(self.0.write(p, data))
248    }
249    pub fn write_files(&self, files: Vec<WriteEntry>) -> Result<Vec<WriteInfo>> {
250        block_on(self.0.write_files(files))
251    }
252    pub fn list(&self, p: &str) -> Result<Vec<EntryInfo>> {
253        block_on(self.0.list(p))
254    }
255    pub fn exists(&self, p: &str) -> Result<bool> {
256        block_on(self.0.exists(p))
257    }
258    pub fn get_info(&self, p: &str) -> Result<EntryInfo> {
259        block_on(self.0.get_info(p))
260    }
261    pub fn make_dir(&self, p: &str) -> Result<bool> {
262        block_on(self.0.make_dir(p))
263    }
264    pub fn remove(&self, p: &str) -> Result<()> {
265        block_on(self.0.remove(p))
266    }
267    pub fn rename(&self, old_path: &str, new_path: &str) -> Result<EntryInfo> {
268        block_on(self.0.rename(old_path, new_path))
269    }
270    pub fn upload(&self, local_path: impl AsRef<Path>, remote_path: &str) -> Result<()> {
271        block_on(self.0.upload(local_path, remote_path))
272    }
273    pub fn download(&self, remote_path: &str, local_path: impl AsRef<Path>) -> Result<()> {
274        block_on(self.0.download(remote_path, local_path))
275    }
276    pub fn upload_dir(&self, local_dir: impl AsRef<Path>, remote_dir: &str) -> Result<()> {
277        block_on(self.0.upload_dir(local_dir, remote_dir))
278    }
279    pub fn download_dir(&self, remote_dir: &str, local_dir: impl AsRef<Path>) -> Result<()> {
280        block_on(self.0.download_dir(remote_dir, local_dir))
281    }
282}
283
284/// See [`crate::list`].
285pub fn list(o: ConnectOptions) -> Result<Vec<Info>> {
286    block_on(crate::list(o))
287}
288
289/// See [`crate::kill`].
290pub fn kill(id: &str, o: ConnectOptions) -> Result<bool> {
291    block_on(crate::kill(id, o))
292}
293
294/// See [`crate::list_organizations`].
295pub fn list_organizations() -> Result<Vec<Organization>> {
296    block_on(crate::list_organizations())
297}
298
299/// See [`crate::workspaces_status`].
300pub fn workspaces_status(o: &SetupOptions) -> Result<WorkspacesStatus> {
301    block_on(crate::workspaces_status(o))
302}
303
304/// See [`crate::enable_workspaces`].
305pub fn enable_workspaces(o: &SetupOptions) -> Result<WorkspacesStatus> {
306    block_on(crate::enable_workspaces(o))
307}