blob: 826778ab01368611c5de6ec7147b9737ab598256 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package dockerimg
2package dockerimg
3
4import (
5 "bytes"
6 "context"
Philip Zeyliger5e227dd2025-04-21 15:55:29 -07007 "crypto/rand"
Earl Lee2e463fb2025-04-17 11:22:22 -07008 "crypto/sha256"
9 "encoding/hex"
10 "encoding/json"
11 "fmt"
12 "io"
13 "log/slog"
14 "net"
15 "net/http"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "runtime"
20 "strings"
Josh Bleecher Snyder99570462025-05-05 10:26:14 -070021 "sync/atomic"
Earl Lee2e463fb2025-04-17 11:22:22 -070022 "time"
23
Sean McCullough7013e9e2025-05-14 02:03:58 +000024 "golang.org/x/crypto/ssh"
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000025 "sketch.dev/browser"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070026 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070027 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070028 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070029)
30
31// ContainerConfig holds all configuration for launching a container
32type ContainerConfig struct {
33 // SessionID is the unique identifier for this session
34 SessionID string
35
36 // LocalAddr is the initial address to use (though it may be overwritten later)
37 LocalAddr string
38
39 // SkabandAddr is the address of the skaband service if available
40 SkabandAddr string
41
David Crawshaw5a7b3692025-05-05 16:49:15 -070042 // Model is the name of the LLM model to use.
43 Model string
Earl Lee2e463fb2025-04-17 11:22:22 -070044
David Crawshaw5a7b3692025-05-05 16:49:15 -070045 // ModelURL is the URL of the LLM service.
46 ModelURL string
47
48 // ModelAPIKey is the API key for LLM service.
49 ModelAPIKey string
Earl Lee2e463fb2025-04-17 11:22:22 -070050
51 // Path is the local filesystem path to use
52 Path string
53
54 // GitUsername is the username to use for git operations
55 GitUsername string
56
57 // GitEmail is the email to use for git operations
58 GitEmail string
59
60 // OpenBrowser determines whether to open a browser automatically
61 OpenBrowser bool
62
63 // NoCleanup prevents container cleanup when set to true
64 NoCleanup bool
65
66 // ForceRebuild forces rebuilding of the Docker image even if it exists
67 ForceRebuild bool
68
Philip Zeyliger983b58a2025-07-02 19:42:08 -070069 // BaseImage is the base Docker image to use for layering the repo
70 BaseImage string
71
Earl Lee2e463fb2025-04-17 11:22:22 -070072 // Host directory to copy container logs into, if not set to ""
73 ContainerLogDest string
74
75 // Path to pre-built linux sketch binary, or build a new one if set to ""
76 SketchBinaryLinux string
77
78 // Sketch client public key.
79 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000080
Sean McCulloughbaa2b592025-04-23 10:40:08 -070081 // Host port for the container's ssh server
82 SSHPort int
83
Philip Zeyliger18532b22025-04-23 21:11:46 +000084 // Outside information to pass to the container
85 OutsideHostname string
86 OutsideOS string
87 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070088
Pokey Rule0dcebe12025-04-28 14:51:04 +010089 // If true, exit after the first turn
90 OneShot bool
91
92 // Initial prompt
93 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000094
David Crawshawb5f6a002025-05-05 08:27:16 -070095 // Verbose enables verbose output
96 Verbose bool
Philip Zeyliger1dc21372025-05-05 19:54:44 +000097
98 // DockerArgs are additional arguments to pass to the docker create command
99 DockerArgs string
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000100
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000101 // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container
102 Mounts []string
103
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000104 // ExperimentFlag contains the experimental features to enable
105 ExperimentFlag string
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700106
107 // TermUI enables terminal UI
108 TermUI bool
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700109
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000110 // Budget configuration
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000111 MaxDollars float64
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000112
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700113 GitRemoteUrl string
114
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000115 // Upstream branch for git work
116 Upstream string
117
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700118 // Commit hash to checkout from GetRemoteUrl
119 Commit string
120
121 // Outtie's HTTP server
122 OutsideHTTP string
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000123
124 // Prefix for git branches created by sketch
125 BranchPrefix string
philip.zeyliger6d3de482025-06-10 19:38:14 -0700126
127 // LinkToGitHub enables GitHub branch linking in UI
128 LinkToGitHub bool
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700129
130 // SubtraceToken enables running sketch under subtrace.dev (development only)
131 SubtraceToken string
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700132
133 // MCPServers contains MCP server configurations
134 MCPServers []string
Earl Lee2e463fb2025-04-17 11:22:22 -0700135}
136
137// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
138// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700139func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700140 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700141 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700142 if runtime.GOOS == "darwin" {
143 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
144 } else {
145 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
146 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700147 }
148
149 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
150 // `docker ps` provides a good error message here that can be
151 // easily chatgpt'ed by users, so send it to the user as-is:
152 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
153 return fmt.Errorf("docker ps: %s (%w)", out, err)
154 }
155
156 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
157 if err != nil {
158 return err
159 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700160 gitRoot, err := findGitRoot(ctx, config.Path)
161 if err != nil {
162 return err
163 }
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700164 err = checkForEmptyGitRepo(ctx, config.Path)
165 if err != nil {
166 return err
167 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700168
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700169 imgName, err := findOrBuildDockerImage(ctx, gitRoot, config.BaseImage, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700170 if err != nil {
171 return err
172 }
173
174 linuxSketchBin := config.SketchBinaryLinux
175 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700176 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700177 if err != nil {
178 return err
179 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700180 }
181
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000182 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700183 defer func() {
184 if config.NoCleanup {
185 return
186 }
187 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
188 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
189 _ = out
190 }
191 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
192 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
193 _ = out
194 }
195 }()
196
197 // errCh receives errors from operations that this function calls in separate goroutines.
198 errCh := make(chan error)
199
200 // Start the git server
201 gitSrv, err := newGitServer(gitRoot)
202 if err != nil {
203 return fmt.Errorf("failed to start git server: %w", err)
204 }
205 defer gitSrv.shutdown(ctx)
206
207 go func() {
208 errCh <- gitSrv.serve(ctx)
209 }()
210
211 // Get the current host git commit
212 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000213 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
214 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700215 } else {
216 commit = strings.TrimSpace(string(out))
217 }
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000218
219 var upstream string
220 if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil {
221 slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err)
222 } else {
223 upstream = strings.TrimSpace(string(out))
224 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700225 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
226 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
227 }
228
229 relPath, err := filepath.Rel(gitRoot, config.Path)
230 if err != nil {
231 return err
232 }
233
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700234 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
235 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000236 config.Upstream = upstream
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700237 config.Commit = commit
238
Earl Lee2e463fb2025-04-17 11:22:22 -0700239 // Create the sketch container
240 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000241 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700242 }
243
244 // Copy the sketch linux binary into the container
245 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
246 return fmt.Errorf("docker cp: %s, %w", out, err)
247 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700248
249 // Make sure that the webui is built so we can copy the results to the container.
250 _, err = webui.Build()
251 if err != nil {
252 return fmt.Errorf("failed to build webui: %w", err)
253 }
254
David Crawshaw8bff16a2025-04-18 01:16:49 -0700255 webuiZipPath, err := webui.ZipPath()
256 if err != nil {
257 return err
258 }
259 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
260 return fmt.Errorf("docker cp: %s, %w", out, err)
261 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700262
David Crawshaw53786ef2025-04-24 12:52:51 -0700263 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700264
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700265 // Setup subtrace if token is provided (development only) - after container creation, before start
266 if config.SubtraceToken != "" {
267 fmt.Println("🔍 Setting up subtrace (development only)")
268 if err := setupSubtraceBeforeStart(ctx, cntrName, config.SubtraceToken); err != nil {
269 return fmt.Errorf("failed to setup subtrace: %w", err)
270 }
271 }
272
Earl Lee2e463fb2025-04-17 11:22:22 -0700273 // Start the sketch container
274 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
275 return fmt.Errorf("docker start: %s, %w", out, err)
276 }
277
278 // Copies structured logs from the container to the host.
279 copyLogs := func() {
280 if config.ContainerLogDest == "" {
281 return
282 }
283 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
284 if err != nil {
285 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
286 return
287 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700288 prefix := []byte("structured logs:")
289 for line := range bytes.Lines(out) {
290 rest, ok := bytes.CutPrefix(line, prefix)
291 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700292 continue
293 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700294 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700295 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
296 logFileName := filepath.Base(logFile)
297 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
298 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
299 if err != nil {
300 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
301 }
302 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
303 }
304 }
305
306 // NOTE: we want to see what the internal sketch binary prints
307 // regardless of the setting of the verbosity flag on the external
308 // binary, so reading "docker logs", which is the stdout/stderr of
309 // the internal binary is not conditional on the verbose flag.
310 appendInternalErr := func(err error) error {
311 if err == nil {
312 return nil
313 }
314 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000315 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700316 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
317 }
318 out = bytes.TrimSpace(out)
319 if len(out) > 0 {
320 return fmt.Errorf("docker logs: %s;\n%w", out, err)
321 }
322 return err
323 }
324
325 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700326 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700327 if err != nil {
328 return appendInternalErr(err)
329 }
330
Philip Zeyliger00442412025-05-14 11:03:23 -0700331 if config.Verbose {
332 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
333 }
334
Sean McCulloughae3480f2025-04-23 15:28:20 -0700335 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
336 if err != nil {
337 return appendInternalErr(err)
338 }
339 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
340 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700341 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700342 }
Sean McCullough4854c652025-04-24 18:37:02 -0700343
Sean McCullough7013e9e2025-05-14 02:03:58 +0000344 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700345
banksean29d689f2025-06-23 15:41:26 +0000346 cst, err := NewLocalSSHimmer(cntrName, sshHost, sshPort)
Sean McCullough078e85a2025-05-08 17:28:34 -0700347 if err != nil {
348 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
349 }
350
351 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700352 sshAvailable := false
353 sshErrMsg := ""
354 if sshErr != nil {
355 fmt.Println(sshErr.Error())
356 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700357 // continue - ssh config is not required for the rest of sketch to function locally.
358 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700359 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700360 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
361 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700362 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700363🖥️ ssh %s
364🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700365🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700366`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700367 sshUserIdentity = cst.userIdentity
368 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000369
370 // Get the Container CA public key for mutual auth
371 if cst.containerCAPublicKey != nil {
372 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
373 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
374 }
375
376 // Get the host certificate for mutual auth
377 hostCertificate = cst.hostCertificate
378
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700379 defer func() {
380 if err := cst.Cleanup(); err != nil {
381 appendInternalErr(err)
382 }
383 }()
384 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700385
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700386 // Tell the sketch container to Init(), which starts the SSH server
387 // and checks out the right commit.
388 // TODO: I'm trying to move as much configuration as possible into the command-line
389 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
390 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
391 // get the port Docker chose until after the process starts. The SSH config is
392 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
393 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700394 go func() {
395 // TODO: Why is this called in a goroutine? I have found that when I pull this out
396 // of the goroutine and call it inline, then the terminal UI clears itself and all
397 // the scrollback (which is not good, but also not fatal). I can't see why it does this
398 // though, since none of the calls in postContainerInitConfig obviously write to stdout
399 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700400 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700401 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
402 errCh <- appendInternalErr(err)
403 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700404
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700405 // 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 -0700406 ps1URL := "http://" + localAddr
407 if config.SkabandAddr != "" {
408 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700409 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700410 if config.OpenBrowser {
411 browser.Open(ps1URL)
412 }
413 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700414 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700415
Sean McCullough138ec242025-06-02 22:42:06 +0000416 // Start automatic port tunneling if SSH is available
417 if sshAvailable {
418 go func() {
419 containerURL := "http://" + localAddr
420 tunnelManager := NewTunnelManager(containerURL, cntrName, 10) // Allow up to 10 concurrent tunnels
421 tunnelManager.Start(ctx)
422 slog.InfoContext(ctx, "Started automatic port tunnel manager", "container", cntrName)
423 }()
424 }
425
Earl Lee2e463fb2025-04-17 11:22:22 -0700426 go func() {
427 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
428 cmd.Stdin = os.Stdin
429 cmd.Stdout = os.Stdout
430 cmd.Stderr = os.Stderr
431 errCh <- run(ctx, "docker attach", cmd)
432 }()
433
434 defer copyLogs()
435
436 for {
437 select {
438 case <-ctx.Done():
439 return ctx.Err()
440 case err := <-errCh:
441 if err != nil {
442 return appendInternalErr(fmt.Errorf("container process: %w", err))
443 }
444 return nil
445 }
446 }
447}
448
449func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
450 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700451 start := time.Now()
452
453 out, err := cmd.CombinedOutput()
454 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700455 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 -0700456 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700457 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 -0700458 }
459 return out, err
460}
461
462func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
463 start := time.Now()
464 err := cmd.Run()
465 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700466 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 -0700467 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700468 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 -0700469 }
470 return err
471}
472
473type gitServer struct {
474 gitLn net.Listener
475 gitPort string
476 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700477 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700478 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700479}
480
481func (gs *gitServer) shutdown(ctx context.Context) {
482 gs.srv.Shutdown(ctx)
483 gs.gitLn.Close()
484}
485
486// Serve a git remote from the host for the container to fetch from and push to.
487func (gs *gitServer) serve(ctx context.Context) error {
488 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
489 return gs.srv.Serve(gs.gitLn)
490}
491
492func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700493 ret := &gitServer{
494 pass: rand.Text(),
495 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700496
Earl Lee2e463fb2025-04-17 11:22:22 -0700497 gitLn, err := net.Listen("tcp4", ":0")
498 if err != nil {
499 return nil, fmt.Errorf("git listen: %w", err)
500 }
501 ret.gitLn = gitLn
502
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700503 browserC := make(chan bool, 1) // channel of browser open requests
504
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000505 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700506 for range browserC {
507 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000508 }
509 }()
510
511 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700512 ret.srv = &srv
513
514 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
515 if err != nil {
516 return nil, fmt.Errorf("git port: %w", err)
517 }
518 ret.gitPort = gitPort
519 return ret, nil
520}
521
522func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700523 cmdArgs := []string{
524 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700525 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700526 "--name", cntrName,
527 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700528 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700529 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700530 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700531 cmdArgs = append(cmdArgs, "-t")
532 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000533
534 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
535 cmdArgs = append(cmdArgs, "-e", envVar)
536 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700537 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700538 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700539 }
540 if config.SketchPubKey != "" {
541 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
542 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700543 if config.SSHPort > 0 {
544 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
545 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700546 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700547 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700548 if relPath != "." {
549 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
550 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700551 // colima does this by default, but Linux docker seems to need this set explicitly
552 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000553
David Crawshaw1bd636c2025-06-13 19:56:27 +0000554 // Add seccomp profile to prevent killing PID 1 (the sketch process itself)
555 // Write the seccomp profile to cache directory if it doesn't exist
556 seccompPath, err := ensureSeccompProfile(ctx)
557 if err != nil {
558 return fmt.Errorf("failed to create seccomp profile: %w", err)
559 }
560 cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath)
561
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700562 // Add subtrace environment variable if token is provided
563 if config.SubtraceToken != "" {
564 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_TOKEN="+config.SubtraceToken)
565 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_HTTP2=1")
566 }
567
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000568 // Add volume mounts if specified
569 for _, mount := range config.Mounts {
570 if mount != "" {
571 cmdArgs = append(cmdArgs, "-v", mount)
572 }
573 }
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700574 cmdArgs = append(cmdArgs, imgName)
575
576 // Add command: either [sketch] or [subtrace run -- sketch]
577 if config.SubtraceToken != "" {
578 cmdArgs = append(cmdArgs, "/usr/local/bin/subtrace", "run", "--", "/bin/sketch")
579 } else {
580 cmdArgs = append(cmdArgs, "/bin/sketch")
581 }
582
583 // Add all sketch arguments
584 cmdArgs = append(cmdArgs,
Earl Lee2e463fb2025-04-17 11:22:22 -0700585 "-unsafe",
586 "-addr=:80",
587 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000588 "-git-username="+config.GitUsername,
589 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000590 "-outside-hostname="+config.OutsideHostname,
591 "-outside-os="+config.OutsideOS,
592 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000593 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700594 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700595 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700596 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000597 "-x="+config.ExperimentFlag,
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000598 "-branch-prefix="+config.BranchPrefix,
philip.zeyliger6d3de482025-06-10 19:38:14 -0700599 "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub),
Earl Lee2e463fb2025-04-17 11:22:22 -0700600 )
philip.zeyliger8773e682025-06-11 21:36:21 -0700601 // Set SSH connection string based on session ID for SSH Theater
602 cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID)
David Crawshaw5a7b3692025-05-05 16:49:15 -0700603 if config.Model != "" {
604 cmdArgs = append(cmdArgs, "-model="+config.Model)
605 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700606 if config.GitRemoteUrl != "" {
607 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
608 if config.Commit == "" {
609 panic("Commit should have been set when GitRemoteUrl was set")
610 }
611 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000612 cmdArgs = append(cmdArgs, "-upstream="+config.Upstream)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700613 }
614 if config.OutsideHTTP != "" {
615 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
616 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000617 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100618 if config.Prompt != "" {
619 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
620 }
621 if config.OneShot {
622 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700623 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000624 if config.ModelURL == "" {
625 // Forward ANTHROPIC_API_KEY for direct use.
626 // TODO: have outtie run an http proxy?
627 // TODO: select and forward the relevant API key based on the model
628 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
629 }
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700630 // Add MCP server configurations
631 for _, mcpServer := range config.MCPServers {
632 cmdArgs = append(cmdArgs, "-mcp", mcpServer)
633 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000634
635 // Add additional docker arguments if provided
636 if config.DockerArgs != "" {
637 // Parse space-separated docker arguments with support for quotes and escaping
638 args := parseDockerArgs(config.DockerArgs)
639 // Insert arguments after "create" but before other arguments
640 for i := len(args) - 1; i >= 0; i-- {
641 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
642 }
643 }
644
Earl Lee2e463fb2025-04-17 11:22:22 -0700645 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
646 return fmt.Errorf("docker create: %s, %w", out, err)
647 }
648 return nil
649}
650
David Crawshawb5f6a002025-05-05 08:27:16 -0700651func buildLinuxSketchBin(ctx context.Context) (string, error) {
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700652 // Detect if race detector is enabled and use a different cache path
653 raceEnabled := RaceEnabled()
654 cacheSuffix := ""
655 if raceEnabled {
656 cacheSuffix = "-race"
657 }
658
659 homeDir, err := os.UserHomeDir()
660 if err != nil {
661 return "", err
662 }
663
664 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix)
665 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
666 return "", err
667 }
668
669 // When race detector is enabled, use Docker to build the Linux binary
670 if raceEnabled {
671 return buildLinuxSketchBinWithDocker(ctx, linuxGopath)
672 }
673
674 // Standard non-race build using cross-compilation
Pokey Rulea9a786b2025-05-12 10:52:34 +0100675 // Change to directory containing dockerimg.go for module detection
676 _, codeFile, _, _ := runtime.Caller(0)
677 codeDir := filepath.Dir(codeFile)
678 if currentDir, err := os.Getwd(); err != nil {
679 slog.WarnContext(ctx, "could not get current directory", "err", err)
680 } else {
681 if err := os.Chdir(codeDir); err != nil {
682 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
683 } else {
684 defer func() {
685 _ = os.Chdir(currentDir)
686 }()
687 }
688 }
689
David Crawshaw8a617cb2025-04-18 01:28:43 -0700690 verToInstall := "@latest"
691 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
692 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
693 } else {
694 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700695 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700696 verToInstall = ""
697 }
698 }
David Crawshaw69c67312025-04-17 13:42:00 -0700699
Earl Lee2e463fb2025-04-17 11:22:22 -0700700 start := time.Now()
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700701 args := []string{"install"}
702 args = append(args, "sketch.dev/cmd/sketch"+verToInstall)
703
704 cmd := exec.CommandContext(ctx, "go", args...)
David Crawshawb9eaef52025-04-17 15:23:18 -0700705 cmd.Env = append(
706 os.Environ(),
707 "GOOS=linux",
708 "CGO_ENABLED=0",
709 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700710 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700711 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700712 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700713
Earl Lee2e463fb2025-04-17 11:22:22 -0700714 out, err := cmd.CombinedOutput()
715 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700716 slog.ErrorContext(ctx, "go", slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700717 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
718 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700719 slog.DebugContext(ctx, "go", slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700720 }
721
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700722 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700723 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700724 }
David Crawshawc7e77962025-05-03 13:20:18 -0700725 // If we are already on Linux, there's no extra platform name in the path
726 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700727}
728
Sean McCulloughae3480f2025-04-23 15:28:20 -0700729func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700730 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700731 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700732 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
733 } else {
734 v4, _, found := strings.Cut(string(out), "\n")
735 if !found {
736 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
737 }
738 localAddr = v4
739 if strings.HasPrefix(localAddr, "0.0.0.0") {
740 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
741 }
742 }
743 return localAddr, nil
744}
745
746// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700747func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700748 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700749
750 initMsg, err := json.Marshal(
751 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000752 HostAddr: localAddr,
753 SSHAuthorizedKeys: sshAuthorizedKeys,
754 SSHServerIdentity: sshServerIdentity,
755 SSHContainerCAKey: sshContainerCAKey,
756 SSHHostCertificate: sshHostCertificate,
757 SSHAvailable: sshAvailable,
758 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700759 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700760 if err != nil {
761 return fmt.Errorf("init msg: %w", err)
762 }
763
Earl Lee2e463fb2025-04-17 11:22:22 -0700764 // Note: this /init POST is handled in loop/server/loophttp.go:
765 initMsgByteReader := bytes.NewReader(initMsg)
766 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
767 if err != nil {
768 return err
769 }
770
771 var res *http.Response
772 for i := 0; ; i++ {
773 time.Sleep(100 * time.Millisecond)
774 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
775 initMsgByteReader.Reset(initMsg)
776 res, err = http.DefaultClient.Do(req)
777 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700778 if i < 100 {
779 if i%10 == 0 {
780 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
781 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700782 continue
783 }
784 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
785 }
786 break
787 }
788 resBytes, _ := io.ReadAll(res.Body)
789 if res.StatusCode != http.StatusOK {
790 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
791 }
792 return nil
793}
794
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700795func findOrBuildDockerImage(ctx context.Context, gitRoot, baseImage string, forceRebuild, verbose bool) (imgName string, err error) {
796 // Default to the published sketch image if no base image is specified
797 if baseImage == "" {
798 imageTag := dockerfileBaseHash()
799 baseImage = fmt.Sprintf("%s:%s", dockerImgName, imageTag)
Earl Lee2e463fb2025-04-17 11:22:22 -0700800 }
801
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700802 // Ensure the base image exists locally, pull if necessary
803 if err := ensureBaseImageExists(ctx, baseImage); err != nil {
804 return "", fmt.Errorf("failed to ensure base image %s exists: %w", baseImage, err)
805 }
806
807 // Get the base image container ID for caching
808 baseImageID, err := getDockerImageID(ctx, baseImage)
Earl Lee2e463fb2025-04-17 11:22:22 -0700809 if err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700810 return "", fmt.Errorf("failed to get base image ID for %s: %w", baseImage, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700811 }
812
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700813 // Create a cache key based on base image ID and working directory
814 // Docker naming conventions restrict you to 20 characters per path component
815 // and only allow lowercase letters, digits, underscores, and dashes, so encoding
816 // the hash and the repo directory is sadly a bit of a non-starter.
817 cacheKey := createCacheKey(baseImageID, gitRoot)
818 imgName = "sketch-" + cacheKey
Earl Lee2e463fb2025-04-17 11:22:22 -0700819
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700820 // Check if the cached image exists and is up to date
821 if !forceRebuild {
822 if exists, err := dockerImageExists(ctx, imgName); err != nil {
823 return "", fmt.Errorf("failed to check if image exists: %w", err)
824 } else if exists {
825 if verbose {
826 fmt.Printf("using cached image %s\n", imgName)
Kilian Lackhove23772f42025-06-18 20:28:58 +0200827 }
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700828 return imgName, nil
David Crawshawb5f6a002025-05-05 08:27:16 -0700829 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700830 }
831
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700832 // Build the layered image
833 if err := buildLayeredImage(ctx, imgName, baseImage, gitRoot, verbose); err != nil {
834 return "", fmt.Errorf("failed to build layered image: %w", err)
835 }
836
837 return imgName, nil
838}
839
840// ensureBaseImageExists checks if the base image exists locally and pulls it if not
841func ensureBaseImageExists(ctx context.Context, imageName string) error {
842 exists, err := dockerImageExists(ctx, imageName)
843 if err != nil {
844 return fmt.Errorf("failed to check if image exists: %w", err)
845 }
846
847 if !exists {
848 fmt.Printf("🐋 pulling base image %s...\n", imageName)
849 if out, err := combinedOutput(ctx, "docker", "pull", imageName); err != nil {
850 return fmt.Errorf("docker pull %s failed: %s: %w", imageName, out, err)
851 }
852 fmt.Printf("✅ successfully pulled %s\n", imageName)
853 }
854
855 return nil
856}
857
858// getDockerImageID gets the container ID for a Docker image
859func getDockerImageID(ctx context.Context, imageName string) (string, error) {
860 out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{.Id}}", imageName)
861 if err != nil {
862 return "", err
863 }
864 return strings.TrimSpace(string(out)), nil
865}
866
867// createCacheKey creates a cache key from base image ID and working directory
868func createCacheKey(baseImageID, gitRoot string) string {
869 h := sha256.New()
870 h.Write([]byte(baseImageID))
871 h.Write([]byte(gitRoot))
872 return hex.EncodeToString(h.Sum(nil))[:12] // Use first 12 chars for shorter name
873}
874
875// dockerImageExists checks if a Docker image exists locally
876func dockerImageExists(ctx context.Context, imageName string) (bool, error) {
877 out, err := combinedOutput(ctx, "docker", "inspect", imageName)
878 if err != nil {
879 if strings.Contains(strings.ToLower(string(out)), "no such object") ||
880 strings.Contains(strings.ToLower(string(out)), "no such image") {
881 return false, nil
882 }
883 return false, err
884 }
885 return true, nil
886}
887
888// buildLayeredImage builds a new Docker image by layering the repo on top of the base image
889// TODO: git config stuff could be environment variables at runtime for email and username.
890// The git docs seem to say that http.postBuffer is a bug in our git proxy more than a thing
891// that's needed, but we haven't found the bug yet!
892func buildLayeredImage(ctx context.Context, imgName, baseImage, gitRoot string, _ bool) error {
893 dockerfileContent := fmt.Sprintf(`FROM %s
894ARG GIT_USER_EMAIL
895ARG GIT_USER_NAME
896RUN git config --global user.email "$GIT_USER_EMAIL" && \
897 git config --global user.name "$GIT_USER_NAME" && \
898 git config --global http.postBuffer 524288000
899COPY . /app
900WORKDIR /app
901RUN if [ -f go.mod ]; then go mod download; fi
902CMD ["/bin/sketch"]
903`, baseImage)
904
905 // Create a temporary directory for the Dockerfile
906 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
907 if err != nil {
908 return fmt.Errorf("failed to create temporary directory: %w", err)
909 }
910 defer os.RemoveAll(tmpDir)
911
912 dockerfilePath := filepath.Join(tmpDir, "Dockerfile")
913 if err := os.WriteFile(dockerfilePath, []byte(dockerfileContent), 0o666); err != nil {
914 return fmt.Errorf("failed to write Dockerfile: %w", err)
915 }
916
917 // Get git user info
Earl Lee2e463fb2025-04-17 11:22:22 -0700918 var gitUserEmail, gitUserName string
919 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700920 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 -0700921 } else {
922 gitUserEmail = strings.TrimSpace(string(out))
923 }
924 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700925 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 -0700926 } else {
927 gitUserName = strings.TrimSpace(string(out))
928 }
929
930 start := time.Now()
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700931 cmdArgs := []string{
932 "build",
Earl Lee2e463fb2025-04-17 11:22:22 -0700933 "-t", imgName,
934 "-f", dockerfilePath,
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700935 "--build-arg", "GIT_USER_EMAIL=" + gitUserEmail,
936 "--build-arg", "GIT_USER_NAME=" + gitUserName,
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700937 ".",
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700938 }
939
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700940 cmd := exec.CommandContext(ctx, "docker", cmdArgs...)
David Crawshawb5f6a002025-05-05 08:27:16 -0700941 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700942 // We print the docker build output whether or not the user
943 // has selected --verbose. Building an image takes a while
944 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700945 cmd.Stdout = os.Stdout
946 cmd.Stderr = os.Stderr
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700947 fmt.Printf("🏗️ building docker image %s from base %s...\n", imgName, baseImage)
Earl Lee2e463fb2025-04-17 11:22:22 -0700948
949 err = run(ctx, "docker build", cmd)
950 if err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700951 return fmt.Errorf("docker build failed: %v", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700952 }
953 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700954 return nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700955}
956
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700957func checkForEmptyGitRepo(ctx context.Context, path string) error {
958 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
959 cmd.Dir = path
960 _, err := cmd.CombinedOutput()
961 if err != nil {
962 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
963 "git commit --allow-empty -m 'initial commit'")
964 }
965 return nil
966}
967
Earl Lee2e463fb2025-04-17 11:22:22 -0700968func findGitRoot(ctx context.Context, path string) (string, error) {
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400969 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
Earl Lee2e463fb2025-04-17 11:22:22 -0700970 cmd.Dir = path
971 out, err := cmd.CombinedOutput()
972 if err != nil {
973 if strings.Contains(string(out), "not a git repository") {
974 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
975Consider one of the following options:
976 - cd to a different dir that is already part of a git repo first, or
977 - to create a new git repo from this directory (%s), run this command:
978
979 git init . && git commit --allow-empty -m "initial commit"
980
981and try running sketch again.
982`, path, path)
983 }
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400984 return "", fmt.Errorf("git rev-parse --show-toplevel: %s: %w", out, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700985 }
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400986 // The returned path is absolute.
987 return strings.TrimSpace(string(out)), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700988}
989
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000990// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
991// from git config using the sketch.envfwd multi-valued key.
992func getEnvForwardingFromGitConfig(ctx context.Context) []string {
993 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
994 out := string(outb)
995 if err != nil {
996 if strings.Contains(out, "key does not exist") {
997 return nil
998 }
999 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
1000 return nil
1001 }
1002
1003 var envVars []string
1004 for envVar := range strings.Lines(out) {
1005 envVar = strings.TrimSpace(envVar)
1006 if envVar == "" {
1007 continue
1008 }
1009 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
1010 }
1011 return envVars
1012}
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001013
1014// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
1015// It handles quoted arguments and escaped characters.
1016//
1017// Examples:
1018//
1019// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
1020// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
1021// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
1022func parseDockerArgs(args string) []string {
1023 if args = strings.TrimSpace(args); args == "" {
1024 return []string{}
1025 }
1026
1027 var result []string
1028 var current strings.Builder
1029 inQuotes := false
1030 escapeNext := false
1031 quoteChar := rune(0)
1032
1033 for _, char := range args {
1034 if escapeNext {
1035 current.WriteRune(char)
1036 escapeNext = false
1037 continue
1038 }
1039
1040 if char == '\\' {
1041 escapeNext = true
1042 continue
1043 }
1044
1045 if char == '"' || char == '\'' {
1046 if !inQuotes {
1047 inQuotes = true
1048 quoteChar = char
1049 continue
1050 } else if char == quoteChar {
1051 inQuotes = false
1052 quoteChar = rune(0)
1053 continue
1054 }
1055 // Non-matching quote character inside quotes
1056 current.WriteRune(char)
1057 continue
1058 }
1059
1060 // Space outside of quotes is an argument separator
1061 if char == ' ' && !inQuotes {
1062 if current.Len() > 0 {
1063 result = append(result, current.String())
1064 current.Reset()
1065 }
1066 continue
1067 }
1068
1069 current.WriteRune(char)
1070 }
1071
1072 // Add the last argument if there is one
1073 if current.Len() > 0 {
1074 result = append(result, current.String())
1075 }
1076
1077 return result
1078}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001079
1080// buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled.
1081// This avoids cross-compilation issues with CGO which is required for the race detector.
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001082// Mounts host Go module cache and build cache for faster subsequent builds.
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001083func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) {
1084 // Find the git repo root
1085 currentDir, err := os.Getwd()
1086 if err != nil {
1087 return "", fmt.Errorf("could not get current directory: %w", err)
1088 }
1089
1090 gitRoot, err := findGitRoot(ctx, currentDir)
1091 if err != nil {
1092 return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err)
1093 }
1094
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001095 // Get host Go cache directories to mount for faster builds
1096 goCacheDir, err := getHostGoCacheDir(ctx)
1097 if err != nil {
1098 return "", fmt.Errorf("failed to get host GOCACHE: %w", err)
1099 }
1100 goModCacheDir, err := getHostGoModCacheDir(ctx)
1101 if err != nil {
1102 return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err)
1103 }
1104
1105 slog.DebugContext(ctx, "building Linux sketch binary with race detector using Docker", "git_root", gitRoot, "gocache", goCacheDir, "gomodcache", goModCacheDir)
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001106
1107 // Use the published Docker image tag
1108 imageTag := dockerfileBaseHash()
1109 imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag)
1110
1111 // Create destination directory for the binary
1112 destPath := filepath.Join(linuxGopath, "bin")
1113 if err := os.MkdirAll(destPath, 0o777); err != nil {
1114 return "", fmt.Errorf("failed to create destination directory: %w", err)
1115 }
1116 destFile := filepath.Join(destPath, "sketch")
1117
1118 // Create a unique container name
1119 containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano())
1120
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001121 // Run a container with the repo mounted and Go caches for faster builds
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001122 start := time.Now()
1123 slog.DebugContext(ctx, "running Docker container to build sketch with race detector")
1124
1125 // Use explicit output path for clarity
1126 runArgs := []string{
1127 "run",
1128 "--name", containerID,
1129 "-v", gitRoot + ":/app",
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001130 "-v", goCacheDir + ":/root/.cache/go-build",
1131 "-v", goModCacheDir + ":/go/pkg/mod",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001132 "-w", "/app",
1133 imgName,
Josh Bleecher Snyderf4f929a2025-05-23 17:19:26 +00001134 "sh", "-c", "cd /app && mkdir -p /tmp/sketch-out && go build -buildvcs=false -race -o /tmp/sketch-out/sketch sketch.dev/cmd/sketch",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001135 }
1136
1137 out, err := combinedOutput(ctx, "docker", runArgs...)
1138 if err != nil {
1139 // Print the output to help with debugging
1140 slog.ErrorContext(ctx, "docker run for race build failed",
1141 slog.String("output", string(out)),
1142 slog.String("error", err.Error()))
1143 return "", fmt.Errorf("docker run failed: %s: %w", out, err)
1144 }
1145
1146 slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start))
1147
1148 // Copy the binary from the container using the explicit path
1149 out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile)
1150 if err != nil {
1151 return "", fmt.Errorf("docker cp failed: %s: %w", out, err)
1152 }
1153
1154 // Clean up the container
1155 if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil {
1156 slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out))
1157 }
1158
1159 // Make the binary executable
1160 if err := os.Chmod(destFile, 0o755); err != nil {
1161 return "", fmt.Errorf("failed to make binary executable: %w", err)
1162 }
1163
1164 return destFile, nil
1165}
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001166
1167// getHostGoCacheDir returns the host's GOCACHE directory
1168func getHostGoCacheDir(ctx context.Context) (string, error) {
1169 out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput()
1170 if err != nil {
1171 return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err)
1172 }
1173 return strings.TrimSpace(string(out)), nil
1174}
1175
1176// getHostGoModCacheDir returns the host's GOMODCACHE directory
1177func getHostGoModCacheDir(ctx context.Context) (string, error) {
1178 out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput()
1179 if err != nil {
1180 return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err)
1181 }
1182 return strings.TrimSpace(string(out)), nil
1183}
David Crawshaw1bd636c2025-06-13 19:56:27 +00001184
1185const seccompProfile = `{
1186 "defaultAction": "SCMP_ACT_ALLOW",
1187 "syscalls": [
1188 {
1189 "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"],
1190 "action": "SCMP_ACT_ERRNO",
1191 "args": [
1192 {
1193 "index": 0,
1194 "value": 1,
1195 "op": "SCMP_CMP_EQ"
1196 }
1197 ]
1198 }
1199 ]
1200}`
1201
1202// ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist.
1203func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) {
1204 homeDir, err := os.UserHomeDir()
1205 if err != nil {
1206 return "", fmt.Errorf("failed to get home directory: %w", err)
1207 }
1208 cacheDir := filepath.Join(homeDir, ".cache", "sketch")
1209 if err := os.MkdirAll(cacheDir, 0o755); err != nil {
1210 return "", fmt.Errorf("failed to create cache directory: %w", err)
1211 }
1212 seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json")
1213
1214 curBytes, err := os.ReadFile(seccompPath)
1215 if err != nil && !os.IsNotExist(err) {
1216 return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err)
1217 }
1218 if string(curBytes) == seccompProfile {
1219 return seccompPath, nil // File already exists and matches the expected profile
1220 }
1221
1222 if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil {
1223 return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err)
1224 }
1225 slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath)
1226 return seccompPath, nil
1227}