#[cfg(test)]
pub fn configure_container_dns(
rootfs: &std::path::Path,
) -> boxlite_shared::errors::BoxliteResult<()> {
use boxlite_shared::errors::BoxliteError;
use std::fs;
tracing::debug!("Configuring DNS for container at {:?}", rootfs);
let etc_dir = rootfs.join("etc");
fs::create_dir_all(&etc_dir).map_err(|e| {
BoxliteError::Storage(format!("Failed to create /etc directory in rootfs: {}", e))
})?;
let resolv_conf = etc_dir.join("resolv.conf");
let content = format!(
"# Generated by BoxLite\n# DNS queries forwarded to gateway\nnameserver {}\nsearch localdomain\n",
crate::net::constants::DNS_SERVER_IP
);
fs::write(&resolv_conf, content)
.map_err(|e| BoxliteError::Storage(format!("Failed to write /etc/resolv.conf: {}", e)))?;
tracing::info!("Created /etc/resolv.conf in container rootfs");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
#[test]
fn test_configure_dns_creates_file() {
let tmp = TempDir::new().unwrap();
let rootfs = tmp.path();
configure_container_dns(rootfs).unwrap();
let resolv_conf = rootfs.join("etc/resolv.conf");
assert!(resolv_conf.exists());
}
#[test]
fn test_configure_dns_content() {
let tmp = TempDir::new().unwrap();
let rootfs = tmp.path();
configure_container_dns(rootfs).unwrap();
let content = fs::read_to_string(rootfs.join("etc/resolv.conf")).unwrap();
assert!(content.contains(&format!(
"nameserver {}",
crate::net::constants::DNS_SERVER_IP
)));
assert!(content.contains("search localdomain"));
assert!(content.contains("Generated by BoxLite"));
}
#[test]
fn test_configure_dns_creates_etc_dir() {
let tmp = TempDir::new().unwrap();
let rootfs = tmp.path();
assert!(!rootfs.join("etc").exists());
configure_container_dns(rootfs).unwrap();
assert!(rootfs.join("etc").exists());
assert!(rootfs.join("etc").is_dir());
}
#[test]
fn test_configure_dns_idempotent() {
let tmp = TempDir::new().unwrap();
let rootfs = tmp.path();
configure_container_dns(rootfs).unwrap();
configure_container_dns(rootfs).unwrap();
let content = fs::read_to_string(rootfs.join("etc/resolv.conf")).unwrap();
assert!(content.contains(&format!(
"nameserver {}",
crate::net::constants::DNS_SERVER_IP
)));
}
}