use crate::blueprint::instructions::Jailfile;
use crate::blueprint::{self, BuildContext, TemplateExecutor, parse_jailfile};
use crate::error::{Error, Result};
use crate::host::Host;
use crate::release::{Bootstrap, Release};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Build {
file: PathBuf,
context: Option<PathBuf>,
name: Option<String>,
args: Vec<(String, String)>,
}
impl Build {
pub fn jailfile(path: impl Into<PathBuf>) -> Self {
Self {
file: path.into(),
context: None,
name: None,
args: Vec::new(),
}
}
#[must_use]
pub fn context(mut self, dir: impl Into<PathBuf>) -> Self {
self.context = Some(dir.into());
self
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn arg(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.args.push((key.into(), value.into()));
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
pub name: String,
pub root: PathBuf,
pub base: Option<String>,
}
impl Host {
pub fn build(&self, build: &Build) -> Result<Image> {
Error::require_root("building an image")?;
let jailfile = read_jailfile(&build.file)?;
let name = build
.name
.clone()
.or_else(|| jailfile.metadata.name.clone())
.ok_or_else(|| {
Error::InvalidArgument(format!(
"{} has no name; give the build one",
build.file.display()
))
})?;
let context = build
.context
.clone()
.unwrap_or_else(|| context_of(&build.file));
build_root(
self,
&jailfile,
&context,
&name,
build.args.clone(),
BuildMode::Real { verbose: false },
)
}
pub fn commit_image(&self, image: &Image, release: &str) -> Result<Release> {
Error::require_root("committing an image")?;
let layout = self.layout();
let zfs = layout.zfs().ok_or(Error::ZfsNotEnabled)?;
let dataset = zfs.jail_dataset_name(&image.name);
crate::release::commit_dataset(layout, &zfs, &dataset, release)
}
pub fn remove_image(&self, name: &str) -> Result<()> {
Error::require_root("removing an image")?;
crate::manifest::validate_name("jail", name)?;
let layout = self.layout();
let root = layout.config().config.jail_root(name);
if let Some(zfs) = layout.zfs()
&& zfs.jail_dataset_exists(name)?
{
zfs.destroy_dataset_without_dependents(&zfs.jail_dataset_name(name))?;
let _ = std::fs::remove_dir(&root); return Ok(());
}
if root.exists() {
crate::blueprint::context::reject_symlink_ancestors(layout.data_dir(), &root)?;
crate::sys::remove_tree_with_flags(&root)?;
}
Ok(())
}
}
pub fn read_jailfile(path: &Path) -> Result<Jailfile> {
let content = std::fs::read_to_string(path).map_err(|e| {
Error::TemplateParseFailed(format!("Failed to read {}: {}", path.display(), e))
})?;
parse_jailfile(&content)
}
pub fn context_of(file: &Path) -> PathBuf {
match file.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
_ => PathBuf::from("."),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BuildMode {
DryRun,
Real { verbose: bool },
}
pub fn build_root(
host: &Host,
jailfile: &Jailfile,
context_dir: &Path,
name: &str,
build_args: Vec<(String, String)>,
mode: BuildMode,
) -> Result<Image> {
crate::manifest::validate_name("jail", name)?;
let layout = host.layout();
let config = &layout.config().config;
let dry_run = mode == BuildMode::DryRun;
let target_path = config.jail_root(name);
let zfs = layout.zfs();
if !dry_run && let Some(zfs) = &zfs {
zfs.init()?;
}
blueprint::context::reject_symlink_ancestors(&config.data_dir, &target_path)?;
blueprint::context::reject_symlink_target(&target_path)?;
if let Some(release) = &jailfile.from {
crate::manifest::validate_name("release", release)?;
let release_path = config.releases_dir.join(release);
if dry_run {
if !release_path.exists() {
let shown =
std::path::absolute(&release_path).unwrap_or_else(|_| release_path.clone());
println!(
"Would bootstrap base release '{release}' into {} (downloads the base archives)",
shown.display()
);
}
} else {
if !release_path.exists() {
host.bootstrap(&Bootstrap::release(release))?;
}
if let Some(zfs) = &zfs
&& !zfs.jail_dataset_exists(name)?
{
if zfs.release_is_cloneable(release) {
zfs.clone_jail_from_release(release, name)?;
} else {
zfs.create_jail_dataset(name)?;
}
}
if !target_path.join("bin").exists() {
std::fs::create_dir_all(&target_path)?;
copy_release_to(&release_path, &target_path)?;
}
}
}
let layer_cache = zfs.map(|zfs| {
use sha2::Digest;
let mut hasher = sha2::Sha256::new();
hasher.update(jailfile.from.as_deref().unwrap_or("scratch").as_bytes());
let mut sorted_args = build_args.clone();
sorted_args.sort();
for (key, value) in &sorted_args {
hasher.update(key.as_bytes());
hasher.update(value.as_bytes());
}
blueprint::LayerCache {
zfs,
jail: name.to_string(),
seed: hex::encode(hasher.finalize()),
}
});
let verbose = matches!(mode, BuildMode::Real { verbose: true });
let mut ctx = BuildContext::new(context_dir, &target_path, name).verbose(verbose);
for (key, value) in build_args {
ctx.set_arg(&key, &value);
}
TemplateExecutor::new(ctx)
.dry_run(dry_run)
.layer_cache(layer_cache)
.execute(jailfile)?;
Ok(Image {
name: name.to_string(),
root: target_path,
base: jailfile.from.clone(),
})
}
pub fn copy_release_to(release_path: &Path, target: &Path) -> Result<()> {
let status = std::process::Command::new("/bin/cp")
.arg("-a")
.arg(format!("{}/.", release_path.display()))
.arg(target)
.status()
.map_err(|e| Error::BuildFailed {
step: "FROM".to_string(),
message: format!("Failed to copy base release: {e}"),
})?;
if !status.success() {
return Err(Error::BuildFailed {
step: "FROM".to_string(),
message: "cp command failed".to_string(),
});
}
Ok(())
}
#[cfg(test)]
mod tests;