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 config: BlackshipConfig = toml::from_str(&content)?;
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> {
self.jails.iter().find(|j| j.name == name)
}
}
#[derive(Debug, Deserialize)]
pub struct GlobalConfig {
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,
}
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)]
pub struct JailDef {
pub name: String,
pub path: Option<PathBuf>,
pub release: Option<String>,
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) -> 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,
self.name
))
} else {
global.data_dir.join("jails").join(&self.name)
}
}
}
#[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>,
#[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());
}
}