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
//! Embed-supermachine demo: spin up a microVM from a baked
//! snapshot, send an HTTP request to its workload over the
//! vsock-mux unix socket, print the response.
//!
//! Usage:
//!
//! ```sh
//! # Bake the snapshot once via the CLI:
//! supermachine run nginx:1.27-alpine --detach && supermachine run --stop
//!
//! # Then run this example pointing at the resulting snapshot:
//! cargo run --release --example embed_simple -- \
//! ~/.local/supermachine-snapshots/nginx_1_27-alpine/restore.snap
//! ```
//!
//! Required setup: this example's binary needs the HVF
//! entitlement. The `cargo-supermachine` plugin handles it:
//!
//! ```sh
//! cargo install supermachine
//! cargo supermachine build --release --example embed_simple
//! ```
use std::io::{Read, Write};
use std::time::Instant;
use supermachine::{Image, Vm, VmConfig};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let snapshot_path = std::env::args()
.nth(1)
.ok_or("usage: embed_simple <snapshot-path>")?;
let t0 = Instant::now();
let image = Image::from_snapshot(&snapshot_path)?;
let vm = Vm::start(&image, &VmConfig::new())?;
eprintln!("vm started in {:?}", t0.elapsed());
eprintln!("vsock path: {}", vm.vsock_path().display());
// Send an HTTP request directly through the vsock-mux socket.
// The bytes proxy through to the guest's TSI listener (typically
// the workload's :80) — supermachine's vsock bridge is a
// transparent byte pump.
let mut sock = vm.connect()?;
sock.write_all(
b"GET / HTTP/1.1\r\n\
Host: workload\r\n\
Connection: close\r\n\
\r\n",
)?;
let mut response = Vec::new();
sock.read_to_end(&mut response)?;
eprintln!("response: {} bytes", response.len());
// Print the response status line + first few headers.
let preview = String::from_utf8_lossy(&response);
for line in preview.lines().take(6) {
eprintln!(" {line}");
}
vm.stop()?;
eprintln!("vm stopped after {:?}", t0.elapsed());
Ok(())
}