| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 1 | // Package dockerimg |
| 2 | package dockerimg |
| 3 | |
| 4 | import ( |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 5 | "archive/tar" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 6 | "bytes" |
| 7 | "context" |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 8 | "crypto/rand" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 9 | "crypto/sha256" |
| 10 | "encoding/hex" |
| 11 | "encoding/json" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "log/slog" |
| 15 | "net" |
| 16 | "net/http" |
| 17 | "os" |
| 18 | "os/exec" |
| 19 | "path/filepath" |
| 20 | "runtime" |
| 21 | "strings" |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 22 | "sync/atomic" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 23 | "time" |
| 24 | |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 25 | "golang.org/x/crypto/ssh" |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 26 | "sketch.dev/browser" |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 27 | "sketch.dev/embedded" |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 28 | "sketch.dev/loop/server" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 29 | "sketch.dev/skribe" |
| 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 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 70 | // BaseImage is the base Docker image to use for layering the repo |
| 71 | BaseImage string |
| 72 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 73 | // Host directory to copy container logs into, if not set to "" |
| 74 | ContainerLogDest string |
| 75 | |
| 76 | // Path to pre-built linux sketch binary, or build a new one if set to "" |
| 77 | SketchBinaryLinux string |
| 78 | |
| 79 | // Sketch client public key. |
| 80 | SketchPubKey string |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 81 | |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 82 | // Host port for the container's ssh server |
| 83 | SSHPort int |
| 84 | |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 85 | // Outside information to pass to the container |
| 86 | OutsideHostname string |
| 87 | OutsideOS string |
| 88 | OutsideWorkingDir string |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 89 | |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 90 | // If true, exit after the first turn |
| 91 | OneShot bool |
| 92 | |
| 93 | // Initial prompt |
| 94 | Prompt string |
| Philip Zeyliger | 1b47aa2 | 2025-04-28 19:25:38 +0000 | [diff] [blame] | 95 | |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 96 | // Verbose enables verbose output |
| 97 | Verbose bool |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 98 | |
| 99 | // DockerArgs are additional arguments to pass to the docker create command |
| 100 | DockerArgs string |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 101 | |
| Josh Bleecher Snyder | ac761c9 | 2025-05-16 18:58:45 +0000 | [diff] [blame] | 102 | // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container |
| 103 | Mounts []string |
| 104 | |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 105 | // ExperimentFlag contains the experimental features to enable |
| 106 | ExperimentFlag string |
| Philip Zeyliger | 613c0f5 | 2025-05-15 16:36:22 -0700 | [diff] [blame] | 107 | |
| 108 | // TermUI enables terminal UI |
| 109 | TermUI bool |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 110 | |
| Josh Bleecher Snyder | 33032d3 | 2025-05-30 16:28:21 +0000 | [diff] [blame] | 111 | // Budget configuration |
| Philip Zeyliger | e6c294d | 2025-06-04 16:55:21 +0000 | [diff] [blame] | 112 | MaxDollars float64 |
| Josh Bleecher Snyder | 33032d3 | 2025-05-30 16:28:21 +0000 | [diff] [blame] | 113 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 114 | GitRemoteUrl string |
| 115 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 116 | // Original git origin URL from the host repository |
| 117 | OriginalGitOrigin string |
| 118 | |
| Josh Bleecher Snyder | 664404e | 2025-06-04 21:56:42 +0000 | [diff] [blame] | 119 | // Upstream branch for git work |
| 120 | Upstream string |
| 121 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 122 | // Commit hash to checkout from GetRemoteUrl |
| 123 | Commit string |
| 124 | |
| 125 | // Outtie's HTTP server |
| 126 | OutsideHTTP string |
| Philip Zeyliger | be7802a | 2025-06-04 20:15:25 +0000 | [diff] [blame] | 127 | |
| 128 | // Prefix for git branches created by sketch |
| 129 | BranchPrefix string |
| philip.zeyliger | 6d3de48 | 2025-06-10 19:38:14 -0700 | [diff] [blame] | 130 | |
| 131 | // LinkToGitHub enables GitHub branch linking in UI |
| 132 | LinkToGitHub bool |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 133 | |
| 134 | // SubtraceToken enables running sketch under subtrace.dev (development only) |
| 135 | SubtraceToken string |
| Philip Zeyliger | 194bfa8 | 2025-06-24 06:03:06 -0700 | [diff] [blame] | 136 | |
| 137 | // MCPServers contains MCP server configurations |
| 138 | MCPServers []string |
| Philip Zeyliger | 254c49f | 2025-07-17 17:26:24 -0700 | [diff] [blame] | 139 | |
| 140 | // PassthroughUpstream configures upstream remote for passthrough to innie |
| 141 | PassthroughUpstream bool |
| Josh Bleecher Snyder | e75d0ea | 2025-07-21 23:50:44 +0000 | [diff] [blame] | 142 | |
| Josh Bleecher Snyder | 57afbca | 2025-07-23 13:29:59 -0700 | [diff] [blame] | 143 | // DumpLLM requests dumping of raw communications with LLM services to files |
| 144 | DumpLLM bool |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 145 | } |
| 146 | |
| 147 | // LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it. |
| 148 | // It writes status to stdout. |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 149 | func LaunchContainer(ctx context.Context, config ContainerConfig) error { |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 150 | slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 151 | if _, err := exec.LookPath("docker"); err != nil { |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 152 | if runtime.GOOS == "darwin" { |
| 153 | return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start") |
| 154 | } else { |
| 155 | return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)") |
| 156 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 157 | } |
| 158 | |
| 159 | if out, err := combinedOutput(ctx, "docker", "ps"); err != nil { |
| 160 | // `docker ps` provides a good error message here that can be |
| 161 | // easily chatgpt'ed by users, so send it to the user as-is: |
| 162 | // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? |
| 163 | return fmt.Errorf("docker ps: %s (%w)", out, err) |
| 164 | } |
| 165 | |
| 166 | _, hostPort, err := net.SplitHostPort(config.LocalAddr) |
| 167 | if err != nil { |
| 168 | return err |
| 169 | } |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 170 | // Bail early if sketch was started from a path that isn't in a git repo. |
| 171 | err = requireGitRepo(ctx, config.Path) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 172 | if err != nil { |
| 173 | return err |
| 174 | } |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 175 | |
| 176 | // Best effort attempt to get repo root; fall back to current directory. |
| 177 | gitRoot := config.Path |
| 178 | if root, err := gitRepoRoot(ctx, config.Path); err == nil { |
| 179 | gitRoot = root |
| 180 | } |
| 181 | |
| 182 | // Capture the original git origin URL before we set up the temporary git server |
| 183 | config.OriginalGitOrigin = getOriginalGitOrigin(ctx, gitRoot) |
| 184 | |
| Philip Zeyliger | 254c49f | 2025-07-17 17:26:24 -0700 | [diff] [blame] | 185 | // If we've got an upstream, let's configure |
| 186 | if config.OriginalGitOrigin != "" { |
| 187 | config.PassthroughUpstream = true |
| 188 | } |
| 189 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 190 | imgName, err := findOrBuildDockerImage(ctx, gitRoot, config.BaseImage, config.ForceRebuild, config.Verbose) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 191 | if err != nil { |
| 192 | return err |
| 193 | } |
| 194 | |
| Philip Zeyliger | c72fff5 | 2025-04-29 20:17:54 +0000 | [diff] [blame] | 195 | cntrName := "sketch-" + config.SessionID |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 196 | defer func() { |
| 197 | if config.NoCleanup { |
| 198 | return |
| 199 | } |
| 200 | if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil { |
| 201 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 202 | _ = out |
| 203 | } |
| 204 | if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil { |
| 205 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 206 | _ = out |
| 207 | } |
| 208 | }() |
| 209 | |
| 210 | // errCh receives errors from operations that this function calls in separate goroutines. |
| 211 | errCh := make(chan error) |
| 212 | |
| Josh Bleecher Snyder | 725cfe0 | 2025-07-18 01:31:06 +0000 | [diff] [blame] | 213 | var upstream string |
| 214 | if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil { |
| 215 | slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err) |
| 216 | } else { |
| 217 | upstream = strings.TrimSpace(string(out)) |
| 218 | } |
| 219 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 220 | // Start the git server |
| Josh Bleecher Snyder | 725cfe0 | 2025-07-18 01:31:06 +0000 | [diff] [blame] | 221 | gitSrv, err := newGitServer(gitRoot, config.PassthroughUpstream, upstream) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 222 | if err != nil { |
| 223 | return fmt.Errorf("failed to start git server: %w", err) |
| 224 | } |
| 225 | defer gitSrv.shutdown(ctx) |
| 226 | |
| 227 | go func() { |
| 228 | errCh <- gitSrv.serve(ctx) |
| 229 | }() |
| 230 | |
| philz | 2461320 | 2025-07-15 20:56:21 -0700 | [diff] [blame] | 231 | // Check if we have any commits, and if not, create an empty initial commit |
| 232 | cmd := exec.CommandContext(ctx, "git", "rev-list", "--all", "--count") |
| 233 | countOut, err := cmd.CombinedOutput() |
| 234 | if err != nil { |
| 235 | return fmt.Errorf("git rev-list --all --count: %s: %w", countOut, err) |
| 236 | } |
| 237 | commitCount := strings.TrimSpace(string(countOut)) |
| 238 | if commitCount == "0" { |
| 239 | slog.Info("No commits found, creating empty initial commit") |
| 240 | cmd = exec.CommandContext(ctx, "git", "commit", "--allow-empty", "-m", "Initial empty commit") |
| 241 | if commitOut, err := cmd.CombinedOutput(); err != nil { |
| 242 | return fmt.Errorf("git commit --allow-empty: %s: %w", commitOut, err) |
| 243 | } |
| 244 | } |
| 245 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 246 | // Get the current host git commit |
| 247 | var commit string |
| Philip Zeyliger | a347b17 | 2025-06-04 16:18:57 +0000 | [diff] [blame] | 248 | if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil { |
| 249 | return fmt.Errorf("git rev-parse HEAD: %w", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 250 | } else { |
| 251 | commit = strings.TrimSpace(string(out)) |
| 252 | } |
| Josh Bleecher Snyder | 664404e | 2025-06-04 21:56:42 +0000 | [diff] [blame] | 253 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 254 | if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil { |
| 255 | return fmt.Errorf("git config http.receivepack true: %s: %w", out, err) |
| 256 | } |
| 257 | |
| 258 | relPath, err := filepath.Rel(gitRoot, config.Path) |
| 259 | if err != nil { |
| 260 | return err |
| 261 | } |
| 262 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 263 | config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort) |
| 264 | 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] | 265 | config.Upstream = upstream |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 266 | config.Commit = commit |
| 267 | |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 268 | // Create the sketch container, copy over linux sketch |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 269 | if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil { |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 270 | return fmt.Errorf("failed to create docker container: %w", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 271 | } |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 272 | if err := copyEmbeddedLinuxBinaryToContainer(ctx, cntrName); err != nil { |
| 273 | return fmt.Errorf("failed to copy linux binary to container: %w", err) |
| David Crawshaw | 8bff16a | 2025-04-18 01:16:49 -0700 | [diff] [blame] | 274 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 275 | |
| David Crawshaw | 53786ef | 2025-04-24 12:52:51 -0700 | [diff] [blame] | 276 | fmt.Printf("📦 running in container %s\n", cntrName) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 277 | |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 278 | // Setup subtrace if token is provided (development only) - after container creation, before start |
| 279 | if config.SubtraceToken != "" { |
| 280 | fmt.Println("🔍 Setting up subtrace (development only)") |
| 281 | if err := setupSubtraceBeforeStart(ctx, cntrName, config.SubtraceToken); err != nil { |
| 282 | return fmt.Errorf("failed to setup subtrace: %w", err) |
| 283 | } |
| 284 | } |
| 285 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 286 | // Start the sketch container |
| 287 | if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil { |
| 288 | return fmt.Errorf("docker start: %s, %w", out, err) |
| 289 | } |
| 290 | |
| 291 | // Copies structured logs from the container to the host. |
| 292 | copyLogs := func() { |
| 293 | if config.ContainerLogDest == "" { |
| 294 | return |
| 295 | } |
| 296 | out, err := combinedOutput(ctx, "docker", "logs", cntrName) |
| 297 | if err != nil { |
| 298 | fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err) |
| 299 | return |
| 300 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 301 | prefix := []byte("structured logs:") |
| 302 | for line := range bytes.Lines(out) { |
| 303 | rest, ok := bytes.CutPrefix(line, prefix) |
| 304 | if !ok { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 305 | continue |
| 306 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 307 | logFile := string(bytes.TrimSpace(rest)) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 308 | srcPath := fmt.Sprintf("%s:%s", cntrName, logFile) |
| 309 | logFileName := filepath.Base(logFile) |
| 310 | dstPath := filepath.Join(config.ContainerLogDest, logFileName) |
| 311 | _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath) |
| 312 | if err != nil { |
| 313 | fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err) |
| 314 | } |
| 315 | fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath) |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | // NOTE: we want to see what the internal sketch binary prints |
| 320 | // regardless of the setting of the verbosity flag on the external |
| 321 | // binary, so reading "docker logs", which is the stdout/stderr of |
| 322 | // the internal binary is not conditional on the verbose flag. |
| 323 | appendInternalErr := func(err error) error { |
| 324 | if err == nil { |
| 325 | return nil |
| 326 | } |
| 327 | out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName) |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 328 | if logsErr != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 329 | return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr) |
| 330 | } |
| 331 | out = bytes.TrimSpace(out) |
| 332 | if len(out) > 0 { |
| 333 | return fmt.Errorf("docker logs: %s;\n%w", out, err) |
| 334 | } |
| 335 | return err |
| 336 | } |
| 337 | |
| 338 | // Get the sketch server port from the container |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 339 | localAddr, err := getContainerPort(ctx, cntrName, "80") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 340 | if err != nil { |
| 341 | return appendInternalErr(err) |
| 342 | } |
| 343 | |
| Philip Zeyliger | 0044241 | 2025-05-14 11:03:23 -0700 | [diff] [blame] | 344 | if config.Verbose { |
| 345 | fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr) |
| 346 | } |
| 347 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 348 | localSSHAddr, err := getContainerPort(ctx, cntrName, "22") |
| 349 | if err != nil { |
| 350 | return appendInternalErr(err) |
| 351 | } |
| 352 | sshHost, sshPort, err := net.SplitHostPort(localSSHAddr) |
| 353 | if err != nil { |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 354 | 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] | 355 | } |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 356 | |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 357 | var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 358 | |
| banksean | 29d689f | 2025-06-23 15:41:26 +0000 | [diff] [blame] | 359 | cst, err := NewLocalSSHimmer(cntrName, sshHost, sshPort) |
| Sean McCullough | 078e85a | 2025-05-08 17:28:34 -0700 | [diff] [blame] | 360 | if err != nil { |
| 361 | return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err)) |
| 362 | } |
| 363 | |
| 364 | sshErr := CheckSSHReachability(cntrName) |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 365 | sshAvailable := false |
| 366 | sshErrMsg := "" |
| 367 | if sshErr != nil { |
| 368 | fmt.Println(sshErr.Error()) |
| 369 | sshErrMsg = sshErr.Error() |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 370 | // continue - ssh config is not required for the rest of sketch to function locally. |
| 371 | } else { |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 372 | sshAvailable = true |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 373 | // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find: |
| 374 | // 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] | 375 | fmt.Printf(`Connect to this container via any of these methods: |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 376 | 🖥️ ssh %s |
| 377 | 🖥️ code --remote ssh-remote+root@%s /app -n |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 378 | 🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 379 | `, cntrName, cntrName, cntrName) |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 380 | sshUserIdentity = cst.userIdentity |
| 381 | sshServerIdentity = cst.serverIdentity |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 382 | |
| 383 | // Get the Container CA public key for mutual auth |
| 384 | if cst.containerCAPublicKey != nil { |
| 385 | containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey) |
| 386 | fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)") |
| 387 | } |
| 388 | |
| 389 | // Get the host certificate for mutual auth |
| 390 | hostCertificate = cst.hostCertificate |
| 391 | |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 392 | defer func() { |
| 393 | if err := cst.Cleanup(); err != nil { |
| 394 | appendInternalErr(err) |
| 395 | } |
| 396 | }() |
| 397 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 398 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 399 | // Tell the sketch container to Init(), which starts the SSH server |
| 400 | // and checks out the right commit. |
| 401 | // TODO: I'm trying to move as much configuration as possible into the command-line |
| 402 | // arguments to avoid splitting them up. "localAddr" is the only difficult one: |
| 403 | // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't |
| 404 | // get the port Docker chose until after the process starts. The SSH config is |
| 405 | // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg") |
| 406 | // 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] | 407 | go func() { |
| 408 | // TODO: Why is this called in a goroutine? I have found that when I pull this out |
| 409 | // of the goroutine and call it inline, then the terminal UI clears itself and all |
| 410 | // the scrollback (which is not good, but also not fatal). I can't see why it does this |
| 411 | // though, since none of the calls in postContainerInitConfig obviously write to stdout |
| 412 | // or stderr. |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 413 | 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] | 414 | slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error())) |
| 415 | errCh <- appendInternalErr(err) |
| 416 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 417 | |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 418 | // 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] | 419 | ps1URL := "http://" + localAddr |
| 420 | if config.SkabandAddr != "" { |
| 421 | ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID) |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 422 | } |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 423 | if config.OpenBrowser { |
| 424 | browser.Open(ps1URL) |
| 425 | } |
| 426 | gitSrv.ps1URL.Store(&ps1URL) |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 427 | }() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 428 | |
| 429 | go func() { |
| 430 | cmd := exec.CommandContext(ctx, "docker", "attach", cntrName) |
| 431 | cmd.Stdin = os.Stdin |
| 432 | cmd.Stdout = os.Stdout |
| 433 | cmd.Stderr = os.Stderr |
| 434 | errCh <- run(ctx, "docker attach", cmd) |
| 435 | }() |
| 436 | |
| 437 | defer copyLogs() |
| 438 | |
| 439 | for { |
| 440 | select { |
| 441 | case <-ctx.Done(): |
| 442 | return ctx.Err() |
| 443 | case err := <-errCh: |
| 444 | if err != nil { |
| 445 | return appendInternalErr(fmt.Errorf("container process: %w", err)) |
| 446 | } |
| 447 | return nil |
| 448 | } |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) { |
| 453 | cmd := exec.CommandContext(ctx, cmdName, args...) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 454 | start := time.Now() |
| 455 | |
| 456 | out, err := cmd.CombinedOutput() |
| 457 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 458 | 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] | 459 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 460 | 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] | 461 | } |
| 462 | return out, err |
| 463 | } |
| 464 | |
| 465 | func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error { |
| 466 | start := time.Now() |
| 467 | err := cmd.Run() |
| 468 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 469 | 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] | 470 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 471 | 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] | 472 | } |
| 473 | return err |
| 474 | } |
| 475 | |
| 476 | type gitServer struct { |
| 477 | gitLn net.Listener |
| 478 | gitPort string |
| 479 | srv *http.Server |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 480 | pass string |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 481 | ps1URL atomic.Pointer[string] |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 482 | } |
| 483 | |
| 484 | func (gs *gitServer) shutdown(ctx context.Context) { |
| 485 | gs.srv.Shutdown(ctx) |
| 486 | gs.gitLn.Close() |
| 487 | } |
| 488 | |
| 489 | // Serve a git remote from the host for the container to fetch from and push to. |
| 490 | func (gs *gitServer) serve(ctx context.Context) error { |
| 491 | slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git")) |
| 492 | return gs.srv.Serve(gs.gitLn) |
| 493 | } |
| 494 | |
| Josh Bleecher Snyder | 725cfe0 | 2025-07-18 01:31:06 +0000 | [diff] [blame] | 495 | func newGitServer(gitRoot string, configureUpstreamPassthrough bool, upstream string) (*gitServer, error) { |
| Josh Bleecher Snyder | 9f6a998 | 2025-04-22 17:34:15 -0700 | [diff] [blame] | 496 | ret := &gitServer{ |
| 497 | pass: rand.Text(), |
| 498 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 499 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 500 | gitLn, err := net.Listen("tcp4", ":0") |
| 501 | if err != nil { |
| 502 | return nil, fmt.Errorf("git listen: %w", err) |
| 503 | } |
| 504 | ret.gitLn = gitLn |
| 505 | |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 506 | browserC := make(chan bool, 1) // channel of browser open requests |
| 507 | |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 508 | go func() { |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 509 | for range browserC { |
| 510 | browser.Open(*ret.ps1URL.Load()) |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 511 | } |
| 512 | }() |
| 513 | |
| Philip Zeyliger | 254c49f | 2025-07-17 17:26:24 -0700 | [diff] [blame] | 514 | var hooksDir string |
| 515 | if configureUpstreamPassthrough { |
| Josh Bleecher Snyder | 725cfe0 | 2025-07-18 01:31:06 +0000 | [diff] [blame] | 516 | hooksDir, err = setupHooksDir(upstream) |
| Philip Zeyliger | 254c49f | 2025-07-17 17:26:24 -0700 | [diff] [blame] | 517 | if err != nil { |
| 518 | return nil, fmt.Errorf("failed to setup hooks directory: %w", err) |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, hooksDir: hooksDir, pass: []byte(ret.pass), browserC: browserC}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 523 | ret.srv = &srv |
| 524 | |
| 525 | _, gitPort, err := net.SplitHostPort(gitLn.Addr().String()) |
| 526 | if err != nil { |
| 527 | return nil, fmt.Errorf("git port: %w", err) |
| 528 | } |
| 529 | ret.gitPort = gitPort |
| 530 | return ret, nil |
| 531 | } |
| 532 | |
| 533 | 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] | 534 | cmdArgs := []string{ |
| 535 | "create", |
| David Crawshaw | 66cf74e | 2025-05-05 08:48:39 -0700 | [diff] [blame] | 536 | "-i", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 537 | "--name", cntrName, |
| 538 | "-p", hostPort + ":80", // forward container port 80 to a host port |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 539 | "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 540 | } |
| Philip Zeyliger | 3d2eff0 | 2025-05-27 09:30:31 -0700 | [diff] [blame] | 541 | if !(config.OneShot || !config.TermUI) { |
| David Crawshaw | 66cf74e | 2025-05-05 08:48:39 -0700 | [diff] [blame] | 542 | cmdArgs = append(cmdArgs, "-t") |
| 543 | } |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 544 | |
| 545 | for _, envVar := range getEnvForwardingFromGitConfig(ctx) { |
| 546 | cmdArgs = append(cmdArgs, "-e", envVar) |
| 547 | } |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 548 | if config.ModelURL != "" { |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 549 | cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 550 | } |
| 551 | if config.SketchPubKey != "" { |
| 552 | cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey) |
| 553 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 554 | if config.SSHPort > 0 { |
| 555 | cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port |
| 556 | } else { |
| Philip Zeyliger | 87d29ef | 2025-05-16 20:25:28 -0700 | [diff] [blame] | 557 | 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] | 558 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 559 | // colima does this by default, but Linux docker seems to need this set explicitly |
| 560 | cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway") |
| Josh Bleecher Snyder | ac761c9 | 2025-05-16 18:58:45 +0000 | [diff] [blame] | 561 | |
| David Crawshaw | 1bd636c | 2025-06-13 19:56:27 +0000 | [diff] [blame] | 562 | // Add seccomp profile to prevent killing PID 1 (the sketch process itself) |
| 563 | // Write the seccomp profile to cache directory if it doesn't exist |
| 564 | seccompPath, err := ensureSeccompProfile(ctx) |
| 565 | if err != nil { |
| 566 | return fmt.Errorf("failed to create seccomp profile: %w", err) |
| 567 | } |
| 568 | cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath) |
| 569 | |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 570 | // Add subtrace environment variable if token is provided |
| 571 | if config.SubtraceToken != "" { |
| 572 | cmdArgs = append(cmdArgs, "-e", "SUBTRACE_TOKEN="+config.SubtraceToken) |
| 573 | cmdArgs = append(cmdArgs, "-e", "SUBTRACE_HTTP2=1") |
| 574 | } |
| 575 | |
| Josh Bleecher Snyder | ac761c9 | 2025-05-16 18:58:45 +0000 | [diff] [blame] | 576 | // Add volume mounts if specified |
| 577 | for _, mount := range config.Mounts { |
| 578 | if mount != "" { |
| 579 | cmdArgs = append(cmdArgs, "-v", mount) |
| 580 | } |
| 581 | } |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 582 | cmdArgs = append(cmdArgs, imgName) |
| 583 | |
| 584 | // Add command: either [sketch] or [subtrace run -- sketch] |
| 585 | if config.SubtraceToken != "" { |
| 586 | cmdArgs = append(cmdArgs, "/usr/local/bin/subtrace", "run", "--", "/bin/sketch") |
| 587 | } else { |
| 588 | cmdArgs = append(cmdArgs, "/bin/sketch") |
| 589 | } |
| 590 | |
| 591 | // Add all sketch arguments |
| 592 | cmdArgs = append(cmdArgs, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 593 | "-unsafe", |
| 594 | "-addr=:80", |
| 595 | "-session-id="+config.SessionID, |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 596 | "-git-username="+config.GitUsername, |
| 597 | "-git-email="+config.GitEmail, |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 598 | "-outside-hostname="+config.OutsideHostname, |
| 599 | "-outside-os="+config.OutsideOS, |
| 600 | "-outside-working-dir="+config.OutsideWorkingDir, |
| Josh Bleecher Snyder | 33032d3 | 2025-05-30 16:28:21 +0000 | [diff] [blame] | 601 | fmt.Sprintf("-max-dollars=%f", config.MaxDollars), |
| Josh Bleecher Snyder | 3cae7d9 | 2025-04-30 09:54:29 -0700 | [diff] [blame] | 602 | "-open=false", |
| Philip Zeyliger | 613c0f5 | 2025-05-15 16:36:22 -0700 | [diff] [blame] | 603 | "-termui="+fmt.Sprintf("%t", config.TermUI), |
| Philip Zeyliger | cabfa55 | 2025-05-19 16:14:28 -0700 | [diff] [blame] | 604 | "-verbose="+fmt.Sprintf("%t", config.Verbose), |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 605 | "-x="+config.ExperimentFlag, |
| Philip Zeyliger | be7802a | 2025-06-04 20:15:25 +0000 | [diff] [blame] | 606 | "-branch-prefix="+config.BranchPrefix, |
| philip.zeyliger | 6d3de48 | 2025-06-10 19:38:14 -0700 | [diff] [blame] | 607 | "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub), |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 608 | ) |
| philip.zeyliger | 8773e68 | 2025-06-11 21:36:21 -0700 | [diff] [blame] | 609 | // Set SSH connection string based on session ID for SSH Theater |
| 610 | cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID) |
| Josh Bleecher Snyder | a96f9d2 | 2025-07-11 02:47:33 +0000 | [diff] [blame] | 611 | if relPath != "." { |
| 612 | cmdArgs = append(cmdArgs, "-C", relPath) |
| 613 | } |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 614 | if config.Model != "" { |
| 615 | cmdArgs = append(cmdArgs, "-model="+config.Model) |
| 616 | } |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 617 | if config.GitRemoteUrl != "" { |
| 618 | cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl) |
| 619 | if config.Commit == "" { |
| 620 | panic("Commit should have been set when GitRemoteUrl was set") |
| 621 | } |
| 622 | cmdArgs = append(cmdArgs, "-commit="+config.Commit) |
| Josh Bleecher Snyder | 664404e | 2025-06-04 21:56:42 +0000 | [diff] [blame] | 623 | cmdArgs = append(cmdArgs, "-upstream="+config.Upstream) |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 624 | } |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 625 | if config.OriginalGitOrigin != "" { |
| 626 | cmdArgs = append(cmdArgs, "-original-git-origin="+config.OriginalGitOrigin) |
| 627 | } |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 628 | if config.OutsideHTTP != "" { |
| 629 | cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP) |
| 630 | } |
| Josh Bleecher Snyder | e3c2f22 | 2025-05-15 20:54:52 +0000 | [diff] [blame] | 631 | cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr) |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 632 | if config.Prompt != "" { |
| 633 | cmdArgs = append(cmdArgs, "-prompt", config.Prompt) |
| 634 | } |
| 635 | if config.OneShot { |
| 636 | cmdArgs = append(cmdArgs, "-one-shot") |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 637 | } |
| Josh Bleecher Snyder | 9386009 | 2025-07-23 13:24:14 -0700 | [diff] [blame^] | 638 | cmdArgs = append(cmdArgs, "-llm-api-key="+config.ModelAPIKey) |
| Philip Zeyliger | 194bfa8 | 2025-06-24 06:03:06 -0700 | [diff] [blame] | 639 | // Add MCP server configurations |
| 640 | for _, mcpServer := range config.MCPServers { |
| 641 | cmdArgs = append(cmdArgs, "-mcp", mcpServer) |
| 642 | } |
| Philip Zeyliger | 254c49f | 2025-07-17 17:26:24 -0700 | [diff] [blame] | 643 | if config.PassthroughUpstream { |
| 644 | cmdArgs = append(cmdArgs, "-passthrough-upstream") |
| 645 | } |
| Josh Bleecher Snyder | 57afbca | 2025-07-23 13:29:59 -0700 | [diff] [blame] | 646 | if config.DumpLLM { |
| 647 | cmdArgs = append(cmdArgs, "-dump-llm") |
| Josh Bleecher Snyder | e75d0ea | 2025-07-21 23:50:44 +0000 | [diff] [blame] | 648 | } |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 649 | |
| 650 | // Add additional docker arguments if provided |
| 651 | if config.DockerArgs != "" { |
| 652 | // Parse space-separated docker arguments with support for quotes and escaping |
| 653 | args := parseDockerArgs(config.DockerArgs) |
| 654 | // Insert arguments after "create" but before other arguments |
| 655 | for i := len(args) - 1; i >= 0; i-- { |
| 656 | cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...) |
| 657 | } |
| 658 | } |
| 659 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 660 | if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil { |
| 661 | return fmt.Errorf("docker create: %s, %w", out, err) |
| 662 | } |
| 663 | return nil |
| 664 | } |
| 665 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 666 | func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 667 | localAddr := "" |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 668 | if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 669 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 670 | } else { |
| 671 | v4, _, found := strings.Cut(string(out), "\n") |
| 672 | if !found { |
| 673 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 674 | } |
| 675 | localAddr = v4 |
| 676 | if strings.HasPrefix(localAddr, "0.0.0.0") { |
| 677 | localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0") |
| 678 | } |
| 679 | } |
| 680 | return localAddr, nil |
| 681 | } |
| 682 | |
| 683 | // Contact the container and configure it. |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 684 | 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] | 685 | localURL := "http://" + localAddr |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 686 | |
| 687 | initMsg, err := json.Marshal( |
| 688 | server.InitRequest{ |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 689 | HostAddr: localAddr, |
| 690 | SSHAuthorizedKeys: sshAuthorizedKeys, |
| 691 | SSHServerIdentity: sshServerIdentity, |
| 692 | SSHContainerCAKey: sshContainerCAKey, |
| 693 | SSHHostCertificate: sshHostCertificate, |
| 694 | SSHAvailable: sshAvailable, |
| 695 | SSHError: sshError, |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 696 | }) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 697 | if err != nil { |
| 698 | return fmt.Errorf("init msg: %w", err) |
| 699 | } |
| 700 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 701 | // Note: this /init POST is handled in loop/server/loophttp.go: |
| 702 | initMsgByteReader := bytes.NewReader(initMsg) |
| 703 | req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader) |
| 704 | if err != nil { |
| 705 | return err |
| 706 | } |
| 707 | |
| 708 | var res *http.Response |
| 709 | for i := 0; ; i++ { |
| 710 | time.Sleep(100 * time.Millisecond) |
| 711 | // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes. |
| 712 | initMsgByteReader.Reset(initMsg) |
| 713 | res, err = http.DefaultClient.Do(req) |
| 714 | if err != nil { |
| David Crawshaw | 99231ba | 2025-05-03 10:48:26 -0700 | [diff] [blame] | 715 | if i < 100 { |
| 716 | if i%10 == 0 { |
| 717 | slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error())) |
| 718 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 719 | continue |
| 720 | } |
| 721 | return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err) |
| 722 | } |
| 723 | break |
| 724 | } |
| 725 | resBytes, _ := io.ReadAll(res.Body) |
| 726 | if res.StatusCode != http.StatusOK { |
| 727 | return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes) |
| 728 | } |
| 729 | return nil |
| 730 | } |
| 731 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 732 | func findOrBuildDockerImage(ctx context.Context, gitRoot, baseImage string, forceRebuild, verbose bool) (imgName string, err error) { |
| 733 | // Default to the published sketch image if no base image is specified |
| 734 | if baseImage == "" { |
| 735 | imageTag := dockerfileBaseHash() |
| 736 | baseImage = fmt.Sprintf("%s:%s", dockerImgName, imageTag) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 737 | } |
| 738 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 739 | // Ensure the base image exists locally, pull if necessary |
| 740 | if err := ensureBaseImageExists(ctx, baseImage); err != nil { |
| 741 | return "", fmt.Errorf("failed to ensure base image %s exists: %w", baseImage, err) |
| 742 | } |
| 743 | |
| 744 | // Get the base image container ID for caching |
| 745 | baseImageID, err := getDockerImageID(ctx, baseImage) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 746 | if err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 747 | return "", fmt.Errorf("failed to get base image ID for %s: %w", baseImage, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 748 | } |
| 749 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 750 | // Create a cache key based on base image ID and working directory |
| 751 | // Docker naming conventions restrict you to 20 characters per path component |
| 752 | // and only allow lowercase letters, digits, underscores, and dashes, so encoding |
| 753 | // the hash and the repo directory is sadly a bit of a non-starter. |
| 754 | cacheKey := createCacheKey(baseImageID, gitRoot) |
| 755 | imgName = "sketch-" + cacheKey |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 756 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 757 | // Check if the cached image exists and is up to date |
| 758 | if !forceRebuild { |
| 759 | if exists, err := dockerImageExists(ctx, imgName); err != nil { |
| 760 | return "", fmt.Errorf("failed to check if image exists: %w", err) |
| 761 | } else if exists { |
| 762 | if verbose { |
| 763 | fmt.Printf("using cached image %s\n", imgName) |
| Kilian Lackhove | 23772f4 | 2025-06-18 20:28:58 +0200 | [diff] [blame] | 764 | } |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 765 | return imgName, nil |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 766 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 767 | } |
| 768 | |
| Josh Bleecher Snyder | d117143 | 2025-07-18 15:04:05 +0000 | [diff] [blame] | 769 | // Explain a bit what's happening, to help orient and de-FUD new users. |
| 770 | fmt.Println() |
| 771 | fmt.Println("┌──────────────────────────────────────────────────┐") |
| 772 | fmt.Println("│ Building Docker image (one-time) │") |
| 773 | fmt.Println("│ │") |
| 774 | fmt.Println("│ • Built and run locally │") |
| 775 | fmt.Println("│ • Packages your git repo into isolated container │") |
| 776 | fmt.Println("│ • Custom images: https://sketch.dev/docs/docker │") |
| 777 | fmt.Println("│ • Rebuild: sketch -rebuild │") |
| 778 | fmt.Println("└──────────────────────────────────────────────────┘") |
| 779 | fmt.Println() |
| 780 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 781 | if err := buildLayeredImage(ctx, imgName, baseImage, gitRoot, verbose); err != nil { |
| 782 | return "", fmt.Errorf("failed to build layered image: %w", err) |
| 783 | } |
| 784 | |
| 785 | return imgName, nil |
| 786 | } |
| 787 | |
| 788 | // ensureBaseImageExists checks if the base image exists locally and pulls it if not |
| 789 | func ensureBaseImageExists(ctx context.Context, imageName string) error { |
| 790 | exists, err := dockerImageExists(ctx, imageName) |
| 791 | if err != nil { |
| 792 | return fmt.Errorf("failed to check if image exists: %w", err) |
| 793 | } |
| 794 | |
| 795 | if !exists { |
| 796 | fmt.Printf("🐋 pulling base image %s...\n", imageName) |
| 797 | if out, err := combinedOutput(ctx, "docker", "pull", imageName); err != nil { |
| 798 | return fmt.Errorf("docker pull %s failed: %s: %w", imageName, out, err) |
| 799 | } |
| 800 | fmt.Printf("✅ successfully pulled %s\n", imageName) |
| 801 | } |
| 802 | |
| 803 | return nil |
| 804 | } |
| 805 | |
| 806 | // getDockerImageID gets the container ID for a Docker image |
| 807 | func getDockerImageID(ctx context.Context, imageName string) (string, error) { |
| 808 | out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{.Id}}", imageName) |
| 809 | if err != nil { |
| 810 | return "", err |
| 811 | } |
| 812 | return strings.TrimSpace(string(out)), nil |
| 813 | } |
| 814 | |
| 815 | // createCacheKey creates a cache key from base image ID and working directory |
| 816 | func createCacheKey(baseImageID, gitRoot string) string { |
| 817 | h := sha256.New() |
| 818 | h.Write([]byte(baseImageID)) |
| 819 | h.Write([]byte(gitRoot)) |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 820 | // one-time cache-busting for the transition from copying git repos to only copying git objects |
| 821 | h.Write([]byte("git-objects")) |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 822 | return hex.EncodeToString(h.Sum(nil))[:12] // Use first 12 chars for shorter name |
| 823 | } |
| 824 | |
| 825 | // dockerImageExists checks if a Docker image exists locally |
| 826 | func dockerImageExists(ctx context.Context, imageName string) (bool, error) { |
| 827 | out, err := combinedOutput(ctx, "docker", "inspect", imageName) |
| 828 | if err != nil { |
| 829 | if strings.Contains(strings.ToLower(string(out)), "no such object") || |
| 830 | strings.Contains(strings.ToLower(string(out)), "no such image") { |
| 831 | return false, nil |
| 832 | } |
| 833 | return false, err |
| 834 | } |
| 835 | return true, nil |
| 836 | } |
| 837 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 838 | // buildLayeredImage builds a new Docker image by layering the repo on top of the base image. |
| 839 | // |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 840 | // TODO: git config stuff could be environment variables at runtime for email and username. |
| 841 | // The git docs seem to say that http.postBuffer is a bug in our git proxy more than a thing |
| 842 | // that's needed, but we haven't found the bug yet! |
| Philip Zeyliger | 882b1d1 | 2025-07-02 20:04:08 -0700 | [diff] [blame] | 843 | // |
| 844 | // TODO: There is a caching tension. A base image is great for tools (like, some version |
| 845 | // of Go). Then you want a git repo, which is much faster to incrementally fetch rather |
| 846 | // than cloning every time. Then you want some build artifacts, like perhaps the |
| 847 | // "go mod download" cache, or the "go build" cache or the "npm install" cache. |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 848 | // The implementation here copies the git objects into the base image. |
| 849 | // That enables fast clones into the container, because most of the git objects are already there. |
| 850 | // It also avoids copying uncommitted changes, configs/hooks, etc. |
| Josh Bleecher Snyder | fa424f5 | 2025-07-11 18:43:55 +0000 | [diff] [blame] | 851 | // We also set up fake temporary Go module(s) so we can run "go mod download". |
| 852 | // TODO: maybe 'go list ./...' and then do a build as well to populate the build cache. |
| 853 | // TODO: 'npm install', etc? We have the rails for it. |
| Josh Bleecher Snyder | 369f262 | 2025-07-15 00:02:59 +0000 | [diff] [blame] | 854 | // If /app/.git already exists, we fetch from the existing repo instead of cloning. |
| 855 | // This lets advanced users arrange their git repo exactly as they desire. |
| Philip Zeyliger | 882b1d1 | 2025-07-02 20:04:08 -0700 | [diff] [blame] | 856 | // Note that buildx has some support for conditional COPY, but without buildx, which |
| 857 | // we can't reliably depend on, we have to run the base image to inspect its file system, |
| 858 | // and then we can decide what to do. |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 859 | // |
| 860 | // We may in the future want to enable people to bring along uncommitted changes to tracked files. |
| 861 | // To do that, we would run `git stash create` in outie at launch time, treat HEAD as the base commit, |
| 862 | // and add in the stash commit as a new commit atop it. |
| 863 | // That would accurately model the base commit as well as the uncommitted changes. |
| 864 | // (This wouldn't happen here, but at agent/container initialization time.) |
| 865 | // |
| 866 | // repoPath is the current working directory where sketch is being run from. |
| 867 | func buildLayeredImage(ctx context.Context, imgName, baseImage, gitRoot string, verbose bool) error { |
| Josh Bleecher Snyder | fa424f5 | 2025-07-11 18:43:55 +0000 | [diff] [blame] | 868 | goModules, err := collectGoModules(ctx, gitRoot) |
| 869 | if err != nil { |
| 870 | return fmt.Errorf("failed to collect go modules: %w", err) |
| 871 | } |
| 872 | |
| 873 | buf := new(strings.Builder) |
| 874 | line := func(msg string, args ...any) { |
| 875 | fmt.Fprintf(buf, msg+"\n", args...) |
| 876 | } |
| 877 | |
| 878 | line("FROM %s", baseImage) |
| 879 | line("COPY . /git-ref") |
| 880 | |
| 881 | for _, module := range goModules { |
| 882 | line("RUN mkdir -p /go-module") |
| 883 | line("RUN git --git-dir=/git-ref --work-tree=/go-module cat-file blob %s > /go-module/go.mod", module.modSHA) |
| 884 | if module.sumSHA != "" { |
| 885 | line("RUN git --git-dir=/git-ref --work-tree=/go-module cat-file blob %s > /go-module/go.sum", module.sumSHA) |
| 886 | } |
| 887 | // drop any replaced modules |
| 888 | line("RUN cd /go-module && go mod edit -json | jq -r '.Replace? // [] | .[] | .Old.Path' | xargs -r -I{} go mod edit -dropreplace={} -droprequire={}") |
| 889 | // grab what’s left, best effort only to avoid breaking on (say) private modules |
| 890 | line("RUN cd /go-module && go mod download || true") |
| 891 | line("RUN rm -rf /go-module") |
| 892 | } |
| 893 | |
| 894 | line("WORKDIR /app") |
| 895 | line(`CMD ["/bin/sketch"]`) |
| 896 | dockerfileContent := buf.String() |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 897 | |
| 898 | // Create a temporary directory for the Dockerfile |
| 899 | tmpDir, err := os.MkdirTemp("", "sketch-docker-*") |
| 900 | if err != nil { |
| 901 | return fmt.Errorf("failed to create temporary directory: %w", err) |
| 902 | } |
| 903 | defer os.RemoveAll(tmpDir) |
| 904 | |
| 905 | dockerfilePath := filepath.Join(tmpDir, "Dockerfile") |
| 906 | if err := os.WriteFile(dockerfilePath, []byte(dockerfileContent), 0o666); err != nil { |
| 907 | return fmt.Errorf("failed to write Dockerfile: %w", err) |
| 908 | } |
| 909 | |
| 910 | // Get git user info |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 911 | var gitUserEmail, gitUserName string |
| 912 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 913 | 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] | 914 | } else { |
| 915 | gitUserEmail = strings.TrimSpace(string(out)) |
| 916 | } |
| 917 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 918 | 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] | 919 | } else { |
| 920 | gitUserName = strings.TrimSpace(string(out)) |
| 921 | } |
| 922 | |
| 923 | start := time.Now() |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 924 | cmdArgs := []string{ |
| 925 | "build", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 926 | "-t", imgName, |
| 927 | "-f", dockerfilePath, |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 928 | "--build-arg", "GIT_USER_EMAIL=" + gitUserEmail, |
| 929 | "--build-arg", "GIT_USER_NAME=" + gitUserName, |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 930 | ".", |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 931 | } |
| 932 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 933 | commonDir, err := gitCommonDir(ctx, gitRoot) |
| 934 | if err != nil { |
| 935 | return fmt.Errorf("failed to get git common dir: %w", err) |
| 936 | } |
| 937 | |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 938 | cmd := exec.CommandContext(ctx, "docker", cmdArgs...) |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 939 | cmd.Dir = commonDir |
| David Crawshaw | 31f1524 | 2025-05-06 16:03:49 -0700 | [diff] [blame] | 940 | // We print the docker build output whether or not the user |
| 941 | // has selected --verbose. Building an image takes a while |
| 942 | // and this gives good context. |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 943 | cmd.Stdout = os.Stdout |
| 944 | cmd.Stderr = os.Stderr |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 945 | fmt.Printf("🏗️ building docker image %s from base %s...\n", imgName, baseImage) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 946 | |
| 947 | err = run(ctx, "docker build", cmd) |
| 948 | if err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 949 | return fmt.Errorf("docker build failed: %v", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 950 | } |
| 951 | fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond)) |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 952 | return nil |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 953 | } |
| 954 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 955 | // requireGitRepo confirms that path is within a git repository. |
| 956 | func requireGitRepo(ctx context.Context, path string) error { |
| 957 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-dir") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 958 | cmd.Dir = path |
| 959 | out, err := cmd.CombinedOutput() |
| 960 | if err != nil { |
| 961 | if strings.Contains(string(out), "not a git repository") { |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 962 | return fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo. |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 963 | Consider one of the following options: |
| 964 | - cd to a different dir that is already part of a git repo first, or |
| 965 | - to create a new git repo from this directory (%s), run this command: |
| 966 | |
| 967 | git init . && git commit --allow-empty -m "initial commit" |
| 968 | |
| 969 | and try running sketch again. |
| 970 | `, path, path) |
| 971 | } |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 972 | return fmt.Errorf("git rev-parse --git-dir: %s: %w", out, err) |
| 973 | } |
| 974 | return nil |
| 975 | } |
| 976 | |
| 977 | // gitRepoRoot attempts to find the git repository root directory. |
| 978 | // Returns an error if not in a git repository or if it's a bare repository. |
| 979 | // This is used to calculate relative paths for preserving user's working directory context. |
| 980 | func gitRepoRoot(ctx context.Context, path string) (string, error) { |
| 981 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel") |
| 982 | cmd.Dir = path |
| 983 | out, err := cmd.CombinedOutput() |
| 984 | if err != nil { |
| Marc-Antoine Ruel | 467c396 | 2025-06-29 13:32:59 -0400 | [diff] [blame] | 985 | return "", fmt.Errorf("git rev-parse --show-toplevel: %s: %w", out, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 986 | } |
| Marc-Antoine Ruel | 467c396 | 2025-06-29 13:32:59 -0400 | [diff] [blame] | 987 | // The returned path is absolute. |
| 988 | return strings.TrimSpace(string(out)), nil |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 989 | } |
| 990 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 991 | // gitCommonDir finds the git common directory for path. |
| 992 | func gitCommonDir(ctx context.Context, path string) (string, error) { |
| 993 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir") |
| 994 | cmd.Dir = path |
| 995 | out, err := cmd.CombinedOutput() |
| 996 | if err != nil { |
| 997 | return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err) |
| 998 | } |
| 999 | gitCommonDir := strings.TrimSpace(string(out)) |
| 1000 | if !filepath.IsAbs(gitCommonDir) { |
| 1001 | gitCommonDir = filepath.Join(path, gitCommonDir) |
| 1002 | } |
| 1003 | return gitCommonDir, nil |
| 1004 | } |
| 1005 | |
| Josh Bleecher Snyder | fa424f5 | 2025-07-11 18:43:55 +0000 | [diff] [blame] | 1006 | // goModuleInfo represents a Go module with its file paths and blob SHAs |
| 1007 | type goModuleInfo struct { |
| 1008 | // modPath is the path to the go.mod file, for debugging |
| 1009 | modPath string |
| 1010 | // modSHA is the git blob SHA of the go.mod file |
| 1011 | modSHA string |
| 1012 | // sumSHA is the git blob SHA of the go.sum file, empty if no go.sum exists |
| 1013 | sumSHA string |
| 1014 | } |
| 1015 | |
| 1016 | // collectGoModules returns all go.mod files in the git repository with their blob SHAs. |
| 1017 | func collectGoModules(ctx context.Context, gitRoot string) ([]goModuleInfo, error) { |
| 1018 | cmd := exec.CommandContext(ctx, "git", "ls-files", "-z", "*.mod") |
| 1019 | cmd.Dir = gitRoot |
| 1020 | out, err := cmd.CombinedOutput() |
| 1021 | if err != nil { |
| 1022 | return nil, fmt.Errorf("git ls-files -z *.mod: %s: %w", out, err) |
| 1023 | } |
| 1024 | |
| 1025 | modFiles := strings.Split(string(out), "\x00") |
| 1026 | var modules []goModuleInfo |
| 1027 | for _, file := range modFiles { |
| 1028 | if filepath.Base(file) != "go.mod" { |
| 1029 | continue |
| 1030 | } |
| 1031 | |
| 1032 | modSHA, err := getGitBlobSHA(ctx, gitRoot, file) |
| 1033 | if err != nil { |
| 1034 | return nil, fmt.Errorf("failed to get blob SHA for %s: %w", file, err) |
| 1035 | } |
| 1036 | |
| 1037 | // If corresponding go.sum exists, get its SHA |
| 1038 | sumFile := filepath.Join(filepath.Dir(file), "go.sum") |
| 1039 | sumSHA, _ := getGitBlobSHA(ctx, gitRoot, sumFile) // best effort |
| 1040 | |
| 1041 | modules = append(modules, goModuleInfo{ |
| 1042 | modPath: file, |
| 1043 | modSHA: modSHA, |
| 1044 | sumSHA: sumSHA, |
| 1045 | }) |
| 1046 | } |
| 1047 | |
| 1048 | return modules, nil |
| 1049 | } |
| 1050 | |
| 1051 | // getGitBlobSHA returns the git blob SHA for a file at HEAD |
| 1052 | func getGitBlobSHA(ctx context.Context, gitRoot, filePath string) (string, error) { |
| 1053 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "HEAD:"+filePath) |
| 1054 | cmd.Dir = gitRoot |
| 1055 | out, err := cmd.CombinedOutput() |
| 1056 | if err != nil { |
| 1057 | return "", fmt.Errorf("git rev-parse HEAD:%s: %s: %w", filePath, out, err) |
| 1058 | } |
| 1059 | return strings.TrimSpace(string(out)), nil |
| 1060 | } |
| 1061 | |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 1062 | // getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker |
| 1063 | // from git config using the sketch.envfwd multi-valued key. |
| 1064 | func getEnvForwardingFromGitConfig(ctx context.Context) []string { |
| 1065 | outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput() |
| 1066 | out := string(outb) |
| 1067 | if err != nil { |
| 1068 | if strings.Contains(out, "key does not exist") { |
| 1069 | return nil |
| 1070 | } |
| 1071 | slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out) |
| 1072 | return nil |
| 1073 | } |
| 1074 | |
| 1075 | var envVars []string |
| 1076 | for envVar := range strings.Lines(out) { |
| 1077 | envVar = strings.TrimSpace(envVar) |
| 1078 | if envVar == "" { |
| 1079 | continue |
| 1080 | } |
| 1081 | envVars = append(envVars, envVar+"="+os.Getenv(envVar)) |
| 1082 | } |
| 1083 | return envVars |
| 1084 | } |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 1085 | |
| Josh Bleecher Snyder | 784d5bd | 2025-07-11 00:09:30 +0000 | [diff] [blame] | 1086 | // getOriginalGitOrigin returns the URL of the git remote 'origin' if it exists in the given directory |
| 1087 | func getOriginalGitOrigin(ctx context.Context, dir string) string { |
| 1088 | cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url") |
| 1089 | cmd.Dir = dir |
| 1090 | out, err := cmd.Output() |
| 1091 | if err != nil { |
| 1092 | return "" |
| 1093 | } |
| 1094 | return strings.TrimSpace(string(out)) |
| 1095 | } |
| 1096 | |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 1097 | // parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings. |
| 1098 | // It handles quoted arguments and escaped characters. |
| 1099 | // |
| 1100 | // Examples: |
| 1101 | // |
| 1102 | // --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"] |
| 1103 | // --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"] |
| 1104 | // --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""] |
| 1105 | func parseDockerArgs(args string) []string { |
| 1106 | if args = strings.TrimSpace(args); args == "" { |
| 1107 | return []string{} |
| 1108 | } |
| 1109 | |
| 1110 | var result []string |
| 1111 | var current strings.Builder |
| 1112 | inQuotes := false |
| 1113 | escapeNext := false |
| 1114 | quoteChar := rune(0) |
| 1115 | |
| 1116 | for _, char := range args { |
| 1117 | if escapeNext { |
| 1118 | current.WriteRune(char) |
| 1119 | escapeNext = false |
| 1120 | continue |
| 1121 | } |
| 1122 | |
| 1123 | if char == '\\' { |
| 1124 | escapeNext = true |
| 1125 | continue |
| 1126 | } |
| 1127 | |
| 1128 | if char == '"' || char == '\'' { |
| 1129 | if !inQuotes { |
| 1130 | inQuotes = true |
| 1131 | quoteChar = char |
| 1132 | continue |
| 1133 | } else if char == quoteChar { |
| 1134 | inQuotes = false |
| 1135 | quoteChar = rune(0) |
| 1136 | continue |
| 1137 | } |
| 1138 | // Non-matching quote character inside quotes |
| 1139 | current.WriteRune(char) |
| 1140 | continue |
| 1141 | } |
| 1142 | |
| 1143 | // Space outside of quotes is an argument separator |
| 1144 | if char == ' ' && !inQuotes { |
| 1145 | if current.Len() > 0 { |
| 1146 | result = append(result, current.String()) |
| 1147 | current.Reset() |
| 1148 | } |
| 1149 | continue |
| 1150 | } |
| 1151 | |
| 1152 | current.WriteRune(char) |
| 1153 | } |
| 1154 | |
| 1155 | // Add the last argument if there is one |
| 1156 | if current.Len() > 0 { |
| 1157 | result = append(result, current.String()) |
| 1158 | } |
| 1159 | |
| 1160 | return result |
| 1161 | } |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1162 | |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1163 | // copyEmbeddedLinuxBinaryToContainer copies the embedded linux binary to the container |
| 1164 | func copyEmbeddedLinuxBinaryToContainer(ctx context.Context, containerName string) error { |
| Josh Bleecher Snyder | 5ae245b | 2025-07-08 22:00:24 +0000 | [diff] [blame] | 1165 | out, err := combinedOutput(ctx, "docker", "version", "--format", "{{.Server.Arch}}") |
| 1166 | if err != nil { |
| 1167 | return fmt.Errorf("failed to detect Docker server architecture: %s: %w", out, err) |
| 1168 | } |
| 1169 | arch := strings.TrimSpace(string(out)) |
| 1170 | |
| 1171 | bin := embedded.LinuxBinary(arch) |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1172 | if bin == nil { |
| Josh Bleecher Snyder | 5ae245b | 2025-07-08 22:00:24 +0000 | [diff] [blame] | 1173 | return fmt.Errorf("no embedded linux binary for architecture %q", arch) |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1174 | } |
| 1175 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1176 | // Stream a tarball to docker cp. |
| 1177 | pr, pw := io.Pipe() |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1178 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1179 | errCh := make(chan error, 1) |
| 1180 | go func() { |
| 1181 | defer pw.Close() |
| 1182 | tw := tar.NewWriter(pw) |
| 1183 | |
| 1184 | hdr := &tar.Header{ |
| 1185 | Name: "bin/sketch", // final path inside the container |
| 1186 | Mode: 0o700, |
| 1187 | Size: int64(len(bin)), |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1188 | } |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1189 | if err := tw.WriteHeader(hdr); err != nil { |
| 1190 | errCh <- fmt.Errorf("failed to write tar header: %w", err) |
| 1191 | return |
| 1192 | } |
| 1193 | if _, err := tw.Write(bin); err != nil { |
| 1194 | errCh <- fmt.Errorf("failed to write binary to tar: %w", err) |
| 1195 | return |
| 1196 | } |
| 1197 | if err := tw.Close(); err != nil { |
| 1198 | errCh <- fmt.Errorf("failed to close tar writer: %w", err) |
| 1199 | return |
| 1200 | } |
| 1201 | errCh <- nil |
| 1202 | }() |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1203 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1204 | cmd := exec.CommandContext(ctx, "docker", "cp", "-", containerName+":/") |
| 1205 | cmd.Stdin = pr |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1206 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1207 | out, cmdErr := cmd.CombinedOutput() |
| 1208 | |
| 1209 | if tarErr := <-errCh; tarErr != nil { |
| 1210 | return tarErr |
| 1211 | } |
| 1212 | if cmdErr != nil { |
| 1213 | return fmt.Errorf("docker cp failed: %s: %w", out, cmdErr) |
| 1214 | } |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1215 | return nil |
| 1216 | } |
| 1217 | |
| David Crawshaw | 1bd636c | 2025-06-13 19:56:27 +0000 | [diff] [blame] | 1218 | const seccompProfile = `{ |
| 1219 | "defaultAction": "SCMP_ACT_ALLOW", |
| 1220 | "syscalls": [ |
| 1221 | { |
| 1222 | "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"], |
| 1223 | "action": "SCMP_ACT_ERRNO", |
| 1224 | "args": [ |
| 1225 | { |
| 1226 | "index": 0, |
| 1227 | "value": 1, |
| 1228 | "op": "SCMP_CMP_EQ" |
| 1229 | } |
| 1230 | ] |
| 1231 | } |
| 1232 | ] |
| 1233 | }` |
| 1234 | |
| 1235 | // ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist. |
| 1236 | func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) { |
| 1237 | homeDir, err := os.UserHomeDir() |
| 1238 | if err != nil { |
| 1239 | return "", fmt.Errorf("failed to get home directory: %w", err) |
| 1240 | } |
| 1241 | cacheDir := filepath.Join(homeDir, ".cache", "sketch") |
| 1242 | if err := os.MkdirAll(cacheDir, 0o755); err != nil { |
| 1243 | return "", fmt.Errorf("failed to create cache directory: %w", err) |
| 1244 | } |
| 1245 | seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json") |
| 1246 | |
| 1247 | curBytes, err := os.ReadFile(seccompPath) |
| 1248 | if err != nil && !os.IsNotExist(err) { |
| 1249 | return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err) |
| 1250 | } |
| 1251 | if string(curBytes) == seccompProfile { |
| 1252 | return seccompPath, nil // File already exists and matches the expected profile |
| 1253 | } |
| 1254 | |
| 1255 | if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil { |
| 1256 | return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err) |
| 1257 | } |
| 1258 | slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath) |
| 1259 | return seccompPath, nil |
| 1260 | } |