hypha: move components into separate crates

This commit is contained in:
Alex Zenla
2024-02-06 09:07:18 +00:00
parent 0c11744c50
commit e000ab2919
22 changed files with 101 additions and 27 deletions

54
controller/Cargo.toml Normal file
View File

@ -0,0 +1,54 @@
[package]
name = "hyphactrl"
version.workspace = true
edition = "2021"
resolver = "2"
[dependencies]
anyhow = { workspace = true }
log = { workspace = true }
env_logger = { workspace = true }
zstd = { workspace = true }
flate2 = { workspace = true }
tar = { workspace = true }
directories = { workspace = true }
walkdir = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sha256 = { workspace = true }
url = { workspace = true }
ureq = { workspace = true }
path-clean = { workspace = true }
termion = { workspace = true }
cli-tables = { workspace = true }
clap = { workspace = true }
oci-spec = { workspace = true }
backhand = { workspace = true }
uuid = { workspace = true }
ipnetwork = { workspace = true }
[dependencies.hypha]
path = "../shared"
[dependencies.nix]
workspace = true
features = ["process"]
[dependencies.advmac]
path = "../libs/advmac"
[dependencies.loopdev]
path = "../libs/loopdev"
[dependencies.xenclient]
path = "../libs/xen/xenclient"
[dependencies.xenstore]
path = "../libs/xen/xenstore"
[lib]
path = "src/lib.rs"
[[bin]]
name = "hyphactl"
path = "bin/control.rs"

153
controller/bin/control.rs Normal file
View File

@ -0,0 +1,153 @@
use anyhow::{anyhow, Result};
use clap::{Parser, Subcommand};
use env_logger::Env;
use hyphactrl::ctl::Controller;
use std::path::PathBuf;
#[derive(Parser, Debug)]
#[command(version, about)]
struct ControllerArgs {
#[arg(short, long, default_value = "auto")]
store: String,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
List {},
Launch {
#[arg(short, long, default_value = "auto")]
kernel: String,
#[arg(short = 'r', long, default_value = "auto")]
initrd: String,
#[arg(short, long, default_value_t = 1)]
cpus: u32,
#[arg(short, long, default_value_t = 512)]
mem: u64,
#[arg(long)]
config_bundle: Option<String>,
#[arg[short, long]]
env: Option<Vec<String>>,
#[arg(short, long)]
attach: bool,
#[arg(long)]
debug: bool,
#[arg()]
image: String,
#[arg(allow_hyphen_values = true, trailing_var_arg = true)]
run: Vec<String>,
},
Destroy {
#[arg()]
container: String,
},
Console {
#[arg()]
container: String,
},
}
fn main() -> Result<()> {
env_logger::Builder::from_env(Env::default().default_filter_or("warn")).init();
let args = ControllerArgs::parse();
let store_path = if args.store == "auto" {
default_store_path().ok_or_else(|| anyhow!("unable to determine default store path"))
} else {
Ok(PathBuf::from(args.store))
}?;
let store_path = store_path
.to_str()
.map(|x| x.to_string())
.ok_or_else(|| anyhow!("unable to convert store path to string"))?;
let mut controller = Controller::new(store_path.clone())?;
match args.command {
Commands::Launch {
kernel,
initrd,
image,
cpus,
mem,
config_bundle,
attach,
env,
run,
debug,
} => {
let kernel = map_kernel_path(&store_path, kernel);
let initrd = map_initrd_path(&store_path, initrd);
let (uuid, _domid) = controller.launch(
&kernel,
&initrd,
config_bundle.as_deref(),
&image,
cpus,
mem,
env,
if run.is_empty() { None } else { Some(run) },
debug,
)?;
println!("launched container: {}", uuid);
if attach {
controller.console(&uuid.to_string())?;
}
}
Commands::Destroy { container } => {
controller.destroy(&container)?;
}
Commands::Console { container } => {
controller.console(&container)?;
}
Commands::List { .. } => {
let containers = controller.list()?;
let mut table = cli_tables::Table::new();
let header = vec!["uuid", "ipv4", "image"];
table.push_row(&header)?;
for container in containers {
let row = vec![container.uuid.to_string(), container.ipv4, container.image];
table.push_row_string(&row)?;
}
if table.num_records() == 1 {
println!("no containers have been launched");
} else {
println!("{}", table.to_string());
}
}
}
Ok(())
}
fn map_kernel_path(store: &str, value: String) -> String {
if value == "auto" {
return format!("{}/default/kernel", store);
}
value
}
fn map_initrd_path(store: &str, value: String) -> String {
if value == "auto" {
return format!("{}/default/initrd", store);
}
value
}
fn default_store_path() -> Option<PathBuf> {
let user_dirs = directories::UserDirs::new()?;
let mut path = user_dirs.home_dir().to_path_buf();
if path == PathBuf::from("/root") {
path.push("/var/lib/hypha")
} else {
path.push(".hypha");
}
Some(path)
}

View File

