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