Skip to content

Commit

Permalink
feat(xtask): add ci subcommand
Browse files Browse the repository at this point in the history
Signed-off-by: Martin Kröning <[email protected]>
  • Loading branch information
mkroening committed Sep 6, 2023
1 parent d96fe4c commit 95c747d
Show file tree
Hide file tree
Showing 10 changed files with 820 additions and 189 deletions.
235 changes: 47 additions & 188 deletions .github/workflows/ci.yml

Large diffs are not rendered by default.

432 changes: 431 additions & 1 deletion Cargo.lock

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions xtask/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,7 @@ anyhow = "1.0"
clap = { version = "4", features = ["derive"] }
goblin = { version = "0.7", default-features = false, features = ["archive", "elf32", "elf64", "std"] }
llvm-tools = "0.1"
sysinfo = "0.29"
ureq = "2"
wait-timeout = "0.2"
xshell = "0.2"
13 changes: 13 additions & 0 deletions xtask/src/arch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,19 @@ impl Arch {
}
}

pub fn ci_cargo_args(&self) -> &'static [&'static str] {
match self {
Arch::X86_64 => &[
"--target=x86_64-unknown-hermit",
"-Zbuild-std=std,panic_abort",
],
Arch::Aarch64 => &[
"--target=aarch64-unknown-hermit",
"-Zbuild-std=std,panic_abort",
],
}
}