@ -0,0 +1,33 @@
use anyhow::{anyhow, Result};
use loopdev::{LoopControl, LoopDevice};
use xenclient::BlockDeviceRef;
pub struct AutoLoop {
control: LoopControl,
}
impl AutoLoop {
pub(crate) fn new(control: LoopControl) -> AutoLoop {
AutoLoop { control }
}
pub fn loopify(&self, file: &str) -> Result<BlockDeviceRef> {
let device = self.control.next_free()?;
device.with().read_only(true).attach(file)?;
let path = device
.path()
.ok_or(anyhow!("unable to get loop device path"))?
.to_str()
.ok_or(anyhow!("unable to convert loop device path to string",))?
.to_string();
let major = device.major()?;
let minor = device.minor()?;
Ok(BlockDeviceRef { path, major, minor })
}
pub fn unloop(&self, device: &str) -> Result<()> {
let device = LoopDevice::open(device)?;
device.detach()?;
Ok(())
}
}

View File

@ -0,0 +1,93 @@
use crate::image::ImageInfo;
use crate::shared::LaunchInfo;
use anyhow::Result;
use backhand::{FilesystemWriter, NodeHeader};
use log::trace;
use std::fs;
use std::fs::File;
use std::path::PathBuf;
use uuid::Uuid;
pub struct ConfigBlock<'a> {
pub image_info: &'a ImageInfo,
pub config_bundle: Option<&'a str>,
pub file: PathBuf,
pub dir: PathBuf,
}
impl ConfigBlock<'_> {
pub fn new<'a>(
uuid: &Uuid,
image_info: &'a ImageInfo,
config_bundle: Option<&'a str>,
) -> Result<ConfigBlock<'a>> {
let mut dir = std::env::temp_dir().clone();
dir.push(format!("hypha-cfg-{}", uuid));
fs::create_dir_all(&dir)?;
let mut file = dir.clone();
file.push("config.squashfs");
Ok(ConfigBlock {
image_info,
config_bundle,
file,
dir,
})
}
pub fn build(&self, launch_config: &LaunchInfo) -> Result<()> {
trace!("ConfigBlock build launch_config={:?}", launch_config);
let config_bundle_content = match self.config_bundle {
None => None,
Some(path) => Some(fs::read(path)?),
};
let manifest = self.image_info.config.to_string()?;
let launch = serde_json::to_string(launch_config)?;
let mut writer = FilesystemWriter::default();
writer.push_dir(
"/image",
NodeHeader {
permissions: 384,
uid: 0,
gid: 0,
mtime: 0,
},
)?;
writer.push_file(
manifest.as_bytes(),
"/image/config.json",
NodeHeader {
permissions: 384,
uid: 0,
gid: 0,
mtime: 0,
},
)?;
writer.push_file(
launch.as_bytes(),
"/launch.json",
NodeHeader {
permissions: 384,
uid: 0,
gid: 0,
mtime: 0,
},
)?;
if let Some(config_bundle_content) = config_bundle_content.as_ref() {
writer.push_file(
config_bundle_content.as_slice(),
"/bundle",
NodeHeader {
permissions: 384,
uid: 0,
gid: 0,
mtime: 0,
},
)?;
}
let mut file = File::create(&self.file)?;
trace!("ConfigBlock build write sqaushfs");
writer.write(&mut file)?;
trace!("ConfigBlock build complete");
Ok(())
}
}

366
controller/src/ctl/mod.rs Normal file
View File

