diff --git a/.dockerignore b/.dockerignore index 36da7ee2..b8bde8de 100644 --- a/.dockerignore +++ b/.dockerignore @@ -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 diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml new file mode 100644 index 00000000..a538ec52 --- /dev/null +++ b/.github/workflows/installer.yml @@ -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 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 68c4f092..fe8d3619 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -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' diff --git a/.gitignore b/.gitignore index bab099bf..2ade3823 100644 --- a/.gitignore +++ b/.gitignore @@ -12,8 +12,6 @@ test_db*.sqlite3* console/cert.pem* tags dhcpd.* -webvirtcloud/settings.py -/settings.py .coverage htmlcov *.log diff --git a/Dockerfile b/Dockerfile index 87defc3f..ae75b611 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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/ diff --git a/README.md b/README.md index afa5e95e..81088c85 100644 --- a/README.md +++ b/README.md @@ -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://`; 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 `` device, a ``) 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 `` device, a ``) 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 `` device, a ``) 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-`: 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 `. +- 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:///api/v1/instances/ ``` + The VM and compute lists (also a compute's VMs) take `?tag=`. + ### 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 ``` diff --git a/accounts/apps.py b/accounts/apps.py index 56925b7a..7ac5bf2b 100644 --- a/accounts/apps.py +++ b/accounts/apps.py @@ -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 diff --git a/accounts/checks.py b/accounts/checks.py index 88cd90de..50fb7fbc 100644 --- a/accounts/checks.py +++ b/accounts/checks.py @@ -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", ) diff --git a/accounts/forms.py b/accounts/forms.py index f7cb7a9d..cd4222e3 100644 --- a/accounts/forms.py +++ b/accounts/forms.py @@ -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 diff --git a/accounts/lockout.py b/accounts/lockout.py index 0e4720d5..84b8ae95 100644 --- a/accounts/lockout.py +++ b/accounts/lockout.py @@ -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)) diff --git a/accounts/migrations/0014_backup_quota.py b/accounts/migrations/0014_backup_quota.py new file mode 100644 index 00000000..03099e76 --- /dev/null +++ b/accounts/migrations/0014_backup_quota.py @@ -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)'), + ), + ] diff --git a/accounts/models.py b/accounts/models.py index 07e65862..6770720a 100644 --- a/accounts/models.py +++ b/accounts/models.py @@ -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 diff --git a/accounts/otp.py b/accounts/otp.py index fc95da79..694347cb 100644 --- a/accounts/otp.py +++ b/accounts/otp.py @@ -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 diff --git a/accounts/templates/account.html b/accounts/templates/account.html index 54ce99a0..e0e48bb4 100644 --- a/accounts/templates/account.html +++ b/accounts/templates/account.html @@ -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 %}
@@ -19,6 +19,7 @@ {% trans "Template editor" %} {% endif %} {% if not user.is_active %}{% trans "Blocked" %}{% endif %} + {% if locked %}{% trans "Sign-in locked" %}{% endif %}
{{ user.username }} @@ -32,6 +33,11 @@
{% bs_icon 'pencil' %} {% trans "Edit user" %} + {% if locked %} +
{% csrf_token %} + +
+ {% endif %} {% if otp_enabled %}
{% csrf_token %} @@ -48,8 +54,8 @@
@@ -66,6 +72,7 @@
{{ inst.instance.name }}
{% trans "Host" %}: {{ inst.instance.compute.name }}
+ {% include 'common/tag_badges.html' with tags=inst.instance.tags.all %}
{# the rights as the VM's Users tab names them: every owner powers the VM and opens its console #} @@ -92,12 +99,12 @@
-

{% trans "SSH Keys" %} {{ publickeys|length }}

+

{% trans "SSH keys" %} {{ publickeys|length }}

{% include "ssh_key_list.html" with owner=user %}
-

{% trans "API Tokens" %} {{ api_tokens|length }}

+

{% trans "API tokens" %} {{ api_tokens|length }}

{% include "api_token_list.html" with owner=user %}
{% endblock content %} diff --git a/accounts/templates/accounts/change_password_form.html b/accounts/templates/accounts/change_password_form.html index 6d3f2dae..f91d8802 100644 --- a/accounts/templates/accounts/change_password_form.html +++ b/accounts/templates/accounts/change_password_form.html @@ -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 #} diff --git a/accounts/templates/accounts/email_otp_form.html b/accounts/templates/accounts/email_otp_form.html index da7277f0..f7cb28ec 100644 --- a/accounts/templates/accounts/email_otp_form.html +++ b/accounts/templates/accounts/email_otp_form.html @@ -21,9 +21,9 @@
diff --git a/accounts/templates/accounts/otp_qr.html b/accounts/templates/accounts/otp_qr.html index 2ce7af43..538800c9 100644 --- a/accounts/templates/accounts/otp_qr.html +++ b/accounts/templates/accounts/otp_qr.html @@ -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 %}
diff --git a/accounts/templates/login.html b/accounts/templates/login.html index a9261a33..1aca143e 100644 --- a/accounts/templates/login.html +++ b/accounts/templates/login.html @@ -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 %}
@@ -12,9 +13,16 @@

