blob: e5ad648aae91faa82daa73fba8a04d4a4cae8a7e [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"
Kilian Lackhove23772f42025-06-18 20:28:58 +020026 "sketch.dev/llm"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070027 "sketch.dev/llm/ant"
Kilian Lackhove23772f42025-06-18 20:28:58 +020028 "sketch.dev/llm/gem"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070029 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070030 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070031 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070032)
33
34// ContainerConfig holds all configuration for launching a container
35type ContainerConfig struct {
36 // SessionID is the unique identifier for this session
37 SessionID string
38
39 // LocalAddr is the initial address to use (though it may be overwritten later)
40 LocalAddr string
41
42 // SkabandAddr is the address of the skaband service if available
43 SkabandAddr string
44
David Crawshaw5a7b3692025-05-05 16:49:15 -070045 // Model is the name of the LLM model to use.
46 Model string
Earl Lee2e463fb2025-04-17 11:22:22 -070047
David Crawshaw5a7b3692025-05-05 16:49:15 -070048 // ModelURL is the URL of the LLM service.
49 ModelURL string
50
51 // ModelAPIKey is the API key for LLM service.
52 ModelAPIKey string
Earl Lee2e463fb2025-04-17 11:22:22 -070053
54 // Path is the local filesystem path to use
55 Path string
56
57 // GitUsername is the username to use for git operations
58 GitUsername string
59
60 // GitEmail is the email to use for git operations
61 GitEmail string
62
63 // OpenBrowser determines whether to open a browser automatically
64 OpenBrowser bool
65
66 // NoCleanup prevents container cleanup when set to true
67 NoCleanup bool
68
69 // ForceRebuild forces rebuilding of the Docker image even if it exists
70 ForceRebuild bool
71
72 // 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
Earl Lee2e463fb2025-04-17 11:22:22 -0700132}
133
134// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
135// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700136func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700137 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700138 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700139 if runtime.GOOS == "darwin" {
140 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
141 } else {
142 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
143 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700144 }
145
146 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
147 // `docker ps` provides a good error message here that can be
148 // easily chatgpt'ed by users, so send it to the user as-is:
149 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
150 return fmt.Errorf("docker ps: %s (%w)", out, err)
151 }
152
153 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
154 if err != nil {
155 return err
156 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700157 gitRoot, err := findGitRoot(ctx, config.Path)
158 if err != nil {
159 return err
160 }
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700161 err = checkForEmptyGitRepo(ctx, config.Path)
162 if err != nil {
163 return err
164 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700165
David Crawshaw5a7b3692025-05-05 16:49:15 -0700166 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700167 if err != nil {
168 return err
169 }
170
171 linuxSketchBin := config.SketchBinaryLinux
172 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700173 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700174 if err != nil {
175 return err
176 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700177 }
178
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000179 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700180 defer func() {
181 if config.NoCleanup {
182 return
183 }
184 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
185 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
186 _ = out
187 }
188 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
189 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
190 _ = out
191 }
192 }()
193
194 // errCh receives errors from operations that this function calls in separate goroutines.
195 errCh := make(chan error)
196
197 // Start the git server
198 gitSrv, err := newGitServer(gitRoot)
199 if err != nil {
200 return fmt.Errorf("failed to start git server: %w", err)
201 }
202 defer gitSrv.shutdown(ctx)
203
204 go func() {
205 errCh <- gitSrv.serve(ctx)
206 }()
207
208 // Get the current host git commit
209 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000210 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
211 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700212 } else {
213 commit = strings.TrimSpace(string(out))
214 }
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000215
216 var upstream string
217 if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil {
218 slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err)
219 } else {
220 upstream = strings.TrimSpace(string(out))
221 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700222 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
223 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
224 }
225
226 relPath, err := filepath.Rel(gitRoot, config.Path)
227 if err != nil {
228 return err
229 }
230
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700231 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
232 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000233 config.Upstream = upstream
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700234 config.Commit = commit
235
Earl Lee2e463fb2025-04-17 11:22:22 -0700236 // Create the sketch container
237 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000238 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700239 }
240
241 // Copy the sketch linux binary into the container
242 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
243 return fmt.Errorf("docker cp: %s, %w", out, err)
244 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700245
246 // Make sure that the webui is built so we can copy the results to the container.
247 _, err = webui.Build()
248 if err != nil {
249 return fmt.Errorf("failed to build webui: %w", err)
250 }
251
David Crawshaw8bff16a2025-04-18 01:16:49 -0700252 webuiZipPath, err := webui.ZipPath()
253 if err != nil {
254 return err
255 }
256 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
257 return fmt.Errorf("docker cp: %s, %w", out, err)
258 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700259
David Crawshaw53786ef2025-04-24 12:52:51 -0700260 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700261
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700262 // Setup subtrace if token is provided (development only) - after container creation, before start
263 if config.SubtraceToken != "" {
264 fmt.Println("🔍 Setting up subtrace (development only)")
265 if err := setupSubtraceBeforeStart(ctx, cntrName, config.SubtraceToken); err != nil {
266 return fmt.Errorf("failed to setup subtrace: %w", err)
267 }
268 }
269
Earl Lee2e463fb2025-04-17 11:22:22 -0700270 // Start the sketch container
271 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
272 return fmt.Errorf("docker start: %s, %w", out, err)
273 }
274
275 // Copies structured logs from the container to the host.
276 copyLogs := func() {
277 if config.ContainerLogDest == "" {
278 return
279 }
280 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
281 if err != nil {
282 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
283 return
284 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700285 prefix := []byte("structured logs:")
286 for line := range bytes.Lines(out) {
287 rest, ok := bytes.CutPrefix(line, prefix)
288 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700289 continue
290 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700291 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700292 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
293 logFileName := filepath.Base(logFile)
294 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
295 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
296 if err != nil {
297 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
298 }
299 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
300 }
301 }
302
303 // NOTE: we want to see what the internal sketch binary prints
304 // regardless of the setting of the verbosity flag on the external
305 // binary, so reading "docker logs", which is the stdout/stderr of
306 // the internal binary is not conditional on the verbose flag.
307 appendInternalErr := func(err error) error {
308 if err == nil {
309 return nil
310 }
311 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000312 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700313 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
314 }
315 out = bytes.TrimSpace(out)
316 if len(out) > 0 {
317 return fmt.Errorf("docker logs: %s;\n%w", out, err)
318 }
319 return err
320 }
321
322 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700323 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700324 if err != nil {
325 return appendInternalErr(err)
326 }
327
Philip Zeyliger00442412025-05-14 11:03:23 -0700328 if config.Verbose {
329 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
330 }
331
Sean McCulloughae3480f2025-04-23 15:28:20 -0700332 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
333 if err != nil {
334 return appendInternalErr(err)
335 }
336 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
337 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700338 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700339 }
Sean McCullough4854c652025-04-24 18:37:02 -0700340
Sean McCullough7013e9e2025-05-14 02:03:58 +0000341 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700342
banksean29d689f2025-06-23 15:41:26 +0000343 cst, err := NewLocalSSHimmer(cntrName, sshHost, sshPort)
Sean McCullough078e85a2025-05-08 17:28:34 -0700344 if err != nil {
345 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
346 }
347
348 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700349 sshAvailable := false
350 sshErrMsg := ""
351 if sshErr != nil {
352 fmt.Println(sshErr.Error())
353 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700354 // continue - ssh config is not required for the rest of sketch to function locally.
355 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700356 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700357 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
358 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700359 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700360🖥️ ssh %s
361🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700362🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700363`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700364 sshUserIdentity = cst.userIdentity
365 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000366
367 // Get the Container CA public key for mutual auth
368 if cst.containerCAPublicKey != nil {
369 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
370 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
371 }
372
373 // Get the host certificate for mutual auth
374 hostCertificate = cst.hostCertificate
375
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700376 defer func() {
377 if err := cst.Cleanup(); err != nil {
378 appendInternalErr(err)
379 }
380 }()
381 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700382
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700383 // Tell the sketch container to Init(), which starts the SSH server
384 // and checks out the right commit.
385 // TODO: I'm trying to move as much configuration as possible into the command-line
386 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
387 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
388 // get the port Docker chose until after the process starts. The SSH config is
389 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
390 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700391 go func() {
392 // TODO: Why is this called in a goroutine? I have found that when I pull this out
393 // of the goroutine and call it inline, then the terminal UI clears itself and all
394 // the scrollback (which is not good, but also not fatal). I can't see why it does this
395 // though, since none of the calls in postContainerInitConfig obviously write to stdout
396 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700397 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700398 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
399 errCh <- appendInternalErr(err)
400 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700401
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700402 // 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 -0700403 ps1URL := "http://" + localAddr
404 if config.SkabandAddr != "" {
405 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700406 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700407 if config.OpenBrowser {
408 browser.Open(ps1URL)
409 }
410 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700411 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700412
Sean McCullough138ec242025-06-02 22:42:06 +0000413 // Start automatic port tunneling if SSH is available
414 if sshAvailable {
415 go func() {
416 containerURL := "http://" + localAddr
417 tunnelManager := NewTunnelManager(containerURL, cntrName, 10) // Allow up to 10 concurrent tunnels
418 tunnelManager.Start(ctx)
419 slog.InfoContext(ctx, "Started automatic port tunnel manager", "container", cntrName)
420 }()
421 }
422
Earl Lee2e463fb2025-04-17 11:22:22 -0700423 go func() {
424 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
425 cmd.Stdin = os.Stdin
426 cmd.Stdout = os.Stdout
427 cmd.Stderr = os.Stderr
428 errCh <- run(ctx, "docker attach", cmd)
429 }()
430
431 defer copyLogs()
432
433 for {
434 select {
435 case <-ctx.Done():
436 return ctx.Err()
437 case err := <-errCh:
438 if err != nil {
439 return appendInternalErr(fmt.Errorf("container process: %w", err))
440 }
441 return nil
442 }
443 }
444}
445
446func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
447 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700448 start := time.Now()
449
450 out, err := cmd.CombinedOutput()
451 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700452 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 -0700453 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700454 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 -0700455 }
456 return out, err
457}
458
459func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
460 start := time.Now()
461 err := cmd.Run()
462 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700463 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 -0700464 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700465 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 -0700466 }
467 return err
468}
469
470type gitServer struct {
471 gitLn net.Listener
472 gitPort string
473 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700474 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700475 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700476}
477
478func (gs *gitServer) shutdown(ctx context.Context) {
479 gs.srv.Shutdown(ctx)
480 gs.gitLn.Close()
481}
482
483// Serve a git remote from the host for the container to fetch from and push to.
484func (gs *gitServer) serve(ctx context.Context) error {
485 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
486 return gs.srv.Serve(gs.gitLn)
487}
488
489func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700490 ret := &gitServer{
491 pass: rand.Text(),
492 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700493
Earl Lee2e463fb2025-04-17 11:22:22 -0700494 gitLn, err := net.Listen("tcp4", ":0")
495 if err != nil {
496 return nil, fmt.Errorf("git listen: %w", err)
497 }
498 ret.gitLn = gitLn
499
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700500 browserC := make(chan bool, 1) // channel of browser open requests
501
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000502 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700503 for range browserC {
504 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000505 }
506 }()
507
508 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700509 ret.srv = &srv
510
511 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
512 if err != nil {
513 return nil, fmt.Errorf("git port: %w", err)
514 }
515 ret.gitPort = gitPort
516 return ret, nil
517}
518
519func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700520 cmdArgs := []string{
521 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700522 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700523 "--name", cntrName,
524 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700525 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700526 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700527 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700528 cmdArgs = append(cmdArgs, "-t")
529 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000530
531 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
532 cmdArgs = append(cmdArgs, "-e", envVar)
533 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700534 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700535 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700536 }
537 if config.SketchPubKey != "" {
538 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
539 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700540 if config.SSHPort > 0 {
541 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
542 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700543 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700544 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700545 if relPath != "." {
546 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
547 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700548 // colima does this by default, but Linux docker seems to need this set explicitly
549 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000550
David Crawshaw1bd636c2025-06-13 19:56:27 +0000551 // Add seccomp profile to prevent killing PID 1 (the sketch process itself)
552 // Write the seccomp profile to cache directory if it doesn't exist
553 seccompPath, err := ensureSeccompProfile(ctx)
554 if err != nil {
555 return fmt.Errorf("failed to create seccomp profile: %w", err)
556 }
557 cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath)
558
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700559 // Add subtrace environment variable if token is provided
560 if config.SubtraceToken != "" {
561 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_TOKEN="+config.SubtraceToken)
562 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_HTTP2=1")
563 }
564
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000565 // Add volume mounts if specified
566 for _, mount := range config.Mounts {
567 if mount != "" {
568 cmdArgs = append(cmdArgs, "-v", mount)
569 }
570 }
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700571 cmdArgs = append(cmdArgs, imgName)
572
573 // Add command: either [sketch] or [subtrace run -- sketch]
574 if config.SubtraceToken != "" {
575 cmdArgs = append(cmdArgs, "/usr/local/bin/subtrace", "run", "--", "/bin/sketch")
576 } else {
577 cmdArgs = append(cmdArgs, "/bin/sketch")
578 }
579
580 // Add all sketch arguments
581 cmdArgs = append(cmdArgs,
Earl Lee2e463fb2025-04-17 11:22:22 -0700582 "-unsafe",
583 "-addr=:80",
584 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000585 "-git-username="+config.GitUsername,
586 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000587 "-outside-hostname="+config.OutsideHostname,
588 "-outside-os="+config.OutsideOS,
589 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000590 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700591 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700592 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700593 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000594 "-x="+config.ExperimentFlag,
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000595 "-branch-prefix="+config.BranchPrefix,
philip.zeyliger6d3de482025-06-10 19:38:14 -0700596 "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub),
Earl Lee2e463fb2025-04-17 11:22:22 -0700597 )
philip.zeyliger8773e682025-06-11 21:36:21 -0700598 // Set SSH connection string based on session ID for SSH Theater
599 cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID)
David Crawshaw5a7b3692025-05-05 16:49:15 -0700600 if config.Model != "" {
601 cmdArgs = append(cmdArgs, "-model="+config.Model)
602 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700603 if config.GitRemoteUrl != "" {
604 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
605 if config.Commit == "" {
606 panic("Commit should have been set when GitRemoteUrl was set")
607 }
608 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000609 cmdArgs = append(cmdArgs, "-upstream="+config.Upstream)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700610 }
611 if config.OutsideHTTP != "" {
612 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
613 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000614 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100615 if config.Prompt != "" {
616 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
617 }
618 if config.OneShot {
619 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700620 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000621 if config.ModelURL == "" {
622 // Forward ANTHROPIC_API_KEY for direct use.
623 // TODO: have outtie run an http proxy?
624 // TODO: select and forward the relevant API key based on the model
625 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
626 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000627
628 // Add additional docker arguments if provided
629 if config.DockerArgs != "" {
630 // Parse space-separated docker arguments with support for quotes and escaping
631 args := parseDockerArgs(config.DockerArgs)
632 // Insert arguments after "create" but before other arguments
633 for i := len(args) - 1; i >= 0; i-- {
634 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
635 }
636 }
637
Earl Lee2e463fb2025-04-17 11:22:22 -0700638 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
639 return fmt.Errorf("docker create: %s, %w", out, err)
640 }
641 return nil
642}
643
David Crawshawb5f6a002025-05-05 08:27:16 -0700644func buildLinuxSketchBin(ctx context.Context) (string, error) {
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700645 // Detect if race detector is enabled and use a different cache path
646 raceEnabled := RaceEnabled()
647 cacheSuffix := ""
648 if raceEnabled {
649 cacheSuffix = "-race"
650 }
651
652 homeDir, err := os.UserHomeDir()
653 if err != nil {
654 return "", err
655 }
656
657 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix)
658 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
659 return "", err
660 }
661
662 // When race detector is enabled, use Docker to build the Linux binary
663 if raceEnabled {
664 return buildLinuxSketchBinWithDocker(ctx, linuxGopath)
665 }
666
667 // Standard non-race build using cross-compilation
Pokey Rulea9a786b2025-05-12 10:52:34 +0100668 // Change to directory containing dockerimg.go for module detection
669 _, codeFile, _, _ := runtime.Caller(0)
670 codeDir := filepath.Dir(codeFile)
671 if currentDir, err := os.Getwd(); err != nil {
672 slog.WarnContext(ctx, "could not get current directory", "err", err)
673 } else {
674 if err := os.Chdir(codeDir); err != nil {
675 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
676 } else {
677 defer func() {
678 _ = os.Chdir(currentDir)
679 }()
680 }
681 }
682
David Crawshaw8a617cb2025-04-18 01:28:43 -0700683 verToInstall := "@latest"
684 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
685 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
686 } else {
687 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700688 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700689 verToInstall = ""
690 }
691 }
David Crawshaw69c67312025-04-17 13:42:00 -0700692
Earl Lee2e463fb2025-04-17 11:22:22 -0700693 start := time.Now()
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700694 args := []string{"install"}
695 args = append(args, "sketch.dev/cmd/sketch"+verToInstall)
696
697 cmd := exec.CommandContext(ctx, "go", args...)
David Crawshawb9eaef52025-04-17 15:23:18 -0700698 cmd.Env = append(
699 os.Environ(),
700 "GOOS=linux",
701 "CGO_ENABLED=0",
702 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700703 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700704 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700705 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700706
Earl Lee2e463fb2025-04-17 11:22:22 -0700707 out, err := cmd.CombinedOutput()
708 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700709 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 -0700710 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
711 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700712 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 -0700713 }
714
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700715 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700716 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700717 }
David Crawshawc7e77962025-05-03 13:20:18 -0700718 // If we are already on Linux, there's no extra platform name in the path
719 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700720}
721
Sean McCulloughae3480f2025-04-23 15:28:20 -0700722func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700723 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700724 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700725 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
726 } else {
727 v4, _, found := strings.Cut(string(out), "\n")
728 if !found {
729 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
730 }
731 localAddr = v4
732 if strings.HasPrefix(localAddr, "0.0.0.0") {
733 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
734 }
735 }
736 return localAddr, nil
737}
738
739// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700740func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700741 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700742
743 initMsg, err := json.Marshal(
744 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000745 HostAddr: localAddr,
746 SSHAuthorizedKeys: sshAuthorizedKeys,
747 SSHServerIdentity: sshServerIdentity,
748 SSHContainerCAKey: sshContainerCAKey,
749 SSHHostCertificate: sshHostCertificate,
750 SSHAvailable: sshAvailable,
751 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700752 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700753 if err != nil {
754 return fmt.Errorf("init msg: %w", err)
755 }
756
Earl Lee2e463fb2025-04-17 11:22:22 -0700757 // Note: this /init POST is handled in loop/server/loophttp.go:
758 initMsgByteReader := bytes.NewReader(initMsg)
759 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
760 if err != nil {
761 return err
762 }
763
764 var res *http.Response
765 for i := 0; ; i++ {
766 time.Sleep(100 * time.Millisecond)
767 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
768 initMsgByteReader.Reset(initMsg)
769 res, err = http.DefaultClient.Do(req)
770 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700771 if i < 100 {
772 if i%10 == 0 {
773 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
774 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700775 continue
776 }
777 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
778 }
779 break
780 }
781 resBytes, _ := io.ReadAll(res.Body)
782 if res.StatusCode != http.StatusOK {
783 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
784 }
785 return nil
786}
787
David Crawshaw5a7b3692025-05-05 16:49:15 -0700788func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700789 h := sha256.Sum256([]byte(gitRoot))
790 imgName = "sketch-" + hex.EncodeToString(h[:6])
791
792 var curImgInitFilesHash string
793 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
Kilian Lackhovedd6352a2025-06-17 22:01:05 +0200794 if strings.Contains(strings.ToLower(string(out)), "no such object") {
Earl Lee2e463fb2025-04-17 11:22:22 -0700795 // Image does not exist, continue and build it.
796 curImgInitFilesHash = ""
797 } else {
798 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
799 }
800 } else {
801 m := map[string]string{}
802 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
803 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
804 }
805 curImgInitFilesHash = m["sketch_context"]
806 }
807
808 candidates, err := findRepoDockerfiles(cwd, gitRoot)
809 if err != nil {
810 return "", fmt.Errorf("find dockerfile: %w", err)
811 }
812
813 var initFiles map[string]string
814 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700815 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700816
Jon Friesend27921f2025-06-05 13:15:56 +0000817 // Prioritize Dockerfile.sketch over Dockerfile, then fall back to generated dockerfile
818 if len(candidates) > 0 {
819 dockerfilePath = prioritizeDockerfiles(candidates)
Earl Lee2e463fb2025-04-17 11:22:22 -0700820 contents, err := os.ReadFile(dockerfilePath)
821 if err != nil {
822 return "", err
823 }
Jon Friesend27921f2025-06-05 13:15:56 +0000824 fmt.Printf("using %s as dev env\n", dockerfilePath)
Earl Lee2e463fb2025-04-17 11:22:22 -0700825 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700826 return imgName, nil
827 }
828 } else {
829 initFiles, err = readInitFiles(os.DirFS(gitRoot))
830 if err != nil {
831 return "", err
832 }
833 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
834 if err != nil {
835 return "", err
836 }
837 initFileHash := hashInitFiles(initFiles)
838 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700839 return imgName, nil
840 }
841
Kilian Lackhove23772f42025-06-18 20:28:58 +0200842 start := time.Now()
843
844 var service llm.Service
David Crawshaw5a7b3692025-05-05 16:49:15 -0700845 if model == "gemini" {
Kilian Lackhove23772f42025-06-18 20:28:58 +0200846 service = &gem.Service{
847 URL: modelURL,
848 APIKey: modelAPIKey,
849 HTTPC: http.DefaultClient,
850 }
851 } else {
852 service = &ant.Service{
853 URL: modelURL,
854 APIKey: modelAPIKey,
855 HTTPC: http.DefaultClient,
David Crawshaw5a7b3692025-05-05 16:49:15 -0700856 }
857 }
858
Kilian Lackhove23772f42025-06-18 20:28:58 +0200859 generatedDockerfile, err = createDockerfile(ctx, service, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700860 if err != nil {
861 return "", fmt.Errorf("create dockerfile: %w", err)
862 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000863 // Create a unique temporary directory for the Dockerfile
864 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
865 if err != nil {
866 return "", fmt.Errorf("failed to create temporary directory: %w", err)
867 }
868 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700869 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700870 return "", err
871 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000872 // Remove the temporary directory and all contents when done
873 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700874
David Crawshawb5f6a002025-05-05 08:27:16 -0700875 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700876 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 -0700877 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700878 }
879
880 var gitUserEmail, gitUserName string
881 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
Sean McCullough8ad17ba2025-06-09 00:43:57 +0000882 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 -0700883 } else {
884 gitUserEmail = strings.TrimSpace(string(out))
885 }
886 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
Sean McCullough8ad17ba2025-06-09 00:43:57 +0000887 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 -0700888 } else {
889 gitUserName = strings.TrimSpace(string(out))
890 }
891
892 start := time.Now()
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700893 cmdArgs := []string{
894 "build",
Earl Lee2e463fb2025-04-17 11:22:22 -0700895 "-t", imgName,
896 "-f", dockerfilePath,
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700897 "--build-arg", "GIT_USER_EMAIL=" + gitUserEmail,
898 "--build-arg", "GIT_USER_NAME=" + gitUserName,
899 }
900
901 // Add the sketch_context label for image reuse detection
902 var contextHash string
903 if len(candidates) > 0 {
904 // Building from Dockerfile.sketch or similar static file
905 contents, err := os.ReadFile(dockerfilePath)
906 if err != nil {
907 return "", err
908 }
909 contextHash = hashInitFiles(map[string]string{dockerfilePath: string(contents)})
910 } else {
911 // Building from generated dockerfile
912 contextHash = hashInitFiles(initFiles)
913 }
914 cmdArgs = append(cmdArgs, "--label", "sketch_context="+contextHash)
915 cmdArgs = append(cmdArgs, ".")
916
917 cmd := exec.CommandContext(ctx, "docker", cmdArgs...)
David Crawshawb5f6a002025-05-05 08:27:16 -0700918 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700919 // We print the docker build output whether or not the user
920 // has selected --verbose. Building an image takes a while
921 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700922 cmd.Stdout = os.Stdout
923 cmd.Stderr = os.Stderr
924 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700925
926 err = run(ctx, "docker build", cmd)
927 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700928 var msg string
929 if generatedDockerfile != "" {
930 if !verbose {
931 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
932 }
933 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
934 }
935 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700936 }
937 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
938 return imgName, nil
939}
940
941func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
942 files, err := findDirDockerfiles(cwd)
943 if err != nil {
944 return nil, err
945 }
946 if len(files) > 0 {
947 return files, nil
948 }
949
950 path := cwd
951 for path != gitRoot {
952 path = filepath.Dir(path)
953 files, err := findDirDockerfiles(path)
954 if err != nil {
955 return nil, err
956 }
957 if len(files) > 0 {
958 return files, nil
959 }
960 }
961 return files, nil
962}
963
Jon Friesend27921f2025-06-05 13:15:56 +0000964// prioritizeDockerfiles returns the highest priority dockerfile from a list of candidates.
965// Priority order: Dockerfile.sketch > Dockerfile > other Dockerfile.*
966func prioritizeDockerfiles(candidates []string) string {
967 if len(candidates) == 0 {
968 return ""
969 }
970 if len(candidates) == 1 {
971 return candidates[0]
972 }
973
974 // Look for Dockerfile.sketch first (case insensitive)
975 for _, candidate := range candidates {
976 basename := strings.ToLower(filepath.Base(candidate))
977 if basename == "dockerfile.sketch" {
978 return candidate
979 }
980 }
981
982 // Look for Dockerfile second (case insensitive)
983 for _, candidate := range candidates {
984 basename := strings.ToLower(filepath.Base(candidate))
985 if basename == "dockerfile" {
986 return candidate
987 }
988 }
989
990 // Return first remaining candidate
991 return candidates[0]
992}
993
Earl Lee2e463fb2025-04-17 11:22:22 -0700994// findDirDockerfiles finds all "Dockerfile*" files in a directory.
995func findDirDockerfiles(root string) (res []string, err error) {
996 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
997 if err != nil {
998 return err
999 }
1000 if info.IsDir() && root != path {
1001 return filepath.SkipDir
1002 }
1003 name := strings.ToLower(info.Name())
Josh Bleecher Snydera9fd88f2025-06-05 10:43:22 -07001004 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") || strings.HasSuffix(name, ".dockerfile") {
Earl Lee2e463fb2025-04-17 11:22:22 -07001005 res = append(res, path)
1006 }
1007 return nil
1008 })
1009 if err != nil {
1010 return nil, err
1011 }
1012 return res, nil
1013}
1014
Philip Zeyligerd6d12d12025-05-19 19:19:21 -07001015func checkForEmptyGitRepo(ctx context.Context, path string) error {
1016 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
1017 cmd.Dir = path
1018 _, err := cmd.CombinedOutput()
1019 if err != nil {
1020 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
1021 "git commit --allow-empty -m 'initial commit'")
1022 }
1023 return nil
1024}
1025
Earl Lee2e463fb2025-04-17 11:22:22 -07001026func findGitRoot(ctx context.Context, path string) (string, error) {
1027 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
1028 cmd.Dir = path
1029 out, err := cmd.CombinedOutput()
1030 if err != nil {
1031 if strings.Contains(string(out), "not a git repository") {
1032 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
1033Consider one of the following options:
1034 - cd to a different dir that is already part of a git repo first, or
1035 - to create a new git repo from this directory (%s), run this command:
1036
1037 git init . && git commit --allow-empty -m "initial commit"
1038
1039and try running sketch again.
1040`, path, path)
1041 }
1042 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
1043 }
1044 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
1045 absGitDir := filepath.Join(path, gitDir)
1046 return filepath.Dir(absGitDir), err
1047}
1048
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +00001049// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
1050// from git config using the sketch.envfwd multi-valued key.
1051func getEnvForwardingFromGitConfig(ctx context.Context) []string {
1052 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
1053 out := string(outb)
1054 if err != nil {
1055 if strings.Contains(out, "key does not exist") {
1056 return nil
1057 }
1058 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
1059 return nil
1060 }
1061
1062 var envVars []string
1063 for envVar := range strings.Lines(out) {
1064 envVar = strings.TrimSpace(envVar)
1065 if envVar == "" {
1066 continue
1067 }
1068 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
1069 }
1070 return envVars
1071}
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001072
1073// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
1074// It handles quoted arguments and escaped characters.
1075//
1076// Examples:
1077//
1078// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
1079// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
1080// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
1081func parseDockerArgs(args string) []string {
1082 if args = strings.TrimSpace(args); args == "" {
1083 return []string{}
1084 }
1085
1086 var result []string
1087 var current strings.Builder
1088 inQuotes := false
1089 escapeNext := false
1090 quoteChar := rune(0)
1091
1092 for _, char := range args {
1093 if escapeNext {
1094 current.WriteRune(char)
1095 escapeNext = false
1096 continue
1097 }
1098
1099 if char == '\\' {
1100 escapeNext = true
1101 continue
1102 }
1103
1104 if char == '"' || char == '\'' {
1105 if !inQuotes {
1106 inQuotes = true
1107 quoteChar = char
1108 continue
1109 } else if char == quoteChar {
1110 inQuotes = false
1111 quoteChar = rune(0)
1112 continue
1113 }
1114 // Non-matching quote character inside quotes
1115 current.WriteRune(char)
1116 continue
1117 }
1118
1119 // Space outside of quotes is an argument separator
1120 if char == ' ' && !inQuotes {
1121 if current.Len() > 0 {
1122 result = append(result, current.String())
1123 current.Reset()
1124 }
1125 continue
1126 }
1127
1128 current.WriteRune(char)
1129 }
1130
1131 // Add the last argument if there is one
1132 if current.Len() > 0 {
1133 result = append(result, current.String())
1134 }
1135
1136 return result
1137}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001138
1139// buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled.
1140// This avoids cross-compilation issues with CGO which is required for the race detector.
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001141// Mounts host Go module cache and build cache for faster subsequent builds.
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001142func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) {
1143 // Find the git repo root
1144 currentDir, err := os.Getwd()
1145 if err != nil {
1146 return "", fmt.Errorf("could not get current directory: %w", err)
1147 }
1148
1149 gitRoot, err := findGitRoot(ctx, currentDir)
1150 if err != nil {
1151 return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err)
1152 }
1153
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001154 // Get host Go cache directories to mount for faster builds
1155 goCacheDir, err := getHostGoCacheDir(ctx)
1156 if err != nil {
1157 return "", fmt.Errorf("failed to get host GOCACHE: %w", err)
1158 }
1159 goModCacheDir, err := getHostGoModCacheDir(ctx)
1160 if err != nil {
1161 return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err)
1162 }
1163
1164 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 -07001165
1166 // Use the published Docker image tag
1167 imageTag := dockerfileBaseHash()
1168 imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag)
1169
1170 // Create destination directory for the binary
1171 destPath := filepath.Join(linuxGopath, "bin")
1172 if err := os.MkdirAll(destPath, 0o777); err != nil {
1173 return "", fmt.Errorf("failed to create destination directory: %w", err)
1174 }
1175 destFile := filepath.Join(destPath, "sketch")
1176
1177 // Create a unique container name
1178 containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano())
1179
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001180 // Run a container with the repo mounted and Go caches for faster builds
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001181 start := time.Now()
1182 slog.DebugContext(ctx, "running Docker container to build sketch with race detector")
1183
1184 // Use explicit output path for clarity
1185 runArgs := []string{
1186 "run",
1187 "--name", containerID,
1188 "-v", gitRoot + ":/app",
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001189 "-v", goCacheDir + ":/root/.cache/go-build",
1190 "-v", goModCacheDir + ":/go/pkg/mod",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001191 "-w", "/app",
1192 imgName,
Josh Bleecher Snyderf4f929a2025-05-23 17:19:26 +00001193 "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 -07001194 }
1195
1196 out, err := combinedOutput(ctx, "docker", runArgs...)
1197 if err != nil {
1198 // Print the output to help with debugging
1199 slog.ErrorContext(ctx, "docker run for race build failed",
1200 slog.String("output", string(out)),
1201 slog.String("error", err.Error()))
1202 return "", fmt.Errorf("docker run failed: %s: %w", out, err)
1203 }
1204
1205 slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start))
1206
1207 // Copy the binary from the container using the explicit path
1208 out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile)
1209 if err != nil {
1210 return "", fmt.Errorf("docker cp failed: %s: %w", out, err)
1211 }
1212
1213 // Clean up the container
1214 if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil {
1215 slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out))
1216 }
1217
1218 // Make the binary executable
1219 if err := os.Chmod(destFile, 0o755); err != nil {
1220 return "", fmt.Errorf("failed to make binary executable: %w", err)
1221 }
1222
1223 return destFile, nil
1224}
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001225
1226// getHostGoCacheDir returns the host's GOCACHE directory
1227func getHostGoCacheDir(ctx context.Context) (string, error) {
1228 out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput()
1229 if err != nil {
1230 return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err)
1231 }
1232 return strings.TrimSpace(string(out)), nil
1233}
1234
1235// getHostGoModCacheDir returns the host's GOMODCACHE directory
1236func getHostGoModCacheDir(ctx context.Context) (string, error) {
1237 out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput()
1238 if err != nil {
1239 return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err)
1240 }
1241 return strings.TrimSpace(string(out)), nil
1242}
David Crawshaw1bd636c2025-06-13 19:56:27 +00001243
1244const seccompProfile = `{
1245 "defaultAction": "SCMP_ACT_ALLOW",
1246 "syscalls": [
1247 {
1248 "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"],
1249 "action": "SCMP_ACT_ERRNO",
1250 "args": [
1251 {
1252 "index": 0,
1253 "value": 1,
1254 "op": "SCMP_CMP_EQ"
1255 }
1256 ]
1257 }
1258 ]
1259}`
1260
1261// ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist.
1262func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) {
1263 homeDir, err := os.UserHomeDir()
1264 if err != nil {
1265 return "", fmt.Errorf("failed to get home directory: %w", err)
1266 }
1267 cacheDir := filepath.Join(homeDir, ".cache", "sketch")
1268 if err := os.MkdirAll(cacheDir, 0o755); err != nil {
1269 return "", fmt.Errorf("failed to create cache directory: %w", err)
1270 }
1271 seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json")
1272
1273 curBytes, err := os.ReadFile(seccompPath)
1274 if err != nil && !os.IsNotExist(err) {
1275 return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err)
1276 }
1277 if string(curBytes) == seccompProfile {
1278 return seccompPath, nil // File already exists and matches the expected profile
1279 }
1280
1281 if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil {
1282 return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err)
1283 }
1284 slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath)
1285 return seccompPath, nil
1286}