blob: 16865cfd38441a7fa7bbac8f5f3f806f280d7d79 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package dockerimg
2package dockerimg
3
4import (
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00005 "archive/tar"
Earl Lee2e463fb2025-04-17 11:22:22 -07006 "bytes"
7 "context"
Philip Zeyliger5e227dd2025-04-21 15:55:29 -07008 "crypto/rand"
Earl Lee2e463fb2025-04-17 11:22:22 -07009 "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 Snyder99570462025-05-05 10:26:14 -070022 "sync/atomic"
Earl Lee2e463fb2025-04-17 11:22:22 -070023 "time"
24
Sean McCullough7013e9e2025-05-14 02:03:58 +000025 "golang.org/x/crypto/ssh"
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000026 "sketch.dev/browser"
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -070027 "sketch.dev/embedded"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070028 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070029 "sketch.dev/skribe"
30)
31
32// ContainerConfig holds all configuration for launching a container
33type 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 Crawshaw5a7b3692025-05-05 16:49:15 -070043 // Model is the name of the LLM model to use.
44 Model string
Earl Lee2e463fb2025-04-17 11:22:22 -070045
David Crawshaw5a7b3692025-05-05 16:49:15 -070046 // 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 Lee2e463fb2025-04-17 11:22:22 -070051
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 Zeyliger983b58a2025-07-02 19:42:08 -070070 // BaseImage is the base Docker image to use for layering the repo
71 BaseImage string
72
Earl Lee2e463fb2025-04-17 11:22:22 -070073 // 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 Zeyligerd1402952025-04-23 03:54:37 +000081
Sean McCulloughbaa2b592025-04-23 10:40:08 -070082 // Host port for the container's ssh server
83 SSHPort int
84
Philip Zeyliger18532b22025-04-23 21:11:46 +000085 // Outside information to pass to the container
86 OutsideHostname string
87 OutsideOS string
88 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070089
Pokey Rule0dcebe12025-04-28 14:51:04 +010090 // If true, exit after the first turn
91 OneShot bool
92
93 // Initial prompt
94 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000095
David Crawshawb5f6a002025-05-05 08:27:16 -070096 // Verbose enables verbose output
97 Verbose bool
Philip Zeyliger1dc21372025-05-05 19:54:44 +000098
99 // DockerArgs are additional arguments to pass to the docker create command
100 DockerArgs string
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000101
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000102 // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container
103 Mounts []string
104
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000105 // ExperimentFlag contains the experimental features to enable
106 ExperimentFlag string
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700107
108 // TermUI enables terminal UI
109 TermUI bool
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700110
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000111 // Budget configuration
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000112 MaxDollars float64
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000113
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700114 GitRemoteUrl string
115
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000116 // Original git origin URL from the host repository
117 OriginalGitOrigin string
118
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000119 // Upstream branch for git work
120 Upstream string
121
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700122 // Commit hash to checkout from GetRemoteUrl
123 Commit string
124
125 // Outtie's HTTP server
126 OutsideHTTP string
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000127
128 // Prefix for git branches created by sketch
129 BranchPrefix string
philip.zeyliger6d3de482025-06-10 19:38:14 -0700130
131 // LinkToGitHub enables GitHub branch linking in UI
132 LinkToGitHub bool
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700133
134 // SubtraceToken enables running sketch under subtrace.dev (development only)
135 SubtraceToken string
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700136
137 // MCPServers contains MCP server configurations
138 MCPServers []string
Earl Lee2e463fb2025-04-17 11:22:22 -0700139}
140
141// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
142// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700143func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700144 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700145 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700146 if runtime.GOOS == "darwin" {
147 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
148 } else {
149 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
150 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700151 }
152
153 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
154 // `docker ps` provides a good error message here that can be
155 // easily chatgpt'ed by users, so send it to the user as-is:
156 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
157 return fmt.Errorf("docker ps: %s (%w)", out, err)
158 }
159
160 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
161 if err != nil {
162 return err
163 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000164 // Bail early if sketch was started from a path that isn't in a git repo.
165 err = requireGitRepo(ctx, config.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700166 if err != nil {
167 return err
168 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000169
170 // Best effort attempt to get repo root; fall back to current directory.
171 gitRoot := config.Path
172 if root, err := gitRepoRoot(ctx, config.Path); err == nil {
173 gitRoot = root
174 }
175
176 // Capture the original git origin URL before we set up the temporary git server
177 config.OriginalGitOrigin = getOriginalGitOrigin(ctx, gitRoot)
178
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700179 imgName, err := findOrBuildDockerImage(ctx, gitRoot, config.BaseImage, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700180 if err != nil {
181 return err
182 }
183
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000184 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700185 defer func() {
186 if config.NoCleanup {
187 return
188 }
189 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
190 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
191 _ = out
192 }
193 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
194 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
195 _ = out
196 }
197 }()
198
199 // errCh receives errors from operations that this function calls in separate goroutines.
200 errCh := make(chan error)
201
202 // Start the git server
203 gitSrv, err := newGitServer(gitRoot)
204 if err != nil {
205 return fmt.Errorf("failed to start git server: %w", err)
206 }
207 defer gitSrv.shutdown(ctx)
208
209 go func() {
210 errCh <- gitSrv.serve(ctx)
211 }()
212
philz24613202025-07-15 20:56:21 -0700213 // Check if we have any commits, and if not, create an empty initial commit
214 cmd := exec.CommandContext(ctx, "git", "rev-list", "--all", "--count")
215 countOut, err := cmd.CombinedOutput()
216 if err != nil {
217 return fmt.Errorf("git rev-list --all --count: %s: %w", countOut, err)
218 }
219 commitCount := strings.TrimSpace(string(countOut))
220 if commitCount == "0" {
221 slog.Info("No commits found, creating empty initial commit")
222 cmd = exec.CommandContext(ctx, "git", "commit", "--allow-empty", "-m", "Initial empty commit")
223 if commitOut, err := cmd.CombinedOutput(); err != nil {
224 return fmt.Errorf("git commit --allow-empty: %s: %w", commitOut, err)
225 }
226 }
227
Earl Lee2e463fb2025-04-17 11:22:22 -0700228 // Get the current host git commit
229 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000230 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
231 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700232 } else {
233 commit = strings.TrimSpace(string(out))
234 }
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000235
236 var upstream string
237 if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil {
238 slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err)
239 } else {
240 upstream = strings.TrimSpace(string(out))
241 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700242 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
243 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
244 }
245
246 relPath, err := filepath.Rel(gitRoot, config.Path)
247 if err != nil {
248 return err
249 }
250
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700251 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
252 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000253 config.Upstream = upstream
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700254 config.Commit = commit
255
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700256 // Create the sketch container, copy over linux sketch
Earl Lee2e463fb2025-04-17 11:22:22 -0700257 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000258 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700259 }
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700260 if err := copyEmbeddedLinuxBinaryToContainer(ctx, cntrName); err != nil {
261 return fmt.Errorf("failed to copy linux binary to container: %w", err)
David Crawshaw8bff16a2025-04-18 01:16:49 -0700262 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700263
David Crawshaw53786ef2025-04-24 12:52:51 -0700264 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700265
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700266 // Setup subtrace if token is provided (development only) - after container creation, before start
267 if config.SubtraceToken != "" {
268 fmt.Println("🔍 Setting up subtrace (development only)")
269 if err := setupSubtraceBeforeStart(ctx, cntrName, config.SubtraceToken); err != nil {
270 return fmt.Errorf("failed to setup subtrace: %w", err)
271 }
272 }
273
Earl Lee2e463fb2025-04-17 11:22:22 -0700274 // Start the sketch container
275 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
276 return fmt.Errorf("docker start: %s, %w", out, err)
277 }
278
279 // Copies structured logs from the container to the host.
280 copyLogs := func() {
281 if config.ContainerLogDest == "" {
282 return
283 }
284 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
285 if err != nil {
286 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
287 return
288 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700289 prefix := []byte("structured logs:")
290 for line := range bytes.Lines(out) {
291 rest, ok := bytes.CutPrefix(line, prefix)
292 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700293 continue
294 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700295 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700296 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
297 logFileName := filepath.Base(logFile)
298 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
299 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
300 if err != nil {
301 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
302 }
303 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
304 }
305 }
306
307 // NOTE: we want to see what the internal sketch binary prints
308 // regardless of the setting of the verbosity flag on the external
309 // binary, so reading "docker logs", which is the stdout/stderr of
310 // the internal binary is not conditional on the verbose flag.
311 appendInternalErr := func(err error) error {
312 if err == nil {
313 return nil
314 }
315 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000316 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700317 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
318 }
319 out = bytes.TrimSpace(out)
320 if len(out) > 0 {
321 return fmt.Errorf("docker logs: %s;\n%w", out, err)
322 }
323 return err
324 }
325
326 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700327 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700328 if err != nil {
329 return appendInternalErr(err)
330 }
331
Philip Zeyliger00442412025-05-14 11:03:23 -0700332 if config.Verbose {
333 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
334 }
335
Sean McCulloughae3480f2025-04-23 15:28:20 -0700336 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
337 if err != nil {
338 return appendInternalErr(err)
339 }
340 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
341 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700342 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700343 }
Sean McCullough4854c652025-04-24 18:37:02 -0700344
Sean McCullough7013e9e2025-05-14 02:03:58 +0000345 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700346
banksean29d689f2025-06-23 15:41:26 +0000347 cst, err := NewLocalSSHimmer(cntrName, sshHost, sshPort)
Sean McCullough078e85a2025-05-08 17:28:34 -0700348 if err != nil {
349 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
350 }
351
352 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700353 sshAvailable := false
354 sshErrMsg := ""
355 if sshErr != nil {
356 fmt.Println(sshErr.Error())
357 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700358 // continue - ssh config is not required for the rest of sketch to function locally.
359 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700360 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700361 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
362 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700363 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700364🖥️ ssh %s
365🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700366🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700367`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700368 sshUserIdentity = cst.userIdentity
369 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000370
371 // Get the Container CA public key for mutual auth
372 if cst.containerCAPublicKey != nil {
373 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
374 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
375 }
376
377 // Get the host certificate for mutual auth
378 hostCertificate = cst.hostCertificate
379
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700380 defer func() {
381 if err := cst.Cleanup(); err != nil {
382 appendInternalErr(err)
383 }
384 }()
385 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700386
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700387 // Tell the sketch container to Init(), which starts the SSH server
388 // and checks out the right commit.
389 // TODO: I'm trying to move as much configuration as possible into the command-line
390 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
391 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
392 // get the port Docker chose until after the process starts. The SSH config is
393 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
394 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700395 go func() {
396 // TODO: Why is this called in a goroutine? I have found that when I pull this out
397 // of the goroutine and call it inline, then the terminal UI clears itself and all
398 // the scrollback (which is not good, but also not fatal). I can't see why it does this
399 // though, since none of the calls in postContainerInitConfig obviously write to stdout
400 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700401 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700402 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
403 errCh <- appendInternalErr(err)
404 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700405
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700406 // We open the browser after the init config because the above waits for the web server to be serving.
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700407 ps1URL := "http://" + localAddr
408 if config.SkabandAddr != "" {
409 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700410 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700411 if config.OpenBrowser {
412 browser.Open(ps1URL)
413 }
414 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700415 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700416
417 go func() {
418 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
419 cmd.Stdin = os.Stdin
420 cmd.Stdout = os.Stdout
421 cmd.Stderr = os.Stderr
422 errCh <- run(ctx, "docker attach", cmd)
423 }()
424
425 defer copyLogs()
426
427 for {
428 select {
429 case <-ctx.Done():
430 return ctx.Err()
431 case err := <-errCh:
432 if err != nil {
433 return appendInternalErr(fmt.Errorf("container process: %w", err))
434 }
435 return nil
436 }
437 }
438}
439
440func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
441 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700442 start := time.Now()
443
444 out, err := cmd.CombinedOutput()
445 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700446 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 Lee2e463fb2025-04-17 11:22:22 -0700447 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700448 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 Lee2e463fb2025-04-17 11:22:22 -0700449 }
450 return out, err
451}
452
453func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
454 start := time.Now()
455 err := cmd.Run()
456 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700457 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 Lee2e463fb2025-04-17 11:22:22 -0700458 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700459 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 Lee2e463fb2025-04-17 11:22:22 -0700460 }
461 return err
462}
463
464type gitServer struct {
465 gitLn net.Listener
466 gitPort string
467 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700468 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700469 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700470}
471
472func (gs *gitServer) shutdown(ctx context.Context) {
473 gs.srv.Shutdown(ctx)
474 gs.gitLn.Close()
475}
476
477// Serve a git remote from the host for the container to fetch from and push to.
478func (gs *gitServer) serve(ctx context.Context) error {
479 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
480 return gs.srv.Serve(gs.gitLn)
481}
482
483func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700484 ret := &gitServer{
485 pass: rand.Text(),
486 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700487
Earl Lee2e463fb2025-04-17 11:22:22 -0700488 gitLn, err := net.Listen("tcp4", ":0")
489 if err != nil {
490 return nil, fmt.Errorf("git listen: %w", err)
491 }
492 ret.gitLn = gitLn
493
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700494 browserC := make(chan bool, 1) // channel of browser open requests
495
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000496 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700497 for range browserC {
498 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000499 }
500 }()
501
502 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700503 ret.srv = &srv
504
505 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
506 if err != nil {
507 return nil, fmt.Errorf("git port: %w", err)
508 }
509 ret.gitPort = gitPort
510 return ret, nil
511}
512
513func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700514 cmdArgs := []string{
515 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700516 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700517 "--name", cntrName,
518 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700519 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700520 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700521 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700522 cmdArgs = append(cmdArgs, "-t")
523 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000524
525 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
526 cmdArgs = append(cmdArgs, "-e", envVar)
527 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700528 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700529 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700530 }
531 if config.SketchPubKey != "" {
532 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
533 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700534 if config.SSHPort > 0 {
535 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
536 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700537 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700538 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700539 // colima does this by default, but Linux docker seems to need this set explicitly
540 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000541
David Crawshaw1bd636c2025-06-13 19:56:27 +0000542 // Add seccomp profile to prevent killing PID 1 (the sketch process itself)
543 // Write the seccomp profile to cache directory if it doesn't exist
544 seccompPath, err := ensureSeccompProfile(ctx)
545 if err != nil {
546 return fmt.Errorf("failed to create seccomp profile: %w", err)
547 }
548 cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath)
549
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700550 // Add subtrace environment variable if token is provided
551 if config.SubtraceToken != "" {
552 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_TOKEN="+config.SubtraceToken)
553 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_HTTP2=1")
554 }
555
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000556 // Add volume mounts if specified
557 for _, mount := range config.Mounts {
558 if mount != "" {
559 cmdArgs = append(cmdArgs, "-v", mount)
560 }
561 }
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700562 cmdArgs = append(cmdArgs, imgName)
563
564 // Add command: either [sketch] or [subtrace run -- sketch]
565 if config.SubtraceToken != "" {
566 cmdArgs = append(cmdArgs, "/usr/local/bin/subtrace", "run", "--", "/bin/sketch")
567 } else {
568 cmdArgs = append(cmdArgs, "/bin/sketch")
569 }
570
571 // Add all sketch arguments
572 cmdArgs = append(cmdArgs,
Earl Lee2e463fb2025-04-17 11:22:22 -0700573 "-unsafe",
574 "-addr=:80",
575 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000576 "-git-username="+config.GitUsername,
577 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000578 "-outside-hostname="+config.OutsideHostname,
579 "-outside-os="+config.OutsideOS,
580 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000581 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700582 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700583 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700584 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000585 "-x="+config.ExperimentFlag,
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000586 "-branch-prefix="+config.BranchPrefix,
philip.zeyliger6d3de482025-06-10 19:38:14 -0700587 "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub),
Earl Lee2e463fb2025-04-17 11:22:22 -0700588 )
philip.zeyliger8773e682025-06-11 21:36:21 -0700589 // Set SSH connection string based on session ID for SSH Theater
590 cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID)
Josh Bleecher Snydera96f9d22025-07-11 02:47:33 +0000591 if relPath != "." {
592 cmdArgs = append(cmdArgs, "-C", relPath)
593 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700594 if config.Model != "" {
595 cmdArgs = append(cmdArgs, "-model="+config.Model)
596 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700597 if config.GitRemoteUrl != "" {
598 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
599 if config.Commit == "" {
600 panic("Commit should have been set when GitRemoteUrl was set")
601 }
602 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000603 cmdArgs = append(cmdArgs, "-upstream="+config.Upstream)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700604 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000605 if config.OriginalGitOrigin != "" {
606 cmdArgs = append(cmdArgs, "-original-git-origin="+config.OriginalGitOrigin)
607 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700608 if config.OutsideHTTP != "" {
609 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
610 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000611 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100612 if config.Prompt != "" {
613 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
614 }
615 if config.OneShot {
616 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700617 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000618 if config.ModelURL == "" {
619 // Forward ANTHROPIC_API_KEY for direct use.
620 // TODO: have outtie run an http proxy?
621 // TODO: select and forward the relevant API key based on the model
622 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
623 }
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700624 // Add MCP server configurations
625 for _, mcpServer := range config.MCPServers {
626 cmdArgs = append(cmdArgs, "-mcp", mcpServer)
627 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000628
629 // Add additional docker arguments if provided
630 if config.DockerArgs != "" {
631 // Parse space-separated docker arguments with support for quotes and escaping
632 args := parseDockerArgs(config.DockerArgs)
633 // Insert arguments after "create" but before other arguments
634 for i := len(args) - 1; i >= 0; i-- {
635 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
636 }
637 }
638
Earl Lee2e463fb2025-04-17 11:22:22 -0700639 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
640 return fmt.Errorf("docker create: %s, %w", out, err)
641 }
642 return nil
643}
644
Sean McCulloughae3480f2025-04-23 15:28:20 -0700645func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700646 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700647 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700648 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
649 } else {
650 v4, _, found := strings.Cut(string(out), "\n")
651 if !found {
652 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
653 }
654 localAddr = v4
655 if strings.HasPrefix(localAddr, "0.0.0.0") {
656 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
657 }
658 }
659 return localAddr, nil
660}
661
662// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700663func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700664 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700665
666 initMsg, err := json.Marshal(
667 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000668 HostAddr: localAddr,
669 SSHAuthorizedKeys: sshAuthorizedKeys,
670 SSHServerIdentity: sshServerIdentity,
671 SSHContainerCAKey: sshContainerCAKey,
672 SSHHostCertificate: sshHostCertificate,
673 SSHAvailable: sshAvailable,
674 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700675 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700676 if err != nil {
677 return fmt.Errorf("init msg: %w", err)
678 }
679
Earl Lee2e463fb2025-04-17 11:22:22 -0700680 // Note: this /init POST is handled in loop/server/loophttp.go:
681 initMsgByteReader := bytes.NewReader(initMsg)
682 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
683 if err != nil {
684 return err
685 }
686
687 var res *http.Response
688 for i := 0; ; i++ {
689 time.Sleep(100 * time.Millisecond)
690 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
691 initMsgByteReader.Reset(initMsg)
692 res, err = http.DefaultClient.Do(req)
693 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700694 if i < 100 {
695 if i%10 == 0 {
696 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
697 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700698 continue
699 }
700 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
701 }
702 break
703 }
704 resBytes, _ := io.ReadAll(res.Body)
705 if res.StatusCode != http.StatusOK {
706 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
707 }
708 return nil
709}
710
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700711func findOrBuildDockerImage(ctx context.Context, gitRoot, baseImage string, forceRebuild, verbose bool) (imgName string, err error) {
712 // Default to the published sketch image if no base image is specified
713 if baseImage == "" {
714 imageTag := dockerfileBaseHash()
715 baseImage = fmt.Sprintf("%s:%s", dockerImgName, imageTag)
Earl Lee2e463fb2025-04-17 11:22:22 -0700716 }
717
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700718 // Ensure the base image exists locally, pull if necessary
719 if err := ensureBaseImageExists(ctx, baseImage); err != nil {
720 return "", fmt.Errorf("failed to ensure base image %s exists: %w", baseImage, err)
721 }
722
723 // Get the base image container ID for caching
724 baseImageID, err := getDockerImageID(ctx, baseImage)
Earl Lee2e463fb2025-04-17 11:22:22 -0700725 if err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700726 return "", fmt.Errorf("failed to get base image ID for %s: %w", baseImage, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700727 }
728
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700729 // Create a cache key based on base image ID and working directory
730 // Docker naming conventions restrict you to 20 characters per path component
731 // and only allow lowercase letters, digits, underscores, and dashes, so encoding
732 // the hash and the repo directory is sadly a bit of a non-starter.
733 cacheKey := createCacheKey(baseImageID, gitRoot)
734 imgName = "sketch-" + cacheKey
Earl Lee2e463fb2025-04-17 11:22:22 -0700735
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700736 // Check if the cached image exists and is up to date
737 if !forceRebuild {
738 if exists, err := dockerImageExists(ctx, imgName); err != nil {
739 return "", fmt.Errorf("failed to check if image exists: %w", err)
740 } else if exists {
741 if verbose {
742 fmt.Printf("using cached image %s\n", imgName)
Kilian Lackhove23772f42025-06-18 20:28:58 +0200743 }
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700744 return imgName, nil
David Crawshawb5f6a002025-05-05 08:27:16 -0700745 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700746 }
747
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700748 // Build the layered image
749 if err := buildLayeredImage(ctx, imgName, baseImage, gitRoot, verbose); err != nil {
750 return "", fmt.Errorf("failed to build layered image: %w", err)
751 }
752
753 return imgName, nil
754}
755
756// ensureBaseImageExists checks if the base image exists locally and pulls it if not
757func ensureBaseImageExists(ctx context.Context, imageName string) error {
758 exists, err := dockerImageExists(ctx, imageName)
759 if err != nil {
760 return fmt.Errorf("failed to check if image exists: %w", err)
761 }
762
763 if !exists {
764 fmt.Printf("🐋 pulling base image %s...\n", imageName)
765 if out, err := combinedOutput(ctx, "docker", "pull", imageName); err != nil {
766 return fmt.Errorf("docker pull %s failed: %s: %w", imageName, out, err)
767 }
768 fmt.Printf("✅ successfully pulled %s\n", imageName)
769 }
770
771 return nil
772}
773
774// getDockerImageID gets the container ID for a Docker image
775func getDockerImageID(ctx context.Context, imageName string) (string, error) {
776 out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{.Id}}", imageName)
777 if err != nil {
778 return "", err
779 }
780 return strings.TrimSpace(string(out)), nil
781}
782
783// createCacheKey creates a cache key from base image ID and working directory
784func createCacheKey(baseImageID, gitRoot string) string {
785 h := sha256.New()
786 h.Write([]byte(baseImageID))
787 h.Write([]byte(gitRoot))
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000788 // one-time cache-busting for the transition from copying git repos to only copying git objects
789 h.Write([]byte("git-objects"))
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700790 return hex.EncodeToString(h.Sum(nil))[:12] // Use first 12 chars for shorter name
791}
792
793// dockerImageExists checks if a Docker image exists locally
794func dockerImageExists(ctx context.Context, imageName string) (bool, error) {
795 out, err := combinedOutput(ctx, "docker", "inspect", imageName)
796 if err != nil {
797 if strings.Contains(strings.ToLower(string(out)), "no such object") ||
798 strings.Contains(strings.ToLower(string(out)), "no such image") {
799 return false, nil
800 }
801 return false, err
802 }
803 return true, nil
804}
805
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000806// buildLayeredImage builds a new Docker image by layering the repo on top of the base image.
807//
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700808// TODO: git config stuff could be environment variables at runtime for email and username.
809// The git docs seem to say that http.postBuffer is a bug in our git proxy more than a thing
810// that's needed, but we haven't found the bug yet!
Philip Zeyliger882b1d12025-07-02 20:04:08 -0700811//
812// TODO: There is a caching tension. A base image is great for tools (like, some version
813// of Go). Then you want a git repo, which is much faster to incrementally fetch rather
814// than cloning every time. Then you want some build artifacts, like perhaps the
815// "go mod download" cache, or the "go build" cache or the "npm install" cache.
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000816// The implementation here copies the git objects into the base image.
817// That enables fast clones into the container, because most of the git objects are already there.
818// It also avoids copying uncommitted changes, configs/hooks, etc.
Josh Bleecher Snyderfa424f52025-07-11 18:43:55 +0000819// We also set up fake temporary Go module(s) so we can run "go mod download".
820// TODO: maybe 'go list ./...' and then do a build as well to populate the build cache.
821// TODO: 'npm install', etc? We have the rails for it.
Josh Bleecher Snyder369f2622025-07-15 00:02:59 +0000822// If /app/.git already exists, we fetch from the existing repo instead of cloning.
823// This lets advanced users arrange their git repo exactly as they desire.
Philip Zeyliger882b1d12025-07-02 20:04:08 -0700824// Note that buildx has some support for conditional COPY, but without buildx, which
825// we can't reliably depend on, we have to run the base image to inspect its file system,
826// and then we can decide what to do.
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000827//
828// We may in the future want to enable people to bring along uncommitted changes to tracked files.
829// To do that, we would run `git stash create` in outie at launch time, treat HEAD as the base commit,
830// and add in the stash commit as a new commit atop it.
831// That would accurately model the base commit as well as the uncommitted changes.
832// (This wouldn't happen here, but at agent/container initialization time.)
833//
834// repoPath is the current working directory where sketch is being run from.
835func buildLayeredImage(ctx context.Context, imgName, baseImage, gitRoot string, verbose bool) error {
Josh Bleecher Snyderfa424f52025-07-11 18:43:55 +0000836 goModules, err := collectGoModules(ctx, gitRoot)
837 if err != nil {
838 return fmt.Errorf("failed to collect go modules: %w", err)
839 }
840
841 buf := new(strings.Builder)
842 line := func(msg string, args ...any) {
843 fmt.Fprintf(buf, msg+"\n", args...)
844 }
845
846 line("FROM %s", baseImage)
847 line("COPY . /git-ref")
848
849 for _, module := range goModules {
850 line("RUN mkdir -p /go-module")
851 line("RUN git --git-dir=/git-ref --work-tree=/go-module cat-file blob %s > /go-module/go.mod", module.modSHA)
852 if module.sumSHA != "" {
853 line("RUN git --git-dir=/git-ref --work-tree=/go-module cat-file blob %s > /go-module/go.sum", module.sumSHA)
854 }
855 // drop any replaced modules
856 line("RUN cd /go-module && go mod edit -json | jq -r '.Replace? // [] | .[] | .Old.Path' | xargs -r -I{} go mod edit -dropreplace={} -droprequire={}")
857 // grab what’s left, best effort only to avoid breaking on (say) private modules
858 line("RUN cd /go-module && go mod download || true")
859 line("RUN rm -rf /go-module")
860 }
861
862 line("WORKDIR /app")
863 line(`CMD ["/bin/sketch"]`)
864 dockerfileContent := buf.String()
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700865
866 // Create a temporary directory for the Dockerfile
867 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
868 if err != nil {
869 return fmt.Errorf("failed to create temporary directory: %w", err)
870 }
871 defer os.RemoveAll(tmpDir)
872
873 dockerfilePath := filepath.Join(tmpDir, "Dockerfile")
874 if err := os.WriteFile(dockerfilePath, []byte(dockerfileContent), 0o666); err != nil {
875 return fmt.Errorf("failed to write Dockerfile: %w", err)
876 }
877
878 // Get git user info
Earl Lee2e463fb2025-04-17 11:22:22 -0700879 var gitUserEmail, gitUserName string
880 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700881 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 Lee2e463fb2025-04-17 11:22:22 -0700882 } else {
883 gitUserEmail = strings.TrimSpace(string(out))
884 }
885 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700886 return fmt.Errorf("git user.name is not set. Please run 'git config --global user.name \"Your Name\"' to set your name")
Earl Lee2e463fb2025-04-17 11:22:22 -0700887 } else {
888 gitUserName = strings.TrimSpace(string(out))
889 }
890
891 start := time.Now()
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700892 cmdArgs := []string{
893 "build",
Earl Lee2e463fb2025-04-17 11:22:22 -0700894 "-t", imgName,
895 "-f", dockerfilePath,
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700896 "--build-arg", "GIT_USER_EMAIL=" + gitUserEmail,
897 "--build-arg", "GIT_USER_NAME=" + gitUserName,
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700898 ".",
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700899 }
900
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000901 commonDir, err := gitCommonDir(ctx, gitRoot)
902 if err != nil {
903 return fmt.Errorf("failed to get git common dir: %w", err)
904 }
905
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700906 cmd := exec.CommandContext(ctx, "docker", cmdArgs...)
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000907 cmd.Dir = commonDir
David Crawshaw31f15242025-05-06 16:03:49 -0700908 // We print the docker build output whether or not the user
909 // has selected --verbose. Building an image takes a while
910 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700911 cmd.Stdout = os.Stdout
912 cmd.Stderr = os.Stderr
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700913 fmt.Printf("🏗️ building docker image %s from base %s...\n", imgName, baseImage)
Earl Lee2e463fb2025-04-17 11:22:22 -0700914
915 err = run(ctx, "docker build", cmd)
916 if err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700917 return fmt.Errorf("docker build failed: %v", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700918 }
919 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700920 return nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700921}
922
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000923// requireGitRepo confirms that path is within a git repository.
924func requireGitRepo(ctx context.Context, path string) error {
925 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-dir")
Earl Lee2e463fb2025-04-17 11:22:22 -0700926 cmd.Dir = path
927 out, err := cmd.CombinedOutput()
928 if err != nil {
929 if strings.Contains(string(out), "not a git repository") {
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000930 return fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
Earl Lee2e463fb2025-04-17 11:22:22 -0700931Consider one of the following options:
932 - cd to a different dir that is already part of a git repo first, or
933 - to create a new git repo from this directory (%s), run this command:
934
935 git init . && git commit --allow-empty -m "initial commit"
936
937and try running sketch again.
938`, path, path)
939 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000940 return fmt.Errorf("git rev-parse --git-dir: %s: %w", out, err)
941 }
942 return nil
943}
944
945// gitRepoRoot attempts to find the git repository root directory.
946// Returns an error if not in a git repository or if it's a bare repository.
947// This is used to calculate relative paths for preserving user's working directory context.
948func gitRepoRoot(ctx context.Context, path string) (string, error) {
949 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
950 cmd.Dir = path
951 out, err := cmd.CombinedOutput()
952 if err != nil {
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400953 return "", fmt.Errorf("git rev-parse --show-toplevel: %s: %w", out, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700954 }
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400955 // The returned path is absolute.
956 return strings.TrimSpace(string(out)), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700957}
958
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000959// gitCommonDir finds the git common directory for path.
960func gitCommonDir(ctx context.Context, path string) (string, error) {
961 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
962 cmd.Dir = path
963 out, err := cmd.CombinedOutput()
964 if err != nil {
965 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
966 }
967 gitCommonDir := strings.TrimSpace(string(out))
968 if !filepath.IsAbs(gitCommonDir) {
969 gitCommonDir = filepath.Join(path, gitCommonDir)
970 }
971 return gitCommonDir, nil
972}
973
Josh Bleecher Snyderfa424f52025-07-11 18:43:55 +0000974// goModuleInfo represents a Go module with its file paths and blob SHAs
975type goModuleInfo struct {
976 // modPath is the path to the go.mod file, for debugging
977 modPath string
978 // modSHA is the git blob SHA of the go.mod file
979 modSHA string
980 // sumSHA is the git blob SHA of the go.sum file, empty if no go.sum exists
981 sumSHA string
982}
983
984// collectGoModules returns all go.mod files in the git repository with their blob SHAs.
985func collectGoModules(ctx context.Context, gitRoot string) ([]goModuleInfo, error) {
986 cmd := exec.CommandContext(ctx, "git", "ls-files", "-z", "*.mod")
987 cmd.Dir = gitRoot
988 out, err := cmd.CombinedOutput()
989 if err != nil {
990 return nil, fmt.Errorf("git ls-files -z *.mod: %s: %w", out, err)
991 }
992
993 modFiles := strings.Split(string(out), "\x00")
994 var modules []goModuleInfo
995 for _, file := range modFiles {
996 if filepath.Base(file) != "go.mod" {
997 continue
998 }
999
1000 modSHA, err := getGitBlobSHA(ctx, gitRoot, file)
1001 if err != nil {
1002 return nil, fmt.Errorf("failed to get blob SHA for %s: %w", file, err)
1003 }
1004
1005 // If corresponding go.sum exists, get its SHA
1006 sumFile := filepath.Join(filepath.Dir(file), "go.sum")
1007 sumSHA, _ := getGitBlobSHA(ctx, gitRoot, sumFile) // best effort
1008
1009 modules = append(modules, goModuleInfo{
1010 modPath: file,
1011 modSHA: modSHA,
1012 sumSHA: sumSHA,
1013 })
1014 }
1015
1016 return modules, nil
1017}
1018
1019// getGitBlobSHA returns the git blob SHA for a file at HEAD
1020func getGitBlobSHA(ctx context.Context, gitRoot, filePath string) (string, error) {
1021 cmd := exec.CommandContext(ctx, "git", "rev-parse", "HEAD:"+filePath)
1022 cmd.Dir = gitRoot
1023 out, err := cmd.CombinedOutput()
1024 if err != nil {
1025 return "", fmt.Errorf("git rev-parse HEAD:%s: %s: %w", filePath, out, err)
1026 }
1027 return strings.TrimSpace(string(out)), nil
1028}
1029
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +00001030// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
1031// from git config using the sketch.envfwd multi-valued key.
1032func getEnvForwardingFromGitConfig(ctx context.Context) []string {
1033 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
1034 out := string(outb)
1035 if err != nil {
1036 if strings.Contains(out, "key does not exist") {
1037 return nil
1038 }
1039 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
1040 return nil
1041 }
1042
1043 var envVars []string
1044 for envVar := range strings.Lines(out) {
1045 envVar = strings.TrimSpace(envVar)
1046 if envVar == "" {
1047 continue
1048 }
1049 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
1050 }
1051 return envVars
1052}
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001053
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +00001054// getOriginalGitOrigin returns the URL of the git remote 'origin' if it exists in the given directory
1055func getOriginalGitOrigin(ctx context.Context, dir string) string {
1056 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1057 cmd.Dir = dir
1058 out, err := cmd.Output()
1059 if err != nil {
1060 return ""
1061 }
1062 return strings.TrimSpace(string(out))
1063}
1064
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001065// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
1066// It handles quoted arguments and escaped characters.
1067//
1068// Examples:
1069//
1070// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
1071// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
1072// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
1073func parseDockerArgs(args string) []string {
1074 if args = strings.TrimSpace(args); args == "" {
1075 return []string{}
1076 }
1077
1078 var result []string
1079 var current strings.Builder
1080 inQuotes := false
1081 escapeNext := false
1082 quoteChar := rune(0)
1083
1084 for _, char := range args {
1085 if escapeNext {
1086 current.WriteRune(char)
1087 escapeNext = false
1088 continue
1089 }
1090
1091 if char == '\\' {
1092 escapeNext = true
1093 continue
1094 }
1095
1096 if char == '"' || char == '\'' {
1097 if !inQuotes {
1098 inQuotes = true
1099 quoteChar = char
1100 continue
1101 } else if char == quoteChar {
1102 inQuotes = false
1103 quoteChar = rune(0)
1104 continue
1105 }
1106 // Non-matching quote character inside quotes
1107 current.WriteRune(char)
1108 continue
1109 }
1110
1111 // Space outside of quotes is an argument separator
1112 if char == ' ' && !inQuotes {
1113 if current.Len() > 0 {
1114 result = append(result, current.String())
1115 current.Reset()
1116 }
1117 continue
1118 }
1119
1120 current.WriteRune(char)
1121 }
1122
1123 // Add the last argument if there is one
1124 if current.Len() > 0 {
1125 result = append(result, current.String())
1126 }
1127
1128 return result
1129}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001130
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001131// copyEmbeddedLinuxBinaryToContainer copies the embedded linux binary to the container
1132func copyEmbeddedLinuxBinaryToContainer(ctx context.Context, containerName string) error {
Josh Bleecher Snyder5ae245b2025-07-08 22:00:24 +00001133 out, err := combinedOutput(ctx, "docker", "version", "--format", "{{.Server.Arch}}")
1134 if err != nil {
1135 return fmt.Errorf("failed to detect Docker server architecture: %s: %w", out, err)
1136 }
1137 arch := strings.TrimSpace(string(out))
1138
1139 bin := embedded.LinuxBinary(arch)
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001140 if bin == nil {
Josh Bleecher Snyder5ae245b2025-07-08 22:00:24 +00001141 return fmt.Errorf("no embedded linux binary for architecture %q", arch)
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001142 }
1143
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001144 // Stream a tarball to docker cp.
1145 pr, pw := io.Pipe()
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001146
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001147 errCh := make(chan error, 1)
1148 go func() {
1149 defer pw.Close()
1150 tw := tar.NewWriter(pw)
1151
1152 hdr := &tar.Header{
1153 Name: "bin/sketch", // final path inside the container
1154 Mode: 0o700,
1155 Size: int64(len(bin)),
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001156 }
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001157 if err := tw.WriteHeader(hdr); err != nil {
1158 errCh <- fmt.Errorf("failed to write tar header: %w", err)
1159 return
1160 }
1161 if _, err := tw.Write(bin); err != nil {
1162 errCh <- fmt.Errorf("failed to write binary to tar: %w", err)
1163 return
1164 }
1165 if err := tw.Close(); err != nil {
1166 errCh <- fmt.Errorf("failed to close tar writer: %w", err)
1167 return
1168 }
1169 errCh <- nil
1170 }()
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001171
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001172 cmd := exec.CommandContext(ctx, "docker", "cp", "-", containerName+":/")
1173 cmd.Stdin = pr
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001174
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001175 out, cmdErr := cmd.CombinedOutput()
1176
1177 if tarErr := <-errCh; tarErr != nil {
1178 return tarErr
1179 }
1180 if cmdErr != nil {
1181 return fmt.Errorf("docker cp failed: %s: %w", out, cmdErr)
1182 }
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001183 return nil
1184}
1185
David Crawshaw1bd636c2025-06-13 19:56:27 +00001186const seccompProfile = `{
1187 "defaultAction": "SCMP_ACT_ALLOW",
1188 "syscalls": [
1189 {
1190 "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"],
1191 "action": "SCMP_ACT_ERRNO",
1192 "args": [
1193 {
1194 "index": 0,
1195 "value": 1,
1196 "op": "SCMP_CMP_EQ"
1197 }
1198 ]
1199 }
1200 ]
1201}`
1202
1203// ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist.
1204func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) {
1205 homeDir, err := os.UserHomeDir()
1206 if err != nil {
1207 return "", fmt.Errorf("failed to get home directory: %w", err)
1208 }
1209 cacheDir := filepath.Join(homeDir, ".cache", "sketch")
1210 if err := os.MkdirAll(cacheDir, 0o755); err != nil {
1211 return "", fmt.Errorf("failed to create cache directory: %w", err)
1212 }
1213 seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json")
1214
1215 curBytes, err := os.ReadFile(seccompPath)
1216 if err != nil && !os.IsNotExist(err) {
1217 return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err)
1218 }
1219 if string(curBytes) == seccompProfile {
1220 return seccompPath, nil // File already exists and matches the expected profile
1221 }
1222
1223 if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil {
1224 return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err)
1225 }
1226 slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath)
1227 return seccompPath, nil
1228}