summaryrefslogtreecommitdiffstats
path: root/tests/kata.rs
blob: f923ea2f6d255e19086888c2da8539d7810c7a82 (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
mod common;

use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};

use aur_build::config::Config;
use aur_build::error::Result;
use aur_build::sandbox::kata::{KataBackend, LocalAgentProvisioner, ProvisionRequest, Provisioner};
use aur_build::sandbox::{Cmd, SandboxBackend, SandboxSpec};
use common::{env_with_fixture, shim_dir};

#[test]
fn a_provisioned_sandbox_rendezvous_and_runs_a_command() {
    let cfg = Config::default();
    let prov = Arc::new(LocalAgentProvisioner::new(shim_dir().join("sandbox-agent")));
    let backend = KataBackend::bind(&cfg, "127.0.0.1:0", "kata-token", prov.clone()).unwrap();
    let sbx = backend
        .acquire(&SandboxSpec::new("extra-x86_64", "build-1", Duration::from_secs(15)))
        .expect("the provisioned agent should dial in and rendezvous");
    let out = sbx
        .run(&Cmd::new(["/bin/echo", "hi from the sandbox"]), &mut |_| {})
        .unwrap();
    assert!(out.success());
    assert_eq!(String::from_utf8_lossy(&out.stdout), "hi from the sandbox\n");
    sbx.destroy().unwrap();
}

#[test]
fn a_sandbox_that_never_dials_in_is_a_ttl_expiry_not_a_hang() {
    struct NullProvisioner;
    impl Provisioner for NullProvisioner {
        fn provision(&self, _req: &ProvisionRequest) -> Result<()> {
            Ok(())
        }
        fn reclaim(&self, _id: &str) -> Result<()> {
            Ok(())
        }
        fn name(&self) -> &str {
            "null"
        }
    }
    let cfg = Config::default();
    let backend = KataBackend::bind(&cfg, "127.0.0.1:0", "tok", Arc::new(NullProvisioner)).unwrap();
    let started = Instant::now();
    let err = match backend.acquire(&SandboxSpec::new("extra-x86_64", "ghost", Duration::from_secs(1))) {
        Ok(_) => panic!("nobody provisioned anything; the lease must not succeed"),
        Err(e) => e,
    };
    assert!(started.elapsed() >= Duration::from_millis(900), "acquire gave up before the TTL");
    assert!(err.to_string().contains("never dialed in"), "{err}");
}

#[test]
fn the_live_kata_tier_is_recorded_not_silently_absent() {
    if !Path::new("/dev/kvm").exists() {
        println!("note: no /dev/kvm on this host; the live kata tier is skipped, not passed");
        return;
    }
    let Ok(api) = std::env::var("AUR_KATA_API") else {
        println!("note: /dev/kvm present but AUR_KATA_API unset; live kata tier still skipped");
        return;
    };
    let cfg = Config::default();
    let prov = Arc::new(aur_build::sandbox::kata::K8sSandboxProvisioner {
        api,
        bearer: std::env::var("AUR_KATA_TOKEN").unwrap_or_default(),
        namespace: std::env::var("AUR_KATA_NS").unwrap_or_else(|_| "default".into()),
    });
    let backend = KataBackend::bind(&cfg, "0.0.0.0:9443", &std::env::var("AUR_AGENT_TOKEN").unwrap(), prov).unwrap();
    let sbx = backend
        .acquire(&SandboxSpec::new("extra-x86_64", "live", Duration::from_secs(300)))
        .expect("live kata sandbox should lease");
    let out = sbx.run(&Cmd::new(["/bin/echo", "kata"]), &mut |_| {}).unwrap();
    assert!(out.success() && String::from_utf8_lossy(&out.stdout).contains("kata"));
    sbx.destroy().unwrap();
}

fn agent_sandbox_config() -> Config {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("config.json"),
        r#"{
  "sandbox": {
    "kind": "agent-sandbox",
    "api": "https://k8s.test:6443",
    "namespace": "builds",
    "bearer": "kube-bearer",
    "image": "aur-build-sandbox:test",
    "listen": "127.0.0.1:0",
    "token": "kata-cfg-token",
    "shared_workspace": true
  }
}"#,
    )
    .unwrap();
    let cfg = Config::load(tmp.path()).unwrap();
    cfg.validate().expect("the config must survive the startup guard");
    cfg
}

