mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 01:16:10 +00:00
feat(instances): start, shut down or force off the VMs chosen on the VM list
Powering many VMs took a click each. On the VM list each VM its user may power (theirs, or every one for a superuser) has a box; "Choose the VMs shown" chooses those on screen. Start, Shut down and Force off queue an instance.power job for each chosen VM: each holds its VM and shares its host, checks its user and the VM again when it runs, and has the checks of the page's buttons (a template is not started, a host in maintenance starts none, a VM an administrator paused is not an owner's to power), its own recovery and its own log row. A VM the user may not power, or that another job holds, is named and the others are queued; the Jobs page follows them. A VM a filter or a collapsed host hides is neither counted nor sent, and the list does not reload while VMs on screen are chosen.
This commit is contained in:
parent
2b60b79a5f
commit
35c794c50c
15 changed files with 1091 additions and 592 deletions
|
|
@ -8,6 +8,7 @@ from uuid import uuid4
|
|||
|
||||
from django.db import transaction
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.http import Http404
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.urls import reverse
|
||||
from django.template.loader import render_to_string
|
||||
|
|
@ -1516,3 +1517,76 @@ class DeleteInstance(Kind):
|
|||
|
||||
def log_entry(self, op, state):
|
||||
return _log(op, state, "delete")
|
||||
|
||||
|
||||
# the power actions the VM list's chosen VMs take (instance.power), by the name its form sends, and their log words
|
||||
POWER = {
|
||||
"start": "power on",
|
||||
"shutdown": "power off",
|
||||
"force_off": "force off",
|
||||
}
|
||||
|
||||
|
||||
def _powerable(user, pk):
|
||||
"""The page's rule (_power_instance): an owner or a superuser, and not a VM an administrator paused."""
|
||||
from instances.views import _power_instance
|
||||
|
||||
if user is None or not user.is_active:
|
||||
raise PermissionDenied
|
||||
try:
|
||||
return _power_instance(user, pk)
|
||||
except Http404: # gone, or no longer the user's
|
||||
raise PermissionDenied from None
|
||||
|
||||
|
||||
@register
|
||||
class PowerVM(Kind):
|
||||
"""Starts, shuts down or forces off one VM chosen on the VM list: a job of
|
||||
its own, so each VM is held, checked when it runs, scheduled and recovered
|
||||
on its own, and has its own log row."""
|
||||
|
||||
name = "instance.power"
|
||||
label = gettext_noop("Power")
|
||||
|
||||
def normalize(self, raw):
|
||||
if raw["action"] not in POWER:
|
||||
raise ValueError(raw["action"])
|
||||
return {"instance": int(raw["instance"]), "action": raw["action"]}
|
||||
|
||||
def validate(self, user, params):
|
||||
# the owner only: whether an administrator paused it is read by the worker, not in the request
|
||||
from instances.views import get_instance
|
||||
|
||||
get_instance(user, params["instance"], perm_type="power")
|
||||
|
||||
def plan(self, user, params):
|
||||
return _vm_plan(params)
|
||||
|
||||
def precheck(self, op, ctx):
|
||||
if _powerable(op.user, op.params["instance"]).compute_id != op.intent["compute"]:
|
||||
raise util.OperationError(MOVED)
|
||||
|
||||
def run(self, op, ctx):
|
||||
instance, action = _instance(op.params["instance"]), op.params["action"]
|
||||
if action == "start": # the start button's checks, before anything changes
|
||||
if instance.is_template:
|
||||
raise util.OperationError(gettext_noop("Templates cannot be started."))
|
||||
instance.proxy.check_start_hostdevs()
|
||||
instance.compute.refuse_start()
|
||||
ctx.record_intent(powering=True) # libvirt is asked from here: recovery cannot tell what it did
|
||||
if action == "start":
|
||||
instance.proxy.start()
|
||||
elif action == "shutdown":
|
||||
instance.proxy.shutdown()
|
||||
else:
|
||||
instance.proxy.force_shutdown()
|
||||
return {}
|
||||
|
||||
def reconcile(self, op):
|
||||
if not op.intent.get("powering"):
|
||||
return Outcome(Operation.FAILED, error=say(gettext_noop("The job stopped before the VM was powered")))
|
||||
return Outcome(Operation.UNCERTAIN, error=say(gettext_noop(
|
||||
"The job stopped while the VM was powered: check its state")))
|
||||
|
||||
def log_entry(self, op, state):
|
||||
return _log(op, state, POWER[op.params["action"]])
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
{% extends "base.html" %}
|
||||
{% load i18n %}
|
||||
{% load static %}
|
||||
{% load operations %}
|
||||
{% block title %}{% trans "Instances" %}{% endblock %}
|
||||
{% block page_heading %}{% trans "Instances" %}{% endblock page_heading %}
|
||||
|
||||
|
|
@ -55,6 +56,23 @@
|
|||
</div>
|
||||
</nav>
|
||||
{% include 'common/tag_filter.html' %}
|
||||
{% if powerable %}
|
||||
{# the VMs chosen in the list (bulk_power_box.html), an instance.power job each; bulk_power.js counts those on screen #}
|
||||
<form id="bulk-power" class="d-flex flex-wrap align-items-center gap-2 mb-2" action="{% url 'instances:bulk_power' %}" method="post">{% csrf_token %}{% submission_key %}
|
||||
<div class="form-check mb-0">
|
||||
<input class="form-check-input" type="checkbox" id="bulk-power-shown">
|
||||
<label class="form-check-label" for="bulk-power-shown">{% trans "Choose the VMs shown" %}</label>
|
||||
</div>
|
||||
<span class="small text-body-secondary" id="bulk-power-count" data-text="{% trans "%(count)s chosen" %}" aria-live="polite"></span>
|
||||
<div class="btn-group btn-group-sm" role="group" aria-label="{% trans "Power the chosen VMs" %}">
|
||||
<button type="submit" class="btn btn-outline-primary" name="action" value="start" disabled>{% trans "Start" %}</button>
|
||||
<button type="submit" class="btn btn-outline-primary" name="action" value="shutdown" disabled
|
||||
data-confirm="{% trans "Shut down the chosen VMs? Their guests are asked to power off." %}">{% trans "Shut down" %}</button>
|
||||
<button type="submit" class="btn btn-outline-danger" name="action" value="force_off" disabled
|
||||
data-confirm="{% trans "Force off the chosen VMs? They stop at once, as if unplugged, and may lose unsaved data." %}">{% trans "Force off" %}</button>
|
||||
</div>
|
||||
</form>
|
||||
{% endif %}
|
||||
<div id="filter-status" class="visually-hidden" role="status" data-text="{% trans "%(shown)s of %(all)s VMs match" %}"></div>
|
||||
{% endif %}
|
||||
{% if not instances %}
|
||||
|
|
@ -126,6 +144,8 @@
|
|||
{% if app_settings.VIEW_INSTANCES_LIST_STYLE == 'grouped' and request.user.is_superuser %}
|
||||
<script src="{% static 'js/host_groups.js' %}"></script>
|
||||
{% endif %}
|
||||
{# after host_groups.js: the hosts it collapses are off screen #}
|
||||
{% if powerable %}<script src="{% static 'js/bulk_power.js' %}"></script>{% endif %}
|
||||
{% if request.user.is_superuser %}
|
||||
<script src="{% static 'js/new_vm_dialog.js' %}"></script>
|
||||
{% endif %}
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@
|
|||
{% for instance in compute.instance_set.all %}
|
||||
{# searched for its name, title and owners, not its buttons #}
|
||||
<tr host="{{ compute.id }}" data-tags="{% for tag in instance.tags.all %}{{ tag }}{% if not forloop.last %} {% endif %}{% endfor %}" data-search="{{ instance.name }}{% if instance.info %} {{ instance.title }}{% endif %}{% for owner in instance.userinstance_set.all %} {{ owner.user }}{% endfor %}">
|
||||
<td></td>
|
||||
<td>{% include 'instances/bulk_power_box.html' %}</td>
|
||||
<td>{% include 'instance_name_cell.html' with owners=True %}</td>
|
||||
<td>
|
||||
{% include 'instance_state.html' %}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
<table class="table table-hover align-middle" data-sortable>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" data-sort-method="none"><span class="visually-hidden">{% trans "Chosen" %}</span></th>
|
||||
<th scope="col">{% trans 'Name' %}</th>
|
||||
{% if show_hosts %}
|
||||
<th scope="col">{% trans 'Host' %}</th>
|
||||
|
|
@ -20,6 +21,7 @@
|
|||
{% for instance in instances %}
|
||||
{# searched for its name, title, host and owners, not its buttons #}
|
||||
<tr data-tags="{% for tag in instance.tags.all %}{{ tag }}{% if not forloop.last %} {% endif %}{% endfor %}" data-search="{{ instance.name }}{% if instance.info %} {{ instance.title }}{% endif %}{% if show_hosts %} {{ instance.compute.name }}{% for owner in instance.userinstance_set.all %} {{ owner.user }}{% endfor %}{% endif %}">
|
||||
<td>{% include 'instances/bulk_power_box.html' %}</td>
|
||||
<td>{% include 'instance_name_cell.html' with owners=show_hosts %}</td>
|
||||
{% if show_hosts %}
|
||||
<td>
|
||||
|
|
|
|||
2
instances/templates/instances/bulk_power_box.html
Normal file
2
instances/templates/instances/bulk_power_box.html
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
{% load i18n %}{# a VM the user may power, chosen for the bulk power form (allinstances.html) #}
|
||||
{% if instance.pk in powerable %}<input class="form-check-input" type="checkbox" name="vm" value="{{ instance.pk }}" form="bulk-power" aria-label="{% blocktrans with name=instance.name %}Choose {{ name }}{% endblocktrans %}">{% endif %}
|
||||
151
instances/tests/test_bulk_power.py
Normal file
151
instances/tests/test_bulk_power.py
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
"""Start, shut down or force off the VMs chosen on the VM list: an
|
||||
instance.power job each, so each VM is held, checked when it runs and
|
||||
recovered on its own, with its own log row. A VM the user may not power, or
|
||||
that another job holds, is named and the others are queued. Who may power a
|
||||
VM may choose it, as on its own page."""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.messages import get_messages
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.test import TransactionTestCase
|
||||
from django.urls import reverse
|
||||
from lxml import html
|
||||
|
||||
from accounts.models import UserInstance
|
||||
from computes.models import Compute
|
||||
from instances.jobs import PowerVM
|
||||
from instances.models import Instance
|
||||
from operations import claims
|
||||
from operations.jobs import Context
|
||||
from operations.models import Claim, Operation, acquire
|
||||
from vrtManager.util import OperationError
|
||||
|
||||
|
||||
class BulkPowerTestCase(TransactionTestCase):
|
||||
def setUp(self):
|
||||
self.admin = get_user_model().objects.create_superuser("bp-admin", "bp@example.com", "pw")
|
||||
self.client.force_login(self.admin)
|
||||
compute = Compute.objects.create(name="bp-host", hostname="127.0.0.1", login="", password="", type=4)
|
||||
self.vms = [Instance.objects.create(compute=compute, name=f"bp-vm{n}", uuid=f"00000000-0000-4000-8000-00000000000{n}")
|
||||
for n in (1, 2)]
|
||||
self.proxies = {vm.name: MagicMock(**{"get_status.return_value": 5}) for vm in self.vms}
|
||||
patch.object(Instance, "proxy", property(lambda vm: self.proxies[vm.name])).start()
|
||||
patch.object(Compute, "refuse_start", lambda compute: None).start()
|
||||
self.addCleanup(patch.stopall)
|
||||
|
||||
def submit(self, action, vms, user=None):
|
||||
if user:
|
||||
self.client.force_login(user)
|
||||
self.client.cookies.pop("messages", None)
|
||||
response = self.client.post(reverse("instances:bulk_power"), {"action": action, "vm": [vm.pk for vm in vms],
|
||||
"submission_key": "key-bulkpow1"})
|
||||
return response, [str(m) for m in get_messages(response.wsgi_request)]
|
||||
|
||||
def run_job(self, op):
|
||||
acquire("wvc-test:1:a", "wvc-test")
|
||||
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker="wvc-test:1:a")
|
||||
op.refresh_from_db()
|
||||
ctx = Context(op, SimpleNamespace(identity="wvc-test:1:a"))
|
||||
PowerVM().precheck(op, ctx)
|
||||
return PowerVM().run(op, ctx)
|
||||
|
||||
def test_the_list_queues_a_job_for_each_vm(self):
|
||||
response, said = self.submit("start", self.vms)
|
||||
self.assertRedirects(response, reverse("operations:jobs") + "?kind=instance.power", fetch_redirect_response=False)
|
||||
self.assertEqual(said, ["2 VMs are queued; the Jobs page follows them."])
|
||||
ops = list(Operation.objects.order_by("resource_label"))
|
||||
self.assertEqual([(op.kind, op.params, op.resource_label) for op in ops],
|
||||
[("instance.power", {"instance": vm.pk, "action": "start"}, f"bp-host/{vm.name}") for vm in self.vms])
|
||||
# each holds its VM and shares its host, as a job on the VM's page does
|
||||
self.assertEqual(set(Claim.objects.filter(operation=ops[0]).values_list("resource", "mode")),
|
||||
{(f"compute:{self.vms[0].compute_id}", "shared"), (f"instance:{self.vms[0].uuid}", "exclusive")})
|
||||
# the form sent again queues none twice, and says so as the first time (not "busy")
|
||||
_response, said = self.submit("start", self.vms)
|
||||
self.assertEqual(said, ["2 VMs are queued; the Jobs page follows them."])
|
||||
self.assertEqual(Operation.objects.count(), 2)
|
||||
|
||||
def test_each_job_powers_its_vm(self):
|
||||
self.submit("force_off", self.vms)
|
||||
for op in Operation.objects.all():
|
||||
self.run_job(op)
|
||||
for proxy in self.proxies.values():
|
||||
proxy.force_shutdown.assert_called_once_with()
|
||||
proxy.start.assert_not_called()
|
||||
|
||||
def test_a_vm_another_job_holds_is_named_and_the_others_queued(self):
|
||||
holder = Operation.objects.create(kind="instance.snapshot", user=self.admin, username="bp-admin",
|
||||
state=Operation.RUNNING, resource="x", resource_label="bp-host/bp-vm1")
|
||||
Claim.objects.create(resource=claims.instance_key(self.vms[0].uuid), mode=Claim.EXCLUSIVE, operation=holder)
|
||||
_response, said = self.submit("shutdown", self.vms)
|
||||
self.assertTrue(said[0].startswith("bp-vm1: "), said)
|
||||
self.assertEqual(said[1:], ["1 VM is queued; the Jobs page follows it."])
|
||||
self.assertEqual(Operation.objects.get(kind="instance.power").params["instance"], self.vms[1].pk)
|
||||
|
||||
def test_a_template_is_not_started_and_nothing_is_uncertain(self):
|
||||
# refused before libvirt is asked: the job fails (its claims go), recovery is not needed
|
||||
Instance.objects.filter(pk=self.vms[0].pk).update(is_template=True)
|
||||
self.submit("start", self.vms[:1])
|
||||
op = Operation.objects.get()
|
||||
with self.assertRaisesRegex(OperationError, "Templates cannot be started"):
|
||||
self.run_job(op)
|
||||
op.refresh_from_db()
|
||||
self.assertNotIn("powering", op.intent)
|
||||
self.assertEqual(PowerVM().reconcile(op).state, Operation.FAILED)
|
||||
self.proxies["bp-vm1"].start.assert_not_called()
|
||||
|
||||
def test_a_vm_paused_by_an_administrator_or_gone_is_refused_when_the_job_runs(self):
|
||||
owner = get_user_model().objects.create_user("bp-owner3", password="pw")
|
||||
UserInstance.objects.create(instance=self.vms[0], user=owner)
|
||||
self.submit("start", self.vms[:1], user=owner) # the request reads no VM state
|
||||
op = Operation.objects.get()
|
||||
self.proxies["bp-vm1"].get_status.return_value = 3 # paused
|
||||
with self.assertRaises(PermissionDenied):
|
||||
self.run_job(op)
|
||||
Instance.objects.filter(pk=self.vms[0].pk).delete()
|
||||
with self.assertRaises(PermissionDenied):
|
||||
PowerVM().precheck(op, None)
|
||||
|
||||
def test_the_worker_checks_the_user_again(self):
|
||||
# disabled after the form was sent: the job powers nothing
|
||||
owner = get_user_model().objects.create_user("bp-owner2", password="pw")
|
||||
UserInstance.objects.create(instance=self.vms[0], user=owner)
|
||||
self.submit("start", self.vms[:1], user=owner)
|
||||
get_user_model().objects.filter(pk=owner.pk).update(is_active=False)
|
||||
with self.assertRaises(PermissionDenied):
|
||||
self.run_job(Operation.objects.get())
|
||||
self.proxies["bp-vm1"].start.assert_not_called()
|
||||
|
||||
def test_an_owner_powers_only_their_own_vms(self):
|
||||
owner = get_user_model().objects.create_user("bp-owner", password="pw")
|
||||
UserInstance.objects.create(instance=self.vms[0], user=owner)
|
||||
_response, said = self.submit("start", self.vms, user=owner)
|
||||
# another's VM is not named: the owner may not see it
|
||||
self.assertEqual(said, ["a chosen VM: you may not power it now", "1 VM is queued; the Jobs page follows it."])
|
||||
self.assertEqual(Operation.objects.get().params["instance"], self.vms[0].pk)
|
||||
|
||||
def test_an_unknown_action_or_too_many_vms_is_refused(self):
|
||||
self.submit("reboot", self.vms)
|
||||
response = self.client.post(reverse("instances:bulk_power"), {"action": "start", "vm": [str(n) for n in range(1, 502)],
|
||||
"submission_key": "key-bulkpow1"})
|
||||
self.assertIn("at most 500 VMs", " ".join(map(str, get_messages(response.wsgi_request))))
|
||||
self.assertFalse(Operation.objects.exists())
|
||||
|
||||
def test_the_list_offers_a_box_for_each_vm_and_the_actions(self):
|
||||
with patch("instances.views.utils.vm_states", return_value={}), \
|
||||
patch("instances.views.refresh_instance_database"), patch("instances.views.utils.read_list_rows"):
|
||||
page = html.fromstring(self.client.get(reverse("instances:index")).content)
|
||||
boxes = page.xpath("//input[@type='checkbox'][@name='vm']")
|
||||
self.assertEqual(sorted(int(box.get("value")) for box in boxes), [vm.pk for vm in self.vms])
|
||||
(form,) = page.xpath("//form[@id='bulk-power']")
|
||||
self.assertEqual(form.get("action"), reverse("instances:bulk_power"))
|
||||
self.assertEqual(form.xpath(".//button[@name='action']/@value"), ["start", "shutdown", "force_off"])
|
||||
# an owner: a box on their own VM only
|
||||
owner = get_user_model().objects.create_user("bp-lister", password="pw")
|
||||
UserInstance.objects.create(instance=self.vms[1], user=owner)
|
||||
self.client.force_login(owner)
|
||||
with patch("instances.views.utils.vm_states", return_value={}), \
|
||||
patch("instances.views.refresh_instance_database"), patch("instances.views.utils.read_list_rows"):
|
||||
page = html.fromstring(self.client.get(reverse("instances:index")).content)
|
||||
self.assertEqual([int(box.get("value")) for box in page.xpath("//input[@name='vm']")], [self.vms[1].pk])
|
||||
|
|
@ -12,6 +12,7 @@ urlpatterns = [
|
|||
path("flavor/create/", views.flavor_create, name="flavor_create"),
|
||||
path("flavor/<int:pk>/delete/", views.flavor_delete, name="flavor_delete"),
|
||||
path("<int:pk>/", views.instance, name="instance"),
|
||||
path("bulk_power/", views.bulk_power, name="bulk_power"),
|
||||
path("<int:pk>/poweron/", views.poweron, name="poweron"),
|
||||
path("<int:pk>/powercycle/", views.powercycle, name="powercycle"),
|
||||
path("<int:pk>/poweroff/", views.poweroff, name="poweroff"),
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ from django.urls import reverse
|
|||
from django.template.defaultfilters import filesizeformat
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext as _
|
||||
from django.utils.translation import gettext_lazy, gettext_noop
|
||||
from django.utils.translation import gettext_lazy, gettext_noop, ngettext
|
||||
from django.views.decorators.http import require_POST
|
||||
from django.views.decorators.debug import sensitive_post_parameters
|
||||
from passlib.exc import PasswordValueError
|
||||
|
|
@ -54,6 +54,7 @@ from libvirt import (VIR_DOMAIN_PAUSED,
|
|||
from logs.audit import audit, audit_vm, failed_vm
|
||||
from lxml import etree
|
||||
from operations import claims, jobs
|
||||
from operations.jobs import KEY_RE
|
||||
from operations.utils import HOST_BUSY, busy_message, summary
|
||||
from webvirtcloud.middleware import error_text, same_origin_referer
|
||||
from vrtManager import util
|
||||
|
|
@ -130,7 +131,10 @@ def index(request):
|
|||
"unreachable_computes": [c for c in computes if c.status is not True],
|
||||
"states": [label for label, _color in STATES.values()] + [UNKNOWN[0]],
|
||||
"tags": Tag.counts(instances),
|
||||
"states_url": reverse("instances:states"), "vm_states": vm_states},
|
||||
"states_url": reverse("instances:states"), "vm_states": vm_states,
|
||||
# the VMs this user may power (_power_instance): theirs, or every one for a superuser
|
||||
"powerable": {i.pk for i in instances} if request.user.is_superuser else
|
||||
set(UserInstance.objects.filter(user=request.user).values_list("instance_id", flat=True))},
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -695,6 +699,49 @@ def _power_instance(user, pk):
|
|||
return instance
|
||||
|
||||
|
||||
# the most VMs the VM list's bulk power form takes at once
|
||||
BULK_POWER_MAX = 500
|
||||
|
||||
|
||||
@require_POST
|
||||
def bulk_power(request):
|
||||
"""Starts, shuts down or forces off the VMs chosen on the VM list: an
|
||||
instance.power job each, followed on the Jobs page. A VM the user may not
|
||||
power, gone, or held by another job is named (if the user may see it);
|
||||
the others are queued."""
|
||||
from instances.jobs import POWER # instances.jobs imports this module
|
||||
|
||||
action, key = request.POST.get("action", ""), request.POST.get("submission_key", "")
|
||||
vms = list(dict.fromkeys(int(pk) for pk in request.POST.getlist("vm") if pk.isascii() and pk.isdigit() and len(pk) <= 10))
|
||||
if action not in POWER or not vms or not KEY_RE.fullmatch(key) or len(key) > 50:
|
||||
messages.error(request, _("Choose the VMs you may power, and Start, Shut down or Force off"))
|
||||
return redirect("instances:index")
|
||||
if len(vms) > BULK_POWER_MAX:
|
||||
messages.error(request, _("Choose at most %(count)s VMs at once") % {"count": BULK_POWER_MAX})
|
||||
return redirect("instances:index")
|
||||
names = dict(Instance.objects.filter(pk__in=vms).values_list("pk", "name"))
|
||||
seen = names if request.user.is_superuser else dict(Instance.objects.filter(
|
||||
pk__in=vms, userinstance__user=request.user).values_list("pk", "name"))
|
||||
queued = 0
|
||||
for pk in vms:
|
||||
name = seen.get(pk) or _("a chosen VM") # one the user may not see is not named
|
||||
try:
|
||||
# one key per VM: a resent form queues none twice
|
||||
jobs.submit("instance.power", request.user, {"instance": pk, "action": action}, f"{key}-{pk}")
|
||||
queued += 1
|
||||
except claims.Busy as busy:
|
||||
messages.error(request, f"{name}: {busy_message(busy, request.user)}")
|
||||
except (Http404, PermissionDenied, Instance.DoesNotExist):
|
||||
messages.error(request, _("%(vm)s: you may not power it now") % {"vm": name})
|
||||
except (jobs.SubmissionConflict, libvirtError) as err:
|
||||
messages.error(request, f"{name}: {error_text(request, err)}")
|
||||
if not queued:
|
||||
return redirect("instances:index")
|
||||
messages.success(request, ngettext("%(count)s VM is queued; the Jobs page follows it.",
|
||||
"%(count)s VMs are queued; the Jobs page follows them.", queued) % {"count": queued})
|
||||
return redirect(reverse("operations:jobs") + "?kind=instance.power")
|
||||
|
||||
|
||||
def from_script(request):
|
||||
"""A form a page's script sends and answers itself: the create page's
|
||||
flavor forms (it swaps in the reply), the XML editor's dialog (JSON)."""
|
||||
|
|
|
|||
Binary file not shown.
File diff suppressed because it is too large
Load diff
Binary file not shown.
File diff suppressed because it is too large
Load diff
56
static/js/bulk_power.js
Normal file
56
static/js/bulk_power.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
// The VM list's bulk power form. Only the chosen VMs on screen count: one a
|
||||
// filter or a collapsed host hides is neither counted nor sent, so a VM chosen
|
||||
// before the filters changed is not powered unseen. "Choose the VMs shown"
|
||||
// chooses or clears those on screen, and shows whether all, some or none are.
|
||||
(function () {
|
||||
var form = document.getElementById("bulk-power");
|
||||
var shown = document.getElementById("bulk-power-shown");
|
||||
var count = document.getElementById("bulk-power-count");
|
||||
function onScreen() {
|
||||
return Array.prototype.filter.call(document.querySelectorAll("input[name='vm'][form='bulk-power']"),
|
||||
function (box) { return box.getClientRects().length > 0; });
|
||||
}
|
||||
function update() {
|
||||
var boxes = onScreen();
|
||||
var chosen = boxes.filter(function (box) { return box.checked; }).length;
|
||||
form.querySelectorAll("button[name='action']").forEach(function (button) { button.disabled = chosen === 0; });
|
||||
count.textContent = chosen ? count.dataset.text.replace("%(count)s", chosen) : "";
|
||||
shown.disabled = boxes.length === 0;
|
||||
shown.checked = boxes.length > 0 && chosen === boxes.length;
|
||||
shown.indeterminate = chosen > 0 && chosen < boxes.length;
|
||||
}
|
||||
shown.addEventListener("change", function () {
|
||||
var choose = shown.checked;
|
||||
onScreen().forEach(function (box) { box.checked = choose; });
|
||||
update();
|
||||
});
|
||||
// a box, the search, a state or tag pill or a host's collapse changes what is on screen; not
|
||||
// "Choose the VMs shown" itself: its input event comes before its change, which chooses the boxes
|
||||
function changed(event) {
|
||||
if (event.target !== shown) {
|
||||
setTimeout(update, 0);
|
||||
}
|
||||
}
|
||||
["change", "input", "click"].forEach(function (type) { document.addEventListener(type, changed); });
|
||||
// and a filter that answers later (the address search) hides rows by itself
|
||||
var later = null;
|
||||
new MutationObserver(function () {
|
||||
clearTimeout(later);
|
||||
later = setTimeout(update, 50);
|
||||
}).observe(document.querySelector(".table-responsive") || document.body,
|
||||
{attributes: true, attributeFilter: ["hidden", "class"], subtree: true});
|
||||
form.addEventListener("submit", function () {
|
||||
document.querySelectorAll("input[name='vm'][form='bulk-power']:checked").forEach(function (box) {
|
||||
if (!box.getClientRects().length) {
|
||||
box.checked = false; // hidden: not sent
|
||||
}
|
||||
});
|
||||
});
|
||||
update();
|
||||
})();
|
||||
|
||||
// whether VMs on screen are chosen: the list's reload (poll.js pageInUse) waits meanwhile
|
||||
function bulkPowerChosen() {
|
||||
return Array.prototype.some.call(document.querySelectorAll("input[name='vm'][form='bulk-power']:checked"),
|
||||
function (box) { return box.getClientRects().length > 0; });
|
||||
}
|
||||
|
|
@ -50,11 +50,12 @@ function pollWhileVisible(interval, request, onData, firstDelay) {
|
|||
};
|
||||
}
|
||||
|
||||
// The user is in the page: a dialog open, a field in use or an XML edit not
|
||||
// saved. A poll that would reload the page waits for its next answer.
|
||||
// The user is in the page: a dialog open, a field in use, an XML edit not
|
||||
// saved or VMs chosen on the VM list. A poll that would reload the page waits for its next answer.
|
||||
function pageInUse() {
|
||||
var active = document.activeElement;
|
||||
return !!document.querySelector(".modal.show")
|
||||
|| !!(active && active.matches && active.matches("input, select, textarea"))
|
||||
|| !!(window.xmlEditUnsaved && window.xmlEditUnsaved());
|
||||
|| !!(window.xmlEditUnsaved && window.xmlEditUnsaved())
|
||||
|| (typeof bulkPowerChosen === "function" && bulkPowerChosen()); // VMs chosen on the VM list (bulk_power.js)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ ALLOWED_FOR_ANY_USER = {
|
|||
"instances:index": "lists only the user's own instances",
|
||||
"instances:find_address": "searches only the user's own instances",
|
||||
"instances:states": "the VM list's poll: only the user's own instances",
|
||||
"instances:bulk_power": "queues a job only for VMs the user may power (instances.jobs.PowerVM)",
|
||||
"accounts:login": "login page",
|
||||
"accounts:email_otp": "part of the login flow (its own issues are tracked separately)",
|
||||
"accounts:otp_qr": "the OTP QR code a mailed link opens: only with that signed, hour-old-at-most link",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue