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