fix(console): stop leaking termproxy sessions and orphaned terminals
Some checks failed
Backend Tests / pytest (Python 3.12) (push) Failing after 1m22s
Deploy to Production / Trigger production update (push) Failing after 11s
SonarCloud / SonarCloud Analysis (push) Failing after 2m39s

Opening an LXC console left a failed task on the Proxmox node:

  failed waiting for client: timed out
  TASK ERROR: command '/usr/bin/termproxy 5900 ... vzctlconsole101' failed

connectTerminal() called GET /api/{sid}/container/{vid}/terminal first,
which creates a termproxy session on the node, but only the `node` field
of the response was used - port and ticket were discarded. The ws
endpoint then created a second termproxy session and connected to that
one. Nobody ever attached to the first, so Proxmox waited ~10s for a
client and failed the task.

The console also rendered a black screen in dev: React StrictMode mounts
the effect twice, connect* are async, and the effect cleanup ran before
they had assigned wsRef/termRef, so it had nothing to clean up. Two
xterm instances ended up in the same container - the first one filled
the viewport while the live one was pushed out of the overflow-hidden
area, which is why the badge read "connected" over an empty screen.

- drop the redundant REST call; the ws endpoint owns the termproxy
- remove the now unused GET /api/{server_id}/container/{vmid}/terminal
- add a per-session cancellation guard: a stale connect closes its own
  socket and disposes its own terminal without touching refs that may
  already point at the live session
- route mount and the reconnect button through a single startSession()
  that cancels and tears down the previous session first
- apply the same guard to the node shell page
This commit is contained in:
2026-08-21 21:06:44 +05:00
parent 30e92da8b5
commit 7d60afb9fa
3 changed files with 156 additions and 133 deletions

View File

@@ -2884,79 +2884,6 @@ def get_vm_terminal(
raise HTTPException(status_code=500, detail=str(e))
@router.get("/api/{server_id}/container/{vmid}/terminal")
def get_container_terminal(
server_id: int,
vmid: int,
node: str,
db: Session = Depends(get_db),
current_user: User = Depends(PermissionChecker("vm:console"))
):
"""Получить данные для xterm.js терминального подключения к LXC контейнеру"""
import requests
# VPS-style user isolation: check container ownership for limited users
require_vm_access(db, current_user, server_id, vmid)
server = db.query(ProxmoxServer).filter(ProxmoxServer.id == server_id).first()
if not server:
raise HTTPException(status_code=404, detail="Proxmox server not found")
try:
password_to_use = server.password if server.password else None
auth_username = server.api_user.split("!")[0] if "!" in server.api_user else server.api_user
if not password_to_use:
raise HTTPException(status_code=400, detail="Terminal requires password authentication")
# 1. Получаем auth ticket
auth_response = requests.post(
f"https://{server.ip_address}:8006/api2/json/access/ticket",
data={"username": auth_username, "password": password_to_use},
verify=server.verify_ssl,
timeout=10
)
if auth_response.status_code != 200:
raise HTTPException(status_code=401, detail="Failed to authenticate to Proxmox")
auth_data = auth_response.json().get("data", {})
auth_ticket = auth_data.get("ticket")
csrf_token = auth_data.get("CSRFPreventionToken")
# 2. Создаём terminal proxy
term_response = requests.post(
f"https://{server.ip_address}:8006/api2/json/nodes/{node}/lxc/{vmid}/termproxy",
headers={"CSRFPreventionToken": csrf_token},
cookies={"PVEAuthCookie": auth_ticket},
verify=server.verify_ssl,
timeout=10
)
if term_response.status_code != 200:
raise HTTPException(status_code=500, detail=f"Failed to create terminal proxy: {term_response.text}")
term_data = term_response.json().get("data", {})
response_data = {
'port': term_data.get('port'),
'ticket': term_data.get('ticket'),
'host': server.ip_address,
'node': node,
'vmid': vmid,
'type': 'lxc',
'auth_ticket': auth_ticket
}
logger.info(f"User {current_user.username} opened terminal for LXC {vmid}")
return JSONResponse(content=response_data)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error getting terminal for LXC {vmid}: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/api/{server_id}/container/{vmid}/exec")
async def exec_in_container(
server_id: int,