| 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 | |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 24 | "sketch.dev/browser" |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 25 | "sketch.dev/llm/ant" |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 26 | "sketch.dev/loop/server" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 27 | "sketch.dev/skribe" |
| Philip Zeyliger | 5d6af87 | 2025-04-23 19:48:34 -0700 | [diff] [blame] | 28 | "sketch.dev/webui" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 29 | ) |
| 30 | |
| 31 | // ContainerConfig holds all configuration for launching a container |
| 32 | type ContainerConfig struct { |
| 33 | // SessionID is the unique identifier for this session |
| 34 | SessionID string |
| 35 | |
| 36 | // LocalAddr is the initial address to use (though it may be overwritten later) |
| 37 | LocalAddr string |
| 38 | |
| 39 | // SkabandAddr is the address of the skaband service if available |
| 40 | SkabandAddr string |
| 41 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 42 | // Model is the name of the LLM model to use. |
| 43 | Model string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 44 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 45 | // ModelURL is the URL of the LLM service. |
| 46 | ModelURL string |
| 47 | |
| 48 | // ModelAPIKey is the API key for LLM service. |
| 49 | ModelAPIKey string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 50 | |
| 51 | // Path is the local filesystem path to use |
| 52 | Path string |
| 53 | |
| 54 | // GitUsername is the username to use for git operations |
| 55 | GitUsername string |
| 56 | |
| 57 | // GitEmail is the email to use for git operations |
| 58 | GitEmail string |
| 59 | |
| 60 | // OpenBrowser determines whether to open a browser automatically |
| 61 | OpenBrowser bool |
| 62 | |
| 63 | // NoCleanup prevents container cleanup when set to true |
| 64 | NoCleanup bool |
| 65 | |
| 66 | // ForceRebuild forces rebuilding of the Docker image even if it exists |
| 67 | ForceRebuild bool |
| 68 | |
| 69 | // Host directory to copy container logs into, if not set to "" |
| 70 | ContainerLogDest string |
| 71 | |
| 72 | // Path to pre-built linux sketch binary, or build a new one if set to "" |
| 73 | SketchBinaryLinux string |
| 74 | |
| 75 | // Sketch client public key. |
| 76 | SketchPubKey string |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 77 | |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 78 | // Host port for the container's ssh server |
| 79 | SSHPort int |
| 80 | |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 81 | // Outside information to pass to the container |
| 82 | OutsideHostname string |
| 83 | OutsideOS string |
| 84 | OutsideWorkingDir string |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 85 | |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 86 | // If true, exit after the first turn |
| 87 | OneShot bool |
| 88 | |
| 89 | // Initial prompt |
| 90 | Prompt string |
| Philip Zeyliger | 1b47aa2 | 2025-04-28 19:25:38 +0000 | [diff] [blame] | 91 | |
| 92 | // Initial commit to use as starting point |
| 93 | InitialCommit string |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 94 | |
| 95 | // Verbose enables verbose output |
| 96 | Verbose bool |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 97 | |
| 98 | // DockerArgs are additional arguments to pass to the docker create command |
| 99 | DockerArgs string |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 100 | |
| 101 | // ExperimentFlag contains the experimental features to enable |
| 102 | ExperimentFlag string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 103 | } |
| 104 | |
| 105 | // LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it. |
| 106 | // It writes status to stdout. |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 107 | func LaunchContainer(ctx context.Context, config ContainerConfig) error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 108 | if _, err := exec.LookPath("docker"); err != nil { |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 109 | if runtime.GOOS == "darwin" { |
| 110 | return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start") |
| 111 | } else { |
| 112 | return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)") |
| 113 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 114 | } |
| 115 | |
| 116 | if out, err := combinedOutput(ctx, "docker", "ps"); err != nil { |
| 117 | // `docker ps` provides a good error message here that can be |
| 118 | // easily chatgpt'ed by users, so send it to the user as-is: |
| 119 | // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? |
| 120 | return fmt.Errorf("docker ps: %s (%w)", out, err) |
| 121 | } |
| 122 | |
| 123 | _, hostPort, err := net.SplitHostPort(config.LocalAddr) |
| 124 | if err != nil { |
| 125 | return err |
| 126 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 127 | gitRoot, err := findGitRoot(ctx, config.Path) |
| 128 | if err != nil { |
| 129 | return err |
| 130 | } |
| 131 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 132 | 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] | 133 | if err != nil { |
| 134 | return err |
| 135 | } |
| 136 | |
| 137 | linuxSketchBin := config.SketchBinaryLinux |
| 138 | if linuxSketchBin == "" { |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 139 | linuxSketchBin, err = buildLinuxSketchBin(ctx) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 140 | if err != nil { |
| 141 | return err |
| 142 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 143 | } |
| 144 | |
| Philip Zeyliger | c72fff5 | 2025-04-29 20:17:54 +0000 | [diff] [blame] | 145 | cntrName := "sketch-" + config.SessionID |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 146 | defer func() { |
| 147 | if config.NoCleanup { |
| 148 | return |
| 149 | } |
| 150 | if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil { |
| 151 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 152 | _ = out |
| 153 | } |
| 154 | if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil { |
| 155 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 156 | _ = out |
| 157 | } |
| 158 | }() |
| 159 | |
| 160 | // errCh receives errors from operations that this function calls in separate goroutines. |
| 161 | errCh := make(chan error) |
| 162 | |
| 163 | // Start the git server |
| 164 | gitSrv, err := newGitServer(gitRoot) |
| 165 | if err != nil { |
| 166 | return fmt.Errorf("failed to start git server: %w", err) |
| 167 | } |
| 168 | defer gitSrv.shutdown(ctx) |
| 169 | |
| 170 | go func() { |
| 171 | errCh <- gitSrv.serve(ctx) |
| 172 | }() |
| 173 | |
| 174 | // Get the current host git commit |
| 175 | var commit string |
| Philip Zeyliger | 1b47aa2 | 2025-04-28 19:25:38 +0000 | [diff] [blame] | 176 | if out, err := combinedOutput(ctx, "git", "rev-parse", config.InitialCommit); err != nil { |
| 177 | return fmt.Errorf("git rev-parse %s: %w", config.InitialCommit, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 178 | } else { |
| 179 | commit = strings.TrimSpace(string(out)) |
| 180 | } |
| 181 | if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil { |
| 182 | return fmt.Errorf("git config http.receivepack true: %s: %w", out, err) |
| 183 | } |
| 184 | |
| 185 | relPath, err := filepath.Rel(gitRoot, config.Path) |
| 186 | if err != nil { |
| 187 | return err |
| 188 | } |
| 189 | |
| 190 | // Create the sketch container |
| 191 | if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil { |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 192 | return fmt.Errorf("failed to create docker container: %w", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 193 | } |
| 194 | |
| 195 | // Copy the sketch linux binary into the container |
| 196 | if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil { |
| 197 | return fmt.Errorf("docker cp: %s, %w", out, err) |
| 198 | } |
| Sean McCullough | f5bb3d3 | 2025-04-18 10:47:59 -0700 | [diff] [blame] | 199 | |
| 200 | // Make sure that the webui is built so we can copy the results to the container. |
| 201 | _, err = webui.Build() |
| 202 | if err != nil { |
| 203 | return fmt.Errorf("failed to build webui: %w", err) |
| 204 | } |
| 205 | |
| David Crawshaw | 8bff16a | 2025-04-18 01:16:49 -0700 | [diff] [blame] | 206 | webuiZipPath, err := webui.ZipPath() |
| 207 | if err != nil { |
| 208 | return err |
| 209 | } |
| 210 | if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil { |
| 211 | return fmt.Errorf("docker cp: %s, %w", out, err) |
| 212 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 213 | |
| David Crawshaw | 53786ef | 2025-04-24 12:52:51 -0700 | [diff] [blame] | 214 | fmt.Printf("📦 running in container %s\n", cntrName) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 215 | |
| 216 | // Start the sketch container |
| 217 | if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil { |
| 218 | return fmt.Errorf("docker start: %s, %w", out, err) |
| 219 | } |
| 220 | |
| 221 | // Copies structured logs from the container to the host. |
| 222 | copyLogs := func() { |
| 223 | if config.ContainerLogDest == "" { |
| 224 | return |
| 225 | } |
| 226 | out, err := combinedOutput(ctx, "docker", "logs", cntrName) |
| 227 | if err != nil { |
| 228 | fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err) |
| 229 | return |
| 230 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 231 | prefix := []byte("structured logs:") |
| 232 | for line := range bytes.Lines(out) { |
| 233 | rest, ok := bytes.CutPrefix(line, prefix) |
| 234 | if !ok { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 235 | continue |
| 236 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 237 | logFile := string(bytes.TrimSpace(rest)) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 238 | srcPath := fmt.Sprintf("%s:%s", cntrName, logFile) |
| 239 | logFileName := filepath.Base(logFile) |
| 240 | dstPath := filepath.Join(config.ContainerLogDest, logFileName) |
| 241 | _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath) |
| 242 | if err != nil { |
| 243 | fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err) |
| 244 | } |
| 245 | fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath) |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | // NOTE: we want to see what the internal sketch binary prints |
| 250 | // regardless of the setting of the verbosity flag on the external |
| 251 | // binary, so reading "docker logs", which is the stdout/stderr of |
| 252 | // the internal binary is not conditional on the verbose flag. |
| 253 | appendInternalErr := func(err error) error { |
| 254 | if err == nil { |
| 255 | return nil |
| 256 | } |
| 257 | out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName) |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 258 | if logsErr != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 259 | return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr) |
| 260 | } |
| 261 | out = bytes.TrimSpace(out) |
| 262 | if len(out) > 0 { |
| 263 | return fmt.Errorf("docker logs: %s;\n%w", out, err) |
| 264 | } |
| 265 | return err |
| 266 | } |
| 267 | |
| 268 | // Get the sketch server port from the container |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 269 | localAddr, err := getContainerPort(ctx, cntrName, "80") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 270 | if err != nil { |
| 271 | return appendInternalErr(err) |
| 272 | } |
| 273 | |
| Philip Zeyliger | 0044241 | 2025-05-14 11:03:23 -0700 | [diff] [blame^] | 274 | if config.Verbose { |
| 275 | fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr) |
| 276 | } |
| 277 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 278 | localSSHAddr, err := getContainerPort(ctx, cntrName, "22") |
| 279 | if err != nil { |
| 280 | return appendInternalErr(err) |
| 281 | } |
| 282 | sshHost, sshPort, err := net.SplitHostPort(localSSHAddr) |
| 283 | if err != nil { |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 284 | 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] | 285 | } |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 286 | |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 287 | var sshServerIdentity, sshUserIdentity []byte |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 288 | |
| Sean McCullough | 078e85a | 2025-05-08 17:28:34 -0700 | [diff] [blame] | 289 | cst, err := NewSSHTheater(cntrName, sshHost, sshPort) |
| 290 | if err != nil { |
| 291 | return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err)) |
| 292 | } |
| 293 | |
| 294 | sshErr := CheckSSHReachability(cntrName) |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 295 | sshAvailable := false |
| 296 | sshErrMsg := "" |
| 297 | if sshErr != nil { |
| 298 | fmt.Println(sshErr.Error()) |
| 299 | sshErrMsg = sshErr.Error() |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 300 | // continue - ssh config is not required for the rest of sketch to function locally. |
| 301 | } else { |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 302 | sshAvailable = true |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 303 | // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find: |
| 304 | // 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] | 305 | fmt.Printf(`Connect to this container via any of these methods: |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 306 | 🖥️ ssh %s |
| 307 | 🖥️ code --remote ssh-remote+root@%s /app -n |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 308 | 🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 309 | `, cntrName, cntrName, cntrName) |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 310 | sshUserIdentity = cst.userIdentity |
| 311 | sshServerIdentity = cst.serverIdentity |
| 312 | defer func() { |
| 313 | if err := cst.Cleanup(); err != nil { |
| 314 | appendInternalErr(err) |
| 315 | } |
| 316 | }() |
| 317 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 318 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 319 | // Tell the sketch container which git server port and commit to initialize with. |
| 320 | go func() { |
| 321 | // TODO: Why is this called in a goroutine? I have found that when I pull this out |
| 322 | // of the goroutine and call it inline, then the terminal UI clears itself and all |
| 323 | // the scrollback (which is not good, but also not fatal). I can't see why it does this |
| 324 | // though, since none of the calls in postContainerInitConfig obviously write to stdout |
| 325 | // or stderr. |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 326 | if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 327 | slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error())) |
| 328 | errCh <- appendInternalErr(err) |
| 329 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 330 | |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 331 | // 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] | 332 | ps1URL := "http://" + localAddr |
| 333 | if config.SkabandAddr != "" { |
| 334 | ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID) |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 335 | } |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 336 | if config.OpenBrowser { |
| 337 | browser.Open(ps1URL) |
| 338 | } |
| 339 | gitSrv.ps1URL.Store(&ps1URL) |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 340 | }() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 341 | |
| 342 | go func() { |
| 343 | cmd := exec.CommandContext(ctx, "docker", "attach", cntrName) |
| 344 | cmd.Stdin = os.Stdin |
| 345 | cmd.Stdout = os.Stdout |
| 346 | cmd.Stderr = os.Stderr |
| 347 | errCh <- run(ctx, "docker attach", cmd) |
| 348 | }() |
| 349 | |
| 350 | defer copyLogs() |
| 351 | |
| 352 | for { |
| 353 | select { |
| 354 | case <-ctx.Done(): |
| 355 | return ctx.Err() |
| 356 | case err := <-errCh: |
| 357 | if err != nil { |
| 358 | return appendInternalErr(fmt.Errorf("container process: %w", err)) |
| 359 | } |
| 360 | return nil |
| 361 | } |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) { |
| 366 | cmd := exec.CommandContext(ctx, cmdName, args...) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 367 | start := time.Now() |
| 368 | |
| 369 | out, err := cmd.CombinedOutput() |
| 370 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 371 | 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] | 372 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 373 | 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] | 374 | } |
| 375 | return out, err |
| 376 | } |
| 377 | |
| 378 | func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error { |
| 379 | start := time.Now() |
| 380 | err := cmd.Run() |
| 381 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 382 | 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] | 383 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 384 | 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] | 385 | } |
| 386 | return err |
| 387 | } |
| 388 | |
| 389 | type gitServer struct { |
| 390 | gitLn net.Listener |
| 391 | gitPort string |
| 392 | srv *http.Server |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 393 | pass string |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 394 | ps1URL atomic.Pointer[string] |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 395 | } |
| 396 | |
| 397 | func (gs *gitServer) shutdown(ctx context.Context) { |
| 398 | gs.srv.Shutdown(ctx) |
| 399 | gs.gitLn.Close() |
| 400 | } |
| 401 | |
| 402 | // Serve a git remote from the host for the container to fetch from and push to. |
| 403 | func (gs *gitServer) serve(ctx context.Context) error { |
| 404 | slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git")) |
| 405 | return gs.srv.Serve(gs.gitLn) |
| 406 | } |
| 407 | |
| 408 | func newGitServer(gitRoot string) (*gitServer, error) { |
| Josh Bleecher Snyder | 9f6a998 | 2025-04-22 17:34:15 -0700 | [diff] [blame] | 409 | ret := &gitServer{ |
| 410 | pass: rand.Text(), |
| 411 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 412 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 413 | gitLn, err := net.Listen("tcp4", ":0") |
| 414 | if err != nil { |
| 415 | return nil, fmt.Errorf("git listen: %w", err) |
| 416 | } |
| 417 | ret.gitLn = gitLn |
| 418 | |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 419 | browserC := make(chan bool, 1) // channel of browser open requests |
| 420 | |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 421 | go func() { |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 422 | for range browserC { |
| 423 | browser.Open(*ret.ps1URL.Load()) |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 424 | } |
| 425 | }() |
| 426 | |
| 427 | 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] | 428 | ret.srv = &srv |
| 429 | |
| 430 | _, gitPort, err := net.SplitHostPort(gitLn.Addr().String()) |
| 431 | if err != nil { |
| 432 | return nil, fmt.Errorf("git port: %w", err) |
| 433 | } |
| 434 | ret.gitPort = gitPort |
| 435 | return ret, nil |
| 436 | } |
| 437 | |
| 438 | 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] | 439 | cmdArgs := []string{ |
| 440 | "create", |
| David Crawshaw | 66cf74e | 2025-05-05 08:48:39 -0700 | [diff] [blame] | 441 | "-i", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 442 | "--name", cntrName, |
| 443 | "-p", hostPort + ":80", // forward container port 80 to a host port |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 444 | "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 445 | } |
| David Crawshaw | 66cf74e | 2025-05-05 08:48:39 -0700 | [diff] [blame] | 446 | if !config.OneShot { |
| 447 | cmdArgs = append(cmdArgs, "-t") |
| 448 | } |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 449 | |
| 450 | for _, envVar := range getEnvForwardingFromGitConfig(ctx) { |
| 451 | cmdArgs = append(cmdArgs, "-e", envVar) |
| 452 | } |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 453 | if config.ModelURL != "" { |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 454 | cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 455 | } |
| 456 | if config.SketchPubKey != "" { |
| 457 | cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey) |
| 458 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 459 | if config.SSHPort > 0 { |
| 460 | cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port |
| 461 | } else { |
| 462 | cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh. |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 463 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 464 | if relPath != "." { |
| 465 | cmdArgs = append(cmdArgs, "-w", "/app/"+relPath) |
| 466 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 467 | // colima does this by default, but Linux docker seems to need this set explicitly |
| 468 | cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 469 | cmdArgs = append( |
| 470 | cmdArgs, |
| 471 | imgName, |
| 472 | "/bin/sketch", |
| 473 | "-unsafe", |
| 474 | "-addr=:80", |
| 475 | "-session-id="+config.SessionID, |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 476 | "-git-username="+config.GitUsername, |
| 477 | "-git-email="+config.GitEmail, |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 478 | "-outside-hostname="+config.OutsideHostname, |
| 479 | "-outside-os="+config.OutsideOS, |
| 480 | "-outside-working-dir="+config.OutsideWorkingDir, |
| Josh Bleecher Snyder | 3cae7d9 | 2025-04-30 09:54:29 -0700 | [diff] [blame] | 481 | "-open=false", |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 482 | "-x="+config.ExperimentFlag, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 483 | ) |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 484 | if config.Model != "" { |
| 485 | cmdArgs = append(cmdArgs, "-model="+config.Model) |
| 486 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 487 | if config.SkabandAddr != "" { |
| 488 | cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr) |
| 489 | } |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 490 | if config.Prompt != "" { |
| 491 | cmdArgs = append(cmdArgs, "-prompt", config.Prompt) |
| 492 | } |
| 493 | if config.OneShot { |
| 494 | cmdArgs = append(cmdArgs, "-one-shot") |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 495 | } |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 496 | |
| 497 | // Add additional docker arguments if provided |
| 498 | if config.DockerArgs != "" { |
| 499 | // Parse space-separated docker arguments with support for quotes and escaping |
| 500 | args := parseDockerArgs(config.DockerArgs) |
| 501 | // Insert arguments after "create" but before other arguments |
| 502 | for i := len(args) - 1; i >= 0; i-- { |
| 503 | cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...) |
| 504 | } |
| 505 | } |
| 506 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 507 | if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil { |
| 508 | return fmt.Errorf("docker create: %s, %w", out, err) |
| 509 | } |
| 510 | return nil |
| 511 | } |
| 512 | |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 513 | func buildLinuxSketchBin(ctx context.Context) (string, error) { |
| Pokey Rule | a9a786b | 2025-05-12 10:52:34 +0100 | [diff] [blame] | 514 | // Change to directory containing dockerimg.go for module detection |
| 515 | _, codeFile, _, _ := runtime.Caller(0) |
| 516 | codeDir := filepath.Dir(codeFile) |
| 517 | if currentDir, err := os.Getwd(); err != nil { |
| 518 | slog.WarnContext(ctx, "could not get current directory", "err", err) |
| 519 | } else { |
| 520 | if err := os.Chdir(codeDir); err != nil { |
| 521 | slog.WarnContext(ctx, "could not change to code directory for module check", "err", err) |
| 522 | } else { |
| 523 | defer func() { |
| 524 | _ = os.Chdir(currentDir) |
| 525 | }() |
| 526 | } |
| 527 | } |
| 528 | |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 529 | homeDir, err := os.UserHomeDir() |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 530 | if err != nil { |
| 531 | return "", err |
| 532 | } |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 533 | linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo") |
| 534 | if err := os.MkdirAll(linuxGopath, 0o777); err != nil { |
| 535 | return "", err |
| 536 | } |
| 537 | |
| 538 | verToInstall := "@latest" |
| 539 | if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil { |
| 540 | return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err) |
| 541 | } else { |
| 542 | if strings.TrimSpace(string(out)) == "sketch.dev" { |
| David Crawshaw | 094e4d2 | 2025-04-24 11:35:14 -0700 | [diff] [blame] | 543 | slog.DebugContext(ctx, "built linux agent from currently checked out module") |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 544 | verToInstall = "" |
| 545 | } |
| 546 | } |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 547 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 548 | start := time.Now() |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 549 | cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall) |
| David Crawshaw | b9eaef5 | 2025-04-17 15:23:18 -0700 | [diff] [blame] | 550 | cmd.Env = append( |
| 551 | os.Environ(), |
| 552 | "GOOS=linux", |
| 553 | "CGO_ENABLED=0", |
| 554 | "GOTOOLCHAIN=auto", |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 555 | "GOPATH="+linuxGopath, |
| Josh Bleecher Snyder | fae1757 | 2025-04-21 11:48:05 -0700 | [diff] [blame] | 556 | "GOBIN=", |
| David Crawshaw | b9eaef5 | 2025-04-17 15:23:18 -0700 | [diff] [blame] | 557 | ) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 558 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 559 | out, err := cmd.CombinedOutput() |
| 560 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 561 | 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] | 562 | return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err) |
| 563 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 564 | 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] | 565 | } |
| 566 | |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 567 | if runtime.GOOS != "linux" { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 568 | return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 569 | } |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 570 | // If we are already on Linux, there's no extra platform name in the path |
| 571 | return filepath.Join(linuxGopath, "bin", "sketch"), nil |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 572 | } |
| 573 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 574 | func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 575 | localAddr := "" |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 576 | if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 577 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 578 | } else { |
| 579 | v4, _, found := strings.Cut(string(out), "\n") |
| 580 | if !found { |
| 581 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 582 | } |
| 583 | localAddr = v4 |
| 584 | if strings.HasPrefix(localAddr, "0.0.0.0") { |
| 585 | localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0") |
| 586 | } |
| 587 | } |
| 588 | return localAddr, nil |
| 589 | } |
| 590 | |
| 591 | // Contact the container and configure it. |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 592 | func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys []byte) error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 593 | localURL := "http://" + localAddr |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 594 | |
| 595 | initMsg, err := json.Marshal( |
| 596 | server.InitRequest{ |
| 597 | Commit: commit, |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 598 | OutsideHTTP: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitPass, gitPort), |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 599 | GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort), |
| 600 | HostAddr: localAddr, |
| 601 | SSHAuthorizedKeys: sshAuthorizedKeys, |
| 602 | SSHServerIdentity: sshServerIdentity, |
| Philip Zeyliger | c72fff5 | 2025-04-29 20:17:54 +0000 | [diff] [blame] | 603 | SSHAvailable: sshAvailable, |
| 604 | SSHError: sshError, |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 605 | }) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 606 | if err != nil { |
| 607 | return fmt.Errorf("init msg: %w", err) |
| 608 | } |
| 609 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 610 | // Note: this /init POST is handled in loop/server/loophttp.go: |
| 611 | initMsgByteReader := bytes.NewReader(initMsg) |
| 612 | req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader) |
| 613 | if err != nil { |
| 614 | return err |
| 615 | } |
| 616 | |
| 617 | var res *http.Response |
| 618 | for i := 0; ; i++ { |
| 619 | time.Sleep(100 * time.Millisecond) |
| 620 | // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes. |
| 621 | initMsgByteReader.Reset(initMsg) |
| 622 | res, err = http.DefaultClient.Do(req) |
| 623 | if err != nil { |
| David Crawshaw | 99231ba | 2025-05-03 10:48:26 -0700 | [diff] [blame] | 624 | if i < 100 { |
| 625 | if i%10 == 0 { |
| 626 | slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error())) |
| 627 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 628 | continue |
| 629 | } |
| 630 | return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err) |
| 631 | } |
| 632 | break |
| 633 | } |
| 634 | resBytes, _ := io.ReadAll(res.Body) |
| 635 | if res.StatusCode != http.StatusOK { |
| 636 | return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes) |
| 637 | } |
| 638 | return nil |
| 639 | } |
| 640 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 641 | 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] | 642 | h := sha256.Sum256([]byte(gitRoot)) |
| 643 | imgName = "sketch-" + hex.EncodeToString(h[:6]) |
| 644 | |
| 645 | var curImgInitFilesHash string |
| 646 | if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil { |
| 647 | if strings.Contains(string(out), "No such object") { |
| 648 | // Image does not exist, continue and build it. |
| 649 | curImgInitFilesHash = "" |
| 650 | } else { |
| 651 | return "", fmt.Errorf("docker inspect failed: %s, %v", out, err) |
| 652 | } |
| 653 | } else { |
| 654 | m := map[string]string{} |
| 655 | if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil { |
| 656 | return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err) |
| 657 | } |
| 658 | curImgInitFilesHash = m["sketch_context"] |
| 659 | } |
| 660 | |
| 661 | candidates, err := findRepoDockerfiles(cwd, gitRoot) |
| 662 | if err != nil { |
| 663 | return "", fmt.Errorf("find dockerfile: %w", err) |
| 664 | } |
| 665 | |
| 666 | var initFiles map[string]string |
| 667 | var dockerfilePath string |
| David Crawshaw | ff2df6a | 2025-05-12 14:45:29 -0700 | [diff] [blame] | 668 | var generatedDockerfile string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 669 | |
| 670 | // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool. |
| 671 | if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" { |
| 672 | dockerfilePath = candidates[0] |
| 673 | contents, err := os.ReadFile(dockerfilePath) |
| 674 | if err != nil { |
| 675 | return "", err |
| 676 | } |
| 677 | fmt.Printf("using %s as dev env\n", candidates[0]) |
| 678 | if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 679 | return imgName, nil |
| 680 | } |
| 681 | } else { |
| 682 | initFiles, err = readInitFiles(os.DirFS(gitRoot)) |
| 683 | if err != nil { |
| 684 | return "", err |
| 685 | } |
| 686 | subPathWorkingDir, err := filepath.Rel(gitRoot, cwd) |
| 687 | if err != nil { |
| 688 | return "", err |
| 689 | } |
| 690 | initFileHash := hashInitFiles(initFiles) |
| 691 | if curImgInitFilesHash == initFileHash && !forceRebuild { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 692 | return imgName, nil |
| 693 | } |
| 694 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 695 | if model == "gemini" { |
| 696 | if strings.HasSuffix(modelURL, "/gemmsgs") { |
| 697 | // Horrible hack! Switch back to anthropic for container building. |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 698 | // 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] | 699 | modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1) |
| 700 | } else { |
| 701 | return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini") |
| 702 | } |
| 703 | } |
| 704 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 705 | start := time.Now() |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 706 | srv := &ant.Service{ |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 707 | URL: modelURL, |
| 708 | APIKey: modelAPIKey, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 709 | HTTPC: http.DefaultClient, |
| 710 | } |
| Pokey Rule | c31e296 | 2025-05-13 10:53:33 +0000 | [diff] [blame] | 711 | generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 712 | if err != nil { |
| 713 | return "", fmt.Errorf("create dockerfile: %w", err) |
| 714 | } |
| Josh Bleecher Snyder | 7c58b02 | 2025-05-14 17:30:39 +0000 | [diff] [blame] | 715 | // Create a unique temporary directory for the Dockerfile |
| 716 | tmpDir, err := os.MkdirTemp("", "sketch-docker-*") |
| 717 | if err != nil { |
| 718 | return "", fmt.Errorf("failed to create temporary directory: %w", err) |
| 719 | } |
| 720 | dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile) |
| David Crawshaw | ff2df6a | 2025-05-12 14:45:29 -0700 | [diff] [blame] | 721 | if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 722 | return "", err |
| 723 | } |
| Josh Bleecher Snyder | 7c58b02 | 2025-05-14 17:30:39 +0000 | [diff] [blame] | 724 | // Remove the temporary directory and all contents when done |
| 725 | defer os.RemoveAll(tmpDir) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 726 | |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 727 | if verbose { |
| David Crawshaw | ff2df6a | 2025-05-12 14:45:29 -0700 | [diff] [blame] | 728 | 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] | 729 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 730 | } |
| 731 | |
| 732 | var gitUserEmail, gitUserName string |
| 733 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil { |
| 734 | return "", fmt.Errorf("git config: %s: %v", out, err) |
| 735 | } else { |
| 736 | gitUserEmail = strings.TrimSpace(string(out)) |
| 737 | } |
| 738 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil { |
| 739 | return "", fmt.Errorf("git config: %s: %v", out, err) |
| 740 | } else { |
| 741 | gitUserName = strings.TrimSpace(string(out)) |
| 742 | } |
| 743 | |
| 744 | start := time.Now() |
| 745 | cmd := exec.CommandContext(ctx, |
| 746 | "docker", "build", |
| 747 | "-t", imgName, |
| 748 | "-f", dockerfilePath, |
| 749 | "--build-arg", "GIT_USER_EMAIL="+gitUserEmail, |
| 750 | "--build-arg", "GIT_USER_NAME="+gitUserName, |
| David Crawshaw | 31f1524 | 2025-05-06 16:03:49 -0700 | [diff] [blame] | 751 | ".", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 752 | ) |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 753 | cmd.Dir = gitRoot |
| David Crawshaw | 31f1524 | 2025-05-06 16:03:49 -0700 | [diff] [blame] | 754 | // We print the docker build output whether or not the user |
| 755 | // has selected --verbose. Building an image takes a while |
| 756 | // and this gives good context. |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 757 | cmd.Stdout = os.Stdout |
| 758 | cmd.Stderr = os.Stderr |
| 759 | 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] | 760 | |
| 761 | err = run(ctx, "docker build", cmd) |
| 762 | if err != nil { |
| David Crawshaw | ff2df6a | 2025-05-12 14:45:29 -0700 | [diff] [blame] | 763 | var msg string |
| 764 | if generatedDockerfile != "" { |
| 765 | if !verbose { |
| 766 | fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1)) |
| 767 | } |
| 768 | msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.") |
| 769 | } |
| 770 | return "", fmt.Errorf("docker build failed: %v%s", err, msg) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 771 | } |
| 772 | fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond)) |
| 773 | return imgName, nil |
| 774 | } |
| 775 | |
| 776 | func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) { |
| 777 | files, err := findDirDockerfiles(cwd) |
| 778 | if err != nil { |
| 779 | return nil, err |
| 780 | } |
| 781 | if len(files) > 0 { |
| 782 | return files, nil |
| 783 | } |
| 784 | |
| 785 | path := cwd |
| 786 | for path != gitRoot { |
| 787 | path = filepath.Dir(path) |
| 788 | files, err := findDirDockerfiles(path) |
| 789 | if err != nil { |
| 790 | return nil, err |
| 791 | } |
| 792 | if len(files) > 0 { |
| 793 | return files, nil |
| 794 | } |
| 795 | } |
| 796 | return files, nil |
| 797 | } |
| 798 | |
| 799 | // findDirDockerfiles finds all "Dockerfile*" files in a directory. |
| 800 | func findDirDockerfiles(root string) (res []string, err error) { |
| 801 | err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error { |
| 802 | if err != nil { |
| 803 | return err |
| 804 | } |
| 805 | if info.IsDir() && root != path { |
| 806 | return filepath.SkipDir |
| 807 | } |
| 808 | name := strings.ToLower(info.Name()) |
| 809 | if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") { |
| 810 | res = append(res, path) |
| 811 | } |
| 812 | return nil |
| 813 | }) |
| 814 | if err != nil { |
| 815 | return nil, err |
| 816 | } |
| 817 | return res, nil |
| 818 | } |
| 819 | |
| 820 | func findGitRoot(ctx context.Context, path string) (string, error) { |
| 821 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir") |
| 822 | cmd.Dir = path |
| 823 | out, err := cmd.CombinedOutput() |
| 824 | if err != nil { |
| 825 | if strings.Contains(string(out), "not a git repository") { |
| 826 | return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo. |
| 827 | Consider one of the following options: |
| 828 | - cd to a different dir that is already part of a git repo first, or |
| 829 | - to create a new git repo from this directory (%s), run this command: |
| 830 | |
| 831 | git init . && git commit --allow-empty -m "initial commit" |
| 832 | |
| 833 | and try running sketch again. |
| 834 | `, path, path) |
| 835 | } |
| 836 | return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err) |
| 837 | } |
| 838 | gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path |
| 839 | absGitDir := filepath.Join(path, gitDir) |
| 840 | return filepath.Dir(absGitDir), err |
| 841 | } |
| 842 | |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 843 | // getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker |
| 844 | // from git config using the sketch.envfwd multi-valued key. |
| 845 | func getEnvForwardingFromGitConfig(ctx context.Context) []string { |
| 846 | outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput() |
| 847 | out := string(outb) |
| 848 | if err != nil { |
| 849 | if strings.Contains(out, "key does not exist") { |
| 850 | return nil |
| 851 | } |
| 852 | slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out) |
| 853 | return nil |
| 854 | } |
| 855 | |
| 856 | var envVars []string |
| 857 | for envVar := range strings.Lines(out) { |
| 858 | envVar = strings.TrimSpace(envVar) |
| 859 | if envVar == "" { |
| 860 | continue |
| 861 | } |
| 862 | envVars = append(envVars, envVar+"="+os.Getenv(envVar)) |
| 863 | } |
| 864 | return envVars |
| 865 | } |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 866 | |
| 867 | // parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings. |
| 868 | // It handles quoted arguments and escaped characters. |
| 869 | // |
| 870 | // Examples: |
| 871 | // |
| 872 | // --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"] |
| 873 | // --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"] |
| 874 | // --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""] |
| 875 | func parseDockerArgs(args string) []string { |
| 876 | if args = strings.TrimSpace(args); args == "" { |
| 877 | return []string{} |
| 878 | } |
| 879 | |
| 880 | var result []string |
| 881 | var current strings.Builder |
| 882 | inQuotes := false |
| 883 | escapeNext := false |
| 884 | quoteChar := rune(0) |
| 885 | |
| 886 | for _, char := range args { |
| 887 | if escapeNext { |
| 888 | current.WriteRune(char) |
| 889 | escapeNext = false |
| 890 | continue |
| 891 | } |
| 892 | |
| 893 | if char == '\\' { |
| 894 | escapeNext = true |
| 895 | continue |
| 896 | } |
| 897 | |
| 898 | if char == '"' || char == '\'' { |
| 899 | if !inQuotes { |
| 900 | inQuotes = true |
| 901 | quoteChar = char |
| 902 | continue |
| 903 | } else if char == quoteChar { |
| 904 | inQuotes = false |
| 905 | quoteChar = rune(0) |
| 906 | continue |
| 907 | } |
| 908 | // Non-matching quote character inside quotes |
| 909 | current.WriteRune(char) |
| 910 | continue |
| 911 | } |
| 912 | |
| 913 | // Space outside of quotes is an argument separator |
| 914 | if char == ' ' && !inQuotes { |
| 915 | if current.Len() > 0 { |
| 916 | result = append(result, current.String()) |
| 917 | current.Reset() |
| 918 | } |
| 919 | continue |
| 920 | } |
| 921 | |
| 922 | current.WriteRune(char) |
| 923 | } |
| 924 | |
| 925 | // Add the last argument if there is one |
| 926 | if current.Len() > 0 { |
| 927 | result = append(result, current.String()) |
| 928 | } |
| 929 | |
| 930 | return result |
| 931 | } |