mirror of
https://github.com/freedombox/FreedomBox.git
synced 2026-11-29 08:25:10 +00:00
Backups, remote repositories: implement init, info and some test
- added functionality to use remote repositories - added some tests Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
1 parent
4eeceaa695
commit
0e2489ec23
6 files changed
+289
-65
No files matched your search
@@ -26,6 +26,8 @@ from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
from plinth import actions
|
||||
from plinth.menu import main_menu
|
||||
from plinth.errors import ActionError
|
||||
from .errors import BorgError, BorgRepositoryDoesNotExistError
|
||||
|
||||
from . import api
|
||||
|
||||
@@ -45,6 +47,23 @@ MANIFESTS_FOLDER = '/var/lib/plinth/backups-manifests/'
|
||||
REPOSITORY = '/var/lib/freedombox/borgbackup'
|
||||
# session variable name that stores when a backup file should be deleted
|
||||
SESSION_PATH_VARIABLE = 'fbx-backups-upload-path'
|
||||
# known errors that come up when remotely accessing a borg repository
|
||||
# 'errors' are error strings to look for in the stacktrace.
|
||||
KNOWN_ERRORS = [{
|
||||
"errors": ["subprocess.TimeoutExpired"],
|
||||
"message": _("Server not reachable - try providing a password."),
|
||||
"raise_as": BorgError,
|
||||
},
|
||||
{
|
||||
"errors": ["Connection refused"],
|
||||
"message": _("Connection refused"),
|
||||
"raise_as": BorgError,
|
||||
},
|
||||
{
|
||||
"errors": ["not a valid repository", "does not exist"],
|
||||
"message": _("Connection works - Repository does not exist"),
|
||||
"raise_as": BorgRepositoryDoesNotExistError,
|
||||
}]
|
||||
|
||||
|
||||
def init():
|
||||
@@ -59,12 +78,17 @@ def setup(helper, old_version=None):
|
||||
helper.call('post', actions.superuser_run, 'backups', ['setup'])
|
||||
|
||||
|
||||
def get_info(repository, password=None):
|
||||
args = ['backups', ['info', '--repository', repository]]
|
||||
def get_info(repository, encryption_passphrase=None, ssh_password=None,
|
||||
ssh_keyfile=None):
|
||||
args = ['info', '--repository', repository]
|
||||
kwargs = {}
|
||||
if password is not None:
|
||||
kwargs['input'] = password.encode()
|
||||
output = actions.superuser_run(*args, **kwargs)
|
||||
if ssh_password is not None:
|
||||
kwargs['input'] = ssh_password.encode()
|
||||
if ssh_keyfile is not None:
|
||||
args += ['--ssh-keyfile', ssh_keyfile]
|
||||
if encryption_passphrase is not None:
|
||||
args += ['--encryption-passphrase', encryption_passphrase]
|
||||
output = actions.superuser_run('backups', args, **kwargs)
|
||||
return json.loads(output)
|
||||
|
||||
|
||||
@@ -81,6 +105,30 @@ def get_archive(name):
|
||||
return None
|
||||
|
||||
|
||||
def test_connection(repository, encryption_passphrase=None, ssh_password=None,
|
||||
ssh_keyfile=None):
|
||||
"""
|
||||
Test connecting to a local or remote borg repository.
|
||||
Tries to detect (and throw) some known ssh or borg errors.
|
||||
Returns 'borg info' information otherwise.
|
||||
"""
|
||||
try:
|
||||
# TODO: instead of passing encryption_passphrase, ssh_password and
|
||||
# ssh_keyfile around all the time, try using an 'options' dict.
|
||||
message = get_info(repository,
|
||||
encryption_passphrase=encryption_passphrase,
|
||||
ssh_password=ssh_password, ssh_keyfile=ssh_keyfile)
|
||||
return message
|
||||
except ActionError as err:
|
||||
caught_error = str(err)
|
||||
for known_error in KNOWN_ERRORS:
|
||||
for error in known_error["errors"]:
|
||||
if error in caught_error:
|
||||
raise known_error["raise_as"](known_error["message"])
|
||||
else:
|
||||
raise
|
||||
|
||||
|
||||
def _backup_handler(packet):
|
||||
"""Performs backup operation on packet."""
|
||||
if not os.path.exists(MANIFESTS_FOLDER):
|
||||
@@ -108,6 +156,24 @@ def create_archive(name, app_names):
|
||||
api.backup_apps(_backup_handler, app_names, name)
|
||||
|
||||
|
||||
def create_repository(repository, encryption, encryption_passphrase=None,
|
||||
ssh_keyfile=None, ssh_password=None):
|
||||
cmd = ['init', '--repository', repository, '--encryption', encryption]
|
||||
if ssh_keyfile:
|
||||
cmd += ['--ssh-keyfile', ssh_keyfile]
|
||||
if encryption_passphrase:
|
||||
cmd += ['--encryption-passphrase', encryption_passphrase]
|
||||
|
||||
kwargs = {}
|
||||
if ssh_password:
|
||||
kwargs['input'] = ssh_password.encode()
|
||||
|
||||
output = actions.superuser_run('backups', cmd, **kwargs)
|
||||
if output:
|
||||
output = json.loads(output)
|
||||
return output
|
||||
|
||||
|
||||
def delete_archive(name):
|
||||
actions.superuser_run('backups', ['delete', '--name', name])
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#
|
||||
# This file is part of FreedomBox.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from plinth.errors import PlinthError
|
||||
|
||||
|
||||
class BorgError(PlinthError):
|
||||
"""Generic class for borg errors that """
|
||||
pass
|
||||
|
||||
|
||||
class BorgRepositoryDoesNotExistError(BorgError):
|
||||
"""Borg access to a repository works but the repository does not exist"""
|
||||
pass
|
||||
@@ -88,13 +88,12 @@ class CreateRepositoryForm(forms.Form):
|
||||
repository = forms.CharField(
|
||||
label=_('SSH Repository Path'), strip=True,
|
||||
help_text=_('Path of the new repository. Example: '
|
||||
'<i>user@host/path/to/repo/</i>'))
|
||||
'<i>user@host:~/path/to/repo/</i>'))
|
||||
ssh_password = forms.CharField(
|
||||
label=_('SSH password'), strip=True,
|
||||
help_text=_('Password of the SSH Server.<br />'
|
||||
'If you have set up <a href="https://www.ssh.com/ssh/key/"'
|
||||
'target="_blank">SSH key-based authentication</a> you can '
|
||||
'omit the password.'),
|
||||
label=_('SSH server password'), strip=True,
|
||||
help_text=_('Password of the SSH Server.<br />'
|
||||
'SSH key-based authentication is not yet possible.'),
|
||||
widget=forms.PasswordInput(),
|
||||
required=False)
|
||||
encryption = forms.ChoiceField(
|
||||
label=_('Encryption'),
|
||||
@@ -104,33 +103,33 @@ class CreateRepositoryForm(forms.Form):
|
||||
'<b>You need this password to restore a backup!</b>')),
|
||||
choices=[('repokey', 'Key in Repository'), ('none', 'None')]
|
||||
)
|
||||
passphrase = forms.CharField(
|
||||
encryption_passphrase = forms.CharField(
|
||||
label=_('Passphrase'),
|
||||
help_text=_('Passphrase; Only needed when using encryption.'),
|
||||
widget=forms.PasswordInput(),
|
||||
required=False
|
||||
)
|
||||
confirm_passphrase = forms.CharField(
|
||||
confirm_encryption_passphrase = forms.CharField(
|
||||
label=_('Confirm Passphrase'),
|
||||
help_text=_('Repeat the passphrase.'),
|
||||
widget=forms.PasswordInput(),
|
||||
required=False
|
||||
)
|
||||
store_passphrase = forms.BooleanField(
|
||||
label=_('Store passphrase on FreedomBox'),
|
||||
store_passwords = forms.BooleanField(
|
||||
label=_('Store passwords on FreedomBox'),
|
||||
help_text=format_lazy(
|
||||
_('Store the passphrase on your {box_name}.'
|
||||
'<br />You need to store the passphrase if you want to run '
|
||||
_('Store the passwords on your {box_name}.'
|
||||
'<br />You need to store passwords if you want to run '
|
||||
'recurrent backups.'), box_name=_(cfg.box_name)),
|
||||
required=False
|
||||
)
|
||||
|
||||
def clean(self):
|
||||
cleaned_data = super(CreateRepositoryForm, self).clean()
|
||||
passphrase = cleaned_data.get("passphrase")
|
||||
confirm_passphrase = cleaned_data.get("confirm_passphrase")
|
||||
passphrase = cleaned_data.get("encryption_passphrase")
|
||||
confirm_passphrase = cleaned_data.get("confirm_encryption_passphrase")
|
||||
|
||||
if passphrase != confirm_passphrase:
|
||||
raise forms.ValidationError(
|
||||
"passphrase and confirm_passphrase do not match"
|
||||
"The entered encryption passphrases do not match"
|
||||
)
|
||||
@@ -40,11 +40,12 @@ from django.utils.translation import ugettext_lazy
|
||||
from django.views.generic import View, FormView, TemplateView
|
||||
|
||||
from plinth import actions, kvstore
|
||||
from plinth.errors import PlinthError, ActionError
|
||||
from plinth.errors import PlinthError
|
||||
from plinth.modules import backups, storage
|
||||
|
||||
from . import api, forms, SESSION_PATH_VARIABLE, REPOSITORY
|
||||
from .decorators import delete_tmp_backup_file
|
||||
from .errors import BorgRepositoryDoesNotExistError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -316,22 +317,41 @@ class CreateRepositoryView(SuccessMessageMixin, FormView):
|
||||
def get_context_data(self, **kwargs):
|
||||
"""Return additional context for rendering the template."""
|
||||
context = super().get_context_data(**kwargs)
|
||||
context['title'] = _('Create new repository')
|
||||
context['title'] = _('Create remote backup repository')
|
||||
context['subsubmenu'] = subsubmenu
|
||||
return context
|
||||
|
||||
def form_valid(self, form):
|
||||
"""Restore files from the archive on valid form submission."""
|
||||
repository = form.cleaned_data['repository']
|
||||
encryption = form.cleaned_data['encryption']
|
||||
encryption_passphrase = form.cleaned_data['encryption_passphrase']
|
||||
ssh_password = form.cleaned_data['ssh_password']
|
||||
ssh_keyfile = form.cleaned_data['ssh_keyfile']
|
||||
|
||||
# TODO: create borg repository if it doesn't exist
|
||||
import pdb; pdb.set_trace()
|
||||
try:
|
||||
backups.test_connection(repository, ssh_password)
|
||||
except BorgRepositoryDoesNotExistError:
|
||||
kwargs = {}
|
||||
if encryption_passphrase:
|
||||
kwargs['encryption_passphrase'] = encryption_passphrase
|
||||
if ssh_keyfile:
|
||||
kwargs['ssh_keyfile'] = ssh_keyfile
|
||||
backups.create_repository(repository, encryption, **kwargs)
|
||||
|
||||
repositories = kvstore.get_default('backups_repositories', [])
|
||||
if repositories:
|
||||
repositories = json.loads(repositories)
|
||||
new_repo = {
|
||||
'uuid': str(uuid1()),
|
||||
'repository': form.cleaned_data['repository'],
|
||||
'encryption': form.cleaned_data['encryption'],
|
||||
'repository': repository,
|
||||
'encryption': encryption,
|
||||
}
|
||||
if form.cleaned_data['store_passphrase']:
|
||||
new_repo['passphrase'] = form.cleaned_data['passphrase']
|
||||
if form.cleaned_data['store_passwords']:
|
||||
new_repo['encryption_passphrase'] = \
|
||||
form.cleaned_data['encryption_passphrase']
|
||||
repositories.append(new_repo)
|
||||
kvstore.set('backups_repositories', json.dumps(repositories))
|
||||
return super().form_valid(form)
|
||||
@@ -342,18 +362,12 @@ class TestRepositoryView(TemplateView):
|
||||
template_name = 'backups_test_repository.html'
|
||||
|
||||
def post(self, request):
|
||||
# TODO: add support for borg encryption
|
||||
context = self.get_context_data()
|
||||
repository = request.POST['backups-repository']
|
||||
ssh_password = request.POST['backups-ssh_password']
|
||||
try:
|
||||
info = backups.get_info(repository, password=ssh_password)
|
||||
except ActionError as err:
|
||||
if "subprocess.TimeoutExpired" in str(err):
|
||||
msg = _("Server not reachable - try providing a password.")
|
||||
context["error"] = msg
|
||||
else:
|
||||
context["error"] = str(err)
|
||||
else:
|
||||
context["message"] = info
|
||||
(error, message) = backups.test_connection(repository, ssh_password)
|
||||
context["message"] = message
|
||||
context["error"] = error
|
||||
|
||||
return self.render_to_response(context)
|
||||
Reference in new issue
Block a user