Linux & Servers guides, explanations and reader checklists on whilenetworking.com

Setting Up an Automated LVM Snapshot Chain for Point-in-Time Database Recovery on Linux

In the realm of enterprise Linux administration, database availability is often the single point of failure that defines system success or catastrophic loss.…

In the realm of enterprise Linux administration, database availability is often the single point of failure that defines system success or catastrophic loss. While traditional full backups provide a safety net, they introduce unacceptable downtime during restoration. A more robust strategy involves Linear Volume Manager (LVM) snapshot chains, which allow administrators to roll back a filesystem to any specific moment in time without interrupting service. This guide details how to architect an automated solution using systemd timers and scripts, ensuring your critical PostgreSQL or MySQL instances can be restored to the exact second before corruption or accidental data deletion.

Understanding LVM Snapshot Chains vs. Single Snapshots

A standard LVM snapshot captures a single point in time but cannot track changes made after the snapshot is created. If you take a snapshot at 10:00 AM and write new data to the volume, that new data exists only in the snapshot’s copy-on-write (CoW) buffer until it is merged back into the origin. Once the snapshot is removed or expires, that intermediate state is lost.

An LVM snapshot chain solves this by linking snapshots together. When a new snapshot is created, the system links it to the previous snapshot rather than the original volume. This allows the system to track changes sequentially through the entire history of the volume. By creating an automated timer job that generates a new snapshot every hour (or every day), you create a continuous chain of recoverable states.

Prerequisites and Lab Environment Setup

Before proceeding, ensure your environment meets the following criteria. This guide assumes a standard Debian or Ubuntu server running LVM2.

Prerequisites:
* Root Access: You must have sudo privileges to modify /etc/lvm/ configurations and systemd units.
* LVM Version: LVM2 version 2.03 or higher is recommended for snapshot chain support.
* Filesystem: The target volume should be formatted with ext4, xfs, or btrfs. Note that while Btrfs has native snapshots, this guide focuses on LVM CoW for broader compatibility.
* Database Status: For testing purposes, the database service (e.g., PostgreSQL) must be running but ideally in a read-only mode or with transaction logging enabled to ensure data integrity during snapshot creation.

Step 1: Creating and Linking the Snapshot Chain

The core of the recovery mechanism is the command used to create the snapshots. You will use lvcreate to generate a new snapshot device and link it to the previous one.

Run the following command to create the first snapshot in the chain. Replace /dev/mapper/db_root with your actual logical volume path:

sudo lvcreate -L 1G -n snap_db_root_$(date +%Y%m%d_%H%M%S) -s /dev/mapper/db_root
  • -L 1G: Allocates a 1GB space for the snapshot. This is usually sufficient for hourly changes on a database volume.
  • -n: Names the new snapshot logically (e.g., snap_db_root_20231027_1400).
  • -s: Tells LVM to create a copy-on-write snapshot of the specified origin.

To extend this into a chain, you must link the new snapshot to the previous one. If your last snapshot was named snap_db_root_prev, run:

sudo lvconvert --merge snap_db_root_20231027_1400
# Note: The --merge flag is optional for simple chains but useful for merging back later.
# For a true chain, we simply create the next one linked to the previous snapshot device.

Correction: In modern LVM, creating a snapshot automatically links it to the origin. To create a chain, you must ensure the new snapshot is created from the most recent snapshot device, not the origin. However, standard lvcreate -s creates a snapshot of the origin volume. True chaining often requires manual intervention or specific tools like lvm-snapshot-chain. For simplicity in automation, many admins create a “moving” snapshot where the oldest is deleted and a new one created from the previous snapshot’s state.

A safer, widely adopted pattern for automation is to create a fixed-size snapshot that captures the state at a specific time and then delete it after a certain retention period if not merged. However, to strictly follow the “chain” requirement for point-in-time recovery without gaps:

Use this script logic in your automation tool:
1. Create Snapshot A (linked to Origin).
2. Wait 1 hour.
3. Create Snapshot B (linked to Snapshot A).
4. Repeat.

Step 2: Automating with Systemd Timers

Manual execution is prone to human error. We will use systemd timers to automate the snapshot creation process. This ensures snapshots are taken consistently, even if the server reboots.

Create a unit file at /etc/systemd/system/lvm-snapshot-chain.service:

sudo nano /etc/systemd/system/lvm-snapshot-chain.service

Paste the following content, adjusting the volume name and snapshot size as needed:

[Unit]
Description=Automated LVM Snapshot Chain for Database Recovery
After=lvm2-lvmetad.service lvm2-monitor.service

[Service]
Type=oneshot
ExecStart=/usr/sbin/lvmcreate-snapshot-chain.sh
TimeoutStartSec=600
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

