Files
napalm-proxmox/tests/test_storage_images.py
T
Christian Manivong cd60286ac1
driver / lint (pull_request) Successful in 12s
driver / standard (pull_request) Successful in 15s
driver / lowest (pull_request) Successful in 28s
driver / types (pull_request) Successful in 50s
driver / test (3.12) (pull_request) Successful in 1m1s
driver / test (3.13) (pull_request) Successful in 1m0s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 59s
CI / driver (pull_request) Successful in 1m42s
driver / publish (pull_request) Skipped
fix: the root-disk step refuses a missing source instead of asserting it
bandit (B101): an assert vanishes under python -O. The source check refuses
a VM with neither image_url nor image_volume before anything is created; the
root-disk step now raises the same ValueError should it ever be reached.
2026-12-06 22:26:05 +01:00

433 lines
18 KiB
Python

"""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()
def test_the_root_disk_without_a_source_is_refused_even_past_the_check(self):
"""The check refuses it first; the disk step refuses it too, never assumes it."""
mixin, _ = _provisioner()
with pytest.raises(ValueError, match="image_url or image_volume"):
mixin._attach_root_disk(101, "local-zfs", (None, None), None, 60, 60)