backup-tool/app/specs/container.py

66 lines
2.0 KiB
Python
Raw Normal View History

2021-04-26 17:45:19 +02:00
"""Module defining a container-based spec."""
2021-01-15 22:00:56 +01:00
from .spec import Spec
from typing import Union
from pathlib import Path
from datetime import datetime
import subprocess
class ContainerSpec(Spec):
2021-04-25 19:26:12 +02:00
"""Spec for backing up via a container."""
2021-01-15 22:00:56 +01:00
_SKEL = {"container": None, "command": None, "mountpoint": "/from"}
2021-04-25 19:26:12 +02:00
"""The skeleton for the ContainerSpec config."""
2021-01-15 22:00:56 +01:00
def __init__(
self,
name: str,
container: str,
destination: Union[str, Path],
limit: int,
command: str,
extension: str,
mountpoint: str,
notify=None,
):
2021-04-26 18:00:56 +02:00
"""Create a new ContainerSpec object.
2021-04-25 19:26:12 +02:00
Args:
name: name of the spec (used as an identifier)
container: the Docker container to back up
destination: where to store the backups (gets created if
non-existent)
limit: max amount of backups to keep
command: command to run inside the container. This command should
perform a specified backup and output this data to stdout. This
output then gets piped to a backup file.
extension: the extension of the backup files.
2021-04-26 18:00:56 +02:00
mountpoint: I don't actually know, this never gets used
2021-04-25 19:26:12 +02:00
notify: notifier object (may be None)
"""
2021-01-15 22:00:56 +01:00
super().__init__(name, destination, limit, extension, notify)
self.container = container
self.mountpoint = mountpoint
self.command = command
def backup(self):
2021-04-26 17:45:19 +02:00
"""Create a new backup."""
2021-01-15 22:00:56 +01:00
# Remove excess backups
self.remove_backups()
# Run actual backup command
filename = "{}.{}".format(
datetime.now().strftime("%Y-%m-%d_%H-%M-%S"), self.extension
)
process = subprocess.run(
"docker exec -t '{}' {} > '{}/{}'".format(
self.container, self.command, self.destination, filename
),
shell=True,
)
if self.notifier:
self.notifier.notify("backup", self.name, process.returncode)