1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 17:36:05 +00:00

Merge pull request #697 from catborise/upstream-nov26

Fork updates since v5.0.0: VM screen, fault alerts, PostgreSQL panel backup, menu
This commit is contained in:
catborise 2026-11-26 14:23:29 +03:00 • committed by GitHub
commit ccc6473e74
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
62 changed files with 15488 additions and 319 deletions

View file

@ -91,8 +91,8 @@ jobs:
- name: Check Translation Catalogs
if: matrix.python-version == '3.12' && matrix.database == 'sqlite'
run: |
python manage.py makemessages -l tr -l zh --no-obsolete --ignore=staticfiles -v0
for dir in locale/tr/LC_MESSAGES locale/zh/LC_MESSAGES; do
python manage.py makemessages -l tr -l zh -l uk --no-obsolete --ignore=staticfiles -v0
for dir in locale/tr/LC_MESSAGES locale/zh/LC_MESSAGES locale/uk/LC_MESSAGES; do
msgfmt --check -o /tmp/django.mo "$dir/django.po"
missing=$(msgattrib --untranslated "$dir/django.po"; msgattrib --only-fuzzy "$dir/django.po")
if [ -n "$missing" ]; then echo "$missing"; echo "::error file=$dir/django.po::untranslated or fuzzy messages"; exit 1; fi

View file

@ -61,9 +61,9 @@ It lists the dead keys it leaves out: a character only a dead key types cannot b
English is the source language; the panel is translated into the other languages of `LANGUAGES` in `settings.py`, each with a full catalog in `locale/`. A new or changed text needs its translation in each before CI passes (needs `gettext`):
```bash
python manage.py makemessages -l tr -l zh --no-obsolete --ignore=staticfiles --ignore=.venv
# translate the new and fuzzy entries of locale/tr/LC_MESSAGES/django.po and locale/zh/LC_MESSAGES/django.po
python manage.py compilemessages -l tr -l zh
python manage.py makemessages -l tr -l zh -l uk --no-obsolete --ignore=staticfiles --ignore=.venv
# translate the new and fuzzy entries of the django.po of locale/tr, locale/zh and locale/uk
python manage.py compilemessages -l tr -l zh -l uk
```
## Running tests

View file

@ -11,6 +11,7 @@ RUN apt-get update -qq \
libvirt0 \
nginx \
openssh-client \
postgresql-client \
python3 \
supervisor \
tzdata \

View file

@ -83,7 +83,7 @@ flowchart TB
<li>VMs created, renamed or deleted with <code>virsh</code> or <code>virt-manager</code> are picked up on their own</li>
<li>Tags, protected VMs, search by IP or MAC address and a VM report as an Excel file</li>
<li>Alerts by e-mail or webhook, and a health check URL</li>
<li>English, Turkish and Simplified Chinese</li>
<li>English, Turkish, Simplified Chinese and Ukrainian</li>
</ul>
</td>
</tr>

View file

