feat(ipam): several IP addresses per instance
Some checks failed
Backend Tests / pytest (Python 3.12) (push) Failing after 1m46s
Deploy to Production / Trigger production update (push) Failing after 10s
SonarCloud / SonarCloud Analysis (push) Failing after 3m7s

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:
2026-08-21 23:48:20 +05:00
parent c9d8e8207f
commit 6796903712
23 changed files with 2865 additions and 146 deletions

View File

@@ -1838,6 +1838,48 @@ def migrate_app_operations_server_id(conn):
logger.info("✓ app_operations.server_id already exists")
def migrate_ipam_multi_ip(conn):
"""Migration 43: несколько IP-адресов на одного гостя.
Раньше на (server_id, vmid) подразумевалась ровно одна аллокация. Теперь
их может быть несколько: один основной (net0/ipconfig0, попадает в колонку
IP) и произвольное число алиасов, навешенных внутри гостя. Колонки
apply_* хранят состояние применения алиаса к живому гостю.
"""
if not table_exists(conn, 'ipam_allocations'):
logger.info("Table ipam_allocations does not exist, skipping multi-IP migration")
return
added = False
for column, ddl in (
('is_primary', 'BOOLEAN NOT NULL DEFAULT FALSE'),
('assignment_kind', "VARCHAR(10) NOT NULL DEFAULT 'primary'"),
('target_interface', 'VARCHAR(20)'),
('apply_status', 'VARCHAR(20)'),
('apply_error', 'TEXT'),
('applied_at', 'TIMESTAMP WITH TIME ZONE'),
):
if add_column_if_not_exists(conn, 'ipam_allocations', column, ddl):
added = True
if added:
conn.execute(text(
"CREATE INDEX IF NOT EXISTS idx_ipam_alloc_primary "
"ON ipam_allocations(proxmox_server_id, proxmox_vmid, is_primary)"
))
# Всё, что существовало до этой миграции, было единственным адресом
# своего гостя — значит основным. Записи без привязки к гостю
# (ручные брони) основными не считаем.
conn.execute(text("""
UPDATE ipam_allocations
SET is_primary = TRUE, assignment_kind = 'primary'
WHERE proxmox_vmid IS NOT NULL AND is_primary = FALSE
"""))
logger.info("✓ Added multi-IP columns to ipam_allocations")
else:
logger.info("✓ ipam_allocations multi-IP columns already exist")
def migrate_setting_view_panel_only(conn):
"""Migration 42: drop setting:view where it was only granting the profile page.
@@ -2247,6 +2289,14 @@ def run_all_migrations(engine, db_session=None):
logger.warning(f"setting:view split migration: {e}")
conn.rollback()
# Migration 43: several IP addresses per guest
try:
migrate_ipam_multi_ip(conn)
conn.commit()
except Exception as e:
logger.warning(f"IPAM multi-IP migration: {e}")
conn.rollback()
logger.info("=" * 50)
logger.info("✓ All migrations completed successfully")
logger.info("=" * 50)