pub mod render;
use std::io::{IsTerminal, Write};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
pub use render::{Catalog, Resources, Secrets, SslMode, Storage, UrlStyle};
use crate::{Error, token};
pub const USER: &str = "hazine";
pub const HOME: &str = "/var/lib/hazine";
pub const ETC: &str = "/etc/hazine";
pub const HAZINE_BIN: &str = "/usr/local/bin/hazine";
pub const DUCKDB_BIN: &str = "/usr/local/bin/duckdb";
pub const UNIT: &str = "/etc/systemd/system/hazine.service";
const EXTENSIONS: &str = "INSTALL quack; INSTALL ducklake; INSTALL postgres; INSTALL httpfs;";
#[derive(Debug, Clone)]
pub struct Options {
pub catalog: Catalog,
pub storage: Storage,
pub pg_password: Option<String>,
pub s3_key_id: Option<String>,
pub s3_secret: Option<String>,
pub duckdb_version: String,
pub quack_addr: SocketAddr,
pub threads: Option<usize>,
pub memory_limit: Option<String>,
pub memory_max: Option<String>,
pub start: bool,
pub dry_run: bool,
}
pub fn run(options: Options) -> Result<(), Error> {
if !options.quack_addr.ip().is_loopback() {
return Err(Error::NotLoopback {
addr: options.quack_addr,
});
}
if !options.dry_run {
if !cfg!(target_os = "linux") {
return Err(Error::Unsupported("hazine setup needs Linux with systemd"));
}
if effective_uid()? != 0 {
return Err(Error::NotRoot);
}
}
let resources = resources(&options)?;
let env_path = Path::new(ETC).join("hazine.env");
let secrets = secrets(&options, &env_path)?;
let init_sql = render::init_sql(&options.storage, &resources);
let env_file = render::env_file(&secrets, &options.catalog, options.quack_addr)?;
let unit_file = render::unit_file(&resources);
if options.dry_run {
let redacted = render::env_file(
&Secrets {
quack_token: "[REDACTED]".into(),
pg_password: "[REDACTED]".into(),
s3_key_id: "[REDACTED]".into(),
s3_secret: "[REDACTED]".into(),
},
&options.catalog,
options.quack_addr,
)?;
print_plan(
&options,
&[
(Path::new(ETC).join("init.sql"), init_sql),
(env_path, redacted),
(PathBuf::from(UNIT), unit_file),
],
);
return Ok(());
}
let mut changed = install_self()?;
changed |= install_duckdb(&options.duckdb_version)?;
let account = ensure_account()?;
install_extensions(&account)?;
check_lake(&account, &options.storage, &env_file)?;
ensure_dir(Path::new(ETC), 0o750, 0, account.gid)?;
changed |= write_file(
&Path::new(ETC).join("init.sql"),
&init_sql,
0o640,
0,
account.gid,
)?;
changed |= write_file(&env_path, &env_file, 0o640, 0, account.gid)?;
changed |= write_file(Path::new(UNIT), &unit_file, 0o644, 0, 0)?;
command(Command::new("systemctl").arg("daemon-reload"))?;
if options.start {
command(Command::new("systemctl").args(["enable", "--now", "hazine"]))?;
if changed {
command(Command::new("systemctl").args(["restart", "hazine"]))?;
tracing::info!("hazine is restarting; follow it with: journalctl -u hazine -f");
} else {
tracing::info!("nothing changed; hazine keeps running");
}
} else {
tracing::info!("set up; start with: systemctl enable --now hazine");
}
let port = options.quack_addr.port();
tracing::info!(
tunnel = %format!("ssh -N -L {port}:{} <host>", options.quack_addr),
token = "sudo sed -n 's/^QUACK_TOKEN=//p' /etc/hazine/hazine.env",
"connect through an SSH tunnel"
);
Ok(())
}
fn resources(options: &Options) -> Result<Resources, Error> {
let threads = match options.threads {
Some(threads) => threads,
None => std::thread::available_parallelism()?.get(),
};
let (memory_limit, memory_max) = match (&options.memory_limit, &options.memory_max) {
(Some(limit), Some(max)) => (limit.clone(), max.clone()),
(limit, max) => {
let total_gb = memory_gb()?;
(
limit
.clone()
.unwrap_or_else(|| format!("{}GB", (total_gb * 80 / 100).max(1))),
max.clone()
.unwrap_or_else(|| format!("{}G", (total_gb * 90 / 100).max(1))),
)
}
};
Ok(Resources {
threads,
memory_limit,
memory_max,
})
}
fn memory_gb() -> Result<u64, Error> {
let meminfo = std::fs::read_to_string("/proc/meminfo").map_err(|_| Error::InvalidSetting {
name: "memory",
reason: "cannot read /proc/meminfo; give --memory-limit and --memory-max".into(),
})?;
parse_meminfo(&meminfo).ok_or_else(|| Error::InvalidSetting {
name: "memory",
reason: "no MemTotal in /proc/meminfo".into(),
})
}
fn parse_meminfo(meminfo: &str) -> Option<u64> {
let kb: u64 = meminfo
.lines()
.find_map(|line| line.strip_prefix("MemTotal:"))?
.split_whitespace()
.next()?
.parse()
.ok()?;
Some(kb / (1024 * 1024))
}
fn secrets(options: &Options, env_path: &Path) -> Result<Secrets, Error> {
let existing = match std::fs::read_to_string(env_path) {
Ok(content) => render::parse_env(&content),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Default::default(),
Err(error) if options.dry_run => {
tracing::debug!(%error, "cannot read the env file");
Default::default()
}
Err(error) => return Err(error.into()),
};
let pick = |given: &Option<String>, name: &str, prompt: &str| -> Result<String, Error> {
if let Some(value) = given.as_ref().filter(|v| !v.is_empty()) {
return Ok(value.clone());
}
if let Some(value) = existing.get(name).filter(|v| !v.is_empty()) {
return Ok(value.clone());
}
if options.dry_run {
return Ok(String::new());
}
if std::io::stdin().is_terminal() {
let value = rpassword::prompt_password(format!("{prompt}: "))?;
if !value.is_empty() {
return Ok(value);
}
}
Err(Error::MissingSecret { name: name.into() })
};
let quack_token = match existing.get("QUACK_TOKEN").filter(|v| !v.is_empty()) {
Some(token) => token.clone(),
None => token::generate(40)?,
};
Ok(Secrets {
quack_token,
pg_password: pick(&options.pg_password, "PGPASSWORD", "Postgres password")?,
s3_key_id: pick(&options.s3_key_id, "HAZINE_S3_KEY_ID", "S3 access key id")?,
s3_secret: pick(
&options.s3_secret,
"HAZINE_S3_SECRET",
"S3 secret access key",
)?,
})
}
fn print_plan(options: &Options, files: &[(PathBuf, String)]) {
let mut out = std::io::stdout().lock();
let steps = [
format!("install {} as {HAZINE_BIN}", current_exe_display()),
format!(
"install DuckDB {} as {DUCKDB_BIN} (unless that version is there)",
options.duckdb_version
),
format!("create system user {USER} with home {HOME} (unless it exists)"),
format!("install the extensions as {USER}: {EXTENSIONS}"),
format!(
"check that the lake attaches (creating the catalog the first time): \
Postgres {}:{}, data {}",
options.catalog.host, options.catalog.port, options.storage.data_path
),
"write the files below (an existing, different file is kept as .bak)".into(),
if options.start {
"systemctl daemon-reload, enable --now hazine, and restart it if anything changed"
.into()
} else {
"systemctl daemon-reload".into()
},
];
let _ = writeln!(out, "hazine setup would:");
for (n, step) in steps.iter().enumerate() {
let _ = writeln!(out, " {}. {step}", n + 1);
}
for (path, content) in files {
let _ = writeln!(out, "\n==> {} <==\n{content}", path.display());
}
}
fn current_exe_display() -> String {
std::env::current_exe()
.map(|path| path.display().to_string())
.unwrap_or_else(|_| "this binary".into())
}
fn install_self() -> Result<bool, Error> {
let exe = std::env::current_exe()?;
let target = Path::new(HAZINE_BIN);
if same_contents(&exe, target)? {
tracing::info!(path = HAZINE_BIN, "hazine is installed");
return Ok(false);
}
install_binary(&exe, target)?;
tracing::info!(path = HAZINE_BIN, from = %exe.display(), "installed hazine");
Ok(true)
}
fn same_contents(a: &Path, b: &Path) -> Result<bool, Error> {
match std::fs::read(b) {
Ok(existing) => Ok(std::fs::read(a)? == existing),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.into()),
}
}
fn install_duckdb(version: &str) -> Result<bool, Error> {
let wanted = format!("v{}", version.trim_start_matches('v'));
if let Ok(output) = Command::new(DUCKDB_BIN).arg("-version").output() {
let found = String::from_utf8_lossy(&output.stdout);
if found.split_whitespace().next() == Some(wanted.as_str()) {
tracing::info!(path = DUCKDB_BIN, version = %wanted, "DuckDB is installed");
return Ok(false);
}
}
let arch = match std::env::consts::ARCH {
"x86_64" => "amd64",
"aarch64" => "arm64",
other => {
return Err(Error::Unsupported(if other.is_empty() {
"unknown CPU architecture"
} else {
"DuckDB publishes Linux CLIs for x86_64 and aarch64 only"
}));
}
};
let url = format!(
"https://github.com/duckdb/duckdb/releases/download/{wanted}/duckdb-cli-linux-{arch}.tar.gz"
);
let dir = TempDir::new()?;
let archive = dir.path().join("duckdb.tar.gz");
tracing::info!(%url, "downloading DuckDB");
command(
Command::new("curl")
.args([
"--fail",
"--silent",
"--show-error",
"--location",
"--output",
])
.arg(&archive)
.arg(&url),
)?;
command(
Command::new("tar")
.arg("-xzf")
.arg(&archive)
.arg("-C")
.arg(dir.path())
.arg("duckdb"),
)?;
install_binary(&dir.path().join("duckdb"), Path::new(DUCKDB_BIN))?;
let output = command(Command::new(DUCKDB_BIN).arg("-version"))?;
tracing::info!(path = DUCKDB_BIN, version = %output.trim(), "installed DuckDB");
Ok(true)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Account {
uid: u32,
gid: u32,
}
fn ensure_account() -> Result<Account, Error> {
let account = match lookup_account(&std::fs::read_to_string("/etc/passwd")?, USER) {
Some(account) => {
tracing::info!(user = USER, "system user exists");
account
}
None => {
command(Command::new("useradd").args([
"--system",
"--user-group",
"--home-dir",
HOME,
"--create-home",
"--shell",
"/usr/sbin/nologin",
USER,
]))?;
tracing::info!(user = USER, home = HOME, "created system user");
lookup_account(&std::fs::read_to_string("/etc/passwd")?, USER).ok_or(
Error::InvalidSetting {
name: "user",
reason: format!("{USER} is not in /etc/passwd after useradd"),
},
)?
}
};
ensure_dir(Path::new(HOME), 0o750, account.uid, account.gid)?;
ensure_dir(
&Path::new(HOME).join("tmp"),
0o750,
account.uid,
account.gid,
)?;
Ok(account)
}
fn lookup_account(passwd: &str, user: &str) -> Option<Account> {
passwd.lines().find_map(|line| {
let mut fields = line.split(':');
if fields.next()? != user {
return None;
}
let _password = fields.next()?;
Some(Account {
uid: fields.next()?.parse().ok()?,
gid: fields.next()?.parse().ok()?,
})
})
}
fn duckdb_as(account: &Account, sql: &str, env: &[(String, String)]) -> Result<String, Error> {
use std::os::unix::process::CommandExt;
let mut cmd = Command::new(DUCKDB_BIN);
cmd.args(["-no-agent", "-batch", "-bail", "-init", "/dev/null"])
.uid(account.uid)
.gid(account.gid)
.current_dir(HOME)
.env_clear()
.env("HOME", HOME)
.env("PATH", "/usr/local/bin:/usr/bin:/bin")
.env("NO_COLOR", "1")
.envs(env.iter().map(|(name, value)| (name, value)));
command_with_stdin(&mut cmd, sql)
}
fn install_extensions(account: &Account) -> Result<(), Error> {
duckdb_as(account, EXTENSIONS, &[])?;
tracing::info!(user = USER, extensions = EXTENSIONS, "installed extensions");
Ok(())
}
fn check_lake(account: &Account, storage: &Storage, env_file: &str) -> Result<(), Error> {
let env: Vec<(String, String)> = render::parse_env(env_file).into_iter().collect();
let output = duckdb_as(account, &render::check_sql(storage), &env)
.map_err(|error| Error::LakeCheck(error.to_string()))?;
tracing::info!(data_path = %storage.data_path, "the lake attaches");
tracing::debug!(%output, "lake check");
Ok(())
}
fn ensure_dir(path: &Path, mode: u32, uid: u32, gid: u32) -> Result<(), Error> {
use std::os::unix::fs::PermissionsExt;
std::fs::create_dir_all(path)?;
std::os::unix::fs::chown(path, Some(uid), Some(gid))?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))?;
Ok(())
}
fn write_file(path: &Path, content: &str, mode: u32, uid: u32, gid: u32) -> Result<bool, Error> {
use std::os::unix::fs::PermissionsExt;
match std::fs::read_to_string(path) {
Ok(existing) if existing == content => {
std::os::unix::fs::chown(path, Some(uid), Some(gid))?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))?;
tracing::info!(path = %path.display(), "unchanged");
return Ok(false);
}
Ok(_) => {
let backup = with_suffix(path, ".bak");
std::fs::copy(path, &backup)?;
tracing::info!(path = %path.display(), backup = %backup.display(), "kept the old file");
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
let tmp = with_suffix(path, ".tmp");
{
let mut file = std::fs::File::create(&tmp)?;
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(mode))?;
std::os::unix::fs::chown(&tmp, Some(uid), Some(gid))?;
file.write_all(content.as_bytes())?;
file.sync_all()?;
}
std::fs::rename(&tmp, path)?;
tracing::info!(path = %path.display(), "wrote");
Ok(true)
}
fn install_binary(source: &Path, target: &Path) -> Result<(), Error> {
use std::os::unix::fs::PermissionsExt;
let tmp = with_suffix(target, ".tmp");
std::fs::copy(source, &tmp)?;
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?;
std::fs::rename(&tmp, target)?;
Ok(())
}
fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
let mut name = path.as_os_str().to_owned();
name.push(suffix);
PathBuf::from(name)
}
fn command(cmd: &mut Command) -> Result<String, Error> {
command_with_stdin(cmd, "")
}
fn command_with_stdin(cmd: &mut Command, stdin: &str) -> Result<String, Error> {
let program = cmd.get_program().to_string_lossy().into_owned();
let mut child = cmd
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|source| Error::Spawn {
program: program.clone().into(),
source,
})?;
if let Some(mut pipe) = child.stdin.take() {
pipe.write_all(stdin.as_bytes())?;
}
let output = child.wait_with_output()?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let detail = [stderr.trim(), stdout.trim()]
.into_iter()
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join("\n");
Err(Error::Command {
program,
status: output.status.to_string(),
detail,
})
}
}
fn effective_uid() -> Result<u32, Error> {
let status = std::fs::read_to_string("/proc/self/status")?;
status
.lines()
.find_map(|line| line.strip_prefix("Uid:"))
.and_then(|ids| ids.split_whitespace().nth(1)?.parse().ok())
.ok_or(Error::Unsupported("cannot read the effective uid"))
}
struct TempDir(PathBuf);
impl TempDir {
fn new() -> Result<Self, Error> {
let path = std::env::temp_dir().join(format!("hazine-setup-{}", token::generate(12)?));
std::fs::create_dir(&path)?;
Ok(TempDir(path))
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
if let Err(error) = std::fs::remove_dir_all(&self.0) {
tracing::warn!(path = %self.0.display(), %error, "cannot remove temporary directory");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn memory_comes_from_meminfo() {
let meminfo = "MemTotal: 131899664 kB\nMemFree: 1000 kB\n";
assert_eq!(parse_meminfo(meminfo), Some(125));
assert_eq!(parse_meminfo("MemFree: 1 kB\n"), None);
}
#[test]
fn accounts_are_found_in_passwd() {
let passwd = "root:x:0:0:root:/root:/bin/bash\n\
hazinex:x:998:998::/x:/bin/sh\n\
hazine:x:999:997::/var/lib/hazine:/usr/sbin/nologin\n";
assert_eq!(
lookup_account(passwd, "hazine"),
Some(Account { uid: 999, gid: 997 })
);
assert_eq!(lookup_account(passwd, "nobody"), None);
}
#[test]
fn suffixes_are_appended() {
assert_eq!(
with_suffix(Path::new("/etc/hazine/hazine.env"), ".bak"),
PathBuf::from("/etc/hazine/hazine.env.bak")
);
}
}