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
|
use std::collections::HashMap;
use std::io::Read;
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use crossbeam_channel::{Receiver, Sender};
use crate::config::Config;
use crate::error::Result;
pub mod agent;
pub mod kata;
pub mod loopback;
pub mod remote;
pub mod wire;
#[derive(Debug, Clone)]
pub struct Cmd {
pub argv: Vec<String>,
pub cwd: Option<PathBuf>,
}
impl Cmd {
pub fn new<I, S>(argv: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self { argv: argv.into_iter().map(Into::into).collect(), cwd: None }
}
pub fn in_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.cwd = Some(dir.into());
self
}
pub fn name(&self) -> &str {
self.argv.first().map(String::as_str).unwrap_or("")
}
}
mod exit {
#[derive(Debug)]
pub struct Exit {
pub code: Option<i32>,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
}
impl Exit {
pub fn success(&self) -> bool {
self.code == Some(0)
}
}
}
#[cfg(feature = "test-support")]
pub use exit::Exit;
#[cfg(not(feature = "test-support"))]
pub(crate) use exit::Exit;
#[derive(Debug, Clone)]
pub struct SandboxSpec {
pub profile: String,
pub task: String,
pub ttl: Duration,
}
impl SandboxSpec {
pub fn new(profile: impl Into<String>, task: impl Into<String>, ttl: Duration) -> Self {
Self { profile: profile.into(), task: task.into(), ttl }
}
}
/// The real definition. The module is private, so this `pub`
/// is not a nameable path from outside; the alias below is the
/// only way to reach it, and the alias is what carries the
/// feature-conditional visibility.
mod sandbox_info {
#[derive(Debug, Clone)]
pub struct SandboxInfo {
pub id: String,
pub profile: String,
}
}
/// The return type of `SandboxBackend::status`. No production module outside `sandbox` names it; the backend tests do.
///
/// `pub` only under `test-support`. Production reaches the type
/// through its own module and never names it from outside; the
/// outside reader that needs the name is a test.
#[cfg(feature = "test-support")]
pub use sandbox_info::SandboxInfo;
#[cfg(not(feature = "test-support"))]
pub(crate) use sandbox_info::SandboxInfo;
pub trait Sandbox: Send + Sync {
fn id(&self) -> &str;
fn run(&self, cmd: &Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit>;
fn put(&self, digest: &str, r: &mut dyn Read) -> Result<()>;
fn get(&self, digest: &str) -> Result<Box<dyn Read>>;
fn destroy(&self) -> Result<()>;
}
pub trait SandboxBackend: Send + Sync {
fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>>;
fn status(&self) -> Result<Vec<SandboxInfo>>;
}
pub fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> {
cfg.validate()?;
match &cfg.sandbox {
crate::config::Sandbox::Loopback => Ok(Arc::new(loopback::LoopbackBackend::new(cfg))),
crate::config::Sandbox::Remote { listen, token, .. } => {
Ok(Arc::new(remote::RemoteBackend::bind(cfg, listen, token)?))
}
crate::config::Sandbox::AgentSandbox { .. } => {
let backend: Arc<dyn SandboxBackend> = kata::KataBackend::shared_for(cfg)?;
Ok(backend)
}
}
}
#[derive(Clone)]
struct Bound {
pub local: String,
pub rx: Receiver<TcpStream>,
}
fn bound_listener(addr: &str, token: &str) -> Result<Bound> {
static REGISTRY: OnceLock<Mutex<HashMap<(String, String), Bound>>> = OnceLock::new();
let registry = REGISTRY.get_or_init(|| Mutex::new(HashMap::new()));
let key = (addr.to_string(), token.to_string());
// A poisoned registry means a panic in another thread's bind; the map is
// still sound, so recover rather than wedge every later build.
let mut reg = registry.lock().unwrap_or_else(|p| p.into_inner());
if let Some(b) = reg.get(&key) {
return Ok(b.clone());
}
let listener = TcpListener::bind(addr)?;
let local = listener.local_addr()?.to_string();
let (tx, rx): (Sender<TcpStream>, Receiver<TcpStream>) = crossbeam_channel::unbounded();
std::thread::spawn(move || {
for stream in listener.incoming() {
match stream {
Ok(s) => {
let _ = tx.send(s);
}
Err(_) => break,
}
}
});
let bound = Bound { local, rx };
reg.insert(key, bound.clone());
Ok(bound)
}
|