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