15.2. Preparing Consistent Backup Sources

A copy taken while files are changing is a copy of no particular moment. Databases mid-transaction, log files mid-append, and directories renamed under the reader's feet all produce copies that look fine and restore badly. This section builds the practice data - deliberately full of ownership, ACL, extended-attribute, and link detail that later sections must prove they preserved - and then makes it consistent two ways: by exporting through the application, and by snapshotting the storage underneath it.

15.2.1. Quiescing Services and Exporting Application Data

Quiescing means making the on-disk state consistent before reading it. The strongest form is application-level export: pg_dump asks PostgreSQL for a transactionally consistent snapshot of its data through the server's own machinery, and the resulting file is a restore unit that pg_restore understands. The weaker forms are flushing and pausing; the weakest is copying live files and hoping. The rule of thumb is: if the application has an export tool, use it for the data and use file backup for everything else.

The practice data lives on its own volume so the snapshot exercise later has a clean target. On client1, as root, build it - this erases both of client1's practice disks:

# wipefs -a /dev/vdb /dev/vdc

wipefs removes any old signatures and prints nothing; both of client1's practice disks are cleared now, and /dev/vdc stays blank until Section 15.7.1 builds the recovery target on it.

# pvcreate /dev/vdb
  Physical volume "/dev/vdb" successfully created.
# vgcreate backupvg /dev/vdb
  Volume group "backupvg" successfully created
# lvcreate -L 2G -n appdata backupvg
  Logical volume "appdata" created.

The volume group and 2 GiB logical volume follow the LVM procedures from Chapter 13.

# mkfs.ext4 -L appdata /dev/backupvg/appdata
Creating filesystem with 524288 4k blocks and 131072 inodes
Filesystem UUID: 58318db7-0d1f-45a3-b647-8327f7d98829
Superblock backups stored on blocks: 
    32768, 98304, 163840, 229376, 294912

Creating journal (16384 blocks): done
Writing superblocks and filesystem accounting information: done

Selected output; the redrawn progress counters and the version banner that mke2fs prints on standard error are omitted.

# mkdir -p /srv/appdata
# mount /dev/backupvg/appdata /srv/appdata

Both commands print nothing. Give the volume to john and create the practice directories, with deliberately different owners:

# chown john:john /srv/appdata
# install -d -o john -g john -m 755 /srv/appdata/reports /srv/appdata/config /srv/appdata/shared
# install -d -o postgres -g postgres -m 750 /srv/appdata/dumps

All three commands print nothing. install -d creates a directory with chosen ownership and mode in one step; reports, config, and shared belong to john, while dumps is writable only by the postgres account that will write the database export there.

Now create one configuration file that carries every metadata type this chapter later verifies. Create it empty with the service's ownership:

# install -o www-data -g www-data -m 0640 /dev/null /srv/appdata/config/app.conf

The command prints nothing. Write its contents with a redirection - the redirection writes to the file, not the terminal:

# printf "listen_addresses = localhost\nmax_connections = 100\n" >/srv/appdata/config/app.conf

The file now holds two lines; the command itself printed nothing. Add the deliberate metadata:

# setfacl -m u:john:r-- /srv/appdata/config/app.conf
# setfattr -n user.handbook -v chapter15 /srv/appdata/config/app.conf
# ln /srv/appdata/config/app.conf /srv/appdata/config/app.conf.bak
# ln -s app.conf /srv/appdata/config/app.conf.current
# chmod 2775 /srv/appdata/shared

Each command is silent. In order: a POSIX ACL gives john read access that the mode bits alone would not grant, with the ACL mask governing the entry's effective rights; a user extended attribute marks it; a hard link gives the same inode a second name; a symbolic link points at it; and the setgid bit on shared makes files created there inherit the directory's group, as Chapter 5 describes. On client1, in john's shell, add the report file that rides through every later backup and restore:

$ printf "quarterly report\n" >/srv/appdata/reports/quarterly.txt

The redirection writes the file; nothing appears in the terminal. Back in the root shell, set its ownership:

# chown john:www-data /srv/appdata/reports/quarterly.txt && chmod 0640 /srv/appdata/reports/quarterly.txt

Both parts are silent: the file now belongs to john and www-data with mode 0640. One more file, created and owned by john, exists only to be deleted later when mirroring semantics are tested:

$ printf "temporary\n" >/srv/appdata/reports/temporary.txt

