mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-02 08:56:07 +00:00
On a phone the settings page opened with its group index on seven lines, and the index was gone once the page, nine screens long, was scrolled. Below the lg breakpoint it is now one row that scrolls sideways and sticks under the navbar (navbar_height.js gives what sticks the navbar's height, which differs between themes and grows when the phone menu opens). Turkish said "VM" in 65 messages and "sanal makine" everywhere else; it now says "sanal makine" throughout. Headings and buttons that still capitalised every word follow the panel's sentence case, in English too (Change password, SSH keys, Power off, ...). Wrong translations fixed: a password that is set read as the command "Ayarla", the firmware setting was called a chip type, Create flavor said Create user, the console viewport setting was called a port, a DRBD typo, and host and interface are sunucu and arabirim as on every page. A group's save button reads "Kaydet: <group>".
574 lines
25 KiB
Python
574 lines
25 KiB
Python
from contextlib import contextmanager
|
|
from datetime import timedelta
|
|
|
|
from accounts.lockout import locked_usernames
|
|
from accounts.models import ApiToken, Instance, UserAttributes, UserInstance
|
|
from appsettings.settings import app_settings
|
|
from computes.utils import lock_ownership, users_lock
|
|
from django.conf import settings
|
|
from django.contrib import messages
|
|
from django.contrib.auth import SESSION_KEY, update_session_auth_hash
|
|
from django.contrib.auth.models import Group, Permission, User
|
|
from django.contrib.sessions.models import Session
|
|
from django.core.paginator import Paginator
|
|
from django.http import HttpResponse
|
|
from django.db import IntegrityError, transaction
|
|
from django.db.models import Count, Exists, OuterRef, ProtectedError, Q
|
|
from django.shortcuts import get_object_or_404, redirect, render
|
|
from django.utils import timezone
|
|
from django.utils.http import url_has_allowed_host_and_scheme, urlencode
|
|
from django.utils.translation import gettext_lazy as _
|
|
from django.utils.translation import ngettext
|
|
from django.views.decorators.http import require_POST
|
|
from django.views.decorators.debug import sensitive_post_parameters
|
|
from computes.models import Tag
|
|
from instances.models import InstanceTombstone
|
|
from instances.report import workbook
|
|
from logs.audit import audit, changed_fields, snapshot
|
|
from logs.models import Logs
|
|
from operations import claims
|
|
from operations.utils import busy_message
|
|
from vrtManager import util
|
|
from vmbackups.models import Backup, BackupPolicy
|
|
|
|
from . import forms
|
|
from .decorators import superuser_only
|
|
|
|
|
|
def form_seen(*snapshots):
|
|
"""The fingerprint of what an edit form shows (snapshot()s), which it sends
|
|
back: a form opened before another administrator's change would undo it.
|
|
A password or a login of the user is no change of the form."""
|
|
shown = [sorted((key, sorted(value) if isinstance(value, frozenset) else value)
|
|
for key, value in snap.items() if key not in ("password", "last_login")) for snap in snapshots]
|
|
return util.digest(repr(shown))
|
|
|
|
|
|
STALE = _("%(name)s was changed meanwhile: here it is as it is now; make your change again")
|
|
|
|
|
|
def group_snapshot(group):
|
|
"""snapshot() of a group with its members, which are a reverse relation snapshot() does not see."""
|
|
return snapshot(group) | {"users": frozenset(group.user_set.values_list("pk", flat=True))}
|
|
|
|
|
|
@superuser_only
|
|
def group_list(request):
|
|
groups = Group.objects.annotate(members=Count("user", distinct=True), perms=Count("permissions", distinct=True)).order_by("name")
|
|
return render(
|
|
request,
|
|
"admin/group_list.html",
|
|
{
|
|
"groups": groups,
|
|
},
|
|
)
|
|
|
|
|
|
@superuser_only
|
|
def group_create(request):
|
|
form = forms.GroupForm(request.POST or None)
|
|
if form.is_valid():
|
|
with audit(request, None, f"Group {form.cleaned_data['name']}", "add"):
|
|
form.save()
|
|
return redirect("admin:group_list")
|
|
|
|
return render(
|
|
request,
|
|
"admin/group_form.html",
|
|
{
|
|
"form": form,
|
|
"title": _("Create group"),
|
|
},
|
|
)
|
|
|
|
|
|
@superuser_only
|
|
def group_update(request, pk):
|
|
group = get_object_or_404(Group, pk=pk)
|
|
subject = f"Group {group.name}"
|
|
if request.method == "POST":
|
|
try:
|
|
# as user_update: read, checked and saved while no other change of the users runs
|
|
with audit(request, None, subject, "change") as entry, users_lock():
|
|
group = Group.objects.get(pk=pk)
|
|
before = group_snapshot(group)
|
|
if request.POST.get("seen") != form_seen(before):
|
|
raise Stale("changed since the form was shown")
|
|
form = forms.GroupForm(request.POST, instance=group)
|
|
entry.skip = not form.is_valid()
|
|
if form.is_valid():
|
|
form.save()
|
|
fields = changed_fields(before, group_snapshot(group))
|
|
entry.action = "change " + ", ".join(fields)
|
|
entry.skip = not fields
|
|
except Stale:
|
|
messages.error(request, STALE % {"name": group.name})
|
|
return redirect(request.get_full_path())
|
|
except claims.Busy as busy:
|
|
messages.error(request, busy_message(busy, request.user))
|
|
return redirect(request.get_full_path())
|
|
if form.is_valid():
|
|
return redirect("admin:group_list")
|
|
else:
|
|
form = forms.GroupForm(instance=group)
|
|
|
|
return render(
|
|
request,
|
|
"admin/group_form.html",
|
|
{
|
|
"form": form,
|
|
"group": group,
|
|
"seen": form_seen(group_snapshot(group)),
|
|
"title": _("Update group"),
|
|
},
|
|
)
|
|
|
|
|
|
@superuser_only
|
|
def group_delete(request, pk):
|
|
group = get_object_or_404(Group, pk=pk)
|
|
if request.method == "POST":
|
|
with audit(request, None, f"Group {group.name}", "delete"):
|
|
deleted, _rows = group.delete()
|
|
if deleted: # not by another request just before
|
|
messages.success(request, _("Group %(group)s deleted") % {"group": group.name})
|
|
return redirect("admin:group_list")
|
|
|
|
return render(
|
|
request,
|
|
"common/confirm_delete.html",
|
|
{"object": group, "consequence": _("Its members stay but lose the permissions it gave them.")},
|
|
)
|
|
|
|
|
|
# an administrator who blocks, deletes or demotes their own account is out of
|
|
# these pages at once, and may have been the last one
|
|
OWN_ACCOUNT = _("You cannot block, delete or demote your own account")
|
|
NO_SUPERUSER = _("This would leave no active superuser")
|
|
|
|
|
|
class NoSuperuser(Exception):
|
|
pass
|
|
|
|
|
|
@contextmanager
|
|
def users_change():
|
|
"""A change of the panel's users, saved only if an active superuser is
|
|
left: two administrators blocking or demoting each other at once would
|
|
each leave the other, and then none. One change at a time (users_lock)."""
|
|
with users_lock():
|
|
yield
|
|
if not User.objects.filter(is_superuser=True, is_active=True).exists():
|
|
raise NoSuperuser("no active superuser would be left")
|
|
|
|
|
|
def refused(request, err):
|
|
"""The message of a users_change() that was not made."""
|
|
messages.error(request, NO_SUPERUSER if isinstance(err, NoSuperuser) else busy_message(err, request.user))
|
|
|
|
|
|
@superuser_only
|
|
def user_list(request):
|
|
# API tokens that still work: an expired one is deleted only at the user's next create
|
|
live = Q(auth_token_set__expiry__isnull=True) | Q(auth_token_set__expiry__gt=timezone.now())
|
|
# the clone permission, given to the user or to a group of the user: one
|
|
# query for the list, not a has_perm (two queries) a user
|
|
clone = Permission.objects.filter(content_type__app_label="instances", codename="clone_instances")
|
|
users = User.objects.annotate(
|
|
api_tokens=Count("auth_token_set", filter=live),
|
|
can_clone=Exists(clone.filter(Q(user=OuterRef("pk")) | Q(group__user=OuterRef("pk")))),
|
|
).order_by("username").prefetch_related("groups")
|
|
return render(
|
|
request,
|
|
"admin/user_list.html",
|
|
{
|
|
"users": users,
|
|
"locked": locked_usernames(),
|
|
"title": _("Users"),
|
|
},
|
|
)
|
|
|
|
|
|
@sensitive_post_parameters()
|
|
@superuser_only
|
|
def user_create(request):
|
|
user_form = forms.UserCreateForm(request.POST or None)
|
|
attributes_form = forms.UserAttributesForm(request.POST or None)
|
|
if user_form.is_valid() and attributes_form.is_valid():
|
|
# the form's checks again (its e-mail address one user's, the default VMs' one owner), with the inserts
|
|
try:
|
|
with audit(request, None, f"User {user_form.cleaned_data['username']}", "add") as entry, users_lock():
|
|
lock_ownership()
|
|
user_form.full_clean()
|
|
entry.skip = not user_form.is_valid()
|
|
if user_form.is_valid():
|
|
user = user_form.save()
|
|
attributes = attributes_form.save(commit=False)
|
|
attributes.user = user
|
|
attributes.save()
|
|
UserInstance.objects.bulk_create(UserInstance(user=user, instance=instance)
|
|
for instance in user_form.default_instances)
|
|
except claims.Busy as busy: # the form again, with what was entered
|
|
user_form.add_error(None, busy_message(busy, request.user))
|
|
if user_form.is_valid():
|
|
return redirect("admin:user_list")
|
|
|
|
return render(
|
|
request,
|
|
"admin/user_form.html",
|
|
{
|
|
"user_form": user_form,
|
|
"attributes_form": attributes_form,
|
|
"title": _("Create user"),
|
|
},
|
|
)
|
|
|
|
|
|
class Stale(Exception):
|
|
pass
|
|
|
|
|
|
def user_edit_forms(request, pk):
|
|
"""The user and quota forms of user pk as saved now, bound to the posted
|
|
values, and the fingerprint and snapshots of what they hold."""
|
|
user = User.objects.get(pk=pk)
|
|
attributes, _created = UserAttributes.objects.get_or_create(user=user)
|
|
before = (snapshot(user), snapshot(attributes))
|
|
data = request.POST if request.method == "POST" else None
|
|
return (forms.UserForm(data, instance=user), forms.UserAttributesForm(data, instance=attributes),
|
|
form_seen(*before), before)
|
|
|
|
|
|
@sensitive_post_parameters()
|
|
@superuser_only
|
|
def user_update(request, pk):
|
|
user = get_object_or_404(User, pk=pk)
|
|
subject = f"User {user.username}"
|
|
valid = False
|
|
if request.method == "POST":
|
|
try:
|
|
# read, checked and saved while no other change of the users runs: a change
|
|
# saved since this form was shown is not undone, and its checks see what is saved
|
|
with audit(request, None, subject, "change") as entry, users_change():
|
|
user_form, attributes_form, seen, (before, before_attributes) = user_edit_forms(request, pk)
|
|
if request.POST.get("seen") != seen:
|
|
raise Stale("changed since the form was shown")
|
|
valid = user_form.is_valid() and attributes_form.is_valid()
|
|
if valid and user == request.user and not (user_form.cleaned_data["is_active"]
|
|
and user_form.cleaned_data["is_superuser"]):
|
|
user_form.add_error(None, OWN_ACCOUNT)
|
|
valid = False
|
|
entry.skip = not valid
|
|
if valid:
|
|
user = user_form.save()
|
|
attributes = attributes_form.save()
|
|
if not user.is_active: # as user_block
|
|
ApiToken.objects.filter(user=user).delete()
|
|
end_sessions(user)
|
|
fields = set(changed_fields(before, snapshot(user))) | set(changed_fields(before_attributes, snapshot(attributes)))
|
|
fields = sorted(fields - {"password", "last_login"})
|
|
entry.action = "change " + ", ".join(fields)
|
|
entry.skip = not fields
|
|
except Stale:
|
|
messages.error(request, STALE % {"name": user.username})
|
|
return redirect(request.get_full_path())
|
|
except (NoSuperuser, claims.Busy) as err:
|
|
refused(request, err)
|
|
return redirect(request.get_full_path())
|
|
else:
|
|
user_form, attributes_form, seen, _before = user_edit_forms(request, pk)
|
|
if valid:
|
|
next_url = request.GET.get("next")
|
|
if next_url and url_has_allowed_host_and_scheme(
|
|
url=next_url, allowed_hosts={request.get_host()}, require_https=request.is_secure()
|
|
):
|
|
return redirect(next_url)
|
|
return redirect("admin:user_list")
|
|
|
|
return render(
|
|
request,
|
|
"admin/user_form.html",
|
|
{
|
|
"user_form": user_form,
|
|
"attributes_form": attributes_form,
|
|
"edited_user": user,
|
|
"seen": seen,
|
|
"title": _("Update user"),
|
|
},
|
|
)
|
|
|
|
|
|
@sensitive_post_parameters()
|
|
@superuser_only
|
|
def user_update_password(request, pk):
|
|
user = get_object_or_404(User, pk=pk)
|
|
if request.method == "POST":
|
|
form = forms.AdminPasswordForm(user, request.POST)
|
|
valid = form.is_valid()
|
|
if valid and user == request.user and not form.cleaned_data["set_usable_password"]:
|
|
form.add_error(None, OWN_ACCOUNT)
|
|
valid = False
|
|
if valid:
|
|
with audit(request, None, f"User {user.username}", "set password"), transaction.atomic():
|
|
user = form.save()
|
|
UserAttributes.objects.update_or_create(
|
|
user=user, defaults={"must_change_password": form.cleaned_data["must_change_password"]})
|
|
# a reset closes a taken-over account: its tokens would outlive the old password
|
|
ApiToken.objects.filter(user=user).delete()
|
|
update_session_auth_hash(request, user) # Important!
|
|
messages.success(
|
|
request, _("Password changed for %(user)s") % {"user": user.username}
|
|
)
|
|
return redirect("admin:user_list")
|
|
else:
|
|
form = forms.AdminPasswordForm(user)
|
|
|
|
return render(request, "admin/user_password_form.html", {"form": form, "edited_user": user})
|
|
|
|
|
|
@superuser_only
|
|
def user_delete(request, pk):
|
|
user = get_object_or_404(User, pk=pk)
|
|
if user == request.user:
|
|
messages.error(request, OWN_ACCOUNT)
|
|
return redirect("admin:user_list")
|
|
if request.method == "POST":
|
|
try:
|
|
with audit(request, None, f"User {user.username}", "delete"), users_change():
|
|
deleted, _rows = user.delete()
|
|
if deleted: # not by another request just before
|
|
messages.success(request, _("User %(user)s deleted") % {"user": user.username})
|
|
except (NoSuperuser, claims.Busy) as err:
|
|
refused(request, err)
|
|
return redirect("admin:user_list")
|
|
|
|
return render(
|
|
request,
|
|
"common/confirm_delete.html",
|
|
{"object": user,
|
|
"consequence": _("Their access to VMs, SSH keys and settings go; the VMs themselves stay.")},
|
|
)
|
|
|
|
|
|
def end_sessions(user):
|
|
"""Sign a blocked user out: django-auth-ldap does not check is_active for
|
|
an open session, so a blocked LDAP user would keep theirs."""
|
|
for session in Session.objects.filter(expire_date__gt=timezone.now()):
|
|
if session.get_decoded().get(SESSION_KEY) == str(user.pk):
|
|
session.delete()
|
|
|
|
|
|
@require_POST
|
|
@superuser_only
|
|
def user_block(request, pk):
|
|
user: User = get_object_or_404(User, pk=pk)
|
|
if user == request.user:
|
|
messages.error(request, OWN_ACCOUNT)
|
|
return redirect("admin:user_list")
|
|
try:
|
|
with audit(request, None, f"User {user.username}", "block") as entry, users_change():
|
|
entry.skip = not user.is_active # already blocked
|
|
user.is_active = False
|
|
user.save(update_fields=["is_active"]) # not the rest as read before the lock
|
|
# an unblock must not bring back the tokens of someone who took the account over
|
|
ApiToken.objects.filter(user=user).delete()
|
|
end_sessions(user)
|
|
messages.success(request, _("%(user)s is blocked: signed out, API tokens deleted") % {"user": user.username})
|
|
except (NoSuperuser, claims.Busy) as err:
|
|
refused(request, err)
|
|
return redirect("admin:user_list")
|
|
|
|
|
|
@require_POST
|
|
@superuser_only
|
|
def user_unblock(request, pk):
|
|
user: User = get_object_or_404(User, pk=pk)
|
|
try:
|
|
with audit(request, None, f"User {user.username}", "unblock") as entry, users_lock():
|
|
entry.skip = user.is_active # not blocked
|
|
user.is_active = True
|
|
user.save(update_fields=["is_active"])
|
|
messages.success(request, _("%(user)s may sign in again") % {"user": user.username})
|
|
except claims.Busy as busy:
|
|
messages.error(request, busy_message(busy, request.user))
|
|
return redirect("admin:user_list")
|
|
|
|
|
|
# rows in one Logs download: the workbook is built in memory
|
|
EXPORT_ROWS = 100000
|
|
|
|
|
|
def _logs(request):
|
|
"""The Logs rows the search and the failed-only box choose, newest first,
|
|
and the query that chooses them again."""
|
|
rows = Logs.objects.order_by("-date", "-id")
|
|
text = request.GET.get("q", "").strip()
|
|
failed = bool(request.GET.get("failed"))
|
|
if text:
|
|
rows = rows.filter(Q(user__icontains=text) | Q(host__icontains=text) | Q(instance__icontains=text)
|
|
| Q(instance_uuid__icontains=text) | Q(message__icontains=text) | Q(ip__icontains=text))
|
|
if failed:
|
|
rows = rows.filter(success=False)
|
|
query = urlencode([(key, value) for key, value in (("q", text), ("failed", "1" if failed else "")) if value])
|
|
return rows, text, failed, query
|
|
|
|
|
|
def _result(success):
|
|
return _("Unknown") if success is None else _("Done") if success else _("Failed")
|
|
|
|
|
|
@superuser_only
|
|
def logs(request):
|
|
rows, text, failed, query = _logs(request)
|
|
logs = Paginator(rows, int(app_settings.LOGS_PER_PAGE)).get_page(request.GET.get("page"))
|
|
# a VM's rows link to it while it is in the panel
|
|
vms = dict(Instance.objects.filter(uuid__in={log.instance_uuid for log in logs if log.instance_uuid})
|
|
.values_list("uuid", "pk"))
|
|
for log in logs:
|
|
log.vm_pk = vms.get(log.instance_uuid)
|
|
return render(request, "admin/logs.html", {"logs": logs, "q": text, "failed": failed, "query": query,
|
|
"time_zone": timezone.get_current_timezone_name()})
|
|
|
|
|
|
@superuser_only
|
|
def logs_export(request):
|
|
"""The rows the Logs page shows for the same search, every page of them,
|
|
as an Excel workbook."""
|
|
rows, text, failed, _query = _logs(request)
|
|
zone = timezone.get_current_timezone_name()
|
|
header = [f"Date ({zone})", "User", "Host", "VM", "VM UUID", "Message", "Result", "IP"]
|
|
# tuples, not model objects: up to EXPORT_ROWS of them are held at once
|
|
logs = list(rows.values_list("date", "user", "host", "instance", "instance_uuid", "message", "success", "ip")
|
|
[:EXPORT_ROWS + 1])
|
|
data = [[timezone.localtime(date).strftime("%Y-%m-%d %H:%M:%S"), user, host, instance, uuid, message,
|
|
str(_result(success)), ip or ""]
|
|
for date, user, host, instance, uuid, message, success, ip in logs[:EXPORT_ROWS]]
|
|
notes = [f"Search: {text}" if text else "Search: none", "Failed only" if failed else "All results",
|
|
f"Rows: {len(data)}", f"Times in {zone}"]
|
|
if len(logs) > EXPORT_ROWS:
|
|
notes.append(f"Only the newest {EXPORT_ROWS} rows: narrow the search for the others")
|
|
response = HttpResponse(workbook("Logs", header, data, "About", notes),
|
|
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
|
name = f"webvirtcloud-logs-{timezone.localtime():%Y%m%d-%H%M%S}.xlsx"
|
|
response["Content-Disposition"] = f'attachment; filename="{name}"'
|
|
return response
|
|
|
|
|
|
@superuser_only
|
|
def tombstone_list(request):
|
|
"""The owners kept for VMs that vanished from their compute, in case the
|
|
same UUID comes back."""
|
|
tombstones = list(InstanceTombstone.objects.order_by("-removed"))
|
|
ids = {owner["user"] for tombstone in tombstones for owner in tombstone.owners}
|
|
names = dict(User.objects.filter(id__in=ids).values_list("id", "username"))
|
|
retention = timedelta(days=getattr(settings, "INSTANCE_OWNERSHIP_RETENTION_DAYS", 30))
|
|
# what would come back (computes.utils._restore): schedules that choose their VMs one by one, backups unlinked
|
|
policies = dict(BackupPolicy.objects.filter(pk__in={pk for t in tombstones for pk in t.policies}, compute=None,
|
|
tag=None).values_list("pk", "name"))
|
|
backups = set(Backup.objects.filter(pk__in={pk for t in tombstones for pk in t.backups}, instance=None)
|
|
.values_list("pk", flat=True))
|
|
for tombstone in tombstones:
|
|
tombstone.owner_names = [names.get(owner["user"], _("deleted user")) for owner in tombstone.owners]
|
|
tombstone.policy_names = sorted(policies[pk] for pk in tombstone.policies if pk in policies)
|
|
tombstone.backup_count = len(backups.intersection(tombstone.backups))
|
|
tombstone.expires = tombstone.removed + retention
|
|
return render(request, "admin/tombstone_list.html", {"tombstones": tombstones})
|
|
|
|
|
|
@superuser_only
|
|
def tombstone_delete(request, pk):
|
|
tombstone = get_object_or_404(InstanceTombstone, pk=pk)
|
|
if request.method == "POST":
|
|
with audit(request, tombstone.host or None, f"Removed VM {tombstone.name} ({tombstone.uuid})", "delete",
|
|
instance=tombstone.name, uuid=tombstone.uuid):
|
|
tombstone.delete()
|
|
messages.success(request, _("Removed VM %(name)s deleted") % {"name": tombstone.name})
|
|
return redirect("admin:tombstone_list")
|
|
|
|
return render(
|
|
request,
|
|
"common/confirm_delete.html",
|
|
{"object": tombstone,
|
|
"consequence": _("Its owners, tags, protection and schedules no longer come back if its UUID shows up again, nor are its backups linked to it again.")},
|
|
)
|
|
|
|
|
|
|
|
@superuser_only
|
|
def tag_list(request):
|
|
"""The tags of VMs and hosts, with how many of each have them."""
|
|
# in name order: a query that counts leaves the model's ordering out
|
|
tags = Tag.objects.annotate(vm_count=Count("instances", distinct=True),
|
|
host_count=Count("computes", distinct=True)).order_by("name")
|
|
return render(request, "admin/tag_list.html", {"tags": list(tags)})
|
|
|
|
|
|
def _retag_removed_vms(old, new):
|
|
"""The removed VMs' kept tag old named new, or dropped with None: a name
|
|
made again later must not go to them. Under the ownership lock (computes.utils.forget)."""
|
|
for tombstone in InstanceTombstone.objects.all():
|
|
if old in tombstone.tags:
|
|
if new:
|
|
tombstone.tags = [new if name == old else name for name in tombstone.tags]
|
|
else:
|
|
tombstone.tags = [name for name in tombstone.tags if name != old]
|
|
if tombstone.keeps_anything():
|
|
tombstone.save(update_fields=["tags"])
|
|
else: # kept only for the tag (computes.utils._bury)
|
|
tombstone.delete()
|
|
|
|
|
|
@superuser_only
|
|
def tag_update(request, pk):
|
|
tag = get_object_or_404(Tag, pk=pk)
|
|
old = tag.name
|
|
form = forms.TagForm(request.POST or None, instance=tag)
|
|
if request.method == "POST" and form.is_valid():
|
|
if form.cleaned_data["name"] == old:
|
|
return redirect("admin:tag_list")
|
|
try:
|
|
with audit(request, None, f"Tag {old}", f"rename to {form.cleaned_data['name']}"), transaction.atomic():
|
|
lock_ownership()
|
|
current = get_object_or_404(Tag, pk=pk).name # another rename or a delete may have come first
|
|
form.save()
|
|
_retag_removed_vms(current, tag.name)
|
|
except IntegrityError: # the name was given to another tag meanwhile
|
|
form.add_error("name", form.fields["name"].error_messages["unique"])
|
|
else:
|
|
messages.success(request, _("Tag %(old)s renamed to %(tag)s") % {"old": current, "tag": tag.name})
|
|
return redirect("admin:tag_list")
|
|
return render(request, "common/form.html", {"form": form, "title": _("Rename tag %(tag)s") % {"tag": old}})
|
|
|
|
|
|
def _refuse_used(request, schedules):
|
|
"""Tells that the tag cannot go while the backup schedules back up its VMs (models.PROTECT)."""
|
|
messages.error(request, ngettext("The backup schedule %(schedules)s backs up its VMs: change it first",
|
|
"The backup schedules %(schedules)s back up its VMs: change them first",
|
|
len(schedules)) % {"schedules": ", ".join(schedules)})
|
|
return redirect("admin:tag_list")
|
|
|
|
|
|
@superuser_only
|
|
def tag_delete(request, pk):
|
|
tag = get_object_or_404(Tag, pk=pk)
|
|
if request.method == "POST":
|
|
try:
|
|
with audit(request, None, f"Tag {tag.name}", "delete"), transaction.atomic():
|
|
lock_ownership()
|
|
tag = get_object_or_404(Tag, pk=pk) # its name now: another rename may have come first
|
|
tag.delete()
|
|
_retag_removed_vms(tag.name, None)
|
|
except ProtectedError as err: # a schedule backs up its VMs, also one saved since the page was shown
|
|
return _refuse_used(request, sorted(policy.name for policy in err.protected_objects))
|
|
messages.success(request, _("Tag %(tag)s deleted") % {"tag": tag.name})
|
|
return redirect("admin:tag_list")
|
|
schedules = list(tag.backup_policies.values_list("name", flat=True))
|
|
if schedules:
|
|
return _refuse_used(request, schedules)
|
|
vms, hosts = tag.instances.count(), tag.computes.count()
|
|
return render(request, "common/confirm_delete.html", {
|
|
"object": tag,
|
|
"consequence": _("It is taken off %(vms)s and %(hosts)s.") % {
|
|
"vms": ngettext("%(count)s VM", "%(count)s VMs", vms) % {"count": vms},
|
|
"hosts": ngettext("%(count)s host", "%(count)s hosts", hosts) % {"count": hosts}},
|
|
})
|