|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Set up nested podman inside privileged docker/podman containers (codespaces, devpod). |
| 4 | +
|
| 5 | +This handles: |
| 6 | +- Mount propagation fixes |
| 7 | +- /dev/kvm permissions |
| 8 | +- subuid/subgid configuration for constrained UID namespaces |
| 9 | +- containers.conf configuration for nested operation |
| 10 | +""" |
| 11 | + |
| 12 | +import argparse |
| 13 | +import json |
| 14 | +import os |
| 15 | +import shutil |
| 16 | +import subprocess |
| 17 | +import sys |
| 18 | +from pathlib import Path |
| 19 | + |
| 20 | + |
| 21 | +def run_cmd(cmd: list[str], check: bool = True, capture: bool = False) -> subprocess.CompletedProcess: |
| 22 | + """Run a command, optionally capturing output.""" |
| 23 | + return subprocess.run(cmd, check=check, capture_output=capture, text=True) |
| 24 | + |
| 25 | + |
| 26 | +def get_mount_propagation(target: str) -> str: |
| 27 | + """Get mount propagation type for a given mount point.""" |
| 28 | + result = run_cmd(["findmnt", "-J", "-o", "TARGET,PROPAGATION", target], capture=True, check=False) |
| 29 | + if result.returncode != 0: |
| 30 | + return "unknown" |
| 31 | + try: |
| 32 | + data = json.loads(result.stdout) |
| 33 | + return data.get("filesystems", [{}])[0].get("propagation", "unknown") |
| 34 | + except (json.JSONDecodeError, IndexError, KeyError): |
| 35 | + return "unknown" |
| 36 | + |
| 37 | + |
| 38 | +def fix_mount_propagation() -> None: |
| 39 | + """Fix root mount propagation if needed (e.g., in codespaces).""" |
| 40 | + propagation = get_mount_propagation("/") |
| 41 | + if propagation == "private": |
| 42 | + result = run_cmd(["mount", "-o", "remount", "--make-shared", "/"], check=False) |
| 43 | + if result.returncode == 0: |
| 44 | + print("Set / to shared propagation") |
| 45 | + else: |
| 46 | + print("Warning: Could not set / to shared propagation (may not be needed)") |
| 47 | + |
| 48 | + |
| 49 | +def fix_kvm_permissions() -> None: |
| 50 | + """Make /dev/kvm accessible to all users (safe, like Fedora derivatives do).""" |
| 51 | + kvm = Path("/dev/kvm") |
| 52 | + if kvm.exists(): |
| 53 | + try: |
| 54 | + kvm.chmod(0o666) |
| 55 | + except PermissionError: |
| 56 | + pass |
| 57 | + |
| 58 | + |
| 59 | +def detect_constrained_namespace() -> tuple[bool, int]: |
| 60 | + """ |
| 61 | + Detect whether we're in a constrained UID namespace. |
| 62 | +
|
| 63 | + Returns: |
| 64 | + (is_constrained, max_uid): True if constrained (1000-100000 UIDs available), |
| 65 | + along with the maximum usable UID. |
| 66 | + """ |
| 67 | + max_uid = 0 |
| 68 | + try: |
| 69 | + with open("/proc/self/uid_map") as f: |
| 70 | + for line in f: |
| 71 | + parts = line.split() |
| 72 | + if len(parts) >= 3: |
| 73 | + inside = int(parts[0]) |
| 74 | + count = int(parts[2]) |
| 75 | + end = inside + count |
| 76 | + if end > max_uid: |
| 77 | + max_uid = end |
| 78 | + except (OSError, ValueError): |
| 79 | + return False, 0 |
| 80 | + |
| 81 | + # Constrained if between 1000 and 100000 UIDs |
| 82 | + is_constrained = 1000 < max_uid < 100000 |
| 83 | + return is_constrained, max_uid |
| 84 | + |
| 85 | + |
| 86 | +def configure_subuid_subgid(target_user: str | None = None) -> None: |
| 87 | + """ |
| 88 | + Configure subuid/subgid for nested rootless podman in constrained UID namespaces. |
| 89 | +
|
| 90 | + Args: |
| 91 | + target_user: Username to configure. Defaults to SUDO_USER or current user. |
| 92 | + """ |
| 93 | + # Only proceed if podman is available |
| 94 | + if not shutil.which("podman"): |
| 95 | + return |
| 96 | + |
| 97 | + # Check for newuidmap/newgidmap |
| 98 | + if not shutil.which("newuidmap"): |
| 99 | + print("Warning: newuidmap not found, nested podman may fail") |
| 100 | + |
| 101 | + is_constrained, max_uid = detect_constrained_namespace() |
| 102 | + if not is_constrained: |
| 103 | + print(f"Full UID namespace available (max={max_uid}), using default podman config") |
| 104 | + return |
| 105 | + |
| 106 | + # Determine target user |
| 107 | + if target_user is None: |
| 108 | + target_user = os.environ.get("SUDO_USER") |
| 109 | + if target_user is None: |
| 110 | + import pwd |
| 111 | + target_user = pwd.getpwuid(os.getuid()).pw_name |
| 112 | + |
| 113 | + # Get target user's UID |
| 114 | + import pwd |
| 115 | + try: |
| 116 | + target_uid = pwd.getpwnam(target_user).pw_uid |
| 117 | + except KeyError: |
| 118 | + print(f"Warning: User {target_user} not found") |
| 119 | + return |
| 120 | + |
| 121 | + # Calculate subuid range |
| 122 | + subuid_start = target_uid + 1 |
| 123 | + subuid_count = max_uid - subuid_start |
| 124 | + |
| 125 | + if subuid_count < 1000: |
| 126 | + print(f"Insufficient UID range for nested podman (only {subuid_count} UIDs available)") |
| 127 | + return |
| 128 | + |
| 129 | + expected = f"{target_user}:{subuid_start}:{subuid_count}" |
| 130 | + |
| 131 | + # Check if already configured correctly |
| 132 | + subuid_path = Path("/etc/subuid") |
| 133 | + if subuid_path.exists(): |
| 134 | + current = None |
| 135 | + for line in subuid_path.read_text().splitlines(): |
| 136 | + if line.startswith(f"{target_user}:"): |
| 137 | + current = line |
| 138 | + break |
| 139 | + if current == expected: |
| 140 | + print(f"Nested podman subuid/subgid already configured for {target_user}") |
| 141 | + return |
| 142 | + |
| 143 | + print(f"Configuring nested podman for {target_user} (subuid {subuid_start}:{subuid_count})") |
| 144 | + |
| 145 | + # Configure subuid/subgid |
| 146 | + for path in [Path("/etc/subuid"), Path("/etc/subgid")]: |
| 147 | + lines = [] |
| 148 | + if path.exists(): |
| 149 | + lines = [line for line in path.read_text().splitlines() |
| 150 | + if not line.startswith(f"{target_user}:")] |
| 151 | + lines.append(expected) |
| 152 | + path.write_text("\n".join(lines) + "\n") |
| 153 | + |
| 154 | + # Reset podman storage if it exists (may have wrong UID mappings) |
| 155 | + import pwd |
| 156 | + user_home = Path(pwd.getpwnam(target_user).pw_dir) |
| 157 | + storage_dir = user_home / ".local/share/containers/storage" |
| 158 | + if storage_dir.exists(): |
| 159 | + print("Resetting podman storage for new UID mappings") |
| 160 | + shutil.rmtree(storage_dir) |
| 161 | + |
| 162 | + print("Nested podman subuid/subgid configured successfully") |
| 163 | + |
| 164 | + |
| 165 | +def configure_containers_conf() -> None: |
| 166 | + """Configure containers.conf for nested container operation.""" |
| 167 | + if not shutil.which("podman"): |
| 168 | + return |
| 169 | + |
| 170 | + is_constrained, _ = detect_constrained_namespace() |
| 171 | + |
| 172 | + if not is_constrained: |
| 173 | + # Full namespace - just update the shipped config |
| 174 | + conf_path = Path("/usr/share/containers/containers.conf") |
| 175 | + if conf_path.exists(): |
| 176 | + content = conf_path.read_text() |
| 177 | + content = content.replace("#cgroups =", 'cgroups = "no-conmon" #') |
| 178 | + content = content.replace("#cgroup_manager =", 'cgroup_manager = "cgroupfs" #') |
| 179 | + conf_path.write_text(content) |
| 180 | + else: |
| 181 | + # Constrained namespace - create full config for nested operation |
| 182 | + conf_dir = Path("/etc/containers") |
| 183 | + conf_dir.mkdir(parents=True, exist_ok=True) |
| 184 | + conf_path = conf_dir / "containers.conf" |
| 185 | + conf_path.write_text("""\ |
| 186 | +# Generated for nested container support in constrained UID namespace |
| 187 | +[containers] |
| 188 | +cgroups = "disabled" |
| 189 | +utsns = "host" |
| 190 | +
|
| 191 | +[engine] |
| 192 | +cgroup_manager = "cgroupfs" |
| 193 | +""") |
| 194 | + print("Configured containers.conf for constrained UID namespace") |
| 195 | + |
| 196 | + |
| 197 | +def main() -> int: |
| 198 | + parser = argparse.ArgumentParser( |
| 199 | + description="Configure nested podman for devcontainers" |
| 200 | + ) |
| 201 | + parser.add_argument( |
| 202 | + "user", |
| 203 | + nargs="?", |
| 204 | + help="Target user for subuid/subgid configuration (default: SUDO_USER or current user)", |
| 205 | + ) |
| 206 | + args = parser.parse_args() |
| 207 | + |
| 208 | + fix_mount_propagation() |
| 209 | + fix_kvm_permissions() |
| 210 | + configure_subuid_subgid(args.user) |
| 211 | + configure_containers_conf() |
| 212 | + |
| 213 | + return 0 |
| 214 | + |
| 215 | + |
| 216 | +if __name__ == "__main__": |
| 217 | + sys.exit(main()) |
0 commit comments