@ -0,0 +1,366 @@
pub mod cfgblk;
use crate::autoloop::AutoLoop;
use crate::ctl::cfgblk::ConfigBlock;
use crate::image::cache::ImageCache;
use crate::image::name::ImageName;
use crate::image::{ImageCompiler, ImageInfo};
use crate::shared::{LaunchInfo, LaunchNetwork};
use advmac::MacAddr6;
use anyhow::{anyhow, Result};
use ipnetwork::Ipv4Network;
use loopdev::LoopControl;
use std::io::{Read, Write};
use std::net::Ipv4Addr;
use std::path::PathBuf;
use std::process::exit;
use std::str::FromStr;
use std::{fs, io, thread};
use termion::raw::IntoRawMode;
use uuid::Uuid;
use xenclient::{DomainConfig, DomainDisk, DomainNetworkInterface, XenClient};
use xenstore::client::{XsdClient, XsdInterface};
pub struct Controller {
image_cache: ImageCache,
autoloop: AutoLoop,
client: XenClient,
}
pub struct ContainerLoopInfo {
pub device: String,
pub file: String,
pub delete: Option<String>,
}
pub struct ContainerInfo {
pub uuid: Uuid,
pub domid: u32,
pub image: String,
pub loops: Vec<ContainerLoopInfo>,
pub ipv4: String,
}
impl Controller {
pub fn new(store_path: String) -> Result<Controller> {
let mut image_cache_path = PathBuf::from(store_path);
image_cache_path.push("cache");
fs::create_dir_all(&image_cache_path)?;
let client = XenClient::open()?;
image_cache_path.push("image");
fs::create_dir_all(&image_cache_path)?;
let image_cache = ImageCache::new(&image_cache_path)?;
Ok(Controller {
image_cache,
autoloop: AutoLoop::new(LoopControl::open()?),
client,
})
}
fn compile(&mut self, image: &str) -> Result<ImageInfo> {
let image = ImageName::parse(image)?;
let compiler = ImageCompiler::new(&self.image_cache)?;
compiler.compile(&image)
}
#[allow(clippy::too_many_arguments)]
pub fn launch(
&mut self,
kernel_path: &str,
initrd_path: &str,
config_bundle_path: Option<&str>,
image: &str,
vcpus: u32,
mem: u64,
env: Option<Vec<String>>,
run: Option<Vec<String>>,
debug: bool,
) -> Result<(Uuid, u32)> {
let uuid = Uuid::new_v4();
let name = format!("hypha-{uuid}");
let image_info = self.compile(image)?;
let ipv4 = self.allocate_ipv4()?;
let launch_config = LaunchInfo {
network: Some(LaunchNetwork {
link: "eth0".to_string(),
ipv4: format!("{}/24", ipv4),
}),
env,
run,
};
let cfgblk = ConfigBlock::new(&uuid, &image_info, config_bundle_path)?;
cfgblk.build(&launch_config)?;
let image_squashfs_path = image_info
.image_squashfs
.to_str()
.ok_or_else(|| anyhow!("failed to convert image squashfs path to string"))?;
let cfgblk_dir_path = cfgblk
.dir
.to_str()
.ok_or_else(|| anyhow!("failed to convert cfgblk directory path to string"))?;
let cfgblk_squashfs_path = cfgblk
.file
.to_str()
.ok_or_else(|| anyhow!("failed to convert cfgblk squashfs path to string"))?;
let image_squashfs_loop = self.autoloop.loopify(image_squashfs_path)?;
let cfgblk_squashfs_loop = self.autoloop.loopify(cfgblk_squashfs_path)?;
let cmdline_options = [if debug { "debug" } else { "quiet" }, "elevator=noop"];
let cmdline = cmdline_options.join(" ");
let mac = MacAddr6::random()
.to_string()
.replace('-', ":")
.to_lowercase();
let config = DomainConfig {
backend_domid: 0,
name: &name,
max_vcpus: vcpus,
mem_mb: mem,
kernel_path,
initrd_path,
cmdline: &cmdline,
disks: vec![
DomainDisk {
vdev: "xvda",
block: &image_squashfs_loop,
writable: false,
},
DomainDisk {
vdev: "xvdb",
block: &cfgblk_squashfs_loop,
writable: false,
},
],
vifs: vec![DomainNetworkInterface {
mac: &mac,
mtu: 1500,
bridge: None,
script: None,
}],
filesystems: vec![],
extra_keys: vec![
("hypha/uuid".to_string(), uuid.to_string()),
(
"hypha/loops".to_string(),
format!(
"{}:{}:none,{}:{}:{}",
&image_squashfs_loop.path,
image_squashfs_path,
&cfgblk_squashfs_loop.path,
cfgblk_squashfs_path,
cfgblk_dir_path,
),
),
("hypha/image".to_string(), image.to_string()),
("hypha/ipv4".to_string(), ipv4.to_string()),
],
};
match self.client.create(&config) {
Ok(domid) => Ok((uuid, domid)),
Err(error) => {
let _ = self.autoloop.unloop(&image_squashfs_loop.path);
let _ = self.autoloop.unloop(&cfgblk_squashfs_loop.path);
let _ = fs::remove_dir(&cfgblk.dir);
Err(error.into())
}
}
}
pub fn destroy(&mut self, id: &str) -> Result<Uuid> {
let info = self
.resolve(id)?
.ok_or_else(|| anyhow!("unable to resolve container: {}", id))?;
let domid = info.domid;
let mut store = XsdClient::open()?;
let dom_path = store.get_domain_path(domid)?;
let uuid = match store.read_string_optional(format!("{}/hypha/uuid", dom_path).as_str())? {
None => {
return Err(anyhow!(
"domain {} was not found or not created by hypha",
domid
))
}
Some(value) => value,
};
if uuid.is_empty() {
return Err(anyhow!("unable to find hypha uuid based on the domain",));
}
let uuid = Uuid::parse_str(&uuid)?;
let loops = store.read_string(format!("{}/hypha/loops", dom_path).as_str())?;
let loops = Controller::parse_loop_set(&loops);
self.client.destroy(domid)?;
for info in &loops {
self.autoloop.unloop(&info.device)?;
match &info.delete {
None => {}
Some(delete) => {
let delete_path = PathBuf::from(delete);
if delete_path.is_file() || delete_path.is_symlink() {
fs::remove_file(&delete_path)?;
} else if delete_path.is_dir() {
fs::remove_dir_all(&delete_path)?;
}
}
}
}
Ok(uuid)
}
pub fn console(&mut self, id: &str) -> Result<()> {
let info = self
.resolve(id)?
.ok_or_else(|| anyhow!("unable to resolve container: {}", id))?;
let domid = info.domid;
let (mut read, mut write) = self.client.open_console(domid)?;
let mut stdin = io::stdin();
let is_tty = termion::is_tty(&stdin);
let mut stdout_for_exit = io::stdout().into_raw_mode()?;
thread::spawn(move || {
let mut buffer = vec![0u8; 60];
loop {
let size = stdin.read(&mut buffer).expect("failed to read stdin");
if is_tty && size == 1 && buffer[0] == 0x1d {
stdout_for_exit
.suspend_raw_mode()
.expect("failed to disable raw mode");
stdout_for_exit.flush().expect("failed to flush stdout");
exit(0);
}
write
.write_all(&buffer[0..size])
.expect("failed to write to domain console");
write.flush().expect("failed to flush domain console");
}
});
let mut buffer = vec![0u8; 256];
if is_tty {
let mut stdout = io::stdout().into_raw_mode()?;
loop {
let size = read.read(&mut buffer)?;
stdout.write_all(&buffer[0..size])?;
stdout.flush()?;
}
} else {
let mut stdout = io::stdout();
loop {
let size = read.read(&mut buffer)?;
stdout.write_all(&buffer[0..size])?;
stdout.flush()?;
}
}
}
pub fn list(&mut self) -> Result<Vec<ContainerInfo>> {
let mut containers: Vec<ContainerInfo> = Vec::new();
for domid_candidate in self.client.store.list_any("/local/domain")? {
let dom_path = format!("/local/domain/{}", domid_candidate);
let uuid_string = match self
.client
.store
.read_string_optional(&format!("{}/hypha/uuid", &dom_path))?
{
None => continue,
Some(value) => value,
};
let domid =
u32::from_str(&domid_candidate).map_err(|_| anyhow!("failed to parse domid"))?;
let uuid = Uuid::from_str(&uuid_string)?;
let image = self
.client
.store
.read_string_optional(&format!("{}/hypha/image", &dom_path))?
.unwrap_or("unknown".to_string());
let loops = self
.client
.store
.read_string_optional(&format!("{}/hypha/loops", &dom_path))?
.unwrap_or("".to_string());
let ipv4 = self
.client
.store
.read_string_optional(&format!("{}/hypha/ipv4", &dom_path))?
.unwrap_or("unknown".to_string());
let loops = Controller::parse_loop_set(&loops);
containers.push(ContainerInfo {
uuid,
domid,
image,
loops,
ipv4,
});
}
Ok(containers)
}
pub fn resolve(&mut self, id: &str) -> Result<Option<ContainerInfo>> {
for container in self.list()? {
let uuid_string = container.uuid.to_string();
let domid_string = container.domid.to_string();
if uuid_string == id || domid_string == id || id == format!("hypha-{}", uuid_string) {
return Ok(Some(container));
}
}
Ok(None)
}
fn parse_loop_set(input: &str) -> Vec<ContainerLoopInfo> {
let sets = input
.split(',')
.map(|x| x.to_string())
.map(|x| x.split(':').map(|v| v.to_string()).collect::<Vec<String>>())
.map(|x| (x[0].clone(), x[1].clone(), x[2].clone()))
.collect::<Vec<(String, String, String)>>();
sets.iter()
.map(|(device, file, delete)| ContainerLoopInfo {
device: device.clone(),
file: file.clone(),
delete: if delete == "none" {
None
} else {
Some(delete.clone())
},
})
.collect::<Vec<ContainerLoopInfo>>()
}
fn allocate_ipv4(&mut self) -> Result<Ipv4Addr> {
let network = Ipv4Network::new(Ipv4Addr::new(192, 168, 42, 0), 24)?;
let mut used: Vec<Ipv4Addr> = vec![
Ipv4Addr::new(192, 168, 42, 0),
Ipv4Addr::new(192, 168, 42, 1),
Ipv4Addr::new(192, 168, 42, 255),
];
for domid_candidate in self.client.store.list_any("/local/domain")? {
let dom_path = format!("/local/domain/{}", domid_candidate);
let ip_path = format!("{}/hypha/ipv4", dom_path);
let existing_ip = self.client.store.read_string_optional(&ip_path)?;
if let Some(existing_ip) = existing_ip {
used.push(Ipv4Addr::from_str(&existing_ip)?);
}
}
let mut found: Option<Ipv4Addr> = None;
for ip in network.iter() {
if !used.contains(&ip) {
found = Some(ip);
break;
}
}
if found.is_none() {
return Err(anyhow!(
"unable to find ipv4 to allocate to container, ipv4 addresses are exhausted"
));
}
Ok(found.unwrap())
}
}

