clonebox 0.1.21__tar.gz → 0.1.22__tar.gz

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.
Files changed (30) hide show
  1. {clonebox-0.1.21/src/clonebox.egg-info → clonebox-0.1.22}/PKG-INFO +2 -1
  2. {clonebox-0.1.21 → clonebox-0.1.22}/README.md +1 -0
  3. {clonebox-0.1.21 → clonebox-0.1.22}/pyproject.toml +1 -1
  4. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox/cli.py +188 -6
  5. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox/cloner.py +317 -0
  6. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox/validator.py +361 -29
  7. {clonebox-0.1.21 → clonebox-0.1.22/src/clonebox.egg-info}/PKG-INFO +2 -1
  8. {clonebox-0.1.21 → clonebox-0.1.22}/tests/test_validator.py +66 -0
  9. {clonebox-0.1.21 → clonebox-0.1.22}/LICENSE +0 -0
  10. {clonebox-0.1.21 → clonebox-0.1.22}/setup.cfg +0 -0
  11. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox/__init__.py +0 -0
  12. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox/__main__.py +0 -0
  13. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox/container.py +0 -0
  14. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox/dashboard.py +0 -0
  15. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox/detector.py +0 -0
  16. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox/models.py +0 -0
  17. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox/profiles.py +0 -0
  18. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox/templates/profiles/ml-dev.yaml +0 -0
  19. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox.egg-info/SOURCES.txt +0 -0
  20. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox.egg-info/dependency_links.txt +0 -0
  21. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox.egg-info/entry_points.txt +0 -0
  22. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox.egg-info/requires.txt +0 -0
  23. {clonebox-0.1.21 → clonebox-0.1.22}/src/clonebox.egg-info/top_level.txt +0 -0
  24. {clonebox-0.1.21 → clonebox-0.1.22}/tests/test_cli.py +0 -0
  25. {clonebox-0.1.21 → clonebox-0.1.22}/tests/test_cloner.py +0 -0
  26. {clonebox-0.1.21 → clonebox-0.1.22}/tests/test_container.py +0 -0
  27. {clonebox-0.1.21 → clonebox-0.1.22}/tests/test_detector.py +0 -0
  28. {clonebox-0.1.21 → clonebox-0.1.22}/tests/test_models.py +0 -0
  29. {clonebox-0.1.21 → clonebox-0.1.22}/tests/test_network.py +0 -0
  30. {clonebox-0.1.21 → clonebox-0.1.22}/tests/test_profiles.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clonebox
3
- Version: 0.1.21
3
+ Version: 0.1.22
4
4
  Summary: Clone your workstation environment to an isolated VM with selective apps, paths and services
5
5
  Author: CloneBox Team
6
6
  License: Apache-2.0
@@ -274,6 +274,7 @@ clonebox
274
274
  clonebox clone . --user --run --replace --base-image ~/ubuntu-22.04-cloud.qcow2 --disk-size-gb 30
275
275
 
276
276
  clonebox test . --user --validate
277
+ clonebox test . --user --validate --require-running-apps
277
278
  ```
278
279
 
279
280
  ### Profiles (Reusable presets)
@@ -226,6 +226,7 @@ clonebox
226
226
  clonebox clone . --user --run --replace --base-image ~/ubuntu-22.04-cloud.qcow2 --disk-size-gb 30
227
227
 
228
228
  clonebox test . --user --validate
229
+ clonebox test . --user --validate --require-running-apps
229
230
  ```
230
231
 
231
232
  ### Profiles (Reusable presets)
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "clonebox"
7
- version = "0.1.21"
7
+ version = "0.1.22"
8
8
  description = "Clone your workstation environment to an isolated VM with selective apps, paths and services"
9
9
  readme = "README.md"
10
10
  license = {text = "Apache-2.0"}
@@ -8,7 +8,8 @@ import json
8
8
  import os
9
9
  import re
10
10
  import sys
11
- from typing import Optional
11
+ import time
12
+ from typing import Any, Dict, Optional, Tuple
12
13
  from datetime import datetime
13
14
  from pathlib import Path
14
15
 
