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