From abc819294cab7dd62ba5659d5626bb3a892126e6 Mon Sep 17 00:00:00 2001 From: Dilshod Rasulov Date: Sat, 22 Aug 2026 14:03:49 +0500 Subject: [PATCH] fix(images): unblock guest-exec in RHEL-family cloud images The RHEL-family qemu-guest-agent package starts the agent with an allow-list that omits guest-exec, guest-exec-status and guest-file-* (FILTER_RPC_ARGS in /etc/sysconfig/qemu-ga; older packages spelled the same restriction as BLOCK_RPCS or BLACKLIST_RPC). The agent answered "The command guest-exec has been disabled for this instance", so running scripts in a VM, assigning extra IP addresses and growing the filesystem after a disk resize did not work on Rocky Linux, AlmaLinux, CentOS Stream and Fedora guests. - patch-cloud-images.sh: clear all three variants while building the mirror (UNBLOCK_RPC=0 opts out) and add an ONLY filter to rebuild only part of the catalog. Three `[ ... ] && ...` statements that aborted the script under set -e are now plain ifs -- the one before mirrors.json generation killed every run that passed BASE_URL - builtin.py: point the five RHEL-family amd64 entries at the rebuilt mirror release 2026-08-22 with their new checksums. Ubuntu and Debian images are unaffected and stay in the previous releases, so older panel versions keep working - client.py: annotate the Proxmox error with what to clear inside the guest, the raw message names neither the file nor the variable - WIKI, CHANGELOG: document the restriction and the unblock command --- CHANGELOG.md | 10 ++++ CHANGELOG.ru.md | 10 ++++ WIKI.md | 18 ++++-- WIKI.ru.md | 18 ++++-- backend/app/catalog/builtin.py | 27 +++++---- backend/app/proxmox/client.py | 25 +++++++- backend/tests/test_container_interfaces.py | 31 ++++++++++ patch-cloud-images.sh | 68 ++++++++++++++++++++-- 8 files changed, 179 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c5f29b..3483758 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ All notable changes to PVEmanager will be documented in this file. --- +## [Unreleased] + +### 🐛 Fixes + +- **`guest-exec` is unblocked in the Rocky Linux, AlmaLinux, CentOS Stream and Fedora images** — the RHEL-family `qemu-guest-agent` package runs the agent with an allow-list that omits `guest-exec`, `guest-exec-status` and `guest-file-*` (`FILTER_RPC_ARGS` in `/etc/sysconfig/qemu-ga`; older packages expressed the same thing through `BLOCK_RPCS`/`BLACKLIST_RPC`). Because of it, script execution, extra IP addresses and filesystem growth after a disk resize did not work in such VMs +- **Five mirror images were rebuilt** — release `2026-08-22`, and the bundled catalog now points at it; Ubuntu and Debian are untouched and stay in the previous releases, so older panel versions keep working +- **`patch-cloud-images.sh` clears the restriction while building** (turn it off with `UNBLOCK_RPC=0`) and can build part of the catalog — `ONLY="rocky alma centos fedora"`. And when the panel hits the block, it spells out what to fix inside the guest + +--- + ## [v1.18.0] - 2026-08-22 ### 🌐 Several IP addresses per instance diff --git a/CHANGELOG.ru.md b/CHANGELOG.ru.md index 47e2364..7dc9ec2 100644 --- a/CHANGELOG.ru.md +++ b/CHANGELOG.ru.md @@ -4,6 +4,16 @@ --- +## [Unreleased] + +### 🐛 Исправления + +- **В образах Rocky Linux, AlmaLinux, CentOS Stream и Fedora разблокирован `guest-exec`** — пакет `qemu-guest-agent` в RHEL-семействе запускает агента с allow-list, в котором нет `guest-exec`, `guest-exec-status` и `guest-file-*` (`FILTER_RPC_ARGS` в `/etc/sysconfig/qemu-ga`; в пакетах постарше то же самое задавалось через `BLOCK_RPCS`/`BLACKLIST_RPC`). Из-за этого в таких ВМ не работали выполнение скриптов, выдача дополнительных IP и расширение ФС после ресайза диска +- **Пять образов зеркала пересобраны** — релиз `2026-08-22`, встроенный каталог переключён на него; Ubuntu и Debian не затронуты и остаются в прежних релизах, поэтому старые версии панели продолжают работать +- **`patch-cloud-images.sh` снимает ограничение при сборке** (отключается через `UNBLOCK_RPC=0`) и умеет собирать часть каталога — `ONLY="rocky alma centos fedora"`. Панель же, наткнувшись на запрет, объясняет в тексте ошибки, что и где поправить в госте + +--- + ## [v1.18.0] - 2026-08-22 ### 🌐 Несколько IP-адресов на инстанс diff --git a/WIKI.md b/WIKI.md index 8ef3650..861519a 100644 --- a/WIKI.md +++ b/WIKI.md @@ -739,6 +739,7 @@ Either action that changes boot order applies it via a **hybrid reboot**: a grac The bundled amd64 image catalog points to a **GitHub mirror** that contains cloud images pre-patched with `qemu-guest-agent`. This means: - Live per-VM metrics (CPU, memory, disk fill, I/O rates) work immediately after deploy — no post-install agent setup needed +- RHEL-family images (Rocky Linux, AlmaLinux, CentOS Stream, Fedora) get their RPC restriction cleared: the stock `qemu-guest-agent` package there runs the agent with an allow-list that omits `guest-exec`, `guest-exec-status` and `guest-file-*` (`FILTER_RPC_ARGS` in `/etc/sysconfig/qemu-ga`), which broke script execution, extra IP addresses and filesystem growth after a disk resize in such VMs - Images include a **sha256 checksum** for integrity verification; if the cached file no longer matches the published checksum, the panel re-downloads it automatically To rebuild or update the mirror yourself, run the included helper script on a Linux host with QEMU installed: @@ -747,7 +748,7 @@ To rebuild or update the mirror yourself, run the included helper script on a Li bash patch-cloud-images.sh ``` -It downloads the upstream `.qcow2`, installs `qemu-guest-agent` via `virt-customize`, and publishes the patched image as a GitHub Release. +It downloads the upstream `.qcow2`, installs `qemu-guest-agent` via `virt-customize`, clears the RPC blocklist (turn it off with `UNBLOCK_RPC=0`), and publishes the patched image as a GitHub Release. ### Custom Mirrors (Admin Only) @@ -1187,7 +1188,7 @@ The primary address is not releasable from this card — it belongs to the NIC c The address is brought up with `ip addr add` and the guest's networking is **never restarted**, so a running guest keeps its connectivity. Delivery reuses the script engine: - **LXC** — `pct exec` over SSH to the node (needs the server password or an SSH key for `root@node`) -- **QEMU** — the guest agent, which must allow `guest-exec` (some images ship with it blocked in `/etc/sysconfig/qemu-ga` or `/etc/default/qemu-guest-agent`) +- **QEMU** — the guest agent, which must allow `guest-exec` (some images ship with it blocked in `/etc/sysconfig/qemu-ga` or `/etc/default/qemu-guest-agent`, see [Installing Guest Agent](#installing-guest-agent); the bundled catalog images already have it unblocked) Proxmox regenerates the guest network configuration on **every start** of a guest, wiping anything written into the native stack. To make an address survive a reboot, PVEmanager installs a small oneshot systemd unit (`pvemanager-aliases.service`) that re-adds the recorded addresses after `network-online.target`; `/etc/systemd` is not touched by Proxmox. The native stack is configured as well when it is recognised — ifupdown, netplan, NetworkManager or sysconfig/network-scripts for RHEL-based guests. @@ -1227,12 +1228,21 @@ apt install qemu-guest-agent systemctl enable --now qemu-guest-agent ``` -**CentOS/RHEL/AlmaLinux:** +**CentOS/RHEL/AlmaLinux/Rocky/Fedora:** ```bash -yum install qemu-guest-agent +dnf install qemu-guest-agent systemctl enable --now qemu-guest-agent ``` +On these distributions the agent blocks `guest-exec` by default — the panel gets `The command guest-exec has been disabled for this instance`, and command execution, extra IP addresses and filesystem growth stop working. To unblock: + +```bash +sed -i -e 's/^FILTER_RPC_ARGS=.*/FILTER_RPC_ARGS=/' -e 's/^BLACKLIST_RPC=.*/BLACKLIST_RPC=/' -e 's/^BLOCK_RPCS=.*/BLOCK_RPCS=/' /etc/sysconfig/qemu-ga +systemctl restart qemu-guest-agent +``` + +The layout of `/etc/sysconfig/qemu-ga` changed across releases, so the command clears all three variants: `FILTER_RPC_ARGS` (current packages — an allow-list that simply omits `guest-exec`), `BLOCK_RPCS` (qemu-ga 8.1+) and `BLACKLIST_RPC` (before 8.1). An empty value means no restrictions at all, the same as on Debian/Ubuntu where no filter is configured; lines that do not exist are left alone. + **Windows:** Download [virtio-win drivers](https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/) diff --git a/WIKI.ru.md b/WIKI.ru.md index 6e6f030..cd10986 100644 --- a/WIKI.ru.md +++ b/WIKI.ru.md @@ -738,6 +738,7 @@ RAM: 512 МБ – 128 ГБ Встроенный каталог образов amd64 ссылается на **GitHub-зеркало**, содержащее облачные образы с предустановленным `qemu-guest-agent`. Это даёт: - Живые метрики на ВМ (CPU, память, заполнение диска, скорости I/O) сразу после деплоя — дополнительная установка агента не нужна +- В образах RHEL-семейства (Rocky Linux, AlmaLinux, CentOS Stream, Fedora) снято штатное ограничение RPC: пакет `qemu-guest-agent` там оставляет агенту allow-list без `guest-exec`, `guest-exec-status` и `guest-file-*` (`FILTER_RPC_ARGS` в `/etc/sysconfig/qemu-ga`), из-за чего в таких ВМ не работали выполнение скриптов, дополнительные IP-адреса и расширение ФС после ресайза диска - Образы включают контрольную сумму **sha256**; если закешированный файл не совпадает с опубликованной суммой, панель скачает его повторно автоматически Чтобы собрать или обновить зеркало самостоятельно, запустите вспомогательный скрипт на Linux-хосте с установленным QEMU: @@ -746,7 +747,7 @@ RAM: 512 МБ – 128 ГБ bash patch-cloud-images.sh ``` -Скрипт скачивает исходный `.qcow2`, устанавливает `qemu-guest-agent` через `virt-customize` и публикует патченный образ как GitHub Release. +Скрипт скачивает исходный `.qcow2`, устанавливает `qemu-guest-agent` через `virt-customize`, снимает блокировку RPC (отключается через `UNBLOCK_RPC=0`) и публикует патченный образ как GitHub Release. ### Кастомные зеркала (только админ) @@ -1186,7 +1187,7 @@ End: 192.168.1.50 Адрес поднимается командой `ip addr add`, сеть гостя при этом **не перезапускается**, поэтому работающий гость не теряет связь. Доставка использует тот же движок скриптов, что и раздел Scripts: - **LXC** — `pct exec` по SSH к ноде (нужен пароль сервера либо SSH-ключ для `root@node`) -- **QEMU** — guest agent, в котором должен быть разрешён `guest-exec` (в некоторых образах он заблокирован в `/etc/sysconfig/qemu-ga` или `/etc/default/qemu-guest-agent`) +- **QEMU** — guest agent, в котором должен быть разрешён `guest-exec` (в некоторых образах он заблокирован в `/etc/sysconfig/qemu-ga` или `/etc/default/qemu-guest-agent`, см. [Установка Guest Agent](#установка-guest-agent); в образах встроенного каталога блокировка уже снята) Proxmox пересоздаёт сетевую конфигурацию гостя при **каждом старте**, стирая всё, что было записано в родной стек. Чтобы адрес пережил перезагрузку, PVEmanager устанавливает небольшой oneshot systemd-юнит (`pvemanager-aliases.service`), который заново поднимает записанные адреса после `network-online.target`; каталог `/etc/systemd` Proxmox не трогает. Родной стек настраивается дополнительно, если он распознан — ifupdown, netplan, NetworkManager или sysconfig/network-scripts для RHEL-подобных гостей. @@ -1226,12 +1227,21 @@ apt install qemu-guest-agent systemctl enable --now qemu-guest-agent ``` -**CentOS/RHEL/AlmaLinux:** +**CentOS/RHEL/AlmaLinux/Rocky/Fedora:** ```bash -yum install qemu-guest-agent +dnf install qemu-guest-agent systemctl enable --now qemu-guest-agent ``` +В этих дистрибутивах агент по умолчанию запрещает `guest-exec` — панель получает `The command guest-exec has been disabled for this instance`, и выполнение команд, выдача дополнительных IP и расширение ФС не работают. Разблокировать: + +```bash +sed -i -e 's/^FILTER_RPC_ARGS=.*/FILTER_RPC_ARGS=/' -e 's/^BLACKLIST_RPC=.*/BLACKLIST_RPC=/' -e 's/^BLOCK_RPCS=.*/BLOCK_RPCS=/' /etc/sysconfig/qemu-ga +systemctl restart qemu-guest-agent +``` + +Разметка `/etc/sysconfig/qemu-ga` менялась от версии к версии, поэтому команда чистит все три варианта: `FILTER_RPC_ARGS` (актуальные пакеты — allow-list, в котором `guest-exec` просто отсутствует), `BLOCK_RPCS` (qemu-ga 8.1+) и `BLACKLIST_RPC` (до 8.1). Пустое значение = агент без ограничений, как в Debian/Ubuntu, где фильтра нет вовсе; отсутствующие строки sed просто не найдёт. + **Windows:** Скачайте [virtio-win drivers](https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/) diff --git a/backend/app/catalog/builtin.py b/backend/app/catalog/builtin.py index ac88736..9c33a61 100644 --- a/backend/app/catalog/builtin.py +++ b/backend/app/catalog/builtin.py @@ -2,8 +2,10 @@ Встроенный curated-каталог cloud-образов ВМ (qcow2). amd64-образы берутся с собственного GitHub-зеркала (markmorado/pvemanager-images) -с предустановленным qemu-guest-agent и фиксированным sha256. arm64-образы идут -напрямую с upstream-серверов дистрибутивов (патченых arm64-версий нет). +с предустановленным qemu-guest-agent и фиксированным sha256; у RHEL-семейства +там же снято штатное ограничение RPC, иначе агент отказывает в guest-exec (см. +patch-cloud-images.sh). arm64-образы идут напрямую с upstream-серверов +дистрибутивов (патченых arm64-версий нет). LXC-шаблоны (vztmpl) здесь НЕ хардкодятся: их список берётся динамически из репозитория Proxmox (aplinfo), плюс произвольные vztmpl-зеркала из ImageMirror. @@ -16,6 +18,7 @@ from typing import Dict, List, Optional, Tuple _GH = 'https://github.com/markmorado/pvemanager-images/releases/download/2026-08-14' _GH2 = 'https://github.com/markmorado/pvemanager-images/releases/download/2026-08-18' +_GH3 = 'https://github.com/markmorado/pvemanager-images/releases/download/2026-08-22' # (id_base, os, version, name, icon, {arch: (url, checksum_or_None)}) # amd64 → собственное GitHub-зеркало + sha256; arm64 → upstream без checksum @@ -55,32 +58,32 @@ _CLOUD_IMAGES = [ ( 'rocky-9-cloud', 'rocky', '9', 'Rocky Linux 9 GenericCloud', 'rocky', { - 'amd64': (f'{_GH}/Rocky-9-GenericCloud.latest.x86_64.qcow2', - 'a01fbfa6750c2a7f1c290f7e2ab51bfdbb564e95413f8f52ab27175a7646e30b'), + 'amd64': (f'{_GH3}/Rocky-9-GenericCloud.latest.x86_64.qcow2', + 'c15042de9805e2b9581715d46361484a2c94187a15608344f85e775fb34081f5'), 'arm64': ('https://download.rockylinux.org/pub/rocky/9/images/aarch64/Rocky-9-GenericCloud.latest.aarch64.qcow2', None), }, ), ( 'alma-9-cloud', 'almalinux', '9', 'AlmaLinux 9 GenericCloud', 'almalinux', { - 'amd64': (f'{_GH}/AlmaLinux-9-GenericCloud-latest.x86_64.qcow2', - '49c75c0b49d9831338d06288e7f751f98302144218b462e5d9b2b6fe25c66f5e'), + 'amd64': (f'{_GH3}/AlmaLinux-9-GenericCloud-latest.x86_64.qcow2', + 'c3a21566c92c520c5ab9fa68e6ce38190ff173c531fbe0eea00573955d0b5131'), 'arm64': ('https://repo.almalinux.org/almalinux/9/cloud/aarch64/images/AlmaLinux-9-GenericCloud-latest.aarch64.qcow2', None), }, ), ( 'alma-10-cloud', 'almalinux', '10', 'AlmaLinux 10 GenericCloud', 'almalinux', { - 'amd64': (f'{_GH2}/AlmaLinux-10-GenericCloud-latest.x86_64.qcow2', - 'd0bdbc4fabb365b27e8d4a77118c1100ebdab42341312338e63724a2f9ee217f'), + 'amd64': (f'{_GH3}/AlmaLinux-10-GenericCloud-latest.x86_64.qcow2', + '7b91f6ad87aeac7193ece070e06e25406a76a7084d1628d89a5bb1ddd9d1642e'), 'arm64': ('https://repo.almalinux.org/almalinux/10/cloud/aarch64/images/AlmaLinux-10-GenericCloud-latest.aarch64.qcow2', None), }, ), ( 'centos-stream-9-cloud', 'centos', '9-stream', 'CentOS Stream 9 GenericCloud', 'centos', { - 'amd64': (f'{_GH2}/CentOS-Stream-GenericCloud-9-latest.x86_64.qcow2', - '63c13542e94678b0a41d318e7758f1cf23609564b1cbaa9051616457ce771903'), + 'amd64': (f'{_GH3}/CentOS-Stream-GenericCloud-9-latest.x86_64.qcow2', + 'd9818217c2ad20809973013f32094c2d82cbb74c08709afb4bef3d426b06dd37'), 'arm64': ('https://cloud.centos.org/centos/9-stream/aarch64/images/CentOS-Stream-GenericCloud-9-latest.aarch64.qcow2', None), }, ), @@ -95,8 +98,8 @@ _CLOUD_IMAGES = [ ( 'fedora-41-cloud', 'fedora', '41', 'Fedora 41 Cloud', 'fedora', { - 'amd64': (f'{_GH2}/Fedora-Cloud-Base-Generic-41-1.4.x86_64.qcow2', - '6c12ad70a8b5058f032de10d463bda8c93391162e5a72a90c79dd548ecc8e378'), + 'amd64': (f'{_GH3}/Fedora-Cloud-Base-Generic-41-1.4.x86_64.qcow2', + '40f101f44a83f714a1f586e6285f14a90e570c874a4bee2399873582b20dea80'), 'arm64': ('https://download.fedoraproject.org/pub/fedora/linux/releases/41/Cloud/aarch64/images/Fedora-Cloud-Base-Generic-41-1.4.aarch64.qcow2', None), }, ), diff --git a/backend/app/proxmox/client.py b/backend/app/proxmox/client.py index 36530c6..3f581ad 100644 --- a/backend/app/proxmox/client.py +++ b/backend/app/proxmox/client.py @@ -35,6 +35,27 @@ async def _run_in_executor(func, *args, **kwargs): loop = asyncio.get_event_loop() return await loop.run_in_executor(proxmox_executor, lambda: func(*args, **kwargs)) +# qemu-guest-agent в образах RHEL-семейства (Rocky Linux, AlmaLinux, CentOS +# Stream, Fedora) собран с урезанным набором RPC. Ограничение задаётся в +# /etc/sysconfig/qemu-ga, откуда systemd-юнит берёт аргументы агента: +# FILTER_RPC_ARGS с allow-list без guest-exec (актуальные пакеты) либо +# BLOCK_RPCS / BLACKLIST_RPC с block-list (пакеты постарше). Proxmox отдаёт +# это как "The command guest-exec has been disabled for this instance" — по +# такому тексту не догадаться, что и где чинить, поэтому дописываем инструкцию. +def agent_error_hint(error: str) -> str: + """Дополнить ошибку guest agent подсказкой, если в госте запрещён RPC.""" + low = (error or '').lower() + if 'has been disabled' in low and 'guest-exec' in low: + return ( + f'{error}. В гостевой ОС запрещён RPC guest-exec — так по умолчанию ' + 'собран qemu-guest-agent в Rocky Linux, AlmaLinux, CentOS Stream и ' + 'Fedora. Внутри ВМ очистите в /etc/sysconfig/qemu-ga значение ' + 'FILTER_RPC_ARGS (в пакетах постарше — BLOCK_RPCS или ' + 'BLACKLIST_RPC) и выполните systemctl restart qemu-guest-agent' + ) + return error + + def get_proxmox_resources(host: str, user: str = "root@pam", password: str = None, token_name: str = None, token_value: str = None, verify_ssl: bool = False, @@ -1774,7 +1795,7 @@ class ProxmoxClient(VmMixin, LxcMixin, ClusterMixin, StorageMixin, NetworkMixin, logger.error(f"Failed to execute command on VM {vmid}: {e}") return { 'success': False, - 'error': str(e), + 'error': agent_error_hint(str(e)), 'stdout': '', 'stderr': '', 'exit_code': -1 @@ -1879,7 +1900,7 @@ class ProxmoxClient(VmMixin, LxcMixin, ClusterMixin, StorageMixin, NetworkMixin, logger.error(f"Failed to execute script on VM {vmid}: {e}") return { 'success': False, - 'error': str(e), + 'error': agent_error_hint(str(e)), 'stdout': '', 'stderr': '', 'exit_code': -1 diff --git a/backend/tests/test_container_interfaces.py b/backend/tests/test_container_interfaces.py index c59235b..58c53ef 100644 --- a/backend/tests/test_container_interfaces.py +++ b/backend/tests/test_container_interfaces.py @@ -123,3 +123,34 @@ def test_execute_script_sends_bytes_not_wide_chars(): sent = agent.exec.post.call_args.kwargs["input-data"] assert all(ord(ch) < 256 for ch in sent), "в API уходят широкие символы" assert sent.encode("latin-1").decode("utf-8") == script + + +def test_blocked_guest_exec_explains_how_to_fix(): + """Образы RHEL-семейства запрещают guest-exec — ошибка должна это объяснять. + + Proxmox отдаёт лишь "The command guest-exec has been disabled for this + instance"; по такому тексту не догадаться, что чинить нужно + /etc/sysconfig/qemu-ga внутри гостя. + """ + px = MagicMock() + px.nodes.return_value.qemu.return_value.agent.exec.post.side_effect = RuntimeError( + "500 Internal Server Error: QEMU guest agent command failed - " + "The command guest-exec has been disabled for this instance" + ) + + result = _client_with_mock(px).execute_script("prod", 103, "echo ok") + + assert result["success"] is False + assert "/etc/sysconfig/qemu-ga" in result["error"] + assert "FILTER_RPC_ARGS" in result["error"] + + +def test_unrelated_agent_error_is_not_annotated(): + px = MagicMock() + px.nodes.return_value.qemu.return_value.agent.exec.post.side_effect = RuntimeError( + "500 QEMU guest agent is not running" + ) + + result = _client_with_mock(px).execute_script("prod", 104, "echo ok") + + assert result["error"] == "500 QEMU guest agent is not running" diff --git a/patch-cloud-images.sh b/patch-cloud-images.sh index e5e37cc..98008ac 100644 --- a/patch-cloud-images.sh +++ b/patch-cloud-images.sh @@ -5,7 +5,8 @@ # Что делает: # 1) скачивает cloud-образы из curated-каталога (см. backend/app/catalog/builtin.py) # 2) прогоняет каждый через virt-customize: ставит qemu-guest-agent, включает -# сервис и (опц.) обнуляет machine-id +# сервис, снимает блокировку guest-exec (RHEL-семейство) и (опц.) обнуляет +# machine-id # 3) считает sha256 и пишет sha256sums.txt # 4) генерирует mirrors.json — готовый список для добавления через # POST /api/images/mirrors (или ручного ввода в UI) @@ -21,6 +22,7 @@ # Пример: # BASE_URL="https://mirror.lan/pve-images" ./patch-cloud-images.sh # INCLUDE_ARM64=1 OUTDIR=/srv/images ./patch-cloud-images.sh +# ONLY="rocky alma centos fedora" ./patch-cloud-images.sh # только RHEL-семейство # # Установка: скопируйте файл на машину-патчер и запустите. Скрипт самодостаточен. @@ -31,6 +33,10 @@ OUTDIR="${OUTDIR:-./patched-images}" # куда складывать гот INSTALL_PKG="${INSTALL_PKG:-qemu-guest-agent}" INCLUDE_ARM64="${INCLUDE_ARM64:-0}" # 1 — патчить и arm64 (нужен qemu-user-static) RESET_MACHINE_ID="${RESET_MACHINE_ID:-1}" # 1 — обнулить /etc/machine-id (уникальный id у клонов) +UNBLOCK_RPC="${UNBLOCK_RPC:-1}" # 1 — снять блокировку guest-exec/guest-file-* в qemu-ga +ONLY="${ONLY:-}" # фильтр образов по id/os, через пробел или запятую + # напр. ONLY="rocky alma centos fedora" + # пусто — собирать весь каталог FORCE_DOWNLOAD="${FORCE_DOWNLOAD:-0}" # 1 — перекачать образы даже если уже скачаны AUTO_INSTALL="${AUTO_INSTALL:-1}" # 1 — доустановить недостающие зависимости самому BASE_URL="${BASE_URL:-}" # публичный префикс зеркала для url в mirrors.json @@ -105,6 +111,19 @@ pm_install() { esac } +# Подходит ли образ под фильтр ONLY (совпадение подстроки с id или os) +match_only() { + local id="$1" os="$2" pat + if [ -z "$ONLY" ]; then + return 0 + fi + for pat in $(echo "$ONLY" | tr ',' ' '); do + case "$id" in *"$pat"*) return 0 ;; esac + case "$os" in *"$pat"*) return 0 ;; esac + done + return 1 +} + # ── Preflight ────────────────────────────────────────────────────────────────── step "Проверка окружения" @@ -155,11 +174,26 @@ fi mkdir -p "$RAW_DIR" +# ── Снятие блокировки RPC у guest agent ─────────────────────────────────────── +# Rocky / AlmaLinux / CentOS Stream / Fedora ставят qemu-guest-agent с +# урезанным набором RPC — в /etc/sysconfig/qemu-ga, откуда systemd-юнит берёт +# аргументы командной строки агента. Разметка файла менялась трижды: +# FILTER_RPC_ARGS="--allow-rpcs=..." — актуальные пакеты (RHEL 9/10, Fedora): +# allow-list, где guest-exec просто нет +# BLOCK_RPCS=... — qemu-ga 8.1+, block-list +# BLACKLIST_RPC=... — qemu-ga < 8.1, block-list +# Пустое значение любой из них = агент без ограничений, как в Debian/Ubuntu, +# где фильтра нет вовсе. Без этого панель не может выполнить скрипт в ВМ, +# навесить дополнительный IP и расширить ФС после ресайза диска: агент +# отвечает "The command guest-exec has been disabled for this instance". +# Закомментированные строки не трогаем, в Debian/Ubuntu файла нет вообще. +QGA_UNBLOCK_CMD='f=/etc/sysconfig/qemu-ga; if [ -f "$f" ]; then sed -i -e "s/^[[:space:]]*FILTER_RPC_ARGS=.*/FILTER_RPC_ARGS=/" -e "s/^[[:space:]]*BLACKLIST_RPC=.*/BLACKLIST_RPC=/" -e "s/^[[:space:]]*BLOCK_RPCS=.*/BLOCK_RPCS=/" "$f"; echo "qemu-ga RPC unblocked:" $(grep -E "^(FILTER_RPC_ARGS|BLACKLIST_RPC|BLOCK_RPCS)=" "$f"); else echo "qemu-ga: no /etc/sysconfig/qemu-ga, nothing to unblock"; fi' + # ── Обход каталога ───────────────────────────────────────────────────────────── SUMS_FILE="$OUTDIR/sha256sums.txt" : > "$SUMS_FILE" declare -a MIRROR_ROWS=() # строки для mirrors.json: os|version|arch|name|file|sha -FAILED=0; DONE=0; SKIPPED=0 +FAILED=0; DONE=0; SKIPPED=0; FILTERED=0 for row in "${IMAGES[@]}"; do IFS='|' read -r id os version name arch url <<< "$row" @@ -168,6 +202,10 @@ for row in "${IMAGES[@]}"; do SKIPPED=$((SKIPPED+1)); continue fi + if ! match_only "$id" "$os"; then + FILTERED=$((FILTERED+1)); continue + fi + file="$(basename "$url")" raw="$RAW_DIR/$file" out="$OUTDIR/$file" @@ -193,7 +231,14 @@ for row in "${IMAGES[@]}"; do info "virt-customize: ставлю $INSTALL_PKG" VC_ARGS=(-a "$out" --install "$INSTALL_PKG" --run-command "systemctl enable ${INSTALL_PKG}.service") - [ "$RESET_MACHINE_ID" = "1" ] && VC_ARGS+=(--run-command "truncate -s 0 /etc/machine-id") + # if, а не `[ ... ] && ...`: при set -e ложное условие в конце AND-списка + # завершает скрипт. + if [ "$UNBLOCK_RPC" = "1" ]; then + VC_ARGS+=(--run-command "$QGA_UNBLOCK_CMD") + fi + if [ "$RESET_MACHINE_ID" = "1" ]; then + VC_ARGS+=(--run-command "truncate -s 0 /etc/machine-id") + fi if ! LIBGUESTFS_BACKEND="${LIBGUESTFS_BACKEND:-direct}" virt-customize "${VC_ARGS[@]}"; then err "virt-customize не смог обработать $out — пропускаю." rm -f "$out"; FAILED=$((FAILED+1)); continue @@ -210,8 +255,12 @@ done # ── mirrors.json ─────────────────────────────────────────────────────────────── step "Генерация mirrors.json" MIRRORS_FILE="$OUTDIR/mirrors.json" +# Тот же set -e: с заданным BASE_URL ложное условие оборвало бы скрипт +# ровно перед генерацией mirrors.json. url_prefix="${BASE_URL%/}" -[ -z "$url_prefix" ] && url_prefix="REPLACE_ME" +if [ -z "$url_prefix" ]; then + url_prefix="REPLACE_ME" +fi { echo "[" @@ -237,8 +286,15 @@ url_prefix="${BASE_URL%/}" # ── Итог ─────────────────────────────────────────────────────────────────────── step "Итог" ok "Готово образов: $DONE" -[ "$SKIPPED" -gt 0 ] && info "Пропущено arm64: $SKIPPED (INCLUDE_ARM64=1 чтобы включить)" -[ "$FAILED" -gt 0 ] && warn "С ошибками: $FAILED" +if [ "$SKIPPED" -gt 0 ]; then + info "Пропущено arm64: $SKIPPED (INCLUDE_ARM64=1 чтобы включить)" +fi +if [ "$FILTERED" -gt 0 ]; then + info "Отфильтровано по ONLY=\"$ONLY\": $FILTERED" +fi +if [ "$FAILED" -gt 0 ]; then + warn "С ошибками: $FAILED" +fi echo info "Готовые образы: $OUTDIR/" info "Контрольные суммы: $SUMS_FILE"