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