pub fn rustflags(&self) -> &'static [&'static str] {
match self {
Self::X86_64 => &[],
Expand Down
12 changes: 12 additions & 0 deletions xtask/src/artifact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,16 @@ impl Artifact {
.collect::<PathBuf>()
.into()
}

pub fn ci_image(&self, package: &str) -> PathBuf {
[
"..".as_ref(),
self.target_dir(),
self.arch.hermit_triple().as_ref(),
self.profile_path_component().as_ref(),
package.as_ref(),
]
.iter()
.collect()
}
}
34 changes: 34 additions & 0 deletions xtask/src/ci/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use std::path::PathBuf;

use anyhow::Result;
use clap::Args;
use xshell::cmd;

use crate::cargo_build::{CargoBuild, CmdExt};

#[derive(Args)]
pub struct Build {
#[command(flatten)]
pub cargo_build: CargoBuild,

#[arg(short, long)]
pub package: String,
}

impl Build {
pub fn run(&self) -> Result<()> {
let sh = crate::sh()?;

cmd!(sh, "cargo build --manifest-path ../Cargo.toml")
.args(self.cargo_build.artifact.arch.ci_cargo_args())
.cargo_build_args(&self.cargo_build)
.args(&["--package", self.package.as_str()])
.run()?;

Ok(())
}

pub fn image(&self) -> PathBuf {
self.cargo_build.artifact.ci_image(&self.package)
}
}
23 changes: 23 additions & 0 deletions xtask/src/ci/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use anyhow::Result;
use clap::Subcommand;

mod build;
mod qemu;
mod uhyve;

#[derive(Subcommand)]
pub enum Ci {
Build(build::Build),
Qemu(qemu::Qemu),
Uhyve(uhyve::Uhyve),
}

impl Ci {
pub fn run(self) -> Result<()> {
match self {
Self::Build(build) => build.run(),
Self::Qemu(qemu) => qemu.run(),
Self::Uhyve(uhyve) => uhyve.run(),
}
}
}
214 changes: 214 additions & 0 deletions xtask/src/ci/qemu.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
use std::net::UdpSocket;
use std::path::Path;
use std::process::{Child, Command, ExitStatus};
use std::thread;
use std::time::Duration;

use anyhow::{anyhow, ensure, Result};
use clap::{Args, ValueEnum};
use sysinfo::{CpuExt, CpuRefreshKind, System, SystemExt};
use wait_timeout::ChildExt;
use xshell::cmd;

use super::build::Build;
use crate::arch::Arch;

#[derive(Args)]
pub struct Qemu {
#[command(flatten)]
build: Build,

#[arg(long)]
accel: bool,

#[arg(long)]
smp: bool,

#[arg(long)]
microvm: bool,

#[arg(long)]
netdev: Option<NetworkDevice>,

#[arg(long)]
virtiofsd: bool,
}

#[derive(ValueEnum, Clone, Copy)]
pub enum NetworkDevice {
VirtioNetPci,
Rtl8139,
}

trait ExitStatusExt {
fn qemu_success(&self) -> bool;
}

impl ExitStatusExt for ExitStatus {
fn qemu_success(&self) -> bool {
self.success() || self.code() == Some(3)
}
}

struct KillChildOnDrop(Child);

impl Drop for KillChildOnDrop {
fn drop(&mut self) {
self.0.kill().ok();
}
}

impl Qemu {
pub fn run(self) -> Result<()> {
self.build.run()?;

let sh = crate::sh()?;

let virtiofsd = self.virtiofsd.then(|| self.spawn_virtiofsd()).transpose()?;

let arch = self.build.cargo_build.artifact.arch.name();

let cmd = cmd!(sh, "qemu-system-{arch}")
.args(&["-display", "none"])
.args(&["-serial", "stdio"])
.args(&["-kernel", format!("../rusty-loader-{arch}").as_ref()]);

let cmd = if self.smp {
cmd.args(&["-smp", "4"]).args(&["-m", "4G"])
} else {
cmd.args(&["-smp", "1"]).args(&["-m", "1G"])
};

let cmd = if self.microvm {
let mut sys = System::new();
sys.refresh_cpu_specifics(CpuRefreshKind::new().with_frequency());
let frequency = sys.cpus().first().unwrap().frequency();
assert!(sys.cpus().iter().all(|cpu| cpu.frequency() == frequency));

cmd.args(&["-M", "microvm,x-option-roms=off,pit=off,pic=off,rtc=on"])
.args(&["-global", "virtio-mmio.force-legacy=on"])
.arg("-nodefaults")
.arg("-no-user-config")
.args(&["-append", format!("-freq {frequency}").as_str()])
} else {
cmd
};

let cmd = match self.netdev {
Some(NetworkDevice::VirtioNetPci) => cmd
.args(&[
"-netdev",
"user,id=u1,hostfwd=tcp::9975-:9975,hostfwd=udp::9975-:9975,net=192.168.76.0/24,dhcpstart=192.168.76.9",
])
.args(&["-device", "virtio-net-pci,netdev=u1,disable-legacy=on"]),
Some(NetworkDevice::Rtl8139) => cmd
.args(&[
"-netdev",
"user,id=u1,hostfwd=tcp::9975-:9975,hostfwd=udp::9975-:9975,net=192.168.76.0/24,dhcpstart=192.168.76.9",
])
.args(&["-device", "rtl8139,netdev=u1"]),
None => cmd,
};

let cmd = if self.virtiofsd {
cmd.args(&["-chardev", "socket,id=char0,path=./vhostqemu"])
.args(&[
"-device",
"vhost-user-fs-pci,queue-size=1024,chardev=char0,tag=root",
])
.args(&[
"-object",
"memory-backend-file,id=mem,size=1G,mem-path=/dev/shm,share=on",
])
.args(&["-numa", "node,memdev=mem"])
} else {
cmd
};

let cmd = match self.build.cargo_build.artifact.arch {
Arch::X86_64 => {
let cpu_args = if self.accel {
if cfg!(target_os = "linux") {
&["-enable-kvm", "-cpu", "host"][..]
} else {
todo!()
}
} else {
&["-cpu", "Skylake-Client"][..]
};
cmd.args(cpu_args)
.args(&["-device", "isa-debug-exit,iobase=0xf4,iosize=0x04"])
.args::<&[&Path]>(&["-initrd".as_ref(), self.build.image().as_ref()])
}
Arch::Aarch64 => {
if self.accel {
todo!()
}
cmd.arg("-semihosting")
.args(&["-machine", "virt,gic-version=3"])
.args(&["-cpu", "cortex-a72"])
.args::<&[&Path]>(&[
"-device".as_ref(),
format!(
"guest-loader,addr=0x48000000,initrd={}",
self.build.image().display()
)
.as_ref(),
])
}
};

eprintln!("$ {cmd}");
let mut child = KillChildOnDrop(Command::from(cmd).spawn()?);

thread::sleep(Duration::from_millis(100));
if let Some(status) = child.0.try_wait()? {
ensure!(status.qemu_success(), "QEMU exit code: {:?}", status.code());
}

if self.build.package == "httpd" {
thread::sleep(Duration::from_secs(5));
eprintln!("[CI] GET http://127.0.0.1:9975");
let body = ureq::get("http://127.0.0.1:9975")
.timeout(Duration::from_secs(3))
.call()?
.into_string()?;
eprintln!("[CI] {body}");
assert_eq!(body.lines().next(), Some("Hello from Hermit! 🦀"));
}

if self.build.package == "testudp" {
thread::sleep(Duration::from_secs(5));
let buf = "exit";
eprintln!("[CI] send {buf:?} via UDP to 127.0.0.1:9975");
let socket = UdpSocket::bind("127.0.0.1:0")?;
socket.connect("127.0.0.1:9975")?;
socket.send(buf.as_bytes())?;
}

let status = child
.0
.wait_timeout(Duration::from_secs(60 * 2))?
.ok_or(anyhow!("QEMU timeout"))?;
ensure!(status.qemu_success(), "QEMU exit code: {:?}", status.code());

if let Some(mut virtiofsd) = virtiofsd {
let status = virtiofsd.wait()?;
assert!(status.success());
}

Ok(())
}

fn spawn_virtiofsd(&self) -> Result<Child> {
let sh = crate::sh()?;

sh.create_dir("foo")?;

let cmd = cmd!(sh, "virtiofsd --socket-path=./vhostqemu --shared-dir ./foo --announce-submounts --sandbox none --seccomp none --inode-file-handles=never");

eprintln!("$ {cmd}");

Ok(Command::from(cmd).spawn()?)
}
}
39 changes: 39 additions & 0 deletions xtask/src/ci/uhyve.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use anyhow::Result;
use clap::Args;
use xshell::cmd;

use super::build::Build;

#[derive(Args)]
pub struct Uhyve {
#[command(flatten)]
build: Build,

#[arg(long)]
smp: bool,
}

impl Uhyve {
pub fn run(self) -> Result<()> {
self.build.run()?;

let sh = crate::sh()?;

let image = self.build.image();

cmd!(sh, "uhyve --verbose {image}")
.env("RUST_LOG", "debug")
.args(self.cpu_count_args())
.run()?;

Ok(())
}

fn cpu_count_args(&self) -> &'static [&'static str] {
if self.smp {
&["--cpu-count=4"]
} else {
&[]
}
}
}
4 changes: 4 additions & 0 deletions xtask/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod archive;
mod artifact;
mod build;
mod cargo_build;
mod ci;
mod clippy;

use std::path::Path;
Expand All @@ -16,13 +17,16 @@ use xshell::Shell;
#[derive(Parser)]
enum Cli {
Build(build::Build),
#[command(subcommand)]
Ci(ci::Ci),
Clippy(clippy::Clippy),
}

impl Cli {
fn run(self) -> Result<()> {
match self {
Self::Build(build) => build.run(),
Self::Ci(ci) => ci.run(),
Self::Clippy(clippy) => clippy.run(),
}
}
Expand Down

0 comments on commit 95c747d

Please sign in to comment.