@@ -16,6 +17,7 @@ import questionary
16
17
  import yaml
17
18
  from questionary import Style
18
19
  from rich.console import Console
20
+ from rich.live import Live
19
21
  from rich.panel import Panel
20
22
  from rich.progress import Progress, SpinnerColumn, TextColumn
21
23
  from rich.table import Table
@@ -61,7 +63,7 @@ def print_banner():
61
63
  console.print(f" Version {__version__}\n", style="dim")
62
64
 
63
65
 
64
- def _resolve_vm_name_and_config_file(name: Optional[str]) -> tuple[str, Optional[Path]]:
66
+ def _resolve_vm_name_and_config_file(name: Optional[str]) -> Tuple[str, Optional[Path]]:
65
67
  config_file: Optional[Path] = None
66
68
 
67
69
  if name and (name.startswith(".") or name.startswith("/") or name.startswith("~")):
@@ -196,6 +198,9 @@ def run_vm_diagnostics(
196
198
 
197
199
  console.print(f"[bold cyan]🧪 Diagnostics: {vm_name}[/]\n")
198
200
 
201
+ guest_agent_ready = _qga_ping(vm_name, conn_uri)
202
+ result["qga"]["ready"] = guest_agent_ready
203
+
199
204
  try:
200
205
  domstate = subprocess.run(
201
206
  ["virsh", "--connect", conn_uri, "domstate", vm_name],
@@ -257,8 +262,6 @@ def run_vm_diagnostics(
257
262
  result["network"] = {"error": str(e)}
258
263
  console.print(f"[yellow]⚠️ Cannot get IP: {e}[/]")
259
264
 
260
- guest_agent_ready = _qga_ping(vm_name, conn_uri)
261
- result["qga"]["ready"] = guest_agent_ready
262
265
  if verbose:
263
266
  console.print("\n[bold]🤖 QEMU Guest Agent...[/]")
264
267
  console.print(f"{'[green]✅' if guest_agent_ready else '[red]❌'} QGA connected")
@@ -334,7 +337,7 @@ def run_vm_diagnostics(
334
337
  if not cloud_init_complete:
335
338
  console.print("[dim]Mounts may not be ready until cloud-init completes.[/]")
336
339
 
337
- mounts_detail: list[dict] = []
340
+ mounts_detail: list = []
338
341
  result["mounts"]["details"] = mounts_detail
339
342
  if not guest_agent_ready:
340
343
  console.print("[yellow]⏳ QEMU guest agent not connected yet - cannot verify mounts.[/]")
@@ -426,6 +429,109 @@ def run_vm_diagnostics(
426
429
  return result
427
430
 
428
431
 
432
+ def cmd_watch(args):
433
+ name = args.name
434
+ user_session = getattr(args, "user", False)
435
+ conn_uri = "qemu:///session" if user_session else "qemu:///system"
436
+ refresh = getattr(args, "refresh", 1.0)
437
+ max_wait = getattr(args, "timeout", 600)
438
+
439
+ try:
440
+ vm_name, _ = _resolve_vm_name_and_config_file(name)
441
+ except FileNotFoundError as e:
442
+ console.print(f"[red]❌ {e}[/]")
443
+ return
444
+
445
+ console.print(f"[bold cyan]👀 Watching boot diagnostics: {vm_name}[/]")
446
+ console.print("[dim]Waiting for QEMU Guest Agent...[/]")
447
+
448
+ start = time.time()
449
+ while time.time() - start < max_wait:
450
+ if _qga_ping(vm_name, conn_uri):
451
+ break
452
+ time.sleep(min(refresh, 2.0))
453
+
454
+ if not _qga_ping(vm_name, conn_uri):
455
+ console.print("[yellow]⚠️ QEMU Guest Agent not connected - cannot watch diagnostic status yet[/]")
456
+ console.print(f"[dim]Try: clonebox status {name or vm_name} {'--user' if user_session else ''} --verbose[/]")
457
+ return
458
+
459
+ def _read_status() -> Tuple[Optional[Dict[str, Any]], str]:
460
+ status_raw = _qga_exec(vm_name, conn_uri, "cat /var/run/clonebox-status.json 2>/dev/null || true", timeout=10)
461
+ log_tail = _qga_exec(vm_name, conn_uri, "tail -n 40 /var/log/clonebox-boot.log 2>/dev/null || true", timeout=10) or ""
462
+
463
+ status_obj: Optional[Dict[str, Any]] = None
464
+ if status_raw:
465
+ try:
466
+ status_obj = json.loads(status_raw)
467
+ except Exception:
468
+ status_obj = None
469
+ return status_obj, log_tail
470
+
471
+ with Live(refresh_per_second=max(1, int(1 / max(refresh, 0.2))), console=console) as live:
472
+ while True:
473
+ status_obj, log_tail = _read_status()
474
+ phase = (status_obj or {}).get("phase") if status_obj else None
475
+ current_task = (status_obj or {}).get("current_task") if status_obj else None
476
+
477
+ header = f"phase={phase or 'unknown'}"
478
+ if current_task:
479
+ header += f" | {current_task}"
480
+
481
+ stats = ""
482
+ if status_obj:
483
+ stats = (
484
+ f"passed={status_obj.get('passed', 0)} failed={status_obj.get('failed', 0)} repaired={status_obj.get('repaired', 0)} total={status_obj.get('total', 0)}"
485
+ )
486
+
487
+ body = "\n".join([s for s in [header, stats, "", log_tail.strip()] if s])
488
+ live.update(Panel(body or "(no output yet)", title="CloneBox boot diagnostic", border_style="cyan"))
489
+
490
+ if phase == "complete":
491
+ break
492
+
493
+ if time.time() - start >= max_wait:
494
+ break
495
+
496
+ time.sleep(refresh)
497
+
498
+
499
+ def cmd_repair(args):
500
+ name = args.name
501
+ user_session = getattr(args, "user", False)
502
+ conn_uri = "qemu:///session" if user_session else "qemu:///system"
503
+ timeout = getattr(args, "timeout", 600)
504
+ follow = getattr(args, "watch", False)
505
+
506
+ try:
507
+ vm_name, _ = _resolve_vm_name_and_config_file(name)
508
+ except FileNotFoundError as e:
509
+ console.print(f"[red]❌ {e}[/]")
510
+ return
511
+
512
+ if not _qga_ping(vm_name, conn_uri):
513
+ console.print("[yellow]⚠️ QEMU Guest Agent not connected - cannot trigger repair[/]")
514
+ console.print("[dim]Inside VM you can run: sudo /usr/local/bin/clonebox-boot-diagnostic[/]")
515
+ return
516
+
517
+ console.print(f"[cyan]🔧 Running boot diagnostic/repair in VM: {vm_name}[/]")
518
+ out = _qga_exec(vm_name, conn_uri, "/usr/local/bin/clonebox-boot-diagnostic || true", timeout=timeout)
519
+ if out is None:
520
+ console.print("[yellow]⚠️ Repair triggered but output not available via QGA (check VM console/log)[/]")
521
+ elif out.strip():
522
+ console.print(Panel(out.strip()[-3000:], title="Command output", border_style="cyan"))
523
+
524
+ if follow:
525
+ cmd_watch(
526
+ argparse.Namespace(
527
+ name=name,
528
+ user=user_session,
529
+ refresh=getattr(args, "refresh", 1.0),
530
+ timeout=timeout,
531
+ )
532
+ )
533
+
534
+
429
535
  def interactive_mode():
430
536
  """Run the interactive VM creation wizard."""
431
537
  print_banner()
@@ -1444,6 +1550,8 @@ def cmd_test(args):
1444
1550
  quick = getattr(args, "quick", False)
1445
1551
  verbose = getattr(args, "verbose", False)
1446
1552
  validate_all = getattr(args, "validate", False)
1553
+ require_running_apps = getattr(args, "require_running_apps", False)
1554
+ smoke_test = getattr(args, "smoke_test", False)
1447
1555
  conn_uri = "qemu:///session" if user_session else "qemu:///system"
1448
1556
 
1449
1557
  # If name is a path, load config
@@ -1636,7 +1744,14 @@ def cmd_test(args):
1636
1744
 
1637
1745
  # Run full validation if requested
1638
1746
  if validate_all and state == "running":
1639
- validator = VMValidator(config, vm_name, conn_uri, console)
1747
+ validator = VMValidator(
1748
+ config,
1749
+ vm_name,
1750
+ conn_uri,
1751
+ console,
1752
+ require_running_apps=require_running_apps,
1753
+ smoke_test=smoke_test,
1754
+ )
1640
1755
  results = validator.validate_all()
1641
1756
 
1642
1757
  # Exit with error code if validations failed
@@ -2629,6 +2744,63 @@ def main():
2629
2744
  )
2630
2745
  diagnose_parser.set_defaults(func=cmd_diagnose)
2631
2746
 
2747
+ watch_parser = subparsers.add_parser(
2748
+ "watch", help="Watch boot diagnostic output from VM (via QEMU Guest Agent)"
2749
+ )
2750
+ watch_parser.add_argument(
2751
+ "name", nargs="?", default=None, help="VM name or '.' to use .clonebox.yaml"
2752
+ )
2753
+ watch_parser.add_argument(
2754
+ "-u",
2755
+ "--user",
2756
+ action="store_true",
2757
+ help="Use user session (qemu:///session)",
2758
+ )
2759
+ watch_parser.add_argument(
2760
+ "--refresh",
2761
+ type=float,
2762
+ default=1.0,
2763
+ help="Refresh interval in seconds (default: 1.0)",
2764
+ )
2765
+ watch_parser.add_argument(
2766
+ "--timeout",
2767
+ type=int,
2768
+ default=600,
2769
+ help="Max seconds to wait (default: 600)",
2770
+ )
2771
+ watch_parser.set_defaults(func=cmd_watch)
2772
+
2773
+ repair_parser = subparsers.add_parser(
2774
+ "repair", help="Trigger boot diagnostic/repair inside VM (via QEMU Guest Agent)"
2775
+ )
2776
+ repair_parser.add_argument(
2777
+ "name", nargs="?", default=None, help="VM name or '.' to use .clonebox.yaml"
2778
+ )
2779
+ repair_parser.add_argument(
2780
+ "-u",
2781
+ "--user",
2782
+ action="store_true",
2783
+ help="Use user session (qemu:///session)",
2784
+ )
2785
+ repair_parser.add_argument(
2786
+ "--timeout",
2787
+ type=int,
2788
+ default=600,
2789
+ help="Max seconds to wait for repair (default: 600)",
2790
+ )
2791
+ repair_parser.add_argument(
2792
+ "--watch",
2793
+ action="store_true",
2794
+ help="After triggering repair, watch status/log output",
2795
+ )
2796
+ repair_parser.add_argument(
2797
+ "--refresh",
2798
+ type=float,
2799
+ default=1.0,
2800
+ help="Refresh interval for --watch (default: 1.0)",
2801
+ )
2802
+ repair_parser.set_defaults(func=cmd_repair)
2803
+
2632
2804
  # Export command - package VM for migration
2633
2805
  export_parser = subparsers.add_parser("export", help="Export VM and data for migration")
2634
2806
  export_parser.add_argument(
@@ -2674,6 +2846,16 @@ def main():
2674
2846
  test_parser.add_argument(
2675
2847
  "--validate", action="store_true", help="Run full validation (mounts, packages, services)"
2676
2848
  )
2849
+ test_parser.add_argument(
2850
+ "--require-running-apps",
2851
+ action="store_true",
2852
+ help="Fail validation if expected apps are installed but not currently running",
2853
+ )
2854
+ test_parser.add_argument(
2855
+ "--smoke-test",
2856
+ action="store_true",
2857
+ help="Run smoke tests (installed ≠ works): headless launch checks for key apps",
2858
+ )
2677
2859
  test_parser.set_defaults(func=cmd_test)
2678
2860
 
2679
2861
  args = parser.parse_args()
@@ -487,6 +487,268 @@ class SelectiveVMCloner:
487
487
 
488
488
  return ET.tostring(root, encoding="unicode")
489
489
 
490
+ def _generate_boot_diagnostic_script(self, config: VMConfig) -> str:
491
+ """Generate boot diagnostic script with self-healing capabilities."""
492
+ import base64
493
+
494
+ wants_google_chrome = any(
495
+ p == "/home/ubuntu/.config/google-chrome" for p in (config.paths or {}).values()
496
+ )
497
+
498
+ apt_pkg_list = list(config.packages or [])
499
+ for base_pkg in ["qemu-guest-agent", "cloud-guest-utils"]:
500
+ if base_pkg not in apt_pkg_list:
501
+ apt_pkg_list.insert(0, base_pkg)
502
+ if config.gui:
503
+ for gui_pkg in ["ubuntu-desktop-minimal", "firefox"]:
504
+ if gui_pkg not in apt_pkg_list:
505
+ apt_pkg_list.append(gui_pkg)
506
+
507
+ apt_packages = " ".join(f'"{p}"' for p in apt_pkg_list) if apt_pkg_list else ""
508
+ snap_packages = " ".join(f'"{p}"' for p in config.snap_packages) if config.snap_packages else ""
509
+ services = " ".join(f'"{s}"' for s in config.services) if config.services else ""
510
+
511
+ snap_ifaces_bash = "\n".join(
512
+ f'SNAP_INTERFACES["{snap}"]="{" ".join(ifaces)}"'
513
+ for snap, ifaces in SNAP_INTERFACES.items()
514
+ )
515
+
516
+ script = f'''#!/bin/bash
517
+ set -uo pipefail
518
+ LOG="/var/log/clonebox-boot.log"
519
+ STATUS_KV="/var/run/clonebox-status"
520
+ STATUS_JSON="/var/run/clonebox-status.json"
521
+ MAX_RETRIES=3
522
+ PASSED=0 FAILED=0 REPAIRED=0 TOTAL=0
523
+
524
+ RED='\\033[0;31m' GREEN='\\033[0;32m' YELLOW='\\033[1;33m' CYAN='\\033[0;36m' NC='\\033[0m' BOLD='\\033[1m'
525
+
526
+ log() {{ echo -e "[$(date +%H:%M:%S)] $1" | tee -a "$LOG"; }}
527
+ ok() {{ log "${{GREEN}}✅ $1${{NC}}"; ((PASSED++)); ((TOTAL++)); }}
528
+ fail() {{ log "${{RED}}❌ $1${{NC}}"; ((FAILED++)); ((TOTAL++)); }}
529
+ repair() {{ log "${{YELLOW}}🔧 $1${{NC}}"; }}
530
+ section() {{ log ""; log "${{BOLD}}[$1] $2${{NC}}"; }}
531
+
532
+ write_status() {{
533
+ local phase="$1"
534
+ local current_task="${{2:-}}"
535
+ printf 'passed=%s failed=%s repaired=%s\n' "$PASSED" "$FAILED" "$REPAIRED" > "$STATUS_KV" 2>/dev/null || true
536
+ cat > "$STATUS_JSON" <<EOF
537
+ {{"phase":"$phase","current_task":"$current_task","total":$TOTAL,"passed":$PASSED,"failed":$FAILED,"repaired":$REPAIRED,"timestamp":"$(date -Iseconds)"}}
538
+ EOF
539
+ }}
540
+
541
+ header() {{
542
+ log ""
543
+ log "${{BOLD}}${{CYAN}}═══════════════════════════════════════════════════════════${{NC}}"
544
+ log "${{BOLD}}${{CYAN}} $1${{NC}}"
545
+ log "${{BOLD}}${{CYAN}}═══════════════════════════════════════════════════════════${{NC}}"
546
+ }}
547
+
548
+ declare -A SNAP_INTERFACES
549
+ {snap_ifaces_bash}
550
+ DEFAULT_IFACES="desktop desktop-legacy x11 home network"
551
+
552
+ check_apt() {{
553
+ dpkg -l "$1" 2>/dev/null | grep -q "^ii"
554
+ }}
555
+
556
+ install_apt() {{
557
+ for i in $(seq 1 $MAX_RETRIES); do
558
+ DEBIAN_FRONTEND=noninteractive apt-get install -y "$1" &>>"$LOG" && return 0
559
+ sleep 3
560
+ done
561
+ return 1
562
+ }}
563
+
564
+ check_snap() {{
565
+ snap list "$1" &>/dev/null
566
+ }}
567
+
568
+ install_snap() {{
569
+ timeout 60 snap wait system seed.loaded 2>/dev/null || true
570
+ for i in $(seq 1 $MAX_RETRIES); do
571
+ snap install "$1" --classic &>>"$LOG" && return 0
572
+ snap install "$1" &>>"$LOG" && return 0
573
+ sleep 5
574
+ done
575
+ return 1
576
+ }}
577
+
578
+ connect_interfaces() {{
579
+ local snap="$1"
580
+ local ifaces="${{SNAP_INTERFACES[$snap]:-$DEFAULT_IFACES}}"
581
+ for iface in $ifaces; do
582
+ snap connect "$snap:$iface" ":$iface" 2>/dev/null && log " ${{GREEN}}✓${{NC}} $snap:$iface" || true
583
+ done
584
+ }}
585
+
586
+ test_launch() {{
587
+ case "$1" in
588
+ pycharm-community) /snap/pycharm-community/current/jbr/bin/java -version &>/dev/null ;;
589
+ chromium) timeout 10 chromium --headless=new --dump-dom about:blank &>/dev/null ;;
590
+ firefox) timeout 10 firefox --headless --screenshot /tmp/ff-test.png about:blank &>/dev/null; rm -f /tmp/ff-test.png ;;
591
+ docker) docker info &>/dev/null ;;
592
+ *) command -v "$1" &>/dev/null ;;
593
+ esac
594
+ }}
595
+
596
+ header "CloneBox VM Boot Diagnostic"
597
+ write_status "starting" "boot diagnostic starting"
598
+
599
+ APT_PACKAGES=({apt_packages})
600
+ SNAP_PACKAGES=({snap_packages})
601
+ SERVICES=({services})
602
+
603
+ section "1/5" "Checking APT packages..."
604
+ write_status "checking_apt" "checking APT packages"
605
+ for pkg in "${{APT_PACKAGES[@]}}"; do
606
+ [ -z "$pkg" ] && continue
607
+ if check_apt "$pkg"; then
608
+ ok "$pkg"
609
+ else
610
+ repair "Installing $pkg..."
611
+ if install_apt "$pkg"; then
612
+ ok "$pkg installed"
613
+ ((REPAIRED++))
614
+ else
615
+ fail "$pkg FAILED"
616
+ fi
617
+ fi
618
+ done
619
+
620
+ section "2/5" "Checking Snap packages..."
621
+ write_status "checking_snaps" "checking snap packages"
622
+ timeout 120 snap wait system seed.loaded 2>/dev/null || true
623
+ for pkg in "${{SNAP_PACKAGES[@]}}"; do
624
+ [ -z "$pkg" ] && continue
625
+ if check_snap "$pkg"; then
626
+ ok "$pkg (snap)"
627
+ else
628
+ repair "Installing $pkg..."
629
+ if install_snap "$pkg"; then
630
+ ok "$pkg installed"
631
+ ((REPAIRED++))
632
+ else
633
+ fail "$pkg FAILED"
634
+ fi
635
+ fi
636
+ done
637
+
638
+ section "3/5" "Connecting Snap interfaces..."
639
+ write_status "connecting_interfaces" "connecting snap interfaces"
640
+ for pkg in "${{SNAP_PACKAGES[@]}}"; do
641
+ [ -z "$pkg" ] && continue
642
+ check_snap "$pkg" && connect_interfaces "$pkg"
643
+ done
644
+ systemctl restart snapd 2>/dev/null || true
645
+
646
+ section "4/5" "Testing application launch..."
647
+ write_status "testing_launch" "testing application launch"
648
+ APPS_TO_TEST=()
649
+ for pkg in "${{SNAP_PACKAGES[@]}}"; do
650
+ [ -z "$pkg" ] && continue
651
+ APPS_TO_TEST+=("$pkg")
652
+ done
653
+ if [ "{str(wants_google_chrome).lower()}" = "true" ]; then
654
+ APPS_TO_TEST+=("google-chrome")
655
+ fi
656
+ if printf '%s\n' "${{APT_PACKAGES[@]}}" | grep -qx "docker.io"; then
657
+ APPS_TO_TEST+=("docker")
658
+ fi
659
+
660
+ for app in "${{APPS_TO_TEST[@]}}"; do
661
+ [ -z "$app" ] && continue
662
+ case "$app" in
663
+ google-chrome)
664
+ if ! command -v google-chrome >/dev/null 2>&1 && ! command -v google-chrome-stable >/dev/null 2>&1; then
665
+ repair "Installing google-chrome..."
666
+ tmp_deb="/tmp/google-chrome-stable_current_amd64.deb"
667
+ if curl -fsSL -o "$tmp_deb" "https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb" \
668
+ && DEBIAN_FRONTEND=noninteractive apt-get install -y "$tmp_deb" &>>"$LOG"; then
669
+ rm -f "$tmp_deb"
670
+ ((REPAIRED++))
671
+ else
672
+ rm -f "$tmp_deb" 2>/dev/null || true
673
+ fi
674
+ fi
675
+ ;;
676
+ docker)
677
+ check_apt "docker.io" || continue
678
+ ;;
679
+ *)
680
+ if check_snap "$app"; then
681
+ :
682
+ else
683
+ continue
684
+ fi
685
+ ;;
686
+ esac
687
+
688
+ if test_launch "$app"; then
689
+ ok "$app launches OK"
690
+ else
691
+ fail "$app launch test FAILED"
692
+ fi
693
+ done
694
+
695
+ section "5/6" "Checking mount points..."
696
+ write_status "checking_mounts" "checking mount points"
697
+ while IFS= read -r line; do
698
+ tag=$(echo "$line" | awk '{{print $1}}')
699
+ mp=$(echo "$line" | awk '{{print $2}}')
700
+ if [[ "$tag" =~ ^mount[0-9]+$ ]] && [[ "$mp" == /* ]]; then
701
+ if mountpoint -q "$mp" 2>/dev/null; then
702
+ ok "$mp mounted"
703
+ else
704
+ repair "Mounting $mp..."
705
+ mkdir -p "$mp" 2>/dev/null || true
706
+ if mount "$mp" &>>"$LOG"; then
707
+ ok "$mp mounted"
708
+ ((REPAIRED++))
709
+ else
710
+ fail "$mp mount FAILED"
711
+ fi
712
+ fi
713
+ fi
714
+ done < /etc/fstab
715
+
716
+ section "6/6" "Checking services..."
717
+ write_status "checking_services" "checking services"
718
+ for svc in "${{SERVICES[@]}}"; do
719
+ [ -z "$svc" ] && continue
720
+ if systemctl is-active "$svc" &>/dev/null; then
721
+ ok "$svc running"
722
+ else
723
+ repair "Starting $svc..."
724
+ systemctl enable --now "$svc" &>/dev/null && ok "$svc started" && ((REPAIRED++)) || fail "$svc FAILED"
725
+ fi
726
+ done
727
+
728
+ header "Diagnostic Summary"
729
+ log ""
730
+ log " Total: $TOTAL"
731
+ log " ${{GREEN}}Passed:${{NC}} $PASSED"
732
+ log " ${{YELLOW}}Repaired:${{NC}} $REPAIRED"
733
+ log " ${{RED}}Failed:${{NC}} $FAILED"
734
+ log ""
735
+
736
+ write_status "complete" "complete"
737
+
738
+ if [ $FAILED -eq 0 ]; then
739
+ log "${{GREEN}}${{BOLD}}═══════════════════════════════════════════════════════════${{NC}}"
740
+ log "${{GREEN}}${{BOLD}} ✅ All checks passed! CloneBox VM is ready.${{NC}}"
741
+ log "${{GREEN}}${{BOLD}}═══════════════════════════════════════════════════════════${{NC}}"
742
+ exit 0
743
+ else
744
+ log "${{RED}}${{BOLD}}═══════════════════════════════════════════════════════════${{NC}}"
745
+ log "${{RED}}${{BOLD}} ⚠️ $FAILED checks failed. See /var/log/clonebox-boot.log${{NC}}"
746
+ log "${{RED}}${{BOLD}}═══════════════════════════════════════════════════════════${{NC}}"
747
+ exit 1
748
+ fi
749
+ '''
750
+ return base64.b64encode(script.encode()).decode()
751
+
490
752
  def _generate_health_check_script(self, config: VMConfig) -> str:
491
753
  """Generate a health check script that validates all installed components."""
492
754
  import base64
@@ -759,6 +1021,61 @@ fi
759
1021
  runcmd_lines.append(" - /usr/local/bin/clonebox-health >> /var/log/clonebox-health.log 2>&1")
760
1022
  runcmd_lines.append(" - echo 'CloneBox VM ready!' > /var/log/clonebox-ready")
761
1023
 
1024
+ # Generate boot diagnostic script (self-healing)
1025
+ boot_diag_script = self._generate_boot_diagnostic_script(config)
1026
+ runcmd_lines.append(f" - echo '{boot_diag_script}' | base64 -d > /usr/local/bin/clonebox-boot-diagnostic")
1027
+ runcmd_lines.append(" - chmod +x /usr/local/bin/clonebox-boot-diagnostic")
1028
+
1029
+ # Create systemd service for boot diagnostic (runs before GDM on subsequent boots)
1030
+ systemd_service = '''[Unit]
1031
+ Description=CloneBox Boot Diagnostic
1032
+ After=network-online.target snapd.service
1033
+ Before=gdm.service display-manager.service
1034
+ Wants=network-online.target
1035
+
1036
+ [Service]
1037
+ Type=oneshot
1038
+ ExecStart=/usr/local/bin/clonebox-boot-diagnostic
1039
+ StandardOutput=journal+console
1040
+ StandardError=journal+console
1041
+ TTYPath=/dev/tty1
1042
+ TTYReset=yes
1043
+ TTYVHangup=yes
1044
+ RemainAfterExit=yes
1045
+ TimeoutStartSec=600
1046
+
1047
+ [Install]
1048
+ WantedBy=multi-user.target'''
1049
+ import base64
1050
+ systemd_b64 = base64.b64encode(systemd_service.encode()).decode()
1051
+ runcmd_lines.append(f" - echo '{systemd_b64}' | base64 -d > /etc/systemd/system/clonebox-diagnostic.service")
1052
+ runcmd_lines.append(" - systemctl daemon-reload")
1053
+ runcmd_lines.append(" - systemctl enable clonebox-diagnostic.service")
1054
+ runcmd_lines.append(" - systemctl start clonebox-diagnostic.service || true")
1055
+
1056
+ # Create MOTD banner
1057
+ motd_banner = '''#!/bin/bash
1058
+ S="/var/run/clonebox-status"
1059
+ echo ""
1060
+ echo -e "\\033[1;34m═══════════════════════════════════════════════════════════\\033[0m"
1061
+ echo -e "\\033[1;34m CloneBox VM Status\\033[0m"
1062
+ echo -e "\\033[1;34m═══════════════════════════════════════════════════════════\\033[0m"
1063
+ if [ -f "$S" ]; then
1064
+ source "$S"
1065
+ if [ "${failed:-0}" -eq 0 ]; then
1066
+ echo -e " \\033[0;32m✅ All systems operational\\033[0m"
1067
+ else
1068
+ echo -e " \\033[0;31m⚠️ $failed checks failed\\033[0m"
1069
+ fi
1070
+ echo -e " Passed: ${passed:-0} | Repaired: ${repaired:-0} | Failed: ${failed:-0}"
1071
+ fi
1072
+ echo -e " Log: /var/log/clonebox-boot.log"
1073
+ echo -e "\\033[1;34m═══════════════════════════════════════════════════════════\\033[0m"
1074
+ echo ""'''
1075
+ motd_b64 = base64.b64encode(motd_banner.encode()).decode()
1076
+ runcmd_lines.append(f" - echo '{motd_b64}' | base64 -d > /etc/update-motd.d/99-clonebox")
1077
+ runcmd_lines.append(" - chmod +x /etc/update-motd.d/99-clonebox")
1078
+
762
1079
  # Add reboot command at the end if GUI is enabled
763
1080
  if config.gui:
764
1081
  runcmd_lines.append(" - echo 'Rebooting in 10 seconds to start GUI...'")