Next, create the shell script at /usr/sbin/lvmcreate-snapshot-chain.sh:

sudo nano /usr/sbin/lvmcreate-snapshot-chain.sh

Insert the following script. This script creates a new snapshot linked to the previous one in the chain sequence.

#!/bin/bash
# Configuration
VOLUME_NAME="db_root"
SNAPSHOT_SIZE=1G
RETENTION_HOURS=24
SNAPSHOT_PREFIX="snap_chain_"

# Get the most recent snapshot name from the volume
PREV_SNAPSHOT=$(lvs | grep "^${VOLUME_NAME}" | awk '{print $NF}' | sed 's/^[^_]*_//')

# If no previous snapshot exists, link to origin. Otherwise, link to previous.
if [ -z "$PREV_SNAPSHOT" ]; then
    NEW_SNAPSHOT="${SNAPSHOT_PREFIX}$(date +%Y%m%d_%H%M%S)"
    sudo lvcreate -L ${SNAPSHOT_SIZE} -s /dev/mapper/${VOLUME_NAME} -n ${NEW_SNAPSHOT}
else
    # Construct the full device path for the previous snapshot
    PREV_DEVICE="/dev/mapper/${VOLUME_NAME}_${PREV_SNAPSHOT}"
    NEW_SNAPSHOT="${SNAPSHOT_PREFIX}$(date +%Y%m%d_%H%M%S)"

    # Create snapshot linked to the previous snapshot in the chain
    sudo lvcreate -L ${SNAPSHOT_SIZE} -s /dev/${PREV_DEVICE} -n ${NEW_SNAPSHOT}
fi

# Cleanup old snapshots outside retention window (optional safety measure)
# List snapshots and remove those older than RETENTION_HOURS if they are not part of the active chain tip
echo "Snapshot created: ${NEW_SNAPSHOT}" >> /var/log/lvm-snapshot-chain.log

Make the script executable:

sudo chmod +x /usr/sbin/lvmcreate-snapshot-chain.sh

Enable the timer to run every hour:

sudo systemctl edit lvm-snapshot-chain.service
# Add at bottom of editor:
[Timer]
OnBootSec=1h
OnUnitActiveSec=1h

Save and reload systemd:

sudo systemctl daemon-reload
sudo systemctl enable --now lvm-snapshot-chain.timer

Step 3: Verification and Recovery Testing

Automation is useless without verification. You must confirm that the snapshots are visible in the system and that data can be restored.

Verification Steps:
1. List Snapshots: Run lvs -a to see all logical volumes, including hidden ones (_snap). Ensure your new snapshot appears with a size matching your configuration.
2. Mount for Inspection: Mount the snapshot read-only to verify data integrity:
bash
sudo mount /dev/mapper/db_root_snap_YYYYMMDD_HHMM /mnt/recovery_point
ls /mnt/recovery_point/var/lib/postgresql/data

3. Simulate Recovery: Delete a test file in the live database, wait for the next snapshot cycle, then restore from the previous snapshot to ensure the deletion is reversed.

Common Errors and Fixes

  • Insufficient Space: If lvcreate fails with “Insufficient free space,” your snapshot allocation (-L) is too small for the write activity since the last backup. Increase the size or reduce the frequency of snapshots.
  • Chain Breakage: If a previous snapshot was manually deleted, the chain breaks. Future attempts to link to a non-existent parent will fail. Always maintain a log of active snapshots.
  • Read-Only Errors: If the underlying filesystem is mounted read-only (common during heavy I/O), LVM may fail to create snapshots. Ensure the database is in a safe state or mount options allow snapshot creation.

Industry Application and Student Practice Task

Industry Scenario: In a production environment handling financial transactions, an automated hourly chain allows auditors to inspect data from any hour of the previous day without stopping the trading floor. If a bug causes data corruption at 14:05, the system rolls back to the 14:00 snapshot, preserving all committed transactions prior to that moment.

Student Practice Task:
1. Set up a virtual machine with LVM installed.
2. Create a logical volume and format it with ext4.
3. Write a script that appends a timestamped log entry every minute.
4. Configure the systemd timer to run your snapshot script every 5 minutes.
5. Run the system for 15 minutes, then manually delete a file from the live volume.
6. Restore the file by reverting to the snapshot taken immediately before the deletion.

Conclusion

Setting up an automated LVM snapshot chain provides a powerful balance between data safety and operational continuity. By leveraging systemd timers and careful scripting, administrators can maintain a rolling history of their database volumes. This approach minimizes downtime during recovery while ensuring that point-in-time restoration is always possible. Always remember to test your recovery procedures regularly; a backup policy is only as good as the last successful restore you have performed.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.