use crate::error::{Error, Result};
use crate::hooks::Hook;
use crate::sickbay::checker::HealthCheckConfig;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::Write as _;
use std::fs;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
pub fn validate_name(kind: &str, name: &str) -> Result<()> {
if name.is_empty() {
return Err(Error::ConfigValidation(format!(
"{kind} name cannot be empty"
)));
}
if name.contains('/') || name.contains('\0') || name == "." || name == ".." {
return Err(Error::ConfigValidation(format!(
"{kind} name '{name}' contains invalid characters"
)));
}
if !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
{
return Err(Error::ConfigValidation(format!(
"{kind} name '{name}' contains invalid characters (only alphanumeric, dash, underscore, dot allowed)"
)));
}
Ok(())
}
pub fn data_root(config: Option<&BlackshipConfig>) -> PathBuf {
config.map_or_else(
|| PathBuf::from("/var/blackship"),
|cfg| cfg.config.data_dir.clone(),
)
}
pub fn validate_record_name(kind: &str, name: &str) -> Result<()> {
if name.is_empty() {
return Err(Error::InvalidArgument(format!(
"{kind} name cannot be empty"
)));
}
if name.contains('/') || name.contains('\\') || name.contains("..") {
return Err(Error::InvalidArgument(format!(
"{kind} name '{name}' contains invalid characters"
)));
}
Ok(())
}
fn validate_zfs_component(kind: &str, name: &str) -> Result<()> {
if name.is_empty() {
return Err(Error::ConfigValidation(format!(
"{kind} name cannot be empty"
)));
}
if name.starts_with('-') {
return Err(Error::ConfigValidation(format!(
"{kind} name '{name}' must not start with '-'"
)));
}
if name == "." || name == ".." || name.contains("..") {
return Err(Error::ConfigValidation(format!(
"{kind} name '{name}' contains invalid component"
)));
}
if name.contains('@') || name.contains('\0') {
return Err(Error::ConfigValidation(format!(
"{kind} name '{name}' contains invalid characters"
)));
}
if !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ':' | '/'))
{
return Err(Error::ConfigValidation(format!(
"{kind} name '{name}' contains invalid characters"
)));
}
Ok(())
}
pub fn read_config_file(path: &Path) -> Result<String> {
fs::read_to_string(path).map_err(|e| Error::ConfigRead {
path: path.to_path_buf(),
source: e,
})
}
fn project_name_from_path(path: &Path) -> String {
path.parent()
.filter(|p| !p.as_os_str().is_empty() && p.as_os_str() != ".")
.and_then(|p| p.file_name())
.and_then(|n| n.to_str())
.map(std::string::ToString::to_string)
.or_else(|| {
std::env::current_dir()
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
})
.unwrap_or_else(|| black_ship_name_from_path(path))
}
pub fn load(path: &Path) -> Result<BlackshipConfig> {
let content = read_config_file(path)?;
let mut config: BlackshipConfig = toml::from_str(&content)?;
if config.config.project.is_none() {
config.config.project = Some(project_name_from_path(path));
}
config.validate()?;
Ok(config)
}
pub fn load_or_default(path: &Path) -> Result<BlackshipConfig> {
if path.exists() {
load(path)
} else {
let mut config: BlackshipConfig = toml::from_str("[config]\n")?;
config.config.project = Some(project_name_from_path(path));
Ok(config)
}
}
pub fn load_merged(paths: &[PathBuf]) -> Result<BlackshipConfig> {
if paths.is_empty() {
return Err(Error::ConfigValidation(
"No configuration files provided".into(),
));
}
let mut base: Option<BlackshipConfig> = None;
let first_path = &paths[0];
for path in paths {
let content = read_config_file(path)?;
let config: BlackshipConfig = toml::from_str(&content)?;
base = Some(match base {
None => config,
Some(b) => b.merge(config),
});
}
let mut config = base.expect("paths is non-empty, checked above");
if config.config.project.is_none() {
config.config.project = Some(project_name_from_path(first_path));
}
config.validate()?;
Ok(config)
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BlackshipConfig {
pub config: GlobalConfig,
#[serde(default)]
pub networks: Vec<NetworkConfig>,
#[serde(default)]
pub jails: Vec<JailDef>,
pub telemetry: Option<crate::telemetry::TelemetryConfig>,
}
impl BlackshipConfig {
pub fn validate(&self) -> Result<()> {
validate_name("project", self.config.project_name())?;
let mut names = std::collections::HashSet::new();
let mut full_names = std::collections::HashSet::new();
for jail in &self.jails {
validate_name("jail", &jail.name)?;
if !names.insert(&jail.name) {
return Err(Error::ConfigValidation(format!(
"Duplicate jail name: {}",
jail.name
)));
}
let full = self.jail_name(&jail.name);
if full_names.contains(&full) {
return Err(Error::ConfigValidation(format!(
"Jail '{}' resolves to full name '{}' which collides with another jail",
jail.name, full
)));
}
full_names.insert(full);
}
for jail in &self.jails {
for dep in &jail.depends_on {
if !names.contains(dep) {
return Err(Error::UnknownDependency(dep.clone()));
}
}
}
for jail in &self.jails {
if jail.depends_on.contains(&jail.name) {
return Err(Error::ConfigValidation(format!(
"Jail '{}' depends on itself",
jail.name
)));
}
}
for net in &self.networks {
validate_name("network", &net.name)?;
}
for jail in &self.jails {
if let Some(release) = &jail.release {
validate_name("release", release)?;
}
if let Some(net) = &jail.network {
if let Some(bridge) = &net.bridge {
validate_name("bridge", bridge)?;
}
for net_ref in &net.networks {
validate_name("network reference", net_ref)?;
}
}
}
if self.config.zfs_enabled {
if self.config.zpool.is_none() {
return Err(Error::ConfigValidation(
"ZFS is enabled but no zpool specified".into(),
));
}
if let Some(pool) = &self.config.zpool {
validate_zfs_component("zpool", pool)?;
}
validate_zfs_component("dataset", &self.config.dataset)?;
}
Ok(())
}
pub fn get_jail(&self, name: &str) -> Option<&JailDef> {
if let Some(jail) = self.jails.iter().find(|j| j.name == name) {
return Some(jail);
}
self.jails
.iter()
.find(|j| self.full_name_matches(&j.name, name))
}
pub fn require_jail_names(&self, name: &str) -> Result<(String, String)> {
self.resolve_jail_names(name)
.ok_or_else(|| Error::JailNotFound(name.to_string()))
}
pub fn resolve_jail_names(&self, name: &str) -> Option<(String, String)> {
let names_of = |jail: &JailDef| (jail.name.clone(), self.jail_name(&jail.name));
if let Some(jail) = self.jails.iter().find(|j| j.name == name) {
return Some(names_of(jail));
}
if let Some(jail) = self
.jails
.iter()
.find(|j| self.full_name_matches(&j.name, name))
{
return Some(names_of(jail));
}
let mut matches = self
.jails
.iter()
.filter(|j| j.name.starts_with(name) || self.full_name_starts_with(&j.name, name));
let first = matches.next()?;
if matches.next().is_none() {
return Some(names_of(first));
}
None
}
fn full_name_matches(&self, service_name: &str, candidate: &str) -> bool {
if self.is_prefixed(service_name) {
return service_name == candidate;
}
match candidate.strip_prefix(self.config.project_name()) {
Some(rest) => rest.strip_prefix('-') == Some(service_name),
None => false,
}
}
fn full_name_starts_with(&self, service_name: &str, prefix: &str) -> bool {
if self.is_prefixed(service_name) {
return service_name.starts_with(prefix);
}
let project = self.config.project_name();
match prefix.len().cmp(&project.len()) {
std::cmp::Ordering::Less | std::cmp::Ordering::Equal => project.starts_with(prefix),
std::cmp::Ordering::Greater => match prefix.strip_prefix(project) {
Some(rest) => match rest.strip_prefix('-') {
Some(tail) => service_name.starts_with(tail),
None => false,
},
None => false,
},
}
}
fn is_prefixed(&self, service_name: &str) -> bool {
service_name
.strip_prefix(self.config.project_name())
.is_some_and(|rest| rest.starts_with('-'))
}
pub fn jail_name(&self, service_name: &str) -> String {
if self.is_prefixed(service_name) {
service_name.to_string()
} else {
format!("{}-{}", self.config.project_name(), service_name)
}
}
pub fn merge(mut self, other: Self) -> Self {
self.config = self.config.merge(other.config);
for net in other.networks {
if let Some(existing) = self.networks.iter_mut().find(|n| n.name == net.name) {
*existing = net;
} else {
self.networks.push(net);
}
}
for jail in other.jails {
if let Some(existing) = self.jails.iter_mut().find(|j| j.name == jail.name) {
*existing = existing.clone().merge(jail);
} else {
self.jails.push(jail);
}
}
self
}
}
const BLACK_SHIP_NAMES: &[&str] = &[
"aegis_of_truth",
"aeria_gloris",
"enduring_abundance",
"honour_haltis",
"lamentation",
"norns_ghost",
"psythanatos",
"validus",
"white_sun",
];
pub fn black_ship_name(seed: usize) -> String {
BLACK_SHIP_NAMES[seed % BLACK_SHIP_NAMES.len()].to_string()
}
pub fn black_ship_name_from_path(path: &Path) -> String {
let hash = path.to_string_lossy().bytes().fold(0usize, |acc, b| {
acc.wrapping_add(b as usize).wrapping_mul(31)
});
black_ship_name(hash)
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GlobalConfig {
pub project: Option<String>,
#[serde(default = "default_data_dir")]
pub data_dir: PathBuf,
#[serde(default)]
pub zfs_enabled: bool,
pub zpool: Option<String>,
#[serde(default = "default_dataset")]
pub dataset: String,
#[serde(default = "default_releases_dir")]
pub releases_dir: PathBuf,
#[serde(default = "default_cache_dir")]
pub cache_dir: PathBuf,
#[serde(default = "default_mirror_url")]
pub mirror_url: String,
pub monitor_ping_url: Option<String>,
#[serde(default = "default_bootstrap_archives")]
pub bootstrap_archives: Vec<String>,
#[serde(default)]
pub rate_limit: RateLimitConfig,
#[serde(default)]
pub health: HealthDefaults,
#[serde(default)]
pub retry: RetryConfig,
pub bridge: Option<BridgeVlanConfig>,
pub usage_sample_secs: Option<u64>,
}
impl GlobalConfig {
pub fn jails_dir(&self) -> PathBuf {
self.data_dir.join("jails")
}
pub fn jail_root(&self, full_name: &str) -> PathBuf {
self.jails_dir().join(full_name)
}
pub fn project_name(&self) -> &str {
self.project.as_deref().unwrap_or("blackship")
}
fn merge(self, other: Self) -> Self {
Self {
project: other.project.or(self.project),
data_dir: if other.data_dir == default_data_dir() {
self.data_dir
} else {
other.data_dir
},
zfs_enabled: other.zfs_enabled,
monitor_ping_url: other.monitor_ping_url.or(self.monitor_ping_url),
zpool: other.zpool.or(self.zpool),
dataset: if other.dataset == default_dataset() {
self.dataset
} else {
other.dataset
},
releases_dir: if other.releases_dir == default_releases_dir() {
self.releases_dir
} else {
other.releases_dir
},
cache_dir: if other.cache_dir == default_cache_dir() {
self.cache_dir
} else {
other.cache_dir
},
mirror_url: if other.mirror_url == default_mirror_url() {
self.mirror_url
} else {
other.mirror_url
},
bootstrap_archives: if other.bootstrap_archives == default_bootstrap_archives() {
self.bootstrap_archives
} else {
other.bootstrap_archives
},
rate_limit: other.rate_limit, health: other.health, retry: other.retry, bridge: other.bridge.or(self.bridge), usage_sample_secs: other.usage_sample_secs.or(self.usage_sample_secs),
}
}
}
impl Default for GlobalConfig {
fn default() -> Self {
Self {
project: None,
data_dir: default_data_dir(),
zfs_enabled: false,
zpool: None,
dataset: default_dataset(),
releases_dir: default_releases_dir(),
cache_dir: default_cache_dir(),
mirror_url: default_mirror_url(),
monitor_ping_url: None,
bootstrap_archives: default_bootstrap_archives(),
rate_limit: RateLimitConfig::default(),
health: HealthDefaults::default(),
retry: RetryConfig::default(),
bridge: None,
usage_sample_secs: None,
}
}
}
impl Default for BlackshipConfig {
fn default() -> Self {
Self {
config: GlobalConfig::default(),
networks: Vec::new(),
jails: Vec::new(),
telemetry: None,
}
}
}
fn default_dataset() -> String {
"blackship".into()
}
fn get_home_dir() -> PathBuf {
std::env::var("HOME").map_or_else(|_| PathBuf::from("/root"), PathBuf::from)
}
pub fn get_xdg_data_dir() -> PathBuf {
std::env::var("XDG_DATA_HOME")
.map_or_else(|_| get_home_dir().join(".local/share"), PathBuf::from)
.join("blackship")
}
pub fn get_xdg_cache_dir() -> PathBuf {
std::env::var("XDG_CACHE_HOME")
.map_or_else(|_| get_home_dir().join(".cache"), PathBuf::from)
.join("blackship")
}
pub fn default_data_dir() -> PathBuf {
get_xdg_data_dir()
}
fn default_releases_dir() -> PathBuf {
get_xdg_data_dir().join("releases")
}
fn default_cache_dir() -> PathBuf {
get_xdg_cache_dir()
}
fn default_mirror_url() -> String {
"https://download.freebsd.org/releases".into()
}
fn default_bootstrap_archives() -> Vec<String> {
vec!["base".into()]
}
const fn default_jail_start_capacity() -> f64 {
3.0
}
const fn default_health_capacity() -> f64 {
5.0
}
const fn default_health_refill_rate() -> f64 {
0.5
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RateLimitConfig {
#[serde(default = "default_jail_start_capacity")]
pub jail_start_capacity: f64,
#[serde(default = "default_health_capacity")]
pub health_capacity: f64,
#[serde(default = "default_health_refill_rate")]
pub health_refill_rate: f64,
}
impl Default for RateLimitConfig {
fn default() -> Self {
Self {
jail_start_capacity: default_jail_start_capacity(),
health_capacity: default_health_capacity(),
health_refill_rate: default_health_refill_rate(),
}
}
}
const fn default_health_interval() -> u64 {
30
}
const fn default_health_timeout() -> u64 {
10
}
const fn default_health_start_period() -> u64 {
60
}
const fn default_health_retries() -> u32 {
3
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HealthDefaults {
#[serde(default = "default_health_interval")]
pub interval: u64,
#[serde(default = "default_health_timeout")]
pub timeout: u64,
#[serde(default = "default_health_start_period")]
pub start_period: u64,
#[serde(default = "default_health_retries")]
pub retries: u32,
}
impl Default for HealthDefaults {
fn default() -> Self {
Self {
interval: default_health_interval(),
timeout: default_health_timeout(),
start_period: default_health_start_period(),
retries: default_health_retries(),
}
}
}
const fn default_base_delay_ms() -> u64 {
1000
}
const fn default_max_delay_ms() -> u64 {
30000
}
const fn default_multiplier() -> f64 {
2.0
}
const fn default_max_attempts() -> u8 {
5
}
const fn default_jitter_factor() -> f64 {
0.25
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RetryConfig {
#[serde(default = "default_base_delay_ms")]
pub base_delay_ms: u64,
#[serde(default = "default_max_delay_ms")]
pub max_delay_ms: u64,
#[serde(default = "default_multiplier")]
pub multiplier: f64,
#[serde(default = "default_max_attempts")]
pub max_attempts: u8,
#[serde(default = "default_jitter_factor")]
pub jitter_factor: f64,
}
impl Default for RetryConfig {
fn default() -> Self {
Self {
base_delay_ms: default_base_delay_ms(),
max_delay_ms: default_max_delay_ms(),
multiplier: default_multiplier(),
max_attempts: default_max_attempts(),
jitter_factor: default_jitter_factor(),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NetworkConfig {
pub name: String,
pub subnet: String,
pub gateway: Option<IpAddr>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BridgeVlanConfig {
pub name: String,
#[serde(default)]
pub vlan_filtering: bool,
pub trunk: Option<TrunkConfig>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TrunkConfig {
pub interface: String,
#[serde(default)]
pub tagged: Vec<u16>,
#[serde(default)]
pub disable_hwfilter: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JailDef {
pub name: String,
pub path: Option<PathBuf>,
pub release: Option<String>,
pub build: Option<PathBuf>,
pub jailfile: Option<PathBuf>,
pub hostname: Option<String>,
#[serde(default)]
pub depends_on: Vec<String>,
#[serde(default)]
pub params: HashMap<String, toml::Value>,
pub network: Option<JailNetworkConfig>,
pub mount: Option<JailMountConfig>,
#[serde(default)]
pub hooks: Vec<Hook>,
#[serde(default)]
pub healthcheck: HealthCheckConfig,
#[serde(default)]
pub resources: crate::rctl::ResourceConfig,
pub qos: Option<crate::rctl::QosConfig>,
pub drain: Option<DrainConfig>,
#[serde(default)]
pub cascade: crate::scope::CascadePolicy,
pub ephemeral: Option<bool>,
pub devfs_ruleset: Option<u32>,
pub init: Option<bool>,
pub stop: Option<String>,
#[serde(default)]
pub tags: Vec<String>,
}
impl JailDef {
pub fn effective_path(&self, global: &GlobalConfig, full_name: &str) -> PathBuf {
if let Some(path) = &self.path {
path.clone()
} else {
global.jail_root(full_name)
}
}
pub const fn startup_resources(&self) -> &crate::rctl::ResourceConfig {
match &self.qos {
Some(qos) => &qos.startup,
None => &self.resources,
}
}
pub fn resolve_stop(&self) -> Option<String> {
if let Some(stop) = &self.stop {
return Some(stop.clone());
}
let path = self.jailfile_path()?;
let content = std::fs::read_to_string(path).ok()?;
crate::blueprint::parser::parse_jailfile(&content)
.ok()?
.stop
}
pub fn jailfile_path(&self) -> Option<PathBuf> {
if let Some(explicit) = &self.jailfile
&& explicit.exists()
{
return Some(explicit.clone());
}
let candidate = self.build.as_ref()?.join("Jailfile");
candidate.exists().then_some(candidate)
}
pub fn merge(self, other: Self) -> Self {
Self {
name: other.name, path: other.path.or(self.path),
release: other.release.or(self.release),
build: other.build.or(self.build),
jailfile: other.jailfile.or(self.jailfile),
hostname: other.hostname.or(self.hostname),
depends_on: if other.depends_on.is_empty() {
self.depends_on
} else {
other.depends_on
},
params: {
let mut merged = self.params;
merged.extend(other.params);
merged
},
network: other.network.or(self.network),
mount: other.mount.or(self.mount),
hooks: if other.hooks.is_empty() {
self.hooks
} else {
other.hooks
},
healthcheck: if other.healthcheck.enabled || !other.healthcheck.checks.is_empty() {
other.healthcheck
} else {
self.healthcheck
},
resources: if other.resources.is_empty() {
self.resources
} else {
other.resources
},
qos: other.qos.or(self.qos),
drain: other.drain.or(self.drain),
cascade: if other.cascade == crate::scope::CascadePolicy::default() {
self.cascade
} else {
other.cascade
},
ephemeral: other.ephemeral.or(self.ephemeral),
devfs_ruleset: other.devfs_ruleset.or(self.devfs_ruleset),
init: other.init.or(self.init),
stop: other.stop.or(self.stop),
tags: if other.tags.is_empty() {
self.tags
} else {
other.tags
},
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DrainConfig {
#[serde(default = "default_true")]
pub enabled: bool,
#[serde(default = "default_drain_timeout")]
pub timeout_secs: u64,
}
impl Default for DrainConfig {
fn default() -> Self {
Self {
enabled: true,
timeout_secs: default_drain_timeout(),
}
}
}
const fn default_true() -> bool {
true
}
const fn default_drain_timeout() -> u64 {
30
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JailNetworkConfig {
#[serde(default)]
pub vnet: bool,
#[serde(default)]
pub shared: bool,
pub bridge: Option<String>,
#[serde(default)]
pub networks: Vec<String>,
pub ip: Option<IpAddr>,
pub ip_cidr: Option<String>,
pub gateway: Option<IpAddr>,
pub mac_address: Option<String>,
pub vlan_id: Option<u16>,
pub backend: Option<crate::network::vnet::NetworkBackend>,
#[serde(default)]
pub dns: DnsConfig,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct DnsConfig {
#[serde(default)]
pub nameservers: Vec<String>,
#[serde(default)]
pub search: Vec<String>,
pub domain: Option<String>,
#[serde(default = "default_dns_mode")]
pub mode: String,
}
fn default_dns_mode() -> String {
"inherit".to_string()
}
impl DnsConfig {
pub fn is_inherit(&self) -> bool {
self.mode == "inherit" || (self.mode != "custom" && self.nameservers.is_empty())
}
pub fn to_resolv_conf(&self) -> Option<String> {
if self.is_inherit() {
return None; }
let mut content = String::new();
if let Some(domain) = &self.domain {
let _ = writeln!(content, "domain {domain}"); }
if !self.search.is_empty() {
content.push_str("search ");
for (i, term) in self.search.iter().enumerate() {
if i > 0 {
content.push(' ');
}
content.push_str(term);
}
content.push('\n');
}
for ns in &self.nameservers {
let _ = writeln!(content, "nameserver {ns}"); }
Some(content)
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JailMountConfig {
#[serde(default)]
pub volumes: Vec<String>,
}
#[cfg(test)]
mod tests;