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

            
9
use std::path::{Path, PathBuf};
10
use std::process::Command;
11

            
12
use anyhow::{Context, Result, bail};
13

            
14
const DIRECTORY_DUMP: &str = "nomisync";
15
const DUMP_EXTENSION: &str = "dump";
16
/// The CLI demands a user id the admin command does not use.
17
const NIL_USER: &str = "00000000-0000-0000-0000-000000000000";
18

            
19
2
fn database_url(server: &str, name: &str) -> String {
20
2
    format!("{}/{name}", server.trim_end_matches('/'))
21
2
}
22

            
23
/// Tenant database names: every dump of `dir` except the directory's own.
24
2
fn tenant_names(dir: &Path) -> Result<Vec<String>> {
25
2
    let mut names = Vec::new();
26
2
    for entry in std::fs::read_dir(dir).with_context(|| format!("cannot read {}", dir.display()))? {
27
4
        let path: PathBuf = entry?.path();
28
4
        let stem = path.file_stem().and_then(|s| s.to_str());
29
4
        match (path.extension().and_then(|e| e.to_str()), stem) {
30
3
            (Some(DUMP_EXTENSION), Some(name)) if name != DIRECTORY_DUMP => {
31
2
                names.push(name.to_string());
32
            }
33
2
            _ => {}
34
        }
35
    }
36
1
    names.sort();
37
1
    Ok(names)
38
2
}
39

            
40
1
fn tenant_copy_name(name: &str) -> String {
41
1
    format!("pf{}_{name}", std::process::id())
42
1
}
43

            
44
/// SQL pointing the restored directory at the restored copy of a tenant.
45
1
fn repoint(name: &str, copy: &str) -> String {
46
1
    format!("UPDATE users SET database_name = '{copy}' WHERE database_name = '{name}'")
47
1
}
48

            
49
fn 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.
61
struct Restored<'a> {
62
    server: &'a str,
63
    names: Vec<String>,
64
}
65

            
66
impl 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

            
82
impl 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.
95
pub 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.
100
2
fn references_args(sources: Option<&Path>) -> Vec<String> {
101
2
    let flag = sources.map(|path| ["--sources".to_string(), path.to_string_lossy().into_owned()]);
102
2
    std::iter::once("check-references".to_string())
103
2
        .chain(flag.into_iter().flatten())
104
2
        .collect()
105
2
}
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`.
109
pub fn check_references(dir: &Path, server: &str, sources: Option<&Path>) -> Result<()> {
110
    run_admin(dir, server, &references_args(sources))
111
}
112

            
113
fn 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)]
147
mod tests;