blob: 79d4b2854d0a05d7108ba75cc24fa2855f86cf23 [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
109 MaxDollars float64
110 MaxIterations uint64
111 MaxWallTime time.Duration
112
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700113 GitRemoteUrl string
114
115 // Commit hash to checkout from GetRemoteUrl
116 Commit string
117
118 // Outtie's HTTP server
119 OutsideHTTP string
Earl Lee2e463fb2025-04-17 11:22:22 -0700120}
121
122// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
123// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700124func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700125 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700126 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700127 if runtime.GOOS == "darwin" {
128 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
129 } else {
130 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
131 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700132 }
133
134 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
135 // `docker ps` provides a good error message here that can be
136 // easily chatgpt'ed by users, so send it to the user as-is:
137 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
138 return fmt.Errorf("docker ps: %s (%w)", out, err)
139 }
140
141 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
142 if err != nil {
143 return err
144 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700145 gitRoot, err := findGitRoot(ctx, config.Path)
146 if err != nil {
147 return err
148 }
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700149 err = checkForEmptyGitRepo(ctx, config.Path)
150 if err != nil {
151 return err
152 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700153
David Crawshaw5a7b3692025-05-05 16:49:15 -0700154 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700155 if err != nil {
156 return err
157 }
158
159 linuxSketchBin := config.SketchBinaryLinux
160 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700161 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700162 if err != nil {
163 return err
164 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700165 }
166
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000167 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700168 defer func() {
169 if config.NoCleanup {
170 return
171 }
172 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
173 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
174 _ = out
175 }
176 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
177 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
178 _ = out
179 }
180 }()
181
182 // errCh receives errors from operations that this function calls in separate goroutines.
183 errCh := make(chan error)
184
185 // Start the git server
186 gitSrv, err := newGitServer(gitRoot)
187 if err != nil {
188 return fmt.Errorf("failed to start git server: %w", err)
189 }
190 defer gitSrv.shutdown(ctx)
191
192 go func() {
193 errCh <- gitSrv.serve(ctx)
194 }()
195
196 // Get the current host git commit
197 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000198 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
199 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700200 } else {
201 commit = strings.TrimSpace(string(out))
202 }
203 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
204 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
205 }
206
207 relPath, err := filepath.Rel(gitRoot, config.Path)
208 if err != nil {
209 return err
210 }
211
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700212 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
213 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
214 config.Commit = commit
215
Earl Lee2e463fb2025-04-17 11:22:22 -0700216 // Create the sketch container
217 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000218 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700219 }
220
221 // Copy the sketch linux binary into the container
222 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
223 return fmt.Errorf("docker cp: %s, %w", out, err)
224 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700225
226 // Make sure that the webui is built so we can copy the results to the container.
227 _, err = webui.Build()
228 if err != nil {
229 return fmt.Errorf("failed to build webui: %w", err)
230 }
231
David Crawshaw8bff16a2025-04-18 01:16:49 -0700232 webuiZipPath, err := webui.ZipPath()
233 if err != nil {
234 return err
235 }
236 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
237 return fmt.Errorf("docker cp: %s, %w", out, err)
238 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700239
David Crawshaw53786ef2025-04-24 12:52:51 -0700240 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700241
242 // Start the sketch container
243 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
244 return fmt.Errorf("docker start: %s, %w", out, err)
245 }
246
247 // Copies structured logs from the container to the host.
248 copyLogs := func() {
249 if config.ContainerLogDest == "" {
250 return
251 }
252 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
253 if err != nil {
254 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
255 return
256 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700257 prefix := []byte("structured logs:")
258 for line := range bytes.Lines(out) {
259 rest, ok := bytes.CutPrefix(line, prefix)
260 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700261 continue
262 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700263 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700264 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
265 logFileName := filepath.Base(logFile)
266 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
267 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
268 if err != nil {
269 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
270 }
271 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
272 }
273 }
274
275 // NOTE: we want to see what the internal sketch binary prints
276 // regardless of the setting of the verbosity flag on the external
277 // binary, so reading "docker logs", which is the stdout/stderr of
278 // the internal binary is not conditional on the verbose flag.
279 appendInternalErr := func(err error) error {
280 if err == nil {
281 return nil
282 }
283 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000284 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700285 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
286 }
287 out = bytes.TrimSpace(out)
288 if len(out) > 0 {
289 return fmt.Errorf("docker logs: %s;\n%w", out, err)
290 }
291 return err
292 }
293
294 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700295 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700296 if err != nil {
297 return appendInternalErr(err)
298 }
299
Philip Zeyliger00442412025-05-14 11:03:23 -0700300 if config.Verbose {
301 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
302 }
303
Sean McCulloughae3480f2025-04-23 15:28:20 -0700304 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
305 if err != nil {
306 return appendInternalErr(err)
307 }
308 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
309 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700310 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700311 }
Sean McCullough4854c652025-04-24 18:37:02 -0700312
Sean McCullough7013e9e2025-05-14 02:03:58 +0000313 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700314
Sean McCullough078e85a2025-05-08 17:28:34 -0700315 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
316 if err != nil {
317 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
318 }
319
320 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700321 sshAvailable := false
322 sshErrMsg := ""
323 if sshErr != nil {
324 fmt.Println(sshErr.Error())
325 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700326 // continue - ssh config is not required for the rest of sketch to function locally.
327 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700328 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700329 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
330 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700331 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700332🖥️ ssh %s
333🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700334🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700335`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700336 sshUserIdentity = cst.userIdentity
337 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000338
339 // Get the Container CA public key for mutual auth
340 if cst.containerCAPublicKey != nil {
341 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
342 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
343 }
344
345 // Get the host certificate for mutual auth
346 hostCertificate = cst.hostCertificate
347
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700348 defer func() {
349 if err := cst.Cleanup(); err != nil {
350 appendInternalErr(err)
351 }
352 }()
353 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700354
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700355 // Tell the sketch container to Init(), which starts the SSH server
356 // and checks out the right commit.
357 // TODO: I'm trying to move as much configuration as possible into the command-line
358 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
359 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
360 // get the port Docker chose until after the process starts. The SSH config is
361 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
362 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700363 go func() {
364 // TODO: Why is this called in a goroutine? I have found that when I pull this out
365 // of the goroutine and call it inline, then the terminal UI clears itself and all
366 // the scrollback (which is not good, but also not fatal). I can't see why it does this
367 // though, since none of the calls in postContainerInitConfig obviously write to stdout
368 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700369 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700370 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
371 errCh <- appendInternalErr(err)
372 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700373
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700374 // 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 -0700375 ps1URL := "http://" + localAddr
376 if config.SkabandAddr != "" {
377 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700378 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700379 if config.OpenBrowser {
380 browser.Open(ps1URL)
381 }
382 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700383 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700384
Sean McCullough138ec242025-06-02 22:42:06 +0000385 // Start automatic port tunneling if SSH is available
386 if sshAvailable {
387 go func() {
388 containerURL := "http://" + localAddr
389 tunnelManager := NewTunnelManager(containerURL, cntrName, 10) // Allow up to 10 concurrent tunnels
390 tunnelManager.Start(ctx)
391 slog.InfoContext(ctx, "Started automatic port tunnel manager", "container", cntrName)
392 }()
393 }
394
Earl Lee2e463fb2025-04-17 11:22:22 -0700395 go func() {
396 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
397 cmd.Stdin = os.Stdin
398 cmd.Stdout = os.Stdout
399 cmd.Stderr = os.Stderr
400 errCh <- run(ctx, "docker attach", cmd)
401 }()
402
403 defer copyLogs()
404
405 for {
406 select {
407 case <-ctx.Done():
408 return ctx.Err()
409 case err := <-errCh:
410 if err != nil {
411 return appendInternalErr(fmt.Errorf("container process: %w", err))
412 }
413 return nil
414 }
415 }
416}
417
418func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
419 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700420 start := time.Now()
421
422 out, err := cmd.CombinedOutput()
423 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700424 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 -0700425 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700426 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 -0700427 }
428 return out, err
429}
430
431func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
432 start := time.Now()
433 err := cmd.Run()
434 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700435 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 -0700436 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700437 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 -0700438 }
439 return err
440}
441
442type gitServer struct {
443 gitLn net.Listener
444 gitPort string
445 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700446 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700447 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700448}
449
450func (gs *gitServer) shutdown(ctx context.Context) {
451 gs.srv.Shutdown(ctx)
452 gs.gitLn.Close()
453}
454
455// Serve a git remote from the host for the container to fetch from and push to.
456func (gs *gitServer) serve(ctx context.Context) error {
457 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
458 return gs.srv.Serve(gs.gitLn)
459}
460
461func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700462 ret := &gitServer{
463 pass: rand.Text(),
464 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700465
Earl Lee2e463fb2025-04-17 11:22:22 -0700466 gitLn, err := net.Listen("tcp4", ":0")
467 if err != nil {
468 return nil, fmt.Errorf("git listen: %w", err)
469 }
470 ret.gitLn = gitLn
471
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700472 browserC := make(chan bool, 1) // channel of browser open requests
473
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000474 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700475 for range browserC {
476 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000477 }
478 }()
479
480 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700481 ret.srv = &srv
482
483 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
484 if err != nil {
485 return nil, fmt.Errorf("git port: %w", err)
486 }
487 ret.gitPort = gitPort
488 return ret, nil
489}
490
491func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700492 cmdArgs := []string{
493 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700494 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700495 "--name", cntrName,
496 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700497 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700498 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700499 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700500 cmdArgs = append(cmdArgs, "-t")
501 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000502
503 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
504 cmdArgs = append(cmdArgs, "-e", envVar)
505 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700506 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700507 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700508 }
509 if config.SketchPubKey != "" {
510 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
511 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700512 if config.SSHPort > 0 {
513 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
514 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700515 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700516 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700517 if relPath != "." {
518 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
519 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700520 // colima does this by default, but Linux docker seems to need this set explicitly
521 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000522
523 // Add volume mounts if specified
524 for _, mount := range config.Mounts {
525 if mount != "" {
526 cmdArgs = append(cmdArgs, "-v", mount)
527 }
528 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700529 cmdArgs = append(
530 cmdArgs,
531 imgName,
532 "/bin/sketch",
533 "-unsafe",
534 "-addr=:80",
535 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000536 "-git-username="+config.GitUsername,
537 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000538 "-outside-hostname="+config.OutsideHostname,
539 "-outside-os="+config.OutsideOS,
540 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000541 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
542 fmt.Sprintf("-max-iterations=%d", config.MaxIterations),
543 fmt.Sprintf("-max-wall-time=%s", config.MaxWallTime.String()),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700544 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700545 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700546 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000547 "-x="+config.ExperimentFlag,
Earl Lee2e463fb2025-04-17 11:22:22 -0700548 )
David Crawshaw5a7b3692025-05-05 16:49:15 -0700549 if config.Model != "" {
550 cmdArgs = append(cmdArgs, "-model="+config.Model)
551 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700552 if config.GitRemoteUrl != "" {
553 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
554 if config.Commit == "" {
555 panic("Commit should have been set when GitRemoteUrl was set")
556 }
557 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
558 }
559 if config.OutsideHTTP != "" {
560 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
561 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000562 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100563 if config.Prompt != "" {
564 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
565 }
566 if config.OneShot {
567 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700568 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000569 if config.ModelURL == "" {
570 // Forward ANTHROPIC_API_KEY for direct use.
571 // TODO: have outtie run an http proxy?
572 // TODO: select and forward the relevant API key based on the model
573 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
574 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000575
576 // Add additional docker arguments if provided
577 if config.DockerArgs != "" {
578 // Parse space-separated docker arguments with support for quotes and escaping
579 args := parseDockerArgs(config.DockerArgs)
580 // Insert arguments after "create" but before other arguments
581 for i := len(args) - 1; i >= 0; i-- {
582 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
583 }
584 }
585
Earl Lee2e463fb2025-04-17 11:22:22 -0700586 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
587 return fmt.Errorf("docker create: %s, %w", out, err)
588 }
589 return nil
590}
591
David Crawshawb5f6a002025-05-05 08:27:16 -0700592func buildLinuxSketchBin(ctx context.Context) (string, error) {
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700593 // Detect if race detector is enabled and use a different cache path
594 raceEnabled := RaceEnabled()
595 cacheSuffix := ""
596 if raceEnabled {
597 cacheSuffix = "-race"
598 }
599
600 homeDir, err := os.UserHomeDir()
601 if err != nil {
602 return "", err
603 }
604
605 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix)
606 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
607 return "", err
608 }
609
610 // When race detector is enabled, use Docker to build the Linux binary
611 if raceEnabled {
612 return buildLinuxSketchBinWithDocker(ctx, linuxGopath)
613 }
614
615 // Standard non-race build using cross-compilation
Pokey Rulea9a786b2025-05-12 10:52:34 +0100616 // Change to directory containing dockerimg.go for module detection
617 _, codeFile, _, _ := runtime.Caller(0)
618 codeDir := filepath.Dir(codeFile)
619 if currentDir, err := os.Getwd(); err != nil {
620 slog.WarnContext(ctx, "could not get current directory", "err", err)
621 } else {
622 if err := os.Chdir(codeDir); err != nil {
623 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
624 } else {
625 defer func() {
626 _ = os.Chdir(currentDir)
627 }()
628 }
629 }
630
David Crawshaw8a617cb2025-04-18 01:28:43 -0700631 verToInstall := "@latest"
632 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
633 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
634 } else {
635 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700636 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700637 verToInstall = ""
638 }
639 }
David Crawshaw69c67312025-04-17 13:42:00 -0700640
Earl Lee2e463fb2025-04-17 11:22:22 -0700641 start := time.Now()
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700642 args := []string{"install"}
643 args = append(args, "sketch.dev/cmd/sketch"+verToInstall)
644
645 cmd := exec.CommandContext(ctx, "go", args...)
David Crawshawb9eaef52025-04-17 15:23:18 -0700646 cmd.Env = append(
647 os.Environ(),
648 "GOOS=linux",
649 "CGO_ENABLED=0",
650 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700651 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700652 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700653 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700654
Earl Lee2e463fb2025-04-17 11:22:22 -0700655 out, err := cmd.CombinedOutput()
656 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700657 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 -0700658 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
659 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700660 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 -0700661 }
662
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700663 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700664 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700665 }
David Crawshawc7e77962025-05-03 13:20:18 -0700666 // If we are already on Linux, there's no extra platform name in the path
667 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700668}
669
Sean McCulloughae3480f2025-04-23 15:28:20 -0700670func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700671 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700672 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700673 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
674 } else {
675 v4, _, found := strings.Cut(string(out), "\n")
676 if !found {
677 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
678 }
679 localAddr = v4
680 if strings.HasPrefix(localAddr, "0.0.0.0") {
681 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
682 }
683 }
684 return localAddr, nil
685}
686
687// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700688func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700689 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700690
691 initMsg, err := json.Marshal(
692 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000693 HostAddr: localAddr,
694 SSHAuthorizedKeys: sshAuthorizedKeys,
695 SSHServerIdentity: sshServerIdentity,
696 SSHContainerCAKey: sshContainerCAKey,
697 SSHHostCertificate: sshHostCertificate,
698 SSHAvailable: sshAvailable,
699 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700700 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700701 if err != nil {
702 return fmt.Errorf("init msg: %w", err)
703 }
704
Earl Lee2e463fb2025-04-17 11:22:22 -0700705 // Note: this /init POST is handled in loop/server/loophttp.go:
706 initMsgByteReader := bytes.NewReader(initMsg)
707 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
708 if err != nil {
709 return err
710 }
711
712 var res *http.Response
713 for i := 0; ; i++ {
714 time.Sleep(100 * time.Millisecond)
715 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
716 initMsgByteReader.Reset(initMsg)
717 res, err = http.DefaultClient.Do(req)
718 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700719 if i < 100 {
720 if i%10 == 0 {
721 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
722 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700723 continue
724 }
725 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
726 }
727 break
728 }
729 resBytes, _ := io.ReadAll(res.Body)
730 if res.StatusCode != http.StatusOK {
731 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
732 }
733 return nil
734}
735
David Crawshaw5a7b3692025-05-05 16:49:15 -0700736func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700737 h := sha256.Sum256([]byte(gitRoot))
738 imgName = "sketch-" + hex.EncodeToString(h[:6])
739
740 var curImgInitFilesHash string
741 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
742 if strings.Contains(string(out), "No such object") {
743 // Image does not exist, continue and build it.
744 curImgInitFilesHash = ""
745 } else {
746 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
747 }
748 } else {
749 m := map[string]string{}
750 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
751 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
752 }
753 curImgInitFilesHash = m["sketch_context"]
754 }
755
756 candidates, err := findRepoDockerfiles(cwd, gitRoot)
757 if err != nil {
758 return "", fmt.Errorf("find dockerfile: %w", err)
759 }
760
761 var initFiles map[string]string
762 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700763 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700764
765 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
766 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
767 dockerfilePath = candidates[0]
768 contents, err := os.ReadFile(dockerfilePath)
769 if err != nil {
770 return "", err
771 }
772 fmt.Printf("using %s as dev env\n", candidates[0])
773 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700774 return imgName, nil
775 }
776 } else {
777 initFiles, err = readInitFiles(os.DirFS(gitRoot))
778 if err != nil {
779 return "", err
780 }
781 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
782 if err != nil {
783 return "", err
784 }
785 initFileHash := hashInitFiles(initFiles)
786 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700787 return imgName, nil
788 }
789
David Crawshaw5a7b3692025-05-05 16:49:15 -0700790 if model == "gemini" {
791 if strings.HasSuffix(modelURL, "/gemmsgs") {
792 // Horrible hack! Switch back to anthropic for container building.
David Crawshaw3659d872025-05-05 17:52:23 -0700793 // We can do this because we are talking to skaband and know the address.
David Crawshaw5a7b3692025-05-05 16:49:15 -0700794 modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1)
795 } else {
796 return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini")
797 }
798 }
799
Earl Lee2e463fb2025-04-17 11:22:22 -0700800 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700801 srv := &ant.Service{
David Crawshaw5a7b3692025-05-05 16:49:15 -0700802 URL: modelURL,
803 APIKey: modelAPIKey,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700804 HTTPC: http.DefaultClient,
805 }
Pokey Rulec31e2962025-05-13 10:53:33 +0000806 generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700807 if err != nil {
808 return "", fmt.Errorf("create dockerfile: %w", err)
809 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000810 // Create a unique temporary directory for the Dockerfile
811 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
812 if err != nil {
813 return "", fmt.Errorf("failed to create temporary directory: %w", err)
814 }
815 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700816 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700817 return "", err
818 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000819 // Remove the temporary directory and all contents when done
820 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700821
David Crawshawb5f6a002025-05-05 08:27:16 -0700822 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700823 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 -0700824 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700825 }
826
827 var gitUserEmail, gitUserName string
828 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
829 return "", fmt.Errorf("git config: %s: %v", out, err)
830 } else {
831 gitUserEmail = strings.TrimSpace(string(out))
832 }
833 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
834 return "", fmt.Errorf("git config: %s: %v", out, err)
835 } else {
836 gitUserName = strings.TrimSpace(string(out))
837 }
838
839 start := time.Now()
840 cmd := exec.CommandContext(ctx,
841 "docker", "build",
842 "-t", imgName,
843 "-f", dockerfilePath,
844 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
845 "--build-arg", "GIT_USER_NAME="+gitUserName,
David Crawshaw31f15242025-05-06 16:03:49 -0700846 ".",
Earl Lee2e463fb2025-04-17 11:22:22 -0700847 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700848 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700849 // We print the docker build output whether or not the user
850 // has selected --verbose. Building an image takes a while
851 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700852 cmd.Stdout = os.Stdout
853 cmd.Stderr = os.Stderr
854 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700855
856 err = run(ctx, "docker build", cmd)
857 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700858 var msg string
859 if generatedDockerfile != "" {
860 if !verbose {
861 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
862 }
863 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
864 }
865 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700866 }
867 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
868 return imgName, nil
869}
870
871func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
872 files, err := findDirDockerfiles(cwd)
873 if err != nil {
874 return nil, err
875 }
876 if len(files) > 0 {
877 return files, nil
878 }
879
880 path := cwd
881 for path != gitRoot {
882 path = filepath.Dir(path)
883 files, err := findDirDockerfiles(path)
884 if err != nil {
885 return nil, err
886 }
887 if len(files) > 0 {
888 return files, nil
889 }
890 }
891 return files, nil
892}
893
894// findDirDockerfiles finds all "Dockerfile*" files in a directory.
895func findDirDockerfiles(root string) (res []string, err error) {
896 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
897 if err != nil {
898 return err
899 }
900 if info.IsDir() && root != path {
901 return filepath.SkipDir
902 }
903 name := strings.ToLower(info.Name())
904 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
905 res = append(res, path)
906 }
907 return nil
908 })
909 if err != nil {
910 return nil, err
911 }
912 return res, nil
913}
914
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700915func checkForEmptyGitRepo(ctx context.Context, path string) error {
916 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
917 cmd.Dir = path
918 _, err := cmd.CombinedOutput()
919 if err != nil {
920 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
921 "git commit --allow-empty -m 'initial commit'")
922 }
923 return nil
924}
925
Earl Lee2e463fb2025-04-17 11:22:22 -0700926func findGitRoot(ctx context.Context, path string) (string, error) {
927 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
928 cmd.Dir = path
929 out, err := cmd.CombinedOutput()
930 if err != nil {
931 if strings.Contains(string(out), "not a git repository") {
932 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
933Consider one of the following options:
934 - cd to a different dir that is already part of a git repo first, or
935 - to create a new git repo from this directory (%s), run this command:
936
937 git init . && git commit --allow-empty -m "initial commit"
938
939and try running sketch again.
940`, path, path)
941 }
942 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
943 }
944 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
945 absGitDir := filepath.Join(path, gitDir)
946 return filepath.Dir(absGitDir), err
947}
948
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000949// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
950// from git config using the sketch.envfwd multi-valued key.
951func getEnvForwardingFromGitConfig(ctx context.Context) []string {
952 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
953 out := string(outb)
954 if err != nil {
955 if strings.Contains(out, "key does not exist") {
956 return nil
957 }
958 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
959 return nil
960 }
961
962 var envVars []string
963 for envVar := range strings.Lines(out) {
964 envVar = strings.TrimSpace(envVar)
965 if envVar == "" {
966 continue
967 }
968 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
969 }
970 return envVars
971}
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000972
973// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
974// It handles quoted arguments and escaped characters.
975//
976// Examples:
977//
978// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
979// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
980// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
981func parseDockerArgs(args string) []string {
982 if args = strings.TrimSpace(args); args == "" {
983 return []string{}
984 }
985
986 var result []string
987 var current strings.Builder
988 inQuotes := false
989 escapeNext := false
990 quoteChar := rune(0)
991
992 for _, char := range args {
993 if escapeNext {
994 current.WriteRune(char)
995 escapeNext = false
996 continue
997 }
998
999 if char == '\\' {
1000 escapeNext = true
1001 continue
1002 }
1003
1004 if char == '"' || char == '\'' {
1005 if !inQuotes {
1006 inQuotes = true
1007 quoteChar = char
1008 continue
1009 } else if char == quoteChar {
1010 inQuotes = false
1011 quoteChar = rune(0)
1012 continue
1013 }
1014 // Non-matching quote character inside quotes
1015 current.WriteRune(char)
1016 continue
1017 }
1018
1019 // Space outside of quotes is an argument separator
1020 if char == ' ' && !inQuotes {
1021 if current.Len() > 0 {
1022 result = append(result, current.String())
1023 current.Reset()
1024 }
1025 continue
1026 }
1027
1028 current.WriteRune(char)
1029 }
1030
1031 // Add the last argument if there is one
1032 if current.Len() > 0 {
1033 result = append(result, current.String())
1034 }
1035
1036 return result
1037}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001038
1039// buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled.
1040// This avoids cross-compilation issues with CGO which is required for the race detector.
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001041// Mounts host Go module cache and build cache for faster subsequent builds.
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001042func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) {
1043 // Find the git repo root
1044 currentDir, err := os.Getwd()
1045 if err != nil {
1046 return "", fmt.Errorf("could not get current directory: %w", err)
1047 }
1048
1049 gitRoot, err := findGitRoot(ctx, currentDir)
1050 if err != nil {
1051 return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err)
1052 }
1053
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001054 // Get host Go cache directories to mount for faster builds
1055 goCacheDir, err := getHostGoCacheDir(ctx)
1056 if err != nil {
1057 return "", fmt.Errorf("failed to get host GOCACHE: %w", err)
1058 }
1059 goModCacheDir, err := getHostGoModCacheDir(ctx)
1060 if err != nil {
1061 return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err)
1062 }
1063
1064 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 -07001065
1066 // Use the published Docker image tag
1067 imageTag := dockerfileBaseHash()
1068 imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag)
1069
1070 // Create destination directory for the binary
1071 destPath := filepath.Join(linuxGopath, "bin")
1072 if err := os.MkdirAll(destPath, 0o777); err != nil {
1073 return "", fmt.Errorf("failed to create destination directory: %w", err)
1074 }
1075 destFile := filepath.Join(destPath, "sketch")
1076
1077 // Create a unique container name
1078 containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano())
1079
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001080 // Run a container with the repo mounted and Go caches for faster builds
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001081 start := time.Now()
1082 slog.DebugContext(ctx, "running Docker container to build sketch with race detector")
1083
1084 // Use explicit output path for clarity
1085 runArgs := []string{
1086 "run",
1087 "--name", containerID,
1088 "-v", gitRoot + ":/app",
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001089 "-v", goCacheDir + ":/root/.cache/go-build",
1090 "-v", goModCacheDir + ":/go/pkg/mod",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001091 "-w", "/app",
1092 imgName,
Josh Bleecher Snyderf4f929a2025-05-23 17:19:26 +00001093 "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 -07001094 }
1095
1096 out, err := combinedOutput(ctx, "docker", runArgs...)
1097 if err != nil {
1098 // Print the output to help with debugging
1099 slog.ErrorContext(ctx, "docker run for race build failed",
1100 slog.String("output", string(out)),
1101 slog.String("error", err.Error()))
1102 return "", fmt.Errorf("docker run failed: %s: %w", out, err)
1103 }
1104
1105 slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start))
1106
1107 // Copy the binary from the container using the explicit path
1108 out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile)
1109 if err != nil {
1110 return "", fmt.Errorf("docker cp failed: %s: %w", out, err)
1111 }
1112
1113 // Clean up the container
1114 if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil {
1115 slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out))
1116 }
1117
1118 // Make the binary executable
1119 if err := os.Chmod(destFile, 0o755); err != nil {
1120 return "", fmt.Errorf("failed to make binary executable: %w", err)
1121 }
1122
1123 return destFile, nil
1124}
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001125
1126// getHostGoCacheDir returns the host's GOCACHE directory
1127func getHostGoCacheDir(ctx context.Context) (string, error) {
1128 out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput()
1129 if err != nil {
1130 return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err)
1131 }
1132 return strings.TrimSpace(string(out)), nil
1133}
1134
1135// getHostGoModCacheDir returns the host's GOMODCACHE directory
1136func getHostGoModCacheDir(ctx context.Context) (string, error) {
1137 out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput()
1138 if err != nil {
1139 return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err)
1140 }
1141 return strings.TrimSpace(string(out)), nil
1142}