The redirection writes the file; nothing appears in the terminal. Record the metadata baseline that every copy method must reproduce. On client1, as root:

# getfacl -p /srv/appdata/config/app.conf && getfattr -d /srv/appdata/config/app.conf && stat -c "%U:%G %a %h %n" /srv/appdata/config/app.conf /srv/appdata/config/app.conf.bak
# file: /srv/appdata/config/app.conf
# owner: www-data
# group: www-data
user::rw-
user:john:r--
group::r--
mask::r--
other::---

# file: srv/appdata/config/app.conf
user.handbook="chapter15"

www-data:www-data 640 2 /srv/appdata/config/app.conf
www-data:www-data 640 2 /srv/appdata/config/app.conf.bak

The compound runs three inspections: getfacl prints the ACL (the john:r-- entry with its mask), getfattr prints the extended attribute (getfattr reports paths relative to the root of the current directory, which is why the second header lacks the leading slash), and stat summarizes ownership, mode, and link count - 2 for both names of the hard-linked file. A backup that cannot reproduce all three lines produces a file the application cannot use.

Now the application data. Create a database and a small table in it. The postgresql package already created the postgres administrative account and a running cluster, and the examples run psql as that account. On client1, as root:

# sudo -u postgres psql -v ON_ERROR_STOP=1 -c "CREATE DATABASE inventory;"
CREATE DATABASE

Write the table definition as a file in john's workspace, on client1, in john's shell. The workspace holds the exclusion lists and practice files for the rest of the chapter, so make it the working directory once:

$ cd ~/debian-handbook/backup-restore

The command prints nothing. The here-document lines are typed as shown; the quoted delimiter SQL means the shell takes them literally, and the whole command prints nothing:

$ cat > inventory.sql <<'SQL'
CREATE TABLE parts (id integer PRIMARY KEY, name text NOT NULL, quantity integer NOT NULL);
INSERT INTO parts VALUES (1, 'bolt', 120), (2, 'nut', 300), (3, 'washer', 500);
SQL

Load it as the postgres account:

# sudo -u postgres psql -v ON_ERROR_STOP=1 -d inventory < /home/john/debian-handbook/backup-restore/inventory.sql
CREATE TABLE
INSERT 0 3

The redirection feeds the file to psql; three rows are inserted. Now the export - the piece that makes the database safely backupable while it runs:

# sudo -u postgres pg_dump -Fc -f /srv/appdata/dumps/inventory.dump inventory
Option Description
-Fc custom format: compressed, restored with pg_restore, and selectively restorable
-f PATH write the dump to this file instead of standard output

pg_dump prints nothing on success and leaves the export in the postgres-owned dumps directory. Confirm what the dump contains:

# sudo -u postgres pg_restore --list /srv/appdata/dumps/inventory.dump | grep 'TABLE DATA public parts'
3418; 0 16390 TABLE DATA public parts postgres

The pipeline runs pg_restore --list to print the dump's table of contents and grep to select the one line that matters: the parts table's data is in the file. Section 15.6.3 restores exactly this dump; the whole-root backup in Section 15.7 deliberately excludes PostgreSQL's live data directory and relies on this export instead.

15.2.2. Using Storage Snapshots as a Consistency Boundary

Application export is per-service work. A storage snapshot gives the same consistency benefit to everything on a volume at once: it fixes a read-only view of the filesystem at one instant, and the backup then reads the view instead of the changing original. On LVM, the view is a snapshot logical volume; Chapter 13 covers the mechanism, and Chapter 12 covers the snapshot equivalents on Btrfs.

Two facts govern the procedure. First, a snapshot is only as consistent as the filesystem was at the moment of its creation: fsfreeze flushes and blocks writes first, so the fixed view is not mid-write. Second, the snapshot's reserved space holds copies of every block the original changes afterwards - when that space is exhausted the snapshot is invalidated, so the freeze window is kept short and the snapshot is removed as soon as the backup has read it.

The freeze window, the snapshot fixed at that moment, and the backup reading the snapshot while the origin keeps changing.

Figure 15.2. A storage snapshot as a consistency boundary. Conceptual schematic; block mechanics are LVM copy-on-write.

On client1, as root, freeze the volume:

# fsfreeze -f /srv/appdata
Option Description
-f flush writes to the filesystem's storage and block new writes
-u unblock writes and resume the filesystem