@ -1,39 +1,93 @@
{% extends "base.html" %}
{% load django_bootstrap5 %}
{% load static %}
{% load i18n %}
{% block title %}{% trans "Change password" %}{% endblock title %}
{% block page_heading %}{% trans "Change password" %}{% endblock page_heading %}
{# a user who must change it (the first admin, a new or reset account) can go nowhere else first #}
{% block navbar %}{% if not must_change %}{{ block.super }}{% endif %}{% endblock navbar %}
{% block page_header %}{% endblock page_header %}{# the card has its own heading #}
{% block content %}
{# a user changes their own password; one who must (a new or reset account) cannot go elsewhere first #}
<form id="password-change" method="post">
{% csrf_token %}
{% bootstrap_form_errors form type="non_fields" %}
<div class="row justify-content-center{% if must_change %} pt-5{% endif %}">
<div class="col-sm-9 col-md-7 col-lg-6">
<div class="card shadow-sm">
<div class="card-body p-4 p-sm-5">
<div class="text-center mb-4">
<div class="d-inline-block rounded-3 text-bg-primary fs-2 lh-1 p-3 mb-3"><i class="bi bi-key" aria-hidden="true"></i></div>
<h1 class="h3 fw-bold mb-1">{% if must_change %}{% trans "Set your own password" %}{% else %}{% trans "Change password" %}{% endif %}</h1>
<p class="text-body-secondary small mb-0">
{% if must_change %}
{% blocktrans with name=request.user.username %}Signed in as {{ name }} with a temporary password. Replace it to continue.{% endblocktrans %}
{% else %}
{% blocktrans with name=request.user.username %}For {{ name }}. You stay signed in here; your other sessions end.{% endblocktrans %}
{% endif %}
</p>
</div>
<section class="form-section">
<div class="row g-3">
<div class="col-lg-3">
<h2 class="h6 fw-semibold mb-1 text-break">{{ request.user.username }}</h2>
<p class="small text-body-secondary mb-0">
{% if must_change %}{% trans "Choose a new password before you go on." %}{% else %}{% trans "You stay signed in here; your other sessions end." %}{% endif %}
</p>
</div>
<div class="col-lg-9 form-section-fields">
<div class="row g-3">
<div class="col-sm-6">{% bootstrap_field form.old_password %}</div>
<div class="w-100 m-0"></div>
<div class="col-sm-6">{% bootstrap_field form.new_password1 %}</div>
<div class="col-sm-6">{% bootstrap_field form.new_password2 show_help=False %}</div>
{% for error in form.non_field_errors %}
<div class="alert alert-danger mb-4" role="alert">{{ error }}</div>
{% endfor %}
<form id="password-change" method="post" novalidate>
{% csrf_token %}
{# focus: the first entry with an error; a refused new password is typed again from the first entry #}
{% with old_bad=form.old_password.errors new_bad=form.new_password1.errors again_bad=form.new_password2.errors %}
<div class="mb-4">
<label class="form-label small fw-medium" for="id_old_password">{% if must_change %}{% trans "Temporary password" %}{% else %}{% trans "Current password" %}{% endif %}</label>
<input type="password" id="id_old_password" name="old_password" class="form-control{% if old_bad %} is-invalid{% endif %}"
autocomplete="current-password" required{% if old_bad %} aria-invalid="true" aria-describedby="old-password-error"{% elif must_change %} aria-describedby="old-password-help"{% endif %}{% if not form.is_bound or old_bad %} autofocus{% endif %}>
{% if old_bad %}<div id="old-password-error" class="invalid-feedback">{{ old_bad|join:" " }}</div>{% endif %}
{% if must_change %}<div id="old-password-help" class="form-text">{% trans "The one you just signed in with." %}</div>{% endif %}
</div>
<div class="mb-4">
<label class="form-label small fw-medium" for="id_new_password1">{% trans "New password" %}</label>
<div class="input-group has-validation">
<input type="password" id="id_new_password1" name="new_password1" class="form-control{% if new_bad or again_bad %} is-invalid{% endif %}"
autocomplete="new-password" aria-describedby="{% if new_bad %}new-password-error {% endif %}password-rules" required{% if new_bad or again_bad %} aria-invalid="true"{% if not old_bad %} autofocus{% endif %}{% endif %}>
<button class="btn btn-outline-secondary" type="button" id="toggle-new-password" aria-label="{% trans 'Toggle password visibility' %}" aria-pressed="false"><i class="bi bi-eye"></i></button>
{% if new_bad %}<div id="new-password-error" class="invalid-feedback">{{ new_bad|join:" " }}</div>{% endif %}
</div>
</div>
<div class="mb-3">
<label class="form-label small fw-medium" for="id_new_password2">{% trans "New password again" %}</label>
<input type="password" id="id_new_password2" name="new_password2" class="form-control{% if again_bad %} is-invalid{% endif %}"
autocomplete="new-password" aria-describedby="password-rules" required{% if again_bad %} aria-invalid="true"{% endif %}>
</div>
{# the rules the server checks; the first three are checked as you type, its refusals follow #}
<ul id="password-rules" class="list-unstyled small mb-4" data-met="{% trans "met" %}" data-unmet="{% trans "not met" %}">
<li class="d-flex" data-rule="length"><i class="bi bi-circle me-2" aria-hidden="true"></i><span>{% trans "8 characters or more" %} <span class="visually-hidden">{% trans "not met" %}</span></span></li>
<li class="d-flex" data-rule="letters"><i class="bi bi-circle me-2" aria-hidden="true"></i><span>{% trans "Not only digits" %} <span class="visually-hidden">{% trans "not met" %}</span></span></li>
<li class="d-flex" data-rule="match"><i class="bi bi-circle me-2" aria-hidden="true"></i><span>{% trans "Both entries match" %} <span class="visually-hidden">{% trans "not met" %}</span></span></li>
<li class="d-flex text-body-secondary"><i class="bi bi-hourglass me-2" aria-hidden="true"></i><span>{% trans "Not like your name or e-mail, and not a common password: checked when you save" %}</span></li>
{% for error in again_bad %}
<li class="d-flex text-danger fw-medium"><i class="bi bi-x-circle-fill me-2" aria-hidden="true"></i><span>{{ error }}</span></li>
{% endfor %}
</ul>
{% endwith %}
<button type="submit" class="btn btn-primary w-100 py-2">
{% if must_change %}{% trans "Save and continue" %}{% else %}{% trans "Change password" %}{% endif %}
</button>
</form>
<div class="text-center small mt-4">
{% if must_change %}
<form method="post" action="{% url 'accounts:logout' %}" class="d-inline">{% csrf_token %}
<button type="submit" class="btn btn-link btn-sm text-body-secondary">{% trans "Log out" %}</button>
</form>
{% else %}
<a class="text-body-secondary" href="{% url 'accounts:profile' %}">{% trans "Cancel" %}</a>
{% endif %}
</div>
</div>
</div>
</section>
<div class="form-section d-flex justify-content-end gap-2">
{% if not must_change %}<a class="btn btn-outline-secondary" href="{% url 'accounts:profile' %}">{% trans "Cancel" %}</a>{% endif %}
<button type="submit" class="btn btn-primary">{% trans "Change password" %}</button>
</div>
</form>
</div>
{% endblock content %}
{% block script %}
<script src="{% static 'js/password_change.js' %}"></script>
{% endblock script %}

View file

@ -11,7 +11,7 @@
<div class="card shadow-sm">
<div class="card-body p-4 p-sm-5">
<div class="text-center mb-4">
<div class="d-inline-block rounded-3 bg-primary text-white fs-2 lh-1 p-3 mb-3"><i class="bi bi-hdd-network"></i></div>
<div class="d-inline-block rounded-3 text-bg-primary fs-2 lh-1 p-3 mb-3"><i class="bi bi-hdd-network"></i></div>
<h1 class="h3 fw-bold mb-1">WebVirtCloud</h1>
<p class="text-body-secondary small mb-0">{% trans "Virtualization management console" %}</p>
</div>

View file

@ -1,7 +1,10 @@
"""Changes to a user's own account, VM ownership, OTP mails and SSH keys write rows on the Logs page."""
import tempfile
from pathlib import Path
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.test import TestCase, override_settings
from django.urls import reverse
from accounts.models import UserAttributes
@ -38,8 +41,10 @@ class OwnAccountRowTests(TestCase):
def test_the_first_login_password_change(self):
self.bob.user_permissions.clear()
UserAttributes.objects.update_or_create(user=self.bob, defaults={"must_change_password": True})
self.client.post(reverse("accounts:change_password"), {
"old_password": "Bob-pass-2026", "new_password1": "Bob-new-pass-1", "new_password2": "Bob-new-pass-1"})
# the last forced change deletes data/admin_password: not this checkout's
with tempfile.TemporaryDirectory() as base, override_settings(BASE_DIR=Path(base)):
self.client.post(reverse("accounts:change_password"), {
"old_password": "Bob-pass-2026", "new_password1": "Bob-new-pass-1", "new_password2": "Bob-new-pass-1"})
self.assertEqual(rows(), [("User bob: change password", True)])

View file

@ -44,7 +44,7 @@ class ChangePasswordPermissionTestCase(TestCase):
self.assertContains(page, f'href="{reverse("accounts:profile")}">Cancel')
UserAttributes.objects.create(user=user, must_change_password=True)
page = self.client.get(reverse("accounts:change_password"))
self.assertContains(page, "Choose a new password before you go on.")
self.assertContains(page, "Replace it to continue.")
self.assertNotContains(page, f'href="{reverse("accounts:profile")}">Cancel')
def test_a_user_without_a_local_password_cannot_change_it(self):

View file

@ -59,6 +59,43 @@ class FirstLoginPasswordChangeTestCase(TestCase):
response = self.client.get(reverse("instances:index"))
self.assertEqual(response.status_code, 200)
def test_the_forced_form_has_no_menu_and_offers_sign_out(self):
# every page but this one sends the user back here: no links that lead nowhere
self.client.force_login(self.admin)
response = self.client.get(reverse("accounts:change_password"))
self.assertNotContains(response, f'href="{reverse("instances:index")}"')
self.assertContains(response, f'action="{reverse("accounts:logout")}"')
self.assertContains(response, "Temporary password")
def test_a_refused_new_password_shows_the_reasons_in_the_rules(self):
self.client.force_login(self.admin)
response = self.client.post(reverse("accounts:change_password"), {
"old_password": GENERATED, "new_password1": "12345678", "new_password2": "12345678",
})
rules = response.content.decode().split('id="password-rules"')[1].split("</ul>")[0]
self.assertIn("This password is entirely numeric.", rules)
def test_an_empty_first_new_entry_is_shown_and_focused(self):
self.client.force_login(self.admin)
response = self.client.post(reverse("accounts:change_password"), {
"old_password": GENERATED, "new_password1": "", "new_password2": "A-new-strong-pass-456",
})
page = response.content.decode()
self.assertIn('id="new-password-error"', page)
first_entry = page.split('id="id_new_password1"')[1].split(">")[0]
self.assertIn('aria-invalid="true"', first_entry)
self.assertIn("autofocus", first_entry)
def test_a_chosen_change_keeps_the_menu_and_a_way_back(self):
other = get_user_model().objects.create_superuser(
username="otheradmin", email="otheradmin@example.com", password="Other-pass-789"
)
self.client.force_login(other)
response = self.client.get(reverse("accounts:change_password"))
self.assertContains(response, f'href="{reverse("instances:index")}"')
self.assertContains(response, f'href="{reverse("accounts:profile")}"')
self.assertContains(response, "Current password")
def test_user_with_another_password_is_not_forced(self):
get_user_model().objects.create_superuser(
username="otheradmin", email="otheradmin@example.com", password="Other-pass-789"

View file

@ -15,8 +15,8 @@ PREFIX = "webvirtcloud-backup-"
class Command(BaseCommand):
help = ("Copy the database, secret key, worker id, local settings and the SSH keys and TLS certificates of the "
"panel's user into a new directory in backups/, then delete all but the newest --keep backups.")
help = ("Copy the database (sqlite) or dump it (PostgreSQL), the secret key, worker id, local settings and the "
"SSH keys and TLS certificates of the panel's user into a new directory in backups/, then delete all but the newest --keep backups.")
def add_arguments(self, parser):
parser.add_argument("--keep", type=int, default=7, help="how many backups to keep (default 7)")
@ -65,6 +65,8 @@ class Command(BaseCommand):
result = copy.execute("PRAGMA integrity_check").fetchone()[0]
if result != "ok":
raise CommandError(f"The copy of the database is damaged: {result}")
elif database["ENGINE"] == "django.db.backends.postgresql":
self.dump_postgresql(database, to / "db.pgdump")
else:
self.stderr.write("The database is not sqlite and is not in the backup: back it up with its own tools.")
# the key in use: SECRET_KEY from the environment has no data/secret_key
@ -87,3 +89,16 @@ class Command(BaseCommand):
commit = subprocess.run(["git", "rev-parse", "HEAD"], cwd=settings.BASE_DIR, capture_output=True, text=True)
if commit.returncode == 0:
(to / "commit").write_text(commit.stdout)
@staticmethod
def dump_postgresql(database, to):
"""pg_dump's own format, which pg_restore reads; a consistent state while the panel writes."""
if shutil.which("pg_dump") is None:
raise CommandError("pg_dump is not installed: install the PostgreSQL client (postgresql-client)")
# libpq reads the password and the connect timeout from the environment, not the command line
env = {**os.environ, "PGPASSWORD": database["PASSWORD"], "PGCONNECT_TIMEOUT": "10"}
dump = subprocess.run(["pg_dump", "--format=custom", f"--file={to}", f"--host={database['HOST']}",
f"--port={database['PORT']}", f"--username={database['USER']}", f"--dbname={database['NAME']}"],
env=env, capture_output=True, text=True)
if dump.returncode != 0:
raise CommandError(f"pg_dump failed: {dump.stderr.strip()}")

View file

@ -31,7 +31,7 @@ class AppSettingsTestCase(TestCase):
page = self.client.get(reverse("appsettings")).content.decode()
choice = page[page.index('<select id="language"'):]
choice = choice[:choice.index("</select>")]
self.assertEqual(re.findall(r'<option value="([^"]+)"', choice), ["en", "tr", "zh-hans"])
self.assertEqual(re.findall(r'<option value="([^"]+)"', choice), ["en", "tr", "zh-hans", "uk"])
def test_the_page_answers_in_the_users_language(self):
response = self.client.post(reverse("appsettings"), {}, HTTP_ACCEPT_LANGUAGE="tr", follow=True)

View file

@ -6,11 +6,11 @@ from datetime import datetime
import os
import shutil
import sqlite3
import subprocess
import tempfile
from contextlib import closing
from io import StringIO
from pathlib import Path
from unittest import skipUnless
from unittest.mock import patch
from django.core.management import call_command
@ -21,8 +21,6 @@ from django.test import SimpleTestCase, override_settings
from appsettings.management.commands.backup import Command
SQLITE_ONLY = skipUnless(connection.vendor == "sqlite", "the backup copies only a sqlite database")
class BackupTests(SimpleTestCase):
def setUp(self):
@ -49,7 +47,8 @@ class BackupTests(SimpleTestCase):
db.execute("CREATE TABLE computes_compute (name)")
db.execute("INSERT INTO computes_compute VALUES ('kept')")
db.commit()
name = patch.dict(connection.settings_dict, NAME=str(self.base / "db.sqlite3"))
# a sqlite panel also on the PostgreSQL test run; the PostgreSQL tests patch their own
name = patch.dict(connection.settings_dict, ENGINE="django.db.backends.sqlite3", NAME=str(self.base / "db.sqlite3"))
name.start()
self.addCleanup(name.stop)
@ -61,7 +60,6 @@ class BackupTests(SimpleTestCase):
def kept(self):
return sorted(p.name for p in self.backups.iterdir() if p.name != ".lock")
@SQLITE_ONLY
def test_a_backup_holds_the_database_keys_and_settings_for_the_panel_user_only(self):
backup = self.backup()
with closing(sqlite3.connect(backup / "db.sqlite3")) as db:
@ -110,7 +108,6 @@ class BackupTests(SimpleTestCase):
self.backup("--keep", "1")
self.assertEqual(self.kept(), ["webvirtcloud-backup-20260101-000000"])
@SQLITE_ONLY
def test_a_damaged_copy_fails(self):
with patch("appsettings.management.commands.backup.sqlite3") as sqlite, \
self.assertRaisesRegex(CommandError, "damaged: row 3 missing from index"):
@ -126,10 +123,34 @@ class BackupTests(SimpleTestCase):
self.backup()
self.assertEqual(self.kept(), [])
def test_a_database_other_than_sqlite_is_left_out(self):
errors = StringIO()
with patch.dict(connection.settings_dict, ENGINE="django.db.backends.postgresql"):
call_command("backup", stdout=StringIO(), stderr=errors)
backup = self.backups / self.kept()[0]
self.assertNotIn("db.sqlite3", [p.name for p in backup.iterdir()])
self.assertIn("back it up with its own tools", errors.getvalue())
def postgresql(self):
return patch.dict(connection.settings_dict, ENGINE="django.db.backends.postgresql", HOST="192.0.2.10",
PORT="5432", NAME="webvirtcloud", USER="webvirtcloud", PASSWORD="db password")
def test_a_postgresql_database_is_dumped_with_its_password_out_of_the_command_line(self):
def pg_dump(args, env, **kwargs):
Path(args[2].removeprefix("--file=")).write_bytes(b"PGDMP")
return subprocess.CompletedProcess(args, 0, "", "")
with self.postgresql(), patch("shutil.which", return_value="/usr/bin/pg_dump"), \
patch("subprocess.run", side_effect=pg_dump) as run:
backup = self.backup()
args, env = run.call_args.args[0], run.call_args.kwargs["env"]
self.assertEqual(args, ["pg_dump", "--format=custom", f"--file={backup.parent}/.{backup.name}/db.pgdump",
"--host=192.0.2.10", "--port=5432", "--username=webvirtcloud", "--dbname=webvirtcloud"])
self.assertEqual(env["PGPASSWORD"], "db password")
self.assertEqual((backup / "db.pgdump").read_bytes(), b"PGDMP")
self.assertEqual(oct((backup / "db.pgdump").stat().st_mode & 0o777), "0o600")
def test_a_failed_dump_fails_the_backup(self):
failed = subprocess.CompletedProcess([], 1, "", "pg_dump: error: server version mismatch\n")
with self.postgresql(), patch("shutil.which", return_value="/usr/bin/pg_dump"), \
patch("subprocess.run", return_value=failed), self.assertRaisesRegex(CommandError, "server version mismatch"):
self.backup()
self.assertEqual(self.kept(), [])
def test_a_postgresql_database_without_pg_dump_fails_the_backup(self):
with self.postgresql(), patch("shutil.which", return_value=None), \
self.assertRaisesRegex(CommandError, "install the PostgreSQL client"):
self.backup()
self.assertEqual(self.kept(), [])

View file

@ -11,12 +11,10 @@ from django.conf import settings
from django.shortcuts import redirect, render
from django.utils.translation import gettext_lazy as _
from instances.models import Instance
from instances.utils import can_open_console
from instances.utils import can_open_console, novnc_unreachable
from libvirt import libvirtError
from operations.utils import safe_text
from vrtManager.connection import CONN_TCP, CONN_TLS
from vrtManager.instance import wvmInstance
from vrtManager.util import is_loopback
from webvirtcloud.middleware import error_text
logger = logging.getLogger(__name__)
@ -68,9 +66,8 @@ def console(request, compute_id, uuid):
running = conn.instance.isActive()
# novncd reaches a console that listens on its host's loopback only
# through SSH (or on this host); the running VM's listener, as novncd sees it
unreachable = instance.compute.type in (CONN_TCP, CONN_TLS) and bool(
conn.get_console_socket() or is_loopback(conn.get_console_listener_addr())
)
unreachable = novnc_unreachable(instance.compute.type, conn.get_console_socket(),
conn.get_console_listener_addr())
except libvirtError as err:
# the host or the VM could not be read: the page says that, not to check the console settings
logger.warning("Console of %s on %s: %s", instance.name, instance.compute.name, safe_text(err))

View file

@ -7,7 +7,8 @@
The panel backs itself up every day at 03:15 (cron in Docker; otherwise `webvirt-backup.timer`, within 10 minutes after and at the next boot if the server was off) into a new directory under `/srv/webvirtcloud/backups`, in Docker the `webvirtcloud-backups` volume, and keeps the newest 7. A backup holds:
- `db.sqlite3`: a consistent copy taken while the panel runs, checked with `PRAGMA integrity_check`; with PostgreSQL it is left out, so back up that database yourself
- `db.sqlite3`: a consistent copy taken while the panel runs, checked with `PRAGMA integrity_check`
- `db.pgdump` instead, with PostgreSQL: a `pg_dump` of the database in its custom format. The Docker image has `pg_dump`; otherwise install the PostgreSQL client (`postgresql-client` on Debian and Ubuntu, `postgresql` on RHEL), of the server's major version or newer. Without it the backup fails
- `secret_key`, `node_id` and `local_settings.py`
- `ssh/`: the SSH keys of the panel's user, which the SSH computes accept
- `pki/`: the TLS client certificates of the panel's user, which the TLS computes accept

View file

@ -16,7 +16,7 @@ What an update from an older version changes for operators and users. To run the
- gstfsd does only what the panel signs with the host's key: it does not start without `GSTFSD_KEY` in `/etc/default/webvirt-gstfsd`. On every compute, update gstfsd and its unit and make the key as in [Adding a Compute Node, step 3](compute-nodes.md#3-install-gstfsd) (a remote panel's `GSTFSD_BIND_HOST` and `GSTFSD_ALLOW_REMOTE` move into that file from `systemctl edit webvirt-gstfsd`), then enter the key on each compute's edit page.
- LDAP login's packages are in `conf/requirements-ldap.txt` and no longer installed by default, nor their build headers by the installer; the Docker image keeps them. An existing virtualenv keeps them, but only installing that file updates them (see [LDAP](ldap.md)).
- The themes ship compiled; picking one on the Settings page only saves its name, and the "Theme SASS Path" setting is gone. Browsers revalidate static files on each load: files cached before the update can stay until a hard reload (Ctrl+F5) of each page; an external caching proxy may need a purge.
- The panel backs itself up every day ([Backups](backups.md)); in Docker into a new volume, `webvirtcloud-backups`.
- The panel backs itself up every day ([Backups](backups.md)); in Docker into a new volume, `webvirtcloud-backups`. With PostgreSQL the backup holds a `pg_dump` of the database and fails without `pg_dump`: outside Docker, install the PostgreSQL client.
- The Docker image is built on Ubuntu 26.04 LTS (Python 3.14, libvirt 12) instead of 24.04; `docker compose up -d --build` rebuilds it.
- New passwords must pass Django's password validators: at least 8 characters, not a common password, not only digits, not like the user's name or e-mail. Existing passwords keep working.
- In Docker, the TLS client certificates of TLS computes are kept in a new volume, `webvirtcloud-pki` (`/var/www/.pki`), and backed up; put them there once ([Adding a Compute Node, TLS](compute-nodes.md#tls)).
@ -33,6 +33,8 @@ What an update from an older version changes for operators and users. To run the
- On a running VM the edit forms show the settings as they will be at the next start, so saving an edit no longer reverts another pending change.
- External snapshots need libvirt 9.9 or newer on the computes. libvirt 9.10 (openEuler 24.03 LTS) refuses to revert a snapshot taken without memory of a running or paused VM ("Invalid target domain state 'disk-snapshot'"); 11.10 reverts it. A VM's snapshots form one chain: after a revert, delete the newer snapshots before taking another. An internal snapshot is reverted only on a shut-off VM. Snapshot names no longer get an `s1.` prefix. A snapshot an older version took of a UEFI VM can only be deleted, not reverted. On NFS, the qemu user needs write access to the image directory to remove merged snapshot files.
- A superuser limits a disk's I/O (IOPS and MiB/s, reads and writes together) under its Device details on the Disks tab; a running VM gets the limit at once.
- The VM page shows a running or paused VM's screen beside its summary, read again every 10 seconds, to those who may open its console; clicking it opens the console. It needs a VNC or SPICE console and a host whose libvirt gives screenshots as PNG (libvirt 9 and QEMU 7.1 or later); otherwise it is not shown.
- **Free unused space** on a running VM's Disks tab (superusers) has its guest agent trim each file system (`guest-fstrim`, a job that lists what each one trimmed). Only a disk with the discard mode `unmap` (Device details, from the VM's next start; Settings > Disk Discard for new disks) passes it to its image file, which then shrinks; the tab says when no disk has it.
- A storage volume a VM still needs (a disk, a backing file or a snapshot's file) is not deleted; deleting a VM with its files keeps a file another compute's VM or volume uses at the same path, and is refused before the VM is stopped when one of the other computes cannot be reached. A pool's page names the VMs of its host that use each volume and lists those the host does not use.
- A VM that vanishes from its compute, or whose compute is deleted, keeps its owners, tags, protection and schedules for `INSTANCE_OWNERSHIP_RETENTION_DAYS` (30) in case the same UUID comes back, and its backups are linked to it again; superusers manage these records on the "Removed VMs" page.
- The Logs page records who changed what (computes, users, groups, VM owners, settings, SSH keys, host networks, pools, volumes, interfaces, secrets and network filters), every login, failed login and lockout, and every page or API call answered 401 or 403 to a signed-in user or a request with credentials, with the address and the result (a VM hidden with 404 is not logged).

View file

@ -108,6 +108,24 @@ datasource:
Without the network: tick **Cloud-init seed** (Advanced) when creating a VM. The VM gets a CD-ROM with its hostname and your SSH keys (a NoCloud seed, `cidata-<uuid>.iso` in the disk's directory pool), which the image's cloud-init reads at first boot; it is deleted with the VM's disks.
### A template for the seed
Distribution cloud images (`GenericCloud`, `genericcloud`) come with cloud-init. A template installed from an ISO needs it once:
1. Start a VM on the template disk and install cloud-init in it: `dnf install -y cloud-init` or `apt install -y cloud-init`.
2. Remove what makes it this machine and shut it down:
```sh
cloud-init clean --logs --seed
truncate -s 0 /etc/machine-id
poweroff
```
Empty `/etc/machine-id`, do not delete it: without the file a Debian 12 clone gets no DHCP address (`cloud-init clean --machine-id` deletes it there).
3. Turn on **Settings > Options > Use as a template**, so the VM is not started again.
Create VMs with **Clone from template**, this VM's disk as **Template volume** and **Cloud-init seed** ticked. At first boot a VM takes its name as hostname and gets new SSH host keys and a new machine-id; your keys go to the image's default user (`default_user` in `/etc/cloud/cloud.cfg`, for example `almalinux` or `debian`), and `cloud-init status` says `done`. The seed sets no password and no static address: the network comes up with DHCP. A copy made on the VM's **Clone** tab gets no seed.
## Two-factor login (OTP)
Set `OTP_ENABLED = True` in [`data/local_settings.py`](#local-settings) to ask for a one-time code at login. It is per user: a user without a confirmed device signs in with the password alone.
@ -116,7 +134,7 @@ The QR code is mailed as a link to a page that shows it, good for one hour: the
## Alerts
On the Settings page (Alerts), **Alert e-mail addresses** get a mail, through the server's SMTP settings (`EMAIL_HOST` and the others, as for OTP), and **Alert webhook** a JSON POST (`subject`, `text`, `time`; Slack and Mattermost take it) when a backup job fails, a scheduled backup is not taken (not for a host in maintenance), the daily target check finds backups missing, a verification finds a backup damaged, or a job ends uncertain. The job worker sends them within a minute and tries a failed channel again for ten minutes.
On the Settings page (Alerts), **Alert e-mail addresses** get a mail, through the server's SMTP settings (`EMAIL_HOST` and the others, as for OTP), and **Alert webhook** a JSON POST (`subject`, `text`, `time`; Slack and Mattermost take it) when a backup job fails, a scheduled backup is not taken (not for a host in maintenance), the daily target check finds backups missing, a verification finds a backup damaged, a job ends uncertain, or a fault stops or pauses a VM (a disk error, a crash, a kernel panic: the reasons the VM page shows; once a fault, read every minute from each host, so told within two minutes). The job worker sends them within a minute and tries a failed channel again for ten minutes.
## Health check

View file

@ -24,7 +24,7 @@ WebVirtCloud combines three kinds of access rights:
| Clone | ✅ | ✅ | `is_change` and `instances.clone_instances` (templates: viewing the template is enough) | templates only, with `instances.clone_instances` |
| Delete the VM, with its disk files when chosen | ✅ | ✅ | `is_delete` | ❌ |
| Disks and media (add, attach, edit, detach, delete volumes; CD-ROM/ISO) | ✅ | ❌ | — | ❌ |
| Network interfaces, host devices (PCI/USB), boot options, vCPU hotplug, autostart, guest agent, video, RNG, TPM, crash and hang action, disk I/O limits, suspend/resume, migrate, disk moves, protection, raw XML, owners | ✅ | ❌ | — | ❌ |
| Network interfaces, host devices (PCI/USB), boot options, vCPU hotplug, autostart, guest agent, video, RNG, TPM, crash and hang action, disk I/O limits, free unused space (fstrim), suspend/resume, migrate, disk moves, protection, raw XML, owners | ✅ | ❌ | — | ❌ |
| Set tags (owners and `view_instances` see them) | ✅ | ❌ | — | ❌ |
| Backups: back up (within the backup quota), restore over the VM or as a new VM (within the VM quota), into and from targets open to VM owners | ✅ | ✅ | `is_change` and `instances.backup_instances` | ❌ |
| Delete a backup one took by hand (not a schedule's) on a target open to VM owners | ✅ | ✅ | `instances.backup_instances` (ownership not needed) | ❌ |

View file

@ -70,7 +70,7 @@ From a root shell:
## Restore and rollback
Restoring puts back the database as it was at the backup; changes made since are lost. Migrations are not reversed. This covers sqlite; restore a PostgreSQL database from your own backup before rolling back the code. Set `b` to the backup directory to restore. To restore the database without rolling back the code, leave out the `build` line and every line that takes another file from `$b`: the commit, `local-migrations.tar`, `settings.py` and `local_settings.py`, the nginx config and `/etc/default/webvirtcloud`.
Restoring puts back the database as it was at the backup; changes made since are lost. Migrations are not reversed. With PostgreSQL, restore the database from the backup's `db.pgdump` before rolling back the code, as in [Restoring a PostgreSQL database](#restoring-a-postgresql-database), and leave out the line below that restores `db.sqlite3`. Set `b` to the backup directory to restore. To restore the database without rolling back the code, leave out the `build` line and every line that takes another file from `$b`: the commit, `local-migrations.tar`, `settings.py` and `local_settings.py`, the nginx config and `/etc/default/webvirtcloud`.
Docker, in the directory you installed from:
@ -123,9 +123,19 @@ nginx -t && systemctl reload nginx && systemctl start webvirt-cloud webvirt-novn
A version from before v3.0.0 has no worker: `systemctl disable --now webvirt-worker`. A rollback keeps the systemd units, and drops what a stopped `update.sh` kept to go on with (`data/.update-backup`). A rollback leaves the clone on a detached HEAD at the restored commit; `update.sh` records that commit before it switches back to `master`.
### Restoring a PostgreSQL database
With the panel stopped, from a shell with the PostgreSQL client and the `WEBVIRTCLOUD_DB_*` values the panel uses. The first command empties the database, also of tables a later version added:
```bash
export PGPASSWORD="$WEBVIRTCLOUD_DB_PASSWORD" &&
psql -h "$WEBVIRTCLOUD_DB_HOST" -U webvirtcloud -d webvirtcloud -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public" &&
pg_restore --no-owner -h "$WEBVIRTCLOUD_DB_HOST" -U webvirtcloud -d webvirtcloud "$b/db.pgdump"
```
## Moving to a new machine
A [backup](backups.md) moves the panel to a new machine, or back onto lost volumes: the database, the secret key (signed-in users stay signed in), the worker's id and the SSH keys and TLS certificates the computes accept. Install the panel there first, the same version or a newer one, then copy the backup directory over and set `b` to it. The backup does not hold `docker-compose.override.yml`, the nginx config or `/etc/default/webvirtcloud`: bring your own lines over yourself. Users sign in with their passwords from the backup; the new installation's `data/admin_password` no longer applies. The backup's `secret_key` is the key in use, also one set as `SECRET_KEY` in the environment. With PostgreSQL, restore that database yourself and leave out the line below that restores `db.sqlite3` (the backup has none), and stop the old panel before the new one starts: both would run the jobs of the one database.
A [backup](backups.md) moves the panel to a new machine, or back onto lost volumes: the database, the secret key (signed-in users stay signed in), the worker's id and the SSH keys and TLS certificates the computes accept. Install the panel there first, the same version or a newer one, then copy the backup directory over and set `b` to it. The backup does not hold `docker-compose.override.yml`, the nginx config or `/etc/default/webvirtcloud`: bring your own lines over yourself. Users sign in with their passwords from the backup; the new installation's `data/admin_password` no longer applies. The backup's `secret_key` is the key in use, also one set as `SECRET_KEY` in the environment. With PostgreSQL, restore the backup's `db.pgdump` as in [Restoring a PostgreSQL database](#restoring-a-postgresql-database) and leave out the line below that restores `db.sqlite3` (the backup has none); stop the old panel before the new one starts: both would run the jobs of the one database.
Docker, in the directory you installed from:

View file

@ -31,10 +31,11 @@ from appsettings.settings import app_settings
from computes.models import Compute
from instances import addresses, utils
from instances.models import Instance
from instances.states import state_reason
from logs.audit import write
from operations import claims
from operations import alerts, claims
from operations.utils import REPORTED, safe_text, say
from operations.jobs import Cancelled, Kind, Outcome, Plan, register
from operations.jobs import Cancelled, Kind, Outcome, Plan, register, register_periodic
from operations.models import Claim, Operation
@ -1660,3 +1661,87 @@ class ForceOffVM(_Power):
def done(self, dom): # shut off, or gone: a transient VM is removed as it stops
return dom is None or not dom.isActive()
@register
class TrimVM(Kind):
"""Has a running VM's guest agent trim the free space of its file systems (guest-fstrim): a disk whose
discard mode is unmap passes it on, and its image file shrinks. Trimming again is harmless."""
name = "instance.fstrim"
label = gettext_noop("Free unused space")
time_limit = 1800 # the agent's wait (FSTRIM_TIMEOUT): over time is only noted
def normalize(self, raw):
return {"instance": int(raw["instance"])}
def validate(self, user, params):
if not user.is_superuser: # as the Disks tab's other superuser controls
raise PermissionDenied
def plan(self, user, params):
return _vm_plan(params)
def precheck(self, op, ctx):
if op.user is None or not (op.user.is_active and op.user.is_superuser): # still, when it runs
raise PermissionDenied
if _instance(op.params["instance"]).compute_id != op.intent["compute"]:
raise util.OperationError(MOVED)
def run(self, op, ctx):
instance = _instance(op.params["instance"])
proxy = instance.proxy
if proxy.get_status() != 1:
raise util.OperationError(gettext_noop("The VM is not running"))
if not proxy.is_agent_ready():
raise util.OperationError(gettext_noop("The guest agent is not connected"))
ctx.record_intent(trimming=True) # the guest is asked from here
trimmed = proxy.fstrim()
if trimmed and all(fs["error"] for fs in trimmed): # the guest refused every file system
raise util.OperationError(gettext_noop("No file system was trimmed: %(errors)s"),
errors="; ".join(f"{fs['path']}: {fs['error']}" for fs in trimmed))
result = {"trimmed": trimmed}
if not instance.discard_unmap:
result["warning"] = say(NO_DISCARD)
return result
def reconcile(self, op):
return Outcome(Operation.FAILED, error=say(gettext_noop(
"The job stopped before the guest answered; trimming again is harmless")))
def log_entry(self, op, state):
return _log(op, state, "free unused space")
NO_DISCARD = _("No disk of the running VM has the discard mode unmap: its image files keep their size. Set it in "
"a disk's device details; it takes effect at the VM's next start.")
VM_FAULT = _("VM fault: %(vm)s")
VM_FAULT_TEXT = _("%(vm)s on %(host)s: %(reason)s")
def watch_faults():
"""Alerts once when a fault stops or pauses a VM (instances.states.REASONS), while an alert channel is set:
each host's VMs read in one call, all hosts at once (utils.host_domain_states); a host that does not answer
is read again at the next pass. Without a channel nothing is told, nor kept as told."""
if not any(alerts.channels()):
Instance.objects.exclude(fault="").update(fault="")
return
computes = list(Compute.objects.all())
states = utils.host_domain_states(computes)
for compute in computes:
domains = states[compute.pk]
if domains is None:
continue
for vm in Instance.objects.filter(compute=compute):
_name, state, reason = domains.get(vm.uuid, (None, None, None))
why = state_reason(state, reason)
fault = f"{state}:{reason}" if why else ""
if fault == vm.fault:
continue
if why:
alerts.alert(say(VM_FAULT, vm=vm.name), say(VM_FAULT_TEXT, vm=vm.name, host=compute.name, reason=str(why)))
Instance.objects.filter(pk=vm.pk).update(fault=fault)
register_periodic(watch_faults)

View file

@ -0,0 +1,18 @@
# Generated by Django 5.2.18 on 2026-11-25 06:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('instances', '0020_tombstone_keeps'),
]
operations = [
migrations.AddField(
model_name='instance',
name='fault',
field=models.CharField(blank=True, default='', max_length=16),
),
]

View file

@ -43,6 +43,8 @@ class Instance(models.Model):
created = models.DateTimeField(_("created"), auto_now_add=True)
drbd = models.CharField(_("drbd"), max_length=24, default="None")
tags = models.ManyToManyField("computes.Tag", blank=True, related_name="instances", verbose_name=_("tags"))
# "state:reason" of the fault (instances.states.REASONS) last alerted; empty without one (instances.jobs.watch_faults)
fault = models.CharField(max_length=16, blank=True, default="")
objects = InstanceManager()
@ -77,6 +79,11 @@ class Instance(models.Model):
def disks(self) -> list[dict]:
return self.proxy.get_disk_devices()
@property
def discard_unmap(self) -> bool:
"""Whether a disk of the running definition passes the guest's trim to its image (discard unmap)."""
return any(disk.get("discard") == "unmap" for disk in self.disks)
@cached_property
def info(self) -> list | None:
"""virDomainGetInfo, read once: state, max memory KiB, memory KiB, vCPUs, CPU time.

View file

@ -21,9 +21,11 @@
data-opens-on="{% if instance.is_template and can_clone %}#clone{% endif %}"
data-random-mac-url="{% url 'instances:random_mac_address' %}"
{% if can_open_console and vdi_reachable %}data-vdi-url="{% url 'vdi_url' compute.id instance.name %}"{% endif %}>
<div class="card-body p-3">
<div class="d-flex flex-wrap justify-content-between align-items-start gap-2">
<div style="min-width: 0;">
<div class="card-body p-3 d-flex flex-wrap flex-md-nowrap gap-3">
<div class="flex-grow-1" style="min-width: 0;">
{# from 576px the buttons keep the name's row: many tags wrap within the name's side #}
<div class="d-flex flex-wrap flex-sm-nowrap justify-content-between align-items-start gap-2">
<div class="flex-grow-1" style="min-width: 0;">
<div class="d-flex flex-wrap align-items-center gap-2">
<h1 class="h4 mb-0 text-break" id="vm-name">{{ instance.name }}</h1>
{% vm_state instance.status as state %}
@ -34,7 +36,7 @@
{% if instance.title %}<p class="text-body-secondary mb-1">{{ instance.title }}</p>{% endif %}
{% include 'instances/host_link.html' %}
</div>
<div class="d-flex gap-2">
<div class="d-flex gap-2 flex-shrink-0">
{% if instance.is_template and can_clone %}
<button type="button" class="btn btn-sm btn-primary" id="clone-button">{% bs_icon 'copy' %} {% trans "Clone" %}</button>
{% endif %}
@ -88,6 +90,24 @@
</div>
{% endif %}
</dl>
</div>
{% if show_screen %}
{# the VM's screen, read by instance_page.js every few seconds and shown once one has come; opens the console where it can #}
{# its caption: whether the picture follows the VM (a suspended one's stays), and that a click opens the console #}
{% if screen_opens_console %}
<button type="button" class="vm-screen" id="vm-screen" hidden data-url="{% url 'console' compute.id instance.uuid %}"
data-window="console-{{ instance.uuid }}" data-screen-url="{% url 'instances:screen' instance.id %}">
{% else %}
<div class="vm-screen" id="vm-screen" hidden data-screen-url="{% url 'instances:screen' instance.id %}">
{% endif %}
<span class="vm-screen-frame"><img alt="{% blocktrans with name=instance.name %}Screen of {{ name }}{% endblocktrans %}"></span>
<span class="vm-screen-caption">
{% if instance.status == 3 %}<span class="vm-screen-state">{% bs_icon 'pause-fill' %} {% trans "Suspended" %}</span>
{% else %}<span class="vm-screen-state"><span class="vm-screen-live" aria-hidden="true"></span> {% trans "Live" context "screen" %}</span>{% endif %}
{% if screen_opens_console %}<span class="vm-screen-open">{% trans "Open console" %}</span>{% endif %}
</span>
{% if screen_opens_console %}</button>{% else %}</div>{% endif %}
{% endif %}
</div>
<div class="card-footer p-1">
{# p-1 inside the scroller keeps the focus ring from being clipped #}

View file

@ -293,6 +293,15 @@
{% endfor %}
</div>
</div>
{% if instance.status == 1 and request.user.is_superuser %}
{# the guest agent trims its file systems' free space; a disk passes it to its image only with discard unmap #}
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2 small mt-3">
<span class="text-body-secondary">{% if instance.discard_unmap %}{% trans "Free space the guest no longer uses in the image files." %}{% else %}{% trans "No disk has the discard mode unmap while the VM runs: trimming frees no space in its image files. Set it in a disk's device details; it takes effect at the next start." %}{% endif %}</span>
<form action="{% url 'instances:fstrim' instance.id %}" method="post">{% csrf_token %}{% submission_key %}
<button type="submit" class="btn btn-sm btn-outline-secondary"{% if not instance.guest_agent_ready %} disabled title="{% trans "The guest agent is not connected" %}"{% endif %}>{% trans "Free unused space" %}</button>
</form>
</div>
{% endif %}
{% if instance.pcie_slots %}
{# a PCIe machine gives each virtio disk and network device a slot; a running VM gets no new one #}
{% with total=instance.pcie_slots.0 free=instance.pcie_slots.1 next=instance.config_pcie_slots %}

View file

@ -0,0 +1,59 @@
from unittest import mock
import libvirt
from django.test import TestCase
from appsettings.models import AppSettings
from computes.models import Compute
from instances import jobs
from instances.models import Instance
from operations.models import Alert
from operations.utils import words
PAUSED_IOERROR = (libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_IOERROR)
RUNNING = (libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_RUNNING_BOOTED)
PAUSED_BY_USER = (libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_USER)
class FaultAlertTests(TestCase):
def setUp(self):
AppSettings.objects.update_or_create(key="ALERT_WEBHOOK", defaults={"name": "Alert webhook",
"value": "http://192.0.2.9/hook"})
self.compute = Compute.objects.create(name="h1", hostname="192.0.2.71", login="u", password="p", type=1)
self.vm = Instance.objects.create(compute=self.compute, name="vm1", uuid="71717171-0000-4000-8000-000000000001")
def watch(self, state):
"""One pass with the host's VM in state (state, reason), or the host not answering (None)."""
answer = None if state is None else {self.vm.uuid: ["vm1", *state]}
with mock.patch.object(jobs.utils, "host_domain_states", return_value={self.compute.pk: answer}):
jobs.watch_faults()
self.vm.refresh_from_db()
def test_a_fault_is_alerted_once_and_again_after_the_vm_recovers(self):
self.watch(PAUSED_IOERROR)
self.assertEqual([(words(a.subject), words(a.text)) for a in Alert.objects.all()],
[("VM fault: vm1", "vm1 on h1: Paused by a disk error")])
self.watch(PAUSED_IOERROR)
self.watch(None) # a host that does not answer changes nothing
self.assertEqual(Alert.objects.count(), 1)
self.watch(RUNNING)
self.assertEqual(self.vm.fault, "")
self.watch(PAUSED_IOERROR)
self.assertEqual(Alert.objects.count(), 2)
def test_no_alert_for_an_ordinary_state_nor_without_a_channel(self):
self.watch(PAUSED_BY_USER)
self.assertFalse(Alert.objects.exists())
AppSettings.objects.filter(key="ALERT_WEBHOOK").update(value="")
with mock.patch.object(jobs.utils, "host_domain_states") as read:
jobs.watch_faults()
read.assert_not_called() # no host is read for nobody
def test_a_fault_is_told_again_after_the_channels_were_off(self):
self.watch(PAUSED_IOERROR)
AppSettings.objects.filter(key="ALERT_WEBHOOK").update(value="")
self.watch(PAUSED_IOERROR)
self.assertEqual(self.vm.fault, "") # nobody heard of what happens meanwhile
AppSettings.objects.filter(key="ALERT_WEBHOOK").update(value="http://192.0.2.9/hook")
self.watch(PAUSED_IOERROR)
self.assertEqual(Alert.objects.count(), 2)

View file

@ -0,0 +1,105 @@
"""Free unused space: the guest agent trims each mounted file system (instance.fstrim); a disk passes it to its
image only with the discard mode unmap, which the Disks tab and the job say when no disk has it."""
import json
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from django.contrib.auth import get_user_model
from django.core.exceptions import PermissionDenied
from django.test import TransactionTestCase
from django.urls import reverse
from computes.models import Compute
from instances.jobs import TrimVM
from instances.models import Instance
from operations.jobs import Context
from operations.models import Operation, acquire
from operations.utils import words
from vrtManager import instance as vrt_instance
from vrtManager.util import OperationError
def disk(discard):
return {"dev": "vda", "discard": discard}
class FstrimTestCase(TransactionTestCase):
def setUp(self):
self.admin = get_user_model().objects.create_superuser("ft-admin", "ft@example.com", "pw")
self.client.force_login(self.admin)
compute = Compute.objects.create(name="ft-host", hostname="192.0.2.81", login="", password="", type=4)
self.vm = Instance.objects.create(compute=compute, name="ft-vm", uuid="81818181-0000-4000-8000-000000000001")
self.proxy = MagicMock(**{"get_status.return_value": 1, "is_agent_ready.return_value": True,
"get_disk_devices.return_value": [disk("unmap")],
"fstrim.return_value": [{"path": "/", "trimmed": 1 << 30, "error": None}]})
patch.object(Instance, "proxy", property(lambda vm: self.proxy)).start()
self.addCleanup(patch.stopall)
def queue_and_run(self):
response = self.client.post(reverse("instances:fstrim", args=[self.vm.pk]), {"submission_key": "key-fstrim01"})
self.assertRedirects(response, reverse("instances:instance", args=[self.vm.pk]) + "#disks",
fetch_redirect_response=False)
op = Operation.objects.get(kind="instance.fstrim")
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"))
TrimVM().precheck(op, ctx)
return TrimVM().run(op, ctx)
def test_the_job_returns_what_each_file_system_trimmed(self):
self.assertEqual(self.queue_and_run(), {"trimmed": [{"path": "/", "trimmed": 1 << 30, "error": None}]})
def test_without_discard_unmap_the_job_warns_that_the_images_keep_their_size(self):
self.proxy.get_disk_devices.return_value = [disk("default")]
result = self.queue_and_run()
self.assertIn("image files keep their size", words(result["warning"]))
def test_the_job_fails_when_the_guest_trims_no_file_system(self):
self.proxy.fstrim.return_value = [{"path": "/", "trimmed": None, "error": "not supported"}]
with self.assertRaisesMessage(OperationError, "No file system was trimmed: /: not supported"):
self.queue_and_run()
self.assertTrue(Operation.objects.get().effects_started) # recovery knows the guest was asked
def test_only_a_superuser_still_active_trims(self):
owner = get_user_model().objects.create_user("ft-owner", "o@example.com", "pw")
self.client.force_login(owner)
self.assertEqual(self.client.post(reverse("instances:fstrim", args=[self.vm.pk]),
{"submission_key": "key-fstrim02"}).status_code, 403)
self.client.force_login(self.admin)
self.client.post(reverse("instances:fstrim", args=[self.vm.pk]), {"submission_key": "key-fstrim03"})
op = Operation.objects.get()
self.admin.is_superuser = False
self.admin.save()
op.refresh_from_db()
with self.assertRaises(PermissionDenied):
TrimVM().precheck(op, None)
def test_a_vm_not_running_or_without_an_agent_is_refused(self):
self.proxy.get_status.return_value = 5
with self.assertRaisesMessage(OperationError, "not running"):
self.queue_and_run()
self.proxy.fstrim.assert_not_called()
def test_the_job_page_lists_each_file_system(self):
op = Operation.objects.create(kind="instance.fstrim", user=self.admin, username="ft-admin", resource="r",
resource_label="ft-host/ft-vm", state=Operation.SUCCEEDED, result={"trimmed": [
{"path": "/", "trimmed": 1 << 30, "error": None},
{"path": "/boot", "trimmed": None, "error": "not supported"}]})
page = self.client.get(reverse("operations:job", args=[op.pk])).content.decode()
self.assertInHTML("<li class=\"text-break\"><code>/</code> 1\xa0GiB</li>", page)
self.assertInHTML("<li class=\"text-break\"><code>/boot</code> not supported</li>", page)
class AgentFstrimTestCase(TransactionTestCase):
def test_the_agent_answer_is_read_per_path(self):
answer = {"paths": [{"path": "/", "trimmed": 4096, "minimum": 0}, {"path": "/boot", "error": "not supported"},
{"path": "C:\\"}, "garbage", {"trimmed": 1}]}
dom = MagicMock()
proxy = SimpleNamespace(instance=dom, ping_agent=lambda: None)
with patch.object(vrt_instance, "qemuAgentCommand", return_value=json.dumps({"return": answer})) as command:
paths = vrt_instance.wvmInstance.fstrim(proxy)
self.assertEqual(paths, [{"path": "/", "trimmed": 4096, "error": None},
{"path": "/boot", "trimmed": None, "error": "not supported"},
{"path": "C:\\", "trimmed": None, "error": None}])
self.assertEqual(command.call_args.args[2], vrt_instance.FSTRIM_TIMEOUT) # not the 10 s of other agent calls

View file

@ -178,6 +178,36 @@ class PendingEditsTestCase(TestCase):
doc = self.page(get_pcie_slots=(None, None))
self.assertFalse(doc.xpath("//form[@action=$a]", a=reverse("instances:add_pcie_slots", args=[self.instance.id])))
def test_the_disks_tab_frees_unused_space_of_a_running_vm_and_says_when_no_disk_passes_it_on(self):
url = reverse("instances:fstrim", args=[self.instance.id])
for discard, said in (("default", "trimming frees no space"), ("unmap", "Free space the guest no longer uses")):
with self.subTest(discard=discard):
doc = self.page(live=[{**disk("vda", "default", ""), "discard": discard}])
(form,) = doc.xpath("//form[@action=$a]", a=url)
self.assertIn(said, form.getparent().text_content())
self.assertTrue(form.xpath(".//input[@name='submission_key']/@value")) # the job needs it
self.assertFalse(self.page(status=5).xpath("//form[@action=$a]", a=url)) # the agent of a running VM trims
def test_the_summary_shows_the_screen_of_a_running_or_paused_vm_with_graphics(self):
screen = "//*[@id='vm-screen']"
url = reverse("instances:screen", args=[self.instance.id])
reachable = {"get_console_type": ("vnc", "vnc"), "get_console_socket": (None, None),
"get_console_listener_addr": ("0.0.0.0", "0.0.0.0")}
for status in (1, 3):
(element,) = self.page(status=status, **reachable).xpath(screen)
# shown once its script has read a frame; a button that opens the console
self.assertEqual((element.tag, element.get("hidden"), element.get("data-screen-url")), ("button", "", url))
caption = "normalize-space(//*[@id='vm-screen']/*[@class='vm-screen-caption'])"
self.assertEqual(self.page(status=1, **reachable).xpath(caption), "Live Open console")
self.assertEqual(self.page(status=3, **reachable).xpath(caption), "Suspended Open console") # its last picture
self.assertFalse(self.page(status=5, **reachable).xpath(screen))
# a console the panel cannot open (loopback VNC on a TCP host, SPICE): the screen alone, not a button
for console in ({**reachable, "get_console_listener_addr": ("127.0.0.1", "127.0.0.1")},
{**reachable, "get_console_type": ("spice", "spice")}):
(element,) = self.page(**console).xpath(screen)
self.assertEqual((element.tag, element.get("data-window")), ("div", None))
self.assertNotIn("Open console", element.text_content())
def test_the_clone_form_lists_the_persistent_devices(self):
nic = {"type": "network", "mac": "52:54:10:00:00:01", "nic": "default", "state": "up", "model": "virtio",
"ipv4": None, "ipv6": None, "filterref": "", "target": "", "inbound": [], "outbound": []}

View file

@ -0,0 +1,66 @@
"""The VM's screen on its page: a PNG from libvirt (virDomainScreenshot), for those who may open its console."""
from unittest.mock import MagicMock, PropertyMock, patch
import libvirt
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import TestCase
from django.urls import reverse
from accounts.models import UserInstance
from computes.models import Compute
from instances.models import Instance
from vrtManager.instance import wvmInstance
PNG = b"\x89PNG\r\n\x1a\nimage"
class ScreenTestCase(TestCase):
def setUp(self):
self.admin = get_user_model().objects.create_superuser("sc-admin", "sc@example.com", "pw")
compute = Compute.objects.create(name="sc-host", hostname="192.0.2.91", login="", password="", type=4)
self.vm = Instance.objects.create(compute=compute, name="sc-vm", uuid="91919191-0000-4000-8000-000000000001")
self.proxy = MagicMock(**{"screenshot.return_value": ("image/png", PNG)})
patch.object(Instance, "proxy", property(lambda vm: self.proxy)).start()
self.status = patch.object(Instance, "status", new_callable=PropertyMock, return_value=1).start()
self.console = patch.object(Instance, "console_type", new_callable=PropertyMock, return_value="vnc").start()
self.addCleanup(patch.stopall)
def get(self, user):
self.client.force_login(user)
return self.client.get(reverse("instances:screen", args=[self.vm.pk]))
def test_a_running_vm_s_screen_is_a_png_not_kept_by_the_browser(self):
response = self.get(self.admin)
self.assertEqual((response.status_code, response["Content-Type"], response.content), (200, "image/png", PNG))
self.assertEqual(response["Cache-Control"], "no-store")
def test_only_those_who_may_open_the_console_see_it(self):
viewer = get_user_model().objects.create_user("sc-viewer", "v@example.com", "pw")
viewer.user_permissions.add(Permission.objects.get(codename="view_instances"))
self.assertEqual(self.get(viewer).status_code, 403) # reads every VM, opens no console
owner = get_user_model().objects.create_user("sc-owner", "o@example.com", "pw")
UserInstance.objects.create(user=owner, instance=self.vm)
self.assertEqual(self.get(owner).status_code, 200)
def test_no_screen_is_a_404(self):
for status, console, answer in ((5, "vnc", None), (1, "", None), (1, "vnc", ("image/x-portable-pixmap", b"P6")),
(1, "vnc", libvirt.libvirtError("no screen"))):
with self.subTest(status=status, console=console, answer=answer):
self.status.return_value, self.console.return_value = status, console
self.proxy.screenshot.side_effect = [answer] if answer else None
self.assertEqual(self.get(self.admin).status_code, 404)
class ScreenshotCallTestCase(TestCase):
def test_the_stream_is_read_whole_and_aborted_on_failure(self):
proxy = MagicMock()
stream = proxy.wvm.newStream.return_value
proxy.instance.screenshot.return_value = "image/png"
stream.recvAll.side_effect = lambda handler, buffer: [handler(stream, part, buffer) for part in (b"ab", b"cd")]
self.assertEqual(wvmInstance.screenshot(proxy), ("image/png", b"abcd"))
stream.finish.assert_called_once_with()
proxy.instance.screenshot.side_effect = libvirt.libvirtError("gone")
with self.assertRaises(libvirt.libvirtError):
wvmInstance.screenshot(proxy)
stream.abort.assert_called_once_with()

View file

@ -24,6 +24,7 @@ urlpatterns = [
path("<int:pk>/destroy/", views.destroy, name="destroy"),
path("<int:pk>/migrate/", views.migrate, name="migrate"),
path("<int:pk>/status/", views.status, name="status"),
path("<int:pk>/screen/", views.screen, name="screen"),
path("<int:pk>/addresses/", views.nic_addresses, name="nic_addresses"),
path("<int:pk>/stats/", views.stats, name="stats"),
path("<int:pk>/osinfo/", views.osinfo, name="osinfo"),
@ -40,6 +41,7 @@ urlpatterns = [
path("<int:pk>/detach_vol/", views.detach_vol, name="detach_vol"),
path("<int:pk>/add_cdrom/", views.add_cdrom, name="add_cdrom"),
path("<int:pk>/add_pcie_slots/", views.add_pcie_slots, name="add_pcie_slots"),
path("<int:pk>/fstrim/", views.fstrim, name="fstrim"),
path("<int:pk>/detach_cdrom/<str:dev>/", views.detach_cdrom, name="detach_cdrom"),
path("<int:pk>/unmount_iso/", views.unmount_iso, name="unmount_iso"),
path("<int:pk>/mount_iso/", views.mount_iso, name="mount_iso"),

View file

@ -20,9 +20,9 @@ from libvirt import libvirtError
from logs.audit import reason, write
from operations.models import Operation
from operations.utils import migration_bandwidth
from vrtManager.connection import counted_thread, other_hosts, wvmConnect
from vrtManager.connection import CONN_TCP, CONN_TLS, counted_thread, other_hosts, wvmConnect
from vrtManager.instance import wvmInstance, wvmInstances
from vrtManager.util import ConnectionFailed, HostBusy, message, vol_dev_type
from vrtManager.util import ConnectionFailed, HostBusy, is_loopback, message, vol_dev_type
from .models import Instance
from .states import state_reason
@ -42,6 +42,13 @@ def can_open_console(user, instance):
return UserInstance.objects.filter(instance=instance, user=user).exists()
def novnc_unreachable(compute_type, socket, listener):
"""Whether novncd cannot reach a VNC console: one that listens on its host's loopback or on a
socket only, on a host the panel reaches over TCP or TLS (SSH tunnels to it, the socket type is
on this host)."""
return compute_type in (CONN_TCP, CONN_TLS) and bool(socket or is_loopback(listener))
def get_clone_free_names(size=10):
prefix = app_settings.CLONE_INSTANCE_DEFAULT_PREFIX
free_names = []

View file

@ -352,6 +352,12 @@ def _instance_page(request, pk, instance, compute):
vdi_reachable = instance.console_type in ("vnc", "spice") and not util.is_loopback(instance.console_listener_address)
# root's password and keys change in a shut-off VM's disk (gstfsd on the host), or through a running VM's agent
guest_access_ready = instance.status == 5 or (instance.status == 1 and instance.guest_agent_ready)
# its screen beside the summary: what the console shows, so for those who may open it
show_screen = can_open_console and not instance.is_template and instance.status in (1, 3) \
and instance.console_type in ("vnc", "spice")
# clicked, it opens the console where the console page can: a VNC one novncd reaches
screen_opens_console = show_screen and instance.console_type == "vnc" and not utils.novnc_unreachable(
instance.compute.type, instance.proxy.get_console_socket(), instance.console_listener_address)
# get_instance(perm_type="delete"): a template only for superusers and staff owners
can_delete = request.user.is_superuser or bool(
userinstance and userinstance.is_delete and (request.user.is_staff or not instance.is_template)
@ -432,6 +438,8 @@ def _instance_page(request, pk, instance, compute):
"can_manage_console": can_manage_console,
"console_form": console_form,
"can_open_console": can_open_console,
"show_screen": show_screen,
"screen_opens_console": screen_opens_console,
"can_power": can_power,
"can_delete": can_delete,
"can_change": can_change,
@ -471,6 +479,26 @@ def status(request, pk):
return JsonResponse({"status": state, "reason": reason})
def screen(request, pk):
"""The VM's screen as a PNG, for the users who may open its console (utils.can_open_console):
404 while it has none to show (not running or paused, no graphics, or a host whose libvirt
gives no PNG)."""
instance = get_instance(request.user, pk)
if not utils.can_open_console(request.user, instance):
raise PermissionDenied
if instance.status not in (1, 3) or instance.console_type not in ("vnc", "spice"):
raise Http404
try:
mime, data = instance.proxy.screenshot()
except libvirtError:
raise Http404 from None
if mime != "image/png":
raise Http404
response = HttpResponse(data, content_type="image/png")
response["Cache-Control"] = "no-store"
return response
def nic_addresses(request, pk):
"""The VM's addresses by MAC, which its page shows once it has loaded
(vm_addresses.js): the guest agent may take its whole timeout. A host
@ -1616,6 +1644,24 @@ def add_pcie_slots(request, pk):
return _back(request, pk, "disks")
@require_POST
@superuser_only
def fstrim(request, pk):
"""Queue a trim of the running VM's file systems (instance.fstrim): the job panel shows it."""
get_instance(request.user, pk)
try:
op = jobs.submit("instance.fstrim", request.user, {"instance": pk}, request.POST.get("submission_key", ""))
except claims.Busy as busy:
messages.error(request, busy_message(busy, request.user))
except jobs.SubmissionConflict as err:
messages.error(request, str(err))
except libvirtError as err:
messages.error(request, error_text(request, err))
else:
jobs.remember_job(request, op)
return _back(request, pk, "disks")
@require_POST
@superuser_only
@serialize_instance_mutation

Binary file not shown.

View file

@ -279,14 +279,6 @@ msgstr "Kullanıcıdan kaldır"
msgid "No VMs."
msgstr "Sanal makine yok."
#: accounts/templates/accounts/change_password_form.html:20
msgid "Choose a new password before you go on."
msgstr "Devam etmeden önce yeni bir parola seçin."
#: accounts/templates/accounts/change_password_form.html:20
msgid "You stay signed in here; your other sessions end."
msgstr "Burada oturumunuz açık kalır; diğer oturumlarınız kapanır."
#: accounts/templates/accounts/change_password_form.html:35
#: accounts/templates/accounts/email_otp_form.html:25
#: admin/templates/admin/group_form.html:73
@ -693,8 +685,14 @@ msgid "Can view instances"
msgstr "Sanal makineleri görebilir"
#: admin/forms.py:33
msgid "Back up the VMs they may change into targets open to VM owners, restore those backups over the VM or as a new VM, and delete the backups they took, within their quotas"
msgstr "Değiştirebildiği sanal makineleri sanal makine sahiplerine açık hedeflere yedekleme, bu yedekleri sanal makinenin üzerine ya da yeni bir sanal makine olarak geri yükleme ve kendi aldığı yedekleri silme; kotaları içinde"
msgid ""
"Back up the VMs they may change into targets open to VM owners, restore those"
" backups over the VM or as a new VM, and delete the backups they took, within"
" their quotas"
msgstr ""
"Değiştirebildiği sanal makineleri sanal makine sahiplerine açık hedeflere "
"yedekleme, bu yedekleri sanal makinenin üzerine ya da yeni bir sanal makine "
"olarak geri yükleme ve kendi aldığı yedekleri silme; kotaları içinde"
#: admin/forms.py:35
msgid "Change their own password on their profile page"
@ -2269,8 +2267,13 @@ msgid "encrypt migrations (TLS)"
msgstr "taşımaları şifrele (TLS)"
#: computes/models.py:76
msgid "A VM migrating between two hosts that both have this sends its memory and disks over TLS; each host needs QEMU's certificates in /etc/pki/qemu"
msgstr "İki sunucuda da bu seçiliyse aralarında taşınan sanal makine, belleğini ve disklerini TLS ile gönderir; her sunucuda /etc/pki/qemu içinde QEMU sertifikaları gerekir"
msgid ""
"A VM migrating between two hosts that both have this sends its memory and "
"disks over TLS; each host needs QEMU's certificates in /etc/pki/qemu"
msgstr ""
"İki sunucuda da bu seçiliyse aralarında taşınan sanal makine, belleğini ve "
"disklerini TLS ile gönderir; her sunucuda /etc/pki/qemu içinde QEMU "
"sertifikaları gerekir"
#: computes/models.py:81 computes/templates/computes/form.html:42
msgid "gstfsd key"
@ -2311,16 +2314,25 @@ msgstr "Bu sunucu zaten %(name)s olarak ekli"
#: computes/models.py:253
#, python-format
msgid "The panel cannot reach the host to tell that its VMs are there: %(error)s"
msgstr "Panel sunucuya ulaşamadığı için sanal makinelerinin orada olduğunu doğrulayamıyor: %(error)s"
msgid ""
"The panel cannot reach the host to tell that its VMs are there: %(error)s"
msgstr ""
"Panel sunucuya ulaşamadığı için sanal makinelerinin orada olduğunu "
"doğrulayamıyor: %(error)s"
#: computes/models.py:260
msgid "The host its VMs are on is not known yet: change the connection when the panel has reached the host at its current one"
msgstr "Sanal makinelerinin bulunduğu sunucu henüz bilinmiyor: bağlantıyı, panel sunucuya mevcut bağlantısından ulaştıktan sonra değiştirin"
msgid ""
"The host its VMs are on is not known yet: change the connection when the "
"panel has reached the host at its current one"
msgstr ""
"Sanal makinelerinin bulunduğu sunucu henüz bilinmiyor: bağlantıyı, panel "
"sunucuya mevcut bağlantısından ulaştıktan sonra değiştirin"
#: computes/models.py:263
msgid "This is another host than the one its VMs are on: add it as a new host"
msgstr "Bu, sanal makinelerinin bulunduğu sunucudan başka bir sunucu: yeni bir sunucu olarak ekleyin"
msgstr ""
"Bu, sanal makinelerinin bulunduğu sunucudan başka bir sunucu: yeni bir sunucu"
" olarak ekleyin"
#: computes/reach.py:60
msgid ""
@ -4871,7 +4883,9 @@ msgstr "%(label)s: %(vcpu)s vCPU, %(memory)s MiB, yeni %(disk)s GiB disk"
#: instances/templates/create_presets.html:13
msgid "A preset fills vCPUs, memory and a new disk of its size."
msgstr "Hazır boyut; vCPU, bellek ve kendi boyutunda yeni bir disk alanlarını doldurur."
msgstr ""
"Hazır boyut; vCPU, bellek ve kendi boyutunda yeni bir disk alanlarını "
"doldurur."
#: instances/templates/create_presets.html:15
msgid "No flavors yet."
@ -5159,8 +5173,12 @@ msgstr ""
#: instances/templates/instances/destroy_instance_form.html:13
#: instances/templates/instances/destroy_tab.html:9
msgid "This VM is protected: an administrator turns its protection off on the Settings tab first."
msgstr "Bu sanal makine korumalı: önce bir yönetici Ayarlar sekmesinde korumasını kapatmalı."
msgid ""
"This VM is protected: an administrator turns its protection off on the "
"Settings tab first."
msgstr ""
"Bu sanal makine korumalı: önce bir yönetici Ayarlar sekmesinde korumasını "
"kapatmalı."
#: instances/templates/instances/destroy_instance_form.html:18
msgid "What should happen to the files?"
@ -6728,8 +6746,14 @@ msgid "Stop"
msgstr "Durdur"
#: instances/templates/instances/settings_tab.html:1028
msgid "A hang is noticed once the guest arms its watchdog (Linux: RuntimeWatchdogSec in systemd's system.conf). Stop keeps a VM that crashes again and again down for a look. From the next start."
msgstr "Donma, konuk sistem watchdog'unu kurduğunda fark edilir (Linux: systemd'nin system.conf dosyasında RuntimeWatchdogSec). Durdur, tekrar tekrar çöken bir sanal makineyi incelemek için kapalı tutar. Sonraki başlatmadan itibaren."
msgid ""
"A hang is noticed once the guest arms its watchdog (Linux: RuntimeWatchdogSec"
" in systemd's system.conf). Stop keeps a VM that crashes again and again down"
" for a look. From the next start."
msgstr ""
"Donma, konuk sistem watchdog'unu kurduğunda fark edilir (Linux: systemd'nin "
"system.conf dosyasında RuntimeWatchdogSec). Durdur, tekrar tekrar çöken bir "
"sanal makineyi incelemek için kapalı tutar. Sonraki başlatmadan itibaren."
#: instances/templates/instances/settings_tab.html:1030
#, python-format
@ -7147,8 +7171,11 @@ msgstr ""
#: instances/views.py:274
#, python-format
msgid "Guest agents not read (a paused VM, no answer in time, or an error): %(n)s"
msgstr "Okunamayan konuk ajanları (duraklatılmış sanal makine, zamanında yanıt yok ya da hata): %(n)s"
msgid ""
"Guest agents not read (a paused VM, no answer in time, or an error): %(n)s"
msgstr ""
"Okunamayan konuk ajanları (duraklatılmış sanal makine, zamanında yanıt yok ya"
" da hata): %(n)s"
#: instances/views.py:276
#, python-format
@ -9772,8 +9799,12 @@ msgid "Volume name"
msgstr "Birim adı"
#: storages/templates/create_stg_vol_block.html:98
msgid "Empty: the file's name in the address. An ISO keeps its .iso ending, or VMs do not list it as media."
msgstr "Boş bırakılırsa: adresteki dosyanın adı. ISO dosyasının adı .iso ile bitmeli; yoksa sanal makineler onu ortam olarak listelemez."
msgid ""
"Empty: the file's name in the address. An ISO keeps its .iso ending, or VMs "
"do not list it as media."
msgstr ""
"Boş bırakılırsa: adresteki dosyanın adı. ISO dosyasının adı .iso ile bitmeli;"
" yoksa sanal makineler onu ortam olarak listelemez."
#: storages/templates/create_stg_vol_block.html:103
#: storages/templates/storage.html:176
@ -10486,8 +10517,12 @@ msgid ""
msgstr "Ayrıca yedeği olan en yeni N ayın her birinin en yeni yedeği; 0: yok"
#: vmbackups/forms.py:102
msgid "1: every backup is full. Above 1, the backups between copy only what changed (running VMs with qcow2 disks)."
msgstr "1: her yedek tamdır. 1'den büyükse aradaki yedekler yalnızca değişenleri kopyalar (qcow2 diskli, çalışan sanal makineler)."
msgid ""
"1: every backup is full. Above 1, the backups between copy only what changed "
"(running VMs with qcow2 disks)."
msgstr ""
"1: her yedek tamdır. 1'den büyükse aradaki yedekler yalnızca değişenleri "
"kopyalar (qcow2 diskli, çalışan sanal makineler)."
#: vmbackups/forms.py:119 vmbackups/jobs.py:115
#, python-format
@ -10767,25 +10802,38 @@ msgstr "Üzerine yedek geri yüklemek için sanal makineyi kapatın"
#: vmbackups/jobs.py:1177
msgid "The VM has snapshots; delete them to restore a backup over it"
msgstr "Sanal makinenin anlık görüntüleri var; üzerine yedek geri yüklemek için onları silin"
msgstr ""
"Sanal makinenin anlık görüntüleri var; üzerine yedek geri yüklemek için "
"onları silin"
#: vmbackups/jobs.py:1182
#, python-format
msgid "The VM's disks (%(now)s) are not the backup's (%(then)s); restore it as a new VM or one disk"
msgstr "Sanal makinenin diskleri (%(now)s) yedeğinkiler (%(then)s) değil; yeni bir sanal makine olarak ya da tek disk olarak geri yükleyin"
msgid ""
"The VM's disks (%(now)s) are not the backup's (%(then)s); restore it as a new"
" VM or one disk"
msgstr ""
"Sanal makinenin diskleri (%(now)s) yedeğinkiler (%(then)s) değil; yeni bir "
"sanal makine olarak ya da tek disk olarak geri yükleyin"
#: vmbackups/jobs.py:1186
#, python-format
msgid "The backup's disk %(dev)s is larger than the VM's now; restore it as a new VM"
msgstr "Yedeğin %(dev)s diski sanal makinenin şimdiki diskinden büyük; yeni bir sanal makine olarak geri yükleyin"
msgid ""
"The backup's disk %(dev)s is larger than the VM's now; restore it as a new VM"
msgstr ""
"Yedeğin %(dev)s diski sanal makinenin şimdiki diskinden büyük; yeni bir sanal"
" makine olarak geri yükleyin"
#: vmbackups/jobs.py:1189
msgid "The VM's UEFI firmware changed since the backup; restore it as a new VM"
msgstr "Sanal makinenin UEFI donanım yazılımı yedekten sonra değişti; yeni bir sanal makine olarak geri yükleyin"
msgstr ""
"Sanal makinenin UEFI donanım yazılımı yedekten sonra değişti; yeni bir sanal "
"makine olarak geri yükleyin"
#: vmbackups/jobs.py:1191
msgid "The VM's TPM changed since the backup; restore it as a new VM"
msgstr "Sanal makinenin TPM'i yedekten sonra değişti; yeni bir sanal makine olarak geri yükleyin"
msgstr ""
"Sanal makinenin TPM'i yedekten sonra değişti; yeni bir sanal makine olarak "
"geri yükleyin"
#: vmbackups/jobs.py:1222
msgid "Restore backup over the VM"
@ -10793,7 +10841,9 @@ msgstr "Yedeği sanal makinenin üzerine geri yükle"
#: vmbackups/jobs.py:1235
msgid "The backup's VM is no longer in the panel; restore it as a new VM"
msgstr "Yedeğin sanal makinesi artık panelde yok; yeni bir sanal makine olarak geri yükleyin"
msgstr ""
"Yedeğin sanal makinesi artık panelde yok; yeni bir sanal makine olarak geri "
"yükleyin"
#: vmbackups/jobs.py:1266
msgid "The VM's disks changed after the job was queued"
@ -10801,19 +10851,28 @@ msgstr "İş kuyruğa alındıktan sonra sanal makinenin diskleri değişti"
#: vmbackups/jobs.py:1300
msgid "The VM changed while its backup was copied; it keeps its disks"
msgstr "Yedeği kopyalanırken sanal makine değişti; sanal makine disklerini koruyor"
msgstr ""
"Yedeği kopyalanırken sanal makine değişti; sanal makine disklerini koruyor"
#: vmbackups/jobs.py:1303
msgid "Replacing the VM's disks"
msgstr "Sanal makinenin diskleri değiştiriliyor"
#: vmbackups/jobs.py:1363
msgid "The VM moved to another compute; check its disks and the restore's copies, then resolve this job"
msgstr "Sanal makine başka bir sunucuya taşındı; disklerini ve geri yüklemenin kopyalarını denetleyin, sonra bu işi çözümleyin"
msgid ""
"The VM moved to another compute; check its disks and the restore's copies, "
"then resolve this job"
msgstr ""
"Sanal makine başka bir sunucuya taşındı; disklerini ve geri yüklemenin "
"kopyalarını denetleyin, sonra bu işi çözümleyin"
#: vmbackups/jobs.py:1376
msgid "The VM was started while its disks were being replaced; check its disks, then resolve this job"
msgstr "Sanal makinenin diskleri değiştirilirken sanal makine başlatıldı; disklerini denetleyin, sonra bu işi çözümleyin"
msgid ""
"The VM was started while its disks were being replaced; check its disks, then"
" resolve this job"
msgstr ""
"Sanal makinenin diskleri değiştirilirken sanal makine başlatıldı; disklerini "
"denetleyin, sonra bu işi çözümleyin"
#: vmbackups/jobs.py:1394
msgid "The VM keeps its disks; the restore's copies were removed"
@ -10955,8 +11014,12 @@ msgstr "Doğrula"
#: vmbackups/templates/vmbackups/delete_form.html:16
#, python-format
msgid "Delete the backup of %(vm)s taken %(time)s? Its files are removed from %(target)s; this cannot be undone."
msgstr "%(vm)s sanal makinesinin %(time)s tarihli yedeği silinsin mi? Dosyaları %(target)s hedefinden kaldırılır; bu geri alınamaz."
msgid ""
"Delete the backup of %(vm)s taken %(time)s? Its files are removed from "
"%(target)s; this cannot be undone."
msgstr ""
"%(vm)s sanal makinesinin %(time)s tarihli yedeği silinsin mi? Dosyaları "
"%(target)s hedefinden kaldırılır; bu geri alınamaz."
#: vmbackups/templates/vmbackups/index.html:13
#: vmbackups/templates/vmbackups/target.html:7
@ -11088,8 +11151,12 @@ msgid "No backup schedule yet."
msgstr "Henüz yedekleme zamanlaması yok."
#: vmbackups/templates/vmbackups/policies.html:36
msgid "A schedule backs chosen VMs, or every VM of a compute, up every day and keeps the newest."
msgstr "Bir zamanlama, seçilen sanal makineleri ya da bir sunucunun bütün sanal makinelerini her gün yedekler ve en yenilerini tutar."
msgid ""
"A schedule backs chosen VMs, or every VM of a compute, up every day and keeps"
" the newest."
msgstr ""
"Bir zamanlama, seçilen sanal makineleri ya da bir sunucunun bütün sanal "
"makinelerini her gün yedekler ve en yenilerini tutar."
#: vmbackups/templates/vmbackups/policy.html:13
#, python-format
@ -11104,34 +11171,26 @@ msgstr "Bu zamanlama silinsin mi? Yedekleri tutulur."
msgid "Delete schedule"
msgstr "Zamanlamayı sil"
#: vmbackups/templates/vmbackups/policy.html:26
msgid "Runs"
msgstr "Çalışmalar"
#: vmbackups/templates/vmbackups/policy.html:30
msgid "Day"
msgstr "Gün"
#: vmbackups/templates/vmbackups/policy.html:37
msgid "Backup job"
msgstr "Yedekleme işi"
#: vmbackups/templates/vmbackups/policy.html:38
msgid "Skipped"
msgstr "Atlandı"
#: vmbackups/templates/vmbackups/policy.html:48
msgid "No run yet."
msgstr "Henüz çalışma yok."
#: vmbackups/templates/vmbackups/policy_form.html:13
#, python-format
msgid "Time zone: %(time_zone)s"
msgstr "Saat dilimi: %(time_zone)s"
#: vmbackups/templates/vmbackups/policy_form.html:23
msgid "Each VM is backed up once a day, starting at the time; a VM that has not started within 6 hours waits for the next day. Older backups of each VM beyond those kept are deleted, a chain of incremental backups once all of it is beyond; backups taken by hand are not."
msgstr "Her sanal makine günde bir kez, belirtilen saatte başlayarak yedeklenir; 6 saat içinde başlamayan sanal makine ertesi günü bekler. Her sanal makinenin tutulanların dışında kalan eski yedekleri silinir; artımlı yedek zinciri ise tamamı bunların dışına çıkınca silinir. Elle alınan yedekler silinmez."
msgid ""
"Each VM is backed up once a day, starting at the time; a VM that has not "
"started within 6 hours waits for the next day. Older backups of each VM "
"beyond those kept are deleted, a chain of incremental backups once all of it "
"is beyond; backups taken by hand are not."
msgstr ""
"Her sanal makine günde bir kez, belirtilen saatte başlayarak yedeklenir; 6 "
"saat içinde başlamayan sanal makine ertesi günü bekler. Her sanal makinenin "
"tutulanların dışında kalan eski yedekleri silinir; artımlı yedek zinciri ise "
"tamamı bunların dışına çıkınca silinir. Elle alınan yedekler silinmez."
#: vmbackups/templates/vmbackups/restore.html:12
#, python-format
@ -11144,8 +11203,12 @@ msgstr ""
#: vmbackups/templates/vmbackups/restore.html:18
#, python-format
msgid "On %(compute)s, in storage pool %(pool)s: the VM's host and the pool of its first disk."
msgstr "%(compute)s üzerinde, %(pool)s depolama havuzunda: sanal makinenin sunucusu ve ilk diskinin havuzu."
msgid ""
"On %(compute)s, in storage pool %(pool)s: the VM's host and the pool of its "
"first disk."
msgstr ""
"%(compute)s üzerinde, %(pool)s depolama havuzunda: sanal makinenin sunucusu "
"ve ilk diskinin havuzu."
#: vmbackups/templates/vmbackups/restore_disk.html:7
#: vmbackups/templates/vmbackups/restore_disk.html:9
@ -11154,8 +11217,12 @@ msgstr "Tek disk geri yükle"
#: vmbackups/templates/vmbackups/restore_disk.html:12
#, python-format
msgid "A disk of the backup of %(vm)s taken %(time)s, in %(target)s, is copied as a new volume, attached to no VM."
msgstr "%(vm)s sanal makinesinin %(time)s tarihli, %(target)s içindeki yedeğinden bir disk, hiçbir sanal makineye bağlanmadan yeni bir birim olarak kopyalanır."
msgid ""
"A disk of the backup of %(vm)s taken %(time)s, in %(target)s, is copied as a "
"new volume, attached to no VM."
msgstr ""
"%(vm)s sanal makinesinin %(time)s tarihli, %(target)s içindeki yedeğinden bir"
" disk, hiçbir sanal makineye bağlanmadan yeni bir birim olarak kopyalanır."
#: vmbackups/templates/vmbackups/restore_over.html:6
#: vmbackups/templates/vmbackups/restore_over.html:8
@ -11165,8 +11232,15 @@ msgstr "Sanal makinenin üzerine geri yükle"
#: vmbackups/templates/vmbackups/restore_over.html:11
#, python-format
msgid "The backup of %(vm)s taken %(time)s, in %(target)s, is restored over the VM: its disks are copied as new volumes and the VM is switched to them. Its settings, MAC addresses and UUID stay."
msgstr "%(vm)s sanal makinesinin %(time)s tarihli, %(target)s içindeki yedeği sanal makinenin üzerine geri yüklenir: diskleri yeni birimler olarak kopyalanır ve sanal makine bunlara geçirilir. Ayarları, MAC adresleri ve UUID'si aynı kalır."
msgid ""
"The backup of %(vm)s taken %(time)s, in %(target)s, is restored over the VM: "
"its disks are copied as new volumes and the VM is switched to them. Its "
"settings, MAC addresses and UUID stay."
msgstr ""
"%(vm)s sanal makinesinin %(time)s tarihli, %(target)s içindeki yedeği sanal "
"makinenin üzerine geri yüklenir: diskleri yeni birimler olarak kopyalanır ve "
"sanal makine bunlara geçirilir. Ayarları, MAC adresleri ve UUID'si aynı "
"kalır."
#: vmbackups/templates/vmbackups/restore_over.html:19
msgid "After the restore"
@ -11177,8 +11251,11 @@ msgid "The old volumes stay in their pools until you delete them."
msgstr "Eski birimler siz silene kadar havuzlarında kalır."
#: vmbackups/templates/vmbackups/restore_over.html:28
msgid "The disks the VM runs from now are deleted once it is switched to the new ones."
msgstr "Sanal makine yeni disklere geçirilince şu an çalıştığı diskler silinir."
msgid ""
"The disks the VM runs from now are deleted once it is switched to the new "
"ones."
msgstr ""
"Sanal makine yeni disklere geçirilince şu an çalıştığı diskler silinir."
#: vmbackups/templates/vmbackups/restore_over.html:29
msgid "The UEFI variables return to the backup's."
@ -11190,8 +11267,12 @@ msgstr "TPM durumu yedekteki haline döner."
#: vmbackups/templates/vmbackups/restore_over.html:35
#, python-format
msgid "Restore the backup over %(vm)s? What the VM wrote since the backup is no longer on the disks it runs from."
msgstr "Yedek %(vm)s üzerine geri yüklensin mi? Sanal makinenin yedekten sonra yazdıkları, çalışacağı disklerde artık olmaz."
msgid ""
"Restore the backup over %(vm)s? What the VM wrote since the backup is no "
"longer on the disks it runs from."
msgstr ""
"Yedek %(vm)s üzerine geri yüklensin mi? Sanal makinenin yedekten sonra "
"yazdıkları, çalışacağı disklerde artık olmaz."
#: vmbackups/templates/vmbackups/state.html:1
msgid "Its deletion did not end; delete it again"
@ -11346,8 +11427,11 @@ msgstr ""
"%(pool)s depolama havuzu %(target)s yedek hedefidir; önce hedeften çıkarın"
#: vmbackups/utils.py:84
msgid "No backup target open to VM owners has a storage pool on this VM's host."
msgstr "Sanal makine sahiplerine açık hiçbir yedek hedefinin bu sanal makinenin sunucusunda depolama havuzu yok."
msgid ""
"No backup target open to VM owners has a storage pool on this VM's host."
msgstr ""
"Sanal makine sahiplerine açık hiçbir yedek hedefinin bu sanal makinenin "
"sunucusunda depolama havuzu yok."
#: vmbackups/utils.py:85
msgid "No backup target has a storage pool on this VM's host."
@ -11381,7 +11465,9 @@ msgstr ""
#: vmbackups/views.py:155
#, python-format
msgid "VM owners with the backup permission may now use %(target)s."
msgstr "Yedekleme izni olan sanal makine sahipleri artık %(target)s hedefini kullanabilir."
msgstr ""
"Yedekleme izni olan sanal makine sahipleri artık %(target)s hedefini "
"kullanabilir."
#: vmbackups/views.py:156
#, python-format
@ -11643,13 +11729,18 @@ msgstr "Hedef sunucuda sanal makinenin şu ağları yok: %(names)s"
#: vrtManager/instance.py:231
#, python-format
msgid "The destination host does not have these network filters of the VM: %(names)s"
msgid ""
"The destination host does not have these network filters of the VM: %(names)s"
msgstr "Hedef sunucuda sanal makinenin şu ağ filtreleri yok: %(names)s"
#: vrtManager/instance.py:234
#, python-format
msgid "These network filters of the VM have other rules on the destination host: %(names)s"
msgstr "Sanal makinenin şu ağ filtrelerinin hedef sunucudaki kuralları farklı: %(names)s"
msgid ""
"These network filters of the VM have other rules on the destination host: "
"%(names)s"
msgstr ""
"Sanal makinenin şu ağ filtrelerinin hedef sunucudaki kuralları farklı: "
"%(names)s"
#: vrtManager/instance.py:237
#, python-format
@ -11901,8 +11992,12 @@ msgstr "Sanal makinede ekran kartı yok"
#: vrtManager/instance.py:1977
#, python-format
msgid "The VM's CPU topology has %(count)s vCPUs: change it in the XML editor to set another maximum"
msgstr "Sanal makinenin CPU topolojisi %(count)s vCPU içeriyor: başka bir en fazla değer için onu XML düzenleyicide değiştirin"
msgid ""
"The VM's CPU topology has %(count)s vCPUs: change it in the XML editor to set"
" another maximum"
msgstr ""
"Sanal makinenin CPU topolojisi %(count)s vCPU içeriyor: başka bir en fazla "
"değer için onu XML düzenleyicide değiştirin"
#: vrtManager/instance.py:2003
#, python-format
@ -12311,8 +12406,12 @@ msgstr ""
#: vrtManager/interface.py:314
#, python-format
msgid "Interface %(iface)s is in use by the running VMs %(vms)s; shut them down or move their network cards first"
msgstr "%(iface)s arabirimini çalışan %(vms)s sanal makineleri kullanıyor; önce onları kapatın ya da ağ kartlarını başka yere taşıyın"
msgid ""
"Interface %(iface)s is in use by the running VMs %(vms)s; shut them down or "
"move their network cards first"
msgstr ""
"%(iface)s arabirimini çalışan %(vms)s sanal makineleri kullanıyor; önce "
"onları kapatın ya da ağ kartlarını başka yere taşıyın"
#: vrtManager/interface.py:332 vrtManager/virtsecrets.py:118
#, python-format
@ -12831,15 +12930,21 @@ msgstr "Oturum açma kilitlendi"
#: accounts/templates/accounts/lockout.html:14
#, python-format
msgid "Too many failed sign-ins. The lock ends within %(minutes)s minute."
msgid_plural "Too many failed sign-ins. The lock ends within %(minutes)s minutes."
msgstr[0] "Çok fazla başarısız oturum açma denemesi. Kilit en geç %(minutes)s dakika içinde kalkar."
msgstr[1] "Çok fazla başarısız oturum açma denemesi. Kilit en geç %(minutes)s dakika içinde kalkar."
msgid_plural ""
"Too many failed sign-ins. The lock ends within %(minutes)s minutes."
msgstr[0] ""
"Çok fazla başarısız oturum açma denemesi. Kilit en geç %(minutes)s dakika "
"içinde kalkar."
msgstr[1] ""
"Çok fazla başarısız oturum açma denemesi. Kilit en geç %(minutes)s dakika "
"içinde kalkar."
#: accounts/templates/accounts/lockout.html:20
msgid "Back to sign in"
msgstr "Oturum açmaya dön"
#: accounts/templates/accounts/otp_login.html:52 accounts/templates/login.html:51
#: accounts/templates/accounts/otp_login.html:52
#: accounts/templates/login.html:51
msgid "Caps Lock is on"
msgstr "Caps Lock açık"
@ -12851,7 +12956,9 @@ msgstr "Oturum açma duyurusu"
msgid ""
"Shown above the sign-in form, e.g. planned maintenance or a terms-of-use "
"line; empty: none"
msgstr "Oturum açma formunun üstünde gösterilir; örneğin planlı bakım ya da kullanım koşulları satırı; boş: yok"
msgstr ""
"Oturum açma formunun üstünde gösterilir; örneğin planlı bakım ya da kullanım "
"koşulları satırı; boş: yok"
#: accounts/templates/account.html:38
msgid "Unlock sign-in"
@ -12868,7 +12975,9 @@ msgstr "Oturum süresi (saat)"
#: appsettings/migrations/0030_login_session_hours.py:6
msgid "How long a sign-in lasts; a change applies from the next sign-in"
msgstr "Bir oturum ne kadar açık kalır; değişiklik bir sonraki oturum açmadan itibaren geçerlidir"
msgstr ""
"Bir oturum ne kadar açık kalır; değişiklik bir sonraki oturum açmadan "
"itibaren geçerlidir"
#. django-otp's sign-in errors, shown on the OTP sign-in page
msgid "Please enter your OTP token."
@ -12878,10 +12987,18 @@ msgid "Invalid token. Please make sure you have entered it correctly."
msgstr "Geçersiz kod. Lütfen doğru girdiğinizden emin olun."
#, python-format
msgid "Verification temporarily disabled because of %(failure_count)d failed attempt, please try again soon."
msgid_plural "Verification temporarily disabled because of %(failure_count)d failed attempts, please try again soon."
msgstr[0] "%(failure_count)d başarısız deneme nedeniyle doğrulama geçici olarak kapatıldı; lütfen biraz sonra tekrar deneyin."
msgstr[1] "%(failure_count)d başarısız deneme nedeniyle doğrulama geçici olarak kapatıldı; lütfen biraz sonra tekrar deneyin."
msgid ""
"Verification temporarily disabled because of %(failure_count)d failed "
"attempt, please try again soon."
msgid_plural ""
"Verification temporarily disabled because of %(failure_count)d failed "
"attempts, please try again soon."
msgstr[0] ""
"%(failure_count)d başarısız deneme nedeniyle doğrulama geçici olarak "
"kapatıldı; lütfen biraz sonra tekrar deneyin."
msgstr[1] ""
"%(failure_count)d başarısız deneme nedeniyle doğrulama geçici olarak "
"kapatıldı; lütfen biraz sonra tekrar deneyin."
msgid "Verification of the token is currently disabled"
msgstr "Kod doğrulaması şu anda kapalı"
@ -12987,12 +13104,18 @@ msgstr "%(job)s iptal edilsin mi? Olduğu yerde durur."
#: admin/templates/admin/user_list.html
#, python-format
msgid "Block %(name)s? They are signed out and their API tokens are deleted; unblocking does not bring the tokens back."
msgstr "%(name)s engellensin mi? Oturumları kapatılır ve API anahtarları silinir; engeli kaldırmak anahtarları geri getirmez."
msgid ""
"Block %(name)s? They are signed out and their API tokens are deleted; "
"unblocking does not bring the tokens back."
msgstr ""
"%(name)s engellensin mi? Oturumları kapatılır ve API anahtarları silinir; "
"engeli kaldırmak anahtarları geri getirmez."
#: webvirtcloud/middleware.py
msgid "You were signed out, so it was not done: sign in and do it again."
msgstr "Oturumunuz kapanmıştı, bu yüzden işlem yapılmadı: giriş yapıp yeniden deneyin."
msgstr ""
"Oturumunuz kapanmıştı, bu yüzden işlem yapılmadı: giriş yapıp yeniden "
"deneyin."
#: templates/base.html
msgid "You were signed out: this page is no longer updated."
@ -13018,7 +13141,6 @@ msgstr "Hangi sanal makineler"
msgid "Choose the VMs to back up"
msgstr "Yedeklenecek sanal makineleri seçin"
#: webvirtcloud/common_tags.py:29
#, python-format
msgid "%(percent)s%%"
@ -13027,15 +13149,18 @@ msgstr "%%%(percent)s"
#: operations/templates/operations/jobs.html:16
#: operations/templatetags/operations.py:98
#, python-format
msgid "The job worker is not running; it was last seen %(when)s. Jobs wait until it runs again."
msgstr "İş işleyicisi çalışmıyor; en son %(when)s görüldü. İşler o yeniden çalışana kadar bekler."
msgid ""
"The job worker is not running; it was last seen %(when)s. Jobs wait until it "
"runs again."
msgstr ""
"İş işleyicisi çalışmıyor; en son %(when)s görüldü. İşler o yeniden çalışana "
"kadar bekler."
#: operations/templates/operations/jobs.html:16
#: operations/templatetags/operations.py:99
msgid "The job worker has not run yet. Jobs wait until it runs."
msgstr "İş işleyicisi henüz hiç çalışmadı. İşler o çalışana kadar bekler."
#: instances/states.py:27
msgid "Paused by a disk error"
msgstr "Bir disk hatası nedeniyle duraklatıldı"
@ -13084,8 +13209,215 @@ msgstr "Depolamasında yer açın, ardından sanal makineyi devam ettirin."
#: instances/templates/instance.html:55
msgid "An administrator has to free space on its storage and resume it."
msgstr "Bir yöneticinin depolamasında yer açıp sanal makineyi devam ettirmesi gerekir."
msgstr ""
"Bir yöneticinin depolamasında yer açıp sanal makineyi devam ettirmesi "
"gerekir."
#: instances/templates/instances/settings_tab.html:1030
msgid "This VM cannot report a crash or a hang yet: a choice adds the devices it reports them through, from the next start."
msgstr "Bu sanal makine henüz çöktüğünü ya da donduğunu bildiremiyor: bir seçim, bildirdiği aygıtları sonraki başlatmadan itibaren ekler."
msgid ""
"This VM cannot report a crash or a hang yet: a choice adds the devices it "
"reports them through, from the next start."
msgstr ""
"Bu sanal makine henüz çöktüğünü ya da donduğunu bildiremiyor: bir seçim, "
"bildirdiği aygıtları sonraki başlatmadan itibaren ekler."
#: accounts/templates/accounts/change_password_form.html:17
msgid "Set your own password"
msgstr "Kendi parolanızı belirleyin"
#: accounts/templates/accounts/change_password_form.html:20
#, python-format
msgid ""
"Signed in as %(name)s with a temporary password. Replace it to continue."
msgstr ""
"%(name)s olarak geçici bir parolayla oturum açtınız. Devam etmek için onu "
"değiştirin."
#: accounts/templates/accounts/change_password_form.html:22
#, python-format
msgid "For %(name)s. You stay signed in here; your other sessions end."
msgstr ""
"%(name)s için. Burada oturumunuz açık kalır; diğer oturumlarınız kapanır."
#: accounts/templates/accounts/change_password_form.html:34
msgid "Temporary password"
msgstr "Geçici parola"
#: accounts/templates/accounts/change_password_form.html:34
msgid "Current password"
msgstr "Mevcut parola"
#: accounts/templates/accounts/change_password_form.html:38
msgid "The one you just signed in with."
msgstr "Az önce oturum açarken kullandığınız parola."
#: accounts/templates/accounts/change_password_form.html:51
msgid "New password again"
msgstr "Yeni parola (tekrar)"
#: accounts/templates/accounts/change_password_form.html:57
msgid "8 characters or more"
msgstr "En az 8 karakter"
#: accounts/templates/accounts/change_password_form.html:58
msgid "Not only digits"
msgstr "Yalnızca rakamlardan oluşmuyor"
#: accounts/templates/accounts/change_password_form.html:59
msgid "Both entries match"
msgstr "İki giriş aynı"
#: accounts/templates/accounts/change_password_form.html:60
msgid ""
"Not like your name or e-mail, and not a common password: checked when you "
"save"
msgstr ""
"Adınıza veya e-postanıza benzemiyor ve yaygın bir parola değil: "
"kaydettiğinizde denetlenir"
#: accounts/templates/accounts/change_password_form.html:67
msgid "Save and continue"
msgstr "Kaydet ve devam et"
#: accounts/templates/accounts/change_password_form.html:60
msgid "met"
msgstr "sağlandı"
#: accounts/templates/accounts/change_password_form.html:60
#: accounts/templates/accounts/change_password_form.html:61
#: accounts/templates/accounts/change_password_form.html:62
#: accounts/templates/accounts/change_password_form.html:63
msgid "not met"
msgstr "sağlanmadı"
#: vmbackups/models.py:88 vmbackups/templates/vmbackups/policy.html:36
msgid "Backed up"
msgstr "Yedeklendi"
#: vmbackups/models.py:88 vmbackups/templates/vmbackups/policy.html:39
msgid "Running"
msgstr "Çalışıyor"
#: vmbackups/templates/vmbackups/policies.html:17
#: vmbackups/templates/vmbackups/policy.html:13
#, python-format
msgid "Last day"
msgid_plural "Last %(days)s days"
msgstr[0] "Son gün"
msgstr[1] "Son %(days)s gün"
#: vmbackups/templates/vmbackups/policies.html:24
msgid "no run"
msgstr "çalışma yok"
#: vmbackups/templates/vmbackups/policy.html:26
#, python-format
msgid "%(day)s, %(vm)s: %(outcome)s"
msgstr "%(day)s, %(vm)s: %(outcome)s"
#: vmbackups/templates/vmbackups/policy.html:40
msgid "No run"
msgstr "Çalışma yok"
#: vmbackups/templates/vmbackups/policy.html:43
msgid "The schedule has no VM."
msgstr "Zamanlamada sanal makine yok."
#: vmbackups/templates/vmbackups/policy.html:47
msgid "Not backed up"
msgstr "Yedeklenmedi"
#: vmbackups/views.py:359
#, python-format
msgid "%(n)s backed up"
msgstr "%(n)s yedeklendi"
#: vmbackups/views.py:359
#, python-format
msgid "%(n)s running"
msgstr "%(n)s çalışıyor"
#: vmbackups/views.py:360
#, python-format
msgid "%(n)s failed"
msgstr "%(n)s başarısız"
#: vmbackups/views.py:361
#, python-format
msgid "%(n)s skipped"
msgstr "%(n)s atlandı"
#: vmbackups/models.py:15
msgid "The job was cancelled"
msgstr "İş iptal edildi"
#: instances/jobs.py:1666
msgid "VM fault: %(vm)s"
msgstr "Sanal makine arızası: %(vm)s"
#: instances/jobs.py:1667
msgid "%(vm)s on %(host)s: %(reason)s"
msgstr "%(host)s üzerindeki %(vm)s: %(reason)s"
#: instances/jobs.py:1672 instances/templates/instances/settings_tab.html:301
msgid "Free unused space"
msgstr "Kullanılmayan alanı boşalt"
#: instances/jobs.py:1696 instances/templates/instances/settings_tab.html:301
msgid "The guest agent is not connected"
msgstr "Konuk ajanı bağlı değil"
#: instances/jobs.py:1704
msgid "The job stopped before the guest answered; trimming again is harmless"
msgstr "İş, konuk yanıt vermeden durdu; yeniden boşaltmanın zararı yok"
#: instances/jobs.py:1710
msgid ""
"No disk of the running VM has the discard mode unmap: its image files keep "
"their size. Set it in a disk's device details; it takes effect at the VM's "
"next start."
msgstr ""
"Çalışan sanal makinenin hiçbir diskinde diskard modu unmap değil: imaj "
"dosyaları boyutunu korur. Bunu bir diskin aygıt ayrıntılarından ayarlayın; "
"sanal makinenin bir sonraki başlatılışında geçerli olur."
#: instances/templates/instances/settings_tab.html:299
msgid "Free space the guest no longer uses in the image files."
msgstr "Konuğun artık kullanmadığı alanı imaj dosyalarında boşaltır."
#: instances/templates/instances/settings_tab.html:299
msgid ""
"No disk has the discard mode unmap while the VM runs: trimming frees no space"
" in its image files. Set it in a disk's device details; it takes effect at "
"the next start."
msgstr ""
"Sanal makine çalışırken hiçbir diskin diskard modu unmap değil: boşaltma imaj"
" dosyalarında yer açmaz. Bunu bir diskin aygıt ayrıntılarından ayarlayın; bir"
" sonraki başlatılışta geçerli olur."
#: operations/templates/operations/job.html:68
msgid "Trimmed"
msgstr "Boşaltılan"
#: operations/templates/operations/job.html:70
msgid "trimmed"
msgstr "boşaltıldı"
#: instances/jobs.py:1701
msgid "No file system was trimmed: %(errors)s"
msgstr "Hiçbir dosya sistemi boşaltılmadı: %(errors)s"
#: instances/templates/instance.html:98
msgid "Screen of %(name)s"
msgstr "%(name)s ekranı"
#: instances/templates/instance.html:105
msgctxt "screen"
msgid "Live"
msgstr "Canlı"
#: templates/navbar.html:35
msgid "%(n)s job not finished"
msgid_plural "%(n)s jobs not finished"
msgstr[0] "Bitmemiş %(n)s iş"
msgstr[1] "Bitmemiş %(n)s iş"

Binary file not shown.

File diff suppressed because it is too large Load diff

Binary file not shown.

View file

@ -274,14 +274,6 @@ msgstr "从用户移除"
msgid "No VMs."
msgstr "没有虚拟机。"
#: accounts/templates/accounts/change_password_form.html:20
msgid "Choose a new password before you go on."
msgstr "请先设置新密码再继续。"
#: accounts/templates/accounts/change_password_form.html:20
msgid "You stay signed in here; your other sessions end."
msgstr "您在此处保持登录;您的其他会话将结束。"
#: accounts/templates/accounts/change_password_form.html:35
#: accounts/templates/accounts/email_otp_form.html:25
#: admin/templates/admin/group_form.html:73
@ -6363,8 +6355,13 @@ msgid "Stop"
msgstr "停止"
#: instances/templates/instances/settings_tab.html:1028
msgid "A hang is noticed once the guest arms its watchdog (Linux: RuntimeWatchdogSec in systemd's system.conf). Stop keeps a VM that crashes again and again down for a look. From the next start."
msgstr "客户机启用其看门狗后才能发现挂起(Linux:systemd 的 system.conf 中的 RuntimeWatchdogSec)。“停止”会让反复崩溃的虚拟机保持停止状态以便排查。下次启动时生效。"
msgid ""
"A hang is noticed once the guest arms its watchdog (Linux: RuntimeWatchdogSec"
" in systemd's system.conf). Stop keeps a VM that crashes again and again down"
" for a look. From the next start."
msgstr ""
"客户机启用其看门狗后才能发现挂起(Linux:systemd 的 system.conf 中的 "
"RuntimeWatchdogSec)。“停止”会让反复崩溃的虚拟机保持停止状态以便排查。下次启动时生效。"
#: instances/templates/instances/settings_tab.html:1030
#, python-format
@ -10506,26 +10503,10 @@ msgstr "要删除此计划吗?其备份将保留。"
msgid "Delete schedule"
msgstr "删除计划"
#: vmbackups/templates/vmbackups/policy.html:26
msgid "Runs"
msgstr "运行记录"
#: vmbackups/templates/vmbackups/policy.html:30
msgid "Day"
msgstr "日期"
#: vmbackups/templates/vmbackups/policy.html:37
msgid "Backup job"
msgstr "备份作业"
#: vmbackups/templates/vmbackups/policy.html:38
msgid "Skipped"
msgstr "已跳过"
#: vmbackups/templates/vmbackups/policy.html:48
msgid "No run yet."
msgstr "还没有运行记录。"
#: vmbackups/templates/vmbackups/policy_form.html:13
#, python-format
msgid "Time zone: %(time_zone)s"
@ -12111,14 +12092,16 @@ msgstr "登录已锁定"
#: accounts/templates/accounts/lockout.html:14
#, python-format
msgid "Too many failed sign-ins. The lock ends within %(minutes)s minute."
msgid_plural "Too many failed sign-ins. The lock ends within %(minutes)s minutes."
msgid_plural ""
"Too many failed sign-ins. The lock ends within %(minutes)s minutes."
msgstr[0] "登录失败次数过多。锁定将在 %(minutes)s 分钟内解除。"
#: accounts/templates/accounts/lockout.html:20
msgid "Back to sign in"
msgstr "返回登录"
#: accounts/templates/accounts/otp_login.html:52 accounts/templates/login.html:51
#: accounts/templates/accounts/otp_login.html:52
#: accounts/templates/login.html:51
msgid "Caps Lock is on"
msgstr "大写锁定已开启"
@ -12157,8 +12140,12 @@ msgid "Invalid token. Please make sure you have entered it correctly."
msgstr "验证码无效。请确认输入正确。"
#, python-format
msgid "Verification temporarily disabled because of %(failure_count)d failed attempt, please try again soon."
msgid_plural "Verification temporarily disabled because of %(failure_count)d failed attempts, please try again soon."
msgid ""
"Verification temporarily disabled because of %(failure_count)d failed "
"attempt, please try again soon."
msgid_plural ""
"Verification temporarily disabled because of %(failure_count)d failed "
"attempts, please try again soon."
msgstr[0] "由于 %(failure_count)d 次验证失败,验证已暂时停用,请稍后再试。"
msgid "Verification of the token is currently disabled"
@ -12265,7 +12252,9 @@ msgstr "取消 %(job)s?它将停在当前进度。"
#: admin/templates/admin/user_list.html
#, python-format
msgid "Block %(name)s? They are signed out and their API tokens are deleted; unblocking does not bring the tokens back."
msgid ""
"Block %(name)s? They are signed out and their API tokens are deleted; "
"unblocking does not bring the tokens back."
msgstr "禁用 %(name)s?其登录将被注销,API 令牌将被删除;解除禁用不会恢复这些令牌。"
#: webvirtcloud/middleware.py
@ -12296,7 +12285,6 @@ msgstr "哪些虚拟机"
msgid "Choose the VMs to back up"
msgstr "请选择要备份的虚拟机"
#: webvirtcloud/common_tags.py:29
#, python-format
msgid "%(percent)s%%"
@ -12305,7 +12293,9 @@ msgstr "%(percent)s%%"
#: operations/templates/operations/jobs.html:16
#: operations/templatetags/operations.py:98
#, python-format
msgid "The job worker is not running; it was last seen %(when)s. Jobs wait until it runs again."
msgid ""
"The job worker is not running; it was last seen %(when)s. Jobs wait until it "
"runs again."
msgstr "工作进程未在运行;最后在线时间 %(when)s。任务将等待它重新运行。"
#: operations/templates/operations/jobs.html:16
@ -12313,7 +12303,6 @@ msgstr "工作进程未在运行;最后在线时间 %(when)s。任务将等待
msgid "The job worker has not run yet. Jobs wait until it runs."
msgstr "工作进程尚未运行过。任务将等待它运行。"
#: instances/states.py:27
msgid "Paused by a disk error"
msgstr "因磁盘错误而暂停"
@ -12365,5 +12354,195 @@ msgid "An administrator has to free space on its storage and resume it."
msgstr "需要管理员在其存储上释放空间并恢复它。"
#: instances/templates/instances/settings_tab.html:1030
msgid "This VM cannot report a crash or a hang yet: a choice adds the devices it reports them through, from the next start."
msgid ""
"This VM cannot report a crash or a hang yet: a choice adds the devices it "
"reports them through, from the next start."
msgstr "此虚拟机尚无法报告崩溃或挂起:做出选择即会添加其报告所用的设备,下次启动时生效。"
#: accounts/templates/accounts/change_password_form.html:17
msgid "Set your own password"
msgstr "设置您自己的密码"
#: accounts/templates/accounts/change_password_form.html:20
#, python-format
msgid ""
"Signed in as %(name)s with a temporary password. Replace it to continue."
msgstr "您已使用临时密码以 %(name)s 身份登录。请更换后继续。"
#: accounts/templates/accounts/change_password_form.html:22
#, python-format
msgid "For %(name)s. You stay signed in here; your other sessions end."
msgstr "用户 %(name)s。您在此处保持登录;您的其他会话将结束。"
#: accounts/templates/accounts/change_password_form.html:34
msgid "Temporary password"
msgstr "临时密码"
#: accounts/templates/accounts/change_password_form.html:34
msgid "Current password"
msgstr "当前密码"
#: accounts/templates/accounts/change_password_form.html:38
msgid "The one you just signed in with."
msgstr "即您刚才登录时使用的密码。"
#: accounts/templates/accounts/change_password_form.html:51
msgid "New password again"
msgstr "再次输入新密码"
#: accounts/templates/accounts/change_password_form.html:57
msgid "8 characters or more"
msgstr "至少 8 个字符"
#: accounts/templates/accounts/change_password_form.html:58
msgid "Not only digits"
msgstr "不全是数字"
#: accounts/templates/accounts/change_password_form.html:59
msgid "Both entries match"
msgstr "两次输入一致"
#: accounts/templates/accounts/change_password_form.html:60
msgid ""
"Not like your name or e-mail, and not a common password: checked when you "
"save"
msgstr "与您的姓名或电子邮件不相似,且不是常见密码:保存时检查"
#: accounts/templates/accounts/change_password_form.html:67
msgid "Save and continue"
msgstr "保存并继续"
#: accounts/templates/accounts/change_password_form.html:60
msgid "met"
msgstr "已满足"
#: accounts/templates/accounts/change_password_form.html:60
#: accounts/templates/accounts/change_password_form.html:61
#: accounts/templates/accounts/change_password_form.html:62
#: accounts/templates/accounts/change_password_form.html:63
msgid "not met"
msgstr "未满足"
#: vmbackups/models.py:88 vmbackups/templates/vmbackups/policy.html:36
msgid "Backed up"
msgstr "已备份"
#: vmbackups/models.py:88 vmbackups/templates/vmbackups/policy.html:39
msgid "Running"
msgstr "运行中"
#: vmbackups/templates/vmbackups/policies.html:17
#: vmbackups/templates/vmbackups/policy.html:13
#, python-format
msgid "Last day"
msgid_plural "Last %(days)s days"
msgstr[0] "最近 %(days)s 天"
#: vmbackups/templates/vmbackups/policies.html:24
msgid "no run"
msgstr "未运行"
#: vmbackups/templates/vmbackups/policy.html:26
#, python-format
msgid "%(day)s, %(vm)s: %(outcome)s"
msgstr "%(day)s,%(vm)s:%(outcome)s"
#: vmbackups/templates/vmbackups/policy.html:40
msgid "No run"
msgstr "未运行"
#: vmbackups/templates/vmbackups/policy.html:43
msgid "The schedule has no VM."
msgstr "该计划没有虚拟机。"
#: vmbackups/templates/vmbackups/policy.html:47
msgid "Not backed up"
msgstr "未备份"
#: vmbackups/views.py:359
#, python-format
msgid "%(n)s backed up"
msgstr "%(n)s 台已备份"
#: vmbackups/views.py:359
#, python-format
msgid "%(n)s running"
msgstr "%(n)s 台运行中"
#: vmbackups/views.py:360
#, python-format
msgid "%(n)s failed"
msgstr "%(n)s 台失败"
#: vmbackups/views.py:361
#, python-format
msgid "%(n)s skipped"
msgstr "%(n)s 台已跳过"
#: vmbackups/models.py:15
msgid "The job was cancelled"
msgstr "作业已取消"
#: instances/jobs.py:1666
msgid "VM fault: %(vm)s"
msgstr "虚拟机故障:%(vm)s"
#: instances/jobs.py:1667
msgid "%(vm)s on %(host)s: %(reason)s"
msgstr "%(host)s 上的 %(vm)s:%(reason)s"
#: instances/jobs.py:1672 instances/templates/instances/settings_tab.html:301
msgid "Free unused space"
msgstr "释放未使用空间"
#: instances/jobs.py:1696 instances/templates/instances/settings_tab.html:301
msgid "The guest agent is not connected"
msgstr "客户机代理未连接"
#: instances/jobs.py:1704
msgid "The job stopped before the guest answered; trimming again is harmless"
msgstr "作业在客户机应答前停止;再次修剪无害"
#: instances/jobs.py:1710
msgid ""
"No disk of the running VM has the discard mode unmap: its image files keep "
"their size. Set it in a disk's device details; it takes effect at the VM's "
"next start."
msgstr "运行中的虚拟机没有任何磁盘的 Discard 模式为 unmap:其镜像文件大小不变。请在磁盘的设备详情中设置;虚拟机下次启动时生效。"
#: instances/templates/instances/settings_tab.html:299
msgid "Free space the guest no longer uses in the image files."
msgstr "释放客户机不再使用的镜像文件空间。"
#: instances/templates/instances/settings_tab.html:299
msgid ""
"No disk has the discard mode unmap while the VM runs: trimming frees no space"
" in its image files. Set it in a disk's device details; it takes effect at "
"the next start."
msgstr "虚拟机运行时没有任何磁盘的 Discard 模式为 unmap:修剪不会释放其镜像文件中的空间。请在磁盘的设备详情中设置;下次启动时生效。"
#: operations/templates/operations/job.html:68
msgid "Trimmed"
msgstr "已修剪"
#: operations/templates/operations/job.html:70
msgid "trimmed"
msgstr "已修剪"
#: instances/jobs.py:1701
msgid "No file system was trimmed: %(errors)s"
msgstr "没有文件系统被修剪:%(errors)s"
#: instances/templates/instance.html:98
msgid "Screen of %(name)s"
msgstr "%(name)s 的屏幕"
#: instances/templates/instance.html:105
msgctxt "screen"
msgid "Live"
msgstr "实时"
#: templates/navbar.html:35
msgid "%(n)s job not finished"
msgid_plural "%(n)s jobs not finished"
msgstr[0] "%(n)s 个任务未完成"

View file

@ -1,7 +1,8 @@
"""Notices for the operator: a backup that failed, was not taken, is missing or damaged, and a job that ended
uncertain. alert() queues one in the caller's transaction, so a failed send never holds up the change it tells
of; send(), a periodic task of the worker, mails it to the Settings page's alert addresses and POSTs it as JSON
to its alert webhook, trying again at the next passes."""
"""Notices for the operator: a backup that failed, was not taken, is missing or damaged, a job that ended
uncertain, and a VM a fault stopped or paused (instances.jobs.watch_faults). alert() queues one in the
caller's transaction, so a failed send never holds up the change it tells of; send(), a periodic task of the
worker, mails it to the Settings page's alert addresses and POSTs it as JSON to its alert webhook, trying again
at the next passes."""
import json
import logging

View file

@ -66,6 +66,11 @@ class Operation(models.Model):
ordering = ["-created_at"]
constraints = [models.UniqueConstraint(fields=["user", "submission_key"], name="unique_submission")]
@classmethod
def visible_to(cls, user):
"""The jobs a user sees: all for a superuser, their own for others."""
return cls.objects.all() if user.is_superuser else cls.objects.filter(user=user)
def __str__(self):
return f"{self.kind} {self.id}"

View file

@ -21,7 +21,7 @@
</div>
<div class="small text-body-secondary mt-1">{% trans "User" %}: {{ job.username }}</div>
</div>
{% if job.phase or op.progress_total or job.cancellable or job.error or job.result.open or job.result.links or job.result.warning or job.result.left_behind or job.resolution %}
{% if job.phase or op.progress_total or job.cancellable or job.error or job.result.open or job.result.links or job.result.warning or job.result.left_behind or job.result.trimmed or job.resolution %}
<div class="card-body pb-0">
{% if job.phase or job.cancellable %}
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
@ -64,6 +64,12 @@
{% if job.result.warning %}
<div class="alert alert-warning text-break" role="alert">{{ job.result.warning }}</div>
{% endif %}
{% if job.result.trimmed %}
<h2 class="h6">{% trans "Trimmed" %}</h2>
<ul class="list-unstyled mb-3">
{% for fs in job.result.trimmed %}<li class="text-break"><code>{{ fs.path }}</code> {% if fs.error %}{{ fs.error }}{% elif fs.trimmed is None %}{% trans "trimmed" %}{% else %}{{ fs.trimmed|binary_size }}{% endif %}</li>{% endfor %}
</ul>
{% endif %}
{% if job.result.left_behind %}
<h2 class="h6">{% trans "Left behind" %}</h2>
<ul class="list-unstyled mb-3">

View file

@ -77,6 +77,12 @@ def wrap_at_slash(label):
return format_html_join(mark_safe("/<wbr>"), '<span class="text-nowrap">{}</span>', ((part,) for part in label.split("/")))
@register.simple_tag
def active_job_count(user):
"""How many of the jobs the user sees are queued, running or cancelling: the menu's Jobs badge."""
return Operation.visible_to(user).filter(state__in=Operation.ACTIVE).count()
@register.inclusion_tag("operations/job_panel_script.html", takes_context=True)
def job_panel_script(context, resource):
"""The job panel's script for the page of resource."""

View file

@ -24,19 +24,15 @@ from .models import Operation, last_seen, worker_gone
from .utils import said, words
def _visible(user):
return Operation.objects.all() if user.is_superuser else Operation.objects.filter(user=user)
def _get(user, pk):
try:
return _visible(user).get(pk=pk)
return Operation.visible_to(user).get(pk=pk)
except Operation.DoesNotExist:
raise Http404 from None
def jobs(request):
qs = _visible(request.user)
qs = Operation.visible_to(request.user)
if request.user.is_superuser:
# the host and the user as typed: the start of the host, any part of the name
if compute := request.GET.get("compute"):
@ -54,7 +50,7 @@ def jobs(request):
seen = last_seen()
# a job the worker has to start, run or stop, not one a request runs (job_panel.js uses the same rule)
unavailable = (worker_gone(seen)
and _visible(request.user).filter(state__in=Operation.ACTIVE)
and Operation.visible_to(request.user).filter(state__in=Operation.ACTIVE)
.exclude(worker=Operation.REQUEST).exists())
return render(request, "operations/jobs.html",
{"page": page, "rows": rows, "worker_last_seen": seen, "worker_unavailable": unavailable,

View file

@ -130,8 +130,13 @@ class Worker:
except BlockingIOError:
logger.error("Another worker runs on this host; exiting")
return 1
signal.signal(signal.SIGTERM, lambda *_: self.stopping.set())
signal.signal(signal.SIGINT, lambda *_: self.stopping.set())
# a signal runs its handler in this thread, which may be inside stopping.wait() holding the
# event's lock: set from a thread of its own, the event waits for that lock instead of deadlocking
def stop(*_):
threading.Thread(target=self.stopping.set, daemon=True).start()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
status = 0
try:
while not acquire(self.identity, self.host):

View file

@ -349,7 +349,121 @@ td .tag-more {
height: 0.85em;
}
/* the menu: its links in the full light of the theme's navbar, an icon beside each label; the page's own
section underlined (on a phone, a bar at its side) and bolder */
.navbar-dark {
--bs-navbar-color: #fff;
--bs-navbar-hover-color: #fff;
--bs-navbar-active-color: #fff;
}
.navbar .nav-link {
display: flex;
align-items: center;
gap: .375rem;
}
.navbar .nav-link svg {
flex: none;
}
.navbar .nav-link.active {
font-weight: 600;
box-shadow: inset 3px 0 0 currentColor;
padding-left: .75rem;
}
@media (min-width: 768px) {
.navbar .nav-link.active {
box-shadow: inset 0 -2px 0 currentColor;
padding-left: var(--bs-navbar-nav-link-padding-x);
}
.navbar .nav-link:hover:not(.active) {
box-shadow: inset 0 -2px 0 rgba(255, 255, 255, .45);
}
}
.navbar .dropdown-item svg {
vertical-align: -.125em;
}
/* beside the other links Jobs and Administration are icons; their names stay for screen readers and the phone menu */
@media (min-width: 768px) {
.navbar .nav-label {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
}
}
/* "Skip to content" brings #main up below the sticky navbar, not behind it */
#main {
scroll-margin-top: 5rem;
}
/* a backup schedule's runs, a mark a day: filled backed up, crossed failed, hollow skipped, half running */
.run-days { display: inline-flex; gap: 2px; }
.run-mark {
display: inline-flex;
align-items: center;
justify-content: center;
width: .75rem;
height: .75rem;
border: 2px solid transparent;
border-radius: 3px;
vertical-align: middle;
text-decoration: none;
}
.run-grid .run-mark { width: 1.125rem; height: 1.125rem; }
.run-grid td, .run-grid th { padding: 2px; }
.run-grid-vm { max-width: 14rem; padding-right: .75rem !important; position: sticky; left: 0; background: var(--bs-body-bg); }
/* the grid scrolls on a phone starting at its newest day, at the right */
.run-grid-scroll { overflow-x: auto; direction: rtl; width: fit-content; max-width: 100%; }
.run-grid-scroll > table { direction: ltr; }
.run-succeeded { background: var(--bs-success); }
.run-failed { background: var(--bs-danger); }
.run-failed::after { content: "\00d7"; color: #fff; font-size: .75rem; font-weight: 700; line-height: 1; }
.run-days .run-failed::after { font-size: .625rem; }
.run-skipped { border-color: var(--bs-secondary-color); }
.run-running { border-color: var(--bs-info); background: linear-gradient(90deg, var(--bs-info) 50%, transparent 50%); }
.run-none { background: var(--bs-secondary-bg); }
/* high contrast themes would drop the marks' colours, which carry their meaning */
@media (forced-colors: active) { .run-mark { forced-color-adjust: none; } }
/* the VM page's screen thumbnail (instance.html): the picture at its own shape, a caption under it
(live or suspended, and "Open console" when it is a button); on phones a small picture beside the caption */
.vm-screen {
display: flex;
align-items: center;
gap: .75rem;
width: 100%;
padding: 0;
color: var(--bs-body-color);
text-align: start;
background: none;
border: 0;
}
.vm-screen[hidden] { display: none; }
.vm-screen-frame {
flex: none;
display: flex;
align-items: center;
justify-content: center;
width: 6.5rem;
max-height: 5rem;
overflow: hidden;
background: var(--bs-tertiary-bg);
border: 1px solid var(--bs-border-color);
border-radius: var(--bs-border-radius);
}
.vm-screen-frame img { display: block; max-width: 100%; max-height: 5rem; height: auto; }
.vm-screen-caption { display: flex; flex-direction: column; gap: .125rem; font-size: .875em; line-height: 1.3; }
.vm-screen-state { color: var(--bs-secondary-color); }
.vm-screen-live { display: inline-block; width: .5rem; height: .5rem; border-radius: 50%; background: var(--bs-success); vertical-align: .05em; }
.vm-screen-open { color: var(--bs-link-color); }
button.vm-screen:hover .vm-screen-open { text-decoration: underline; }
button.vm-screen:hover .vm-screen-frame { border-color: var(--bs-link-color); }
.vm-screen:focus-visible { outline: 0; border-radius: var(--bs-border-radius); box-shadow: 0 0 0 var(--bs-focus-ring-width) var(--bs-focus-ring-color); }
@media (min-width: 768px) {
.vm-screen { flex: none; flex-direction: column; align-items: stretch; gap: .375rem; width: 13rem; align-self: flex-start; }
.vm-screen-frame { width: 100%; max-height: 10rem; }
.vm-screen-frame img { max-height: 10rem; }
.vm-screen-caption { flex-direction: row; justify-content: space-between; gap: .5rem; }
}

View file

@ -1,11 +0,0 @@
<?xml version="1.0" ?>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-person-plus" viewBox="0 0 16 16">
<path d="M6 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0zm4 8c0 1-1 1-1 1H1s-1 0-1-1 1-4 6-4 6 3 6 4zm-1-.004c-.001-.246-.154-.986-.832-1.664C9.516 10.68 8.289 10 6 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664h10z"/>
<path fill-rule="evenodd" d="M13.5 5a.5.5 0 0 1 .5.5V7h1.5a.5.5 0 0 1 0 1H14v1.5a.5.5 0 0 1-1 0V8h-1.5a.5.5 0 0 1 0-1H13V5.5a.5.5 0 0 1 .5-.5z"/>
</svg>

Before

Width:  |  Height:  |  Size: 573 B

View file

@ -20,6 +20,25 @@
if (element) element.addEventListener(event, handler);
}
// the VM's screen: read now and every 10 s while the page is in view, one read at a time; a frame
// replaces the shown one once it has fully come, and the screen is hidden while there is none
var screen = document.getElementById("vm-screen");
if (screen) {
var shown = screen.querySelector("img");
var reading = false;
var read_screen = function () {
if (reading || document.hidden) return;
reading = true;
var frame = new Image();
frame.alt = shown.alt;
frame.onload = function () { shown.replaceWith(frame); shown = frame; screen.hidden = false; reading = false; };
frame.onerror = function () { screen.hidden = true; reading = false; };
frame.src = screen.dataset.screenUrl + "?t=" + Date.now();
};
read_screen();
setInterval(read_screen, 10000);
}
// the guest OS details, read through the guest agent
function load_osinfo() {
var error = $('#osinfo-error');

View file

@ -0,0 +1,31 @@
// The password change form: the eye button shows or hides both new
// entries, and the rules the browser can check are ticked as you type.
// The server checks every rule again when the form is sent.
var newPassword = document.getElementById("id_new_password1");
var again = document.getElementById("id_new_password2");
var rules = document.getElementById("password-rules");
document.getElementById("toggle-new-password").addEventListener("click", function () {
var shown = newPassword.type === "password";
newPassword.type = again.type = shown ? "text" : "password";
this.setAttribute("aria-pressed", String(shown));
this.querySelector("i").className = shown ? "bi bi-eye-slash" : "bi bi-eye";
});
function tick() {
var value = newPassword.value;
// as Python counts them: characters, not UTF-16 units; any digit, as str.isdigit
var met = {
length: Array.from(value).length >= 8,
letters: value !== "" && !/^[\p{Nd}\p{No}]+$/u.test(value),
match: value !== "" && value === again.value,
};
Object.keys(met).forEach(function (rule) {
var item = rules.querySelector('[data-rule="' + rule + '"]');
item.classList.toggle("text-success", met[rule]);
item.querySelector("i").className = (met[rule] ? "bi bi-check-circle-fill" : "bi bi-circle") + " me-2";
item.querySelector(".visually-hidden").textContent = met[rule] ? rules.dataset.met : rules.dataset.unmet;
});
}
newPassword.addEventListener("input", tick);
again.addEventListener("input", tick);

View file

@ -29,11 +29,13 @@
<body class="pb-5"{% block body_attrs %}{% endblock %}>
{% block navbar %}{# a page that leads nowhere else leaves it out #}
{% if request.user.is_authenticated %}
{# for the keyboard: past the menu, shown when it has the focus #}
<a class="visually-hidden-focusable d-block text-center p-2" href="#main">{% trans "Skip to content" %}</a>
{% include 'navbar.html' %}
{% endif %}
{% endblock navbar %}
<div role="main" id="main" class="container">
{% block page_header %}{# a page with a heading of its own leaves it out #}

View file

@ -1,8 +1,9 @@
{% load i18n %}
{% load bootstrap_icons %}
{% load common_tags %}
<!-- Fixed navbar -->
<nav class="navbar sticky-top navbar-expand-md navbar-dark bg-primary mb-3" aria-label="Main top navbar">
{% load operations %}
{# the page's own section is marked (active, aria-current); the labels of Jobs and Administration show only in the phone menu #}
<nav class="navbar sticky-top navbar-expand-md navbar-dark bg-primary mb-3" aria-label="{% trans 'Menu' %}">
<div class="container">
<a class="navbar-brand" href="{% url 'index' %}">WebVirtCloud</a>
<button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbar" aria-expanded="false" aria-label="{% trans 'Menu' %}">
@ -10,56 +11,77 @@
</button>
<div class="collapse navbar-collapse" id="navbar">
<ul class="navbar-nav">
<li class="nav-item {% class_active request '^/instances' %}">
<a class="nav-link" href="{% url 'instances:index' %}">{% bs_icon 'pc-display-horizontal' %} {% trans "Instances" %}</a>
{% class_active request '^/instances' as here %}
<li class="nav-item">
<a class="nav-link {{ here }}" href="{% url 'instances:index' %}"{% if here %} aria-current="page"{% endif %}>{% bs_icon 'pc-display-horizontal' %} {% trans "Instances" %}</a>
</li>
{% if request.user.is_superuser %}
<li class="nav-item {% class_active request '^/computes' %}">
<a class="nav-link" href="{% url 'computes' %}">{% bs_icon 'pc-display' %} {% trans "Computes" %}</a>
{% class_active request '^/computes' as here %}
<li class="nav-item">
<a class="nav-link {{ here }}" href="{% url 'computes' %}"{% if here %} aria-current="page"{% endif %}>{% bs_icon 'pc-display' %} {% trans "Computes" %}</a>
</li>
<li class="nav-item {% class_active request '^/backups' %}">
<a class="nav-link" href="{% url 'vmbackups:index' %}">{% bs_icon 'archive' %} {% trans "Backups" %}</a>
{% class_active request '^/backups' as here %}
<li class="nav-item">
<a class="nav-link {{ here }}" href="{% url 'vmbackups:index' %}"{% if here %} aria-current="page"{% endif %}>{% bs_icon 'archive' %} {% trans "Backups" %}</a>
</li>
{% endif %}
</ul>
<ul class="navbar-nav ms-auto">
<li class="nav-item {% class_active request '^/jobs' %}">
<a class="nav-link" href="{% url 'operations:jobs' %}" aria-label="{% trans 'Jobs' %}">{% bs_icon 'list-task' %}</a>
{% class_active request '^/jobs' as here %}
{% active_job_count request.user as active_jobs %}
<li class="nav-item">
<a class="nav-link {{ here }}" href="{% url 'operations:jobs' %}" title="{% trans 'Jobs' %}"{% if here %} aria-current="page"{% endif %}>
{% bs_icon 'list-task' %} <span class="nav-label">{% trans "Jobs" %}</span>
{% if active_jobs %}<span class="badge rounded-pill text-bg-light"><span aria-hidden="true">{{ active_jobs }}</span><span class="visually-hidden">{% blocktrans count n=active_jobs %}{{ n }} job not finished{% plural %}{{ n }} jobs not finished{% endblocktrans %}</span></span>{% endif %}
</a>
</li>
{% if request.user.is_superuser %}
<li class="nav-item dropdown {% app_active request 'admin' %}">
<a class="nav-link" id="administration" href="#" title="{% trans "Administration" %}" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{% bs_icon 'wrench-adjustable' %}
{% app_active request 'admin' as here %}
{% if not here %}{% view_active request 'appsettings' as here %}{% endif %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle {{ here }}" id="administration" href="#" title="{% trans 'Administration' %}" role="button" data-bs-toggle="dropdown" aria-expanded="false">
{% bs_icon 'wrench-adjustable' %} <span class="nav-label">{% trans "Administration" %}</span>
</a>
<div class="dropdown-menu" aria-labelledby="administration">
<a class="dropdown-item {% view_active request 'admin:user_list' %}" href="{% url 'admin:user_list' %}">{% bs_icon 'person-plus' %} {% trans "Users" %}</a>
<div class="dropdown-menu dropdown-menu-end" aria-labelledby="administration">
<a class="dropdown-item {% view_active request 'admin:user_list' %}" href="{% url 'admin:user_list' %}">{% bs_icon 'person' %} {% trans "Users" %}</a>
<a class="dropdown-item {% view_active request 'admin:group_list' %}" href="{% url 'admin:group_list' %}">{% bs_icon 'people-fill' %} {% trans "Groups" %}</a>
<a class="dropdown-item {% view_active request 'admin:logs' %}" href="{% url 'admin:logs' %}">{% bs_icon 'card-list' %} {% trans "Logs" %}</a>
<a class="dropdown-item {% view_active request 'admin:tombstone_list' %}" href="{% url 'admin:tombstone_list' %}">{% bs_icon 'trash' %} {% trans "Removed VMs" %}</a>
<a class="dropdown-item {% view_active request 'admin:tag_list' %}" href="{% url 'admin:tag_list' %}">{% bs_icon 'tag' %} {% trans "Tags" %}</a>
<a class="dropdown-item" href="{% url 'instances:vm_report' %}">{% bs_icon 'download' %} {% trans "VM report (.xlsx)" %}</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item {% view_active request 'appsettings' %}" href="{% url 'appsettings' %}">{% bs_icon 'gear-wide-connected' %} {% trans "Settings" %}</a>
</div>
</li>
{% endif %}
<li class="nav-item dropdown {% class_active request '^/accounts' %}">
<a class="nav-link dropdown-toggle" href="#" id="navbarUserDropdown" data-bs-toggle="dropdown" role="button" aria-expanded="false">
{% bs_icon 'person-square' %} {{ request.user.username }}
{% class_active request '^/accounts' as here %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle {{ here }}" href="#" id="navbarUserDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
{% bs_icon 'person-square' %} {{ request.user.username }}
</a>
<div class="dropdown-menu" aria-labelledby="navbarUserDropdown">
{% get_current_language as LANGUAGE_CODE %}
<a class="dropdown-item disabled" href="#">
{% trans "Language" %}: <span class="badge bg-secondary">{{ LANGUAGE_CODE }}</span>
</a>
<div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarUserDropdown">
<a class="dropdown-item {% view_active request 'accounts:profile' %}" href="{% url 'accounts:profile' %}">{% bs_icon 'person-vcard' %} {% trans "Profile" %}</a>
<div class="dropdown-divider"></div>
{# the languages, each a button that sets it; Django comes back to this page (the Referer) #}
<div class="dropdown-header">{% trans "Language" %}</div>
<form method="post" action="{% url 'set_language' %}">
{% csrf_token %}
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<button type="submit" name="language" value="{{ language.code }}" lang="{{ language.code }}"
class="dropdown-item{% if language.code == LANGUAGE_CODE %} active{% endif %}"{% if language.code == LANGUAGE_CODE %} aria-current="true"{% endif %}>{{ language.name_local }}</button>
{% endfor %}
</form>
<div class="dropdown-divider"></div>
<form method="post" action="{% url 'accounts:logout' %}">
{% csrf_token %}
<button type="submit" class="dropdown-item">{% bs_icon 'power' %} {% trans "Log out" %}</button>
<button type="submit" class="dropdown-item">{% bs_icon 'power' %} {% trans "Log out" %}</button>
</form>
</div>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</nav>
</nav>

View file

@ -1,6 +1,17 @@
from django.apps import AppConfig
from django.db.models.signals import pre_delete
def keep_job_end(sender, instance, **kwargs):
from .models import BackupRun
BackupRun.keep_job_end(instance)
class VmbackupsConfig(AppConfig):
name = "vmbackups"
verbose_name = "Backups"
def ready(self):
# the job history drops ended jobs (operations.worker.housekeeping); a schedule's run keeps how its job went
pre_delete.connect(keep_job_end, sender="operations.Operation")

View file

@ -0,0 +1,18 @@
# Generated by Django 5.2.18 on 2026-11-25 06:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vmbackups', '0010_keep_weekly_monthly'),
]
operations = [
migrations.AlterField(
model_name='backuprun',
name='state',
field=models.CharField(choices=[('submitted', 'submitted'), ('skipped', 'skipped'), ('failed', 'failed'), ('succeeded', 'succeeded')], max_length=16),
),
]

View file

@ -3,6 +3,8 @@ import uuid
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext_noop
from computes.models import Compute, Tag
from instances.models import Instance
@ -10,6 +12,9 @@ from operations.models import Operation
from vrtManager.backup import backup_prefix
JOB_CANCELLED = gettext_noop("The job was cancelled")
class BackupTarget(models.Model):
"""Storage the backups go to: a pool on each compute that sees it."""
@ -79,8 +84,11 @@ class BackupPolicy(models.Model):
class BackupRun(models.Model):
"""A schedule's backup of one VM on one day: what it submitted, or why not."""
SUBMITTED, SKIPPED, FAILED = "submitted", "skipped", "failed"
STATES = [(SUBMITTED, "submitted"), (SKIPPED, "skipped"), (FAILED, "failed")]
SUBMITTED, SKIPPED, FAILED, SUCCEEDED = "submitted", "skipped", "failed", "succeeded"
# succeeded and failed also once its job has ended and the job history drops the job (keep_job_end)
STATES = [(SUBMITTED, "submitted"), (SKIPPED, "skipped"), (FAILED, "failed"), (SUCCEEDED, "succeeded")]
RUNNING = "running" # what came of it, its job's end included (outcome)
OUTCOMES = {SUCCEEDED: _("Backed up"), RUNNING: _("Running"), FAILED: _("Failed"), SKIPPED: _("Skipped")}
policy = models.ForeignKey(BackupPolicy, on_delete=models.CASCADE, related_name="runs")
instance = models.ForeignKey(Instance, on_delete=models.CASCADE, related_name="backup_runs")
@ -93,6 +101,42 @@ class BackupRun(models.Model):
class Meta:
constraints = [models.UniqueConstraint(fields=["policy", "instance", "day"], name="one_run_per_day")]
@classmethod
def outcome_of(cls, state, job_state):
"""Its state; a submitted run's as its job goes."""
if state != cls.SUBMITTED:
return state
if job_state == Operation.SUCCEEDED:
return cls.SUCCEEDED
return cls.RUNNING if job_state in Operation.ACTIVE else cls.FAILED
@property
def outcome(self):
return self.outcome_of(self.state, self.operation.state if self.operation_id else None)
@property
def outcome_label(self):
return self.OUTCOMES[self.outcome]
@property
def reason(self):
"""Why it did not back up: its note, else its job's error."""
if self.note or not self.operation_id:
return self.note
if self.operation.state == Operation.CANCELLED and not self.operation.error:
from operations.utils import say # operations.utils imports the models
return say(JOB_CANCELLED)
return self.operation.error
@classmethod
def keep_job_end(cls, job):
"""Its runs keep what the job came to, which is gone with the job."""
for run in cls.objects.filter(operation=job, state=cls.SUBMITTED).select_related("operation"):
run.state = cls.SUCCEEDED if job.state == Operation.SUCCEEDED else cls.FAILED
run.note = run.reason
run.save(update_fields=["state", "note"])
UUID_IN_NAME = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")

View file

@ -14,13 +14,14 @@
<div class="table-responsive mb-4">
<table class="table table-hover align-middle">
<thead>
<tr><th>{% trans "Name" %}</th><th>{% trans "VMs" %}</th><th>{% trans "Target" %}</th><th>{% trans "Daily at" %}</th>
<tr><th>{% trans "Name" %}</th><th>{% blocktrans count days=days|length %}Last day{% plural %}Last {{ days }} days{% endblocktrans %}</th><th>{% trans "VMs" %}</th><th>{% trans "Target" %}</th><th>{% trans "Daily at" %}</th>
<th class="text-end">{% trans "Backups kept" %}</th><th>{% trans "Full backup" %}</th><th>{% trans "State" %}</th></tr>
</thead>
<tbody>
{% for policy in policies %}
<tr>
<td><a href="{% url 'vmbackups:policy' policy.id %}">{{ policy.name }}</a></td>
<td class="text-nowrap"><a href="{% url 'vmbackups:policy' policy.id %}">{{ policy.name }}</a></td>
<td class="text-nowrap"><a class="run-days" href="{% url 'vmbackups:policy' policy.id %}">{% for day in policy.history %}<span class="run-mark run-{{ day.outcome|default:"none" }}" role="img" title="{{ day.day|date:"Y-m-d" }}: {{ day.text|default:_("no run") }}" aria-label="{{ day.day|date:"Y-m-d" }}: {{ day.text|default:_("no run") }}"></span>{% endfor %}</a></td>
<td>{% if policy.compute %}{% blocktrans with compute=policy.compute.name %}Every VM of {{ compute }}{% endblocktrans %}{% elif policy.tag %}{% blocktrans with tag=policy.tag.name %}VMs tagged {{ tag }}{% endblocktrans %}{% else %}{% blocktrans count counter=policy.vm_count %}{{ counter }} VM{% plural %}{{ counter }} VMs{% endblocktrans %}{% endif %}</td>
<td>{{ policy.target.name }}</td>
<td>{{ policy.time|time:"H:i" }}</td>

View file

@ -10,45 +10,64 @@
{% block page_heading %}<a href="{% url 'vmbackups:policies' %}">{% trans "Schedules" %}</a> / {{ policy.name }}{% endblock page_heading %}
{% block content %}
<p class="text-body-secondary">{% blocktrans with owner=policy.owner.username|default:"–" %}Its jobs run as {{ owner }}, who saved it last.{% endblocktrans %}</p>
<div class="row g-4">
<div class="col-lg-6">
<div class="card">
<div class="card-body">{% include "vmbackups/policy_form.html" %}</div>
</div>
<form method="post" class="mt-3">
{% csrf_token %}
<button type="submit" name="delete" value="1" class="btn btn-outline-danger"
data-confirm="{% trans "Delete this schedule? Its backups are kept." %}">{% bs_icon 'trash' %} {% trans "Delete schedule" %}</button>
</form>
</div>
<div class="col-lg-6">
<h2 class="h6">{% trans "Runs" %}</h2>
{% if runs %}
<div class="table-responsive">
<table class="table table-sm align-middle">
<thead><tr><th>{% trans "Day" %}</th><th>{% trans "VM" %}</th><th>{% trans "Result" %}</th></tr></thead>
<tbody>
{% for run in runs %}
<tr>
<td class="text-nowrap">{{ run.day|date:"Y-m-d" }}</td>
<td><a href="{% url 'instances:instance' run.instance_id %}">{{ run.instance.name }}</a></td>
<td>
{% if run.state == "submitted" %}{% if run.operation_id %}<a href="{% url 'operations:job' run.operation_id %}">{% trans "Backup job" %}</a>{% else %}{% trans "Started" %}{% endif %}
{% elif run.state == "skipped" %}<span class="badge text-bg-secondary">{% trans "Skipped" %}</span>
{% else %}<span class="badge text-bg-danger">{% trans "Failed" %}</span>{% endif %}
{% if run.note %}<div class="small text-body-secondary">{{ run.note|words }}</div>{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="text-body-secondary">{% trans "No run yet." %}</p>
{% endif %}
</div>
<h2 class="h5">{% blocktrans count days=days|length %}Last day{% plural %}Last {{ days }} days{% endblocktrans %}</h2>
{% if grid %}
<div class="run-grid-scroll mb-2">
<table class="align-middle run-grid">
<thead>
<tr><th scope="col" class="run-grid-vm"><span class="visually-hidden">{% trans "VM" %}</span></th>
{% for day in days %}<th scope="col" class="text-center fw-normal small text-body-secondary{% if forloop.last %} fw-semibold text-body{% endif %}" title="{{ day|date:"Y-m-d" }}">{{ day|date:"j" }}</th>{% endfor %}</tr>
</thead>
<tbody>
{% for vm, runs in grid %}
<tr>
<th scope="row" class="fw-normal text-truncate run-grid-vm"><a href="{% url 'instances:instance' vm.id %}">{{ vm.name }}</a></th>
{% for run in runs %}<td class="text-center">
{% if run %}{% blocktrans asvar mark with day=run.day|date:"Y-m-d" vm=vm.name outcome=run.outcome_label %}{{ day }}, {{ vm }}: {{ outcome }}{% endblocktrans %}
{% if run.operation_id %}<a class="run-mark run-{{ run.outcome }}" href="{% url 'operations:job' run.operation_id %}" title="{{ mark }}" aria-label="{{ mark }}"></a>
{% else %}<span class="run-mark run-{{ run.outcome }}" role="img" title="{{ mark }}" aria-label="{{ mark }}"></span>{% endif %}
{% else %}<span class="run-mark run-none" aria-hidden="true"></span>{% endif %}</td>{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
<p class="small text-body-secondary d-flex flex-wrap gap-3">
<span><span class="run-mark run-succeeded"></span> {% trans "Backed up" %}</span>
<span><span class="run-mark run-failed"></span> {% trans "Failed" %}</span>
<span><span class="run-mark run-skipped"></span> {% trans "Skipped" %}</span>
<span><span class="run-mark run-running"></span> {% trans "Running" %}</span>
<span><span class="run-mark run-none"></span> {% trans "No run" %}</span>
</p>
{% else %}
<p class="text-body-secondary">{% trans "The schedule has no VM." %}</p>
{% endif %}
{% if problems %}
<h2 class="h5 mt-4">{% trans "Not backed up" %}</h2>
<ul class="list-unstyled" id="run-problems">
{% for run in problems %}
<li class="py-2 border-bottom">
<span class="run-mark run-{{ run.outcome }}" aria-hidden="true"></span>
<span class="text-nowrap">{{ run.day|date:"Y-m-d" }}</span>
<a href="{% url 'instances:instance' run.instance_id %}">{{ run.instance.name }}</a>
<span class="text-body-secondary">{{ run.outcome_label }}{% if run.reason %}: {{ run.reason|words }}{% endif %}</span>
{% if run.operation_id %}<a class="ms-1" href="{% url 'operations:job' run.operation_id %}">{% trans "Job" %}</a>{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
<h2 class="h5 mt-4">{% trans "Settings" %}</h2>
<p class="text-body-secondary">{% blocktrans with owner=policy.owner.username|default:"–" %}Its jobs run as {{ owner }}, who saved it last.{% endblocktrans %}</p>
<div class="card" style="max-width: 48rem;">
<div class="card-body">{% include "vmbackups/policy_form.html" %}</div>
</div>
<form method="post" class="mt-3">
{% csrf_token %}
<button type="submit" name="delete" value="1" class="btn btn-outline-danger"
data-confirm="{% trans "Delete this schedule? Its backups are kept." %}">{% bs_icon 'trash' %} {% trans "Delete schedule" %}</button>
</form>
{% endblock %}
{% block script %}
<script src="{% static 'js/tom-select.complete.min.js' %}"></script>

View file

@ -12,6 +12,7 @@ from computes.models import Compute, Tag
from instances.models import Instance
from instances.tests.test_page_controls import PageControls
from logs.models import Logs
from operations.models import Operation
from operations.utils import say
from vmbackups.models import Backup, BackupPolicy, BackupRun, BackupTarget, BackupTargetPool
@ -119,6 +120,51 @@ class PolicyPageTests(TestCase):
self.assertContains(page, "Backup schedule nightly is saved.")
self.assertContains(page, "3 + 4 weekly + 6 monthly")
def add_run(self, policy, vm, days_ago, state=BackupRun.SUBMITTED, job_state=None, note=(), job_error=()):
day = datetime.date.today() - datetime.timedelta(days=days_ago)
job = job_state and Operation.objects.create(kind="backup.create", username="pp_admin", submission_key=f"{vm.pk}-{day}",
resource="r", state=job_state, error=list(job_error))
return BackupRun.objects.create(policy=policy, instance=vm, day=day, state=state, operation=job, note=list(note))
def test_the_runs_of_the_last_14_days(self):
policy = self.schedule()
self.add_run(policy, self.vm1, 0, job_state=Operation.SUCCEEDED)
failed = self.add_run(policy, self.vm1, 1, job_state=Operation.FAILED, job_error=say("The guest agent did not answer"))
self.add_run(policy, self.vm1, 2, BackupRun.SKIPPED, note=say("The host was in maintenance"))
self.add_run(policy, self.vm1, 14, BackupRun.FAILED) # before the 14 days
self.add_run(policy, self.vm1, -1, BackupRun.FAILED) # after them: the time zone moved west
self.add_run(policy, self.vm3, 3, job_state=Operation.SUCCEEDED) # a VM the schedule no longer backs up
page = lxml_html.fromstring(self.client.get(reverse("vmbackups:policy", args=[policy.pk])).content)
rows = page.xpath("//table[contains(@class, 'run-grid')]/tbody/tr")
self.assertEqual([row.xpath("string(th)") for row in rows], ["vm1", "vm3"])
marks = [mark.get("class").split()[1] for mark in rows[0].xpath(".//*[contains(@class, 'run-mark')]")]
self.assertEqual(marks, ["run-none"] * 11 + ["run-skipped", "run-failed", "run-succeeded"])
self.assertEqual(rows[0].xpath(".//a[contains(@class, 'run-failed')]/@href"),
[reverse("operations:job", args=[failed.operation_id])])
problems = [" ".join(item.text_content().split()) for item in page.xpath("//ul[@id='run-problems']/li")]
self.assertEqual(len(problems), 2)
self.assertIn("vm1 Failed: The guest agent did not answer", problems[0])
self.assertIn("vm1 Skipped: The host was in maintenance", problems[1])
def test_the_list_marks_a_day_by_its_worst_run(self):
policy = self.schedule()
policy.instances.add(self.vm3)
self.add_run(policy, self.vm1, 1, job_state=Operation.SUCCEEDED)
self.add_run(policy, self.vm3, 1, job_state=Operation.FAILED)
self.add_run(policy, self.vm1, 0, job_state=Operation.RUNNING)
self.add_run(policy, self.vm3, 0, job_state=Operation.SUCCEEDED)
page = lxml_html.fromstring(self.client.get(reverse("vmbackups:policies")).content)
strip = page.xpath("//a[contains(@class, 'run-days')]") # one link to the schedule, for touch and keyboard
self.assertEqual(strip[0].get("href"), reverse("vmbackups:policy", args=[policy.pk]))
marks = strip[0].xpath("./span")
self.assertEqual(len(marks), 14)
yesterday = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
self.assertEqual((marks[-2].get("class"), marks[-2].get("title")),
("run-mark run-failed", f"{yesterday}: 1 failed, 1 backed up"))
self.assertEqual(marks[-1].get("class"), "run-mark run-running")
self.assertTrue(marks[-1].get("title").endswith(": 1 running, 1 backed up"))
self.assertEqual(marks[0].get("class"), "run-mark run-none")
def test_delete_keeps_the_backups(self):
policy = self.schedule()
backup = Backup.objects.create(target=self.target, instance=self.vm1, vm_uuid=self.vm1.uuid, vm_name="vm1",

View file

@ -6,6 +6,7 @@ from django.test import TestCase
from computes.models import Compute
from instances.models import Instance
from operations.models import Operation
from vmbackups.models import Backup, BackupPolicy, BackupRun, BackupTarget
@ -24,6 +25,46 @@ class PolicyModelTests(TestCase):
with self.assertRaises(IntegrityError):
BackupRun.objects.create(policy=self.policy, instance=self.vm, day=datetime.date(2026, 11, 17))
def test_a_run_comes_to_what_its_job_did(self):
def outcome(state, job_state=None):
job = job_state and Operation.objects.create(kind="backup.create", username="pm_admin", submission_key=job_state,
resource="r", state=job_state)
return BackupRun(policy=self.policy, instance=self.vm, state=state, operation=job).outcome
self.assertEqual(outcome(BackupRun.SKIPPED), BackupRun.SKIPPED)
self.assertEqual(outcome(BackupRun.FAILED), BackupRun.FAILED)
self.assertEqual(outcome(BackupRun.SUBMITTED, Operation.SUCCEEDED), BackupRun.SUCCEEDED)
self.assertEqual(outcome(BackupRun.SUBMITTED, Operation.QUEUED), BackupRun.RUNNING)
self.assertEqual(outcome(BackupRun.SUBMITTED, Operation.RUNNING), BackupRun.RUNNING)
for job_state in (Operation.FAILED, Operation.CANCELLED, Operation.UNCERTAIN): # no backup came of it
self.assertEqual(outcome(BackupRun.SUBMITTED, job_state), BackupRun.FAILED)
def test_a_run_keeps_what_its_job_came_to_when_the_job_history_drops_the_job(self):
from django.utils import timezone
from operations.utils import say
from operations.worker import housekeeping
old = timezone.now() - datetime.timedelta(days=400)
runs = {}
for n, (job_state, error) in enumerate([(Operation.SUCCEEDED, []), (Operation.FAILED, say("Disk %(d)s gone", d="vda")),
(Operation.CANCELLED, [])]):
job = Operation.objects.create(kind="backup.create", username="pm_admin", submission_key=str(n), resource="r",
state=job_state, error=error, finished_at=old)
vm = Instance.objects.create(compute=self.compute, name=f"k{n}", uuid=f"61616161-0000-4000-8000-00000000010{n}")
runs[job_state] = BackupRun.objects.create(policy=self.policy, instance=vm, day=datetime.date(2026, 11, 17),
state=BackupRun.SUBMITTED, operation=job)
self.assertEqual(runs[Operation.CANCELLED].reason, say("The job was cancelled")) # a job cancelled without an error
housekeeping()
self.assertFalse(Operation.objects.exists())
for run in runs.values():
run.refresh_from_db()
self.assertEqual((runs[Operation.SUCCEEDED].outcome, runs[Operation.SUCCEEDED].note), (BackupRun.SUCCEEDED, []))
self.assertEqual((runs[Operation.FAILED].outcome, runs[Operation.FAILED].reason),
(BackupRun.FAILED, say("Disk %(d)s gone", d="vda")))
self.assertEqual((runs[Operation.CANCELLED].outcome, runs[Operation.CANCELLED].reason),
(BackupRun.FAILED, say("The job was cancelled")))
def test_a_deleted_policy_keeps_its_backups(self):
backup = Backup.objects.create(target=self.target, instance=self.vm, vm_uuid=self.vm.uuid, vm_name="vm1",
compute_name="h1", policy=self.policy, state=Backup.READY)

View file

@ -156,11 +156,11 @@ class ScheduleTests(TransactionTestCase):
def test_the_window_is_checked_again_after_the_host_answered(self):
self.pass_at(at(2026, 11, 17, 7, 59))
# the host answers the checks only after the window ended
self.proxy.backup_plan.side_effect = lambda: patch_now.start() or {
"definition": "<domain/>", "disks": [], "nvram": None, "left_out": []}
patch_now = patch("django.utils.timezone.now", return_value=at(2026, 11, 17, 8, 30))
self.addCleanup(patch.stopall)
def answer_late(): # the host answers the checks only after the window ended
timezone.now.return_value = at(2026, 11, 17, 8, 30) # the clock started() set
return {"definition": "<domain/>", "disks": [], "nvram": None, "left_out": []}
self.proxy.backup_plan.side_effect = answer_late
with self.assertRaisesMessage(OperationError, "window ended"):
self.started(at(2026, 11, 17, 7, 59, 30), self.creates()[0])
self.assertFalse(Backup.objects.exists())

View file

@ -1,3 +1,5 @@
import datetime
from collections import Counter
from urllib.parse import urlencode
from django.contrib import messages
@ -33,7 +35,7 @@ from vrtManager.util import OperationError
from .forms import PolicyForm, RestoreDiskForm, RestoreForm, TargetForm, TargetPoolForm
from .jobs import _over_names, _over_plan, _proxy, _vm_pool
from .models import Backup, BackupPolicy, BackupTarget
from .models import Backup, BackupPolicy, BackupRun, BackupTarget
from .utils import inside_vm_pool, pending_deletes
@ -351,11 +353,38 @@ def restore_disk(request, uuid):
return render(request, "vmbackups/restore_disk.html", {"backup": backup, "form": form})
HISTORY_DAYS = 14 # the days a schedule's runs are shown for
# a day of a schedule on the list is marked as the first of these its runs came to
WORST_FIRST = (BackupRun.FAILED, BackupRun.SKIPPED, BackupRun.RUNNING, BackupRun.SUCCEEDED)
DAY_COUNTS = {BackupRun.SUCCEEDED: _("%(n)s backed up"), BackupRun.RUNNING: _("%(n)s running"),
BackupRun.FAILED: _("%(n)s failed"), BackupRun.SKIPPED: _("%(n)s skipped")}
def history_days():
"""The local days of the run history, the oldest first."""
today = timezone.localdate()
return [today - datetime.timedelta(days=n) for n in range(HISTORY_DAYS - 1, -1, -1)]
@superuser_only
def policies(request):
"""The backup schedules."""
"""The backup schedules, each with what its runs of each day came to."""
days = history_days()
counts = {} # (schedule id, day) -> Counter of outcomes
runs = (BackupRun.objects.filter(day__range=(days[0], days[-1])).order_by()
.values_list("policy_id", "day", "state", "operation__state").annotate(n=Count("id")))
for policy_id, day, state, job_state, n in runs:
counts.setdefault((policy_id, day), Counter())[BackupRun.outcome_of(state, job_state)] += n
rows = BackupPolicy.objects.select_related("target", "compute", "tag", "owner").annotate(vm_count=Count("instances"))
return render(request, "vmbackups/policies.html", {"policies": rows.order_by("name")})
rows = list(rows.order_by("name"))
for policy in rows:
policy.history = []
for day in days:
day_counts = counts.get((policy.pk, day), Counter())
worst = next((outcome for outcome in WORST_FIRST if day_counts[outcome]), None)
text = ", ".join(str(DAY_COUNTS[o] % {"n": day_counts[o]}) for o in WORST_FIRST if day_counts[o])
policy.history.append({"day": day, "outcome": worst, "text": text})
return render(request, "vmbackups/policies.html", {"policies": rows, "days": days})
@superuser_only
@ -391,6 +420,13 @@ def policy(request, policy_id):
form.save_m2m()
messages.success(request, _("Backup schedule %(name)s is saved.") % {"name": policy.name})
return redirect("vmbackups:policies")
runs = policy.runs.select_related("instance", "operation").order_by("-day", "instance__name")[:200]
return render(request, "vmbackups/policy.html", {"policy": policy, "form": form, "runs": runs,
"time_zone": settings.TIME_ZONE})
days = history_days()
runs = list(policy.runs.filter(day__range=(days[0], days[-1])).select_related("instance", "operation"))
cells = {vm: {} for vm in policy.vms()} # its VMs now, and those it ran for in these days
for run in runs:
cells.setdefault(run.instance, {})[run.day] = run
grid = [(vm, [vm_runs.get(day) for day in days]) for vm, vm_runs in sorted(cells.items(), key=lambda i: i[0].name)]
problems = sorted((run for run in runs if run.outcome in (BackupRun.FAILED, BackupRun.SKIPPED)),
key=lambda run: (run.day, run.instance.name), reverse=True)
return render(request, "vmbackups/policy.html", {"policy": policy, "form": form, "days": days, "grid": grid,
"problems": problems, "time_zone": settings.TIME_ZONE})

View file

@ -103,6 +103,7 @@ USAGE_MAX_WINDOW = 30
USAGE_STATS = VIR_DOMAIN_STATS_CPU_TOTAL | VIR_DOMAIN_STATS_BLOCK | VIR_DOMAIN_STATS_INTERFACE
# seconds the guest agent has to set a password or add a key
AGENT_TIMEOUT = 10
FSTRIM_TIMEOUT = 1800 # a guest trims each file system's free space: minutes on a large one
# libvirt's values; bindings built against older libvirt (Ubuntu 24.04's) lack
# the names, and the code comes from the host's libvirtd
VIR_ERR_AGENT_COMMAND_TIMEOUT = 112
@ -719,14 +720,14 @@ def disk_source(disk):
tuple(tuple(sorted(host.attrib.items())) for host in source.findall("host")))
def agent_command(dom, command, arguments=None):
"""The answer of one guest agent command that waits AGENT_TIMEOUT seconds
def agent_command(dom, command, arguments=None, timeout=AGENT_TIMEOUT):
"""The answer of one guest agent command that waits timeout seconds
at most: libvirt's own calls for it wait for a hung agent indefinitely,
and the domain's agent timeout is shared by every agent call."""
request = {"execute": command}
if arguments is not None:
request["arguments"] = arguments
return json.loads(qemuAgentCommand(dom, json.dumps(request), AGENT_TIMEOUT, 0))["return"]
return json.loads(qemuAgentCommand(dom, json.dumps(request), timeout, 0))["return"]
def agent_interfaces(dom):
@ -2978,6 +2979,32 @@ class wvmInstance(wvmConnect):
def abort_backup(self):
self.instance.abortJob()
def screenshot(self):
"""The running or paused VM's screen as libvirt gives it: (MIME type, bytes); PNG from
libvirt 9.x with QEMU 7.1 on, PPM before."""
stream = self.wvm.newStream(0)
try:
mime = self.instance.screenshot(stream, 0, 0)
data = bytearray()
stream.recvAll(lambda _stream, chunk, buffer: buffer.extend(chunk), data)
stream.finish()
except libvirtError:
with contextlib.suppress(libvirtError):
stream.abort()
raise
return mime, bytes(data)
def fstrim(self):
"""Has the guest agent trim the free space of each mounted file system, waiting
FSTRIM_TIMEOUT seconds at most: [{"path", "trimmed": bytes or None, "error": text or None}].
The image files shrink only for disks whose discard mode is unmap."""
self.ping_agent()
answer = agent_command(self.instance, "guest-fstrim", timeout=FSTRIM_TIMEOUT)
paths = answer.get("paths") if isinstance(answer, dict) else None
return [{"path": str(p["path"]), "trimmed": p.get("trimmed") if type(p.get("trimmed")) is int else None,
"error": str(p["error"]) if p.get("error") else None}
for p in paths or [] if isinstance(p, dict) and p.get("path")]
def ping_agent(self):
"""A frozen or dead agent fails here in AGENT_TIMEOUT seconds. The
freeze that follows is libvirt's, without a timeout: a timed freeze

View file

@ -237,6 +237,7 @@ LANGUAGES = [
("en", "English"),
("tr", "Türkçe"),
("zh-hans", "简体中文"),
("uk", "Українська"),
]
# the installer writes the server's zone; Docker takes TZ (Django sets the process's TZ from this)

View file

@ -105,6 +105,7 @@ POWER_AND_CONSOLE = {
"compute-instance-powercycle",
"compute-instance-forceoff",
"instances:getvvfile",
"instances:screen",
# vdi_url is also allowed for owners, but answers 404 here because the
# test compute is unreachable; see the console rule tests.
}

View file

@ -0,0 +1,33 @@
"""Each translated language of LANGUAGES gets its locale/ django.mo: Django
finds the catalog for the language code (zh-hans reads locale/zh) and every
message comes out as the catalog translates it, none covered by another
catalog."""
import gettext
from django.conf import settings
from django.test import SimpleTestCase
from django.utils import translation
CATALOG_DIRS = {"tr": "tr", "zh-hans": "zh", "uk": "uk"}
class CatalogTests(SimpleTestCase):
def test_every_language_has_a_catalog(self):
self.assertEqual({code for code, _ in settings.LANGUAGES} - {"en"}, set(CATALOG_DIRS))
def test_every_message_is_translated_as_its_catalog_says(self):
for code, directory in CATALOG_DIRS.items():
path = settings.BASE_DIR / "locale" / directory / "LC_MESSAGES" / "django.mo"
with open(path, "rb") as mo:
catalog = gettext.GNUTranslations(mo)._catalog
messages = {key: text for key, text in catalog.items() if isinstance(key, str) and key}
self.assertGreater(len(messages), 100, path)
with translation.override(code):
for key, text in messages.items():
context, _, message = key.rpartition("\x04")
with self.subTest(language=code, message=message):
if context:
self.assertEqual(translation.pgettext(context, message), text)
else:
self.assertEqual(translation.gettext(message), text)

View file

@ -0,0 +1,48 @@
"""The menu on every page: the page's own section marked, the count of unfinished jobs, the languages."""
from django.contrib.auth import get_user_model
from django.test import TestCase
from lxml import html
from operations.models import Operation
class NavbarTests(TestCase):
def setUp(self):
users = get_user_model().objects
self.owner = users.create_user("navbar_owner", password="pw")
self.other = users.create_user("navbar_other", password="pw")
self.client.force_login(self.owner)
def menu(self, url="/jobs/"):
return html.fromstring(self.client.get(url).content).get_element_by_id("navbar")
def job(self, user, state, key):
Operation.objects.create(kind="test.noop", user=user, username=user.username, state=state,
submission_key=key, resource="r", resource_label="c/vm")
def test_the_pages_section_is_marked_for_eyes_and_screen_readers(self):
current = self.menu().xpath('.//a[@aria-current="page"]')
self.assertEqual([a.get("href") for a in current], ["/jobs/"])
self.assertIn("active", current[0].get("class").split())
def test_jobs_shows_how_many_of_ones_own_jobs_are_not_finished(self):
self.job(self.owner, Operation.QUEUED, "a")
self.job(self.owner, Operation.RUNNING, "b")
self.job(self.owner, Operation.SUCCEEDED, "c")
self.job(self.other, Operation.RUNNING, "d") # another user's job is not counted for this one
badge = self.menu().xpath('.//a[@href="/jobs/"]//span[contains(@class, "badge")]')[0]
self.assertEqual(badge.xpath('./span[@aria-hidden="true"]')[0].text, "2")
self.assertEqual(badge.xpath('./span[@class="visually-hidden"]')[0].text, "2 jobs not finished")
def test_no_badge_without_unfinished_jobs(self):
self.job(self.owner, Operation.FAILED, "a")
self.assertEqual(self.menu().xpath('.//span[contains(@class, "badge")]'), [])
def test_a_language_button_sets_the_language_and_comes_back_to_the_page(self):
buttons = self.menu().xpath('.//form[@action="/i18n/setlang/"]//button[@name="language"]')
self.assertEqual([b.get("value") for b in buttons], ["en", "tr", "zh-hans", "uk"])
self.assertEqual([b.get("value") for b in buttons if b.get("aria-current")], ["en"])
answer = self.client.post("/i18n/setlang/", {"language": "tr"}, HTTP_REFERER="http://testserver/jobs/")
self.assertEqual(answer["Location"], "http://testserver/jobs/")
self.assertEqual(self.client.cookies["django_language"].value, "tr")