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