The command prints nothing - and from this moment until the unfreeze, every write to /srv/appdata blocks. Take the snapshot immediately:

# lvcreate -s -L 512M -n appdata-snap /dev/backupvg/appdata
  Logical volume "appdata-snap" created.
Option Description
-s create a snapshot of the given origin logical volume
-L SIZE reserve this much copy-on-write space for blocks the origin changes
-n NAME name the snapshot volume

Then release the writers:

# fsfreeze -u /srv/appdata

The command is silent and writes resume; the total blocked window here was one command long. Mount the fixed view read-only:

# mkdir -p /mnt/appdata-snap
# mount -o ro /dev/backupvg/appdata-snap /mnt/appdata-snap

Both commands print nothing. Read from the view:

# ls -l /mnt/appdata-snap/reports
total 8
-rw-r----- 1 john www-data 17 Nov 21 00:20 quarterly.txt
-rw-rw-r-- 1 john john     10 Nov 21 00:20 temporary.txt

The snapshot holds exactly the state at the freeze moment - both report files, with their ownership intact. Confirm that the view and the original agree:

# cmp /srv/appdata/reports/quarterly.txt /mnt/appdata-snap/reports/quarterly.txt

cmp prints nothing when the two files are identical, which is the expected result here. The snapshot has served its purpose, so remove it before its reserved space can fill:

# umount /mnt/appdata-snap
# lvremove -f /dev/backupvg/appdata-snap
  Logical volume "appdata-snap" successfully removed.

umount is silent; lvremove -f removes the volume without an interactive confirmation prompt and reports success. The pattern to keep is the sequence itself: freeze, snapshot, unfreeze, read the snapshot, delete the snapshot. Production backup scripts run exactly this around their copy step, and Section 15.5.2 uses the same reasoning - a quiescent moment - when it copies a repository.

15.2.3. Excluding Virtual Filesystems, Caches, and Temporary Data

Whole-filesystem backups include directories that must not be copied. /proc, /sys, /dev, and /run are kernel interfaces, not files: their contents are the running system's state, they change while being read, and restoring them is meaningless. Caches and package downloads are safe to drop because they regenerate. A backup tool's own cache must be excluded so the backup does not back up its own scratch space. Write the exclusion list in john's workspace - still john's shell on client1, still inside ~/debian-handbook/backup-restore:

$ cat > exclude.txt <<'EOF'
/proc
/sys
/dev
/run
/tmp
/var/tmp
/var/cache/apt/archives
/var/lib/apt/lists
/home/john/.cache/borg
EOF

The here-document writes the file; nothing is printed.

Excluded path Why
/proc, /sys, /dev, /run virtual or stateful; not files on any disk
/tmp, /var/tmp scratch by definition
/var/cache/apt/archives, /var/lib/apt/lists regenerated by apt update; Chapter 6 rebuilds them
/home/john/.cache/borg the backup tool's own cache

Preview what a full-root copy would contain before committing to one. On client1, as root:

# rsync -aHAXS --numeric-ids --one-file-system --exclude-from=/home/john/debian-handbook/backup-restore/exclude.txt --dry-run --stats / /srv/root-preview

Number of files: 35,558 (reg: 28,178, dir: 3,459, link: 3,921)
Number of created files: 35,558 (reg: 28,178, dir: 3,459, link: 3,921)
Number of deleted files: 0
Number of regular files transferred: 28,172
Total file size: 1,128,151,407 bytes
Total transferred file size: 1,124,003,101 bytes
Literal data: 0 bytes
Matched data: 0 bytes
File list size: 0
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 1,077,846
Total bytes received: 110,536

sent 1,077,846 bytes  received 110,536 bytes  792,254.67 bytes/sec
total size is 1,128,151,407  speedup is 949.32 (DRY RUN)

--dry-run builds the complete transfer plan and the --stats summary without copying anything, so /srv/root-preview is never created. The two Number of files lines describe the planned tree - about 35,000 files and 1.1 GB even on this nearly empty system, with 3,921 symlinks, which is why metadata flags matter at this scale. --one-file-system keeps the plan off /srv/appdata, which is a separate mounted filesystem; Section 15.7.1 backs that volume with its own archive instead of letting the root archive silently include or miss it. A dry run like this one is the cheapest capacity-planning tool available: it converts an exclusion list into a file count and a byte count before any backup exists to be too small.