feat(ipam): several IP addresses per instance
A guest was implicitly limited to a single allocation: lookups were
"(server, vmid) -> one row", release_ip_by_vmid freed one address, and
the link tool skipped guests that already had one. An instance can now
hold a primary address plus any number of aliases, managed from the
Network tab of the instance and visible on the IPAM pages.
Schema and service:
- ipam_allocations gains is_primary, assignment_kind, target_interface
and apply_* columns; migration 43 marks existing rows as primary
- find_allocations_by_resource/set_primary; release_ip_by_vmid now frees
every address of a deleted guest instead of just the first one
- next-available search may scan the whole subnet when a network has no
auto-assign pool, skipping node and cached guest addresses so it never
hands out an address that is already live
Applying to the guest (services/guest_ip_service.py):
- reuses script_engine, so LXC goes through pct exec and VMs through the
guest agent; the shell script synchronises the whole alias list of an
interface, which makes add, remove and retry the same code path
- persists via ifupdown, netplan, NetworkManager or sysconfig and never
restarts guest networking; an unknown stack degrades to runtime_only
and an unreachable guest keeps the allocation as pending
API and UI:
- /ipam/api/guests/{server_id}/{vmid}/addresses: list, add, apply,
primary, delete; allocations list accepts guest filters
- instance list exposes ips[] alongside the primary ip
- addresses card on the Network tab, "+N" badge in the IP column,
primary badge in the allocations table
Fixes found along the way:
- link-allocations registers every address of a guest, carries the MAC
over, refuses to take an address away from another live guest and no
longer matches allocations by resource name (which leaked an address
between same-named guests on different servers)
- IPAM history no longer fails to serialise datetime values, which used
to abort re-linking with a 500
This commit is contained in:
298
backend/tests/test_guest_ip_aliases_script.py
Normal file
298
backend/tests/test_guest_ip_aliases_script.py
Normal file
@@ -0,0 +1,298 @@
|
||||
"""Скрипт синхронизации alias-адресов: детект стека и содержимое конфигов.
|
||||
|
||||
Скрипт запускается настоящим /bin/sh в песочнице: PVEM_ROOT подменяет корень
|
||||
файловой системы, а ip/nmcli/ifup подставляются заглушками через PATH. Так
|
||||
проверяется именно shell-логика — то, что реально выполняется внутри гостя.
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parent.parent / "app" / "services" / "guest_ip" / "sync_aliases.sh"
|
||||
|
||||
FAKE_IP = """#!/bin/sh
|
||||
echo "$*" >> "$FAKE_LOG/ip.log"
|
||||
# 'addr show' печатает пустоту: считаем, что на интерфейсе адресов ещё нет
|
||||
exit 0
|
||||
"""
|
||||
|
||||
FAKE_NMCLI = """#!/bin/sh
|
||||
echo "$*" >> "$FAKE_LOG/nmcli.log"
|
||||
if [ "$1" = "-g" ]; then
|
||||
printf '%s' "$NM_CONNECTION"
|
||||
fi
|
||||
exit 0
|
||||
"""
|
||||
|
||||
FAKE_IFUP = """#!/bin/sh
|
||||
exit 0
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sandbox(tmp_path):
|
||||
"""Песочница с фейковыми ip/nmcli/ifup и пустым «корнем» гостя."""
|
||||
root = tmp_path / "root"
|
||||
bindir = tmp_path / "bin"
|
||||
logdir = tmp_path / "log"
|
||||
for path in (root, bindir, logdir):
|
||||
path.mkdir(parents=True)
|
||||
|
||||
for name, body in (("ip", FAKE_IP), ("nmcli", FAKE_NMCLI), ("ifup", FAKE_IFUP)):
|
||||
target = bindir / name
|
||||
target.write_text(body)
|
||||
target.chmod(0o755)
|
||||
|
||||
def run(addresses="", iface="eth0", nm_connection="", tools=("ip",)):
|
||||
"""Запустить скрипт. tools — какие команды «установлены» в госте."""
|
||||
env = {
|
||||
"PATH": f"{bindir}:{os.environ['PATH']}",
|
||||
"PVEM_ROOT": str(root),
|
||||
"FAKE_LOG": str(logdir),
|
||||
"NM_CONNECTION": nm_connection,
|
||||
"IFACE": iface,
|
||||
"ADDRESSES": addresses,
|
||||
}
|
||||
# Прячем инструменты, которых в этом сценарии быть не должно
|
||||
for name in ("ip", "nmcli", "ifup"):
|
||||
path = bindir / name
|
||||
hidden = bindir / f"{name}.hidden"
|
||||
if name in tools and hidden.exists():
|
||||
hidden.rename(path)
|
||||
elif name not in tools and path.exists():
|
||||
path.rename(hidden)
|
||||
|
||||
result = subprocess.run(
|
||||
["/bin/sh", str(SCRIPT)], env=env, capture_output=True, text=True, timeout=30
|
||||
)
|
||||
return result
|
||||
|
||||
def persist_of(result) -> str:
|
||||
for line in result.stdout.splitlines():
|
||||
if line.startswith("PVEMANAGER_PERSIST="):
|
||||
return line.split("=", 1)[1]
|
||||
raise AssertionError(f"нет маркера persist: {result.stdout} {result.stderr}")
|
||||
|
||||
def log(name: str) -> str:
|
||||
path = logdir / f"{name}.log"
|
||||
return path.read_text() if path.exists() else ""
|
||||
|
||||
return {"root": root, "run": run, "persist_of": persist_of, "log": log}
|
||||
|
||||
|
||||
def _mkdirs(root: Path, *relative: str):
|
||||
for item in relative:
|
||||
(root / item).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
# --- sysconfig / network-scripts ----------------------------------------------
|
||||
|
||||
def test_sysconfig_branch_writes_ifcfg_alias(sandbox):
|
||||
"""RHEL-based LXC: alias закрепляется отдельным ifcfg-файлом."""
|
||||
root = sandbox["root"]
|
||||
_mkdirs(root, "etc/sysconfig/network-scripts")
|
||||
|
||||
result = sandbox["run"](addresses="10.10.10.90/24")
|
||||
|
||||
assert sandbox["persist_of"](result) == "sysconfig"
|
||||
written = (root / "etc/sysconfig/network-scripts/ifcfg-eth0:1").read_text()
|
||||
assert "DEVICE=eth0:1" in written
|
||||
assert "IPADDR=10.10.10.90" in written
|
||||
assert "PREFIX=24" in written
|
||||
assert "BOOTPROTO=none" in written
|
||||
assert "ONBOOT=yes" in written
|
||||
assert "managed by PVEmanager" in written
|
||||
|
||||
|
||||
def test_sysconfig_numbers_aliases_in_order(sandbox):
|
||||
root = sandbox["root"]
|
||||
_mkdirs(root, "etc/sysconfig/network-scripts")
|
||||
|
||||
sandbox["run"](addresses="10.10.10.90/24 10.10.10.91/24")
|
||||
|
||||
scripts = root / "etc/sysconfig/network-scripts"
|
||||
assert "IPADDR=10.10.10.90" in (scripts / "ifcfg-eth0:1").read_text()
|
||||
assert "IPADDR=10.10.10.91" in (scripts / "ifcfg-eth0:2").read_text()
|
||||
|
||||
|
||||
def test_sysconfig_drops_files_of_removed_addresses(sandbox):
|
||||
"""Список сократился — лишний ifcfg удаляется, оставшийся переписывается."""
|
||||
root = sandbox["root"]
|
||||
scripts = root / "etc/sysconfig/network-scripts"
|
||||
_mkdirs(root, "etc/sysconfig/network-scripts")
|
||||
|
||||
sandbox["run"](addresses="10.10.10.90/24 10.10.10.91/24")
|
||||
sandbox["run"](addresses="10.10.10.91/24")
|
||||
|
||||
assert not (scripts / "ifcfg-eth0:2").exists()
|
||||
assert "IPADDR=10.10.10.91" in (scripts / "ifcfg-eth0:1").read_text()
|
||||
|
||||
|
||||
def test_sysconfig_removes_everything_on_empty_list(sandbox):
|
||||
root = sandbox["root"]
|
||||
scripts = root / "etc/sysconfig/network-scripts"
|
||||
_mkdirs(root, "etc/sysconfig/network-scripts")
|
||||
|
||||
sandbox["run"](addresses="10.10.10.90/24")
|
||||
result = sandbox["run"](addresses="")
|
||||
|
||||
assert sandbox["persist_of"](result) == "sysconfig"
|
||||
assert list(scripts.glob("ifcfg-eth0:*")) == []
|
||||
|
||||
|
||||
def test_sysconfig_keeps_foreign_ifcfg_files(sandbox):
|
||||
"""Файлы, написанные не нами, остаются нетронутыми."""
|
||||
root = sandbox["root"]
|
||||
scripts = root / "etc/sysconfig/network-scripts"
|
||||
_mkdirs(root, "etc/sysconfig/network-scripts")
|
||||
foreign = scripts / "ifcfg-eth0:9"
|
||||
foreign.write_text("DEVICE=eth0:9\nIPADDR=10.10.10.250\n")
|
||||
|
||||
sandbox["run"](addresses="10.10.10.90/24")
|
||||
|
||||
assert foreign.exists()
|
||||
assert "10.10.10.250" in foreign.read_text()
|
||||
|
||||
|
||||
def test_sysconfig_removes_alias_del_from_interface(sandbox):
|
||||
"""Ушедший адрес снимается с интерфейса, а не только из конфига."""
|
||||
root = sandbox["root"]
|
||||
_mkdirs(root, "etc/sysconfig/network-scripts")
|
||||
|
||||
sandbox["run"](addresses="10.10.10.90/24")
|
||||
sandbox["run"](addresses="")
|
||||
|
||||
assert "addr del 10.10.10.90/24 dev eth0" in sandbox["log"]("ip")
|
||||
|
||||
|
||||
# --- порядок веток -------------------------------------------------------------
|
||||
|
||||
def test_networkmanager_without_connection_falls_through_to_sysconfig(sandbox):
|
||||
"""nmcli установлен, но интерфейсом не управляет — частый случай в LXC."""
|
||||
root = sandbox["root"]
|
||||
_mkdirs(root, "etc/sysconfig/network-scripts")
|
||||
|
||||
result = sandbox["run"](addresses="10.10.10.90/24", nm_connection="",
|
||||
tools=("ip", "nmcli"))
|
||||
|
||||
assert sandbox["persist_of"](result) == "sysconfig"
|
||||
assert (root / "etc/sysconfig/network-scripts/ifcfg-eth0:1").exists()
|
||||
|
||||
|
||||
def test_networkmanager_with_connection_wins_over_sysconfig(sandbox):
|
||||
root = sandbox["root"]
|
||||
_mkdirs(root, "etc/sysconfig/network-scripts")
|
||||
|
||||
result = sandbox["run"](addresses="10.10.10.90/24", nm_connection="System eth0",
|
||||
tools=("ip", "nmcli"))
|
||||
|
||||
assert sandbox["persist_of"](result) == "nm"
|
||||
assert "+ipv4.addresses 10.10.10.90/24" in sandbox["log"]("nmcli")
|
||||
assert list((root / "etc/sysconfig/network-scripts").glob("ifcfg-*")) == []
|
||||
|
||||
|
||||
def test_networkmanager_drops_previous_address(sandbox):
|
||||
_mkdirs(sandbox["root"], "etc/sysconfig/network-scripts")
|
||||
|
||||
sandbox["run"](addresses="10.10.10.90/24", nm_connection="System eth0",
|
||||
tools=("ip", "nmcli"))
|
||||
sandbox["run"](addresses="10.10.10.91/24", nm_connection="System eth0",
|
||||
tools=("ip", "nmcli"))
|
||||
|
||||
assert "-ipv4.addresses 10.10.10.90/24" in sandbox["log"]("nmcli")
|
||||
|
||||
|
||||
def test_ifupdown_wins_when_several_stacks_present(sandbox):
|
||||
root = sandbox["root"]
|
||||
_mkdirs(root, "etc/network/interfaces.d", "etc/netplan", "etc/sysconfig/network-scripts")
|
||||
(root / "etc/network/interfaces").write_text("auto eth0\niface eth0 inet dhcp\n")
|
||||
|
||||
result = sandbox["run"](addresses="10.10.10.90/24", nm_connection="System eth0",
|
||||
tools=("ip", "nmcli", "ifup"))
|
||||
|
||||
assert sandbox["persist_of"](result) == "ifupdown"
|
||||
written = (root / "etc/network/interfaces.d/pvemanager-aliases-eth0").read_text()
|
||||
assert "iface eth0:1 inet static" in written
|
||||
assert "address 10.10.10.90/24" in written
|
||||
# source-строка дописывается, раз шаблон её не содержит
|
||||
assert "source /etc/network/interfaces.d/*" in (root / "etc/network/interfaces").read_text()
|
||||
|
||||
|
||||
def test_ifupdown_needs_ifup_present(sandbox):
|
||||
"""Каталог interfaces.d без ifupdown — не наш стек, уходим в sysconfig."""
|
||||
root = sandbox["root"]
|
||||
_mkdirs(root, "etc/network/interfaces.d", "etc/sysconfig/network-scripts")
|
||||
(root / "etc/network/interfaces").write_text("auto eth0\n")
|
||||
|
||||
result = sandbox["run"](addresses="10.10.10.90/24", tools=("ip",))
|
||||
|
||||
assert sandbox["persist_of"](result) == "sysconfig"
|
||||
|
||||
|
||||
def test_netplan_branch_writes_yaml(sandbox):
|
||||
root = sandbox["root"]
|
||||
_mkdirs(root, "etc/netplan", "etc/sysconfig/network-scripts")
|
||||
|
||||
result = sandbox["run"](addresses="10.10.10.90/24 10.10.10.91/24")
|
||||
|
||||
assert sandbox["persist_of"](result) == "netplan"
|
||||
written = (root / "etc/netplan/99-pvemanager-aliases.yaml").read_text()
|
||||
assert " eth0:" in written
|
||||
assert " - 10.10.10.90/24" in written
|
||||
assert " - 10.10.10.91/24" in written
|
||||
|
||||
|
||||
def test_no_known_stack_reports_none_but_still_adds_address(sandbox):
|
||||
"""Адрес поднимается всегда; не закрепился — об этом говорит persist=none."""
|
||||
result = sandbox["run"](addresses="10.10.10.90/24")
|
||||
|
||||
assert sandbox["persist_of"](result) == "none"
|
||||
assert "addr add 10.10.10.90/24 dev eth0" in sandbox["log"]("ip")
|
||||
assert "PVEMANAGER_OK=1" in result.stdout
|
||||
|
||||
|
||||
# --- общие инварианты ----------------------------------------------------------
|
||||
|
||||
def test_state_file_tracks_managed_addresses(sandbox):
|
||||
root = sandbox["root"]
|
||||
_mkdirs(root, "etc/sysconfig/network-scripts")
|
||||
|
||||
sandbox["run"](addresses="10.10.10.90/24 10.10.10.91/24")
|
||||
|
||||
assert (root / "var/lib/pvemanager/aliases.eth0").read_text().strip() == \
|
||||
"10.10.10.90/24 10.10.10.91/24"
|
||||
|
||||
|
||||
def test_second_run_is_idempotent(sandbox):
|
||||
"""Повтор с тем же списком не должен ни удалять, ни добавлять заново."""
|
||||
root = sandbox["root"]
|
||||
_mkdirs(root, "etc/sysconfig/network-scripts")
|
||||
|
||||
sandbox["run"](addresses="10.10.10.90/24")
|
||||
before = sandbox["log"]("ip")
|
||||
sandbox["run"](addresses="10.10.10.90/24")
|
||||
added_again = sandbox["log"]("ip")[len(before):]
|
||||
|
||||
assert "addr del" not in added_again
|
||||
|
||||
|
||||
def test_other_interface_aliases_are_untouched(sandbox):
|
||||
root = sandbox["root"]
|
||||
scripts = root / "etc/sysconfig/network-scripts"
|
||||
_mkdirs(root, "etc/sysconfig/network-scripts")
|
||||
|
||||
sandbox["run"](addresses="10.10.10.90/24", iface="eth0")
|
||||
sandbox["run"](addresses="10.10.10.91/24", iface="eth1")
|
||||
|
||||
assert (scripts / "ifcfg-eth0:1").exists()
|
||||
assert (scripts / "ifcfg-eth1:1").exists()
|
||||
|
||||
|
||||
def test_missing_iface_is_rejected(sandbox):
|
||||
result = sandbox["run"](addresses="10.10.10.90/24", iface="")
|
||||
|
||||
assert result.returncode == 2
|
||||
assert "missing IFACE" in result.stdout
|
||||
218
backend/tests/test_guest_ip_service.py
Normal file
218
backend/tests/test_guest_ip_service.py
Normal file
@@ -0,0 +1,218 @@
|
||||
"""Дополнительные адреса гостя: что уезжает в гостя и как трактуется ответ."""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.ipam_service import IPAMService
|
||||
from app.models import IPAMAllocation, IPAMNetwork, ProxmoxServer, VMInstance
|
||||
from app.services import guest_ip_service, script_engine
|
||||
|
||||
|
||||
OK_IFUPDOWN = "PVEMANAGER_PERSIST=ifupdown\nPVEMANAGER_OK=1\n"
|
||||
OK_NO_PERSIST = "PVEMANAGER_PERSIST=none\nPVEMANAGER_OK=1\n"
|
||||
|
||||
|
||||
class _Recorder:
|
||||
"""Подменяет script_engine.execute и запоминает, что ушло в гостя."""
|
||||
|
||||
def __init__(self, result):
|
||||
self.result = result
|
||||
self.calls = []
|
||||
|
||||
def __call__(self, server, **kwargs):
|
||||
self.calls.append(kwargs)
|
||||
return self.result
|
||||
|
||||
@property
|
||||
def last_script(self) -> str:
|
||||
return self.calls[-1]["script"]
|
||||
|
||||
def exported(self, name: str) -> str:
|
||||
"""Значение переменной из блока export, который добавляет render_params."""
|
||||
for line in self.last_script.splitlines():
|
||||
if line.startswith(f"export {name}="):
|
||||
return line.split("=", 1)[1].strip().strip("'")
|
||||
raise AssertionError(f"{name} not exported: {self.last_script[:200]}")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def guest(db_session):
|
||||
server = ProxmoxServer(name="Devserver", ip_address="192.168.43.254", hostname="dev",
|
||||
api_user="root@pam", use_password=True, password="pw")
|
||||
db_session.add(server)
|
||||
db_session.commit()
|
||||
|
||||
network = IPAMNetwork(name="Home-Net", network="10.10.10.0/24", gateway="10.10.10.1",
|
||||
is_active=True)
|
||||
db_session.add(network)
|
||||
db_session.commit()
|
||||
|
||||
instance = VMInstance(server_id=server.id, vmid=120, node="dev", vm_type="lxc",
|
||||
name="act-runner", status="running")
|
||||
db_session.add(instance)
|
||||
db_session.commit()
|
||||
|
||||
service = IPAMService(db_session)
|
||||
|
||||
def add_alias(ip, interface="eth0"):
|
||||
allocation, error = service.allocate_ip(
|
||||
ip_address=ip, network_id=network.id, resource_type="lxc",
|
||||
resource_name="act-runner", proxmox_server_id=server.id, proxmox_vmid=120,
|
||||
proxmox_node="dev", allocated_by="tester", assignment_kind="alias",
|
||||
target_interface=interface, apply_status=guest_ip_service.PENDING,
|
||||
)
|
||||
assert error is None
|
||||
return allocation
|
||||
|
||||
return {"db": db_session, "server": server, "network": network, "instance": instance,
|
||||
"service": service, "add_alias": add_alias}
|
||||
|
||||
|
||||
def _patch(monkeypatch, result):
|
||||
recorder = _Recorder(result)
|
||||
monkeypatch.setattr(guest_ip_service.script_engine, "execute", recorder)
|
||||
return recorder
|
||||
|
||||
|
||||
def test_apply_sends_every_alias_of_the_interface(guest, monkeypatch):
|
||||
"""В гостя уезжает полный список адресов, а не только новый."""
|
||||
guest["add_alias"]("10.10.10.90")
|
||||
second = guest["add_alias"]("10.10.10.91")
|
||||
recorder = _patch(monkeypatch, script_engine.ExecResult(True, OK_IFUPDOWN, 0))
|
||||
|
||||
result = guest_ip_service.apply_address(guest["db"], second)
|
||||
|
||||
assert result.success and result.status == guest_ip_service.APPLIED
|
||||
assert recorder.exported("IFACE") == "eth0"
|
||||
assert recorder.exported("ADDRESSES") == "10.10.10.90/24 10.10.10.91/24"
|
||||
assert recorder.calls[-1]["vm_type"] == "lxc"
|
||||
assert recorder.calls[-1]["vmid"] == 120
|
||||
|
||||
|
||||
def test_prefix_comes_from_the_ipam_network(guest, monkeypatch):
|
||||
guest["network"].network = "10.10.0.0/16"
|
||||
guest["db"].commit()
|
||||
allocation = guest["add_alias"]("10.10.10.90")
|
||||
recorder = _patch(monkeypatch, script_engine.ExecResult(True, OK_IFUPDOWN, 0))
|
||||
|
||||
guest_ip_service.apply_address(guest["db"], allocation)
|
||||
assert recorder.exported("ADDRESSES") == "10.10.10.90/16"
|
||||
|
||||
|
||||
def test_unrecognised_stack_is_runtime_only(guest, monkeypatch):
|
||||
allocation = guest["add_alias"]("10.10.10.90")
|
||||
_patch(monkeypatch, script_engine.ExecResult(True, OK_NO_PERSIST, 0))
|
||||
|
||||
result = guest_ip_service.apply_address(guest["db"], allocation)
|
||||
|
||||
assert result.success
|
||||
assert result.status == guest_ip_service.RUNTIME_ONLY
|
||||
assert allocation.apply_status == guest_ip_service.RUNTIME_ONLY
|
||||
assert allocation.applied_at is not None
|
||||
|
||||
|
||||
def test_unreachable_guest_keeps_allocation_pending(guest, monkeypatch):
|
||||
"""Гость выключен или нет SSH — адрес остаётся за ним, статус pending."""
|
||||
allocation = guest["add_alias"]("10.10.10.90")
|
||||
_patch(monkeypatch, script_engine.ExecResult(
|
||||
False, "", -1, error="Не удалось подключиться по SSH к Devserver"))
|
||||
|
||||
result = guest_ip_service.apply_address(guest["db"], allocation)
|
||||
|
||||
assert not result.success
|
||||
assert result.status == guest_ip_service.PENDING
|
||||
assert allocation.apply_status == guest_ip_service.PENDING
|
||||
assert "SSH" in allocation.apply_error
|
||||
assert allocation.applied_at is None
|
||||
# Аллокация никуда не делась — адрес зарезервирован
|
||||
assert guest["db"].query(IPAMAllocation).count() == 1
|
||||
|
||||
|
||||
def test_script_error_marks_allocation_failed(guest, monkeypatch):
|
||||
allocation = guest["add_alias"]("10.10.10.90")
|
||||
_patch(monkeypatch, script_engine.ExecResult(
|
||||
False, "failed to add 10.10.10.90/24 on eth0", 1))
|
||||
|
||||
result = guest_ip_service.apply_address(guest["db"], allocation)
|
||||
|
||||
assert result.status == guest_ip_service.FAILED
|
||||
assert allocation.apply_status == guest_ip_service.FAILED
|
||||
|
||||
|
||||
def test_missing_ok_marker_is_not_treated_as_success(guest, monkeypatch):
|
||||
"""exit=0 без маркера — скрипт не доработал; успехом это не считаем."""
|
||||
allocation = guest["add_alias"]("10.10.10.90")
|
||||
_patch(monkeypatch, script_engine.ExecResult(True, "some noise", 0))
|
||||
|
||||
result = guest_ip_service.apply_address(guest["db"], allocation)
|
||||
assert not result.success and result.status == guest_ip_service.FAILED
|
||||
|
||||
|
||||
def test_released_address_disappears_from_the_synced_list(guest, monkeypatch):
|
||||
"""Снятие адреса = синхронизация без него: скрипт сам сделает ip addr del."""
|
||||
keep = guest["add_alias"]("10.10.10.90")
|
||||
drop = guest["add_alias"]("10.10.10.91")
|
||||
recorder = _patch(monkeypatch, script_engine.ExecResult(True, OK_IFUPDOWN, 0))
|
||||
|
||||
guest["service"].release_ip(drop.ip_address, released_by="tester")
|
||||
guest_ip_service.sync_interface(guest["db"], guest["server"].id, 120, "eth0")
|
||||
|
||||
assert recorder.exported("ADDRESSES") == "10.10.10.90/24"
|
||||
assert keep.apply_status == guest_ip_service.APPLIED
|
||||
|
||||
|
||||
def test_last_address_removal_sends_empty_list(guest, monkeypatch):
|
||||
only = guest["add_alias"]("10.10.10.90")
|
||||
recorder = _patch(monkeypatch, script_engine.ExecResult(True, OK_IFUPDOWN, 0))
|
||||
|
||||
guest["service"].release_ip(only.ip_address, released_by="tester")
|
||||
guest_ip_service.sync_interface(guest["db"], guest["server"].id, 120, "eth0")
|
||||
|
||||
assert recorder.exported("ADDRESSES") == ""
|
||||
|
||||
|
||||
def test_addresses_of_other_interfaces_are_not_touched(guest, monkeypatch):
|
||||
guest["add_alias"]("10.10.10.90", interface="eth0")
|
||||
guest["add_alias"]("10.10.10.91", interface="eth1")
|
||||
recorder = _patch(monkeypatch, script_engine.ExecResult(True, OK_IFUPDOWN, 0))
|
||||
|
||||
guest_ip_service.sync_interface(guest["db"], guest["server"].id, 120, "eth1")
|
||||
|
||||
assert recorder.exported("IFACE") == "eth1"
|
||||
assert recorder.exported("ADDRESSES") == "10.10.10.91/24"
|
||||
|
||||
|
||||
def test_bogus_interface_name_never_reaches_the_guest(guest, monkeypatch):
|
||||
recorder = _patch(monkeypatch, script_engine.ExecResult(True, OK_IFUPDOWN, 0))
|
||||
|
||||
result = guest_ip_service.sync_interface(
|
||||
guest["db"], guest["server"].id, 120, "eth0; rm -rf /")
|
||||
|
||||
assert not result.success and result.status == guest_ip_service.FAILED
|
||||
assert recorder.calls == []
|
||||
|
||||
|
||||
def test_primary_address_is_not_pushed_into_the_guest(guest, monkeypatch):
|
||||
"""Основной адрес задаётся конфигом Proxmox — скрипт для него не нужен."""
|
||||
allocation, _ = guest["service"].allocate_ip(
|
||||
ip_address="10.10.10.5", network_id=guest["network"].id,
|
||||
proxmox_server_id=guest["server"].id, proxmox_vmid=120,
|
||||
allocated_by="tester", is_primary=True, assignment_kind="primary",
|
||||
)
|
||||
recorder = _patch(monkeypatch, script_engine.ExecResult(True, OK_IFUPDOWN, 0))
|
||||
|
||||
result = guest_ip_service.apply_address(guest["db"], allocation)
|
||||
|
||||
assert result.success
|
||||
assert recorder.calls == []
|
||||
|
||||
|
||||
def test_unknown_guest_is_pending_not_crash(guest, monkeypatch):
|
||||
allocation = guest["add_alias"]("10.10.10.90")
|
||||
guest["instance"].deleted_at = __import__("app.config", fromlist=["utcnow"]).utcnow()
|
||||
guest["db"].commit()
|
||||
recorder = _patch(monkeypatch, script_engine.ExecResult(True, OK_IFUPDOWN, 0))
|
||||
|
||||
result = guest_ip_service.sync_interface(guest["db"], guest["server"].id, 120, "eth0")
|
||||
|
||||
assert result.status == guest_ip_service.PENDING
|
||||
assert recorder.calls == []
|
||||
178
backend/tests/test_ipam_link.py
Normal file
178
backend/tests/test_ipam_link.py
Normal file
@@ -0,0 +1,178 @@
|
||||
"""Tests for IPAM link-allocations: MAC propagation and duplicate-IP handling."""
|
||||
|
||||
import ipaddress
|
||||
|
||||
import pytest
|
||||
|
||||
from app.api.ipam import _extract_ipv4s
|
||||
from app.ipam_service import IPAMService
|
||||
from app.models import IPAMAllocation, IPAMNetwork, ProxmoxServer, VMInstance
|
||||
|
||||
|
||||
# --- _extract_ipv4s -----------------------------------------------------------
|
||||
|
||||
HOME_NET = ipaddress.ip_network("10.10.10.0/24")
|
||||
|
||||
|
||||
class _Net:
|
||||
"""Stand-in for an IPAMNetwork row (only .id is read by the caller)."""
|
||||
|
||||
def __init__(self, id_=1):
|
||||
self.id = id_
|
||||
|
||||
|
||||
def test_extract_returns_mac_and_interface_of_matching_nic():
|
||||
interfaces = [
|
||||
{"name": "eth0", "hardware_address": "bc:24:11:aa:bb:cc",
|
||||
"ips": [{"address": "10.10.10.9", "type": "ipv4", "prefix": 24}]},
|
||||
]
|
||||
found = _extract_ipv4s(interfaces, [(_Net(), HOME_NET)])
|
||||
assert len(found) == 1
|
||||
assert (found[0].ip, found[0].mac, found[0].interface) == (
|
||||
"10.10.10.9", "BC:24:11:AA:BB:CC", "eth0")
|
||||
|
||||
|
||||
def test_extract_returns_every_address_in_ipam_networks():
|
||||
"""Гость с несколькими адресами отдаёт их все, а не только первый."""
|
||||
interfaces = [
|
||||
{"name": "eth0", "hardware_address": "AA:AA:AA:AA:AA:AA",
|
||||
"ips": [{"address": "192.168.99.5", "type": "ipv4", "prefix": 24},
|
||||
{"address": "10.10.10.9", "type": "ipv4", "prefix": 24},
|
||||
{"address": "10.10.10.90", "type": "ipv4", "prefix": 24}]},
|
||||
{"name": "eth1", "hardware_address": "BB:BB:BB:BB:BB:BB",
|
||||
"ips": [{"address": "10.10.10.44", "type": "ipv4", "prefix": 24}]},
|
||||
]
|
||||
found = _extract_ipv4s(interfaces, [(_Net(), HOME_NET)])
|
||||
|
||||
assert [f.ip for f in found] == ["10.10.10.9", "10.10.10.90", "10.10.10.44"]
|
||||
assert [f.interface for f in found] == ["eth0", "eth0", "eth1"]
|
||||
assert found[-1].mac == "BB:BB:BB:BB:BB:BB"
|
||||
|
||||
|
||||
def test_extract_skips_loopback_and_link_local():
|
||||
interfaces = [{"name": "eth0", "ips": [
|
||||
{"address": "127.0.0.1", "type": "ipv4", "prefix": 8},
|
||||
{"address": "169.254.1.5", "type": "ipv4", "prefix": 16},
|
||||
{"address": "10.10.10.9", "type": "ipv4", "prefix": 24},
|
||||
]}]
|
||||
assert [f.ip for f in _extract_ipv4s(interfaces, [(_Net(), HOME_NET)])] == ["10.10.10.9"]
|
||||
|
||||
|
||||
def test_extract_without_mac_returns_none():
|
||||
interfaces = [{"name": "eth0", "ips": [{"address": "10.10.10.9", "type": "ipv4", "prefix": 24}]}]
|
||||
assert _extract_ipv4s(interfaces, [(_Net(), HOME_NET)])[0].mac is None
|
||||
|
||||
|
||||
def test_extract_no_match_returns_empty_list():
|
||||
interfaces = [{"name": "eth0", "hardware_address": "AA:BB:CC:DD:EE:FF",
|
||||
"ips": [{"address": "192.168.43.222", "type": "ipv4", "prefix": 24}]}]
|
||||
assert _extract_ipv4s(interfaces, [(_Net(), HOME_NET)]) == []
|
||||
|
||||
|
||||
# --- sync_from_proxmox_vm -----------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def ipam_env(db_session):
|
||||
"""A server, a network and a helper to add guests."""
|
||||
server = ProxmoxServer(name="Homelab: Dev", ip_address="10.10.10.2", hostname="pve1",
|
||||
api_user="root@pam", use_password=True, password="x")
|
||||
db_session.add(server)
|
||||
db_session.commit()
|
||||
|
||||
network = IPAMNetwork(name="Home-Net", network="10.10.10.0/24", gateway="10.10.10.1",
|
||||
is_active=True)
|
||||
db_session.add(network)
|
||||
db_session.commit()
|
||||
|
||||
def add_guest(vmid, name, vm_type="lxc", deleted_at=None):
|
||||
guest = VMInstance(server_id=server.id, vmid=vmid, node="pve1", vm_type=vm_type,
|
||||
name=name, status="running", deleted_at=deleted_at)
|
||||
db_session.add(guest)
|
||||
db_session.commit()
|
||||
return guest
|
||||
|
||||
return {"db": db_session, "server": server, "network": network, "add_guest": add_guest,
|
||||
"service": IPAMService(db_session)}
|
||||
|
||||
|
||||
def _sync(env, vmid, name, ip, mac=None):
|
||||
return env["service"].sync_from_proxmox_vm(
|
||||
network_id=env["network"].id,
|
||||
proxmox_server_id=env["server"].id,
|
||||
vmid=vmid,
|
||||
vm_name=name,
|
||||
vm_type="lxc",
|
||||
ip_address=ip,
|
||||
node="pve1",
|
||||
mac_address=mac,
|
||||
synced_by="tester",
|
||||
)
|
||||
|
||||
|
||||
def test_sync_stores_mac_on_new_allocation(ipam_env):
|
||||
ipam_env["add_guest"](109, "gitea")
|
||||
alloc, error = _sync(ipam_env, 109, "gitea", "10.10.10.17", "BC:24:11:AA:BB:CC")
|
||||
|
||||
assert error is None
|
||||
assert alloc.mac_address == "BC:24:11:AA:BB:CC"
|
||||
assert alloc.proxmox_vmid == 109
|
||||
|
||||
|
||||
def test_duplicate_ip_does_not_steal_allocation_from_a_live_guest(ipam_env):
|
||||
"""The 10.10.10.101 case: two live guests advertising the same address."""
|
||||
ipam_env["add_guest"](101, "proxmox-center")
|
||||
ipam_env["add_guest"](104, "powerdns-admin")
|
||||
|
||||
first, error = _sync(ipam_env, 101, "proxmox-center", "10.10.10.101")
|
||||
assert error is None and first is not None
|
||||
|
||||
second, error = _sync(ipam_env, 104, "powerdns-admin", "10.10.10.101")
|
||||
assert second is None
|
||||
assert "already linked to proxmox-center" in error
|
||||
assert "VMID 101" in error
|
||||
|
||||
# Owner untouched.
|
||||
alloc = ipam_env["db"].query(IPAMAllocation).filter(
|
||||
IPAMAllocation.ip_address == "10.10.10.101").one()
|
||||
assert (alloc.proxmox_vmid, alloc.resource_name) == (101, "proxmox-center")
|
||||
|
||||
|
||||
def test_allocation_of_a_vanished_guest_is_reclaimed(ipam_env):
|
||||
"""A guest that no longer exists must not hold the address hostage."""
|
||||
ipam_env["add_guest"](101, "old-guest", deleted_at=None)
|
||||
_sync(ipam_env, 101, "old-guest", "10.10.10.101")
|
||||
|
||||
# Guest disappears from Proxmox (soft-deleted by the sync worker).
|
||||
guest = ipam_env["db"].query(VMInstance).filter(VMInstance.vmid == 101).one()
|
||||
from app.config import utcnow
|
||||
guest.deleted_at = utcnow()
|
||||
ipam_env["db"].commit()
|
||||
|
||||
ipam_env["add_guest"](104, "powerdns-admin")
|
||||
alloc, error = _sync(ipam_env, 104, "powerdns-admin", "10.10.10.101")
|
||||
|
||||
assert error is None
|
||||
assert (alloc.proxmox_vmid, alloc.resource_name) == (104, "powerdns-admin")
|
||||
|
||||
|
||||
def test_manual_allocation_without_vmid_is_adopted(ipam_env):
|
||||
"""A hand-made record with no Proxmox link is still linkable."""
|
||||
ipam_env["add_guest"](110, "postgresql")
|
||||
manual, error = ipam_env["service"].allocate_ip(
|
||||
ip_address="10.10.10.19", network_id=ipam_env["network"].id,
|
||||
resource_name="reserved by hand", allocated_by="admin")
|
||||
assert error is None and manual.proxmox_vmid is None
|
||||
|
||||
alloc, error = _sync(ipam_env, 110, "postgresql", "10.10.10.19", "AA:BB:CC:DD:EE:FF")
|
||||
assert error is None
|
||||
assert alloc.proxmox_vmid == 110
|
||||
|
||||
|
||||
def test_resync_of_the_same_guest_is_idempotent(ipam_env):
|
||||
ipam_env["add_guest"](115, "termix")
|
||||
first, _ = _sync(ipam_env, 115, "termix", "10.10.10.36", "AA:11:22:33:44:55")
|
||||
again, error = _sync(ipam_env, 115, "termix", "10.10.10.36", "AA:11:22:33:44:55")
|
||||
|
||||
assert error is None
|
||||
assert again.id == first.id
|
||||
assert ipam_env["db"].query(IPAMAllocation).count() == 1
|
||||
257
backend/tests/test_ipam_multi_ip.py
Normal file
257
backend/tests/test_ipam_multi_ip.py
Normal file
@@ -0,0 +1,257 @@
|
||||
"""Несколько IP-адресов на одном инстансе: сервис, API и колонка IP."""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.ipam_service import IPAMService
|
||||
from app.models import IPAMAllocation, IPAMNetwork, ProxmoxServer, VMInstance
|
||||
from app.services import guest_ip_service, script_engine
|
||||
|
||||
|
||||
OK_OUTPUT = "PVEMANAGER_PERSIST=ifupdown\nPVEMANAGER_OK=1\n"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env(db_session, seed_users):
|
||||
server = ProxmoxServer(name="Homelab: Dev", ip_address="10.10.10.2", hostname="dev",
|
||||
api_user="root@pam", use_password=True, password="pw",
|
||||
is_online=True)
|
||||
db_session.add(server)
|
||||
db_session.commit()
|
||||
|
||||
network = IPAMNetwork(name="Home-Net", network="10.10.10.0/24", gateway="10.10.10.1",
|
||||
is_active=True)
|
||||
db_session.add(network)
|
||||
db_session.commit()
|
||||
|
||||
instance = VMInstance(server_id=server.id, vmid=109, node="dev", vm_type="lxc",
|
||||
name="gitea", status="running")
|
||||
db_session.add(instance)
|
||||
db_session.commit()
|
||||
|
||||
service = IPAMService(db_session)
|
||||
|
||||
def allocate(ip, primary=False, kind="alias", interface="eth0"):
|
||||
allocation, error = service.allocate_ip(
|
||||
ip_address=ip, network_id=network.id, resource_type="lxc", resource_name="gitea",
|
||||
proxmox_server_id=server.id, proxmox_vmid=109, proxmox_node="dev",
|
||||
allocated_by="tester", is_primary=primary, assignment_kind=kind,
|
||||
target_interface=interface,
|
||||
)
|
||||
assert error is None, error
|
||||
return allocation
|
||||
|
||||
return {"db": db_session, "server": server, "network": network, "instance": instance,
|
||||
"service": service, "allocate": allocate}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_real_guest(monkeypatch):
|
||||
"""Скрипт в гостя не уезжает — транспорт проверяется отдельным тестом."""
|
||||
monkeypatch.setattr(
|
||||
guest_ip_service.script_engine, "execute",
|
||||
lambda server, **kwargs: script_engine.ExecResult(True, OK_OUTPUT, 0),
|
||||
)
|
||||
|
||||
|
||||
# --- сервис -------------------------------------------------------------------
|
||||
|
||||
def test_guest_can_hold_several_addresses(env):
|
||||
env["allocate"]("10.10.10.17", primary=True, kind="primary")
|
||||
env["allocate"]("10.10.10.90")
|
||||
env["allocate"]("10.10.10.91")
|
||||
|
||||
rows = env["service"].find_allocations_by_resource(env["server"].id, 109)
|
||||
assert [r.ip_address for r in rows] == ["10.10.10.17", "10.10.10.90", "10.10.10.91"]
|
||||
assert rows[0].is_primary is True
|
||||
|
||||
|
||||
def test_primary_lookup_returns_the_flagged_address(env):
|
||||
env["allocate"]("10.10.10.90")
|
||||
primary = env["allocate"]("10.10.10.17", primary=True, kind="primary")
|
||||
|
||||
found = env["service"].find_allocation_by_resource(env["server"].id, 109)
|
||||
assert found.id == primary.id
|
||||
|
||||
|
||||
def test_lookup_falls_back_to_earliest_without_flag(env):
|
||||
"""Записи старше миграции multi-IP флага не имеют — берём самую раннюю."""
|
||||
first = env["allocate"]("10.10.10.90")
|
||||
env["allocate"]("10.10.10.91")
|
||||
|
||||
found = env["service"].find_allocation_by_resource(env["server"].id, 109)
|
||||
assert found.id == first.id
|
||||
|
||||
|
||||
def test_set_primary_leaves_exactly_one_primary(env):
|
||||
old = env["allocate"]("10.10.10.17", primary=True, kind="primary")
|
||||
new = env["allocate"]("10.10.10.90")
|
||||
|
||||
updated, error = env["service"].set_primary(env["server"].id, 109, new.id, changed_by="tester")
|
||||
|
||||
assert error is None and updated.id == new.id
|
||||
env["db"].refresh(old)
|
||||
assert [a.is_primary for a in env["service"].find_allocations_by_resource(env["server"].id, 109)] \
|
||||
== [True, False]
|
||||
assert old.is_primary is False
|
||||
|
||||
|
||||
def test_set_primary_rejects_foreign_allocation(env):
|
||||
other = env["service"].allocate_ip(
|
||||
ip_address="10.10.10.50", network_id=env["network"].id,
|
||||
proxmox_server_id=env["server"].id, proxmox_vmid=999, allocated_by="tester")[0]
|
||||
|
||||
updated, error = env["service"].set_primary(env["server"].id, 109, other.id)
|
||||
assert updated is None and "does not belong" in error
|
||||
|
||||
|
||||
def test_deleting_a_guest_releases_every_address(env):
|
||||
env["allocate"]("10.10.10.17", primary=True, kind="primary")
|
||||
env["allocate"]("10.10.10.90")
|
||||
env["allocate"]("10.10.10.91")
|
||||
|
||||
released, ips = env["service"].release_ip_by_vmid(env["server"].id, 109, released_by="tester")
|
||||
|
||||
assert released is True
|
||||
assert "10.10.10.17" in ips and "10.10.10.91" in ips
|
||||
assert env["db"].query(IPAMAllocation).count() == 0
|
||||
|
||||
|
||||
# --- API ----------------------------------------------------------------------
|
||||
|
||||
def test_list_addresses_returns_primary_first(env, client, admin_headers):
|
||||
env["allocate"]("10.10.10.90")
|
||||
env["allocate"]("10.10.10.17", primary=True, kind="primary")
|
||||
|
||||
response = client.get(
|
||||
f"/ipam/api/guests/{env['server'].id}/109/addresses", headers=admin_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["count"] == 2
|
||||
assert body["addresses"][0]["ip_address"] == "10.10.10.17"
|
||||
assert body["addresses"][0]["is_primary"] is True
|
||||
assert body["addresses"][0]["prefix"] == "24"
|
||||
|
||||
|
||||
def test_add_address_allocates_and_applies(env, client, admin_headers):
|
||||
response = client.post(
|
||||
f"/ipam/api/guests/{env['server'].id}/109/addresses",
|
||||
headers=admin_headers,
|
||||
json={"network_id": env["network"].id, "ip_address": "10.10.10.90",
|
||||
"target_interface": "eth0"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200, response.text
|
||||
body = response.json()
|
||||
assert body["applied"] is True
|
||||
assert body["apply_status"] == guest_ip_service.APPLIED
|
||||
assert body["address"]["assignment_kind"] == "alias"
|
||||
|
||||
stored = env["db"].query(IPAMAllocation).filter(
|
||||
IPAMAllocation.ip_address == "10.10.10.90").one()
|
||||
assert stored.proxmox_vmid == 109
|
||||
assert stored.target_interface == "eth0"
|
||||
|
||||
|
||||
def test_add_address_picks_next_free_ip(env, client, admin_headers):
|
||||
env["allocate"]("10.10.10.2", primary=True, kind="primary")
|
||||
|
||||
response = client.post(
|
||||
f"/ipam/api/guests/{env['server'].id}/109/addresses",
|
||||
headers=admin_headers,
|
||||
json={"network_id": env["network"].id, "target_interface": "eth0"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200, response.text
|
||||
assigned = response.json()["address"]["ip_address"]
|
||||
assert assigned.startswith("10.10.10.")
|
||||
assert assigned not in ("10.10.10.1", "10.10.10.2") # шлюз и занятый адрес
|
||||
|
||||
|
||||
def test_add_address_can_take_over_as_primary(env, client, admin_headers):
|
||||
old = env["allocate"]("10.10.10.17", primary=True, kind="primary")
|
||||
|
||||
response = client.post(
|
||||
f"/ipam/api/guests/{env['server'].id}/109/addresses",
|
||||
headers=admin_headers,
|
||||
json={"network_id": env["network"].id, "ip_address": "10.10.10.90",
|
||||
"target_interface": "eth0", "make_primary": True},
|
||||
)
|
||||
|
||||
assert response.status_code == 200, response.text
|
||||
env["db"].refresh(old)
|
||||
env["db"].refresh(env["instance"])
|
||||
assert old.is_primary is False
|
||||
# Кэш инстанса показывает новый основной адрес
|
||||
assert env["instance"].ip_address == "10.10.10.90"
|
||||
|
||||
|
||||
def test_duplicate_address_is_rejected(env, client, admin_headers):
|
||||
env["allocate"]("10.10.10.90")
|
||||
|
||||
response = client.post(
|
||||
f"/ipam/api/guests/{env['server'].id}/109/addresses",
|
||||
headers=admin_headers,
|
||||
json={"network_id": env["network"].id, "ip_address": "10.10.10.90",
|
||||
"target_interface": "eth0"},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "already allocated" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_release_address_frees_it(env, client, admin_headers):
|
||||
alias = env["allocate"]("10.10.10.90")
|
||||
|
||||
response = client.delete(
|
||||
f"/ipam/api/guests/{env['server'].id}/109/addresses/{alias.id}", headers=admin_headers)
|
||||
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json()["released"] == "10.10.10.90"
|
||||
assert env["db"].query(IPAMAllocation).filter(
|
||||
IPAMAllocation.ip_address == "10.10.10.90").first() is None
|
||||
|
||||
|
||||
def test_primary_address_cannot_be_released_here(env, client, admin_headers):
|
||||
primary = env["allocate"]("10.10.10.17", primary=True, kind="primary")
|
||||
|
||||
response = client.delete(
|
||||
f"/ipam/api/guests/{env['server'].id}/109/addresses/{primary.id}", headers=admin_headers)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "NIC config" in response.json()["detail"]
|
||||
assert env["db"].query(IPAMAllocation).count() == 1
|
||||
|
||||
|
||||
def test_address_of_another_guest_is_not_accessible(env, client, admin_headers):
|
||||
foreign = env["service"].allocate_ip(
|
||||
ip_address="10.10.10.50", network_id=env["network"].id,
|
||||
proxmox_server_id=env["server"].id, proxmox_vmid=999, allocated_by="tester")[0]
|
||||
|
||||
response = client.delete(
|
||||
f"/ipam/api/guests/{env['server'].id}/109/addresses/{foreign.id}", headers=admin_headers)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_instance_list_exposes_all_addresses(env, client, admin_headers):
|
||||
env["allocate"]("10.10.10.17", primary=True, kind="primary")
|
||||
env["allocate"]("10.10.10.90")
|
||||
|
||||
response = client.get("/proxmox/api/virtual-machines", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
|
||||
vm = next(v for v in response.json() if v["vmid"] == 109)
|
||||
assert vm["ip"] == "10.10.10.17" # колонка IP показывает основной
|
||||
assert [a["ip"] for a in vm["ips"]] == ["10.10.10.17", "10.10.10.90"]
|
||||
assert [a["is_primary"] for a in vm["ips"]] == [True, False]
|
||||
|
||||
|
||||
def test_network_scan_skips_node_and_cached_guest_ips(env):
|
||||
"""Скан вне пула не должен предлагать адрес ноды или известного гостя."""
|
||||
# Нода Homelab: Dev живёт на 10.10.10.2, гость gitea — на 10.10.10.3
|
||||
env["instance"].ip_address = "10.10.10.3"
|
||||
env["db"].commit()
|
||||
|
||||
ip = env["service"].get_next_available_ip(
|
||||
env["network"].id, None, allow_network_scan=True)
|
||||
|
||||
assert ip not in ("10.10.10.1", "10.10.10.2", "10.10.10.3")
|
||||
74
backend/tests/test_vm_list_ipam_lookup.py
Normal file
74
backend/tests/test_vm_list_ipam_lookup.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""IP shown for a guest must come from its own IPAM allocation, never from a
|
||||
same-named guest on another server."""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import IPAMAllocation, IPAMNetwork, ProxmoxServer, VMInstance
|
||||
|
||||
|
||||
@pytest.mark.integration
|
||||
class TestVMListIPAMLookup:
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup(self, db_session, seed_users):
|
||||
def _server(name, ip):
|
||||
server = ProxmoxServer(name=name, hostname=name, ip_address=ip, port=8006,
|
||||
api_user="root@pam", use_password=True, password="pw",
|
||||
verify_ssl=False, is_online=False)
|
||||
db_session.add(server)
|
||||
db_session.commit()
|
||||
db_session.refresh(server)
|
||||
return server
|
||||
|
||||
# Two distinct servers, each with its own node that happens to share a name.
|
||||
self.server_a = _server("homelab-dev", "10.10.10.2")
|
||||
self.server_b = _server("devserver", "192.168.43.254")
|
||||
|
||||
network = IPAMNetwork(name="Home-Net", network="10.10.10.0/24",
|
||||
gateway="10.10.10.1", is_active=True)
|
||||
db_session.add(network)
|
||||
db_session.commit()
|
||||
|
||||
# Same guest name on both servers — the real-world "wireguard" case.
|
||||
self.linked = VMInstance(server_id=self.server_a.id, vmid=107, node="dev",
|
||||
vm_type="lxc", name="wireguard", status="running")
|
||||
self.other = VMInstance(server_id=self.server_b.id, vmid=102, node="dev",
|
||||
vm_type="lxc", name="wireguard", status="running")
|
||||
db_session.add_all([self.linked, self.other])
|
||||
db_session.commit()
|
||||
|
||||
db_session.add(IPAMAllocation(
|
||||
ip_address="10.10.10.35", network_id=network.id, status="allocated",
|
||||
resource_type="lxc", resource_name="wireguard",
|
||||
proxmox_server_id=self.server_a.id, proxmox_vmid=107, proxmox_node="dev",
|
||||
))
|
||||
db_session.commit()
|
||||
self.db = db_session
|
||||
|
||||
def _instances(self, client, headers):
|
||||
response = client.get("/proxmox/api/virtual-machines", headers=headers)
|
||||
assert response.status_code == 200
|
||||
return {(vm["server_id"], vm["vmid"]): vm for vm in response.json()}
|
||||
|
||||
def test_allocation_is_not_shared_with_a_same_named_guest(self, client, admin_headers):
|
||||
vms = self._instances(client, admin_headers)
|
||||
|
||||
assert vms[(self.server_a.id, 107)]["ip"] == "10.10.10.35"
|
||||
# The namesake on the other server owns no allocation and has no cached IP.
|
||||
assert vms[(self.server_b.id, 102)]["ip"] == ""
|
||||
|
||||
def test_cached_ip_still_wins_when_no_allocation_exists(self, client, admin_headers):
|
||||
self.other.ip_address = "192.168.43.246"
|
||||
self.db.commit()
|
||||
|
||||
vms = self._instances(client, admin_headers)
|
||||
assert vms[(self.server_b.id, 102)]["ip"] == "192.168.43.246"
|
||||
assert vms[(self.server_a.id, 107)]["ip"] == "10.10.10.35"
|
||||
|
||||
def test_allocation_hostname_does_not_leak_either(self, client, admin_headers):
|
||||
"""A hostname on the allocation used to match guests by name as well."""
|
||||
alloc = self.db.query(IPAMAllocation).one()
|
||||
alloc.hostname = "wireguard"
|
||||
self.db.commit()
|
||||
|
||||
vms = self._instances(client, admin_headers)
|
||||
assert vms[(self.server_b.id, 102)]["ip"] == ""
|
||||
Reference in New Issue
Block a user