blob: 77af08a0089a180756a0add5068ddb71bd416b72 [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"
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -070026 "sketch.dev/embedded"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070027 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070028 "sketch.dev/skribe"
29)
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
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000174 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700175 defer func() {
176 if config.NoCleanup {
177 return
178 }
179 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
180 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
181 _ = out
182 }
183 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
184 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
185 _ = out
186 }
187 }()
188
189 // errCh receives errors from operations that this function calls in separate goroutines.
190 errCh := make(chan error)
191
192 // Start the git server
193 gitSrv, err := newGitServer(gitRoot)
194 if err != nil {
195 return fmt.Errorf("failed to start git server: %w", err)
196 }
197 defer gitSrv.shutdown(ctx)
198
199 go func() {
200 errCh <- gitSrv.serve(ctx)
201 }()
202
203 // Get the current host git commit
204 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000205 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
206 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700207 } else {
208 commit = strings.TrimSpace(string(out))
209 }
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000210
211 var upstream string
212 if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil {
213 slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err)
214 } else {
215 upstream = strings.TrimSpace(string(out))
216 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700217 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
218 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
219 }
220
221 relPath, err := filepath.Rel(gitRoot, config.Path)
222 if err != nil {
223 return err
224 }
225
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700226 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
227 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000228 config.Upstream = upstream
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700229 config.Commit = commit
230
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700231 // Create the sketch container, copy over linux sketch
Earl Lee2e463fb2025-04-17 11:22:22 -0700232 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000233 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700234 }
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700235 if err := copyEmbeddedLinuxBinaryToContainer(ctx, cntrName); err != nil {
236 return fmt.Errorf("failed to copy linux binary to container: %w", err)
David Crawshaw8bff16a2025-04-18 01:16:49 -0700237 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700238
David Crawshaw53786ef2025-04-24 12:52:51 -0700239 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700240
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700241 // Setup subtrace if token is provided (development only) - after container creation, before start
242 if config.SubtraceToken != "" {
243 fmt.Println("🔍 Setting up subtrace (development only)")
244 if err := setupSubtraceBeforeStart(ctx, cntrName, config.SubtraceToken); err != nil {
245 return fmt.Errorf("failed to setup subtrace: %w", err)
246 }
247 }
248
Earl Lee2e463fb2025-04-17 11:22:22 -0700249 // Start the sketch container
250 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
251 return fmt.Errorf("docker start: %s, %w", out, err)
252 }
253
254 // Copies structured logs from the container to the host.
255 copyLogs := func() {
256 if config.ContainerLogDest == "" {
257 return
258 }
259 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
260 if err != nil {
261 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
262 return
263 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700264 prefix := []byte("structured logs:")
265 for line := range bytes.Lines(out) {
266 rest, ok := bytes.CutPrefix(line, prefix)
267 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700268 continue
269 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700270 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700271 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
272 logFileName := filepath.Base(logFile)
273 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
274 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
275 if err != nil {
276 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
277 }
278 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
279 }
280 }
281
282 // NOTE: we want to see what the internal sketch binary prints
283 // regardless of the setting of the verbosity flag on the external
284 // binary, so reading "docker logs", which is the stdout/stderr of
285 // the internal binary is not conditional on the verbose flag.
286 appendInternalErr := func(err error) error {
287 if err == nil {
288 return nil
289 }
290 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000291 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700292 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
293 }
294 out = bytes.TrimSpace(out)
295 if len(out) > 0 {
296 return fmt.Errorf("docker logs: %s;\n%w", out, err)
297 }
298 return err
299 }
300
301 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700302 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700303 if err != nil {
304 return appendInternalErr(err)
305 }
306
Philip Zeyliger00442412025-05-14 11:03:23 -0700307 if config.Verbose {
308 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
309 }
310
Sean McCulloughae3480f2025-04-23 15:28:20 -0700311 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
312 if err != nil {
313 return appendInternalErr(err)
314 }
315 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
316 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700317 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700318 }
Sean McCullough4854c652025-04-24 18:37:02 -0700319
Sean McCullough7013e9e2025-05-14 02:03:58 +0000320 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700321
banksean29d689f2025-06-23 15:41:26 +0000322 cst, err := NewLocalSSHimmer(cntrName, sshHost, sshPort)
Sean McCullough078e85a2025-05-08 17:28:34 -0700323 if err != nil {
324 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
325 }
326
327 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700328 sshAvailable := false
329 sshErrMsg := ""
330 if sshErr != nil {
331 fmt.Println(sshErr.Error())
332 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700333 // continue - ssh config is not required for the rest of sketch to function locally.
334 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700335 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700336 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
337 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700338 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700339🖥️ ssh %s
340🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700341🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700342`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700343 sshUserIdentity = cst.userIdentity
344 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000345
346 // Get the Container CA public key for mutual auth
347 if cst.containerCAPublicKey != nil {
348 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
349 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
350 }
351
352 // Get the host certificate for mutual auth
353 hostCertificate = cst.hostCertificate
354
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700355 defer func() {
356 if err := cst.Cleanup(); err != nil {
357 appendInternalErr(err)
358 }
359 }()
360 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700361
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700362 // Tell the sketch container to Init(), which starts the SSH server
363 // and checks out the right commit.
364 // TODO: I'm trying to move as much configuration as possible into the command-line
365 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
366 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
367 // get the port Docker chose until after the process starts. The SSH config is
368 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
369 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700370 go func() {
371 // TODO: Why is this called in a goroutine? I have found that when I pull this out
372 // of the goroutine and call it inline, then the terminal UI clears itself and all
373 // the scrollback (which is not good, but also not fatal). I can't see why it does this
374 // though, since none of the calls in postContainerInitConfig obviously write to stdout
375 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700376 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700377 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
378 errCh <- appendInternalErr(err)
379 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700380
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700381 // 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 -0700382 ps1URL := "http://" + localAddr
383 if config.SkabandAddr != "" {
384 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700385 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700386 if config.OpenBrowser {
387 browser.Open(ps1URL)
388 }
389 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700390 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700391
392 go func() {
393 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
394 cmd.Stdin = os.Stdin
395 cmd.Stdout = os.Stdout
396 cmd.Stderr = os.Stderr
397 errCh <- run(ctx, "docker attach", cmd)
398 }()
399
400 defer copyLogs()
401
402 for {
403 select {
404 case <-ctx.Done():
405 return ctx.Err()
406 case err := <-errCh:
407 if err != nil {
408 return appendInternalErr(fmt.Errorf("container process: %w", err))
409 }
410 return nil
411 }
412 }
413}
414
415func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
416 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700417 start := time.Now()
418
419 out, err := cmd.CombinedOutput()
420 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700421 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 -0700422 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700423 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 -0700424 }
425 return out, err
426}
427
428func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
429 start := time.Now()
430 err := cmd.Run()
431 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700432 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 -0700433 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700434 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 -0700435 }
436 return err
437}
438
439type gitServer struct {
440 gitLn net.Listener
441 gitPort string
442 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700443 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700444 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700445}
446
447func (gs *gitServer) shutdown(ctx context.Context) {
448 gs.srv.Shutdown(ctx)
449 gs.gitLn.Close()
450}
451
452// Serve a git remote from the host for the container to fetch from and push to.
453func (gs *gitServer) serve(ctx context.Context) error {
454 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
455 return gs.srv.Serve(gs.gitLn)
456}
457
458func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700459 ret := &gitServer{
460 pass: rand.Text(),
461 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700462
Earl Lee2e463fb2025-04-17 11:22:22 -0700463 gitLn, err := net.Listen("tcp4", ":0")
464 if err != nil {
465 return nil, fmt.Errorf("git listen: %w", err)
466 }
467 ret.gitLn = gitLn
468
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700469 browserC := make(chan bool, 1) // channel of browser open requests
470
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000471 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700472 for range browserC {
473 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000474 }
475 }()
476
477 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700478 ret.srv = &srv
479
480 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
481 if err != nil {
482 return nil, fmt.Errorf("git port: %w", err)
483 }
484 ret.gitPort = gitPort
485 return ret, nil
486}
487
488func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700489 cmdArgs := []string{
490 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700491 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700492 "--name", cntrName,
493 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700494 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700495 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700496 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700497 cmdArgs = append(cmdArgs, "-t")
498 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000499
500 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
501 cmdArgs = append(cmdArgs, "-e", envVar)
502 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700503 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700504 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700505 }
506 if config.SketchPubKey != "" {
507 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
508 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700509 if config.SSHPort > 0 {
510 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
511 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700512 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700513 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700514 if relPath != "." {
515 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
516 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700517 // colima does this by default, but Linux docker seems to need this set explicitly
518 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000519
David Crawshaw1bd636c2025-06-13 19:56:27 +0000520 // Add seccomp profile to prevent killing PID 1 (the sketch process itself)
521 // Write the seccomp profile to cache directory if it doesn't exist
522 seccompPath, err := ensureSeccompProfile(ctx)
523 if err != nil {
524 return fmt.Errorf("failed to create seccomp profile: %w", err)
525 }
526 cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath)
527
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700528 // Add subtrace environment variable if token is provided
529 if config.SubtraceToken != "" {
530 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_TOKEN="+config.SubtraceToken)
531 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_HTTP2=1")
532 }
533
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000534 // Add volume mounts if specified
535 for _, mount := range config.Mounts {
536 if mount != "" {
537 cmdArgs = append(cmdArgs, "-v", mount)
538 }
539 }
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700540 cmdArgs = append(cmdArgs, imgName)
541
542 // Add command: either [sketch] or [subtrace run -- sketch]
543 if config.SubtraceToken != "" {
544 cmdArgs = append(cmdArgs, "/usr/local/bin/subtrace", "run", "--", "/bin/sketch")
545 } else {
546 cmdArgs = append(cmdArgs, "/bin/sketch")
547 }
548
549 // Add all sketch arguments
550 cmdArgs = append(cmdArgs,
Earl Lee2e463fb2025-04-17 11:22:22 -0700551 "-unsafe",
552 "-addr=:80",
553 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000554 "-git-username="+config.GitUsername,
555 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000556 "-outside-hostname="+config.OutsideHostname,
557 "-outside-os="+config.OutsideOS,
558 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000559 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700560 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700561 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700562 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000563 "-x="+config.ExperimentFlag,
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000564 "-branch-prefix="+config.BranchPrefix,
philip.zeyliger6d3de482025-06-10 19:38:14 -0700565 "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub),
Earl Lee2e463fb2025-04-17 11:22:22 -0700566 )
philip.zeyliger8773e682025-06-11 21:36:21 -0700567 // Set SSH connection string based on session ID for SSH Theater
568 cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID)
David Crawshaw5a7b3692025-05-05 16:49:15 -0700569 if config.Model != "" {
570 cmdArgs = append(cmdArgs, "-model="+config.Model)
571 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700572 if config.GitRemoteUrl != "" {
573 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
574 if config.Commit == "" {
575 panic("Commit should have been set when GitRemoteUrl was set")
576 }
577 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000578 cmdArgs = append(cmdArgs, "-upstream="+config.Upstream)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700579 }
580 if config.OutsideHTTP != "" {
581 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
582 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000583 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100584 if config.Prompt != "" {
585 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
586 }
587 if config.OneShot {
588 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700589 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000590 if config.ModelURL == "" {
591 // Forward ANTHROPIC_API_KEY for direct use.
592 // TODO: have outtie run an http proxy?
593 // TODO: select and forward the relevant API key based on the model
594 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
595 }
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700596 // Add MCP server configurations
597 for _, mcpServer := range config.MCPServers {
598 cmdArgs = append(cmdArgs, "-mcp", mcpServer)
599 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000600
601 // Add additional docker arguments if provided
602 if config.DockerArgs != "" {
603 // Parse space-separated docker arguments with support for quotes and escaping
604 args := parseDockerArgs(config.DockerArgs)
605 // Insert arguments after "create" but before other arguments
606 for i := len(args) - 1; i >= 0; i-- {
607 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
608 }
609 }
610
Earl Lee2e463fb2025-04-17 11:22:22 -0700611 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
612 return fmt.Errorf("docker create: %s, %w", out, err)
613 }
614 return nil
615}
616
David Crawshawb5f6a002025-05-05 08:27:16 -0700617func buildLinuxSketchBin(ctx context.Context) (string, error) {
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700618 // Detect if race detector is enabled and use a different cache path
619 raceEnabled := RaceEnabled()
620 cacheSuffix := ""
621 if raceEnabled {
622 cacheSuffix = "-race"
623 }
624
625 homeDir, err := os.UserHomeDir()
626 if err != nil {
627 return "", err
628 }
629
630 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix)
631 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
632 return "", err
633 }
634
635 // When race detector is enabled, use Docker to build the Linux binary
636 if raceEnabled {
637 return buildLinuxSketchBinWithDocker(ctx, linuxGopath)
638 }
639
640 // Standard non-race build using cross-compilation
Pokey Rulea9a786b2025-05-12 10:52:34 +0100641 // Change to directory containing dockerimg.go for module detection
642 _, codeFile, _, _ := runtime.Caller(0)
643 codeDir := filepath.Dir(codeFile)
644 if currentDir, err := os.Getwd(); err != nil {
645 slog.WarnContext(ctx, "could not get current directory", "err", err)
646 } else {
647 if err := os.Chdir(codeDir); err != nil {
648 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
649 } else {
650 defer func() {
651 _ = os.Chdir(currentDir)
652 }()
653 }
654 }
655
David Crawshaw8a617cb2025-04-18 01:28:43 -0700656 verToInstall := "@latest"
657 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
658 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
659 } else {
660 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700661 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700662 verToInstall = ""
663 }
664 }
David Crawshaw69c67312025-04-17 13:42:00 -0700665
Earl Lee2e463fb2025-04-17 11:22:22 -0700666 start := time.Now()
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700667 args := []string{"install"}
668 args = append(args, "sketch.dev/cmd/sketch"+verToInstall)
669
670 cmd := exec.CommandContext(ctx, "go", args...)
David Crawshawb9eaef52025-04-17 15:23:18 -0700671 cmd.Env = append(
672 os.Environ(),
673 "GOOS=linux",
674 "CGO_ENABLED=0",
675 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700676 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700677 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700678 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700679
Earl Lee2e463fb2025-04-17 11:22:22 -0700680 out, err := cmd.CombinedOutput()
681 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700682 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 -0700683 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
684 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700685 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 -0700686 }
687
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700688 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700689 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700690 }
David Crawshawc7e77962025-05-03 13:20:18 -0700691 // If we are already on Linux, there's no extra platform name in the path
692 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700693}
694
Sean McCulloughae3480f2025-04-23 15:28:20 -0700695func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700696 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700697 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700698 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
699 } else {
700 v4, _, found := strings.Cut(string(out), "\n")
701 if !found {
702 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
703 }
704 localAddr = v4
705 if strings.HasPrefix(localAddr, "0.0.0.0") {
706 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
707 }
708 }
709 return localAddr, nil
710}
711
712// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700713func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700714 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700715
716 initMsg, err := json.Marshal(
717 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000718 HostAddr: localAddr,
719 SSHAuthorizedKeys: sshAuthorizedKeys,
720 SSHServerIdentity: sshServerIdentity,
721 SSHContainerCAKey: sshContainerCAKey,
722 SSHHostCertificate: sshHostCertificate,
723 SSHAvailable: sshAvailable,
724 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700725 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700726 if err != nil {
727 return fmt.Errorf("init msg: %w", err)
728 }
729
Earl Lee2e463fb2025-04-17 11:22:22 -0700730 // Note: this /init POST is handled in loop/server/loophttp.go:
731 initMsgByteReader := bytes.NewReader(initMsg)
732 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
733 if err != nil {
734 return err
735 }
736
737 var res *http.Response
738 for i := 0; ; i++ {
739 time.Sleep(100 * time.Millisecond)
740 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
741 initMsgByteReader.Reset(initMsg)
742 res, err = http.DefaultClient.Do(req)
743 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700744 if i < 100 {
745 if i%10 == 0 {
746 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
747 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700748 continue
749 }
750 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
751 }
752 break
753 }
754 resBytes, _ := io.ReadAll(res.Body)
755 if res.StatusCode != http.StatusOK {
756 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
757 }
758 return nil
759}
760
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700761func findOrBuildDockerImage(ctx context.Context, gitRoot, baseImage string, forceRebuild, verbose bool) (imgName string, err error) {
762 // Default to the published sketch image if no base image is specified
763 if baseImage == "" {
764 imageTag := dockerfileBaseHash()
765 baseImage = fmt.Sprintf("%s:%s", dockerImgName, imageTag)
Earl Lee2e463fb2025-04-17 11:22:22 -0700766 }
767
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700768 // Ensure the base image exists locally, pull if necessary
769 if err := ensureBaseImageExists(ctx, baseImage); err != nil {
770 return "", fmt.Errorf("failed to ensure base image %s exists: %w", baseImage, err)
771 }
772
773 // Get the base image container ID for caching
774 baseImageID, err := getDockerImageID(ctx, baseImage)
Earl Lee2e463fb2025-04-17 11:22:22 -0700775 if err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700776 return "", fmt.Errorf("failed to get base image ID for %s: %w", baseImage, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700777 }
778
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700779 // Create a cache key based on base image ID and working directory
780 // Docker naming conventions restrict you to 20 characters per path component
781 // and only allow lowercase letters, digits, underscores, and dashes, so encoding
782 // the hash and the repo directory is sadly a bit of a non-starter.
783 cacheKey := createCacheKey(baseImageID, gitRoot)
784 imgName = "sketch-" + cacheKey
Earl Lee2e463fb2025-04-17 11:22:22 -0700785
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700786 // Check if the cached image exists and is up to date
787 if !forceRebuild {
788 if exists, err := dockerImageExists(ctx, imgName); err != nil {
789 return "", fmt.Errorf("failed to check if image exists: %w", err)
790 } else if exists {
791 if verbose {
792 fmt.Printf("using cached image %s\n", imgName)
Kilian Lackhove23772f42025-06-18 20:28:58 +0200793 }
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700794 return imgName, nil
David Crawshawb5f6a002025-05-05 08:27:16 -0700795 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700796 }
797
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700798 // Build the layered image
799 if err := buildLayeredImage(ctx, imgName, baseImage, gitRoot, verbose); err != nil {
800 return "", fmt.Errorf("failed to build layered image: %w", err)
801 }
802
803 return imgName, nil
804}
805
806// ensureBaseImageExists checks if the base image exists locally and pulls it if not
807func ensureBaseImageExists(ctx context.Context, imageName string) error {
808 exists, err := dockerImageExists(ctx, imageName)
809 if err != nil {
810 return fmt.Errorf("failed to check if image exists: %w", err)
811 }
812
813 if !exists {
814 fmt.Printf("🐋 pulling base image %s...\n", imageName)
815 if out, err := combinedOutput(ctx, "docker", "pull", imageName); err != nil {
816 return fmt.Errorf("docker pull %s failed: %s: %w", imageName, out, err)
817 }
818 fmt.Printf("✅ successfully pulled %s\n", imageName)
819 }
820
821 return nil
822}
823
824// getDockerImageID gets the container ID for a Docker image
825func getDockerImageID(ctx context.Context, imageName string) (string, error) {
826 out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{.Id}}", imageName)
827 if err != nil {
828 return "", err
829 }
830 return strings.TrimSpace(string(out)), nil
831}
832
833// createCacheKey creates a cache key from base image ID and working directory
834func createCacheKey(baseImageID, gitRoot string) string {
835 h := sha256.New()
836 h.Write([]byte(baseImageID))
837 h.Write([]byte(gitRoot))
838 return hex.EncodeToString(h.Sum(nil))[:12] // Use first 12 chars for shorter name
839}
840
841// dockerImageExists checks if a Docker image exists locally
842func dockerImageExists(ctx context.Context, imageName string) (bool, error) {
843 out, err := combinedOutput(ctx, "docker", "inspect", imageName)
844 if err != nil {
845 if strings.Contains(strings.ToLower(string(out)), "no such object") ||
846 strings.Contains(strings.ToLower(string(out)), "no such image") {
847 return false, nil
848 }
849 return false, err
850 }
851 return true, nil
852}
853
854// buildLayeredImage builds a new Docker image by layering the repo on top of the base image
855// TODO: git config stuff could be environment variables at runtime for email and username.
856// The git docs seem to say that http.postBuffer is a bug in our git proxy more than a thing
857// that's needed, but we haven't found the bug yet!
Philip Zeyliger882b1d12025-07-02 20:04:08 -0700858//
859// TODO: There is a caching tension. A base image is great for tools (like, some version
860// of Go). Then you want a git repo, which is much faster to incrementally fetch rather
861// than cloning every time. Then you want some build artifacts, like perhaps the
862// "go mod download" cache, or the "go build" cache or the "npm install" cache.
863// The implementation here copies the working directory (not just the git repo!),
864// and runs "go mod download". This is an ok compromise, but a power user might want
865// less caching or more caching, depending on their use case. One approach we could take
866// is to punt entirely if /app/.git already exists. If the user has provided a -base-image with
867// their git repo, let's assume they know what they're doing, and they've customized their image
868// for their use case. On the other side of the spectrum is cloning their repo every time,
869// or running git clean -xdf, which minimizes surprises but slows down builds.
870// Note that buildx has some support for conditional COPY, but without buildx, which
871// we can't reliably depend on, we have to run the base image to inspect its file system,
872// and then we can decide what to do.
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700873func buildLayeredImage(ctx context.Context, imgName, baseImage, gitRoot string, _ bool) error {
874 dockerfileContent := fmt.Sprintf(`FROM %s
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700875COPY . /app
876WORKDIR /app
877RUN if [ -f go.mod ]; then go mod download; fi
878CMD ["/bin/sketch"]
879`, baseImage)
880
881 // Create a temporary directory for the Dockerfile
882 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
883 if err != nil {
884 return fmt.Errorf("failed to create temporary directory: %w", err)
885 }
886 defer os.RemoveAll(tmpDir)
887
888 dockerfilePath := filepath.Join(tmpDir, "Dockerfile")
889 if err := os.WriteFile(dockerfilePath, []byte(dockerfileContent), 0o666); err != nil {
890 return fmt.Errorf("failed to write Dockerfile: %w", err)
891 }
892
893 // Get git user info
Earl Lee2e463fb2025-04-17 11:22:22 -0700894 var gitUserEmail, gitUserName string
895 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700896 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 -0700897 } else {
898 gitUserEmail = strings.TrimSpace(string(out))
899 }
900 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700901 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 -0700902 } else {
903 gitUserName = strings.TrimSpace(string(out))
904 }
905
906 start := time.Now()
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700907 cmdArgs := []string{
908 "build",
Earl Lee2e463fb2025-04-17 11:22:22 -0700909 "-t", imgName,
910 "-f", dockerfilePath,
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700911 "--build-arg", "GIT_USER_EMAIL=" + gitUserEmail,
912 "--build-arg", "GIT_USER_NAME=" + gitUserName,
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700913 ".",
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700914 }
915
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700916 cmd := exec.CommandContext(ctx, "docker", cmdArgs...)
David Crawshawb5f6a002025-05-05 08:27:16 -0700917 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700918 // We print the docker build output whether or not the user
919 // has selected --verbose. Building an image takes a while
920 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700921 cmd.Stdout = os.Stdout
922 cmd.Stderr = os.Stderr
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700923 fmt.Printf("🏗️ building docker image %s from base %s...\n", imgName, baseImage)
Earl Lee2e463fb2025-04-17 11:22:22 -0700924
925 err = run(ctx, "docker build", cmd)
926 if err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700927 return fmt.Errorf("docker build failed: %v", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700928 }
929 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700930 return nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700931}
932
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700933func checkForEmptyGitRepo(ctx context.Context, path string) error {
934 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
935 cmd.Dir = path
936 _, err := cmd.CombinedOutput()
937 if err != nil {
938 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
939 "git commit --allow-empty -m 'initial commit'")
940 }
941 return nil
942}
943
Earl Lee2e463fb2025-04-17 11:22:22 -0700944func findGitRoot(ctx context.Context, path string) (string, error) {
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400945 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
Earl Lee2e463fb2025-04-17 11:22:22 -0700946 cmd.Dir = path
947 out, err := cmd.CombinedOutput()
948 if err != nil {
949 if strings.Contains(string(out), "not a git repository") {
950 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
951Consider one of the following options:
952 - cd to a different dir that is already part of a git repo first, or
953 - to create a new git repo from this directory (%s), run this command:
954
955 git init . && git commit --allow-empty -m "initial commit"
956
957and try running sketch again.
958`, path, path)
959 }
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400960 return "", fmt.Errorf("git rev-parse --show-toplevel: %s: %w", out, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700961 }
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400962 // The returned path is absolute.
963 return strings.TrimSpace(string(out)), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700964}
965
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000966// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
967// from git config using the sketch.envfwd multi-valued key.
968func getEnvForwardingFromGitConfig(ctx context.Context) []string {
969 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
970 out := string(outb)
971 if err != nil {
972 if strings.Contains(out, "key does not exist") {
973 return nil
974 }
975 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
976 return nil
977 }
978
979 var envVars []string
980 for envVar := range strings.Lines(out) {
981 envVar = strings.TrimSpace(envVar)
982 if envVar == "" {
983 continue
984 }
985 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
986 }
987 return envVars
988}
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000989
990// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
991// It handles quoted arguments and escaped characters.
992//
993// Examples:
994//
995// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
996// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
997// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
998func parseDockerArgs(args string) []string {
999 if args = strings.TrimSpace(args); args == "" {
1000 return []string{}
1001 }
1002
1003 var result []string
1004 var current strings.Builder
1005 inQuotes := false
1006 escapeNext := false
1007 quoteChar := rune(0)
1008
1009 for _, char := range args {
1010 if escapeNext {
1011 current.WriteRune(char)
1012 escapeNext = false
1013 continue
1014 }
1015
1016 if char == '\\' {
1017 escapeNext = true
1018 continue
1019 }
1020
1021 if char == '"' || char == '\'' {
1022 if !inQuotes {
1023 inQuotes = true
1024 quoteChar = char
1025 continue
1026 } else if char == quoteChar {
1027 inQuotes = false
1028 quoteChar = rune(0)
1029 continue
1030 }
1031 // Non-matching quote character inside quotes
1032 current.WriteRune(char)
1033 continue
1034 }
1035
1036 // Space outside of quotes is an argument separator
1037 if char == ' ' && !inQuotes {
1038 if current.Len() > 0 {
1039 result = append(result, current.String())
1040 current.Reset()
1041 }
1042 continue
1043 }
1044
1045 current.WriteRune(char)
1046 }
1047
1048 // Add the last argument if there is one
1049 if current.Len() > 0 {
1050 result = append(result, current.String())
1051 }
1052
1053 return result
1054}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001055
1056// buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled.
1057// This avoids cross-compilation issues with CGO which is required for the race detector.
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001058// Mounts host Go module cache and build cache for faster subsequent builds.
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001059func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) {
1060 // Find the git repo root
1061 currentDir, err := os.Getwd()
1062 if err != nil {
1063 return "", fmt.Errorf("could not get current directory: %w", err)
1064 }
1065
1066 gitRoot, err := findGitRoot(ctx, currentDir)
1067 if err != nil {
1068 return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err)
1069 }
1070
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001071 // Get host Go cache directories to mount for faster builds
1072 goCacheDir, err := getHostGoCacheDir(ctx)
1073 if err != nil {
1074 return "", fmt.Errorf("failed to get host GOCACHE: %w", err)
1075 }
1076 goModCacheDir, err := getHostGoModCacheDir(ctx)
1077 if err != nil {
1078 return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err)
1079 }
1080
1081 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 -07001082
1083 // Use the published Docker image tag
1084 imageTag := dockerfileBaseHash()
1085 imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag)
1086
1087 // Create destination directory for the binary
1088 destPath := filepath.Join(linuxGopath, "bin")
1089 if err := os.MkdirAll(destPath, 0o777); err != nil {
1090 return "", fmt.Errorf("failed to create destination directory: %w", err)
1091 }
1092 destFile := filepath.Join(destPath, "sketch")
1093
1094 // Create a unique container name
1095 containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano())
1096
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001097 // Run a container with the repo mounted and Go caches for faster builds
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001098 start := time.Now()
1099 slog.DebugContext(ctx, "running Docker container to build sketch with race detector")
1100
1101 // Use explicit output path for clarity
1102 runArgs := []string{
1103 "run",
1104 "--name", containerID,
1105 "-v", gitRoot + ":/app",
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001106 "-v", goCacheDir + ":/root/.cache/go-build",
1107 "-v", goModCacheDir + ":/go/pkg/mod",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001108 "-w", "/app",
1109 imgName,
Josh Bleecher Snyderf4f929a2025-05-23 17:19:26 +00001110 "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 -07001111 }
1112
1113 out, err := combinedOutput(ctx, "docker", runArgs...)
1114 if err != nil {
1115 // Print the output to help with debugging
1116 slog.ErrorContext(ctx, "docker run for race build failed",
1117 slog.String("output", string(out)),
1118 slog.String("error", err.Error()))
1119 return "", fmt.Errorf("docker run failed: %s: %w", out, err)
1120 }
1121
1122 slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start))
1123
1124 // Copy the binary from the container using the explicit path
1125 out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile)
1126 if err != nil {
1127 return "", fmt.Errorf("docker cp failed: %s: %w", out, err)
1128 }
1129
1130 // Clean up the container
1131 if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil {
1132 slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out))
1133 }
1134
1135 // Make the binary executable
1136 if err := os.Chmod(destFile, 0o755); err != nil {
1137 return "", fmt.Errorf("failed to make binary executable: %w", err)
1138 }
1139
1140 return destFile, nil
1141}
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001142
1143// getHostGoCacheDir returns the host's GOCACHE directory
1144func getHostGoCacheDir(ctx context.Context) (string, error) {
1145 out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput()
1146 if err != nil {
1147 return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err)
1148 }
1149 return strings.TrimSpace(string(out)), nil
1150}
1151
1152// getHostGoModCacheDir returns the host's GOMODCACHE directory
1153func getHostGoModCacheDir(ctx context.Context) (string, error) {
1154 out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput()
1155 if err != nil {
1156 return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err)
1157 }
1158 return strings.TrimSpace(string(out)), nil
1159}
David Crawshaw1bd636c2025-06-13 19:56:27 +00001160
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001161// copyEmbeddedLinuxBinaryToContainer copies the embedded linux binary to the container
1162func copyEmbeddedLinuxBinaryToContainer(ctx context.Context, containerName string) error {
1163 bin := embedded.LinuxBinary()
1164 if bin == nil {
1165 return fmt.Errorf("nil embedded linux binary reader, did you build using `make`?")
1166 }
1167
1168 cacheDir := filepath.Join(os.TempDir(), "sketch-binary-cache")
1169 if err := os.MkdirAll(cacheDir, 0o700); err != nil {
1170 return fmt.Errorf("failed to create cache directory: %w", err)
1171 }
1172
1173 hash := sha256.Sum256(bin)
1174 binaryPath := filepath.Join(cacheDir, hex.EncodeToString(hash[:]))
1175 _, statErr := os.Stat(binaryPath)
1176 switch {
1177 case os.IsNotExist(statErr):
1178 if err := os.WriteFile(binaryPath, bin, 0o700); err != nil {
1179 return fmt.Errorf("failed to write binary to cache: %w", err)
1180 }
1181 case statErr != nil:
1182 return fmt.Errorf("failed to check if cached binary exists: %w", statErr)
1183 }
1184 // TODO: clean up old sketch binaries from the cache dir:
1185 // maybe set a max of 5, and then delete oldest after that by atime/mtime/ctime
1186
1187 if out, err := combinedOutput(ctx, "docker", "cp", binaryPath, containerName+":/bin/sketch"); err != nil {
1188 return fmt.Errorf("docker cp failed: %s: %w", out, err)
1189 }
1190
1191 slog.DebugContext(ctx, "copied embedded linux binary to container", "container", containerName)
1192 return nil
1193}
1194
David Crawshaw1bd636c2025-06-13 19:56:27 +00001195const seccompProfile = `{
1196 "defaultAction": "SCMP_ACT_ALLOW",
1197 "syscalls": [
1198 {
1199 "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"],
1200 "action": "SCMP_ACT_ERRNO",
1201 "args": [
1202 {
1203 "index": 0,
1204 "value": 1,
1205 "op": "SCMP_CMP_EQ"
1206 }
1207 ]
1208 }
1209 ]
1210}`
1211
1212// ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist.
1213func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) {
1214 homeDir, err := os.UserHomeDir()
1215 if err != nil {
1216 return "", fmt.Errorf("failed to get home directory: %w", err)
1217 }
1218 cacheDir := filepath.Join(homeDir, ".cache", "sketch")
1219 if err := os.MkdirAll(cacheDir, 0o755); err != nil {
1220 return "", fmt.Errorf("failed to create cache directory: %w", err)
1221 }
1222 seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json")
1223
1224 curBytes, err := os.ReadFile(seccompPath)
1225 if err != nil && !os.IsNotExist(err) {
1226 return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err)
1227 }
1228 if string(curBytes) == seccompProfile {
1229 return seccompPath, nil // File already exists and matches the expected profile
1230 }
1231
1232 if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil {
1233 return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err)
1234 }
1235 slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath)
1236 return seccompPath, nil
1237}