View File

@ -0,0 +1,69 @@
use crate::image::{ImageInfo, Result};
use log::debug;
use oci_spec::image::{ImageConfiguration, ImageManifest};
use std::fs;
use std::path::{Path, PathBuf};
pub struct ImageCache {
cache_dir: PathBuf,
}
impl ImageCache {
pub fn new(cache_dir: &Path) -> Result<ImageCache> {
Ok(ImageCache {
cache_dir: cache_dir.to_path_buf(),
})
}
pub fn recall(&self, digest: &str) -> Result<Option<ImageInfo>> {
let mut squashfs_path = self.cache_dir.clone();
let mut config_path = self.cache_dir.clone();
let mut manifest_path = self.cache_dir.clone();
squashfs_path.push(format!("{}.squashfs", digest));
manifest_path.push(format!("{}.manifest.json", digest));
config_path.push(format!("{}.config.json", digest));
Ok(
if squashfs_path.exists() && manifest_path.exists() && config_path.exists() {
let squashfs_metadata = fs::metadata(&squashfs_path)?;
let manifest_metadata = fs::metadata(&manifest_path)?;
let config_metadata = fs::metadata(&config_path)?;
if squashfs_metadata.is_file()
&& manifest_metadata.is_file()
&& config_metadata.is_file()
{
let manifest_text = fs::read_to_string(&manifest_path)?;
let manifest: ImageManifest = serde_json::from_str(&manifest_text)?;
let config_text = fs::read_to_string(&config_path)?;
let config: ImageConfiguration = serde_json::from_str(&config_text)?;
debug!("cache hit digest={}", digest);
Some(ImageInfo::new(squashfs_path.clone(), manifest, config)?)
} else {
None
}
} else {
debug!("cache miss digest={}", digest);
None
},
)
}
pub fn store(&self, digest: &str, info: &ImageInfo) -> Result<ImageInfo> {
debug!("cache store digest={}", digest);
let mut squashfs_path = self.cache_dir.clone();
let mut manifest_path = self.cache_dir.clone();
let mut config_path = self.cache_dir.clone();
squashfs_path.push(format!("{}.squashfs", digest));
manifest_path.push(format!("{}.manifest.json", digest));
config_path.push(format!("{}.config.json", digest));
fs::copy(&info.image_squashfs, &squashfs_path)?;
let manifest_text = serde_json::to_string_pretty(&info.manifest)?;
fs::write(&manifest_path, manifest_text)?;
let config_text = serde_json::to_string_pretty(&info.config)?;
fs::write(&config_path, config_text)?;
ImageInfo::new(
squashfs_path.clone(),
info.manifest.clone(),
info.config.clone(),
)
}
}

