blob: e2079041c74e77096c37938a52b255f410b3fdfc [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 Snyder4f84ab72025-04-22 16:40:54 -070026 "sketch.dev/llm/ant"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070027 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070028 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070029 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070030)
31
32// ContainerConfig holds all configuration for launching a container
33type ContainerConfig struct {
34 // SessionID is the unique identifier for this session
35 SessionID string
36
37 // LocalAddr is the initial address to use (though it may be overwritten later)
38 LocalAddr string
39
40 // SkabandAddr is the address of the skaband service if available
41 SkabandAddr string
42
David Crawshaw5a7b3692025-05-05 16:49:15 -070043 // Model is the name of the LLM model to use.
44 Model string
Earl Lee2e463fb2025-04-17 11:22:22 -070045
David Crawshaw5a7b3692025-05-05 16:49:15 -070046 // ModelURL is the URL of the LLM service.
47 ModelURL string
48
49 // ModelAPIKey is the API key for LLM service.
50 ModelAPIKey string
Earl Lee2e463fb2025-04-17 11:22:22 -070051
52 // Path is the local filesystem path to use
53 Path string
54
55 // GitUsername is the username to use for git operations
56 GitUsername string
57
58 // GitEmail is the email to use for git operations
59 GitEmail string
60
61 // OpenBrowser determines whether to open a browser automatically
62 OpenBrowser bool
63
64 // NoCleanup prevents container cleanup when set to true
65 NoCleanup bool
66
67 // ForceRebuild forces rebuilding of the Docker image even if it exists
68 ForceRebuild bool
69
70 // Host directory to copy container logs into, if not set to ""
71 ContainerLogDest string
72
73 // Path to pre-built linux sketch binary, or build a new one if set to ""
74 SketchBinaryLinux string
75
76 // Sketch client public key.
77 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000078
Sean McCulloughbaa2b592025-04-23 10:40:08 -070079 // Host port for the container's ssh server
80 SSHPort int
81
Philip Zeyliger18532b22025-04-23 21:11:46 +000082 // Outside information to pass to the container
83 OutsideHostname string
84 OutsideOS string
85 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070086
Pokey Rule0dcebe12025-04-28 14:51:04 +010087 // If true, exit after the first turn
88 OneShot bool
89
90 // Initial prompt
91 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000092
David Crawshawb5f6a002025-05-05 08:27:16 -070093 // Verbose enables verbose output
94 Verbose bool
Philip Zeyliger1dc21372025-05-05 19:54:44 +000095
96 // DockerArgs are additional arguments to pass to the docker create command
97 DockerArgs string
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +000098
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +000099 // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container
100 Mounts []string
101
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000102 // ExperimentFlag contains the experimental features to enable
103 ExperimentFlag string
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700104
105 // TermUI enables terminal UI
106 TermUI bool
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700107
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000108 // Budget configuration
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000109 MaxDollars float64
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000110
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700111 GitRemoteUrl string
112
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000113 // Upstream branch for git work
114 Upstream string
115
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700116 // Commit hash to checkout from GetRemoteUrl
117 Commit string
118
119 // Outtie's HTTP server
120 OutsideHTTP string
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000121
122 // Prefix for git branches created by sketch
123 BranchPrefix string
philip.zeyliger6d3de482025-06-10 19:38:14 -0700124
125 // LinkToGitHub enables GitHub branch linking in UI
126 LinkToGitHub bool
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700127
128 // SubtraceToken enables running sketch under subtrace.dev (development only)
129 SubtraceToken string
Earl Lee2e463fb2025-04-17 11:22:22 -0700130}
131
132// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
133// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700134func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700135 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700136 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700137 if runtime.GOOS == "darwin" {
138 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
139 } else {
140 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
141 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700142 }
143
144 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
145 // `docker ps` provides a good error message here that can be
146 // easily chatgpt'ed by users, so send it to the user as-is:
147 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
148 return fmt.Errorf("docker ps: %s (%w)", out, err)
149 }
150
151 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
152 if err != nil {
153 return err
154 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700155 gitRoot, err := findGitRoot(ctx, config.Path)
156 if err != nil {
157 return err
158 }
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700159 err = checkForEmptyGitRepo(ctx, config.Path)
160 if err != nil {
161 return err
162 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700163
David Crawshaw5a7b3692025-05-05 16:49:15 -0700164 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700165 if err != nil {
166 return err
167 }
168
169 linuxSketchBin := config.SketchBinaryLinux
170 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700171 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700172 if err != nil {
173 return err
174 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700175 }
176
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000177 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700178 defer func() {
179 if config.NoCleanup {
180 return
181 }
182 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
183 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
184 _ = out
185 }
186 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
187 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
188 _ = out
189 }
190 }()
191
192 // errCh receives errors from operations that this function calls in separate goroutines.
193 errCh := make(chan error)
194
195 // Start the git server
196 gitSrv, err := newGitServer(gitRoot)
197 if err != nil {
198 return fmt.Errorf("failed to start git server: %w", err)
199 }
200 defer gitSrv.shutdown(ctx)
201
202 go func() {
203 errCh <- gitSrv.serve(ctx)
204 }()
205
206 // Get the current host git commit
207 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000208 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
209 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700210 } else {
211 commit = strings.TrimSpace(string(out))
212 }
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000213
214 var upstream string
215 if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil {
216 slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err)
217 } else {
218 upstream = strings.TrimSpace(string(out))
219 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700220 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
221 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
222 }
223
224 relPath, err := filepath.Rel(gitRoot, config.Path)
225 if err != nil {
226 return err
227 }
228
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700229 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
230 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000231 config.Upstream = upstream
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700232 config.Commit = commit
233
Earl Lee2e463fb2025-04-17 11:22:22 -0700234 // Create the sketch container
235 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000236 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700237 }
238
239 // Copy the sketch linux binary into the container
240 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
241 return fmt.Errorf("docker cp: %s, %w", out, err)
242 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700243
244 // Make sure that the webui is built so we can copy the results to the container.
245 _, err = webui.Build()
246 if err != nil {
247 return fmt.Errorf("failed to build webui: %w", err)
248 }
249
David Crawshaw8bff16a2025-04-18 01:16:49 -0700250 webuiZipPath, err := webui.ZipPath()
251 if err != nil {
252 return err
253 }
254 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
255 return fmt.Errorf("docker cp: %s, %w", out, err)
256 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700257
David Crawshaw53786ef2025-04-24 12:52:51 -0700258 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700259
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700260 // Setup subtrace if token is provided (development only) - after container creation, before start
261 if config.SubtraceToken != "" {
262 fmt.Println("🔍 Setting up subtrace (development only)")
263 if err := setupSubtraceBeforeStart(ctx, cntrName, config.SubtraceToken); err != nil {
264 return fmt.Errorf("failed to setup subtrace: %w", err)
265 }
266 }
267
Earl Lee2e463fb2025-04-17 11:22:22 -0700268 // Start the sketch container
269 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
270 return fmt.Errorf("docker start: %s, %w", out, err)
271 }
272
273 // Copies structured logs from the container to the host.
274 copyLogs := func() {
275 if config.ContainerLogDest == "" {
276 return
277 }
278 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
279 if err != nil {
280 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
281 return
282 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700283 prefix := []byte("structured logs:")
284 for line := range bytes.Lines(out) {
285 rest, ok := bytes.CutPrefix(line, prefix)
286 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700287 continue
288 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700289 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700290 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
291 logFileName := filepath.Base(logFile)
292 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
293 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
294 if err != nil {
295 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
296 }
297 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
298 }
299 }
300
301 // NOTE: we want to see what the internal sketch binary prints
302 // regardless of the setting of the verbosity flag on the external
303 // binary, so reading "docker logs", which is the stdout/stderr of
304 // the internal binary is not conditional on the verbose flag.
305 appendInternalErr := func(err error) error {
306 if err == nil {
307 return nil
308 }
309 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000310 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700311 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
312 }
313 out = bytes.TrimSpace(out)
314 if len(out) > 0 {
315 return fmt.Errorf("docker logs: %s;\n%w", out, err)
316 }
317 return err
318 }
319
320 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700321 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700322 if err != nil {
323 return appendInternalErr(err)
324 }
325
Philip Zeyliger00442412025-05-14 11:03:23 -0700326 if config.Verbose {
327 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
328 }
329
Sean McCulloughae3480f2025-04-23 15:28:20 -0700330 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
331 if err != nil {
332 return appendInternalErr(err)
333 }
334 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
335 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700336 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700337 }
Sean McCullough4854c652025-04-24 18:37:02 -0700338
Sean McCullough7013e9e2025-05-14 02:03:58 +0000339 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700340
Sean McCullough078e85a2025-05-08 17:28:34 -0700341 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
342 if err != nil {
343 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
344 }
345
346 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700347 sshAvailable := false
348 sshErrMsg := ""
349 if sshErr != nil {
350 fmt.Println(sshErr.Error())
351 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700352 // continue - ssh config is not required for the rest of sketch to function locally.
353 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700354 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700355 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
356 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700357 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700358🖥️ ssh %s
359🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700360🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700361`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700362 sshUserIdentity = cst.userIdentity
363 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000364
365 // Get the Container CA public key for mutual auth
366 if cst.containerCAPublicKey != nil {
367 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
368 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
369 }
370
371 // Get the host certificate for mutual auth
372 hostCertificate = cst.hostCertificate
373
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700374 defer func() {
375 if err := cst.Cleanup(); err != nil {
376 appendInternalErr(err)
377 }
378 }()
379 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700380
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700381 // Tell the sketch container to Init(), which starts the SSH server
382 // and checks out the right commit.
383 // TODO: I'm trying to move as much configuration as possible into the command-line
384 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
385 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
386 // get the port Docker chose until after the process starts. The SSH config is
387 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
388 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700389 go func() {
390 // TODO: Why is this called in a goroutine? I have found that when I pull this out
391 // of the goroutine and call it inline, then the terminal UI clears itself and all
392 // the scrollback (which is not good, but also not fatal). I can't see why it does this
393 // though, since none of the calls in postContainerInitConfig obviously write to stdout
394 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700395 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700396 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
397 errCh <- appendInternalErr(err)
398 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700399
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700400 // 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 -0700401 ps1URL := "http://" + localAddr
402 if config.SkabandAddr != "" {
403 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700404 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700405 if config.OpenBrowser {
406 browser.Open(ps1URL)
407 }
408 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700409 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700410
Sean McCullough138ec242025-06-02 22:42:06 +0000411 // Start automatic port tunneling if SSH is available
412 if sshAvailable {
413 go func() {
414 containerURL := "http://" + localAddr
415 tunnelManager := NewTunnelManager(containerURL, cntrName, 10) // Allow up to 10 concurrent tunnels
416 tunnelManager.Start(ctx)
417 slog.InfoContext(ctx, "Started automatic port tunnel manager", "container", cntrName)
418 }()
419 }
420
Earl Lee2e463fb2025-04-17 11:22:22 -0700421 go func() {
422 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
423 cmd.Stdin = os.Stdin
424 cmd.Stdout = os.Stdout
425 cmd.Stderr = os.Stderr
426 errCh <- run(ctx, "docker attach", cmd)
427 }()
428
429 defer copyLogs()
430
431 for {
432 select {
433 case <-ctx.Done():
434 return ctx.Err()
435 case err := <-errCh:
436 if err != nil {
437 return appendInternalErr(fmt.Errorf("container process: %w", err))
438 }
439 return nil
440 }
441 }
442}
443
444func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
445 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700446 start := time.Now()
447
448 out, err := cmd.CombinedOutput()
449 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700450 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 -0700451 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700452 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 -0700453 }
454 return out, err
455}
456
457func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
458 start := time.Now()
459 err := cmd.Run()
460 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700461 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 -0700462 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700463 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 -0700464 }
465 return err
466}
467
468type gitServer struct {
469 gitLn net.Listener
470 gitPort string
471 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700472 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700473 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700474}
475
476func (gs *gitServer) shutdown(ctx context.Context) {
477 gs.srv.Shutdown(ctx)
478 gs.gitLn.Close()
479}
480
481// Serve a git remote from the host for the container to fetch from and push to.
482func (gs *gitServer) serve(ctx context.Context) error {
483 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
484 return gs.srv.Serve(gs.gitLn)
485}
486
487func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700488 ret := &gitServer{
489 pass: rand.Text(),
490 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700491
Earl Lee2e463fb2025-04-17 11:22:22 -0700492 gitLn, err := net.Listen("tcp4", ":0")
493 if err != nil {
494 return nil, fmt.Errorf("git listen: %w", err)
495 }
496 ret.gitLn = gitLn
497
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700498 browserC := make(chan bool, 1) // channel of browser open requests
499
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000500 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700501 for range browserC {
502 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000503 }
504 }()
505
506 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700507 ret.srv = &srv
508
509 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
510 if err != nil {
511 return nil, fmt.Errorf("git port: %w", err)
512 }
513 ret.gitPort = gitPort
514 return ret, nil
515}
516
517func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700518 cmdArgs := []string{
519 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700520 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700521 "--name", cntrName,
522 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700523 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700524 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700525 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700526 cmdArgs = append(cmdArgs, "-t")
527 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000528
529 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
530 cmdArgs = append(cmdArgs, "-e", envVar)
531 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700532 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700533 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700534 }
535 if config.SketchPubKey != "" {
536 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
537 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700538 if config.SSHPort > 0 {
539 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
540 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700541 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700542 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700543 if relPath != "." {
544 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
545 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700546 // colima does this by default, but Linux docker seems to need this set explicitly
547 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000548
David Crawshaw1bd636c2025-06-13 19:56:27 +0000549 // Add seccomp profile to prevent killing PID 1 (the sketch process itself)
550 // Write the seccomp profile to cache directory if it doesn't exist
551 seccompPath, err := ensureSeccompProfile(ctx)
552 if err != nil {
553 return fmt.Errorf("failed to create seccomp profile: %w", err)
554 }
555 cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath)
556
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700557 // Add subtrace environment variable if token is provided
558 if config.SubtraceToken != "" {
559 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_TOKEN="+config.SubtraceToken)
560 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_HTTP2=1")
561 }
562
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000563 // Add volume mounts if specified
564 for _, mount := range config.Mounts {
565 if mount != "" {
566 cmdArgs = append(cmdArgs, "-v", mount)
567 }
568 }
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700569 cmdArgs = append(cmdArgs, imgName)
570
571 // Add command: either [sketch] or [subtrace run -- sketch]
572 if config.SubtraceToken != "" {
573 cmdArgs = append(cmdArgs, "/usr/local/bin/subtrace", "run", "--", "/bin/sketch")
574 } else {
575 cmdArgs = append(cmdArgs, "/bin/sketch")
576 }
577
578 // Add all sketch arguments
579 cmdArgs = append(cmdArgs,
Earl Lee2e463fb2025-04-17 11:22:22 -0700580 "-unsafe",
581 "-addr=:80",
582 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000583 "-git-username="+config.GitUsername,
584 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000585 "-outside-hostname="+config.OutsideHostname,
586 "-outside-os="+config.OutsideOS,
587 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000588 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700589 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700590 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700591 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000592 "-x="+config.ExperimentFlag,
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000593 "-branch-prefix="+config.BranchPrefix,
philip.zeyliger6d3de482025-06-10 19:38:14 -0700594 "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub),
Earl Lee2e463fb2025-04-17 11:22:22 -0700595 )
philip.zeyliger8773e682025-06-11 21:36:21 -0700596 // Set SSH connection string based on session ID for SSH Theater
597 cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID)
David Crawshaw5a7b3692025-05-05 16:49:15 -0700598 if config.Model != "" {
599 cmdArgs = append(cmdArgs, "-model="+config.Model)
600 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700601 if config.GitRemoteUrl != "" {
602 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
603 if config.Commit == "" {
604 panic("Commit should have been set when GitRemoteUrl was set")
605 }
606 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000607 cmdArgs = append(cmdArgs, "-upstream="+config.Upstream)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700608 }
609 if config.OutsideHTTP != "" {
610 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
611 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000612 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100613 if config.Prompt != "" {
614 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
615 }
616 if config.OneShot {
617 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700618 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000619 if config.ModelURL == "" {
620 // Forward ANTHROPIC_API_KEY for direct use.
621 // TODO: have outtie run an http proxy?
622 // TODO: select and forward the relevant API key based on the model
623 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
624 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000625
626 // Add additional docker arguments if provided
627 if config.DockerArgs != "" {
628 // Parse space-separated docker arguments with support for quotes and escaping
629 args := parseDockerArgs(config.DockerArgs)
630 // Insert arguments after "create" but before other arguments
631 for i := len(args) - 1; i >= 0; i-- {
632 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
633 }
634 }
635
Earl Lee2e463fb2025-04-17 11:22:22 -0700636 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
637 return fmt.Errorf("docker create: %s, %w", out, err)
638 }
639 return nil
640}
641
David Crawshawb5f6a002025-05-05 08:27:16 -0700642func buildLinuxSketchBin(ctx context.Context) (string, error) {
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700643 // Detect if race detector is enabled and use a different cache path
644 raceEnabled := RaceEnabled()
645 cacheSuffix := ""
646 if raceEnabled {
647 cacheSuffix = "-race"
648 }
649
650 homeDir, err := os.UserHomeDir()
651 if err != nil {
652 return "", err
653 }
654
655 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix)
656 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
657 return "", err
658 }
659
660 // When race detector is enabled, use Docker to build the Linux binary
661 if raceEnabled {
662 return buildLinuxSketchBinWithDocker(ctx, linuxGopath)
663 }
664
665 // Standard non-race build using cross-compilation
Pokey Rulea9a786b2025-05-12 10:52:34 +0100666 // Change to directory containing dockerimg.go for module detection
667 _, codeFile, _, _ := runtime.Caller(0)
668 codeDir := filepath.Dir(codeFile)
669 if currentDir, err := os.Getwd(); err != nil {
670 slog.WarnContext(ctx, "could not get current directory", "err", err)
671 } else {
672 if err := os.Chdir(codeDir); err != nil {
673 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
674 } else {
675 defer func() {
676 _ = os.Chdir(currentDir)
677 }()
678 }
679 }
680
David Crawshaw8a617cb2025-04-18 01:28:43 -0700681 verToInstall := "@latest"
682 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
683 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
684 } else {
685 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700686 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700687 verToInstall = ""
688 }
689 }
David Crawshaw69c67312025-04-17 13:42:00 -0700690
Earl Lee2e463fb2025-04-17 11:22:22 -0700691 start := time.Now()
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700692 args := []string{"install"}
693 args = append(args, "sketch.dev/cmd/sketch"+verToInstall)
694
695 cmd := exec.CommandContext(ctx, "go", args...)
David Crawshawb9eaef52025-04-17 15:23:18 -0700696 cmd.Env = append(
697 os.Environ(),
698 "GOOS=linux",
699 "CGO_ENABLED=0",
700 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700701 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700702 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700703 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700704
Earl Lee2e463fb2025-04-17 11:22:22 -0700705 out, err := cmd.CombinedOutput()
706 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700707 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 -0700708 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
709 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700710 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 -0700711 }
712
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700713 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700714 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700715 }
David Crawshawc7e77962025-05-03 13:20:18 -0700716 // If we are already on Linux, there's no extra platform name in the path
717 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700718}
719
Sean McCulloughae3480f2025-04-23 15:28:20 -0700720func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700721 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700722 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700723 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
724 } else {
725 v4, _, found := strings.Cut(string(out), "\n")
726 if !found {
727 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
728 }
729 localAddr = v4
730 if strings.HasPrefix(localAddr, "0.0.0.0") {
731 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
732 }
733 }
734 return localAddr, nil
735}
736
737// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700738func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700739 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700740
741 initMsg, err := json.Marshal(
742 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000743 HostAddr: localAddr,
744 SSHAuthorizedKeys: sshAuthorizedKeys,
745 SSHServerIdentity: sshServerIdentity,
746 SSHContainerCAKey: sshContainerCAKey,
747 SSHHostCertificate: sshHostCertificate,
748 SSHAvailable: sshAvailable,
749 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700750 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700751 if err != nil {
752 return fmt.Errorf("init msg: %w", err)
753 }
754
Earl Lee2e463fb2025-04-17 11:22:22 -0700755 // Note: this /init POST is handled in loop/server/loophttp.go:
756 initMsgByteReader := bytes.NewReader(initMsg)
757 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
758 if err != nil {
759 return err
760 }
761
762 var res *http.Response
763 for i := 0; ; i++ {
764 time.Sleep(100 * time.Millisecond)
765 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
766 initMsgByteReader.Reset(initMsg)
767 res, err = http.DefaultClient.Do(req)
768 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700769 if i < 100 {
770 if i%10 == 0 {
771 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
772 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700773 continue
774 }
775 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
776 }
777 break
778 }
779 resBytes, _ := io.ReadAll(res.Body)
780 if res.StatusCode != http.StatusOK {
781 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
782 }
783 return nil
784}
785
David Crawshaw5a7b3692025-05-05 16:49:15 -0700786func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700787 h := sha256.Sum256([]byte(gitRoot))
788 imgName = "sketch-" + hex.EncodeToString(h[:6])
789
790 var curImgInitFilesHash string
791 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
792 if strings.Contains(string(out), "No such object") {
793 // Image does not exist, continue and build it.
794 curImgInitFilesHash = ""
795 } else {
796 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
797 }
798 } else {
799 m := map[string]string{}
800 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
801 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
802 }
803 curImgInitFilesHash = m["sketch_context"]
804 }
805
806 candidates, err := findRepoDockerfiles(cwd, gitRoot)
807 if err != nil {
808 return "", fmt.Errorf("find dockerfile: %w", err)
809 }
810
811 var initFiles map[string]string
812 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700813 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700814
Jon Friesend27921f2025-06-05 13:15:56 +0000815 // Prioritize Dockerfile.sketch over Dockerfile, then fall back to generated dockerfile
816 if len(candidates) > 0 {
817 dockerfilePath = prioritizeDockerfiles(candidates)
Earl Lee2e463fb2025-04-17 11:22:22 -0700818 contents, err := os.ReadFile(dockerfilePath)
819 if err != nil {
820 return "", err
821 }
Jon Friesend27921f2025-06-05 13:15:56 +0000822 fmt.Printf("using %s as dev env\n", dockerfilePath)
Earl Lee2e463fb2025-04-17 11:22:22 -0700823 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700824 return imgName, nil
825 }
826 } else {
827 initFiles, err = readInitFiles(os.DirFS(gitRoot))
828 if err != nil {
829 return "", err
830 }
831 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
832 if err != nil {
833 return "", err
834 }
835 initFileHash := hashInitFiles(initFiles)
836 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700837 return imgName, nil
838 }
839
David Crawshaw5a7b3692025-05-05 16:49:15 -0700840 if model == "gemini" {
841 if strings.HasSuffix(modelURL, "/gemmsgs") {
842 // Horrible hack! Switch back to anthropic for container building.
David Crawshaw3659d872025-05-05 17:52:23 -0700843 // We can do this because we are talking to skaband and know the address.
David Crawshaw5a7b3692025-05-05 16:49:15 -0700844 modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1)
845 } else {
846 return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini")
847 }
848 }
849
Earl Lee2e463fb2025-04-17 11:22:22 -0700850 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700851 srv := &ant.Service{
David Crawshaw5a7b3692025-05-05 16:49:15 -0700852 URL: modelURL,
853 APIKey: modelAPIKey,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700854 HTTPC: http.DefaultClient,
855 }
Pokey Rulec31e2962025-05-13 10:53:33 +0000856 generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700857 if err != nil {
858 return "", fmt.Errorf("create dockerfile: %w", err)
859 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000860 // Create a unique temporary directory for the Dockerfile
861 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
862 if err != nil {
863 return "", fmt.Errorf("failed to create temporary directory: %w", err)
864 }
865 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700866 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700867 return "", err
868 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000869 // Remove the temporary directory and all contents when done
870 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700871
David Crawshawb5f6a002025-05-05 08:27:16 -0700872 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700873 fmt.Fprintf(os.Stderr, "generated Dockerfile in %s:\n\t%s\n\n", time.Since(start).Round(time.Millisecond), strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
David Crawshawb5f6a002025-05-05 08:27:16 -0700874 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700875 }
876
877 var gitUserEmail, gitUserName string
878 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
Sean McCullough8ad17ba2025-06-09 00:43:57 +0000879 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 -0700880 } else {
881 gitUserEmail = strings.TrimSpace(string(out))
882 }
883 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
Sean McCullough8ad17ba2025-06-09 00:43:57 +0000884 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 -0700885 } else {
886 gitUserName = strings.TrimSpace(string(out))
887 }
888
889 start := time.Now()
890 cmd := exec.CommandContext(ctx,
891 "docker", "build",
892 "-t", imgName,
893 "-f", dockerfilePath,
894 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
895 "--build-arg", "GIT_USER_NAME="+gitUserName,
David Crawshaw31f15242025-05-06 16:03:49 -0700896 ".",
Earl Lee2e463fb2025-04-17 11:22:22 -0700897 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700898 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700899 // We print the docker build output whether or not the user
900 // has selected --verbose. Building an image takes a while
901 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700902 cmd.Stdout = os.Stdout
903 cmd.Stderr = os.Stderr
904 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700905
906 err = run(ctx, "docker build", cmd)
907 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700908 var msg string
909 if generatedDockerfile != "" {
910 if !verbose {
911 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
912 }
913 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
914 }
915 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700916 }
917 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
918 return imgName, nil
919}
920
921func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
922 files, err := findDirDockerfiles(cwd)
923 if err != nil {
924 return nil, err
925 }
926 if len(files) > 0 {
927 return files, nil
928 }
929
930 path := cwd
931 for path != gitRoot {
932 path = filepath.Dir(path)
933 files, err := findDirDockerfiles(path)
934 if err != nil {
935 return nil, err
936 }
937 if len(files) > 0 {
938 return files, nil
939 }
940 }
941 return files, nil
942}
943
Jon Friesend27921f2025-06-05 13:15:56 +0000944// prioritizeDockerfiles returns the highest priority dockerfile from a list of candidates.
945// Priority order: Dockerfile.sketch > Dockerfile > other Dockerfile.*
946func prioritizeDockerfiles(candidates []string) string {
947 if len(candidates) == 0 {
948 return ""
949 }
950 if len(candidates) == 1 {
951 return candidates[0]
952 }
953
954 // Look for Dockerfile.sketch first (case insensitive)
955 for _, candidate := range candidates {
956 basename := strings.ToLower(filepath.Base(candidate))
957 if basename == "dockerfile.sketch" {
958 return candidate
959 }
960 }
961
962 // Look for Dockerfile second (case insensitive)
963 for _, candidate := range candidates {
964 basename := strings.ToLower(filepath.Base(candidate))
965 if basename == "dockerfile" {
966 return candidate
967 }
968 }
969
970 // Return first remaining candidate
971 return candidates[0]
972}
973
Earl Lee2e463fb2025-04-17 11:22:22 -0700974// findDirDockerfiles finds all "Dockerfile*" files in a directory.
975func findDirDockerfiles(root string) (res []string, err error) {
976 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
977 if err != nil {
978 return err
979 }
980 if info.IsDir() && root != path {
981 return filepath.SkipDir
982 }
983 name := strings.ToLower(info.Name())
Josh Bleecher Snydera9fd88f2025-06-05 10:43:22 -0700984 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") || strings.HasSuffix(name, ".dockerfile") {
Earl Lee2e463fb2025-04-17 11:22:22 -0700985 res = append(res, path)
986 }
987 return nil
988 })
989 if err != nil {
990 return nil, err
991 }
992 return res, nil
993}
994
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700995func checkForEmptyGitRepo(ctx context.Context, path string) error {
996 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
997 cmd.Dir = path
998 _, err := cmd.CombinedOutput()
999 if err != nil {
1000 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
1001 "git commit --allow-empty -m 'initial commit'")
1002 }
1003 return nil
1004}
1005
Earl Lee2e463fb2025-04-17 11:22:22 -07001006func findGitRoot(ctx context.Context, path string) (string, error) {
1007 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
1008 cmd.Dir = path
1009 out, err := cmd.CombinedOutput()
1010 if err != nil {
1011 if strings.Contains(string(out), "not a git repository") {
1012 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
1013Consider one of the following options:
1014 - cd to a different dir that is already part of a git repo first, or
1015 - to create a new git repo from this directory (%s), run this command:
1016
1017 git init . && git commit --allow-empty -m "initial commit"
1018
1019and try running sketch again.
1020`, path, path)
1021 }
1022 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
1023 }
1024 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
1025 absGitDir := filepath.Join(path, gitDir)
1026 return filepath.Dir(absGitDir), err
1027}
1028
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +00001029// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
1030// from git config using the sketch.envfwd multi-valued key.
1031func getEnvForwardingFromGitConfig(ctx context.Context) []string {
1032 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
1033 out := string(outb)
1034 if err != nil {
1035 if strings.Contains(out, "key does not exist") {
1036 return nil
1037 }
1038 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
1039 return nil
1040 }
1041
1042 var envVars []string
1043 for envVar := range strings.Lines(out) {
1044 envVar = strings.TrimSpace(envVar)
1045 if envVar == "" {
1046 continue
1047 }
1048 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
1049 }
1050 return envVars
1051}
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001052
1053// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
1054// It handles quoted arguments and escaped characters.
1055//
1056// Examples:
1057//
1058// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
1059// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
1060// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
1061func parseDockerArgs(args string) []string {
1062 if args = strings.TrimSpace(args); args == "" {
1063 return []string{}
1064 }
1065
1066 var result []string
1067 var current strings.Builder
1068 inQuotes := false
1069 escapeNext := false
1070 quoteChar := rune(0)
1071
1072 for _, char := range args {
1073 if escapeNext {
1074 current.WriteRune(char)
1075 escapeNext = false
1076 continue
1077 }
1078
1079 if char == '\\' {
1080 escapeNext = true
1081 continue
1082 }
1083
1084 if char == '"' || char == '\'' {
1085 if !inQuotes {
1086 inQuotes = true
1087 quoteChar = char
1088 continue
1089 } else if char == quoteChar {
1090 inQuotes = false
1091 quoteChar = rune(0)
1092 continue
1093 }
1094 // Non-matching quote character inside quotes
1095 current.WriteRune(char)
1096 continue
1097 }
1098
1099 // Space outside of quotes is an argument separator
1100 if char == ' ' && !inQuotes {
1101 if current.Len() > 0 {
1102 result = append(result, current.String())
1103 current.Reset()
1104 }
1105 continue
1106 }
1107
1108 current.WriteRune(char)
1109 }
1110
1111 // Add the last argument if there is one
1112 if current.Len() > 0 {
1113 result = append(result, current.String())
1114 }
1115
1116 return result
1117}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001118
1119// buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled.
1120// This avoids cross-compilation issues with CGO which is required for the race detector.
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001121// Mounts host Go module cache and build cache for faster subsequent builds.
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001122func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) {
1123 // Find the git repo root
1124 currentDir, err := os.Getwd()
1125 if err != nil {
1126 return "", fmt.Errorf("could not get current directory: %w", err)
1127 }
1128
1129 gitRoot, err := findGitRoot(ctx, currentDir)
1130 if err != nil {
1131 return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err)
1132 }
1133
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001134 // Get host Go cache directories to mount for faster builds
1135 goCacheDir, err := getHostGoCacheDir(ctx)
1136 if err != nil {
1137 return "", fmt.Errorf("failed to get host GOCACHE: %w", err)
1138 }
1139 goModCacheDir, err := getHostGoModCacheDir(ctx)
1140 if err != nil {
1141 return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err)
1142 }
1143
1144 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 -07001145
1146 // Use the published Docker image tag
1147 imageTag := dockerfileBaseHash()
1148 imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag)
1149
1150 // Create destination directory for the binary
1151 destPath := filepath.Join(linuxGopath, "bin")
1152 if err := os.MkdirAll(destPath, 0o777); err != nil {
1153 return "", fmt.Errorf("failed to create destination directory: %w", err)
1154 }
1155 destFile := filepath.Join(destPath, "sketch")
1156
1157 // Create a unique container name
1158 containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano())
1159
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001160 // Run a container with the repo mounted and Go caches for faster builds
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001161 start := time.Now()
1162 slog.DebugContext(ctx, "running Docker container to build sketch with race detector")
1163
1164 // Use explicit output path for clarity
1165 runArgs := []string{
1166 "run",
1167 "--name", containerID,
1168 "-v", gitRoot + ":/app",
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001169 "-v", goCacheDir + ":/root/.cache/go-build",
1170 "-v", goModCacheDir + ":/go/pkg/mod",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001171 "-w", "/app",
1172 imgName,
Josh Bleecher Snyderf4f929a2025-05-23 17:19:26 +00001173 "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 -07001174 }
1175
1176 out, err := combinedOutput(ctx, "docker", runArgs...)
1177 if err != nil {
1178 // Print the output to help with debugging
1179 slog.ErrorContext(ctx, "docker run for race build failed",
1180 slog.String("output", string(out)),
1181 slog.String("error", err.Error()))
1182 return "", fmt.Errorf("docker run failed: %s: %w", out, err)
1183 }
1184
1185 slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start))
1186
1187 // Copy the binary from the container using the explicit path
1188 out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile)
1189 if err != nil {
1190 return "", fmt.Errorf("docker cp failed: %s: %w", out, err)
1191 }
1192
1193 // Clean up the container
1194 if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil {
1195 slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out))
1196 }
1197
1198 // Make the binary executable
1199 if err := os.Chmod(destFile, 0o755); err != nil {
1200 return "", fmt.Errorf("failed to make binary executable: %w", err)
1201 }
1202
1203 return destFile, nil
1204}
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001205
1206// getHostGoCacheDir returns the host's GOCACHE directory
1207func getHostGoCacheDir(ctx context.Context) (string, error) {
1208 out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput()
1209 if err != nil {
1210 return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err)
1211 }
1212 return strings.TrimSpace(string(out)), nil
1213}
1214
1215// getHostGoModCacheDir returns the host's GOMODCACHE directory
1216func getHostGoModCacheDir(ctx context.Context) (string, error) {
1217 out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput()
1218 if err != nil {
1219 return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err)
1220 }
1221 return strings.TrimSpace(string(out)), nil
1222}
David Crawshaw1bd636c2025-06-13 19:56:27 +00001223
1224const seccompProfile = `{
1225 "defaultAction": "SCMP_ACT_ALLOW",
1226 "syscalls": [
1227 {
1228 "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"],
1229 "action": "SCMP_ACT_ERRNO",
1230 "args": [
1231 {
1232 "index": 0,
1233 "value": 1,
1234 "op": "SCMP_CMP_EQ"
1235 }
1236 ]
1237 }
1238 ]
1239}`
1240
1241// ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist.
1242func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) {
1243 homeDir, err := os.UserHomeDir()
1244 if err != nil {
1245 return "", fmt.Errorf("failed to get home directory: %w", err)
1246 }
1247 cacheDir := filepath.Join(homeDir, ".cache", "sketch")
1248 if err := os.MkdirAll(cacheDir, 0o755); err != nil {
1249 return "", fmt.Errorf("failed to create cache directory: %w", err)
1250 }
1251 seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json")
1252
1253 curBytes, err := os.ReadFile(seccompPath)
1254 if err != nil && !os.IsNotExist(err) {
1255 return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err)
1256 }
1257 if string(curBytes) == seccompProfile {
1258 return seccompPath, nil // File already exists and matches the expected profile
1259 }
1260
1261 if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil {
1262 return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err)
1263 }
1264 slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath)
1265 return seccompPath, nil
1266}