Lines
28.72 %
Functions
27.27 %
Branches
100 %
//! The prod-snapshot preflights: restore the dumps of a directory and its
//! tenants into fresh local databases, run `cli admin check-forms` or
//! `check-references` on them and drop what it created.
//!
//! Tenants are restored under a prefixed name and the restored directory is
//! rewritten to point at it, so no existing database is ever reused. The check
//! saves every transaction, which is why it only runs on these copies.
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{Context, Result, bail};
const DIRECTORY_DUMP: &str = "nomisync";
const DUMP_EXTENSION: &str = "dump";
/// The CLI demands a user id the admin command does not use.
const NIL_USER: &str = "00000000-0000-0000-0000-000000000000";
fn database_url(server: &str, name: &str) -> String {
format!("{}/{name}", server.trim_end_matches('/'))
}
/// Tenant database names: every dump of `dir` except the directory's own.
fn tenant_names(dir: &Path) -> Result<Vec<String>> {
let mut names = Vec::new();
for entry in std::fs::read_dir(dir).with_context(|| format!("cannot read {}", dir.display()))? {
let path: PathBuf = entry?.path();
let stem = path.file_stem().and_then(|s| s.to_str());
match (path.extension().and_then(|e| e.to_str()), stem) {
(Some(DUMP_EXTENSION), Some(name)) if name != DIRECTORY_DUMP => {
names.push(name.to_string());
_ => {}
names.sort();
Ok(names)
fn tenant_copy_name(name: &str) -> String {
format!("pf{}_{name}", std::process::id())
/// SQL pointing the restored directory at the restored copy of a tenant.
fn repoint(name: &str, copy: &str) -> String {
format!("UPDATE users SET database_name = '{copy}' WHERE database_name = '{name}'")
fn run(program: &str, args: &[&str]) -> Result<()> {
let status = Command::new(program)
.args(args)
.status()
.with_context(|| format!("failed to run {program}"))?;
if !status.success() {
bail!("{program} exited with {status}");
Ok(())
/// The databases created so far; dropped when the run ends, however it ends.
struct Restored<'a> {
server: &'a str,
names: Vec<String>,
impl Restored<'_> {
fn restore(&mut self, name: &str, dump: &Path) -> Result<()> {
let admin = database_url(self.server, "postgres");
run(
"psql",
&[&admin, "-c", &format!("CREATE DATABASE \"{name}\"")],
)?;
self.names.push(name.to_string());
let target = database_url(self.server, name);
"pg_restore",
&["--no-owner", "--dbname", &target, &dump.to_string_lossy()],
)
impl Drop for Restored<'_> {
fn drop(&mut self) {
for name in &self.names {
let drop = format!("DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)");
if let Err(err) = run("psql", &[&admin, "-c", &drop]) {
eprintln!("cannot drop {name}: {err}");
/// Restores the dumps in `dir` under `server` and checks the forms on them.
pub fn check_forms(dir: &Path, server: &str) -> Result<()> {
run_admin(dir, server, &["check-forms", "--disposable"])
/// The `cli admin` arguments of the reference check.
fn references_args(sources: Option<&Path>) -> Vec<String> {
let flag = sources.map(|path| ["--sources".to_string(), path.to_string_lossy().into_owned()]);
std::iter::once("check-references".to_string())
.chain(flag.into_iter().flatten())
.collect()
/// Restores the dumps in `dir` under `server` and lists the ambiguous and bare
/// references of the templates and of the sources in `sources`.
pub fn check_references(dir: &Path, server: &str, sources: Option<&Path>) -> Result<()> {
run_admin(dir, server, &references_args(sources))
fn run_admin<S: AsRef<str>>(dir: &Path, server: &str, admin: &[S]) -> Result<()> {
let directory = format!("nomisync_preflight_{}", std::process::id());
let mut restored = Restored {
server,
names: Vec::new(),
};
restored.restore(
&directory,
&dir.join(format!("{DIRECTORY_DUMP}.{DUMP_EXTENSION}")),
for name in tenant_names(dir)? {
let copy = tenant_copy_name(&name);
restored.restore(©, &dir.join(format!("{name}.{DUMP_EXTENSION}")))?;
let directory_url = database_url(server, &directory);
run("psql", &[&directory_url, "-c", &repoint(&name, ©)])?;
let database = database_url(server, &directory);
let mut args = vec![
"run",
"--quiet",
"--bin",
"cli",
"--",
"--userid",
NIL_USER,
"--database",
&database,
"admin",
];
args.extend(admin.iter().map(AsRef::as_ref));
run("cargo", &args)
#[cfg(test)]
mod tests;