View File

@ -0,0 +1,96 @@
use anyhow::{anyhow, Result};
use oci_spec::image::{Arch, Descriptor, ImageIndex, ImageManifest, MediaType, Os, ToDockerV2S2};
use std::io::copy;
use std::io::{Read, Write};
use std::ops::DerefMut;
use ureq::{Agent, Request, Response};
use url::Url;
pub struct RegistryClient {
agent: Agent,
url: Url,
}
impl RegistryClient {
pub fn new(url: Url) -> Result<RegistryClient> {
Ok(RegistryClient {
agent: Agent::new(),
url,
})
}
fn call(&mut self, req: Request) -> Result<Response> {
Ok(req.call()?)
}
pub fn get_blob(&mut self, name: &str, descriptor: &Descriptor) -> Result<Vec<u8>> {
let url = self
.url
.join(&format!("/v2/{}/blobs/{}", name, descriptor.digest()))?;
let response = self.call(self.agent.get(url.as_str()))?;
let mut buffer: Vec<u8> = Vec::new();
response.into_reader().read_to_end(&mut buffer)?;
Ok(buffer)
}
pub fn write_blob(
&mut self,
name: &str,
descriptor: &Descriptor,
dest: &mut dyn Write,
) -> Result<u64> {
let url = self
.url
.join(&format!("/v2/{}/blobs/{}", name, descriptor.digest()))?;
let response = self.call(self.agent.get(url.as_str()))?;
let mut reader = response.into_reader();
Ok(copy(reader.deref_mut(), dest)?)
}
pub fn get_manifest_with_digest(
&mut self,
name: &str,
reference: &str,
) -> Result<(ImageManifest, String)> {
let url = self
.url
.join(&format!("/v2/{}/manifests/{}", name, reference))?;
let accept = format!(
"{}, {}, {}, {}",
MediaType::ImageManifest.to_docker_v2s2()?,
MediaType::ImageManifest,
MediaType::ImageIndex,
MediaType::ImageIndex.to_docker_v2s2()?,
);
let response = self.call(self.agent.get(url.as_str()).set("Accept", &accept))?;
let content_type = response
.header("Content-Type")
.ok_or_else(|| anyhow!("registry response did not have a Content-Type header"))?;
if content_type == MediaType::ImageIndex.to_string()
|| content_type == MediaType::ImageIndex.to_docker_v2s2()?
{
let index = ImageIndex::from_reader(response.into_reader())?;
let descriptor = self
.pick_manifest(index)
.ok_or_else(|| anyhow!("unable to pick manifest from index"))?;
return self.get_manifest_with_digest(name, descriptor.digest());
}
let digest = response
.header("Docker-Content-Digest")
.ok_or_else(|| anyhow!("fetching manifest did not yield a content digest"))?
.to_string();
let manifest = ImageManifest::from_reader(response.into_reader())?;
Ok((manifest, digest))
}
fn pick_manifest(&mut self, index: ImageIndex) -> Option<Descriptor> {
for item in index.manifests() {
if let Some(platform) = item.platform() {
if *platform.os() == Os::Linux && *platform.architecture() == Arch::Amd64 {
return Some(item.clone());
}
}
}
None
}
}

