1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

Merge pull request #692 from catborise/upstream-v5

VM backups, tags, host maintenance and Balance, alerts and one-command updates (fork v4.3.0 to v5.0.0 and after)
This commit is contained in:
catborise 2026-11-23 10:40:08 +03:00 • committed by GitHub
commit 90c2bfe5b5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
376 changed files with 28024 additions and 4409 deletions

View file

@ -13,9 +13,8 @@ backups
**/*.swo
**/console/cert.pem*
**/dhcpd.*
webvirtcloud/settings.py
# the copy the README has Docker users keep next to the compose file
settings.py
# a settings.py older versions had Docker users mount from next to the compose file
/settings.py
**/staticfiles
# virtualenvs, caches and editor files

69
.github/workflows/installer.yml vendored Normal file
View file

@ -0,0 +1,69 @@
name: Installer
# install.sh on each supported distribution, and update.sh from the last
# release on two (dev/test-installer.sh): on each
# push to master (the panel it installs changed), on a pull request that
# changes the installer or what it installs, and weekly, as the
# distributions' packages change under it
on:
push:
branches: [master]
pull_request:
paths:
- install.sh
- webvirtcloud.sh
- conf/**
- update.sh
- dev/test-installer.sh
- .github/workflows/installer.yml
schedule:
- cron: '0 4 * * 1'
workflow_dispatch:
permissions:
contents: read
jobs:
install:
name: ${{ matrix.image }}
runs-on: ubuntu-latest
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
image:
- ubuntu:22.04
- ubuntu:24.04
- ubuntu:26.04
- debian:12
- debian:13
- almalinux:10
- opensuse/leap:15.6
- opensuse/leap:16.0
- openeuler/openeuler:24.03-lts
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Install and check the panel
run: dev/test-installer.sh "${{ matrix.image }}"
# update.sh from the last release, as an operator runs it
update:
name: ${{ matrix.image }} from v4.3.0
runs-on: ubuntu-latest
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
image:
- debian:13
- almalinux:10
steps:
- name: Checkout Code
uses: actions/checkout@v4
with:
fetch-depth: 0 # the release's commit
- name: Install v4.3.0, update to this commit and check the panel
run: dev/test-installer.sh "${{ matrix.image }}" v4.3.0

View file

@ -42,6 +42,7 @@ jobs:
--health-retries 10
env:
SECRET_KEY: ci-only-not-a-secret
WEBVIRTCLOUD_DB_HOST: ${{ matrix.database == 'postgresql' && 'localhost' || '' }}
WEBVIRTCLOUD_DB_PASSWORD: webvirtcloud
@ -79,12 +80,6 @@ jobs:
python -m pip install --upgrade pip setuptools
pip install -r dev/requirements.txt
- name: Configure WebVirtCloud Settings
run: |
cp webvirtcloud/settings.py.template webvirtcloud/settings.py
SECRET_KEY=$(python -c 'import secrets; print(secrets.token_urlsafe(50))')
sed -i "s|^SECRET_KEY = .*|SECRET_KEY = \"${SECRET_KEY}\"|" webvirtcloud/settings.py
- name: Check For Missing Migrations
run: python manage.py makemigrations --check --dry-run
@ -152,8 +147,7 @@ jobs:
- name: Plant Secret Sentinels
run: |
mkdir -p data
for f in data/secret_key data/admin_password settings.py webvirtcloud/settings.py.bak \
'webvirtcloud/settings.py~' webvirtcloud/.settings.py.swp; do
for f in data/secret_key data/admin_password data/local_settings.py data/local_settings.py~ settings.py; do
echo sentinel > "$f"
done
@ -175,8 +169,7 @@ jobs:
run: |
docker run --rm --entrypoint sh webvirtcloud:ci -c '
cd /srv/webvirtcloud
for f in data/secret_key data/admin_password settings.py webvirtcloud/settings.py.bak \
"webvirtcloud/settings.py~" webvirtcloud/.settings.py.swp; do
for f in data/secret_key data/admin_password data/local_settings.py data/local_settings.py~ settings.py; do
if [ -e "$f" ]; then echo "$f is in the image"; exit 1; fi
done'

2
.gitignore vendored
View file

@ -12,8 +12,6 @@ test_db*.sqlite3*
console/cert.pem*
tags
dhcpd.*
webvirtcloud/settings.py
/settings.py
.coverage
htmlcov
*.log

View file

@ -51,11 +51,9 @@ COPY --from=build /srv/webvirtcloud/venv venv
COPY . .
# The code stays root's: the panel writes only to its data and backup
# directories (made its own at start). A settings file and a key exist only
# for collectstatic.
RUN cp webvirtcloud/settings.py.template webvirtcloud/settings.py \
&& SECRET_KEY=build-only WEBVIRTCLOUD_LOG_FILE=/tmp/build.log venv/bin/python3 manage.py collectstatic --noinput \
&& rm -f webvirtcloud/settings.py /tmp/build.log # the log handler makes the file at its first line only
# directories (made its own at start). A key exists only for collectstatic.
RUN SECRET_KEY=build-only WEBVIRTCLOUD_LOG_FILE=/tmp/build.log venv/bin/python3 manage.py collectstatic --noinput \
&& rm -f /tmp/build.log # the log handler makes the file at its first line only
COPY conf/docker/nginx.conf /etc/nginx/nginx.conf
COPY conf/nginx/webvirtcloud.conf /etc/nginx/conf.d/

304
README.md
View file

@ -32,12 +32,15 @@ WebVirtCloud and `virt-manager`/`virsh` can manage the same libvirt host **concu
## Features
* QEMU/KVM hypervisor management (multiple compute nodes), with each host's capacity and what its VMs were given
* Virtual machine lifecycle: create, delete, power management, clone (also of a running VM, with libvirt 11.10 or later), migrate (with or without shared storage), disk moves between pools
* Long operations (create, clone, delete, snapshots, migration, disk moves, ISO upload) run as jobs that the page follows; a queued job can be cancelled, and a running clone, migration, disk move or ISO upload too
* Host maintenance: a host in maintenance takes no new VMs, incoming migrations or VM starts; putting it in maintenance offers to migrate its VMs away with Bulk Migrate
* Balance: proposes migrations that even out the running VMs' memory, then vCPUs, as a share of each host's size
* Virtual machine lifecycle: create, delete, power management, clone (also of a running VM, with libvirt 11.10 or later), migrate (with or without shared storage), bulk migrate (a host's chosen VMs to another host, the chosen number at once), disk moves between pools
* Long operations (create, clone, delete, bulk power, snapshots, migration, disk moves, ISO upload, downloads from a URL, VM backups) run as jobs that the page follows; a queued job can be cancelled, and a running migration, ISO upload, download, backup or verification and the copy of a running VM (clone, disk move) too
* External snapshots (memory optional; without memory, guest file systems can be frozen through the agent)
* **External change detection:** VMs created, deleted or renamed via `virt-manager` or `virsh` are reconciled into the database automatically
* Real-time hypervisor and VM statistics (CPU, RAM, disk, network)
* Storage pool and volume management
* Real-time host statistics (CPU, RAM) and VM statistics (CPU, RAM, disk, network)
* A VM a fault stopped or paused says why (a disk error such as a full storage, a guest crash or kernel panic, its watchdog); its Settings tab chooses whether a guest that crashes, or hangs once it arms its watchdog, is restarted or stopped (new VMs get the panic device and watchdog this needs, older ones with the choice)
* Storage pool and volume management; a superuser downloads a volume from its pool page (not one a running VM uses), or makes one from a file at a URL
* Network (with DHCP leases), interface, network filter and secret management
* PCI and USB devices of the host given to VMs
* UEFI Secure Boot and TPM 2.0 for new VMs, as Windows 11 needs
@ -46,10 +49,13 @@ WebVirtCloud and `virt-manager`/`virsh` can manage the same libvirt host **concu
* 2FA (OTP / TOTP) and failed-login lockout
* SSH public key and root password management (guest agent for a running VM, gstfsd for a shut-off one)
* Finding VMs by IP or MAC address, and a VM report as an Excel file
* Tags on VMs and hosts, set by superusers: the lists filter by them, Bulk Migrate chooses VMs by them and a backup schedule backs up every VM with a chosen tag (templates left out)
* Protected VMs, set by superusers on the VM's Settings tab: not deleted and not restored over until the protection is turned off
* An audit log of who changed what, with its result
* Cloud-init datasource interface (OpenStack metadata compatible) and NoCloud seed media
* REST API — OpenAPI 3.0 (Swagger & ReDoc), with API tokens
* LDAP / Active Directory integration (optional)
* VM backups, of a running or shut-off VM, into a storage pool of your choice; a backup is restored as a new VM, over its own shut-off VM, or one disk as a new volume
* Daily backups of the panel, with an optional off-site copy (restic over SFTP)
* English, Turkish and Simplified Chinese
@ -57,15 +63,15 @@ WebVirtCloud and `virt-manager`/`virsh` can manage the same libvirt host **concu
1. [Installation](#installation): [installer](#installer), [Docker](#docker), [manual](#manual-installation), [first login](#first-login)
2. [Adding a Compute Node](#adding-a-compute-node)
3. [Configuration](#configuration): [environment variables](#environment-variables), [HTTPS and reverse proxy](#https-and-reverse-proxy), [cloud-init datasource](#cloud-init-datasource), [LDAP](#ldap), [OTP](#two-factor-login-otp), [serial console](#serial-console)
4. [Backups](#backups): [off-site copy](#off-site-copy)
3. [Configuration](#configuration): [environment variables](#environment-variables), [local settings](#local-settings), [HTTPS and reverse proxy](#https-and-reverse-proxy), [cloud-init datasource](#cloud-init-datasource), [LDAP](#ldap), [OTP](#two-factor-login-otp), [serial console](#serial-console)
4. [Backups](#backups): [off-site copy](#off-site-copy), [VM backups](#vm-backups)
5. [Updating](#updating): [Docker](#docker-1), [installer and manual](#installer-and-manual-installation), [restore and rollback](#restore-and-rollback), [moving to a new machine](#moving-to-a-new-machine), [behavior changes](#behavior-changes)
6. [Usage](#usage): [users and permissions](#users-roles-and-permissions), [REST API](#rest-api), [screenshots](#screenshots)
7. [Development](#development)
## Installation
The installer supports Ubuntu 22.04 / 24.04 / 26.04, Debian 12 / 13, RHEL / Rocky Linux / AlmaLinux / Oracle Linux 10, openEuler 24.03 LTS, openSUSE Leap 15.x / Tumbleweed and SLES 15; the panel runs on a virtual machine, a physical host or a KVM host itself and needs Python 3.10 or newer. CI tests Python 3.10–3.14 on Ubuntu (sqlite, and PostgreSQL on 3.12) and the Docker image; the distro installs are not tested in CI. Pick one of the three ways below, then do the [first login](#first-login).
The installer supports Ubuntu 22.04 / 24.04 / 26.04, Debian 12 / 13, RHEL / Rocky Linux / AlmaLinux / Oracle Linux 10, openEuler 24.03 LTS, openSUSE Leap 15.x / 16.0 / Tumbleweed and SLES 15; the panel runs on a virtual machine, a physical host or a KVM host itself and needs Python 3.10 or newer. CI tests Python 3.10–3.14 on Ubuntu (sqlite, and PostgreSQL on 3.12), the Docker image, and the installer on Ubuntu 22.04 / 24.04 / 26.04, Debian 12 / 13, AlmaLinux 10, openEuler 24.03 and openSUSE Leap 15.6 / 16.0 (`dev/test-installer.sh`). Pick one of the three ways below, then do the [first login](#first-login).
### Installer
@ -75,7 +81,7 @@ chmod 744 install.sh
sudo ./install.sh
```
The installer writes the server's names and IPs to `ALLOWED_HOSTS`. Running it again keeps `settings.py`, the database, the secret key and the main nginx config, but replaces `/etc/nginx/conf.d/webvirtcloud.conf` and the systemd units; back up your own lines in the nginx config (TLS) first. Put your own service settings in `/etc/default/webvirtcloud` or in drop-ins (`systemctl edit webvirt-cloud`), which a re-run keeps.
The installer writes the server's names and IPs to `ALLOWED_HOSTS`. Running it again keeps `data/local_settings.py` (and its noVNC port, whatever the answer), the database, the secret key and the main nginx config, but replaces `/etc/nginx/conf.d/webvirtcloud.conf` and the systemd units; back up your own lines in the nginx config (TLS) first. Put your own service settings in `/etc/default/webvirtcloud` or in drop-ins (`systemctl edit webvirt-cloud`), which a re-run keeps.
### Docker
@ -114,10 +120,10 @@ apt-get update && apt-get -y install git python3-venv python3-dev python3-lxml p
git clone https://github.com/retspen/webvirtcloud /srv/webvirtcloud
cd /srv/webvirtcloud
# 3. Settings, allowed hosts and secret key
cp webvirtcloud/settings.py.template webvirtcloud/settings.py
sed -i 's|^ALLOWED_HOSTS = .*|ALLOWED_HOSTS = ["wvc.example.com", "192.0.2.10", "localhost", "127.0.0.1", "[::1]"]|' webvirtcloud/settings.py
mkdir -p data && python3 conf/secret_generator.py > data/secret_key && chmod 600 data/secret_key
# 3. This installation's settings (data/local_settings.py, see Configuration) and secret key
mkdir -p -m 700 data && (umask 077 &&
echo 'ALLOWED_HOSTS += ["wvc.example.com", "192.0.2.10"]' > data/local_settings.py &&
python3 conf/secret_generator.py > data/secret_key)
# 4. Virtualenv and dependencies
python3 -m venv --system-site-packages venv
@ -135,8 +141,8 @@ rm -f /etc/nginx/sites-enabled/default
# 7. Ownership, private files, start (the groups let the services reach a local libvirt and KVM)
chown -R www-data:www-data /srv/webvirtcloud
usermod -a -G libvirt,kvm www-data 2>/dev/null || true # on a KVM host
chmod 700 data && chmod 600 webvirtcloud/settings.py db.sqlite3
for g in libvirt kvm; do usermod -a -G $g www-data 2>/dev/null || true; done # on a KVM host
chmod 700 data && chmod 600 data/local_settings.py data/secret_key && { [ ! -f db.sqlite3 ] || chmod 600 db.sqlite3; }
systemctl daemon-reload && systemctl enable --now webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker webvirt-backup.timer
nginx -t && systemctl restart nginx
```
@ -145,17 +151,17 @@ nginx -t && systemctl restart nginx
```bash
# 1. System packages (libvirt-devel is in the CRB repository)
dnf -y install epel-release && crb enable
dnf -y install epel-release && crb enable # Rocky / AlmaLinux; on RHEL and Oracle Linux enable their CodeReady Builder repository and EPEL as their documentation says
dnf -y install git python3-devel libvirt-devel python3-libvirt python3-lxml cyrus-sasl-md5 openssl-devel glibc gcc nginx python3-libguestfs iproute-tc policycoreutils-python-utils
# 2. Code
git clone https://github.com/retspen/webvirtcloud /srv/webvirtcloud
cd /srv/webvirtcloud
# 3. Settings, allowed hosts and secret key
cp webvirtcloud/settings.py.template webvirtcloud/settings.py
sed -i 's|^ALLOWED_HOSTS = .*|ALLOWED_HOSTS = ["wvc.example.com", "192.0.2.10", "localhost", "127.0.0.1", "[::1]"]|' webvirtcloud/settings.py
mkdir -p data && python3 conf/secret_generator.py > data/secret_key && chmod 600 data/secret_key
# 3. This installation's settings (data/local_settings.py, see Configuration) and secret key
mkdir -p -m 700 data && (umask 077 &&
echo 'ALLOWED_HOSTS += ["wvc.example.com", "192.0.2.10"]' > data/local_settings.py &&
python3 conf/secret_generator.py > data/secret_key)
# 4. Virtualenv and dependencies
python3 -m venv --system-site-packages venv
@ -174,8 +180,8 @@ cp conf/nginx/webvirtcloud.conf /etc/nginx/conf.d/
# 7. Ownership, private files, SELinux, firewall, start (the groups let the services reach a local libvirt and KVM)
chown -R nginx:nginx /srv/webvirtcloud
usermod -a -G libvirt,kvm nginx 2>/dev/null || true # on a KVM host
chmod 700 data && chmod 600 webvirtcloud/settings.py db.sqlite3
for g in libvirt kvm; do usermod -a -G $g nginx 2>/dev/null || true; done # on a KVM host
chmod 700 data && chmod 600 data/local_settings.py data/secret_key && { [ ! -f db.sqlite3 ] || chmod 600 db.sqlite3; }
# nginx reads the static files, systemd runs the virtualenv's programs
semanage fcontext -a -t httpd_sys_content_t "/srv/webvirtcloud(/.*)?" 2>/dev/null || true
semanage fcontext -a -t bin_t "/srv/webvirtcloud/venv/bin(/.*)?" 2>/dev/null || true
@ -187,20 +193,22 @@ systemctl daemon-reload && systemctl enable --now webvirt-cloud webvirt-novncd w
systemctl enable nginx && nginx -t && systemctl restart nginx
```
#### openSUSE Leap 15.x / Tumbleweed, SLES 15
#### openSUSE Leap 15.x / 16.0 / Tumbleweed, SLES 15
On SLES 15, enable the Python 3 module and SUSE Package Hub first (`SUSEConnect -p sle-module-python3/15.7/x86_64` and `SUSEConnect -p PackageHub/15.7/x86_64`, with your service pack); the installer needs them too.
```bash
# 1. System packages (Python 3.11 stack)
# 1. System packages (Python 3.11 stack; on Leap 16 and Tumbleweed python313-* packages and python3.13 below)
zypper --non-interactive install -y git hostname python311 python311-base python311-devel python311-pip python311-libvirt-python python311-lxml libvirt-devel libopenssl-devel gcc pkg-config nginx
# 2. Code
git clone https://github.com/retspen/webvirtcloud /srv/webvirtcloud
cd /srv/webvirtcloud
# 3. Settings, allowed hosts and secret key
cp webvirtcloud/settings.py.template webvirtcloud/settings.py
sed -i 's|^ALLOWED_HOSTS = .*|ALLOWED_HOSTS = ["wvc.example.com", "192.0.2.10", "localhost", "127.0.0.1", "[::1]"]|' webvirtcloud/settings.py
mkdir -p data && python3.11 conf/secret_generator.py > data/secret_key && chmod 600 data/secret_key
# 3. This installation's settings (data/local_settings.py, see Configuration) and secret key
mkdir -p -m 700 data && (umask 077 &&
echo 'ALLOWED_HOSTS += ["wvc.example.com", "192.0.2.10"]' > data/local_settings.py &&
python3.11 conf/secret_generator.py > data/secret_key)
# 4. Virtualenv and dependencies
python3.11 -m venv --system-site-packages venv
@ -219,8 +227,8 @@ cp conf/nginx/webvirtcloud.conf /etc/nginx/conf.d/
# 7. Ownership, private files, start (the groups let the services reach a local libvirt and KVM)
chown -R nginx:nginx /srv/webvirtcloud
usermod -a -G libvirt,kvm nginx 2>/dev/null || true # on a KVM host
chmod 700 data && chmod 600 webvirtcloud/settings.py db.sqlite3
for g in libvirt kvm; do usermod -a -G $g nginx 2>/dev/null || true; done # on a KVM host
chmod 700 data && chmod 600 data/local_settings.py data/secret_key && { [ ! -f db.sqlite3 ] || chmod 600 db.sqlite3; }
systemctl daemon-reload && systemctl enable --now webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker webvirt-backup.timer
systemctl enable nginx && nginx -t && systemctl restart nginx
```
@ -240,7 +248,7 @@ Sign in at `http://<server-ip>`; you must set a new password at the first login,
A compute node is a KVM host the panel manages over libvirt.
1. Install KVM and libvirt. The bootstrap script handles Ubuntu, Debian, CentOS, Fedora, Rocky Linux and AlmaLinux 10, openEuler 24.03 LTS, openSUSE and SLES. On RHEL, which needs EPEL from its release RPM, install the `qemu-kvm`, `libvirt` and `python3-libguestfs` (for gstfsd, step 3) packages yourself and enable `virtqemud.socket` (plus `virtproxyd-tcp.socket` for TCP):
1. Install KVM and libvirt. The bootstrap script handles Ubuntu, Debian, CentOS, Fedora, Rocky Linux and AlmaLinux 10, openEuler 24.03 LTS, openSUSE and SLES. On RHEL, which needs EPEL from its release RPM, install the `qemu-kvm`, `libvirt` and `python3-libguestfs` (for gstfsd, step 3) packages yourself and enable the sockets of the daemons the panel talks to, `virt{qemu,network,storage,nodedev,nwfilter,secret,interface}d.socket` (for TCP also `virtproxyd-tcp.socket` and SASL, set up as `dev/libvirt-bootstrap.sh` does on EL10):
```bash
curl -fsSL https://raw.githubusercontent.com/retspen/webvirtcloud/master/dev/libvirt-bootstrap.sh | sudo sh
@ -325,9 +333,12 @@ Firewall: the compute's VNC ports (`5900`–`65535`) must accept connections **o
### Migration
- **Shared storage:** define it as a storage pool on every host. A VM migrates when its disk, backing and ISO files and block devices are volumes of the destination's pools.
- **Hosts that differ:** the Computes page's box above the hosts names a host that lacks an active network, a network filter or a secret the VMs of another host use, or has a filter of that name with other rules: the migration check refuses moving those VMs there.
- **Address:** a migrating VM goes to the destination's address on the Computes page; for a dedicated migration network, set the compute's **Migration address** on its edit page.
- **Without shared storage:** after choosing the destination, the **Disks** list shows each disk and the destination pools that can take a copy (directory, filesystem and NFS pools; a pool with a file of the same name refuses it); a disk on storage both hosts share can stay there. Plain raw or qcow2 disks without a backing file are copied, through the destination's migration port range (49152-49215 by default). **Delete the source files of copied disks** removes them after the migration, unless another VM or volume uses them.
- **Shut-off VMs:** a shut-off VM moves offline, with its NVRAM file (UEFI). When its disks are copied or it has a TPM, it is started paused for the migration instead (its CPUs never run) and shut off on the destination.
- **Encryption:** QEMU sends a VM's memory and copied disks in the clear. With **Encrypt migrations (TLS)** ticked on both hosts' edit pages (Advanced), it sends them over TLS. Each host needs QEMU's certificates from one CA: `ca-cert.pem`, `server-cert.pem`, `server-key.pem`, `client-cert.pem` and `client-key.pem` in `/etc/pki/qemu`, readable by QEMU (owner `root`, group the one QEMU runs as: `qemu` on the RHEL family and openSUSE, `kvm` on Debian and Ubuntu; keys `0640`), the server certificate naming the host's migration address (or the address the panel reaches it at) as it is written there, a name or an IP. A host without them refuses the migration before anything moves: `Unable to access credentials /etc/pki/qemu/ca-cert.pem`.
- **Bandwidth:** **Settings → Migrations** gives libvirt a limit in MiB/s, so a migration leaves room for the VMs' own traffic. It applies to the memory transfer until the final switchover and to each copied disk on its own (two disks may take twice it); a shut-off VM's UEFI variables file is not limited. 0 leaves libvirt's default, no limit unless one was set on the host.
If libvirt warns `Host SMBIOS information is not available`, install `dmidecode` (`apt-get`, `dnf` or `zypper install -y dmidecode`) and restart `libvirtd` (`virtqemud` on the RHEL family 10).
@ -344,7 +355,7 @@ If libvirt warns `Host SMBIOS information is not available`, install `dmidecode`
| `WEBVIRTCLOUD_DEBUG=1` | Django debug mode: error pages show the traceback and settings; for trying things out only, never on a panel others use |
| `WEBVIRTCLOUD_DB_HOST` | use PostgreSQL instead of sqlite (new installs); `WEBVIRTCLOUD_DB_PORT`/`_NAME`/`_USER`/`_PASSWORD` default to 5432/webvirtcloud/webvirtcloud/empty |
| `EMAIL_HOST`, `EMAIL_PORT`, `EMAIL_HOST_USER`, `EMAIL_HOST_PASSWORD`, `EMAIL_USE_TLS`, `DEFAULT_FROM_EMAIL` | SMTP for e-mail OTP; `EMAIL_USE_TLS` is 1 (STARTTLS, the default) or 0; the sender `DEFAULT_FROM_EMAIL` defaults to `EMAIL_HOST_USER` |
| `TZ` | time zone of the panel's dates and times and, in Docker, of the container (its daily backup), e.g. `Europe/Istanbul`; default UTC (the installer writes the server's zone into `settings.py` instead) |
| `TZ` | time zone of the panel's dates and times and, in Docker, of the container (its daily backup), e.g. `Europe/Istanbul`; default UTC (the installer writes the server's zone into `data/local_settings.py`, which wins) |
| `WEBVIRTCLOUD_LOG_FILE` | log file (default `data/webvirtcloud.log`; a relative path is from the panel's directory; rotated at 10 MB × 5) |
| `SECRET_KEY` | Django secret key (default: the `data/secret_key` file) |
| `ADMIN_USERNAME`, `ADMIN_PASSWORD` | the first superuser, read by the first `migrate` only, see [First login](#first-login) |
@ -353,28 +364,23 @@ The on/off variables take `1` or `0`; any other value, such as `true`, stops the
Where to set them:
- **Docker:** the `environment:` list of `docker-compose.override.yml`; every process in the container gets it.
- **Installer and manual installation:** `/etc/default/webvirtcloud` (root, mode 600), one `NAME='value'` per line (single quotes: systemd and the shell then read the same value); the panel's services read it. `settings.py` does not read these names: a line `WEBVIRTCLOUD_HTTPS = 1` there does nothing. To set an option in `settings.py` instead, change the setting the template fills from the variable, e.g. `SERIAL_CONSOLE_ENABLED = True`. Then `systemctl restart webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker`, and load the file before running `manage.py`: `set -a; . /etc/default/webvirtcloud; set +a`.
Some options exist only in `settings.py` (LDAP, `OTP_ENABLED`, `LOGIN_TRUSTED_PROXIES`). Docker builds that file from the template in each new container; to keep such options there, mount your own copy and update it from the template after each update:
```bash
docker compose exec webvirtcloud cat webvirtcloud/settings.py > settings.py # then edit it
```
add it to `docker-compose.override.yml` and run `docker compose up -d`:
```yaml
services:
webvirtcloud:
volumes:
- ./settings.py:/srv/webvirtcloud/webvirtcloud/settings.py
```
The container makes the file the panel user's (uid 33) with mode 600; edit it as root.
- **Docker:** the `environment:` list of `docker-compose.override.yml`, then `docker compose up -d`; every process in the container gets it.
- **Installer and manual installation:** `/etc/default/webvirtcloud` (root, mode 600), one `NAME='value'` per line (single quotes: systemd and the shell then read the same value); the panel's services read it. [`data/local_settings.py`](#local-settings) does not read these names: a line `WEBVIRTCLOUD_HTTPS = 1` there does nothing; it sets the setting the variable fills, e.g. `SERIAL_CONSOLE_ENABLED = True`. Then `systemctl restart webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker`, and load the file before running `manage.py`: `set -a; . /etc/default/webvirtcloud; set +a`.
gunicorn runs at most 8 workers (fewer on hosts with under 4 CPUs), in Docker 4, of 4 threads each; each worker takes about 140 MB and sends at most 2 requests at a time to one compute. To change it, set `GUNICORN_CMD_ARGS=--workers N` in a drop-in of `webvirt-cloud` (`systemctl edit webvirt-cloud`: `[Service]` and `Environment="GUNICORN_CMD_ARGS=--workers N"`) or in `docker-compose.override.yml`.
### Local settings
Options that are not environment variables (LDAP, `OTP_ENABLED`, `LOGIN_TRUSTED_PROXIES` or any other setting of `webvirtcloud/settings.py`) go into `data/local_settings.py`. `settings.py` runs it after its own defaults and with their names, so it sets or changes any of them, and its values win over the environment's; updates replace `settings.py` and leave this file alone. For example:
```python
TIME_ZONE = "Europe/Istanbul"
ALLOWED_HOSTS += ["wvc.example.com"]
OTP_ENABLED = True
```
The installer writes the server's time zone, the noVNC port and its names and IPs into it. A value `settings.py` works out from another before the file runs stays as it was: with `EMAIL_HOST_USER` set here, set `DEFAULT_FROM_EMAIL` here too; the log file is set with `WEBVIRTCLOUD_LOG_FILE` in the environment. It may hold passwords (LDAP): keep it the panel user's with mode 600. After a change, `systemctl restart webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker`. Docker keeps it in the `webvirtcloud-data` volume: write it next to the compose file, then `docker compose cp local_settings.py webvirtcloud:/srv/webvirtcloud/data/` and `docker compose restart webvirtcloud` (the start makes it the panel user's).
### HTTPS and reverse proxy
For a panel served over HTTPS:
@ -382,7 +388,7 @@ For a panel served over HTTPS:
- set `WEBVIRTCLOUD_HTTPS=1`: session and CSRF cookies become HTTPS-only, HTTP is redirected to HTTPS (except `/datasource/`, which VMs fetch over HTTP), and HSTS is sent for one year;
- add the HTTPS origin to `CSRF_TRUSTED_ORIGINS`, e.g. `CSRF_TRUSTED_ORIGINS=https://wvc.example.com` and `WEBVIRTCLOUD_HTTPS=1` in `/etc/default/webvirtcloud`.
TLS can end at the bundled nginx or at a proxy in front of it; such a proxy must send `X-Forwarded-Proto: https`. Failed logins are counted per client address, which the bundled nginx passes in `X-Real-IP`. A proxy that replaces the bundled nginx must set `X-Real-IP` itself; one on another machine (gunicorn bound beyond 127.0.0.1) must also be in `LOGIN_TRUSTED_PROXIES` in `settings.py`. With a proxy in front of the bundled nginx, configure nginx's `set_real_ip_from` / `real_ip_header` for that proxy, or all clients share its address.
TLS can end at the bundled nginx or at a proxy in front of it; such a proxy must send `X-Forwarded-Proto: https`. Failed logins are counted per client address, which the bundled nginx passes in `X-Real-IP`. A proxy that replaces the bundled nginx must set `X-Real-IP` itself; one on another machine (gunicorn bound beyond 127.0.0.1) must also be in `LOGIN_TRUSTED_PROXIES` in [`data/local_settings.py`](#local-settings). With a proxy in front of the bundled nginx, configure nginx's `set_real_ip_from` / `real_ip_header` for that proxy, or all clients share its address.
Every page is sent with `X-Frame-Options: DENY` and `Content-Security-Policy: script-src 'self'; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'`: the panel runs only scripts it serves itself, cannot be shown in a frame, and its forms post only to its own origin.
@ -400,7 +406,7 @@ Without the network: tick **Cloud-init seed** (Advanced) when creating a VM. The
### LDAP
The options below are set in `webvirtcloud/settings.py` (Docker: see [Environment variables](#environment-variables) for keeping your own). Variants for Active Directory and OpenLDAP are shown; this is a minimal config, see the [django-auth-ldap documentation](https://django-auth-ldap.readthedocs.io) for more.
The options below go into [`data/local_settings.py`](#local-settings), which has `ldap`, `LDAPSearch` and `NestedActiveDirectoryGroupType` at hand. Variants for Active Directory and OpenLDAP are shown; this is a minimal config, see the [django-auth-ldap documentation](https://django-auth-ldap.readthedocs.io) for more.
The Docker image includes the LDAP packages. On an installer or manual install, add them to the virtualenv first; pip builds `python-ldap` against these headers:
@ -413,8 +419,8 @@ zypper --non-interactive install -y openldap2-devel cyrus-sasl-devel # openSUS
Enable the LDAP backend:
```bash
sudo sed -i "s~#\"django_auth_ldap.backend.LDAPBackend\",~\"django_auth_ldap.backend.LDAPBackend\",~g" /srv/webvirtcloud/webvirtcloud/settings.py
```python
AUTHENTICATION_BACKENDS.append("django_auth_ldap.backend.LDAPBackend")
```
Set the LDAP server and bind DN:
@ -450,7 +456,8 @@ AUTH_LDAP_USER_SEARCH = LDAPSearch(
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
"ou=groups,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=groupOfUniqueNames)"
)
AUTH_LDAP_GROUP_TYPE = GroupOfUniqueNamesType() # import needs to be changed at the top of settings.py
from django_auth_ldap.config import GroupOfUniqueNamesType
AUTH_LDAP_GROUP_TYPE = GroupOfUniqueNamesType()
```
Set the group required to access WebVirtCloud (`False` disables this filter):
@ -477,18 +484,24 @@ An LDAP user is authenticated by LDAP and authorized through the WebVirtCloud pe
### Two-factor login (OTP)
Set `OTP_ENABLED = True` in `settings.py` 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.
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.
The QR code is mailed as a link to a page that shows it, good for one hour: the mail does not hold the code's secret. Email OTP QR code on a user's page (Users) sends it; Lost OTP? on the login page sends it to an enrolled user who gives their address.
### 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.
`/healthz`, without a login, answers 200 while the database answers and the job worker runs, 503 otherwise: point a monitor at it. The Docker image's health check reads it too.
### Serial console
A VM without graphics (no `<graphics>` device, a `<console type='pty'>`) opens a serial console (xterm.js) instead of VNC. It is off by default. To turn it on, set `WEBVIRTCLOUD_SERIAL_CONSOLE=1` (Docker: in `docker-compose.override.yml`, then `docker compose up -d`) or `SERIAL_CONSOLE_ENABLED = True` in `settings.py` and `systemctl restart webvirt-cloud webvirt-socketiod`.
A VM without graphics (no `<graphics>` device, a `<console type='pty'>`) opens a serial console (xterm.js) instead of VNC. It is off by default. To turn it on, set `WEBVIRTCLOUD_SERIAL_CONSOLE=1` (Docker: in `docker-compose.override.yml`, then `docker compose up -d`) or `SERIAL_CONSOLE_ENABLED = True` in [`data/local_settings.py`](#local-settings) and `systemctl restart webvirt-cloud webvirt-socketiod`.
- The VM page's Settings → Console switches a shut-off VM between VNC and serial (Console type). A new VNC console takes the form's other fields; on a TCP or TLS compute it needs Listen on: All interfaces (SSH and socket computes reach a localhost console).
- The guest must use its serial port: a login prompt needs `systemctl enable --now serial-getty@ttyS0`, boot messages need the kernel parameter `console=ttyS0,115200`. The console shows only what the guest writes after it opens; press Enter for a new prompt.
- socketiod listens on 127.0.0.1:6081; the page reaches it through nginx's `/socket.io/` location on the panel's own address.
- It accepts the console page's signed token, which expires after 120 s, only from the session of the user it was given to, as noVNC does. An open console closes within 10 s once its user loses access to the VM.
- It accepts the console page's signed token, which expires after 120 s, only from a session of the user it was given to, as noVNC does. An open console checks its user's access about every 10 s and closes once it is lost.
- One console per VM, at most 20 at a time; a second one is refused with the reason, except a superuser's, which takes the console over.
- novncd and socketiod log to the journal (`journalctl -u webvirt-novncd -u webvirt-socketiod`) or, in Docker, to `docker logs`: a console that was refused or could not connect says why there.
@ -497,7 +510,7 @@ A VM without graphics (no `<graphics>` device, a `<console type='pty'>`) opens a
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
- `secret_key`, `node_id` and `settings.py`
- `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
- `commit`, outside Docker
@ -580,18 +593,45 @@ To get a backup back when the panel's host is lost, give the new host a key as i
read -rs RESTIC_PASSWORD && export RESTIC_PASSWORD RESTIC_REPOSITORY=sftp:webvirtcloud-offsite:restic
restic snapshots --tag webvirtcloud
restic restore latest --tag webvirtcloud --target /root/offsite-restore
b=$(find /root/offsite-restore -type d -name 'webvirtcloud-backup-*' | sort | tail -n 1)
b=$(find /root/offsite-restore -type d -name 'webvirtcloud-backup-*' -printf '%T@ %p\n' | sort -n | tail -n 1 | cut -d' ' -f2-)
```
and follow [Moving to a new machine](#moving-to-a-new-machine) with that `b` (leave out its `b=` line).
### VM backups
Superusers back a VM up from its **Backups** tab into a backup target: a `dir` or `netfs` storage pool made on each host that sees it, added on **Backups → Backup targets** (another host's pool is accepted only when it is the same directory). A running VM keeps running: its disks are copied from one instant, with its file systems frozen for it when the guest agent answers; a shut-off VM's disks are copied as they are. A backup holds the disks, the VM's definition, its UEFI variables, its TPM state and a manifest; a VM with a TPM is backed up shut off. It is restored as a new VM, with its network disconnected unless asked, on a host that has the target's pool; the new VM gets the backed-up VM's TPM state. A backup is also restored over its own shut-off VM (its disks copied as new volumes it is switched to, its UEFI variables and TPM state back to the backup's, the old volumes kept until deleted), or one of its disks as a new volume. After the panel's database is lost, add the target again and use **Read backups from target**.
Users with the **Can back up instances** permission back up the VMs they may change into targets opened to VM owners on the target's page, restore those backups over the VM (the disks it ran from are then deleted) or as a new VM on the VM's host, within their quota, and delete the backups they took; those count in their backup quota (GiB, with the user's quota).
VMs with a TPM of their own settings (encryption, a state path), host devices, shared host directories, or encrypted or non-file disks are not backed up; CD-ROMs are left out.
**Backups → Schedules** backs VMs up every day: chosen VMs, every VM of a compute or every VM with a chosen tag (not templates), into a target, at a time in the panel's time zone (`TZ`), keeping the newest backups of each VM up to a number, and optionally the newest backup of each of the last N weeks and of the last N months. The job worker starts each VM's backup within 6 hours of the time, one copy at a time per target, and waits for a host in maintenance; a VM not started in that window waits for the next day. Older backups of a schedule are deleted; backups taken by hand are not. With "A full backup every N backups" above 1, a schedule's backups of a running VM with qcow2 disks between two full ones copy only what changed since the previous one; each is restored like a full one, and a chain of them is deleted once all of it is beyond the number kept. A migration, a restore over the VM or a shut-off VM's backup makes the next one full. Each target is checked once a day: a backup whose files are gone is marked missing.
**Verify** (a ready backup's Restore menu, superusers) reads the backup's files whole from the target, with those of the backups it builds on: each must be there at its size and format, an incremental disk on its base's file, and every file with the SHA-256 it had when written or, for a disk, at its first verification (recorded then; a disk changed since is reported). What is wrong marks the backup **Damaged**; the job can be cancelled.
The target must be:
- on storage apart from the VMs' disks: a target on the same storage is lost with it;
- writable by QEMU;
- with NFS on SELinux hosts, allowed: `setsebool -P virt_use_nfs 1`.
An NFS target, on each host:
```bash
virsh -c qemu:///system pool-define-as vmbackups netfs --source-host nfs.example.com --source-path /export/vmbackups --target /var/lib/libvirt/vmbackups
virsh -c qemu:///system pool-build vmbackups && virsh -c qemu:///system pool-start vmbackups && virsh -c qemu:///system pool-autostart vmbackups
```
The panel does not copy VM backups off site: the target's storage does.
## Updating
Every update starts with a backup in its own directory (mode 700, named by date) that holds the database, the commit it was taken from, for Docker the TLS client certificates and, for installer and manual installations, `settings.py`, the nginx config, `/etc/default/webvirtcloud` if there is one and migrations an old installer generated (`local-migrations.tar`). The database is copied with SQLite's backup API, which also finishes a write interrupted by a crash. This covers sqlite only; with PostgreSQL (`WEBVIRTCLOUD_DB_HOST`), back up that database yourself before updating.
Every update starts with a backup in its own directory (mode 700, named by date) that holds the database, the commit it was taken from, for Docker the TLS client certificates and, for installer and manual installations, `data/local_settings.py` (and a `settings.py` of an older version), the nginx config, `/etc/default/webvirtcloud` if there is one and migrations an old installer generated (`local-migrations.tar`). The database is copied with SQLite's backup API, which also finishes a write interrupted by a crash. This covers sqlite only; with PostgreSQL (`WEBVIRTCLOUD_DB_HOST`), back up that database yourself before updating.
### Docker
Each new container builds `settings.py` from the template and runs the migrations at start; the database and the secret key stay in the `webvirtcloud-data` volume. Keep your settings in `docker-compose.override.yml` (at least `ALLOWED_HOSTS`, see [Docker](#docker)).
Each new container runs the migrations at start; the database, the secret key and [`data/local_settings.py`](#local-settings) stay in the `webvirtcloud-data` volume. Keep your environment in `docker-compose.override.yml` (at least `ALLOWED_HOSTS`, see [Docker](#docker)). An override that mounts your own `settings.py` (`./settings.py:/srv/webvirtcloud/webvirtcloud/settings.py`, as older versions of this README said) would keep that old file: remove the mount and move your own values into `data/local_settings.py`.
Run the commands in the directory you installed from. Compose names the deployment after that directory (`webvirtcloud`), so another clone in a directory of the same name acts on the same containers and volumes.
@ -615,7 +655,7 @@ The TLS client certificates (`/var/www/.pki`) go into the backup and back into t
### Moving from supervisor to systemd
Versions up to v3.0.0 ran the panel under supervisor. Once, before the update steps below, stop it there, keep its config and remove it:
Versions up to v3.0.0 ran the panel under supervisor. Once, before the update below, stop it there, keep its config and remove it:
```bash
supervisorctl stop webvirtcloud novncd socketiod webvirt-worker
@ -624,91 +664,29 @@ mv /etc/supervisord.d/webvirtcloud.ini /root/webvirtcloud-supervisor.conf
supervisorctl update
```
Move the `environment=` values of that config into `/etc/default/webvirtcloud` (root, mode 600), one `NAME='value'` per line; leave out the worker's `WEBVIRTCLOUD_LOG_FILE`. Step 4 installs and starts the systemd units. Remove supervisor once nothing else uses it; a compute moves gstfsd as in [Adding a Compute Node](#adding-a-compute-node), step 3.
Move the `environment=` values of that config into `/etc/default/webvirtcloud` (root, mode 600), one `NAME='value'` per line; leave out the worker's `WEBVIRTCLOUD_LOG_FILE`. The update installs and starts the systemd units. Remove supervisor once nothing else uses it; a compute moves gstfsd as in [Adding a Compute Node](#adding-a-compute-node), step 3.
### Installer and manual installation
`git pull` never overwrites `webvirtcloud/settings.py` or `/etc/nginx/conf.d/webvirtcloud.conf`; steps 2 and 4 bring them up to date. Run the steps from a root shell; they use `$b`, so in a new shell set it again to the backup directory.
From a root shell:
1. Stop the panel, back up and pull:
```bash
(set -o pipefail &&
git -C /srv/webvirtcloud -c safe.directory=/srv/webvirtcloud fetch -q origin &&
git -C /srv/webvirtcloud -c safe.directory=/srv/webvirtcloud show origin/master:update.sh | bash)
```
```bash
systemctl stop webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker
# once: root may use the repo, which belongs to the service user
git config --global --add safe.directory /srv/webvirtcloud
b=/root/webvirtcloud-backup-$(date +%Y%m%d-%H%M%S)
cd /srv/webvirtcloud &&
! systemctl is-active --quiet webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker &&
mkdir -m 700 "$b" &&
venv/bin/python3 -c "import sqlite3,sys; sqlite3.connect('db.sqlite3').backup(sqlite3.connect(sys.argv[1]))" "$b/db.sqlite3.part" &&
mv "$b/db.sqlite3.part" "$b/db.sqlite3" &&
cp -p webvirtcloud/settings.py /etc/nginx/conf.d/webvirtcloud.conf "$b"/ &&
{ [ ! -f /etc/default/webvirtcloud ] || cp -p /etc/default/webvirtcloud "$b"/; } &&
git rev-parse HEAD > "$b/commit" &&
git ls-files -z --others --exclude-standard -- '*/migrations/*.py' | tar --null -T - --remove-files -cf "$b/local-migrations.tar" &&
git checkout -- $(git ls-files -m -- static dev/scss install.sh webvirtcloud.sh) &&
git checkout master && git pull
```
Older installers collected static files into the tracked `static/` and deleted the tracked `install.sh` and `webvirtcloud.sh`; the second-to-last line puts those files back, so that `git pull` can update them.
2. Rebuild `settings.py` from the template (the file keeps its owner and mode), then put back your own values; the `diff` lists them:
```bash
cat webvirtcloud/settings.py.template > webvirtcloud/settings.py
diff "$b/settings.py" webvirtcloud/settings.py
```
Typical ones are `TIME_ZONE`, `WS_*`, `ALLOWED_HOSTS`, `CSRF_TRUSTED_ORIGINS`, LDAP and, with PostgreSQL, your `DATABASES`: the template's is sqlite, so without it `migrate` would make a new, empty sqlite database and the panel would start on that. Two need care:
- a literal `SECRET_KEY = "..."` (older installers wrote it there): put the value into `data/secret_key` instead (`mkdir -p data` first if there is no `data/`). With no key, `migrate` in step 3 stops with "The SECRET_KEY setting must not be empty" and every page fails; with another key, every user is signed out;
- `SHOW_PROFILE_EDIT_PASSWORD`: keep it for this one `migrate` if you have it (migration `accounts.0008` reads it), then delete it.
3. Load `/etc/default/webvirtcloud` if you use it (its database is the one to migrate), install, migrate, and fix ownership and modes (`nginx:nginx` instead of `www-data:www-data` on RHEL / openSUSE). With LDAP, also run `venv/bin/pip3 install -U -r conf/requirements-ldap.txt` (headers: [LDAP](#ldap)):
```bash
{ [ ! -f /etc/default/webvirtcloud ] || { set -a; . /etc/default/webvirtcloud; set +a; }; } &&
venv/bin/pip3 install -U -r conf/requirements.txt &&
{ ! tar -tf "$b/local-migrations.tar" | grep -qx accounts/migrations/0006_alter_userattributes_id_alter_userinstance_id_and_more.py ||
venv/bin/python3 manage.py migrate accounts 0005 --fake; } &&
venv/bin/python3 manage.py migrate &&
venv/bin/python3 manage.py collectstatic --noinput &&
chown -R www-data:www-data /srv/webvirtcloud &&
chmod -R go-rwx data webvirtcloud/settings.py db.sqlite3
```
Installers from before September 2025 generated migrations of their own; step 1 moved them into `local-migrations.tar`. One of them has the name of a tracked migration, which `migrate` would skip; the second line marks it unapplied so that the tracked one runs.
4. Update the nginx config the same way as `settings.py`:
```bash
cp conf/nginx/webvirtcloud.conf /etc/nginx/conf.d/webvirtcloud.conf
diff "$b/webvirtcloud.conf" /etc/nginx/conf.d/webvirtcloud.conf
```
Put back your own lines (`server_name`, TLS, the noVNC port). Install the systemd units; your own service settings stay in `/etc/default/webvirtcloud` and in drop-ins. Debian / Ubuntu:
```bash
cp conf/systemd/webvirt-{cloud,novncd,socketiod,worker,backup}.service conf/systemd/webvirt-backup.timer /etc/systemd/system/
```
RHEL / openSUSE:
```bash
for u in cloud novncd socketiod worker backup; do sed 's/^\(User\|Group\)=.*/\1=nginx/' conf/systemd/webvirt-$u.service > /etc/systemd/system/webvirt-$u.service; done
cp conf/systemd/webvirt-backup.timer /etc/systemd/system/
```
Then reload nginx and start the panel:
```bash
nginx -t && systemctl reload nginx && systemctl daemon-reload && systemctl enable --now webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker webvirt-backup.timer
```
Older versions collected static files into `static/`; `git clean -n static/` lists the leftovers, which can be deleted.
- It runs the newest `update.sh` of the repository, also on an installation that has none yet. Another directory than `/srv/webvirtcloud`: set it in the command and `APP_PATH` for `bash`; the units get it.
- Nothing in the installation changes until its checks pass; files of the repository changed by hand stop it, listed. With PostgreSQL (the database Django is set up with), back that database up first and run it with `... | bash -s -- --database-backed-up`.
- An installation of an older version has its own `webvirtcloud/settings.py`: it stops and lists the lines that differ from that version's template: your own. Put your own values into [`data/local_settings.py`](#local-settings) and run it again. Typical ones are `TIME_ZONE`, `WS_PORT`, `ALLOWED_HOSTS`, `CSRF_TRUSTED_ORIGINS`, LDAP and, with PostgreSQL, your `DATABASES`: the default is sqlite, so without it `migrate` would make a new, empty sqlite database and the panel would start on that. A literal `SECRET_KEY = "..."` (older installers wrote it there) goes into `data/secret_key` instead (with no key every page fails, with another every user is signed out); keep `SHOW_PROFILE_EDIT_PASSWORD` for this one update if you have it (migration `accounts.0008` reads it), then delete it.
- It stops the panel and backs it up into `/root/webvirtcloud-backup-<date>`: the database, the commit, `data/local_settings.py`, the nginx config, `/etc/default/webvirtcloud`, an older version's own `settings.py` and the migrations an old installer generated (`local-migrations.tar`). Then it pulls `master`, installs the requirements (the LDAP ones too if installed), migrates, collects the static files, gives the files to the panel's user (the owner of `/srv/webvirtcloud`), installs the systemd units and starts the panel.
- It does not replace `/etc/nginx/conf.d/webvirtcloud.conf`, which holds your `server_name`, TLS and noVNC port: when the new version changes that config, it prints the change to apply by hand.
- A failure stops it with the reason and the backup's directory. A failed backup starts the panel again; a later failure before the panel starts leaves it stopped until the cause is fixed and the command runs again, which goes on with that backup, or it is [rolled back](#restore-and-rollback). An nginx config nginx refuses stops it after the panel started: fix it and `systemctl reload nginx`.
- Older versions collected static files into `static/`; `git clean -n static/` lists the leftovers, which can be deleted.
### 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`, 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. 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`.
Docker, in the directory you installed from:
@ -726,7 +704,7 @@ docker compose start &&
docker compose exec webvirtcloud chown -R www-data:www-data /var/www/.pki
```
The container fixes the ownership and modes of the database and keys at start; the last line gives the TLS client certificates to `www-data` also in an image of v4.3.0 or older, which neither does that nor keeps them in a volume.
A version from before `data/local_settings.py` builds its `settings.py` from a template and does not read that file: to roll back to one, mount your `settings.py` again as that version's README says. The container fixes the ownership and modes of the database and keys at start; the last line gives the TLS client certificates to `www-data` also in an image of v4.3.0 or older, which neither does that nor keeps them in a volume.
Installer and manual installation, from a root shell (`nginx:nginx` on RHEL / openSUSE):
@ -739,23 +717,27 @@ git checkout -- $(git ls-files -m -- static/css dev/scss) &&
git checkout "$(cat "$b/commit")" &&
{ [ ! -f "$b/local-migrations.tar" ] || tar -xf "$b/local-migrations.tar"; } &&
venv/bin/python3 -c "import os,sqlite3,sys; [os.remove(p) for p in ('db.sqlite3-journal','db.sqlite3-wal','db.sqlite3-shm') if os.path.exists(p)]; sqlite3.connect(sys.argv[1]).backup(sqlite3.connect('db.sqlite3'))" "$b/db.sqlite3" &&
cp "$b/settings.py" webvirtcloud/settings.py &&
{ [ ! -f "$b/settings.py" ] || cp "$b/settings.py" webvirtcloud/settings.py; } &&
{ [ ! -f "$b/local_settings.py" ] || cp -p "$b/local_settings.py" data/; } &&
{ [ ! -f "$b/webvirtcloud.conf" ] || cp "$b/webvirtcloud.conf" /etc/nginx/conf.d/webvirtcloud.conf; } &&
{ [ ! -f "$b/webvirtcloud" ] || { set -a; . "$b/webvirtcloud"; set +a; }; } &&
venv/bin/pip3 install -r conf/requirements.txt &&
venv/bin/python3 manage.py migrate &&
venv/bin/python3 manage.py collectstatic --noinput &&
chown -R www-data:www-data /srv/webvirtcloud &&
chmod 600 db.sqlite3 webvirtcloud/settings.py
chmod 600 db.sqlite3 && { [ ! -f "$b/settings.py" ] || chmod 600 webvirtcloud/settings.py; } &&
rm -f data/.update-backup
```
A backup of a version that had its own `settings.py` (not in the repository) holds that file: the steps put it back for the older code.
Put back `/etc/default/webvirtcloud` if the backup has it (`cp -p "$b/webvirtcloud" /etc/default/`), then reload nginx and start the panel:
```bash
nginx -t && systemctl reload nginx && systemctl start webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker
```
A version from before v3.0.0 has no worker: `systemctl disable --now webvirt-worker`. A rollback keeps the systemd units. A rollback leaves the clone on a detached HEAD at the restored commit; the update steps record that commit before they switch back to `master`.
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`.
### Moving to a new machine
@ -770,25 +752,28 @@ docker compose stop -t 95 &&
docker compose run --rm --no-deps -T --entrypoint /srv/webvirtcloud/venv/bin/python3 webvirtcloud \
-c "import os,sqlite3,sys,tempfile; t=tempfile.mktemp(); open(t,'wb').write(sys.stdin.buffer.read()); [os.remove(p) for p in ('data/db.sqlite3-journal','data/db.sqlite3-wal','data/db.sqlite3-shm') if os.path.exists(p)]; sqlite3.connect(t).backup(sqlite3.connect('data/db.sqlite3'))" < "$b/db.sqlite3" &&
{ [ ! -f "$b/secret_key" ] || docker compose cp "$b/secret_key" webvirtcloud:/srv/webvirtcloud/data/; } &&
{ [ ! -f "$b/local_settings.py" ] || docker compose cp "$b/local_settings.py" webvirtcloud:/srv/webvirtcloud/data/; } &&
docker compose cp "$b/node_id" webvirtcloud:/srv/webvirtcloud/data/ &&
{ [ ! -d "$b/ssh" ] || docker compose cp "$b/ssh/." webvirtcloud:/var/www/.ssh/; } &&
{ [ ! -d "$b/pki" ] || docker compose cp "$b/pki/." webvirtcloud:/var/www/.pki/; } &&
docker compose up -d # the container migrates and fixes ownership and modes at start
```
Installer and manual installation, from a root shell (`nginx` instead of `www-data` on RHEL / openSUSE). Compare `$b/settings.py` with `webvirtcloud/settings.py` and carry your own values over:
Installer and manual installation, from a root shell (`nginx` instead of `www-data` on RHEL / openSUSE / openEuler), with your `/etc/default/webvirtcloud` in place first. A backup of an older version has a `settings.py` instead of `local_settings.py`: carry your own values from it into [`data/local_settings.py`](#local-settings).
```bash
b=/root/webvirtcloud-backup-YYYYMMDD-HHMMSS
systemctl stop webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker
cd /srv/webvirtcloud &&
{ [ ! -f /etc/default/webvirtcloud ] || { set -a; . /etc/default/webvirtcloud; set +a; }; } &&
venv/bin/python3 -c "import os,sqlite3,sys; [os.remove(p) for p in ('db.sqlite3-journal','db.sqlite3-wal','db.sqlite3-shm') if os.path.exists(p)]; sqlite3.connect(sys.argv[1]).backup(sqlite3.connect('db.sqlite3'))" "$b/db.sqlite3" &&
cp "$b/node_id" data/ && { [ ! -f "$b/secret_key" ] || cp "$b/secret_key" data/; } &&
{ [ ! -f "$b/node_id" ] || cp "$b/node_id" data/; } && { [ ! -f "$b/secret_key" ] || cp "$b/secret_key" data/; } &&
{ [ ! -f "$b/local_settings.py" ] || cp "$b/local_settings.py" data/; } &&
mkdir -p ~www-data/.ssh && { [ ! -d "$b/ssh" ] || cp -r "$b"/ssh/. ~www-data/.ssh/; } &&
mkdir -p ~www-data/.pki && { [ ! -d "$b/pki" ] || cp -r "$b"/pki/. ~www-data/.pki/; } &&
venv/bin/python3 manage.py migrate &&
chown -R www-data:www-data data ~www-data/.ssh ~www-data/.pki &&
chmod 700 data ~www-data/.ssh ~www-data/.pki && { [ ! -f db.sqlite3 ] || chmod 600 db.sqlite3; } &&
chmod 700 data ~www-data/.ssh ~www-data/.pki && chmod -R go-rwx data && { [ ! -f db.sqlite3 ] || chmod 600 db.sqlite3; } &&
systemctl start webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker
```
@ -799,13 +784,13 @@ What an update from an older version changes for operators and users. `manage.py
- Requests for a host not in `ALLOWED_HOSTS` get 400. The installer writes the server's names and IPs; add more with the `ALLOWED_HOSTS` env var. The cloud-init datasource host must be allowed too.
- Logging out needs a POST; a GET to `/accounts/logout/` gets 405.
- The API accepts only a session from the login form or an API token (no HTTP Basic), and the API docs need a login. Sessions opened through the old password-only doors skip OTP; end them once after the update (everyone signs in again): `manage.py shell -c "from django.contrib.sessions.models import Session; Session.objects.all().delete()"`.
- Failed logins lock a user (django-axes). The limit and lock time are on the Settings page; unlock with `manage.py axes_reset_username <username>`.
- Failed logins lock a user (django-axes): the sign-in page then says how long. The limit and lock time are on the Settings page; a locked user is marked on the Users page, and a superuser ends the lock with Unlock sign-in on the user's page. A sign-in lasts the session length set on the Settings page (24 hours by default). A sign-in notice set there (e.g. planned maintenance) is shown above the sign-in form.
- Changing one's own password is the "Can change password" permission (per user or group; new users have it); `SHOW_PROFILE_EDIT_PASSWORD` is gone.
- The admin's first-login password change survives losing `data/admin_password` (migration `accounts.0007`); run `migrate` as a user who can read that file.
- A new VM and each clone get a random VNC password of their own (clones no longer share their source's). The console page sends it for a user with **Open a console without the VM's console password**, which a new user has unless unticked; others are asked for it. Existing VMs keep theirs.
- An `admin` account that still has the password `admin` (the first user of versions up to v2.0.0) must change it at its next login, and its API tokens are refused until then (migration `accounts.0013`).
- A `settings.py` kept from an older version must match the template (apps, middleware, the SQLite `OPTIONS`, the REST framework, knox, axes and password settings): rebuild it from the template and carry your own values over, as step 2 of the update does.
- The VNC console connects to `/novncd/` on the panel's own address through nginx, and the serial console to `/socket.io/`: they work on HTTPS and behind another proxy without settings. `WS_PUBLIC_PORT`, `WS_PUBLIC_HOST`, `WS_PUBLIC_PATH`, `WS_CERT` and `SOCKETIO_PUBLIC_HOST`/`_PORT`/`_PATH` are gone; remove them from `docker-compose.override.yml`, `/etc/default/webvirtcloud` or a kept `settings.py`, set `WS_HOST = "127.0.0.1"` in a kept `settings.py`, and close port 6080 in the firewall.
- `webvirtcloud/settings.py` is part of the code, and every update replaces it; an installation's own settings are in [`data/local_settings.py`](#local-settings). `update.sh` has them moved there once from an older version's own `settings.py`; in Docker, remove a mounted `settings.py` from `docker-compose.override.yml`.
- The VNC console connects to `/novncd/` on the panel's own address through nginx, and the serial console to `/socket.io/`: they work on HTTPS and behind another proxy without settings. `WS_PUBLIC_PORT`, `WS_PUBLIC_HOST`, `WS_PUBLIC_PATH`, `WS_CERT` and `SOCKETIO_PUBLIC_HOST`/`_PORT`/`_PATH` are gone; remove them from `docker-compose.override.yml`, `/etc/default/webvirtcloud` or `data/local_settings.py`, and close port 6080 in the firewall.
- Installer and manual installations run the panel as systemd units (`webvirt-cloud`, `webvirt-novncd`, `webvirt-socketiod`, `webvirt-worker`, `webvirt-backup.timer`) and computes run `webvirt-gstfsd`, instead of supervisor; see [Moving from supervisor to systemd](#moving-from-supervisor-to-systemd). Service settings go into `/etc/default/webvirtcloud`, service output into the journal (`journalctl -u webvirt-cloud`); the app log stays in `data/`. novncd and socketiod run sandboxed (read-only system directories, no `/home`).
- 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](#adding-a-compute-node), step 3 (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)).
@ -815,7 +800,7 @@ What an update from an older version changes for operators and users. `manage.py
- 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](#adding-a-compute-node), step 2).
- The SQLite database must be on a local file system (WAL). Outside compose, stop the Docker container with `docker stop -t 95 webvirtcloud` so the worker can finish running jobs.
- Long operations run as jobs in a worker process (`manage.py run_worker`): creating, cloning, migrating and deleting VMs, moving disks, cloning volumes, taking and reverting snapshots and deleting external snapshots. The page returns at once and the job panel and the Jobs page follow them; a migration can be cancelled. The API's VM create, migrate and delete answer 202 with the job and need a new `submission_key` per request. The create form no longer takes a console password; set it on the VM page.
- Long operations run as jobs in a worker process (`manage.py run_worker`): creating, cloning, migrating and deleting VMs, bulk power actions, moving disks, cloning and downloading volumes, taking and reverting snapshots, deleting external snapshots and VM backups. The page returns at once and the job panel and the Jobs page follow them. The API's VM create, migrate and delete answer 202 with the job and need a `submission_key`: a new one for each operation, the same one to retry it (a delete retried after its VM is gone gets 404). The create form no longer takes a console password; set it on the VM page.
- An API error other than a field the request got wrong (which answers with the fields) is `{"detail": ...}` with a status that says what it is: 404 for a VM, pool or volume read or deleted that the host does not have, 409 for a volume in use, a template started or a stopped pool, 503 for a host that cannot be reached (all were 400 or 200 before); an unknown API URL answers JSON.
- An ISO upload is tracked as a job that can be cancelled. The browser sends the file, so stay on the page until it ends; an upload left idle for an hour is ended and its partial file deleted.
- A clone of a running VM (libvirt 11.10 or later, local file disks, no TPM) locks the VM until the copy ends and can be cancelled; cancelling a clone of a shut-off VM has no effect. A job that ends uncertain keeps its VM locked until a superuser resolves it on its job page.
@ -826,11 +811,11 @@ What an update from an older version changes for operators and users. `manage.py
- A template VM is changed or deleted only by superusers and staff owners with the matching permission; other owners can still view, open the console and clone it.
- 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 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 VM that vanishes from its compute, or whose compute is deleted, keeps its owners for `INSTANCE_OWNERSHIP_RETENTION_DAYS` (30) in case the same UUID comes back; superusers manage these records on the "Removed VMs" page.
- 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.
- 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).
- On a host whose libvirt cannot change network interfaces (the udev backend: RHEL 9 and later, Debian 12), the interface pages offer no create, start, stop or delete.
- The panel is offered in English, Turkish and Simplified Chinese.
- With SELinux (RHEL family, openEuler), systemd could not run the virtualenv's programs and the panel did not start. The installer now writes file context rules (`httpd_sys_content_t` for the panel, `bin_t` for `venv/bin`) instead of `chcon`, so a relabel keeps them. A manual installation runs `semanage fcontext -a -t bin_t "/srv/webvirtcloud/venv/bin(/.*)?"` and `restorecon -R /srv/webvirtcloud` once; an installer one runs the installer again.
## Usage
@ -852,6 +837,8 @@ The REST API (Django REST Framework, documented with `drf-spectacular`) takes th
curl -H "Authorization: Token wvc_..." https://<server>/api/v1/instances/
```
The VM and compute lists (also a compute's VMs) take `?tag=<name>`.
### Screenshots
| VM list | VM page |
@ -868,7 +855,7 @@ The REST API (Django REST Framework, documented with `drf-spectacular`) takes th
## Development
Run every step as your normal user, not with `sudo`: if `manage.py` ever runs as root, `db.sqlite3` and `data/` end up root-owned and later runs fail with "readonly database" or "Permission denied".
Run `manage.py` as your normal user (`sudo` only for system packages): if it ever runs as root, `db.sqlite3` and `data/` end up root-owned and later runs fail with "readonly database" or "Permission denied".
1. System packages. The virtualenv reuses the distro's `libvirt`, `lxml` and `ldap` bindings when their versions satisfy `conf/requirements.txt`; otherwise pip installs or builds newer ones:
@ -891,10 +878,9 @@ Run every step as your normal user, not with `sudo`: if `manage.py` ever runs as
pip install -r dev/requirements.txt
```
3. Settings and secret key:
3. Secret key (your own settings go into [`data/local_settings.py`](#local-settings)):
```bash
cp webvirtcloud/settings.py.template webvirtcloud/settings.py
mkdir -p data && python conf/secret_generator.py > data/secret_key && chmod 600 data/secret_key
```
@ -927,7 +913,7 @@ It lists the dead keys it leaves out: a character only a dead key types cannot b
### Translations
The panel is translated into the 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`):
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
@ -970,7 +956,7 @@ python manage.py test
HOME=$PWD/.vagrant/tls TEST_LIBVIRT_TYPE=3 TEST_LIBVIRT_SSH_HOST= python manage.py test # compute1 again, over TLS
# a socket compute is the panel's own libvirt: the committed HEAD runs inside compute1
git archive HEAD | vagrant ssh compute1 -c "sudo sh -c 'rm -rf /root/wvc && mkdir /root/wvc && tar -x -C /root/wvc'"
vagrant ssh compute1 -c "sudo -i sh -ec 'dnf -y install python3-devel openldap-devel cyrus-sasl-devel gcc; cd /root/wvc; python3 -m venv --system-site-packages venv; venv/bin/pip install -r dev/requirements.txt; cp webvirtcloud/settings.py.template webvirtcloud/settings.py; mkdir data; venv/bin/python conf/secret_generator.py > data/secret_key; TEST_LIBVIRT_HOST=localhost TEST_LIBVIRT_TYPE=4 TEST_LIBVIRT_LOGIN=wvc TEST_LIBVIRT_PASSWORD=wvc-test TEST_LIBVIRT_LVM_DEVICE=/dev/vdb TEST_LIBVIRT_ISCSI_TARGET=iqn.2026-10.test.wvc:lun TEST_LIBVIRT_NFS_EXPORT=/srv/wvc-nfs venv/bin/python manage.py test'"
vagrant ssh compute1 -c "sudo -i sh -ec 'dnf -y install python3-devel openldap-devel cyrus-sasl-devel gcc; cd /root/wvc; python3 -m venv --system-site-packages venv; venv/bin/pip install -r dev/requirements.txt; mkdir data; venv/bin/python conf/secret_generator.py > data/secret_key; TEST_LIBVIRT_HOST=localhost TEST_LIBVIRT_TYPE=4 TEST_LIBVIRT_LOGIN=wvc TEST_LIBVIRT_PASSWORD=wvc-test TEST_LIBVIRT_LVM_DEVICE=/dev/vdb TEST_LIBVIRT_ISCSI_TARGET=iqn.2026-10.test.wvc:lun TEST_LIBVIRT_NFS_EXPORT=/srv/wvc-nfs venv/bin/python manage.py test'"
vagrant destroy -f
```

View file

@ -112,4 +112,9 @@ class AccountsConfig(AppConfig):
from django.db.models.signals import post_save
post_save.connect(grant_change_password, sender=settings.AUTH_USER_MODEL)
from django.contrib.auth.signals import user_logged_in
from .lockout import start_session
user_logged_in.connect(start_session, dispatch_uid="accounts.session_length")
from . import checks # noqa: F401

View file

@ -14,7 +14,7 @@ def password_change_middleware_check(app_configs, **kwargs):
return [
Error(
"ForcePasswordChangeMiddleware must follow AuthenticationMiddleware.",
hint=f"Add '{required}' to MIDDLEWARE in webvirtcloud/settings.py, as settings.py.template does.",
hint=f"data/local_settings.py sets MIDDLEWARE: keep '{required}' after AuthenticationMiddleware, as webvirtcloud/settings.py has it.",
id="accounts.E001",
)
]
@ -24,14 +24,25 @@ def password_change_middleware_check(app_configs, **kwargs):
@register(Tags.security)
def login_required_middleware_check(app_configs, **kwargs):
middleware = list(settings.MIDDLEWARE)
required = "django.contrib.auth.middleware.LoginRequiredMiddleware"
required = "webvirtcloud.middleware.LoginRequiredMiddleware"
django_s = "django.contrib.auth.middleware.LoginRequiredMiddleware"
old = "login_required.middleware.LoginRequiredMiddleware"
if django_s in middleware and old not in middleware:
# it signs in as well; a page whose session ended does not say so, and a form sent then is lost
return [
Warning(
"MIDDLEWARE uses Django's LoginRequiredMiddleware, not the panel's.",
hint=f"data/local_settings.py sets MIDDLEWARE: replace '{django_s}' with '{required}', "
"as webvirtcloud/settings.py has it.",
id="accounts.W002",
)
]
if old in middleware or required not in middleware:
return [
Error(
"MIDDLEWARE must use Django's LoginRequiredMiddleware.",
hint=f"In webvirtcloud/settings.py replace '{old}' with '{required}' "
"and delete LOGIN_REQUIRED_IGNORE_VIEW_NAMES, as settings.py.template does.",
"MIDDLEWARE must use the panel's LoginRequiredMiddleware.",
hint=f"data/local_settings.py sets MIDDLEWARE: replace '{old}' with '{required}' "
"and delete LOGIN_REQUIRED_IGNORE_VIEW_NAMES, as webvirtcloud/settings.py has it.",
id="accounts.E002",
)
]
@ -44,7 +55,7 @@ def obsolete_settings_check(app_configs, **kwargs):
return [
Warning(
"SHOW_PROFILE_EDIT_PASSWORD is no longer used.",
hint="Remove it from webvirtcloud/settings.py. Whether a user may change their own "
hint="Remove it from data/local_settings.py. Whether a user may change their own "
"password is the 'Can change password' permission, per user or group.",
id="accounts.W001",
)

View file

@ -32,7 +32,7 @@ class UserInstanceForm(ModelForm):
model = UserInstance
fields = "__all__"
# the rights beyond power and console, as the VM's Users tab names them
labels = {"is_change": _("Change settings"), "is_delete": _("Delete the VM"),
labels = {"user": _("User"), "instance": _("Instance"), "is_change": _("Change settings"), "is_delete": _("Delete the VM"),
"is_vnc": _("Change console settings")}
help_texts = {"is_vnc": _("Only together with Change settings")}
# a list of every user and every VM

View file

@ -1,16 +1,22 @@
"""
Settings for django-axes, read from the Settings page (AppSettings) on each
use, so an administrator can change them without a restart.
Settings for django-axes and the session length, read from the Settings page
(AppSettings) on each use, so an administrator can change them without a
restart.
"""
from datetime import timedelta
from ipaddress import ip_address, ip_network
from appsettings.models import AppSettings
from axes.models import AccessAttempt
from django.conf import settings
from django.db.models import Sum
from django.shortcuts import render
from django.utils import timezone
DEFAULT_FAILURE_LIMIT = 5
DEFAULT_LOCKOUT_MINUTES = 15
DEFAULT_SESSION_HOURS = 24
def _positive_int(key, default):
@ -52,3 +58,32 @@ def client_ip(request):
remote = request.META.get("REMOTE_ADDR", "")
real_ip = request.META.get("HTTP_X_REAL_IP", "").strip()
return real_ip if real_ip and _from_trusted_proxy(remote) else remote
def lockout_response(request, original_response, credentials):
"""AXES_LOCKOUT_CALLABLE: the locked sign-in page, with the lock time."""
minutes = cooloff_time(request) // timedelta(minutes=1)
return render(request, "accounts/lockout.html", {"minutes": minutes}, status=429)
def locked_usernames():
"""The usernames, in lower case, locked now from some address. As django-axes
counts them, a username's recent failures from one address add up over
the browsers they came from."""
since = timezone.now() - cooloff_time(None)
per_address = (AccessAttempt.objects.filter(attempt_time__gte=since).values("username", "ip_address")
.annotate(failures=Sum("failures_since_start")).filter(failures__gte=failure_limit(None, {})))
return {row["username"].lower() for row in per_address}
def unlock(username):
"""End the username's locks, from every address and in any letter case;
returns how many records went."""
return AccessAttempt.objects.filter(username__iexact=username).delete()[1].get(AccessAttempt._meta.label, 0)
def start_session(sender, request, user, **kwargs):
"""user_logged_in: a session ends LOGIN_SESSION_HOURS after the sign-in (a
date, as a number of seconds would count again from each session save)."""
hours = _positive_int("LOGIN_SESSION_HOURS", DEFAULT_SESSION_HOURS)
request.session.set_expiry(timezone.now() + timedelta(hours=hours))

View file

@ -0,0 +1,19 @@
# Generated by Django 5.2.18 on 2026-11-17 16:04
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0013_default_admin_password'),
]
operations = [
migrations.AddField(
model_name='userattributes',
name='max_backup_size',
field=models.IntegerField(default=0, help_text='-1: no limit; 0: none allowed', validators=[django.core.validators.MinValueValidator(-1)], verbose_name='max backup size (GiB)'),
),
]

View file

@ -67,6 +67,12 @@ class UserAttributes(models.Model):
help_text=_("-1: no limit; 0: none allowed"),
validators=[MinValueValidator(-1)],
)
max_backup_size = models.IntegerField(
_("max backup size (GiB)"),
default=0,
help_text=_("-1: no limit; 0: none allowed"),
validators=[MinValueValidator(-1)],
)
def __str__(self):
return self.user.username

View file

@ -12,6 +12,8 @@ ignored.
from django.contrib.auth.signals import user_login_failed
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from django.utils.translation import ngettext_lazy
from django_otp.forms import OTPAuthenticationForm
from django_otp.plugins.otp_totp.models import TOTPDevice
@ -19,6 +21,19 @@ from accounts.forms import BoundedUsernameMixin
class SingleDeviceOTPForm(BoundedUsernameMixin, OTPAuthenticationForm):
# the errors this form can give, here so that the panel's catalogs translate them
otp_error_messages = dict(
OTPAuthenticationForm.otp_error_messages,
token_required=_("Please enter your OTP token."),
invalid_token=_("Invalid token. Please make sure you have entered it correctly."),
n_failed_attempts=ngettext_lazy(
"Verification temporarily disabled because of %(failure_count)d failed attempt, please try again soon.",
"Verification temporarily disabled because of %(failure_count)d failed attempts, please try again soon.",
"failure_count",
),
verification_not_allowed=_("Verification of the token is currently disabled"),
)
def _confirmed_totp(self, user, for_verify=False):
"""The user's oldest confirmed TOTP device, or None. With for_verify
the row is locked (select_for_update) so the token's replay and

View file

@ -3,8 +3,8 @@
{% load i18n %}
{% load bootstrap_icons %}
{% block title %}{% trans "User Profile" %} - {{ user }}{% endblock %}
{% block page_heading %}{% trans "User Profile" %}{% endblock page_heading %}
{% block title %}{% trans "User profile" %} - {{ user }}{% endblock %}
{% block page_heading %}{% trans "User profile" %}{% endblock page_heading %}
{% block content %}
<section class="card mb-4" aria-labelledby="identity-title">
@ -19,6 +19,7 @@
<span class="badge text-bg-secondary">{% trans "Template editor" %}</span>
{% endif %}
{% if not user.is_active %}<span class="badge text-bg-danger">{% trans "Blocked" %}</span>{% endif %}
{% if locked %}<span class="badge bg-warning text-dark">{% trans "Sign-in locked" %}</span>{% endif %}
</div>
<div class="d-flex flex-wrap align-items-center gap-2 small mt-2">
<span class="text-body-secondary text-break">{{ user.username }}</span>
@ -32,6 +33,11 @@
</div>
<div class="col-lg-4 d-flex flex-wrap justify-content-lg-end gap-2">
<a href="{% url 'admin:user_update' user.id %}?next={% url 'accounts:account' user.id %}" class="btn btn-primary">{% bs_icon 'pencil' %} {% trans "Edit user" %}</a>
{% if locked %}
<form method="post" action="{% url 'accounts:admin_unlock' user.id %}">{% csrf_token %}
<button type="submit" class="btn btn-outline-secondary"><i class="bi bi-unlock" aria-hidden="true"></i> {% trans "Unlock sign-in" %}</button>
</form>
{% endif %}
{% if otp_enabled %}
<form method="post" action="{% url 'accounts:admin_email_otp' user.id %}">{% csrf_token %}
<button type="submit" class="btn btn-outline-secondary">{% bs_icon 'qr-code' %} {% trans "Email OTP QR code" %}</button>
@ -48,8 +54,8 @@
</div>
<nav class="card-footer d-flex flex-wrap gap-3 small" aria-label="{% trans 'User sections' %}">
<a href="#instances">{% trans "VMs" %} <span class="badge text-bg-light border">{{ user_insts|length }}</span></a>
<a href="#public-keys">{% trans "SSH Keys" %} <span class="badge text-bg-light border">{{ publickeys|length }}</span></a>
<a href="#apitokens">{% trans "API Tokens" %} <span class="badge text-bg-light border">{{ api_tokens|length }}</span></a>
<a href="#public-keys">{% trans "SSH keys" %} <span class="badge text-bg-light border">{{ publickeys|length }}</span></a>
<a href="#apitokens">{% trans "API tokens" %} <span class="badge text-bg-light border">{{ api_tokens|length }}</span></a>
</nav>
</section>
@ -66,6 +72,7 @@
<div class="col-12 col-md-6">
<a class="fw-semibold text-break" href="{% url 'instances:instance' inst.instance.id %}">{{ inst.instance.name }}</a>
<div class="small text-body-secondary text-break">{% trans "Host" %}: {{ inst.instance.compute.name }}</div>
{% include 'common/tag_badges.html' with tags=inst.instance.tags.all %}
</div>
<div class="col-12 col-md-6 d-flex flex-wrap gap-1">
{# the rights as the VM's Users tab names them: every owner powers the VM and opens its console #}
@ -92,12 +99,12 @@
</section>
<section class="card mb-4" id="public-keys" aria-labelledby="public-keys-title">
<div class="card-header"><h2 class="h5 mb-0" id="public-keys-title">{% trans "SSH Keys" %} <span class="badge text-bg-light border">{{ publickeys|length }}</span></h2></div>
<div class="card-header"><h2 class="h5 mb-0" id="public-keys-title">{% trans "SSH keys" %} <span class="badge text-bg-light border">{{ publickeys|length }}</span></h2></div>
<div class="list-group list-group-flush">{% include "ssh_key_list.html" with owner=user %}</div>
</section>
<section class="card" id="apitokens" aria-labelledby="apitokens-title">
<div class="card-header"><h2 class="h5 mb-0" id="apitokens-title">{% trans "API Tokens" %} <span class="badge text-bg-light border">{{ api_tokens|length }}</span></h2></div>
<div class="card-header"><h2 class="h5 mb-0" id="apitokens-title">{% trans "API tokens" %} <span class="badge text-bg-light border">{{ api_tokens|length }}</span></h2></div>
<div class="list-group list-group-flush">{% include "api_token_list.html" with owner=user %}</div>
</section>
{% endblock content %}

View file

@ -2,9 +2,9 @@
{% load django_bootstrap5 %}
{% load i18n %}
{% block title %}{% trans "Change Password" %}{% endblock title %}
{% block title %}{% trans "Change password" %}{% endblock title %}
{% block page_heading %}{% trans "Change Password" %}{% endblock page_heading %}
{% block page_heading %}{% trans "Change password" %}{% endblock page_heading %}
{% block content %}
{# a user changes their own password; one who must (a new or reset account) cannot go elsewhere first #}

View file

@ -21,9 +21,9 @@
</form>
</div>
<div class="card-footer">
<div class="mb-0 float-end">
<a class="btn btn-primary" href="#" data-history-back>{% bs_icon 'arrow-left' %} {% trans "Cancel" %}</a>
<button type="submit" form="create-update" class="btn btn-success">
<div class="d-flex justify-content-end gap-2">
<a class="btn btn-outline-secondary" href="#" data-history-back>{% trans "Cancel" %}</a>
<button type="submit" form="create-update" class="btn btn-primary">
{% bs_icon 'envelope-open' %} {% trans "Send" %}
</button>
</div>

View file

@ -0,0 +1,26 @@
{% extends "base.html" %}
{% load i18n %}
{% block title %}{% trans "WebVirtCloud" %} - {% trans "Sign-in locked" %}{% endblock title %}
{% block page_header %}{% endblock page_header %}{# the page has its own heading #}
{% block content %}
<div class="row justify-content-center pt-5">
<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 text-center">
<div class="d-inline-block rounded-3 bg-warning text-dark fs-2 lh-1 p-3 mb-3"><i class="bi bi-lock"></i></div>
<h1 class="h3 fw-bold mb-3">{% trans "Sign-in locked" %}</h1>
<p class="mb-4">
{% blocktrans trimmed count minutes=minutes %}
Too many failed sign-ins. The lock ends within {{ minutes }} minute.
{% plural %}
Too many failed sign-ins. The lock ends within {{ minutes }} minutes.
{% endblocktrans %}
</p>
<a href="{% url 'accounts:login' %}{% if request.GET.next %}?next={{ request.GET.next|urlencode }}{% endif %}" class="btn btn-primary w-100 py-2">{% trans "Back to sign in" %}</a>
</div>
</div>
</div>
</div>
{% endblock %}

View file

@ -1,9 +1,9 @@
{% extends "base.html" %}
{% load static %}
{% load i18n %}
{% load django_bootstrap5 %}
{% block title %}{% trans "WebVirtCloud" %} - {% trans "Sign In with OTP" %}{% endblock title %}
{% block title %}{% trans "WebVirtCloud" %} - {% trans "Sign in with OTP" %}{% endblock title %}
{% block page_header %}{% endblock page_header %}{# the page has its own heading #}
{% block content %}
<div class="row justify-content-center pt-5">
@ -12,14 +12,21 @@
<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-shield-check"></i></div>
<h1 class="h3 fw-bold mb-1">{% trans "Two-Factor Auth" %}</h1>
<h1 class="h3 fw-bold mb-1">{% trans "Two-factor authentication" %}</h1>
<p class="text-body-secondary small mb-0">{% trans "Enter your authentication code to continue" %}</p>
</div>
{% if app_settings.LOGIN_NOTICE %}
<div class="alert alert-info d-flex align-items-center mb-4" role="note">
<i class="bi bi-info-circle-fill fs-5 me-2 flex-shrink-0"></i>
<div>{{ app_settings.LOGIN_NOTICE }}</div>
</div>
{% endif %}
{% if form.errors %}
<div class="alert alert-danger d-flex align-items-center mb-4" role="alert">
<i class="bi bi-exclamation-triangle-fill fs-5 me-2 flex-shrink-0"></i>
<div>{% bootstrap_form_errors form %}</div>
<div>{% for errors in form.errors.values %}{% for error in errors %}<div>{{ error }}</div>{% endfor %}{% endfor %}</div>
</div>
{% endif %}
@ -29,7 +36,7 @@
<label class="form-label small fw-medium" for="id_username">{% trans "Username" %}</label>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-person"></i></span>
<input type="text" id="id_username" class="form-control" name="username" value="{{ form.username.value|default:'' }}" placeholder="{% trans 'Enter username' %}" autocapitalize="none" autocorrect="off" required>
<input type="text" id="id_username" class="form-control" name="username" value="{{ form.username.value|default:'' }}" placeholder="{% trans 'Enter username' %}" autocomplete="username" autocapitalize="none" autocorrect="off" {% if not form.non_field_errors %}autofocus {% endif %}required>
</div>
</div>
@ -37,35 +44,31 @@
<label class="form-label small fw-medium" for="id_password">{% trans "Password" %}</label>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-shield-lock"></i></span>
<input type="password" id="id_password" class="form-control" name="password" placeholder="{% trans 'Enter password' %}" required>
<button class="btn btn-outline-secondary" type="button" id="btn-toggle-pwd" tabindex="-1" aria-label="{% trans 'Toggle password visibility' %}">
<input type="password" id="id_password" class="form-control" name="password" placeholder="{% trans 'Enter password' %}" autocomplete="current-password" {% if form.non_field_errors %}autofocus {% endif %}required>
<button class="btn btn-outline-secondary" type="button" id="btn-toggle-pwd" aria-label="{% trans 'Toggle password visibility' %}">
<i class="bi bi-eye" id="toggle-icon"></i>
</button>
</div>
<div id="caps-lock" class="form-text d-none"><i class="bi bi-capslock-fill text-warning me-1"></i>{% trans "Caps Lock is on" %}</div>
</div>
<div class="mb-4">
<div class="d-flex justify-content-between align-items-center mb-2">
<label class="form-label small fw-medium mb-0" for="id_otp_token">{% trans "Security Code" %}</label>
<label class="form-label small fw-medium mb-0" for="id_otp_token">{% trans "Security code" %}</label>
<a href="{% url 'accounts:email_otp' %}" class="small">{% trans "Lost OTP?" %}</a>
</div>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-key"></i></span>
<input type="text" id="id_otp_token" class="form-control font-monospace" name="otp_token" placeholder="000000" inputmode="numeric" pattern="[0-9]*" maxlength="6" autofocus>
<input type="text" id="id_otp_token" class="form-control font-monospace" name="otp_token" placeholder="000000" inputmode="numeric" pattern="[0-9]*" maxlength="6" autocomplete="one-time-code">
</div>
<div class="form-text">{% trans "Leave empty if you have not set up two-factor authentication." %}</div>
</div>
<button id="btn-signin" class="btn btn-primary w-100 py-2" type="submit" data-busy-text="{% trans "Verifying..." %}">
<button id="btn-signin" class="btn btn-primary w-100 py-2" type="submit">
<i class="bi bi-shield-lock-fill me-1"></i>
<span id="btn-text">{% trans "Verify & Sign In" %}</span>
<span id="btn-text">{% trans "Verify and sign in" %}</span>
</button>
</form>
<div class="d-flex align-items-center small text-body-secondary border-top mt-4 pt-3">
<span class="d-inline-block rounded-circle p-1 bg-success me-2" aria-hidden="true"></span>
{% trans "2FA Protection Active" %}
</div>
</div>
</div>
</div>

View file

@ -1,9 +1,9 @@
{% extends "base.html" %}
{% load i18n static %}
{% block title %}{% trans "OTP QR Code" %}{% endblock %}
{% block title %}{% trans "OTP QR code" %}{% endblock %}
{% block page_heading %}{% trans "OTP QR Code" %}{% endblock page_heading %}
{% block page_heading %}{% trans "OTP QR code" %}{% endblock page_heading %}
{% block content %}
<div class="card">

View file

@ -2,7 +2,8 @@
{% load static %}
{% load i18n %}
{% block title %}{% trans "WebVirtCloud" %} - {% trans "Sign In" %}{% endblock title %}
{% block title %}{% trans "WebVirtCloud" %} - {% trans "Sign in" %}{% endblock title %}
{% block page_header %}{% endblock page_header %}{# the page has its own heading #}
{% block content %}
<div class="row justify-content-center pt-5">
@ -12,9 +13,16 @@
<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>
<h1 class="h3 fw-bold mb-1">WebVirtCloud</h1>
<p class="text-body-secondary small mb-0">{% trans "Virtualization Management Console" %}</p>
<p class="text-body-secondary small mb-0">{% trans "Virtualization management console" %}</p>
</div>
{% if app_settings.LOGIN_NOTICE %}
<div class="alert alert-info d-flex align-items-center mb-4" role="note">
<i class="bi bi-info-circle-fill fs-5 me-2 flex-shrink-0"></i>
<div>{{ app_settings.LOGIN_NOTICE }}</div>
</div>
{% endif %}
{% if form.errors %}
<div class="alert alert-danger d-flex align-items-center mb-4" role="alert">
<i class="bi bi-exclamation-triangle-fill fs-5 me-2 flex-shrink-0"></i>
@ -28,7 +36,7 @@
<label class="form-label small fw-medium" for="id_username">{% trans "Username" %}</label>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-person"></i></span>
<input type="text" id="id_username" class="form-control" name="username" placeholder="{% trans 'Enter username' %}" autocapitalize="none" autocorrect="off" autofocus required>
<input type="text" id="id_username" class="form-control" name="username" value="{{ form.username.value|default:'' }}" placeholder="{% trans 'Enter username' %}" autocomplete="username" autocapitalize="none" autocorrect="off" {% if not form.non_field_errors %}autofocus {% endif %}required>
</div>
</div>
@ -36,25 +44,21 @@
<label class="form-label small fw-medium" for="id_password">{% trans "Password" %}</label>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-shield-lock"></i></span>
<input type="password" id="id_password" class="form-control" name="password" placeholder="{% trans 'Enter password' %}" required>
<button class="btn btn-outline-secondary" type="button" id="btn-toggle-pwd" tabindex="-1" aria-label="{% trans 'Toggle password visibility' %}">
<input type="password" id="id_password" class="form-control{% if form.non_field_errors %} is-invalid{% endif %}" name="password" placeholder="{% trans 'Enter password' %}" autocomplete="current-password" {% if form.non_field_errors %}autofocus {% endif %}required>
<button class="btn btn-outline-secondary" type="button" id="btn-toggle-pwd" aria-label="{% trans 'Toggle password visibility' %}">
<i class="bi bi-eye" id="toggle-icon"></i>
</button>
</div>
<div id="caps-lock" class="form-text d-none"><i class="bi bi-capslock-fill text-warning me-1"></i>{% trans "Caps Lock is on" %}</div>
</div>
<input type="hidden" name="next" value="{{ next }}">
<button id="btn-signin" class="btn btn-primary w-100 py-2" type="submit" data-busy-text="{% trans "Signing in..." %}">
<button id="btn-signin" class="btn btn-primary w-100 py-2" type="submit">
<i class="bi bi-box-arrow-in-right me-1"></i>
<span id="btn-text">{% trans "Sign In" %}</span>
<span id="btn-text">{% trans "Sign in" %}</span>
</button>
</form>
<div class="d-flex align-items-center small text-body-secondary border-top mt-4 pt-3">
<span class="d-inline-block rounded-circle p-1 bg-success me-2" aria-hidden="true"></span>
KVM / Libvirt
</div>
</div>
</div>
</div>

View file

@ -20,7 +20,7 @@
<span class="badge text-bg-secondary">{% trans "Template editor" %}</span>
{% endif %}
</div>
<div class="text-body-secondary text-break">{{ user.username }}</div>
{% if user.get_full_name %}<div class="text-body-secondary text-break">{{ user.username }}</div>{% endif %}
{% if user.email %}<div class="small text-break mt-2">{{ user.email }}</div>{% endif %}
<div class="small text-body-secondary mt-2">{% trans "Last login" %} {{ user.last_login|date:"Y-m-d H:i"|default:_("never") }}</div>
</div>
@ -32,7 +32,7 @@
{# an LDAP user's password is changed in LDAP #}
{% if perms.accounts.change_password and user.has_usable_password %}
<div class="card-footer">
<a href="{% url 'accounts:change_password' %}" class="btn btn-sm btn-outline-secondary">{% bs_icon 'lock' %} {% trans "Change Password" %}</a>
<a href="{% url 'accounts:change_password' %}" class="btn btn-sm btn-outline-secondary">{% bs_icon 'lock' %} {% trans "Change password" %}</a>
</div>
{% endif %}
</section>
@ -41,9 +41,9 @@
<div class="col-lg-8">
<section class="card mb-4" id="sshkeys" aria-labelledby="sshkeys-title">
<div class="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
<h2 class="h5 mb-0" id="sshkeys-title">{% trans "SSH Keys" %} <span class="badge text-bg-light border">{{ publickeys|length }}</span></h2>
<h2 class="h5 mb-0" id="sshkeys-title">{% trans "SSH keys" %} <span class="badge text-bg-light border">{{ publickeys|length }}</span></h2>
<button class="btn btn-sm btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#add-ssh-key" aria-expanded="false" aria-controls="add-ssh-key">
{% bs_icon 'plus-lg' %} {% trans "Add SSH Key" %}
{% bs_icon 'plus-lg' %} {% trans "Add SSH key" %}
</button>
</div>
<div class="card-body small text-body-secondary">{% trans "Offered when you create a VM and on a VM's Access tab." %}</div>
@ -59,7 +59,7 @@
<section class="card" id="apitokens" aria-labelledby="apitokens-title">
<div class="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
<h2 class="h5 mb-0" id="apitokens-title">{% trans "API Tokens" %} <span class="badge text-bg-light border">{{ api_tokens|length }}</span></h2>
<h2 class="h5 mb-0" id="apitokens-title">{% trans "API tokens" %} <span class="badge text-bg-light border">{{ api_tokens|length }}</span></h2>
<button class="btn btn-sm btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#create-api-token" aria-expanded="false" aria-controls="create-api-token">
{% bs_icon 'plus-lg' %} {% trans "Create an API token" %}
</button>

View file

@ -22,6 +22,19 @@ class AccountPageTests(TestCase):
def page(self):
return self.client.get(reverse("accounts:account", args=[self.alice.pk]))
def test_the_vms_and_keys_are_in_name_order(self):
compute = Compute.objects.create(name="ap-host", hostname="localhost", login="", password="", details="", type=4)
for i, name in enumerate(("web", "db")):
vm = Instance.objects.create(compute=compute, name=name, uuid=f"00000000-0000-0000-0000-00000000010{i}")
UserInstance.objects.create(user=self.alice, instance=vm)
UserSSHKey.objects.create(user=self.alice, keyname="desktop", keypublic=KEY)
response = self.page()
self.assertEqual([ui.instance.name for ui in response.context["user_insts"]], ["db", "web"])
self.assertEqual([key.keyname for key in response.context["publickeys"]], ["desktop", "laptop"])
self.client.force_login(self.alice)
response = self.client.get(reverse("accounts:profile"))
self.assertEqual([key.keyname for key in response.context["publickeys"]], ["desktop", "laptop"])
def test_the_permissions_are_marks_not_true_or_false(self):
compute = Compute.objects.create(name="ap-host", hostname="localhost", login="", password="", details="", type=4)
vm = Instance.objects.create(compute=compute, name="ap-vm", uuid="00000000-0000-0000-0000-000000000001")

View file

@ -4,7 +4,8 @@ from django.test import SimpleTestCase, override_settings
from accounts.checks import login_required_middleware_check
OLD = "login_required.middleware.LoginRequiredMiddleware"
NEW = "django.contrib.auth.middleware.LoginRequiredMiddleware"
NEW = "webvirtcloud.middleware.LoginRequiredMiddleware"
DJANGO = "django.contrib.auth.middleware.LoginRequiredMiddleware"
class LoginRequiredMiddlewareCheckTestCase(SimpleTestCase):
@ -19,5 +20,9 @@ class LoginRequiredMiddlewareCheckTestCase(SimpleTestCase):
old = [OLD if m == NEW else m for m in settings.MIDDLEWARE]
self.assertEqual(self.ids(old), ["accounts.E002"])
def test_django_s_own_is_warned_of(self):
# it signs in too: an update with it in data/local_settings.py still starts the panel
self.assertEqual(self.ids([DJANGO if m == NEW else m for m in settings.MIDDLEWARE]), ["accounts.W002"])
def test_missing_login_middleware_is_rejected(self):
self.assertEqual(self.ids([m for m in settings.MIDDLEWARE if m != NEW]), ["accounts.E002"])

View file

@ -0,0 +1,127 @@
"""The sign-in page: a failed sign-in keeps the username and puts the cursor
on the password, a locked user gets a page with the lock time, and the
administrator's notice from the Settings page is shown above the form; a sign-in
lasts the hours set there, and a superuser can end a lock."""
from appsettings.models import AppSettings
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
@override_settings(OTP_ENABLED=False)
class LoginPageTests(TestCase):
def setUp(self):
get_user_model().objects.create_user("lp-user", password="right-pass-1")
def login(self, password, username="lp-user", url=None):
return self.client.post(url or reverse("accounts:login"), {"username": username, "password": password})
def test_a_failed_sign_in_keeps_the_username_and_marks_the_password(self):
page = self.login("wrong").content.decode()
self.assertIn('value="lp-user"', page)
self.assertRegex(page, r'id="id_password" class="form-control is-invalid"[^>]*autofocus')
self.assertNotRegex(page, r'id="id_username"[^>]*autofocus')
def test_a_username_error_keeps_the_cursor_on_the_username(self):
page = self.login("right-pass-1", username="u" * 151).content.decode()
self.assertRegex(page, r'id="id_username"[^>]*autofocus')
self.assertNotIn("is-invalid", page)
def test_the_lock_page_links_back_with_the_destination(self):
AppSettings.objects.filter(key="LOGIN_FAILURE_LIMIT").update(value="1")
url = reverse("accounts:login") + "?next=/computes/"
self.login("wrong", url=url)
self.assertContains(self.login("wrong", url=url), 'href="%s?next=/computes/"' % reverse("accounts:login"),
status_code=429)
def test_the_empty_page_focuses_the_username(self):
page = self.client.get(reverse("accounts:login")).content.decode()
self.assertRegex(page, r'id="id_username"[^>]*autocomplete="username"[^>]*autofocus')
self.assertIn('autocomplete="current-password"', page)
self.assertIn('id="caps-lock"', page)
def test_a_locked_user_gets_the_lock_page_with_the_lock_time(self):
AppSettings.objects.filter(key="LOGIN_FAILURE_LIMIT").update(value="2")
AppSettings.objects.filter(key="LOGIN_LOCKOUT_MINUTES").update(value="20")
self.login("wrong")
self.login("wrong")
response = self.login("right-pass-1")
self.assertEqual(response.status_code, 429)
self.assertTemplateUsed(response, "accounts/lockout.html")
self.assertEqual(response.content.decode().count("<h1"), 1)
self.assertContains(response, "The lock ends within 20 minutes.", status_code=429)
def test_the_notice_is_shown_only_when_set(self):
self.assertNotContains(self.client.get(reverse("accounts:login")), "alert-info")
AppSettings.objects.filter(key="LOGIN_NOTICE").update(value="Maintenance at <22:00>")
self.assertContains(self.client.get(reverse("accounts:login")), "Maintenance at &lt;22:00&gt;")
@override_settings(OTP_ENABLED=False)
class SessionLengthTests(TestCase):
def test_a_sign_in_lasts_the_hours_from_the_settings_page(self):
get_user_model().objects.create_user("sl-user", password="right-pass-1")
self.client.post(reverse("accounts:login"), {"username": "sl-user", "password": "right-pass-1"})
self.assertAlmostEqual(self.client.session.get_expiry_age(), 24 * 3600, delta=5)
AppSettings.objects.filter(key="LOGIN_SESSION_HOURS").update(value="2")
self.client.post(reverse("accounts:logout"))
self.client.post(reverse("accounts:login"), {"username": "sl-user", "password": "right-pass-1"})
self.assertAlmostEqual(self.client.session.get_expiry_age(), 2 * 3600, delta=5)
# a later save of the session does not move the end
end = self.client.session.get_expiry_date()
session = self.client.session
session["touched"] = True
session.save()
self.assertEqual(self.client.session.get_expiry_date(), end)
@override_settings(OTP_ENABLED=False)
class UnlockTests(TestCase):
def setUp(self):
User = get_user_model()
self.user = User.objects.create_user("ul-user", password="right-pass-1")
self.admin = User.objects.create_superuser("ul-admin", "ul@example.com", "admin-pass-1")
AppSettings.objects.filter(key="LOGIN_FAILURE_LIMIT").update(value="2")
# one failure from each of two browsers at the same address, one typed in capitals
self.client.post(reverse("accounts:login"), {"username": "ul-user", "password": "wrong"},
HTTP_USER_AGENT="browser-a")
self.client.post(reverse("accounts:login"), {"username": "UL-User", "password": "wrong"},
HTTP_USER_AGENT="browser-b")
self.client.post(reverse("accounts:login"), {"username": "ul-user", "password": "wrong"},
HTTP_USER_AGENT="browser-b")
def sign_in_works(self):
client = self.client_class()
return client.post(reverse("accounts:login"), {"username": "ul-user", "password": "right-pass-1"}).status_code == 302
def test_the_lock_is_shown_and_a_superuser_ends_it(self):
self.assertFalse(self.sign_in_works())
self.client.force_login(self.admin)
self.assertContains(self.client.get(reverse("admin:user_list")), "Sign-in locked")
self.assertContains(self.client.get(reverse("accounts:account", args=[self.user.pk])), "Unlock sign-in")
self.client.post(reverse("accounts:admin_unlock", args=[self.user.pk]))
self.assertTrue(self.sign_in_works())
self.assertNotContains(self.client.get(reverse("accounts:account", args=[self.user.pk])), "Sign-in locked")
from logs.models import Logs
self.assertTrue(Logs.objects.filter(message__icontains="unlock sign-in").exists())
def test_only_a_superuser_unlocks(self):
other = get_user_model().objects.create_user("ul-other", password="other-pass-1")
self.client.force_login(other)
self.assertEqual(self.client.post(reverse("accounts:admin_unlock", args=[self.user.pk])).status_code, 403)
self.assertFalse(self.sign_in_works())
@override_settings(OTP_ENABLED=False)
class BlockEndsSessionsTests(TestCase):
def test_a_blocked_user_is_signed_out(self):
User = get_user_model()
User.objects.create_user("bl-user", password="right-pass-1")
user_client = self.client_class()
user_client.post(reverse("accounts:login"), {"username": "bl-user", "password": "right-pass-1"})
self.client.force_login(User.objects.create_superuser("bl-admin", "bl@example.com", "admin-pass-1"))
self.client.post(reverse("admin:user_block", args=[User.objects.get(username="bl-user").pk]))
self.assertEqual(user_client.get(reverse("instances:index")).status_code, 302)
from django.contrib.sessions.models import Session
self.assertEqual(Session.objects.count(), 1) # the administrator's

View file

@ -108,7 +108,7 @@ class AccountsUtilsTestCase(TestCase):
send_email_with_otp(RequestFactory().get("/"), device)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertEqual((message.subject, message.to, message.alternatives), ("OTP QR Code", ["user@example.com"], []))
self.assertEqual((message.subject, message.to, message.alternatives), ("OTP QR code", ["user@example.com"], []))
self.assertNotIn(device.bin_key.hex(), message.body)
self.assertNotIn("otpauth", message.body)
# the token is the fragment, which no request (no access log) carries

View file

@ -4,6 +4,7 @@ from appsettings.models import AppSettings
from appsettings.settings import app_settings
from computes.models import Compute
from django.conf import settings
from django.contrib.messages import get_messages
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.shortcuts import reverse
@ -192,6 +193,8 @@ class AccountsTestCase(TestCase):
self.assertRedirects(
response, reverse("accounts:account", args=[self.test_user.id])
)
self.assertIn(f"{self.test_user.username} is no longer an owner of {self.instance.name}",
[str(m) for m in get_messages(response.wsgi_request)])
# test 'next' redirect during deletion
user_instance = UserInstance.objects.create(

View file

@ -45,6 +45,7 @@ urlpatterns = [
name="admin_email_otp",
),
path("admin_reset_otp/<int:user_id>/", views.admin_reset_otp, name="admin_reset_otp"),
path("admin_unlock/<int:user_id>/", views.admin_unlock, name="admin_unlock"),
]
if settings.OTP_ENABLED:

View file

@ -63,7 +63,7 @@ def send_email_with_otp(request, device):
user = device.user
url = request.build_absolute_uri(reverse("accounts:otp_qr")) + "#" + OTP_LINK.sign(str(device.pk))
send_mail(
_("OTP QR Code"),
_("OTP QR code"),
_("Open this link within an hour to see the OTP QR code of account '%(user)s':\n\n%(url)s")
% {"user": user, "url": url},
None,

View file

@ -33,11 +33,12 @@ from accounts.forms import ApiTokenForm, EmailOTPForm, ProfileForm, UserSSHKeyFo
from accounts.models import ApiToken, User, UserAttributes, UserInstance, UserSSHKey
from . import forms
from .lockout import locked_usernames, unlock
from .utils import OTP_LINK, OTP_LINK_MAX_AGE, get_existing_totp_device, get_user_totp_device, otp_qr_svg, send_email_with_otp
def profile(request):
publickeys = UserSSHKey.objects.filter(user_id=request.user.id)
publickeys = UserSSHKey.objects.filter(user_id=request.user.id).order_by("keyname")
profile_form = ProfileForm(request.POST or None, instance=request.user)
ssh_key_form = UserSSHKeyForm()
@ -192,8 +193,9 @@ def ssh_key_delete(request, pk, user_id=None):
@superuser_only
def account(request, user_id):
user = get_object_or_404(User, id=user_id)
user_insts = UserInstance.objects.filter(user_id=user_id).select_related("instance__compute")
publickeys = UserSSHKey.objects.filter(user_id=user_id)
user_insts = UserInstance.objects.filter(user_id=user_id).select_related("instance__compute").prefetch_related(
"instance__tags").order_by("instance__name")
publickeys = UserSSHKey.objects.filter(user_id=user_id).order_by("keyname")
return render(
request,
@ -205,6 +207,7 @@ def account(request, user_id):
"api_tokens": ApiToken.objects.filter(user_id=user_id),
"otp_enabled": settings.OTP_ENABLED,
"has_otp": TOTPDevice.objects.filter(user=user).exists(),
"locked": user.username.lower() in locked_usernames(),
},
)
@ -234,7 +237,7 @@ def change_password(request):
pass
except OSError:
logging.getLogger(__name__).warning("Could not remove the generated admin password file")
messages.success(request, _("Password Changed"))
messages.success(request, _("Password changed"))
return redirect("accounts:profile")
if form.has_error("old_password", "password_incorrect"): # someone at an open session guessing it
failed(request, None, f"User {request.user.username}", "change password", "wrong old password")
@ -265,7 +268,7 @@ def user_instance_create(request, user_id):
"common/form.html",
{
"form": form,
"title": _("Create User Instance"),
"title": _("Create user instance"),
"searchable": True,
},
)
@ -300,7 +303,7 @@ def user_instance_update(request, pk):
"common/form.html",
{
"form": form,
"title": _("Update User Instance"),
"title": _("Update user instance"),
},
)
@ -311,7 +314,9 @@ def user_instance_delete(request, pk):
if request.method == "POST":
user, instance = user_instance.user, user_instance.instance
with audit_vm(request, instance, f"remove owner {user.username}"):
user_instance.delete()
deleted, _rows = user_instance.delete()
if deleted: # not by another request just before
messages.success(request, _("%(user)s is no longer an owner of %(vm)s") % {"user": user.username, "vm": instance.name})
return _next_or(request, reverse("accounts:account", args=[user.id]))
return render(
@ -408,6 +413,17 @@ def admin_email_otp(request, user_id):
return redirect("accounts:account", user.id)
@require_POST
@superuser_only
def admin_unlock(request, user_id):
"""End the user's lock after failed sign-ins, from every address."""
user = get_object_or_404(get_user_model(), pk=user_id)
with audit(request, None, f"User {user.username}", "unlock sign-in") as entry:
entry.skip = not unlock(user.username) # another administrator was first, or the lock ran out
messages.success(request, _("The sign-in lock of %(user)s is ended.") % {"user": user})
return redirect("accounts:account", user.id)
@require_POST
@superuser_only
def admin_reset_otp(request, user_id):

View file

@ -12,6 +12,7 @@ from django.utils.translation import gettext_lazy as _
from accounts.forms import UniqueEmailMixin
from accounts.models import UserAttributes, UserInstance
from appsettings.settings import app_settings
from computes.models import Tag
from instances.models import Instance
from .models import Permission
@ -19,6 +20,7 @@ from .models import Permission
# each permission's name in the user's language: the database keeps the English one
PERMISSION_NAMES = {
"backup_instances": _("Can back up instances"),
"change_password": _("Can change password"),
"clone_instances": _("Can clone instances"),
"passwordless_console": _("Can access console without password"),
@ -28,6 +30,8 @@ PERMISSION_NAMES = {
# what each permission lets a user do, shown beside its switch
PERMISSION_HELP = {
"backup_instances": _("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"),
"change_password": _("Change their own password on their profile page"),
"clone_instances": _("Clone the VMs they may change and the templates they may view, within their quota"),
"passwordless_console": _("Open a console without the VM's console password"),
@ -46,6 +50,16 @@ def permission_rows(field):
return rows
class TagForm(forms.ModelForm):
class Meta:
model = Tag
fields = ["name"]
error_messages = {"name": {"unique": _("There is a tag with this name already")}}
def clean_name(self):
return self.cleaned_data["name"].strip().lower()
class GroupForm(forms.ModelForm):
permissions = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
@ -85,6 +99,7 @@ class UserForm(UniqueEmailMixin, forms.ModelForm):
# one choice for is_staff and is_superuser: a superuser keeps the
# is_staff it had (it adds nothing to every permission)
role = forms.ChoiceField(
label=_("Role"),
widget=forms.RadioSelect,
choices=[("user", _("User")), ("template_editor", _("Template editor")), ("superuser", _("Superuser"))],
initial="user",
@ -136,7 +151,7 @@ class UserForm(UniqueEmailMixin, forms.ModelForm):
return permission_rows(self["user_permissions"])
class UserCreateForm(UserForm):
password = forms.CharField(widget=forms.PasswordInput)
password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@ -197,7 +212,7 @@ class UserCreateForm(UserForm):
# the quota's limits, with the unit each is entered in (memory in GiB, kept in MiB)
QUOTA_UNITS = {"max_instances": "", "max_cpus": "", "max_memory": "GiB", "max_disk_size": "GiB"}
QUOTA_UNITS = {"max_instances": "", "max_cpus": "", "max_memory": "GiB", "max_disk_size": "GiB", "max_backup_size": "GiB"}
class UserAttributesForm(forms.ModelForm):
@ -208,6 +223,7 @@ class UserAttributesForm(forms.ModelForm):
max_cpus = forms.IntegerField(label=_("vCPUs"), min_value=0, required=False)
max_memory = forms.DecimalField(label=_("Memory"), min_value=0, required=False)
max_disk_size = forms.IntegerField(label=_("Disk"), min_value=0, required=False)
max_backup_size = forms.IntegerField(label=_("Backups"), min_value=0, required=False)
class Meta:
model = UserAttributes

View file

@ -0,0 +1,2 @@
{% load i18n %}{# how a log row's action ended (logs.html) #}
{% if log.success is None %}<span class="small text-body-secondary">{% trans "Unknown" %}</span>{% elif log.success %}<span class="badge text-bg-light border">{% trans "Done" %}</span>{% else %}<span class="badge text-bg-danger">{% trans "Failed" %}</span>{% endif %}

View file

@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% load django_bootstrap5 %}
{% load bootstrap_icons %}
@ -15,7 +16,7 @@
{% block content %}
<div class="card mb-3">
{# the search runs on the server over every row; the download takes the same rows #}
<form method="get" class="card-header d-flex flex-wrap align-items-center gap-2" role="search">
<form method="get" class="card-header d-flex flex-wrap align-items-center gap-2" role="search" data-filter-form>
<span class="me-auto">{% trans "Logs" %} <span class="badge text-bg-light border">{{ logs.paginator.count }}</span></span>
<input name="q" value="{{ q }}" class="form-control form-control-sm w-auto" type="search" placeholder="{% trans 'Search' %}"
aria-label="{% trans 'Search the logs' %}">
@ -23,7 +24,7 @@
<input id="logs-failed" class="form-check-input" type="checkbox" name="failed" value="1"{% if failed %} checked{% endif %}>
<label class="form-check-label small" for="logs-failed">{% trans "Failed only" %}</label>
</div>
<button type="submit" class="btn btn-sm btn-primary">{% trans "Search" %}</button>
{% if q or failed %}<a class="btn btn-sm btn-link" href="{% url 'admin:logs' %}">{% trans "Clear the filters" %}</a>{% endif %}
</form>
{% if not logs %}
<div class="card-body text-center text-body-secondary">
@ -32,29 +33,30 @@
{% else %}
<div class="table-responsive position-relative">
<table class="table table-hover align-middle mb-0">
{# on a phone: the date, who, which VM, and what, with how it ended under it #}
<thead>
<tr>
<th scope="col">#</th>
<th scope="col" class="d-none d-md-table-cell">#</th>
<th scope="col">{% blocktrans %}Date ({{ time_zone }}){% endblocktrans %}</th>
<th scope="col">{% trans "User" %}</th>
<th scope="col">{% trans "Host" %}</th>
<th scope="col" class="d-none d-md-table-cell">{% trans "Host" %}</th>
<th scope="col">{% trans "Instance" %}</th>
<th scope="col">{% trans "Message" %}</th>
<th scope="col">{% trans "Result" %}</th>
<th scope="col">{% trans "IP" %}</th>
<th scope="col" class="d-none d-md-table-cell">{% trans "Result" %}</th>
<th scope="col" class="d-none d-md-table-cell">{% trans "IP" %}</th>
</tr>
</thead>
<tbody>
{% for log in logs %}
<tr>
<td class="small text-body-secondary">{{ log.id }}</td>
<td class="small text-nowrap">{{ log.date|date:"Y-m-d H:i:s" }}</td>
<td class="small text-body-secondary d-none d-md-table-cell">{{ log.id }}</td>
<td class="small"><span class="text-nowrap">{{ log.date|date:"Y-m-d" }}</span> <span class="text-nowrap">{{ log.date|date:"H:i:s" }}</span></td>
<td>{{ log.user }}</td>
<td>{{ log.host }}</td>
<td class="d-none d-md-table-cell">{{ log.host }}</td>
<td>{% if log.vm_pk %}<a href="{% url 'instances:instance' log.vm_pk %}">{{ log.instance }}</a>{% else %}{{ log.instance }}{% endif %}</td>
<td class="log-message">{{ log.message }}</td>
<td>{% if log.success is None %}<span class="small text-body-secondary">{% trans "Unknown" %}</span>{% elif log.success %}<span class="badge text-bg-light border">{% trans "Done" %}</span>{% else %}<span class="badge text-bg-danger">{% trans "Failed" %}</span>{% endif %}</td>
<td class="small font-monospace">{{ log.ip|default:"" }}</td>
<td class="log-message">{{ log.message }}<div class="d-md-none">{% include "admin/log_result.html" %}</div></td>
<td class="d-none d-md-table-cell">{% include "admin/log_result.html" %}</td>
<td class="small font-monospace d-none d-md-table-cell">{{ log.ip|default:"" }}</td>
</tr>
{% endfor %}
</tbody>
@ -64,3 +66,4 @@
</div>
{% if logs %}{% bootstrap_pagination logs extra=query pages_to_show=5 extra_classes="flex-wrap" %}{% endif %}
{% endblock %}
{% block script %}<script src="{% static 'js/filter_form.js' %}"></script>{% endblock %}

View file

@ -0,0 +1,55 @@
{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% load bootstrap_icons %}
{% block title %}{% trans "Tags" %}{% endblock %}
{% block page_heading %}{% trans "Tags" %}{% endblock page_heading %}
{% block content %}
<p class="text-body-secondary">{% trans "The tags of VMs and hosts. A tag is made when it is first given, on a VM's Options tab or a host's form." %}</p>
{% if not tags %}
<p class="text-center text-body-secondary py-4">{% trans "No tags yet" %}</p>
{% else %}
<div class="card mb-3">
<div class="card-header d-flex flex-wrap align-items-center gap-2">
<span class="me-auto">{% trans "Tags" %} <span class="badge text-bg-light border">{{ tags|length }}</span></span>
<input id="filter" class="form-control form-control-sm w-auto" type="search" placeholder="{% trans "Search" %}" aria-label="{% trans "Search tags" %}">
</div>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0" data-sortable>
<thead>
<tr>
<th scope="col">{% trans "Tag" %}</th>
<th scope="col" data-sort-method="number">{% trans "VMs" %}</th>
<th scope="col" data-sort-method="number">{% trans "Hosts" %}</th>
<th scope="col" data-sort-method="none"><span class="visually-hidden">{% trans "Actions" %}</span></th>
</tr>
</thead>
<tbody class="searchable">
{% for tag in tags %}
<tr data-search="{{ tag.name }}">
<td>{% include 'common/tag_badge.html' with tag=tag.name %}</td>
{# the VM list or the Computes page, showing the tag's only #}
<td>{% if tag.vm_count %}<a href="{% url 'instances:index' %}?tag={{ tag.name|urlencode }}">{{ tag.vm_count }}</a>{% else %}0{% endif %}</td>
<td>{% if tag.host_count %}<a href="{% url 'computes' %}?tag={{ tag.name|urlencode }}">{{ tag.host_count }}</a>{% else %}0{% endif %}</td>
<td class="text-end text-nowrap">
<a class="btn btn-sm btn-outline-secondary" href="{% url 'admin:tag_update' tag.id %}">{% trans "Rename" %}</a>
<a class="btn btn-sm btn-outline-danger" href="{% url 'admin:tag_delete' tag.id %}">{% trans "Delete" %}</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div role="status">
<div id="no-match" class="text-center text-body-secondary py-3" hidden>{% trans "No tag matches the search." %}</div>
</div>
</div>
{% endif %}
{% endblock content %}
{% block script %}
{% if tags %}<script src="{% static 'js/table_filter.js' %}"></script>{% endif %}
{% endblock script %}

View file

@ -8,11 +8,9 @@
{% block page_heading %}{% trans "Removed VMs" %}{% endblock page_heading %}
{% block content %}
<p class="text-body-secondary">{% trans "VMs that vanished from their compute. Their owners come back if the same UUID shows up again before the record expires." %}</p>
<p class="text-body-secondary">{% trans "VMs that vanished from their compute. Their owners, tags, protection and schedules come back if the same UUID shows up again before the record expires; their backups come back with them." %}</p>
{% if not tombstones %}
<div class="alert alert-info shadow-sm">
{% bs_icon 'info-circle' %} {% trans "No removed VMs" %}
</div>
<p class="text-center text-body-secondary py-4">{% trans "No removed VMs" %}</p>
{% else %}
<div class="card mb-3">
<div class="card-header d-flex flex-wrap align-items-center gap-2">
@ -21,11 +19,13 @@
</div>
<div class="list-group list-group-flush searchable">
{% for tombstone in tombstones %}
<div class="list-group-item py-3" data-search="{{ tombstone.name }} {{ tombstone.uuid }} {{ tombstone.host }} {{ tombstone.owner_names|join:' ' }}">
<div class="list-group-item py-3" data-search="{{ tombstone.name }} {{ tombstone.uuid }} {{ tombstone.host }} {{ tombstone.owner_names|join:' ' }} {{ tombstone.tags|join:' ' }}">
<div class="row g-2 align-items-center">
<div class="col-12 col-md-4">
<span class="fw-semibold text-break">{{ tombstone.name }}</span>
{% if tombstone.is_template %}<span class="badge text-bg-light border">{% trans "Template" %}</span>{% endif %}
{% if tombstone.protected %}<span class="badge text-bg-light border">{% trans "Protected" %}</span>{% endif %}
{% include 'common/tag_badges.html' with tags=tombstone.tags %}
<div class="font-monospace small text-body-secondary text-break mt-1">{{ tombstone.uuid }}</div>
</div>
<div class="col-12 col-md-5 small">
@ -33,6 +33,12 @@
{% trans "Left" %} <span class="fw-semibold">{{ tombstone.host }}</span>
<span class="text-body-secondary">· {% trans "Owners" %}:</span> {{ tombstone.owner_names|join:", "|default:"–" }}
</div>
{% if tombstone.policy_names or tombstone.backup_count %}
<div class="mt-1">
{% if tombstone.policy_names %}<span class="text-body-secondary">{% trans "Schedules" %}:</span> {{ tombstone.policy_names|join:", " }}{% endif %}
{% if tombstone.backup_count %}{% if tombstone.policy_names %} · {% endif %}{% blocktrans count counter=tombstone.backup_count %}{{ counter }} backup{% plural %}{{ counter }} backups{% endblocktrans %}{% endif %}
</div>
{% endif %}
<div class="text-body-secondary mt-1">
{% trans "Removed" %} <span class="text-nowrap">{{ tombstone.removed|date:"Y-m-d H:i" }}</span>
· {% trans "expires" %} <span class="text-nowrap">{{ tombstone.expires|date:"Y-m-d H:i" }}</span>

View file

@ -21,7 +21,7 @@
</div>
<div class="list-group list-group-flush searchable">
{% for user in users %}
<div class="list-group-item py-3" data-search="{{ user.username }} {{ user.email }}{% for group in user.groups.all %} {{ group.name }}{% endfor %} {% if user.is_superuser %}{% trans "Superuser" %}{% elif user.is_staff %}{% trans "Template editor" %}{% else %}{% trans "User" %}{% endif %} {% if user.is_active %}{% trans "Active" %}{% else %}{% trans "Blocked" %}{% endif %}">
<div class="list-group-item py-3" data-search="{{ user.username }} {{ user.email }}{% for group in user.groups.all %} {{ group.name }}{% endfor %} {% if user.is_superuser %}{% trans "Superuser" %}{% elif user.is_staff %}{% trans "Template editor" %}{% else %}{% trans "User" %}{% endif %} {% if user.is_active %}{% trans "Active" %}{% else %}{% trans "Blocked" %}{% endif %}{% if user.username|lower in locked %} {% trans "Sign-in locked" %}{% endif %}">
<div class="row g-2 align-items-center">
<div class="col-12 col-md-4">
<a href="{% url 'accounts:account' user.id %}" class="fw-semibold text-break">{{ user.username }}</a>
@ -38,6 +38,9 @@
{% else %}
<span class="badge text-bg-danger"><span aria-hidden="true">{% bs_icon 'slash-circle' %}</span> {% trans "Blocked" %}</span>
{% endif %}
{% if user.username|lower in locked %}
<a href="{% url 'accounts:account' user.id %}" class="badge bg-warning text-dark text-decoration-none"><span aria-hidden="true">{% bs_icon 'lock' %}</span> {% trans "Sign-in locked" %}</a>
{% endif %}
</div>
</div>
<div class="col-12 col-md-5 small">
@ -65,7 +68,8 @@
<li><a class="dropdown-item" href="{% url 'accounts:account' user.id %}">{% bs_icon 'person' %} {% trans "View profile" %}</a></li>
{# an administrator does not block or delete their own account #}
<li><form method="post" action="{% if user.is_active %}{% url 'admin:user_block' user.id %}{% else %}{% url 'admin:user_unblock' user.id %}{% endif %}">{% csrf_token %}
<button type="submit" class="dropdown-item"{% if user == request.user %} disabled{% endif %}>
<button type="submit" class="dropdown-item"{% if user == request.user %} disabled{% endif %}
{% if user.is_active %}data-confirm="{% blocktrans with name=user.username %}Block {{ name }}? They are signed out and their API tokens are deleted; unblocking does not bring the tokens back.{% endblocktrans %}"{% endif %}>
{% if user.is_active %}{% bs_icon 'slash-circle' %} {% trans "Block" %}{% else %}{% bs_icon 'play' %} {% trans "Unblock" %}{% endif %}
</button>
</form></li>

View file

@ -2,9 +2,9 @@
{% load django_bootstrap5 %}
{% load i18n %}
{% block title %}{% trans "Change Password" %}{% endblock %}
{% block title %}{% trans "Change password" %}{% endblock %}
{% block page_heading %}{% trans "Change Password" %}{% endblock page_heading %}
{% block page_heading %}{% trans "Change password" %}{% endblock page_heading %}
{% block content %}
{# an administrator sets another user's password, or takes it away (sign-in by LDAP, for one) #}

View file

@ -7,7 +7,7 @@ from django.urls import reverse
from logs.models import Logs
from admin.tests.edits import group_seen, user_seen
ATTRIBUTES = {"role": "user", "max_instances": 2, "max_cpus": 2, "max_memory": 2, "max_disk_size": 20}
ATTRIBUTES = {"role": "user", "max_instances": 2, "max_cpus": 2, "max_memory": 2, "max_disk_size": 20, "max_backup_size": 0}
def rows():

View file

@ -63,6 +63,7 @@ class LogsPageTests(TestCase):
self.assertEqual(self.rows(page)[0][1], log.date.strftime("%Y-%m-%d %H:%M:%S"))
def test_a_vm_row_links_the_vm_while_it_is_there(self):
# not its user or host: the row keeps their names, which another may take later
page = self.page(q="alice")
self.assertEqual(page.xpath("//tbody/tr/td/a/@href"), [reverse("instances:instance", args=[self.vm.pk])])
self.vm.delete()

135
admin/tests/test_tags.py Normal file
View file

@ -0,0 +1,135 @@
"""Superusers rename and delete the tags of VMs and hosts."""
from django.contrib.auth.models import User
from django.test import TestCase
from unittest.mock import patch
from django.urls import reverse
from django.utils import translation
from computes.models import Compute, Tag
from instances.models import Instance, InstanceTombstone
from logs.models import Logs
class TagAdminTests(TestCase):
def setUp(self):
self.client.force_login(User.objects.create_superuser("tg-admin", "tg@example.com", "pw"))
self.prod = Tag.objects.create(name="prod")
compute = Compute.objects.create(name="tg", hostname="192.0.2.7", login="u", password="p", type=1)
compute.tags.add(self.prod)
Instance.objects.create(compute=compute, name="vm", uuid="12345678-0000-0000-0000-00000000dd01").tags.add(self.prod)
self.tombstone = InstanceTombstone.objects.create(uuid="12345678-0000-0000-0000-00000000dd02", name="gone",
tags=["prod", "db"])
def messages(self):
return list(Logs.objects.filter(message__startswith="Tag").order_by("id").values_list("message", flat=True))
def test_the_list_counts_each_tag_s_vms_and_hosts(self):
response = self.client.get(reverse("admin:tag_list"))
self.assertEqual([(t.name, t.vm_count, t.host_count) for t in response.context["tags"]], [("prod", 1, 1)])
self.assertContains(response, 'class="badge tag-badge') # as small as on the other pages
def test_the_list_is_in_name_order_and_searched(self):
Tag.objects.create(name="web")
Tag.objects.create(name="db")
response = self.client.get(reverse("admin:tag_list"))
self.assertEqual([t.name for t in response.context["tags"]], ["db", "prod", "web"])
self.assertContains(response, 'id="filter"')
self.assertContains(response, 'data-search="web"')
def test_a_rename_keeps_the_tag_on_its_vms_hosts_and_removed_vms(self):
self.client.post(reverse("admin:tag_update", args=[self.prod.pk]), {"name": "Live"})
self.prod.refresh_from_db()
self.assertEqual(self.prod.name, "live")
self.assertEqual(self.prod.instances.count(), 1)
self.tombstone.refresh_from_db()
self.assertEqual(self.tombstone.tags, ["live", "db"])
self.assertEqual(self.messages(), ["Tag prod: rename to live"])
def test_a_name_taken_or_bad_is_refused(self):
Tag.objects.create(name="db")
for name in ("DB", "two words", "x" * 13):
with self.subTest(name):
response = self.client.post(reverse("admin:tag_update", args=[self.prod.pk]), {"name": name})
self.assertEqual(response.status_code, 200)
self.assertTrue(response.context["form"].errors)
self.prod.refresh_from_db()
self.assertEqual(self.prod.name, "prod")
def test_a_delete_takes_it_off_everything(self):
self.assertContains(self.client.get(reverse("admin:tag_delete", args=[self.prod.pk])), "1 VM and 1 host")
self.client.post(reverse("admin:tag_delete", args=[self.prod.pk]))
self.assertFalse(Tag.objects.exists())
self.assertFalse(Instance.objects.get(name="vm").tags.exists())
self.assertEqual(self.messages(), ["Tag prod: delete"])
def test_a_deleted_name_made_again_is_not_given_to_a_vm_that_returns(self):
self.client.post(reverse("admin:tag_delete", args=[self.prod.pk]))
self.tombstone.refresh_from_db()
self.assertEqual(self.tombstone.tags, ["db"])
def test_the_same_name_is_no_rename(self):
self.client.post(reverse("admin:tag_update", args=[self.prod.pk]), {"name": "PROD"})
self.assertEqual(self.messages(), [])
def test_a_tag_a_backup_schedule_uses_is_kept(self):
import datetime
from vmbackups.models import BackupPolicy, BackupTarget
BackupPolicy.objects.create(name="nightly", target=BackupTarget.objects.create(name="nfs"), tag=self.prod,
time=datetime.time(2), keep=3)
# the confirm page is not shown, and a delete sent anyway (the schedule saved since) is refused
self.assertContains(self.client.get(reverse("admin:tag_delete", args=[self.prod.pk]), follow=True),
"The backup schedule nightly backs up its VMs")
response = self.client.post(reverse("admin:tag_delete", args=[self.prod.pk]), follow=True)
self.assertContains(response, "The backup schedule nightly backs up its VMs")
self.assertTrue(Tag.objects.filter(name="prod").exists())
# what another request does while this one waits for the ownership lock
def meanwhile(self, change):
from computes import utils
real = utils.lock_ownership
def lock():
change()
real()
return patch("admin.views.lock_ownership", side_effect=lock)
def test_a_rename_meanwhile_is_cleaned_from_removed_vms_on_delete(self):
def rename():
Tag.objects.filter(pk=self.prod.pk).update(name="live")
InstanceTombstone.objects.filter(pk=self.tombstone.pk).update(tags=["live", "db"])
with self.meanwhile(rename):
self.client.post(reverse("admin:tag_delete", args=[self.prod.pk]))
self.tombstone.refresh_from_db()
self.assertEqual(self.tombstone.tags, ["db"])
def test_a_tag_deleted_while_its_rename_waits_is_not_found(self):
with self.meanwhile(lambda: Tag.objects.filter(pk=self.prod.pk).delete()):
response = self.client.post(reverse("admin:tag_update", args=[self.prod.pk]), {"name": "live"})
self.assertEqual(response.status_code, 404)
def test_a_removed_vm_kept_only_for_the_deleted_tag_goes(self):
InstanceTombstone.objects.create(uuid="12345678-0000-0000-0000-00000000dd03", name="tagged-only", tags=["prod"])
self.client.post(reverse("admin:tag_delete", args=[self.prod.pk]))
self.assertEqual(list(InstanceTombstone.objects.values_list("name", flat=True)), ["gone"])
def test_a_name_taken_meanwhile_is_refused(self):
with self.meanwhile(lambda: Tag.objects.create(name="live")):
response = self.client.post(reverse("admin:tag_update", args=[self.prod.pk]), {"name": "live"})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["form"].errors["name"], ["There is a tag with this name already"])
self.assertEqual(Tag.objects.get(pk=self.prod.pk).name, "prod")
def test_a_name_taken_is_refused_in_the_reader_s_language(self):
Tag.objects.create(name="db")
response = self.client.post(reverse("admin:tag_update", args=[self.prod.pk]), {"name": "db"})
with translation.override("tr"): # the message is read in the reader's language
self.assertEqual(list(response.context["form"].errors["name"]), ["Bu adla bir etiket zaten var"])
def test_only_superusers(self):
self.client.force_login(User.objects.create_user("tg-user", password="pw"))
for url in (reverse("admin:tag_list"), reverse("admin:tag_update", args=[self.prod.pk]),
reverse("admin:tag_delete", args=[self.prod.pk])):
self.assertEqual(self.client.post(url, {"name": "x"}).status_code, 403)
self.assertEqual(Tag.objects.get().name, "prod")

View file

@ -1,6 +1,6 @@
"""Superusers list the ownership kept for VMs that vanished and can remove it."""
from datetime import timedelta
from datetime import time, timedelta
from django.contrib.auth.models import User
from django.test import TestCase, override_settings
@ -9,6 +9,9 @@ from django.utils import timezone
from instances.models import InstanceTombstone
from logs.models import Logs
from lxml import html
from computes.models import Tag
from vmbackups.models import Backup, BackupPolicy, BackupTarget
UUID = "00000000-0000-4000-8000-000000000001"
@ -21,6 +24,7 @@ class TombstoneTests(TestCase):
uuid=UUID,
name="ts-vm",
host="ts-host",
tags=["prod"],
owners=[
{"user": self.owner.id, "is_change": True, "is_delete": False, "is_vnc": True},
{"user": 999999, "is_change": False, "is_delete": False, "is_vnc": False},
@ -39,6 +43,7 @@ class TombstoneTests(TestCase):
self.assertContains(response, "ts-vm")
self.assertContains(response, UUID)
self.assertContains(response, "ts-owner")
self.assertContains(response, "prod")
self.assertContains(response, '<span class="fw-semibold">ts-host</span>', html=True)
def test_only_superusers_see_or_remove_them(self):
@ -48,9 +53,26 @@ class TombstoneTests(TestCase):
self.assertEqual(self.client.post(url).status_code, 403)
self.assertTrue(InstanceTombstone.objects.exists())
def test_the_list_names_its_schedules_and_counts_its_backups(self):
# a VM kept for its backups or schedules alone has no owner to show; only what would come back is told
target = BackupTarget.objects.create(name="t")
chosen, by_tag = (BackupPolicy.objects.create(name=name, target=target, time=time(2), keep=1)
for name in ("nightly", "by-tag"))
BackupPolicy.objects.filter(pk=by_tag.pk).update(tag=Tag.objects.create(name="web"))
kept = [Backup.objects.create(target=target, vm_uuid=UUID, vm_name="ts-vm", compute_name="ts-host").pk
for _ in range(2)]
InstanceTombstone.objects.filter(pk=self.tombstone.pk).update(
owners=[], tags=[], policies=[chosen.pk, by_tag.pk, 999999], backups=[*kept, 999999])
page = html.fromstring(self.client.get(reverse("admin:tombstone_list")).content)
(row,) = page.xpath("//div[@data-search][contains(@data-search, 'ts-vm')]")
text = " ".join(row.text_content().split())
self.assertIn("Schedules: nightly · 2 backups", text)
self.assertNotIn("by-tag", text)
def test_a_get_only_asks_for_confirmation(self):
response = self.client.get(reverse("admin:tombstone_delete", args=[self.tombstone.pk]))
self.assertContains(response, "ts-vm")
self.assertContains(response, "Its owners, tags, protection and schedules no longer come back if its UUID shows up again, nor are its backups linked to it again.")
self.assertTrue(InstanceTombstone.objects.exists())
def test_a_post_removes_it(self):

View file

@ -13,7 +13,7 @@ from computes.models import Compute
from instances.models import Instance
RAW = "Raw-Passw0rd-in-the-form"
LIMITS = {"role": "user", "max_instances": 1, "max_cpus": 1, "max_memory": 1, "max_disk_size": 4}
LIMITS = {"role": "user", "max_instances": 1, "max_cpus": 1, "max_memory": 1, "max_disk_size": 4, "max_backup_size": 0}
class UserCreateTests(TestCase):

View file

@ -28,10 +28,17 @@ class UserPagesTests(TestCase):
def form_data(self, user, **changes):
data = {"username": user.username, "is_active": "on", "role": "superuser" if user.is_superuser else "user",
"max_instances": "2", "max_cpus": "2", "max_memory": "2", "max_disk_size": "20", "seen": user_seen(user),
"max_instances": "2", "max_cpus": "2", "max_memory": "2", "max_disk_size": "20", "max_backup_size": 0, "seen": user_seen(user),
**changes}
return {key: value for key, value in data.items() if value != ""}
def test_the_list_is_in_name_order(self):
get_user_model().objects.create_user("up-bob")
get_user_model().objects.create_user("up-adam")
users = self.client.get(reverse("admin:user_list")).context["users"]
self.assertTrue(users.ordered) # SQLite keeps the name order without asking; PostgreSQL does not
self.assertEqual([user.username for user in users], sorted(user.username for user in users))
def test_an_administrator_cannot_block_delete_or_demote_themselves(self):
own = self.admin.pk
for response in (self.client.post(reverse("admin:user_block", args=[own])),
@ -77,7 +84,7 @@ class UserPagesTests(TestCase):
def test_a_refused_choice_is_said_beside_its_field(self):
url = reverse("admin:user_update", args=[self.alice.pk])
response = self.client.post(url, {"username": "up-alice", "is_active": "on", "groups": "99999", "user_permissions": "99999",
"role": "user", "max_instances": 1, "max_cpus": 1, "max_memory": 1, "max_disk_size": 1,
"role": "user", "max_instances": 1, "max_cpus": 1, "max_memory": 1, "max_disk_size": 1, "max_backup_size": 0,
"seen": user_seen(self.alice)})
page = html.fromstring(response.content)
self.assertEqual(len(page.xpath("//fieldset//div[contains(@class, 'invalid-feedback')]")), 2)
@ -99,13 +106,13 @@ class UserPagesTests(TestCase):
page = html.fromstring(self.client.get(reverse("admin:user_update", args=[self.alice.pk])).content)
shown = {box.get("name"): (box.get("value"), box.get("disabled") is not None) for box in page.xpath("//input[@type='number']")}
self.assertEqual(shown, {"max_instances": ("", True), "max_cpus": ("1", False), "max_memory": ("1.5", False),
"max_disk_size": ("", True)})
"max_disk_size": ("", True), "max_backup_size": ("0", False)})
self.assertEqual(page.xpath("//input[@checked][@data-no-limit]/@name"), ["max_instances_unlimited", "max_disk_size_unlimited"])
def test_a_new_user_starts_with_the_default_quota(self):
page = html.fromstring(self.client.get(reverse("admin:user_create")).content)
shown = {box.get("name"): box.get("value") for box in page.xpath("//input[@type='number']")}
self.assertEqual(shown, {"max_instances": "2", "max_cpus": "2", "max_memory": "2", "max_disk_size": "20"})
self.assertEqual(shown, {"max_instances": "2", "max_cpus": "2", "max_memory": "2", "max_disk_size": "20", "max_backup_size": "0"})
self.assertEqual(page.xpath("//input[@name='role'][@checked]/@value"), ["user"])
def test_no_limit_is_kept_as_minus_one_and_gib_as_mib(self):
@ -222,7 +229,7 @@ class SavedAsCheckedTests(TestCase):
with self.meanwhile(take):
response = self.client.post(reverse("admin:user_create"), {
"username": "sc-bob", "email": "bob@example.com", "password": "Wvc-bob-pass-9", "role": "user",
"max_instances": 1, "max_cpus": 1, "max_memory": 1, "max_disk_size": 1})
"max_instances": 1, "max_cpus": 1, "max_memory": 1, "max_disk_size": 1, "max_backup_size": 0})
self.assertEqual(response.status_code, 200)
self.assertFalse(get_user_model().objects.filter(username="sc-bob").exists())
@ -231,7 +238,7 @@ class SavedAsCheckedTests(TestCase):
alice = get_user_model().objects.create_user("sc-alice")
url = reverse("admin:user_update", args=[alice.pk])
data = {"username": "sc-alice", "is_active": "on", "role": "user", "max_instances": 1, "max_cpus": 1,
"max_memory": 1, "max_disk_size": 1, "seen": user_seen(alice)}
"max_memory": 1, "max_disk_size": 1, "max_backup_size": 0, "seen": user_seen(alice)}
with self.meanwhile(lambda: get_user_model().objects.filter(pk=alice.pk).update(is_active=False)):
response = self.client.post(url, data)
self.assertRedirects(response, url, fetch_redirect_response=False)
@ -244,7 +251,7 @@ class SavedAsCheckedTests(TestCase):
with patch("admin.views.users_lock", side_effect=claims.Busy("users")):
response = self.client.post(reverse("admin:user_create"), {
"username": "sc-carl", "password": "Wvc-carl-pass-9", "role": "user",
"max_instances": 1, "max_cpus": 1, "max_memory": 1, "max_disk_size": 1})
"max_instances": 1, "max_cpus": 1, "max_memory": 1, "max_disk_size": 1, "max_backup_size": 0})
self.assertContains(response, "short operation")
self.assertFalse(get_user_model().objects.filter(username="sc-carl").exists())

View file

@ -5,7 +5,7 @@ from django.test import TestCase
from django.urls import reverse
from admin.tests.edits import user_seen
LIMITS = {"role": "user", "max_instances": 1, "max_cpus": 1, "max_memory": 1, "max_disk_size": 4}
LIMITS = {"role": "user", "max_instances": 1, "max_cpus": 1, "max_memory": 1, "max_disk_size": 4, "max_backup_size": 0}
class UserUpdateNextTests(TestCase):

View file

@ -106,13 +106,53 @@ class AdminTestCase(TestCase):
for block in (lambda: self.client.post(reverse("admin:user_block", args=[user.id])),
lambda: self.client.post(reverse("admin:user_update", args=[user.id]),
{"username": "taken", "role": "user", "max_instances": 1, "max_cpus": 1,
"max_memory": 1, "max_disk_size": 1, "seen": user_seen(user)})):
"max_memory": 1, "max_disk_size": 1, "max_backup_size": 0, "seen": user_seen(user)})):
_, token = ApiToken.objects.create(user)
self.assertEqual(block().status_code, 302)
self.client.post(reverse("admin:user_unblock", args=[user.id]))
self.assertEqual(Client().get("/api/v1/instances/", HTTP_AUTHORIZATION=f"Token {token}").status_code, 401)
self.assertFalse(ApiToken.objects.filter(user=user).exists())
def test_a_block_is_asked_first_and_each_change_is_said(self):
from django.contrib.messages import get_messages
from computes.models import Tag
def said(response): # this response's messages; the next one starts afresh
self.client.cookies.pop("messages", None)
return [str(m) for m in get_messages(response.wsgi_request)]
user = User.objects.create_user("asked", password="Wvc-asked-9")
page = html.fromstring(self.client.get(reverse("admin:user_list")).content)
(block,) = page.xpath("//form[@action=$u]/button", u=reverse("admin:user_block", args=[user.id]))
self.assertIn("API tokens are deleted", block.get("data-confirm"))
self.assertEqual(said(self.client.post(reverse("admin:user_block", args=[user.id]))),
["asked is blocked: signed out, API tokens deleted"])
page = html.fromstring(self.client.get(reverse("admin:user_list")).content)
(unblock,) = page.xpath("//form[@action=$u]/button", u=reverse("admin:user_unblock", args=[user.id]))
self.assertIsNone(unblock.get("data-confirm"))
self.assertEqual(said(self.client.post(reverse("admin:user_unblock", args=[user.id]))), ["asked may sign in again"])
self.assertEqual(said(self.client.post(reverse("admin:user_delete", args=[user.id]))), ["User asked deleted"])
group = Group.objects.create(name="said")
self.assertEqual(said(self.client.post(reverse("admin:group_delete", args=[group.id]))), ["Group said deleted"])
tag = Tag.objects.create(name="old-name")
self.assertEqual(said(self.client.post(reverse("admin:tag_update", args=[tag.id]), {"name": "new-name"})),
["Tag old-name renamed to new-name"])
def test_a_tag_s_counts_link_its_vms_and_hosts(self):
from computes.models import Compute, Tag
from instances.models import Instance
host = Compute.objects.create(name="tg-host", hostname="192.0.2.8", login="", password="", type=4)
tag = Tag.objects.create(name="web")
Instance.objects.create(compute=host, name="tg-vm", uuid="00000000-0000-4000-8000-0000000000cc").tags.add(tag)
page = html.fromstring(self.client.get(reverse("admin:tag_list")).content)
self.assertEqual(page.xpath("//tbody//td/a[not(contains(@class, 'btn'))]/@href"), [reverse("instances:index") + "?tag=web"])
host.tags.add(tag)
page = html.fromstring(self.client.get(reverse("admin:tag_list")).content)
self.assertEqual(page.xpath("//tbody//td/a[not(contains(@class, 'btn'))]/@href"),
[reverse("instances:index") + "?tag=web", reverse("computes") + "?tag=web"])
def test_users(self):
response = self.client.get(reverse("admin:user_create"))
self.assertEqual(response.status_code, 200)
@ -126,7 +166,7 @@ class AdminTestCase(TestCase):
"max_instances": 1,
"max_cpus": 1,
"max_memory": 1, # GiB
"max_disk_size": 4,
"max_disk_size": 4, "max_backup_size": 0,
},
)
self.assertRedirects(response, reverse("admin:user_list"))
@ -153,7 +193,7 @@ class AdminTestCase(TestCase):
"max_instances": 2,
"max_cpus": 2,
"max_memory": 2, # GiB
"max_disk_size": 8,
"max_disk_size": 8, "max_backup_size": 0,
},
)
self.assertRedirects(response, reverse("admin:user_list"))

View file

@ -18,4 +18,7 @@ urlpatterns = [
path("logs/export.xlsx", views.logs_export, name="logs_export"),
path("removed-vms/", views.tombstone_list, name="tombstone_list"),
path("removed-vms/<int:pk>/delete/", views.tombstone_delete, name="tombstone_delete"),
path("tags/", views.tag_list, name="tag_list"),
path("tags/<int:pk>/update/", views.tag_update, name="tag_update"),
path("tags/<int:pk>/delete/", views.tag_delete, name="tag_delete"),
]

View file

@ -1,23 +1,27 @@
from contextlib import contextmanager
from datetime import timedelta
from accounts.lockout import locked_usernames
from accounts.models import ApiToken, Instance, UserAttributes, UserInstance
from appsettings.settings import app_settings
from computes.utils import lock_ownership, users_lock
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth import SESSION_KEY, update_session_auth_hash
from django.contrib.auth.models import Group, Permission, User
from django.contrib.sessions.models import Session
from django.core.paginator import Paginator
from django.http import HttpResponse
from django.db import transaction
from django.db.models import Count, Exists, OuterRef, Q
from django.db import IntegrityError, transaction
from django.db.models import Count, Exists, OuterRef, ProtectedError, Q
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone
from django.utils.http import url_has_allowed_host_and_scheme, urlencode
from django.utils.translation import gettext_lazy as _
from django.utils.translation import ngettext
from django.views.decorators.http import require_POST
from django.views.decorators.debug import sensitive_post_parameters
from computes.models import Tag
from instances.models import InstanceTombstone
from instances.report import workbook
from logs.audit import audit, changed_fields, snapshot
@ -25,6 +29,7 @@ from logs.models import Logs
from operations import claims
from operations.utils import busy_message
from vrtManager import util
from vmbackups.models import Backup, BackupPolicy
from . import forms
from .decorators import superuser_only
@ -72,7 +77,7 @@ def group_create(request):
"admin/group_form.html",
{
"form": form,
"title": _("Create Group"),
"title": _("Create group"),
},
)
@ -114,7 +119,7 @@ def group_update(request, pk):
"form": form,
"group": group,
"seen": form_seen(group_snapshot(group)),
"title": _("Update Group"),
"title": _("Update group"),
},
)
@ -124,7 +129,9 @@ def group_delete(request, pk):
group = get_object_or_404(Group, pk=pk)
if request.method == "POST":
with audit(request, None, f"Group {group.name}", "delete"):
group.delete()
deleted, _rows = group.delete()
if deleted: # not by another request just before
messages.success(request, _("Group %(group)s deleted") % {"group": group.name})
return redirect("admin:group_list")
return render(
@ -170,12 +177,13 @@ def user_list(request):
users = User.objects.annotate(
api_tokens=Count("auth_token_set", filter=live),
can_clone=Exists(clone.filter(Q(user=OuterRef("pk")) | Q(group__user=OuterRef("pk")))),
).prefetch_related("groups")
).order_by("username").prefetch_related("groups")
return render(
request,
"admin/user_list.html",
{
"users": users,
"locked": locked_usernames(),
"title": _("Users"),
},
)
@ -211,7 +219,7 @@ def user_create(request):
{
"user_form": user_form,
"attributes_form": attributes_form,
"title": _("Create User"),
"title": _("Create user"),
},
)
@ -256,6 +264,7 @@ def user_update(request, pk):
attributes = attributes_form.save()
if not user.is_active: # as user_block
ApiToken.objects.filter(user=user).delete()
end_sessions(user)
fields = set(changed_fields(before, snapshot(user))) | set(changed_fields(before_attributes, snapshot(attributes)))
fields = sorted(fields - {"password", "last_login"})
entry.action = "change " + ", ".join(fields)
@ -284,7 +293,7 @@ def user_update(request, pk):
"attributes_form": attributes_form,
"edited_user": user,
"seen": seen,
"title": _("Update User"),
"title": _("Update user"),
},
)
@ -326,7 +335,9 @@ def user_delete(request, pk):
if request.method == "POST":
try:
with audit(request, None, f"User {user.username}", "delete"), users_change():
user.delete()
deleted, _rows = user.delete()
if deleted: # not by another request just before
messages.success(request, _("User %(user)s deleted") % {"user": user.username})
except (NoSuperuser, claims.Busy) as err:
refused(request, err)
return redirect("admin:user_list")
@ -339,6 +350,14 @@ def user_delete(request, pk):
)
def end_sessions(user):
"""Sign a blocked user out: django-auth-ldap does not check is_active for
an open session, so a blocked LDAP user would keep theirs."""
for session in Session.objects.filter(expire_date__gt=timezone.now()):
if session.get_decoded().get(SESSION_KEY) == str(user.pk):
session.delete()
@require_POST
@superuser_only
def user_block(request, pk):
@ -353,6 +372,8 @@ def user_block(request, pk):
user.save(update_fields=["is_active"]) # not the rest as read before the lock
# an unblock must not bring back the tokens of someone who took the account over
ApiToken.objects.filter(user=user).delete()
end_sessions(user)
messages.success(request, _("%(user)s is blocked: signed out, API tokens deleted") % {"user": user.username})
except (NoSuperuser, claims.Busy) as err:
refused(request, err)
return redirect("admin:user_list")
@ -367,6 +388,7 @@ def user_unblock(request, pk):
entry.skip = user.is_active # not blocked
user.is_active = True
user.save(update_fields=["is_active"])
messages.success(request, _("%(user)s may sign in again") % {"user": user.username})
except claims.Busy as busy:
messages.error(request, busy_message(busy, request.user))
return redirect("admin:user_list")
@ -440,8 +462,15 @@ def tombstone_list(request):
ids = {owner["user"] for tombstone in tombstones for owner in tombstone.owners}
names = dict(User.objects.filter(id__in=ids).values_list("id", "username"))
retention = timedelta(days=getattr(settings, "INSTANCE_OWNERSHIP_RETENTION_DAYS", 30))
# what would come back (computes.utils._restore): schedules that choose their VMs one by one, backups unlinked
policies = dict(BackupPolicy.objects.filter(pk__in={pk for t in tombstones for pk in t.policies}, compute=None,
tag=None).values_list("pk", "name"))
backups = set(Backup.objects.filter(pk__in={pk for t in tombstones for pk in t.backups}, instance=None)
.values_list("pk", flat=True))
for tombstone in tombstones:
tombstone.owner_names = [names.get(owner["user"], _("deleted user")) for owner in tombstone.owners]
tombstone.policy_names = sorted(policies[pk] for pk in tombstone.policies if pk in policies)
tombstone.backup_count = len(backups.intersection(tombstone.backups))
tombstone.expires = tombstone.removed + retention
return render(request, "admin/tombstone_list.html", {"tombstones": tombstones})
@ -460,6 +489,86 @@ def tombstone_delete(request, pk):
request,
"common/confirm_delete.html",
{"object": tombstone,
"consequence": _("Its owners no longer get the VM back if its UUID shows up again.")},
"consequence": _("Its owners, tags, protection and schedules no longer come back if its UUID shows up again, nor are its backups linked to it again.")},
)
@superuser_only
def tag_list(request):
"""The tags of VMs and hosts, with how many of each have them."""
# in name order: a query that counts leaves the model's ordering out
tags = Tag.objects.annotate(vm_count=Count("instances", distinct=True),
host_count=Count("computes", distinct=True)).order_by("name")
return render(request, "admin/tag_list.html", {"tags": list(tags)})
def _retag_removed_vms(old, new):
"""The removed VMs' kept tag old named new, or dropped with None: a name
made again later must not go to them. Under the ownership lock (computes.utils.forget)."""
for tombstone in InstanceTombstone.objects.all():
if old in tombstone.tags:
if new:
tombstone.tags = [new if name == old else name for name in tombstone.tags]
else:
tombstone.tags = [name for name in tombstone.tags if name != old]
if tombstone.keeps_anything():
tombstone.save(update_fields=["tags"])
else: # kept only for the tag (computes.utils._bury)
tombstone.delete()
@superuser_only
def tag_update(request, pk):
tag = get_object_or_404(Tag, pk=pk)
old = tag.name
form = forms.TagForm(request.POST or None, instance=tag)
if request.method == "POST" and form.is_valid():
if form.cleaned_data["name"] == old:
return redirect("admin:tag_list")
try:
with audit(request, None, f"Tag {old}", f"rename to {form.cleaned_data['name']}"), transaction.atomic():
lock_ownership()
current = get_object_or_404(Tag, pk=pk).name # another rename or a delete may have come first
form.save()
_retag_removed_vms(current, tag.name)
except IntegrityError: # the name was given to another tag meanwhile
form.add_error("name", form.fields["name"].error_messages["unique"])
else:
messages.success(request, _("Tag %(old)s renamed to %(tag)s") % {"old": current, "tag": tag.name})
return redirect("admin:tag_list")
return render(request, "common/form.html", {"form": form, "title": _("Rename tag %(tag)s") % {"tag": old}})
def _refuse_used(request, schedules):
"""Tells that the tag cannot go while the backup schedules back up its VMs (models.PROTECT)."""
messages.error(request, ngettext("The backup schedule %(schedules)s backs up its VMs: change it first",
"The backup schedules %(schedules)s back up its VMs: change them first",
len(schedules)) % {"schedules": ", ".join(schedules)})
return redirect("admin:tag_list")
@superuser_only
def tag_delete(request, pk):
tag = get_object_or_404(Tag, pk=pk)
if request.method == "POST":
try:
with audit(request, None, f"Tag {tag.name}", "delete"), transaction.atomic():
lock_ownership()
tag = get_object_or_404(Tag, pk=pk) # its name now: another rename may have come first
tag.delete()
_retag_removed_vms(tag.name, None)
except ProtectedError as err: # a schedule backs up its VMs, also one saved since the page was shown
return _refuse_used(request, sorted(policy.name for policy in err.protected_objects))
messages.success(request, _("Tag %(tag)s deleted") % {"tag": tag.name})
return redirect("admin:tag_list")
schedules = list(tag.backup_policies.values_list("name", flat=True))
if schedules:
return _refuse_used(request, schedules)
vms, hosts = tag.instances.count(), tag.computes.count()
return render(request, "common/confirm_delete.html", {
"object": tag,
"consequence": _("It is taken off %(vms)s and %(hosts)s.") % {
"vms": ngettext("%(count)s VM", "%(count)s VMs", vms) % {"count": vms},
"hosts": ngettext("%(count)s host", "%(count)s hosts", hosts) % {"count": hosts}},
})

View file

@ -15,7 +15,7 @@ PREFIX = "webvirtcloud-backup-"
class Command(BaseCommand):
help = ("Copy the database, secret key, worker id, settings and the SSH keys and TLS certificates of the "
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.")
def add_arguments(self, parser):
@ -70,7 +70,7 @@ class Command(BaseCommand):
# the key in use: SECRET_KEY from the environment has no data/secret_key
(to / "secret_key").write_text(settings.SECRET_KEY + "\n")
data = settings.BASE_DIR / "data"
for source in (data / "node_id", settings.BASE_DIR / "webvirtcloud" / "settings.py"):
for source in (data / "node_id", data / "local_settings.py"):
if source.is_file():
shutil.copyfile(source, to / source.name)
ssh = Path.home() / ".ssh"

View file

@ -0,0 +1,35 @@
from django.core.management.color import no_style
from django.db import migrations, models
from django.utils.translation import gettext_noop as _
SETTINGS = (
(_("Alert e-mail addresses"), "ALERT_EMAILS",
_("Comma-separated; mailed when a backup fails, is skipped, missing or damaged, or a job is uncertain")),
(_("Alert webhook"), "ALERT_WEBHOOK", _("An http(s) URL that gets the same alerts as a JSON POST (subject, text, time)")),
)
def add_settings(apps, schema_editor):
setting = apps.get_model("appsettings", "AppSettings")
db_alias = schema_editor.connection.alias
# see 0014: move a PostgreSQL id sequence past the fixed ids first
with schema_editor.connection.cursor() as cursor:
for sql in schema_editor.connection.ops.sequence_reset_sql(no_style(), [setting]):
cursor.execute(sql)
for name, key, description in SETTINGS:
setting.objects.using(db_alias).get_or_create(
key=key, defaults={"name": name, "value": "", "choices": "", "description": description})
def del_settings(apps, schema_editor):
apps.get_model("appsettings", "AppSettings").objects.using(schema_editor.connection.alias).filter(
key__in=[key for _name, key, _description in SETTINGS]).delete()
class Migration(migrations.Migration):
dependencies = [("appsettings", "0026_repair_number_settings")]
operations = [
migrations.AlterField("appsettings", "value", models.CharField(max_length=255, verbose_name="value")),
migrations.RunPython(add_settings, del_settings),
]

View file

@ -0,0 +1,29 @@
from django.core.management.color import no_style
from django.db import migrations
from django.utils.translation import gettext_noop as _
SETTING = (_("Migration bandwidth"), "MIGRATION_BANDWIDTH", "0",
_("MiB/s for the memory and each copied disk, not the final switchover; 0: libvirt's default"))
def add_setting(apps, schema_editor):
setting = apps.get_model("appsettings", "AppSettings")
db_alias = schema_editor.connection.alias
# see 0014: move a PostgreSQL id sequence past the fixed ids first
with schema_editor.connection.cursor() as cursor:
for sql in schema_editor.connection.ops.sequence_reset_sql(no_style(), [setting]):
cursor.execute(sql)
name, key, value, description = SETTING
setting.objects.using(db_alias).get_or_create(
key=key, defaults={"name": name, "value": value, "choices": "", "description": description})
def del_setting(apps, schema_editor):
apps.get_model("appsettings", "AppSettings").objects.using(schema_editor.connection.alias).filter(
key=SETTING[1]).delete()
class Migration(migrations.Migration):
dependencies = [("appsettings", "0027_alert_settings")]
operations = [migrations.RunPython(add_setting, del_setting)]

View file

@ -0,0 +1,29 @@
from django.core.management.color import no_style
from django.db import migrations
from django.utils.translation import gettext_noop as _
SETTING = (_("Sign-in notice"), "LOGIN_NOTICE", "",
_("Shown above the sign-in form, e.g. planned maintenance or a terms-of-use line; empty: none"))
def add_setting(apps, schema_editor):
setting = apps.get_model("appsettings", "AppSettings")
db_alias = schema_editor.connection.alias
# see 0014: move a PostgreSQL id sequence past the fixed ids first
with schema_editor.connection.cursor() as cursor:
for sql in schema_editor.connection.ops.sequence_reset_sql(no_style(), [setting]):
cursor.execute(sql)
name, key, value, description = SETTING
setting.objects.using(db_alias).get_or_create(
key=key, defaults={"name": name, "value": value, "choices": "", "description": description})
def del_setting(apps, schema_editor):
apps.get_model("appsettings", "AppSettings").objects.using(schema_editor.connection.alias).filter(
key=SETTING[1]).delete()
class Migration(migrations.Migration):
dependencies = [("appsettings", "0028_migration_bandwidth")]
operations = [migrations.RunPython(add_setting, del_setting)]

View file

@ -0,0 +1,29 @@
from django.core.management.color import no_style
from django.db import migrations
from django.utils.translation import gettext_noop as _
SETTING = (_("Session length (hours)"), "LOGIN_SESSION_HOURS", "24",
_("How long a sign-in lasts; a change applies from the next sign-in"))
def add_setting(apps, schema_editor):
setting = apps.get_model("appsettings", "AppSettings")
db_alias = schema_editor.connection.alias
# see 0014: move a PostgreSQL id sequence past the fixed ids first
with schema_editor.connection.cursor() as cursor:
for sql in schema_editor.connection.ops.sequence_reset_sql(no_style(), [setting]):
cursor.execute(sql)
name, key, value, description = SETTING
setting.objects.using(db_alias).get_or_create(
key=key, defaults={"name": name, "value": value, "choices": "", "description": description})
def del_setting(apps, schema_editor):
apps.get_model("appsettings", "AppSettings").objects.using(schema_editor.connection.alias).filter(
key=SETTING[1]).delete()
class Migration(migrations.Migration):
dependencies = [("appsettings", "0029_login_notice")]
operations = [migrations.RunPython(add_setting, del_setting)]

View file

@ -8,6 +8,6 @@ class AppSettings(models.Model):
name = models.CharField(_("name"), max_length=25, null=False)
key = models.CharField(_("key"), db_index=True, max_length=50, unique=True)
value = models.CharField(_("value"), max_length=25)
value = models.CharField(_("value"), max_length=255)
choices = models.CharField(_("choices"), max_length=70)
description = models.CharField(_("description"), max_length=100, null=True)

View file

@ -1,4 +1,4 @@
from django.db import DatabaseError
from django.db import Error as DatabaseError
from .models import AppSettings

View file

@ -1,25 +1,40 @@
{% extends "base.html" %}
{% load i18n %}
{% block title %}{% trans "Edit Settings" %}{% endblock title %}
{% block title %}{% trans "Edit settings" %}{% endblock title %}
{% block page_heading %}{% trans "Edit Settings" %}{% endblock page_heading %}
{% block page_heading %}{% trans "Edit settings" %}{% endblock page_heading %}
{% block style %}
<style>
/* a group's card stops below the sticky navbar; the group index stays in view */
/* a group's card stops below the sticky navbar; the group index stays in view: beside the
groups, or on a narrow screen as one row under the navbar that scrolls sideways */
.settings-group { scroll-margin-top: 5rem; }
@media (min-width: 992px) {
.settings-index { position: sticky; top: 5rem; }
}
@media (max-width: 991.98px) {
/* the column sticks: the index alone would only stick within it */
.settings-index-column {
position: sticky;
top: var(--navbar-height, 4rem);
z-index: 1000;
background: var(--bs-body-bg);
padding-block: .5rem;
}
/* the padding keeps a link's focus ring inside the scrolling row */
.settings-index .nav { flex-wrap: nowrap; overflow-x: auto; white-space: nowrap; padding: .25rem; }
/* below the navbar and the index, whose height the theme and a scrollbar set */
.settings-group { scroll-margin-top: calc(var(--navbar-height, 4rem) + 6rem); }
}
</style>
{% endblock style %}
{% block content %}
<div class="row g-4">
<div class="col-lg-3">
<div class="col-lg-3 settings-index-column">
<nav class="settings-index" aria-label="{% trans 'Settings groups' %}">
<div class="nav nav-pills flex-wrap flex-lg-column gap-1">
<div class="nav nav-pills flex-lg-column gap-1">
<a class="nav-link" href="#appearance">{% trans "Appearance" %}</a>
{% for title, settings in groups %}
<a class="nav-link" href="#{{ title|slugify }}">{% trans title %}</a>
@ -86,7 +101,7 @@
min="{{ setting.bounds.0 }}" max="{{ setting.bounds.1 }}" step="1" required aria-describedby="help-{{ setting.key }}">
{% else %}
<input id="setting-{{ setting.key }}" class="form-control" type="text" name="{{ setting.key }}" value="{{ setting.value }}"
maxlength="25" aria-describedby="help-{{ setting.key }}">
maxlength="255" aria-describedby="help-{{ setting.key }}">
{% endif %}
{% endif %}
<input type="hidden" name="was-{{ setting.key }}" value="{{ setting.value }}">
@ -94,8 +109,12 @@
</div>
{% endfor %}
</div>
<div class="border-top mt-3 pt-3 text-end">
<div class="border-top mt-3 pt-3 d-flex flex-wrap justify-content-end gap-2">
{# Save first: Enter in a field saves #}
<button type="submit" class="btn btn-primary">{% blocktrans %}Save {{ group_title }}{% endblocktrans %}</button>
{% if title == "Alerts" %}{# to the addresses and webhook saved #}
<button type="submit" name="test_alert" value="1" class="btn btn-outline-secondary order-first" formnovalidate>{% trans "Send a test alert" %}</button>
{% endif %}
</div>
</form>
</section>

View file

@ -72,6 +72,11 @@ class AppSettingsTestCase(TestCase):
self.assertEqual(AppSettings.objects.get(key="WORKER_CONCURRENCY").value, "4")
self.assertTrue(any("between 1 and 16" in str(m) for m in get_messages(response.wsgi_request)))
def test_a_refused_setting_is_named_in_the_pages_language(self):
response = self.client.post(reverse("appsettings"), {"MIGRATION_BANDWIDTH": "-1"}, HTTP_ACCEPT_LANGUAGE="tr")
self.assertEqual(AppSettings.objects.get(key="MIGRATION_BANDWIDTH").value, "0")
self.assertTrue(any(str(m).startswith("Taşıma bant genişliği") for m in get_messages(response.wsgi_request)))
def post(self, key, value):
response = self.client.post(reverse("appsettings"), {key: value})
# not followed: the messages would stay in the cookie for the next post
@ -213,7 +218,7 @@ class AppSettingsTestCase(TestCase):
AppSettings.objects.filter(key="LOGIN_FAILURE_LIMIT").update(value="10")
self.client.post(reverse("appsettings"), {"LOGIN_FAILURE_LIMIT": "5", "was-LOGIN_FAILURE_LIMIT": "5",
"LOGIN_LOCKOUT_MINUTES": "30", "was-LOGIN_LOCKOUT_MINUTES": "15"})
values = dict(AppSettings.objects.filter(key__startswith="LOGIN_").values_list("key", "value"))
values = dict(AppSettings.objects.filter(key__in=["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES"]).values_list("key", "value"))
self.assertEqual(values, {"LOGIN_FAILURE_LIMIT": "10", "LOGIN_LOCKOUT_MINUTES": "30"})
def test_a_failed_save_changes_none_of_its_group(self):

View file

@ -30,7 +30,7 @@ class BackupTests(SimpleTestCase):
self.addCleanup(shutil.rmtree, self.base)
self.addCleanup(os.umask, os.umask(0o022)) # the command sets its own
for path, text in (("data/secret_key", "key"), ("data/node_id", "a1b2c3"),
("webvirtcloud/settings.py", "DEBUG = False"), ("home/.ssh/id_ed25519", "private")):
("data/local_settings.py", "DEBUG = False"), ("home/.ssh/id_ed25519", "private")):
(self.base / path).parent.mkdir(parents=True, exist_ok=True)
(self.base / path).write_text(text)
(self.base / "home/.ssh/agent").symlink_to(self.base / "data/secret_key")
@ -66,7 +66,7 @@ class BackupTests(SimpleTestCase):
backup = self.backup()
with closing(sqlite3.connect(backup / "db.sqlite3")) as db:
self.assertEqual(db.execute("SELECT name FROM computes_compute").fetchall(), [("kept",)])
self.assertEqual(sorted(p.name for p in backup.iterdir()), ["db.sqlite3", "node_id", "secret_key", "settings.py", "ssh"])
self.assertEqual(sorted(p.name for p in backup.iterdir()), ["db.sqlite3", "local_settings.py", "node_id", "secret_key", "ssh"])
# the key in use, also when it came from the environment and not data/secret_key
self.assertEqual((backup / "secret_key").read_text(), "key in use\n")
self.assertEqual(oct((backup / "secret_key").stat().st_mode & 0o777), "0o600")

View file

@ -28,7 +28,7 @@ class SequenceAfterFixedIdsTestCase(TransactionTestCase):
with connection.cursor() as cursor:
cursor.execute("SELECT setval(pg_get_serial_sequence('appsettings_appsettings', 'id'), 1, false)")
login_lockout.add_settings(apps, schema_editor)
self.assertEqual(AppSettings.objects.filter(key__startswith="LOGIN_").count(), 2)
self.assertEqual(AppSettings.objects.filter(key__in=["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES"]).count(), 2)
nic_type = importlib.import_module("appsettings.migrations.0016_nic_type_rtl8139")
@ -129,8 +129,9 @@ class RepairNumbersTestCase(TestCase):
def test_a_number_an_older_version_saved_goes_back_to_its_default(self):
from appsettings.views import NUMBERS
# the same ranges as the Settings page checks
self.assertEqual({key: bounds[:2] for key, bounds in repair_numbers.NUMBERS.items()}, NUMBERS)
# the same ranges as the Settings page checks (a setting added since is not the migration's)
self.assertEqual({key: bounds[:2] for key, bounds in repair_numbers.NUMBERS.items()},
{key: NUMBERS[key] for key in repair_numbers.NUMBERS})
for key, value in (("LOGS_PER_PAGE", "abc"), ("WORKER_CONCURRENCY", "0"), ("LOGIN_FAILURE_LIMIT", "")):
AppSettings.objects.filter(key=key).update(value=value)
AppSettings.objects.filter(key="LOG_RETENTION_DAYS").update(value="90")

View file

@ -1,8 +1,11 @@
import re
from urllib.parse import urlsplit
from pathlib import Path
from admin.decorators import superuser_only
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator, validate_email
from django.contrib import messages
from django.db import DatabaseError, transaction
from django.http import HttpResponseRedirect
@ -10,6 +13,7 @@ from django.shortcuts import render
from django.utils.translation import gettext as _
from django.utils.translation import gettext_noop
from logs.audit import audit
from operations import alerts
from operations.utils import BOUNDS
from vrtManager.util import OperationError
@ -26,6 +30,7 @@ NUMBERS = {
"LOGS_PER_PAGE": (1, 1000),
"LOGIN_FAILURE_LIMIT": (1, 1000),
"LOGIN_LOCKOUT_MINUTES": (1, 10080),
"LOGIN_SESSION_HOURS": (1, 8760),
"SNAPSHOT_FREE_SPACE_PERCENT": (0, 100),
"SNAPSHOT_FREE_SPACE_MIN_GIB": (0, 100000),
"INSTANCE_VOLUME_DEFAULT_OWNER_UID": (0, 4294967294),
@ -33,6 +38,9 @@ NUMBERS = {
}
# settings whose values the audit log does not show
SECRET_SETTINGS = {"ALERT_WEBHOOK"}
# the Settings page's groups, in order; a setting in none shows under Other. The
# titles stay English here: the page links them by slug and translates them
GROUPS = [
@ -49,7 +57,10 @@ GROUPS = [
"ALLOW_INSTANCE_MULTIPLE_OWNER", "QUOTA_DEBUG"]),
(gettext_noop("Snapshots and jobs"), ["SNAPSHOT_FREE_SPACE_PERCENT", "SNAPSHOT_FREE_SPACE_MIN_GIB",
"WORKER_CONCURRENCY", "JOB_RETENTION_DAYS"]),
(gettext_noop("Login"), ["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES"]),
(gettext_noop("Migrations"), ["MIGRATION_BANDWIDTH"]),
(gettext_noop("Login"), ["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES", "LOGIN_SESSION_HOURS",
"LOGIN_NOTICE"]),
(gettext_noop("Alerts"), ["ALERT_EMAILS", "ALERT_WEBHOOK"]),
(gettext_noop("Lists and pages"), ["VIEW_INSTANCES_LIST_STYLE", "VM_DRBD_STATUS", "LOGS_PER_PAGE",
"LOG_RETENTION_DAYS"]),
]
@ -59,18 +70,28 @@ def refusal(setting, value):
"""Why the value cannot be saved for the setting, or None."""
if len(value) > AppSettings._meta.get_field("value").max_length:
return _("%(setting)s takes at most %(length)s characters") % {
"setting": setting.name, "length": AppSettings._meta.get_field("value").max_length}
"setting": _(setting.name), "length": AppSettings._meta.get_field("value").max_length}
if setting.key in NUMBERS:
low, high = NUMBERS[setting.key]
if not (value.isascii() and value.isdigit() and len(value) <= 10 and low <= int(value) <= high):
return _("%(setting)s must be a whole number between %(low)s and %(high)s") % {
"setting": setting.name, "low": low, "high": high}
"setting": _(setting.name), "low": low, "high": high}
elif setting.choices and value not in setting.choices_as_list():
return _("%(setting)s must be one of %(choices)s") % {
"setting": setting.name, "choices": ", ".join(setting.choices_as_list())}
"setting": _(setting.name), "choices": ", ".join(setting.choices_as_list())}
elif setting.key == "CLONE_INSTANCE_DEFAULT_PREFIX" and not re.fullmatch(r"[a-zA-Z0-9-]+", value):
# a clone's name is the prefix and a number, and takes only these
return _("%(setting)s takes letters, digits and '-' only") % {"setting": setting.name}
return _("%(setting)s takes letters, digits and '-' only") % {"setting": _(setting.name)}
try:
if setting.key == "ALERT_EMAILS":
for address in filter(None, (a.strip() for a in value.split(","))):
validate_email(address)
elif setting.key == "ALERT_WEBHOOK" and value.strip():
URLValidator(schemes=["http", "https"])(value.strip())
if "@" in urlsplit(value.strip()).netloc: # urllib would take user:password@ for the host
raise ValidationError("credentials in the URL")
except ValidationError:
return _("%(setting)s: %(value)s is not an e-mail address or an http(s) URL") % {"setting": _(setting.name), "value": value}
return None
@ -93,6 +114,17 @@ def appsettings(request):
settings_by_key = {s.key: s for s in AppSettings.objects.exclude(key="BOOTSTRAP_THEME")}
if request.method == "POST":
if "test_alert" in request.POST: # with the settings saved
results = alerts.test()
if not results:
messages.error(request, _("Set an alert e-mail address or webhook and save it first"))
for channel, error in results.items():
name = _("E-mail") if channel == "mail" else _("Webhook")
if error is None:
messages.success(request, _("%(channel)s: the test alert was sent") % {"channel": name})
else:
messages.error(request, _("%(channel)s: the test alert failed: %(error)s") % {"channel": name, "error": error})
return HttpResponseRedirect(request.get_full_path()) # the results are at the top
if "BOOTSTRAP_THEME" in request.POST:
theme = request.POST.get("BOOTSTRAP_THEME", "")
if theme not in themes_list:
@ -121,7 +153,9 @@ def appsettings(request):
for refused in refusals:
messages.error(request, refused)
if changed and not refusals:
action = "change " + ", ".join(f"{s.name} to {value}" for s, value in changed)
# a webhook URL is a secret of its own (Slack's): not in the log
action = "change " + ", ".join(f"{s.name} to {'(not shown)' if s.key in SECRET_SETTINGS else value}"
for s, value in changed)
try:
# one row, and all of the group or none of it
with audit(request, None, "Settings", action), transaction.atomic():

View file

@ -2,11 +2,24 @@ from copy import copy
from computes.models import Compute
from computes.validators import validate_gstfsd_key
from drf_spectacular.utils import OpenApiParameter
from rest_framework import serializers
from vrtManager.connection import CONN_SOCKET, CONN_SSH, CONN_TCP, CONN_TLS
# a VM's or host's tags, by name: set on the web pages only
TAGS = {"many": True, "read_only": True, "slug_field": "name"}
TAG_PARAMETER = OpenApiParameter("tag", str, description="Only those with this tag")
def with_tag(queryset, request):
"""queryset's VMs or hosts with the ?tag= of request, all without one; their tags read at once."""
tag = request.query_params.get("tag", "").strip().lower() # the names are kept in lower case
return (queryset.filter(tags__name=tag) if tag else queryset).prefetch_related("tags")
class ComputeSerializer(serializers.ModelSerializer):
tags = serializers.SlugRelatedField(**TAGS)
password = serializers.CharField(
style={"input_type": "password"},
write_only=True,
@ -48,4 +61,5 @@ class ComputeSerializer(serializers.ModelSerializer):
class Meta:
model = Compute
fields = ["id", "name", "hostname", "login", "password", "type", "details", "migration_address", "gstfsd_key"]
fields = ["id", "name", "hostname", "login", "password", "type", "details", "migration_address", "migration_tls",
"gstfsd_key", "tags"]

View file

@ -9,7 +9,7 @@ from rest_framework import viewsets
from rest_framework.response import Response
from vrtManager.create import wvmCreate
from .serializers import ComputeSerializer
from .serializers import TAG_PARAMETER, ComputeSerializer, with_tag
class ComputeViewSet(viewsets.ModelViewSet):
@ -22,6 +22,14 @@ class ComputeViewSet(viewsets.ModelViewSet):
serializer_class = ComputeSerializer
permission_classes = [IsSuperUser]
def get_queryset(self):
queryset = super().get_queryset()
return with_tag(queryset, self.request) if self.action == "list" else queryset
@extend_schema(parameters=[TAG_PARAMETER])
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
# checked and saved under hosts_lock, as on the web (Compute.clean)
def create(self, request, *args, **kwargs):
with hosts_lock():

106
computes/balance.py Normal file
View file

@ -0,0 +1,106 @@
"""Where VMs migrate: the Balance page's proposal (propose), which running
VMs to migrate so that the hosts give their running VMs about the same
share of their memory, then of their CPUs; and a bulk migration's spread
over the other hosts (spread). A host twice as large takes twice as much."""
from fractions import Fraction
def _share(load, size):
"""The load (memory KiB, vCPUs) as shares of the host's size (memory KiB, CPUs), exact."""
return tuple(Fraction(part, max(whole, 1)) for part, whole in zip(load, size))
def _spread_of(load, size):
"""What a host adds to the sums propose lowers: each part of its load
squared over its size. The sums are least when every host has the same
share, as a sum of squared shares is not: it is least when a host twice
as large has half the share."""
return tuple(Fraction(part ** 2, max(whole, 1)) for part, whole in zip(load, size))
def propose(loads, vms, room, sizes):
"""The moves [(VM, source, target)] and the loads after them.
loads: {host: (memory KiB, vCPUs)} that each host gives its running VMs,
all of them, also those that cannot move. vms: the VMs that may move,
(VM, host, memory KiB, vCPUs, the hosts it may go to). room: {host: its
memory KiB its running and paused VMs leave}; the VMs moved to a host
fit in it without those moved away, so the moves may run in any order.
sizes: {host: (memory KiB, CPUs)}.
The proposal is made twice, step by step, each step taking the move
that most lowers the sum of the hosts' memory, then vCPUs, squared over
their size (_spread_of): once the move that lowers it most, once the move
that lowers it most for the memory it moves. The one that evens out the
hosts more is taken, and of two that do it as well, the one that moves
less memory: small VMs rather than a large one."""
memory = {vm[0]: vm[2] for vm in vms}
def rank(plan):
moves, after = plan
spreads = [_spread_of(load, sizes[host]) for host, load in after.items()]
return tuple(sum(part[i] for part in spreads) for i in (0, 1)), sum(memory[pk] for pk, _source, _target in moves)
return min((_steps(loads, vms, room, sizes, per_memory) for per_memory in (False, True)), key=rank)
def _steps(loads, vms, room, sizes, per_memory):
"""The moves and the loads after them, a move at a time while one lowers
the sums (_spread_of); each VM moves at most once."""
loads = {host: list(load) for host, load in loads.items()}
room = dict(room)
left, moves = sorted(vms), []
while True:
best = None
for vm in left:
pk, source, ram, vcpus, targets = vm
for target in sorted(targets):
if ram > room[target]:
continue
# the change of each sum: ((s - x)² - s²) / S + ((t + x)² - t²) / T
change = tuple(
Fraction(size * (size - 2 * loads[source][i]), max(sizes[source][i], 1))
+ Fraction(size * (size + 2 * loads[target][i]), max(sizes[target][i], 1))
for i, size in enumerate((ram, vcpus)))
if change >= (0, 0):
continue
gain = (change[0] / ram, change[1]) if per_memory and ram else change
if best is None or gain < best[0]:
best = (gain, vm, target)
if best is None:
return moves, loads
_gain, vm, target = best
pk, source, ram, vcpus, _targets = vm
for i, size in enumerate((ram, vcpus)):
loads[source][i] -= size
loads[target][i] += size
room[target] -= ram
left.remove(vm)
moves.append((pk, source, target))
def spread(loads, vms, room, sizes):
"""Where each VM of a host being emptied goes: {VM: target}, and the
loads after. loads, room and sizes as propose's, of the hosts the VMs
may go to. vms: (VM, memory KiB, vCPUs, whether it holds its memory (not
shut off), the hosts it may go to).
The largest VMs first, each to the host it may go to that has the least
share of its memory, then of its CPUs, with it; one that holds its
memory only where it fits the room. A shut-off VM counts too: it takes
its memory when it starts. A VM no host takes is left out."""
loads = {host: list(load) for host, load in loads.items()}
room = dict(room)
placed = {}
for pk, ram, vcpus, holds, targets in sorted(vms, key=lambda vm: (-vm[1], -vm[2], vm[0])):
fits = sorted(target for target in targets if not holds or ram <= room[target])
if not fits:
continue
target = min(fits, key=lambda host: _share((loads[host][0] + ram, loads[host][1] + vcpus), sizes[host]))
loads[target][0] += ram
loads[target][1] += vcpus
if holds:
room[target] -= ram
placed[pk] = target
return placed, loads

View file

@ -1,8 +1,10 @@
from django import forms
from django.db import transaction
from django.utils.translation import gettext_lazy as _
from vrtManager.connection import CONN_SOCKET, CONN_SSH, CONN_TCP, CONN_TLS
from computes.models import Compute
from computes.models import TAG_LENGTH, TAG_NAME, Compute, Tag
from computes.utils import lock_ownership
from .validators import validate_hostname
@ -27,27 +29,93 @@ class KeepSecretsMixin:
return self.cleaned_data["gstfsd_key"] or self.instance.gstfsd_key
class TagsWidget(forms.SelectMultiple):
"""The tags there are and those given, to choose from or add to (Tom Select)."""
def __init__(self):
# Tom Select's line for a new name typed, and for one that cannot be a tag (searchable_select.js)
super().__init__(attrs={"data-tags": "", "data-add": _("Add tag %(tag)s"), "data-rule": _(
"A new tag: letters a-z, digits, dots, dashes and underscores, beginning with a letter or digit; "
"at most 12 characters")})
def optgroups(self, name, value, attrs=None):
self.choices = [(n, n) for n in sorted(set(Tag.objects.values_list("name", flat=True)) | set(value))]
return super().optgroups(name, value, attrs)
class TagsField(forms.Field):
"""Tag names, each once and in lower case; the tags are made when saved (Tag.named).
The form carries the names it showed: sent back unchanged, they are not set again,
so a form shown before a tag was renamed or deleted does not undo that."""
widget = TagsWidget
hidden_widget = forms.MultipleHiddenInput
def __init__(self, **kwargs):
super().__init__(required=False, label=_("Tags"), show_hidden_initial=True, **kwargs)
def to_python(self, value):
names = [str(name).strip().lower() for name in value or ()]
return list(dict.fromkeys(name for name in names if name))
def has_changed(self, initial, data):
return set(self.to_python(initial)) != set(self.to_python(data))
def validate(self, value):
existing = set(Tag.objects.filter(name__in=value).values_list("name", flat=True))
for name in value:
if name not in existing: # a tag made before the limit can still be given
TAG_LENGTH(name)
TAG_NAME(name)
class TagsForm(forms.Form):
tags = TagsField()
class ComputeTagsMixin:
"""The compute's tags on its form."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["tags"] = TagsField()
if self.is_bound: # shown again (an error): the tags first shown, still to tell them from a change
self.initial["tags"] = self["tags"].field.hidden_widget().value_from_datadict(
self.data, self.files, self["tags"].html_initial_name)
elif self.instance.pk:
self.initial["tags"] = list(self.instance.tags.values_list("name", flat=True))
def save(self, commit=True):
# the host and its tags in one step, not while the Tags page deletes or renames one
with transaction.atomic():
lock_ownership()
compute = super().save(commit)
if commit and "tags" in self.changed_data:
compute.tags.set(Tag.named(self.cleaned_data["tags"]))
return compute
SECRET_WIDGETS = {"password": forms.PasswordInput(), "gstfsd_key": forms.PasswordInput()}
DETAILS = {"details": _("Description")}
DETAILS_HELP = {"details": _("Shown on the hosts list")}
SASL_LABELS = {"login": _("SASL login"), "password": _("SASL password")} | DETAILS
class TcpComputeForm(KeepSecretsMixin, forms.ModelForm):
class TcpComputeForm(ComputeTagsMixin, KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_TCP
kind = "TCP"
about = _("libvirt over TCP, with a SASL login")
hostname = forms.CharField(validators=[validate_hostname])
hostname = forms.CharField(validators=[validate_hostname], label=_("FQDN/IP"))
class Meta:
model = Compute
widgets = SECRET_WIDGETS
labels = SASL_LABELS
help_texts = DETAILS_HELP
exclude = ["type"]
exclude = ["type", "tags"]
class SshComputeForm(KeepSecretsMixin, forms.ModelForm):
class SshComputeForm(ComputeTagsMixin, KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_SSH
kind = "SSH"
about = _("libvirt over SSH, with the panel's SSH key")
@ -58,24 +126,24 @@ class SshComputeForm(KeepSecretsMixin, forms.ModelForm):
widgets = SECRET_WIDGETS
labels = {"login": _("SSH user")} | DETAILS
help_texts = DETAILS_HELP
exclude = ["password", "type"]
exclude = ["password", "type", "tags"]
class TlsComputeForm(KeepSecretsMixin, forms.ModelForm):
class TlsComputeForm(ComputeTagsMixin, KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_TLS
kind = "TLS"
about = _("libvirt over TLS, with certificates")
hostname = forms.CharField(validators=[validate_hostname])
hostname = forms.CharField(validators=[validate_hostname], label=_("FQDN/IP"))
class Meta:
model = Compute
widgets = SECRET_WIDGETS
labels = SASL_LABELS
help_texts = DETAILS_HELP
exclude = ["type"]
exclude = ["type", "tags"]
class SocketComputeForm(KeepSecretsMixin, forms.ModelForm):
class SocketComputeForm(ComputeTagsMixin, KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_SOCKET
kind = _("Local")
about = _("the libvirt of the host the panel runs on, by its socket")
@ -86,4 +154,4 @@ class SocketComputeForm(KeepSecretsMixin, forms.ModelForm):
widgets = SECRET_WIDGETS
labels = DETAILS
help_texts = DETAILS_HELP
fields = ["name", "details", "hostname", "migration_address", "gstfsd_key"]
fields = ["name", "details", "hostname", "migration_address", "migration_tls", "gstfsd_key"]

223
computes/jobs.py Normal file
View file

@ -0,0 +1,223 @@
"""Jobs of the computes app (operations framework)."""
import time
from contextlib import suppress
from django.core.exceptions import PermissionDenied
from django.utils.translation import gettext_noop
from instances.models import Instance
from vrtManager import util
from computes.models import Compute
from operations import claims, jobs, utils
from operations.jobs import Cancelled, Kind, Outcome, Plan, register
from operations.models import Claim, Operation
# where a host is: a bulk migration stops if a host's record points elsewhere since it was asked
WHERE = ("hostname", "login", "type")
def _where(hosts):
return [list(Compute.objects.filter(pk=pk).values_list(*WHERE).first() or []) for pk in sorted(hosts)]
def parallel_limit():
"""The most migrations a bulk migration runs at once: the worker gives a
host's jobs half of its slots, and the bulk migration itself takes one."""
slots = utils.concurrency()
return min(max(1, slots // 2), slots - 1)
class Migrations(Kind):
"""Migrates VMs, each in a migrate job of its own, at most parallel at
once: one that fails stays where it is and the rest go on. One such job
at a time (it waits in a worker slot for its migrations). A kind gives
its moves, [(VM, source, target)], and the options of its migrations."""
cancellable = True
options = {}
def moves(self, params):
raise NotImplementedError
def hosts(self, params):
return {host for _vm, source, target in self.moves(params) for host in (source, target)}
def check_move(self, source, target):
"""Refuses (OperationError) a move to a host in maintenance, when the
job is asked for and again before the VM's migration starts; the
migrate job checks the rest."""
if host := Compute.objects.filter(pk=target).first():
host.refuse_new_vms()
def validate(self, user, params):
if not user.is_superuser:
raise PermissionDenied
if not self.moves(params):
raise util.OperationError(gettext_noop("Choose the VMs to migrate"))
if not 1 <= params["parallel"] <= parallel_limit():
raise util.OperationError(gettext_noop("At most %(limit)s migrations can run at once"),
limit=parallel_limit())
for _vm, source, target in self.moves(params):
self.check_move(source, target)
def precheck(self, op, ctx):
if op.user is None or not op.user.is_active or not op.user.is_superuser:
raise PermissionDenied
def run(self, op, ctx):
p = op.params
moves = self.moves(p)
names = dict(Instance.objects.filter(pk__in=[vm for vm, _source, _target in moves]).values_list("pk", "name"))
waiting = [move for move in moves if move[0] in names] # one deleted meanwhile is left out
started, refused = {}, [] # VM: its migrate job; the VMs whose job was refused, and why
ctx.record_intent()
ctx.set_phase(gettext_noop("Migrating the VMs"))
def stop(text, **values):
"""End the job failed; recovery, which the worker hands such a job, adds nothing."""
ctx.record_intent(stopped=True)
raise util.OperationError(text, **values)
while True:
running = list(Operation.objects.filter(pk__in=started.values(), state__in=Operation.ACTIVE)
.values_list("pk", flat=True))
op.refresh_from_db(fields=["cancel_requested"])
if op.cancel_requested:
for pk in running:
with suppress(Exception): # it ended meanwhile
jobs.cancel(pk, op.user)
raise Cancelled
# the worker's slots may have been lowered: this job waits in one, its migrations need others;
# once it ends, the migrations it queued run
if parallel_limit() < 1:
stop(gettext_noop("The worker now runs one job at a time: the VMs not yet started stay where they are"))
if waiting and _where(self.hosts(p)) != op.intent["where"]:
stop(gettext_noop("A host was changed or deleted: the VMs not yet started stay where they are"))
for move in list(waiting):
if len(running) >= min(p["parallel"], parallel_limit()):
break
waiting.remove(move)
vm, source, target = move
if not Instance.objects.filter(pk=vm, compute_id=source).exists():
continue # it left its host meanwhile
raw = {"instance": vm, "source": source, "target": target, "live": True, "autoconverge": True,
**self.options}
try:
self.check_move(source, target) # a host put in maintenance since
child = jobs.submit("instance.migrate", op.user, raw, f"bulk-{op.pk.hex}-{vm}", parent=op)
except claims.Busy as busy:
if busy.blocker is not None and busy.blocker.state == Operation.UNCERTAIN:
# it holds its claims until someone resolves it
refused.append(f"{names[vm]}: {utils.busy_message(busy, op.user, named=False)}")
else:
waiting.append(move) # another job holds the VM or a host: asked again on the next round
except Exception as err:
refused.append(f"{names[vm]}: {utils.safe_text(err)}")
else:
started[vm] = child.pk
running.append(child.pk)
ctx.record_intent(migrations={str(vm): str(job) for vm, job in started.items()})
if not waiting and not running:
break
time.sleep(2)
migrated = set(Operation.objects.filter(pk__in=started.values(), state=Operation.SUCCEEDED)
.values_list("pk", flat=True))
failed = refused + [names[vm] for vm, job in started.items() if job not in migrated]
if failed:
stop(gettext_noop("These VMs did not migrate: %(vms)s"), vms=", ".join(failed))
return {}
def progress(self, op):
"""(the VMs whose migration ended, the VMs to migrate)."""
return op.children.filter(state__in=Operation.TERMINAL).count(), len(self.moves(op.params))
def cancel(self, op):
"""run sees the cancel and cancels the migrations that run."""
def reconcile(self, op):
if op.intent.get("stopped"):
return Outcome(Operation.FAILED) # its own error says why
return Outcome(Operation.FAILED, error=utils.say(gettext_noop(
"The bulk migration stopped: the migrations it started go on as their own jobs; the other VMs stay")))
@register
class BulkMigrate(Migrations):
"""Migrates the chosen VMs of a host to other hosts, one or several,
for the host's maintenance: a running VM live, a shut-off one offline."""
name = "host.bulk_migrate"
label = gettext_noop("Bulk migrate")
def normalize(self, raw):
moves = {int(vm): int(target) for vm, target in raw["moves"]}
# maintenance: the host was put in maintenance with the job (computes.views.bulk_migrate)
return {"compute": int(raw["compute"]), "parallel": int(raw["parallel"]),
"moves": [[vm, target] for vm, target in sorted(moves.items())],
"maintenance": bool(raw.get("maintenance"))}
def moves(self, params):
return [(vm, params["compute"], target) for vm, target in params["moves"]]
def validate(self, user, params):
super().validate(user, params)
targets = {target for _vm, target in params["moves"]}
if params["compute"] in targets:
raise util.OperationError(gettext_noop("A VM is already on its destination"))
if Compute.objects.filter(pk__in=targets).count() != len(targets):
raise util.OperationError(gettext_noop("A destination host was deleted"))
def plan(self, user, params):
compute = Compute.objects.get(pk=params["compute"])
targets = {target for _vm, target in params["moves"]}
names = Compute.objects.filter(pk__in=targets).order_by("name").values_list("name", flat=True)
return Plan(claims={claims.bulk_migrate_key(): Claim.EXCLUSIVE}, resource=claims.compute_key(compute.pk),
label=f"{compute.name} -> {', '.join(names)}",
intent={"migrations": {}, "where": _where(self.hosts(params))})
def log_entry(self, op, state):
source, _sep, targets = op.resource_label.partition(" -> ")
message = f"Bulk migrate to {targets}"
return source, "", "", message if state == Operation.SUCCEEDED else f"{message} ({state})"
@register
class Balance(Migrations):
"""Migrates running VMs between hosts, as the Balance page proposed, to
even out what the hosts give their running VMs. Each migration takes
only a running VM: one stopped since is left where it is."""
name = "host.balance"
label = gettext_noop("Balance")
options = {"running_only": True}
def normalize(self, raw):
moves = {int(vm): (int(source), int(target)) for vm, source, target in raw["moves"]}
return {"parallel": int(raw["parallel"]),
"moves": [[vm, source, target] for vm, (source, target) in sorted(moves.items())]}
def moves(self, params):
return [tuple(move) for move in params["moves"]]
def check_move(self, source, target):
"""Balance leaves a host in maintenance out: it takes no VM and gives none."""
super().check_move(source, target)
if host := Compute.objects.filter(pk=source, maintenance_since__isnull=False).first():
raise util.OperationError(gettext_noop("%(compute)s is in maintenance: Balance leaves it out"),
compute=host.name)
def validate(self, user, params):
super().validate(user, params)
if any(source == target for _vm, source, target in self.moves(params)):
raise util.OperationError(gettext_noop("A VM is already on its destination"))
def plan(self, user, params):
names = Compute.objects.filter(pk__in=self.hosts(params)).order_by("name").values_list("name", flat=True)
return Plan(claims={claims.bulk_migrate_key(): Claim.EXCLUSIVE}, resource=claims.bulk_migrate_key(),
label=", ".join(names), intent={"migrations": {}, "where": _where(self.hosts(params))})
def log_entry(self, op, state):
message = f"Balance {op.resource_label}: {len(op.params['moves'])} VMs"
return "", "", "", message if state == Operation.SUCCEEDED else f"{message} ({state})"

View file

@ -0,0 +1,18 @@
# Generated by Django 5.2.18 on 2026-11-16 12:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('computes', '0009_host_uuid'),
]
operations = [
migrations.AddField(
model_name='compute',
name='maintenance',
field=models.BooleanField(default=False, editable=False),
),
]

View file

@ -0,0 +1,27 @@
from django.db import migrations, models
from django.utils import timezone
def keep_maintenance(apps, schema_editor):
# a host in maintenance stays in it, from now on
apps.get_model("computes", "Compute").objects.filter(maintenance=True).update(maintenance_since=timezone.now())
class Migration(migrations.Migration):
dependencies = [
("computes", "0010_maintenance"),
]
operations = [
migrations.AddField(
model_name="compute",
name="maintenance_since",
field=models.DateTimeField(blank=True, editable=False, null=True),
),
migrations.RunPython(keep_maintenance, migrations.RunPython.noop),
migrations.RemoveField(
model_name="compute",
name="maintenance",
),
]

View file

@ -0,0 +1,29 @@
# Generated by Django 5.2.18 on 2026-11-18 16:21
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('computes', '0011_maintenance_since'),
]
operations = [
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32, unique=True, validators=[django.core.validators.RegexValidator('^[a-z0-9][a-z0-9._-]*\\Z', 'A tag is letters a-z, digits, dots, dashes and underscores, and begins with a letter or digit')], verbose_name='name')),
],
options={
'ordering': ['name'],
},
),
migrations.AddField(
model_name='compute',
name='tags',
field=models.ManyToManyField(blank=True, related_name='computes', to='computes.tag', verbose_name='tags'),
),
]

View file

@ -0,0 +1,19 @@
# Generated by Django 5.2.18 on 2026-11-19 06:31
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('computes', '0012_tags'),
]
operations = [
migrations.AlterField(
model_name='tag',
name='name',
field=models.CharField(max_length=32, unique=True, validators=[django.core.validators.RegexValidator('^[a-z0-9][a-z0-9._-]*\\Z', 'A tag is letters a-z, digits, dots, dashes and underscores, and begins with a letter or digit'), django.core.validators.MaxLengthValidator(12, 'A tag has at most %(limit_value)d characters')], verbose_name='name'),
),
]

View file

@ -0,0 +1,18 @@
# Generated by Django 5.2.18 on 2026-11-19 11:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('computes', '0013_tag_length'),
]
operations = [
migrations.AddField(
model_name='compute',
name='migration_tls',
field=models.BooleanField(default=False, help_text="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", verbose_name='encrypt migrations (TLS)'),
),
]

View file

@ -1,17 +1,52 @@
from collections import Counter
from ipaddress import ip_address
from django.core.exceptions import ValidationError
from django.core.validators import MaxLengthValidator, RegexValidator
from django.db import IntegrityError, transaction
from django.db.models import CharField, IntegerField, Model, Q, UniqueConstraint
from django.db.models import BooleanField, CharField, DateTimeField, IntegerField, ManyToManyField, Model, Q, UniqueConstraint
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext_noop
from libvirt import libvirtError, virConnect
from computes.validators import validate_gstfsd_key, validate_hostname, validate_login, validate_migration_address
from vrtManager import util
from vrtManager.connection import connection_manager
from vrtManager.hostdetails import wvmHostDetails
# a new or renamed tag's length, so its badge stays short in a list's row; the
# column keeps 32: names made before the limit stay until renamed
TAG_LENGTH = MaxLengthValidator(12, _("A tag has at most %(limit_value)d characters"))
TAG_NAME = RegexValidator(r"^[a-z0-9][a-z0-9._-]*\Z",
_("A tag is letters a-z, digits, dots, dashes and underscores, and begins with a letter or digit"))
class Tag(Model):
"""A name given to VMs and hosts, kept in lower case: one name is one tag."""
name = CharField(_("name"), max_length=32, unique=True, validators=[TAG_NAME, TAG_LENGTH])
class Meta:
ordering = ["name"]
def __str__(self):
return self.name
@staticmethod
def counts(rows):
"""The tag list's choices for rows (VMs or hosts, their tags read):
[(name, how many have it)], the most used first, and how many have no tag."""
counts = Counter(tag.name for row in rows for tag in row.tags.all())
return sorted(counts.items(), key=lambda item: (-item[1], item[0])), sum(1 for row in rows if not row.tags.all())
@classmethod
def named(cls, names):
"""The tags of names, those not there yet made."""
return [cls.objects.get_or_create(name=name)[0] for name in names]
# what the panel connects to a compute with
ENDPOINT = ("hostname", "login", "password", "type")
@ -34,6 +69,14 @@ class Compute(Model):
"empty: the address the panel reaches the host at"
),
)
migration_tls = BooleanField(
_("encrypt migrations (TLS)"),
default=False,
help_text=_(
"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"
),
)
gstfsd_key = CharField(
_("gstfsd key"),
max_length=64,
@ -50,9 +93,36 @@ class Compute(Model):
# reaches it: one host is one compute, and a compute's VMs stay on it
host_uuid = CharField(max_length=36, blank=True, default="", editable=False)
# in maintenance: no new VM and no migration comes to the host, none of its
# VMs starts there, and Balance leaves it out; Bulk Migrate empties it, and
# it is ready once none of its VMs runs (refuse_new_vms, refuse_start);
# since when: the host's bulk migrations from then on are its own
maintenance_since = DateTimeField(null=True, blank=True, editable=False)
tags = ManyToManyField(Tag, blank=True, related_name="computes", verbose_name=_("tags"))
class Meta:
constraints = [UniqueConstraint(fields=["host_uuid"], condition=~Q(host_uuid=""), name="one_compute_per_host")]
@property
def maintenance(self):
return self.maintenance_since is not None
def _in_maintenance_now(self):
"""Read now: a page or job may hold the compute from before it went in maintenance."""
return Compute.objects.filter(pk=self.pk, maintenance_since__isnull=False).exists()
def refuse_new_vms(self):
"""Refuses a VM made on or migrated to the host while it is in maintenance."""
if self._in_maintenance_now():
raise util.OperationError(gettext_noop("%(compute)s is in maintenance: no new VM or migration comes to it"),
compute=self.name)
def refuse_start(self):
"""Refuses starting or resuming a VM of the host, or its autostart, while it is in maintenance."""
if self._in_maintenance_now():
raise util.OperationError(gettext_noop("%(compute)s is in maintenance: its VMs cannot be started there; "
"migrate the VM to start it on another host"), compute=self.name)
@property
def migration_uri(self):
"""The native migration URI for VMs migrated to this host: its

61
computes/reach.py Normal file
View file

@ -0,0 +1,61 @@
"""Where the VMs of a bulk migration or a balance can migrate without a disk
copy, each host and each directory a pair of hosts may share asked once:
the pages ask it for every VM and destination."""
import os
from django.utils.translation import gettext_lazy as _
from libvirt import VIR_DOMAIN_XML_INACTIVE, libvirtError
from vrtManager.instance import file_disks, wvmInstances
from webvirtcloud.middleware import error_text
class Reach:
def __init__(self, request):
self.request = request
self.conns = {} # compute pk: its connection
self.hosts = set() # (source pk, target pk) a VM of the source was found able to go to
self.shared = {} # (source pk, target pk, directory): whether both hosts see it as one, or why not known
self.directories = {} # VM pk: the directories of its file disks, or the error that read them
def _conn(self, compute):
if compute.pk not in self.conns:
self.conns[compute.pk] = wvmInstances(compute.hostname, compute.login, compute.password, compute.type)
return self.conns[compute.pk]
def refusal(self, instance, target):
"""Why the VM cannot migrate to target in a bulk migration, or None:
target is another host the panel reaches, and both hosts see every
disk file of the VM, now and at its next start (one they do not
takes a copy, chosen on the VM's Migrate tab)."""
from instances.jobs import migration_target
pair = (instance.compute_id, target.pk)
if pair not in self.hosts:
# kept once it passed: a refusal may be the VM's own (gone meanwhile), not the hosts'
try:
migration_target(instance, target.pk)
self.hosts.add(pair)
except libvirtError as err:
return error_text(self.request, err)
if instance.pk not in self.directories:
try:
domain = instance.proxy.instance
xmls = (domain.XMLDesc(0), domain.XMLDesc(VIR_DOMAIN_XML_INACTIVE))
self.directories[instance.pk] = {os.path.dirname(path) for xml in xmls for _disk, path in file_disks(xml)}
except libvirtError as err:
self.directories[instance.pk] = error_text(self.request, err)
if isinstance(self.directories[instance.pk], str):
return self.directories[instance.pk]
for directory in sorted(self.directories[instance.pk]):
key = (*pair, directory)
if key not in self.shared:
try:
self.shared[key] = self._conn(target).shares(self._conn(instance.compute), directory)
except libvirtError as err: # a host's pools could not be read: not that destination
self.shared[key] = error_text(self.request, err)
if isinstance(self.shared[key], str):
return self.shared[key]
if not self.shared[key]:
return _("A disk file is not on storage both hosts share: migrate it from its page")
return None

View file

@ -0,0 +1,39 @@
{% load i18n %}{% load bootstrap_icons %}{# what wants a look: views.attention, each with a link to where it is handled #}
{% if attention %}
<div class="alert alert-warning" role="status">
<h2 class="h6">{% bs_icon 'exclamation-triangle' %} {% trans "Needs attention" %}</h2>
<ul class="mb-0 small">
{% for compute in attention.hosts %}
<li><a href="{% url 'overview' compute.pk %}">{{ compute.name }}</a>: {% trans "not answering" %}</li>
{% endfor %}
{% for compute, pool in attention.pools %}
<li><a href="{% url 'storage' compute.pk pool.name %}">{{ compute.name }} / {{ pool.name }}</a>: {% blocktrans with percent=pool.percent %}{{ percent }}% full{% endblocktrans %}</li>
{% endfor %}
{% for compute, vm, snapshots in attention.snapshots %}
<li>{% if vm %}<a href="{% url 'instances:instance' vm.pk %}{% if not vm.is_template %}#snapshots{% endif %}">{{ compute.name }} / {{ vm.name }}</a>{% else %}{{ compute.name }} / {{ snapshots.vm }}{% endif %}:
{% blocktrans count counter=snapshots.count %}{{ counter }} snapshot older than 30 days{% plural %}{{ counter }} snapshots older than 30 days{% endblocktrans %}</li>
{% endfor %}
{% for target, source, what in attention.lacking %}
<li><a href="{% url 'overview' target.pk %}">{{ target.name }}</a>: {% blocktrans with host=source.name %}VMs of {{ host }} could not migrate here:{% endblocktrans %} {{ what|join:"; " }}</li>
{% endfor %}
{% if attention.failed %}
<li><a href="{% url 'operations:jobs' %}?kind=backup.create&amp;state=failed">{% blocktrans count counter=attention.failed %}{{ counter }} backup failed in the last 7 days{% plural %}{{ counter }} backups failed in the last 7 days{% endblocktrans %}</a></li>
{% endif %}
{% for policy, count in attention.not_taken %}
<li><a href="{% url 'vmbackups:policy' policy.pk %}">{{ policy.name }}</a>: {% blocktrans count counter=count %}{{ counter }} scheduled backup not taken in the last 7 days{% plural %}{{ counter }} scheduled backups not taken in the last 7 days{% endblocktrans %}</li>
{% endfor %}
{% if attention.missing %}
<li><a href="{% url 'vmbackups:index' %}?state=missing">{% blocktrans count counter=attention.missing %}{{ counter }} backup missing from its target{% plural %}{{ counter }} backups missing from their targets{% endblocktrans %}</a></li>
{% endif %}
{% if attention.damaged %}
<li><a href="{% url 'vmbackups:index' %}?state=damaged">{% blocktrans count counter=attention.damaged %}{{ counter }} backup damaged{% plural %}{{ counter }} backups damaged{% endblocktrans %}</a></li>
{% endif %}
{% if attention.uncertain %}
<li><a href="{% url 'operations:jobs' %}?state=uncertain">{% blocktrans count counter=attention.uncertain %}{{ counter }} job ended uncertain{% plural %}{{ counter }} jobs ended uncertain{% endblocktrans %}</a></li>
{% endif %}
{% if attention.waiting %}
<li><a href="{% url 'operations:jobs' %}?state=queued">{% blocktrans count counter=attention.waiting %}{{ counter }} job queued for over an hour{% plural %}{{ counter }} jobs queued for over an hour{% endblocktrans %}</a></li>
{% endif %}
</ul>
</div>
{% endif %}

View file

@ -0,0 +1,141 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load static %}
{% load operations %}
{% load bootstrap_icons %}
{% block title %}{% trans "Balance" %}{% endblock %}
{% block page_header %}{% endblock page_header %}{# the page has its own heading #}
{% block content %}
<nav aria-label="breadcrumb">
<ol class="breadcrumb shadow-sm">
<li class="breadcrumb-item"><a href="{% url 'computes' %}">{% bs_icon 'hdd-rack' %} {% trans "Computes" %}</a></li>
<li class="breadcrumb-item active fw-bold" aria-current="page">{% trans "Balance" %}</li>
</ol>
</nav>
<h1 class="visually-hidden">{% trans "Balance" %}</h1>
<p class="text-body-secondary">{% trans "Migrations that give each host about the same share of its memory, then of its CPUs, for its running VMs: a host twice as large takes twice as much." %}</p>
{% if unreachable %}
<div class="alert alert-warning shadow-sm">{% trans "These hosts cannot be read and are left out:" %} {{ unreachable|join:", " }}</div>
{% endif %}
{% if resting %}
<div class="alert alert-secondary shadow-sm">{% trans "These hosts are in maintenance and are left out:" %} {{ resting|join:", " }}</div>
{% endif %}
{# each host's running VMs: the share of its memory now and, light to dark, after the migrations #}
<div class="row row-cols-1 row-cols-md-2 row-cols-xl-3 g-3 mb-4">
{% for host in hosts %}
<div class="col">
<div class="card h-100 shadow-sm"><div class="card-body">
<div class="d-flex justify-content-between mb-2"><span class="fw-semibold">{{ host.name }}</span>
<span class="small text-body-secondary">{% widthratio host.size.0 1 1024 as bytes %}{{ bytes|binary_size }}</span></div>
{% for bar in host.bars %}{% if forloop.first or moves %}
{% if forloop.first %}{% with memory=host.before.0 vcpus=host.before.1 %}
<div class="d-flex justify-content-between small"><span class="text-body-secondary">{% if moves %}{% trans "Now" %}{% else %}{% trans "Running VMs" %}{% endif %}</span>
<span>{% widthratio memory 1 1024 as bytes %}{{ bytes|binary_size }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}</span></div>
{% endwith %}{% else %}{% with memory=host.after.0 vcpus=host.after.1 %}
<div class="d-flex justify-content-between small mt-2"><span class="text-body-secondary">{% trans "After" %}</span>
<span class="fw-semibold">{% widthratio memory 1 1024 as bytes %}{{ bytes|binary_size }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}</span></div>
{% endwith %}{% endif %}
<div class="progress" role="progressbar" style="--bs-progress-height: 0.6rem;" aria-label="{% if forloop.first %}{% trans "Memory now" %}{% else %}{% trans "Memory after" %}{% endif %}"
aria-valuenow="{{ bar|floatformat:0 }}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar bg-primary{% if forloop.first and moves %} bg-opacity-50{% endif %}" style="width: {{ bar|stringformat:".1f" }}%"></div>
</div>
{% endif %}{% endfor %}
</div></div>
</div>
{% endfor %}
</div>
{# unticking a VM keeps it where it is and makes the proposal again #}
<form method="get" id="balance-form">
{% for instance in moves %}<input type="hidden" name="shown" value="{{ instance.pk }}">{% endfor %}
{% for instance in pinned %}<input type="hidden" name="shown" value="{{ instance.pk }}">{% endfor %}
</form>
{% if moves %}
<form method="post" class="card shadow-sm mb-4">{% csrf_token %}{% submission_key %}
<div class="card-header fw-semibold">{% blocktrans count counter=moves|length %}Proposed migration ({{ counter }}){% plural %}Proposed migrations ({{ counter }}){% endblocktrans %}</div>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead>
<tr>
<th scope="col" class="ps-3"><input class="form-check-input" type="checkbox" id="balance-all" form="balance-form"{% if not pinned %} checked{% endif %} aria-label="{% trans "Select all" %}" title="{% trans "Select all" %}"></th>
<th scope="col">{% trans "Name" %}</th>
<th scope="col" class="text-end">{% trans "Memory" %}</th>
<th scope="col" class="text-end">vCPU</th>
<th scope="col">{% trans "Migration" %}</th>
</tr>
</thead>
<tbody>
{% for instance in moves %}
<tr>
<td class="ps-3"><input class="form-check-input" type="checkbox" name="vm" value="{{ instance.pk }}" id="balance-{{ instance.pk }}" form="balance-form" checked></td>
<td><label for="balance-{{ instance.pk }}">{{ instance.name }}</label>
<input type="hidden" name="instance" value="{{ instance.pk }}">
<input type="hidden" name="source" value="{{ instance.compute_id }}">
<input type="hidden" name="target" value="{{ instance.target.pk }}"></td>
<td class="text-end text-nowrap">{% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|binary_size }}</td>
<td class="text-end">{{ instance.info.3 }}</td>
<td>{{ instance.compute.name }} {% bs_icon 'arrow-right' %} {{ instance.target.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="card-footer d-flex flex-wrap align-items-center gap-2">
{% if parallel %}
<label class="small text-body-secondary" for="balance-parallel">{% trans "Migrations at once" %}</label>
<select name="parallel" id="balance-parallel" class="form-select form-select-sm w-auto">
{% for n in parallel %}<option value="{{ n }}"{% if forloop.last %} selected{% endif %}>{{ n }}</option>{% endfor %}
</select>
{% blocktrans count counter=moves|length asvar label %}Migrate {{ counter }} VM{% plural %}Migrate {{ counter }} VMs{% endblocktrans %}
<button type="submit" class="btn btn-primary ms-auto" data-confirm="{% trans "Migrate the VMs listed?" %}">{{ label }}</button>
{% else %}
<span class="small text-warning-emphasis">{% trans "The worker runs one job at a time: set Worker Concurrency to 2 or more on the Settings page." %}</span>
{% endif %}
</div>
</form>
{% else %}
<div class="alert alert-success shadow-sm">{% trans "The hosts are balanced: no migration would even them out more." %}</div>
{% endif %}
{% if pinned or unmovable %}
<div class="card shadow-sm">
<div class="card-header fw-semibold">{% trans "Stay where they are" %}</div>
<div class="table-responsive">
<table class="table align-middle mb-0">
<thead>
<tr>
<th scope="col" class="ps-3"><span class="visually-hidden">{% trans "Let it move" %}</span></th>
<th scope="col">{% trans "Name" %}</th>
<th scope="col">{% trans "Host" %}</th>
<th scope="col">{% trans "Why" %}</th>
</tr>
</thead>
<tbody>
{% for instance in pinned %}
<tr>
<td class="ps-3"><input class="form-check-input" type="checkbox" name="vm" value="{{ instance.pk }}" id="balance-{{ instance.pk }}" form="balance-form" aria-label="{% trans "Let it move" %}" title="{% trans "Let it move" %}"></td>
<td><label for="balance-{{ instance.pk }}">{{ instance.name }}</label></td>
<td>{{ instance.compute.name }}</td>
<td class="small text-body-secondary">{% trans "You kept it here: tick it to let it move" %}</td>
</tr>
{% endfor %}
{% for instance in unmovable %}
<tr>
<td class="ps-3"></td>
<td>{{ instance.name }}</td>
<td>{{ instance.compute.name }}</td>
<td class="small text-body-secondary">{% for refusal in instance.refusals %}{{ refusal }}{% if not forloop.last %}<br>{% endif %}{% endfor %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
{% endblock %}
{% block script %}
<script src="{% static 'js/balance.js' %}"></script>
{% endblock %}

View file

@ -0,0 +1,127 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load static %}
{% load operations %}
{% load bootstrap_icons %}
{% block title %}{% trans "Bulk migrate" %} - {{ compute.name }}{% endblock %}
{% block page_heading %}{{ compute.name }} - {% trans "Bulk migrate" %}{% endblock page_heading %}
{% block content %}
<div class="row">
<div class="col-lg-12">
{% include "computes/host_nav.html" with section="instances" detail=True %}
</div>
</div>
{% if entering %}
{# asked from "Put in maintenance": the host goes in maintenance with its VMs' migration, or without one #}
<div class="alert alert-warning shadow-sm d-flex flex-wrap align-items-center gap-2">
<div class="me-auto">{% blocktrans with host=compute.name %}Put {{ host }} in maintenance: from then on no new VM or migration comes to it, its VMs cannot be started there, and Balance leaves it out. Migrate its VMs below, or put it in maintenance without migrating them.{% endblocktrans %}</div>
<form method="post" action="{% url 'compute_maintenance' compute.id %}">{% csrf_token %}
<input type="hidden" name="maintenance" value="on">
<button type="submit" class="btn btn-sm btn-warning" data-confirm="{% trans "Put the host in maintenance without migrating its VMs?" %}">{% trans "Put in maintenance without migrating" %}</button>
</form>
</div>
{% endif %}
{% if not targets %}
<div class="alert alert-warning shadow-sm">{% trans "There is no other host to migrate to." %}</div>
{% else %}
<p class="text-body-secondary">{% trans "Each chosen VM migrates in a job of its own: a running VM live, a shut-off one offline. A VM that fails stays on this host." %}</p>
{% if unreachable %}
<div class="alert alert-warning shadow-sm">{% trans "These hosts cannot be read and are left out:" %} {{ unreachable|join:", " }}</div>
{% endif %}
{# another destination reloads the list: which VMs can go depends on it; spread over the hosts, so does a VM ticked #}
<form method="get" id="bulk-migrate-choose"{% if spreading %} data-spread{% endif %}>
{% if entering %}<input type="hidden" name="maintenance" value="on">{% endif %}
{% if spreading %}{% for instance in instances %}{% if not instance.refusal %}<input type="hidden" name="shown" value="{{ instance.pk }}">{% endif %}{% endfor %}{% endif %}
</form>
{% if not parallel %}
<div class="alert alert-warning shadow-sm">{% trans "The worker runs one job at a time: set Worker Concurrency to 2 or more on the Settings page." %}</div>
{% elif not instances %}
<p class="text-center text-body-secondary py-4">{% trans "The host has no VMs." %}</p>
{% else %}
<form method="post" class="card shadow-sm">{% csrf_token %}{% submission_key %}
{% if entering %}<input type="hidden" name="maintenance" value="on">{% endif %}
{% if spreading %}<input type="hidden" name="spread" value="1">{% else %}<input type="hidden" name="target" value="{{ target.pk }}">{% endif %}
<div class="card-header d-flex flex-wrap align-items-center gap-2">
<span class="fw-semibold">{{ compute.name }}</span> {% bs_icon 'arrow-right' %}
{% if targets|length > 1 %}
<select name="target" id="bulk-migrate-target" form="bulk-migrate-choose" class="form-select form-select-sm w-auto" aria-label="{% trans "Destination" %}">
<option value="spread"{% if spreading %} selected{% endif %}>{% trans "Spread over the other hosts" %}</option>
{% for host in targets %}<option value="{{ host.pk }}"{% if host == target %} selected{% endif %}>{{ host.name }}</option>{% endfor %}
</select>
{% else %}
<span class="fw-semibold">{{ target.name }}</span>
{% endif %}
{% if tags %}{# bulk_migrate.js ticks the VMs with the tag chosen #}
<select id="bulk-migrate-tag" class="form-select form-select-sm w-auto ms-auto" aria-label="{% trans "Choose by tag" %}">
<option value="">{% trans "Choose by tag" %}</option>
{% for tag in tags %}<option value="{{ tag }}">{{ tag }}</option>{% endfor %}
</select>
{% endif %}
<div class="form-check form-switch {% if not tags %}ms-auto {% endif %}mb-0">
<input class="form-check-input" type="checkbox" role="switch" id="bulk-migrate-shut-off"{% if shut_off_ticked %} checked{% endif %}>
<label class="form-check-label small" for="bulk-migrate-shut-off">{% trans "Also migrate the shut-off VMs" %}</label>
</div>
</div>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead>
<tr>
<th scope="col" class="ps-3"><input class="form-check-input" type="checkbox" id="bulk-migrate-all"{% if all_ticked %} checked{% endif %} aria-label="{% trans "Select all" %}" title="{% trans "Select all" %}"></th>
<th scope="col">{% trans "Name" %}</th>
<th scope="col">{% trans "Status" %}</th>
<th scope="col" class="text-end">{% trans "Memory" %}</th>
<th scope="col" class="text-end">vCPU</th>
{% if spreading %}<th scope="col">{% trans "Destination" %}</th>{% endif %}
<th scope="col"><span class="visually-hidden">{% trans "Why" %}</span></th>
</tr>
</thead>
<tbody>
{% for instance in instances %}
<tr>
<td class="ps-3">
{% if spreading %}
<input class="form-check-input bulk-migrate-vm" type="checkbox" name="vm" value="{{ instance.pk }}" id="bulk-migrate-{{ instance.pk }}" data-tags="{% for tag in instance.tags.all %}{{ tag }}{% if not forloop.last %} {% endif %}{% endfor %}" form="bulk-migrate-choose"
{% if instance.info.0 == 5 %} data-shut-off{% endif %}{% if instance.target %} checked{% endif %}{% if instance.refusal %} disabled{% endif %}>
{% if instance.target %}<input type="hidden" name="instance" value="{{ instance.pk }}"><input type="hidden" name="target" value="{{ instance.target.pk }}">{% endif %}
{% else %}
<input class="form-check-input bulk-migrate-vm" type="checkbox" name="instance" value="{{ instance.pk }}" id="bulk-migrate-{{ instance.pk }}" data-tags="{% for tag in instance.tags.all %}{{ tag }}{% if not forloop.last %} {% endif %}{% endfor %}"
{% if instance.info.0 == 5 %} data-shut-off{% elif not instance.refusal %} checked{% endif %}{% if instance.refusal %} disabled{% endif %}>
{% endif %}
</td>
<td><label for="bulk-migrate-{{ instance.pk }}">{{ instance.name }}</label></td>
<td>{% include 'instance_state.html' %}</td>
<td class="text-end text-nowrap">{% if instance.info %}{% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|binary_size }}{% endif %}</td>
<td class="text-end">{{ instance.info.3 }}</td>
{% if spreading %}<td>{{ instance.target.name|default:"" }}</td>{% endif %}
<td class="small text-body-secondary">{{ instance.refusal|default:"" }}{{ instance.note|default:"" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{# kept in sight below a long list #}
<div class="card-footer sticky-bottom bg-body-tertiary d-flex flex-wrap align-items-center gap-2">
<label class="small text-body-secondary" for="bulk-migrate-parallel">{% trans "Migrations at once" %}</label>
<select name="parallel" id="bulk-migrate-parallel" class="form-select form-select-sm w-auto">
{% for n in parallel %}<option value="{{ n }}"{% if forloop.last %} selected{% endif %}>{{ n }}</option>{% endfor %}
</select>
{% if entering %}
{% blocktrans with source=compute.name asvar question %}Put {{ source }} in maintenance and migrate the chosen VMs?{% endblocktrans %}
{% elif spreading %}
{% blocktrans with source=compute.name asvar question %}Migrate the chosen VMs from {{ source }} to the hosts shown?{% endblocktrans %}
{% else %}
{% blocktrans with source=compute.name dest=target.name asvar question %}Migrate the chosen VMs from {{ source }} to {{ dest }}?{% endblocktrans %}
{% endif %}
<button type="submit" class="btn btn-primary ms-auto" id="bulk-migrate-submit" data-confirm="{{ question }}">
{% if entering %}{% trans "Migrate and put in maintenance" %}{% else %}{% trans "Migrate the chosen VMs" %}{% endif %} <span class="badge text-bg-light" id="bulk-migrate-count"></span>
</button>
</div>
</form>
{% endif %}
{% endif %}
{% endblock %}
{% block script %}
<script src="{% static 'js/bulk_migrate.js' %}"></script>
{% endblock %}

View file

@ -1,5 +1,5 @@
{% load i18n %}{% autoescape off %}{% if given %}
{% blocktrans count counter=given.vcpus.all with ratio=given.ratio|floatformat:1 assigned=given.assigned.all|filesizeformat %}Given to VMs: {{ counter }} vCPU ({{ ratio }}:1), {{ assigned }} memory.{% plural %}Given to VMs: {{ counter }} vCPUs ({{ ratio }}:1), {{ assigned }} memory.{% endblocktrans %}
{% load i18n common_tags %}{% autoescape off %}{% if given %}
{% blocktrans count counter=given.vcpus.all with ratio=given.ratio|floatformat:1 assigned=given.assigned.all|binary_size %}Given to VMs: {{ counter }} vCPU ({{ ratio }}:1), {{ assigned }} memory.{% plural %}Given to VMs: {{ counter }} vCPUs ({{ ratio }}:1), {{ assigned }} memory.{% endblocktrans %}
{% else %}
{% trans "The capacity could not be read." %}
{% endif %}{% endautoescape %}

View file

@ -1,18 +1,19 @@
{% load i18n %}
{% load common_tags %}
{# the memory a host has given its VMs: given, from views.shown_capacity #}
<div class="fs-4 lh-sm {% if given.bar.over %}text-danger{% elif given.memory_percent > 90 %}text-warning-emphasis{% endif %}">{{ given.memory_percent }} %</div>
<div class="small text-body-secondary mb-1">{{ given.assigned.all|filesizeformat }} / {{ given.memory|filesizeformat }}</div>
<div class="fs-4 lh-sm {% if given.bar.over %}text-danger{% elif given.memory_percent > 90 %}text-warning-emphasis{% endif %}">{{ given.memory_percent|percent }}</div>
<div class="small text-body-secondary mb-1">{{ given.assigned.all|binary_size }} / {{ given.memory|binary_size }}</div>
{# running VMs' memory, then shut-off VMs', on a scale that holds the host's memory or all given, whichever is larger #}
<div class="progress-stacked" style="--bs-progress-height: 0.6rem;" title="{% trans "Dark: running VMs. Light: shut-off VMs, which take their memory again when they start." %}">
<div class="progress" role="progressbar" style="width: {{ given.bar.running|stringformat:".1f" }}%"
aria-label="{% trans "Memory of running VMs" %}" aria-valuenow="{{ given.bar.running|floatformat:0 }}" aria-valuemin="0" aria-valuemax="100"
aria-valuetext="{% blocktrans with running=given.assigned.running|filesizeformat memory=given.memory|filesizeformat %}{{ running }} of the host's {{ memory }}{% endblocktrans %}">
aria-valuetext="{% blocktrans with running=given.assigned.running|binary_size memory=given.memory|binary_size %}{{ running }} of the host's {{ memory }}{% endblocktrans %}">
<div class="progress-bar {% if given.bar.over %}bg-danger{% else %}bg-primary{% endif %}"></div>
</div>
<div class="progress" role="progressbar" style="width: {{ given.bar.stopped|stringformat:".1f" }}%"
aria-label="{% trans "Memory of shut-off VMs" %}" aria-valuenow="{{ given.bar.stopped|floatformat:0 }}" aria-valuemin="0" aria-valuemax="100"
aria-valuetext="{% blocktrans with stopped=given.assigned.stopped|filesizeformat memory=given.memory|filesizeformat %}{{ stopped }} of the host's {{ memory }}{% endblocktrans %}">
aria-valuetext="{% blocktrans with stopped=given.assigned.stopped|binary_size memory=given.memory|binary_size %}{{ stopped }} of the host's {{ memory }}{% endblocktrans %}">
<div class="progress-bar {% if given.bar.over %}bg-danger{% else %}bg-primary{% endif %} bg-opacity-50"></div>
</div>
</div>
<div class="small text-body-secondary mt-1">{% blocktrans with running=given.assigned.running|filesizeformat %}{{ running }} running{% endblocktrans %}</div>
<div class="small text-body-secondary mt-1">{% blocktrans with running=given.assigned.running|binary_size %}{{ running }} in running VMs{% endblocktrans %}</div>

View file

@ -15,4 +15,4 @@
<div class="progress-bar {% if given.ratio > 4 %}bg-danger{% elif given.ratio > 2 %}bg-warning{% else %}bg-primary{% endif %} bg-opacity-50"></div>
</div>
</div>
<div class="small text-body-secondary mt-1">{% blocktrans with running=given.vcpus.running %}{{ running }} running{% endblocktrans %}</div>
<div class="small text-body-secondary mt-1">{% blocktrans with running=given.vcpus.running %}{{ running }} in running VMs{% endblocktrans %}</div>

View file

@ -1,6 +1,7 @@
{% extends "base.html" %}
{% load django_bootstrap5 %}
{% load i18n %}
{% load static %}
{% block title %}{% if form.instance.pk %}{% trans "Edit host" %}{% else %}{% trans "Add host" %}{% endif %}{% endblock %}
@ -9,6 +10,8 @@
<span class="badge text-bg-light border align-middle fs-6">{{ form.kind }}</span>
{% endblock page_heading %}
{% block style %}<link href="{% static 'css/tom-select.bootstrap5.min.css' %}" rel="stylesheet">{% endblock %}
{% block content %}
<p class="text-body-secondary">{{ form.about }}</p>
<form method="post">
@ -24,18 +27,24 @@
{% if "login" in form.fields %}<div class="col-md-6">{% bootstrap_field form.login %}</div>{% endif %}
{% if "password" in form.fields %}<div class="col-md-6">{% bootstrap_field form.password %}</div>{% endif %}
<div class="col-12">{% bootstrap_field form.details %}</div>
<div class="col-12">{% bootstrap_field form.tags %}
{# the tags shown, sent back to tell them from a change (TagsField); bootstrap_field leaves them out #}
{% for name in form.tags.initial %}<input type="hidden" name="{{ form.tags.html_initial_name }}" value="{{ name }}">{% endfor %}
</div>
</div>
{# open when one of them is set or refused #}
<details class="border-top pt-3"{% if form.migration_address.value or form.migration_address.errors or form.gstfsd_key.errors %} open{% endif %}>
<details class="border-top pt-3"{% if form.migration_address.value or form.migration_address.errors or form.migration_tls.value or form.gstfsd_key.errors %} open{% endif %}>
<summary>
<span class="fw-semibold">{% trans "Advanced" %}</span>
<span class="d-block small text-body-secondary text-break ms-3">
{% trans "Migration address" %}: {{ form.migration_address.value|default:_("the host name") }}
{% if form.migration_tls.value %}&middot; {% trans "migrations over TLS" %}{% endif %}
&middot; {% trans "gstfsd key" %}: {% if form.instance.gstfsd_key %}{% trans "stored" %}{% else %}{% trans "none" %}{% endif %}
</span>
</summary>
<div class="mt-3">
{% bootstrap_field form.migration_address %}
{% bootstrap_field form.migration_tls %}
{% bootstrap_field form.gstfsd_key %}
</div>
</details>
@ -47,3 +56,7 @@
</div>
</form>
{% endblock content %}
{% block script %}
<script src="{% static 'js/tom-select.complete.min.js' %}"></script>
<script src="{% static 'js/searchable_select.js' %}"></script>
{% endblock script %}

View file

@ -2,7 +2,7 @@
{% load bootstrap_icons %}
{# The host's sections. section: the one this page belongs to; detail: the page is an item of it (a pool, a network), not the section's own page #}
<nav class="host-nav" aria-label="{% trans "Host sections" %}">
<ol class="breadcrumb shadow-sm">
<ol class="breadcrumb flex-nowrap overflow-x-auto text-nowrap shadow-sm">
<li class="breadcrumb-item">
{% if section == "overview" and not detail %}<span class="fw-bold" aria-current="page">{% bs_icon 'laptop' %} {% trans "Overview" %}</span>
{% else %}<a href="{% url 'overview' compute.id %}"{% if section == "overview" %} class="fw-bold" aria-current="true"{% endif %}>{% bs_icon 'laptop' %} {% trans "Overview" %}</a>{% endif %}

View file

@ -7,87 +7,31 @@
{% block page_heading %}{{ compute.name }} - {% trans "Instances" %}{% endblock page_heading %}
{% block page_heading_extra %}
<a href="{% url 'instances:create_instance_select_type' compute.id %}"
class="btn btn-success mt-1 float-end" title="{% trans "New Instance" %}">
{% bs_icon 'plus-circle-fill' %}
</a>
<input id="filter" class="form-control w-auto" type="text" placeholder="{% trans 'Search' %}" aria-label="{% trans 'Search' %}">
{% if instances %}
{% include 'search_block.html' %}
<a href="{% url 'bulk_migrate' compute.id %}" class="btn btn-outline-primary">{% trans "Bulk migrate" %}</a>
{% endif %}
{% if compute.maintenance %}
{# a disabled button shows no title: its wrapper says why #}
<span class="d-inline-block" tabindex="0" title="{% blocktrans with compute=compute.name %}{{ compute }} is in maintenance: no new VM or migration comes to it{% endblocktrans %}">
<button type="button" class="btn btn-primary" disabled>{% bs_icon 'plus-lg' %} {% trans "New VM" %}</button>
</span>
{% else %}
<a href="{% url 'instances:create_instance_select_type' compute.id %}" class="btn btn-primary">{% bs_icon 'plus-lg' %} {% trans "New VM" %}</a>
{% endif %}
{% endblock page_heading_extra %}
{% block content %}
<div id="job-panel" aria-live="polite"></div>
<div class="row">
<div class="col-lg-12">
{% include "computes/host_nav.html" with section="instances" %}
{% include "computes/host_nav.html" with section="instances" %}
{% if compute.status is not True %}
<div class="alert alert-danger shadow-sm">
{% blocktrans with name=compute.name error=compute.connection_error %}Problem occurred with host {{ name }}: {{ error }}{% endblocktrans %}
</div>
</div>
<div class="row">
<div class="col-lg-12">
{% if compute.status is not True %}
<div class="alert alert-danger shadow-sm">
{% blocktrans with name=compute.name error=compute.connection_error %}Problem occurred with host {{ name }}: {{ error }}{% endblocktrans %}
</div>
{% endif %}
{% if not instances %}
{% if compute.status is True %}
<div class="alert alert-warning shadow-sm fade show">
{% bs_icon 'exclamation-triangle' %} <strong>{% trans "Warning" %}:</strong>
{% trans "Hypervisor doesn't have any Instances" %}
</div>
{% endif %}
{% else %}
<div class="table-responsive">
<table class="table table-hover align-middle" data-sortable>
<thead>
<tr>
<th scope="col">{% trans 'Name' %}<br>{% trans 'Description' %}</th>
<th scope="col">{% trans 'User' %}</th>
<th scope="col">{% trans 'Status' %}</th>
<th scope="col" data-sort-method="number">{% trans 'VCPU' %}</th>
<th scope="col" class="text-end" data-sort-method="number">{% trans 'Memory' %}</th>
<th scope="col" data-sort-method="none">{% trans 'Actions' %}</th>
</tr>
</thead>
<tbody class="searchable">
{% for instance in instances %}
<tr>
<td>
<a class="link-primary" href="{% url 'instances:instance' instance.id %}">{{ instance.name }}</a>
<br>
{% if instance.info %}<p class="m-0 small fst-italic">{{ instance.title }}</p>{% endif %}
</td>
<td>
<em>
{% if instance.userinstance_set.all.count > 0 %}
{{ instance.userinstance_set.all.0.user }}
{% if instance.userinstance_set.all.count > 1 %}
(+{{ instance.userinstance_set.all.count|add:"-1" }})
{% endif %}
{% endif %}
</em>
</td>
<td>
{% include 'instance_state.html' %}
</td>
<td data-sort="{{ instance.info.3 }}">{{ instance.info.3 }}</td>
<td data-sort="{{ instance.info.2 }}"><p class="text-end">{% if instance.info %}{% widthratio instance.info.2 1024 1 %} MiB{% endif %}</p></td>
<td class="text-nowrap">
{% include 'instance_actions.html' %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
</div>
</div>
{% endif %}
{% include 'instances/vm_list.html' %}
{% endblock %}
{% block script %}
<script src="{% static 'js/poll.js' %}"></script>
{% include 'instances/vm_list_scripts.html' %}
{% job_panel_script job_resource %}
{% include "instances/vm_states_poll.html" %}
<script src="{% static 'js/table_filter.js' %}"></script>
{% endblock %}
{% endblock %}

View file

@ -1,20 +1,21 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load static %}
{% load bootstrap_icons %}
{% load operations %}
{% block title %}{% trans "Computes" %}{% endblock %}
{% block page_heading %}{% trans "Computes" %}{% endblock page_heading %}
{% block page_heading_extra %}
<input id="filter" class="form-control w-auto" type="text" placeholder="{% trans 'Search' %}" aria-label="{% trans 'Search' %}">
{% if computes|length > 1 %}<a href="{% url 'balance' %}" class="btn btn-outline-primary">{% trans "Balance" %}</a>{% endif %}
{% include 'create_comp_block.html' %}
{% endblock page_heading_extra %}
{% block content %}
<div class="row">
<div class="col-lg-12">
{% include 'create_comp_block.html' %}
{% include 'search_block.html' %}
<h3 class="mb-3">{% trans "Computes" %}</h3>
</div>
</div>
<div id="job-panel" aria-live="polite"></div>
{% include "computes/attention.html" %}
{% if not computes %}
<div class="alert alert-warning shadow-sm">
{% bs_icon 'exclamation-triangle'%} <strong>{% trans "Warning" %}:</strong> {% trans "You don't have any computes" %}
</div>
<p class="text-center text-body-secondary py-4">{% trans "You don't have any computes" %}</p>
{% else %}
{# the totals of the hosts the panel reaches #}
<div class="row row-cols-2 row-cols-lg-4 g-3 mb-4">
@ -42,20 +43,21 @@
<div class="col">
<div class="card h-100"><div class="card-body">
<div class="small text-body-secondary">{% bs_icon 'memory' %} {% trans "Memory given" %}</div>
<div class="fs-4 lh-sm">{{ totals.assigned|filesizeformat }}</div>
<div class="small text-body-secondary">{% blocktrans with memory=totals.memory|filesizeformat %}of {{ memory }}{% endblocktrans %}</div>
<div class="fs-4 lh-sm">{{ totals.assigned|binary_size }}</div>
<div class="small text-body-secondary">{% blocktrans with memory=totals.memory|binary_size %}of {{ memory }}{% endblocktrans %}</div>
</div></div>
</div>
</div>
{% include 'common/tag_filter.html' %}
{# position-relative: the hidden status texts are positioned within it, not the page #}
<div class="table-responsive position-relative">
<table class="table table-hover align-middle" data-sortable>
<thead>
<tr>
<th scope="col">{% trans "Host" %}</th>
<th scope="col" data-sort-method="number">{% trans "VMs" %}</th>
<th scope="col" data-sort-method="number">{% trans "vCPUs" %}</th>
<th scope="col" class="d-none d-md-table-cell" data-sort-method="number">{% trans "VMs" %}</th>
<th scope="col" class="d-none d-md-table-cell" data-sort-method="number">{% trans "vCPUs" %}</th>
<th scope="col" data-sort-method="number">{% trans "Memory" %}</th>
<th scope="col" data-sort-method="none"><span class="visually-hidden">{% trans "Actions" %}</span></th>
</tr>
@ -63,7 +65,7 @@
<tbody class="searchable">
{% for compute in computes %}
{% with given=compute.shown_capacity %}
<tr{% if compute.status is not True %} class="table-warning"{% endif %}>
<tr data-tags="{% for tag in compute.tags.all %}{{ tag }}{% if not forloop.last %} {% endif %}{% endfor %}"{% if compute.status is not True %} class="table-warning"{% endif %}>
<td class="py-3">
<div class="d-flex flex-wrap align-items-center gap-2">
<a class="fw-semibold" href="{% url 'overview' compute.id %}">{{ compute.name }}</a>
@ -72,27 +74,32 @@
{% else %}
<span class="badge text-bg-danger">{% trans "Not connected" %}</span>
{% endif %}
{% if compute.maintenance %}{# ready once none of its VMs runs; while that is not known, only asked for #}
<span class="badge text-bg-warning">{% if compute.shown_capacity and not compute.shown_capacity.active %}{% trans "In maintenance" %}{% else %}{% trans "Maintenance requested" %}{% endif %}</span>{% endif %}
<span class="badge text-bg-light border">{{ compute.connection_name }}</span>
</div>
<div class="small text-body-secondary font-monospace mt-1">{{ compute.hostname }}</div>
{% if compute.details %}<div class="small text-body-secondary">{{ compute.details }}</div>{% endif %}
{% with tags=compute.tags.all %}{% if tags %}<div class="mt-1">{% include 'common/tag_badges.html' with tags=tags|slice:":3" more=tags|slice:"3:" filter=True %}</div>{% endif %}{% endwith %}
{% if compute.status is not True %}
<div class="small text-danger">{{ compute.connection_error }}</div>
{% endif %}
</td>
{% if given %}
<td class="py-3" data-sort="{{ given.vm_count }}">
<td class="py-3 d-none d-md-table-cell" data-sort="{{ given.vm_count }}">
<a class="fs-4 lh-sm text-decoration-none" href="{% url 'instances' compute.id %}">{{ given.vm_count }}</a>
<div class="small text-body-secondary">{% blocktrans with running=given.vms.running %}{{ running }} running{% endblocktrans %}</div>
</td>
<td class="py-3" data-sort="{{ given.ratio|stringformat:".2f" }}">
<td class="py-3 d-none d-md-table-cell" data-sort="{{ given.ratio|stringformat:".2f" }}">
{% include "computes/capacity_vcpus.html" %}
</td>
<td class="py-3" data-sort="{{ given.memory_percent }}">
{% include "computes/capacity_memory.html" %}
</td>
{% else %}
<td colspan="3" class="py-3 small text-body-secondary">{% if compute.status is True %}{% trans "The capacity could not be read." %}{% else %}{% trans "No capacity while the host cannot be reached." %}{% endif %}</td>
{# on a phone the VM and vCPU columns are hidden: the totals above have them #}
<td class="d-none d-md-table-cell"></td><td class="d-none d-md-table-cell"></td>
<td class="py-3 small text-body-secondary">{% if compute.status is True %}{% trans "The capacity could not be read." %}{% else %}{% trans "No capacity while the host cannot be reached." %}{% endif %}</td>
{% endif %}
<td class="py-3 text-end">
{# fixed: the menu would be cut off by the table's scrolling box #}
@ -114,9 +121,16 @@
</tbody>
</table>
</div>
{# table_filter.js shows it while no host matches #}
<div id="no-match" class="text-center text-body-secondary py-4" hidden>
{% trans "No host matches the filters." %}
<button type="button" class="btn btn-link" id="clear-filters">{% trans "Clear the filters" %}</button>
</div>
{% endif %}
{% endblock content %}
{% block script %}
<script src="{% static 'js/poll.js' %}"></script>
{% job_panel_script job_resource %}
<script src="{% static 'js/table_filter.js' %}"></script>
{% endblock script %}

View file

@ -1,8 +1,9 @@
{% load i18n %}
{% load common_tags %}
{# a pool's space; hide_name: the page names the pool next to it #}
{% if not hide_name %}<div class="small">{{ pool.name }}</div>{% endif %}
<div class="progress my-1" role="progressbar" style="--bs-progress-height: 0.3rem;"
aria-label="{% blocktrans with name=pool.name %}{{ name }} used{% endblocktrans %}" aria-valuenow="{{ pool.used_percent|floatformat:0 }}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar {% if pool.used_percent > 90 %}bg-danger{% elif pool.used_percent > 75 %}bg-warning{% endif %}" style="width: {{ pool.used_percent|stringformat:".1f" }}%"></div>
</div>
<div class="small text-body-secondary">{% blocktrans with free=pool.free|filesizeformat size=pool.size|filesizeformat %}{{ free }} free of {{ size }}{% endblocktrans %}</div>
<div class="small text-body-secondary">{% blocktrans with free=pool.free|binary_size size=pool.size|binary_size %}{{ free }} free of {{ size }}{% endblocktrans %}</div>

View file

@ -1,6 +1,6 @@
{% load i18n %}
{% load bootstrap_icons %}
<div class="dropdown float-end mt-1 ms-1">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
{% bs_icon 'plus-lg' %} {% trans "Add host" %}
</button>

View file

@ -1,11 +1,27 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load static %}
{% load bootstrap_icons %}
{% load operations %}
{% block title %}{% trans "Overview" %} - {{ compute.name }}{% endblock %}
{% block page_heading_extra %}
{% if compute.maintenance %}
<form method="post" action="{% url 'compute_maintenance' compute.id %}" class="d-inline">{% csrf_token %}
<input type="hidden" name="maintenance" value="off">
<button type="submit" class="btn btn-sm btn-warning"{% if bulk_running %} data-confirm="{% trans "Allow new VMs and migrations on the host again? Its bulk migration goes on." %}"{% endif %}>{% bs_icon 'wrench-adjustable' %} {% trans "End maintenance" %}</button>
</form>
{% elif given.active %}
{# its VMs are migrated with it: the Bulk Migrate page puts it in maintenance, with or without moving them #}
<a class="btn btn-sm btn-outline-secondary" href="{% url 'bulk_migrate' compute.id %}?maintenance=on">{% bs_icon 'wrench-adjustable' %} {% trans "Put in maintenance" %}</a>
{% else %}
<form method="post" action="{% url 'compute_maintenance' compute.id %}" class="d-inline">{% csrf_token %}
<input type="hidden" name="maintenance" value="on">
<button type="submit" class="btn btn-sm btn-outline-secondary" data-confirm="{% trans "Put the host in maintenance? No new VM or migration comes to it, its VMs cannot be started there, and Balance leaves it out." %}">{% bs_icon 'wrench-adjustable' %} {% trans "Put in maintenance" %}</button>
</form>
{% endif %}
<a class="btn btn-sm btn-outline-primary" href="{% url 'compute_update' compute.id %}">{% bs_icon 'pencil' %} {% trans "Edit connection" %}</a>
<a class="btn btn-sm btn-outline-danger" href="{% url 'compute_delete' compute.id %}">{% bs_icon 'x-circle' %} {% trans "Remove from panel" %}</a>
{% endblock page_heading_extra %}
@ -27,6 +43,35 @@
{% include "computes/host_nav.html" with section="overview" %}
{% if compute.maintenance %}
{# ready once none of its VMs runs: the state comes from its VMs, not from a job #}
<div class="alert alert-warning" role="status">
{% url 'bulk_migrate' compute.id as bulk_url %}
{% if not given %}
{% trans "Maintenance requested: the host cannot be read, so whether its VMs still run is not known." %}
{% elif given.active %}
{% blocktrans count counter=given.active %}Maintenance requested: {{ counter }} VM still runs on this host.{% plural %}Maintenance requested: {{ counter }} VMs still run on this host.{% endblocktrans %}
{% blocktrans %}<a href="{{ bulk_url }}">Bulk Migrate</a> moves them to the other hosts; shut down those that cannot move.{% endblocktrans %}
{% else %}
<span class="fw-semibold">{% trans "In maintenance: no VM runs on this host." %}</span>
{% endif %}
{% trans "No new VM or migration comes to it, its VMs cannot be started there, and Balance leaves it out." %}
{% if autostart %}
<div class="mt-2">{% blocktrans with vms=autostart|join:", " %}These VMs start by themselves when the host boots: {{ vms }}. Turn their autostart off before restarting the host.{% endblocktrans %}</div>
{% endif %}
{% if bulk and not given or bulk and given.active %}
<div class="mt-2 small">
{% url 'operations:job' bulk.pk as job_url %}
{% if bulk_running %}
{% blocktrans %}Its VMs are being migrated: <a href="{{ job_url }}">see the job</a>.{% endblocktrans %}
{% else %}
{% blocktrans with state=bulk.state|state_label when=bulk.created_at|date:"SHORT_DATETIME_FORMAT" %}Its last bulk migration, of {{ when }}: {{ state }}. <a href="{{ job_url }}">See the job</a>.{% endblocktrans %}
{% endif %}
</div>
{% endif %}
</div>
{% endif %}
{% if not connected %}
<div class="alert alert-warning" role="alert">
<div class="mb-2">{% trans "The panel cannot reach this host, so its VMs, capacity and load are not shown:" %} {{ compute.connection_error }}</div>
@ -148,7 +193,7 @@
</li>
<li class="list-group-item py-1 d-flex justify-content-between align-items-baseline gap-3">
<span class="text-body-secondary">{% trans "Memory" %}</span>
<span class="text-end text-break"><span class="fw-semibold">{{ host.memory|filesizeformat }}</span></span>
<span class="text-end text-break"><span class="fw-semibold">{{ host.memory|binary_size }}</span></span>
</li>
</ul>
</div>

View file

@ -0,0 +1,297 @@
"""The box above the Computes page's hosts: what wants a look, each with a link to where it is handled."""
import datetime
import threading
import time
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from django.contrib.auth import get_user_model
from libvirt import VIR_DOMAIN_XML_INACTIVE, VIR_ERR_NO_DOMAIN, libvirtError
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from lxml import html
from computes import views
from computes.models import Compute
from instances.models import Instance
from operations.models import Operation
from operations.utils import say
from vmbackups.models import Backup, BackupPolicy, BackupRun, BackupTarget
from vmbackups.schedule import IN_MAINTENANCE, NOT_STARTED
from vrtManager.hostdetails import wvmHostDetails
NOW = timezone.now()
class AttentionBoxTests(TestCase):
def setUp(self):
self.admin = get_user_model().objects.create_superuser("at-admin", "at@example.com", "pw")
self.client.force_login(self.admin)
self.up = Compute.objects.create(name="up", hostname="192.0.2.1", login="wvc", password="", type=1,
host_uuid="11111111-0000-0000-0000-000000000000")
self.down = Compute.objects.create(name="down", hostname="192.0.2.2", login="wvc", password="", type=1,
host_uuid="22222222-0000-0000-0000-000000000000")
self.vm = Instance.objects.create(compute=self.up, name="vm1", uuid="33333333-0000-4000-8000-000000000001")
self.addCleanup(lambda: [read.join(5) for read in views._reading.values()]) # none left for the next test
def read(self, compute):
return (False, "refused", None, "") if compute.name == "down" else (True, None, None, "")
def page(self, pools=(), snapshots=(), needs=None, read_needs=None, fresh=True):
with patch("computes.views._read_host", side_effect=self.read), patch(
"computes.views._read_attention", return_value={"pools": list(pools), "snapshots": list(snapshots)}), \
patch("computes.views._read_needs", side_effect=read_needs or (lambda compute: (needs or {}).get(compute.name))):
if fresh: # no read of what VMs need kept from another test
views._reading.clear()
return self.client.get(reverse("computes"))
def test_what_vms_need_is_read_on_each_load_the_last_standing_in_when_late(self):
self.down.delete()
Compute.objects.create(name="up2", hostname="192.0.2.3", login="wvc", password="", type=1,
host_uuid="44444444-0000-0000-0000-000000000000")
none = {"networks": [], "filters": [], "secrets": [], "usages": []}
lacking = {"up": {"uses": {**none, "networks": ["lab"]}, "has": {**none, "networks": ["lab"], "filters": {}}},
"up2": {"uses": none, "has": {**none, "filters": {}}}}
fixed = {**lacking, "up2": {"uses": none, "has": {**none, "networks": ["lab"], "filters": {}}}}
held = threading.Event()
self.addCleanup(held.set)
def settle(): # every read of the load ended: the next load starts its own
held.set()
for read in list(views._reading.values()):
read.join(5)
held.clear()
def text(**kwargs):
page = self.page(fresh=False, **kwargs)
settle()
return " ".join(html.fromstring(page.content).text_content().split())
def late(compute): # a read that outlasts the wait, then says the network is added
held.wait(5)
return fixed.get(compute.name)
self.page(needs=lacking)
settle()
self.assertNotIn("could not migrate", text(needs=fixed)) # the network added: told at the next load
# a host whose listing could not be read: the others still count
unread = {**lacking, "up2": {"uses": none, "has": {**none, "networks": None, "filters": {}, "secrets": None,
"usages": None}}}
self.assertNotIn("could not migrate", text(needs=unread))
secrets_unread = {**lacking, "up2": {"uses": none, "has": {**none, "filters": {}, "secrets": None, "usages": None}}}
self.assertIn("could not migrate here: no active network lab", text(needs=secrets_unread))
# a late read: the last stands in, waited for NEEDS_GRACE only, not ATTENTION_WAIT
self.assertIn("could not migrate", text(needs=lacking))
with patch("computes.views.NEEDS_GRACE", 0.1), patch("computes.views.ATTENTION_WAIT", 5):
began = time.monotonic()
page = self.page(fresh=False, read_needs=late)
self.assertLess(time.monotonic() - began, 2)
settle()
self.assertContains(page, "could not migrate")
# a host that stopped answering: its stand-in, with the warning, is not told, nor waited for
self.assertIn("could not migrate", text(needs=lacking))
with patch.object(self, "read", lambda compute: (False, "refused", None, "") if compute.name == "up2"
else (True, None, None, "")), patch("computes.views.NEEDS_GRACE", 5):
began = time.monotonic() # only the silent host's read is late: it would be waited 5 s
page = self.page(fresh=False, read_needs=lambda c: late(c) if c.name == "up2" else lacking.get(c.name))
self.assertLess(time.monotonic() - began, 2)
settle()
shown = " ".join(html.fromstring(page.content).text_content().split())
self.assertIn("up2: not answering", shown)
self.assertNotIn("could not migrate", shown)
# a read that failed leaves no stand-in: a late read after it tells no older warning
self.assertIn("could not migrate", text(needs=lacking))
text(needs={}) # this load's read fails (None)
with patch("computes.views.ATTENTION_WAIT", 0.1):
page = self.page(fresh=False, read_needs=late)
settle()
self.assertNotContains(page, "could not migrate")
def test_what_a_vm_could_not_find_on_another_host(self):
# a network, a filter or a secret its VMs use that another host lacks, or a filter of other rules there
self.down.delete()
up2 = Compute.objects.create(name="up2", hostname="192.0.2.3", login="wvc", password="", type=1,
host_uuid="44444444-0000-0000-0000-000000000000")
none = {"networks": [], "filters": [], "secrets": [], "usages": []}
needs = {"up": {"uses": {"networks": ["prod", "lab"], "filters": ["base", "web", "gone"], "secrets": ["s-1"],
"usages": [("ceph", "client.vm")]},
"has": {"networks": ["prod", "lab"], "secrets": ["s-1"], "usages": [("ceph", "client.vm")],
"filters": {"web": "<filter name='web'/>", "base": "<filter name='base'/>"}}},
"up2": {"uses": none,
"has": {"networks": ["prod"], "secrets": [], "usages": [],
"filters": {"web": "<filter name='web'><rule/></filter>", "gone": "<filter name='gone'/>"}}}}
text = " ".join(html.fromstring(self.page(needs=needs).content).text_content().split())
# "gone": up's VMs name it, up lacks it too: not another host's rules
self.assertIn("up2: VMs of up could not migrate here: no active network lab; no network filter base; network "
"filter web with other rules; no secret client.vm, s-1", text)
self.assertNotIn("VMs of up2", text) # what up2's VMs use, up has
Compute.objects.filter(pk=up2.pk).update(maintenance_since=timezone.now()) # no destination now
self.assertNotIn("could not migrate", " ".join(html.fromstring(self.page(needs=needs).content).text_content().split()))
def test_what_vms_need_is_read_apart_from_the_pools(self):
# its read failing or slow hides no full pool; it reads the host's migration_needs
page = self.page(pools=[{"name": "default", "percent": 91}], needs={})
self.assertContains(page, "91% full")
late = threading.Event()
with patch("computes.views.ATTENTION_WAIT", 0.2):
page = self.page(pools=[{"name": "default", "percent": 91}], read_needs=lambda compute: late.wait(5) and None)
late.set()
self.assertContains(page, "91% full")
compute = SimpleNamespace(status=True, proxy=MagicMock(**{"migration_needs.return_value": {"uses": {}}}))
self.assertEqual(views._read_needs(compute), {"uses": {}})
compute.proxy.migration_needs.side_effect = libvirtError("refused")
self.assertIsNone(views._read_needs(compute))
def test_nothing_to_look_at_shows_no_box(self):
self.down.delete()
self.assertNotContains(self.page(), "Needs attention")
def test_hosts_pools_and_snapshots(self):
page = self.page(pools=[{"name": "default", "percent": 91}], snapshots=[{"vm": "vm1", "count": 2}])
self.assertContains(page, "Needs attention")
self.assertContains(page, f'<a href="{reverse("overview", args=[self.down.pk])}">down</a>: not answering',
html=False)
self.assertContains(page, reverse("storage", args=[self.up.pk, "default"]))
self.assertContains(page, "91% full")
self.assertContains(page, reverse("instances:instance", args=[self.vm.pk]) + "#snapshots")
self.assertContains(page, "2 snapshots older than 30 days")
def test_snapshots_slow_to_list_do_not_hold_the_page(self):
slow = {"pools": [{"name": "default", "percent": 91}], "snapshots": []}
with patch("computes.views._read_host", side_effect=self.read), patch("computes.views.ATTENTION_WAIT", 0.2), patch(
"computes.views._read_attention", side_effect=lambda compute: time.sleep(1) or slow):
started = time.monotonic()
page = self.client.get(reverse("computes"))
took = time.monotonic() - started
self.assertLess(took, 0.9)
self.assertEqual({c.name: c.status for c in page.context["computes"]}, {"up": True, "down": False})
self.assertNotContains(page, "91% full") # left out this time
def test_backups_and_jobs(self):
target = BackupTarget.objects.create(name="t")
policy = BackupPolicy.objects.create(name="n", target=target, time=datetime.time(2), keep=1)
def backup(state, days_ago=0, **fields):
b = Backup.objects.create(target=target, instance=self.vm, vm_uuid=self.vm.uuid, vm_name="vm1",
compute_name="up", state=state, **fields)
Backup.objects.filter(pk=b.pk).update(created_at=NOW - datetime.timedelta(days=days_ago))
backup(Backup.MISSING, days_ago=40)
backup(Backup.READY, damage=say("x"))
today = timezone.localdate()
BackupRun.objects.create(policy=policy, instance=self.vm, day=today, state=BackupRun.SKIPPED, note=say(NOT_STARTED))
BackupRun.objects.create(policy=policy, instance=self.vm, day=today - datetime.timedelta(days=1),
state=BackupRun.SKIPPED, note=say(IN_MAINTENANCE)) # the operator's choice
Operation.objects.create(kind="backup.verify", user=self.admin, username="at-admin", submission_key="k1",
resource="r1", state=Operation.UNCERTAIN)
for key, days_ago in (("k4", 0), ("k5", 8)): # a backup job failed this week, one before
Operation.objects.create(kind="backup.create", user=self.admin, username="at-admin", submission_key=key,
resource=key, state=Operation.FAILED,
finished_at=NOW - datetime.timedelta(days=days_ago))
waiting = Operation.objects.create(kind="backup.verify", user=self.admin, username="at-admin",
submission_key="k2", resource="r2", state=Operation.QUEUED)
Operation.objects.filter(pk=waiting.pk).update(created_at=NOW - datetime.timedelta(hours=2))
Operation.objects.create(kind="backup.verify", user=self.admin, username="at-admin", submission_key="k3",
resource="r3", state=Operation.QUEUED) # just queued
self.down.delete()
page = self.page()
for text in ("1 backup failed in the last 7 days", "1 scheduled backup not taken in the last 7 days",
"1 backup missing from its target", "1 backup damaged", "1 job ended uncertain",
"1 job queued for over an hour"):
self.assertContains(page, text)
self.assertContains(page, reverse("operations:jobs") + "?kind=backup.create&amp;state=failed")
self.assertContains(page, f'<a href="{reverse("vmbackups:policy", args=[policy.pk])}">n</a>: 1 scheduled')
self.assertContains(page, reverse("vmbackups:index") + "?state=damaged")
self.assertContains(page, reverse("operations:jobs") + "?state=uncertain")
listed = self.client.get(reverse("vmbackups:index") + "?state=damaged")
self.assertEqual([b.state for b in listed.context["rows"]], [Backup.READY])
class HostAttentionTests(TestCase):
def test_full_pools_and_old_snapshots_of_the_host(self):
def pool(name, capacity, allocation):
return MagicMock(**{"name.return_value": name, "info.return_value": [2, capacity, allocation, 0]})
def snapshot(days_ago):
created = int((NOW - datetime.timedelta(days=days_ago)).timestamp())
return MagicMock(**{"getXMLDesc.return_value": f"<domainsnapshot><creationTime>{created}</creationTime>"
"</domainsnapshot>"})
def domain(name, *snapshots):
return MagicMock(**{"name.return_value": name, "listAllSnapshots.return_value": list(snapshots)})
host = wvmHostDetails.__new__(wvmHostDetails)
gone = MagicMock(**{"info.side_effect": libvirtError("undefined meanwhile")})
deleted = MagicMock(**{"getXMLDesc.side_effect": libvirtError("deleted meanwhile")})
host.wvm = SimpleNamespace(
listAllStoragePools=lambda flags: [pool("default", 100, 90), gone, pool("big", 100, 10), pool("empty", 0, 0)],
listAllDomains=lambda flags: [domain("old", snapshot(40), deleted, snapshot(31), snapshot(1)),
domain("new", snapshot(2))])
self.assertEqual(host.get_attention(85, NOW - datetime.timedelta(days=30)),
{"pools": [{"name": "default", "percent": 90}], "snapshots": [{"vm": "old", "count": 2}]})
def test_what_the_hosts_vms_need_of_another_host(self):
# its VMs' networks, filters (with those they reference) and secrets, of their running definition and the
# one for the next start; its active networks, filters and secrets
def domain(live, config=None):
xml = {0: live, VIR_DOMAIN_XML_INACTIVE: config or live}
return MagicMock(**{"XMLDesc.side_effect": lambda flags: xml[flags], "isPersistent.return_value": config is not None})
def nwfilter(name, rules, refs=()):
refs = "".join(f"<filterref filter='{ref}'/>" for ref in refs)
return MagicMock(**{"name.return_value": name,
"XMLDesc.return_value": f"<filter name='{name}'><uuid>u-{name}</uuid>{rules}{refs}</filter>"})
def nic(network, filterref=""):
return (f"<interface type='network'><source network='{network}'/>"
f"{f'<filterref filter={chr(39)}{filterref}{chr(39)}/>' if filterref else ''}</interface>")
host = wvmHostDetails.__new__(wvmHostDetails)
gone = MagicMock(**{"XMLDesc.side_effect": libvirtError("gone meanwhile")})
gone.XMLDesc.side_effect.get_error_code = lambda: VIR_ERR_NO_DOMAIN
secret = MagicMock(**{"UUIDString.return_value": "S-2", "XMLDesc.return_value":
"<secret><usage type='ceph'><name>client.other</name></usage></secret>"})
host.wvm = SimpleNamespace(
listAllDomains=lambda flags=0: [gone, domain(
f"<domain><devices>{nic('prod', 'web')}<disk><source><auth><secret type='ceph' uuid='S-1'/></auth>"
"</source></disk><disk><source><auth><secret type='ceph' usage='client.vm'/></auth></source></disk>"
"</devices></domain>",
f"<domain><devices>{nic('lab')}</devices></domain>")], # lab: at the next start
listAllNetworks=lambda flags=0: [MagicMock(**{"name.return_value": "prod"})] if flags else [],
listAllNWFilters=lambda flags=0: [nwfilter("web", "<rule/>", ["base"]), nwfilter("base", "<rule x='1'/>")],
listAllSecrets=lambda flags=0: [secret])
self.assertEqual(host.migration_needs(), {
"uses": {"networks": ["lab", "prod"], "filters": ["base", "web"], "secrets": ["s-1"],
"usages": [("ceph", "client.vm")]},
"has": {"networks": ["prod"], "secrets": ["s-2"], "usages": [("ceph", "client.other")],
"filters": {"web": "<filter name=\"web\"><rule/><filterref filter=\"base\"/></filter>",
"base": "<filter name=\"base\"><rule x=\"1\"/></filter>"}}})
def test_a_listing_that_cannot_be_read_is_none_and_the_others_count(self):
host = wvmHostDetails.__new__(wvmHostDetails)
refused = MagicMock(side_effect=libvirtError("secrets driver down"))
host.wvm = SimpleNamespace(listAllDomains=lambda flags=0: [], listAllNWFilters=lambda flags=0: [],
listAllSecrets=refused,
listAllNetworks=lambda flags=0: [MagicMock(**{"name.return_value": "prod"})])
has = host.migration_needs()["has"]
self.assertEqual((has["networks"], has["filters"], has["secrets"], has["usages"]), (["prod"], {}, None, None))
def test_a_host_whose_vms_cannot_be_listed_is_still_a_destination(self):
host = wvmHostDetails.__new__(wvmHostDetails)
host.wvm = SimpleNamespace(listAllDomains=MagicMock(side_effect=libvirtError("refused")),
listAllNWFilters=lambda flags=0: [], listAllSecrets=lambda flags=0: [],
listAllNetworks=lambda flags=0: [MagicMock(**{"name.return_value": "prod"})])
needs = host.migration_needs()
self.assertIsNone(needs["uses"])
self.assertEqual(needs["has"]["networks"], ["prod"])
none = {"networks": [], "filters": [], "secrets": [], "usages": []}
source = MagicMock(status=True, maintenance=False, needs={"uses": {**none, "networks": ["lab"]},
"has": {**none, "filters": {}}})
target = MagicMock(status=True, maintenance=False, needs=needs)
self.assertEqual([(t, s) for t, s, _what in views.lacking([source, target])], [(target, source)])

View file

@ -0,0 +1,250 @@
"""Balance proposes migrations of running VMs that even out the share of
their memory, then of their CPUs, the hosts give their running VMs, and runs
the proposal shown in one job of migrate jobs that take only a running VM."""
from unittest.mock import patch
import libvirt
from computes.balance import propose, spread
from computes.jobs import Balance
from computes.models import Compute
from django.utils import timezone
from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase
from django.urls import reverse
from instances.models import Instance
from lxml import html
from operations import claims, jobs
from operations.models import Operation
DOMAIN = """<domain type='test'><name>{name}</name><memory unit='MiB'>128</memory><vcpu>1</vcpu>
<os><type arch='i686'>hvm</type></os>{disk}</domain>"""
LOCAL = "<devices><disk type='file' device='disk'><source file='/local/{name}.img'/><target dev='vda'/></disk></devices>"
ROOM = {"a": 100, "b": 100, "c": 100, "d": 100}
SIZES = {host: (64, 16) for host in "abcd"} # hosts of one size
class ProposeTests(SimpleTestCase):
def test_moves_even_out_the_memory_also_past_a_plateau_of_the_spread(self):
# the largest minus the smallest load stays 10 after the first move; the sum of squares does not
loads = {"a": (10, 0), "b": (10, 0), "c": (0, 0), "d": (0, 0)}
vms = [(1, "a", 5, 0, {"b", "c", "d"}), (2, "a", 5, 0, {"b", "c", "d"}),
(3, "b", 5, 0, {"a", "c", "d"}), (4, "b", 5, 0, {"a", "c", "d"})]
moves, after = propose(loads, vms, ROOM, SIZES)
self.assertEqual(len(moves), 2)
self.assertEqual(sorted(load[0] for load in after.values()), [5, 5, 5, 5])
def test_the_memory_comes_first_then_the_vcpus(self):
loads = {"a": (8, 2), "b": (0, 6)}
vms = [(1, "a", 4, 1, {"b"}), (2, "b", 0, 3, {"a"})]
moves, after = propose(loads, vms, ROOM, SIZES)
self.assertEqual(moves, [(1, "a", "b"), (2, "b", "a")])
self.assertEqual(after, {"a": [4, 4], "b": [4, 4]})
def test_a_vm_moves_once_and_only_where_it_may_go(self):
loads = {"a": (12, 0), "b": (0, 0), "c": (0, 0)}
moves, _after = propose(loads, [(1, "a", 6, 0, {"b"}), (2, "a", 6, 0, {"b"})], ROOM, SIZES)
self.assertEqual(moves, [(1, "a", "b")])
def test_no_move_fills_a_host_past_its_room(self):
loads = {"a": (60, 0), "b": (50, 0)}
self.assertEqual(propose(loads, [(1, "a", 30, 0, {"b"})], {"a": 40, "b": 20}, SIZES), ([], {"a": [60, 0], "b": [50, 0]}))
def test_a_vm_moved_away_makes_no_room_for_one_moved_in(self):
# b's room stays 0 after vm 2 leaves it: vm 1 would fill b before vm 2 has left, if it ran first
loads = {"a": (100, 0), "b": (80, 0), "c": (0, 0)}
vms = [(1, "a", 30, 0, {"b"}), (2, "b", 40, 0, {"c"})]
self.assertEqual(propose(loads, vms, {"a": 0, "b": 0, "c": 100}, SIZES)[0], [(2, "b", "c")])
def test_small_vms_move_rather_than_a_large_one_for_the_same_balance(self):
# a: a large VM (16) and two small ones (1, 2); b: one small VM (1). Moving the large VM to b and
# the small one back ends as even as moving the two small ones, which moves far less memory
loads = {"a": (19, 7), "b": (1, 4)}
vms = [(1, "a", 16, 2, {"b"}), (2, "a", 1, 1, {"b"}), (3, "a", 2, 4, {"b"}), (4, "b", 1, 4, {"a"})]
moves, after = propose(loads, vms, ROOM, SIZES)
self.assertEqual(moves, [(2, "a", "b"), (3, "a", "b")])
self.assertEqual(after, {"a": [16, 2], "b": [4, 9]})
def test_a_large_vm_moves_when_only_it_evens_out_the_hosts(self):
loads = {"a": (20, 0), "b": (0, 0)}
vms = [(1, "a", 10, 0, {"b"}), (2, "a", 1, 0, {"b"})]
self.assertEqual(propose(loads, vms, {"a": 100, "b": 100}, SIZES)[0], [(1, "a", "b")])
def test_even_hosts_need_no_move(self):
loads = {"a": (4, 2), "b": (4, 2)}
self.assertEqual(propose(loads, [(1, "a", 4, 2, {"b"})], ROOM, SIZES)[0], [])
def test_a_host_twice_as_large_takes_twice_the_memory(self):
loads = {"a": (12, 0), "b": (0, 0)}
vms = [(n, "a", 2, 0, {"b"}) for n in range(1, 7)]
moves, after = propose(loads, vms, ROOM, {"a": (32, 8), "b": (64, 8)})
self.assertEqual(len(moves), 4)
self.assertEqual(after, {"a": [4, 0], "b": [8, 0]})
def test_the_vcpus_count_against_the_cpus_of_each_host(self):
loads = {"a": (0, 6), "b": (0, 0)}
_moves, after = propose(loads, [(n, "a", 0, 1, {"b"}) for n in range(1, 7)], ROOM, {"a": (64, 4), "b": (64, 8)})
self.assertEqual(after, {"a": [0, 2], "b": [0, 4]})
class SpreadTests(SimpleTestCase):
def test_the_largest_vm_goes_first_each_to_the_emptiest_host(self):
loads = {"b": (4, 0), "c": (0, 0)}
vms = [(1, 2, 1, True, {"b", "c"}), (2, 6, 1, True, {"b", "c"}), (3, 3, 1, False, {"b", "c"})]
placed, after = spread(loads, vms, ROOM, SIZES)
self.assertEqual(placed, {2: "c", 3: "b", 1: "c"})
self.assertEqual(after, {"b": [7, 1], "c": [8, 2]})
def test_a_running_vm_goes_only_where_it_fits_and_a_shut_off_one_anywhere(self):
loads = {"b": (0, 0)}
placed, _after = spread(loads, [(1, 8, 1, True, {"b"}), (2, 8, 1, False, {"b"})], {"b": 4}, SIZES)
self.assertEqual(placed, {2: "b"})
def test_the_larger_host_takes_more(self):
loads = {"b": (0, 0), "c": (0, 0)}
vms = [(n, 2, 0, False, {"b", "c"}) for n in range(1, 7)]
_placed, after = spread(loads, vms, ROOM, {"b": (32, 8), "c": (64, 8)})
self.assertEqual(after, {"b": [4, 0], "c": [8, 0]})
class BalancePageTests(TestCase):
def setUp(self):
self.conn = libvirt.open("test:///default")
self.addCleanup(self.conn.close)
self.compute = Compute.objects.create(name="ba", hostname="localhost", login="", password="", type=4)
self.other = Compute.objects.create(name="ba-other", hostname="198.51.100.41", login="", password="", type=4)
self.vms = {}
for name, running, disk in (("ba-1", True, ""), ("ba-2", True, ""), ("ba-off", False, ""),
("ba-local", True, LOCAL)):
domain = self.conn.defineXML(DOMAIN.format(name=name, disk=disk.format(name=name)))
self.addCleanup(domain.undefine)
if running:
domain.create()
self.addCleanup(domain.destroy)
self.vms[name] = Instance.objects.create(compute=self.compute, name=name, uuid=domain.UUIDString())
self.client.force_login(get_user_model().objects.create_superuser("ba-admin", "ba@example.com", "pw"))
def page(self, **query):
with patch("vrtManager.connection.connection_manager.get_connection", return_value=self.conn), \
patch("computes.views.utils.refresh_instance_database"), \
patch("instances.jobs.migration_target"), \
patch("computes.reach.wvmInstances") as dest:
dest.return_value.shares.side_effect = lambda conn, directory: directory != "/local"
self.response = self.client.get(reverse("balance"), query)
return html.fromstring(self.response.content)
def moved(self, page):
return page.xpath("//form[@method='post']//input[@name='instance']/@value")
def test_a_running_vm_moves_to_the_emptier_host(self):
page = self.page()
self.assertEqual(self.moved(page), [str(self.vms["ba-1"].pk)])
self.assertEqual(page.xpath("//form[@method='post']//input[@name='target']/@value"), [str(self.other.pk)])
def test_a_vm_unticked_stays_and_another_moves_instead(self):
pk = str(self.vms["ba-1"].pk)
page = self.page(shown=pk)
self.assertEqual(self.moved(page), [str(self.vms["ba-2"].pk)])
(box,) = page.xpath("//input[@name='vm'][@value=$pk]", pk=pk)
self.assertIsNone(box.get("checked")) # listed to tick again
self.assertEqual(self.moved(self.page(shown=pk, vm=pk)), [pk])
def test_a_vm_with_a_disk_the_hosts_do_not_share_cannot_move_and_still_counts(self):
page = self.page()
(row,) = [row for row in page.xpath("//tr") if "ba-local" in row.text_content()]
self.assertIn("not on storage both hosts share", row.text_content())
host = next(host for host in self.response.context["hosts"] if host == self.compute)
self.assertEqual(host.before, [3 * 128 * 1024, 3]) # the shut-off VM is not counted
self.assertNotIn(str(self.vms["ba-off"].pk), page.xpath("//input[@name='vm' or @name='instance']/@value"))
def test_a_host_that_does_not_answer_is_left_out(self):
def read_hosts(computes):
for compute in computes:
compute.status, compute.shown_capacity = (False, None) if compute == self.other else (True, compute.capacity)
with patch("computes.views.read_hosts", side_effect=read_hosts):
page = self.page()
self.assertEqual(self.moved(page), [])
self.assertIn("ba-other", page.xpath("//div[contains(@class, 'alert-warning')]")[0].text_content())
def test_a_host_in_maintenance_is_left_out(self):
Compute.objects.filter(pk=self.other.pk).update(maintenance_since=timezone.now())
page = self.page()
self.assertEqual(self.moved(page), [])
self.assertEqual(list(self.response.context["hosts"]), [self.compute])
self.assertIn("in maintenance and are left out: ba-other", page.xpath("//div[contains(@class, 'alert-secondary')]")[0].text_content())
self.assertEqual(page.xpath("//div[contains(@class, 'alert-warning')]"), []) # not said to be unreadable
def test_the_moves_shown_go_in_one_balance_job(self):
vm = self.vms["ba-1"].pk
response = self.client.post(reverse("balance"), {"instance": [vm], "source": [self.compute.pk],
"target": [self.other.pk], "parallel": "1",
"submission_key": "bal00000key"})
self.assertRedirects(response, reverse("computes"), fetch_redirect_response=False)
(op,) = Operation.objects.all()
self.assertEqual((op.kind, op.params, op.resource),
("host.balance", {"parallel": 1, "moves": [[vm, self.compute.pk, self.other.pk]]},
claims.bulk_migrate_key()))
class Ctx:
"""The job context run uses, without a worker."""
def __init__(self, op):
self.op = op
def record_intent(self, **values):
self.op.intent = {**self.op.intent, **values}
def set_phase(self, text):
pass
class BalanceJobTests(TestCase):
def setUp(self):
self.hosts = [Compute.objects.create(name=f"bj-{n}", hostname=f"192.0.2.5{n}", login="", password="", type=4)
for n in range(3)]
self.vms = [Instance.objects.create(compute=self.hosts[0], name=f"bj-{n}",
uuid=f"00000000-0000-4000-8000-00000000010{n}") for n in range(2)]
self.admin = get_user_model().objects.create_superuser("bj-admin", "bj@example.com", "pw")
patcher = patch("instances.jobs.MigrateInstance.validate") # the hosts are not asked
patcher.start()
self.addCleanup(patcher.stop)
self.moves = [[self.vms[0].pk, self.hosts[0].pk, self.hosts[1].pk],
[self.vms[1].pk, self.hosts[0].pk, self.hosts[2].pk]]
def test_each_vm_migrates_to_its_own_host_and_only_while_running(self):
params = {"parallel": 2, "moves": self.moves}
op = Operation.objects.create(kind="host.balance", user=self.admin, username=self.admin.username,
submission_key="key-bal00001", params=params,
intent=Balance().plan(self.admin, params).intent)
def ends(seconds):
Operation.objects.filter(kind="instance.migrate").update(state=Operation.SUCCEEDED)
with patch("computes.jobs.time.sleep", side_effect=ends):
self.assertEqual(Balance().run(op, Ctx(op)), {})
children = Operation.objects.filter(kind="instance.migrate", parent=op)
self.assertEqual(sorted([job.params["instance"], job.params["source"], job.params["target"]] for job in children),
self.moves)
self.assertTrue(all(job.params["running_only"] for job in children))
self.assertEqual(Balance().progress(op), (2, 2))
def test_the_computes_page_shows_the_balance_and_the_hosts_pages_not_its_migrations(self):
balance = jobs.submit("host.balance", self.admin, {"parallel": 1, "moves": self.moves[:1]}, "key-bal00002")
child = jobs.submit("instance.migrate", self.admin, {"instance": self.vms[0].pk, "target": self.hosts[1].pk},
"key-mig00010", parent=balance)
self.client.force_login(self.admin)
def shown(key):
return [job["id"] for job in self.client.get(reverse("operation-resource"), {"key": key}).json()["jobs"]]
self.assertEqual(shown(claims.bulk_migrate_key()), [str(balance.pk)])
self.assertEqual(shown(claims.compute_key(self.hosts[0].pk)), [])
self.assertEqual(shown(claims.instance_key(self.vms[0].uuid)), [str(child.pk)])
def test_a_move_to_the_vms_own_host_is_refused(self):
raw = {"parallel": 1, "moves": [[self.vms[0].pk, self.hosts[0].pk, self.hosts[0].pk]]}
with self.assertRaisesRegex(Exception, "already on its destination"):
jobs.submit("host.balance", self.admin, raw, "key-bal00003")

View file

@ -0,0 +1,48 @@
"""The Balance page's script (static/js/balance.js): a ticked or unticked VM
makes the proposal again; the header box ticks or unticks every VM listed
first."""
import json
import shutil
import subprocess
import unittest
from pathlib import Path
SCRIPT = Path(__file__).resolve().parents[2] / "static" / "js" / "balance.js"
RUN = """
const vm = require("vm");
const boxes = [{name: "vm", id: "moves", checked: true}, {name: "vm", id: "stays", checked: false}];
let handler, submitted = 0;
const form = {elements: boxes, submit: () => { submitted += 1; }};
const other = {elements: [], submit: () => { throw new Error("another form"); }};
vm.runInNewContext(SCRIPT, vm.createContext({document: {
getElementById: () => form,
addEventListener: (name, fn) => { handler = fn; },
}}));
const seen = [];
for (const [id, checked, owner] of STEPS) {
handler({target: {id, checked, form: owner === "other" ? other : form}});
seen.push(boxes.filter((b) => b.checked).map((b) => b.id));
}
console.log(JSON.stringify({seen, submitted}));
"""
@unittest.skipUnless(shutil.which("node"), "node is not installed")
class BalanceScriptTests(unittest.TestCase):
def run_script(self, steps):
"""{seen: the ticked VMs after each step, submitted: the form's reloads}."""
code = f"const SCRIPT = {json.dumps(SCRIPT.read_text())};" + RUN.replace("STEPS", json.dumps(steps))
out = subprocess.run(["node", "-e", code], capture_output=True, text=True, check=True, timeout=30)
return json.loads(out.stdout)
def test_a_vm_box_makes_the_proposal_again(self):
self.assertEqual(self.run_script([["balance-7", False]]), {"seen": [["moves"]], "submitted": 1})
def test_a_change_outside_the_proposal_does_not_reload_it(self):
self.assertEqual(self.run_script([["balance-parallel", True, "other"]])["submitted"], 0)
def test_select_all_ticks_or_unticks_every_vm_and_makes_the_proposal_again(self):
result = self.run_script([["balance-all", True], ["balance-all", False]])
self.assertEqual(result, {"seen": [["moves", "stays"], []], "submitted": 2})

View file

@ -0,0 +1,297 @@
"""Bulk migrating a host migrates its chosen VMs in one job, a migrate job each,
the chosen number at once; the page ticks the running VMs, leaves the
shut-off ones to choose and refuses a VM with a disk the two hosts do not
share. Migrations share the hosts, so the job's migrations are admitted
together; a create still waits for them."""
from unittest.mock import patch
import libvirt
from computes.models import Compute
from django.utils import timezone
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from instances.models import Instance
from lxml import html
from appsettings.models import AppSettings
from computes.jobs import BulkMigrate
from operations import claims, jobs
from operations.models import Claim, Operation
from vrtManager import util
DOMAIN = """<domain type='test'><name>{name}</name><memory unit='MiB'>128</memory><vcpu>1</vcpu>
<os><type arch='i686'>hvm</type></os>{disk}</domain>"""
LOCAL = "<devices><disk type='file' device='disk'><source file='/local/{name}.img'/><target dev='vda'/></disk></devices>"
class BulkMigratePageTests(TestCase):
def setUp(self):
self.conn = libvirt.open("test:///default")
self.addCleanup(self.conn.close)
self.compute = Compute.objects.create(name="ev", hostname="localhost", login="", password="", type=4)
self.other = Compute.objects.create(name="ev-other", hostname="198.51.100.31", login="", password="", type=4)
self.vms = {}
for name, running, disk in (("ev-run", True, ""), ("ev-off", False, ""), ("ev-local", True, LOCAL)):
domain = self.conn.defineXML(DOMAIN.format(name=name, disk=disk.format(name=name)))
self.addCleanup(domain.undefine)
if running:
domain.create()
self.addCleanup(domain.destroy)
self.vms[name] = Instance.objects.create(compute=self.compute, name=name, uuid=domain.UUIDString())
self.client.force_login(get_user_model().objects.create_superuser("ev-admin", "ev@example.com", "pw"))
def page(self, **query):
with patch("vrtManager.connection.connection_manager.get_connection", return_value=self.conn), \
patch("computes.views.utils.refresh_instance_database"), \
patch("instances.jobs.migration_target"), \
patch("computes.reach.wvmInstances") as dest:
dest.return_value.shares.side_effect = lambda conn, directory: directory != "/local"
response = self.client.get(reverse("bulk_migrate", args=[self.compute.id]), query)
return html.fromstring(response.content)
def box(self, page, name):
(box,) = page.xpath("//input[@name='instance'][@value=$pk]", pk=str(self.vms[name].pk))
return box
def test_running_vms_are_ticked_and_shut_off_ones_left_to_choose(self):
page = self.page()
self.assertIsNotNone(self.box(page, "ev-run").get("checked"))
off = self.box(page, "ev-off")
self.assertIsNone(off.get("checked"))
self.assertIsNotNone(off.get("data-shut-off"))
def test_the_vms_tags_choose_them(self):
from computes.models import Tag
self.vms["ev-run"].tags.add(Tag.objects.create(name="prod"), Tag.objects.create(name="web"))
page = self.page()
self.assertEqual(page.xpath("//select[@id='bulk-migrate-tag']/option/@value"), ["", "prod", "web"])
self.assertEqual(self.box(page, "ev-run").get("data-tags"), "prod web")
self.assertEqual(self.box(page, "ev-off").get("data-tags"), "")
def test_a_vm_with_a_disk_the_hosts_do_not_share_is_refused(self):
page = self.page()
local = self.box(page, "ev-local")
self.assertIsNotNone(local.get("disabled"))
self.assertIn("not on storage both hosts share", local.getparent().getparent().text_content())
def test_a_host_in_maintenance_is_no_destination(self):
Compute.objects.create(name="ev-rest", hostname="198.51.100.32", login="", password="", type=4, maintenance_since=timezone.now())
page = self.page()
self.assertEqual(page.xpath("//select[@id='bulk-migrate-target']"), []) # one destination left: no choice
self.assertNotIn("ev-rest", page.text_content())
def bulk_migrate(self, target, chosen):
return self.client.post(reverse("bulk_migrate", args=[self.compute.id]),
{"target": target, "instance": chosen, "parallel": "2", "submission_key": "evac0000key"})
def test_the_chosen_vms_go_in_one_bulk_migration_job(self):
chosen = [self.vms["ev-run"].pk, self.vms["ev-off"].pk]
response = self.bulk_migrate(self.other.pk, chosen)
self.assertRedirects(response, reverse("instances", args=[self.compute.id]), fetch_redirect_response=False)
(op,) = Operation.objects.all()
self.assertEqual((op.kind, op.params), ("host.bulk_migrate", {
"compute": self.compute.pk, "parallel": 2, "moves": [[pk, self.other.pk] for pk in sorted(chosen)],
"maintenance": False}))
def test_a_destination_gone_since_the_form_was_shown_is_refused(self):
gone = self.other.pk
self.other.delete()
self.assertEqual(self.bulk_migrate(gone, [self.vms["ev-run"].pk]).status_code, 404)
self.assertFalse(Operation.objects.exists())
def test_one_destination_is_named_and_several_are_a_choice(self):
self.assertEqual(self.page().xpath("//select[@name='target']"), [])
self.assertIn("ev-other", self.page().xpath("//div[contains(@class, 'card-header')]/span/text()"))
Compute.objects.create(name="ev-third", hostname="198.51.100.32", login="", password="", type=4)
self.assertEqual(self.page().xpath("//select[@name='target']/option/text()"),
["Spread over the other hosts", "ev-other", "ev-third"])
def spread(self, page):
"""{VM name: the host it goes to} of the migrations the page would run."""
names = {str(vm.pk): name for name, vm in self.vms.items()}
hosts = {str(host.pk): host.name for host in Compute.objects.all()}
(form,) = page.xpath("//form[contains(@class, 'card')]")
return {names[vm]: hosts[target] for vm, target in zip(form.xpath(".//input[@name='instance']/@value"),
form.xpath(".//input[@name='target']/@value"))}
def test_with_several_hosts_the_vms_spread_over_them(self):
Compute.objects.create(name="ev-third", hostname="198.51.100.32", login="", password="", type=4)
self.assertEqual(self.spread(self.page()), {"ev-run": "ev-other"})
both = [self.vms["ev-run"].pk, self.vms["ev-off"].pk]
# a shut-off VM ticked goes too, to the host the running one left emptier
self.assertEqual(self.spread(self.page(shown=both, vm=both)), {"ev-run": "ev-other", "ev-off": "ev-third"})
# one unticked stays
self.assertEqual(self.spread(self.page(shown=both, vm=both[1:])), {"ev-off": "ev-other"})
def test_the_vms_spread_also_when_this_hosts_capacity_cannot_be_read(self):
Compute.objects.create(name="ev-third", hostname="198.51.100.32", login="", password="", type=4)
real = Compute.capacity.func
def capacity(host):
return None if host.pk == self.compute.pk else real(host)
with patch.object(Compute, "capacity", property(capacity)):
self.assertEqual(self.spread(self.page()), {"ev-run": "ev-other"})
def test_spread_vms_go_in_one_bulk_migration_job_with_their_hosts(self):
third = Compute.objects.create(name="ev-third", hostname="198.51.100.32", login="", password="", type=4)
run, off = self.vms["ev-run"].pk, self.vms["ev-off"].pk
response = self.client.post(reverse("bulk_migrate", args=[self.compute.id]),
{"spread": "1", "instance": [run, off], "target": [self.other.pk, third.pk],
"parallel": "2", "submission_key": "evac0000spr"})
self.assertRedirects(response, reverse("instances", args=[self.compute.id]), fetch_redirect_response=False)
(op,) = Operation.objects.all()
self.assertEqual(op.params["moves"], sorted([[run, self.other.pk], [off, third.pk]]))
self.assertEqual(op.resource_label, "ev -> ev-other, ev-third")
def test_a_host_with_no_other_host_says_so(self):
self.other.delete()
self.assertIn("There is no other host to migrate to.", self.page().text_content())
class Ctx:
"""The job context run uses, without a worker."""
def __init__(self, op):
self.op = op
def record_intent(self, **values):
self.op.intent = {**self.op.intent, **values}
def set_phase(self, text):
pass
class BulkMigrateJobTests(TestCase):
def setUp(self):
self.compute = Compute.objects.create(name="ej", hostname="192.0.2.40", login="", password="", type=4)
self.other = Compute.objects.create(name="ej-other", hostname="192.0.2.41", login="", password="", type=4)
self.vms = [Instance.objects.create(compute=self.compute, name=f"ej-{n}", uuid=f"00000000-0000-4000-8000-00000000000{n}")
for n in range(3)]
self.admin = get_user_model().objects.create_superuser("ej-admin", "ej@example.com", "pw")
patcher = patch("instances.jobs.MigrateInstance.validate") # the hosts are not asked
patcher.start()
self.addCleanup(patcher.stop)
def run_job(self, parallel, ends):
"""Runs the bulk migration of every VM; each round, ends(job) gives the end state of a running migration."""
params = {"compute": self.compute.pk, "parallel": parallel, "moves": [[vm.pk, self.other.pk] for vm in self.vms]}
op = Operation.objects.create(kind="host.bulk_migrate", user=self.admin, username=self.admin.username,
submission_key="key-evac0001", params=params,
intent=BulkMigrate().plan(self.admin, params).intent)
most = []
def round_ends(seconds):
running = Operation.objects.filter(kind="instance.migrate", state__in=Operation.ACTIVE)
most.append(running.count())
for job in running:
job.state = ends(job)
job.save()
self.op = op
with patch("computes.jobs.time.sleep", side_effect=round_ends):
try:
return BulkMigrate().run(op, Ctx(op)), max(most)
finally:
self.migrations = Operation.objects.filter(kind="instance.migrate")
def test_the_migrations_run_the_chosen_number_at_once(self):
result, most = self.run_job(2, lambda job: Operation.SUCCEEDED)
self.assertEqual((result, most), ({}, 2))
self.assertEqual(sorted(job.params["instance"] for job in self.migrations), [vm.pk for vm in self.vms])
def test_the_vms_that_did_not_migrate_are_named(self):
fail = self.vms[1].pk
with self.assertRaisesRegex(util.OperationError, "did not migrate"):
self.run_job(1, lambda job: Operation.FAILED if job.params["instance"] == fail else Operation.SUCCEEDED)
self.assertEqual(self.migrations.count(), 3)
# the worker hands a failed job that made changes to recovery: it adds no "stopped" message
outcome = BulkMigrate().reconcile(self.op)
self.assertEqual((outcome.state, outcome.error), (Operation.FAILED, []))
def test_a_bulk_migration_the_worker_left_says_it_stopped(self):
op = Operation(kind="host.bulk_migrate", intent={"migrations": {}})
self.assertIn("stopped", BulkMigrate().reconcile(op).error[0]["text"])
def test_a_create_waits_for_the_migrations(self):
Operation.objects.all().delete()
jobs.submit("instance.migrate", self.admin, {"instance": self.vms[0].pk, "target": self.other.pk}, "key-mig00001")
jobs.submit("instance.migrate", self.admin, {"instance": self.vms[1].pk, "target": self.other.pk}, "key-mig00002")
with self.assertRaises(claims.Busy):
claims.admit({claims.reconcile_key(self.compute.pk): Claim.EXCLUSIVE}, holder="test")
def test_a_vm_that_left_the_host_meanwhile_stays_where_it_went(self):
third = Compute.objects.create(name="ej-third", hostname="192.0.2.42", login="", password="", type=4)
left = self.vms[2]
def ends(job): # while the first migrations run, the last VM is moved to a third host
Instance.objects.filter(pk=left.pk).update(compute=third)
return Operation.SUCCEEDED
self.run_job(1, ends)
self.assertNotIn(left.pk, [job.params["instance"] for job in self.migrations])
def test_one_bulk_migration_runs_at_a_time(self):
raw = {"compute": self.compute.pk, "parallel": 1, "moves": [[self.vms[0].pk, self.other.pk]]}
jobs.submit("host.bulk_migrate", self.admin, raw, "key-evac0002")
with self.assertRaises(claims.Busy):
jobs.submit("host.bulk_migrate", self.admin,
{**raw, "compute": self.other.pk, "moves": [[self.vms[0].pk, self.compute.pk]]}, "key-evac0003")
def test_a_host_changed_meanwhile_stops_the_bulk_migration(self):
def ends(job):
Compute.objects.filter(pk=self.other.pk).update(hostname="192.0.2.99")
return Operation.SUCCEEDED
with self.assertRaisesRegex(util.OperationError, "changed or deleted"):
self.run_job(1, ends)
self.assertEqual(self.migrations.count(), 1)
def test_a_worker_lowered_to_one_slot_stops_the_bulk_migration(self):
def ends(job):
AppSettings.objects.filter(key="WORKER_CONCURRENCY").update(value="1")
return Operation.SUCCEEDED
with self.assertRaisesRegex(util.OperationError, "one job at a time"):
self.run_job(1, ends)
self.assertEqual(self.migrations.count(), 1)
def test_a_busy_vm_lets_the_others_go_first(self):
held = claims.admit({claims.instance_key(self.vms[0].uuid): Claim.EXCLUSIVE}, holder=claims.holder_id())
def ends(job):
Claim.objects.filter(pk__in=held).delete() # the short operation on the first VM ends
return Operation.SUCCEEDED
self.run_job(1, ends)
order = [job.params["instance"] for job in self.migrations.order_by("created_at")]
self.assertEqual(order, [self.vms[1].pk, self.vms[2].pk, self.vms[0].pk])
def test_a_vm_an_uncertain_job_holds_is_not_waited_for(self):
stuck = Operation.objects.create(kind="instance.migrate", user=self.admin, username=self.admin.username,
submission_key="key-stuck001", state=Operation.UNCERTAIN)
Claim.objects.create(operation=stuck, resource=claims.instance_key(self.vms[0].uuid), mode=Claim.EXCLUSIVE)
with self.assertRaisesRegex(util.OperationError, "did not migrate"):
self.run_job(2, lambda job: Operation.SUCCEEDED)
self.assertEqual(self.migrations.exclude(pk=stuck.pk).count(), 2)
def test_a_migration_from_a_host_the_vm_left_is_refused(self):
third = Compute.objects.create(name="ej-third", hostname="192.0.2.42", login="", password="", type=4)
raw = {"instance": self.vms[0].pk, "source": third.pk, "target": self.other.pk}
with self.assertRaisesRegex(util.OperationError, "moved to another compute"):
jobs.submit("instance.migrate", self.admin, raw, "key-mig00003")
def test_the_host_page_shows_the_bulk_migration_and_not_its_migrations(self):
params = {"compute": self.compute.pk, "parallel": 2, "moves": [[self.vms[0].pk, self.other.pk]]}
bulk = jobs.submit("host.bulk_migrate", self.admin, params, "key-bulk0001")
child = jobs.submit("instance.migrate", self.admin, {"instance": self.vms[0].pk, "target": self.other.pk},
"key-mig00004", parent=bulk)
self.client.force_login(self.admin)
def shown(key):
return [job["id"] for job in self.client.get(reverse("operation-resource"), {"key": key}).json()["jobs"]]
self.assertEqual(shown(claims.compute_key(self.compute.pk)), [str(bulk.pk)])
self.assertEqual(shown(claims.instance_key(self.vms[0].uuid)), [str(child.pk)])
self.assertEqual(BulkMigrate().progress(bulk), (0, 1))

View file

@ -0,0 +1,95 @@
"""The Bulk Migrate page's script (static/js/bulk_migrate.js): another
destination reloads the list; the header box ticks or unticks every VM that
can migrate, "Also migrate the shut-off VMs" only the shut-off ones; a
refused VM stays unticked; a tag chosen ticks the VMs with it. The button counts the ticked VMs. Spread over the
hosts, every change reloads the list."""
import json
import shutil
import subprocess
import unittest
from pathlib import Path
SCRIPT = Path(__file__).resolve().parents[2] / "static" / "js" / "bulk_migrate.js"
RUN = """
const vm = require("vm");
const boxes = [
{name: "run", checked: true, disabled: false, shutOff: false, dataset: {tags: "web"}},
{name: "off", checked: false, disabled: false, shutOff: true, dataset: {tags: "prod web"}},
{name: "refused", checked: false, disabled: true, shutOff: false, dataset: {tags: "prod"}},
];
const handlers = {};
const box = (id) => ({id, addEventListener: (name, fn) => { handlers[id] = fn; }});
const button = {disabled: false}, counter = {textContent: ""};
let submitted = 0, shownRemoved = 0;
const choose = {
dataset: SPREAD ? {spread: ""} : {},
submit: () => { submitted += 1; },
querySelectorAll: () => [{remove: () => { shownRemoved += 1; }}],
};
const ids = {"bulk-migrate-all": box("bulk-migrate-all"), "bulk-migrate-shut-off": box("bulk-migrate-shut-off"),
"bulk-migrate-tag": box("bulk-migrate-tag"),
"bulk-migrate-target": box("bulk-migrate-target"), "bulk-migrate-submit": button,
"bulk-migrate-count": counter, "bulk-migrate-choose": choose};
const selectors = {
".bulk-migrate-vm:not(:disabled)": (b) => !b.disabled,
".bulk-migrate-vm[data-shut-off]:not(:disabled)": (b) => b.shutOff && !b.disabled,
".bulk-migrate-vm:checked": (b) => b.checked,
};
vm.runInNewContext(SCRIPT, vm.createContext({document: {
getElementById: (id) => ids[id],
querySelectorAll: (selector) => boxes.filter(selectors[selector]),
addEventListener: (name, fn) => { handlers.document = fn; },
}}));
const ticked = () => boxes.filter((b) => b.checked).map((b) => b.name);
const seen = [], counts = [[counter.textContent, button.disabled]];
let tagChoice;
for (const [id, checked, value] of STEPS) {
const target = {id, checked, value, form: choose};
if (id === "bulk-migrate-tag") tagChoice = target;
handlers[id]?.({target});
handlers.document({target}); // the change bubbles to the page
seen.push(ticked());
if (tagChoice === target) tagChoice = target.value;
counts.push([counter.textContent, button.disabled]);
}
console.log(JSON.stringify({seen, submitted, counts, shownRemoved, tagChoice}));
"""
@unittest.skipUnless(shutil.which("node"), "node is not installed")
class BulkMigrateScriptTests(unittest.TestCase):
def run_script(self, steps, spread=False):
"""{seen: the ticked VMs after each step, submitted: the list's reloads, counts: the button's
[count, off] before and after each step, shownRemoved: the spread's VMs dropped from the reload}."""
code = (f"const SCRIPT = {json.dumps(SCRIPT.read_text())}; const SPREAD = {json.dumps(spread)};"
+ RUN.replace("STEPS", json.dumps(steps)))
out = subprocess.run(["node", "-e", code], capture_output=True, text=True, check=True, timeout=30)
return json.loads(out.stdout)
def test_select_all_ticks_every_vm_that_can_migrate(self):
self.assertEqual(self.run_script([["bulk-migrate-all", True], ["bulk-migrate-all", False]])["seen"],
[["run", "off"], []])
def test_the_shut_off_box_ticks_only_the_shut_off_vms(self):
result = self.run_script([["bulk-migrate-shut-off", True], ["bulk-migrate-shut-off", False]])
self.assertEqual(result["seen"], [["run", "off"], ["run"]])
def test_a_tag_ticks_the_vms_with_it_that_can_migrate_and_only_them(self):
result = self.run_script([["bulk-migrate-tag", False, "prod"], ["bulk-migrate-tag", False, ""],
["bulk-migrate-tag", False, "web"]])
self.assertEqual(result["seen"], [["off"], ["off"], ["run", "off"]]) # "": the ticks stay
self.assertEqual(result["tagChoice"], "", "the list goes back to its title: the same tag can be chosen again")
def test_the_button_counts_the_ticked_vms_and_is_off_without_one(self):
self.assertEqual(self.run_script([["bulk-migrate-all", False], ["bulk-migrate-all", True]])["counts"],
[[1, False], [0, True], [2, False]])
def test_another_destination_reloads_the_list(self):
result = self.run_script([["bulk-migrate-target", False, "7"]])
self.assertEqual((result["submitted"], result["shownRemoved"]), (1, 1))
def test_spread_over_the_hosts_a_change_reloads_the_list(self):
result = self.run_script([["bulk-migrate-3", False], ["bulk-migrate-parallel", False]], spread=True)
self.assertEqual(result["submitted"], 1) # the number at once changes nothing of the list

View file

@ -52,7 +52,7 @@ class ComputesPageTests(TestCase):
found = {c1.id: {"cpus": 16, "memory": 64 * GIB, "vcpus": {"all": 40, "running": 24},
"assigned": {"all": 48 * GIB, "running": 32 * GIB}, "ratio": 2.5, "vms": VMS}}
with patch.object(Compute, "capacity", new=property(lambda c: found.get(c.id))), \
patch.object(Compute, "status", new=True):
patch.object(Compute, "status", new=True), patch("computes.views._read_attention", return_value=None):
page = html.fromstring(self.client.get(reverse("computes")).content)
headers = [" ".join(th.text_content().split()) for th in page.xpath("//thead//th")]
# no pools: measuring their space scans each pool of each host (views.host_pools)
@ -63,13 +63,13 @@ class ComputesPageTests(TestCase):
self.assertEqual(cells[1], "6 3 running")
self.assertIn("2.5:1", cells[2])
self.assertIn("40 vCPUs on 16 CPUs", cells[2])
self.assertIn("24 running", cells[2])
self.assertIn("75 % 48.0 GB / 64.0 GB", cells[3])
self.assertIn("32.0 GB running", cells[3])
self.assertIn("24 in running VMs", cells[2])
self.assertIn("75% 48 GiB / 64 GiB", cells[3])
self.assertIn("32 GiB in running VMs", cells[3])
# the totals of the hosts read: host-two's capacity could not be
totals = [" ".join(card.text_content().split()) for card in page.xpath("//div[@class='card-body']")]
self.assertEqual(totals, ["Hosts 2 / 2 connected", "VMs 3 / 6 running", "vCPUs given 40 on 16 CPUs",
"Memory given 48.0 GB of 64.0 GB"])
"Memory given 48 GiB of 64 GiB"])
# host-two could not be read: one cell says so
self.assertIn("capacity could not be read", " ".join(two.text_content().split()))
@ -86,7 +86,7 @@ class SingularTests(TestCase):
line = self.client.get(reverse("compute_capacity", args=[c.id])).content.decode()
(cell,) = page.xpath("//tbody/tr/td[3]")
self.assertIn("1 vCPU on 1 CPU", " ".join(cell.text_content().split()))
self.assertEqual(" ".join(line.split()), "Given to VMs: 1 vCPU (1.0:1), 1.0 GB memory.")
self.assertEqual(" ".join(line.split()), "Given to VMs: 1 vCPU (1.0:1), 1 GiB memory.")
class NewVmDialogLineTests(TestCase):
@ -107,10 +107,10 @@ class NewVmDialogLineTests(TestCase):
given = {"cpus": 16, "memory": 64 * GIB, "vcpus": {"all": 24, "running": 8},
"assigned": {"all": 48 * GIB, "running": 32 * GIB}, "ratio": 1.5,
}
self.assertEqual(self.line(given), "Given to VMs: 24 vCPUs (1.5:1), 48.0 GB memory.")
self.assertEqual(self.line(given), "Given to VMs: 24 vCPUs (1.5:1), 48 GiB memory.")
def test_a_host_without_pools_or_capacity_says_so(self):
given = {"cpus": 2, "memory": 4 * GIB, "vcpus": {"all": 0, "running": 0},
"assigned": {"all": 0, "running": 0}, "ratio": 0}
self.assertEqual(self.line(given), "Given to VMs: 0 vCPUs (0.0:1), 0 bytes memory.")
self.assertEqual(self.line(given), "Given to VMs: 0 vCPUs (0.0:1), 0 B memory.")
self.assertEqual(self.line(None), "The capacity could not be read.")

View file

@ -119,7 +119,7 @@ class GraphScriptTestCase(TestCase):
cpu_now: element({}), mem_now: element({})};
let poll;
const page = {
document: {body: {}, getElementById: (id) => elements[id] || {}},
document: {body: {}, documentElement: {lang: "en"}, getElementById: (id) => elements[id] || {}},
// Chart.js adds the lists a config leaves out
getComputedStyle: () => ({getPropertyValue: () => ""}),
Chart: Object.assign(function (canvas, config) {
@ -143,7 +143,7 @@ class GraphScriptTestCase(TestCase):
poll.request();
poll.onData({cpudata: null, memdata: {total: null, usage: null}, timeline: "t"});
poll.request();
const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", dataIndex: 0});
const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", parsed: {y: 3}, dataIndex: 0});
console.log(JSON.stringify({requests, timeouts, label, shown, state: elements.graph_state.textContent,
cpu: charts[0].data.datasets[0].data.map((point) => point.y),
mem: charts[1].data.datasets[0].data.map((point) => point.y), memMax: charts[1].options.scales.y.max}));
@ -159,9 +159,9 @@ class GraphScriptTestCase(TestCase):
# a host that could not be read leaves a gap and keeps the memory axis
self.assertEqual((result["mem"], result["memMax"]), ([1, None], 2))
# the readings in words, and since when they are not updated
self.assertEqual(result["shown"], ["3 %", "1 / 2 GiB", "Updated at t."])
self.assertEqual(result["shown"], ["3%", "1 / 2 GiB", "Updated at t."])
self.assertEqual(result["state"], "Not updated since t.")
self.assertTrue(result["label"].endswith(": 3 % (average over 5.1 s)"), result["label"])
self.assertTrue(result["label"].endswith(": 3% (average over 5.1 s)"), result["label"])
@unittest.skipUnless(shutil.which("node"), "node is not installed")
@ -174,7 +174,7 @@ class ChartAxisTestCase(unittest.TestCase):
const vm = require("vm");
let chart;
const page = {
document: {body: {}},
document: {body: {}, documentElement: {lang: "en"}},
getComputedStyle: () => ({getPropertyValue: () => ""}),
Chart: Object.assign(function (canvas, config) {
this.data = config.data; this.options = config.options; this.update = () => {}; chart = this;

View file

@ -9,6 +9,7 @@ from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from computes import views
from computes.models import Compute
@ -18,6 +19,10 @@ class ListHostsTests(TestCase):
for number, name in enumerate(("fast", "slow-1", "slow-2")):
Compute.objects.create(name=name, hostname="192.0.2.1", login="wvc", password="", type=1,
host_uuid=f"{number}" * 8 + "-0000-0000-0000-000000000000")
patcher = patch("computes.views._read_attention", return_value=None) # the box's reads: test_attention
patcher.start()
self.addCleanup(patcher.stop) # last: the reads still running end with it
self.addCleanup(lambda: [read.join(5) for read in views._reading.values()])
self.release = threading.Event()
self.addCleanup(self.release.set)

View file

@ -0,0 +1,372 @@
"""A host in maintenance takes no new VM and no migration, and Balance leaves
it out; its VMs run on. A superuser puts it in maintenance and takes it out
on its page, each change audited."""
from datetime import timedelta
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from accounts.models import UserInstance
from computes.jobs import Balance
from computes.models import Compute
from computes.tests.test_balance import Ctx
from django.contrib.auth import get_user_model
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
from django.test import TestCase, TransactionTestCase
from django.urls import reverse
from django.utils import timezone
from instances.jobs import CloneInstance, CreateInstance, RevertSnapshot, _finish_clone, _revert_start, migration_target
from instances.models import Instance
from libvirt import libvirtError
from logs.models import Logs
from operations.jobs import SUBMISSION_KEY_TTL
from operations.models import Claim, Operation
from vrtManager import util
REFUSED = "is in maintenance: no new VM or migration comes to it"
class MaintenanceSwitchTests(TestCase):
def setUp(self):
self.compute = Compute.objects.create(name="mt", hostname="192.0.2.61", login="", password="", type=4)
self.client.force_login(get_user_model().objects.create_superuser("mt-admin", "mt@example.com", "pw"))
Logs.objects.all().delete() # the login's row
def switch(self, state):
return self.client.post(reverse("compute_maintenance", args=[self.compute.pk]), {"maintenance": state})
def test_the_form_sets_the_state_it_names_and_each_change_is_audited(self):
self.assertRedirects(self.switch("on"), reverse("overview", args=[self.compute.pk]), fetch_redirect_response=False)
self.compute.refresh_from_db()
since = self.compute.maintenance_since
self.switch("on") # a second page sent meanwhile does not turn it back, nor starts it anew
self.compute.refresh_from_db()
self.assertEqual(self.compute.maintenance_since, since)
self.switch("off")
self.compute.refresh_from_db()
self.assertFalse(self.compute.maintenance)
self.assertEqual(list(Logs.objects.order_by("id").values_list("message", flat=True)),
["Compute mt: maintenance on", "Compute mt: maintenance on", "Compute mt: maintenance off"])
def test_only_a_post_changes_it(self):
self.assertEqual(self.client.get(reverse("compute_maintenance", args=[self.compute.pk])).status_code, 405)
def test_a_vm_cannot_be_created_from_its_pages(self):
self.compute.maintenance_since = timezone.now()
self.compute.save()
host_vms = reverse("instances", args=[self.compute.pk])
for url in (reverse("instances:create_instance_select_type", args=[self.compute.pk]),
reverse("instances:create_instance", args=[self.compute.pk, "x86_64", "q35"])):
# back to the page it was asked from (the host's VM list), not every VM's
response = self.client.get(url, HTTP_REFERER=f"http://testserver{host_vms}")
self.assertEqual(response.url, f"http://testserver{host_vms}")
response = self.client.get(url, follow=True) # typed in: the host's VM list too
self.assertRedirects(response, host_vms)
self.assertContains(response, f"mt {REFUSED}")
def test_the_host_vm_list_offers_no_new_vm(self):
from lxml import html as lxml_html
page = lambda: lxml_html.fromstring(self.client.get(reverse("instances", args=[self.compute.pk])).content)
create = reverse("instances:create_instance_select_type", args=[self.compute.pk])
self.assertTrue(page().xpath("//a[@href=$u]", u=create))
self.compute.maintenance_since = timezone.now()
self.compute.save()
self.assertFalse(page().xpath("//a[@href=$u]", u=create))
self.assertTrue(page().xpath("//button[@disabled][contains(., 'New VM')]"))
class MaintenanceGuardTests(TestCase):
def setUp(self):
self.admin = get_user_model().objects.create_superuser("mg-admin", "mg@example.com", "pw")
self.host = Compute.objects.create(name="mg", hostname="192.0.2.62", login="", password="", type=4,
maintenance_since=timezone.now())
self.other = Compute.objects.create(name="mg-other", hostname="192.0.2.63", login="", password="", type=4)
def test_no_vm_migrates_to_it(self):
with self.assertRaisesRegex(util.OperationError, f"mg {REFUSED}"):
migration_target(Instance(compute=self.other, name="vm"), self.host.pk)
def test_no_vm_is_created_on_it_nor_by_a_job_queued_before(self):
with self.assertRaisesRegex(util.OperationError, REFUSED):
CreateInstance().validate(self.admin, {"compute": self.host.pk})
with self.assertRaisesRegex(util.OperationError, REFUSED):
CreateInstance().precheck(SimpleNamespace(user=self.admin, params={"compute": self.host.pk, "name": "new"}),
None)
def test_no_vm_is_cloned_on_it(self):
with patch("instances.jobs._clonable", return_value=Instance(compute=self.host, name="vm")), \
self.assertRaisesRegex(util.OperationError, REFUSED):
CloneInstance().plan(self.admin, {"instance": 1, "fields": {}})
class BalanceLeavesItOutTests(TestCase):
def setUp(self):
self.admin = get_user_model().objects.create_superuser("mb-admin", "mb@example.com", "pw")
self.hosts = [Compute.objects.create(name=f"mb-{n}", hostname=f"192.0.2.7{n}", login="", password="", type=4)
for n in range(2)]
self.vm = Instance.objects.create(compute=self.hosts[0], name="mb-vm", uuid="00000000-0000-4000-8000-000000000201")
self.params = {"parallel": 1, "moves": [[self.vm.pk, self.hosts[0].pk, self.hosts[1].pk]]}
def maintenance(self, host):
Compute.objects.filter(pk=host.pk).update(maintenance_since=timezone.now())
def test_a_move_from_or_to_a_host_in_maintenance_is_refused(self):
for host, text in ((self.hosts[0], "mb-0 is in maintenance: Balance leaves it out"),
(self.hosts[1], f"mb-1 {REFUSED}")):
Compute.objects.update(maintenance_since=None)
self.maintenance(host)
with self.assertRaisesRegex(util.OperationError, text):
Balance().validate(self.admin, Balance().normalize(self.params))
def test_a_host_put_in_maintenance_after_the_job_was_asked_for_gives_no_vm(self):
op = Operation.objects.create(kind="host.balance", user=self.admin, username=self.admin.username,
submission_key="key-mb000001", params=self.params,
intent=Balance().plan(self.admin, self.params).intent)
self.maintenance(self.hosts[0])
with self.assertRaisesRegex(util.OperationError, "mb-vm: mb-0 is in maintenance"):
Balance().run(op, Ctx(op))
self.assertFalse(Operation.objects.filter(kind="instance.migrate").exists())
class NoStartTests(TestCase):
"""None of the VMs of a host in maintenance starts there, also for its owner."""
def setUp(self):
self.compute = Compute.objects.create(name="ms", hostname="192.0.2.81", login="", password="", type=1,
maintenance_since=timezone.now())
self.instance = Instance.objects.create(compute=self.compute, name="ms-vm",
uuid="00000000-0000-4000-8000-000000000301")
self.client.force_login(get_user_model().objects.create_superuser("ms-admin", "ms@example.com", "pw"))
self.proxy = MagicMock()
patcher = patch.object(Instance, "proxy", new_callable=lambda: self.proxy)
patcher.start()
self.addCleanup(patcher.stop)
def test_a_vm_is_not_started_nor_resumed_nor_power_cycled(self):
for action in ("poweron", "resume", "powercycle"):
response = self.client.post(reverse(f"instances:{action}", args=[self.instance.pk]), follow=True)
self.assertContains(response, "ms is in maintenance: its VMs cannot be started there")
self.assertNotContains(response, "libvirt Error") # the panel's own refusal
self.proxy.start.assert_not_called()
self.proxy.resume.assert_not_called()
self.proxy.force_shutdown.assert_not_called() # a power cycle would leave it off
def test_no_revert_starts_a_shut_off_vm(self):
self.proxy.get_status.return_value = 5
for state, refused in (("running", True), ("paused", True), ("shutoff", False), ("disk-snapshot", False)):
self.proxy._snapshot.return_value.getXMLDesc.return_value = (
f"<domainsnapshot><state>{state}</state></domainsnapshot>")
if refused:
with self.assertRaisesRegex(util.OperationError, "its VMs cannot be started there"):
_revert_start(self.instance, self.proxy, {"name": "s", "external": False})
else:
_revert_start(self.instance, self.proxy, {"name": "s", "external": False})
self.proxy.get_status.return_value = 3 # paused: a running snapshot resumes it
self.proxy._snapshot.return_value.getXMLDesc.return_value = "<domainsnapshot><state>running</state></domainsnapshot>"
with self.assertRaisesRegex(util.OperationError, "its VMs cannot be started there"):
_revert_start(self.instance, self.proxy, {"name": "s", "external": False})
self.proxy.get_status.return_value = 1 # running already: the revert starts nothing
self.proxy._snapshot.return_value.getXMLDesc.return_value = "<domainsnapshot><state>running</state></domainsnapshot>"
_revert_start(self.instance, self.proxy, {"name": "s", "external": False})
def test_nor_by_its_owner(self):
owner = get_user_model().objects.create_user("ms-owner", "owner@example.com", "pw")
UserInstance.objects.create(instance=self.instance, user=owner)
self.client.force_login(owner)
response = self.client.post(reverse("instances:poweron", args=[self.instance.pk]), follow=True)
self.assertContains(response, "ms is in maintenance: its VMs cannot be started there")
self.proxy.start.assert_not_called()
def test_a_revert_job_that_would_start_it_is_refused(self):
self.proxy.get_status.return_value = 5
self.proxy._snapshot.return_value.getXMLDesc.return_value = "<domainsnapshot><state>running</state></domainsnapshot>"
admin = get_user_model().objects.get(username="ms-admin")
with patch("instances.jobs._proxy", return_value=self.proxy), \
self.assertRaisesRegex(util.OperationError, "its VMs cannot be started there"):
RevertSnapshot().validate(admin, {"instance": self.instance.pk, "name": "s", "external": False})
def test_its_autostart_cannot_be_turned_on(self):
response = self.client.post(reverse("instances:set_autostart", args=[self.instance.pk]), follow=True)
self.assertContains(response, "ms is in maintenance: its VMs cannot be started there")
self.proxy.set_autostart.assert_not_called()
def test_a_compute_read_before_the_maintenance_refuses_too(self):
held = Compute.objects.get(pk=self.compute.pk)
Compute.objects.filter(pk=held.pk).update(maintenance_since=None)
held.refuse_start() # out of maintenance now, though the object says otherwise
Compute.objects.filter(pk=held.pk).update(maintenance_since=timezone.now())
stale = Compute.objects.get(pk=held.pk)
stale.maintenance_since = None # as read before it went in maintenance
with self.assertRaisesRegex(util.OperationError, "its VMs cannot be started there"):
stale.refuse_start()
with self.assertRaisesRegex(util.OperationError, REFUSED):
stale.refuse_new_vms()
def test_a_running_vm_still_stops(self):
self.client.post(reverse("instances:poweroff", args=[self.instance.pk]))
self.proxy.shutdown.assert_called_once()
class MaintenanceWithMigrationTests(TestCase):
""""Put in maintenance" on a host with running VMs opens Bulk Migrate,
which puts the host in maintenance with the job, or without migrating."""
def setUp(self):
self.compute = Compute.objects.create(name="me", hostname="192.0.2.91", login="", password="", type=4)
self.other = Compute.objects.create(name="me-other", hostname="192.0.2.92", login="", password="", type=4)
self.vm = Instance.objects.create(compute=self.compute, name="me-vm", uuid="00000000-0000-4000-8000-000000000401")
self.admin = get_user_model().objects.create_superuser("me-admin", "me@example.com", "pw")
self.client.force_login(self.admin)
Logs.objects.all().delete()
def post(self, key="mnt00000key", moves=True):
return self.client.post(reverse("bulk_migrate", args=[self.compute.pk]), {
"target": self.other.pk, "instance": [self.vm.pk] if moves else [], "parallel": "1",
"maintenance": "on", "submission_key": key})
def maintenance(self):
self.compute.refresh_from_db()
return self.compute.maintenance
def test_the_host_goes_in_maintenance_with_the_job(self):
self.assertRedirects(self.post(), reverse("instances", args=[self.compute.pk]), fetch_redirect_response=False)
(op,) = Operation.objects.all()
self.assertTrue(op.params["maintenance"])
self.assertTrue(self.maintenance())
self.assertEqual(self.compute.maintenance_since, op.created_at) # the job is of this maintenance
self.assertEqual(list(Logs.objects.values_list("message", flat=True)), ["Compute me: maintenance on"])
def test_a_refused_job_leaves_the_host_out_of_maintenance(self):
response = self.post(moves=False)
self.assertRedirects(response, reverse("bulk_migrate", args=[self.compute.pk]) + f"?target={self.other.pk}"
"&maintenance=on", fetch_redirect_response=False)
self.assertFalse(Operation.objects.exists())
self.assertFalse(self.maintenance())
def test_the_form_sent_after_its_key_expired_puts_it_back_with_its_new_job(self):
self.post()
Operation.objects.update(created_at=timezone.now() - SUBMISSION_KEY_TTL - timedelta(minutes=1),
state=Operation.SUCCEEDED)
Claim.objects.all().delete() # it ended
Compute.objects.filter(pk=self.compute.pk).update(maintenance_since=None)
self.post()
self.assertTrue(self.maintenance())
self.assertEqual(Operation.objects.count(), 2)
def test_the_form_sent_again_does_not_put_it_back(self):
self.post()
Compute.objects.filter(pk=self.compute.pk).update(maintenance_since=None) # taken out since
self.post()
self.assertFalse(self.maintenance())
self.assertEqual(Operation.objects.count(), 1)
def page(self, **query):
def read_list_rows(instances, computes): # a running VM, without asking a host
for instance in instances:
instance.__dict__["info"] = [1, 131072, 131072, 1, 0]
instance.__dict__["state_reason"] = None
with patch("computes.views.utils.refresh_instance_database"), \
patch("computes.views.read_list_rows", side_effect=read_list_rows), \
patch("computes.reach.Reach.refusal", return_value=None):
return self.client.get(reverse("bulk_migrate", args=[self.compute.pk]), query)
def test_the_page_offers_both_ways_into_maintenance(self):
response = self.page(maintenance="on")
self.assertContains(response, "Put in maintenance without migrating")
self.assertContains(response, '<input type="hidden" name="maintenance" value="on">', count=3)
Compute.objects.filter(pk=self.compute.pk).update(maintenance_since=timezone.now()) # already: the plain page
self.assertNotContains(self.page(maintenance="on"), "Put in maintenance without migrating")
class MaintenanceStateTests(TestCase):
"""A host in maintenance is ready once none of its VMs runs; until then,
or while it cannot be read, its maintenance is only asked for."""
def setUp(self):
self.compute = Compute.objects.create(name="mz", hostname="192.0.2.95", login="", password="", type=4,
maintenance_since=timezone.now())
self.client.force_login(get_user_model().objects.create_superuser("mz-admin", "mz@example.com", "pw"))
@staticmethod
def given(**vms):
return {"vms": {"running": 0, "paused": 0, "shutoff": 0, "other": 0, **vms}, "cpus": 1, "memory": 1,
"vcpus": {"all": 0, "running": 0}, "assigned": {"all": 0, "running": 0}}
def overview(self, given):
with patch.object(Compute, "status", True), patch("computes.views.wvmHostDetails", side_effect=libvirtError("not read")), \
patch.object(Compute, "capacity", given), patch("computes.views.host_pools"):
return self.client.get(reverse("overview", args=[self.compute.pk]))
def test_running_or_paused_vms_keep_it_requested(self):
response = self.overview(self.given(running=1, paused=1, shutoff=3))
self.assertContains(response, "Maintenance requested: 2 VMs still run on this host.")
self.assertNotContains(response, "In maintenance: no VM runs")
def test_with_only_shut_off_vms_it_is_in_maintenance(self):
self.assertContains(self.overview(self.given(shutoff=3)), "In maintenance: no VM runs on this host.")
def test_the_vms_that_autostart_when_the_host_boots_are_named(self):
doms = [MagicMock(**{"name.return_value": name, "autostart.return_value": on})
for name, on in (("mz-b", 1), ("mz-off", 0), ("mz-a", 1))]
proxy = MagicMock(**{"wvm.listAllDomains.return_value": doms})
with patch.object(Compute, "proxy", new_callable=lambda: proxy):
response = self.overview(self.given(shutoff=3))
self.assertContains(response, "These VMs start by themselves when the host boots: mz-a, mz-b.")
def test_a_host_that_cannot_be_read_is_not_said_ready(self):
self.assertContains(self.overview(None), "whether its VMs still run is not known")
def bulk(self, state, before):
op = Operation.objects.create(kind="host.bulk_migrate", user=None, username="mz-admin", state=state,
resource=f"compute:{self.compute.pk}")
if before:
Operation.objects.filter(pk=op.pk).update(created_at=self.compute.maintenance_since - timedelta(hours=1))
return op
def test_only_a_bulk_migration_of_this_maintenance_or_one_still_running_is_shown(self):
self.bulk(Operation.SUCCEEDED, before=True) # an earlier one
response = self.overview(self.given(running=1))
self.assertNotContains(response, "bulk migration")
self.assertNotContains(response, "being migrated")
running = self.bulk(Operation.RUNNING, before=True)
self.assertContains(self.overview(self.given(running=1)), "Its VMs are being migrated")
Operation.objects.filter(pk=running.pk).update(state=Operation.FAILED)
self.bulk(Operation.FAILED, before=False)
self.assertContains(self.overview(self.given(running=1)), "Its last bulk migration")
def test_put_in_maintenance_leads_to_bulk_migrate_while_vms_run(self):
Compute.objects.filter(pk=self.compute.pk).update(maintenance_since=None)
response = self.overview(self.given(running=1))
self.assertContains(response, reverse("bulk_migrate", args=[self.compute.pk]) + "?maintenance=on")
response = self.overview(self.given(shutoff=1))
self.assertContains(response, reverse("compute_maintenance", args=[self.compute.pk]))
class CloneStaysOffTests(TestCase):
def test_a_clone_made_while_the_host_went_in_maintenance_stays_off(self):
compute = Compute.objects.create(name="mc", hostname="192.0.2.97", login="", password="", type=1,
maintenance_since=timezone.now())
op = SimpleNamespace(intent={"compute": compute.pk, "name": "mc-clone",
"uuid": "00000000-0000-4000-8000-000000000501"},
username="mc-admin", client_ip=None)
with patch("instances.jobs.wvmInstance") as proxy:
result = _finish_clone(op, {"start": True}, "")
proxy.return_value.start.assert_not_called()
self.assertIn("is in maintenance: its VMs cannot be started there", str(result["warning"]))
class MaintenanceSinceMigrationTests(TransactionTestCase):
"""A host in maintenance before maintenance_since stays in maintenance."""
def test_a_host_in_maintenance_stays_in_it(self):
executor = MigrationExecutor(connection)
executor.migrate([("computes", "0010_maintenance")])
old = executor.loader.project_state([("computes", "0010_maintenance")]).apps.get_model("computes", "Compute")
old.objects.create(name="mm-on", hostname="192.0.2.97", login="", password="", type=4, maintenance=True)
old.objects.create(name="mm-off", hostname="192.0.2.98", login="", password="", type=4)
executor = MigrationExecutor(connection)
executor.migrate(executor.loader.graph.leaf_nodes())
self.assertEqual({c.name: c.maintenance for c in Compute.objects.all()}, {"mm-on": True, "mm-off": False})

View file

@ -12,6 +12,7 @@ from computes.models import Compute
from computes.validators import validate_migration_address
from instances.models import Instance
from instances.utils import migrate_instance
from appsettings.models import AppSettings
class MigrationAddressTests(TestCase):
@ -50,6 +51,13 @@ class MigrationAddressTests(TestCase):
self.client.post(reverse("compute_update", args=[compute.id]), {**data, "migration_address": "tcp://x"})
compute.refresh_from_db()
self.assertEqual(compute.migration_address, "198.51.100.9")
self.assertFalse(compute.migration_tls)
page = self.client.get(reverse("compute_update", args=[compute.id]))
self.assertContains(page, 'name="migration_tls"')
self.client.post(reverse("compute_update", args=[compute.id]), {**data, "migration_tls": "on"})
compute.refresh_from_db()
self.assertTrue(compute.migration_tls)
self.assertContains(self.client.get(reverse("compute_update", args=[compute.id])), "migrations over TLS")
def test_a_migration_uses_the_destination_address(self):
source = Compute.objects.create(name="ma-src", hostname="10.0.0.8", login="root", password="", type=2)
@ -64,3 +72,13 @@ class MigrationAddressTests(TestCase):
instances.return_value.moveto.return_value = ("live", [])
migrate_instance(dest, vm, user, live=True)
self.assertEqual(instances.return_value.moveto.call_args.kwargs["uri"], "tcp://198.51.100.9")
self.assertEqual(instances.return_value.moveto.call_args.kwargs["bandwidth"], 0) # the default: no limit
AppSettings.objects.filter(key="MIGRATION_BANDWIDTH").update(value="200")
vm = Instance.objects.create(compute=source, name="vm2", uuid="u-ma2") # the first was moved
with patch.object(Compute, "status", True), \
patch("instances.utils.wvmInstances") as instances, \
patch("instances.utils.wvmInstance"), \
patch.object(Instance, "proxy", MagicMock()):
instances.return_value.moveto.return_value = ("live", [])
migrate_instance(dest, vm, user, live=True)
self.assertEqual(instances.return_value.moveto.call_args.kwargs["bandwidth"], 200)

View file

@ -138,9 +138,13 @@ class ComputeConcurrencyTestCase(TransactionTestCase):
compute.status = True
claims.admit({claims.compute_key(compute.id): Claim.EXCLUSIVE}, holder="other")
refresh_instance_database(compute)
self.assertIsNone(refresh_instance_database(compute)) # not synchronized: the caller may try again
self.assertEqual(Instance.objects.filter(compute=compute).count(), 1)
mock_proxy.wvm.listAllDomains.assert_called_once() # the pre-check's read; no reconcile
Claim.objects.all().delete()
self.assertIs(refresh_instance_database(compute), True) # synchronized
self.assertEqual(Instance.objects.filter(compute=compute).count(), 0)
self.assertIs(refresh_instance_database(compute), True) # already matching
def _reconcile_compute(self, name, domains):
"""A compute whose database differs from libvirt (a VM libvirt no

View file

@ -59,12 +59,12 @@ class OverviewTestCase(TestCase):
self.assertIn("rack 4", text(page, "//div[@id='host_status']"))
cards = [" ".join(" ".join(card.itertext()).split()) for card in page.xpath("//div[@class='card h-100']")]
self.assertIn("VMs 6 3 running, 2 shut off, 1 paused Instances →", cards)
self.assertTrue(any(card.startswith("vCPUs 1.5:1 12 vCPUs on 8 CPUs 6 running") for card in cards), cards)
self.assertTrue(any(card.startswith("Memory 75 % 24.0 GB / 32.0 GB") for card in cards), cards)
self.assertTrue(any("120.0 GB free of 500.0 GB" in card for card in cards), cards)
self.assertTrue(any(card.startswith("vCPUs 1.5:1 12 vCPUs on 8 CPUs 6 in running VMs") for card in cards), cards)
self.assertTrue(any(card.startswith("Memory 75% 24 GiB / 32 GiB") for card in cards), cards)
self.assertTrue(any("120 GiB free of 500 GiB" in card for card in cards), cards)
hardware = text(page, "//div[@class='card-header'][normalize-space()='Hardware']/..")
self.assertIn("Processor Xeon Architecture x86_64 Logical CPUs 8 Physical cores 4 Sockets 2 NUMA nodes 2 "
"Clock 2.4 GHz Memory 32.0 GB", hardware)
"Clock 2.4 GHz Memory 32 GiB", hardware)
software = text(page, "//div[@class='card-header'][normalize-space()='Software and connection']/..")
self.assertIn("QEMU 10.1.0 libvirt 11.10.0", software)
self.assertIn("x86_64 kvm · qemu", software)
@ -78,7 +78,7 @@ class OverviewTestCase(TestCase):
pool("backup", 900, 800), pool("iso", 100, 90)]
page = self.page(pools=pools)
storage = page.xpath("//div[@class='card-header'][normalize-space()='Storage']/..")[0]
self.assertIn("default 120.0 GB free of 500.0 GB", " ".join(" ".join(storage.xpath("./div/div//text()")).split()))
self.assertIn("default 120 GiB free of 500 GiB", " ".join(" ".join(storage.xpath("./div/div//text()")).split()))
(more,) = storage.xpath(".//details")
self.assertEqual(" ".join(more.xpath("summary")[0].text_content().split()), "3 more pools")
# active pools only, by name after the default one

View file

@ -1,10 +1,10 @@
"""Ownership survives a VM's temporary disappearance or an out-of-band move."""
from datetime import timedelta
from datetime import time, timedelta
from unittest.mock import MagicMock
from accounts.models import UserInstance
from computes.models import Compute
from computes.models import Compute, Tag
from computes.utils import refresh_instance_database
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
@ -15,6 +15,7 @@ from logs.models import Logs
from operations import claims
from operations.models import Claim
from rest_framework.test import APIClient
from vmbackups.models import Backup, BackupPolicy, BackupTarget
from computes.tests.fakes import Domain
UUID = "44444444-4444-4444-4444-444444444444"
@ -37,7 +38,7 @@ class OwnershipTestCase(TestCase):
compute.proxy.wvm.listAllDomains.return_value = [Domain(n, u) for n, u in domains]
def owned_vm(self, compute):
vm = Instance.objects.create(compute=compute, name="vm", uuid=UUID, is_template=True)
vm = Instance.objects.create(compute=compute, name="vm", uuid=UUID, is_template=True, protected=True)
UserInstance.objects.create(instance=vm, user=self.owner, is_change=True, is_vnc=True)
return vm
@ -59,14 +60,57 @@ class OwnershipTestCase(TestCase):
self.assertEqual(self.ownership(self.host_a), (True, [(self.owner, True, False, True)]))
self.assertFalse(InstanceTombstone.objects.exists())
self.assertEqual(self.rows(), [
("-", "host-a", f"VM vm ({UUID}): owners kept on the Removed VMs page"),
("-", "host-a", f"VM vm ({UUID}): owners restored"),
("-", "host-a", f"VM vm ({UUID}): kept on the Removed VMs page"),
("-", "host-a", f"VM vm ({UUID}): restored from the Removed VMs page"),
])
def test_vm_that_returns_gets_its_protection_schedules_and_backups_back(self):
vm = Instance.objects.create(compute=self.host_a, name="vm", uuid=UUID, protected=True)
target = BackupTarget.objects.create(name="t")
policy = BackupPolicy.objects.create(name="nightly", target=target, time=time(2), keep=1)
policy.instances.add(vm)
backup = Backup.objects.create(target=target, instance=vm, vm_uuid=UUID, vm_name="vm", compute_name="host-a",
state=Backup.READY, policy=policy)
refresh_instance_database(self.host_a) # undefined for a while
self.assertEqual(InstanceTombstone.objects.get().policies, [policy.pk])
self.on(self.host_a, [("vm", UUID)]) # defined again
refresh_instance_database(self.host_a)
vm = Instance.objects.get(uuid=UUID)
self.assertTrue(vm.protected)
self.assertEqual(list(vm.backup_policies.all()), [policy])
backup.refresh_from_db()
self.assertEqual(backup.instance, vm)
def test_a_schedule_that_chooses_by_tag_since_is_not_given_the_vm(self):
vm = Instance.objects.create(compute=self.host_a, name="vm", uuid=UUID)
policy = BackupPolicy.objects.create(name="nightly", target=BackupTarget.objects.create(name="t"),
time=time(2), keep=1)
policy.instances.add(vm)
refresh_instance_database(self.host_a)
BackupPolicy.objects.filter(pk=policy.pk).update(tag=Tag.objects.create(name="prod"))
self.on(self.host_a, [("vm", UUID)])
refresh_instance_database(self.host_a)
self.assertFalse(policy.instances.exists())
def test_vm_that_returns_does_not_get_a_copys_backups(self):
target = BackupTarget.objects.create(name="t")
copy = Instance.objects.create(compute=self.host_b, name="vm", uuid=UUID)
theirs = Backup.objects.create(target=target, instance=copy, vm_uuid=UUID, vm_name="vm", compute_name="host-b",
state=Backup.READY)
copy.delete() # deleted in the panel: its backups stay, unlinked
Instance.objects.create(compute=self.host_a, name="vm", uuid=UUID, protected=True)
refresh_instance_database(self.host_a)
self.on(self.host_a, [("vm", UUID)])
refresh_instance_database(self.host_a)
theirs.refresh_from_db()
self.assertIsNone(theirs.instance)
def test_an_ownerless_vm_leaves_a_row(self):
Instance.objects.create(compute=self.host_a, name="vm", uuid=UUID)
refresh_instance_database(self.host_a)
self.assertEqual(self.rows(), [("-", "host-a", f"VM vm ({UUID}): left the panel (no owners)")])
self.assertEqual(self.rows(), [("-", "host-a", f"VM vm ({UUID}): left the panel (nothing to keep)")])
def test_move_seen_on_the_new_host_first(self):
self.owned_vm(self.host_a)
@ -77,6 +121,7 @@ class OwnershipTestCase(TestCase):
refresh_instance_database(self.host_a) # gone from A: it moved to B
self.assertEqual(self.ownership(self.host_b), (True, [(self.owner, True, False, True)]))
self.assertTrue(Instance.objects.get(compute=self.host_b).protected)
self.assertFalse(Instance.objects.filter(compute=self.host_a).exists())
self.assertEqual(self.rows(), [("-", "host-a", f"VM vm ({UUID}): owners moved to host-b")])
@ -164,7 +209,7 @@ class OwnershipTestCase(TestCase):
self.assertEqual((tombstone.owners[0]["user"], tombstone.host), (self.owner.id, "host-a"))
self.assertEqual(self.rows(), [
("cd-admin", "-", "Login"),
("-", "host-a", f"VM vm ({UUID}): owners kept on the Removed VMs page"),
("-", "host-a", f"VM vm ({UUID}): kept on the Removed VMs page"),
("cd-admin", "host-a", "Compute host-a (host-a.example): delete"),
])

View file

@ -0,0 +1,40 @@
"""Reach asks each host pair and each directory once, however many VMs and
destinations a page asks about."""
from unittest.mock import MagicMock, patch
from computes.models import Compute
from computes.reach import Reach
from django.test import RequestFactory, TestCase
from instances.models import Instance
from libvirt import libvirtError
XML = "<domain><devices><disk type='file'><source file='/shared/{name}.qcow2'/><target dev='vda'/></disk></devices></domain>"
class ReachTests(TestCase):
def test_hosts_and_directories_are_asked_once(self):
source = Compute.objects.create(name="re", hostname="192.0.2.60", login="", password="", type=4)
targets = [Compute.objects.create(name=f"re-{n}", hostname=f"192.0.2.6{n}", login="", password="", type=4)
for n in (1, 2)]
vms = [Instance.objects.create(compute=source, name=f"re-vm{n}", uuid=f"00000000-0000-4000-8000-00000000020{n}")
for n in range(3)]
with patch("instances.jobs.migration_target") as target_check, patch("computes.reach.wvmInstances") as conn, \
patch.object(Instance, "proxy", new_callable=lambda: property(lambda vm: MagicMock(
instance=MagicMock(XMLDesc=lambda flags: XML.format(name=vm.name))))):
conn.return_value.shares.return_value = True
reach = Reach(RequestFactory().get("/"))
refusals = [reach.refusal(vm, target) for vm in vms for target in targets]
self.assertEqual(refusals, [None] * 6)
self.assertEqual(target_check.call_count, 2) # a host pair once it passed
self.assertEqual(conn.return_value.shares.call_count, 2) # a directory of a host pair once
def test_a_host_whose_pools_cannot_be_read_is_refused_not_raised(self):
source = Compute.objects.create(name="rf", hostname="192.0.2.70", login="", password="", type=4)
target = Compute.objects.create(name="rf-1", hostname="192.0.2.71", login="", password="", type=4)
vm = Instance.objects.create(compute=source, name="rf-vm", uuid="00000000-0000-4000-8000-000000000301")
with patch("instances.jobs.migration_target"), patch("computes.reach.wvmInstances") as conn, \
patch.object(Instance, "proxy", new_callable=lambda: property(lambda vm: MagicMock(
instance=MagicMock(XMLDesc=lambda flags: XML.format(name=vm.name))))):
conn.return_value.shares.side_effect = libvirtError("cannot list pools")
self.assertIn("cannot list pools", Reach(RequestFactory().get("/")).refusal(vm, target))

173
computes/tests/test_tags.py Normal file
View file

@ -0,0 +1,173 @@
"""Tags of VMs and hosts: one list of names, kept with a VM that leaves its
host for a while or moves out of band, and set on the host form."""
from unittest.mock import MagicMock, patch
from django import forms
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from django.utils import translation
from computes.forms import TagsField, TagsForm
from computes.models import Compute, Tag
from computes.tests.fakes import Domain, no_host_answers
from computes.utils import move_ownership, refresh_instance_database
from instances.models import Instance, InstanceTombstone
UUID = "55555555-5555-5555-5555-555555555555"
class TagsFieldTests(TestCase):
def test_names_are_kept_in_lower_case_once(self):
self.assertEqual(TagsField().clean(["Prod", "db", "prod"]), ["prod", "db"])
def test_a_name_is_letters_digits_and_dot_dash_underscore(self):
self.assertEqual(TagsField().clean(["x" * 12]), ["x" * 12])
# a tag made before the limit can still be given
Tag.objects.create(name="y" * 20)
self.assertEqual(TagsField().clean(["y" * 20]), ["y" * 20])
for bad in ("two words", "-lead", "ç", "x" * 13):
with self.subTest(bad), self.assertRaises(forms.ValidationError):
TagsField().clean([bad])
def test_the_box_tells_in_the_reader_s_language_what_a_new_name_adds(self):
with translation.override("tr"):
html = TagsForm().as_p()
self.assertIn('data-add="Etiket ekle: %(tag)s"', html)
# and what a new name may be, shown when the one typed cannot be a tag
self.assertIn('data-rule="Yeni etiket: a-z harfleri, rakamlar, nokta, tire ve alt çizgi, harf ya da rakamla başlar; '
'en fazla 12 karakter"', html)
def test_the_tags_are_made_when_saved(self):
Tag.objects.create(name="prod")
tags = Tag.named(["prod", "db"])
self.assertEqual(sorted(t.name for t in tags), ["db", "prod"])
self.assertEqual(Tag.objects.count(), 2)
class TagsFollowTheVmTests(TestCase):
def setUp(self):
self.prod, self.db = Tag.objects.create(name="prod"), Tag.objects.create(name="db")
self.host_a = self.compute("host-a")
self.host_b = self.compute("host-b")
def compute(self, name):
compute = Compute.objects.create(name=name, hostname=f"{name}.example", login="", password="", type=1)
compute.__dict__["proxy"] = MagicMock()
compute.__dict__["status"] = True
compute.proxy.wvm.listAllDomains.return_value = []
return compute
def tag_names(self, compute):
return sorted(Instance.objects.get(compute=compute, uuid=UUID).tags.values_list("name", flat=True))
def test_a_vm_with_tags_only_gets_them_back(self):
Instance.objects.create(compute=self.host_a, name="vm", uuid=UUID).tags.add(self.prod)
refresh_instance_database(self.host_a) # undefined for a while
self.assertEqual(InstanceTombstone.objects.get(uuid=UUID).tags, ["prod"])
self.host_a.proxy.wvm.listAllDomains.return_value = [Domain("vm", UUID)]
refresh_instance_database(self.host_a)
self.assertEqual(self.tag_names(self.host_a), ["prod"])
def test_a_tag_deleted_meanwhile_is_not_given_back(self):
Instance.objects.create(compute=self.host_a, name="vm", uuid=UUID).tags.add(self.prod, self.db)
refresh_instance_database(self.host_a)
self.db.delete()
self.host_b.proxy.wvm.listAllDomains.return_value = [Domain("vm", UUID)]
refresh_instance_database(self.host_b)
self.assertEqual(self.tag_names(self.host_b), ["prod"])
def test_a_move_adds_the_tags_to_those_already_there(self):
source = Instance.objects.create(compute=self.host_a, name="vm", uuid=UUID)
source.tags.add(self.prod)
target = Instance.objects.create(compute=self.host_b, name="vm", uuid=UUID)
target.tags.add(self.db)
move_ownership(source, target)
self.assertEqual(self.tag_names(self.host_b), ["db", "prod"])
class HostTagsTests(TestCase):
def setUp(self):
self.client.force_login(get_user_model().objects.create_superuser("ht-admin", "ht@example.com", "pw"))
no_host_answers(self)
def test_the_host_form_sets_the_tags(self):
self.client.post(reverse("add_tcp_host"), {"name": "kvm1", "hostname": "192.0.2.1", "login": "wvc",
"password": "pw", "details": "", "tags": ["Rack-1", "gpu"]})
compute = Compute.objects.get(name="kvm1")
self.assertEqual(sorted(compute.tags.values_list("name", flat=True)), ["gpu", "rack-1"])
self.client.post(reverse("compute_update", args=[compute.id]),
{"name": "kvm1", "hostname": "192.0.2.1", "login": "wvc", "password": "", "details": "",
"initial-tags": ["gpu", "rack-1"]})
self.assertFalse(compute.tags.exists())
def test_a_form_shown_before_a_rename_keeps_the_new_name(self):
compute = Compute.objects.create(name="kvm1", hostname="192.0.2.1", login="wvc", password="pw", type=1)
compute.tags.add(Tag.objects.create(name="prod"))
# the form carries the tags it showed, and sends them back unchanged
self.assertContains(self.client.get(reverse("compute_update", args=[compute.id])),
'<input type="hidden" name="initial-tags" value="prod">', html=True)
Tag.objects.filter(name="prod").update(name="production") # the Tags page renames it meanwhile
self.client.post(reverse("compute_update", args=[compute.id]),
{"name": "kvm1b", "hostname": "192.0.2.1", "login": "wvc", "password": "", "details": "",
"tags": ["prod"], "initial-tags": ["prod"]})
compute.refresh_from_db()
self.assertEqual((compute.name, list(compute.tags.values_list("name", flat=True))), ("kvm1b", ["production"]))
self.assertFalse(Tag.objects.filter(name="prod").exists())
def test_a_form_shown_again_with_an_error_carries_the_tags_first_shown(self):
compute = Compute.objects.create(name="kvm1", hostname="192.0.2.1", login="wvc", password="pw", type=1)
compute.tags.add(Tag.objects.create(name="production")) # renamed from prod since the form was shown
response = self.client.post(reverse("compute_update", args=[compute.id]),
{"name": "kvm1", "hostname": "bad host", "login": "wvc", "password": "",
"details": "", "tags": ["prod"], "initial-tags": ["prod"]})
self.assertContains(response, '<input type="hidden" name="initial-tags" value="prod">', html=True)
def test_the_same_tags_in_another_order_are_no_change(self):
compute = Compute.objects.create(name="kvm1", hostname="192.0.2.1", login="wvc", password="pw", type=1)
compute.tags.add(Tag.objects.create(name="production"))
self.client.post(reverse("compute_update", args=[compute.id]),
{"name": "kvm1", "hostname": "192.0.2.1", "login": "wvc", "password": "", "details": "",
"tags": ["b", "a"], "initial-tags": ["a", "b"]})
self.assertEqual(list(compute.tags.values_list("name", flat=True)), ["production"])
def test_a_tag_deleted_meanwhile_is_made_again(self):
compute = Compute.objects.create(name="kvm1", hostname="192.0.2.1", login="wvc", password="pw", type=1)
compute.tags.add(Tag.objects.create(name="gpu"))
from computes import utils
real = utils.lock_ownership
def lock(): # the Tags page deletes it while the form waits for the lock
Tag.objects.filter(name="gpu").delete()
real()
with patch("computes.forms.lock_ownership", side_effect=lock):
response = self.client.post(reverse("compute_update", args=[compute.id]),
{"name": "kvm1b", "hostname": "192.0.2.1", "login": "wvc", "password": "",
"details": "", "tags": ["gpu"]})
self.assertEqual(response.status_code, 302)
compute.refresh_from_db()
self.assertEqual((compute.name, list(compute.tags.values_list("name", flat=True))), ("kvm1b", ["gpu"]))
def test_the_socket_form_has_them_too(self):
self.client.post(reverse("add_socket_host"), {"name": "local", "hostname": "localhost", "details": "",
"tags": ["lab"]})
self.assertEqual(list(Compute.objects.get(name="local").tags.values_list("name", flat=True)), ["lab"])
def test_the_hosts_list_shows_them(self):
compute = Compute.objects.create(name="kvm1", hostname="192.0.2.1", login="wvc", password="pw", type=1)
compute.tags.add(*(Tag.objects.create(name=name) for name in ("rack-1", "gpu", "ssd", "lab")))
response = self.client.get(reverse("computes"))
self.assertContains(response, 'data-show-tags title="ssd"') # three, and "…" for the others
self.assertContains(response, "rack-1")
self.assertContains(response, '<button type="button" class="nav-link py-1 px-2" data-pill="rack-1" '
'aria-pressed="false">rack-1 <span class="badge text-bg-light ms-1" data-count-tag="rack-1">1</span>'
'</button>',
html=True)
self.assertContains(response, 'data-tag-filter="rack-1"')
# a search and a tag that match no host: the page says so and clears them
self.assertContains(response, 'id="no-match"')
self.assertContains(response, 'id="clear-filters"')
self.assertContains(response, 'data-tags="gpu lab rack-1 ssd"')

View file

@ -6,7 +6,7 @@ from interfaces.views import interface, interfaces
from networks.views import network, networks
from nodedevs.views import nodedevs
from nwfilters.views import nwfilter, nwfilters
from storages.views import get_volumes, storage, storages
from storages.views import download_volume, get_volumes, storage, storages
from . import forms, views
@ -28,6 +28,7 @@ def superuser_only_patterns(patterns):
urlpatterns = [
path("", views.computes, name="computes"),
path("balance/", views.balance, name="balance"),
path(
"add_tcp_host/",
views.compute_create,
@ -59,13 +60,16 @@ urlpatterns = [
path("", views.overview, name="overview"),
path("update/", views.compute_update, name="compute_update"),
path("delete/", views.compute_delete, name="compute_delete"),
path("maintenance/", views.maintenance, name="compute_maintenance"),
path("statistics", views.compute_graph, name="compute_graph"),
path("capacity/", views.capacity, name="compute_capacity"),
path("instances/", views.instances, name="instances"),
path("bulk-migrate/", views.bulk_migrate, name="bulk_migrate"),
path("nodedevs/", nodedevs, name="nodedevs"),
path("storages/", storages, name="storages"),
path("storage/<str:pool>/volumes/", get_volumes, name="volumes"),
path("storage/<str:pool>/", storage, name="storage"),
path("storage/<str:pool>/download/<str:vol>", download_volume, name="download_volume"),
path("networks/", networks, name="networks"),
path("network/<str:pool>/", network, name="network"),
path("interfaces/", interfaces, name="interfaces"),

View file

@ -7,11 +7,12 @@ from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import connection, transaction
from django.utils import timezone
from computes.models import ENDPOINT, Compute
from computes.models import ENDPOINT, Compute, Tag
from instances.models import Instance, InstanceTombstone
from logs.audit import write
from operations import claims
from operations.models import Claim
from vmbackups.models import Backup, BackupPolicy, BackupRun
logger = logging.getLogger(__name__)
@ -86,7 +87,16 @@ def _log(inst, what):
def move_ownership(source, target):
"""Give target the owners and template flag of source; a user's rights are merged."""
"""Give target the owners, tags, template and protected flags, backups and schedules of source; a user's rights
are merged."""
target.tags.add(*source.tags.all())
Backup.objects.filter(instance=source).update(instance=target)
for policy in source.backup_policies.all():
policy.instances.add(target)
taken = set(BackupRun.objects.filter(instance=target).values_list("policy_id", "day"))
for run in BackupRun.objects.filter(instance=source): # a schedule's run of the day: not taken twice
if (run.policy_id, run.day) not in taken:
BackupRun.objects.filter(pk=run.pk).update(instance=target)
for ui in UserInstance.objects.filter(instance=source):
existing = UserInstance.objects.filter(instance=target, user=ui.user).first()
if existing is None:
@ -97,9 +107,11 @@ def move_ownership(source, target):
if getattr(ui, flag):
setattr(existing, flag, True)
existing.save()
if source.is_template and not target.is_template:
target.is_template = True
target.save(update_fields=["is_template"])
flags = [flag for flag in ("is_template", "protected") if getattr(source, flag) and not getattr(target, flag)]
for flag in flags:
setattr(target, flag, True)
if flags:
target.save(update_fields=flags)
def forget(inst):
@ -122,12 +134,16 @@ def _bury(inst):
{"user": ui.user_id, "is_change": ui.is_change, "is_delete": ui.is_delete, "is_vnc": ui.is_vnc}
for ui in UserInstance.objects.filter(instance=inst)
]
if owners or inst.is_template:
InstanceTombstone.objects.create(uuid=inst.uuid, name=inst.name, host=inst.compute.name,
is_template=inst.is_template, owners=owners)
_log(inst, "owners kept on the Removed VMs page")
tombstone = InstanceTombstone(uuid=inst.uuid, name=inst.name, host=inst.compute.name, is_template=inst.is_template,
protected=inst.protected, owners=owners,
tags=list(inst.tags.values_list("name", flat=True)),
policies=list(inst.backup_policies.values_list("pk", flat=True)),
backups=list(inst.backups.values_list("pk", flat=True)))
if tombstone.keeps_anything():
tombstone.save()
_log(inst, "kept on the Removed VMs page")
else:
_log(inst, "left the panel (no owners)")
_log(inst, "left the panel (nothing to keep)")
def _restore(inst):
@ -144,11 +160,14 @@ def _restore(inst):
is_delete=owner["is_delete"],
is_vnc=owner["is_vnc"],
)
if tombstone.is_template:
inst.is_template = True
inst.save(update_fields=["is_template"])
inst.tags.set(Tag.objects.filter(name__in=tombstone.tags))
# not a schedule that chooses its VMs by compute or tag since: it chooses this one, or not, by itself
inst.backup_policies.set(BackupPolicy.objects.filter(pk__in=tombstone.policies, compute=None, tag=None))
Backup.objects.filter(pk__in=tombstone.backups, instance__isnull=True).update(instance=inst)
inst.is_template, inst.protected = tombstone.is_template, tombstone.protected
inst.save(update_fields=["is_template", "protected"])
InstanceTombstone.objects.filter(uuid=inst.uuid).delete()
_log(inst, "owners restored")
_log(inst, "restored from the Removed VMs page")
def _host_domains(compute):
@ -173,6 +192,8 @@ def refresh_instance_database(compute):
UserInstance permission relationships (matched by UUID).
- If libvirt is unreachable (connection/network error), the database is left
untouched to avoid false deletions.
True when the database matches the host's VMs afterwards; None when it was
not synchronized (host not answering, busy or changed meanwhile).
"""
compute_pk = getattr(compute, "pk", getattr(compute, "id", None))
if not compute_pk:
@ -191,7 +212,7 @@ def refresh_instance_database(compute):
cutoff = timezone.now() - timedelta(days=retention)
if (dict(Instance.objects.filter(compute_id=compute_pk).values_list("uuid", "name")) == host_domains
and not InstanceTombstone.objects.filter(removed__lt=cutoff).exists()):
return
return True
try:
# The compute shared: VM operations and jobs on it go on; changes of
@ -249,6 +270,7 @@ def refresh_instance_database(compute):
)
if created and not Instance.objects.filter(uuid=uuid).exclude(compute=compute).exists():
_restore(inst)
return True
except claims.Busy:
logger.debug("Compute %s is busy; not synchronized now", compute_pk)
return

Some files were not shown because too many files have changed in this diff Show more