backup-tool/app/specs/volume.py

73 lines
1.9 KiB
Python
Raw Normal View History

2021-04-26 18:00:56 +02:00
"""Module defining a Docker volume-based spec."""
2021-01-15 21:47:09 +01:00
from .spec import Spec
from typing import Union
from pathlib import Path
from datetime import datetime
import subprocess
class VolumeSpec(Spec):
2021-04-26 17:45:19 +02:00
"""A spec for backing up a Docker volume."""
2021-01-15 21:47:09 +01:00
_SKEL = {
"volume": None,
"image": "alpine:latest",
"command": "tar -czf '/to/{filename}' .",
}
def __init__(
self,
name: str,
volume: str,
image: str,
destination: Union[str, Path],
limit: int,
command: str,
extension: str,
notify=None,
):
2021-04-26 18:00:56 +02:00
"""Initialize a new VolumeSpec object.
Args:
name: name of the spec
volume: Docker volume to back up
image: base image to use to run backup command
destination: where to store the backup files
limit: max backup files to keep
command: backup command to run within the base image
extension: file extension of the backup files
notify: Notifier object
"""
2021-01-15 21:47:09 +01:00
super().__init__(name, destination, limit, extension, notify)
self.volume = volume
self.image = image
self.command = command
def backup(self):
2021-04-26 18:00:56 +02:00
"""Create a new backup."""
2021-01-15 21:47:09 +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
)
2021-04-26 18:00:56 +02:00
base_cmd = "docker run --rm -v '{}:/from' -v '{}:/to' -w /from '{}' {}"
2021-01-15 21:47:09 +01:00
process = subprocess.run(
2021-04-26 18:00:56 +02:00
base_cmd.format(
2021-01-15 21:47:09 +01:00
self.volume,
self.destination,
self.image,
self.command.format(
filename=filename,
),
),
shell=True,
)
if self.notifier:
self.notifier.notify("backup", self.name, process.returncode)