mirror of
https://github.com/freedombox/FreedomBox.git
synced 2026-11-29 08:25:10 +00:00
backups: Use the backup component in all apps
Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org> Reviewed-by: Veiko Aasa <veiko17@disroot.org>
This commit is contained in:
1 parent
f630fb6059
commit
fb1898befc
105 files changed
+748
-644
No files matched your search
@@ -75,10 +75,10 @@ def _backup_handler(packet, encryption_passphrase=None):
|
||||
get_valid_filename(packet.path) + '.json')
|
||||
manifests = {
|
||||
'apps': [{
|
||||
'name': app.name,
|
||||
'version': app.app.app.info.version,
|
||||
'backup': app.manifest
|
||||
} for app in packet.apps]
|
||||
'name': component.app.app_id,
|
||||
'version': component.app.info.version,
|
||||
'backup': component.manifest
|
||||
} for component in packet.components]
|
||||
}
|
||||
with open(manifest_path, 'w') as manifest_file:
|
||||
json.dump(manifests, manifest_file)
|
||||
@@ -124,9 +124,9 @@ def restore_archive_handler(packet, encryption_passphrase=None):
|
||||
actions.superuser_run('backups', arguments, input=locations_data.encode())
|
||||
|
||||
|
||||
def restore_from_upload(path, apps=None):
|
||||
def restore_from_upload(path, app_ids=None):
|
||||
"""Restore files from an uploaded .tar.gz backup file"""
|
||||
api.restore_apps(_restore_exported_archive_handler, app_names=apps,
|
||||
api.restore_apps(_restore_exported_archive_handler, app_ids=app_ids,
|
||||
create_subvolume=False, backup_file=path)
|
||||
|
||||
|
||||
|
||||
+84
-150
@@ -10,79 +10,38 @@ TODO:
|
||||
- Implement unit tests.
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
|
||||
from plinth import actions, action_utils, module_loader, setup
|
||||
from plinth import action_utils, actions
|
||||
from plinth import app as app_module
|
||||
from plinth import setup
|
||||
|
||||
from .components import BackupRestore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def validate(backup):
|
||||
"""Validate the backup' information schema."""
|
||||
assert isinstance(backup, dict)
|
||||
|
||||
if 'config' in backup:
|
||||
assert isinstance(backup['config'], dict)
|
||||
_validate_directories_and_files(backup['config'])
|
||||
|
||||
if 'data' in backup:
|
||||
assert isinstance(backup['data'], dict)
|
||||
_validate_directories_and_files(backup['data'])
|
||||
|
||||
if 'secrets' in backup:
|
||||
assert isinstance(backup['secrets'], dict)
|
||||
_validate_directories_and_files(backup['secrets'])
|
||||
|
||||
if 'services' in backup:
|
||||
assert isinstance(backup['services'], list)
|
||||
for service in backup['services']:
|
||||
assert isinstance(service, (str, dict))
|
||||
if isinstance(service, dict):
|
||||
_validate_service(service)
|
||||
|
||||
return backup
|
||||
|
||||
|
||||
def _validate_directories_and_files(section):
|
||||
"""Validate directories and files keys in a section."""
|
||||
if 'directories' in section:
|
||||
assert isinstance(section['directories'], list)
|
||||
for directory in section['directories']:
|
||||
assert isinstance(directory, str)
|
||||
|
||||
if 'files' in section:
|
||||
assert isinstance(section['files'], list)
|
||||
for file_path in section['files']:
|
||||
assert isinstance(file_path, str)
|
||||
|
||||
|
||||
def _validate_service(service):
|
||||
"""Validate a service manifest provided as a dictionary."""
|
||||
assert isinstance(service['name'], str)
|
||||
assert isinstance(service['type'], str)
|
||||
assert service['type'] in ('apache', 'uwsgi', 'system')
|
||||
if service['type'] == 'apache':
|
||||
assert service['kind'] in ('config', 'site', 'module')
|
||||
|
||||
|
||||
class BackupError:
|
||||
"""Represent an backup/restore operation error."""
|
||||
def __init__(self, error_type, app, hook=None):
|
||||
|
||||
def __init__(self, error_type, component, hook=None):
|
||||
"""Initialize the error object."""
|
||||
self.error_type = error_type
|
||||
self.app = app
|
||||
self.component = component
|
||||
self.hook = hook
|
||||
|
||||
def __eq__(self, other_error):
|
||||
"""Compare to error objects."""
|
||||
return (self.error_type == other_error.error_type
|
||||
and self.app == other_error.app
|
||||
and self.component == other_error.component
|
||||
and self.hook == other_error.hook)
|
||||
|
||||
|
||||
class Packet:
|
||||
"""Information passed to a handlers for backup/restore operations."""
|
||||
def __init__(self, operation, scope, root, apps=None, path=None):
|
||||
|
||||
def __init__(self, operation, scope, root, components=None, path=None):
|
||||
"""Initialize the packet.
|
||||
|
||||
operation is either 'backup' or 'restore.
|
||||
@@ -101,7 +60,7 @@ class Packet:
|
||||
self.operation = operation
|
||||
self.scope = scope
|
||||
self.root = root
|
||||
self.apps = apps
|
||||
self.components = components
|
||||
self.path = path
|
||||
self.errors = []
|
||||
|
||||
@@ -112,11 +71,11 @@ class Packet:
|
||||
|
||||
def _process_manifests(self):
|
||||
"""Look at manifests and fill up the list of directories/files."""
|
||||
for app in self.apps:
|
||||
for component in self.components:
|
||||
for section in ['config', 'data', 'secrets']:
|
||||
self.directories += app.manifest.get(section, {}).get(
|
||||
'directories', [])
|
||||
self.files += app.manifest.get(section, {}).get('files', [])
|
||||
section = getattr(component, section)
|
||||
self.directories += section.get('directories', [])
|
||||
self.files += section.get('files', [])
|
||||
|
||||
|
||||
def backup_full(backup_handler, path=None):
|
||||
@@ -146,25 +105,25 @@ def restore_full(restore_handler):
|
||||
_switch_to_subvolume(subvolume)
|
||||
|
||||
|
||||
def backup_apps(backup_handler, path, app_names=None,
|
||||
def backup_apps(backup_handler, path, app_ids=None,
|
||||
encryption_passphrase=None):
|
||||
"""Backup data belonging to a set of applications."""
|
||||
if not app_names:
|
||||
apps = get_all_apps_for_backup()
|
||||
if not app_ids:
|
||||
components = get_all_components_for_backup()
|
||||
else:
|
||||
apps = get_apps_in_order(app_names)
|
||||
components = get_components_in_order(app_ids)
|
||||
|
||||
if _is_snapshot_available():
|
||||
snapshot = _take_snapshot()
|
||||
backup_root = snapshot['mount_path']
|
||||
snapshotted = True
|
||||
else:
|
||||
_lockdown_apps(apps, lockdown=True)
|
||||
original_state = _shutdown_services(apps)
|
||||
_lockdown_apps(components, lockdown=True)
|
||||
original_state = _shutdown_services(components)
|
||||
backup_root = '/'
|
||||
snapshotted = False
|
||||
|
||||
packet = Packet('backup', 'apps', backup_root, apps, path)
|
||||
packet = Packet('backup', 'apps', backup_root, components, path)
|
||||
_run_operation(backup_handler, packet,
|
||||
encryption_passphrase=encryption_passphrase)
|
||||
|
||||
@@ -172,29 +131,29 @@ def backup_apps(backup_handler, path, app_names=None,
|
||||
_delete_snapshot(snapshot)
|
||||
else:
|
||||
_restore_services(original_state)
|
||||
_lockdown_apps(apps, lockdown=False)
|
||||
_lockdown_apps(components, lockdown=False)
|
||||
|
||||
|
||||
def restore_apps(restore_handler, app_names=None, create_subvolume=True,
|
||||
def restore_apps(restore_handler, app_ids=None, create_subvolume=True,
|
||||
backup_file=None, encryption_passphrase=None):
|
||||
"""Restore data belonging to a set of applications."""
|
||||
if not app_names:
|
||||
apps = get_all_apps_for_backup()
|
||||
if not app_ids:
|
||||
components = get_all_components_for_backup()
|
||||
else:
|
||||
apps = get_apps_in_order(app_names)
|
||||
components = get_components_in_order(app_ids)
|
||||
|
||||
_install_apps_before_restore(apps)
|
||||
_install_apps_before_restore(components)
|
||||
|
||||
if _is_snapshot_available() and create_subvolume:
|
||||
subvolume = _create_subvolume(empty=False)
|
||||
restore_root = subvolume['mount_path']
|
||||
else:
|
||||
_lockdown_apps(apps, lockdown=True)
|
||||
original_state = _shutdown_services(apps)
|
||||
_lockdown_apps(components, lockdown=True)
|
||||
original_state = _shutdown_services(components)
|
||||
restore_root = '/'
|
||||
subvolume = False
|
||||
|
||||
packet = Packet('restore', 'apps', restore_root, apps, backup_file)
|
||||
packet = Packet('restore', 'apps', restore_root, components, backup_file)
|
||||
_run_operation(restore_handler, packet,
|
||||
encryption_passphrase=encryption_passphrase)
|
||||
|
||||
@@ -202,10 +161,10 @@ def restore_apps(restore_handler, app_names=None, create_subvolume=True,
|
||||
_switch_to_subvolume(subvolume)
|
||||
else:
|
||||
_restore_services(original_state)
|
||||
_lockdown_apps(apps, lockdown=False)
|
||||
_lockdown_apps(components, lockdown=False)
|
||||
|
||||
|
||||
def _install_apps_before_restore(apps):
|
||||
def _install_apps_before_restore(components):
|
||||
"""Install/upgrade apps needed before restoring a backup.
|
||||
|
||||
Upgrading apps to latest version before backups reduces the chance of newer
|
||||
@@ -213,92 +172,57 @@ def _install_apps_before_restore(apps):
|
||||
|
||||
"""
|
||||
modules_to_setup = []
|
||||
for backup_app in apps:
|
||||
if backup_app.app.setup_helper.get_state() in ('needs-setup',
|
||||
'needs-update'):
|
||||
modules_to_setup.append(backup_app.name)
|
||||
for component in components:
|
||||
module = importlib.import_module(component.app.__class__.__module__)
|
||||
if module.setup_helper.get_state() in ('needs-setup', 'needs-update'):
|
||||
modules_to_setup.append(component.app.app_id)
|
||||
|
||||
setup.run_setup_on_modules(modules_to_setup)
|
||||
|
||||
|
||||
class BackupApp:
|
||||
"""A application that can be backed up and its manifest."""
|
||||
def __init__(self, name, app):
|
||||
"""Initialize object and load manfiest."""
|
||||
self.name = name
|
||||
self.app = app
|
||||
def _get_backup_restore_component(app):
|
||||
"""Return the backup/restore component of the app."""
|
||||
for component in app.components.values():
|
||||
if isinstance(component, BackupRestore):
|
||||
return component
|
||||
|
||||
# Has no backup related meta data
|
||||
raise TypeError
|
||||
|
||||
|
||||
def get_all_components_for_backup():
|
||||
"""Return a list of all components that can be backed up."""
|
||||
components = []
|
||||
|
||||
for app_ in app_module.App.list():
|
||||
try:
|
||||
self.manifest = app.backup
|
||||
except AttributeError:
|
||||
raise TypeError
|
||||
|
||||
self.has_data = bool(app.backup)
|
||||
|
||||
def __eq__(self, other_app):
|
||||
"""Check if this app is same as another."""
|
||||
return self.name == other_app.name and \
|
||||
self.app == other_app.app and \
|
||||
self.manifest == other_app.manifest and \
|
||||
self.has_data == other_app.has_data
|
||||
|
||||
def is_installed(self):
|
||||
"""Return whether app is installed.
|
||||
|
||||
Return true even if the app needs update.
|
||||
"""
|
||||
return self.app.setup_helper.get_state() != 'needs-setup'
|
||||
|
||||
def run_hook(self, hook, packet):
|
||||
"""Run a hook inside an application."""
|
||||
if not hasattr(self.app, hook):
|
||||
return
|
||||
|
||||
try:
|
||||
getattr(self.app, hook)(packet)
|
||||
except Exception as exception:
|
||||
logger.exception(
|
||||
'Error running backup/restore hook for app %s: %s', self.name,
|
||||
exception)
|
||||
packet.errors.append(BackupError('hook', self.app, hook=hook))
|
||||
|
||||
|
||||
def get_all_apps_for_backup():
|
||||
"""Return a list of all applications that can be backed up."""
|
||||
apps = []
|
||||
for module_name, module in module_loader.loaded_modules.items():
|
||||
try:
|
||||
backup_app = BackupApp(module_name, module)
|
||||
if backup_app.is_installed():
|
||||
apps.append(backup_app)
|
||||
module = importlib.import_module(app_.__class__.__module__)
|
||||
if module.setup_helper.get_state() != 'needs-setup':
|
||||
components.append(_get_backup_restore_component(app_))
|
||||
except TypeError: # Application not available for backup/restore
|
||||
pass
|
||||
|
||||
return apps
|
||||
return components
|
||||
|
||||
|
||||
def get_apps_in_order(app_names):
|
||||
"""Return a list of app modules in order of dependency."""
|
||||
apps = []
|
||||
for module_name, module in module_loader.loaded_modules.items():
|
||||
if module_name in app_names:
|
||||
apps.append(BackupApp(module_name, module))
|
||||
def get_components_in_order(app_ids):
|
||||
"""Return a list of backup components in order of app dependencies."""
|
||||
components = []
|
||||
for app_ in app_module.App.list():
|
||||
if app_.app_id in app_ids:
|
||||
components.append(_get_backup_restore_component(app_))
|
||||
|
||||
return apps
|
||||
return components
|
||||
|
||||
|
||||
def _lockdown_apps(apps, lockdown):
|
||||
def _lockdown_apps(components, lockdown):
|
||||
"""Mark apps as in/out of lockdown mode and disable all user interaction.
|
||||
|
||||
This is a flag in the app module. It will enforced by a middleware that
|
||||
will intercept all interaction and show a lockdown message.
|
||||
|
||||
"""
|
||||
for app in apps:
|
||||
app.app.locked = lockdown
|
||||
|
||||
# XXX: Lockdown the application UI by implementing a middleware
|
||||
for component in components:
|
||||
component.app.locked = lockdown
|
||||
|
||||
|
||||
def _is_snapshot_available():
|
||||
@@ -347,6 +271,7 @@ def _switch_to_subvolume(subvolume):
|
||||
|
||||
class ServiceHandler:
|
||||
"""Abstraction to help with service shutdown/restart."""
|
||||
|
||||
@staticmethod
|
||||
def create(backup_app, service):
|
||||
service_type = 'system'
|
||||
@@ -381,6 +306,7 @@ class ServiceHandler:
|
||||
|
||||
class SystemServiceHandler(ServiceHandler):
|
||||
"""Handle starting and stopping of system services for backup."""
|
||||
|
||||
def __init__(self, backup_app, service):
|
||||
"""Initialize the object."""
|
||||
super().__init__(backup_app, service)
|
||||
@@ -400,6 +326,7 @@ class SystemServiceHandler(ServiceHandler):
|
||||
|
||||
class ApacheServiceHandler(ServiceHandler):
|
||||
"""Handle starting and stopping of Apache services for backup."""
|
||||
|
||||
def __init__(self, backup_app, service):
|
||||
"""Initialize the object."""
|
||||
super().__init__(backup_app, service)
|
||||
@@ -424,18 +351,19 @@ class ApacheServiceHandler(ServiceHandler):
|
||||
['enable', '--name', self.web_name, '--kind', self.kind])
|
||||
|
||||
|
||||
def _shutdown_services(apps):
|
||||
"""Shutdown all services specified by manifests.
|
||||
def _shutdown_services(components):
|
||||
"""Shutdown all services specified by backup manifests.
|
||||
|
||||
- Services are shutdown in the reverse order of the apps listing.
|
||||
- Services are shutdown in the reverse order of the components listing.
|
||||
|
||||
Return the current state of the services so they can be restored
|
||||
accurately.
|
||||
|
||||
"""
|
||||
state = []
|
||||
for app in apps:
|
||||
for service in app.manifest.get('services', []):
|
||||
state.append(ServiceHandler.create(app, service))
|
||||
for component in components:
|
||||
for service in component.services:
|
||||
state.append(ServiceHandler.create(component, service))
|
||||
|
||||
for service in reversed(state):
|
||||
service.stop()
|
||||
@@ -480,8 +408,14 @@ def _run_hooks(hook, packet):
|
||||
|
||||
"""
|
||||
logger.info('Running %s hooks', hook)
|
||||
for app in packet.apps:
|
||||
app.run_hook(hook, packet)
|
||||
for component in packet.components:
|
||||
try:
|
||||
getattr(component, hook)(packet)
|
||||
except Exception as exception:
|
||||
logger.exception(
|
||||
'Error running backup/restore hook for app %s: %s',
|
||||
component.app.app_id, exception)
|
||||
packet.errors.append(BackupError('hook', component, hook=hook))
|
||||
|
||||
|
||||
def _run_operation(handler, packet, encryption_passphrase=None):
|
||||
|
||||
@@ -24,16 +24,16 @@ from .repository import get_repositories
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _get_app_choices(apps):
|
||||
"""Return a list of check box multiple choices from list of apps."""
|
||||
def _get_app_choices(components):
|
||||
"""Return a list of check box multiple choices from list of components."""
|
||||
choices = []
|
||||
for app in apps:
|
||||
name = app.app.app.info.name
|
||||
if not app.has_data:
|
||||
for component in components:
|
||||
name = component.app.info.name
|
||||
if not component.has_data:
|
||||
name = ugettext('{app} (No data to backup)').format(
|
||||
app=app.app.app.info.name)
|
||||
app=component.app.info.name)
|
||||
|
||||
choices.append((app.name, name))
|
||||
choices.append((component.app_id, name))
|
||||
|
||||
return choices
|
||||
|
||||
@@ -59,9 +59,12 @@ class CreateArchiveForm(forms.Form):
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize the form with selectable apps."""
|
||||
super().__init__(*args, **kwargs)
|
||||
apps = api.get_all_apps_for_backup()
|
||||
self.fields['selected_apps'].choices = _get_app_choices(apps)
|
||||
self.fields['selected_apps'].initial = [app.name for app in apps]
|
||||
components = api.get_all_components_for_backup()
|
||||
choices = _get_app_choices(components)
|
||||
self.fields['selected_apps'].choices = choices
|
||||
self.fields['selected_apps'].initial = [
|
||||
choice[0] for choice in choices
|
||||
]
|
||||
self.fields['repository'].choices = _get_repository_choices()
|
||||
|
||||
|
||||
@@ -72,10 +75,13 @@ class RestoreForm(forms.Form):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize the form with selectable apps."""
|
||||
apps = kwargs.pop('apps')
|
||||
components = kwargs.pop('components')
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['selected_apps'].choices = _get_app_choices(apps)
|
||||
self.fields['selected_apps'].initial = [app.name for app in apps]
|
||||
choices = _get_app_choices(components)
|
||||
self.fields['selected_apps'].choices = choices
|
||||
self.fields['selected_apps'].initial = [
|
||||
choice[0] for choice in choices
|
||||
]
|
||||
|
||||
|
||||
class UploadForm(forms.Form):
|
||||
|
||||
@@ -3,9 +3,7 @@
|
||||
Application manifest for backups.
|
||||
"""
|
||||
|
||||
from plinth.modules.backups.api import validate as validate_backup
|
||||
|
||||
# Currently, backup application does not have any settings. However, settings
|
||||
# such as scheduler settings, backup location, secrets to connect to remove
|
||||
# servers need to be backed up.
|
||||
backup = validate_backup({})
|
||||
backup = {}
|
||||
@@ -158,6 +158,7 @@ class BaseBorgRepository(abc.ABC):
|
||||
|
||||
def remove(self):
|
||||
"""Remove a borg repository"""
|
||||
|
||||
def list_archives(self):
|
||||
"""Return list of archives in this repository."""
|
||||
output = self.run(['list-repo', '--path', self.borg_path])
|
||||
@@ -165,12 +166,12 @@ class BaseBorgRepository(abc.ABC):
|
||||
return sorted(archives, key=lambda archive: archive['start'],
|
||||
reverse=True)
|
||||
|
||||
def create_archive(self, archive_name, app_names):
|
||||
def create_archive(self, archive_name, app_ids):
|
||||
"""Create a new archive in this repository with given name."""
|
||||
archive_path = self._get_archive_path(archive_name)
|
||||
passphrase = self.credentials.get('encryption_passphrase', None)
|
||||
api.backup_apps(_backup_handler, path=archive_path,
|
||||
app_names=app_names, encryption_passphrase=passphrase)
|
||||
api.backup_apps(_backup_handler, path=archive_path, app_ids=app_ids,
|
||||
encryption_passphrase=passphrase)
|
||||
|
||||
def delete_archive(self, archive_name):
|
||||
"""Delete an archive with given name from this repository."""
|
||||
@@ -222,6 +223,7 @@ class BaseBorgRepository(abc.ABC):
|
||||
|
||||
def get_download_stream(self, archive_name):
|
||||
"""Return an stream of .tar.gz binary data for a backup archive."""
|
||||
|
||||
class BufferedReader(io.BufferedReader):
|
||||
"""Improve performance of buffered binary streaming.
|
||||
|
||||
@@ -235,6 +237,7 @@ class BaseBorgRepository(abc.ABC):
|
||||
binary data.
|
||||
|
||||
"""
|
||||
|
||||
def __next__(self):
|
||||
"""Override to call read() instead of readline()."""
|
||||
chunk = self.read(io.DEFAULT_BUFFER_SIZE)
|
||||
@@ -279,11 +282,11 @@ class BaseBorgRepository(abc.ABC):
|
||||
output = self.run(['get-archive-apps', '--path', archive_path])
|
||||
return output.splitlines()
|
||||
|
||||
def restore_archive(self, archive_name, apps=None):
|
||||
def restore_archive(self, archive_name, app_ids=None):
|
||||
"""Restore an archive from this repository to the system."""
|
||||
archive_path = self._get_archive_path(archive_name)
|
||||
passphrase = self.credentials.get('encryption_passphrase', None)
|
||||
api.restore_apps(restore_archive_handler, app_names=apps,
|
||||
api.restore_apps(restore_archive_handler, app_ids=app_ids,
|
||||
create_subvolume=False, backup_file=archive_path,
|
||||
encryption_passphrase=passphrase)
|
||||
|
||||
|
||||
@@ -8,13 +8,18 @@ from unittest.mock import MagicMock, call, patch
|
||||
import pytest
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
|
||||
from plinth.app import App
|
||||
|
||||
from .. import api, forms, repository
|
||||
from ..components import BackupRestore
|
||||
|
||||
# pylint: disable=protected-access
|
||||
|
||||
setup_helper = MagicMock()
|
||||
|
||||
|
||||
def _get_test_manifest(name):
|
||||
return api.validate({
|
||||
return {
|
||||
'config': {
|
||||
'directories': ['/etc/' + name + '/config.d/'],
|
||||
'files': ['/etc/' + name + '/config'],
|
||||
@@ -32,50 +37,42 @@ def _get_test_manifest(name):
|
||||
'name': name,
|
||||
'kind': 'site'
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
def _get_backup_app(name):
|
||||
"""Return a dummy BackupApp object."""
|
||||
return api.BackupApp(name, MagicMock(backup=_get_test_manifest(name)))
|
||||
def _get_backup_component(name):
|
||||
"""Return a BackupRestore component."""
|
||||
return BackupRestore(name, **_get_test_manifest(name))
|
||||
|
||||
|
||||
class TestBackupApp:
|
||||
"""Test the BackupApp class."""
|
||||
@staticmethod
|
||||
def test_run_hook():
|
||||
"""Test running a hook on an application."""
|
||||
packet = api.Packet('backup', 'apps', '/', [])
|
||||
hook = 'testhook_pre'
|
||||
app = MagicMock()
|
||||
backup_app = api.BackupApp('app_name', app)
|
||||
backup_app.run_hook(hook, packet)
|
||||
class AppTest(App):
|
||||
"""Sample App for testing."""
|
||||
app_id = 'test-app'
|
||||
|
||||
app.testhook_pre.assert_has_calls([call(packet)])
|
||||
assert not packet.errors
|
||||
|
||||
app.testhook_pre.reset_mock()
|
||||
app.testhook_pre.side_effect = Exception()
|
||||
backup_app.run_hook(hook, packet)
|
||||
assert packet.errors == [api.BackupError('hook', app, hook=hook)]
|
||||
|
||||
del app.testhook_pre
|
||||
backup_app.run_hook(hook, packet)
|
||||
def _get_test_app(name):
|
||||
"""Return an App."""
|
||||
app = AppTest()
|
||||
app.app_id = name
|
||||
app._all_apps[name] = app
|
||||
app.add(_get_backup_component(name + '-component'))
|
||||
return app
|
||||
|
||||
|
||||
@pytest.mark.usefixtures('load_cfg')
|
||||
class TestBackupProcesses:
|
||||
"""Test cases for backup processes"""
|
||||
|
||||
@staticmethod
|
||||
def test_packet_process_manifests():
|
||||
def test_packet_collected_files_directories():
|
||||
"""Test that directories/files are collected from manifests."""
|
||||
apps = [_get_backup_app('a'), _get_backup_app('b')]
|
||||
packet = api.Packet('backup', 'apps', '/', apps)
|
||||
for app in apps:
|
||||
components = [_get_backup_component('a'), _get_backup_component('b')]
|
||||
packet = api.Packet('backup', 'apps', '/', components)
|
||||
for component in components:
|
||||
for section in ['config', 'data', 'secrets']:
|
||||
for directory in app.manifest[section]['directories']:
|
||||
for directory in getattr(component, section)['directories']:
|
||||
assert directory in packet.directories
|
||||
for file_path in app.manifest[section]['files']:
|
||||
for file_path in getattr(component, section)['files']:
|
||||
assert file_path in packet.files
|
||||
|
||||
@staticmethod
|
||||
@@ -97,50 +94,56 @@ class TestBackupProcesses:
|
||||
restore_handler.assert_called_once()
|
||||
|
||||
@staticmethod
|
||||
@patch('plinth.module_loader.loaded_modules.items')
|
||||
def test_get_all_apps_for_backup(modules):
|
||||
"""Test listing apps supporting backup and needing backup."""
|
||||
apps = [
|
||||
('a', MagicMock(backup=_get_test_manifest('a'))),
|
||||
('b', MagicMock(backup=_get_test_manifest('b'))),
|
||||
('c', MagicMock(backup=None)),
|
||||
('d', MagicMock()),
|
||||
]
|
||||
del apps[3][1].backup
|
||||
modules.return_value = apps
|
||||
@patch('importlib.import_module')
|
||||
@patch('plinth.app.App.list')
|
||||
def test_get_all_components_for_backup(apps_list, import_module):
|
||||
"""Test listing components supporting backup and needing backup."""
|
||||
modules = [MagicMock(), MagicMock(), MagicMock()]
|
||||
import_module.side_effect = modules
|
||||
apps = [_get_test_app('a'), _get_test_app('b'), _get_test_app('c')]
|
||||
modules[1].setup_helper.get_state.side_effect = ['needs-setup']
|
||||
apps_list.return_value = apps
|
||||
|
||||
returned_apps = api.get_all_apps_for_backup()
|
||||
expected_apps = [
|
||||
api.BackupApp('a', apps[0][1]),
|
||||
api.BackupApp('b', apps[1][1]),
|
||||
api.BackupApp('c', apps[2][1])
|
||||
returned_components = api.get_all_components_for_backup()
|
||||
expected_components = [
|
||||
apps[0].components['a-component'],
|
||||
apps[2].components['c-component']
|
||||
]
|
||||
assert returned_apps == expected_apps
|
||||
assert returned_components == expected_components
|
||||
|
||||
@staticmethod
|
||||
@patch('plinth.module_loader.loaded_modules.items')
|
||||
def test_get_apps_in_order(modules):
|
||||
"""Test that apps are listed in correct dependency order."""
|
||||
@patch('plinth.app.App.list')
|
||||
def test_get_components_in_order(apps_list):
|
||||
"""Test that components are listed in correct dependency order."""
|
||||
apps = [
|
||||
('names', MagicMock(backup=_get_test_manifest('names'))),
|
||||
('config', MagicMock(backup=_get_test_manifest('config'))),
|
||||
_get_test_app('names'),
|
||||
_get_test_app('other'),
|
||||
_get_test_app('config')
|
||||
]
|
||||
modules.return_value = apps
|
||||
apps_list.return_value = apps
|
||||
|
||||
app_names = ['config', 'names']
|
||||
apps = api.get_apps_in_order(app_names)
|
||||
assert apps[0].name == 'names'
|
||||
assert apps[1].name == 'config'
|
||||
app_ids = ['config', 'names']
|
||||
components = api.get_components_in_order(app_ids)
|
||||
assert len(components) == 2
|
||||
assert components[0].app_id == 'names'
|
||||
assert components[1].app_id == 'config'
|
||||
|
||||
@staticmethod
|
||||
def test__lockdown_apps():
|
||||
"""Test that locked flag is set for each app."""
|
||||
app_a = MagicMock(locked=False)
|
||||
app_b = MagicMock(locked=None)
|
||||
apps = [MagicMock(app=app_a), MagicMock(app=app_b)]
|
||||
api._lockdown_apps(apps, True)
|
||||
assert app_a.locked is True
|
||||
assert app_b.locked is True
|
||||
apps = [_get_test_app('test-app-1'), _get_test_app('test-app-2')]
|
||||
components = [
|
||||
apps[0].components['test-app-1-component'],
|
||||
apps[1].components['test-app-2-component']
|
||||
]
|
||||
|
||||
api._lockdown_apps(components, True)
|
||||
assert apps[0].locked
|
||||
assert apps[1].locked
|
||||
|
||||
api._lockdown_apps(components, False)
|
||||
assert not apps[0].locked
|
||||
assert not apps[1].locked
|
||||
|
||||
@staticmethod
|
||||
@patch('plinth.action_utils.webserver_is_enabled')
|
||||
@@ -148,19 +151,20 @@ class TestBackupProcesses:
|
||||
@patch('plinth.actions.superuser_run')
|
||||
def test__shutdown_services(run, service_is_running, webserver_is_enabled):
|
||||
"""Test that services are stopped in correct order."""
|
||||
apps = [_get_backup_app('a'), _get_backup_app('b')]
|
||||
components = [_get_backup_component('a'), _get_backup_component('b')]
|
||||
service_is_running.return_value = True
|
||||
webserver_is_enabled.return_value = True
|
||||
state = api._shutdown_services(apps)
|
||||
state = api._shutdown_services(components)
|
||||
|
||||
expected_state = [
|
||||
api.ServiceHandler.create(apps[0],
|
||||
apps[0].manifest['services'][0]),
|
||||
api.ServiceHandler.create(apps[0],
|
||||
apps[0].manifest['services'][1]),
|
||||
api.ServiceHandler.create(apps[1],
|
||||
apps[1].manifest['services'][0]),
|
||||
api.ServiceHandler.create(apps[1], apps[1].manifest['services'][1])
|
||||
api.ServiceHandler.create(components[0],
|
||||
components[0].services[0]),
|
||||
api.ServiceHandler.create(components[0],
|
||||
components[0].services[1]),
|
||||
api.ServiceHandler.create(components[1],
|
||||
components[1].services[0]),
|
||||
api.ServiceHandler.create(components[1],
|
||||
components[1].services[1]),
|
||||
]
|
||||
assert state == expected_state
|
||||
|
||||
@@ -207,21 +211,26 @@ class TestBackupProcesses:
|
||||
@staticmethod
|
||||
def test__run_operation():
|
||||
"""Test that operation runs handler and app hooks."""
|
||||
apps = [_get_backup_app('a'), _get_backup_app('b')]
|
||||
packet = api.Packet('backup', 'apps', '/', apps)
|
||||
packet.apps[0].run_hook = MagicMock()
|
||||
packet.apps[1].run_hook = MagicMock()
|
||||
components = [_get_backup_component('a'), _get_backup_component('b')]
|
||||
packet = api.Packet('backup', 'apps', '/', components)
|
||||
packet.components[0].backup_pre = MagicMock()
|
||||
packet.components[0].backup_post = MagicMock()
|
||||
packet.components[1].backup_pre = MagicMock()
|
||||
packet.components[1].backup_post = MagicMock()
|
||||
handler = MagicMock()
|
||||
api._run_operation(handler, packet)
|
||||
handler.assert_has_calls([call(packet, encryption_passphrase=None)])
|
||||
|
||||
calls = [call('backup_pre', packet), call('backup_post', packet)]
|
||||
packet.apps[0].run_hook.assert_has_calls(calls)
|
||||
packet.apps[1].run_hook.assert_has_calls(calls)
|
||||
calls = [call(packet)]
|
||||
packet.components[0].backup_pre.assert_has_calls(calls)
|
||||
packet.components[0].backup_post.assert_has_calls(calls)
|
||||
packet.components[1].backup_pre.assert_has_calls(calls)
|
||||
packet.components[1].backup_post.assert_has_calls(calls)
|
||||
|
||||
|
||||
class TestBackupModule:
|
||||
"""Tests of the backups django module, like views or forms."""
|
||||
|
||||
@staticmethod
|
||||
def test_file_upload():
|
||||
# posting a video should fail
|
||||
|
||||
@@ -147,7 +147,7 @@ class BaseRestoreView(SuccessMessageMixin, FormView):
|
||||
"""Pass additional keyword args for instantiating the form."""
|
||||
kwargs = super().get_form_kwargs()
|
||||
included_apps = self._get_included_apps()
|
||||
kwargs['apps'] = api.get_apps_in_order(included_apps)
|
||||
kwargs['components'] = api.get_components_in_order(included_apps)
|
||||
return kwargs
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
|
||||
Reference in new issue
Block a user