| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 1 | // Package dockerimg |
| 2 | package dockerimg |
| 3 | |
| 4 | import ( |
| 5 | "bytes" |
| 6 | "context" |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 7 | "crypto/rand" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 8 | "crypto/sha256" |
| 9 | "encoding/hex" |
| 10 | "encoding/json" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "log/slog" |
| 14 | "net" |
| 15 | "net/http" |
| 16 | "os" |
| 17 | "os/exec" |
| 18 | "path/filepath" |
| 19 | "runtime" |
| 20 | "strings" |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 21 | "sync/atomic" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 22 | "time" |
| 23 | |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 24 | "golang.org/x/crypto/ssh" |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 25 | "sketch.dev/browser" |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 26 | "sketch.dev/llm/ant" |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 27 | "sketch.dev/loop/server" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 28 | "sketch.dev/skribe" |
| Philip Zeyliger | 5d6af87 | 2025-04-23 19:48:34 -0700 | [diff] [blame] | 29 | "sketch.dev/webui" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 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 | |
| 70 | // Host directory to copy container logs into, if not set to "" |
| 71 | ContainerLogDest string |
| 72 | |
| 73 | // Path to pre-built linux sketch binary, or build a new one if set to "" |
| 74 | SketchBinaryLinux string |
| 75 | |
| 76 | // Sketch client public key. |
| 77 | SketchPubKey string |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 78 | |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 79 | // Host port for the container's ssh server |
| 80 | SSHPort int |
| 81 | |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 82 | // Outside information to pass to the container |
| 83 | OutsideHostname string |
| 84 | OutsideOS string |
| 85 | OutsideWorkingDir string |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 86 | |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 87 | // If true, exit after the first turn |
| 88 | OneShot bool |
| 89 | |
| 90 | // Initial prompt |
| 91 | Prompt string |
| Philip Zeyliger | 1b47aa2 | 2025-04-28 19:25:38 +0000 | [diff] [blame] | 92 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 93 | // Initial commit to use as starting point. Resolved into Commit on the host. |
| Philip Zeyliger | 1b47aa2 | 2025-04-28 19:25:38 +0000 | [diff] [blame] | 94 | InitialCommit string |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 95 | |
| 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 |
| 112 | MaxDollars float64 |
| 113 | MaxIterations uint64 |
| 114 | MaxWallTime time.Duration |
| 115 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 116 | GitRemoteUrl string |
| 117 | |
| 118 | // Commit hash to checkout from GetRemoteUrl |
| 119 | Commit string |
| 120 | |
| 121 | // Outtie's HTTP server |
| 122 | OutsideHTTP string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 123 | } |
| 124 | |
| 125 | // LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it. |
| 126 | // It writes status to stdout. |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 127 | func LaunchContainer(ctx context.Context, config ContainerConfig) error { |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 128 | slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 129 | if _, err := exec.LookPath("docker"); err != nil { |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 130 | if runtime.GOOS == "darwin" { |
| 131 | return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start") |
| 132 | } else { |
| 133 | return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)") |
| 134 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 135 | } |
| 136 | |
| 137 | if out, err := combinedOutput(ctx, "docker", "ps"); err != nil { |
| 138 | // `docker ps` provides a good error message here that can be |
| 139 | // easily chatgpt'ed by users, so send it to the user as-is: |
| 140 | // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? |
| 141 | return fmt.Errorf("docker ps: %s (%w)", out, err) |
| 142 | } |
| 143 | |
| 144 | _, hostPort, err := net.SplitHostPort(config.LocalAddr) |
| 145 | if err != nil { |
| 146 | return err |
| 147 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 148 | gitRoot, err := findGitRoot(ctx, config.Path) |
| 149 | if err != nil { |
| 150 | return err |
| 151 | } |
| Philip Zeyliger | d6d12d1 | 2025-05-19 19:19:21 -0700 | [diff] [blame] | 152 | err = checkForEmptyGitRepo(ctx, config.Path) |
| 153 | if err != nil { |
| 154 | return err |
| 155 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 156 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 157 | imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 158 | if err != nil { |
| 159 | return err |
| 160 | } |
| 161 | |
| 162 | linuxSketchBin := config.SketchBinaryLinux |
| 163 | if linuxSketchBin == "" { |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 164 | linuxSketchBin, err = buildLinuxSketchBin(ctx) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 165 | if err != nil { |
| 166 | return err |
| 167 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 168 | } |
| 169 | |
| Philip Zeyliger | c72fff5 | 2025-04-29 20:17:54 +0000 | [diff] [blame] | 170 | cntrName := "sketch-" + config.SessionID |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 171 | defer func() { |
| 172 | if config.NoCleanup { |
| 173 | return |
| 174 | } |
| 175 | if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil { |
| 176 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 177 | _ = out |
| 178 | } |
| 179 | if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil { |
| 180 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 181 | _ = out |
| 182 | } |
| 183 | }() |
| 184 | |
| 185 | // errCh receives errors from operations that this function calls in separate goroutines. |
| 186 | errCh := make(chan error) |
| 187 | |
| 188 | // Start the git server |
| 189 | gitSrv, err := newGitServer(gitRoot) |
| 190 | if err != nil { |
| 191 | return fmt.Errorf("failed to start git server: %w", err) |
| 192 | } |
| 193 | defer gitSrv.shutdown(ctx) |
| 194 | |
| 195 | go func() { |
| 196 | errCh <- gitSrv.serve(ctx) |
| 197 | }() |
| 198 | |
| 199 | // Get the current host git commit |
| 200 | var commit string |
| Philip Zeyliger | 1b47aa2 | 2025-04-28 19:25:38 +0000 | [diff] [blame] | 201 | if out, err := combinedOutput(ctx, "git", "rev-parse", config.InitialCommit); err != nil { |
| 202 | return fmt.Errorf("git rev-parse %s: %w", config.InitialCommit, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 203 | } else { |
| 204 | commit = strings.TrimSpace(string(out)) |
| 205 | } |
| 206 | if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil { |
| 207 | return fmt.Errorf("git config http.receivepack true: %s: %w", out, err) |
| 208 | } |
| 209 | |
| 210 | relPath, err := filepath.Rel(gitRoot, config.Path) |
| 211 | if err != nil { |
| 212 | return err |
| 213 | } |
| 214 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 215 | config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort) |
| 216 | config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort) |
| 217 | config.Commit = commit |
| 218 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 219 | // Create the sketch container |
| 220 | if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil { |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 221 | return fmt.Errorf("failed to create docker container: %w", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 222 | } |
| 223 | |
| 224 | // Copy the sketch linux binary into the container |
| 225 | if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil { |
| 226 | return fmt.Errorf("docker cp: %s, %w", out, err) |
| 227 | } |
| Sean McCullough | f5bb3d3 | 2025-04-18 10:47:59 -0700 | [diff] [blame] | 228 | |
| 229 | // Make sure that the webui is built so we can copy the results to the container. |
| 230 | _, err = webui.Build() |
| 231 | if err != nil { |
| 232 | return fmt.Errorf("failed to build webui: %w", err) |
| 233 | } |
| 234 | |
| David Crawshaw | 8bff16a | 2025-04-18 01:16:49 -0700 | [diff] [blame] | 235 | webuiZipPath, err := webui.ZipPath() |
| 236 | if err != nil { |
| 237 | return err |
| 238 | } |
| 239 | if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil { |
| 240 | return fmt.Errorf("docker cp: %s, %w", out, err) |
| 241 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 242 | |
| David Crawshaw | 53786ef | 2025-04-24 12:52:51 -0700 | [diff] [blame] | 243 | fmt.Printf("📦 running in container %s\n", cntrName) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 244 | |
| 245 | // Start the sketch container |
| 246 | if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil { |
| 247 | return fmt.Errorf("docker start: %s, %w", out, err) |
| 248 | } |
| 249 | |
| 250 | // Copies structured logs from the container to the host. |
| 251 | copyLogs := func() { |
| 252 | if config.ContainerLogDest == "" { |
| 253 | return |
| 254 | } |
| 255 | out, err := combinedOutput(ctx, "docker", "logs", cntrName) |
| 256 | if err != nil { |
| 257 | fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err) |
| 258 | return |
| 259 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 260 | prefix := []byte("structured logs:") |
| 261 | for line := range bytes.Lines(out) { |
| 262 | rest, ok := bytes.CutPrefix(line, prefix) |
| 263 | if !ok { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 264 | continue |
| 265 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 266 | logFile := string(bytes.TrimSpace(rest)) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 267 | srcPath := fmt.Sprintf("%s:%s", cntrName, logFile) |
| 268 | logFileName := filepath.Base(logFile) |
| 269 | dstPath := filepath.Join(config.ContainerLogDest, logFileName) |
| 270 | _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath) |
| 271 | if err != nil { |
| 272 | fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err) |
| 273 | } |
| 274 | fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath) |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | // NOTE: we want to see what the internal sketch binary prints |
| 279 | // regardless of the setting of the verbosity flag on the external |
| 280 | // binary, so reading "docker logs", which is the stdout/stderr of |
| 281 | // the internal binary is not conditional on the verbose flag. |
| 282 | appendInternalErr := func(err error) error { |
| 283 | if err == nil { |
| 284 | return nil |
| 285 | } |
| 286 | out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName) |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 287 | if logsErr != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 288 | return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr) |
| 289 | } |
| 290 | out = bytes.TrimSpace(out) |
| 291 | if len(out) > 0 { |
| 292 | return fmt.Errorf("docker logs: %s;\n%w", out, err) |
| 293 | } |
| 294 | return err |
| 295 | } |
| 296 | |
| 297 | // Get the sketch server port from the container |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 298 | localAddr, err := getContainerPort(ctx, cntrName, "80") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 299 | if err != nil { |
| 300 | return appendInternalErr(err) |
| 301 | } |
| 302 | |
| Philip Zeyliger | 0044241 | 2025-05-14 11:03:23 -0700 | [diff] [blame] | 303 | if config.Verbose { |
| 304 | fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr) |
| 305 | } |
| 306 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 307 | localSSHAddr, err := getContainerPort(ctx, cntrName, "22") |
| 308 | if err != nil { |
| 309 | return appendInternalErr(err) |
| 310 | } |
| 311 | sshHost, sshPort, err := net.SplitHostPort(localSSHAddr) |
| 312 | if err != nil { |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 313 | 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] | 314 | } |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 315 | |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 316 | var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 317 | |
| Sean McCullough | 078e85a | 2025-05-08 17:28:34 -0700 | [diff] [blame] | 318 | cst, err := NewSSHTheater(cntrName, sshHost, sshPort) |
| 319 | if err != nil { |
| 320 | return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err)) |
| 321 | } |
| 322 | |
| 323 | sshErr := CheckSSHReachability(cntrName) |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 324 | sshAvailable := false |
| 325 | sshErrMsg := "" |
| 326 | if sshErr != nil { |
| 327 | fmt.Println(sshErr.Error()) |
| 328 | sshErrMsg = sshErr.Error() |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 329 | // continue - ssh config is not required for the rest of sketch to function locally. |
| 330 | } else { |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 331 | sshAvailable = true |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 332 | // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find: |
| 333 | // 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] | 334 | fmt.Printf(`Connect to this container via any of these methods: |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 335 | 🖥️ ssh %s |
| 336 | 🖥️ code --remote ssh-remote+root@%s /app -n |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 337 | 🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 338 | `, cntrName, cntrName, cntrName) |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 339 | sshUserIdentity = cst.userIdentity |
| 340 | sshServerIdentity = cst.serverIdentity |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 341 | |
| 342 | // Get the Container CA public key for mutual auth |
| 343 | if cst.containerCAPublicKey != nil { |
| 344 | containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey) |
| 345 | fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)") |
| 346 | } |
| 347 | |
| 348 | // Get the host certificate for mutual auth |
| 349 | hostCertificate = cst.hostCertificate |
| 350 | |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 351 | defer func() { |
| 352 | if err := cst.Cleanup(); err != nil { |
| 353 | appendInternalErr(err) |
| 354 | } |
| 355 | }() |
| 356 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 357 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 358 | // Tell the sketch container to Init(), which starts the SSH server |
| 359 | // and checks out the right commit. |
| 360 | // TODO: I'm trying to move as much configuration as possible into the command-line |
| 361 | // arguments to avoid splitting them up. "localAddr" is the only difficult one: |
| 362 | // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't |
| 363 | // get the port Docker chose until after the process starts. The SSH config is |
| 364 | // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg") |
| 365 | // 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] | 366 | go func() { |
| 367 | // TODO: Why is this called in a goroutine? I have found that when I pull this out |
| 368 | // of the goroutine and call it inline, then the terminal UI clears itself and all |
| 369 | // the scrollback (which is not good, but also not fatal). I can't see why it does this |
| 370 | // though, since none of the calls in postContainerInitConfig obviously write to stdout |
| 371 | // or stderr. |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 372 | 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] | 373 | slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error())) |
| 374 | errCh <- appendInternalErr(err) |
| 375 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 376 | |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 377 | // 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] | 378 | ps1URL := "http://" + localAddr |
| 379 | if config.SkabandAddr != "" { |
| 380 | ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID) |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 381 | } |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 382 | if config.OpenBrowser { |
| 383 | browser.Open(ps1URL) |
| 384 | } |
| 385 | gitSrv.ps1URL.Store(&ps1URL) |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 386 | }() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 387 | |
| Sean McCullough | 138ec24 | 2025-06-02 22:42:06 +0000 | [diff] [blame^] | 388 | // Start automatic port tunneling if SSH is available |
| 389 | if sshAvailable { |
| 390 | go func() { |
| 391 | containerURL := "http://" + localAddr |
| 392 | tunnelManager := NewTunnelManager(containerURL, cntrName, 10) // Allow up to 10 concurrent tunnels |
| 393 | tunnelManager.Start(ctx) |
| 394 | slog.InfoContext(ctx, "Started automatic port tunnel manager", "container", cntrName) |
| 395 | }() |
| 396 | } |
| 397 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 398 | go func() { |
| 399 | cmd := exec.CommandContext(ctx, "docker", "attach", cntrName) |
| 400 | cmd.Stdin = os.Stdin |
| 401 | cmd.Stdout = os.Stdout |
| 402 | cmd.Stderr = os.Stderr |
| 403 | errCh <- run(ctx, "docker attach", cmd) |
| 404 | }() |
| 405 | |
| 406 | defer copyLogs() |
| 407 | |
| 408 | for { |
| 409 | select { |
| 410 | case <-ctx.Done(): |
| 411 | return ctx.Err() |
| 412 | case err := <-errCh: |
| 413 | if err != nil { |
| 414 | return appendInternalErr(fmt.Errorf("container process: %w", err)) |
| 415 | } |
| 416 | return nil |
| 417 | } |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) { |
| 422 | cmd := exec.CommandContext(ctx, cmdName, args...) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 423 | start := time.Now() |
| 424 | |
| 425 | out, err := cmd.CombinedOutput() |
| 426 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 427 | 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] | 428 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 429 | 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] | 430 | } |
| 431 | return out, err |
| 432 | } |
| 433 | |
| 434 | func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error { |
| 435 | start := time.Now() |
| 436 | err := cmd.Run() |
| 437 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 438 | 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] | 439 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 440 | 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] | 441 | } |
| 442 | return err |
| 443 | } |
| 444 | |
| 445 | type gitServer struct { |
| 446 | gitLn net.Listener |
| 447 | gitPort string |
| 448 | srv *http.Server |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 449 | pass string |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 450 | ps1URL atomic.Pointer[string] |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 451 | } |
| 452 | |
| 453 | func (gs *gitServer) shutdown(ctx context.Context) { |
| 454 | gs.srv.Shutdown(ctx) |
| 455 | gs.gitLn.Close() |
| 456 | } |
| 457 | |
| 458 | // Serve a git remote from the host for the container to fetch from and push to. |
| 459 | func (gs *gitServer) serve(ctx context.Context) error { |
| 460 | slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git")) |
| 461 | return gs.srv.Serve(gs.gitLn) |
| 462 | } |
| 463 | |
| 464 | func newGitServer(gitRoot string) (*gitServer, error) { |
| Josh Bleecher Snyder | 9f6a998 | 2025-04-22 17:34:15 -0700 | [diff] [blame] | 465 | ret := &gitServer{ |
| 466 | pass: rand.Text(), |
| 467 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 468 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 469 | gitLn, err := net.Listen("tcp4", ":0") |
| 470 | if err != nil { |
| 471 | return nil, fmt.Errorf("git listen: %w", err) |
| 472 | } |
| 473 | ret.gitLn = gitLn |
| 474 | |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 475 | browserC := make(chan bool, 1) // channel of browser open requests |
| 476 | |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 477 | go func() { |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 478 | for range browserC { |
| 479 | browser.Open(*ret.ps1URL.Load()) |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 480 | } |
| 481 | }() |
| 482 | |
| 483 | 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] | 484 | ret.srv = &srv |
| 485 | |
| 486 | _, gitPort, err := net.SplitHostPort(gitLn.Addr().String()) |
| 487 | if err != nil { |
| 488 | return nil, fmt.Errorf("git port: %w", err) |
| 489 | } |
| 490 | ret.gitPort = gitPort |
| 491 | return ret, nil |
| 492 | } |
| 493 | |
| 494 | 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] | 495 | cmdArgs := []string{ |
| 496 | "create", |
| David Crawshaw | 66cf74e | 2025-05-05 08:48:39 -0700 | [diff] [blame] | 497 | "-i", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 498 | "--name", cntrName, |
| 499 | "-p", hostPort + ":80", // forward container port 80 to a host port |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 500 | "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 501 | } |
| Philip Zeyliger | 3d2eff0 | 2025-05-27 09:30:31 -0700 | [diff] [blame] | 502 | if !(config.OneShot || !config.TermUI) { |
| David Crawshaw | 66cf74e | 2025-05-05 08:48:39 -0700 | [diff] [blame] | 503 | cmdArgs = append(cmdArgs, "-t") |
| 504 | } |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 505 | |
| 506 | for _, envVar := range getEnvForwardingFromGitConfig(ctx) { |
| 507 | cmdArgs = append(cmdArgs, "-e", envVar) |
| 508 | } |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 509 | if config.ModelURL != "" { |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 510 | cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 511 | } |
| 512 | if config.SketchPubKey != "" { |
| 513 | cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey) |
| 514 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 515 | if config.SSHPort > 0 { |
| 516 | cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port |
| 517 | } else { |
| Philip Zeyliger | 87d29ef | 2025-05-16 20:25:28 -0700 | [diff] [blame] | 518 | 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] | 519 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 520 | if relPath != "." { |
| 521 | cmdArgs = append(cmdArgs, "-w", "/app/"+relPath) |
| 522 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 523 | // colima does this by default, but Linux docker seems to need this set explicitly |
| 524 | cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway") |
| Josh Bleecher Snyder | ac761c9 | 2025-05-16 18:58:45 +0000 | [diff] [blame] | 525 | |
| 526 | // Add volume mounts if specified |
| 527 | for _, mount := range config.Mounts { |
| 528 | if mount != "" { |
| 529 | cmdArgs = append(cmdArgs, "-v", mount) |
| 530 | } |
| 531 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 532 | cmdArgs = append( |
| 533 | cmdArgs, |
| 534 | imgName, |
| 535 | "/bin/sketch", |
| 536 | "-unsafe", |
| 537 | "-addr=:80", |
| 538 | "-session-id="+config.SessionID, |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 539 | "-git-username="+config.GitUsername, |
| 540 | "-git-email="+config.GitEmail, |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 541 | "-outside-hostname="+config.OutsideHostname, |
| 542 | "-outside-os="+config.OutsideOS, |
| 543 | "-outside-working-dir="+config.OutsideWorkingDir, |
| Josh Bleecher Snyder | 33032d3 | 2025-05-30 16:28:21 +0000 | [diff] [blame] | 544 | fmt.Sprintf("-max-dollars=%f", config.MaxDollars), |
| 545 | fmt.Sprintf("-max-iterations=%d", config.MaxIterations), |
| 546 | fmt.Sprintf("-max-wall-time=%s", config.MaxWallTime.String()), |
| Josh Bleecher Snyder | 3cae7d9 | 2025-04-30 09:54:29 -0700 | [diff] [blame] | 547 | "-open=false", |
| Philip Zeyliger | 613c0f5 | 2025-05-15 16:36:22 -0700 | [diff] [blame] | 548 | "-termui="+fmt.Sprintf("%t", config.TermUI), |
| Philip Zeyliger | cabfa55 | 2025-05-19 16:14:28 -0700 | [diff] [blame] | 549 | "-verbose="+fmt.Sprintf("%t", config.Verbose), |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 550 | "-x="+config.ExperimentFlag, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 551 | ) |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 552 | if config.Model != "" { |
| 553 | cmdArgs = append(cmdArgs, "-model="+config.Model) |
| 554 | } |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 555 | if config.GitRemoteUrl != "" { |
| 556 | cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl) |
| 557 | if config.Commit == "" { |
| 558 | panic("Commit should have been set when GitRemoteUrl was set") |
| 559 | } |
| 560 | cmdArgs = append(cmdArgs, "-commit="+config.Commit) |
| 561 | } |
| 562 | if config.OutsideHTTP != "" { |
| 563 | cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP) |
| 564 | } |
| Josh Bleecher Snyder | e3c2f22 | 2025-05-15 20:54:52 +0000 | [diff] [blame] | 565 | cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr) |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 566 | if config.Prompt != "" { |
| 567 | cmdArgs = append(cmdArgs, "-prompt", config.Prompt) |
| 568 | } |
| 569 | if config.OneShot { |
| 570 | cmdArgs = append(cmdArgs, "-one-shot") |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 571 | } |
| Josh Bleecher Snyder | e3c2f22 | 2025-05-15 20:54:52 +0000 | [diff] [blame] | 572 | if config.ModelURL == "" { |
| 573 | // Forward ANTHROPIC_API_KEY for direct use. |
| 574 | // TODO: have outtie run an http proxy? |
| 575 | // TODO: select and forward the relevant API key based on the model |
| 576 | cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY")) |
| 577 | } |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 578 | |
| 579 | // Add additional docker arguments if provided |
| 580 | if config.DockerArgs != "" { |
| 581 | // Parse space-separated docker arguments with support for quotes and escaping |
| 582 | args := parseDockerArgs(config.DockerArgs) |
| 583 | // Insert arguments after "create" but before other arguments |
| 584 | for i := len(args) - 1; i >= 0; i-- { |
| 585 | cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...) |
| 586 | } |
| 587 | } |
| 588 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 589 | if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil { |
| 590 | return fmt.Errorf("docker create: %s, %w", out, err) |
| 591 | } |
| 592 | return nil |
| 593 | } |
| 594 | |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 595 | func buildLinuxSketchBin(ctx context.Context) (string, error) { |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 596 | // Detect if race detector is enabled and use a different cache path |
| 597 | raceEnabled := RaceEnabled() |
| 598 | cacheSuffix := "" |
| 599 | if raceEnabled { |
| 600 | cacheSuffix = "-race" |
| 601 | } |
| 602 | |
| 603 | homeDir, err := os.UserHomeDir() |
| 604 | if err != nil { |
| 605 | return "", err |
| 606 | } |
| 607 | |
| 608 | linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix) |
| 609 | if err := os.MkdirAll(linuxGopath, 0o777); err != nil { |
| 610 | return "", err |
| 611 | } |
| 612 | |
| 613 | // When race detector is enabled, use Docker to build the Linux binary |
| 614 | if raceEnabled { |
| 615 | return buildLinuxSketchBinWithDocker(ctx, linuxGopath) |
| 616 | } |
| 617 | |
| 618 | // Standard non-race build using cross-compilation |
| Pokey Rule | a9a786b | 2025-05-12 10:52:34 +0100 | [diff] [blame] | 619 | // Change to directory containing dockerimg.go for module detection |
| 620 | _, codeFile, _, _ := runtime.Caller(0) |
| 621 | codeDir := filepath.Dir(codeFile) |
| 622 | if currentDir, err := os.Getwd(); err != nil { |
| 623 | slog.WarnContext(ctx, "could not get current directory", "err", err) |
| 624 | } else { |
| 625 | if err := os.Chdir(codeDir); err != nil { |
| 626 | slog.WarnContext(ctx, "could not change to code directory for module check", "err", err) |
| 627 | } else { |
| 628 | defer func() { |
| 629 | _ = os.Chdir(currentDir) |
| 630 | }() |
| 631 | } |
| 632 | } |
| 633 | |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 634 | verToInstall := "@latest" |
| 635 | if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil { |
| 636 | return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err) |
| 637 | } else { |
| 638 | if strings.TrimSpace(string(out)) == "sketch.dev" { |
| David Crawshaw | 094e4d2 | 2025-04-24 11:35:14 -0700 | [diff] [blame] | 639 | slog.DebugContext(ctx, "built linux agent from currently checked out module") |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 640 | verToInstall = "" |
| 641 | } |
| 642 | } |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 643 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 644 | start := time.Now() |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 645 | args := []string{"install"} |
| 646 | args = append(args, "sketch.dev/cmd/sketch"+verToInstall) |
| 647 | |
| 648 | cmd := exec.CommandContext(ctx, "go", args...) |
| David Crawshaw | b9eaef5 | 2025-04-17 15:23:18 -0700 | [diff] [blame] | 649 | cmd.Env = append( |
| 650 | os.Environ(), |
| 651 | "GOOS=linux", |
| 652 | "CGO_ENABLED=0", |
| 653 | "GOTOOLCHAIN=auto", |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 654 | "GOPATH="+linuxGopath, |
| Josh Bleecher Snyder | fae1757 | 2025-04-21 11:48:05 -0700 | [diff] [blame] | 655 | "GOBIN=", |
| David Crawshaw | b9eaef5 | 2025-04-17 15:23:18 -0700 | [diff] [blame] | 656 | ) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 657 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 658 | out, err := cmd.CombinedOutput() |
| 659 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 660 | slog.ErrorContext(ctx, "go", 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] | 661 | return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err) |
| 662 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 663 | slog.DebugContext(ctx, "go", 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] | 664 | } |
| 665 | |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 666 | if runtime.GOOS != "linux" { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 667 | return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 668 | } |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 669 | // If we are already on Linux, there's no extra platform name in the path |
| 670 | return filepath.Join(linuxGopath, "bin", "sketch"), nil |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 671 | } |
| 672 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 673 | func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 674 | localAddr := "" |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 675 | if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 676 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 677 | } else { |
| 678 | v4, _, found := strings.Cut(string(out), "\n") |
| 679 | if !found { |
| 680 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 681 | } |
| 682 | localAddr = v4 |
| 683 | if strings.HasPrefix(localAddr, "0.0.0.0") { |
| 684 | localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0") |
| 685 | } |
| 686 | } |
| 687 | return localAddr, nil |
| 688 | } |
| 689 | |
| 690 | // Contact the container and configure it. |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 691 | 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] | 692 | localURL := "http://" + localAddr |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 693 | |
| 694 | initMsg, err := json.Marshal( |
| 695 | server.InitRequest{ |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 696 | HostAddr: localAddr, |
| 697 | SSHAuthorizedKeys: sshAuthorizedKeys, |
| 698 | SSHServerIdentity: sshServerIdentity, |
| 699 | SSHContainerCAKey: sshContainerCAKey, |
| 700 | SSHHostCertificate: sshHostCertificate, |
| 701 | SSHAvailable: sshAvailable, |
| 702 | SSHError: sshError, |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 703 | }) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 704 | if err != nil { |
| 705 | return fmt.Errorf("init msg: %w", err) |
| 706 | } |
| 707 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 708 | // Note: this /init POST is handled in loop/server/loophttp.go: |
| 709 | initMsgByteReader := bytes.NewReader(initMsg) |
| 710 | req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader) |
| 711 | if err != nil { |
| 712 | return err |
| 713 | } |
| 714 | |
| 715 | var res *http.Response |
| 716 | for i := 0; ; i++ { |
| 717 | time.Sleep(100 * time.Millisecond) |
| 718 | // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes. |
| 719 | initMsgByteReader.Reset(initMsg) |
| 720 | res, err = http.DefaultClient.Do(req) |
| 721 | if err != nil { |
| David Crawshaw | 99231ba | 2025-05-03 10:48:26 -0700 | [diff] [blame] | 722 | if i < 100 { |
| 723 | if i%10 == 0 { |
| 724 | slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error())) |
| 725 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 726 | continue |
| 727 | } |
| 728 | return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err) |
| 729 | } |
| 730 | break |
| 731 | } |
| 732 | resBytes, _ := io.ReadAll(res.Body) |
| 733 | if res.StatusCode != http.StatusOK { |
| 734 | return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes) |
| 735 | } |
| 736 | return nil |
| 737 | } |
| 738 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 739 | func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 740 | h := sha256.Sum256([]byte(gitRoot)) |
| 741 | imgName = "sketch-" + hex.EncodeToString(h[:6]) |
| 742 | |
| 743 | var curImgInitFilesHash string |
| 744 | if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil { |
| 745 | if strings.Contains(string(out), "No such object") { |
| 746 | // Image does not exist, continue and build it. |
| 747 | curImgInitFilesHash = "" |
| 748 | } else { |
| 749 | return "", fmt.Errorf("docker inspect failed: %s, %v", out, err) |
| 750 | } |
| 751 | } else { |
| 752 | m := map[string]string{} |
| 753 | if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil { |
| 754 | return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err) |
| 755 | } |
| 756 | curImgInitFilesHash = m["sketch_context"] |
| 757 | } |
| 758 | |
| 759 | candidates, err := findRepoDockerfiles(cwd, gitRoot) |
| 760 | if err != nil { |
| 761 | return "", fmt.Errorf("find dockerfile: %w", err) |
| 762 | } |
| 763 | |
| 764 | var initFiles map[string]string |
| 765 | var dockerfilePath string |
| David Crawshaw | ff2df6a | 2025-05-12 14:45:29 -0700 | [diff] [blame] | 766 | var generatedDockerfile string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 767 | |
| 768 | // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool. |
| 769 | if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" { |
| 770 | dockerfilePath = candidates[0] |
| 771 | contents, err := os.ReadFile(dockerfilePath) |
| 772 | if err != nil { |
| 773 | return "", err |
| 774 | } |
| 775 | fmt.Printf("using %s as dev env\n", candidates[0]) |
| 776 | if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 777 | return imgName, nil |
| 778 | } |
| 779 | } else { |
| 780 | initFiles, err = readInitFiles(os.DirFS(gitRoot)) |
| 781 | if err != nil { |
| 782 | return "", err |
| 783 | } |
| 784 | subPathWorkingDir, err := filepath.Rel(gitRoot, cwd) |
| 785 | if err != nil { |
| 786 | return "", err |
| 787 | } |
| 788 | initFileHash := hashInitFiles(initFiles) |
| 789 | if curImgInitFilesHash == initFileHash && !forceRebuild { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 790 | return imgName, nil |
| 791 | } |
| 792 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 793 | if model == "gemini" { |
| 794 | if strings.HasSuffix(modelURL, "/gemmsgs") { |
| 795 | // Horrible hack! Switch back to anthropic for container building. |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 796 | // We can do this because we are talking to skaband and know the address. |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 797 | modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1) |
| 798 | } else { |
| 799 | return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini") |
| 800 | } |
| 801 | } |
| 802 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 803 | start := time.Now() |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 804 | srv := &ant.Service{ |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 805 | URL: modelURL, |
| 806 | APIKey: modelAPIKey, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 807 | HTTPC: http.DefaultClient, |
| 808 | } |
| Pokey Rule | c31e296 | 2025-05-13 10:53:33 +0000 | [diff] [blame] | 809 | generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 810 | if err != nil { |
| 811 | return "", fmt.Errorf("create dockerfile: %w", err) |
| 812 | } |
| Josh Bleecher Snyder | 7c58b02 | 2025-05-14 17:30:39 +0000 | [diff] [blame] | 813 | // Create a unique temporary directory for the Dockerfile |
| 814 | tmpDir, err := os.MkdirTemp("", "sketch-docker-*") |
| 815 | if err != nil { |
| 816 | return "", fmt.Errorf("failed to create temporary directory: %w", err) |
| 817 | } |
| 818 | dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile) |
| David Crawshaw | ff2df6a | 2025-05-12 14:45:29 -0700 | [diff] [blame] | 819 | if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 820 | return "", err |
| 821 | } |
| Josh Bleecher Snyder | 7c58b02 | 2025-05-14 17:30:39 +0000 | [diff] [blame] | 822 | // Remove the temporary directory and all contents when done |
| 823 | defer os.RemoveAll(tmpDir) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 824 | |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 825 | if verbose { |
| David Crawshaw | ff2df6a | 2025-05-12 14:45:29 -0700 | [diff] [blame] | 826 | fmt.Fprintf(os.Stderr, "generated Dockerfile in %s:\n\t%s\n\n", time.Since(start).Round(time.Millisecond), strings.Replace(generatedDockerfile, "\n", "\n\t", -1)) |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 827 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 828 | } |
| 829 | |
| 830 | var gitUserEmail, gitUserName string |
| 831 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil { |
| 832 | return "", fmt.Errorf("git config: %s: %v", out, err) |
| 833 | } else { |
| 834 | gitUserEmail = strings.TrimSpace(string(out)) |
| 835 | } |
| 836 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil { |
| 837 | return "", fmt.Errorf("git config: %s: %v", out, err) |
| 838 | } else { |
| 839 | gitUserName = strings.TrimSpace(string(out)) |
| 840 | } |
| 841 | |
| 842 | start := time.Now() |
| 843 | cmd := exec.CommandContext(ctx, |
| 844 | "docker", "build", |
| 845 | "-t", imgName, |
| 846 | "-f", dockerfilePath, |
| 847 | "--build-arg", "GIT_USER_EMAIL="+gitUserEmail, |
| 848 | "--build-arg", "GIT_USER_NAME="+gitUserName, |
| David Crawshaw | 31f1524 | 2025-05-06 16:03:49 -0700 | [diff] [blame] | 849 | ".", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 850 | ) |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 851 | cmd.Dir = gitRoot |
| David Crawshaw | 31f1524 | 2025-05-06 16:03:49 -0700 | [diff] [blame] | 852 | // We print the docker build output whether or not the user |
| 853 | // has selected --verbose. Building an image takes a while |
| 854 | // and this gives good context. |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 855 | cmd.Stdout = os.Stdout |
| 856 | cmd.Stderr = os.Stderr |
| 857 | fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 858 | |
| 859 | err = run(ctx, "docker build", cmd) |
| 860 | if err != nil { |
| David Crawshaw | ff2df6a | 2025-05-12 14:45:29 -0700 | [diff] [blame] | 861 | var msg string |
| 862 | if generatedDockerfile != "" { |
| 863 | if !verbose { |
| 864 | fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1)) |
| 865 | } |
| 866 | msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.") |
| 867 | } |
| 868 | return "", fmt.Errorf("docker build failed: %v%s", err, msg) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 869 | } |
| 870 | fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond)) |
| 871 | return imgName, nil |
| 872 | } |
| 873 | |
| 874 | func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) { |
| 875 | files, err := findDirDockerfiles(cwd) |
| 876 | if err != nil { |
| 877 | return nil, err |
| 878 | } |
| 879 | if len(files) > 0 { |
| 880 | return files, nil |
| 881 | } |
| 882 | |
| 883 | path := cwd |
| 884 | for path != gitRoot { |
| 885 | path = filepath.Dir(path) |
| 886 | files, err := findDirDockerfiles(path) |
| 887 | if err != nil { |
| 888 | return nil, err |
| 889 | } |
| 890 | if len(files) > 0 { |
| 891 | return files, nil |
| 892 | } |
| 893 | } |
| 894 | return files, nil |
| 895 | } |
| 896 | |
| 897 | // findDirDockerfiles finds all "Dockerfile*" files in a directory. |
| 898 | func findDirDockerfiles(root string) (res []string, err error) { |
| 899 | err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error { |
| 900 | if err != nil { |
| 901 | return err |
| 902 | } |
| 903 | if info.IsDir() && root != path { |
| 904 | return filepath.SkipDir |
| 905 | } |
| 906 | name := strings.ToLower(info.Name()) |
| 907 | if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") { |
| 908 | res = append(res, path) |
| 909 | } |
| 910 | return nil |
| 911 | }) |
| 912 | if err != nil { |
| 913 | return nil, err |
| 914 | } |
| 915 | return res, nil |
| 916 | } |
| 917 | |
| Philip Zeyliger | d6d12d1 | 2025-05-19 19:19:21 -0700 | [diff] [blame] | 918 | func checkForEmptyGitRepo(ctx context.Context, path string) error { |
| 919 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD") |
| 920 | cmd.Dir = path |
| 921 | _, err := cmd.CombinedOutput() |
| 922 | if err != nil { |
| 923 | return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s", |
| 924 | "git commit --allow-empty -m 'initial commit'") |
| 925 | } |
| 926 | return nil |
| 927 | } |
| 928 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 929 | func findGitRoot(ctx context.Context, path string) (string, error) { |
| 930 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir") |
| 931 | cmd.Dir = path |
| 932 | out, err := cmd.CombinedOutput() |
| 933 | if err != nil { |
| 934 | if strings.Contains(string(out), "not a git repository") { |
| 935 | return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo. |
| 936 | Consider one of the following options: |
| 937 | - cd to a different dir that is already part of a git repo first, or |
| 938 | - to create a new git repo from this directory (%s), run this command: |
| 939 | |
| 940 | git init . && git commit --allow-empty -m "initial commit" |
| 941 | |
| 942 | and try running sketch again. |
| 943 | `, path, path) |
| 944 | } |
| 945 | return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err) |
| 946 | } |
| 947 | gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path |
| 948 | absGitDir := filepath.Join(path, gitDir) |
| 949 | return filepath.Dir(absGitDir), err |
| 950 | } |
| 951 | |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 952 | // getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker |
| 953 | // from git config using the sketch.envfwd multi-valued key. |
| 954 | func getEnvForwardingFromGitConfig(ctx context.Context) []string { |
| 955 | outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput() |
| 956 | out := string(outb) |
| 957 | if err != nil { |
| 958 | if strings.Contains(out, "key does not exist") { |
| 959 | return nil |
| 960 | } |
| 961 | slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out) |
| 962 | return nil |
| 963 | } |
| 964 | |
| 965 | var envVars []string |
| 966 | for envVar := range strings.Lines(out) { |
| 967 | envVar = strings.TrimSpace(envVar) |
| 968 | if envVar == "" { |
| 969 | continue |
| 970 | } |
| 971 | envVars = append(envVars, envVar+"="+os.Getenv(envVar)) |
| 972 | } |
| 973 | return envVars |
| 974 | } |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 975 | |
| 976 | // parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings. |
| 977 | // It handles quoted arguments and escaped characters. |
| 978 | // |
| 979 | // Examples: |
| 980 | // |
| 981 | // --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"] |
| 982 | // --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"] |
| 983 | // --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""] |
| 984 | func parseDockerArgs(args string) []string { |
| 985 | if args = strings.TrimSpace(args); args == "" { |
| 986 | return []string{} |
| 987 | } |
| 988 | |
| 989 | var result []string |
| 990 | var current strings.Builder |
| 991 | inQuotes := false |
| 992 | escapeNext := false |
| 993 | quoteChar := rune(0) |
| 994 | |
| 995 | for _, char := range args { |
| 996 | if escapeNext { |
| 997 | current.WriteRune(char) |
| 998 | escapeNext = false |
| 999 | continue |
| 1000 | } |
| 1001 | |
| 1002 | if char == '\\' { |
| 1003 | escapeNext = true |
| 1004 | continue |
| 1005 | } |
| 1006 | |
| 1007 | if char == '"' || char == '\'' { |
| 1008 | if !inQuotes { |
| 1009 | inQuotes = true |
| 1010 | quoteChar = char |
| 1011 | continue |
| 1012 | } else if char == quoteChar { |
| 1013 | inQuotes = false |
| 1014 | quoteChar = rune(0) |
| 1015 | continue |
| 1016 | } |
| 1017 | // Non-matching quote character inside quotes |
| 1018 | current.WriteRune(char) |
| 1019 | continue |
| 1020 | } |
| 1021 | |
| 1022 | // Space outside of quotes is an argument separator |
| 1023 | if char == ' ' && !inQuotes { |
| 1024 | if current.Len() > 0 { |
| 1025 | result = append(result, current.String()) |
| 1026 | current.Reset() |
| 1027 | } |
| 1028 | continue |
| 1029 | } |
| 1030 | |
| 1031 | current.WriteRune(char) |
| 1032 | } |
| 1033 | |
| 1034 | // Add the last argument if there is one |
| 1035 | if current.Len() > 0 { |
| 1036 | result = append(result, current.String()) |
| 1037 | } |
| 1038 | |
| 1039 | return result |
| 1040 | } |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1041 | |
| 1042 | // buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled. |
| 1043 | // This avoids cross-compilation issues with CGO which is required for the race detector. |
| Josh Bleecher Snyder | 3e6a4c4 | 2025-05-23 17:29:57 +0000 | [diff] [blame] | 1044 | // Mounts host Go module cache and build cache for faster subsequent builds. |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1045 | func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) { |
| 1046 | // Find the git repo root |
| 1047 | currentDir, err := os.Getwd() |
| 1048 | if err != nil { |
| 1049 | return "", fmt.Errorf("could not get current directory: %w", err) |
| 1050 | } |
| 1051 | |
| 1052 | gitRoot, err := findGitRoot(ctx, currentDir) |
| 1053 | if err != nil { |
| 1054 | return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err) |
| 1055 | } |
| 1056 | |
| Josh Bleecher Snyder | 3e6a4c4 | 2025-05-23 17:29:57 +0000 | [diff] [blame] | 1057 | // Get host Go cache directories to mount for faster builds |
| 1058 | goCacheDir, err := getHostGoCacheDir(ctx) |
| 1059 | if err != nil { |
| 1060 | return "", fmt.Errorf("failed to get host GOCACHE: %w", err) |
| 1061 | } |
| 1062 | goModCacheDir, err := getHostGoModCacheDir(ctx) |
| 1063 | if err != nil { |
| 1064 | return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err) |
| 1065 | } |
| 1066 | |
| 1067 | slog.DebugContext(ctx, "building Linux sketch binary with race detector using Docker", "git_root", gitRoot, "gocache", goCacheDir, "gomodcache", goModCacheDir) |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1068 | |
| 1069 | // Use the published Docker image tag |
| 1070 | imageTag := dockerfileBaseHash() |
| 1071 | imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag) |
| 1072 | |
| 1073 | // Create destination directory for the binary |
| 1074 | destPath := filepath.Join(linuxGopath, "bin") |
| 1075 | if err := os.MkdirAll(destPath, 0o777); err != nil { |
| 1076 | return "", fmt.Errorf("failed to create destination directory: %w", err) |
| 1077 | } |
| 1078 | destFile := filepath.Join(destPath, "sketch") |
| 1079 | |
| 1080 | // Create a unique container name |
| 1081 | containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano()) |
| 1082 | |
| Josh Bleecher Snyder | 3e6a4c4 | 2025-05-23 17:29:57 +0000 | [diff] [blame] | 1083 | // Run a container with the repo mounted and Go caches for faster builds |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1084 | start := time.Now() |
| 1085 | slog.DebugContext(ctx, "running Docker container to build sketch with race detector") |
| 1086 | |
| 1087 | // Use explicit output path for clarity |
| 1088 | runArgs := []string{ |
| 1089 | "run", |
| 1090 | "--name", containerID, |
| 1091 | "-v", gitRoot + ":/app", |
| Josh Bleecher Snyder | 3e6a4c4 | 2025-05-23 17:29:57 +0000 | [diff] [blame] | 1092 | "-v", goCacheDir + ":/root/.cache/go-build", |
| 1093 | "-v", goModCacheDir + ":/go/pkg/mod", |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1094 | "-w", "/app", |
| 1095 | imgName, |
| Josh Bleecher Snyder | f4f929a | 2025-05-23 17:19:26 +0000 | [diff] [blame] | 1096 | "sh", "-c", "cd /app && mkdir -p /tmp/sketch-out && go build -buildvcs=false -race -o /tmp/sketch-out/sketch sketch.dev/cmd/sketch", |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1097 | } |
| 1098 | |
| 1099 | out, err := combinedOutput(ctx, "docker", runArgs...) |
| 1100 | if err != nil { |
| 1101 | // Print the output to help with debugging |
| 1102 | slog.ErrorContext(ctx, "docker run for race build failed", |
| 1103 | slog.String("output", string(out)), |
| 1104 | slog.String("error", err.Error())) |
| 1105 | return "", fmt.Errorf("docker run failed: %s: %w", out, err) |
| 1106 | } |
| 1107 | |
| 1108 | slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start)) |
| 1109 | |
| 1110 | // Copy the binary from the container using the explicit path |
| 1111 | out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile) |
| 1112 | if err != nil { |
| 1113 | return "", fmt.Errorf("docker cp failed: %s: %w", out, err) |
| 1114 | } |
| 1115 | |
| 1116 | // Clean up the container |
| 1117 | if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil { |
| 1118 | slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out)) |
| 1119 | } |
| 1120 | |
| 1121 | // Make the binary executable |
| 1122 | if err := os.Chmod(destFile, 0o755); err != nil { |
| 1123 | return "", fmt.Errorf("failed to make binary executable: %w", err) |
| 1124 | } |
| 1125 | |
| 1126 | return destFile, nil |
| 1127 | } |
| Josh Bleecher Snyder | 3e6a4c4 | 2025-05-23 17:29:57 +0000 | [diff] [blame] | 1128 | |
| 1129 | // getHostGoCacheDir returns the host's GOCACHE directory |
| 1130 | func getHostGoCacheDir(ctx context.Context) (string, error) { |
| 1131 | out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput() |
| 1132 | if err != nil { |
| 1133 | return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err) |
| 1134 | } |
| 1135 | return strings.TrimSpace(string(out)), nil |
| 1136 | } |
| 1137 | |
| 1138 | // getHostGoModCacheDir returns the host's GOMODCACHE directory |
| 1139 | func getHostGoModCacheDir(ctx context.Context) (string, error) { |
| 1140 | out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput() |
| 1141 | if err != nil { |
| 1142 | return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err) |
| 1143 | } |
| 1144 | return strings.TrimSpace(string(out)), nil |
| 1145 | } |