diff --git a/CHANGELOG.md b/CHANGELOG.md index 72d35a6..9043c63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.22.0] - 2026-12-06 + +### Added +- The images on the cluster's storages (napalm-device-types 4.61.0, NetOrk/netork#3176). + `get_clusters()` gives each storage with `iso` or `import` content its `images`: every + such file with its volid, format, size, creation time and the nodes it is on. A shared + storage is read once, a local one on each of its nodes. A storage that cannot be read + whole is None. +- `stage_storage_image()` downloads a cloud image into an import storage through + `download-url`, verified, under the name a provisioning download gives it. + `storage_image_checksum()` hashes a file on the node. `delete_storage_image()` deletes + one. The static `staged_image_name()` and `staged_image_series()` tell two builds of one + image apart. +- `create_vm_from_cloud_init(image_volume=…)` imports a disk image already on a storage + as the root disk. It refuses installation media, or a file the node does not have, + before creating anything. The result names the volume the root disk came from: + `image_volume`, None over the SSH path. + ## [0.21.0] - 2026-12-01 ### Added diff --git a/napalm_proxmox/cluster_mixin.py b/napalm_proxmox/cluster_mixin.py index 08b6f17..2dad4d9 100644 --- a/napalm_proxmox/cluster_mixin.py +++ b/napalm_proxmox/cluster_mixin.py @@ -15,7 +15,8 @@ cluster of one, without a name). Read from: of their zone; - ``GET /cluster/ha/status/manager_status``: which node is in maintenance; - quorum votes and HA resources: see ``cluster_ha``; backup jobs and backups: - see ``cluster_backups``. Each of those is best-effort and None when it cannot + see ``cluster_backups``; the files on iso and import storages: see + ``storage_images``. Each of those is best-effort and None when it cannot be read, without failing the rest of the report. """ @@ -30,6 +31,7 @@ from napalm_proxmox.network_targets import bridge_targets, vnet_target from napalm_proxmox.pve_values import split_list as _list from napalm_proxmox.pve_values import to_flag as _flag from napalm_proxmox.pve_values import to_int as _int +from napalm_proxmox.storage_images import read_images from napalm_proxmox.utils import cpu_flags if TYPE_CHECKING: @@ -186,6 +188,7 @@ class ProxmoxClusterMixin: members = self._members(status if head else []) storages = _storages(resources) _name_backup_servers(storages, self._api) + read_images(self._api, storages, self._node_name) return [ { "id": _cluster_id(head, status), diff --git a/napalm_proxmox/driver.py b/napalm_proxmox/driver.py index 51ec826..71eeb38 100644 --- a/napalm_proxmox/driver.py +++ b/napalm_proxmox/driver.py @@ -66,6 +66,7 @@ from napalm_proxmox.routing_mixin import ProxmoxRoutingMixin from napalm_proxmox.running_backups import ProxmoxRunningBackupsMixin from napalm_proxmox.scheduled_jobs import PVE_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin +from napalm_proxmox.storage_images import ProxmoxStorageImagesMixin from napalm_proxmox.system_mixin import ProxmoxSystemMixin from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin from napalm_proxmox.update_history import ProxmoxUpdateHistoryMixin @@ -98,6 +99,7 @@ class ProxmoxDriver( ProxmoxVMMixin, ProxmoxVMContractMixin, ProxmoxVMSnapshotMixin, + ProxmoxStorageImagesMixin, ProxmoxVMProvisionMixin, ProxmoxClusterMixin, ProxmoxVMMigrateMixin, diff --git a/napalm_proxmox/storage_images.py b/napalm_proxmox/storage_images.py new file mode 100644 index 0000000..85db934 --- /dev/null +++ b/napalm_proxmox/storage_images.py @@ -0,0 +1,203 @@ +"""The images on the cluster's storages, and staging, checking and deleting them +(NetOrk/netork#3176). + +Read from ``GET /nodes//storage//content`` for each storage whose +content includes ``iso`` or ``import``: a shared one once, on the own node if it +answers, else on the next node that does; a local one on every node that has it, +each file with the nodes it is on. A storage that cannot be read whole is None, the +way the backups are (``cluster_backups``): half a list would say a file is gone. + +A single file is addressed as ``…/content/``, the volid URL-encoded into one +path segment (proxmoxer splits a resource id on "/"). +""" + +from __future__ import annotations + +import logging +import re +import shlex +from typing import TYPE_CHECKING, Any +from urllib.parse import quote + +from napalm_proxmox.image_names import import_volume_name + +if TYPE_CHECKING: + # Type-only: newer than the napalm_device_types floor in pyproject.toml. + from napalm_device_types import ClusterStorageDict, StorageImageDict + +logger = logging.getLogger(__name__) + +_JsonDict = dict[str, Any] + +#: napalm_device_types.STORAGE_IMAGE_CONTENT, kept here for the older floor. +_IMAGE_CONTENT = ("iso", "import") + +# The checksum algorithms with a coreutils "sum" on the node. +_CHECKSUM_ALGORITHMS = frozenset({"md5", "sha1", "sha224", "sha256", "sha384", "sha512"}) + +# A file this driver downloaded: "netork-<12 hex of the URL>-". +_STAGED = re.compile(r"^netork-[0-9a-f]{12}-(.+)$") + + +def _content(api: Any, node: str, storage: str) -> list[_JsonDict]: + return list(api.nodes(node).storage(storage).content.get() or []) + + +def _shared_rows(api: Any, storage: str, nodes: list[str]) -> list[_JsonDict]: + error: Exception | None = None + for node in nodes: + try: + return _content(api, node, storage) + except Exception as exc: + logger.debug("Cannot read the content of %s from %s: %s", storage, node, exc) + error = exc + if error is not None: + raise error + return [] + + +def _rows_by_node( + api: Any, storage: ClusterStorageDict, local: str +) -> list[tuple[_JsonDict, list[str]]]: + if storage["shared"]: + order = sorted(storage["nodes"], key=lambda n: n != local) + return [(row, list(storage["nodes"])) for row in _shared_rows(api, storage["name"], order)] + return [(row, [n]) for n in storage["nodes"] for row in _content(api, n, storage["name"])] + + +def _image(row: _JsonDict, nodes: list[str]) -> StorageImageDict: + volid = str(row["volid"]) + return { + "volid": volid, + "name": volid.split(":", 1)[-1].rsplit("/", 1)[-1], + "content": str(row.get("content")), + "format": row.get("format") or None, + "size": int(row["size"]) if row.get("size") is not None else None, + "created": int(row["ctime"]) if row.get("ctime") is not None else None, + "nodes": nodes, + } + + +def _storage_images( + api: Any, storage: ClusterStorageDict, local: str +) -> list[StorageImageDict] | None: + if not storage["nodes"]: + return None # available nowhere, an unmounted share: not read + try: + rows = _rows_by_node(api, storage, local) + except Exception as exc: + logger.warning("Cannot read the images on storage %s: %s", storage["name"], exc) + return None + images: dict[str, StorageImageDict] = {} + for row, nodes in rows: + if row.get("content") not in _IMAGE_CONTENT or not row.get("volid"): + continue + known = images.get(str(row["volid"])) + if known is None: + images[str(row["volid"])] = _image(row, nodes) + else: + known["nodes"] = [*known["nodes"], *(n for n in nodes if n not in known["nodes"])] + return list(images.values()) + + +def read_images(api: Any, storages: list[ClusterStorageDict], local_node: str) -> None: + """Give each storage that holds iso or import content its ``images``, in place.""" + for storage in storages: + if any(kind in storage["content"] for kind in _IMAGE_CONTENT): + storage["images"] = _storage_images(api, storage, local_node) + + +def _storage_of(volid: str) -> str: + storage, sep, path = volid.partition(":") + if not (storage and sep and path): + raise ValueError(f"{volid!r} is not a volume id (:)") + return storage + + +def volume(node_api: Any, node_name: str, volid: str) -> _JsonDict: + """The attributes of *volid* on the node *node_api* addresses (``path``, ``format``). + + :raises ValueError: a volid without a storage, or a file the node does not have. + """ + storage = _storage_of(volid) + try: + return dict(node_api.storage(storage).content(quote(volid, safe="")).get() or {}) + except Exception as exc: + raise ValueError(f"{volid} is not on a storage of {node_name}: {exc}") from exc + + +def check_image_source( + node_api: Any, node_name: str, image_url: str | None, image_volume: str | None +) -> None: + """Exactly one image; a file named by its volid a disk image the node has.""" + if (image_url is None) == (image_volume is None): + raise ValueError("Name the image by image_url or by image_volume, exactly one") + if image_volume is not None: + if image_volume.partition(":")[2].startswith("iso/"): + raise ValueError(f"{image_volume} is installation media, not a disk image") + volume(node_api, node_name, image_volume) + + +class ProxmoxStorageImagesMixin: + """Stage, check and delete the images on this node's storages.""" + + _node_name: str + _node_api: Any + _run_node_command: Any + _wait_for_task: Any + _import_cloud_image: Any + + @staticmethod + def staged_image_name(image_url: str) -> str | None: + return import_volume_name(image_url) + + @staticmethod + def staged_image_series(file_name: str) -> str | None: + match = _STAGED.match(file_name) + return match.group(1) if match else None + + def _volume(self, volid: str) -> _JsonDict: + """The attributes of *volid* on this node (its ``path``, ``format``).""" + return volume(self._node_api(), self._node_name, volid) + + def stage_storage_image( + self, + storage: str, + image_url: str, + *, + image_checksum: str | None = None, + timeout: int = 1800, + ) -> str: + name = import_volume_name(image_url) + if name is None: + raise ValueError(f"{image_url} cannot be staged: Proxmox imports no such file type") + config = next( + (s for s in self._node_api().storage.get() if s.get("storage") == storage), None + ) + if config is None or "import" not in str(config.get("content", "")).split(","): + raise ValueError( + f"{self._node_name} has no storage {storage!r} for disk images to import" + ) + if config.get("enabled", 1) == 0 or config.get("active", 1) == 0: + raise ValueError(f"Storage {storage!r} is not active on {self._node_name}") + return str( + self._import_cloud_image(storage, name, image_url, image_checksum, timeout=timeout) + ) + + def storage_image_checksum( + self, volid: str, algorithm: str = "sha256", *, timeout: int = 3600 + ) -> str: + if algorithm not in _CHECKSUM_ALGORITHMS: + raise ValueError(f"Unknown checksum algorithm {algorithm!r}") + path = self._volume(volid).get("path") + if not path: + raise RuntimeError(f"{volid} has no path on {self._node_name}") + out = self._run_node_command(f"{algorithm}sum {shlex.quote(str(path))}", timeout=timeout) + return str(out).split()[0].lower() + + def delete_storage_image(self, volid: str) -> None: + self._volume(volid) + content = self._node_api().storage(_storage_of(volid)).content(quote(volid, safe="")) + upid = content.delete() + if upid: + self._wait_for_task(upid, timeout=120) diff --git a/napalm_proxmox/vm_provision_mixin.py b/napalm_proxmox/vm_provision_mixin.py index d2d0f1a..0d45471 100644 --- a/napalm_proxmox/vm_provision_mixin.py +++ b/napalm_proxmox/vm_provision_mixin.py @@ -28,6 +28,7 @@ from napalm_device_types.provisioning import ( from napalm_proxmox.image_names import cache_name, import_volume_name, split_checksum from napalm_proxmox.network_targets import bridge_targets, vnet_target +from napalm_proxmox.storage_images import check_image_source from napalm_proxmox.utils import cpu_flags from napalm_proxmox.vm_mixin import qemu_status @@ -364,27 +365,28 @@ class ProxmoxVMProvisionMixin: self, vmid: int, image_storage: str, - image_url: str, + image: tuple[str | None, str | None], image_checksum: str | None, download_timeout: int, timeout: int, - ) -> None: - """Get the cloud image onto the node and make it the VM's root disk. - - Through an import storage when the node has one — Proxmox downloads, - verifies and copies the image itself — and over SSH otherwise. + ) -> str | None: + """Make *image*, ``(image_url, image_volume)``, the VM's root disk; return + the volid it came from, None over SSH. A URL goes through an import storage + when the node has one (Proxmox downloads and verifies it), else over SSH. """ - import_storage = self._find_import_storage() - filename = import_volume_name(image_url) if import_storage else None - if not import_storage or not filename: - self._import_over_ssh( - vmid, image_storage, image_url, image_checksum, download_timeout, timeout + image_url, volid = image + if volid is None: + assert image_url is not None # _check_image_source + import_storage = self._find_import_storage() + filename = import_volume_name(image_url) if import_storage else None + if not import_storage or not filename: + self._import_over_ssh( + vmid, image_storage, image_url, image_checksum, download_timeout, timeout + ) + return None + volid = self._import_cloud_image( + import_storage, filename, image_url, image_checksum, timeout=download_timeout ) - return - - volid = self._import_cloud_image( - import_storage, filename, image_url, image_checksum, timeout=download_timeout - ) _logger.info(f"Importing {volid} into VM {vmid} on storage {image_storage}") upid = ( self._node_api() @@ -396,6 +398,7 @@ class ProxmoxVMProvisionMixin: ) if upid: self._wait_for_task(upid, timeout=timeout) + return str(volid) def _find_default_image_storage(self) -> str: """Find a storage suitable for VM root disks (content includes 'images'). @@ -540,8 +543,12 @@ class ProxmoxVMProvisionMixin: time.sleep(2) - def _check_placement(self, guest_os: str, node: str | None) -> None: - """Refuse a guest this driver cannot provision, or a node other than its own.""" + def _check_placement( + self, guest_os: str, node: str | None, image_url: str | None, image_volume: str | None + ) -> None: + """Refuse a guest this driver cannot provision, a node other than its own, or + an image that is not exactly one URL or one disk image this node has.""" + check_image_source(self._node_api(), self._node_name, image_url, image_volume) if guest_os not in self.GUEST_AGENTS: raise ValueError( f"Cannot provision a {guest_os!r} guest; this driver provisions " @@ -557,7 +564,8 @@ class ProxmoxVMProvisionMixin: self, name: str, *, - image_url: str, + image_url: str | None = None, + image_volume: str | None = None, cpu: int, memory: int, nics: list[dict[str, Any]], @@ -578,8 +586,7 @@ class ProxmoxVMProvisionMixin: Steps: 1. Get next available VMID from cluster 2. Create an empty VM shell (no clone — no pre-existing template needed) - 3. Download the cloud image on the node (cached by filename) and - import it as the VM's root disk + 3. Get the image onto the node (or take image_volume), import it as root disk 4. Configure CPU, memory, and network interfaces 5. Verify snippet storage exists 6. Render cloud-init config to YAML and upload @@ -590,7 +597,7 @@ class ProxmoxVMProvisionMixin: Args: name: new VM display name - image_url: URL of the cloud image to download and use as root disk + image_url / image_volume: a URL to download, or a volid on a storage; one of them cpu: number of vCPUs memory: RAM in MB nics: list of NIC config dicts (bridge, vlan_tag/trunk_vlan_tags, dhcp flag) @@ -613,7 +620,7 @@ class ProxmoxVMProvisionMixin: timeout: max seconds for the remaining provisioning steps Returns: - {"vmid": str, "name": str, "node": str} + {"vmid": str, "name": str, "node": str, "image_volume": str | None} Raises: VMProvisionIncomplete: any failure once the VM shell exists (download, @@ -626,10 +633,10 @@ class ProxmoxVMProvisionMixin: run, a guest_os it cannot provision, or another node (raised before anything is created) """ - self._check_placement(guest_os, node) + self._check_placement(guest_os, node, image_url, image_volume) created: int | None = None # the VMID once the shell exists on the node try: - _logger.info(f"Creating {guest_os} VM '{name}' from image {image_url}") + _logger.info(f"Creating {guest_os} VM '{name}'") cpu_model = self._resolve_cpu_type(cpu_type) # Step 1: Get next VMID @@ -655,8 +662,13 @@ class ProxmoxVMProvisionMixin: # Step 3: Download cloud image (cached) and import as root disk image_storage = storage or self._find_default_image_storage() - self._attach_root_disk( - vmid, image_storage, image_url, image_checksum, download_timeout, timeout + vol = self._attach_root_disk( + vmid, + image_storage, + (image_url, image_volume), + image_checksum, + download_timeout, + timeout, ) # Step 4: Configure network interfaces (CPU/memory already set at shell creation) @@ -664,8 +676,7 @@ class ProxmoxVMProvisionMixin: self._node_api().qemu(vmid).config.post(**_nic_config_args(nics)) # Step 5: Verify snippet storage exists - # (enabled is absent-not-falsy, and node-scoping matters — see - # _find_default_image_storage) + # (absent "enabled" is enabled; node-scoped: see _find_default_image_storage) _logger.info("Checking for snippet storage...") storages = self._node_api().storage.get() snippet_storage = None @@ -761,11 +772,7 @@ class ProxmoxVMProvisionMixin: self._wait_for_task(start_upid, timeout=timeout) _logger.info(f"VM {vmid} ('{name}') provisioned successfully on {self._node_name}") - return { - "vmid": str(vmid), - "name": name, - "node": self._node_name, - } + return {"vmid": str(vmid), "name": name, "node": self._node_name, "image_volume": vol} except Exception as e: _logger.exception(f"Failed to create VM '{name}': {e}") diff --git a/pyproject.toml b/pyproject.toml index b482aad..6f5667b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-proxmox" -version = "0.21.0" +version = "0.22.0" description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server" readme = "README.md" license = "Apache-2.0" @@ -21,7 +21,7 @@ classifiers = [ requires-python = ">=3.12" dependencies = [ "napalm>=5.0.0", - "napalm_device_types>=4.55.0", # LoginSessionsMixin + "napalm_device_types>=4.61.0", # storage images "paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py) "proxmoxer>=2.0.0", "netaddr>=0.9.0", diff --git a/tests/test_cluster_ha_backups.py b/tests/test_cluster_ha_backups.py index 21239bc..ce73ac8 100644 --- a/tests/test_cluster_ha_backups.py +++ b/tests/test_cluster_ha_backups.py @@ -519,7 +519,13 @@ class TestBackups: def test_storage_without_backup_content_is_not_read(self): api, calls = _storage_api() _report(api) - assert not [key for key in calls if key[1] in ("ceph-vm", "local-lvm", "nfs-iso")] + # The images on an iso storage are read on their own (storage_images). + backup_reads = [ + key + for key, res in calls.items() + if any(c.kwargs.get("content") == "backup" for c in res.content.get.call_args_list) + ] + assert not [key for key in backup_reads if key[1] in ("ceph-vm", "local-lvm", "nfs-iso")] def test_entry_without_vmid_is_skipped(self): api, _ = _storage_api() diff --git a/tests/test_storage_images.py b/tests/test_storage_images.py new file mode 100644 index 0000000..39870ec --- /dev/null +++ b/tests/test_storage_images.py @@ -0,0 +1,426 @@ +"""The images on the cluster's storages, and staging, checking and deleting them +(NetOrk/netork#3176). + +Storage content rows follow ``GET /nodes/{node}/storage/{storage}/content`` +(pve-storage ``PVE/API2/Storage/Content.pm``): ``volid``, ``content``, ``format``, +``size`` and ``ctime``. ``GET …/content/{volume}`` answers a file's ``path`` on the +node (read live on PVE 9.2, 2026-12-06, with the volid URL-encoded as one segment). +""" + +from __future__ import annotations + +from typing import Any +from unittest.mock import MagicMock, patch +from urllib.parse import quote + +import pytest + +from napalm_proxmox.image_names import import_volume_name +from napalm_proxmox.storage_images import ProxmoxStorageImagesMixin, read_images +from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin +from tests.test_clusters import _api, _by_name, _driver + +_UBUNTU = ( + "https://cloud-images.ubuntu.com/releases/24.04/release-20261120/" + "ubuntu-24.04-server-cloudimg-amd64.img" +) +_UBUNTU_NEXT = _UBUNTU.replace("20261120", "20261201") + + +def _row(volid: str, content: str, fmt: str = "qcow2", size: int = 100, ctime: int = 1) -> dict: + return {"volid": volid, "content": content, "format": fmt, "size": size, "ctime": ctime} + + +def _storage(name: str, content: list[str], nodes: list[str], shared: bool) -> dict[str, Any]: + return {"name": name, "type": "cifs" if shared else "dir", "shared": shared, + "content": content, "nodes": nodes, "total": None, "used": None} # fmt: skip + + +def _content_api(rows: dict[tuple[str, str], list[dict] | Exception]) -> MagicMock: + """``api.nodes(node).storage(storage).content.get()`` answers *rows*.""" + api = MagicMock() + + def node(name: str) -> MagicMock: + res = MagicMock() + + def storage(sname: str) -> MagicMock: + answer = rows.get((name, sname), []) + st = MagicMock() + if isinstance(answer, Exception): + st.content.get.side_effect = answer + else: + st.content.get.return_value = answer + return st + + res.storage.side_effect = storage + return res + + api.nodes.side_effect = node + return api + + +# ── reading ────────────────────────────────────────────────────────────────── + + +class TestReadImages: + def test_a_shared_storage_is_read_once_on_the_own_node(self): + software = _storage("software", ["import", "iso"], ["pve1", "pve2"], shared=True) + api = _content_api( + { + ("pve2", "software"): [ + _row("software:iso/virtio-win.iso", "iso", "iso", 877373440, 1790270490), + _row("software:import/debian-13.qcow2", "import", "qcow2", 341508096, 17), + ] + } + ) + read_images(api, [software], "pve2") + assert [c.args for c in api.nodes.call_args_list] == [("pve2",)] + assert software["images"] == [ + { + "volid": "software:iso/virtio-win.iso", + "name": "virtio-win.iso", + "content": "iso", + "format": "iso", + "size": 877373440, + "created": 1790270490, + "nodes": ["pve1", "pve2"], + }, + { + "volid": "software:import/debian-13.qcow2", + "name": "debian-13.qcow2", + "content": "import", + "format": "qcow2", + "size": 341508096, + "created": 17, + "nodes": ["pve1", "pve2"], + }, + ] + + def test_a_shared_storage_the_own_node_cannot_read_is_read_on_the_next(self): + software = _storage("software", ["iso"], ["pve1", "pve2"], shared=True) + api = _content_api( + { + ("pve1", "software"): ConnectionError("share not mounted"), + ("pve2", "software"): [_row("software:iso/a.iso", "iso", "iso")], + } + ) + read_images(api, [software], "pve1") + assert [i["name"] for i in software["images"]] == ["a.iso"] + + def test_a_local_storage_lists_each_file_with_the_nodes_it_is_on(self): + local = _storage("local", ["iso", "vztmpl", "backup"], ["pve1", "pve2"], shared=False) + api = _content_api( + { + ("pve1", "local"): [_row("local:iso/a.iso", "iso", "iso")], + ("pve2", "local"): [ + _row("local:iso/a.iso", "iso", "iso"), + _row("local:iso/b.iso", "iso", "iso"), + ], + } + ) + read_images(api, [local], "pve1") + assert {i["name"]: i["nodes"] for i in local["images"]} == { + "a.iso": ["pve1", "pve2"], + "b.iso": ["pve2"], + } + + def test_other_content_is_left_out(self): + local = _storage("local", ["iso", "vztmpl", "snippets", "backup"], ["pve1"], shared=False) + api = _content_api( + { + ("pve1", "local"): [ + _row("local:iso/a.iso", "iso", "iso"), + _row("local:vztmpl/debian.tar.zst", "vztmpl", "tzst"), + _row("local:snippets/101-user-data.yaml", "snippets", "snippet"), + _row("local:backup/vzdump-qemu-100.vma.zst", "backup", "vma.zst"), + ] + } + ) + read_images(api, [local], "pve1") + assert [i["name"] for i in local["images"]] == ["a.iso"] + + def test_a_storage_without_images_gets_no_key_and_is_not_read(self): + zfs = _storage("local-zfs", ["images", "rootdir"], ["pve1"], shared=False) + api = _content_api({}) + read_images(api, [zfs], "pve1") + assert "images" not in zfs + api.nodes.assert_not_called() + + def test_a_node_of_a_local_storage_that_does_not_answer_leaves_it_unread(self): + """Half a list would say the other node's files are gone.""" + local = _storage("local", ["iso"], ["pve1", "pve2"], shared=False) + api = _content_api( + { + ("pve1", "local"): [_row("local:iso/a.iso", "iso", "iso")], + ("pve2", "local"): ConnectionError("pve2 unreachable"), + } + ) + read_images(api, [local], "pve1") + assert local["images"] is None + + def test_a_shared_storage_no_node_can_read_is_unread(self): + software = _storage("software", ["iso"], ["pve1"], shared=True) + api = _content_api({("pve1", "software"): ConnectionError("down")}) + read_images(api, [software], "pve1") + assert software["images"] is None + + def test_a_storage_available_on_no_node_is_unread(self): + """An unmounted share is on no node: that is not a storage without files.""" + software = _storage("software", ["iso"], [], shared=True) + api = _content_api({}) + read_images(api, [software], "pve1") + assert software["images"] is None + + def test_values_the_platform_leaves_out_are_none(self): + software = _storage("software", ["iso"], ["pve1"], shared=True) + api = _content_api( + {("pve1", "software"): [{"volid": "software:iso/x.iso", "content": "iso"}]} + ) + read_images(api, [software], "pve1") + [image] = software["images"] + assert (image["format"], image["size"], image["created"]) == (None, None, None) + + def test_get_clusters_reports_the_images(self): + api = _api() + api.nodes("pve1").storage.side_effect = lambda name: MagicMock( + content=MagicMock( + get=MagicMock( + return_value=[_row(f"{name}:iso/x.iso", "iso", "iso")] + if name == "nfs-iso" + else [] + ) + ) + ) + [cluster] = _driver(api).get_clusters() + storages = _by_name(cluster["storages"]) + assert [i["volid"] for i in storages["nfs-iso"]["images"]] == ["nfs-iso:iso/x.iso"] + assert "images" not in storages["ceph-vm"] + + +# ── names ──────────────────────────────────────────────────────────────────── + + +class TestNames: + def test_the_staged_name_is_the_import_name(self): + assert ProxmoxStorageImagesMixin.staged_image_name(_UBUNTU) == import_volume_name(_UBUNTU) + + def test_an_image_that_cannot_be_staged_has_no_name(self): + assert ProxmoxStorageImagesMixin.staged_image_name("https://x.org/a.qcow2.xz") is None + + def test_two_builds_of_one_image_are_one_series(self): + series = ProxmoxStorageImagesMixin.staged_image_series + first = ProxmoxStorageImagesMixin.staged_image_name(_UBUNTU) + second = ProxmoxStorageImagesMixin.staged_image_name(_UBUNTU_NEXT) + assert first != second + assert series(first) == series(second) == "ubuntu-24.04-server-cloudimg-amd64.qcow2" + + def test_a_file_netork_did_not_name_has_no_series(self): + series = ProxmoxStorageImagesMixin.staged_image_series + assert series("ubuntu-24.04.5-preinstalled-server-arm64.qcow2") is None + assert series("netork-notahash-x.qcow2") is None + + +# ── stage, checksum, delete ────────────────────────────────────────────────── + + +def _mixin(storages: list[dict] | None = None) -> tuple[Any, MagicMock]: + class Mixin(ProxmoxStorageImagesMixin, ProxmoxVMProvisionMixin): + pass + + mixin = Mixin() + mixin._node_name = "pve1" + node = MagicMock() + node.storage.get.return_value = storages if storages is not None else [ + {"storage": "software", "content": "import,iso", "active": 1, "enabled": 1}, + {"storage": "local", "content": "iso,vztmpl", "active": 1}, + ] # fmt: skip + node.tasks.return_value.status.get.return_value = {"status": "stopped", "exitstatus": "OK"} + mixin._node_api = MagicMock(return_value=node) + mixin._run_node_command = MagicMock(return_value="") + return mixin, node + + +class TestStage: + def test_downloads_into_the_storage_under_its_name(self): + mixin, _ = _mixin() + mixin._import_cloud_image = MagicMock(return_value="software:import/x.qcow2") + volid = mixin.stage_storage_image("software", _UBUNTU, image_checksum="sha256:ab") + assert volid == "software:import/x.qcow2" + mixin._import_cloud_image.assert_called_once_with( + "software", import_volume_name(_UBUNTU), _UBUNTU, "sha256:ab", timeout=1800 + ) + + @pytest.mark.parametrize( + "storage, url", + [ + ("software", "https://x.org/a.qcow2.xz"), # packed: only the SSH path unpacks + ("local", _UBUNTU), # takes no disk images to import + ("elsewhere", _UBUNTU), # not on this node + ], + ) + def test_refuses_what_it_cannot_stage(self, storage: str, url: str): + mixin, _ = _mixin() + mixin._import_cloud_image = MagicMock() + with pytest.raises(ValueError): + mixin.stage_storage_image(storage, url) + mixin._import_cloud_image.assert_not_called() + + def test_refuses_an_inactive_storage(self): + mixin, _ = _mixin([{"storage": "software", "content": "import", "active": 0}]) + with pytest.raises(ValueError, match="not active"): + mixin.stage_storage_image("software", _UBUNTU) + + +class TestChecksum: + def test_hashes_the_file_on_the_node(self): + mixin, node = _mixin() + volid = "software:iso/virtio-win.iso" + node.storage.return_value.content.return_value.get.return_value = { + "path": "/mnt/pve/software/template/iso/virtio-win.iso" + } + mixin._run_node_command.return_value = ( + "ABCDEF /mnt/pve/software/template/iso/virtio-win.iso" + ) + + assert mixin.storage_image_checksum(volid, "sha512", timeout=99) == "abcdef" + node.storage.assert_any_call("software") + node.storage.return_value.content.assert_called_with(quote(volid, safe="")) + mixin._run_node_command.assert_called_once_with( + "sha512sum /mnt/pve/software/template/iso/virtio-win.iso", timeout=99 + ) + + def test_an_unknown_algorithm_is_refused_before_anything_runs(self): + mixin, _ = _mixin() + with pytest.raises(ValueError): + mixin.storage_image_checksum("software:iso/a.iso", "crc32") + mixin._run_node_command.assert_not_called() + + def test_a_file_not_on_this_node_is_refused(self): + mixin, node = _mixin() + node.storage.return_value.content.return_value.get.side_effect = RuntimeError( + "500 no such volume" + ) + with pytest.raises(ValueError, match="not on"): + mixin.storage_image_checksum("software:iso/gone.iso") + + def test_a_volid_without_a_storage_is_refused(self): + mixin, _ = _mixin() + with pytest.raises(ValueError): + mixin.storage_image_checksum("gone.iso") + + +class TestDelete: + def test_deletes_the_file_and_waits_for_the_task(self): + mixin, node = _mixin() + volid = "software:import/netork-96bc7f0f1aa3-ubuntu-24.04-server-cloudimg-amd64.qcow2" + content = node.storage.return_value.content.return_value + content.get.return_value = {"path": "/mnt/pve/software/import/x"} + content.delete.return_value = "UPID:pve1:delete" + mixin._wait_for_task = MagicMock() + + mixin.delete_storage_image(volid) + + node.storage.return_value.content.assert_called_with(quote(volid, safe="")) + content.delete.assert_called_once_with() + mixin._wait_for_task.assert_called_once_with("UPID:pve1:delete", timeout=120) + + def test_a_file_not_on_this_node_is_refused(self): + mixin, node = _mixin() + content = node.storage.return_value.content.return_value + content.get.side_effect = RuntimeError("500") + with pytest.raises(ValueError): + mixin.delete_storage_image("software:iso/gone.iso") + content.delete.assert_not_called() + + +# ── a VM from a file already on a storage ──────────────────────────────────── + + +def _provisioner(storages: list[dict] | None = None) -> tuple[Any, MagicMock]: + mixin, node = _mixin( + storages + if storages is not None + else [ + {"storage": "local", "content": "iso,backup,vztmpl,snippets"}, + {"storage": "software", "content": "import,iso"}, + {"storage": "local-zfs", "content": "images,rootdir"}, + ] + ) + api = MagicMock() + api.cluster.nextid.get.return_value = 101 + api.storage.return_value.get.return_value = {"path": "/var/lib/vz"} + mixin._api = api + mixin._download_cloud_image = MagicMock(return_value="/var/lib/vz/template/x.qcow2") + vm = node.qemu.return_value + vm.config.get.return_value = {"unused0": "local-zfs:vm-101-disk-0"} + vm.config.post.return_value = None + node.storage.return_value.content.get.return_value = [] + node.storage.return_value.content.return_value.get.return_value = {"path": "/mnt/pve/x"} + return mixin, node + + +def _create(mixin: Any, **image: Any) -> dict: + with patch("time.sleep"): + return dict( + mixin.create_vm_from_cloud_init( + name="vm", + cpu=1, + memory=1024, + nics=[{"bridge": "vmbr0"}], + cloud_init_config={"hostname": "vm"}, + storage="local-zfs", + timeout=60, + **image, + ) + ) + + +class TestCreateFromAVolume: + def test_the_file_becomes_the_root_disk_without_a_download(self): + mixin, node = _provisioner() + volid = "software:import/ubuntu-24.04.5-preinstalled-server-amd64.qcow2" + + result = _create(mixin, image_volume=volid) + + mixin._download_cloud_image.assert_not_called() + node.storage.return_value.content.get.assert_not_called() # nothing looked up to download + disk = next( + c.kwargs + for c in node.qemu.return_value.config.post.call_args_list + if "scsi0" in c.kwargs + ) + assert disk["scsi0"] == f"local-zfs:0,import-from={volid},discard=on" + assert result["image_volume"] == volid + + def test_a_download_names_the_file_it_staged(self): + mixin, _ = _provisioner() + result = _create(mixin, image_url=_UBUNTU) + assert result["image_volume"] == f"software:import/{import_volume_name(_UBUNTU)}" + + def test_the_ssh_path_keeps_no_file_on_a_storage(self): + mixin, _ = _provisioner([{"storage": "local-zfs", "content": "images,rootdir"}, + {"storage": "local", "content": "snippets"}]) # fmt: skip + result = _create(mixin, image_url=_UBUNTU) + assert result["image_volume"] is None + + @pytest.mark.parametrize( + "image", + [ + {}, + {"image_url": _UBUNTU, "image_volume": "software:import/x.qcow2"}, + {"image_volume": "software:iso/virtio-win.iso"}, + ], + ids=["neither", "both", "an-iso"], + ) + def test_refuses_before_anything_is_created(self, image: dict): + mixin, _ = _provisioner() + with pytest.raises(ValueError): + _create(mixin, **image) + mixin._api.cluster.nextid.get.assert_not_called() + + def test_refuses_a_file_this_node_does_not_have(self): + mixin, node = _provisioner() + node.storage.return_value.content.return_value.get.side_effect = RuntimeError("500") + with pytest.raises(ValueError, match="not on"): + _create(mixin, image_volume="local:import/elsewhere.qcow2") + mixin._api.cluster.nextid.get.assert_not_called()