From c9d8e8207f4ea7fb1f79877cfe9863bac2e920ed Mon Sep 17 00:00:00 2001 From: Dilshod Rasulov Date: Fri, 21 Aug 2026 23:47:45 +0500 Subject: [PATCH] fix(proxmox): read LXC addresses from netN and live interfaces get_container_interfaces() looked for ipconfigN keys, which exist only on QEMU cloud-init guests. LXC keeps the address inside the netN string, so the method never returned anything and containers showed no IP at all. Parse netN with the existing net_parser, fall back to /nodes/{node}/lxc/{vmid}/interfaces for DHCP guests (skipped when the config already carries a static address or the container is stopped), and validate addresses so loopback, link-local and the literal "dhcp" are dropped. IPv6 from ip6/inet6 is reported as well. --- backend/app/proxmox/client.py | 119 +++++++++++++-------- backend/tests/test_container_interfaces.py | 105 ++++++++++++++++++ 2 files changed, 179 insertions(+), 45 deletions(-) create mode 100644 backend/tests/test_container_interfaces.py diff --git a/backend/app/proxmox/client.py b/backend/app/proxmox/client.py index 54ade4e..5e39a85 100644 --- a/backend/app/proxmox/client.py +++ b/backend/app/proxmox/client.py @@ -1,4 +1,5 @@ import time +import ipaddress import urllib3 import asyncio from concurrent.futures import ThreadPoolExecutor @@ -10,6 +11,7 @@ from functools import lru_cache from contextlib import asynccontextmanager import base64 +from .net_parser import parse_guest_nics from .mixins.vm import VmMixin from .mixins.lxc import LxcMixin from .mixins.cluster import ClusterMixin @@ -1642,62 +1644,89 @@ class ProxmoxClient(VmMixin, LxcMixin, ClusterMixin, StorageMixin, NetworkMixin, logger.debug(f"netstat unavailable for node {node}: {e}") return [] - def get_container_interfaces(self, node: str, vmid: int) -> List[Dict]: + def get_container_interfaces(self, node: str, vmid: int, + include_live: bool = True) -> List[Dict]: """ - Получить сетевые интерфейсы контейнера - + Получить сетевые интерфейсы контейнера с их IP адресами. + + LXC держит адрес внутри строки netN + ("name=eth0,bridge=vmbr0,hwaddr=..,ip=10.0.0.5/24"); ключа ipconfigN у + контейнеров не бывает — это cloud-init QEMU. При ip=dhcp статики в + конфиге нет вовсе, поэтому фактические адреса запущенного контейнера + дочитываются из /nodes/{node}/lxc/{vmid}/interfaces. + Args: node: Имя ноды vmid: ID контейнера - + include_live: опрашивать ли /interfaces (бесполезно для остановленного CT) + Returns: - Список интерфейсов с IP адресами + Список интерфейсов: {'name', 'hardware_address', 'ips': [{'address', 'type', 'prefix'}]} """ if not self.proxmox: return [] - + + interfaces: Dict[str, Dict] = {} + + def _slot(name: str, mac: str = '') -> Dict: + iface = interfaces.setdefault( + name, {'name': name, 'hardware_address': '', 'ips': []} + ) + if mac and not iface['hardware_address']: + iface['hardware_address'] = mac + return iface + + def _add_ip(iface: Dict, value: str) -> None: + """Принимает '10.0.0.5/24' либо '10.0.0.5'; мусор и dhcp игнорирует.""" + addr, _, prefix = (value or '').strip().partition('/') + if not addr or addr in ('dhcp', 'manual', 'auto'): + return + try: + ip_obj = ipaddress.ip_address(addr) + except ValueError: + return + if ip_obj.is_loopback or ip_obj.is_link_local: + return + if any(existing['address'] == addr for existing in iface['ips']): + return + iface['ips'].append({ + 'address': addr, + 'type': 'ipv6' if ip_obj.version == 6 else 'ipv4', + 'prefix': int(prefix) if prefix.isdigit() else (128 if ip_obj.version == 6 else 32), + }) + + # 1) Статика из конфига контейнера try: - # Для LXC можем получить IP из конфигурации config = self.proxmox.nodes(node).lxc(vmid).config.get() - interfaces = [] - - # Проверяем net0, net1 и т.д. - for i in range(10): - net_key = f'net{i}' - if net_key in config: - net_config = config[net_key] - # Парсим строку конфигурации сети - iface_info = {'name': f'eth{i}', 'ips': []} - - # Пытаемся извлечь MAC адрес - if 'hwaddr=' in net_config: - mac = net_config.split('hwaddr=')[1].split(',')[0] - iface_info['hardware_address'] = mac - - interfaces.append(iface_info) - - # Также проверяем IP из конфигурации - for i in range(10): - ipconfig_key = f'ipconfig{i}' - if ipconfig_key in config and interfaces and i < len(interfaces): - ipconfig = config[ipconfig_key] - # Парсим ip=192.168.1.10/24,gw=192.168.1.1 - if 'ip=' in ipconfig: - ip_part = ipconfig.split('ip=')[1].split(',')[0] - if ip_part != 'dhcp': - # Разделяем IP и префикс - if '/' in ip_part: - ip, prefix = ip_part.split('/') - interfaces[i]['ips'].append({ - 'address': ip, - 'type': 'ipv4', - 'prefix': int(prefix) - }) - - return [iface for iface in interfaces if iface.get('ips')] + for nic in parse_guest_nics(config): + iface = _slot(nic.name or f'eth{nic.index}', nic.mac or '') + _add_ip(iface, nic.ip or '') + _add_ip(iface, nic.ip6 or '') except Exception as e: - logger.debug(f"Не удалось получить сетевые интерфейсы контейнера {vmid}: {e}") - return [] + logger.debug(f"Не удалось прочитать конфиг контейнера {vmid}: {e}") + + # 2) Живые адреса — единственный источник для DHCP-контейнеров. + # Если статика уже найдена, лишний запрос не делаем: у остановленного + # контейнера этот эндпоинт всё равно отдаёт ошибку. + has_static_v4 = any( + ip_info['type'] == 'ipv4' + for iface in interfaces.values() for ip_info in iface['ips'] + ) + if not has_static_v4 and include_live: + try: + for iface_data in (self.proxmox.nodes(node).lxc(vmid).interfaces.get() or []): + name = iface_data.get('name') or '' + if not name or name == 'lo': + continue + iface = _slot(name, (iface_data.get('hwaddr') or '').upper()) + _add_ip(iface, iface_data.get('inet') or '') + _add_ip(iface, iface_data.get('inet6') or '') + except Exception as e: + logger.debug( + f"Интерфейсы контейнера {vmid} недоступны (возможно, остановлен): {e}" + ) + + return [iface for iface in interfaces.values() if iface['ips']] def execute_command(self, node: str, vmid: int, command: str, timeout: int = 30) -> Dict: """ diff --git a/backend/tests/test_container_interfaces.py b/backend/tests/test_container_interfaces.py new file mode 100644 index 0000000..42395c7 --- /dev/null +++ b/backend/tests/test_container_interfaces.py @@ -0,0 +1,105 @@ +from unittest.mock import MagicMock + +from app.proxmox.client import ProxmoxClient + + +def _client_with_mock(proxmox): + c = ProxmoxClient.__new__(ProxmoxClient) + c.proxmox = proxmox + return c + + +def _lxc_mock(config=None, interfaces=None): + """MagicMock whose nodes(..).lxc(..).config/.interfaces behave like Proxmox.""" + px = MagicMock() + lxc = px.nodes.return_value.lxc.return_value + if isinstance(config, Exception): + lxc.config.get.side_effect = config + else: + lxc.config.get.return_value = config or {} + if isinstance(interfaces, Exception): + lxc.interfaces.get.side_effect = interfaces + else: + lxc.interfaces.get.return_value = interfaces or [] + return px, lxc + + +def test_static_ip_comes_from_net0_not_ipconfig(): + px, lxc = _lxc_mock(config={ + "hostname": "gitea", + "net0": "name=eth0,bridge=vmbr0,hwaddr=BC:24:11:AA:BB:CC,ip=10.10.10.9/24,gw=10.10.10.1,type=veth", + }) + ifaces = _client_with_mock(px).get_container_interfaces("pve1", 109) + + assert ifaces == [{ + "name": "eth0", + "hardware_address": "BC:24:11:AA:BB:CC", + "ips": [{"address": "10.10.10.9", "type": "ipv4", "prefix": 24}], + }] + # Static address is authoritative — no extra call to the live endpoint. + lxc.interfaces.get.assert_not_called() + + +def test_dhcp_container_falls_back_to_live_interfaces(): + px, _ = _lxc_mock( + config={"net0": "name=eth0,bridge=vmbr0,hwaddr=BC:24:11:00:11:22,ip=dhcp,type=veth"}, + interfaces=[ + {"name": "lo", "inet": "127.0.0.1/8"}, + {"name": "eth0", "hwaddr": "bc:24:11:00:11:22", "inet": "10.10.10.55/24", + "inet6": "fe80::be24:11ff:fe00:1122/64"}, + ], + ) + ifaces = _client_with_mock(px).get_container_interfaces("pve1", 120) + + assert ifaces == [{ + "name": "eth0", + "hardware_address": "BC:24:11:00:11:22", + "ips": [{"address": "10.10.10.55", "type": "ipv4", "prefix": 24}], + }] + + +def test_stopped_dhcp_container_yields_nothing(): + px, _ = _lxc_mock( + config={"net0": "name=eth0,bridge=vmbr0,ip=dhcp,type=veth"}, + interfaces=RuntimeError("500 CT is not running"), + ) + assert _client_with_mock(px).get_container_interfaces("pve1", 120) == [] + + +def test_multiple_nics_and_ipv6_static(): + px, _ = _lxc_mock(config={ + "net0": "name=eth0,bridge=vmbr0,ip=10.10.10.9/24,gw=10.10.10.1", + "net1": "name=eth1,bridge=vmbr1,ip=192.168.50.4/24,ip6=2001:db8::4/64", + }) + ifaces = _client_with_mock(px).get_container_interfaces("pve1", 121) + + assert [i["name"] for i in ifaces] == ["eth0", "eth1"] + assert ifaces[1]["ips"] == [ + {"address": "192.168.50.4", "type": "ipv4", "prefix": 24}, + {"address": "2001:db8::4", "type": "ipv6", "prefix": 64}, + ] + + +def test_unreadable_config_still_tries_live_interfaces(): + px, _ = _lxc_mock( + config=RuntimeError("permission denied"), + interfaces=[{"name": "eth0", "hwaddr": "aa:bb:cc:dd:ee:ff", "inet": "10.0.0.7/24"}], + ) + ifaces = _client_with_mock(px).get_container_interfaces("pve1", 122) + assert ifaces[0]["ips"] == [{"address": "10.0.0.7", "type": "ipv4", "prefix": 24}] + + +def test_no_proxmox_connection(): + c = ProxmoxClient.__new__(ProxmoxClient) + c.proxmox = None + assert c.get_container_interfaces("pve1", 100) == [] + + +def test_include_live_false_skips_live_endpoint(): + px, lxc = _lxc_mock( + config={"net0": "name=eth0,bridge=vmbr0,ip=dhcp,type=veth"}, + interfaces=[{"name": "eth0", "inet": "10.0.0.8/24"}], + ) + # Stopped container: querying /interfaces would only produce a 500. + assert _client_with_mock(px).get_container_interfaces("pve1", 130, include_live=False) == [] + lxc.interfaces.get.assert_not_called()