407
controller/src/image/mod.rs Normal file
View File

@ -0,0 +1,407 @@
pub mod cache;
pub mod fetch;
pub mod name;
use crate::image::cache::ImageCache;
use crate::image::fetch::RegistryClient;
use crate::image::name::ImageName;
use anyhow::{anyhow, Result};
use backhand::compression::Compressor;
use backhand::{FilesystemCompressor, FilesystemWriter, NodeHeader};
use flate2::read::GzDecoder;
use log::{debug, trace, warn};
use oci_spec::image::{Descriptor, ImageConfiguration, ImageManifest, MediaType, ToDockerV2S2};
use std::fs::File;
use std::io::{BufReader, Cursor};
use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::{fs, io};
use tar::{Archive, Entry};
use uuid::Uuid;
use walkdir::WalkDir;
pub const IMAGE_SQUASHFS_VERSION: u64 = 1;
const LAYER_BUFFER_SIZE: usize = 128 * 1024;
// we utilize in-memory buffers when generating the squashfs for files
// under this size. for files of or above this size, we open a file.
// the file is then read during writing. we want to reduce the number
// of open files during squashfs generation, so this limit should be set
// to something that limits the number of files on average, at the expense
// of increased memory usage.
// TODO: it may be wise to, during crawling of the image layers, infer this
// value from the size to file count ratio of all layers.
const SQUASHFS_MEMORY_BUFFER_LIMIT: usize = 8 * 1024 * 1024;
pub struct ImageInfo {
pub image_squashfs: PathBuf,
pub manifest: ImageManifest,
pub config: ImageConfiguration,
}
impl ImageInfo {
fn new(
squashfs: PathBuf,
manifest: ImageManifest,
config: ImageConfiguration,
) -> Result<ImageInfo> {
Ok(ImageInfo {
image_squashfs: squashfs,
manifest,
config,
})
}
}
pub struct ImageCompiler<'a> {
cache: &'a ImageCache,
}
#[derive(Debug)]
enum LayerCompressionType {
None,
Gzip,
Zstd,
}
struct LayerFile {
digest: String,
compression: LayerCompressionType,
path: PathBuf,
}
impl LayerFile {
fn open_reader(&self) -> Result<Box<dyn io::Read>> {
Ok(match self.compression {
LayerCompressionType::None => Box::new(BufReader::with_capacity(
LAYER_BUFFER_SIZE,
File::open(&self.path)?,
)),
LayerCompressionType::Gzip => Box::new(GzDecoder::new(BufReader::with_capacity(
LAYER_BUFFER_SIZE,
File::open(&self.path)?,
))),
LayerCompressionType::Zstd => Box::new(zstd::Decoder::new(BufReader::with_capacity(
LAYER_BUFFER_SIZE,
File::open(&self.path)?,
))?),
})
}
}
impl ImageCompiler<'_> {
pub fn new(cache: &ImageCache) -> Result<ImageCompiler> {
Ok(ImageCompiler { cache })
}
pub fn compile(&self, image: &ImageName) -> Result<ImageInfo> {
debug!("ImageCompiler compile image={image}");
let mut tmp_dir = std::env::temp_dir().clone();
tmp_dir.push(format!("hypha-compile-{}", Uuid::new_v4()));
let mut image_dir = tmp_dir.clone();
image_dir.push("image");
fs::create_dir_all(&image_dir)?;
let mut layer_dir = tmp_dir.clone();
layer_dir.push("layer");
fs::create_dir_all(&layer_dir)?;
let mut squash_file = tmp_dir.clone();
squash_file.push("image.squashfs");
let info = self.download_and_compile(image, &layer_dir, &image_dir, &squash_file)?;
fs::remove_dir_all(&tmp_dir)?;
Ok(info)
}
fn download_and_compile(
&self,
image: &ImageName,
layer_dir: &Path,
image_dir: &PathBuf,
squash_file: &PathBuf,
) -> Result<ImageInfo> {
debug!(
"ImageCompiler download manifest image={image}, image_dir={}",
image_dir.to_str().unwrap()
);
let mut client = RegistryClient::new(image.registry_url()?)?;
let (manifest, digest) = client.get_manifest_with_digest(&image.name, &image.reference)?;
let cache_key = format!(
"manifest={}:squashfs-version={}\n",
digest, IMAGE_SQUASHFS_VERSION
);
let cache_digest = sha256::digest(cache_key);
if let Some(cached) = self.cache.recall(&cache_digest)? {
return Ok(cached);
}
debug!(
"ImageCompiler download config digest={} size={}",
manifest.config().digest(),
manifest.config().size(),
);
let config_bytes = client.get_blob(&image.name, manifest.config())?;
let config: ImageConfiguration = serde_json::from_slice(&config_bytes)?;
let mut layers: Vec<LayerFile> = Vec::new();
for layer in manifest.layers() {
layers.push(self.download_layer(image, layer, layer_dir, &mut client)?);
}
for layer in layers {
debug!(
"ImageCompiler process layer digest={} compression={:?}",
&layer.digest, layer.compression
);
let mut archive = Archive::new(layer.open_reader()?);
for entry in archive.entries()? {
let mut entry = entry?;
let path = entry.path()?;
let Some(name) = path.file_name() else {
return Err(anyhow!("unable to get file name"));
};
let Some(name) = name.to_str() else {
return Err(anyhow!("unable to get file name as string"));
};
if name.starts_with(".wh.") {
self.process_whiteout_entry(&entry, name, &layer, image_dir)?;
} else {
self.process_write_entry(&mut entry, &layer, image_dir)?;
}
}
fs::remove_file(&layer.path)?;
}
self.squash(image_dir, squash_file)?;
let info = ImageInfo::new(squash_file.clone(), manifest.clone(), config)?;
self.cache.store(&cache_digest, &info)
}
fn process_whiteout_entry<T: io::Read>(
&self,
entry: &Entry<T>,
name: &str,
layer: &LayerFile,
image_dir: &PathBuf,
) -> Result<()> {
let dst = self.check_safe_entry(entry, image_dir)?;
let mut dst = dst.clone();
dst.pop();
let opaque = name == ".wh..wh..opq";
if !opaque {
dst.push(name);
self.check_safe_path(&dst, image_dir)?;
}
trace!(
"ImageCompiler whiteout entry layer={} path={:?}",
&layer.digest,
entry.path()?
);
if opaque {
if dst.is_dir() {
for entry in fs::read_dir(dst)? {
let entry = entry?;
let path = entry.path();
if path.is_symlink() || path.is_file() {
fs::remove_file(&path)?;
} else if path.is_dir() {
fs::remove_dir_all(&path)?;
} else {
return Err(anyhow!("opaque whiteout entry did not exist"));
}
}
} else {
warn!(
"ImageCompiler whiteout entry missing locally layer={} path={:?} local={:?}",
&layer.digest,
entry.path()?,
dst,
);
}
} else if dst.is_file() || dst.is_symlink() {
fs::remove_file(&dst)?;
} else if dst.is_dir() {
fs::remove_dir(&dst)?;
} else {
warn!(
"ImageCompiler whiteout entry missing locally layer={} path={:?} local={:?}",
&layer.digest,
entry.path()?,
dst,
);
}
Ok(())
}
fn process_write_entry<T: io::Read>(
&self,
entry: &mut Entry<T>,
layer: &LayerFile,
image_dir: &PathBuf,
) -> Result<()> {
trace!(
"ImageCompiler unpack entry layer={} path={:?} type={:?}",
&layer.digest,
entry.path()?,
entry.header().entry_type()
);
entry.unpack_in(image_dir)?;
Ok(())
}
fn check_safe_entry<T: io::Read>(
&self,
entry: &Entry<T>,
image_dir: &PathBuf,
) -> Result<PathBuf> {
let mut dst = image_dir.clone();
dst.push(entry.path()?);
if let Some(name) = dst.file_name() {
if let Some(name) = name.to_str() {
if name.starts_with(".wh.") {
let copy = dst.clone();
dst.pop();
self.check_safe_path(&dst, image_dir)?;
return Ok(copy);
}
}
}
self.check_safe_path(&dst, image_dir)?;
Ok(dst)
}
fn check_safe_path(&self, dst: &PathBuf, image_dir: &PathBuf) -> Result<()> {
let resolved = path_clean::clean(dst);
if !resolved.starts_with(image_dir) {
return Err(anyhow!("layer attempts to work outside image dir"));
}
Ok(())
}
fn download_layer(
&self,
image: &ImageName,
layer: &Descriptor,
layer_dir: &Path,
client: &mut RegistryClient,
) -> Result<LayerFile> {
debug!(
"ImageCompiler download layer digest={} size={}",
layer.digest(),
layer.size()
);
let mut layer_path = layer_dir.to_path_buf();
layer_path.push(layer.digest());
let mut tmp_path = layer_dir.to_path_buf();
tmp_path.push(format!("{}.tmp", layer.digest()));
{
let mut file = File::create(&layer_path)?;
let size = client.write_blob(&image.name, layer, &mut file)?;
if layer.size() as u64 != size {
return Err(anyhow!(
"downloaded layer size differs from size in manifest",
));
}
}
let mut media_type = layer.media_type().clone();
// docker layer compatibility
if media_type.to_string() == MediaType::ImageLayerGzip.to_docker_v2s2()? {
media_type = MediaType::ImageLayerGzip;
}
let compression = match media_type {
MediaType::ImageLayer => LayerCompressionType::None,
MediaType::ImageLayerGzip => LayerCompressionType::Gzip,
MediaType::ImageLayerZstd => LayerCompressionType::Zstd,
other => return Err(anyhow!("found layer with unknown media type: {}", other)),
};
Ok(LayerFile {
digest: layer.digest().clone(),
compression,
path: layer_path,
})
}
fn squash(&self, image_dir: &PathBuf, squash_file: &PathBuf) -> Result<()> {
let mut writer = FilesystemWriter::default();
writer.set_compressor(FilesystemCompressor::new(Compressor::Gzip, None)?);
let walk = WalkDir::new(image_dir).follow_links(false);
for entry in walk {
let entry = entry?;
let rel = entry
.path()
.strip_prefix(image_dir)?
.to_str()
.ok_or_else(|| anyhow!("failed to strip prefix of tmpdir"))?;
let rel = format!("/{}", rel);
trace!("ImageCompiler squash write {}", rel);
let typ = entry.file_type();
let metadata = fs::symlink_metadata(entry.path())?;
let uid = metadata.uid();
let gid = metadata.gid();
let mode = metadata.permissions().mode();
let mtime = metadata.mtime();
if rel == "/" {
writer.set_root_uid(uid);
writer.set_root_gid(gid);
writer.set_root_mode(mode as u16);
continue;
}
let header = NodeHeader {
permissions: mode as u16,
uid,
gid,
mtime: mtime as u32,
};
if typ.is_symlink() {
let symlink = fs::read_link(entry.path())?;
let symlink = symlink
.to_str()
.ok_or_else(|| anyhow!("failed to read symlink"))?;
writer.push_symlink(symlink, rel, header)?;
} else if typ.is_dir() {
writer.push_dir(rel, header)?;
} else if typ.is_file() {
if metadata.size() >= SQUASHFS_MEMORY_BUFFER_LIMIT as u64 {
let reader =
BufReader::with_capacity(LAYER_BUFFER_SIZE, File::open(entry.path())?);
writer.push_file(reader, rel, header)?;
} else {
let cursor = Cursor::new(fs::read(entry.path())?);
writer.push_file(cursor, rel, header)?;
}
} else if typ.is_block_device() {
let device = metadata.dev();
writer.push_block_device(device as u32, rel, header)?;
} else if typ.is_char_device() {
let device = metadata.dev();
writer.push_char_device(device as u32, rel, header)?;
} else {
return Err(anyhow!("invalid file type"));
}
}
fs::remove_dir_all(image_dir)?;
let squash_file_path = squash_file
.to_str()
.ok_or_else(|| anyhow!("failed to convert squashfs string"))?;
let mut file = File::create(squash_file)?;
trace!("ImageCompiler squash generate: {}", squash_file_path);
writer.write(&mut file)?;
Ok(())
}
}

