| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 1 | // Package dockerimg |
| 2 | package dockerimg |
| 3 | |
| 4 | import ( |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 5 | "archive/tar" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 6 | "bytes" |
| 7 | "context" |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 8 | "crypto/rand" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 9 | "crypto/sha256" |
| 10 | "encoding/hex" |
| 11 | "encoding/json" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "log/slog" |
| 15 | "net" |
| 16 | "net/http" |
| 17 | "os" |
| 18 | "os/exec" |
| 19 | "path/filepath" |
| 20 | "runtime" |
| 21 | "strings" |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 22 | "sync/atomic" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 23 | "time" |
| 24 | |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 25 | "golang.org/x/crypto/ssh" |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 26 | "sketch.dev/browser" |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 27 | "sketch.dev/embedded" |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 28 | "sketch.dev/loop/server" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 29 | "sketch.dev/skribe" |
| 30 | ) |
| 31 | |
| 32 | // ContainerConfig holds all configuration for launching a container |
| 33 | type ContainerConfig struct { |
| 34 | // SessionID is the unique identifier for this session |
| 35 | SessionID string |
| 36 | |
| 37 | // LocalAddr is the initial address to use (though it may be overwritten later) |
| 38 | LocalAddr string |
| 39 | |
| 40 | // SkabandAddr is the address of the skaband service if available |
| 41 | SkabandAddr string |
| 42 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 43 | // Model is the name of the LLM model to use. |
| 44 | Model string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 45 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 46 | // ModelURL is the URL of the LLM service. |
| 47 | ModelURL string |
| 48 | |
| 49 | // ModelAPIKey is the API key for LLM service. |
| 50 | ModelAPIKey string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 51 | |
| 52 | // Path is the local filesystem path to use |
| 53 | Path string |
| 54 | |
| 55 | // GitUsername is the username to use for git operations |
| 56 | GitUsername string |
| 57 | |
| 58 | // GitEmail is the email to use for git operations |
| 59 | GitEmail string |
| 60 | |
| 61 | // OpenBrowser determines whether to open a browser automatically |
| 62 | OpenBrowser bool |
| 63 | |
| 64 | // NoCleanup prevents container cleanup when set to true |
| 65 | NoCleanup bool |
| 66 | |
| 67 | // ForceRebuild forces rebuilding of the Docker image even if it exists |
| 68 | ForceRebuild bool |
| 69 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 70 | // BaseImage is the base Docker image to use for layering the repo |
| 71 | BaseImage string |
| 72 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 73 | // Host directory to copy container logs into, if not set to "" |
| 74 | ContainerLogDest string |
| 75 | |
| 76 | // Path to pre-built linux sketch binary, or build a new one if set to "" |
| 77 | SketchBinaryLinux string |
| 78 | |
| 79 | // Sketch client public key. |
| 80 | SketchPubKey string |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 81 | |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 82 | // Host port for the container's ssh server |
| 83 | SSHPort int |
| 84 | |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 85 | // Outside information to pass to the container |
| 86 | OutsideHostname string |
| 87 | OutsideOS string |
| 88 | OutsideWorkingDir string |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 89 | |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 90 | // If true, exit after the first turn |
| 91 | OneShot bool |
| 92 | |
| 93 | // Initial prompt |
| 94 | Prompt string |
| Philip Zeyliger | 1b47aa2 | 2025-04-28 19:25:38 +0000 | [diff] [blame] | 95 | |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 96 | // Verbose enables verbose output |
| 97 | Verbose bool |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 98 | |
| 99 | // DockerArgs are additional arguments to pass to the docker create command |
| 100 | DockerArgs string |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 101 | |
| Josh Bleecher Snyder | ac761c9 | 2025-05-16 18:58:45 +0000 | [diff] [blame] | 102 | // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container |
| 103 | Mounts []string |
| 104 | |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 105 | // ExperimentFlag contains the experimental features to enable |
| 106 | ExperimentFlag string |
| Philip Zeyliger | 613c0f5 | 2025-05-15 16:36:22 -0700 | [diff] [blame] | 107 | |
| 108 | // TermUI enables terminal UI |
| 109 | TermUI bool |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 110 | |
| Josh Bleecher Snyder | 33032d3 | 2025-05-30 16:28:21 +0000 | [diff] [blame] | 111 | // Budget configuration |
| Philip Zeyliger | e6c294d | 2025-06-04 16:55:21 +0000 | [diff] [blame] | 112 | MaxDollars float64 |
| Josh Bleecher Snyder | 33032d3 | 2025-05-30 16:28:21 +0000 | [diff] [blame] | 113 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 114 | GitRemoteUrl string |
| 115 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 116 | // Original git origin URL from the host repository |
| 117 | OriginalGitOrigin string |
| 118 | |
| Josh Bleecher Snyder | 664404e | 2025-06-04 21:56:42 +0000 | [diff] [blame] | 119 | // Upstream branch for git work |
| 120 | Upstream string |
| 121 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 122 | // Commit hash to checkout from GetRemoteUrl |
| 123 | Commit string |
| 124 | |
| 125 | // Outtie's HTTP server |
| 126 | OutsideHTTP string |
| Philip Zeyliger | be7802a | 2025-06-04 20:15:25 +0000 | [diff] [blame] | 127 | |
| 128 | // Prefix for git branches created by sketch |
| 129 | BranchPrefix string |
| philip.zeyliger | 6d3de48 | 2025-06-10 19:38:14 -0700 | [diff] [blame] | 130 | |
| 131 | // LinkToGitHub enables GitHub branch linking in UI |
| 132 | LinkToGitHub bool |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 133 | |
| 134 | // SubtraceToken enables running sketch under subtrace.dev (development only) |
| 135 | SubtraceToken string |
| Philip Zeyliger | 194bfa8 | 2025-06-24 06:03:06 -0700 | [diff] [blame] | 136 | |
| 137 | // MCPServers contains MCP server configurations |
| 138 | MCPServers []string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 139 | } |
| 140 | |
| 141 | // LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it. |
| 142 | // It writes status to stdout. |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 143 | func LaunchContainer(ctx context.Context, config ContainerConfig) error { |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 144 | slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 145 | if _, err := exec.LookPath("docker"); err != nil { |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 146 | if runtime.GOOS == "darwin" { |
| 147 | return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start") |
| 148 | } else { |
| 149 | return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)") |
| 150 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 151 | } |
| 152 | |
| 153 | if out, err := combinedOutput(ctx, "docker", "ps"); err != nil { |
| 154 | // `docker ps` provides a good error message here that can be |
| 155 | // easily chatgpt'ed by users, so send it to the user as-is: |
| 156 | // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? |
| 157 | return fmt.Errorf("docker ps: %s (%w)", out, err) |
| 158 | } |
| 159 | |
| 160 | _, hostPort, err := net.SplitHostPort(config.LocalAddr) |
| 161 | if err != nil { |
| 162 | return err |
| 163 | } |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 164 | // Bail early if sketch was started from a path that isn't in a git repo. |
| 165 | err = requireGitRepo(ctx, config.Path) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 166 | if err != nil { |
| 167 | return err |
| 168 | } |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 169 | |
| 170 | // Best effort attempt to get repo root; fall back to current directory. |
| 171 | gitRoot := config.Path |
| 172 | if root, err := gitRepoRoot(ctx, config.Path); err == nil { |
| 173 | gitRoot = root |
| 174 | } |
| 175 | |
| 176 | // Capture the original git origin URL before we set up the temporary git server |
| 177 | config.OriginalGitOrigin = getOriginalGitOrigin(ctx, gitRoot) |
| 178 | |
| Philip Zeyliger | d6d12d1 | 2025-05-19 19:19:21 -0700 | [diff] [blame] | 179 | err = checkForEmptyGitRepo(ctx, config.Path) |
| 180 | if err != nil { |
| 181 | return err |
| 182 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 183 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 184 | imgName, err := findOrBuildDockerImage(ctx, gitRoot, config.BaseImage, config.ForceRebuild, config.Verbose) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 185 | if err != nil { |
| 186 | return err |
| 187 | } |
| 188 | |
| Philip Zeyliger | c72fff5 | 2025-04-29 20:17:54 +0000 | [diff] [blame] | 189 | cntrName := "sketch-" + config.SessionID |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 190 | defer func() { |
| 191 | if config.NoCleanup { |
| 192 | return |
| 193 | } |
| 194 | if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil { |
| 195 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 196 | _ = out |
| 197 | } |
| 198 | if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil { |
| 199 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 200 | _ = out |
| 201 | } |
| 202 | }() |
| 203 | |
| 204 | // errCh receives errors from operations that this function calls in separate goroutines. |
| 205 | errCh := make(chan error) |
| 206 | |
| 207 | // Start the git server |
| 208 | gitSrv, err := newGitServer(gitRoot) |
| 209 | if err != nil { |
| 210 | return fmt.Errorf("failed to start git server: %w", err) |
| 211 | } |
| 212 | defer gitSrv.shutdown(ctx) |
| 213 | |
| 214 | go func() { |
| 215 | errCh <- gitSrv.serve(ctx) |
| 216 | }() |
| 217 | |
| 218 | // Get the current host git commit |
| 219 | var commit string |
| Philip Zeyliger | a347b17 | 2025-06-04 16:18:57 +0000 | [diff] [blame] | 220 | if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil { |
| 221 | return fmt.Errorf("git rev-parse HEAD: %w", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 222 | } else { |
| 223 | commit = strings.TrimSpace(string(out)) |
| 224 | } |
| Josh Bleecher Snyder | 664404e | 2025-06-04 21:56:42 +0000 | [diff] [blame] | 225 | |
| 226 | var upstream string |
| 227 | if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil { |
| 228 | slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err) |
| 229 | } else { |
| 230 | upstream = strings.TrimSpace(string(out)) |
| 231 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 232 | if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil { |
| 233 | return fmt.Errorf("git config http.receivepack true: %s: %w", out, err) |
| 234 | } |
| 235 | |
| 236 | relPath, err := filepath.Rel(gitRoot, config.Path) |
| 237 | if err != nil { |
| 238 | return err |
| 239 | } |
| 240 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 241 | config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort) |
| 242 | config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort) |
| Josh Bleecher Snyder | 664404e | 2025-06-04 21:56:42 +0000 | [diff] [blame] | 243 | config.Upstream = upstream |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 244 | config.Commit = commit |
| 245 | |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 246 | // Create the sketch container, copy over linux sketch |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 247 | if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil { |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 248 | return fmt.Errorf("failed to create docker container: %w", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 249 | } |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 250 | if err := copyEmbeddedLinuxBinaryToContainer(ctx, cntrName); err != nil { |
| 251 | return fmt.Errorf("failed to copy linux binary to container: %w", err) |
| David Crawshaw | 8bff16a | 2025-04-18 01:16:49 -0700 | [diff] [blame] | 252 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 253 | |
| David Crawshaw | 53786ef | 2025-04-24 12:52:51 -0700 | [diff] [blame] | 254 | fmt.Printf("📦 running in container %s\n", cntrName) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 255 | |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 256 | // Setup subtrace if token is provided (development only) - after container creation, before start |
| 257 | if config.SubtraceToken != "" { |
| 258 | fmt.Println("🔍 Setting up subtrace (development only)") |
| 259 | if err := setupSubtraceBeforeStart(ctx, cntrName, config.SubtraceToken); err != nil { |
| 260 | return fmt.Errorf("failed to setup subtrace: %w", err) |
| 261 | } |
| 262 | } |
| 263 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 264 | // Start the sketch container |
| 265 | if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil { |
| 266 | return fmt.Errorf("docker start: %s, %w", out, err) |
| 267 | } |
| 268 | |
| 269 | // Copies structured logs from the container to the host. |
| 270 | copyLogs := func() { |
| 271 | if config.ContainerLogDest == "" { |
| 272 | return |
| 273 | } |
| 274 | out, err := combinedOutput(ctx, "docker", "logs", cntrName) |
| 275 | if err != nil { |
| 276 | fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err) |
| 277 | return |
| 278 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 279 | prefix := []byte("structured logs:") |
| 280 | for line := range bytes.Lines(out) { |
| 281 | rest, ok := bytes.CutPrefix(line, prefix) |
| 282 | if !ok { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 283 | continue |
| 284 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 285 | logFile := string(bytes.TrimSpace(rest)) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 286 | srcPath := fmt.Sprintf("%s:%s", cntrName, logFile) |
| 287 | logFileName := filepath.Base(logFile) |
| 288 | dstPath := filepath.Join(config.ContainerLogDest, logFileName) |
| 289 | _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath) |
| 290 | if err != nil { |
| 291 | fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err) |
| 292 | } |
| 293 | fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath) |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | // NOTE: we want to see what the internal sketch binary prints |
| 298 | // regardless of the setting of the verbosity flag on the external |
| 299 | // binary, so reading "docker logs", which is the stdout/stderr of |
| 300 | // the internal binary is not conditional on the verbose flag. |
| 301 | appendInternalErr := func(err error) error { |
| 302 | if err == nil { |
| 303 | return nil |
| 304 | } |
| 305 | out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName) |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 306 | if logsErr != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 307 | return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr) |
| 308 | } |
| 309 | out = bytes.TrimSpace(out) |
| 310 | if len(out) > 0 { |
| 311 | return fmt.Errorf("docker logs: %s;\n%w", out, err) |
| 312 | } |
| 313 | return err |
| 314 | } |
| 315 | |
| 316 | // Get the sketch server port from the container |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 317 | localAddr, err := getContainerPort(ctx, cntrName, "80") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 318 | if err != nil { |
| 319 | return appendInternalErr(err) |
| 320 | } |
| 321 | |
| Philip Zeyliger | 0044241 | 2025-05-14 11:03:23 -0700 | [diff] [blame] | 322 | if config.Verbose { |
| 323 | fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr) |
| 324 | } |
| 325 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 326 | localSSHAddr, err := getContainerPort(ctx, cntrName, "22") |
| 327 | if err != nil { |
| 328 | return appendInternalErr(err) |
| 329 | } |
| 330 | sshHost, sshPort, err := net.SplitHostPort(localSSHAddr) |
| 331 | if err != nil { |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 332 | return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err)) |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 333 | } |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 334 | |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 335 | var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 336 | |
| banksean | 29d689f | 2025-06-23 15:41:26 +0000 | [diff] [blame] | 337 | cst, err := NewLocalSSHimmer(cntrName, sshHost, sshPort) |
| Sean McCullough | 078e85a | 2025-05-08 17:28:34 -0700 | [diff] [blame] | 338 | if err != nil { |
| 339 | return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err)) |
| 340 | } |
| 341 | |
| 342 | sshErr := CheckSSHReachability(cntrName) |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 343 | sshAvailable := false |
| 344 | sshErrMsg := "" |
| 345 | if sshErr != nil { |
| 346 | fmt.Println(sshErr.Error()) |
| 347 | sshErrMsg = sshErr.Error() |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 348 | // continue - ssh config is not required for the rest of sketch to function locally. |
| 349 | } else { |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 350 | sshAvailable = true |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 351 | // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find: |
| 352 | // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878 |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 353 | fmt.Printf(`Connect to this container via any of these methods: |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 354 | 🖥️ ssh %s |
| 355 | 🖥️ code --remote ssh-remote+root@%s /app -n |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 356 | 🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 357 | `, cntrName, cntrName, cntrName) |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 358 | sshUserIdentity = cst.userIdentity |
| 359 | sshServerIdentity = cst.serverIdentity |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 360 | |
| 361 | // Get the Container CA public key for mutual auth |
| 362 | if cst.containerCAPublicKey != nil { |
| 363 | containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey) |
| 364 | fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)") |
| 365 | } |
| 366 | |
| 367 | // Get the host certificate for mutual auth |
| 368 | hostCertificate = cst.hostCertificate |
| 369 | |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 370 | defer func() { |
| 371 | if err := cst.Cleanup(); err != nil { |
| 372 | appendInternalErr(err) |
| 373 | } |
| 374 | }() |
| 375 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 376 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 377 | // Tell the sketch container to Init(), which starts the SSH server |
| 378 | // and checks out the right commit. |
| 379 | // TODO: I'm trying to move as much configuration as possible into the command-line |
| 380 | // arguments to avoid splitting them up. "localAddr" is the only difficult one: |
| 381 | // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't |
| 382 | // get the port Docker chose until after the process starts. The SSH config is |
| 383 | // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg") |
| 384 | // may also empirically need to be done after the SSH server is up and running. |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 385 | go func() { |
| 386 | // TODO: Why is this called in a goroutine? I have found that when I pull this out |
| 387 | // of the goroutine and call it inline, then the terminal UI clears itself and all |
| 388 | // the scrollback (which is not good, but also not fatal). I can't see why it does this |
| 389 | // though, since none of the calls in postContainerInitConfig obviously write to stdout |
| 390 | // or stderr. |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 391 | if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 392 | slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error())) |
| 393 | errCh <- appendInternalErr(err) |
| 394 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 395 | |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 396 | // We open the browser after the init config because the above waits for the web server to be serving. |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 397 | ps1URL := "http://" + localAddr |
| 398 | if config.SkabandAddr != "" { |
| 399 | ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID) |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 400 | } |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 401 | if config.OpenBrowser { |
| 402 | browser.Open(ps1URL) |
| 403 | } |
| 404 | gitSrv.ps1URL.Store(&ps1URL) |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 405 | }() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 406 | |
| 407 | go func() { |
| 408 | cmd := exec.CommandContext(ctx, "docker", "attach", cntrName) |
| 409 | cmd.Stdin = os.Stdin |
| 410 | cmd.Stdout = os.Stdout |
| 411 | cmd.Stderr = os.Stderr |
| 412 | errCh <- run(ctx, "docker attach", cmd) |
| 413 | }() |
| 414 | |
| 415 | defer copyLogs() |
| 416 | |
| 417 | for { |
| 418 | select { |
| 419 | case <-ctx.Done(): |
| 420 | return ctx.Err() |
| 421 | case err := <-errCh: |
| 422 | if err != nil { |
| 423 | return appendInternalErr(fmt.Errorf("container process: %w", err)) |
| 424 | } |
| 425 | return nil |
| 426 | } |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) { |
| 431 | cmd := exec.CommandContext(ctx, cmdName, args...) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 432 | start := time.Now() |
| 433 | |
| 434 | out, err := cmd.CombinedOutput() |
| 435 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 436 | slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 437 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 438 | slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 439 | } |
| 440 | return out, err |
| 441 | } |
| 442 | |
| 443 | func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error { |
| 444 | start := time.Now() |
| 445 | err := cmd.Run() |
| 446 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 447 | slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 448 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 449 | slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 450 | } |
| 451 | return err |
| 452 | } |
| 453 | |
| 454 | type gitServer struct { |
| 455 | gitLn net.Listener |
| 456 | gitPort string |
| 457 | srv *http.Server |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 458 | pass string |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 459 | ps1URL atomic.Pointer[string] |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 460 | } |
| 461 | |
| 462 | func (gs *gitServer) shutdown(ctx context.Context) { |
| 463 | gs.srv.Shutdown(ctx) |
| 464 | gs.gitLn.Close() |
| 465 | } |
| 466 | |
| 467 | // Serve a git remote from the host for the container to fetch from and push to. |
| 468 | func (gs *gitServer) serve(ctx context.Context) error { |
| 469 | slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git")) |
| 470 | return gs.srv.Serve(gs.gitLn) |
| 471 | } |
| 472 | |
| 473 | func newGitServer(gitRoot string) (*gitServer, error) { |
| Josh Bleecher Snyder | 9f6a998 | 2025-04-22 17:34:15 -0700 | [diff] [blame] | 474 | ret := &gitServer{ |
| 475 | pass: rand.Text(), |
| 476 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 477 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 478 | gitLn, err := net.Listen("tcp4", ":0") |
| 479 | if err != nil { |
| 480 | return nil, fmt.Errorf("git listen: %w", err) |
| 481 | } |
| 482 | ret.gitLn = gitLn |
| 483 | |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 484 | browserC := make(chan bool, 1) // channel of browser open requests |
| 485 | |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 486 | go func() { |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 487 | for range browserC { |
| 488 | browser.Open(*ret.ps1URL.Load()) |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 489 | } |
| 490 | }() |
| 491 | |
| 492 | srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 493 | ret.srv = &srv |
| 494 | |
| 495 | _, gitPort, err := net.SplitHostPort(gitLn.Addr().String()) |
| 496 | if err != nil { |
| 497 | return nil, fmt.Errorf("git port: %w", err) |
| 498 | } |
| 499 | ret.gitPort = gitPort |
| 500 | return ret, nil |
| 501 | } |
| 502 | |
| 503 | func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error { |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 504 | cmdArgs := []string{ |
| 505 | "create", |
| David Crawshaw | 66cf74e | 2025-05-05 08:48:39 -0700 | [diff] [blame] | 506 | "-i", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 507 | "--name", cntrName, |
| 508 | "-p", hostPort + ":80", // forward container port 80 to a host port |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 509 | "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 510 | } |
| Philip Zeyliger | 3d2eff0 | 2025-05-27 09:30:31 -0700 | [diff] [blame] | 511 | if !(config.OneShot || !config.TermUI) { |
| David Crawshaw | 66cf74e | 2025-05-05 08:48:39 -0700 | [diff] [blame] | 512 | cmdArgs = append(cmdArgs, "-t") |
| 513 | } |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 514 | |
| 515 | for _, envVar := range getEnvForwardingFromGitConfig(ctx) { |
| 516 | cmdArgs = append(cmdArgs, "-e", envVar) |
| 517 | } |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 518 | if config.ModelURL != "" { |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 519 | cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 520 | } |
| 521 | if config.SketchPubKey != "" { |
| 522 | cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey) |
| 523 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 524 | if config.SSHPort > 0 { |
| 525 | cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port |
| 526 | } else { |
| Philip Zeyliger | 87d29ef | 2025-05-16 20:25:28 -0700 | [diff] [blame] | 527 | cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh. |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 528 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 529 | // colima does this by default, but Linux docker seems to need this set explicitly |
| 530 | cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway") |
| Josh Bleecher Snyder | ac761c9 | 2025-05-16 18:58:45 +0000 | [diff] [blame] | 531 | |
| David Crawshaw | 1bd636c | 2025-06-13 19:56:27 +0000 | [diff] [blame] | 532 | // Add seccomp profile to prevent killing PID 1 (the sketch process itself) |
| 533 | // Write the seccomp profile to cache directory if it doesn't exist |
| 534 | seccompPath, err := ensureSeccompProfile(ctx) |
| 535 | if err != nil { |
| 536 | return fmt.Errorf("failed to create seccomp profile: %w", err) |
| 537 | } |
| 538 | cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath) |
| 539 | |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 540 | // Add subtrace environment variable if token is provided |
| 541 | if config.SubtraceToken != "" { |
| 542 | cmdArgs = append(cmdArgs, "-e", "SUBTRACE_TOKEN="+config.SubtraceToken) |
| 543 | cmdArgs = append(cmdArgs, "-e", "SUBTRACE_HTTP2=1") |
| 544 | } |
| 545 | |
| Josh Bleecher Snyder | ac761c9 | 2025-05-16 18:58:45 +0000 | [diff] [blame] | 546 | // Add volume mounts if specified |
| 547 | for _, mount := range config.Mounts { |
| 548 | if mount != "" { |
| 549 | cmdArgs = append(cmdArgs, "-v", mount) |
| 550 | } |
| 551 | } |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 552 | cmdArgs = append(cmdArgs, imgName) |
| 553 | |
| 554 | // Add command: either [sketch] or [subtrace run -- sketch] |
| 555 | if config.SubtraceToken != "" { |
| 556 | cmdArgs = append(cmdArgs, "/usr/local/bin/subtrace", "run", "--", "/bin/sketch") |
| 557 | } else { |
| 558 | cmdArgs = append(cmdArgs, "/bin/sketch") |
| 559 | } |
| 560 | |
| 561 | // Add all sketch arguments |
| 562 | cmdArgs = append(cmdArgs, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 563 | "-unsafe", |
| 564 | "-addr=:80", |
| 565 | "-session-id="+config.SessionID, |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 566 | "-git-username="+config.GitUsername, |
| 567 | "-git-email="+config.GitEmail, |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 568 | "-outside-hostname="+config.OutsideHostname, |
| 569 | "-outside-os="+config.OutsideOS, |
| 570 | "-outside-working-dir="+config.OutsideWorkingDir, |
| Josh Bleecher Snyder | 33032d3 | 2025-05-30 16:28:21 +0000 | [diff] [blame] | 571 | fmt.Sprintf("-max-dollars=%f", config.MaxDollars), |
| Josh Bleecher Snyder | 3cae7d9 | 2025-04-30 09:54:29 -0700 | [diff] [blame] | 572 | "-open=false", |
| Philip Zeyliger | 613c0f5 | 2025-05-15 16:36:22 -0700 | [diff] [blame] | 573 | "-termui="+fmt.Sprintf("%t", config.TermUI), |
| Philip Zeyliger | cabfa55 | 2025-05-19 16:14:28 -0700 | [diff] [blame] | 574 | "-verbose="+fmt.Sprintf("%t", config.Verbose), |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 575 | "-x="+config.ExperimentFlag, |
| Philip Zeyliger | be7802a | 2025-06-04 20:15:25 +0000 | [diff] [blame] | 576 | "-branch-prefix="+config.BranchPrefix, |
| philip.zeyliger | 6d3de48 | 2025-06-10 19:38:14 -0700 | [diff] [blame] | 577 | "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub), |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 578 | ) |
| philip.zeyliger | 8773e68 | 2025-06-11 21:36:21 -0700 | [diff] [blame] | 579 | // Set SSH connection string based on session ID for SSH Theater |
| 580 | cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID) |
| Josh Bleecher Snyder | a96f9d2 | 2025-07-11 02:47:33 +0000 | [diff] [blame] | 581 | if relPath != "." { |
| 582 | cmdArgs = append(cmdArgs, "-C", relPath) |
| 583 | } |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 584 | if config.Model != "" { |
| 585 | cmdArgs = append(cmdArgs, "-model="+config.Model) |
| 586 | } |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 587 | if config.GitRemoteUrl != "" { |
| 588 | cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl) |
| 589 | if config.Commit == "" { |
| 590 | panic("Commit should have been set when GitRemoteUrl was set") |
| 591 | } |
| 592 | cmdArgs = append(cmdArgs, "-commit="+config.Commit) |
| Josh Bleecher Snyder | 664404e | 2025-06-04 21:56:42 +0000 | [diff] [blame] | 593 | cmdArgs = append(cmdArgs, "-upstream="+config.Upstream) |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 594 | } |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 595 | if config.OriginalGitOrigin != "" { |
| 596 | cmdArgs = append(cmdArgs, "-original-git-origin="+config.OriginalGitOrigin) |
| 597 | } |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 598 | if config.OutsideHTTP != "" { |
| 599 | cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP) |
| 600 | } |
| Josh Bleecher Snyder | e3c2f22 | 2025-05-15 20:54:52 +0000 | [diff] [blame] | 601 | cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr) |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 602 | if config.Prompt != "" { |
| 603 | cmdArgs = append(cmdArgs, "-prompt", config.Prompt) |
| 604 | } |
| 605 | if config.OneShot { |
| 606 | cmdArgs = append(cmdArgs, "-one-shot") |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 607 | } |
| Josh Bleecher Snyder | e3c2f22 | 2025-05-15 20:54:52 +0000 | [diff] [blame] | 608 | if config.ModelURL == "" { |
| 609 | // Forward ANTHROPIC_API_KEY for direct use. |
| 610 | // TODO: have outtie run an http proxy? |
| 611 | // TODO: select and forward the relevant API key based on the model |
| 612 | cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY")) |
| 613 | } |
| Philip Zeyliger | 194bfa8 | 2025-06-24 06:03:06 -0700 | [diff] [blame] | 614 | // Add MCP server configurations |
| 615 | for _, mcpServer := range config.MCPServers { |
| 616 | cmdArgs = append(cmdArgs, "-mcp", mcpServer) |
| 617 | } |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 618 | |
| 619 | // Add additional docker arguments if provided |
| 620 | if config.DockerArgs != "" { |
| 621 | // Parse space-separated docker arguments with support for quotes and escaping |
| 622 | args := parseDockerArgs(config.DockerArgs) |
| 623 | // Insert arguments after "create" but before other arguments |
| 624 | for i := len(args) - 1; i >= 0; i-- { |
| 625 | cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...) |
| 626 | } |
| 627 | } |
| 628 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 629 | if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil { |
| 630 | return fmt.Errorf("docker create: %s, %w", out, err) |
| 631 | } |
| 632 | return nil |
| 633 | } |
| 634 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 635 | func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 636 | localAddr := "" |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 637 | if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 638 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 639 | } else { |
| 640 | v4, _, found := strings.Cut(string(out), "\n") |
| 641 | if !found { |
| 642 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 643 | } |
| 644 | localAddr = v4 |
| 645 | if strings.HasPrefix(localAddr, "0.0.0.0") { |
| 646 | localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0") |
| 647 | } |
| 648 | } |
| 649 | return localAddr, nil |
| 650 | } |
| 651 | |
| 652 | // Contact the container and configure it. |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 653 | func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 654 | localURL := "http://" + localAddr |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 655 | |
| 656 | initMsg, err := json.Marshal( |
| 657 | server.InitRequest{ |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 658 | HostAddr: localAddr, |
| 659 | SSHAuthorizedKeys: sshAuthorizedKeys, |
| 660 | SSHServerIdentity: sshServerIdentity, |
| 661 | SSHContainerCAKey: sshContainerCAKey, |
| 662 | SSHHostCertificate: sshHostCertificate, |
| 663 | SSHAvailable: sshAvailable, |
| 664 | SSHError: sshError, |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 665 | }) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 666 | if err != nil { |
| 667 | return fmt.Errorf("init msg: %w", err) |
| 668 | } |
| 669 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 670 | // Note: this /init POST is handled in loop/server/loophttp.go: |
| 671 | initMsgByteReader := bytes.NewReader(initMsg) |
| 672 | req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader) |
| 673 | if err != nil { |
| 674 | return err |
| 675 | } |
| 676 | |
| 677 | var res *http.Response |
| 678 | for i := 0; ; i++ { |
| 679 | time.Sleep(100 * time.Millisecond) |
| 680 | // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes. |
| 681 | initMsgByteReader.Reset(initMsg) |
| 682 | res, err = http.DefaultClient.Do(req) |
| 683 | if err != nil { |
| David Crawshaw | 99231ba | 2025-05-03 10:48:26 -0700 | [diff] [blame] | 684 | if i < 100 { |
| 685 | if i%10 == 0 { |
| 686 | slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error())) |
| 687 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 688 | continue |
| 689 | } |
| 690 | return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err) |
| 691 | } |
| 692 | break |
| 693 | } |
| 694 | resBytes, _ := io.ReadAll(res.Body) |
| 695 | if res.StatusCode != http.StatusOK { |
| 696 | return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes) |
| 697 | } |
| 698 | return nil |
| 699 | } |
| 700 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 701 | func findOrBuildDockerImage(ctx context.Context, gitRoot, baseImage string, forceRebuild, verbose bool) (imgName string, err error) { |
| 702 | // Default to the published sketch image if no base image is specified |
| 703 | if baseImage == "" { |
| 704 | imageTag := dockerfileBaseHash() |
| 705 | baseImage = fmt.Sprintf("%s:%s", dockerImgName, imageTag) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 706 | } |
| 707 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 708 | // Ensure the base image exists locally, pull if necessary |
| 709 | if err := ensureBaseImageExists(ctx, baseImage); err != nil { |
| 710 | return "", fmt.Errorf("failed to ensure base image %s exists: %w", baseImage, err) |
| 711 | } |
| 712 | |
| 713 | // Get the base image container ID for caching |
| 714 | baseImageID, err := getDockerImageID(ctx, baseImage) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 715 | if err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 716 | return "", fmt.Errorf("failed to get base image ID for %s: %w", baseImage, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 717 | } |
| 718 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 719 | // Create a cache key based on base image ID and working directory |
| 720 | // Docker naming conventions restrict you to 20 characters per path component |
| 721 | // and only allow lowercase letters, digits, underscores, and dashes, so encoding |
| 722 | // the hash and the repo directory is sadly a bit of a non-starter. |
| 723 | cacheKey := createCacheKey(baseImageID, gitRoot) |
| 724 | imgName = "sketch-" + cacheKey |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 725 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 726 | // Check if the cached image exists and is up to date |
| 727 | if !forceRebuild { |
| 728 | if exists, err := dockerImageExists(ctx, imgName); err != nil { |
| 729 | return "", fmt.Errorf("failed to check if image exists: %w", err) |
| 730 | } else if exists { |
| 731 | if verbose { |
| 732 | fmt.Printf("using cached image %s\n", imgName) |
| Kilian Lackhove | 23772f4 | 2025-06-18 20:28:58 +0200 | [diff] [blame] | 733 | } |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 734 | return imgName, nil |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 735 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 736 | } |
| 737 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 738 | // Build the layered image |
| 739 | if err := buildLayeredImage(ctx, imgName, baseImage, gitRoot, verbose); err != nil { |
| 740 | return "", fmt.Errorf("failed to build layered image: %w", err) |
| 741 | } |
| 742 | |
| 743 | return imgName, nil |
| 744 | } |
| 745 | |
| 746 | // ensureBaseImageExists checks if the base image exists locally and pulls it if not |
| 747 | func ensureBaseImageExists(ctx context.Context, imageName string) error { |
| 748 | exists, err := dockerImageExists(ctx, imageName) |
| 749 | if err != nil { |
| 750 | return fmt.Errorf("failed to check if image exists: %w", err) |
| 751 | } |
| 752 | |
| 753 | if !exists { |
| 754 | fmt.Printf("🐋 pulling base image %s...\n", imageName) |
| 755 | if out, err := combinedOutput(ctx, "docker", "pull", imageName); err != nil { |
| 756 | return fmt.Errorf("docker pull %s failed: %s: %w", imageName, out, err) |
| 757 | } |
| 758 | fmt.Printf("✅ successfully pulled %s\n", imageName) |
| 759 | } |
| 760 | |
| 761 | return nil |
| 762 | } |
| 763 | |
| 764 | // getDockerImageID gets the container ID for a Docker image |
| 765 | func getDockerImageID(ctx context.Context, imageName string) (string, error) { |
| 766 | out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{.Id}}", imageName) |
| 767 | if err != nil { |
| 768 | return "", err |
| 769 | } |
| 770 | return strings.TrimSpace(string(out)), nil |
| 771 | } |
| 772 | |
| 773 | // createCacheKey creates a cache key from base image ID and working directory |
| 774 | func createCacheKey(baseImageID, gitRoot string) string { |
| 775 | h := sha256.New() |
| 776 | h.Write([]byte(baseImageID)) |
| 777 | h.Write([]byte(gitRoot)) |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 778 | // one-time cache-busting for the transition from copying git repos to only copying git objects |
| 779 | h.Write([]byte("git-objects")) |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 780 | return hex.EncodeToString(h.Sum(nil))[:12] // Use first 12 chars for shorter name |
| 781 | } |
| 782 | |
| 783 | // dockerImageExists checks if a Docker image exists locally |
| 784 | func dockerImageExists(ctx context.Context, imageName string) (bool, error) { |
| 785 | out, err := combinedOutput(ctx, "docker", "inspect", imageName) |
| 786 | if err != nil { |
| 787 | if strings.Contains(strings.ToLower(string(out)), "no such object") || |
| 788 | strings.Contains(strings.ToLower(string(out)), "no such image") { |
| 789 | return false, nil |
| 790 | } |
| 791 | return false, err |
| 792 | } |
| 793 | return true, nil |
| 794 | } |
| 795 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 796 | // buildLayeredImage builds a new Docker image by layering the repo on top of the base image. |
| 797 | // |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 798 | // TODO: git config stuff could be environment variables at runtime for email and username. |
| 799 | // The git docs seem to say that http.postBuffer is a bug in our git proxy more than a thing |
| 800 | // that's needed, but we haven't found the bug yet! |
| Philip Zeyliger | 882b1d1 | 2025-07-02 20:04:08 -0700 | [diff] [blame] | 801 | // |
| 802 | // TODO: There is a caching tension. A base image is great for tools (like, some version |
| 803 | // of Go). Then you want a git repo, which is much faster to incrementally fetch rather |
| 804 | // than cloning every time. Then you want some build artifacts, like perhaps the |
| 805 | // "go mod download" cache, or the "go build" cache or the "npm install" cache. |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 806 | // The implementation here copies the git objects into the base image. |
| 807 | // That enables fast clones into the container, because most of the git objects are already there. |
| 808 | // It also avoids copying uncommitted changes, configs/hooks, etc. |
| 809 | // TODO: We should also set up fake temporary Go module(s) so we can run "go mod download". |
| 810 | // This is an ok compromise, but a power user might want |
| Philip Zeyliger | 882b1d1 | 2025-07-02 20:04:08 -0700 | [diff] [blame] | 811 | // less caching or more caching, depending on their use case. One approach we could take |
| 812 | // is to punt entirely if /app/.git already exists. If the user has provided a -base-image with |
| 813 | // their git repo, let's assume they know what they're doing, and they've customized their image |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 814 | // for their use case. |
| Philip Zeyliger | 882b1d1 | 2025-07-02 20:04:08 -0700 | [diff] [blame] | 815 | // Note that buildx has some support for conditional COPY, but without buildx, which |
| 816 | // we can't reliably depend on, we have to run the base image to inspect its file system, |
| 817 | // and then we can decide what to do. |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 818 | // |
| 819 | // We may in the future want to enable people to bring along uncommitted changes to tracked files. |
| 820 | // To do that, we would run `git stash create` in outie at launch time, treat HEAD as the base commit, |
| 821 | // and add in the stash commit as a new commit atop it. |
| 822 | // That would accurately model the base commit as well as the uncommitted changes. |
| 823 | // (This wouldn't happen here, but at agent/container initialization time.) |
| 824 | // |
| 825 | // repoPath is the current working directory where sketch is being run from. |
| 826 | func buildLayeredImage(ctx context.Context, imgName, baseImage, gitRoot string, verbose bool) error { |
| 827 | // Shove a bunch of git objects into the image for faster future cloning. |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 828 | dockerfileContent := fmt.Sprintf(`FROM %s |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 829 | COPY . /git-ref |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 830 | WORKDIR /app |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 831 | # TODO: restore go.mod download |
| 832 | # RUN if [ -f go.mod ]; then go mod download; fi |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 833 | CMD ["/bin/sketch"] |
| 834 | `, baseImage) |
| 835 | |
| 836 | // Create a temporary directory for the Dockerfile |
| 837 | tmpDir, err := os.MkdirTemp("", "sketch-docker-*") |
| 838 | if err != nil { |
| 839 | return fmt.Errorf("failed to create temporary directory: %w", err) |
| 840 | } |
| 841 | defer os.RemoveAll(tmpDir) |
| 842 | |
| 843 | dockerfilePath := filepath.Join(tmpDir, "Dockerfile") |
| 844 | if err := os.WriteFile(dockerfilePath, []byte(dockerfileContent), 0o666); err != nil { |
| 845 | return fmt.Errorf("failed to write Dockerfile: %w", err) |
| 846 | } |
| 847 | |
| 848 | // Get git user info |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 849 | var gitUserEmail, gitUserName string |
| 850 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 851 | return fmt.Errorf("git user.email is not set. Please run 'git config --global user.email \"your.email@example.com\"' to set your email address") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 852 | } else { |
| 853 | gitUserEmail = strings.TrimSpace(string(out)) |
| 854 | } |
| 855 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 856 | return fmt.Errorf("git user.name is not set. Please run 'git config --global user.name \"Your Name\"' to set your name") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 857 | } else { |
| 858 | gitUserName = strings.TrimSpace(string(out)) |
| 859 | } |
| 860 | |
| 861 | start := time.Now() |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 862 | cmdArgs := []string{ |
| 863 | "build", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 864 | "-t", imgName, |
| 865 | "-f", dockerfilePath, |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 866 | "--build-arg", "GIT_USER_EMAIL=" + gitUserEmail, |
| 867 | "--build-arg", "GIT_USER_NAME=" + gitUserName, |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 868 | ".", |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 869 | } |
| 870 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 871 | commonDir, err := gitCommonDir(ctx, gitRoot) |
| 872 | if err != nil { |
| 873 | return fmt.Errorf("failed to get git common dir: %w", err) |
| 874 | } |
| 875 | |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 876 | cmd := exec.CommandContext(ctx, "docker", cmdArgs...) |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 877 | cmd.Dir = commonDir |
| David Crawshaw | 31f1524 | 2025-05-06 16:03:49 -0700 | [diff] [blame] | 878 | // We print the docker build output whether or not the user |
| 879 | // has selected --verbose. Building an image takes a while |
| 880 | // and this gives good context. |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 881 | cmd.Stdout = os.Stdout |
| 882 | cmd.Stderr = os.Stderr |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 883 | fmt.Printf("🏗️ building docker image %s from base %s...\n", imgName, baseImage) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 884 | |
| 885 | err = run(ctx, "docker build", cmd) |
| 886 | if err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 887 | return fmt.Errorf("docker build failed: %v", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 888 | } |
| 889 | fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond)) |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 890 | return nil |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 891 | } |
| 892 | |
| Philip Zeyliger | d6d12d1 | 2025-05-19 19:19:21 -0700 | [diff] [blame] | 893 | func checkForEmptyGitRepo(ctx context.Context, path string) error { |
| 894 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD") |
| 895 | cmd.Dir = path |
| 896 | _, err := cmd.CombinedOutput() |
| 897 | if err != nil { |
| 898 | return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s", |
| 899 | "git commit --allow-empty -m 'initial commit'") |
| 900 | } |
| 901 | return nil |
| 902 | } |
| 903 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 904 | // requireGitRepo confirms that path is within a git repository. |
| 905 | func requireGitRepo(ctx context.Context, path string) error { |
| 906 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-dir") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 907 | cmd.Dir = path |
| 908 | out, err := cmd.CombinedOutput() |
| 909 | if err != nil { |
| 910 | if strings.Contains(string(out), "not a git repository") { |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 911 | return fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo. |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 912 | Consider one of the following options: |
| 913 | - cd to a different dir that is already part of a git repo first, or |
| 914 | - to create a new git repo from this directory (%s), run this command: |
| 915 | |
| 916 | git init . && git commit --allow-empty -m "initial commit" |
| 917 | |
| 918 | and try running sketch again. |
| 919 | `, path, path) |
| 920 | } |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 921 | return fmt.Errorf("git rev-parse --git-dir: %s: %w", out, err) |
| 922 | } |
| 923 | return nil |
| 924 | } |
| 925 | |
| 926 | // gitRepoRoot attempts to find the git repository root directory. |
| 927 | // Returns an error if not in a git repository or if it's a bare repository. |
| 928 | // This is used to calculate relative paths for preserving user's working directory context. |
| 929 | func gitRepoRoot(ctx context.Context, path string) (string, error) { |
| 930 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel") |
| 931 | cmd.Dir = path |
| 932 | out, err := cmd.CombinedOutput() |
| 933 | if err != nil { |
| Marc-Antoine Ruel | 467c396 | 2025-06-29 13:32:59 -0400 | [diff] [blame] | 934 | return "", fmt.Errorf("git rev-parse --show-toplevel: %s: %w", out, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 935 | } |
| Marc-Antoine Ruel | 467c396 | 2025-06-29 13:32:59 -0400 | [diff] [blame] | 936 | // The returned path is absolute. |
| 937 | return strings.TrimSpace(string(out)), nil |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 938 | } |
| 939 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 940 | // gitCommonDir finds the git common directory for path. |
| 941 | func gitCommonDir(ctx context.Context, path string) (string, error) { |
| 942 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir") |
| 943 | cmd.Dir = path |
| 944 | out, err := cmd.CombinedOutput() |
| 945 | if err != nil { |
| 946 | return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err) |
| 947 | } |
| 948 | gitCommonDir := strings.TrimSpace(string(out)) |
| 949 | if !filepath.IsAbs(gitCommonDir) { |
| 950 | gitCommonDir = filepath.Join(path, gitCommonDir) |
| 951 | } |
| 952 | return gitCommonDir, nil |
| 953 | } |
| 954 | |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 955 | // getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker |
| 956 | // from git config using the sketch.envfwd multi-valued key. |
| 957 | func getEnvForwardingFromGitConfig(ctx context.Context) []string { |
| 958 | outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput() |
| 959 | out := string(outb) |
| 960 | if err != nil { |
| 961 | if strings.Contains(out, "key does not exist") { |
| 962 | return nil |
| 963 | } |
| 964 | slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out) |
| 965 | return nil |
| 966 | } |
| 967 | |
| 968 | var envVars []string |
| 969 | for envVar := range strings.Lines(out) { |
| 970 | envVar = strings.TrimSpace(envVar) |
| 971 | if envVar == "" { |
| 972 | continue |
| 973 | } |
| 974 | envVars = append(envVars, envVar+"="+os.Getenv(envVar)) |
| 975 | } |
| 976 | return envVars |
| 977 | } |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 978 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame^] | 979 | // getOriginalGitOrigin returns the URL of the git remote 'origin' if it exists in the given directory |
| 980 | func getOriginalGitOrigin(ctx context.Context, dir string) string { |
| 981 | cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url") |
| 982 | cmd.Dir = dir |
| 983 | out, err := cmd.Output() |
| 984 | if err != nil { |
| 985 | return "" |
| 986 | } |
| 987 | return strings.TrimSpace(string(out)) |
| 988 | } |
| 989 | |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 990 | // parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings. |
| 991 | // It handles quoted arguments and escaped characters. |
| 992 | // |
| 993 | // Examples: |
| 994 | // |
| 995 | // --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"] |
| 996 | // --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"] |
| 997 | // --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""] |
| 998 | func parseDockerArgs(args string) []string { |
| 999 | if args = strings.TrimSpace(args); args == "" { |
| 1000 | return []string{} |
| 1001 | } |
| 1002 | |
| 1003 | var result []string |
| 1004 | var current strings.Builder |
| 1005 | inQuotes := false |
| 1006 | escapeNext := false |
| 1007 | quoteChar := rune(0) |
| 1008 | |
| 1009 | for _, char := range args { |
| 1010 | if escapeNext { |
| 1011 | current.WriteRune(char) |
| 1012 | escapeNext = false |
| 1013 | continue |
| 1014 | } |
| 1015 | |
| 1016 | if char == '\\' { |
| 1017 | escapeNext = true |
| 1018 | continue |
| 1019 | } |
| 1020 | |
| 1021 | if char == '"' || char == '\'' { |
| 1022 | if !inQuotes { |
| 1023 | inQuotes = true |
| 1024 | quoteChar = char |
| 1025 | continue |
| 1026 | } else if char == quoteChar { |
| 1027 | inQuotes = false |
| 1028 | quoteChar = rune(0) |
| 1029 | continue |
| 1030 | } |
| 1031 | // Non-matching quote character inside quotes |
| 1032 | current.WriteRune(char) |
| 1033 | continue |
| 1034 | } |
| 1035 | |
| 1036 | // Space outside of quotes is an argument separator |
| 1037 | if char == ' ' && !inQuotes { |
| 1038 | if current.Len() > 0 { |
| 1039 | result = append(result, current.String()) |
| 1040 | current.Reset() |
| 1041 | } |
| 1042 | continue |
| 1043 | } |
| 1044 | |
| 1045 | current.WriteRune(char) |
| 1046 | } |
| 1047 | |
| 1048 | // Add the last argument if there is one |
| 1049 | if current.Len() > 0 { |
| 1050 | result = append(result, current.String()) |
| 1051 | } |
| 1052 | |
| 1053 | return result |
| 1054 | } |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1055 | |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1056 | // copyEmbeddedLinuxBinaryToContainer copies the embedded linux binary to the container |
| 1057 | func copyEmbeddedLinuxBinaryToContainer(ctx context.Context, containerName string) error { |
| Josh Bleecher Snyder | 5ae245b | 2025-07-08 22:00:24 +0000 | [diff] [blame] | 1058 | out, err := combinedOutput(ctx, "docker", "version", "--format", "{{.Server.Arch}}") |
| 1059 | if err != nil { |
| 1060 | return fmt.Errorf("failed to detect Docker server architecture: %s: %w", out, err) |
| 1061 | } |
| 1062 | arch := strings.TrimSpace(string(out)) |
| 1063 | |
| 1064 | bin := embedded.LinuxBinary(arch) |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1065 | if bin == nil { |
| Josh Bleecher Snyder | 5ae245b | 2025-07-08 22:00:24 +0000 | [diff] [blame] | 1066 | return fmt.Errorf("no embedded linux binary for architecture %q", arch) |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1067 | } |
| 1068 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1069 | // Stream a tarball to docker cp. |
| 1070 | pr, pw := io.Pipe() |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1071 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1072 | errCh := make(chan error, 1) |
| 1073 | go func() { |
| 1074 | defer pw.Close() |
| 1075 | tw := tar.NewWriter(pw) |
| 1076 | |
| 1077 | hdr := &tar.Header{ |
| 1078 | Name: "bin/sketch", // final path inside the container |
| 1079 | Mode: 0o700, |
| 1080 | Size: int64(len(bin)), |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1081 | } |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1082 | if err := tw.WriteHeader(hdr); err != nil { |
| 1083 | errCh <- fmt.Errorf("failed to write tar header: %w", err) |
| 1084 | return |
| 1085 | } |
| 1086 | if _, err := tw.Write(bin); err != nil { |
| 1087 | errCh <- fmt.Errorf("failed to write binary to tar: %w", err) |
| 1088 | return |
| 1089 | } |
| 1090 | if err := tw.Close(); err != nil { |
| 1091 | errCh <- fmt.Errorf("failed to close tar writer: %w", err) |
| 1092 | return |
| 1093 | } |
| 1094 | errCh <- nil |
| 1095 | }() |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1096 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1097 | cmd := exec.CommandContext(ctx, "docker", "cp", "-", containerName+":/") |
| 1098 | cmd.Stdin = pr |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1099 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1100 | out, cmdErr := cmd.CombinedOutput() |
| 1101 | |
| 1102 | if tarErr := <-errCh; tarErr != nil { |
| 1103 | return tarErr |
| 1104 | } |
| 1105 | if cmdErr != nil { |
| 1106 | return fmt.Errorf("docker cp failed: %s: %w", out, cmdErr) |
| 1107 | } |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1108 | return nil |
| 1109 | } |
| 1110 | |
| David Crawshaw | 1bd636c | 2025-06-13 19:56:27 +0000 | [diff] [blame] | 1111 | const seccompProfile = `{ |
| 1112 | "defaultAction": "SCMP_ACT_ALLOW", |
| 1113 | "syscalls": [ |
| 1114 | { |
| 1115 | "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"], |
| 1116 | "action": "SCMP_ACT_ERRNO", |
| 1117 | "args": [ |
| 1118 | { |
| 1119 | "index": 0, |
| 1120 | "value": 1, |
| 1121 | "op": "SCMP_CMP_EQ" |
| 1122 | } |
| 1123 | ] |
| 1124 | } |
| 1125 | ] |
| 1126 | }` |
| 1127 | |
| 1128 | // ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist. |
| 1129 | func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) { |
| 1130 | homeDir, err := os.UserHomeDir() |
| 1131 | if err != nil { |
| 1132 | return "", fmt.Errorf("failed to get home directory: %w", err) |
| 1133 | } |
| 1134 | cacheDir := filepath.Join(homeDir, ".cache", "sketch") |
| 1135 | if err := os.MkdirAll(cacheDir, 0o755); err != nil { |
| 1136 | return "", fmt.Errorf("failed to create cache directory: %w", err) |
| 1137 | } |
| 1138 | seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json") |
| 1139 | |
| 1140 | curBytes, err := os.ReadFile(seccompPath) |
| 1141 | if err != nil && !os.IsNotExist(err) { |
| 1142 | return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err) |
| 1143 | } |
| 1144 | if string(curBytes) == seccompProfile { |
| 1145 | return seccompPath, nil // File already exists and matches the expected profile |
| 1146 | } |
| 1147 | |
| 1148 | if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil { |
| 1149 | return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err) |
| 1150 | } |
| 1151 | slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath) |
| 1152 | return seccompPath, nil |
| 1153 | } |