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