2021-06-10 19:16:23 +03:00
|
|
|
"""
|
|
|
|
|
Module with backup functions.
|
|
|
|
|
"""
|
|
|
|
|
import logging
|
|
|
|
|
import os
|
2021-06-21 08:27:18 +03:00
|
|
|
import shutil
|
2025-11-15 04:34:41 +00:00
|
|
|
import time
|
2021-11-12 02:53:21 +03:00
|
|
|
from datetime import datetime, timedelta
|
2026-08-03 22:00:21 +00:00
|
|
|
from typing import Dict, Optional, Iterable, Union
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
import fcntl
|
|
|
|
|
except ImportError:
|
|
|
|
|
# Not available on Windows. cli.py's own platform check reports this
|
|
|
|
|
# cleanly before any locking function here is ever called; importing
|
|
|
|
|
# fcntl lazily/optionally lets that check run instead of crashing at
|
|
|
|
|
# `from curateipsum import backup` time.
|
|
|
|
|
fcntl = None
|
2021-06-10 19:16:23 +03:00
|
|
|
|
2021-11-13 07:57:11 +03:00
|
|
|
from curateipsum import fs
|
2021-06-10 19:16:23 +03:00
|
|
|
|
2021-11-12 11:30:11 +03:00
|
|
|
BACKUP_ENT_FMT = "%Y%m%d_%H%M%S"
|
|
|
|
|
LOCK_FILE = ".backups_lock"
|
|
|
|
|
DELTA_DIR = ".backup_delta"
|
2023-05-06 23:06:15 -07:00
|
|
|
BACKUP_MARKER = ".backup_finished"
|
2026-08-03 21:30:39 +00:00
|
|
|
STAGING_PREFIX = ".incomplete-"
|
2021-06-10 19:16:23 +03:00
|
|
|
_lg = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
2026-08-03 21:30:39 +00:00
|
|
|
class BackupFailedError(Exception):
|
|
|
|
|
"""Raised when a backup could not be completed successfully.
|
|
|
|
|
|
|
|
|
|
Any failure while building a snapshot (copy error, parse error,
|
|
|
|
|
unsupported entry, nonzero subprocess exit) is fatal: the partially
|
|
|
|
|
built snapshot is discarded and this is the only way that failure is
|
|
|
|
|
reported to callers.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
2023-05-07 22:00:05 -07:00
|
|
|
def _get_backup_marker(
|
|
|
|
|
backup_entry: Union[os.DirEntry, fs.PseudoDirEntry]
|
|
|
|
|
) -> fs.PseudoDirEntry:
|
|
|
|
|
"""Return DirEntry for marker file of given backup."""
|
|
|
|
|
marker_name = "%s_%s" % (BACKUP_MARKER, backup_entry.name)
|
|
|
|
|
marker_path = os.path.join(backup_entry.path, marker_name)
|
|
|
|
|
return fs.PseudoDirEntry(path=marker_path)
|
|
|
|
|
|
|
|
|
|
|
2023-05-06 23:06:15 -07:00
|
|
|
def _is_backup(backup_entry: Union[os.DirEntry, fs.PseudoDirEntry]) -> bool:
|
|
|
|
|
"""Guess if backup_entry is a real backup."""
|
2023-05-07 22:00:05 -07:00
|
|
|
backup_marker = _get_backup_marker(backup_entry)
|
2023-05-06 23:06:15 -07:00
|
|
|
# if there is no marker file in the backup dir, it's not a backup
|
2023-05-07 22:00:05 -07:00
|
|
|
if not os.path.exists(backup_marker.path):
|
2023-05-06 23:06:15 -07:00
|
|
|
return False
|
|
|
|
|
# if there is only a marker file in the backup dir, it's not a backup
|
2023-05-07 22:00:05 -07:00
|
|
|
if os.listdir(backup_entry.path) == [backup_marker.name]:
|
2021-10-24 21:20:05 +03:00
|
|
|
return False
|
2021-06-10 19:16:23 +03:00
|
|
|
try:
|
2021-11-12 02:53:21 +03:00
|
|
|
datetime.strptime(backup_entry.name, BACKUP_ENT_FMT)
|
2021-06-10 19:16:23 +03:00
|
|
|
return True
|
|
|
|
|
except ValueError:
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
2023-05-06 23:06:15 -07:00
|
|
|
def _iterate_backups(backups_dir: str) -> Iterable[os.DirEntry]:
|
|
|
|
|
"""Iterate over backups in backups_dir."""
|
|
|
|
|
b_iter = os.scandir(backups_dir)
|
2021-11-12 02:53:21 +03:00
|
|
|
|
|
|
|
|
b_ent: os.DirEntry
|
|
|
|
|
for b_ent in b_iter:
|
2023-05-06 23:06:15 -07:00
|
|
|
if not _is_backup(b_ent):
|
2021-11-12 02:53:21 +03:00
|
|
|
continue
|
|
|
|
|
yield b_ent
|
|
|
|
|
|
|
|
|
|
b_iter.close()
|
|
|
|
|
|
|
|
|
|
|
2023-05-06 23:06:15 -07:00
|
|
|
def _get_latest_backup(backups_dir: str) -> Optional[os.DirEntry]:
|
|
|
|
|
"""Returns path to latest backup created in backups_dir or None."""
|
|
|
|
|
all_backups = sorted(_iterate_backups(backups_dir), key=lambda e: e.name)
|
2021-11-12 02:53:21 +03:00
|
|
|
if all_backups:
|
|
|
|
|
return all_backups[-1]
|
2021-06-10 19:16:23 +03:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
2023-05-06 23:06:15 -07:00
|
|
|
def _date_from_backup(backup_entry: os.DirEntry) -> datetime:
|
|
|
|
|
"""Returns datetime object from backup name."""
|
|
|
|
|
return datetime.strptime(backup_entry.name, BACKUP_ENT_FMT)
|
2021-11-12 02:53:21 +03:00
|
|
|
|
|
|
|
|
|
2026-08-03 22:00:21 +00:00
|
|
|
# Open lock file descriptors currently held by this process, keyed by the
|
|
|
|
|
# absolute path of the backups directory they lock. The kernel associates
|
|
|
|
|
# an flock() with this exact open file description, so the descriptor must
|
|
|
|
|
# stay open for the full duration of the operation: closing it (including
|
|
|
|
|
# on process crash or signal) is what releases the lock.
|
|
|
|
|
_held_locks: Dict[str, int] = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_LOCK_METADATA_MAX_BYTES = 256
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _read_lock_metadata(lock_file_path: str) -> str:
|
|
|
|
|
"""
|
|
|
|
|
Read lock file content for diagnostic logging only. Never raises, and
|
|
|
|
|
never trusted for anything beyond a human-readable log line: the read
|
|
|
|
|
is capped and newlines are stripped so a stale or forged lock file
|
|
|
|
|
can't inject bogus log lines or force an unbounded read.
|
|
|
|
|
"""
|
2023-05-06 23:06:15 -07:00
|
|
|
try:
|
2026-08-03 22:00:21 +00:00
|
|
|
with open(lock_file_path, "r") as f:
|
|
|
|
|
content = f.read(_LOCK_METADATA_MAX_BYTES)
|
|
|
|
|
except OSError:
|
|
|
|
|
return "<unreadable>"
|
|
|
|
|
return content.replace("\n", " ").replace("\r", " ").strip()
|
2021-11-12 11:30:11 +03:00
|
|
|
|
2023-05-06 23:06:15 -07:00
|
|
|
|
|
|
|
|
def set_backups_lock(backups_dir: str,
|
|
|
|
|
force: bool = False) -> bool:
|
|
|
|
|
"""
|
2026-08-03 22:00:21 +00:00
|
|
|
Acquire an exclusive kernel (flock) lock to prevent multiple backups
|
|
|
|
|
running at the same time. The lock file also holds the PID and start
|
|
|
|
|
time of the holder, kept for diagnostics only - they play no part in
|
|
|
|
|
deciding whether the lock can be acquired.
|
|
|
|
|
|
|
|
|
|
If another process already holds the lock:
|
|
|
|
|
- with force=False, return False immediately.
|
|
|
|
|
- with force=True, block until that process releases it (normal exit,
|
|
|
|
|
signal, or crash all release the kernel lock), then acquire it.
|
2023-05-06 23:06:15 -07:00
|
|
|
"""
|
2026-08-03 22:00:21 +00:00
|
|
|
backups_dir_abs = os.path.abspath(backups_dir)
|
|
|
|
|
if backups_dir_abs in _held_locks:
|
|
|
|
|
_lg.error("This process already holds the backup lock for %s",
|
|
|
|
|
backups_dir)
|
2025-11-15 04:34:41 +00:00
|
|
|
return False
|
|
|
|
|
|
2026-08-03 22:00:21 +00:00
|
|
|
lock_file_path = os.path.join(backups_dir_abs, LOCK_FILE)
|
|
|
|
|
|
|
|
|
|
fd = os.open(lock_file_path, os.O_CREAT | os.O_RDWR, 0o644)
|
|
|
|
|
|
|
|
|
|
flock_flags = fcntl.LOCK_EX if force else fcntl.LOCK_EX | fcntl.LOCK_NB
|
|
|
|
|
try:
|
|
|
|
|
fcntl.flock(fd, flock_flags)
|
|
|
|
|
except BlockingIOError:
|
|
|
|
|
held_by = _read_lock_metadata(lock_file_path)
|
|
|
|
|
_lg.warning(
|
|
|
|
|
"Previous backup is still in progress (%s), exiting", held_by
|
|
|
|
|
)
|
|
|
|
|
os.close(fd)
|
|
|
|
|
return False
|
|
|
|
|
except OSError as err:
|
|
|
|
|
_lg.error("Failed to acquire backup lock: %s", err)
|
|
|
|
|
os.close(fd)
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
# Lock acquired: replace metadata, it belongs to us now. If writing it
|
|
|
|
|
# fails, don't leave the lock held forever - release and report failure.
|
|
|
|
|
try:
|
|
|
|
|
os.ftruncate(fd, 0)
|
|
|
|
|
os.lseek(fd, 0, os.SEEK_SET)
|
|
|
|
|
metadata = "%d\n%s\n" % (os.getpid(), datetime.now().isoformat())
|
|
|
|
|
os.write(fd, metadata.encode())
|
|
|
|
|
os.fsync(fd)
|
|
|
|
|
except OSError as err:
|
|
|
|
|
_lg.error("Failed to write backup lock metadata: %s", err)
|
|
|
|
|
try:
|
|
|
|
|
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
|
|
|
finally:
|
|
|
|
|
os.close(fd)
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
_held_locks[backups_dir_abs] = fd
|
|
|
|
|
return True
|
2021-11-12 11:30:11 +03:00
|
|
|
|
|
|
|
|
|
2023-05-06 23:06:15 -07:00
|
|
|
def release_backups_lock(backups_dir: str):
|
2026-08-03 22:00:21 +00:00
|
|
|
"""
|
|
|
|
|
Release the kernel lock held by this process for backups_dir, if any.
|
|
|
|
|
Only releases a lock this process actually acquired via
|
|
|
|
|
set_backups_lock() - verified by looking up our own held descriptor,
|
|
|
|
|
never by trusting the lock file's on-disk content.
|
|
|
|
|
"""
|
|
|
|
|
backups_dir_abs = os.path.abspath(backups_dir)
|
|
|
|
|
fd = _held_locks.pop(backups_dir_abs, None)
|
|
|
|
|
if fd is None:
|
|
|
|
|
_lg.debug("No lock held by this process for %s, nothing to release",
|
|
|
|
|
backups_dir)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
|
|
|
finally:
|
|
|
|
|
os.close(fd)
|
|
|
|
|
# Deliberately not unlinking the lock file: flock() locks an inode, not
|
|
|
|
|
# a path. Unlinking it here while another process is blocked opening
|
|
|
|
|
# the same path (force=True) would let that process (or a third one)
|
|
|
|
|
# create a fresh inode at the same path and acquire an independent
|
|
|
|
|
# lock, defeating mutual exclusion. The file is small and harmless to
|
|
|
|
|
# leave in place; only its content (diagnostics) gets overwritten by
|
|
|
|
|
# whoever next holds the lock.
|
2021-11-12 11:30:11 +03:00
|
|
|
|
|
|
|
|
|
2023-05-06 23:06:15 -07:00
|
|
|
def set_backup_marker(backup_entry: Union[os.DirEntry, fs.PseudoDirEntry]):
|
|
|
|
|
"""Create finished backup marker file in backup's directory."""
|
2023-05-07 22:00:05 -07:00
|
|
|
backup_marker = _get_backup_marker(backup_entry)
|
|
|
|
|
if not os.path.exists(backup_marker.path):
|
|
|
|
|
open(backup_marker.path, "a").close()
|
2023-05-06 23:06:15 -07:00
|
|
|
|
|
|
|
|
|
2026-08-03 21:30:39 +00:00
|
|
|
_O_DIRECTORY = getattr(os, "O_DIRECTORY", 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _fsync_dir(path: str):
|
|
|
|
|
"""Fsync a directory so its content is durable before it is renamed."""
|
|
|
|
|
dir_fd = os.open(path, os.O_RDONLY | _O_DIRECTORY)
|
|
|
|
|
try:
|
|
|
|
|
os.fsync(dir_fd)
|
|
|
|
|
finally:
|
|
|
|
|
os.close(dir_fd)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _reserve_snapshot_name(backups_dir: str) -> str:
|
|
|
|
|
"""
|
|
|
|
|
Return a snapshot name that doesn't collide with an existing entry or
|
|
|
|
|
an in-progress staging directory. Guards against two backups started
|
|
|
|
|
within the same second.
|
|
|
|
|
"""
|
|
|
|
|
def _taken(candidate: str) -> bool:
|
|
|
|
|
return (os.path.lexists(os.path.join(backups_dir, candidate))
|
|
|
|
|
or os.path.lexists(os.path.join(
|
|
|
|
|
backups_dir, f"{STAGING_PREFIX}{candidate}")))
|
|
|
|
|
|
|
|
|
|
name = datetime.now().strftime(BACKUP_ENT_FMT)
|
|
|
|
|
while _taken(name):
|
|
|
|
|
time.sleep(1)
|
|
|
|
|
name = datetime.now().strftime(BACKUP_ENT_FMT)
|
|
|
|
|
return name
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def cleanup_stale_staging_dirs(backups_dir: str):
|
|
|
|
|
"""
|
|
|
|
|
Remove staging directories abandoned by a crashed or interrupted
|
|
|
|
|
backup run. Must be called before a new backup starts so a stale
|
|
|
|
|
staging directory can never be mistaken for a real snapshot.
|
|
|
|
|
"""
|
|
|
|
|
with os.scandir(backups_dir) as it:
|
|
|
|
|
entry: os.DirEntry
|
|
|
|
|
for entry in it:
|
|
|
|
|
if entry.name.startswith(STAGING_PREFIX) and entry.is_dir():
|
|
|
|
|
_lg.warning("Removing abandoned staging directory: %s",
|
|
|
|
|
entry.name)
|
|
|
|
|
shutil.rmtree(entry.path, ignore_errors=True)
|
|
|
|
|
|
|
|
|
|
|
2023-05-06 23:06:15 -07:00
|
|
|
def cleanup_old_backups(backups_dir: str,
|
|
|
|
|
dry_run: bool = False,
|
|
|
|
|
keep_all: int = 7,
|
|
|
|
|
keep_daily: int = 30,
|
|
|
|
|
keep_weekly: int = 52,
|
|
|
|
|
keep_monthly: int = 12,
|
|
|
|
|
keep_yearly: int = 5):
|
2021-11-12 02:53:21 +03:00
|
|
|
"""
|
|
|
|
|
Delete old backups. Never deletes the only backup.
|
2023-05-06 23:06:15 -07:00
|
|
|
For keep_* params threshold is inclusive, e.g.:
|
|
|
|
|
keep_weekly=1 being run on Thursday will keep one backup from this week and
|
|
|
|
|
one from the previous, even if the previous week's backup was created on
|
|
|
|
|
Monday.
|
|
|
|
|
keep_monthly=3 being run on any day of April will keep one backup from each
|
|
|
|
|
of months of January, February and March.
|
|
|
|
|
|
|
|
|
|
:param backups_dir: full path to backups directory.
|
|
|
|
|
:param dry_run: don't do anything.
|
|
|
|
|
:param keep_all:
|
|
|
|
|
up to this amount of days in the past all backups must be kept.
|
|
|
|
|
:param keep_daily:
|
|
|
|
|
up to this amount of days in the past one daily backup must be kept.
|
|
|
|
|
:param keep_weekly:
|
|
|
|
|
up to this amount of weeks in the past one weekly backup must be kept.
|
|
|
|
|
:param keep_monthly:
|
|
|
|
|
up to this amount of months in the past one monthly backup must be kept.
|
|
|
|
|
1 month is considered to be 30 days.
|
|
|
|
|
:param keep_yearly:
|
|
|
|
|
up to this amount of years in the past one yearly backup must be kept.
|
|
|
|
|
1 year is considered to be 365 days.
|
2021-11-12 02:53:21 +03:00
|
|
|
"""
|
2023-05-06 23:06:15 -07:00
|
|
|
all_backups = sorted(_iterate_backups(backups_dir),
|
2021-11-12 02:53:21 +03:00
|
|
|
key=lambda e: e.name, reverse=True)
|
|
|
|
|
if dry_run:
|
|
|
|
|
_lg.info("Dry-run, no backups will be actually removed")
|
|
|
|
|
if not all_backups:
|
|
|
|
|
_lg.debug("No backups, exiting")
|
|
|
|
|
return
|
2021-11-13 07:57:11 +03:00
|
|
|
if len(all_backups) == 1:
|
2021-11-12 02:53:21 +03:00
|
|
|
_lg.debug("Only one backup (%s) exists, will not remove it",
|
|
|
|
|
all_backups[0].name)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
now = datetime.now()
|
|
|
|
|
thresholds = {k: now.strftime(BACKUP_ENT_FMT)
|
|
|
|
|
for k in ("all", "daily", "weekly", "monthly", "yearly")}
|
|
|
|
|
if keep_all is not None:
|
|
|
|
|
thresholds["all"] = ((now - timedelta(days=keep_all))
|
|
|
|
|
.replace(hour=0, minute=0, second=0)
|
|
|
|
|
.strftime(BACKUP_ENT_FMT))
|
|
|
|
|
if keep_daily is not None:
|
|
|
|
|
thresholds["daily"] = ((now - timedelta(days=keep_daily))
|
|
|
|
|
.replace(hour=0, minute=0, second=0)
|
|
|
|
|
.strftime(BACKUP_ENT_FMT))
|
|
|
|
|
if keep_weekly is not None:
|
|
|
|
|
thresholds["weekly"] = (
|
|
|
|
|
(now - timedelta(weeks=keep_weekly, days=now.weekday()))
|
|
|
|
|
.strftime(BACKUP_ENT_FMT)
|
|
|
|
|
)
|
|
|
|
|
if keep_monthly is not None:
|
|
|
|
|
thresholds["monthly"] = ((now - timedelta(days=30*keep_monthly))
|
|
|
|
|
.replace(day=1, hour=0, minute=0, second=0)
|
|
|
|
|
.strftime(BACKUP_ENT_FMT))
|
|
|
|
|
if keep_yearly is not None:
|
|
|
|
|
thresholds["yearly"] = (
|
|
|
|
|
(now - timedelta(days=365*keep_yearly))
|
|
|
|
|
.replace(month=1, day=1, hour=0, minute=0, second=0)
|
|
|
|
|
.strftime(BACKUP_ENT_FMT)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
prev_backup = all_backups[0]
|
|
|
|
|
to_remove = {b: False for b in all_backups}
|
|
|
|
|
|
|
|
|
|
for backup in all_backups[1:]:
|
|
|
|
|
# skip all backups made after threshold
|
|
|
|
|
if backup.name > thresholds["all"]:
|
|
|
|
|
prev_backup = backup
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
# leave only one backup per day for backups made after threshold
|
|
|
|
|
if backup.name > thresholds["daily"]:
|
|
|
|
|
if (_date_from_backup(prev_backup).date()
|
|
|
|
|
== _date_from_backup(backup).date()):
|
|
|
|
|
to_remove[prev_backup] = True
|
|
|
|
|
prev_backup = backup
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
# leave only one backup per week for backups made after threshold
|
|
|
|
|
if backup.name > thresholds["weekly"]:
|
|
|
|
|
if (_date_from_backup(prev_backup).isocalendar()[1]
|
|
|
|
|
== _date_from_backup(backup).isocalendar()[1]):
|
|
|
|
|
to_remove[prev_backup] = True
|
|
|
|
|
prev_backup = backup
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
# leave only one backup per month for backups made after threshold
|
|
|
|
|
if backup.name > thresholds["monthly"]:
|
|
|
|
|
if (_date_from_backup(prev_backup).date().replace(day=1)
|
|
|
|
|
== _date_from_backup(backup).date().replace(day=1)):
|
|
|
|
|
to_remove[prev_backup] = True
|
|
|
|
|
prev_backup = backup
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
# leave only one backup per year for backups made after threshold
|
|
|
|
|
if backup.name > thresholds["yearly"]:
|
|
|
|
|
if (_date_from_backup(prev_backup).date().replace(month=1, day=1)
|
|
|
|
|
== _date_from_backup(backup).date().replace(month=1, day=1)):
|
|
|
|
|
to_remove[prev_backup] = True
|
|
|
|
|
prev_backup = backup
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
to_remove[backup] = True
|
|
|
|
|
|
|
|
|
|
for backup, do_delete in to_remove.items():
|
2023-05-06 23:06:15 -07:00
|
|
|
if do_delete:
|
|
|
|
|
if dry_run:
|
|
|
|
|
_lg.info("Would remove old backup %s", backup.name)
|
|
|
|
|
else:
|
|
|
|
|
_lg.info("Removing old backup %s", backup.name)
|
|
|
|
|
shutil.rmtree(backup.path)
|
2021-11-12 02:53:21 +03:00
|
|
|
|
|
|
|
|
|
2023-05-06 23:06:15 -07:00
|
|
|
def process_backed_entry(backup_dir: str,
|
|
|
|
|
entry_relpath: str,
|
|
|
|
|
action: fs.Actions,
|
|
|
|
|
msg: str):
|
|
|
|
|
"""
|
|
|
|
|
Additional processing of backed up DirEntry (file/dir/symlink).
|
|
|
|
|
Actions:
|
|
|
|
|
- if DirEntry was not deleted, hardlink it to DELTA_DIR.
|
|
|
|
|
"""
|
2021-11-15 22:36:09 +03:00
|
|
|
_lg.debug("%s %s %s", action, entry_relpath, msg)
|
|
|
|
|
if action not in (fs.Actions.ERROR, fs.Actions.DELETE):
|
2021-11-09 00:43:18 +03:00
|
|
|
fs.nest_hardlink(src_dir=backup_dir, src_relpath=entry_relpath,
|
|
|
|
|
dst_dir=os.path.join(backup_dir, DELTA_DIR))
|
|
|
|
|
|
|
|
|
|
|
2021-06-23 20:11:42 +03:00
|
|
|
def initiate_backup(sources,
|
2023-05-06 23:06:15 -07:00
|
|
|
backups_dir: str,
|
2021-06-23 20:11:42 +03:00
|
|
|
dry_run: bool = False,
|
2021-10-24 21:20:05 +03:00
|
|
|
external_rsync: bool = False,
|
2026-08-03 21:30:39 +00:00
|
|
|
external_hardlink: bool = False
|
|
|
|
|
) -> Optional[fs.PseudoDirEntry]:
|
2023-05-06 23:06:15 -07:00
|
|
|
"""
|
|
|
|
|
Main backup function.
|
2026-08-03 21:30:39 +00:00
|
|
|
Builds the new snapshot in a private ".incomplete-<name>" staging
|
|
|
|
|
directory, copying data from the latest backup and then syncing data
|
|
|
|
|
from sources. Any failure is fatal: the staging directory is discarded
|
|
|
|
|
and BackupFailedError is raised, so a failed or interrupted backup can
|
|
|
|
|
never be mistaken for a successful one. On success, the staging
|
|
|
|
|
directory is fsync'd and atomically renamed into its final snapshot
|
|
|
|
|
name.
|
2023-05-06 23:06:15 -07:00
|
|
|
:param sources: list of directories to backup (relative paths ok)
|
|
|
|
|
:param backups_dir: directory where all backups are stored
|
|
|
|
|
:param dry_run: if True, no actual changes will be made
|
|
|
|
|
:param external_rsync: if True, use external rsync instead of python
|
|
|
|
|
:param external_hardlink: if True, use external hardlink instead of python
|
2026-08-03 21:30:39 +00:00
|
|
|
:return: DirEntry-like object of the created snapshot, or None if no
|
|
|
|
|
snapshot was created (dry-run or no changes since last backup).
|
|
|
|
|
:raises BackupFailedError: if the backup could not be completed.
|
2023-05-06 23:06:15 -07:00
|
|
|
"""
|
2026-08-03 21:30:39 +00:00
|
|
|
cleanup_stale_staging_dirs(backups_dir)
|
2021-06-10 19:16:23 +03:00
|
|
|
|
2026-08-03 21:30:39 +00:00
|
|
|
snapshot_name = _reserve_snapshot_name(backups_dir)
|
|
|
|
|
staging = fs.PseudoDirEntry(
|
|
|
|
|
os.path.join(backups_dir, f"{STAGING_PREFIX}{snapshot_name}")
|
|
|
|
|
)
|
|
|
|
|
_lg.debug("Staging directory: %s", staging.path)
|
2021-06-10 19:16:23 +03:00
|
|
|
|
2023-05-06 23:06:15 -07:00
|
|
|
latest_backup = _get_latest_backup(backups_dir)
|
2021-06-10 19:16:23 +03:00
|
|
|
|
|
|
|
|
if latest_backup is None:
|
2026-08-03 21:30:39 +00:00
|
|
|
_lg.info("Creating empty staging directory for backup: %s",
|
|
|
|
|
snapshot_name)
|
|
|
|
|
try:
|
|
|
|
|
os.mkdir(staging.path)
|
|
|
|
|
except OSError as err:
|
|
|
|
|
raise BackupFailedError(
|
|
|
|
|
"Failed to create staging directory %s: %s"
|
|
|
|
|
% (staging.path, err)
|
|
|
|
|
) from err
|
2021-06-19 15:28:42 +03:00
|
|
|
|
2021-11-12 02:53:21 +03:00
|
|
|
else:
|
2026-08-03 21:30:39 +00:00
|
|
|
_lg.info("Copying data from latest backup %s to staging for %s",
|
|
|
|
|
latest_backup.name, snapshot_name)
|
2021-11-12 02:53:21 +03:00
|
|
|
|
|
|
|
|
hl_res = fs.hardlink_dir(src_dir=latest_backup.path,
|
2026-08-03 21:30:39 +00:00
|
|
|
dst_dir=staging.path,
|
2021-10-24 21:20:05 +03:00
|
|
|
use_external=external_hardlink)
|
2021-06-21 10:20:45 +03:00
|
|
|
if not hl_res:
|
2023-05-06 23:06:15 -07:00
|
|
|
_lg.error("Something went wrong during copying data from latest"
|
2026-08-03 21:30:39 +00:00
|
|
|
" backup, removing staging directory for %s",
|
|
|
|
|
snapshot_name)
|
|
|
|
|
shutil.rmtree(staging.path, ignore_errors=True)
|
|
|
|
|
raise BackupFailedError(
|
|
|
|
|
"Failed to copy data from latest backup %s"
|
|
|
|
|
% latest_backup.name
|
|
|
|
|
)
|
2021-06-21 10:24:53 +03:00
|
|
|
|
2023-05-07 22:00:05 -07:00
|
|
|
# remove backup markers from copied backup
|
2026-08-03 21:30:39 +00:00
|
|
|
for fname in os.listdir(staging.path):
|
2023-05-07 22:00:05 -07:00
|
|
|
if fname.startswith(BACKUP_MARKER):
|
2026-08-03 21:30:39 +00:00
|
|
|
os.remove(os.path.join(staging.path, fname))
|
2023-05-07 22:00:05 -07:00
|
|
|
|
2021-11-09 00:43:18 +03:00
|
|
|
# clean up delta dir from copied backup
|
2026-08-03 21:30:39 +00:00
|
|
|
shutil.rmtree(os.path.join(staging.path, DELTA_DIR),
|
2023-05-06 23:06:15 -07:00
|
|
|
ignore_errors=True)
|
2021-11-09 00:43:18 +03:00
|
|
|
|
2021-06-23 20:11:42 +03:00
|
|
|
rsync_func = fs.rsync_ext if external_rsync else fs.rsync
|
|
|
|
|
|
2021-11-09 22:51:49 +03:00
|
|
|
backup_changed = False
|
2026-08-03 21:30:39 +00:00
|
|
|
try:
|
|
|
|
|
for src in sources:
|
|
|
|
|
src_abs = os.path.abspath(src)
|
|
|
|
|
src_name = os.path.basename(src_abs)
|
|
|
|
|
dst_abs = os.path.join(staging.path, src_name)
|
|
|
|
|
_lg.info("Backing up directory %s to staging for %s",
|
|
|
|
|
src_abs, snapshot_name)
|
2023-05-06 23:06:15 -07:00
|
|
|
for entry_relpath, action, msg in rsync_func(
|
|
|
|
|
src_abs, dst_abs, dry_run=dry_run
|
|
|
|
|
):
|
2026-08-03 21:30:39 +00:00
|
|
|
if action == fs.Actions.ERROR:
|
|
|
|
|
raise BackupFailedError(
|
|
|
|
|
"Failed to copy %s: %s" % (entry_relpath, msg)
|
|
|
|
|
)
|
2023-05-06 23:06:15 -07:00
|
|
|
# TODO maybe should be run if first backup too?
|
2021-11-15 22:36:09 +03:00
|
|
|
if latest_backup is not None:
|
|
|
|
|
process_backed_entry(
|
2026-08-03 21:30:39 +00:00
|
|
|
backup_dir=staging.path,
|
2021-11-15 22:36:09 +03:00
|
|
|
entry_relpath=os.path.join(src_name, entry_relpath),
|
|
|
|
|
action=action,
|
|
|
|
|
msg=msg,
|
|
|
|
|
)
|
2023-05-06 23:06:15 -07:00
|
|
|
# raise flag if something was changed since last backup
|
2021-11-15 22:36:09 +03:00
|
|
|
backup_changed = True
|
2026-08-03 21:30:39 +00:00
|
|
|
except fs.BackupCreationError as err:
|
|
|
|
|
_lg.error("Error during backup creation: %s", err)
|
|
|
|
|
_lg.error("Failed to create backup %s, removing staging directory",
|
|
|
|
|
snapshot_name)
|
|
|
|
|
shutil.rmtree(staging.path, ignore_errors=True)
|
|
|
|
|
raise BackupFailedError(str(err)) from err
|
|
|
|
|
except BackupFailedError:
|
|
|
|
|
_lg.error("Failed to create backup %s, removing staging directory",
|
|
|
|
|
snapshot_name)
|
|
|
|
|
shutil.rmtree(staging.path, ignore_errors=True)
|
|
|
|
|
raise
|
2021-11-09 22:51:49 +03:00
|
|
|
|
|
|
|
|
# do not create backup on dry-run
|
2021-06-21 08:27:18 +03:00
|
|
|
if dry_run:
|
2026-08-03 21:30:39 +00:00
|
|
|
_lg.info("Dry-run, removing staging directory: %s", snapshot_name)
|
|
|
|
|
shutil.rmtree(staging.path, ignore_errors=True)
|
|
|
|
|
return None
|
2021-11-09 22:51:49 +03:00
|
|
|
# do not create backup if no change from previous one
|
2026-08-03 21:30:39 +00:00
|
|
|
if latest_backup is not None and not backup_changed:
|
|
|
|
|
_lg.info("Staged backup is the same as previous one %s, removing",
|
|
|
|
|
latest_backup.name)
|
|
|
|
|
shutil.rmtree(staging.path, ignore_errors=True)
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
# write and fsync completion marker only after every source succeeded,
|
|
|
|
|
# then atomically rename the staging dir into its final snapshot name
|
|
|
|
|
marker_name = "%s_%s" % (BACKUP_MARKER, snapshot_name)
|
|
|
|
|
marker_fd = os.open(os.path.join(staging.path, marker_name),
|
|
|
|
|
os.O_CREAT | os.O_WRONLY, 0o644)
|
|
|
|
|
try:
|
|
|
|
|
os.fsync(marker_fd)
|
|
|
|
|
finally:
|
|
|
|
|
os.close(marker_fd)
|
|
|
|
|
_fsync_dir(staging.path)
|
|
|
|
|
|
|
|
|
|
final_path = os.path.join(backups_dir, snapshot_name)
|
|
|
|
|
os.rename(staging.path, final_path)
|
|
|
|
|
_fsync_dir(backups_dir)
|
|
|
|
|
_lg.info("Backup created: %s", snapshot_name)
|
|
|
|
|
return fs.PseudoDirEntry(final_path)
|