| 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" |
| 7 | "crypto/sha256" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "log/slog" |
| 13 | "net" |
| 14 | "net/http" |
| 15 | "os" |
| 16 | "os/exec" |
| 17 | "path/filepath" |
| 18 | "runtime" |
| 19 | "strings" |
| 20 | "time" |
| 21 | |
| David Crawshaw | 8bff16a | 2025-04-18 01:16:49 -0700 | [diff] [blame] | 22 | "sketch.dev/loop/webui" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 23 | "sketch.dev/skribe" |
| 24 | ) |
| 25 | |
| 26 | // ContainerConfig holds all configuration for launching a container |
| 27 | type ContainerConfig struct { |
| 28 | // SessionID is the unique identifier for this session |
| 29 | SessionID string |
| 30 | |
| 31 | // LocalAddr is the initial address to use (though it may be overwritten later) |
| 32 | LocalAddr string |
| 33 | |
| 34 | // SkabandAddr is the address of the skaband service if available |
| 35 | SkabandAddr string |
| 36 | |
| 37 | // AntURL is the URL of the LLM service. |
| 38 | AntURL string |
| 39 | |
| 40 | // AntAPIKey is the API key for LLM service. |
| 41 | AntAPIKey string |
| 42 | |
| 43 | // Path is the local filesystem path to use |
| 44 | Path string |
| 45 | |
| 46 | // GitUsername is the username to use for git operations |
| 47 | GitUsername string |
| 48 | |
| 49 | // GitEmail is the email to use for git operations |
| 50 | GitEmail string |
| 51 | |
| 52 | // OpenBrowser determines whether to open a browser automatically |
| 53 | OpenBrowser bool |
| 54 | |
| 55 | // NoCleanup prevents container cleanup when set to true |
| 56 | NoCleanup bool |
| 57 | |
| 58 | // ForceRebuild forces rebuilding of the Docker image even if it exists |
| 59 | ForceRebuild bool |
| 60 | |
| 61 | // Host directory to copy container logs into, if not set to "" |
| 62 | ContainerLogDest string |
| 63 | |
| 64 | // Path to pre-built linux sketch binary, or build a new one if set to "" |
| 65 | SketchBinaryLinux string |
| 66 | |
| 67 | // Sketch client public key. |
| 68 | SketchPubKey string |
| 69 | } |
| 70 | |
| 71 | // LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it. |
| 72 | // It writes status to stdout. |
| 73 | func LaunchContainer(ctx context.Context, stdout, stderr io.Writer, config ContainerConfig) error { |
| 74 | if _, err := exec.LookPath("docker"); err != nil { |
| 75 | return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start") |
| 76 | } |
| 77 | |
| 78 | if out, err := combinedOutput(ctx, "docker", "ps"); err != nil { |
| 79 | // `docker ps` provides a good error message here that can be |
| 80 | // easily chatgpt'ed by users, so send it to the user as-is: |
| 81 | // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? |
| 82 | return fmt.Errorf("docker ps: %s (%w)", out, err) |
| 83 | } |
| 84 | |
| 85 | _, hostPort, err := net.SplitHostPort(config.LocalAddr) |
| 86 | if err != nil { |
| 87 | return err |
| 88 | } |
| 89 | |
| 90 | gitRoot, err := findGitRoot(ctx, config.Path) |
| 91 | if err != nil { |
| 92 | return err |
| 93 | } |
| 94 | |
| 95 | imgName, err := findOrBuildDockerImage(ctx, stdout, stderr, config.Path, gitRoot, config.AntURL, config.AntAPIKey, config.ForceRebuild) |
| 96 | if err != nil { |
| 97 | return err |
| 98 | } |
| 99 | |
| 100 | linuxSketchBin := config.SketchBinaryLinux |
| 101 | if linuxSketchBin == "" { |
| 102 | linuxSketchBin, err = buildLinuxSketchBin(ctx, config.Path) |
| 103 | if err != nil { |
| 104 | return err |
| 105 | } |
| 106 | defer os.Remove(linuxSketchBin) |
| 107 | } |
| 108 | |
| 109 | cntrName := imgName + "-" + config.SessionID |
| 110 | defer func() { |
| 111 | if config.NoCleanup { |
| 112 | return |
| 113 | } |
| 114 | if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil { |
| 115 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 116 | _ = out |
| 117 | } |
| 118 | if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil { |
| 119 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 120 | _ = out |
| 121 | } |
| 122 | }() |
| 123 | |
| 124 | // errCh receives errors from operations that this function calls in separate goroutines. |
| 125 | errCh := make(chan error) |
| 126 | |
| 127 | // Start the git server |
| 128 | gitSrv, err := newGitServer(gitRoot) |
| 129 | if err != nil { |
| 130 | return fmt.Errorf("failed to start git server: %w", err) |
| 131 | } |
| 132 | defer gitSrv.shutdown(ctx) |
| 133 | |
| 134 | go func() { |
| 135 | errCh <- gitSrv.serve(ctx) |
| 136 | }() |
| 137 | |
| 138 | // Get the current host git commit |
| 139 | var commit string |
| 140 | if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil { |
| 141 | return fmt.Errorf("git rev-parse HEAD: %w", err) |
| 142 | } else { |
| 143 | commit = strings.TrimSpace(string(out)) |
| 144 | } |
| 145 | if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil { |
| 146 | return fmt.Errorf("git config http.receivepack true: %s: %w", out, err) |
| 147 | } |
| 148 | |
| 149 | relPath, err := filepath.Rel(gitRoot, config.Path) |
| 150 | if err != nil { |
| 151 | return err |
| 152 | } |
| 153 | |
| 154 | // Create the sketch container |
| 155 | if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil { |
| 156 | return err |
| 157 | } |
| 158 | |
| 159 | // Copy the sketch linux binary into the container |
| 160 | if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil { |
| 161 | return fmt.Errorf("docker cp: %s, %w", out, err) |
| 162 | } |
| Sean McCullough | f5bb3d3 | 2025-04-18 10:47:59 -0700 | [diff] [blame] | 163 | |
| 164 | // Make sure that the webui is built so we can copy the results to the container. |
| 165 | _, err = webui.Build() |
| 166 | if err != nil { |
| 167 | return fmt.Errorf("failed to build webui: %w", err) |
| 168 | } |
| 169 | |
| David Crawshaw | 8bff16a | 2025-04-18 01:16:49 -0700 | [diff] [blame] | 170 | webuiZipPath, err := webui.ZipPath() |
| 171 | if err != nil { |
| 172 | return err |
| 173 | } |
| 174 | if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil { |
| 175 | return fmt.Errorf("docker cp: %s, %w", out, err) |
| 176 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 177 | |
| 178 | fmt.Printf("starting container %s\ncommits made by the agent will be pushed to \033[1msketch/*\033[0m\n", cntrName) |
| 179 | |
| 180 | // Start the sketch container |
| 181 | if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil { |
| 182 | return fmt.Errorf("docker start: %s, %w", out, err) |
| 183 | } |
| 184 | |
| 185 | // Copies structured logs from the container to the host. |
| 186 | copyLogs := func() { |
| 187 | if config.ContainerLogDest == "" { |
| 188 | return |
| 189 | } |
| 190 | out, err := combinedOutput(ctx, "docker", "logs", cntrName) |
| 191 | if err != nil { |
| 192 | fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err) |
| 193 | return |
| 194 | } |
| 195 | logLines := strings.Split(string(out), "\n") |
| 196 | for _, logLine := range logLines { |
| 197 | if !strings.HasPrefix(logLine, "structured logs:") { |
| 198 | continue |
| 199 | } |
| 200 | logFile := strings.TrimSpace(strings.TrimPrefix(logLine, "structured logs:")) |
| 201 | srcPath := fmt.Sprintf("%s:%s", cntrName, logFile) |
| 202 | logFileName := filepath.Base(logFile) |
| 203 | dstPath := filepath.Join(config.ContainerLogDest, logFileName) |
| 204 | _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath) |
| 205 | if err != nil { |
| 206 | fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err) |
| 207 | } |
| 208 | fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | // NOTE: we want to see what the internal sketch binary prints |
| 213 | // regardless of the setting of the verbosity flag on the external |
| 214 | // binary, so reading "docker logs", which is the stdout/stderr of |
| 215 | // the internal binary is not conditional on the verbose flag. |
| 216 | appendInternalErr := func(err error) error { |
| 217 | if err == nil { |
| 218 | return nil |
| 219 | } |
| 220 | out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName) |
| 221 | if err != nil { |
| 222 | return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr) |
| 223 | } |
| 224 | out = bytes.TrimSpace(out) |
| 225 | if len(out) > 0 { |
| 226 | return fmt.Errorf("docker logs: %s;\n%w", out, err) |
| 227 | } |
| 228 | return err |
| 229 | } |
| 230 | |
| 231 | // Get the sketch server port from the container |
| 232 | localAddr, err := getContainerPort(ctx, cntrName) |
| 233 | if err != nil { |
| 234 | return appendInternalErr(err) |
| 235 | } |
| 236 | |
| 237 | // Tell the sketch container which git server port and commit to initialize with. |
| 238 | go func() { |
| 239 | // TODO: Why is this called in a goroutine? I have found that when I pull this out |
| 240 | // of the goroutine and call it inline, then the terminal UI clears itself and all |
| 241 | // the scrollback (which is not good, but also not fatal). I can't see why it does this |
| 242 | // though, since none of the calls in postContainerInitConfig obviously write to stdout |
| 243 | // or stderr. |
| 244 | if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort); err != nil { |
| 245 | slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error())) |
| 246 | errCh <- appendInternalErr(err) |
| 247 | } |
| 248 | }() |
| 249 | |
| 250 | if config.OpenBrowser { |
| 251 | OpenBrowser(ctx, "http://"+localAddr) |
| 252 | } |
| 253 | |
| 254 | go func() { |
| 255 | cmd := exec.CommandContext(ctx, "docker", "attach", cntrName) |
| 256 | cmd.Stdin = os.Stdin |
| 257 | cmd.Stdout = os.Stdout |
| 258 | cmd.Stderr = os.Stderr |
| 259 | errCh <- run(ctx, "docker attach", cmd) |
| 260 | }() |
| 261 | |
| 262 | defer copyLogs() |
| 263 | |
| 264 | for { |
| 265 | select { |
| 266 | case <-ctx.Done(): |
| 267 | return ctx.Err() |
| 268 | case err := <-errCh: |
| 269 | if err != nil { |
| 270 | return appendInternalErr(fmt.Errorf("container process: %w", err)) |
| 271 | } |
| 272 | return nil |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) { |
| 278 | cmd := exec.CommandContext(ctx, cmdName, args...) |
| 279 | // Really only needed for the "go build" command for the linux sketch binary |
| 280 | cmd.Env = append(os.Environ(), "GOOS=linux", "CGO_ENABLED=0") |
| 281 | start := time.Now() |
| 282 | |
| 283 | out, err := cmd.CombinedOutput() |
| 284 | if err != nil { |
| 285 | slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 286 | } else { |
| 287 | slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 288 | } |
| 289 | return out, err |
| 290 | } |
| 291 | |
| 292 | func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error { |
| 293 | start := time.Now() |
| 294 | err := cmd.Run() |
| 295 | if err != nil { |
| 296 | slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 297 | } else { |
| 298 | slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 299 | } |
| 300 | return err |
| 301 | } |
| 302 | |
| 303 | type gitServer struct { |
| 304 | gitLn net.Listener |
| 305 | gitPort string |
| 306 | srv *http.Server |
| 307 | } |
| 308 | |
| 309 | func (gs *gitServer) shutdown(ctx context.Context) { |
| 310 | gs.srv.Shutdown(ctx) |
| 311 | gs.gitLn.Close() |
| 312 | } |
| 313 | |
| 314 | // Serve a git remote from the host for the container to fetch from and push to. |
| 315 | func (gs *gitServer) serve(ctx context.Context) error { |
| 316 | slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git")) |
| 317 | return gs.srv.Serve(gs.gitLn) |
| 318 | } |
| 319 | |
| 320 | func newGitServer(gitRoot string) (*gitServer, error) { |
| 321 | ret := &gitServer{} |
| 322 | gitLn, err := net.Listen("tcp4", ":0") |
| 323 | if err != nil { |
| 324 | return nil, fmt.Errorf("git listen: %w", err) |
| 325 | } |
| 326 | ret.gitLn = gitLn |
| 327 | |
| 328 | srv := http.Server{ |
| 329 | Handler: &gitHTTP{gitRepoRoot: gitRoot}, |
| 330 | } |
| 331 | ret.srv = &srv |
| 332 | |
| 333 | _, gitPort, err := net.SplitHostPort(gitLn.Addr().String()) |
| 334 | if err != nil { |
| 335 | return nil, fmt.Errorf("git port: %w", err) |
| 336 | } |
| 337 | ret.gitPort = gitPort |
| 338 | return ret, nil |
| 339 | } |
| 340 | |
| 341 | func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error { |
| 342 | //, config.SessionID, config.GitUsername, config.GitEmail, config.SkabandAddr |
| 343 | // sessionID, gitUsername, gitEmail, skabandAddr string |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 344 | cmdArgs := []string{ |
| 345 | "create", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 346 | "-it", |
| 347 | "--name", cntrName, |
| 348 | "-p", hostPort + ":80", // forward container port 80 to a host port |
| 349 | "-e", "ANTHROPIC_API_KEY=" + config.AntAPIKey, |
| 350 | } |
| 351 | if config.AntURL != "" { |
| 352 | cmdArgs = append(cmdArgs, "-e", "ANT_URL="+config.AntURL) |
| 353 | } |
| 354 | if config.SketchPubKey != "" { |
| 355 | cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey) |
| 356 | } |
| 357 | if relPath != "." { |
| 358 | cmdArgs = append(cmdArgs, "-w", "/app/"+relPath) |
| 359 | } |
| 360 | cmdArgs = append( |
| 361 | cmdArgs, |
| 362 | imgName, |
| 363 | "/bin/sketch", |
| 364 | "-unsafe", |
| 365 | "-addr=:80", |
| 366 | "-session-id="+config.SessionID, |
| 367 | "-git-username="+config.GitUsername, "-git-email="+config.GitEmail, |
| 368 | ) |
| 369 | if config.SkabandAddr != "" { |
| 370 | cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr) |
| 371 | } |
| 372 | if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil { |
| 373 | return fmt.Errorf("docker create: %s, %w", out, err) |
| 374 | } |
| 375 | return nil |
| 376 | } |
| 377 | |
| 378 | func buildLinuxSketchBin(ctx context.Context, path string) (string, error) { |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 379 | homeDir, err := os.UserHomeDir() |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 380 | if err != nil { |
| 381 | return "", err |
| 382 | } |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 383 | linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo") |
| 384 | if err := os.MkdirAll(linuxGopath, 0o777); err != nil { |
| 385 | return "", err |
| 386 | } |
| 387 | |
| 388 | verToInstall := "@latest" |
| 389 | if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil { |
| 390 | return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err) |
| 391 | } else { |
| 392 | if strings.TrimSpace(string(out)) == "sketch.dev" { |
| 393 | fmt.Printf("building linux agent from currently checked out module\n") |
| 394 | verToInstall = "" |
| 395 | } |
| 396 | } |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 397 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 398 | start := time.Now() |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 399 | cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall) |
| David Crawshaw | b9eaef5 | 2025-04-17 15:23:18 -0700 | [diff] [blame] | 400 | cmd.Env = append( |
| 401 | os.Environ(), |
| 402 | "GOOS=linux", |
| 403 | "CGO_ENABLED=0", |
| 404 | "GOTOOLCHAIN=auto", |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 405 | "GOPATH="+linuxGopath, |
| Josh Bleecher Snyder | fae1757 | 2025-04-21 11:48:05 -0700 | [diff] [blame] | 406 | "GOBIN=", |
| David Crawshaw | b9eaef5 | 2025-04-17 15:23:18 -0700 | [diff] [blame] | 407 | ) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 408 | |
| 409 | fmt.Printf("building linux agent binary...\n") |
| 410 | out, err := cmd.CombinedOutput() |
| 411 | if err != nil { |
| 412 | slog.ErrorContext(ctx, "go", slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 413 | return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err) |
| 414 | } else { |
| 415 | slog.DebugContext(ctx, "go", slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 416 | } |
| 417 | |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 418 | src := filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch") |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 419 | dst := filepath.Join(path, "tmp-sketch-binary-linux") |
| 420 | if err := os.Rename(src, dst); err != nil { |
| 421 | return "", err |
| 422 | } |
| 423 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 424 | fmt.Printf("built linux agent binary in %s\n", time.Since(start).Round(100*time.Millisecond)) |
| 425 | |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 426 | return dst, nil |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 427 | } |
| 428 | |
| 429 | func getContainerPort(ctx context.Context, cntrName string) (string, error) { |
| 430 | localAddr := "" |
| 431 | if out, err := combinedOutput(ctx, "docker", "port", cntrName, "80"); err != nil { |
| 432 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 433 | } else { |
| 434 | v4, _, found := strings.Cut(string(out), "\n") |
| 435 | if !found { |
| 436 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 437 | } |
| 438 | localAddr = v4 |
| 439 | if strings.HasPrefix(localAddr, "0.0.0.0") { |
| 440 | localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0") |
| 441 | } |
| 442 | } |
| 443 | return localAddr, nil |
| 444 | } |
| 445 | |
| 446 | // Contact the container and configure it. |
| 447 | func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort string) error { |
| 448 | localURL := "http://" + localAddr |
| 449 | initMsg, err := json.Marshal(map[string]string{ |
| 450 | "commit": commit, |
| 451 | "git_remote_addr": "http://host.docker.internal:" + gitPort + "/.git", |
| 452 | "host_addr": localAddr, |
| 453 | }) |
| 454 | if err != nil { |
| 455 | return fmt.Errorf("init msg: %w", err) |
| 456 | } |
| 457 | |
| 458 | slog.DebugContext(ctx, "/init POST", slog.String("initMsg", string(initMsg))) |
| 459 | |
| 460 | // Note: this /init POST is handled in loop/server/loophttp.go: |
| 461 | initMsgByteReader := bytes.NewReader(initMsg) |
| 462 | req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader) |
| 463 | if err != nil { |
| 464 | return err |
| 465 | } |
| 466 | |
| 467 | var res *http.Response |
| 468 | for i := 0; ; i++ { |
| 469 | time.Sleep(100 * time.Millisecond) |
| 470 | // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes. |
| 471 | initMsgByteReader.Reset(initMsg) |
| 472 | res, err = http.DefaultClient.Do(req) |
| 473 | if err != nil { |
| 474 | // In addition to "connection refused", we also occasionally see "EOF" errors that can succeed on retries. |
| 475 | if i < 100 && (strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "EOF")) { |
| 476 | slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error())) |
| 477 | continue |
| 478 | } |
| 479 | return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err) |
| 480 | } |
| 481 | break |
| 482 | } |
| 483 | resBytes, _ := io.ReadAll(res.Body) |
| 484 | if res.StatusCode != http.StatusOK { |
| 485 | return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes) |
| 486 | } |
| 487 | return nil |
| 488 | } |
| 489 | |
| 490 | func findOrBuildDockerImage(ctx context.Context, stdout, stderr io.Writer, cwd, gitRoot, antURL, antAPIKey string, forceRebuild bool) (imgName string, err error) { |
| 491 | h := sha256.Sum256([]byte(gitRoot)) |
| 492 | imgName = "sketch-" + hex.EncodeToString(h[:6]) |
| 493 | |
| 494 | var curImgInitFilesHash string |
| 495 | if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil { |
| 496 | if strings.Contains(string(out), "No such object") { |
| 497 | // Image does not exist, continue and build it. |
| 498 | curImgInitFilesHash = "" |
| 499 | } else { |
| 500 | return "", fmt.Errorf("docker inspect failed: %s, %v", out, err) |
| 501 | } |
| 502 | } else { |
| 503 | m := map[string]string{} |
| 504 | if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil { |
| 505 | return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err) |
| 506 | } |
| 507 | curImgInitFilesHash = m["sketch_context"] |
| 508 | } |
| 509 | |
| 510 | candidates, err := findRepoDockerfiles(cwd, gitRoot) |
| 511 | if err != nil { |
| 512 | return "", fmt.Errorf("find dockerfile: %w", err) |
| 513 | } |
| 514 | |
| 515 | var initFiles map[string]string |
| 516 | var dockerfilePath string |
| 517 | |
| 518 | // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool. |
| 519 | if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" { |
| 520 | dockerfilePath = candidates[0] |
| 521 | contents, err := os.ReadFile(dockerfilePath) |
| 522 | if err != nil { |
| 523 | return "", err |
| 524 | } |
| 525 | fmt.Printf("using %s as dev env\n", candidates[0]) |
| 526 | if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild { |
| 527 | fmt.Printf("using existing docker image %s\n", imgName) |
| 528 | return imgName, nil |
| 529 | } |
| 530 | } else { |
| 531 | initFiles, err = readInitFiles(os.DirFS(gitRoot)) |
| 532 | if err != nil { |
| 533 | return "", err |
| 534 | } |
| 535 | subPathWorkingDir, err := filepath.Rel(gitRoot, cwd) |
| 536 | if err != nil { |
| 537 | return "", err |
| 538 | } |
| 539 | initFileHash := hashInitFiles(initFiles) |
| 540 | if curImgInitFilesHash == initFileHash && !forceRebuild { |
| 541 | fmt.Printf("using existing docker image %s\n", imgName) |
| 542 | return imgName, nil |
| 543 | } |
| 544 | |
| 545 | start := time.Now() |
| 546 | dockerfile, err := createDockerfile(ctx, http.DefaultClient, antURL, antAPIKey, initFiles, subPathWorkingDir) |
| 547 | if err != nil { |
| 548 | return "", fmt.Errorf("create dockerfile: %w", err) |
| 549 | } |
| 550 | dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile") |
| 551 | if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil { |
| 552 | return "", err |
| 553 | } |
| 554 | defer os.Remove(dockerfilePath) |
| 555 | |
| 556 | fmt.Fprintf(stderr, "generated Dockerfile in %s:\n\t%s\n\n", time.Since(start).Round(time.Millisecond), strings.Replace(dockerfile, "\n", "\n\t", -1)) |
| 557 | } |
| 558 | |
| 559 | var gitUserEmail, gitUserName string |
| 560 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil { |
| 561 | return "", fmt.Errorf("git config: %s: %v", out, err) |
| 562 | } else { |
| 563 | gitUserEmail = strings.TrimSpace(string(out)) |
| 564 | } |
| 565 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil { |
| 566 | return "", fmt.Errorf("git config: %s: %v", out, err) |
| 567 | } else { |
| 568 | gitUserName = strings.TrimSpace(string(out)) |
| 569 | } |
| 570 | |
| 571 | start := time.Now() |
| 572 | cmd := exec.CommandContext(ctx, |
| 573 | "docker", "build", |
| 574 | "-t", imgName, |
| 575 | "-f", dockerfilePath, |
| 576 | "--build-arg", "GIT_USER_EMAIL="+gitUserEmail, |
| 577 | "--build-arg", "GIT_USER_NAME="+gitUserName, |
| 578 | ".", |
| 579 | ) |
| 580 | cmd.Dir = gitRoot |
| 581 | cmd.Stdout = stdout |
| 582 | cmd.Stderr = stderr |
| 583 | fmt.Printf("building docker image %s...\n", imgName) |
| 584 | |
| 585 | err = run(ctx, "docker build", cmd) |
| 586 | if err != nil { |
| 587 | return "", fmt.Errorf("docker build failed: %v", err) |
| 588 | } |
| 589 | fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond)) |
| 590 | return imgName, nil |
| 591 | } |
| 592 | |
| 593 | func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) { |
| 594 | files, err := findDirDockerfiles(cwd) |
| 595 | if err != nil { |
| 596 | return nil, err |
| 597 | } |
| 598 | if len(files) > 0 { |
| 599 | return files, nil |
| 600 | } |
| 601 | |
| 602 | path := cwd |
| 603 | for path != gitRoot { |
| 604 | path = filepath.Dir(path) |
| 605 | files, err := findDirDockerfiles(path) |
| 606 | if err != nil { |
| 607 | return nil, err |
| 608 | } |
| 609 | if len(files) > 0 { |
| 610 | return files, nil |
| 611 | } |
| 612 | } |
| 613 | return files, nil |
| 614 | } |
| 615 | |
| 616 | // findDirDockerfiles finds all "Dockerfile*" files in a directory. |
| 617 | func findDirDockerfiles(root string) (res []string, err error) { |
| 618 | err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error { |
| 619 | if err != nil { |
| 620 | return err |
| 621 | } |
| 622 | if info.IsDir() && root != path { |
| 623 | return filepath.SkipDir |
| 624 | } |
| 625 | name := strings.ToLower(info.Name()) |
| 626 | if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") { |
| 627 | res = append(res, path) |
| 628 | } |
| 629 | return nil |
| 630 | }) |
| 631 | if err != nil { |
| 632 | return nil, err |
| 633 | } |
| 634 | return res, nil |
| 635 | } |
| 636 | |
| 637 | func findGitRoot(ctx context.Context, path string) (string, error) { |
| 638 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir") |
| 639 | cmd.Dir = path |
| 640 | out, err := cmd.CombinedOutput() |
| 641 | if err != nil { |
| 642 | if strings.Contains(string(out), "not a git repository") { |
| 643 | return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo. |
| 644 | Consider one of the following options: |
| 645 | - cd to a different dir that is already part of a git repo first, or |
| 646 | - to create a new git repo from this directory (%s), run this command: |
| 647 | |
| 648 | git init . && git commit --allow-empty -m "initial commit" |
| 649 | |
| 650 | and try running sketch again. |
| 651 | `, path, path) |
| 652 | } |
| 653 | return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err) |
| 654 | } |
| 655 | gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path |
| 656 | absGitDir := filepath.Join(path, gitDir) |
| 657 | return filepath.Dir(absGitDir), err |
| 658 | } |
| 659 | |
| 660 | func OpenBrowser(ctx context.Context, url string) { |
| 661 | var cmd *exec.Cmd |
| 662 | switch runtime.GOOS { |
| 663 | case "darwin": |
| 664 | cmd = exec.CommandContext(ctx, "open", url) |
| 665 | case "windows": |
| 666 | cmd = exec.CommandContext(ctx, "cmd", "/c", "start", url) |
| 667 | default: // Linux and other Unix-like systems |
| 668 | cmd = exec.CommandContext(ctx, "xdg-open", url) |
| 669 | } |
| 670 | if b, err := cmd.CombinedOutput(); err != nil { |
| 671 | fmt.Fprintf(os.Stderr, "failed to open browser: %v: %s\n", err, b) |
| 672 | } |
| 673 | } |