View File

@ -0,0 +1,67 @@
use anyhow::Result;
use std::fmt;
use url::Url;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ImageName {
pub hostname: String,
pub port: Option<u16>,
pub name: String,
pub reference: String,
}
impl fmt::Display for ImageName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(port) = self.port {
write!(
f,
"{}:{}/{}:{}",
self.hostname, port, self.name, self.reference
)
} else {
write!(f, "{}/{}:{}", self.hostname, self.name, self.reference)
}
}
}
impl Default for ImageName {
fn default() -> Self {
Self::parse(&format!("{}", uuid::Uuid::new_v4().as_hyphenated()))
.expect("UUID hyphenated must be valid name")
}
}
impl ImageName {
pub fn parse(name: &str) -> Result<Self> {
let (hostname, name) = name
.split_once('/')
.unwrap_or(("registry-1.docker.io", name));
let (hostname, port) = if let Some((hostname, port)) = hostname.split_once(':') {
(hostname, Some(str::parse(port)?))
} else {
(hostname, None)
};
let (name, reference) = name.split_once(':').unwrap_or((name, "latest"));
Ok(ImageName {
hostname: hostname.to_string(),
port,
name: name.to_string(),
reference: reference.to_string(),
})
}
/// URL for OCI distribution API endpoint
pub fn registry_url(&self) -> Result<Url> {
let hostname = if let Some(port) = self.port {
format!("{}:{}", self.hostname, port)
} else {
self.hostname.clone()
};
let url = if self.hostname.starts_with("localhost") {
format!("http://{}", hostname)
} else {
format!("https://{}", hostname)
};
Ok(Url::parse(&url)?)
}
}

4
controller/src/lib.rs Normal file
View File

@ -0,0 +1,4 @@
pub mod autoloop;
pub mod ctl;
pub mod image;
pub mod shared;

View File

@ -0,0 +1,14 @@
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
pub struct LaunchNetwork {
pub link: String,
pub ipv4: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct LaunchInfo {
pub network: Option<LaunchNetwork>,
pub env: Option<Vec<String>>,
pub run: Option<Vec<String>>,
}