diff --git a/backend/app/services/device_discovery.py b/backend/app/services/device_discovery.py index f496fc9..58a51f6 100644 --- a/backend/app/services/device_discovery.py +++ b/backend/app/services/device_discovery.py @@ -479,6 +479,14 @@ async def discover_via_ssh( return result # Step 2: SSH into each rack, parse config, upsert devices + # Build mapping of external_id -> Rack ID for device assignment + rack_id_mapping = {} + from app.models.rack import Rack + all_racks = (await db.execute(select(Rack).where(Rack.object_id == obj.id))).scalars().all() + for rack in all_racks: + if rack.external_id: + rack_id_mapping[rack.external_id] = rack.id + for external_id, rack_host, rack_name in rack_hosts: # Resolve config_path override from the embedded device's connection_params existing_rack_pc = (await db.execute( @@ -563,8 +571,9 @@ async def discover_via_ssh( logger.info(f"[ssh_discovery] Found {len(devices_found)} devices from plugins in {rack_host}") for found in devices_found: - # Hostname: "rack{rack_name}-{plugin_name}", e.g. "rack01-camera_grz" - hostname = f"rack{rack_name}-{found.plugin_name}" + # Hostname: "{external_id}-{plugin_name}", e.g. "lane-1-1-camera_1" + hostname = f"{external_id}-{found.plugin_name}" + rack_id = rack_id_mapping.get(external_id) try: existing = (await db.execute( @@ -583,10 +592,14 @@ async def discover_via_ssh( changes.append(f"role: other→{found.role}") existing.role = found.role # Update hostname if it was never set or still auto-generated - if not existing.hostname or existing.hostname.startswith("rack"): + if not existing.hostname or existing.hostname.startswith("rack") or existing.hostname.startswith("lane"): if existing.hostname != hostname: changes.append(f"hostname: '{existing.hostname}'→'{hostname}'") existing.hostname = hostname + # Update rack_id if not set + if existing.rack_id is None and rack_id is not None: + existing.rack_id = rack_id + changes.append(f"rack_id: None→{rack_id}") if changes: logger.info(f"[ssh_discovery] {found.ip} ({found.plugin_name}) - UPDATED: {', '.join(changes)}") @@ -618,9 +631,10 @@ async def discover_via_ssh( category=found.category, role=found.role, source="auto_ssh", + rack_id=rack_id, device_meta={"plugin": found.plugin_name, "cls": found.cls}, )) - logger.info(f"[ssh_discovery] {found.ip} ({found.plugin_name}) - ADDED: category={found.category}, role={found.role}, hostname={hostname}, source=auto_ssh") + logger.info(f"[ssh_discovery] {found.ip} ({found.plugin_name}) - ADDED: category={found.category}, role={found.role}, hostname={hostname}, rack_id={rack_id}, source=auto_ssh") result.created += 1 result.actions.append(DeviceAction( ip=found.ip,