bdbackup 0.6.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bdbackup/__init__.py +15 -0
- bdbackup/backends.py +56 -0
- bdbackup/cli.py +1045 -0
- bdbackup/config.py +114 -0
- bdbackup/dboperations.py +88 -0
- bdbackup/engines.py +167 -0
- bdbackup/filebackup.py +305 -0
- bdbackup/history.py +180 -0
- bdbackup/mysql/__init__.py +26 -0
- bdbackup/mysql/helpers.py +50 -0
- bdbackup/mysql/mysqldump.py +161 -0
- bdbackup/mysql/xtrabackup.py +471 -0
- bdbackup/recovery.py +80 -0
- bdbackup/retention.py +636 -0
- bdbackup/scheduling.py +196 -0
- bdbackup/templates/__init__.py +163 -0
- bdbackup/templates/_matching.py +159 -0
- bdbackup/templates/python_dev.py +54 -0
- bdbackup/utils.py +58 -0
- bdbackup/validation.py +400 -0
- bdbackup-0.6.1.dist-info/METADATA +752 -0
- bdbackup-0.6.1.dist-info/RECORD +25 -0
- bdbackup-0.6.1.dist-info/WHEEL +4 -0
- bdbackup-0.6.1.dist-info/entry_points.txt +2 -0
- bdbackup-0.6.1.dist-info/licenses/LICENSE +21 -0
bdbackup/retention.py
ADDED
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
"""GFS (grandfather-father-son) retention policy for backup trees.
|
|
2
|
+
|
|
3
|
+
Tiered retention — every backup for the last N days, then one per ISO week
|
|
4
|
+
for N weeks, then one per calendar month for N months. Tiers are SEQUENTIAL,
|
|
5
|
+
not overlapping: the weekly tier only considers backups older than the daily
|
|
6
|
+
window, and the monthly tier only considers backups older than the weekly
|
|
7
|
+
range. Chain safety keeps incrementals restorable: an incremental is dropped
|
|
8
|
+
when its parent full is gone (orphan / broken chain), and a full that still
|
|
9
|
+
anchors a live incremental is pinned even past its tier ("chain anchor").
|
|
10
|
+
|
|
11
|
+
This module is the policy engine only. The ``bdbackup retention`` CLI command
|
|
12
|
+
and ``type = "retention"`` config jobs are thin wrappers over ``main()`` /
|
|
13
|
+
:func:`run_job` (see below); nothing here depends on backends or engines.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import calendar
|
|
19
|
+
import fnmatch
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import sys
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from datetime import date, datetime, timedelta
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"BackupFile",
|
|
29
|
+
"Policy",
|
|
30
|
+
"human",
|
|
31
|
+
"looks_temporary",
|
|
32
|
+
"main",
|
|
33
|
+
"month_end",
|
|
34
|
+
"month_start",
|
|
35
|
+
"parse_timestamp_from_name",
|
|
36
|
+
"run_job",
|
|
37
|
+
"scan",
|
|
38
|
+
"shift_month",
|
|
39
|
+
"week_start",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
# Exit-code contract (mirrors bdbackup.cli: 2 usage, 3 refuses-empty).
|
|
43
|
+
EXIT_OK = 0
|
|
44
|
+
EXIT_DELETE_FAILURES = 1
|
|
45
|
+
EXIT_USAGE = 2
|
|
46
|
+
EXIT_REFUSED = 3
|
|
47
|
+
|
|
48
|
+
# Conservative defaults, matching the reference policy script.
|
|
49
|
+
DEFAULTS = {
|
|
50
|
+
"full_glob": "full_*.mbi",
|
|
51
|
+
"incr_glob": "incr_*.mbi",
|
|
52
|
+
"log_glob": "*.log",
|
|
53
|
+
"daily": 7,
|
|
54
|
+
"weekly": 4,
|
|
55
|
+
"monthly": 6,
|
|
56
|
+
"incr_days": 7,
|
|
57
|
+
"log_days": 30,
|
|
58
|
+
"pick": "first",
|
|
59
|
+
"min_keep_fulls": 2,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
# Markers for files still being written; matched as dot-separated components
|
|
63
|
+
# so both "full_x.mbi.tmp" and "full_x.tmp.mbi" are recognised.
|
|
64
|
+
IGNORE_TOKENS = frozenset(
|
|
65
|
+
{"tmp", "temp", "part", "partial", "inprogress", "incomplete", "lock", "writing", "new"}
|
|
66
|
+
)
|
|
67
|
+
GRACE_MINUTES = 60
|
|
68
|
+
USE_FILENAME_TIMESTAMP = True
|
|
69
|
+
|
|
70
|
+
# Never operate on these, ever.
|
|
71
|
+
FORBIDDEN_DIRS = frozenset(
|
|
72
|
+
{
|
|
73
|
+
"/",
|
|
74
|
+
"/bin",
|
|
75
|
+
"/boot",
|
|
76
|
+
"/dev",
|
|
77
|
+
"/etc",
|
|
78
|
+
"/home",
|
|
79
|
+
"/lib",
|
|
80
|
+
"/proc",
|
|
81
|
+
"/root",
|
|
82
|
+
"/sbin",
|
|
83
|
+
"/sys",
|
|
84
|
+
"/usr",
|
|
85
|
+
"/var",
|
|
86
|
+
}
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# Ordered most-specific first; each exposes named groups Y/m/d[/H/M/S].
|
|
90
|
+
_TS_PATTERNS = (
|
|
91
|
+
# 2026-07-29T14-30-00 / 2026-07-29_14-30-00 / 2026-07-29 14:30:00
|
|
92
|
+
re.compile(
|
|
93
|
+
r"(?P<Y>\d{4})[-_.](?P<m>\d{2})[-_.](?P<d>\d{2})"
|
|
94
|
+
r"[T_ -](?P<H>\d{2})[-:.]?(?P<M>\d{2})[-:.]?(?P<S>\d{2})"
|
|
95
|
+
),
|
|
96
|
+
# 20260729_143000 / 20260729-143000 / 20260729143000
|
|
97
|
+
re.compile(
|
|
98
|
+
r"(?P<Y>\d{4})(?P<m>\d{2})(?P<d>\d{2})"
|
|
99
|
+
r"[-_T]?(?P<H>\d{2})(?P<M>\d{2})(?P<S>\d{2})"
|
|
100
|
+
),
|
|
101
|
+
# 2026-07-29
|
|
102
|
+
re.compile(r"(?P<Y>\d{4})[-_.](?P<m>\d{2})[-_.](?P<d>\d{2})"),
|
|
103
|
+
# 20260729
|
|
104
|
+
re.compile(r"(?P<Y>\d{4})(?P<m>\d{2})(?P<d>\d{2})"),
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# --------------------------------------------------------------------------
|
|
109
|
+
# Filename timestamp parsing
|
|
110
|
+
# --------------------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def parse_timestamp_from_name(name: str) -> datetime | None:
|
|
114
|
+
"""Return a datetime parsed out of *name*, or None."""
|
|
115
|
+
for pattern in _TS_PATTERNS:
|
|
116
|
+
match = pattern.search(name)
|
|
117
|
+
if not match:
|
|
118
|
+
continue
|
|
119
|
+
parts = match.groupdict()
|
|
120
|
+
try:
|
|
121
|
+
stamp = datetime(
|
|
122
|
+
int(parts["Y"]),
|
|
123
|
+
int(parts["m"]),
|
|
124
|
+
int(parts["d"]),
|
|
125
|
+
int(parts.get("H") or 0),
|
|
126
|
+
int(parts.get("M") or 0),
|
|
127
|
+
int(parts.get("S") or 0),
|
|
128
|
+
)
|
|
129
|
+
except ValueError:
|
|
130
|
+
continue # e.g. matched 20261345 -- try the next pattern
|
|
131
|
+
# Reject obvious nonsense so a version number never becomes a date.
|
|
132
|
+
if 1990 <= stamp.year <= 2200:
|
|
133
|
+
return stamp
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# --------------------------------------------------------------------------
|
|
138
|
+
# Model
|
|
139
|
+
# --------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def looks_temporary(entry: str) -> bool:
|
|
143
|
+
"""True if *entry* looks like a file the backup job is still writing."""
|
|
144
|
+
lowered = entry.lower()
|
|
145
|
+
if lowered.startswith(".") or lowered.endswith("~"):
|
|
146
|
+
return True
|
|
147
|
+
return any(token in lowered.split(".") for token in IGNORE_TOKENS)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@dataclass(slots=True)
|
|
151
|
+
class BackupFile:
|
|
152
|
+
"""One file on disk, with the timestamp we make decisions from."""
|
|
153
|
+
|
|
154
|
+
path: str | Path
|
|
155
|
+
kind: str # "full" | "incr" | "log"
|
|
156
|
+
ts: datetime
|
|
157
|
+
size: int
|
|
158
|
+
ts_source: str # "name" | "mtime"
|
|
159
|
+
keep: bool = False
|
|
160
|
+
reason: str = "expired"
|
|
161
|
+
parent: BackupFile | None = None # for incrementals: the BackupFile full
|
|
162
|
+
|
|
163
|
+
def __post_init__(self) -> None:
|
|
164
|
+
self.path = Path(self.path)
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def name(self) -> str:
|
|
168
|
+
return self.path.name
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def day(self) -> date:
|
|
172
|
+
return self.ts.date()
|
|
173
|
+
|
|
174
|
+
def mark(self, reason: str) -> None:
|
|
175
|
+
"""Keeping wins over deleting; the first reason recorded is kept."""
|
|
176
|
+
if not self.keep:
|
|
177
|
+
self.keep = True
|
|
178
|
+
self.reason = reason
|
|
179
|
+
|
|
180
|
+
def __repr__(self) -> str:
|
|
181
|
+
return f"<{self.kind} {self.name} {self.ts}>"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def scan(
|
|
185
|
+
directory: str | Path,
|
|
186
|
+
glob_pattern: str,
|
|
187
|
+
kind: str,
|
|
188
|
+
now: datetime,
|
|
189
|
+
) -> tuple[list[BackupFile], list[tuple[Path, str]]]:
|
|
190
|
+
"""Collect BackupFile objects for *glob_pattern* inside *directory*."""
|
|
191
|
+
directory = Path(directory)
|
|
192
|
+
if not directory.is_dir():
|
|
193
|
+
raise NotADirectoryError(f"not a directory: {directory}")
|
|
194
|
+
|
|
195
|
+
real = os.path.realpath(directory).rstrip("/")
|
|
196
|
+
if real in {p.rstrip("/") for p in FORBIDDEN_DIRS}:
|
|
197
|
+
raise ValueError(f"refusing to operate on system directory: {real}")
|
|
198
|
+
|
|
199
|
+
grace = timedelta(minutes=GRACE_MINUTES)
|
|
200
|
+
files: list[BackupFile] = []
|
|
201
|
+
skipped: list[tuple[Path, str]] = []
|
|
202
|
+
|
|
203
|
+
for entry in sorted(os.listdir(directory)):
|
|
204
|
+
path = directory / entry
|
|
205
|
+
if not fnmatch.fnmatch(entry, glob_pattern):
|
|
206
|
+
continue
|
|
207
|
+
if looks_temporary(entry):
|
|
208
|
+
skipped.append((path, "temporary suffix"))
|
|
209
|
+
continue
|
|
210
|
+
if path.is_symlink():
|
|
211
|
+
skipped.append((path, "symlink"))
|
|
212
|
+
continue
|
|
213
|
+
if not path.is_file():
|
|
214
|
+
continue
|
|
215
|
+
|
|
216
|
+
try:
|
|
217
|
+
stat = path.stat()
|
|
218
|
+
except OSError as exc:
|
|
219
|
+
skipped.append((path, f"stat failed: {exc}"))
|
|
220
|
+
continue
|
|
221
|
+
|
|
222
|
+
mtime = datetime.fromtimestamp(stat.st_mtime)
|
|
223
|
+
ts = mtime
|
|
224
|
+
source = "mtime"
|
|
225
|
+
if USE_FILENAME_TIMESTAMP:
|
|
226
|
+
parsed = parse_timestamp_from_name(entry)
|
|
227
|
+
if parsed is not None:
|
|
228
|
+
ts = parsed
|
|
229
|
+
source = "name"
|
|
230
|
+
|
|
231
|
+
# Order matters: a future mtime must be reported as a clock problem,
|
|
232
|
+
# not silently absorbed by the grace window (now - mtime goes negative
|
|
233
|
+
# and would otherwise compare as inside the grace window).
|
|
234
|
+
if ts > now + timedelta(days=1) or mtime > now + grace:
|
|
235
|
+
skipped.append((path, "timestamp in the future -- check the clock"))
|
|
236
|
+
continue
|
|
237
|
+
if timedelta(0) <= now - mtime < grace:
|
|
238
|
+
skipped.append((path, f"inside {GRACE_MINUTES} min grace window"))
|
|
239
|
+
continue
|
|
240
|
+
|
|
241
|
+
files.append(BackupFile(path, kind, ts, stat.st_size, source))
|
|
242
|
+
|
|
243
|
+
files.sort(key=lambda f: (f.ts, f.name))
|
|
244
|
+
return files, skipped
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# --------------------------------------------------------------------------
|
|
248
|
+
# Bucket helpers
|
|
249
|
+
# --------------------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def week_start(day: date) -> date:
|
|
253
|
+
"""Monday of the ISO week containing *day*."""
|
|
254
|
+
return day - timedelta(days=day.weekday())
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def month_start(day: date) -> date:
|
|
258
|
+
return date(day.year, day.month, 1)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def shift_month(day: date, months_back: int) -> date:
|
|
262
|
+
"""First day of the month *months_back* months before *day*'s month."""
|
|
263
|
+
total = (day.year * 12 + (day.month - 1)) - months_back
|
|
264
|
+
year, month = divmod(total, 12)
|
|
265
|
+
return date(year, month + 1, 1)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def month_end(first_of_month: date) -> date:
|
|
269
|
+
last = calendar.monthrange(first_of_month.year, first_of_month.month)[1]
|
|
270
|
+
return date(first_of_month.year, first_of_month.month, last)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def pick(bucket_files: list[BackupFile], mode: str) -> BackupFile | None:
|
|
274
|
+
"""Choose the survivor inside a bucket (files already sorted by ts)."""
|
|
275
|
+
if not bucket_files:
|
|
276
|
+
return None
|
|
277
|
+
return bucket_files[0] if mode == "first" else bucket_files[-1]
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# --------------------------------------------------------------------------
|
|
281
|
+
# The policy
|
|
282
|
+
# --------------------------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
@dataclass(slots=True)
|
|
286
|
+
class Policy:
|
|
287
|
+
"""GFS tier settings + selection over a scanned set of files."""
|
|
288
|
+
|
|
289
|
+
daily_days: int = DEFAULTS["daily"]
|
|
290
|
+
weekly: int = DEFAULTS["weekly"]
|
|
291
|
+
monthly: int = DEFAULTS["monthly"]
|
|
292
|
+
incr_days: int = DEFAULTS["incr_days"]
|
|
293
|
+
log_days: int = DEFAULTS["log_days"]
|
|
294
|
+
bucket_pick: str = DEFAULTS["pick"]
|
|
295
|
+
min_keep_fulls: int = DEFAULTS["min_keep_fulls"]
|
|
296
|
+
|
|
297
|
+
# -- window boundaries -------------------------------------------------
|
|
298
|
+
|
|
299
|
+
def daily_floor(self, today: date) -> date:
|
|
300
|
+
"""Oldest date still inside the 'keep everything' window."""
|
|
301
|
+
return today - timedelta(days=self.daily_days - 1)
|
|
302
|
+
|
|
303
|
+
def weekly_buckets(self, today: date) -> list[tuple[date, date]]:
|
|
304
|
+
"""[(start, end)] for the N ISO weeks preceding the current one."""
|
|
305
|
+
current_monday = week_start(today)
|
|
306
|
+
buckets = []
|
|
307
|
+
for i in range(1, self.weekly + 1):
|
|
308
|
+
start = current_monday - timedelta(weeks=i)
|
|
309
|
+
buckets.append((start, start + timedelta(days=6)))
|
|
310
|
+
return buckets
|
|
311
|
+
|
|
312
|
+
def weekly_floor(self, today: date) -> date:
|
|
313
|
+
buckets = self.weekly_buckets(today)
|
|
314
|
+
return buckets[-1][0] if buckets else self.daily_floor(today)
|
|
315
|
+
|
|
316
|
+
def monthly_buckets(self, today: date) -> list[tuple[date, date]]:
|
|
317
|
+
"""[(start, end)] for the N calendar months preceding this one."""
|
|
318
|
+
buckets = []
|
|
319
|
+
for i in range(1, self.monthly + 1):
|
|
320
|
+
start = shift_month(today, i)
|
|
321
|
+
buckets.append((start, month_end(start)))
|
|
322
|
+
return buckets
|
|
323
|
+
|
|
324
|
+
# -- selection ---------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
def apply_to_fulls(self, fulls: list[BackupFile], today: date) -> None:
|
|
327
|
+
daily_floor = self.daily_floor(today)
|
|
328
|
+
weekly_floor = self.weekly_floor(today)
|
|
329
|
+
|
|
330
|
+
# Tier 1 -- everything in the last N days.
|
|
331
|
+
for f in fulls:
|
|
332
|
+
if f.day >= daily_floor:
|
|
333
|
+
f.mark(f"daily (last {self.daily_days} days)")
|
|
334
|
+
|
|
335
|
+
# Tier 2 -- one per ISO week, only for what the daily tier did not take.
|
|
336
|
+
for index, (start, end) in enumerate(self.weekly_buckets(today), 1):
|
|
337
|
+
bucket = [f for f in fulls if start <= f.day <= end and f.day < daily_floor]
|
|
338
|
+
chosen = pick(bucket, self.bucket_pick)
|
|
339
|
+
if chosen is not None:
|
|
340
|
+
chosen.mark(f"weekly -{index} (week of {start})")
|
|
341
|
+
|
|
342
|
+
# Tier 3 -- one per calendar month, older than the weekly range.
|
|
343
|
+
for index, (start, end) in enumerate(self.monthly_buckets(today), 1):
|
|
344
|
+
bucket = [f for f in fulls if start <= f.day <= end and f.day < weekly_floor]
|
|
345
|
+
chosen = pick(bucket, self.bucket_pick)
|
|
346
|
+
if chosen is not None:
|
|
347
|
+
chosen.mark(f"monthly -{index} ({start.strftime('%Y-%m')})")
|
|
348
|
+
|
|
349
|
+
# Safety floor -- always leave the newest N fulls in place.
|
|
350
|
+
for f in list(reversed(fulls))[: self.min_keep_fulls]:
|
|
351
|
+
f.mark(f"safety floor (newest {self.min_keep_fulls} fulls)")
|
|
352
|
+
|
|
353
|
+
def apply_to_incrementals(
|
|
354
|
+
self,
|
|
355
|
+
fulls: list[BackupFile],
|
|
356
|
+
incrs: list[BackupFile],
|
|
357
|
+
today: date,
|
|
358
|
+
) -> None:
|
|
359
|
+
incr_floor = today - timedelta(days=self.incr_days - 1)
|
|
360
|
+
|
|
361
|
+
# Attach each incremental to the newest full at or before it.
|
|
362
|
+
for incr in incrs:
|
|
363
|
+
parent = None
|
|
364
|
+
for full in fulls:
|
|
365
|
+
if full.ts <= incr.ts:
|
|
366
|
+
parent = full
|
|
367
|
+
else:
|
|
368
|
+
break
|
|
369
|
+
incr.parent = parent
|
|
370
|
+
|
|
371
|
+
# Age window first...
|
|
372
|
+
for incr in incrs:
|
|
373
|
+
if incr.parent is None:
|
|
374
|
+
incr.reason = "orphan: no full precedes it"
|
|
375
|
+
continue
|
|
376
|
+
if incr.day >= incr_floor:
|
|
377
|
+
incr.mark(f"incremental (last {self.incr_days} days)")
|
|
378
|
+
|
|
379
|
+
# Pin every earlier incremental since the full, not only the full.
|
|
380
|
+
# Flat files have no LSN metadata: conservatively retain the whole
|
|
381
|
+
# chronological chain through the newest surviving incremental.
|
|
382
|
+
for survivor in list(incrs):
|
|
383
|
+
if survivor.keep and survivor.parent is not None:
|
|
384
|
+
survivor.parent.mark(f"chain anchor for {survivor.name}")
|
|
385
|
+
for prerequisite in incrs:
|
|
386
|
+
if prerequisite.parent is survivor.parent and prerequisite.ts <= survivor.ts:
|
|
387
|
+
prerequisite.mark(f"chain prerequisite for {survivor.name}")
|
|
388
|
+
|
|
389
|
+
# Finally drop any incremental whose parent did not survive.
|
|
390
|
+
for incr in incrs:
|
|
391
|
+
if incr.keep and (incr.parent is None or not incr.parent.keep):
|
|
392
|
+
incr.keep = False
|
|
393
|
+
parent_name = incr.parent.name if incr.parent else "?"
|
|
394
|
+
incr.reason = f"broken chain: parent {parent_name} expired"
|
|
395
|
+
|
|
396
|
+
def apply_to_logs(self, logs: list[BackupFile], today: date) -> None:
|
|
397
|
+
floor = today - timedelta(days=self.log_days - 1)
|
|
398
|
+
for log in logs:
|
|
399
|
+
if log.day >= floor:
|
|
400
|
+
log.mark(f"log (last {self.log_days} days)")
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
# --------------------------------------------------------------------------
|
|
404
|
+
# Reporting / execution
|
|
405
|
+
# --------------------------------------------------------------------------
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def human(size: int) -> str:
|
|
409
|
+
value = float(size)
|
|
410
|
+
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
|
|
411
|
+
if value < 1024.0 or unit == "TiB":
|
|
412
|
+
return f"{value:.1f} {unit}"
|
|
413
|
+
value /= 1024.0
|
|
414
|
+
return f"{value:.1f} TiB"
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def report(
|
|
418
|
+
groups: list[tuple[str, list[BackupFile]]],
|
|
419
|
+
verbose: bool,
|
|
420
|
+
) -> tuple[str, int, int]:
|
|
421
|
+
lines: list[str] = []
|
|
422
|
+
total_keep = total_del = 0
|
|
423
|
+
bytes_keep = bytes_del = 0
|
|
424
|
+
|
|
425
|
+
for label, files in groups:
|
|
426
|
+
if not files:
|
|
427
|
+
continue
|
|
428
|
+
lines.append("")
|
|
429
|
+
lines.append(f"== {label} ({len(files)} files) ==")
|
|
430
|
+
for f in files:
|
|
431
|
+
flag = "KEEP " if f.keep else "DELETE"
|
|
432
|
+
if f.keep:
|
|
433
|
+
total_keep += 1
|
|
434
|
+
bytes_keep += f.size
|
|
435
|
+
else:
|
|
436
|
+
total_del += 1
|
|
437
|
+
bytes_del += f.size
|
|
438
|
+
if verbose or not f.keep:
|
|
439
|
+
lines.append(
|
|
440
|
+
f" {flag} {f.name:<42} {f.ts:%Y-%m-%d %H:%M} {human(f.size):<10} {f.reason}"
|
|
441
|
+
)
|
|
442
|
+
if not verbose:
|
|
443
|
+
kept = sum(1 for f in files if f.keep)
|
|
444
|
+
lines.append(f" ({kept} kept, use -v to list them)")
|
|
445
|
+
|
|
446
|
+
lines.append("")
|
|
447
|
+
lines.append(
|
|
448
|
+
f"Summary: keep {total_keep} ({human(bytes_keep)}), delete {total_del} ({human(bytes_del)})"
|
|
449
|
+
)
|
|
450
|
+
return "\n".join(lines), total_del, bytes_del
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def execute(files: list[BackupFile], apply_changes: bool) -> tuple[int, int, int]:
|
|
454
|
+
deleted = failed = 0
|
|
455
|
+
freed = 0
|
|
456
|
+
for f in files:
|
|
457
|
+
if f.keep:
|
|
458
|
+
continue
|
|
459
|
+
if not apply_changes:
|
|
460
|
+
deleted += 1
|
|
461
|
+
freed += f.size
|
|
462
|
+
continue
|
|
463
|
+
try:
|
|
464
|
+
os.unlink(f.path)
|
|
465
|
+
except OSError as exc:
|
|
466
|
+
sys.stderr.write(f"ERROR: could not delete {f.path}: {exc}\n")
|
|
467
|
+
failed += 1
|
|
468
|
+
continue
|
|
469
|
+
deleted += 1
|
|
470
|
+
freed += f.size
|
|
471
|
+
return deleted, failed, freed
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
# --------------------------------------------------------------------------
|
|
475
|
+
# Runner / CLI core
|
|
476
|
+
# --------------------------------------------------------------------------
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def run_job(
|
|
480
|
+
*,
|
|
481
|
+
full_dir: str | Path,
|
|
482
|
+
incr_dir: str | Path | None = None,
|
|
483
|
+
log_dir: str | Path | None = None,
|
|
484
|
+
full_glob: str = DEFAULTS["full_glob"],
|
|
485
|
+
incr_glob: str = DEFAULTS["incr_glob"],
|
|
486
|
+
log_glob: str = DEFAULTS["log_glob"],
|
|
487
|
+
daily: int = DEFAULTS["daily"],
|
|
488
|
+
weekly: int = DEFAULTS["weekly"],
|
|
489
|
+
monthly: int = DEFAULTS["monthly"],
|
|
490
|
+
incr_days: int = DEFAULTS["incr_days"],
|
|
491
|
+
log_days: int = DEFAULTS["log_days"],
|
|
492
|
+
pick_mode: str = DEFAULTS["pick"],
|
|
493
|
+
min_keep_fulls: int = DEFAULTS["min_keep_fulls"],
|
|
494
|
+
now: datetime | None = None,
|
|
495
|
+
apply_changes: bool = False,
|
|
496
|
+
verbose: bool = False,
|
|
497
|
+
quiet: bool = False,
|
|
498
|
+
out=sys.stdout,
|
|
499
|
+
) -> int:
|
|
500
|
+
"""Plan retention for a tree and optionally apply it. Returns an exit code."""
|
|
501
|
+
if daily < 1:
|
|
502
|
+
sys.stderr.write("ERROR: daily must be >= 1\n")
|
|
503
|
+
return EXIT_USAGE
|
|
504
|
+
if weekly < 0 or monthly < 0:
|
|
505
|
+
sys.stderr.write("ERROR: weekly/monthly must be >= 0\n")
|
|
506
|
+
return EXIT_USAGE
|
|
507
|
+
|
|
508
|
+
if incr_days < 0 or log_days < 0 or min_keep_fulls < 1:
|
|
509
|
+
sys.stderr.write("ERROR: incr_days/log_days must be >= 0; min_keep_fulls must be >= 1\n")
|
|
510
|
+
return EXIT_USAGE
|
|
511
|
+
if pick_mode not in {"first", "last"} or not isinstance(apply_changes, bool):
|
|
512
|
+
sys.stderr.write("ERROR: invalid pick mode or apply flag\n")
|
|
513
|
+
return EXIT_USAGE
|
|
514
|
+
now = now or datetime.now()
|
|
515
|
+
today = now.date()
|
|
516
|
+
|
|
517
|
+
policy = Policy(daily, weekly, monthly, incr_days, log_days, pick_mode, min_keep_fulls)
|
|
518
|
+
|
|
519
|
+
try:
|
|
520
|
+
fulls, skipped_f = scan(full_dir, full_glob, "full", now)
|
|
521
|
+
incrs, skipped_i = scan(incr_dir, incr_glob, "incr", now) if incr_dir else ([], [])
|
|
522
|
+
logs, skipped_l = scan(log_dir, log_glob, "log", now) if log_dir else ([], [])
|
|
523
|
+
except (NotADirectoryError, ValueError, OSError) as exc:
|
|
524
|
+
sys.stderr.write(f"ERROR: {exc}\n")
|
|
525
|
+
return EXIT_USAGE
|
|
526
|
+
|
|
527
|
+
if not fulls:
|
|
528
|
+
sys.stderr.write(
|
|
529
|
+
f"ERROR: no full backups matched {full_glob} in {full_dir} -- "
|
|
530
|
+
"refusing to expire anything, because that is what a broken "
|
|
531
|
+
"backup job looks like.\n"
|
|
532
|
+
)
|
|
533
|
+
return EXIT_REFUSED
|
|
534
|
+
|
|
535
|
+
# If an incremental is still being written or cannot be classified, its
|
|
536
|
+
# prerequisites are unknown. Defer deletion rather than strand that backup.
|
|
537
|
+
if incr_dir and (skipped_i or skipped_f):
|
|
538
|
+
sys.stderr.write("ERROR: incomplete backup scan; refusing to expire chain prerequisites\n")
|
|
539
|
+
return EXIT_REFUSED
|
|
540
|
+
|
|
541
|
+
policy.apply_to_fulls(fulls, today)
|
|
542
|
+
policy.apply_to_incrementals(fulls, incrs, today)
|
|
543
|
+
policy.apply_to_logs(logs, today)
|
|
544
|
+
|
|
545
|
+
groups = [(f"FULL {full_dir}", fulls)]
|
|
546
|
+
if incr_dir:
|
|
547
|
+
groups.append((f"INCR {incr_dir}", incrs))
|
|
548
|
+
if log_dir:
|
|
549
|
+
groups.append((f"LOG {log_dir}", logs))
|
|
550
|
+
|
|
551
|
+
text, _planned, _planned_bytes = report(groups, verbose)
|
|
552
|
+
|
|
553
|
+
header = (
|
|
554
|
+
f"Retention run {now:%Y-%m-%d %H:%M} -- mode: {'APPLY' if apply_changes else 'DRY RUN'}"
|
|
555
|
+
)
|
|
556
|
+
policy_line = (
|
|
557
|
+
f"Policy: keep all of last {daily} days, then {weekly} weekly, then "
|
|
558
|
+
f"{monthly} monthly (pick={pick_mode})"
|
|
559
|
+
)
|
|
560
|
+
|
|
561
|
+
if not quiet:
|
|
562
|
+
out.write(header + "\n")
|
|
563
|
+
out.write(policy_line + "\n")
|
|
564
|
+
for path, why in skipped_f + skipped_i + skipped_l:
|
|
565
|
+
out.write(f" SKIP {Path(path).name} ({why})\n")
|
|
566
|
+
out.write(text + "\n")
|
|
567
|
+
|
|
568
|
+
all_files = fulls + incrs + logs
|
|
569
|
+
deleted, failed, freed = execute(all_files, apply_changes)
|
|
570
|
+
|
|
571
|
+
verb = "deleted" if apply_changes else "would delete"
|
|
572
|
+
out.write(
|
|
573
|
+
f"{verb} {deleted} files, {human(freed)} reclaimed"
|
|
574
|
+
f"{f', {failed} failures' if failed else ''}\n"
|
|
575
|
+
)
|
|
576
|
+
if not apply_changes and deleted:
|
|
577
|
+
out.write("Dry run -- re-run with --apply to perform the deletions.\n")
|
|
578
|
+
|
|
579
|
+
return EXIT_DELETE_FAILURES if failed else EXIT_OK
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def main(argv: list[str] | None = None) -> int:
|
|
583
|
+
"""argparse-compatible entry point (script parity with the reference tool)."""
|
|
584
|
+
import argparse
|
|
585
|
+
|
|
586
|
+
p = argparse.ArgumentParser(description="GFS retention for backups (dry run unless --apply).")
|
|
587
|
+
p.add_argument("--full-dir", required=True)
|
|
588
|
+
p.add_argument("--incr-dir", default=None)
|
|
589
|
+
p.add_argument("--log-dir", default=None)
|
|
590
|
+
p.add_argument("--full-glob", default=DEFAULTS["full_glob"])
|
|
591
|
+
p.add_argument("--incr-glob", default=DEFAULTS["incr_glob"])
|
|
592
|
+
p.add_argument("--log-glob", default=DEFAULTS["log_glob"])
|
|
593
|
+
p.add_argument("--daily", type=int, default=DEFAULTS["daily"])
|
|
594
|
+
p.add_argument("--weekly", type=int, default=DEFAULTS["weekly"])
|
|
595
|
+
p.add_argument("--monthly", type=int, default=DEFAULTS["monthly"])
|
|
596
|
+
p.add_argument("--incr-days", type=int, default=DEFAULTS["incr_days"])
|
|
597
|
+
p.add_argument("--log-days", type=int, default=DEFAULTS["log_days"])
|
|
598
|
+
p.add_argument("--pick", choices=("first", "last"), dest="pick_mode", default=DEFAULTS["pick"])
|
|
599
|
+
p.add_argument("--min-keep-fulls", type=int, default=DEFAULTS["min_keep_fulls"])
|
|
600
|
+
p.add_argument("--now", default=None, help="pretend it is this date (YYYY-MM-DD)")
|
|
601
|
+
p.add_argument("--apply", action="store_true")
|
|
602
|
+
p.add_argument("-v", "--verbose", action="store_true")
|
|
603
|
+
p.add_argument("-q", "--quiet", action="store_true")
|
|
604
|
+
args = p.parse_args(argv)
|
|
605
|
+
|
|
606
|
+
now = None
|
|
607
|
+
if args.now:
|
|
608
|
+
try:
|
|
609
|
+
now = datetime.strptime(args.now, "%Y-%m-%d").replace(hour=23, minute=59, second=59)
|
|
610
|
+
except ValueError:
|
|
611
|
+
sys.stderr.write("ERROR: --now must be YYYY-MM-DD\n")
|
|
612
|
+
return EXIT_USAGE
|
|
613
|
+
|
|
614
|
+
return run_job(
|
|
615
|
+
full_dir=args.full_dir,
|
|
616
|
+
incr_dir=args.incr_dir,
|
|
617
|
+
log_dir=args.log_dir,
|
|
618
|
+
full_glob=args.full_glob,
|
|
619
|
+
incr_glob=args.incr_glob,
|
|
620
|
+
log_glob=args.log_glob,
|
|
621
|
+
daily=args.daily,
|
|
622
|
+
weekly=args.weekly,
|
|
623
|
+
monthly=args.monthly,
|
|
624
|
+
incr_days=args.incr_days,
|
|
625
|
+
log_days=args.log_days,
|
|
626
|
+
pick_mode=args.pick_mode,
|
|
627
|
+
min_keep_fulls=args.min_keep_fulls,
|
|
628
|
+
now=now,
|
|
629
|
+
apply_changes=args.apply,
|
|
630
|
+
verbose=args.verbose,
|
|
631
|
+
quiet=args.quiet,
|
|
632
|
+
)
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
if __name__ == "__main__":
|
|
636
|
+
sys.exit(main())
|