baseimage-tutorial-framework/tfw/components/snapshots/snapshot_handler.py

79 lines
2.5 KiB
Python
Raw Normal View History

2019-06-10 13:32:45 +00:00
import logging
from os.path import join as joinpath
from os.path import basename
from os import makedirs
from datetime import datetime
from dateutil import parser as dateparser
from .snapshot_provider import SnapshotProvider
2019-06-28 13:11:02 +00:00
LOG = logging.getLogger(__name__)
class SnapshotHandler:
keys = ['snapshot']
2019-07-23 13:32:50 +00:00
def __init__(self, *, directories, snapshots_dir, exclude_unix_patterns=None):
self._snapshots_dir = snapshots_dir
self.snapshot_providers = {}
self._exclude_unix_patterns = exclude_unix_patterns
self.init_snapshot_providers(directories)
self.command_handlers = {
2019-08-08 13:05:37 +00:00
'snapshot.take': self.handle_take_snapshot,
'snapshot.restore': self.handle_restore_snapshot,
'snapshot.exclude': self.handle_exclude
}
def init_snapshot_providers(self, directories):
2018-08-06 11:40:16 +00:00
for index, directory in enumerate(directories):
git_dir = self.init_git_dir(index, directory)
self.snapshot_providers[directory] = SnapshotProvider(
directory,
git_dir,
self._exclude_unix_patterns
)
2019-07-23 13:32:50 +00:00
def init_git_dir(self, index, directory):
2018-08-06 11:40:16 +00:00
git_dir = joinpath(
2019-07-23 13:32:50 +00:00
self._snapshots_dir,
2018-08-06 11:40:16 +00:00
f'{basename(directory)}-{index}'
)
makedirs(git_dir, exist_ok=True)
return git_dir
2019-08-08 13:05:37 +00:00
def handle_event(self, message, _):
try:
2019-08-08 13:05:37 +00:00
self.command_handlers[message['key']](message)
except KeyError:
LOG.error('IGNORING MESSAGE: Invalid message received: %s', message)
2019-08-08 13:05:37 +00:00
def handle_take_snapshot(self, _):
LOG.debug('Taking snapshots of directories %s', self.snapshot_providers.keys())
for provider in self.snapshot_providers.values():
provider.take_snapshot()
2019-08-08 13:05:37 +00:00
def handle_restore_snapshot(self, message):
date = dateparser.parse(
2019-08-08 13:05:37 +00:00
message.get(
'value',
datetime.now().isoformat()
)
)
LOG.debug(
'Restoring snapshots (@ %s) of directories %s',
date,
self.snapshot_providers.keys()
)
for provider in self.snapshot_providers.values():
provider.restore_snapshot(date)
2019-08-08 13:05:37 +00:00
def handle_exclude(self, message):
exclude_unix_patterns = message['value']
if not isinstance(exclude_unix_patterns, list):
raise KeyError
for provider in self.snapshot_providers.values():
provider.exclude = exclude_unix_patterns