clonebox 1.1.21__py3-none-any.whl → 1.1.23__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
clonebox/validator.py CHANGED
@@ -1,1415 +1,3 @@
1
- """
2
- VM validation module - validates VM state against YAML configuration.
3
- """
1
+ from clonebox.validation import VMValidator
4
2
 
5
- import subprocess
6
- import json
7
- import base64
8
- import time
9
- import zlib
10
- from typing import Dict, List, Tuple, Optional
11
- from pathlib import Path
12
- from rich.console import Console
13
- from rich.panel import Panel
14
- from rich.table import Table
15
-
16
-
17
- class VMValidator:
18
- """Validates VM configuration against expected state from YAML."""
19
-
20
- def __init__(
21
- self,
22
- config: dict,
23
- vm_name: str,
24
- conn_uri: str,
25
- console: Console = None,
26
- require_running_apps: bool = False,
27
- smoke_test: bool = False,
28
- ):
29
- self.config = config
30
- self.vm_name = vm_name
31
- self.conn_uri = conn_uri
32
- self.console = console or Console()
33
- self.require_running_apps = require_running_apps
34
- self.smoke_test = smoke_test
35
- self.results = {
36
- "mounts": {"passed": 0, "failed": 0, "skipped": 0, "total": 0, "details": []},
37
- "packages": {"passed": 0, "failed": 0, "skipped": 0, "total": 0, "details": []},
38
- "snap_packages": {
39
- "passed": 0,
40
- "failed": 0,
41
- "skipped": 0,
42
- "total": 0,
43
- "details": [],
44
- },
45
- "services": {"passed": 0, "failed": 0, "skipped": 0, "total": 0, "details": []},
46
- "disk": {"usage_pct": 0, "avail": "0", "total": "0"},
47
- "apps": {"passed": 0, "failed": 0, "skipped": 0, "total": 0, "details": []},
48
- "smoke": {"passed": 0, "failed": 0, "skipped": 0, "total": 0, "details": []},
49
- "overall": "unknown",
50
- }
51
-
52
- self._setup_in_progress_cache: Optional[bool] = None
53
- self._exec_transport: str = "qga" # qga|ssh
54
-
55
- def _get_ssh_key_path(self) -> Optional[Path]:
56
- """Return path to the SSH key generated for this VM (if present)."""
57
- try:
58
- if self.conn_uri.endswith("/session"):
59
- images_dir = Path.home() / ".local/share/libvirt/images"
60
- else:
61
- images_dir = Path("/var/lib/libvirt/images")
62
- key_path = images_dir / self.vm_name / "ssh_key"
63
- return key_path if key_path.exists() else None
64
- except Exception:
65
- return None
66
-
67
- def _get_ssh_port(self) -> int:
68
- """Deterministic host-side SSH port for passt port forwarding."""
69
- return 22000 + (zlib.crc32(self.vm_name.encode("utf-8")) % 1000)
70
-
71
- def _ssh_exec(self, command: str, timeout: int = 10) -> Optional[str]:
72
- key_path = self._get_ssh_key_path()
73
- if key_path is None:
74
- return None
75
-
76
- ssh_port = self._get_ssh_port()
77
- user = (self.config.get("vm") or {}).get("username") or "ubuntu"
78
-
79
- try:
80
- result = subprocess.run(
81
- [
82
- "ssh",
83
- "-i",
84
- str(key_path),
85
- "-p",
86
- str(ssh_port),
87
- "-o",
88
- "StrictHostKeyChecking=no",
89
- "-o",
90
- "UserKnownHostsFile=/dev/null",
91
- "-o",
92
- "ConnectTimeout=5",
93
- "-o",
94
- "BatchMode=yes",
95
- f"{user}@127.0.0.1",
96
- command,
97
- ],
98
- capture_output=True,
99
- text=True,
100
- timeout=timeout,
101
- )
102
- if result.returncode != 0:
103
- return None
104
- return (result.stdout or "").strip()
105
- except Exception:
106
- return None
107
-
108
- def _exec_in_vm(self, command: str, timeout: int = 10) -> Optional[str]:
109
- """Execute command in VM using QEMU guest agent, with SSH fallback."""
110
- if self._exec_transport == "ssh":
111
- return self._ssh_exec(command, timeout=timeout)
112
-
113
- try:
114
- # Execute command
115
- result = subprocess.run(
116
- [
117
- "virsh",
118
- "--connect",
119
- self.conn_uri,
120
- "qemu-agent-command",
121
- self.vm_name,
122
- f'{{"execute":"guest-exec","arguments":{{"path":"/bin/sh","arg":["-c","{command}"],"capture-output":true}}}}',
123
- ],
124
- capture_output=True,
125
- text=True,
126
- timeout=timeout,
127
- )
128
-
129
- if result.returncode != 0:
130
- return None
131
-
132
- response = json.loads(result.stdout)
133
- if "return" not in response or "pid" not in response["return"]:
134
- return None
135
-
136
- pid = response["return"]["pid"]
137
-
138
- deadline = time.time() + timeout
139
- while time.time() < deadline:
140
- status_result = subprocess.run(
141
- [
142
- "virsh",
143
- "--connect",
144
- self.conn_uri,
145
- "qemu-agent-command",
146
- self.vm_name,
147
- f'{{"execute":"guest-exec-status","arguments":{{"pid":{pid}}}}}',
148
- ],
149
- capture_output=True,
150
- text=True,
151
- timeout=5,
152
- )
153
-
154
- if status_result.returncode != 0:
155
- return None
156
-
157
- status_resp = json.loads(status_result.stdout)
158
- if "return" not in status_resp:
159
- return None
160
-
161
- ret = status_resp["return"]
162
- if ret.get("exited", False):
163
- if "out-data" in ret:
164
- return base64.b64decode(ret["out-data"]).decode().strip()
165
- return ""
166
-
167
- time.sleep(0.2)
168
-
169
- return None
170
-
171
- except Exception:
172
- return None
173
-
174
- def _setup_in_progress(self) -> Optional[bool]:
175
- if self._setup_in_progress_cache is not None:
176
- return self._setup_in_progress_cache
177
-
178
- out = self._exec_in_vm(
179
- "test -f /var/lib/cloud/instance/boot-finished && echo no || echo yes",
180
- timeout=10,
181
- )
182
- if out is None:
183
- self._setup_in_progress_cache = None
184
- return None
185
-
186
- self._setup_in_progress_cache = out.strip() == "yes"
187
- return self._setup_in_progress_cache
188
-
189
- def validate_mounts(self) -> Dict:
190
- """Validate all mount points and copied data paths."""
191
- setup_in_progress = self._setup_in_progress_cache is True
192
- self.console.print("\n[bold]💾 Validating Mounts & Data...[/]")
193
-
194
- paths = self.config.get("paths", {})
195
- # Support both v1 (app_data_paths) and v2 (copy_paths) config formats
196
- copy_paths = self.config.get("copy_paths", None)
197
- if not isinstance(copy_paths, dict) or not copy_paths:
198
- copy_paths = self.config.get("app_data_paths", {})
199
-
200
- if not paths and not copy_paths:
201
- self.console.print("[dim]No mounts or data paths configured[/]")
202
- return self.results["mounts"]
203
-
204
- # Get mounted filesystems
205
- mount_output = self._exec_in_vm("mount | grep 9p")
206
- mounted_paths = []
207
- if mount_output:
208
- for line in mount_output.split("\n"):
209
- line = line.strip()
210
- if not line:
211
- continue
212
- parts = line.split()
213
- if len(parts) >= 3:
214
- mounted_paths.append(parts[2])
215
-
216
- mount_table = Table(title="Data Validation", border_style="cyan")
217
- mount_table.add_column("Guest Path", style="bold")
218
- mount_table.add_column("Type", justify="center")
219
- mount_table.add_column("Status", justify="center")
220
- mount_table.add_column("Files", justify="right")
221
-
222
- # Validate bind mounts (paths)
223
- for host_path, guest_path in paths.items():
224
- self.results["mounts"]["total"] += 1
225
-
226
- # Check if mounted
227
- is_mounted = any(guest_path in mp for mp in mounted_paths)
228
-
229
- # Check if accessible
230
- accessible = False
231
- file_count = "?"
232
-
233
- if is_mounted:
234
- test_result = self._exec_in_vm(f"test -d {guest_path} && echo 'yes' || echo 'no'")
235
- accessible = test_result == "yes"
236
-
237
- if accessible:
238
- count_str = self._exec_in_vm(f"ls -A {guest_path} 2>/dev/null | wc -l")
239
- if count_str and count_str.isdigit():
240
- file_count = count_str
241
-
242
- if is_mounted and accessible:
243
- status_icon = "[green]✅ Mounted[/]"
244
- self.results["mounts"]["passed"] += 1
245
- status = "pass"
246
- elif is_mounted:
247
- status_icon = "[red]❌ Inaccessible[/]"
248
- self.results["mounts"]["failed"] += 1
249
- status = "mounted_but_inaccessible"
250
- elif setup_in_progress:
251
- status_icon = "[yellow]⏳ Pending[/]"
252
- status = "pending"
253
- self.results["mounts"]["skipped"] += 1
254
- else:
255
- status_icon = "[red]❌ Not Mounted[/]"
256
- self.results["mounts"]["failed"] += 1
257
- status = "not_mounted"
258
-
259
- mount_table.add_row(guest_path, "Bind Mount", status_icon, str(file_count))
260
- self.results["mounts"]["details"].append({
261
- "path": guest_path,
262
- "type": "mount",
263
- "mounted": is_mounted,
264
- "accessible": accessible,
265
- "files": file_count,
266
- "status": status
267
- })
268
-
269
- # Validate copied paths (copy_paths / app_data_paths)
270
- for host_path, guest_path in copy_paths.items():
271
- self.results["mounts"]["total"] += 1
272
-
273
- # Check if exists and has content
274
- exists = False
275
- file_count = "?"
276
-
277
- test_result = self._exec_in_vm(f"test -d {guest_path} && echo 'yes' || echo 'no'")
278
- exists = test_result == "yes"
279
-
280
- if exists:
281
- count_str = self._exec_in_vm(f"ls -A {guest_path} 2>/dev/null | wc -l")
282
- if count_str and count_str.isdigit():
283
- file_count = count_str
284
-
285
- # For copied paths, we just check existence and content
286
- if exists:
287
- # Warning if empty? Maybe, but strictly it passed existence check
288
- status_icon = "[green]✅ Copied[/]"
289
- self.results["mounts"]["passed"] += 1
290
- status = "pass"
291
- elif setup_in_progress:
292
- status_icon = "[yellow]⏳ Pending[/]"
293
- status = "pending"
294
- self.results["mounts"]["skipped"] += 1
295
- else:
296
- status_icon = "[red]❌ Missing[/]"
297
- self.results["mounts"]["failed"] += 1
298
- status = "missing"
299
-
300
- mount_table.add_row(guest_path, "Imported", status_icon, str(file_count))
301
- self.results["mounts"]["details"].append({
302
- "path": guest_path,
303
- "type": "copy",
304
- "mounted": False, # Expected false for copies
305
- "accessible": exists,
306
- "files": file_count,
307
- "status": status
308
- })
309
-
310
- self.console.print(mount_table)
311
- self.console.print(
312
- f"[dim]{self.results['mounts']['passed']}/{self.results['mounts']['total']} paths valid[/]"
313
- )
314
-
315
- return self.results["mounts"]
316
-
317
- def validate_packages(self) -> Dict:
318
- """Validate APT packages are installed."""
319
- setup_in_progress = self._setup_in_progress() is True
320
- self.console.print("\n[bold]📦 Validating APT Packages...[/]")
321
-
322
- packages = self.config.get("packages", [])
323
- if not packages:
324
- self.console.print("[dim]No APT packages configured[/]")
325
- return self.results["packages"]
326
-
327
- total_pkgs = len(packages)
328
- self.console.print(f"[dim]Checking {total_pkgs} packages via QGA...[/]")
329
-
330
- pkg_table = Table(title="Package Validation", border_style="cyan")
331
- pkg_table.add_column("Package", style="bold")
332
- pkg_table.add_column("Status", justify="center")
333
- pkg_table.add_column("Version", style="dim")
334
-
335
- for idx, package in enumerate(packages, 1):
336
- if idx == 1 or idx % 25 == 0 or idx == total_pkgs:
337
- self.console.print(f"[dim] ...packages progress: {idx}/{total_pkgs}[/]")
338
- self.results["packages"]["total"] += 1
339
-
340
- # Check if installed
341
- check_cmd = f"dpkg -l | grep -E '^ii {package}' | awk '{{print $3}}'"
342
- version = self._exec_in_vm(check_cmd)
343
-
344
- if version:
345
- pkg_table.add_row(package, "[green]✅ Installed[/]", version[:40])
346
- self.results["packages"]["passed"] += 1
347
- self.results["packages"]["details"].append(
348
- {"package": package, "installed": True, "version": version}
349
- )
350
- else:
351
- if setup_in_progress:
352
- pkg_table.add_row(package, "[yellow]⏳ Pending[/]", "")
353
- self.results["packages"]["skipped"] += 1
354
- self.results["packages"]["details"].append(
355
- {"package": package, "installed": False, "version": None, "pending": True}
356
- )
357
- else:
358
- pkg_table.add_row(package, "[red]❌ Missing[/]", "")
359
- self.results["packages"]["failed"] += 1
360
- self.results["packages"]["details"].append(
361
- {"package": package, "installed": False, "version": None}
362
- )
363
-
364
- self.console.print(pkg_table)
365
- self.console.print(
366
- f"[dim]{self.results['packages']['passed']}/{self.results['packages']['total']} packages installed[/]"
367
- )
368
-
369
- return self.results["packages"]
370
-
371
- def validate_snap_packages(self) -> Dict:
372
- """Validate snap packages are installed."""
373
- setup_in_progress = self._setup_in_progress() is True
374
- self.console.print("\n[bold]📦 Validating Snap Packages...[/]")
375
-
376
- snap_packages = self.config.get("snap_packages", [])
377
- if not snap_packages:
378
- self.console.print("[dim]No snap packages configured[/]")
379
- return self.results["snap_packages"]
380
-
381
- total_snaps = len(snap_packages)
382
- self.console.print(f"[dim]Checking {total_snaps} snap packages via QGA...[/]")
383
-
384
- snap_table = Table(title="Snap Package Validation", border_style="cyan")
385
- snap_table.add_column("Package", style="bold")
386
- snap_table.add_column("Status", justify="center")
387
- snap_table.add_column("Version", style="dim")
388
-
389
- for idx, package in enumerate(snap_packages, 1):
390
- if idx == 1 or idx % 25 == 0 or idx == total_snaps:
391
- self.console.print(f"[dim] ...snap progress: {idx}/{total_snaps}[/]")
392
- self.results["snap_packages"]["total"] += 1
393
-
394
- # Check if installed
395
- check_cmd = f"snap list | grep '^{package}' | awk '{{print $2}}'"
396
- version = self._exec_in_vm(check_cmd)
397
-
398
- if version:
399
- snap_table.add_row(package, "[green]✅ Installed[/]", version[:40])
400
- self.results["snap_packages"]["passed"] += 1
401
- self.results["snap_packages"]["details"].append(
402
- {"package": package, "installed": True, "version": version}
403
- )
404
- else:
405
- if setup_in_progress:
406
- snap_table.add_row(package, "[yellow]⏳ Pending[/]", "")
407
- self.results["snap_packages"]["skipped"] += 1
408
- self.results["snap_packages"]["details"].append(
409
- {
410
- "package": package,
411
- "installed": False,
412
- "version": None,
413
- "pending": True,
414
- }
415
- )
416
- else:
417
- snap_table.add_row(package, "[red]❌ Missing[/]", "")
418
- self.results["snap_packages"]["failed"] += 1
419
- self.results["snap_packages"]["details"].append(
420
- {"package": package, "installed": False, "version": None}
421
- )
422
-
423
- self.console.print(snap_table)
424
- msg = f"{self.results['snap_packages']['passed']}/{self.results['snap_packages']['total']} snap packages installed"
425
- if self.results["snap_packages"].get("skipped", 0) > 0:
426
- msg += f" ({self.results['snap_packages']['skipped']} pending)"
427
- self.console.print(f"[dim]{msg}[/]")
428
-
429
- return self.results["snap_packages"]
430
-
431
- # Services that should NOT be validated in VM (host-specific)
432
- VM_EXCLUDED_SERVICES = {
433
- "libvirtd",
434
- "virtlogd",
435
- "libvirt-guests",
436
- "qemu-guest-agent",
437
- "bluetooth",
438
- "bluez",
439
- "upower",
440
- "thermald",
441
- "tlp",
442
- "power-profiles-daemon",
443
- "gdm",
444
- "gdm3",
445
- "sddm",
446
- "lightdm",
447
- "snap.cups.cups-browsed",
448
- "snap.cups.cupsd",
449
- "ModemManager",
450
- "wpa_supplicant",
451
- "accounts-daemon",
452
- "colord",
453
- "switcheroo-control",
454
- }
455
-
456
- def validate_services(self) -> Dict:
457
- """Validate services are enabled and running."""
458
- setup_in_progress = self._setup_in_progress() is True
459
- self.console.print("\n[bold]⚙️ Validating Services...[/]")
460
-
461
- services = self.config.get("services", [])
462
- if not services:
463
- self.console.print("[dim]No services configured[/]")
464
- return self.results["services"]
465
-
466
- total_svcs = len(services)
467
- self.console.print(f"[dim]Checking {total_svcs} services via QGA...[/]")
468
-
469
- if "skipped" not in self.results["services"]:
470
- self.results["services"]["skipped"] = 0
471
-
472
- svc_table = Table(title="Service Validation", border_style="cyan")
473
- svc_table.add_column("Service", style="bold")
474
- svc_table.add_column("Enabled", justify="center")
475
- svc_table.add_column("Running", justify="center")
476
- svc_table.add_column("PID", justify="right", style="dim")
477
- svc_table.add_column("Note", style="dim")
478
-
479
- for idx, service in enumerate(services, 1):
480
- if idx == 1 or idx % 25 == 0 or idx == total_svcs:
481
- self.console.print(f"[dim] ...services progress: {idx}/{total_svcs}[/]")
482
- if service in self.VM_EXCLUDED_SERVICES:
483
- svc_table.add_row(service, "[dim]—[/]", "[dim]—[/]", "[dim]—[/]", "host-only")
484
- self.results["services"]["skipped"] += 1
485
- self.results["services"]["details"].append(
486
- {
487
- "service": service,
488
- "enabled": None,
489
- "running": None,
490
- "skipped": True,
491
- "reason": "host-specific service",
492
- }
493
- )
494
- continue
495
-
496
- self.results["services"]["total"] += 1
497
-
498
- enabled_cmd = f"systemctl is-enabled {service} 2>/dev/null"
499
- enabled_status = self._exec_in_vm(enabled_cmd)
500
- is_enabled = enabled_status == "enabled"
501
-
502
- running_cmd = f"systemctl is-active {service} 2>/dev/null"
503
- running_status = self._exec_in_vm(running_cmd)
504
- is_running = running_status == "active"
505
-
506
- pid_value = ""
507
- if is_running:
508
- pid_out = self._exec_in_vm(
509
- f"systemctl show -p MainPID --value {service} 2>/dev/null"
510
- )
511
- if pid_out is None:
512
- pid_value = "?"
513
- else:
514
- pid_value = pid_out.strip() or "?"
515
- else:
516
- pid_value = "—"
517
-
518
- enabled_icon = "[green]✅[/]" if is_enabled else ("[yellow]⏳[/]" if setup_in_progress else "[yellow]⚠️[/]")
519
- running_icon = "[green]✅[/]" if is_running else ("[yellow]⏳[/]" if setup_in_progress else "[red]❌[/]")
520
-
521
- svc_table.add_row(service, enabled_icon, running_icon, pid_value, "")
522
-
523
- if is_enabled and is_running:
524
- self.results["services"]["passed"] += 1
525
- elif setup_in_progress:
526
- self.results["services"]["skipped"] += 1
527
- else:
528
- self.results["services"]["failed"] += 1
529
-
530
- self.results["services"]["details"].append(
531
- {
532
- "service": service,
533
- "enabled": is_enabled,
534
- "running": is_running,
535
- "pid": None if pid_value in ("", "—", "?") else pid_value,
536
- "skipped": False,
537
- }
538
- )
539
-
540
- self.console.print(svc_table)
541
- skipped = self.results["services"].get("skipped", 0)
542
- msg = f"{self.results['services']['passed']}/{self.results['services']['total']} services active"
543
- if skipped > 0:
544
- msg += f" ({skipped} host-only skipped)"
545
- self.console.print(f"[dim]{msg}[/]")
546
-
547
- return self.results["services"]
548
-
549
- def validate_apps(self) -> Dict:
550
- setup_in_progress = self._setup_in_progress() is True
551
- packages = self.config.get("packages", [])
552
- snap_packages = self.config.get("snap_packages", [])
553
- # Support both v1 (app_data_paths) and v2 (copy_paths) config formats
554
- copy_paths = self.config.get("copy_paths", None)
555
- if not isinstance(copy_paths, dict) or not copy_paths:
556
- copy_paths = self.config.get("app_data_paths", {})
557
- vm_user = self.config.get("vm", {}).get("username", "ubuntu")
558
-
559
- snap_app_specs = {
560
- "pycharm-community": {
561
- "process_patterns": ["pycharm-community", "pycharm", "jetbrains"],
562
- "required_interfaces": [
563
- "desktop",
564
- "desktop-legacy",
565
- "x11",
566
- "wayland",
567
- "home",
568
- "network",
569
- ],
570
- },
571
- "chromium": {
572
- "process_patterns": ["chromium", "chromium-browser"],
573
- "required_interfaces": [
574
- "desktop",
575
- "desktop-legacy",
576
- "x11",
577
- "wayland",
578
- "home",
579
- "network",
580
- ],
581
- },
582
- "firefox": {
583
- "process_patterns": ["firefox"],
584
- "required_interfaces": [
585
- "desktop",
586
- "desktop-legacy",
587
- "x11",
588
- "wayland",
589
- "home",
590
- "network",
591
- ],
592
- },
593
- "code": {
594
- "process_patterns": ["code"],
595
- "required_interfaces": [
596
- "desktop",
597
- "desktop-legacy",
598
- "x11",
599
- "wayland",
600
- "home",
601
- "network",
602
- ],
603
- },
604
- }
605
-
606
- expected = []
607
-
608
- if "firefox" in packages:
609
- expected.append("firefox")
610
-
611
- for snap_pkg in snap_packages:
612
- if snap_pkg in snap_app_specs:
613
- expected.append(snap_pkg)
614
-
615
- for _, guest_path in copy_paths.items():
616
- if guest_path == "/home/ubuntu/.config/google-chrome":
617
- expected.append("google-chrome")
618
- break
619
-
620
- expected = sorted(set(expected))
621
- if not expected:
622
- return self.results["apps"]
623
-
624
- self.console.print("\n[bold]🧩 Validating Apps...[/]")
625
- table = Table(title="App Validation", border_style="cyan")
626
- table.add_column("App", style="bold")
627
- table.add_column("Installed", justify="center")
628
- table.add_column("Profile", justify="center")
629
- table.add_column("Running", justify="center")
630
- table.add_column("PID", justify="right", style="dim")
631
- table.add_column("Note", style="dim")
632
-
633
- def _pgrep_pattern(pattern: str) -> str:
634
- if not pattern:
635
- return pattern
636
- return f"[{pattern[0]}]{pattern[1:]}"
637
-
638
- def _check_any_process_running(patterns: List[str]) -> Optional[bool]:
639
- for pattern in patterns:
640
- p = _pgrep_pattern(pattern)
641
- out = self._exec_in_vm(
642
- f"pgrep -u {vm_user} -f '{p}' >/dev/null 2>&1 && echo yes || echo no",
643
- timeout=10,
644
- )
645
- if out is None:
646
- return None
647
- if out == "yes":
648
- return True
649
- return False
650
-
651
- def _find_first_pid(patterns: List[str]) -> Optional[str]:
652
- for pattern in patterns:
653
- p = _pgrep_pattern(pattern)
654
- out = self._exec_in_vm(
655
- f"pgrep -u {vm_user} -f '{p}' 2>/dev/null | head -n 1 || true",
656
- timeout=10,
657
- )
658
- if out is None:
659
- return None
660
- pid = out.strip()
661
- if pid:
662
- return pid
663
- return ""
664
-
665
- def _collect_app_logs(app_name: str) -> str:
666
- chunks: List[str] = []
667
-
668
- def add(cmd: str, title: str, timeout: int = 20):
669
- out = self._exec_in_vm(cmd, timeout=timeout)
670
- if out is None:
671
- return
672
- out = out.strip()
673
- if not out:
674
- return
675
- chunks.append(f"{title}\n$ {cmd}\n{out}")
676
-
677
- if app_name in snap_app_specs:
678
- add(f"snap connections {app_name} 2>/dev/null | head -n 40", "Snap connections")
679
- add(f"snap logs {app_name} -n 80 2>/dev/null | tail -n 60", "Snap logs")
680
-
681
- if app_name == "pycharm-community":
682
- add(
683
- "tail -n 80 /home/ubuntu/snap/pycharm-community/common/.config/JetBrains/*/log/idea.log 2>/dev/null || true",
684
- "idea.log",
685
- )
686
-
687
- if app_name == "google-chrome":
688
- add(
689
- "journalctl -n 200 --no-pager 2>/dev/null | grep -i chrome | tail -n 60 || true",
690
- "Journal (chrome)",
691
- )
692
- if app_name == "firefox":
693
- add(
694
- "journalctl -n 200 --no-pager 2>/dev/null | grep -i firefox | tail -n 60 || true",
695
- "Journal (firefox)",
696
- )
697
-
698
- return "\n\n".join(chunks)
699
-
700
- def _snap_missing_interfaces(snap_name: str, required: List[str]) -> Optional[List[str]]:
701
- out = self._exec_in_vm(
702
- f"snap connections {snap_name} 2>/dev/null | awk 'NR>1{{print $1, $3}}'",
703
- timeout=15,
704
- )
705
- if out is None:
706
- return None
707
-
708
- connected = set()
709
- for line in out.splitlines():
710
- parts = line.split()
711
- if len(parts) < 2:
712
- continue
713
- iface, slot = parts[0], parts[1]
714
- if slot != "-":
715
- connected.add(iface)
716
-
717
- missing = [i for i in required if i not in connected]
718
- return missing
719
-
720
- def _check_dir_nonempty(path: str) -> bool:
721
- out = self._exec_in_vm(
722
- f"test -d {path} && [ $(ls -A {path} 2>/dev/null | wc -l) -gt 0 ] && echo yes || echo no",
723
- timeout=10,
724
- )
725
- return out == "yes"
726
-
727
- for app in expected:
728
- self.results["apps"]["total"] += 1
729
- installed = False
730
- profile_ok = False
731
- running: Optional[bool] = None
732
- pid: Optional[str] = None
733
- note = ""
734
- pending = False
735
-
736
- if app == "firefox":
737
- installed = (
738
- self._exec_in_vm("command -v firefox >/dev/null 2>&1 && echo yes || echo no")
739
- == "yes"
740
- )
741
- if _check_dir_nonempty("/home/ubuntu/snap/firefox/common/.mozilla/firefox"):
742
- profile_ok = True
743
- elif _check_dir_nonempty("/home/ubuntu/.mozilla/firefox"):
744
- profile_ok = True
745
-
746
- if installed:
747
- running = _check_any_process_running(["firefox"])
748
- pid = _find_first_pid(["firefox"]) if running else ""
749
-
750
- elif app in snap_app_specs:
751
- installed = (
752
- self._exec_in_vm(f"snap list {app} >/dev/null 2>&1 && echo yes || echo no")
753
- == "yes"
754
- )
755
- if app == "pycharm-community":
756
- profile_ok = _check_dir_nonempty(
757
- "/home/ubuntu/snap/pycharm-community/common/.config/JetBrains"
758
- )
759
- else:
760
- profile_ok = True
761
-
762
- if installed:
763
- patterns = snap_app_specs[app]["process_patterns"]
764
- running = _check_any_process_running(patterns)
765
- pid = _find_first_pid(patterns) if running else ""
766
- if running is False:
767
- missing_ifaces = _snap_missing_interfaces(
768
- app,
769
- snap_app_specs[app]["required_interfaces"],
770
- )
771
- if missing_ifaces:
772
- note = f"missing interfaces: {', '.join(missing_ifaces)}"
773
- elif missing_ifaces == []:
774
- note = "not running"
775
- else:
776
- note = "interfaces unknown"
777
-
778
- elif app == "google-chrome":
779
- installed = (
780
- self._exec_in_vm(
781
- "(command -v google-chrome >/dev/null 2>&1 || command -v google-chrome-stable >/dev/null 2>&1) && echo yes || echo no"
782
- )
783
- == "yes"
784
- )
785
- profile_ok = _check_dir_nonempty("/home/ubuntu/.config/google-chrome")
786
-
787
- if installed:
788
- running = _check_any_process_running(["google-chrome", "google-chrome-stable"])
789
- pid = (
790
- _find_first_pid(["google-chrome", "google-chrome-stable"])
791
- if running
792
- else ""
793
- )
794
-
795
- if self.require_running_apps and installed and profile_ok and running is None:
796
- note = note or "running unknown"
797
-
798
- if setup_in_progress and not installed:
799
- pending = True
800
- note = note or "setup in progress"
801
- elif setup_in_progress and not profile_ok:
802
- pending = True
803
- note = note or "profile import in progress"
804
-
805
- running_icon = (
806
- "[dim]—[/]"
807
- if not installed
808
- else (
809
- "[green]✅[/]"
810
- if running is True
811
- else "[yellow]⚠️[/]" if running is False else "[dim]?[/]"
812
- )
813
- )
814
-
815
- pid_value = "—" if not installed else ("?" if pid is None else (pid or "—"))
816
-
817
- installed_icon = "[green]✅[/]" if installed else ("[yellow]⏳[/]" if pending else "[red]❌[/]")
818
- profile_icon = "[green]✅[/]" if profile_ok else ("[yellow]⏳[/]" if pending else "[red]❌[/]")
819
-
820
- table.add_row(app, installed_icon, profile_icon, running_icon, pid_value, note)
821
-
822
- should_pass = installed and profile_ok
823
- if self.require_running_apps and installed and profile_ok:
824
- should_pass = running is True
825
-
826
- if pending:
827
- self.results["apps"]["skipped"] += 1
828
- elif should_pass:
829
- self.results["apps"]["passed"] += 1
830
- else:
831
- self.results["apps"]["failed"] += 1
832
-
833
- self.results["apps"]["details"].append(
834
- {
835
- "app": app,
836
- "installed": installed,
837
- "profile": profile_ok,
838
- "running": running,
839
- "pid": pid,
840
- "note": note,
841
- "pending": pending,
842
- }
843
- )
844
-
845
- if installed and profile_ok and running in (False, None):
846
- logs = _collect_app_logs(app)
847
- if logs:
848
- self.console.print(Panel(logs, title=f"Logs: {app}", border_style="yellow"))
849
-
850
- self.console.print(table)
851
- return self.results["apps"]
852
-
853
- def validate_smoke_tests(self) -> Dict:
854
- setup_in_progress = self._setup_in_progress() is True
855
- packages = self.config.get("packages", [])
856
- snap_packages = self.config.get("snap_packages", [])
857
- # Support both v1 (app_data_paths) and v2 (copy_paths) config formats
858
- copy_paths = self.config.get("copy_paths", None)
859
- if not isinstance(copy_paths, dict) or not copy_paths:
860
- copy_paths = self.config.get("app_data_paths", {})
861
- vm_user = self.config.get("vm", {}).get("username", "ubuntu")
862
-
863
- expected = []
864
-
865
- if "firefox" in packages:
866
- expected.append("firefox")
867
-
868
- for snap_pkg in snap_packages:
869
- if snap_pkg in {"pycharm-community", "chromium", "firefox", "code"}:
870
- expected.append(snap_pkg)
871
-
872
- for _, guest_path in copy_paths.items():
873
- if guest_path == "/home/ubuntu/.config/google-chrome":
874
- expected.append("google-chrome")
875
- break
876
-
877
- if "docker" in (self.config.get("services", []) or []) or "docker.io" in packages:
878
- expected.append("docker")
879
-
880
- expected = sorted(set(expected))
881
- if not expected:
882
- return self.results["smoke"]
883
-
884
- def _installed(app: str) -> Optional[bool]:
885
- if app in {"pycharm-community", "chromium", "firefox", "code"}:
886
- out = self._exec_in_vm(
887
- f"snap list {app} >/dev/null 2>&1 && echo yes || echo no", timeout=10
888
- )
889
- return None if out is None else out.strip() == "yes"
890
-
891
- if app == "google-chrome":
892
- out = self._exec_in_vm(
893
- "(command -v google-chrome >/dev/null 2>&1 || command -v google-chrome-stable >/dev/null 2>&1) && echo yes || echo no",
894
- timeout=10,
895
- )
896
- return None if out is None else out.strip() == "yes"
897
-
898
- if app == "docker":
899
- out = self._exec_in_vm(
900
- "command -v docker >/dev/null 2>&1 && echo yes || echo no", timeout=10
901
- )
902
- return None if out is None else out.strip() == "yes"
903
-
904
- if app == "firefox":
905
- out = self._exec_in_vm(
906
- "command -v firefox >/dev/null 2>&1 && echo yes || echo no", timeout=10
907
- )
908
- return None if out is None else out.strip() == "yes"
909
-
910
- out = self._exec_in_vm(
911
- f"command -v {app} >/dev/null 2>&1 && echo yes || echo no", timeout=10
912
- )
913
- return None if out is None else out.strip() == "yes"
914
-
915
- def _run_test(app: str) -> Optional[bool]:
916
- uid_out = self._exec_in_vm(f"id -u {vm_user} 2>/dev/null || true", timeout=10)
917
- vm_uid = (uid_out or "").strip()
918
- if not vm_uid.isdigit():
919
- vm_uid = "1000"
920
-
921
- runtime_dir = f"/run/user/{vm_uid}"
922
- self._exec_in_vm(
923
- f"mkdir -p {runtime_dir} && chown {vm_uid}:{vm_uid} {runtime_dir} && chmod 700 {runtime_dir}",
924
- timeout=10,
925
- )
926
-
927
- user_env = (
928
- f"sudo -u {vm_user} env HOME=/home/{vm_user} USER={vm_user} LOGNAME={vm_user} XDG_RUNTIME_DIR={runtime_dir}"
929
- )
930
-
931
- if app == "pycharm-community":
932
- out = self._exec_in_vm(
933
- "/snap/pycharm-community/current/jbr/bin/java -version >/dev/null 2>&1 && echo yes || echo no",
934
- timeout=20,
935
- )
936
- return None if out is None else out.strip() == "yes"
937
-
938
- if app == "chromium":
939
- out = self._exec_in_vm(
940
- f"{user_env} timeout 20 chromium --headless=new --no-sandbox --disable-gpu --dump-dom about:blank >/dev/null 2>&1 && echo yes || echo no",
941
- timeout=30,
942
- )
943
- return None if out is None else out.strip() == "yes"
944
-
945
- if app == "firefox":
946
- out = self._exec_in_vm(
947
- f"{user_env} timeout 20 firefox --headless --version >/dev/null 2>&1 && echo yes || echo no",
948
- timeout=30,
949
- )
950
- return None if out is None else out.strip() == "yes"
951
-
952
- if app == "google-chrome":
953
- out = self._exec_in_vm(
954
- f"{user_env} timeout 20 google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom about:blank >/dev/null 2>&1 && echo yes || echo no",
955
- timeout=30,
956
- )
957
- return None if out is None else out.strip() == "yes"
958
-
959
- if app == "docker":
960
- out = self._exec_in_vm(
961
- "timeout 20 docker info >/dev/null 2>&1 && echo yes || echo no", timeout=30
962
- )
963
- return None if out is None else out.strip() == "yes"
964
-
965
- out = self._exec_in_vm(
966
- f"timeout 20 {app} --version >/dev/null 2>&1 && echo yes || echo no", timeout=30
967
- )
968
- return None if out is None else out.strip() == "yes"
969
-
970
- self.console.print("\n[bold]🧪 Smoke Tests (installed ≠ works)...[/]")
971
- table = Table(title="Smoke Tests", border_style="cyan")
972
- table.add_column("App", style="bold")
973
- table.add_column("Installed", justify="center")
974
- table.add_column("Launch", justify="center")
975
- table.add_column("Note", style="dim")
976
-
977
- for app in expected:
978
- self.results["smoke"]["total"] += 1
979
- installed = _installed(app)
980
- launched: Optional[bool] = None
981
- note = ""
982
- pending = False
983
-
984
- if installed is True:
985
- launched = _run_test(app)
986
- if launched is None:
987
- note = "test failed to execute"
988
- elif launched is False and setup_in_progress:
989
- pending = True
990
- note = note or "setup in progress"
991
- elif installed is False:
992
- if setup_in_progress:
993
- pending = True
994
- note = "setup in progress"
995
- else:
996
- note = "not installed"
997
- else:
998
- note = "install status unknown"
999
-
1000
- installed_icon = (
1001
- "[green]✅[/]"
1002
- if installed is True
1003
- else ("[yellow]⏳[/]" if pending else "[red]❌[/]")
1004
- if installed is False
1005
- else "[dim]?[/]"
1006
- )
1007
- launch_icon = (
1008
- "[green]✅[/]"
1009
- if launched is True
1010
- else ("[yellow]⏳[/]" if pending else "[red]❌[/]")
1011
- if launched is False
1012
- else ("[dim]—[/]" if installed is not True else "[dim]?[/]")
1013
- )
1014
-
1015
- table.add_row(app, installed_icon, launch_icon, note)
1016
-
1017
- passed = installed is True and launched is True
1018
- if pending:
1019
- self.results["smoke"]["skipped"] += 1
1020
- elif passed:
1021
- self.results["smoke"]["passed"] += 1
1022
- else:
1023
- self.results["smoke"]["failed"] += 1
1024
-
1025
- self.results["smoke"]["details"].append(
1026
- {
1027
- "app": app,
1028
- "installed": installed,
1029
- "launched": launched,
1030
- "note": note,
1031
- "pending": pending,
1032
- }
1033
- )
1034
-
1035
- self.console.print(table)
1036
- return self.results["smoke"]
1037
-
1038
- def _check_qga_ready(self) -> bool:
1039
- """Check if QEMU guest agent is responding."""
1040
- try:
1041
- result = subprocess.run(
1042
- [
1043
- "virsh",
1044
- "--connect",
1045
- self.conn_uri,
1046
- "qemu-agent-command",
1047
- self.vm_name,
1048
- '{"execute":"guest-ping"}',
1049
- ],
1050
- capture_output=True,
1051
- text=True,
1052
- timeout=5,
1053
- )
1054
- return result.returncode == 0
1055
- except Exception:
1056
- return False
1057
-
1058
- def validate_disk_space(self) -> Dict:
1059
- """Validate disk space on root filesystem."""
1060
- setup_in_progress = self._setup_in_progress() is True
1061
- self.console.print("\n[bold]💾 Validating Disk Space...[/]")
1062
-
1063
- df_output = self._exec_in_vm("df -h / --output=pcent,avail,size | tail -n 1", timeout=20)
1064
- if not df_output:
1065
- self.console.print("[red]❌ Could not check disk space[/]")
1066
- return {"status": "error"}
1067
-
1068
- try:
1069
- # Format: pcent avail size
1070
- # Example: 98% 100M 30G
1071
- parts = df_output.split()
1072
- usage_pct = int(parts[0].replace('%', ''))
1073
- avail = parts[1]
1074
- total = parts[2]
1075
-
1076
- self.results["disk"] = {
1077
- "usage_pct": usage_pct,
1078
- "avail": avail,
1079
- "total": total
1080
- }
1081
-
1082
- if usage_pct > 90:
1083
- self.console.print(f"[red]❌ Disk nearly full: {usage_pct}% used ({avail} available of {total})[/]")
1084
- status = "fail"
1085
- elif usage_pct > 85:
1086
- self.console.print(f"[yellow]⚠️ Disk usage high: {usage_pct}% used ({avail} available of {total})[/]")
1087
- status = "warning"
1088
- else:
1089
- self.console.print(f"[green]✅ Disk space OK: {usage_pct}% used ({avail} available of {total})[/]")
1090
- status = "pass"
1091
-
1092
- if usage_pct > 80:
1093
- self._print_disk_usage_breakdown()
1094
-
1095
- return self.results["disk"]
1096
- except Exception as e:
1097
- self.console.print(f"[red]❌ Error parsing df output: {e}[/]")
1098
- return {"status": "error"}
1099
-
1100
- def _print_disk_usage_breakdown(self) -> None:
1101
- def _parse_du_lines(out: Optional[str]) -> List[Tuple[str, str]]:
1102
- if not out:
1103
- return []
1104
- rows: List[Tuple[str, str]] = []
1105
- for line in out.splitlines():
1106
- line = line.strip()
1107
- if not line:
1108
- continue
1109
- parts = line.split(maxsplit=1)
1110
- if len(parts) != 2:
1111
- continue
1112
- size, path = parts
1113
- rows.append((path, size))
1114
- return rows
1115
-
1116
- def _dir_size(path: str, timeout: int = 30) -> Optional[str]:
1117
- out = self._exec_in_vm(f"du -x -s -h {path} 2>/dev/null | head -n 1 | cut -f1", timeout=timeout)
1118
- return out.strip() if out else None
1119
-
1120
- self.console.print("\n[bold]📁 Disk usage breakdown (largest directories)[/]")
1121
-
1122
- top_level = self._exec_in_vm(
1123
- "du -x -h --max-depth=1 / 2>/dev/null | sort -hr | head -n 15",
1124
- timeout=60,
1125
- )
1126
- top_rows = _parse_du_lines(top_level)
1127
-
1128
- if top_rows:
1129
- table = Table(title="Disk Usage: / (Top 15)", border_style="cyan")
1130
- table.add_column("Path", style="bold")
1131
- table.add_column("Size", justify="right")
1132
- for path, size in top_rows:
1133
- table.add_row(path, size)
1134
- self.console.print(table)
1135
- else:
1136
- self.console.print("[dim]Could not compute top-level directory sizes (du may be busy)[/]")
1137
-
1138
- var_sz = _dir_size("/var")
1139
- home_sz = _dir_size("/home")
1140
- if var_sz or home_sz:
1141
- sum_table = Table(title="Disk Usage: Key Directories", border_style="cyan")
1142
- sum_table.add_column("Path", style="bold")
1143
- sum_table.add_column("Size", justify="right")
1144
- for p in ["/var", "/var/lib", "/var/log", "/var/cache", "/var/lib/snapd", "/home", "/home/ubuntu", "/tmp"]:
1145
- sz = _dir_size(p, timeout=30)
1146
- if sz:
1147
- sum_table.add_row(p, sz)
1148
- self.console.print(sum_table)
1149
-
1150
- var_breakdown = self._exec_in_vm(
1151
- "du -x -h --max-depth=1 /var 2>/dev/null | sort -hr | head -n 12",
1152
- timeout=60,
1153
- )
1154
- var_rows = _parse_du_lines(var_breakdown)
1155
- if var_rows:
1156
- vtable = Table(title="Disk Usage: /var (Top 12)", border_style="cyan")
1157
- vtable.add_column("Path", style="bold")
1158
- vtable.add_column("Size", justify="right")
1159
- for path, size in var_rows:
1160
- vtable.add_row(path, size)
1161
- self.console.print(vtable)
1162
-
1163
- home_breakdown = self._exec_in_vm(
1164
- "du -x -h --max-depth=2 /home/ubuntu 2>/dev/null | sort -hr | head -n 12",
1165
- timeout=60,
1166
- )
1167
- home_rows = _parse_du_lines(home_breakdown)
1168
- if home_rows:
1169
- htable = Table(title="Disk Usage: /home/ubuntu (Top 12)", border_style="cyan")
1170
- htable.add_column("Path", style="bold")
1171
- htable.add_column("Size", justify="right")
1172
- for path, size in home_rows:
1173
- htable.add_row(path, size)
1174
- self.console.print(htable)
1175
-
1176
- copy_paths = self.config.get("copy_paths", None)
1177
- if not isinstance(copy_paths, dict) or not copy_paths:
1178
- copy_paths = self.config.get("app_data_paths", {})
1179
- if copy_paths:
1180
- ctable = Table(title="Disk Usage: Configured Imported Paths", border_style="cyan")
1181
- ctable.add_column("Guest Path", style="bold")
1182
- ctable.add_column("Size", justify="right")
1183
- for _, guest_path in copy_paths.items():
1184
- sz = _dir_size(guest_path, timeout=30)
1185
- if sz:
1186
- ctable.add_row(str(guest_path), sz)
1187
- else:
1188
- ctable.add_row(str(guest_path), "—")
1189
- self.console.print(ctable)
1190
-
1191
- def validate_all(self) -> Dict:
1192
- """Run all validations and return comprehensive results."""
1193
- setup_in_progress = self._setup_in_progress() is True
1194
- self.console.print("[bold cyan]🔍 Running Full Validation...[/]")
1195
-
1196
- # Check if VM is running
1197
- try:
1198
- result = subprocess.run(
1199
- ["virsh", "--connect", self.conn_uri, "domstate", self.vm_name],
1200
- capture_output=True,
1201
- text=True,
1202
- timeout=5,
1203
- )
1204
- vm_state = result.stdout.strip()
1205
-
1206
- if "running" not in vm_state.lower():
1207
- self.console.print(f"[yellow]⚠️ VM is not running (state: {vm_state})[/]")
1208
- self.console.print("[dim]Start VM with: clonebox start .[/]")
1209
- self.results["overall"] = "vm_not_running"
1210
- return self.results
1211
- except Exception as e:
1212
- self.console.print(f"[red]❌ Cannot check VM state: {e}[/]")
1213
- self.results["overall"] = "error"
1214
- return self.results
1215
-
1216
- # Check QEMU Guest Agent
1217
- if not self._check_qga_ready():
1218
- wait_deadline = time.time() + 180
1219
- self.console.print("[yellow]⏳ Waiting for QEMU Guest Agent (up to 180s)...[/]")
1220
- last_log = 0
1221
- while time.time() < wait_deadline:
1222
- time.sleep(5)
1223
- if self._check_qga_ready():
1224
- break
1225
- elapsed = int(180 - (wait_deadline - time.time()))
1226
- if elapsed - last_log >= 15:
1227
- self.console.print(f"[dim] ...still waiting for QGA ({elapsed}s elapsed)[/]")
1228
- last_log = elapsed
1229
-
1230
- if not self._check_qga_ready():
1231
- # SSH fallback (primarily for --user networking, where passt can forward ports)
1232
- self.console.print("[yellow]⚠️ QEMU Guest Agent not responding - trying SSH fallback...[/]")
1233
- self._exec_transport = "ssh"
1234
- smoke = self._ssh_exec("echo ok", timeout=10)
1235
- if smoke != "ok":
1236
- self.console.print("[red]❌ SSH fallback failed[/]")
1237
- self.console.print("\n[bold]🔧 Troubleshooting QGA:[/]")
1238
- self.console.print(" 1. The VM might still be booting. Wait 30-60 seconds.")
1239
- self.console.print(" 2. Ensure the agent is installed and running inside the VM:")
1240
- self.console.print(" [dim]virsh console " + self.vm_name + "[/]")
1241
- self.console.print(" [dim]sudo systemctl status qemu-guest-agent[/]")
1242
- self.console.print(" 3. If newly created, cloud-init might still be running.")
1243
- self.console.print(" 4. Check VM logs: [dim]clonebox logs " + self.vm_name + "[/]")
1244
- self.console.print(f"\n[yellow]⚠️ Skipping deep validation as it requires a working Guest Agent or SSH access.[/]")
1245
- self.results["overall"] = "qga_not_ready"
1246
- return self.results
1247
-
1248
- self.console.print("[green]✅ SSH fallback connected (executing validations over SSH)[/]")
1249
-
1250
- ci_status = self._exec_in_vm("cloud-init status --long 2>/dev/null || cloud-init status 2>/dev/null || true", timeout=20)
1251
- if ci_status:
1252
- ci_lower = ci_status.lower()
1253
- if "running" in ci_lower:
1254
- self.console.print("[yellow]⏳ Cloud-init still running - deep validation will show pending states[/]")
1255
- setup_in_progress = True
1256
-
1257
- ready_msg = self._exec_in_vm(
1258
- "cat /var/log/clonebox-ready 2>/dev/null || true",
1259
- timeout=10,
1260
- )
1261
- if not setup_in_progress and not (ready_msg and "clonebox vm ready" in ready_msg.lower()):
1262
- self.console.print(
1263
- "[yellow]⚠️ CloneBox ready marker not found - provisioning may not have completed[/]"
1264
- )
1265
-
1266
- # Run all validations
1267
- self.validate_disk_space()
1268
- self.validate_mounts()
1269
- self.validate_packages()
1270
- self.validate_snap_packages()
1271
- self.validate_services()
1272
- self.validate_apps()
1273
- if self.smoke_test:
1274
- self.validate_smoke_tests()
1275
-
1276
- recent_err = self._exec_in_vm(
1277
- "journalctl -p err -n 30 --no-pager 2>/dev/null || true", timeout=20
1278
- )
1279
- if recent_err:
1280
- recent_err = recent_err.strip()
1281
- if recent_err:
1282
- self.console.print(
1283
- Panel(recent_err, title="Recent system errors", border_style="red")
1284
- )
1285
-
1286
- # Calculate overall status
1287
- disk_failed = 1 if self.results.get("disk", {}).get("usage_pct", 0) > 90 else 0
1288
- total_checks = (
1289
- 1 # Disk space check
1290
- + self.results["mounts"]["total"]
1291
- + self.results["packages"]["total"]
1292
- + self.results["snap_packages"]["total"]
1293
- + self.results["services"]["total"]
1294
- + self.results["apps"]["total"]
1295
- + (self.results["smoke"]["total"] if self.smoke_test else 0)
1296
- )
1297
-
1298
- total_passed = (
1299
- (1 - disk_failed)
1300
- + self.results["mounts"]["passed"]
1301
- + self.results["packages"]["passed"]
1302
- + self.results["snap_packages"]["passed"]
1303
- + self.results["services"]["passed"]
1304
- + self.results["apps"]["passed"]
1305
- + (self.results["smoke"]["passed"] if self.smoke_test else 0)
1306
- )
1307
-
1308
- total_failed = (
1309
- disk_failed
1310
- + self.results["mounts"]["failed"]
1311
- + self.results["packages"]["failed"]
1312
- + self.results["snap_packages"]["failed"]
1313
- + self.results["services"]["failed"]
1314
- + self.results["apps"]["failed"]
1315
- + (self.results["smoke"]["failed"] if self.smoke_test else 0)
1316
- )
1317
-
1318
- # Get skipped counts
1319
- skipped_mounts = self.results["mounts"].get("skipped", 0)
1320
- skipped_packages = self.results["packages"].get("skipped", 0)
1321
- skipped_services = self.results["services"].get("skipped", 0)
1322
- skipped_snaps = self.results["snap_packages"].get("skipped", 0)
1323
- skipped_apps = self.results["apps"].get("skipped", 0)
1324
- skipped_smoke = self.results["smoke"].get("skipped", 0) if self.smoke_test else 0
1325
- total_skipped = skipped_mounts + skipped_packages + skipped_services + skipped_snaps + skipped_apps + skipped_smoke
1326
-
1327
- # Print summary
1328
- self.console.print("\n[bold]📊 Validation Summary[/]")
1329
- summary_table = Table(border_style="cyan")
1330
- summary_table.add_column("Category", style="bold")
1331
- summary_table.add_column("Passed", justify="right", style="green")
1332
- summary_table.add_column("Failed", justify="right", style="red")
1333
- summary_table.add_column("Skipped/Pending", justify="right", style="dim")
1334
- summary_table.add_column("Total", justify="right")
1335
-
1336
- # Add Disk Space row
1337
- disk_usage_pct = self.results.get("disk", {}).get("usage_pct", 0)
1338
- disk_avail = self.results.get("disk", {}).get("avail", "?")
1339
- disk_total = self.results.get("disk", {}).get("total", "?")
1340
-
1341
- # Calculate used space if possible
1342
- disk_status_passed = "[green]OK[/]" if disk_usage_pct <= 90 else "—"
1343
- disk_status_failed = "—" if disk_usage_pct <= 90 else f"[red]FULL ({disk_usage_pct}%)[/]"
1344
-
1345
- summary_table.add_row(
1346
- "Disk Space",
1347
- disk_status_passed,
1348
- disk_status_failed,
1349
- "—",
1350
- f"{disk_usage_pct}% of {disk_total} ({disk_avail} free)",
1351
- )
1352
-
1353
- summary_table.add_row(
1354
- "Mounts",
1355
- str(self.results["mounts"]["passed"]),
1356
- str(self.results["mounts"]["failed"]),
1357
- str(skipped_mounts) if skipped_mounts else "—",
1358
- str(self.results["mounts"]["total"]),
1359
- )
1360
- summary_table.add_row(
1361
- "APT Packages",
1362
- str(self.results["packages"]["passed"]),
1363
- str(self.results["packages"]["failed"]),
1364
- str(skipped_packages) if skipped_packages else "—",
1365
- str(self.results["packages"]["total"]),
1366
- )
1367
- summary_table.add_row(
1368
- "Snap Packages",
1369
- str(self.results["snap_packages"]["passed"]),
1370
- str(self.results["snap_packages"]["failed"]),
1371
- str(skipped_snaps) if skipped_snaps else "—",
1372
- str(self.results["snap_packages"]["total"]),
1373
- )
1374
- summary_table.add_row(
1375
- "Services",
1376
- str(self.results["services"]["passed"]),
1377
- str(self.results["services"]["failed"]),
1378
- str(skipped_services) if skipped_services else "—",
1379
- str(self.results["services"]["total"]),
1380
- )
1381
- summary_table.add_row(
1382
- "Apps",
1383
- str(self.results["apps"]["passed"]),
1384
- str(self.results["apps"]["failed"]),
1385
- str(skipped_apps) if skipped_apps else "—",
1386
- str(self.results["apps"]["total"]),
1387
- )
1388
- summary_table.add_row(
1389
- "[bold]TOTAL",
1390
- f"[bold green]{total_passed}",
1391
- f"[bold red]{total_failed}",
1392
- f"[dim]{total_skipped}[/]" if total_skipped else "[dim]0[/]",
1393
- f"[bold]{total_checks}",
1394
- )
1395
-
1396
- self.console.print(summary_table)
1397
-
1398
- # Determine overall status
1399
- if total_failed == 0 and total_checks > 0 and total_skipped > 0:
1400
- self.results["overall"] = "pending"
1401
- self.console.print("\n[bold yellow]⏳ Setup in progress - some checks are pending[/]")
1402
- elif total_failed == 0 and total_checks > 0:
1403
- self.results["overall"] = "pass"
1404
- self.console.print("\n[bold green]✅ All validations passed![/]")
1405
- elif total_failed > 0:
1406
- self.results["overall"] = "partial"
1407
- self.console.print(f"\n[bold yellow]⚠️ {total_failed}/{total_checks} checks failed[/]")
1408
- self.console.print(
1409
- "[dim]Consider rebuilding VM: clonebox clone . --user --run --replace[/]"
1410
- )
1411
- else:
1412
- self.results["overall"] = "no_checks"
1413
- self.console.print("\n[dim]No validation checks configured[/]")
1414
-
1415
- return self.results
3
+ __all__ = ["VMValidator"]