summaryrefslogtreecommitdiffstats
path: root/src/sandbox/kata.rs
blob: fafe858424d512e7a0bc78f085866b65bdf506c8 (plain)
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use std::collections::HashMap;
use std::io::BufReader;
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::process::{Child, Command};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;

use crossbeam_channel::{bounded, Receiver, Sender};

use crate::config::Config;
use crate::error::{Error, Result};
use crate::sandbox::remote::RemoteSandbox;
use crate::sandbox::wire::{self, Frame};
use crate::sandbox::{Sandbox, SandboxBackend, SandboxInfo, SandboxSpec};

#[derive(Debug, Clone)]
pub struct ProvisionRequest {
    pub sandbox_id: String,
    pub profile: String,
    pub hub_addr: String,
    pub token: String,
    pub ttl: Duration,
    pub image: String,
}

pub trait Provisioner: Send + Sync {
    fn provision(&self, req: &ProvisionRequest) -> Result<()>;
    fn reclaim(&self, sandbox_id: &str) -> Result<()>;
    fn name(&self) -> &str;
}

/// The agent-sandbox-style CR: one disposable Sandbox per build, Kata for the
/// VM boundary, `activeDeadlineSeconds` so the *orchestrator* enforces the
/// TTL even if the hub dies. The token rides in args for v1; a production
/// deployment should mount it from a Secret, and this comment is the honest
/// place that says so.
pub fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value {
    serde_json::json!({
        "apiVersion": "agents.x-k8s.io/v1alpha1",
        "kind": "Sandbox",
        "metadata": {
            "name": req.sandbox_id,
            "labels": {
                "aur-build.io/managed-by": "aur-build",
                "aur-build.io/profile": req.profile,
            },
        },
        "spec": {
            "runtimeClass": "kata",
            "shutdownPolicy": "Delete",
            "activeDeadlineSeconds": req.ttl.as_secs(),
            "template": {
                "spec": {
                    "containers": [{
                        "name": "build-agent",
                        "image": req.image,
                        "args": [
                            "--hub", req.hub_addr,
                            "--token", req.token,
                            "--agent-id", req.sandbox_id,
                            "--profile", req.profile,
                            "--ttl", req.ttl.as_secs().to_string(),
                        ],
                    }],
                },
            },
        },
    })
}

impl K8sSandboxProvisioner {
    pub fn for_config(cfg: &Config) -> Option<Self> {
        match &cfg.sandbox {
            crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => Some(Self {
                api: api.clone(),
                namespace: namespace.clone(),
                bearer: bearer.clone(),
            }),
            _ => None,
        }
    }
}

pub struct K8sSandboxProvisioner {
    pub api: String,
    pub bearer: String,
    pub namespace: String,
}

impl Provisioner for K8sSandboxProvisioner {
    fn provision(&self, req: &ProvisionRequest) -> Result<()> {
        let url = format!(
            "{}/apis/agents.x-k8s.io/v1alpha1/namespaces/{}/sandboxes",
            self.api.trim_end_matches('/'),
            self.namespace
        );
        ureq::post(&url)
            .set("Authorization", &format!("Bearer {}", self.bearer))
            .send_json(sandbox_cr(req))
            .map_err(|e| Error::other(format!("kata provision failed: {e}")))?;
        Ok(())
    }

    fn reclaim(&self, sandbox_id: &str) -> Result<()> {
        let url = format!(
            "{}/apis/agents.x-k8s.io/v1alpha1/namespaces/{}/sandboxes/{sandbox_id}",
            self.api.trim_end_matches('/'),
            self.namespace
        );
        ureq::delete(&url)
            .set("Authorization", &format!("Bearer {}", self.bearer))
            .call()
            .map_err(|e| Error::other(format!("kata reclaim failed: {e}")))?;
        Ok(())
    }

    fn name(&self) -> &str {
        "k8s-sandbox-crd"
    }
}

pub struct LocalAgentProvisioner {
    pub bin: PathBuf,
    children: Mutex<HashMap<String, Child>>,
}

impl LocalAgentProvisioner {
    pub fn new(bin: impl Into<PathBuf>) -> Self {
        Self { bin: bin.into(), children: Mutex::new(HashMap::new()) }
    }
}

impl Provisioner for LocalAgentProvisioner {
    fn provision(&self, req: &ProvisionRequest) -> Result<()> {
        let child = Command::new(&self.bin)
            .arg("--hub")
            .arg(&req.hub_addr)
            .arg("--token")
            .arg(&req.token)
            .arg("--agent-id")
            .arg(&req.sandbox_id)
            .arg("--profile")
            .arg(&req.profile)
            .arg("--ttl")
            .arg(req.ttl.as_secs().to_string())
            .spawn()
            .map_err(|e| Error::other(format!("local agent spawn failed: {e}")))?;
        self.children.lock().unwrap().insert(req.sandbox_id.clone(), child);
        Ok(())
    }

    fn reclaim(&self, sandbox_id: &str) -> Result<()> {
        if let Some(mut child) = self.children.lock().unwrap().remove(sandbox_id) {
            let _ = child.kill();
            let _ = child.wait();
        }
        Ok(())
    }

    fn name(&self) -> &str {
        "local-agent"
    }
}

pub struct KataBackend {
    cfg: Config,
    token: String,
    addr: String,
    provisioner: Arc<dyn Provisioner>,
    pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>>,
    counter: AtomicU64,
}