WebVirtCloud

-

{% trans "Virtualization Management Console" %}

+

{% trans "Virtualization management console" %}

+ {% if app_settings.LOGIN_NOTICE %} +
+ +
{{ app_settings.LOGIN_NOTICE }}
+
+ {% endif %} + {% if form.errors %} @@ -36,25 +44,21 @@
- -
+
{% trans "Caps Lock is on" %}
- - -
- - KVM / Libvirt -
diff --git a/accounts/templates/profile.html b/accounts/templates/profile.html index 22a58a33..e26fd231 100644 --- a/accounts/templates/profile.html +++ b/accounts/templates/profile.html @@ -20,7 +20,7 @@ {% trans "Template editor" %} {% endif %} -
{{ user.username }}
+ {% if user.get_full_name %}
{{ user.username }}
{% endif %} {% if user.email %}
{{ user.email }}
{% endif %}
{% trans "Last login" %} {{ user.last_login|date:"Y-m-d H:i"|default:_("never") }}
@@ -32,7 +32,7 @@ {# an LDAP user's password is changed in LDAP #} {% if perms.accounts.change_password and user.has_usable_password %} {% endif %} @@ -41,9 +41,9 @@
-

{% trans "SSH Keys" %} {{ publickeys|length }}

+

{% trans "SSH keys" %} {{ publickeys|length }}

{% trans "Offered when you create a VM and on a VM's Access tab." %}
@@ -59,7 +59,7 @@
-

{% trans "API Tokens" %} {{ api_tokens|length }}

+

{% trans "API tokens" %} {{ api_tokens|length }}

diff --git a/accounts/tests/test_account_page.py b/accounts/tests/test_account_page.py index 66e52513..b34a69db 100644 --- a/accounts/tests/test_account_page.py +++ b/accounts/tests/test_account_page.py @@ -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") diff --git a/accounts/tests/test_checks.py b/accounts/tests/test_checks.py index a49cd916..240362e9 100644 --- a/accounts/tests/test_checks.py +++ b/accounts/tests/test_checks.py @@ -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"]) diff --git a/accounts/tests/test_login_page.py b/accounts/tests/test_login_page.py new file mode 100644 index 00000000..36b8e31b --- /dev/null +++ b/accounts/tests/test_login_page.py @@ -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("/", views.admin_reset_otp, name="admin_reset_otp"), + path("admin_unlock//", views.admin_unlock, name="admin_unlock"), ] if settings.OTP_ENABLED: diff --git a/accounts/utils.py b/accounts/utils.py index fc0e08cf..8a4a1b6e 100644 --- a/accounts/utils.py +++ b/accounts/utils.py @@ -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, diff --git a/accounts/views.py b/accounts/views.py index c04ffe65..681e3d9f 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -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): diff --git a/admin/forms.py b/admin/forms.py index a428b8e7..b43bafdf 100644 --- a/admin/forms.py +++ b/admin/forms.py @@ -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 diff --git a/admin/templates/admin/log_result.html b/admin/templates/admin/log_result.html new file mode 100644 index 00000000..5db8c402 --- /dev/null +++ b/admin/templates/admin/log_result.html @@ -0,0 +1,2 @@ +{% load i18n %}{# how a log row's action ended (logs.html) #} +{% if log.success is None %}{% trans "Unknown" %}{% elif log.success %}{% trans "Done" %}{% else %}{% trans "Failed" %}{% endif %} diff --git a/admin/templates/admin/logs.html b/admin/templates/admin/logs.html index d0103224..50d765a0 100644 --- a/admin/templates/admin/logs.html +++ b/admin/templates/admin/logs.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% load i18n %} +{% load static %} {% load django_bootstrap5 %} {% load bootstrap_icons %} @@ -15,7 +16,7 @@ {% block content %}
{# the search runs on the server over every row; the download takes the same rows #} -
- + {% if q or failed %}{% trans "Clear the filters" %}{% endif %} {% if not logs %}
@@ -32,29 +33,30 @@ {% else %}
+ {# on a phone: the date, who, which VM, and what, with how it ended under it #} - + - + - - + + {% for log in logs %} - - + + - + - - - + + + {% endfor %} @@ -64,3 +66,4 @@ {% if logs %}{% bootstrap_pagination logs extra=query pages_to_show=5 extra_classes="flex-wrap" %}{% endif %} {% endblock %} +{% block script %}{% endblock %} diff --git a/admin/templates/admin/tag_list.html b/admin/templates/admin/tag_list.html new file mode 100644 index 00000000..6922e3ce --- /dev/null +++ b/admin/templates/admin/tag_list.html @@ -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 %} +

{% 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." %}

+{% if not tags %} +

{% trans "No tags yet" %}

+{% else %} +
+
+ {% trans "Tags" %} {{ tags|length }} + +
+
+
## {% blocktrans %}Date ({{ time_zone }}){% endblocktrans %} {% trans "User" %}{% trans "Host" %}{% trans "Host" %} {% trans "Instance" %} {% trans "Message" %}{% trans "Result" %}{% trans "IP" %}{% trans "Result" %}{% trans "IP" %}
{{ log.id }}{{ log.date|date:"Y-m-d H:i:s" }}{{ log.id }}{{ log.date|date:"Y-m-d" }} {{ log.date|date:"H:i:s" }} {{ log.user }}{{ log.host }}{{ log.host }} {% if log.vm_pk %}{{ log.instance }}{% else %}{{ log.instance }}{% endif %}{{ log.message }}{% if log.success is None %}{% trans "Unknown" %}{% elif log.success %}{% trans "Done" %}{% else %}{% trans "Failed" %}{% endif %}{{ log.ip|default:"" }}{{ log.message }}
{% include "admin/log_result.html" %}
{% include "admin/log_result.html" %}{{ log.ip|default:"" }}
+ + + + + + + + + + {% for tag in tags %} + + + {# the VM list or the Computes page, showing the tag's only #} + + + + + {% endfor %} + +
{% trans "Tag" %}{% trans "VMs" %}{% trans "Hosts" %}{% trans "Actions" %}
{% include 'common/tag_badge.html' with tag=tag.name %}{% if tag.vm_count %}{{ tag.vm_count }}{% else %}0{% endif %}{% if tag.host_count %}{{ tag.host_count }}{% else %}0{% endif %} + {% trans "Rename" %} + {% trans "Delete" %} +
+
+
+ +
+
+{% endif %} +{% endblock content %} + +{% block script %} +{% if tags %}{% endif %} +{% endblock script %} diff --git a/admin/templates/admin/tombstone_list.html b/admin/templates/admin/tombstone_list.html index b43d6929..20e71aed 100644 --- a/admin/templates/admin/tombstone_list.html +++ b/admin/templates/admin/tombstone_list.html @@ -8,11 +8,9 @@ {% block page_heading %}{% trans "Removed VMs" %}{% endblock page_heading %} {% block content %} -

{% trans "VMs that vanished from their compute. Their owners come back if the same UUID shows up again before the record expires." %}

+

{% 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." %}

{% if not tombstones %} -
- {% bs_icon 'info-circle' %} {% trans "No removed VMs" %} -
+

{% trans "No removed VMs" %}

{% else %}
@@ -21,11 +19,13 @@
{% for tombstone in tombstones %} -
+
{{ tombstone.name }} {% if tombstone.is_template %}{% trans "Template" %}{% endif %} + {% if tombstone.protected %}{% trans "Protected" %}{% endif %} + {% include 'common/tag_badges.html' with tags=tombstone.tags %}
{{ tombstone.uuid }}
@@ -33,6 +33,12 @@ {% trans "Left" %} {{ tombstone.host }} · {% trans "Owners" %}: {{ tombstone.owner_names|join:", "|default:"–" }}
+ {% if tombstone.policy_names or tombstone.backup_count %} +
+ {% if tombstone.policy_names %}{% trans "Schedules" %}: {{ 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 %} +
+ {% endif %}
{% trans "Removed" %} {{ tombstone.removed|date:"Y-m-d H:i" }} · {% trans "expires" %} {{ tombstone.expires|date:"Y-m-d H:i" }} diff --git a/admin/templates/admin/user_list.html b/admin/templates/admin/user_list.html index 61810df9..298cc700 100644 --- a/admin/templates/admin/user_list.html +++ b/admin/templates/admin/user_list.html @@ -21,7 +21,7 @@
{% for user in users %} -
+
{{ user.username }} @@ -38,6 +38,9 @@ {% else %} {% trans "Blocked" %} {% endif %} + {% if user.username|lower in locked %} + {% trans "Sign-in locked" %} + {% endif %}
@@ -65,7 +68,8 @@
  • {% bs_icon 'person' %} {% trans "View profile" %}
  • {# an administrator does not block or delete their own account #}
  • {% csrf_token %} -
  • diff --git a/admin/templates/admin/user_password_form.html b/admin/templates/admin/user_password_form.html index d1c12b8f..1f58d58d 100644 --- a/admin/templates/admin/user_password_form.html +++ b/admin/templates/admin/user_password_form.html @@ -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) #} diff --git a/admin/tests/test_audit_rows.py b/admin/tests/test_audit_rows.py index 190d704a..91cc2e23 100644 --- a/admin/tests/test_audit_rows.py +++ b/admin/tests/test_audit_rows.py @@ -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(): diff --git a/admin/tests/test_logs_page.py b/admin/tests/test_logs_page.py index d371da17..08afa871 100644 --- a/admin/tests/test_logs_page.py +++ b/admin/tests/test_logs_page.py @@ -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() diff --git a/admin/tests/test_tags.py b/admin/tests/test_tags.py new file mode 100644 index 00000000..c722aaee --- /dev/null +++ b/admin/tests/test_tags.py @@ -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") diff --git a/admin/tests/test_tombstones.py b/admin/tests/test_tombstones.py index cce11668..d86c2205 100644 --- a/admin/tests/test_tombstones.py +++ b/admin/tests/test_tombstones.py @@ -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, 'ts-host', 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): diff --git a/admin/tests/test_user_create.py b/admin/tests/test_user_create.py index d6258d3b..91db210d 100644 --- a/admin/tests/test_user_create.py +++ b/admin/tests/test_user_create.py @@ -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): diff --git a/admin/tests/test_user_pages.py b/admin/tests/test_user_pages.py index f59609ea..ada50a1e 100644 --- a/admin/tests/test_user_pages.py +++ b/admin/tests/test_user_pages.py @@ -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()) diff --git a/admin/tests/test_user_update_next.py b/admin/tests/test_user_update_next.py index d6d25033..8480a35d 100644 --- a/admin/tests/test_user_update_next.py +++ b/admin/tests/test_user_update_next.py @@ -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): diff --git a/admin/tests/test_views.py b/admin/tests/test_views.py index 4fdec63f..9ab73342 100644 --- a/admin/tests/test_views.py +++ b/admin/tests/test_views.py @@ -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")) diff --git a/admin/urls.py b/admin/urls.py index c0ce1fe1..2af4cd73 100644 --- a/admin/urls.py +++ b/admin/urls.py @@ -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//delete/", views.tombstone_delete, name="tombstone_delete"), + path("tags/", views.tag_list, name="tag_list"), + path("tags//update/", views.tag_update, name="tag_update"), + path("tags//delete/", views.tag_delete, name="tag_delete"), ] diff --git a/admin/views.py b/admin/views.py index 5fd8c619..29c9822f 100644 --- a/admin/views.py +++ b/admin/views.py @@ -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}}, + }) diff --git a/appsettings/management/commands/backup.py b/appsettings/management/commands/backup.py index a8a8d6d1..8229a67e 100644 --- a/appsettings/management/commands/backup.py +++ b/appsettings/management/commands/backup.py @@ -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" diff --git a/appsettings/migrations/0027_alert_settings.py b/appsettings/migrations/0027_alert_settings.py new file mode 100644 index 00000000..205254b0 --- /dev/null +++ b/appsettings/migrations/0027_alert_settings.py @@ -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), + ] diff --git a/appsettings/migrations/0028_migration_bandwidth.py b/appsettings/migrations/0028_migration_bandwidth.py new file mode 100644 index 00000000..78e2c313 --- /dev/null +++ b/appsettings/migrations/0028_migration_bandwidth.py @@ -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)] diff --git a/appsettings/migrations/0029_login_notice.py b/appsettings/migrations/0029_login_notice.py new file mode 100644 index 00000000..de535ad2 --- /dev/null +++ b/appsettings/migrations/0029_login_notice.py @@ -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)] diff --git a/appsettings/migrations/0030_login_session_hours.py b/appsettings/migrations/0030_login_session_hours.py new file mode 100644 index 00000000..2e0dc538 --- /dev/null +++ b/appsettings/migrations/0030_login_session_hours.py @@ -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)] diff --git a/appsettings/models.py b/appsettings/models.py index 0cfb4e70..aa09021d 100644 --- a/appsettings/models.py +++ b/appsettings/models.py @@ -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) diff --git a/appsettings/settings.py b/appsettings/settings.py index c14fc3ab..f8c4c0ab 100644 --- a/appsettings/settings.py +++ b/appsettings/settings.py @@ -1,4 +1,4 @@ -from django.db import DatabaseError +from django.db import Error as DatabaseError from .models import AppSettings diff --git a/appsettings/templates/appsettings.html b/appsettings/templates/appsettings.html index 880ddcf0..2eec4ff9 100644 --- a/appsettings/templates/appsettings.html +++ b/appsettings/templates/appsettings.html @@ -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 %} {% endblock style %} {% block content %}
    -
    +
    diff --git a/appsettings/tests/test_appsettings.py b/appsettings/tests/test_appsettings.py index f1c5eb9f..c6474b40 100644 --- a/appsettings/tests/test_appsettings.py +++ b/appsettings/tests/test_appsettings.py @@ -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): diff --git a/appsettings/tests/test_backup.py b/appsettings/tests/test_backup.py index 4a6790a3..a8f23c93 100644 --- a/appsettings/tests/test_backup.py +++ b/appsettings/tests/test_backup.py @@ -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") diff --git a/appsettings/tests/test_migrations.py b/appsettings/tests/test_migrations.py index 0777e8cb..93da3bbe 100644 --- a/appsettings/tests/test_migrations.py +++ b/appsettings/tests/test_migrations.py @@ -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") diff --git a/appsettings/views.py b/appsettings/views.py index dabf62d5..1be7f671 100644 --- a/appsettings/views.py +++ b/appsettings/views.py @@ -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(): diff --git a/computes/api/serializers.py b/computes/api/serializers.py index 6cdd04f9..d4a74582 100644 --- a/computes/api/serializers.py +++ b/computes/api/serializers.py @@ -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"] diff --git a/computes/api/viewsets.py b/computes/api/viewsets.py index 8e90e07a..55b015ff 100644 --- a/computes/api/viewsets.py +++ b/computes/api/viewsets.py @@ -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(): diff --git a/computes/balance.py b/computes/balance.py new file mode 100644 index 00000000..11d0ba9b --- /dev/null +++ b/computes/balance.py @@ -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 diff --git a/computes/forms.py b/computes/forms.py index deeea929..c533b935 100644 --- a/computes/forms.py +++ b/computes/forms.py @@ -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"] diff --git a/computes/jobs.py b/computes/jobs.py new file mode 100644 index 00000000..4e7fc261 --- /dev/null +++ b/computes/jobs.py @@ -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})" diff --git a/computes/migrations/0010_maintenance.py b/computes/migrations/0010_maintenance.py new file mode 100644 index 00000000..128bfc80 --- /dev/null +++ b/computes/migrations/0010_maintenance.py @@ -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), + ), + ] diff --git a/computes/migrations/0011_maintenance_since.py b/computes/migrations/0011_maintenance_since.py new file mode 100644 index 00000000..38f9d38f --- /dev/null +++ b/computes/migrations/0011_maintenance_since.py @@ -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", + ), + ] diff --git a/computes/migrations/0012_tags.py b/computes/migrations/0012_tags.py new file mode 100644 index 00000000..ef98e531 --- /dev/null +++ b/computes/migrations/0012_tags.py @@ -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'), + ), + ] diff --git a/computes/migrations/0013_tag_length.py b/computes/migrations/0013_tag_length.py new file mode 100644 index 00000000..79c8732f --- /dev/null +++ b/computes/migrations/0013_tag_length.py @@ -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'), + ), + ] diff --git a/computes/migrations/0014_migration_tls.py b/computes/migrations/0014_migration_tls.py new file mode 100644 index 00000000..e3eae75f --- /dev/null +++ b/computes/migrations/0014_migration_tls.py @@ -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)'), + ), + ] diff --git a/computes/models.py b/computes/models.py index 6254d913..21c0e03a 100644 --- a/computes/models.py +++ b/computes/models.py @@ -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 diff --git a/computes/reach.py b/computes/reach.py new file mode 100644 index 00000000..110df1ce --- /dev/null +++ b/computes/reach.py @@ -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 diff --git a/computes/templates/computes/attention.html b/computes/templates/computes/attention.html new file mode 100644 index 00000000..88e03ca3 --- /dev/null +++ b/computes/templates/computes/attention.html @@ -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 %} +
    +

    {% bs_icon 'exclamation-triangle' %} {% trans "Needs attention" %}

    + +
    +{% endif %} diff --git a/computes/templates/computes/balance.html b/computes/templates/computes/balance.html new file mode 100644 index 00000000..7afb6e99 --- /dev/null +++ b/computes/templates/computes/balance.html @@ -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 %} + +

    {% trans "Balance" %}

    +

    {% 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." %}

    +{% if unreachable %} +
    {% trans "These hosts cannot be read and are left out:" %} {{ unreachable|join:", " }}
    +{% endif %} +{% if resting %} +
    {% trans "These hosts are in maintenance and are left out:" %} {{ resting|join:", " }}
    +{% endif %} + +{# each host's running VMs: the share of its memory now and, light to dark, after the migrations #} +
    + {% for host in hosts %} +
    +
    +
    {{ host.name }} + {% widthratio host.size.0 1 1024 as bytes %}{{ bytes|binary_size }}
    + {% for bar in host.bars %}{% if forloop.first or moves %} + {% if forloop.first %}{% with memory=host.before.0 vcpus=host.before.1 %} +
    {% if moves %}{% trans "Now" %}{% else %}{% trans "Running VMs" %}{% endif %} + {% 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 %}
    + {% endwith %}{% else %}{% with memory=host.after.0 vcpus=host.after.1 %} +
    {% trans "After" %} + {% 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 %}
    + {% endwith %}{% endif %} +
    +
    +
    + {% endif %}{% endfor %} +
    +
    + {% endfor %} +
    + +{# unticking a VM keeps it where it is and makes the proposal again #} +
    + {% for instance in moves %}{% endfor %} + {% for instance in pinned %}{% endfor %} +
    +{% if moves %} +
    {% csrf_token %}{% submission_key %} +
    {% blocktrans count counter=moves|length %}Proposed migration ({{ counter }}){% plural %}Proposed migrations ({{ counter }}){% endblocktrans %}
    +
    + + + + + + + + + + + + {% for instance in moves %} + + + + + + + + {% endfor %} + +
    {% trans "Name" %}{% trans "Memory" %}vCPU{% trans "Migration" %}
    + + + {% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|binary_size }}{{ instance.info.3 }}{{ instance.compute.name }} {% bs_icon 'arrow-right' %} {{ instance.target.name }}
    +
    + +
    +{% else %} +
    {% trans "The hosts are balanced: no migration would even them out more." %}
    +{% endif %} + +{% if pinned or unmovable %} +
    +
    {% trans "Stay where they are" %}
    +
    + + + + + + + + + + + {% for instance in pinned %} + + + + + + + {% endfor %} + {% for instance in unmovable %} + + + + + + + {% endfor %} + +
    {% trans "Let it move" %}{% trans "Name" %}{% trans "Host" %}{% trans "Why" %}
    {{ instance.compute.name }}{% trans "You kept it here: tick it to let it move" %}
    {{ instance.name }}{{ instance.compute.name }}{% for refusal in instance.refusals %}{{ refusal }}{% if not forloop.last %}
    {% endif %}{% endfor %}
    +
    +
    +{% endif %} +{% endblock %} +{% block script %} + +{% endblock %} diff --git a/computes/templates/computes/bulk_migrate.html b/computes/templates/computes/bulk_migrate.html new file mode 100644 index 00000000..438b6085 --- /dev/null +++ b/computes/templates/computes/bulk_migrate.html @@ -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 %} +
    +
    + {% include "computes/host_nav.html" with section="instances" detail=True %} +
    +
    +{% if entering %} +{# asked from "Put in maintenance": the host goes in maintenance with its VMs' migration, or without one #} +
    +
    {% 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 %}
    +
    {% csrf_token %} + + +
    +
    +{% endif %} +{% if not targets %} +
    {% trans "There is no other host to migrate to." %}
    +{% else %} +

    {% 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." %}

    +{% if unreachable %} +
    {% trans "These hosts cannot be read and are left out:" %} {{ unreachable|join:", " }}
    +{% endif %} +{# another destination reloads the list: which VMs can go depends on it; spread over the hosts, so does a VM ticked #} +
    + {% if entering %}{% endif %} + {% if spreading %}{% for instance in instances %}{% if not instance.refusal %}{% endif %}{% endfor %}{% endif %} +
    +{% if not parallel %} +
    {% trans "The worker runs one job at a time: set Worker Concurrency to 2 or more on the Settings page." %}
    +{% elif not instances %} +

    {% trans "The host has no VMs." %}

    +{% else %} +
    {% csrf_token %}{% submission_key %} + {% if entering %}{% endif %} + {% if spreading %}{% else %}{% endif %} +
    + {{ compute.name }} {% bs_icon 'arrow-right' %} + {% if targets|length > 1 %} + + {% else %} + {{ target.name }} + {% endif %} + {% if tags %}{# bulk_migrate.js ticks the VMs with the tag chosen #} + + {% endif %} +
    + + +
    +
    +
    + + + + + + + + + {% if spreading %}{% endif %} + + + + + {% for instance in instances %} + + + + + + + {% if spreading %}{% endif %} + + + {% endfor %} + +
    {% trans "Name" %}{% trans "Status" %}{% trans "Memory" %}vCPU{% trans "Destination" %}{% trans "Why" %}
    + {% if spreading %} + + {% if instance.target %}{% endif %} + {% else %} + + {% endif %} + {% include 'instance_state.html' %}{% if instance.info %}{% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|binary_size }}{% endif %}{{ instance.info.3 }}{{ instance.target.name|default:"" }}{{ instance.refusal|default:"" }}{{ instance.note|default:"" }}
    +
    + {# kept in sight below a long list #} + +
    +{% endif %} +{% endif %} +{% endblock %} +{% block script %} + +{% endblock %} diff --git a/computes/templates/computes/capacity_line.txt b/computes/templates/computes/capacity_line.txt index 06a794be..6000c0be 100644 --- a/computes/templates/computes/capacity_line.txt +++ b/computes/templates/computes/capacity_line.txt @@ -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 %} diff --git a/computes/templates/computes/capacity_memory.html b/computes/templates/computes/capacity_memory.html index 03d121fa..cec4f448 100644 --- a/computes/templates/computes/capacity_memory.html +++ b/computes/templates/computes/capacity_memory.html @@ -1,18 +1,19 @@ {% load i18n %} +{% load common_tags %} {# the memory a host has given its VMs: given, from views.shown_capacity #} -
    {{ given.memory_percent }} %
    -
    {{ given.assigned.all|filesizeformat }} / {{ given.memory|filesizeformat }}
    +
    {{ given.memory_percent|percent }}
    +
    {{ given.assigned.all|binary_size }} / {{ given.memory|binary_size }}
    {# running VMs' memory, then shut-off VMs', on a scale that holds the host's memory or all given, whichever is larger #}
    + aria-valuetext="{% blocktrans with running=given.assigned.running|binary_size memory=given.memory|binary_size %}{{ running }} 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 %}">
    -
    {% blocktrans with running=given.assigned.running|filesizeformat %}{{ running }} running{% endblocktrans %}
    +
    {% blocktrans with running=given.assigned.running|binary_size %}{{ running }} in running VMs{% endblocktrans %}
    diff --git a/computes/templates/computes/capacity_vcpus.html b/computes/templates/computes/capacity_vcpus.html index f49174bf..e8802210 100644 --- a/computes/templates/computes/capacity_vcpus.html +++ b/computes/templates/computes/capacity_vcpus.html @@ -15,4 +15,4 @@
    -
    {% blocktrans with running=given.vcpus.running %}{{ running }} running{% endblocktrans %}
    +
    {% blocktrans with running=given.vcpus.running %}{{ running }} in running VMs{% endblocktrans %}
    diff --git a/computes/templates/computes/form.html b/computes/templates/computes/form.html index 2b6f9713..35940a22 100644 --- a/computes/templates/computes/form.html +++ b/computes/templates/computes/form.html @@ -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 @@ {{ form.kind }} {% endblock page_heading %} +{% block style %}{% endblock %} + {% block content %}

    {{ form.about }}

    @@ -24,18 +27,24 @@ {% if "login" in form.fields %}
    {% bootstrap_field form.login %}
    {% endif %} {% if "password" in form.fields %}
    {% bootstrap_field form.password %}
    {% endif %}
    {% bootstrap_field form.details %}
    +
    {% 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 %}{% endfor %} +
    {# open when one of them is set or refused #} -
    +
    {% trans "Advanced" %} {% trans "Migration address" %}: {{ form.migration_address.value|default:_("the host name") }} + {% if form.migration_tls.value %}· {% trans "migrations over TLS" %}{% endif %} · {% trans "gstfsd key" %}: {% if form.instance.gstfsd_key %}{% trans "stored" %}{% else %}{% trans "none" %}{% endif %}
    {% bootstrap_field form.migration_address %} + {% bootstrap_field form.migration_tls %} {% bootstrap_field form.gstfsd_key %}
    @@ -47,3 +56,7 @@ {% endblock content %} +{% block script %} + + +{% endblock script %} diff --git a/computes/templates/computes/host_nav.html b/computes/templates/computes/host_nav.html index daee1973..c6a2fd2b 100644 --- a/computes/templates/computes/host_nav.html +++ b/computes/templates/computes/host_nav.html @@ -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 #}