-
Notifications
You must be signed in to change notification settings - Fork 1
/
borgwrap
executable file
·486 lines (399 loc) · 17.5 KB
/
borgwrap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#!/usr/bin/env python3
import argparse
import datetime
import os
import re
import subprocess
import sys
import tempfile
import time
from typing import Any, Dict, List, Optional, Tuple
import yaml
class HookFailedException(Exception):
pass
class BorgWrap:
def __init__(self, config_path: str) -> None:
self.config = self.parse_config(config_path)
self.borg_version = self.determine_borg_version()
@staticmethod
def parse_config(filename: str) -> Dict[str, Any]:
with open(filename) as file_config:
return yaml.safe_load(file_config) # type: ignore
@staticmethod
def config_is_true(value: Any) -> bool:
if isinstance(value, bool):
return value
elif isinstance(value, str) and value.lower() in ("yes", "true"):
return True
elif value == 1:
return True
else:
return False
def config_get_retries(self) -> Tuple[int, int]:
if "retries" in self.config["remote"]:
retries = int(self.config["remote"]["retries"])
else:
retries = 0
if "retry_wait" in self.config["remote"]:
retry_wait = int(self.config["remote"]["retry_wait"])
else:
retry_wait = 0
return retries, retry_wait
@staticmethod
def determine_borg_version() -> Tuple[int, int, int]:
proc_result = subprocess.run(
["borg", "--version"], check=True, universal_newlines=True, stdout=subprocess.PIPE
)
match = re.search(r"(\d+)\.(\d+)\.(\d+)", proc_result.stdout)
if not match:
raise Exception(f"unable to detect borg version: {proc_result.stdout}")
return (int(match.group(1)), int(match.group(2)), int(match.group(3)))
@staticmethod
def write_exclude_file(excludes: List[str]) -> Any:
tmpfile = tempfile.NamedTemporaryFile("w", suffix="-borgwrap")
tmpfile.write("\n".join(excludes) + "\n")
tmpfile.flush()
return tmpfile
@staticmethod
def human_readable_size(num: float, suffix: str = "B") -> str:
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei"]:
if num < 1024.0:
return f"{int(num)}{unit}{suffix}"
num /= 1024.0
return f"{int(num)}Zi{suffix}"
def archive_prefix_args(self) -> List[str]:
if self.borg_version >= (1, 2, 0):
return ["--glob-archives", self.config["remote"]["prefix"] + "*"]
else:
return ["--prefix", self.config["remote"]["prefix"]]
def run(
self,
action: str,
archive: bool = False,
args: Optional[List[str]] = None,
trailing_args: Optional[List[str]] = None,
capture_stdout: bool = False,
capture_stderr: bool = False,
timeout: Optional[int] = None,
) -> "subprocess.CompletedProcess[str]":
args_list = args if args is not None else []
trailing_args_list = trailing_args if trailing_args is not None else []
repo = self.config["remote"]["repository"]
if archive:
repo += "::{}-{{utcnow:%Y-%m-%dT%H:%M:%SZ}}".format(self.config["remote"]["prefix"])
env = dict(os.environ)
if "rsh" in self.config["remote"]:
env["BORG_RSH"] = self.config["remote"]["rsh"]
if capture_stdout:
stdout: Optional[int] = subprocess.PIPE
else:
stdout = None
if capture_stderr:
stderr: Optional[int] = subprocess.PIPE
else:
stderr = None
return subprocess.run(
["borg", action] + args_list + [repo] + trailing_args_list,
check=True,
env=env,
stdout=stdout,
stderr=stderr,
universal_newlines=True,
timeout=timeout,
)
def action_create(self, dry_run: bool, stats: bool, list_files: bool) -> int:
source = self.config["location"]["source"]
if isinstance(source, str):
source = [source]
cmd = []
if "compression" in self.config["remote"]:
cmd += ["--compression", self.config["remote"]["compression"]]
if "rate_limit" in self.config["remote"]:
if self.borg_version >= (1, 2, 0):
cmd.append("--upload-ratelimit")
else:
cmd.append("--remote-ratelimit")
cmd.append(str(self.config["remote"]["rate_limit"]))
if "one_file_system" in self.config["location"] and self.config_is_true(
self.config["location"]["one_file_system"]
):
cmd.append("--one-file-system")
if "exclude_caches" in self.config["location"] and self.config_is_true(
self.config["location"]["exclude_caches"]
):
cmd.append("--exclude-caches")
if "keep_exclude_tags" in self.config["location"] and self.config_is_true(
self.config["location"]["keep_exclude_tags"]
):
cmd.append("--keep-exclude-tags")
if "exclude_if_present" in self.config["location"]:
for exclude in self.config["location"]["exclude_if_present"]:
cmd += ["--exclude-if-present", exclude]
# noatime is default for borg >= 1.2
if (
self.borg_version < (1, 2, 0)
and "noatime" in self.config["location"]
and self.config_is_true(self.config["location"]["noatime"])
):
cmd.append("--noatime")
if "exclude" in self.config["location"] and len(self.config["location"]["exclude"]) > 0:
exclude_file = self.write_exclude_file(self.config["location"]["exclude"])
cmd += ["--exclude-from", exclude_file.name]
if dry_run:
cmd += ["--dry-run"]
if stats:
cmd += ["--stats"]
if list_files:
cmd += ["--list"]
retries, retry_wait = self.config_get_retries()
for i in range(retries + 1):
try:
self.run("create", archive=True, args=cmd, trailing_args=source)
return 0
except subprocess.CalledProcessError as exc:
# only retry on errors, exit code 1 means a warning occurred
if exc.returncode == 1:
return exc.returncode
print(
f"Backup creation failed with exit code {exc.returncode}",
file=sys.stderr,
flush=True,
)
if i == retries:
sys.exit(exc.returncode)
if retry_wait == 0:
print("Retrying backup ...", file=sys.stderr, flush=True)
else:
print(
f"Retrying backup after {retry_wait} min ..",
file=sys.stderr,
flush=True,
)
time.sleep(retry_wait * 60)
def action_list(self, details: bool) -> None:
args = self.archive_prefix_args()
if details:
args += ["--json"]
try:
proc_result = self.run("info", args=args, capture_stdout=True)
except subprocess.CalledProcessError as exc:
sys.exit(exc.returncode)
archive_info = yaml.safe_load(proc_result.stdout)
archives = []
column_sizes = {}
columns = ["Name", "Orig", "Comp", "Dedup", "Files", "Duration"]
for archive in archive_info["archives"]:
archives.append(
{
"Name": archive["name"],
"Orig": self.human_readable_size(archive["stats"]["original_size"]),
"Comp": self.human_readable_size(archive["stats"]["compressed_size"]),
"Dedup": self.human_readable_size(archive["stats"]["deduplicated_size"]),
"Files": str(archive["stats"]["nfiles"]),
"Duration": f"{int(archive['duration'])}s",
}
)
for column in columns:
max_len = len(column)
for archive in archives:
max_len = max(max_len, len(archive[column]))
column_sizes[column] = max_len + 4
print(f"{column : <{column_sizes[column]}}", end="")
print()
for archive in archives:
for column in columns:
print(f"{archive[column] : <{column_sizes[column]}}", end="")
print()
else:
try:
self.run("list", args=args)
except subprocess.CalledProcessError as exc:
sys.exit(exc.returncode)
def action_check_age(self, max_age: int, min_size: Optional[int]) -> None:
try:
proc_result = self.run(
"info",
archive=False,
args=["--last", "1", "--json"],
capture_stdout=True,
capture_stderr=True,
timeout=150,
)
except subprocess.CalledProcessError as exc:
print("BORGBACKUP UNKNOWN - borgbackup command failed\n\n{}".format(exc.stderr or ""))
sys.exit(3)
except subprocess.TimeoutExpired as exc:
if exc.stderr is None:
stderr_text = ""
else:
stderr_text = exc.stderr.decode(errors="replace")
print(f"BORGBACKUP UNKNOWN - borgbackup command timed out\n\n{stderr_text}")
sys.exit(3)
last_backup = yaml.safe_load(proc_result.stdout)
backup_start = datetime.datetime.strptime(last_backup["archives"][0]["start"], "%Y-%m-%dT%H:%M:%S.%f")
if (datetime.datetime.now() - backup_start).total_seconds() > max_age:
print(f"BORGBACKUP WARNING - last backup too old: {backup_start:%Y-%m-%dT%H:%M:%S}")
sys.exit(1)
size = int(last_backup["archives"][0]["stats"]["original_size"] / 1024 / 1024)
if min_size is not None and size < min_size:
print(f"BORGBACKUP WARNING - last backup too small\n\n{size}M < {min_size}M")
sys.exit(1)
print(f"BORGBACKUP OK - last backup on: {backup_start:%Y-%m-%dT%H:%M:%S}, size: {size}M")
sys.exit(0)
def action_cmd(self, dry_run: bool, raw_args: List[str]) -> None:
env = dict(os.environ)
if "rsh" in self.config["remote"]:
env["BORG_RSH"] = self.config["remote"]["rsh"]
env["BORG_REPO"] = self.config["remote"]["repository"]
cmd = ["borg"] + raw_args
if dry_run:
print('Not running command "{}" as dry run is enabled.'.format(" ".join(cmd)))
else:
proc = subprocess.run(cmd, env=env)
sys.exit(proc.returncode)
def hooks_before(self, dry_run: bool) -> None:
if "hooks" not in self.config or "before" not in self.config["hooks"]:
return
for hook in self.config["hooks"]["before"]:
if dry_run:
print(f'Not running hook "{hook}" as dry run is enabled.')
else:
try:
subprocess.run(hook, shell=True, check=True)
except subprocess.CalledProcessError as exc:
raise HookFailedException(f'before hook "{hook}" failed with exit code {exc.returncode}')
def hooks_after(self, dry_run: bool) -> None:
if "hooks" not in self.config or "after" not in self.config["hooks"]:
return
for hook in self.config["hooks"]["after"]:
if dry_run:
print(f'Not running hook "{hook}" as dry run is enabled.')
else:
try:
subprocess.run(hook, shell=True, check=True)
except subprocess.CalledProcessError as exc:
raise HookFailedException(f'after hook "{hook}" failed with exit code {exc.returncode}')
def action_prune(self, dry_run: bool, stats: bool) -> None:
cmd = ["--list"]
cmd += self.archive_prefix_args()
if dry_run:
cmd += ["--dry-run"]
if stats:
cmd += ["--stats"]
if "keep_last" in self.config["retention"]:
cmd += ["--keep-last", str(self.config["retention"]["keep_last"])]
if "keep_within" in self.config["retention"]:
cmd += ["--keep-within", str(self.config["retention"]["keep_within"])]
if "keep_hourly" in self.config["retention"]:
cmd += ["--keep-hourly", str(self.config["retention"]["keep_hourly"])]
if "keep_daily" in self.config["retention"]:
cmd += ["--keep-daily", str(self.config["retention"]["keep_daily"])]
if "keep_weekly" in self.config["retention"]:
cmd += ["--keep-weekly", str(self.config["retention"]["keep_weekly"])]
if "keep_monthly" in self.config["retention"]:
cmd += ["--keep-monthly", str(self.config["retention"]["keep_monthly"])]
if "keep_yearly" in self.config["retention"]:
cmd += ["--keep-yearly", str(self.config["retention"]["keep_yearly"])]
retries, retry_wait = self.config_get_retries()
for i in range(retries + 1):
try:
proc = self.run("prune", args=cmd, capture_stderr=True)
for line in proc.stderr.splitlines(keepends=True):
if not line.startswith("Keeping archive:"):
print(line, end="", file=sys.stderr)
break
except subprocess.CalledProcessError as exc:
if exc.stderr:
print(exc.stderr, file=sys.stderr, flush=True)
print(
f"Backup prune failed with exit code {exc.returncode}",
file=sys.stderr,
flush=True,
)
if i == retries:
sys.exit(exc.returncode)
if retry_wait == 0:
print("Retrying prune ...", file=sys.stderr, flush=True)
else:
print(
f"Retrying prune after {retry_wait} min ..",
file=sys.stderr,
flush=True,
)
time.sleep(retry_wait * 60)
if self.borg_version >= (1, 2, 0) and not dry_run:
try:
self.run("compact")
except subprocess.CalledProcessError as exc:
print("Compacting failed with exit code {exc.returncode}")
sys.exit(exc.returncode)
def main() -> None:
parser = argparse.ArgumentParser(description="borgbackup wrapper")
parser.add_argument("--config", "-c", required=True, help="Path to the config file")
parser.add_argument(
"--dry-run",
"-n",
action="store_true",
help="Perform a trial run with no changes made",
)
subparsers = parser.add_subparsers(dest="action")
parser_create = subparsers.add_parser("create", help="Create a backup archive")
parser_create.add_argument("--prune", action="store_true", help="Run prune after creating a backup")
parser_create.add_argument(
"--no-prune",
action="store_true",
help="Don't run prune after creating a backup [deprecated, as this is the default]",
)
parser_create.add_argument("--stats", action="store_true", help="Print statistics of the created archive")
parser_create.add_argument(
"--list",
action="store_true",
help="Print a list of all files being processed by borg",
)
parser_list = subparsers.add_parser("list", help="List backup archives")
parser_list.add_argument(
"--details",
action="store_true",
help="List details about each archive",
)
parser_prune = subparsers.add_parser("prune", help="Prune archives according to the config settings")
parser_prune.add_argument("--stats", action="store_true", help="Print statistics of the deleted archives")
parser_check_age = subparsers.add_parser(
"nagios-check-age",
help="Check last backup age, usable as a Icinga/Nagios check",
)
parser_check_age.add_argument("--max-age", type=int, required=True, help="Max age in hours")
parser_check_age.add_argument("--min-size", type=int, help="Min backup size in MiB")
parser_cmd = subparsers.add_parser(
"cmd",
help='Run a borgbackup command. Exports the remote archive as BORG_REPO so it can be referenced as "::".',
)
parser_cmd.add_argument("raw", nargs="+")
args = parser.parse_args()
borgwrap = BorgWrap(args.config)
if args.action == "create":
try:
borgwrap.hooks_before(dry_run=args.dry_run)
exit_code = borgwrap.action_create(dry_run=args.dry_run, stats=args.stats, list_files=args.list)
borgwrap.hooks_after(dry_run=args.dry_run)
if args.prune:
borgwrap.action_prune(dry_run=args.dry_run, stats=args.stats)
sys.exit(exit_code)
except HookFailedException as exc:
print(exc)
# return borg error exit code
sys.exit(2)
elif args.action == "list":
borgwrap.action_list(args.details)
elif args.action == "prune":
borgwrap.action_prune(dry_run=args.dry_run, stats=args.stats)
elif args.action == "nagios-check-age":
if args.min_size:
min_size = args.min_size
else:
min_size = None
borgwrap.action_check_age(max_age=args.max_age * 3600, min_size=min_size)
elif args.action == "cmd":
borgwrap.action_cmd(dry_run=args.dry_run, raw_args=args.raw)
if __name__ == "__main__":
main()