Debian Codegraph @

test/vm-copy-bridge

raw
1 #!/usr/bin/env python3
2
3 #
4 # Copyright (C) 2026 Red Hat, Inc.
5 # SPDX-License-Identifier: LGPL-2.1-or-later
6
7 """
8 Fast iteration of src/cockpit/ against existing running VMs.
9
10 Instead of the slow image-prepare way (building packages), this script:
11 1. Uploads the current src/cockpit code to /var/tmp on the VM
12 2. Detects the package manager (dpkg/rpm/pacman) or container
13 3. Bind-mounts the new code over the installed package path
14 4. For containers, rebuilds the cockpit/ws container image
15
16 Usage:
17 test/vm-copy-bridge PORT
18 """
19
20 import argparse
21 import os
22 import subprocess
23 import sys
24
25 # Add bots to path
26 BOTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "bots")
27 sys.path.insert(0, BOTS_DIR)
28
29 from lib.constants import DEFAULT_IDENTITY_FILE # ruff: ignore[module-import-not-at-top-of-file]
30 from machine.machine_core.ssh_connection import SSHConnection # ruff: ignore[module-import-not-at-top-of-file]
31
32
33 def find_cockpit_path(file_list: str) -> str:
34 """Find the cockpit module path from a list of file paths.
35
36 Handles package manager output formats:
37 - dpkg/rpm: one filepath per line
38 - pacman: "package-name filepath" per line
39 """
40 for line in file_list.splitlines():
41 line = line.strip()
42 if line.endswith('/cockpit/__init__.py'):
43 # Extract the path (for pacman, take last field to skip package name)
44 path = line.split()[-1]
45 return os.path.dirname(path)
46
47 sys.exit("Could not find cockpit module path in package file list: " + file_list)
48
49
50 def setup_bind_mount(conn: SSHConnection, cockpit_path: str, port: int) -> None:
51 """Set up bind mount from /var/tmp/cockpit to the package path."""
52 conn.execute(f"if mountpoint -q {cockpit_path}; then umount {cockpit_path}; fi")
53 conn.execute(f"mount --bind /var/tmp/cockpit {cockpit_path}")
54 print(f"Mounted /var/tmp/cockpit over {cockpit_path}")
55
56
57 def rebuild_container(conn: SSHConnection) -> None:
58 """Rebuild the cockpit/ws container with the new bridge code."""
59 print("Rebuilding cockpit/ws container...")
60
61 # Find the cockpit module path inside the container
62 cockpit_path_in_container = conn.execute(
63 "podman run --rm localhost/cockpit/ws python3 -c "
64 "'import cockpit, os; print(os.path.dirname(cockpit.__file__))'"
65 ).strip()
66
67 # Build Containerfile with stdin - copy uploaded code into container
68 # Note: COPY source is relative to build context (.)
69 containerfile = f"""FROM localhost/cockpit/ws:latest
70 COPY cockpit {cockpit_path_in_container}
71 """
72
73 # Build the new container using stdin input
74 conn.execute(
75 "cd /var/tmp && podman build -t localhost/cockpit/ws:latest -f - .",
76 input=containerfile,
77 timeout=30
78 )
79 print("cockpit/ws container rebuilt successfully!")
80
81
82 #
83 # main
84 #
85
86 parser = argparse.ArgumentParser(description="Copy bridge code to a running VM")
87 parser.add_argument("port", type=int, help="SSH port of the running VM")
88 parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")
89 args = parser.parse_args()
90
91 # Connection parameters matching ~/.ssh/config "Host c" paragraph
92 conn = SSHConnection(
93 user="root",
94 address="127.0.0.2",
95 ssh_port=args.port,
96 identity_file=DEFAULT_IDENTITY_FILE,
97 verbose=args.verbose
98 )
99
100 # Check if we can connect
101 if not conn.wait_execute(timeout_sec=5):
102 sys.exit(f"Cannot connect to VM on port {args.port}")
103
104 print(f"Connected to VM on port {args.port}")
105
106 # Get the local src/cockpit directory
107 src_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
108 cockpit_src = os.path.join(src_dir, "src", "cockpit")
109
110 if not os.path.isdir(cockpit_src):
111 sys.exit(f"{cockpit_src} does not exist")
112
113 # Upload the cockpit module to /var/tmp
114 print(f"Uploading {cockpit_src} to VM...")
115 conn.execute("rm -rf /var/tmp/cockpit")
116 conn.upload(["src/cockpit"], "/var/tmp/", relative_dir=src_dir)
117
118 # Known package managers
119 pkg_managers = [
120 ("dpkg -L cockpit-bridge", "Debian/Ubuntu"),
121 ("rpm -ql cockpit-bridge", "RPM-based"),
122 ("pacman -Ql cockpit", "Arch Linux"),
123 ]
124
125 for cmd, system_type in pkg_managers:
126 try:
127 output = conn.execute(cmd)
128 except subprocess.CalledProcessError:
129 continue
130 else:
131 cockpit_path = find_cockpit_path(output)
132 print(f"Detected {system_type} system, cockpit at: {cockpit_path}")
133 setup_bind_mount(conn, cockpit_path, args.port)
134 break
135 else:
136 # No package manager found, try container
137 try:
138 conn.execute("podman image exists localhost/cockpit/ws")
139 print("Detected container-based system (localhost/cockpit/ws)")
140 rebuild_container(conn)
141 except subprocess.CalledProcessError:
142 sys.exit("Could not detect package type (tried dpkg, rpm, pacman, podman)")
143
144 conn.disconnect()