File: views.py

package info (click to toggle)
freedombox 26.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 82,976 kB
  • sloc: python: 48,504; javascript: 1,736; xml: 481; makefile: 290; sh: 167; php: 32
file content (533 lines) | stat: -rw-r--r-- 19,761 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Views for the backups app.
"""

import contextlib
import logging
import os
import subprocess
from urllib.parse import unquote

from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.http import Http404, HttpRequest, StreamingHttpResponse
from django.shortcuts import redirect
from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy
from django.views.decorators.http import require_POST
from django.views.generic import FormView, TemplateView, View

from plinth.errors import PlinthError
from plinth.modules import backups, storage
from plinth.views import AppView

from . import (SESSION_PATH_VARIABLE, api, errors, forms, get_known_hosts_path,
               is_ssh_hostkey_verified, privileged)
from .decorators import delete_tmp_backup_file
from .repository import (BorgRepository, SshBorgRepository, get_instance,
                         get_repositories)

logger = logging.getLogger(__name__)


@contextlib.contextmanager
def handle_common_errors(request: HttpRequest):
    """If any known Borg exceptions occur, show proper error messages."""
    try:
        yield
    except errors.BorgError as exception:
        messages.error(request, exception.args[0])


@method_decorator(delete_tmp_backup_file, name='dispatch')
class BackupsView(AppView):
    """View to show list of archives."""

    app_id = 'backups'
    template_name = 'backups.html'

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['repositories'] = [
            repository.get_view_content() for repository in get_repositories()
        ]
        return context


class ScheduleView(SuccessMessageMixin, FormView):
    """View to edit a backup schedule."""

    form_class = forms.ScheduleForm
    prefix = 'backups_schedule'
    template_name = 'form.html'
    success_url = reverse_lazy('backups:index')
    success_message = gettext_lazy('Backup schedule updated.')

    def get_initial(self):
        """Return the values to fill in the form."""
        initial = super().get_initial()
        schedule = get_instance(self.kwargs['uuid']).schedule
        initial.update({
            'enabled': schedule.enabled,
            'daily_to_keep': schedule.daily_to_keep,
            'weekly_to_keep': schedule.weekly_to_keep,
            'monthly_to_keep': schedule.monthly_to_keep,
            'run_at_hour': schedule.run_at_hour,
            'unselected_apps': schedule.unselected_apps,
        })
        return initial

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Schedule Backups')
        return context

    def form_valid(self, form):
        """Update backup schedule."""
        repository = get_instance(self.kwargs['uuid'])
        schedule = repository.schedule
        data = form.cleaned_data
        schedule.enabled = data['enabled']
        schedule.daily_to_keep = data['daily_to_keep']
        schedule.weekly_to_keep = data['weekly_to_keep']
        schedule.monthly_to_keep = data['monthly_to_keep']
        schedule.run_at_hour = data['run_at_hour']

        components = api.get_all_components_for_backup()
        unselected_apps = [
            component.app_id for component in components
            if component.app_id not in data['selected_apps']
        ]
        schedule.unselected_apps = unselected_apps

        repository.save()
        backups.on_schedule_save(repository)
        return super().form_valid(form)


class CreateArchiveView(FormView):
    """View to create a new archive."""

    form_class = forms.CreateArchiveForm
    prefix = 'backups'
    template_name = 'form.html'
    success_url = reverse_lazy('backups:index')

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Create a new backup')
        return context

    def get_initial(self):
        """Return initialization arguments to the form."""
        initial = super().get_initial()
        if 'app_id' in self.kwargs:
            initial['selected_apps'] = [self.kwargs['app_id']]

        return initial

    def form_valid(self, form):
        """Create the archive on valid form submission."""
        repository = get_instance(form.cleaned_data['repository'])
        if repository.flags.get('mountable'):
            repository.mount()

        name = form.cleaned_data['name']
        if not name:
            name = repository.generate_archive_name()

        selected_apps = form.cleaned_data['selected_apps']
        with handle_common_errors(self.request):
            repository.create_archive(name, selected_apps)
            messages.success(self.request, _('Archive created.'))

        return super().form_valid(form)


class DeleteArchiveView(TemplateView):
    """View to delete an archive."""
    template_name = 'backups_delete.html'

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Delete Archive')
        repository = get_instance(self.kwargs['uuid'])
        context['archive'] = repository.get_archive(self.kwargs['name'])
        if context['archive'] is None:
            raise Http404

        return context

    def post(self, request, uuid, name):
        """Delete the archive."""
        repository = get_instance(uuid)
        with handle_common_errors(self.request):
            repository.delete_archive(name)
            messages.success(request, _('Archive deleted.'))

        return redirect('backups:index')


class UploadArchiveView(FormView):
    form_class = forms.UploadForm
    prefix = 'backups'
    template_name = 'backups_upload.html'
    success_url = reverse_lazy('backups:restore-from-upload')

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Upload and restore a backup')
        try:
            mount_info = storage.get_mount_info('/')
        except PlinthError as exception:
            logger.exception(
                'Error getting information about root partition: %s',
                exception)
        else:
            # The maximum file size that can be uploaded and restored is at
            # most half of the available disk space:
            # - Django stores uploaded files that do not fit into memory to
            #   disk (/tmp/). These are only copied by form_valid() after
            #   the upload is finished.
            # - For restoring it's highly advisable to have at least as much
            #   free disk space as the file size.
            context['max_filesize'] = storage.format_bytes(
                mount_info['free_bytes'] / 2)

        return context

    def form_valid(self, form):
        """Store uploaded file."""
        uploaded_file = self.request.FILES['backups-file']
        # Hold on to Django's uploaded file. It will be used by other views.
        with handle_common_errors(self.request):
            privileged.add_uploaded_archive(
                uploaded_file.name, uploaded_file.temporary_file_path())
            self.request.session[SESSION_PATH_VARIABLE] = str(
                privileged.BACKUPS_UPLOAD_PATH / uploaded_file.name)
            messages.success(self.request, _('Upload successful.'))

        return super().form_valid(form)


class BaseRestoreView(FormView):
    """View to restore files from an archive."""
    form_class = forms.RestoreForm
    prefix = 'backups'
    template_name = 'backups_restore.html'
    success_url = reverse_lazy('backups:index')

    def get_form_kwargs(self):
        """Pass additional keyword args for instantiating the form."""
        kwargs = super().get_form_kwargs()
        included_apps = self._get_included_apps()
        kwargs['components'] = api.get_components_in_order(included_apps)
        return kwargs

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Restore')
        context['name'] = self.kwargs.get('name', None)
        context['uuid'] = self.kwargs.get('uuid', None)
        return context

    def _get_included_apps(self):
        """To be overridden."""
        raise NotImplementedError


class RestoreFromUploadView(BaseRestoreView):
    """View to restore files from an (uploaded) exported archive."""

    def get(self, *args, **kwargs):
        path = self.request.session.get(SESSION_PATH_VARIABLE)
        if not os.path.isfile(path):
            messages.error(self.request, _('No backup file found.'))
            return redirect(reverse_lazy('backups:index'))

        return super().get(*args, **kwargs)

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Restore from uploaded file')
        return context

    def _get_included_apps(self):
        """Save some data used to instantiate the form."""
        path = self.request.session.get(SESSION_PATH_VARIABLE)
        return privileged.get_exported_archive_apps(path)

    def form_valid(self, form):
        """Restore files from the archive on valid form submission."""
        path = self.request.session.get(SESSION_PATH_VARIABLE)
        selected_apps = form.cleaned_data['selected_apps']
        with handle_common_errors(self.request):
            backups.restore_from_upload(path, selected_apps)
            messages.success(self.request, _('Restored files from backup.'))

        return super().form_valid(form)


class RestoreArchiveView(BaseRestoreView):
    """View to restore files from an archive."""

    def _get_included_apps(self):
        """Save some data used to instantiate the form."""
        name = unquote(self.kwargs['name'])
        uuid = self.kwargs['uuid']
        repository = get_instance(uuid)
        return repository.get_archive_apps(name)

    def form_valid(self, form):
        """Restore files from the archive on valid form submission."""
        repository = get_instance(self.kwargs['uuid'])
        selected_apps = form.cleaned_data['selected_apps']
        with handle_common_errors(self.request):
            repository.restore_archive(self.kwargs['name'], selected_apps)
            messages.success(self.request, _('Restored files from backup.'))

        return super().form_valid(form)


class DownloadArchiveView(View):
    """View to export and download an archive as stream."""

    def get(self, request, uuid, name):
        repository = get_instance(uuid)
        filename = f'{name}.tar.gz'

        response = StreamingHttpResponse(repository.get_download_stream(name),
                                         content_type='application/gzip')
        response['Content-Disposition'] = 'attachment; filename="%s"' % \
            filename
        return response


class AddRepositoryView(FormView):
    """View to create a new backup repository."""
    form_class = forms.AddRepositoryForm
    template_name = 'backups_add_repository.html'
    success_url = reverse_lazy('backups:index')

    def get(self, request, *args, **kwargs):
        """If there are no disks available for adding, throw error."""
        if not forms.get_disk_choices():
            messages.error(
                request,
                _('No additional disks available to add a repository.'))
            return redirect(reverse_lazy('backups:index'))

        return super().get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Create backup repository')
        return context

    def form_valid(self, form):
        """Create and save a Borg repository."""
        path = os.path.join(form.cleaned_data.get('disk'), 'FreedomBoxBackups')
        encryption = form.cleaned_data.get('encryption')
        encryption_passphrase = form.cleaned_data.get('encryption_passphrase')
        if encryption == 'none':
            encryption_passphrase = None

        credentials = {'encryption_passphrase': encryption_passphrase}
        with handle_common_errors(self.request):
            repository = BorgRepository(path, credentials)
            if _save_repository(self.request, repository):
                messages.success(self.request, _('Added new repository.'))
                return super().form_valid(form)

        return redirect(reverse_lazy('backups:add-repository'))


class AddRemoteRepositoryView(FormView):
    """View to create a new remote backup repository."""
    form_class = forms.AddRemoteRepositoryForm
    template_name = 'backups_add_remote_repository.html'

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Create remote backup repository')
        return context

    def form_valid(self, form):
        """Create and save Borg repository.

        Present the Host key verification form if necessary.
        """
        path = form.cleaned_data.get('repository')
        encryption_passphrase = form.cleaned_data.get('encryption_passphrase')
        if form.cleaned_data.get('encryption') == 'none':
            encryption_passphrase = None

        credentials = {
            'ssh_password': form.cleaned_data.get('ssh_password'),
            'encryption_passphrase': encryption_passphrase
        }
        with handle_common_errors(self.request):
            repository = SshBorgRepository(path, credentials)
            repository.verfied = False
            repository.save()
            messages.success(self.request,
                             _('Added new remote SSH repository.'))

        url = reverse('backups:verify-ssh-hostkey', args=[repository.uuid])
        return redirect(url)


class VerifySshHostkeyView(FormView):
    """View to verify SSH Hostkey of the remote repository."""
    form_class = forms.VerifySshHostkeyForm
    template_name = 'verify_ssh_hostkey.html'
    success_url = reverse_lazy('backups:index')
    repository = None

    def get_form_kwargs(self):
        """Pass additional keyword args for instantiating the form."""
        kwargs = super().get_form_kwargs()
        kwargs['hostname'] = self._get_repository().hostname
        return kwargs

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Verify SSH hostkey')
        context['hostname'] = self._get_repository().hostname
        return context

    def _get_repository(self):
        """Fetch the repository data from DB only once."""
        if not self.repository:
            self.repository = get_instance(self.kwargs['uuid'])

        return self.repository

    @staticmethod
    def _add_ssh_hostkey(ssh_public_key):
        """Add the given SSH key to known_hosts."""
        known_hosts_path = get_known_hosts_path()
        known_hosts_path.parent.mkdir(parents=True, exist_ok=True)
        known_hosts_path.touch()

        with known_hosts_path.open('a', encoding='utf-8') as known_hosts_file:
            known_hosts_file.write(ssh_public_key + '\n')

    def get(self, *args, **kwargs):
        """Skip this view if host is already verified."""
        if not is_ssh_hostkey_verified(self._get_repository().hostname):
            return super().get(*args, **kwargs)

        messages.success(self.request, _('SSH host already verified.'))
        if _save_repository(self.request, self._get_repository()):
            return redirect(reverse_lazy('backups:index'))

        return redirect(reverse_lazy('backups:add-remote-repository'))

    def form_valid(self, form):
        """Create and store the repository."""
        ssh_public_key = form.cleaned_data['ssh_public_key']
        with handle_common_errors(self.request):
            self._add_ssh_hostkey(ssh_public_key)
            messages.success(self.request, _('SSH host verified.'))
            if _save_repository(self.request, self._get_repository()):
                return redirect(reverse_lazy('backups:index'))

        return redirect(reverse_lazy('backups:add-remote-repository'))


def _save_repository(request, repository):
    """Initialize and save a repository. Convert errors to messages."""
    try:
        repository.initialize()
        repository.verified = True
        repository.save()
        return True
    except subprocess.CalledProcessError as exception:
        if exception.returncode in (6, 7):
            message = _('SSH host public key could not be verified.')
        elif exception.returncode == 5:
            message = _('Authentication to remote server failed.')
        else:
            message = _('Error establishing connection to server: {}').format(
                str(exception))
    except Exception as exception:
        message = str(exception)
        logger.exception('Error adding repository: %s', exception)

    messages.error(request, message)
    # Remove the repository so that the user can have another go at
    # creating it.
    try:
        repository.remove()
        messages.error(request, _('Repository removed.'))
    except KeyError:
        pass

    return False


class RemoveRepositoryView(TemplateView):
    """View to delete a repository."""
    template_name = 'backups_repository_remove.html'

    def get_context_data(self, uuid, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Remove Repository')
        context['repository'] = get_instance(uuid)
        return context

    def post(self, request, uuid):
        """Delete the repository on confirmation."""
        with handle_common_errors(self.request):
            repository = get_instance(uuid)
            repository.remove()
            messages.success(
                request, _('Repository removed. Backups were not deleted.'))

        return redirect('backups:index')


@require_POST
def umount_repository(request, uuid):
    """View to unmount a remote SSH repository."""
    repository = SshBorgRepository.load(uuid)
    repository.umount()
    if repository.is_mounted:
        messages.error(request, _('Unmounting failed!'))

    return redirect('backups:index')


@require_POST
def mount_repository(request, uuid):
    """View to mount a remote SSH repository."""
    # Do not mount unverified ssh repositories. Prompt for verification.
    if not get_instance(uuid).is_usable():
        return redirect('backups:verify-ssh-hostkey', uuid=uuid)

    repository = SshBorgRepository.load(uuid)
    try:
        repository.mount()
    except Exception as err:
        msg = "%s: %s" % (_('Mounting failed'), str(err))
        messages.error(request, msg)
    else:
        if not repository.is_mounted:
            messages.error(request, _('Mounting failed'))

    return redirect('backups:index')