impl KataBackend {
    pub fn shared_for(cfg: &Config) -> Result<Arc<KataBackend>> {
        let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } =
            &cfg.sandbox
        else {
            return Err(Error::invalid(
                "KataBackend::shared_for needs an agent-sandbox configuration",
            ));
        };
        let key = crate::hash::hex(
            format!("{listen}\n{token}\n{api}\n{namespace}\n{bearer}\n{image}").as_bytes(),
        );
        static CACHE: OnceLock<Mutex<HashMap<String, Arc<KataBackend>>>> = OnceLock::new();
        let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
        let mut guard = cache.lock().unwrap_or_else(|p| p.into_inner());
        if let Some(existing) = guard.get(&key) {
            return Ok(existing.clone());
        }
        let provisioner = Arc::new(K8sSandboxProvisioner::for_config(cfg).ok_or_else(|| {
            Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration")
        })?);
        let backend = Arc::new(Self::bind(cfg, listen, token, provisioner)?);
        guard.insert(key, backend.clone());
        Ok(backend)
    }

    pub fn provision_request(&self, spec: &SandboxSpec, id: &str) -> ProvisionRequest {
        ProvisionRequest {
            sandbox_id: id.to_string(),
            profile: spec.profile.clone(),
            hub_addr: self.addr.clone(),
            token: self.token.clone(),
            ttl: spec.ttl,
            image: self.cfg.sandbox_image(),
        }
    }

    pub fn bind(
        cfg: &Config,
        listen: &str,
        token: &str,
        provisioner: Arc<dyn Provisioner>,
    ) -> Result<Self> {
        let listener = TcpListener::bind(listen)?;
        let addr = listener.local_addr()?.to_string();
        let pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>> = Arc::new(Mutex::new(HashMap::new()));
        {
            let (token, pending) = (token.to_string(), pending.clone());
            std::thread::spawn(move || {
                for stream in listener.incoming() {
                    let Ok(stream) = stream else { break };
                    route_dial_in(stream, &token, &pending);
                }
            });
        }
        Ok(Self {
            cfg: cfg.clone(),
            token: token.to_string(),
            addr,
            provisioner,
            pending,
            counter: AtomicU64::new(1),
        })
    }

    pub fn reclaim(&self, sandbox_id: &str) -> Result<()> {
        self.provisioner.reclaim(sandbox_id)
    }

    pub fn local_addr(&self) -> &str {
        &self.addr
    }

    fn nonce(&self) -> String {
        let n = self.counter.fetch_add(1, Ordering::SeqCst);
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        crate::hash::hex_str(&format!("{}-{n}-{nanos}", std::process::id()))[..20].to_string()
    }
}

fn route_dial_in(
    stream: TcpStream,
    token: &str,
    pending: &Arc<Mutex<HashMap<String, Sender<TcpStream>>>>,
) {
    let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
    let mut reader = match stream.try_clone() {
        Ok(s) => BufReader::new(s),
        Err(_) => return,
    };
    let hello = match wire::read_frame(&mut reader) {
        Ok(Some(Frame::Hello { token: t, agent_id, .. })) if t == token => agent_id,
        _ => return,
    };
    let slot = pending.lock().unwrap().remove(&hello).map(|tx| (tx, stream));
    if let Some((tx, stream)) = slot {
        let _ = tx.send(stream);
    }
}

impl SandboxBackend for KataBackend {
    fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> {
        let id = self.nonce();
        let (tx, rx): (Sender<TcpStream>, Receiver<TcpStream>) = bounded(1);
        self.pending.lock().unwrap().insert(id.clone(), tx);
        let req = self.provision_request(spec, &id);
        if let Err(e) = self.provisioner.provision(&req) {
            self.pending.lock().unwrap().remove(&id);
            return Err(e);
        }
        let stream = match rx.recv_timeout(spec.ttl) {
            Ok(s) => s,
            Err(_) => {
                self.pending.lock().unwrap().remove(&id);
                let _ = self.provisioner.reclaim(&id);
                return Err(Error::pool_exhausted(format!(
                    "sandbox {id} for profile {} never dialed in within its TTL",
                    spec.profile
                )));
            }
        };
        let ttl = spec.ttl.max(Duration::from_secs(1));
        wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: ttl.as_secs() })?;
        Ok(Arc::new(RemoteSandbox::after_hello(&self.cfg, stream, id, ttl)))
    }

    fn status(&self) -> Result<Vec<SandboxInfo>> {
        Ok(vec![SandboxInfo {
            id: format!("kata@{} via {}", self.addr, self.provisioner.name()),
            profile: self.cfg.build_profile.clone(),
            warm: !self.pending.lock().unwrap().is_empty(),
        }])
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn req() -> ProvisionRequest {
        ProvisionRequest {
            sandbox_id: "sbx-abc123".into(),
            profile: "extra-x86_64".into(),
            hub_addr: "10.0.0.5:9443".into(),
            token: "t0ken".into(),
            ttl: Duration::from_secs(120),
            image: "aur-build-sandbox:latest".into(),
        }
    }

    #[test]
    fn the_cr_asks_kata_for_a_vm_that_dies_on_its_own_by_ttl() {
        let cr = sandbox_cr(&req());
        assert_eq!(cr["spec"]["runtimeClass"], "kata");
        assert_eq!(cr["spec"]["activeDeadlineSeconds"], 120,
            "the orchestrator must enforce the TTL even if the hub dies");
        assert_eq!(cr["spec"]["shutdownPolicy"], "Delete");
        let args = cr["spec"]["template"]["spec"]["containers"][0]["args"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap().to_string())
            .collect::<Vec<_>>();
        assert!(args.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-abc123"));
        assert!(args.windows(2).any(|w| w[0] == "--hub" && w[1] == "10.0.0.5:9443"));
        assert!(args.windows(2).any(|w| w[0] == "--token" && w[1] == "t0ken"));
    }
}