use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use crate::model::NetworkMountProvider;
use crate::paths::NetweftPaths;
use crate::plan::network_mount::{ResolvedNetworkMount, ResolvedNetworkMountPlan};
pub fn render_systemd_mounts(
plan: &ResolvedNetworkMountPlan,
paths: &NetweftPaths,
) -> Result<PathBuf> {
let output = paths
.generated_dir
.join(&plan.location)
.join("hosts")
.join(&plan.host)
.join("systemd-mounts");
let parent = output
.parent()
.context("systemd mount output has no parent")?;
fs::create_dir_all(parent)?;
let temp = parent.join(format!(".systemd-mounts-{}.tmp", std::process::id()));
if temp.exists() {
fs::remove_dir_all(&temp)?;
}
fs::create_dir_all(temp.join("etc/systemd/system"))?;
for mount in &plan.mounts {
write(
&temp.join("etc/systemd/system").join(&mount.unit_name),
&render_mount_unit(mount),
)?;
}
let mut services: BTreeMap<String, Vec<&ResolvedNetworkMount>> = BTreeMap::new();
for mount in &plan.mounts {
for service in &mount.required_by {
services.entry(service.clone()).or_default().push(mount);
}
}
for (service, mounts) in services {
let dir = temp.join("etc/systemd/system").join(format!("{service}.d"));
fs::create_dir_all(&dir)?;
let paths = mounts
.iter()
.map(|mount| mount.mount_path.display().to_string())
.collect::<Vec<_>>()
.join(" ");
let after = mounts
.iter()
.map(|mount| mount.unit_name.clone())
.collect::<Vec<_>>()
.join(" ");
write(
&dir.join("10-netweft-network-mounts.conf"),
&format!(
"# Generated by Netweft. Do not edit.\n[Unit]\nRequiresMountsFor={paths}\nAfter={after}\n"
),
)?;
}
write(&temp.join("apply.sh"), &render_apply(plan))?;
write(&temp.join("manifest.txt"), &render_manifest(plan))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(temp.join("apply.sh"), fs::Permissions::from_mode(0o755))?;
}
if output.exists() {
fs::remove_dir_all(&output)?;
}
fs::rename(&temp, &output)?;
Ok(output)
}
fn render_mount_unit(mount: &ResolvedNetworkMount) -> String {
let fs_type = match mount.provider {
NetworkMountProvider::Nfs => "nfs",
};
format!(
"# Generated by Netweft. Do not edit.\n\
[Unit]\nDescription=Netweft network mount {}\nWants=network-online.target\nAfter=network-online.target\n\n\
[Mount]\nWhat={}:{}\nWhere={}\nType={}\nOptions={}\n\n\
[Install]\nWantedBy=multi-user.target\n",
mount.id,
mount.server_ipv4,
mount.export,
mount.mount_path.display(),
fs_type,
mount.options.join(",")
)
}
fn render_apply(plan: &ResolvedNetworkMountPlan) -> String {
let mut out = String::from("#!/usr/bin/env bash\nset -euo pipefail\n\n");
out.push_str("stage_dir=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\n");
out.push_str("backup_dir=\"/var/backups/netweft/systemd-mounts-$(date +%Y%m%d-%H%M%S)\"\n");
out.push_str("sudo mkdir -p \"$backup_dir\"\n\n");
for mount in &plan.mounts {
out.push_str(&format!(
"if [[ -e /etc/systemd/system/{0} ]]; then sudo cp -a /etc/systemd/system/{0} \"$backup_dir/\"; fi\n",
mount.unit_name
));
out.push_str(&format!(
"sudo install -D -m 0644 \"$stage_dir/etc/systemd/system/{0}\" /etc/systemd/system/{0}\n",
mount.unit_name
));
}
let mut services = BTreeMap::<String, ()>::new();
for mount in &plan.mounts {
for service in &mount.required_by {
services.insert(service.clone(), ());
}
}
for service in services.keys() {
out.push_str(&format!(
"if [[ -d /etc/systemd/system/{0}.d ]]; then sudo cp -a /etc/systemd/system/{0}.d \"$backup_dir/\"; fi\n",
service
));
out.push_str(&format!(
"sudo install -D -m 0644 \"$stage_dir/etc/systemd/system/{0}.d/10-netweft-network-mounts.conf\" /etc/systemd/system/{0}.d/10-netweft-network-mounts.conf\n",
service
));
}
out.push_str("\nsudo systemctl daemon-reload\n");
for mount in &plan.mounts {
out.push_str(&format!(
"sudo systemctl enable --now {}\n",
mount.unit_name
));
out.push_str(&format!(
"findmnt {} >/dev/null\n",
shell_quote(&mount.mount_path.display().to_string())
));
}
for service in services.keys() {
out.push_str(&format!(
"sudo systemctl restart {}\nsystemctl is-active --quiet {}\n",
service, service
));
}
out.push_str("echo \"Applied Netweft network mounts. Backup: $backup_dir\"\n");
out
}
fn render_manifest(plan: &ResolvedNetworkMountPlan) -> String {
let mut out = format!(
"adapter=systemd-mounts\nlocation={}\nhost={}\n",
plan.location, plan.host
);
for mount in &plan.mounts {
out.push_str(&format!(
"mount={} source={}:{} target={} unit={} required_by={}\n",
mount.id,
mount.server_ipv4,
mount.export,
mount.mount_path.display(),
mount.unit_name,
mount.required_by.join(",")
));
}
out
}
fn shell_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
fn write(path: &Path, contents: &str) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, contents).with_context(|| format!("failed to write {}", path.display()))
}