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