crates/edge/server/tests/container.rs 6.4 KiB 196 lines Raw
1 //! A bind with `runtime = "container"`: the web starts a sibling Docker2 //! container, the image's plugin connects to the private socket, and a warm or3 //! cold bind serves HTTP. The control's `bin_dir` is empty on purpose: if the4 //! old process path is still taken, this test fails before it serves.5 6 use std::io::{Read, Write};7 use std::net::{TcpListener, TcpStream};8 use std::path::{Path, PathBuf};9 use std::process::{Child, Command, Stdio};10 use std::time::{Duration, Instant};11 12 const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";13 const TARGET: &str = "[target]\nname = \"x64-cpu\"\nbackend = \"cpu\"\narch = [\"x86_64\", \"aarch64\"]\ndevices = 0\nvram_mb = []\n";14 const CONTROL_IMAGE: &str = "inf3r:local";15 const BUNDLE_IMAGE: &str = "inf3r/mock/x64-cpu:local";16 17 fn control_image() -> String {18     std::env::var("INF3R_TEST_CONTROL_IMAGE").unwrap_or_else(|_| CONTROL_IMAGE.to_string())19 }20 21 fn bundle_image() -> String {22     std::env::var("INF3R_TEST_BUNDLE_IMAGE").unwrap_or_else(|_| BUNDLE_IMAGE.to_string())23 }24 25 fn docker_available() -> bool {26     [control_image(), bundle_image()].iter().all(|image| {27         Command::new("docker")28             .args(["image", "inspect", image])29             .stdout(Stdio::null())30             .stderr(Stdio::null())31             .status()32             .is_ok_and(|status| status.success())33     })34 }35 36 struct Engine {37     child: Child,38     dir: PathBuf,39     port: u16,40 }41 42 impl Drop for Engine {43     fn drop(&mut self) {44         let _ = self.child.kill();45         let _ = self.child.wait();46         let _ = std::fs::remove_dir_all(&self.dir);47     }48 }49 50 fn start(warm: bool, serial: u64) -> Engine {51     let dir = Path::new("/tmp").join(format!(52         "inf3r-web-container-{}-{serial}",53         std::process::id()54     ));55     let _ = std::fs::remove_dir_all(&dir);56     std::fs::create_dir_all(dir.join("bin")).expect("bin");57     std::fs::create_dir_all(dir.join("blobs")).expect("blobs");58     std::fs::write(dir.join("token"), format!("{TOKEN}\n")).expect("token");59     let bundles = dir.join("plugins");60     std::fs::create_dir_all(bundles.join("mock/x64-cpu")).expect("bundle");61     std::fs::write(bundles.join("mock/x64-cpu/target.toml"), TARGET).expect("target");62     std::fs::write(63         bundles.join("mock/x64-cpu/bundle.toml"),64         "id = \"mock/x64-cpu\"\nmodel = \"mock\"\ntarget = \"x64-cpu\"\nsummary = \"test\"\nengine = \"authored\"\nbinary = \"inf3r-mock-x64-cpu\"\nfiles = \"target.toml\"\nsha256 = \"\"\n",65     )66     .expect("bundle manifest");67 68     let listener = TcpListener::bind("127.0.0.1:0").expect("bind");69     let port = listener.local_addr().expect("addr").port();70     drop(listener);71 72     let deploy = format!(73         r#"74 [[node]]75 host        = "test"76 bin_dir     = "{}"77 probe_image = "{}"78 bundle_dirs = ["{}"]79 blob_dir    = "{}"80 socket_dir  = "{}"81 web         = {{ tcp = "127.0.0.1:{port}" }}82 auth_file  = "{}"83 84 [[node.bind]]85 bundle   = "mock/x64-cpu"86 runtime  = "container"87 image    = "{}"88 command  = ["/opt/inf3r/bin/inf3r-mock-x64-cpu"]89 models   = ["mock"]90 devices  = ["cpu:0"]91 warm     = {warm}92 "#,93         dir.join("missing-bin").display(),94         control_image(),95         bundles.display(),96         dir.join("blobs").display(),97         Path::new("/tmp")98             .join(format!("ifc-{}-{serial}", std::process::id()))99             .display(),100         dir.join("token").display(),101         bundle_image(),102     );103     std::fs::write(dir.join("deploy.toml"), deploy).expect("deploy");104 105     let log = std::fs::File::create(dir.join("web.err")).expect("web log");106     #[allow(clippy::zombie_processes)]107     let child = Command::new(env!("CARGO_BIN_EXE_inf3r-web"))108         .arg("--deploy")109         .arg(dir.join("deploy.toml"))110         .stdout(Stdio::null())111         .stderr(Stdio::from(log))112         .spawn()113         .expect("spawn inf3r-web");114 115     let started = Instant::now();116     while started.elapsed() < Duration::from_secs(60) {117         if TcpStream::connect(("127.0.0.1", port)).is_ok() {118             return Engine { child, dir, port };119         }120         std::thread::sleep(Duration::from_millis(30));121     }122     panic!("inf3r-web did not listen");123 }124 125 impl Engine {126     fn request(&self, method: &str, target: &str, body: Option<&str>) -> String {127         let body = body.unwrap_or("");128         let header = if body.is_empty() {129             String::new()130         } else {131             format!("Content-Length: {}\r\n", body.len())132         };133         let mut stream = TcpStream::connect(("127.0.0.1", self.port)).expect("connect");134         stream135             .set_read_timeout(Some(Duration::from_secs(60)))136             .expect("timeout");137         write!(138             stream,139             "{method} {target} HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {TOKEN}\r\n{header}Connection: close\r\n\r\n{body}"140         )141         .expect("write");142         let mut reply = String::new();143         stream.read_to_string(&mut reply).expect("read");144         reply145     }146 147     fn models(&self) -> String {148         self.request("GET", "/models", None)149     }150 151     fn chat(&self) -> String {152         self.request(153             "POST",154             "/openai/v1/chat/completions",155             Some(r#"{"model":"mock","messages":[{"role":"user","content":"hello"}]}"#),156         )157     }158 }159 160 #[test]161 fn a_container_bind_serves_warm_and_cold_without_a_control_binary() {162     if !docker_available() {163         eprintln!(164             "container server test skipped: {} or {} is missing",165             control_image(),166             bundle_image()167         );168         return;169     }170 171     let warm = start(true, 1);172     let models = warm.models();173     assert!(models.starts_with("HTTP/1.1 200"), "{models}");174     assert!(models.contains("mock"), "{models}");175     let chat = warm.chat();176     assert!(chat.starts_with("HTTP/1.1 200"), "{chat}");177     assert!(178         chat.contains("completed") || chat.contains("chat.completion"),179         "{chat}"180     );181     drop(warm);182 183     // The cold bind discovers the catalogue in the image and starts the184     // container on the first request. `--describe` therefore crossed the185     // container boundary before any socket existed.186     let cold = start(false, 2);187     let models = cold.models();188     assert!(models.starts_with("HTTP/1.1 200"), "{models}");189     assert!(models.contains("mock"), "{models}");190     let chat = cold.chat();191     assert!(chat.starts_with("HTTP/1.1 200"), "{chat}");192     assert!(193         chat.contains("completed") || chat.contains("chat.completion"),194         "{chat}"195     );196 }