#[test]
fn an_agent_sandbox_config_provisions_a_kata_vm_per_lease() {
    let cfg = agent_sandbox_config();
    let backend = aur_build::sandbox::kata::KataBackend::shared_for(&cfg).unwrap();
    let spec = SandboxSpec::new("extra-x86_64", "build-9", Duration::from_secs(77));
    let cr = aur_build::sandbox::kata::sandbox_cr(&backend.provision_request(&spec, "sbx-nonce-9"));

    assert_eq!(cr["spec"]["runtimeClass"], "kata", "the VM boundary is the point");
    assert_eq!(
        cr["spec"]["activeDeadlineSeconds"], 77,
        "the orchestrator enforces the lease TTL even if the hub dies"
    );
    assert_eq!(
        cr["metadata"]["name"], "sbx-nonce-9",
        "the nonce names the box, so a stray sandbox cannot be leased to the wrong build"
    );
    assert_eq!(cr["spec"]["template"]["spec"]["containers"][0]["image"], "aur-build-sandbox:test");
    let args: Vec<String> = cr["spec"]["template"]["spec"]["containers"][0]["args"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap().to_string())
        .collect();
    assert!(args.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-nonce-9"));
    assert!(args.windows(2).any(|w| w[0] == "--ttl" && w[1] == "77"));

    let prov = aur_build::sandbox::kata::K8sSandboxProvisioner::for_config(&cfg).unwrap();
    assert_eq!(prov.api, "https://k8s.test:6443");
    assert_eq!(prov.namespace, "builds");
    assert_eq!(prov.bearer, "kube-bearer");
}

#[test]
fn agent_sandbox_is_a_backend_not_a_fallthrough_to_loopback() {
    let cfg = agent_sandbox_config();
    let backend = aur_build::sandbox::backend_for(&cfg).unwrap();
    let id = backend.status().unwrap()[0].id.clone();
    assert!(id.contains("kata@"), "expected a kata backend, got {id}");

    let again = aur_build::sandbox::backend_for(&cfg).unwrap();
    assert_eq!(again.status().unwrap()[0].id, id, "two builds must share one kata backend");
}

#[test]
fn a_loopback_config_never_becomes_agent_sandbox_or_vice_versa() {
    let local = Config::default();
    let id = aur_build::sandbox::backend_for(&local).unwrap().status().unwrap()[0].id.clone();
    assert!(!id.contains("kata@"), "loopback must not report kata: {id}");
    assert!(!id.contains("remote@"), "loopback must not report remote: {id}");
}

#[test]
fn a_fixture_builds_and_publishes_through_the_kata_lease_path() {
    let (env, _fx) = env_with_fixture("plain-make");
    aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
    let c = aur_build::review::candidates::pending_candidates(&env.db).unwrap().remove(0);
    let dd = aur_build::review::diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
    aur_build::review::approve::approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
    let c = aur_build::review::candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
    let id = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();

    let mut ctx = aur_build::pipeline::Ctx::new(&env.cfg, &env.db, &id).unwrap();
    let prov = Arc::new(LocalAgentProvisioner::new(shim_dir().join("sandbox-agent")));
    let backend = KataBackend::bind(&env.cfg, "127.0.0.1:0", "kata-e2e", prov).unwrap();
    ctx.backend = Arc::new(backend);

    let out = aur_build::pipeline::run_with(&ctx).unwrap();
    let release = match out {
        aur_build::pipeline::Outcome::Succeeded { release_id } => release_id,
        other => panic!("the kata path must publish, got {other:?}"),
    };
    assert!(release > 0);

    let world = aur_build::pipeline::publish::index_world(&env.db).unwrap();
    assert!(
        world.iter().any(|w| w.pkgbase == "plain-make" && w.version == "1.0-1"),
        "the index must serve what the kata build produced: {world:?}"
    );

    let log = std::fs::read_to_string(env.cfg.build_log_path(&id)).unwrap();
    assert!(log.contains("Making package"), "agent output must reach the log:\n{log}");
    let shimlog = env.cfg.hooks.shim_dir.clone().unwrap();
    assert_eq!(aur_build::shims::called_with(&shimlog, "makepkg", ""), 1);
}