backup: print final results and run notification script on error

This commit is contained in:
Jim Paris 2021-10-15 23:28:00 -04:00 committed by Jim Paris
parent ccf54b98d7
commit 31d88f9345

View File

@ -229,6 +229,7 @@ def main(argv: list[str]):
def humansize(string):
return humanfriendly.parse_size(string)
# Parse args
parser = argparse.ArgumentParser(
prog=argv[0],
description="Back up the local system using borg",
@ -239,6 +240,8 @@ def main(argv: list[str]):
help="Config file", default=str(base / "config.yaml"))
parser.add_argument('-b', '--borg',
help="Borg command", default=str(base / "borg.sh"))
parser.add_argument('-N', '--notify',
help="Notify command", default=str(base / "notify.sh"))
parser.add_argument('-n', '--dry-run', action="store_true",
help="Just print log output, don't run borg")
parser.add_argument('-d', '--debug', action="store_true",
@ -313,6 +316,42 @@ def main(argv: list[str]):
elif ret != 0:
backup.log('E', f"borg exited with return code {ret}")
# See if we had any errors
warnings = sum(1 for (letter, msg) in backup.logs if letter == 'W')
errors = sum(1 for (letter, msg) in backup.logs if letter == 'E')
if not warnings and not errors:
backup.log('I', f"backup successful", bold=True)
else:
if warnings:
backup.log('W', f"reported {warnings} warnings", bold=True)
if errors:
backup.log('E', f"reported {errors} errors", bold=True)
# Send a notification of errors
email = backup.config.notify_email
if email and not args.dry_run:
backup.log('I', f"sending error notification to {email}")
# Show all of our warnings and errors
body = [ "Backup reported the following warnings and errors:" ]
for (letter, msg) in backup.logs:
body.append(f"{letter}: {msg}")
body_text = "\n".join(body).encode()
# Followed by borg output
body_text += b"\nBorg output:\n" + b"".join(captured_output)
# Call notify.sh
res = subprocess.run([args.notify, email], input=body_text)
if res.returncode != 0:
backup.log('E', f"failed to send notification")
errors += 1
# Exit with an error code if we had any errors
if errors:
return 1
return 0
if __name__ == "__main__":