Skip to main content

vcon_server/tenants/
backup.rs

1//! A copy of the whole data directory, made while a server may be running:
2//! server.sqlite with SQLite's online backup API, then each tenant it lists,
3//! as `Store::backup_to` copies one.
4
5use std::collections::BTreeSet;
6use std::io;
7use std::path::Path;
8
9use super::{TenantError, Tenants};
10use crate::audit::{Action, Actor, Entry};
11use crate::ids::TenantId;
12use crate::store::{self, TRIES};
13
14/// What `backup` copied.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct Backup {
17    pub tenants: u64,
18    pub versions: u64,
19    /// How many times server.sqlite was copied.
20    pub tries: usize,
21}
22
23/// Why a backup was refused or failed.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum BackupError {
26    /// Something is already at the backup's path.
27    Exists,
28    /// Tenants were removed, or versions purged, after each try's copy.
29    KeptChanging,
30    /// A file could not be read, written or synced, or a catalog could not
31    /// be copied or read.
32    Io,
33    /// The admin log could not record the backup.
34    AuditFailed,
35    /// The catalogs are in PostgreSQL, which this command does not copy
36    /// into a directory: the database's own backup tools do.
37    NoFileBackup,
38}
39
40/// What a refused backup of a PostgreSQL catalog says to do.
41pub const NO_FILE_BACKUP: &str = "the catalogs are in PostgreSQL, which backup does not copy into \
42                                  a directory: back up the catalog database with pg_dump or a \
43                                  base backup with WAL archiving, and keep the bucket and the \
44                                  master key file with it";
45
46impl Tenants {
47    /// Copies the data directory into `to`, which must not exist, and
48    /// records the run in the admin log with its outcome.
49    ///
50    /// Each try copies server.sqlite in one step inside one read
51    /// transaction, then each tenant that copy lists, as `Store::backup_to`
52    /// copies one. A tenant the copy lists that is gone, or whose versions
53    /// kept being purged, was removed meanwhile, and the next try copies
54    /// server.sqlite again. Tenant directories the final copy does not
55    /// list are removed. Tenants are copied one after another, each as it
56    /// was at its own copy.
57    pub fn backup(&self, who: Actor, to: &Path) -> Result<Backup, BackupError> {
58        let done = self.copy_all(to);
59        let status = match done {
60            Ok(_) => 200,
61            Err(BackupError::Exists) => 409,
62            Err(BackupError::KeptChanging) => 503,
63            Err(BackupError::Io | BackupError::AuditFailed) => 500,
64            Err(BackupError::NoFileBackup) => 501,
65        };
66        self.record_alone(&Entry {
67            actor: who,
68            action: Action::Backup,
69            target: None,
70            version: None,
71            status,
72        })
73        .map_err(|_| BackupError::AuditFailed)?;
74        done
75    }
76
77    fn copy_all(&self, to: &Path) -> Result<Backup, BackupError> {
78        let fail = |_| BackupError::Io;
79        match self.fs.list(to) {
80            Err(e) if e.kind() == io::ErrorKind::NotFound => {}
81            Ok(_) => return Err(BackupError::Exists),
82            Err(e) if e.kind() == io::ErrorKind::NotADirectory => return Err(BackupError::Exists),
83            Err(_) => return Err(BackupError::Io),
84        }
85        let tenants = to.join("tenants");
86        self.fs.create_dir_all(&tenants).map_err(fail)?;
87        // Only the service account may enter the copy, as with the data
88        // directory, which is restored by copying this one with its modes.
89        {
90            use std::os::unix::fs::PermissionsExt;
91            std::fs::set_permissions(to, std::fs::Permissions::from_mode(crate::fs::DIR_MODE))
92                .map_err(fail)?;
93        }
94        let registry = to.join("server.sqlite");
95        'tries: for tries in 1..=TRIES {
96            for file in ["server.sqlite", "server.sqlite-wal", "server.sqlite-shm"] {
97                remove_if_there(&to.join(file)).map_err(fail)?;
98            }
99            let listed = match self.registry.backup_into(&registry) {
100                Ok(listed) => listed,
101                Err(TenantError::NoFileBackup) => {
102                    // Nothing was copied: the directory made for the copy
103                    // goes, so the path is free for a later backup.
104                    self.fs.remove_dir_all(to).map_err(fail)?;
105                    return Err(BackupError::NoFileBackup);
106                }
107                Err(_) => return Err(BackupError::Io),
108            };
109            #[cfg(test)]
110            if let Some(hook) = self.hooks.registry_copied.lock().expect("hook").as_mut() {
111                hook(self);
112            }
113            let mut versions = 0;
114            for id in &listed {
115                let copied = match self.store(*id) {
116                    Ok(store) => store.backup_to(&tenants.join(id.to_string())),
117                    Err(TenantError::NotFound | TenantError::Closing) => continue 'tries,
118                    Err(_) => return Err(BackupError::Io),
119                };
120                match copied {
121                    Ok(copied) => versions += copied.versions,
122                    // A tenant removed while it was copied: its files went
123                    // with it, so no try of its own could finish.
124                    Err(store::BackupError::KeptChanging) if !self.listed(*id)? => {
125                        self.stores().remove(id);
126                        continue 'tries;
127                    }
128                    Err(store::BackupError::KeptChanging) => return Err(BackupError::KeptChanging),
129                    Err(store::BackupError::Io) => return Err(BackupError::Io),
130                }
131            }
132            let names: BTreeSet<String> = listed.iter().map(ToString::to_string).collect();
133            for name in self.fs.list(&tenants).map_err(fail)? {
134                let name = name.into_string().unwrap_or_default();
135                if !names.contains(&name) {
136                    self.fs.remove_dir_all(&tenants.join(&name)).map_err(fail)?;
137                }
138            }
139            self.fs.sync_dir(&tenants).map_err(fail)?;
140            self.fs.sync_dir(to).map_err(fail)?;
141            if let Some(parent) = to.parent() {
142                self.fs.sync_dir(parent).map_err(fail)?;
143            }
144            return Ok(Backup {
145                tenants: listed.len() as u64,
146                versions,
147                tries,
148            });
149        }
150        Err(BackupError::KeptChanging)
151    }
152
153    /// Whether server.sqlite, as it is now, lists the tenant.
154    fn listed(&self, id: TenantId) -> Result<bool, BackupError> {
155        let mut tx = self.registry.snapshot().map_err(|_| BackupError::Io)?;
156        Ok(tx.tenant(id).map_err(|_| BackupError::Io)?.is_some())
157    }
158}
159
160fn remove_if_there(path: &Path) -> io::Result<()> {
161    match std::fs::remove_file(path) {
162        Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
163        _ => Ok(()),
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use std::sync::Arc;
170    use std::sync::atomic::{AtomicUsize, Ordering};
171
172    use super::*;
173    use crate::clock::Clock;
174    use crate::fs::Fs;
175    use crate::ids::TenantId;
176    use crate::store::Caller;
177    use crate::store::testing::vcon;
178    use crate::tenants::Removal;
179    use crate::tenants::tests::{Fixture, fixture};
180
181    /// Two tenants, each holding a vCon.
182    fn two(f: &Fixture) -> [TenantId; 2] {
183        let caller = Caller {
184            key: crate::envelope::Key::generate().expect("key").id(),
185        };
186        let ids = ["acme", "globex"]
187            .map(|name| f.tenants.create(Actor::Cli, name, None).expect("creates"));
188        for (n, id) in ids.iter().enumerate() {
189            let (found, body) = vcon(&format!("01a07da8-c2bb-83e5-b9a2-27900000000{n}"), "held");
190            f.tenants
191                .store(*id)
192                .expect("store")
193                .create(&caller, &found, &body)
194                .expect("create");
195        }
196        ids
197    }
198
199    /// The backup at `to` opened as a registry under the same master key.
200    fn opened(f: &Fixture, to: &Path) -> Tenants {
201        Tenants::open_beside(to, f.master_key(), f.fs.clone(), f.clock.clone())
202            .expect("the backup opens under the master key")
203    }
204
205    /// Checks the backup `backup` holds `tenants` tenants, each whole with
206    /// its one version, examined at the fixture's time.
207    fn assert_whole(backup: &Tenants, tenants: usize, now: time::OffsetDateTime) {
208        let found = backup
209            .examine(crate::retention::Retention::Years(7), now)
210            .expect("examines");
211        assert_eq!(
212            found.tenants.len(),
213            tenants,
214            "the backup holds every tenant the registry did"
215        );
216        for tenant in &found.tenants {
217            let store = tenant
218                .store
219                .as_ref()
220                .expect("each catalog opens under its key");
221            assert!(
222                store.damaged.is_empty(),
223                "every copied version opens: {:?}",
224                store.damaged
225            );
226            assert!(
227                store.leftovers.is_empty(),
228                "the copy holds no file its catalog does not name: {:?}",
229                store.leftovers
230            );
231            assert_eq!(store.versions, 1, "each tenant stored one version");
232        }
233    }
234
235    fn records(f: &Fixture, action: &str) -> Vec<serde_json::Value> {
236        f.tenants
237            .admin_records()
238            .into_iter()
239            .filter(|r| r["action"] == action)
240            .collect()
241    }
242
243    #[test]
244    fn a_backup_opens_whole_under_the_master_key_and_is_recorded() {
245        let f = fixture();
246        two(&f);
247        let to = f.dir.path().join("backup");
248        let done = f.tenants.backup(Actor::Cli, &to).expect("backs up");
249        assert_eq!(
250            done,
251            Backup {
252                tenants: 2,
253                versions: 2,
254                tries: 1
255            }
256        );
257        let backup = opened(&f, &to);
258        assert_whole(&backup, 2, f.clock.now());
259        use std::os::unix::fs::PermissionsExt;
260        let mode = std::fs::metadata(&to)
261            .expect("the backup")
262            .permissions()
263            .mode()
264            & 0o777;
265        assert_eq!(
266            mode, 0o700,
267            "only the service account may enter the backup: {mode:o}"
268        );
269        let names: Vec<String> = backup
270            .list(Actor::Cli)
271            .expect("lists")
272            .into_iter()
273            .map(|t| t.name)
274            .collect();
275        assert_eq!(names, ["acme", "globex"]);
276        let recorded = records(&f, "backup");
277        assert_eq!(recorded.len(), 1);
278        assert_eq!(recorded[0]["status"], 200);
279    }
280
281    #[test]
282    fn a_backup_survives_a_crash_once_it_returns() {
283        let f = fixture();
284        two(&f);
285        let to = f.dir.path().join("backup");
286        f.tenants.backup(Actor::Cli, &to).expect("backs up");
287        f.fs.crash();
288        assert_eq!(
289            f.fs.list(&to.join("tenants"))
290                .expect("the backup is there")
291                .len(),
292            2
293        );
294        assert_whole(&opened(&f, &to), 2, f.clock.now());
295    }
296
297    #[test]
298    fn a_path_already_there_is_refused_and_recorded() {
299        let f = fixture();
300        two(&f);
301        let to = f.dir.path().join("backup");
302        f.fs.create_dir_all(&to).expect("dir");
303        assert_eq!(f.tenants.backup(Actor::Cli, &to), Err(BackupError::Exists));
304        assert!(
305            f.fs.list(&to).expect("list").is_empty(),
306            "nothing is written"
307        );
308        assert_eq!(records(&f, "backup")[0]["status"], 409);
309    }
310
311    #[test]
312    fn a_tenant_removed_after_the_registry_is_copied_starts_the_backup_again() {
313        let f = fixture();
314        let [acme, _] = two(&f);
315        let calls = Arc::new(AtomicUsize::new(0));
316        let seen = calls.clone();
317        *f.tenants.hooks.registry_copied.lock().expect("hook") =
318            Some(Box::new(move |tenants: &Tenants| {
319                if seen.fetch_add(1, Ordering::SeqCst) == 0 {
320                    tenants
321                        .remove(Actor::Cli, acme, Removal::Force)
322                        .expect("removes");
323                }
324            }));
325        let to = f.dir.path().join("backup");
326        let done = f.tenants.backup(Actor::Cli, &to).expect("backs up");
327        assert_eq!(
328            done,
329            Backup {
330                tenants: 1,
331                versions: 1,
332                tries: 2
333            }
334        );
335        assert_whole(&opened(&f, &to), 1, f.clock.now());
336        let dirs = f.fs.list(&to.join("tenants")).expect("list");
337        assert_eq!(
338            dirs.len(),
339            1,
340            "no directory is left for the removed tenant: {dirs:?}"
341        );
342    }
343
344    #[test]
345    fn a_tenant_removed_while_its_data_is_copied_starts_the_backup_again() {
346        let f = fixture();
347        let [acme, _] = two(&f);
348        // Another registry on the same directory, as the server would be,
349        // removes the tenant while this one copies its files: after the
350        // tenant's catalog is copied, before its object files are.
351        let server =
352            Tenants::open_beside(f.dir.path(), f.master_key(), f.fs.clone(), f.clock.clone())
353                .expect("a second registry");
354        let once = std::sync::Mutex::new(Some(server));
355        f.tenants
356            .store(acme)
357            .expect("store")
358            .on_backup_copied(Box::new(move |_: &crate::store::Store| {
359                if let Some(server) = once.lock().expect("once").take() {
360                    server
361                        .remove(Actor::Cli, acme, Removal::Force)
362                        .expect("removes");
363                }
364            }));
365        let to = f.dir.path().join("backup");
366        let done = f.tenants.backup(Actor::Cli, &to).expect("backs up");
367        assert_eq!(
368            done,
369            Backup {
370                tenants: 1,
371                versions: 1,
372                tries: 2
373            },
374            "the second try copies the one tenant left and its one version"
375        );
376        assert_whole(&opened(&f, &to), 1, f.clock.now());
377        let dirs = f.fs.list(&to.join("tenants")).expect("list");
378        assert_eq!(
379            dirs.len(),
380            1,
381            "the removed tenant's partial copy is gone: {dirs:?}"
382        );
383    }
384
385    #[test]
386    fn a_registry_that_keeps_changing_fails_after_its_tries_and_is_recorded() {
387        let f = fixture();
388        let [acme, _] = two(&f);
389        let calls = Arc::new(AtomicUsize::new(0));
390        let seen = calls.clone();
391        let listed = std::sync::Mutex::new(acme);
392        *f.tenants.hooks.registry_copied.lock().expect("hook") =
393            Some(Box::new(move |tenants: &Tenants| {
394                // Each try: a tenant the copy lists is removed before its
395                // data is copied, and a new one is made, which the next
396                // copy lists.
397                let n = seen.fetch_add(1, Ordering::SeqCst);
398                let mut listed = listed.lock().expect("listed");
399                tenants
400                    .remove(Actor::Cli, *listed, Removal::Force)
401                    .expect("removes");
402                *listed = tenants
403                    .create(Actor::Cli, &format!("brief {n}"), None)
404                    .expect("creates");
405            }));
406        let to = f.dir.path().join("backup");
407        assert_eq!(
408            f.tenants.backup(Actor::Cli, &to),
409            Err(BackupError::KeptChanging)
410        );
411        assert_eq!(calls.load(Ordering::SeqCst), crate::store::TRIES);
412        assert_eq!(records(&f, "backup")[0]["status"], 503);
413    }
414}