use crate::error::{Error, Result};
use crate::sickbay::checker::HealthCheckConfig;
use crate::hooks::Hook;
use serde::Deserialize;
use std::collections::HashMap;
use std::fs;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
pub fn load(path: &Path) -> Result<BlackshipConfig> {
let content = fs::read_to_string(path).map_err(|e| Error::ConfigRead {
path: path.to_path_buf(),
source: e,
})?;
let mut config: BlackshipConfig = toml::from_str(&content)?;
if config.config.project.is_none() {
let project_name = 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(|s| s.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));
config.config.project = Some(project_name);
}
config.validate()?;
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 = fs::read_to_string(path).map_err(|e| Error::ConfigRead {
path: path.to_path_buf(),
source: e,
})?;
let config: BlackshipConfig = toml::from_str(&content)?;
base = Some(match base {
None => config,
Some(b) => b.merge(config),
});
}
let mut config = base.unwrap();
if config.config.project.is_none() {
let project_name = first_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(|s| s.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(first_path));
config.config.project = Some(project_name);
}
config.validate()?;
Ok(config)
}
#[derive(Debug, Deserialize)]
pub struct BlackshipConfig {
pub config: GlobalConfig,
#[serde(default)]
#[allow(dead_code)]
pub networks: Vec<NetworkConfig>,
#[serde(default)]
pub jails: Vec<JailDef>,
}
impl BlackshipConfig {
pub fn validate(&self) -> Result<()> {
let mut names = std::collections::HashSet::new();
for jail in &self.jails {
if !names.insert(&jail.name) {
return Err(Error::ConfigValidation(format!(
"Duplicate jail name: {}",
jail.name
)));
}
}
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
)));
}
}
if self.config.zfs_enabled && self.config.zpool.is_none() {
return Err(Error::ConfigValidation(
"ZFS is enabled but no zpool specified".into(),
));
}
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.jail_name(&j.name) == name)
}
pub fn resolve_jail_names(&self, name: &str) -> Option<(String, String)> {
if let Some(jail) = self.jails.iter().find(|j| j.name == name) {
let full = self.jail_name(&jail.name);
return Some((jail.name.clone(), full));
}
if let Some(jail) = self
.jails
.iter()
.find(|j| self.jail_name(&j.name) == name)
{
let full = self.jail_name(&jail.name);
return Some((jail.name.clone(), full));
}
None
}
pub fn jail_name(&self, service_name: &str) -> String {
let project = self.config.project_name();
let prefix = format!("{}-", project);
if service_name.starts_with(&prefix) {
service_name.to_string()
} else {
format!("{}-{}", project, service_name)
}
}
#[allow(dead_code)]
pub fn project_name(&self) -> String {
self.config.project_name()
}
pub fn merge(mut self, other: BlackshipConfig) -> BlackshipConfig {
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, Deserialize)]
pub struct GlobalConfig {
pub project: Option<String>,
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,
#[serde(default = "default_bootstrap_archives")]
pub bootstrap_archives: Vec<String>,
#[serde(default)]
pub rate_limit: RateLimitConfig,
#[serde(default)]
#[allow(dead_code)] pub health: HealthDefaults,
#[serde(default)]
pub retry: RetryConfig,
pub bridge: Option<BridgeVlanConfig>,
}
impl GlobalConfig {
pub fn project_name(&self) -> String {
self.project.clone().unwrap_or_else(|| "blackship".to_string())
}
fn merge(self, other: GlobalConfig) -> GlobalConfig {
GlobalConfig {
project: other.project.or(self.project),
data_dir: other.data_dir, zfs_enabled: other.zfs_enabled,
zpool: other.zpool.or(self.zpool),
dataset: if other.dataset != default_dataset() { other.dataset } else { self.dataset },
releases_dir: if other.releases_dir != default_releases_dir() { other.releases_dir } else { self.releases_dir },
cache_dir: if other.cache_dir != default_cache_dir() { other.cache_dir } else { self.cache_dir },
mirror_url: if other.mirror_url != default_mirror_url() { other.mirror_url } else { self.mirror_url },
bootstrap_archives: if other.bootstrap_archives != default_bootstrap_archives() { other.bootstrap_archives } else { self.bootstrap_archives },
rate_limit: other.rate_limit, health: other.health, retry: other.retry, bridge: other.bridge.or(self.bridge), }
}
}
fn default_dataset() -> String {
"blackship".into()
}
fn default_releases_dir() -> PathBuf {
PathBuf::from("/var/blackship/releases")
}
fn default_cache_dir() -> PathBuf {
PathBuf::from("/var/blackship/cache")
}
fn default_mirror_url() -> String {
"https://download.freebsd.org/releases".into()
}
fn default_bootstrap_archives() -> Vec<String> {
vec!["base".into()]
}
fn default_jail_start_capacity() -> f64 {
3.0
}
fn default_health_capacity() -> f64 {
5.0
}
fn default_health_refill_rate() -> f64 {
0.5
}
#[derive(Debug, Clone, Deserialize)]
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(),
}
}
}
fn default_health_interval() -> u64 {
30
}
fn default_health_timeout() -> u64 {
10
}
fn default_health_start_period() -> u64 {
60
}
fn default_health_retries() -> u32 {
3
}
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)] 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(),
}
}
}
fn default_base_delay_ms() -> u64 {
1000
}
fn default_max_delay_ms() -> u64 {
30000
}
fn default_multiplier() -> f64 {
2.0
}
fn default_max_attempts() -> u8 {
5
}
fn default_jitter_factor() -> f64 {
0.25
}
#[derive(Debug, Clone, Deserialize)]
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, Deserialize)]
#[allow(dead_code)] pub struct NetworkConfig {
pub name: String,
pub subnet: String,
pub gateway: Option<IpAddr>,
}
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)] pub struct BridgeVlanConfig {
pub name: String,
#[serde(default)]
pub vlan_filtering: bool,
pub trunk: Option<TrunkConfig>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct TrunkConfig {
pub interface: String,
#[serde(default)]
pub tagged: Vec<u16>,
#[serde(default)]
pub disable_hwfilter: bool,
}
#[derive(Debug, Clone, Deserialize)]
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>,
#[allow(dead_code)]
pub mount: Option<JailMountConfig>,
#[serde(default)]
pub hooks: Vec<Hook>,
#[serde(default)]
pub healthcheck: HealthCheckConfig,
}
impl JailDef {
pub fn effective_path(&self, global: &GlobalConfig, full_name: &str) -> PathBuf {
if let Some(path) = &self.path {
path.clone()
} else if global.zfs_enabled {
PathBuf::from(format!(
"/{}/{}/jails/{}",
global.zpool.as_deref().unwrap_or("zroot"),
global.dataset,
full_name
))
} else {
global.data_dir.join("jails").join(full_name)
}
}
pub fn merge(self, other: JailDef) -> JailDef {
JailDef {
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
},
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct JailNetworkConfig {
#[serde(default)]
pub vnet: 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>,
#[serde(default)]
pub dns: DnsConfig,
}
#[derive(Debug, Clone, Default, Deserialize)]
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 {
content.push_str(&format!("domain {}\n", domain));
}
if !self.search.is_empty() {
content.push_str(&format!("search {}\n", self.search.join(" ")));
}
for ns in &self.nameservers {
content.push_str(&format!("nameserver {}\n", ns));
}
Some(content)
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct JailMountConfig {
#[serde(default)]
#[allow(dead_code)]
pub volumes: Vec<String>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_minimal_config() {
let toml = r#"
[config]
data_dir = "/var/blackship"
[[jails]]
name = "test"
path = "/jails/test"
"#;
let config: BlackshipConfig = toml::from_str(toml).unwrap();
assert_eq!(config.jails.len(), 1);
assert_eq!(config.jails[0].name, "test");
}
#[test]
fn test_parse_full_config() {
let toml = r#"
[config]
data_dir = "/var/blackship"
zfs_enabled = true
zpool = "zroot"
[[networks]]
name = "backend"
subnet = "10.0.1.0/24"
gateway = "10.0.1.1"
[[jails]]
name = "postgres"
path = "/jails/postgres"
hostname = "db.local"
[jails.params]
"allow.raw_sockets" = true
"exec.start" = "/bin/sh /etc/rc"
[jails.network]
networks = ["backend"]
ip = "10.0.1.10"
[[jails]]
name = "webapp"
path = "/jails/webapp"
depends_on = ["postgres"]
"#;
let config: BlackshipConfig = toml::from_str(toml).unwrap();
assert_eq!(config.jails.len(), 2);
assert_eq!(config.jails[1].depends_on, vec!["postgres"]);
assert!(config.validate().is_ok());
}
#[test]
fn test_duplicate_name_error() {
let toml = r#"
[config]
data_dir = "/var/blackship"
[[jails]]
name = "test"
path = "/jails/test"
[[jails]]
name = "test"
path = "/jails/test2"
"#;
let config: BlackshipConfig = toml::from_str(toml).unwrap();
assert!(config.validate().is_err());
}
#[test]
fn test_unknown_dependency_error() {
let toml = r#"
[config]
data_dir = "/var/blackship"
[[jails]]
name = "webapp"
path = "/jails/webapp"
depends_on = ["nonexistent"]
"#;
let config: BlackshipConfig = toml::from_str(toml).unwrap();
assert!(config.validate().is_err());
}
}