1use std::collections::HashMap;
4use std::sync::Arc;
5use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
6
7use crate::commands::Commands;
8use crate::files::Files;
9use crate::workspaces::{self, Client, ListOptions, Options, Session, pb::Phase};
10use crate::{Error, Result};
11
12pub const DEFAULT_PACKAGES: &[&str] = &[
16 "bash",
17 "coreutils",
18 "curl",
19 "git",
20 "jq",
21 "python-3.13",
22 "nodejs-22",
23];
24
25pub const DEFAULT_WORKDIR: &str = "/work";
27
28const LABEL_PREFIX: &str = "/chainguard-sandbox/";
30
31#[derive(Debug, Clone, Default)]
34pub struct GitSource {
35 pub url: String,
37 pub revision: String,
39}
40
41#[derive(Clone, Default)]
44pub struct CreateOptions {
45 pub packages: Option<Vec<String>>,
49 pub envs: HashMap<String, String>,
52 pub name: String,
54 pub egress: Option<Vec<String>>,
57 pub egress_policy: String,
60 pub document: Option<Vec<u8>>,
63 pub source: Option<GitSource>,
65 pub start_timeout: Option<Duration>,
67 pub client: Option<Client>,
70 pub instance: String,
75}
76
77#[derive(Clone, Default)]
79pub struct ConnectOptions {
80 pub envs: HashMap<String, String>,
82 pub client: Option<Client>,
83 pub instance: String,
84}
85
86pub(crate) struct Inner {
87 pub client: Client,
88 pub id: String,
89 pub name: String,
90 pub envs: HashMap<String, String>,
91}
92
93#[derive(Clone)]
100pub struct Sandbox {
101 pub id: String,
103 pub name: String,
105 pub commands: Commands,
107 pub files: Files,
109 inner: Arc<Inner>,
110}
111
112impl std::fmt::Debug for Sandbox {
113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114 f.debug_struct("Sandbox")
115 .field("id", &self.id)
116 .field("name", &self.name)
117 .finish_non_exhaustive()
118 }
119}
120
121#[derive(Debug, Clone, Default)]
123pub struct Info {
124 pub id: String,
125 pub name: String,
126 pub display_name: String,
127 pub state: String,
129 pub region: String,
130 pub created_at: Option<SystemTime>,
131 pub expires_at: Option<SystemTime>,
133 pub cpus: i32,
134 pub memory_mib: i64,
135}
136
137async fn client_for(c: &Option<Client>, instance: &str) -> Result<Client> {
138 match c {
139 Some(c) => Ok(c.clone()),
140 None => {
141 Client::new(Options {
142 instance: instance.into(),
143 ..Default::default()
144 })
145 .await
146 }
147 }
148}
149
150pub fn document(o: &CreateOptions) -> Vec<u8> {
152 if let Some(d) = &o.document {
153 return d.clone();
154 }
155 let defaults: Vec<String> = DEFAULT_PACKAGES.iter().map(|p| p.to_string()).collect();
156 let pkgs = o.packages.as_ref().unwrap_or(&defaults);
157 let all = vec!["*".to_string()];
158 let egress = o.egress.as_ref().unwrap_or(&all);
159 let policy = if o.egress_policy.is_empty() {
160 "deny"
161 } else {
162 &o.egress_policy
163 };
164 let mut b = String::from(
165 "# Generated by chainguard-sandbox-sdk.\nversion: 1\nenvironment:\n packages:\n",
166 );
167 for p in pkgs {
168 b.push_str(&format!(" - {}\n", yaml_string(p)));
169 }
170 b.push_str("checks:\n develop:\n network:\n egress:");
171 if egress.is_empty() {
172 b.push_str(" []\n");
173 } else {
174 b.push('\n');
175 for h in egress {
176 b.push_str(&format!(" - {}\n", yaml_string(h)));
177 }
178 }
179 b.push_str(&format!(" policy: {}\n", yaml_string(policy)));
180 b.into_bytes()
181}
182
183fn yaml_string(s: &str) -> String {
185 format!(
186 "\"{}\"",
187 s.replace('\\', "\\\\")
188 .replace('"', "\\\"")
189 .replace('\n', "\\n")
190 )
191}
192
193pub(crate) mod timings {
195 use std::sync::atomic::{AtomicU64, Ordering};
196 use std::time::Duration;
197
198 static PLACEMENT_GRACE_MS: AtomicU64 = AtomicU64::new(30_000);
199 static START_POLL_MS: AtomicU64 = AtomicU64::new(1_000);
200 static KILL_WAIT_MS: AtomicU64 = AtomicU64::new(30_000);
201 static KILL_POLL_MS: AtomicU64 = AtomicU64::new(500);
202
203 pub fn placement_grace() -> Duration {
205 Duration::from_millis(PLACEMENT_GRACE_MS.load(Ordering::Relaxed))
206 }
207 pub fn start_poll() -> Duration {
209 Duration::from_millis(START_POLL_MS.load(Ordering::Relaxed))
210 }
211 pub fn kill_wait() -> Duration {
213 Duration::from_millis(KILL_WAIT_MS.load(Ordering::Relaxed))
214 }
215 pub fn kill_poll() -> Duration {
217 Duration::from_millis(KILL_POLL_MS.load(Ordering::Relaxed))
218 }
219
220 #[doc(hidden)]
222 pub fn shorten(placement_grace: u64, start_poll: u64, kill_wait: u64, kill_poll: u64) {
223 PLACEMENT_GRACE_MS.store(placement_grace, Ordering::Relaxed);
224 START_POLL_MS.store(start_poll, Ordering::Relaxed);
225 KILL_WAIT_MS.store(kill_wait, Ordering::Relaxed);
226 KILL_POLL_MS.store(kill_poll, Ordering::Relaxed);
227 }
228}
229
230#[doc(hidden)]
231pub use timings::shorten as shorten_timings_for_tests;
232
233pub(crate) fn wrap(e: Error) -> Error {
235 if matches!(e, Error::OutcomeUnknown { .. }) {
236 return e;
237 }
238 if workspaces::is_guest_held(&e) {
239 return Error::Busy { cause: Box::new(e) };
240 }
241 if let Error::Rpc(s) = &e {
242 if s.code() == tonic::Code::PermissionDenied
243 && s.message()
244 .contains("not entitled to Chainguard Workspaces")
245 {
246 return Error::NotEnabled { cause: Box::new(e) };
247 }
248 if s.code() == tonic::Code::ResourceExhausted {
249 return Error::LimitReached {
250 message: s.message().to_string(),
251 };
252 }
253 }
254 e
255}
256
257impl Sandbox {
258 fn from_session(client: Client, s: &Session, envs: HashMap<String, String>) -> Sandbox {
259 let inner = Arc::new(Inner {
260 client,
261 id: s.short_id.clone(),
262 name: s.name.clone(),
263 envs,
264 });
265 Sandbox {
266 id: inner.id.clone(),
267 name: inner.name.clone(),
268 commands: Commands::new(inner.clone()),
269 files: Files::new(inner.clone()),
270 inner,
271 }
272 }
273
274 pub async fn create(o: CreateOptions) -> Result<Sandbox> {
278 let c = client_for(&o.client, &o.instance).await?;
279 let doc = document(&o);
280 let name = if o.name.is_empty() {
281 "sandbox"
282 } else {
283 &o.name
284 };
285 if name.contains('/') || name.contains('\n') {
286 return Err(Error::other(format!(
287 "sandbox: name {name:?} must not contain '/' or newlines"
288 )));
289 }
290 let start_timeout = o
291 .start_timeout
292 .filter(|d| !d.is_zero())
293 .unwrap_or(Duration::from_secs(180));
294 let mut last_err = String::new();
295 for _attempt in 1..=3 {
296 let req = match &o.source {
297 Some(src) => {
298 let mut s = workspaces::repository_session(&src.url, &src.revision);
299 if let Some(workspaces::pb::session::Environment::Source(so)) =
300 &mut s.environment
301 {
302 so.fallback_document = doc.clone();
303 }
304 s
305 }
306 None => workspaces::workspace_session(
307 &format!("{LABEL_PREFIX}{name}"),
308 "",
309 "",
310 Some(doc.clone()),
311 ),
312 };
313 let s = c.create(req).await.map_err(wrap)?;
314 let created = s.name.clone();
315 let cleanup = || async {
316 let _ = tokio::time::timeout(Duration::from_secs(30), c.delete(&created)).await;
317 };
318 let s = match wait_started(&c, &created, start_timeout).await {
319 Err(Placement(msg)) => {
320 cleanup().await;
321 last_err = msg;
322 continue;
323 }
324 Ok(Err(e)) => {
325 cleanup().await;
326 return Err(e);
327 }
328 Ok(Ok(s)) => s,
329 };
330 if s.workspace_pending
331 && let Err(e) = empty_upload(&c, &s.name).await
332 {
333 cleanup().await;
334 return Err(e);
335 }
336 return Ok(Sandbox::from_session(c, &s, o.envs.clone()));
337 }
338 Err(Error::other(format!(
339 "sandbox: the plane could not start a guest in 3 attempts: the guest failed to start: {last_err}"
340 )))
341 }
342
343 pub async fn with<T, F>(o: CreateOptions, f: F) -> Result<T>
357 where
358 F: AsyncFnOnce(&Sandbox) -> Result<T>,
359 {
360 let sbx = Sandbox::create(o).await?;
361 let mut guard = KillOnDrop(Some(sbx.clone()));
362 let r = f(&sbx).await;
363 guard.0 = None;
364 let k = sbx.kill().await;
365 let v = r?;
366 k?;
367 Ok(v)
368 }
369
370 pub async fn connect(id: &str, o: ConnectOptions) -> Result<Sandbox> {
373 let c = client_for(&o.client, &o.instance).await?;
374 let s = match c.resolve(id).await {
375 Err(Error::NotFound { .. }) => {
376 return Err(Error::NotFound {
377 what: "sandbox".into(),
378 name: id.into(),
379 });
380 }
381 Err(e) => return Err(wrap(e)),
382 Ok(s) => s,
383 };
384 if s.workspace_pending {
385 empty_upload(&c, &s.name).await?;
386 }
387 Ok(Sandbox::from_session(c, &s, o.envs))
388 }
389
390 pub async fn kill(&self) -> Result<bool> {
396 delete_and_wait(&self.inner.client, &self.inner.name).await
397 }
398
399 pub async fn pause(&self) -> Result<()> {
402 self.inner
403 .client
404 .park(&self.inner.name)
405 .await
406 .map_err(wrap)?;
407 Ok(())
408 }
409
410 pub async fn keep_alive(&self, d: Duration) -> Result<()> {
413 self.inner
414 .client
415 .heartbeat(&self.inner.name, d)
416 .await
417 .map_err(wrap)?;
418 Ok(())
419 }
420
421 pub async fn get_info(&self) -> Result<Info> {
423 match self.inner.client.get(&self.inner.name).await {
424 Ok(s) => Ok(info(&s)),
425 Err(e) if e.grpc_code() == Some(tonic::Code::NotFound) => Err(Error::NotFound {
426 what: "sandbox".into(),
427 name: self.id.clone(),
428 }),
429 Err(e) => Err(wrap(e)),
430 }
431 }
432
433 pub async fn is_running(&self) -> Result<bool> {
435 match self.get_info().await {
436 Ok(i) => Ok(i.state == "running"),
437 Err(Error::NotFound { .. }) => Ok(false),
438 Err(e) => Err(e),
439 }
440 }
441
442 pub fn client(&self) -> &Client {
444 &self.inner.client
445 }
446}
447
448struct KillOnDrop(Option<Sandbox>);
450
451impl Drop for KillOnDrop {
452 fn drop(&mut self) {
453 if let Some(sbx) = self.0.take()
454 && let Ok(h) = tokio::runtime::Handle::try_current()
455 {
456 h.spawn(async move {
457 let _ = sbx.kill().await;
458 });
459 }
460 }
461}
462
463struct Placement(String);
465
466async fn wait_started(
470 c: &Client,
471 name: &str,
472 limit: Duration,
473) -> std::result::Result<Result<Session>, Placement> {
474 let t0 = Instant::now();
475 let deadline = t0 + limit;
476 let mut last: Option<Session> = None;
477 let expired = |last: &Option<Session>| {
478 let mut detail = format!("the guest did not start within {}", go_duration(limit));
479 if let Some(s) = last {
480 let phase = Phase::try_from(s.phase)
481 .map(|p| p.as_str_name())
482 .unwrap_or("PHASE_UNSPECIFIED");
483 detail.push_str(&format!(" (phase {phase}: {})", s.message));
484 }
485 Err(Error::Timeout {
486 op: "start".into(),
487 detail,
488 result: None,
489 })
490 };
491 loop {
492 let remaining = deadline.saturating_duration_since(Instant::now());
493 let s = match tokio::time::timeout(remaining, c.get(name)).await {
494 Err(_) => return Ok(expired(&last)),
495 Ok(Err(e)) => return Ok(Err(wrap(e))),
496 Ok(Ok(s)) => s,
497 };
498 if s.guest_started_time.is_some() {
499 return Ok(Ok(s));
500 }
501 if s.message.contains("starting guest failed") && t0.elapsed() > timings::placement_grace()
502 {
503 return Err(Placement(s.message));
504 }
505 last = Some(s);
506 let remaining = deadline.saturating_duration_since(Instant::now());
507 if remaining.is_zero() {
508 return Ok(expired(&last));
509 }
510 tokio::time::sleep(timings::start_poll().min(remaining)).await;
511 if Instant::now() >= deadline {
512 return Ok(expired(&last));
513 }
514 }
515}
516
517pub(crate) fn go_duration(d: Duration) -> String {
519 let ms = d.as_millis();
520 if ms % 1000 != 0 {
521 return format!("{}s", d.as_secs_f64());
522 }
523 let s = d.as_secs();
524 match (s / 3600, (s / 60) % 60, s % 60) {
525 (0, 0, sec) => format!("{sec}s"),
526 (0, m, sec) => format!("{m}m{sec}s"),
527 (h, m, sec) => format!("{h}h{m}m{sec}s"),
528 }
529}
530
531async fn empty_upload(c: &Client, name: &str) -> Result<()> {
534 match c.complete_first_attach(name).await {
535 Ok(()) => Ok(()),
536 Err(e @ Error::Timeout { .. }) => Err(e),
537 Err(e) => Err(Error::other(format!(
538 "sandbox: completing the first attach: {}",
539 wrap(e)
540 ))),
541 }
542}
543
544pub async fn list(o: ConnectOptions) -> Result<Vec<Info>> {
546 let c = client_for(&o.client, &o.instance).await?;
547 let ss = c.list(&ListOptions::default()).await.map_err(wrap)?;
548 Ok(ss
549 .iter()
550 .filter(|s| match &s.environment {
551 Some(workspaces::pb::session::Environment::Workspace(w)) => {
552 w.label.starts_with(LABEL_PREFIX)
553 }
554 _ => false,
555 })
556 .map(info)
557 .collect())
558}
559
560pub async fn kill(id: &str, o: ConnectOptions) -> Result<bool> {
565 let c = client_for(&o.client, &o.instance).await?;
566 match c.resolve(id).await {
567 Err(Error::NotFound { .. }) => Ok(false),
568 Err(e) if e.grpc_code() == Some(tonic::Code::NotFound) => Ok(false),
569 Err(e) => Err(wrap(e)),
570 Ok(s) => delete_and_wait(&c, &s.name).await,
571 }
572}
573
574async fn delete_and_wait(c: &Client, name: &str) -> Result<bool> {
576 match c.delete(name).await {
577 Err(e) if e.grpc_code() == Some(tonic::Code::NotFound) => return Ok(false),
578 Err(e) => return Err(wrap(e)),
579 Ok(()) => {}
580 }
581 let wait = timings::kill_wait();
584 let deadline = Instant::now() + wait;
585 let mut last_err: Option<Error> = None;
586 loop {
587 let remaining = deadline.saturating_duration_since(Instant::now());
588 match tokio::time::timeout(remaining, c.get(name)).await {
589 Ok(Err(e)) if e.grpc_code() == Some(tonic::Code::NotFound) => return Ok(true),
590 Ok(Err(e)) => last_err = Some(wrap(e)),
591 Ok(Ok(_)) => last_err = None,
592 Err(_) => {}
593 }
594 let remaining = deadline.saturating_duration_since(Instant::now());
595 if remaining.is_zero() {
596 let detail = match &last_err {
597 Some(e) if e.grpc_code() != Some(tonic::Code::DeadlineExceeded) => {
598 format!(
599 "could not confirm the sandbox is gone within {} (last check: {e})",
600 go_duration(wait)
601 )
602 }
603 _ => format!(
604 "the sandbox still exists {} after the delete request",
605 go_duration(wait)
606 ),
607 };
608 return Err(Error::Timeout {
609 op: "kill".into(),
610 detail,
611 result: None,
612 });
613 }
614 tokio::time::sleep(timings::kill_poll().min(remaining)).await;
615 }
616}
617
618fn timestamp(t: &Option<prost_types::Timestamp>) -> Option<SystemTime> {
619 t.as_ref()
620 .map(|t| UNIX_EPOCH + Duration::new(t.seconds.max(0) as u64, t.nanos.max(0) as u32))
621}
622
623pub(crate) fn info(s: &Session) -> Info {
624 let rc = s.max_resource_class.unwrap_or_default();
625 let state = match Phase::try_from(s.phase) {
626 Ok(Phase::Creating) => "creating",
627 Ok(Phase::Attached) | Ok(Phase::Idle) => "running",
628 Ok(Phase::Parked) => "paused",
629 _ => "stopped",
630 };
631 Info {
632 id: s.short_id.clone(),
633 name: s.name.clone(),
634 display_name: s.display_name.clone(),
635 state: state.into(),
636 region: s.region.clone(),
637 created_at: timestamp(&s.create_time),
638 expires_at: timestamp(&s.expire_time),
639 cpus: rc.cpus,
640 memory_mib: rc.memory_mib,
641 }
642}
643
644pub(crate) fn guest_path(p: &str) -> String {
646 if p.is_empty() {
647 DEFAULT_WORKDIR.into()
648 } else {
649 workspaces::guest_path(p)
650 }
651}
652
653pub use crate::workspaces::Organization;
655
656crate::opaque_debug!(CreateOptions, ConnectOptions);
657
658pub async fn list_organizations() -> Result<Vec<Organization>> {
662 workspaces::list_organizations(None).await
663}