Skip to main content

xtask/
snapshot.rs

1//! The prod-snapshot preflights: restore the dumps of a directory and its
2//! tenants into fresh local databases, run `cli admin check-forms` or
3//! `check-references` on them and drop what it created.
4//!
5//! Tenants are restored under a prefixed name and the restored directory is
6//! rewritten to point at it, so no existing database is ever reused. The check
7//! saves every transaction, which is why it only runs on these copies.
8
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use anyhow::{Context, Result, bail};
13
14const DIRECTORY_DUMP: &str = "nomisync";
15const DUMP_EXTENSION: &str = "dump";
16/// The CLI demands a user id the admin command does not use.
17const NIL_USER: &str = "00000000-0000-0000-0000-000000000000";
18
19fn database_url(server: &str, name: &str) -> String {
20    format!("{}/{name}", server.trim_end_matches('/'))
21}
22
23/// Tenant database names: every dump of `dir` except the directory's own.
24fn tenant_names(dir: &Path) -> Result<Vec<String>> {
25    let mut names = Vec::new();
26    for entry in std::fs::read_dir(dir).with_context(|| format!("cannot read {}", dir.display()))? {
27        let path: PathBuf = entry?.path();
28        let stem = path.file_stem().and_then(|s| s.to_str());
29        match (path.extension().and_then(|e| e.to_str()), stem) {
30            (Some(DUMP_EXTENSION), Some(name)) if name != DIRECTORY_DUMP => {
31                names.push(name.to_string());
32            }
33            _ => {}
34        }
35    }
36    names.sort();
37    Ok(names)
38}
39
40fn tenant_copy_name(name: &str) -> String {
41    format!("pf{}_{name}", std::process::id())
42}
43
44/// SQL pointing the restored directory at the restored copy of a tenant.
45fn repoint(name: &str, copy: &str) -> String {
46    format!("UPDATE users SET database_name = '{copy}' WHERE database_name = '{name}'")
47}
48
49fn run(program: &str, args: &[&str]) -> Result<()> {
50    let status = Command::new(program)
51        .args(args)
52        .status()
53        .with_context(|| format!("failed to run {program}"))?;
54    if !status.success() {
55        bail!("{program} exited with {status}");
56    }
57    Ok(())
58}
59
60/// The databases created so far; dropped when the run ends, however it ends.
61struct Restored<'a> {
62    server: &'a str,
63    names: Vec<String>,
64}
65
66impl Restored<'_> {
67    fn restore(&mut self, name: &str, dump: &Path) -> Result<()> {
68        let admin = database_url(self.server, "postgres");
69        run(
70            "psql",
71            &[&admin, "-c", &format!("CREATE DATABASE \"{name}\"")],
72        )?;
73        self.names.push(name.to_string());
74        let target = database_url(self.server, name);
75        run(
76            "pg_restore",
77            &["--no-owner", "--dbname", &target, &dump.to_string_lossy()],
78        )
79    }
80}
81
82impl Drop for Restored<'_> {
83    fn drop(&mut self) {
84        let admin = database_url(self.server, "postgres");
85        for name in &self.names {
86            let drop = format!("DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)");
87            if let Err(err) = run("psql", &[&admin, "-c", &drop]) {
88                eprintln!("cannot drop {name}: {err}");
89            }
90        }
91    }
92}
93
94/// Restores the dumps in `dir` under `server` and checks the forms on them.
95pub fn check_forms(dir: &Path, server: &str) -> Result<()> {
96    run_admin(dir, server, &["check-forms", "--disposable"])
97}
98
99/// The `cli admin` arguments of the reference check.
100fn references_args(sources: Option<&Path>) -> Vec<String> {
101    let flag = sources.map(|path| ["--sources".to_string(), path.to_string_lossy().into_owned()]);
102    std::iter::once("check-references".to_string())
103        .chain(flag.into_iter().flatten())
104        .collect()
105}
106
107/// Restores the dumps in `dir` under `server` and lists the ambiguous and bare
108/// references of the templates and of the sources in `sources`.
109pub fn check_references(dir: &Path, server: &str, sources: Option<&Path>) -> Result<()> {
110    run_admin(dir, server, &references_args(sources))
111}
112
113fn run_admin<S: AsRef<str>>(dir: &Path, server: &str, admin: &[S]) -> Result<()> {
114    let directory = format!("nomisync_preflight_{}", std::process::id());
115    let mut restored = Restored {
116        server,
117        names: Vec::new(),
118    };
119    restored.restore(
120        &directory,
121        &dir.join(format!("{DIRECTORY_DUMP}.{DUMP_EXTENSION}")),
122    )?;
123    for name in tenant_names(dir)? {
124        let copy = tenant_copy_name(&name);
125        restored.restore(&copy, &dir.join(format!("{name}.{DUMP_EXTENSION}")))?;
126        let directory_url = database_url(server, &directory);
127        run("psql", &[&directory_url, "-c", &repoint(&name, &copy)])?;
128    }
129    let database = database_url(server, &directory);
130    let mut args = vec![
131        "run",
132        "--quiet",
133        "--bin",
134        "cli",
135        "--",
136        "--userid",
137        NIL_USER,
138        "--database",
139        &database,
140        "admin",
141    ];
142    args.extend(admin.iter().map(AsRef::as_ref));
143    run("cargo", &args)
144}
145
146#[cfg(test)]
147mod tests;