pub mod render;
use std::collections::HashMap;
use std::io::{BufRead, 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::tempdir::TempDir;
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.storage,
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.storage,
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,
})
}
pub(crate) 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 = read_env(env_path, options.dry_run)?;
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::MissingSetting { 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",
)?,
})
}
pub(crate) fn read_env(path: &Path, dry_run: bool) -> Result<HashMap<String, String>, Error> {
match std::fs::read_to_string(path) {
Ok(content) => Ok(render::parse_env(&content)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(HashMap::new()),
Err(error) if dry_run => {
tracing::debug!(%error, "cannot read the env file");
Ok(HashMap::new())
}
Err(error) => Err(error.into()),
}
}
pub fn existing_env(dry_run: bool) -> Result<HashMap<String, String>, Error> {
read_env(&Path::new(ETC).join("hazine.env"), dry_run)
}
pub fn setting(
given: Option<String>,
existing: Option<&str>,
name: &str,
prompt: &str,
check: impl Fn(&str) -> Result<String, Error>,
) -> Result<String, Error> {
if let Some(value) = given.filter(|v| !v.is_empty()) {
return check(&value);
}
let existing = existing.filter(|v| !v.is_empty());
if std::io::stdin().is_terminal() {
return ask(
&mut std::io::stdin().lock(),
&mut std::io::stderr(),
existing,
prompt,
check,
)?
.ok_or_else(|| Error::MissingSetting { name: name.into() });
}
match existing {
Some(value) => check(value),
None => Err(Error::MissingSetting { name: name.into() }),
}
}
fn ask(
input: &mut impl BufRead,
output: &mut impl Write,
default: Option<&str>,
prompt: &str,
check: impl Fn(&str) -> Result<String, Error>,
) -> Result<Option<String>, Error> {
loop {
match default {
Some(default) => write!(output, "{prompt} [{default}]: ")?,
None => write!(output, "{prompt}: ")?,
}
output.flush()?;
let mut line = String::new();
if input.read_line(&mut line)? == 0 {
writeln!(output)?;
return Ok(None);
}
let answer = match (line.trim(), default) {
("", Some(default)) => default,
("", None) => continue,
(answer, _) => answer,
};
match check(answer) {
Ok(value) => return Ok(Some(value)),
Err(error) => writeln!(output, " {error}")?,
}
}
}
pub fn host(value: &str) -> Result<String, Error> {
let value = value.trim();
if value.is_empty()
|| value
.chars()
.any(|c| c.is_whitespace() || c.is_control() || c == '\'')
{
return Err(Error::InvalidSetting {
name: "Postgres host",
reason: format!("{value:?} is not a host name or address"),
});
}
Ok(value.to_string())
}
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)]
pub(crate) struct Account {
uid: u32,
gid: u32,
}
impl Account {
pub(crate) fn chown(&self, path: &Path) -> std::io::Result<()> {
std::os::unix::fs::chown(path, Some(self.uid), Some(self.gid))
}
}
pub(crate) fn service_account() -> Result<Account, Error> {
lookup_account(&std::fs::read_to_string("/etc/passwd")?, USER).ok_or(Error::InvalidSetting {
name: "user",
reason: format!("there is no {USER} user; run hazine setup first"),
})
}
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> {
duckdb_on(account, None, sql, env)
}
pub(crate) fn duckdb_on(
account: &Account,
database: Option<&str>,
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"]);
if let Some(database) = database {
cmd.arg(database);
}
cmd.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(with_hint(error.to_string())))?;
tracing::info!(data_path = %storage.data_path, "the lake attaches");
tracing::debug!(%output, "lake check");
Ok(())
}
fn with_hint(message: String) -> String {
if message.contains("timeout expired") {
format!(
"{message}\nhint: Postgres did not answer; does its firewall allow this \
host's IPv4 and IPv6 addresses?"
)
} else {
message
}
}
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,
})
}
}
pub(crate) 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"))
}
#[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);
}
fn answers(input: &str, default: Option<&str>) -> (Option<String>, String) {
let mut output = Vec::new();
let value = ask(
&mut std::io::Cursor::new(input),
&mut output,
default,
"Data path",
render::data_path,
)
.unwrap();
(value, String::from_utf8(output).unwrap())
}
#[test]
fn asking_takes_the_answer_or_the_default() {
let (value, prompt) = answers("s3://lake/x\n", Some("s3://old/"));
assert_eq!(value.as_deref(), Some("s3://lake/x/"));
assert_eq!(prompt, "Data path [s3://old/]: ");
let (value, _) = answers("\n", Some("s3://old/"));
assert_eq!(value.as_deref(), Some("s3://old/"));
}
#[test]
fn asking_repeats_until_the_answer_is_valid() {
let (value, prompt) = answers("\nlake\ns3://lake\n", None);
assert_eq!(value.as_deref(), Some("s3://lake/"));
assert_eq!(prompt.matches("Data path: ").count(), 3, "{prompt}");
assert!(prompt.contains("does not start with s3://"), "{prompt}");
}
#[test]
fn asking_gives_up_when_input_ends() {
let (value, _) = answers("lake\n", None);
assert_eq!(value, None);
}
#[test]
fn hosts_are_checked() {
assert_eq!(host(" db.example.org ").unwrap(), "db.example.org");
assert_eq!(host("10.0.0.5").unwrap(), "10.0.0.5");
for bad in ["", "db example", "db'x"] {
assert!(host(bad).is_err(), "{bad:?}");
}
}
#[test]
fn connect_timeouts_get_a_hint() {
assert!(with_hint("x: timeout expired".into()).contains("firewall"));
assert_eq!(
with_hint("password authentication failed".into()),
"password authentication failed"
);
}
#[test]
fn suffixes_are_appended() {
assert_eq!(
with_suffix(Path::new("/etc/hazine/hazine.env"), ".bak"),
PathBuf::from("/etc/hazine/hazine.env.bak")
);
}
}