Skip to content

Commit c53a07e

Browse files
committed
refactor(vmm): resolve username in _get_discovery_dirs instead of caller
1 parent 77a9717 commit c53a07e

1 file changed

Lines changed: 13 additions & 19 deletions

File tree

vmm/src/vmm-cli.py

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,21 @@
3737
# VMM discovery directories
3838
# Each user's instances are in $XDG_RUNTIME_DIR/dstack-vmm (typically /run/user/<uid>/dstack-vmm).
3939
# CLI scans all users' directories so operators can see every instance on the host.
40-
def _get_discovery_dirs() -> List[str]:
40+
def _get_discovery_dirs() -> List[Tuple[str, Optional[str]]]:
41+
"""Return list of (discovery_dir, username) tuples."""
42+
import pwd
4143
dirs = []
42-
# Scan all /run/user/*/dstack-vmm
4344
run_user = "/run/user"
4445
if os.path.isdir(run_user):
4546
try:
46-
for uid_dir in os.listdir(run_user):
47-
candidate = os.path.join(run_user, uid_dir, "dstack-vmm")
47+
for uid_str in os.listdir(run_user):
48+
candidate = os.path.join(run_user, uid_str, "dstack-vmm")
4849
if os.path.isdir(candidate):
49-
dirs.append(candidate)
50+
try:
51+
username = pwd.getpwuid(int(uid_str)).pw_name
52+
except (KeyError, ValueError):
53+
username = f"uid:{uid_str}"
54+
dirs.append((candidate, username))
5055
except PermissionError:
5156
pass
5257
return dirs
@@ -76,19 +81,8 @@ def discover_vmm_instances() -> List[Dict[str, Any]]:
7681
List of VMM instance info dicts, sorted by started_at.
7782
7883
"""
79-
import pwd
8084
instances = []
81-
for discovery_dir in _get_discovery_dirs():
82-
# Extract uid from /run/user/<uid>/dstack-vmm path
83-
parts = discovery_dir.split('/')
84-
uid_str = parts[3] if len(parts) > 3 and parts[1] == 'run' and parts[2] == 'user' else None
85-
username = None
86-
if uid_str and uid_str.isdigit():
87-
try:
88-
username = pwd.getpwuid(int(uid_str)).pw_name
89-
except KeyError:
90-
username = f"uid:{uid_str}"
91-
85+
for discovery_dir, username in _get_discovery_dirs():
9286
for fname in os.listdir(discovery_dir):
9387
if not fname.endswith(".json"):
9488
continue
@@ -100,7 +94,7 @@ def discover_vmm_instances() -> List[Dict[str, Any]]:
10094
if pid and not os.path.exists(f"/proc/{pid}"):
10195
continue
10296
if username:
103-
info['user'] = username
97+
info["user"] = username
10498
instances.append(info)
10599
except (json.JSONDecodeError, FileNotFoundError, PermissionError):
106100
continue
@@ -186,7 +180,7 @@ def cmd_ls_vmm(args):
186180

187181
if not instances:
188182
print("No running VMM instances found.")
189-
print(f" (scanned: {', '.join(_get_discovery_dirs()) or '/run/user/*/dstack-vmm'})")
183+
print(f" (scanned: {', '.join(d for d, _ in _get_discovery_dirs()) or '/run/user/*/dstack-vmm'})")
190184
return
191185

192186
if getattr(args, "json", False):

0 commit comments

Comments
 (0)