mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 17:36:05 +00:00
feat(vmbackups): delete a backup; the Backups page
Backups in the menu now opens a page of every backup, newest first, filtered by VM name, target and state; a removed VM's backups are marked. Each backup, there and on the VM's Backups tab, has a Delete button (also DELETE /api/v1/backups/<uuid>/, 202 with the job). The backup.delete job holds the backup and its target. Through the first of the target's computes that reaches its pool, it marks the backup deleting, removes the manifest first, so the target no longer holds a complete backup, then every other file named from the backup's UUID (also those a failed backup left), then the row. Recovery runs the same steps again. A backup being made is refused: its job is cancelled instead. States and consistency are shown in the reader's language.
This commit is contained in:
parent
f4559acbc7
commit
7227867d78
17 changed files with 607 additions and 117 deletions
|
|
@ -9,11 +9,17 @@ from operations.api.serializers import OperationSerializer
|
|||
from webvirtcloud.serializers import ErrorSerializer
|
||||
|
||||
from .models import Backup
|
||||
from .serializers import BackupSerializer, CreateBackupSerializer
|
||||
from .serializers import BackupSerializer, CreateBackupSerializer, SubmissionSerializer
|
||||
|
||||
|
||||
def _accepted(request, op):
|
||||
return Response(OperationSerializer(op, context={"request": request}).data, status=status.HTTP_202_ACCEPTED,
|
||||
headers={"Location": reverse("operation-detail", args=[op.pk])})
|
||||
|
||||
|
||||
class BackupViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
|
||||
"""VM backups: list, read, and back a VM up (a job, answered 202)."""
|
||||
"""VM backups: list, read, back a VM up and delete a backup (jobs,
|
||||
answered 202)."""
|
||||
|
||||
permission_classes = [IsSuperUser]
|
||||
serializer_class = BackupSerializer
|
||||
|
|
@ -27,6 +33,12 @@ class BackupViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.G
|
|||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
data = serializer.validated_data
|
||||
raw = {"instance": data["instance"].pk, "target": data["target"].pk, "frozen": data["frozen"]}
|
||||
op = jobs.submit("backup.create", request.user, raw, data["submission_key"])
|
||||
return Response(OperationSerializer(op, context={"request": request}).data, status=status.HTTP_202_ACCEPTED,
|
||||
headers={"Location": reverse("operation-detail", args=[op.pk])})
|
||||
return _accepted(request, jobs.submit("backup.create", request.user, raw, data["submission_key"]))
|
||||
|
||||
@extend_schema(request=SubmissionSerializer, responses={202: OperationSerializer, 409: ErrorSerializer})
|
||||
def destroy(self, request, uuid=None):
|
||||
backup = self.get_object()
|
||||
serializer = SubmissionSerializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
key = serializer.validated_data["submission_key"]
|
||||
return _accepted(request, jobs.submit("backup.delete", request.user, {"backup": str(backup.uuid)}, key))
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from uuid import uuid4
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.db import transaction
|
||||
|
|
@ -20,6 +20,7 @@ from operations.models import Claim, Operation
|
|||
from operations.utils import safe_text, say
|
||||
from vrtManager import util
|
||||
from vrtManager.backup import backup_file_names, check_target_space, put_file, remove_files, target_pool, wvmBackup
|
||||
from vrtManager.connection import wvmConnect
|
||||
from vrtManager.instance import LIVE_CLONE_MIN_LIBVIRT
|
||||
|
||||
from .models import Backup, BackupFile, BackupTarget
|
||||
|
|
@ -407,3 +408,73 @@ class CreateBackup(Kind):
|
|||
else:
|
||||
action = f"back up to {op.intent['target']}"
|
||||
return _log(op, state, action)
|
||||
|
||||
|
||||
def _target_pool(target):
|
||||
"""The target's pool through the first of its computes that reaches it."""
|
||||
for row in target.pools.select_related("compute").order_by("compute__name"):
|
||||
c = row.compute
|
||||
try:
|
||||
return target_pool(wvmConnect(c.hostname, c.login, c.password, c.type), row.pool, row.pool_uuid)
|
||||
except libvirtError:
|
||||
continue
|
||||
raise util.OperationError(_("No compute of backup target %(target)s reaches its storage pool"), target=target.name)
|
||||
|
||||
|
||||
def _backup(params):
|
||||
return Backup.objects.select_related("target").get(uuid=params["backup"])
|
||||
|
||||
|
||||
@register
|
||||
class DeleteBackup(Kind):
|
||||
"""The manifest goes first, so the target no longer holds a complete
|
||||
backup; then the other files of the backup, then its row."""
|
||||
|
||||
name = "backup.delete"
|
||||
label = _("Delete backup")
|
||||
|
||||
def normalize(self, raw):
|
||||
return {"backup": str(UUID(str(raw["backup"])))}
|
||||
|
||||
def plan(self, user, params):
|
||||
_superuser(user)
|
||||
backup = _backup(params)
|
||||
if backup.state == Backup.CREATING:
|
||||
raise util.OperationError(_("This backup is being made; cancel its job to stop it"))
|
||||
return Plan(
|
||||
claims={claims.backup_key(backup.uuid): Claim.EXCLUSIVE,
|
||||
claims.backup_target_key(backup.target_id): Claim.EXCLUSIVE},
|
||||
resource=claims.backup_key(backup.uuid),
|
||||
label=f"{backup.target.name}/{backup.vm_name}",
|
||||
intent={"compute": backup.compute_name, "vm": backup.vm_name, "uuid": backup.vm_uuid,
|
||||
"time": timezone.localtime(backup.created_at).strftime("%Y-%m-%d %H:%M")},
|
||||
)
|
||||
|
||||
def run(self, op, ctx):
|
||||
_superuser(op.user)
|
||||
backup = _backup(op.params)
|
||||
pool = _target_pool(backup.target)
|
||||
ctx.record_intent(deleting=True)
|
||||
return self._delete(backup, pool)
|
||||
|
||||
@staticmethod
|
||||
def _delete(backup, pool):
|
||||
Backup.objects.filter(pk=backup.pk).update(state=Backup.DELETING)
|
||||
# another compute may have written the files: this one's pool lists them after a refresh
|
||||
pool.refresh(0)
|
||||
manifest = f"{backup.prefix}-manifest.json"
|
||||
remove_files(pool, [manifest])
|
||||
remove_files(pool, [n for n in pool.listVolumes() if n.startswith(backup.prefix + "-") and n != manifest])
|
||||
backup.delete()
|
||||
return {}
|
||||
|
||||
def reconcile(self, op):
|
||||
backup = Backup.objects.select_related("target").filter(uuid=op.params["backup"]).first()
|
||||
if backup is None:
|
||||
return Outcome(Operation.SUCCEEDED)
|
||||
return Outcome(Operation.SUCCEEDED, result=self._delete(backup, _target_pool(backup.target)))
|
||||
|
||||
def log_entry(self, op, state):
|
||||
backup = f"Backup {op.intent['time']} of {op.intent['vm']}"
|
||||
message = f"{backup} deleted" if state == Operation.SUCCEEDED else f"{backup}: delete ({state})"
|
||||
return op.intent["compute"], op.intent["vm"], op.intent["uuid"], message
|
||||
|
|
|
|||
|
|
@ -27,3 +27,7 @@ class CreateBackupSerializer(serializers.Serializer):
|
|||
target = serializers.PrimaryKeyRelatedField(queryset=BackupTarget.objects.all())
|
||||
frozen = serializers.BooleanField(default=False)
|
||||
submission_key = serializers.CharField(write_only=True)
|
||||
|
||||
|
||||
class SubmissionSerializer(serializers.Serializer):
|
||||
submission_key = serializers.CharField(write_only=True)
|
||||
|
|
|
|||
1
vmbackups/templates/vmbackups/consistency.html
Normal file
1
vmbackups/templates/vmbackups/consistency.html
Normal file
|
|
@ -0,0 +1 @@
|
|||
{% load i18n %}{% if backup.consistency == "offline" %}{% trans "Shut off" %}{% elif backup.consistency == "frozen" %}{% trans "Frozen" %}{% elif backup.consistency == "crash" %}{% trans "Crash-consistent" %}{% else %}–{% endif %}
|
||||
3
vmbackups/templates/vmbackups/delete_form.html
Normal file
3
vmbackups/templates/vmbackups/delete_form.html
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
{% load i18n %}{% load operations %}{% load bootstrap_icons %}{% if backup.state != "creating" %}<form method="post" action="{% url 'vmbackups:delete' backup.uuid %}" class="d-inline">{% csrf_token %}{% submission_key %}
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger" aria-label="{% trans "Delete" %}" title="{% trans "Delete" %}"
|
||||
data-confirm="{% blocktrans with time=backup.created_at|date:"Y-m-d H:i" vm=backup.vm_name %}Delete the backup of {{ vm }} taken {{ time }}? Its files are removed from the target.{% endblocktrans %}">{% bs_icon 'trash' %}</button></form>{% endif %}
|
||||
71
vmbackups/templates/vmbackups/index.html
Normal file
71
vmbackups/templates/vmbackups/index.html
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
{% extends "base.html" %}
|
||||
{% load i18n %}
|
||||
{% load bootstrap_icons %}
|
||||
{% load operations %}
|
||||
|
||||
{% block title %}{% trans "Backups" %}{% endblock %}
|
||||
|
||||
{% block page_heading %}{% trans "Backups" %}{% endblock page_heading %}
|
||||
|
||||
{% block page_heading_extra %}<a class="btn btn-outline-primary btn-sm" href="{% url 'vmbackups:targets' %}">{% bs_icon 'hdd-network' %} {% trans "Backup targets" %}</a>{% endblock page_heading_extra %}
|
||||
|
||||
{% block content %}
|
||||
<form method="get" class="row g-2 mb-3" aria-label="{% trans "Filter" %}">
|
||||
<div class="col-12 col-md">
|
||||
<label class="visually-hidden" for="filter-vm">{% trans "VM" %}</label>
|
||||
<input type="search" class="form-control" id="filter-vm" name="vm" value="{{ vm }}" placeholder="{% trans "VM name" %}">
|
||||
</div>
|
||||
<div class="col-6 col-md-auto">
|
||||
<label class="visually-hidden" for="filter-target">{% trans "Target" %}</label>
|
||||
<select class="form-select" id="filter-target" name="target">
|
||||
<option value="">{% trans "All targets" %}</option>
|
||||
{% for t in targets %}<option value="{{ t.id }}"{% if target == t.id|stringformat:"d" %} selected{% endif %}>{{ t.name }}</option>{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-6 col-md-auto">
|
||||
<label class="visually-hidden" for="filter-state">{% trans "State" %}</label>
|
||||
<select class="form-select" id="filter-state" name="state">
|
||||
<option value="">{% trans "All states" %}</option>
|
||||
<option value="ready"{% if state == "ready" %} selected{% endif %}>{% trans "Ready" %}</option>
|
||||
<option value="creating"{% if state == "creating" %} selected{% endif %}>{% trans "Creating" %}</option>
|
||||
<option value="failed"{% if state == "failed" %} selected{% endif %}>{% trans "Failed" %}</option>
|
||||
<option value="deleting"{% if state == "deleting" %} selected{% endif %}>{% trans "Deleting" %}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-12 col-md-auto d-grid">
|
||||
<button type="submit" class="btn btn-outline-secondary">{% bs_icon 'filter' %} {% trans "Filter" %}</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{% if rows %}
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover align-middle" id="backups">
|
||||
<thead>
|
||||
<tr><th>{% trans "Time" %}</th><th>{% trans "VM" %}</th><th>{% trans "Target" %}</th><th>{% trans "Consistency" %}</th>
|
||||
<th class="text-end">{% trans "Size" %}</th><th>{% trans "State" %}</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for backup in rows %}
|
||||
<tr>
|
||||
<td class="text-nowrap">{{ backup.created_at|date:"Y-m-d H:i" }}</td>
|
||||
<td>
|
||||
{% if backup.instance %}<a href="{% url 'instances:instance' backup.instance.id %}">{{ backup.vm_name }}</a>
|
||||
{% else %}{{ backup.vm_name }} <span class="badge text-bg-secondary">{% trans "removed" %}</span>{% endif %}
|
||||
<div class="small text-body-secondary">{{ backup.compute_name }}</div>
|
||||
</td>
|
||||
<td>{{ backup.target.name }}</td>
|
||||
<td>{% include "vmbackups/consistency.html" %}</td>
|
||||
<td class="text-end text-nowrap">{% if backup.size %}{{ backup.size|filesizeformat }}{% else %}–{% endif %}</td>
|
||||
<td>{% include "vmbackups/state.html" %}</td>
|
||||
<td class="text-end">{% include "vmbackups/delete_form.html" %}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% elif vm or target or state %}
|
||||
<div class="alert alert-info">{% trans "No backup matches the filter." %}</div>
|
||||
{% else %}
|
||||
<div class="alert alert-info">{% trans "No backup yet. Back a VM up from its Backups tab." %}</div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
1
vmbackups/templates/vmbackups/state.html
Normal file
1
vmbackups/templates/vmbackups/state.html
Normal file
|
|
@ -0,0 +1 @@
|
|||
{% load i18n %}{% if backup.state == "ready" %}<span class="badge text-bg-success">{% trans "Ready" %}</span>{% elif backup.state == "creating" %}<span class="badge text-bg-info">{% trans "Creating" %}</span>{% elif backup.state == "deleting" %}<span class="badge text-bg-warning">{% trans "Deleting" %}</span>{% else %}<span class="badge text-bg-danger">{% trans "Failed" %}</span>{% endif %}{% if backup.operation_id %} <a class="small" href="{% url 'operations:job' backup.operation_id %}">{% trans "Job" %}</a>{% endif %}
|
||||
|
|
@ -33,22 +33,17 @@
|
|||
<div class="table-responsive mt-3">
|
||||
<table class="table table-sm align-middle mb-0">
|
||||
<thead>
|
||||
<tr><th>{% trans "Time" %}</th><th>{% trans "Target" %}</th><th>{% trans "Consistency" %}</th><th class="text-end">{% trans "Size" %}</th><th>{% trans "State" %}</th></tr>
|
||||
<tr><th>{% trans "Time" %}</th><th>{% trans "Target" %}</th><th>{% trans "Consistency" %}</th><th class="text-end">{% trans "Size" %}</th><th>{% trans "State" %}</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for backup in backups.rows %}
|
||||
<tr>
|
||||
<td class="text-nowrap">{{ backup.created_at|date:"Y-m-d H:i" }}</td>
|
||||
<td>{{ backup.target.name }}</td>
|
||||
<td>{{ backup.get_consistency_display }}</td>
|
||||
<td>{% include "vmbackups/consistency.html" %}</td>
|
||||
<td class="text-end text-nowrap">{% if backup.size %}{{ backup.size|filesizeformat }}{% else %}–{% endif %}</td>
|
||||
<td>
|
||||
{% if backup.state == "ready" %}<span class="badge text-bg-success">{% trans "Ready" %}</span>
|
||||
{% elif backup.state == "creating" %}<span class="badge text-bg-info">{% trans "Creating" %}</span>
|
||||
{% elif backup.state == "deleting" %}<span class="badge text-bg-warning">{% trans "Deleting" %}</span>
|
||||
{% else %}<span class="badge text-bg-danger">{% trans "Failed" %}</span>{% endif %}
|
||||
{% if backup.operation_id %}<a class="small ms-1" href="{% url 'operations:job' backup.operation_id %}">{% trans "Job" %}</a>{% endif %}
|
||||
</td>
|
||||
<td>{% include "vmbackups/state.html" %}</td>
|
||||
<td class="text-end">{% include "vmbackups/delete_form.html" %}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
|
|
|
|||
|
|
@ -400,7 +400,7 @@ class BackupTabTests(PageControls, TransactionTestCase):
|
|||
self.controls(admin)
|
||||
page = lxml_html.fromstring(self.last_page)
|
||||
self.assertIn("ctl-vm has TPM state", page.xpath("string(//div[@id='backups'])"))
|
||||
self.assertFalse(page.xpath("//div[@id='backups']//form"))
|
||||
self.assertFalse(page.xpath("//div[@id='backups']//form[contains(@action, '/create/')]"))
|
||||
|
||||
def test_owners_have_no_backups_tab(self):
|
||||
self.controls(self.user("tab-owner", owner={"is_change": True}))
|
||||
|
|
|
|||
149
vmbackups/tests/test_delete.py
Normal file
149
vmbackups/tests/test_delete.py
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
"""backup.delete: the manifest first, then the other files, then the row;
|
||||
the Backups page lists every backup."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TransactionTestCase
|
||||
from django.urls import reverse
|
||||
from lxml import html as lxml_html
|
||||
|
||||
from appsettings.settings import get_settings
|
||||
from computes.models import Compute
|
||||
from instances.models import Instance
|
||||
from operations import jobs
|
||||
from operations.jobs import Context
|
||||
from operations.models import Operation, acquire
|
||||
from vmbackups.jobs import DeleteBackup
|
||||
from vmbackups.models import Backup, BackupTarget, BackupTargetPool
|
||||
from vrtManager.util import OperationError
|
||||
|
||||
WORKER = "wvc-test:1:a"
|
||||
|
||||
|
||||
class DeleteBackupTests(TransactionTestCase):
|
||||
def setUp(self):
|
||||
get_settings()
|
||||
self.admin = get_user_model().objects.create_superuser("del_admin", "a@example.com", "pw")
|
||||
self.compute = Compute.objects.create(name="h1", hostname="192.0.2.31", login="u", password="p", type=1)
|
||||
self.vm = Instance.objects.create(compute=self.compute, name="vm1", uuid="31313131-0000-4000-8000-000000000001")
|
||||
self.target = BackupTarget.objects.create(name="nfs1")
|
||||
BackupTargetPool.objects.create(target=self.target, compute=self.compute, pool="b1", pool_uuid="u")
|
||||
self.backup = Backup.objects.create(target=self.target, instance=self.vm, vm_uuid=self.vm.uuid, vm_name="vm1",
|
||||
compute_name="h1", state=Backup.READY)
|
||||
prefix = self.backup.prefix
|
||||
self.pool = MagicMock()
|
||||
self.pool.listVolumes.return_value = [f"{prefix}-vda.qcow2", f"{prefix}-domain.xml", f"{prefix}-manifest.json",
|
||||
"wvc-00000000-0000-4000-8000-000000000009-vda.qcow2", "other.img"]
|
||||
self.removed = []
|
||||
for name, value in (
|
||||
("vmbackups.jobs.wvmConnect", MagicMock()),
|
||||
("vmbackups.jobs.target_pool", MagicMock(return_value=self.pool)),
|
||||
("vmbackups.jobs.remove_files", MagicMock(side_effect=lambda pool, names: self.removed.append(list(names)))),
|
||||
):
|
||||
patcher = patch(name, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def submit(self):
|
||||
op = jobs.submit("backup.delete", self.admin, {"backup": str(self.backup.uuid)}, f"key-{uuid4().hex[:12]}")
|
||||
acquire(WORKER, "wvc-test")
|
||||
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER)
|
||||
op.refresh_from_db()
|
||||
return op
|
||||
|
||||
def run_job(self, op):
|
||||
return DeleteBackup().run(op, Context(op, SimpleNamespace(identity=WORKER)))
|
||||
|
||||
def test_the_manifest_goes_first(self):
|
||||
self.run_job(self.submit())
|
||||
prefix = self.backup.prefix
|
||||
self.assertEqual(self.removed, [[f"{prefix}-manifest.json"], [f"{prefix}-vda.qcow2", f"{prefix}-domain.xml"]])
|
||||
self.assertFalse(Backup.objects.exists())
|
||||
|
||||
def test_the_pool_is_refreshed_before_the_manifest_is_looked_up(self):
|
||||
# another compute made the backup: this one's pool lists its files only after a refresh
|
||||
self.pool.refresh.side_effect = lambda flags: self.removed.append("refresh")
|
||||
self.run_job(self.submit())
|
||||
self.assertEqual(self.removed[0], "refresh")
|
||||
|
||||
def test_an_interrupted_delete_is_finished_by_recovery(self):
|
||||
op = self.submit()
|
||||
with patch("vmbackups.jobs.remove_files", side_effect=[None, RuntimeError("worker gone")]):
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.run_job(op)
|
||||
self.backup.refresh_from_db()
|
||||
self.assertEqual(self.backup.state, Backup.DELETING)
|
||||
op.refresh_from_db()
|
||||
self.assertEqual(DeleteBackup().reconcile(op).state, Operation.SUCCEEDED)
|
||||
self.assertFalse(Backup.objects.exists())
|
||||
|
||||
def test_a_creating_backup_is_not_deleted(self):
|
||||
Backup.objects.filter(pk=self.backup.pk).update(state=Backup.CREATING)
|
||||
with self.assertRaisesMessage(OperationError, "being made"):
|
||||
self.submit()
|
||||
|
||||
def test_a_target_no_compute_reaches_is_refused(self):
|
||||
op = self.submit()
|
||||
with patch("vmbackups.jobs.target_pool", side_effect=OperationError("Storage pool %(pool)s is gone", pool="b1")):
|
||||
with self.assertRaisesMessage(OperationError, "nfs1"):
|
||||
self.run_job(op)
|
||||
self.assertTrue(Backup.objects.filter(state=Backup.READY).exists())
|
||||
|
||||
def test_the_log_row(self):
|
||||
op = self.submit()
|
||||
self.run_job(op)
|
||||
entry = DeleteBackup().log_entry(op, Operation.SUCCEEDED)
|
||||
self.assertEqual(entry[:3], ("h1", "vm1", self.vm.uuid))
|
||||
self.assertRegex(entry[3], r"^Backup \d{4}-\d\d-\d\d \d\d:\d\d of vm1 deleted$")
|
||||
|
||||
def test_api_delete(self):
|
||||
self.client.force_login(self.admin)
|
||||
response = self.client.delete(f"/api/v1/backups/{self.backup.uuid}/", {"submission_key": "key-api-del1"},
|
||||
content_type="application/json")
|
||||
self.assertEqual(response.status_code, 202, response.content)
|
||||
self.assertEqual(response.json()["kind"], "backup.delete")
|
||||
|
||||
def test_the_page_deletes_and_goes_back(self):
|
||||
self.client.force_login(self.admin)
|
||||
url = reverse("vmbackups:delete", args=[self.backup.uuid])
|
||||
response = self.client.post(url, {"submission_key": "key-page-del1"}, HTTP_REFERER="http://testserver/backups/")
|
||||
op = Operation.objects.get()
|
||||
self.assertEqual(op.kind, "backup.delete")
|
||||
# the job's own page: neither the Backups page nor the VM page shows a backup's job
|
||||
self.assertRedirects(response, reverse("operations:job", args=[op.pk]), fetch_redirect_response=False)
|
||||
|
||||
|
||||
class IndexTests(TransactionTestCase):
|
||||
def setUp(self):
|
||||
self.admin = get_user_model().objects.create_superuser("idx_admin", "a@example.com", "pw")
|
||||
compute = Compute.objects.create(name="h1", hostname="192.0.2.32", login="u", password="p", type=1)
|
||||
vm = Instance.objects.create(compute=compute, name="web1", uuid="32323232-0000-4000-8000-000000000001")
|
||||
self.t1 = BackupTarget.objects.create(name="nfs1")
|
||||
self.t2 = BackupTarget.objects.create(name="nfs2")
|
||||
Backup.objects.create(target=self.t1, instance=vm, vm_uuid=vm.uuid, vm_name="web1", compute_name="h1",
|
||||
state=Backup.READY)
|
||||
Backup.objects.create(target=self.t2, instance=None, vm_uuid="u2", vm_name="db1", compute_name="h1",
|
||||
state=Backup.FAILED)
|
||||
|
||||
def rows(self, query=""):
|
||||
self.client.force_login(self.admin)
|
||||
page = lxml_html.fromstring(self.client.get(reverse("vmbackups:index") + query).content)
|
||||
return [" ".join(row.text_content().split()) for row in page.xpath("//table[@id='backups']/tbody/tr")]
|
||||
|
||||
def test_the_index_filters_and_marks_removed_vms(self):
|
||||
rows = self.rows()
|
||||
self.assertEqual(len(rows), 2)
|
||||
self.assertIn("removed", next(r for r in rows if "db1" in r))
|
||||
self.assertNotIn("removed", next(r for r in rows if "web1" in r))
|
||||
self.assertEqual(len(self.rows("?vm=WEB")), 1)
|
||||
self.assertIn("db1", self.rows(f"?target={self.t2.pk}")[0])
|
||||
self.assertIn("db1", self.rows("?state=failed")[0])
|
||||
self.assertEqual(self.rows("?state=ready&vm=db"), [])
|
||||
|
||||
def test_only_superusers(self):
|
||||
user = get_user_model().objects.create_user("idx_user", password="pw")
|
||||
self.client.force_login(user)
|
||||
self.assertEqual(self.client.get(reverse("vmbackups:index")).status_code, 403)
|
||||
|
|
@ -5,6 +5,8 @@ from . import views
|
|||
app_name = "vmbackups"
|
||||
|
||||
urlpatterns = [
|
||||
path("", views.index, name="index"),
|
||||
path("<uuid:uuid>/delete/", views.delete, name="delete"),
|
||||
path("targets/", views.targets, name="targets"),
|
||||
path("targets/<int:target_id>/", views.target, name="target"),
|
||||
path("vm/<int:instance_id>/create/", views.create, name="create"),
|
||||
|
|
|
|||
|
|
@ -13,13 +13,13 @@ from instances.models import Instance
|
|||
from logs.audit import audit
|
||||
from operations import claims, jobs
|
||||
from operations.utils import busy_message
|
||||
from webvirtcloud.middleware import error_text
|
||||
from webvirtcloud.middleware import error_text, same_origin_referer
|
||||
from vrtManager.backup import pool_space, target_pool
|
||||
from vrtManager.connection import wvmConnect
|
||||
from vrtManager.util import OperationError
|
||||
|
||||
from .forms import TargetForm, TargetPoolForm
|
||||
from .models import BackupTarget
|
||||
from .models import Backup, BackupTarget
|
||||
from .utils import inside_vm_pool
|
||||
|
||||
|
||||
|
|
@ -125,3 +125,37 @@ def create(request, instance_id):
|
|||
else:
|
||||
jobs.remember_job(request, op)
|
||||
return redirect(page)
|
||||
|
||||
|
||||
@superuser_only
|
||||
def index(request):
|
||||
"""Every backup, newest first; filtered by VM name, target and state."""
|
||||
rows = Backup.objects.select_related("target", "instance")
|
||||
vm, target, state = request.GET.get("vm", "").strip(), request.GET.get("target", ""), request.GET.get("state", "")
|
||||
if vm:
|
||||
rows = rows.filter(vm_name__icontains=vm)
|
||||
if target.isdigit():
|
||||
rows = rows.filter(target_id=int(target))
|
||||
if state in dict(Backup.STATES):
|
||||
rows = rows.filter(state=state)
|
||||
return render(request, "vmbackups/index.html", {
|
||||
"rows": rows, "targets": BackupTarget.objects.order_by("name"),
|
||||
"vm": vm, "target": target, "state": state,
|
||||
})
|
||||
|
||||
|
||||
@require_POST
|
||||
@superuser_only
|
||||
def delete(request, uuid):
|
||||
backup = get_object_or_404(Backup, uuid=uuid)
|
||||
try:
|
||||
op = jobs.submit("backup.delete", request.user, {"backup": str(backup.uuid)},
|
||||
request.POST.get("submission_key", ""))
|
||||
except claims.Busy as busy:
|
||||
messages.error(request, busy_message(busy, request.user))
|
||||
except (jobs.SubmissionConflict, libvirtError) as err:
|
||||
messages.error(request, error_text(request, err))
|
||||
else:
|
||||
# the job's page follows it: the pages listing backups show no backup's job
|
||||
return redirect("operations:job", op.pk)
|
||||
return redirect(same_origin_referer(request, reverse("vmbackups:index")))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue