blob: 66fd691b6ec1a8d0886dbb62f0daf7dab6d5dcf3 [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
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -070093 // Initial commit to use as starting point. Resolved into Commit on the host.
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000094 InitialCommit string
David Crawshawb5f6a002025-05-05 08:27:16 -070095
96 // Verbose enables verbose output
97 Verbose bool
Philip Zeyliger1dc21372025-05-05 19:54:44 +000098
99 // DockerArgs are additional arguments to pass to the docker create command
100 DockerArgs string
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000101
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000102 // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container
103 Mounts []string
104
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000105 // ExperimentFlag contains the experimental features to enable
106 ExperimentFlag string
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700107
108 // TermUI enables terminal UI
109 TermUI bool
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700110
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000111 // Budget configuration
112 MaxDollars float64
113 MaxIterations uint64
114 MaxWallTime time.Duration
115
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700116 GitRemoteUrl string
117
118 // Commit hash to checkout from GetRemoteUrl
119 Commit string
120
121 // Outtie's HTTP server
122 OutsideHTTP string
Earl Lee2e463fb2025-04-17 11:22:22 -0700123}
124
125// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
126// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700127func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700128 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700129 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700130 if runtime.GOOS == "darwin" {
131 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
132 } else {
133 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
134 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700135 }
136
137 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
138 // `docker ps` provides a good error message here that can be
139 // easily chatgpt'ed by users, so send it to the user as-is:
140 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
141 return fmt.Errorf("docker ps: %s (%w)", out, err)
142 }
143
144 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
145 if err != nil {
146 return err
147 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700148 gitRoot, err := findGitRoot(ctx, config.Path)
149 if err != nil {
150 return err
151 }
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700152 err = checkForEmptyGitRepo(ctx, config.Path)
153 if err != nil {
154 return err
155 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700156
David Crawshaw5a7b3692025-05-05 16:49:15 -0700157 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700158 if err != nil {
159 return err
160 }
161
162 linuxSketchBin := config.SketchBinaryLinux
163 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700164 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700165 if err != nil {
166 return err
167 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700168 }
169
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000170 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700171 defer func() {
172 if config.NoCleanup {
173 return
174 }
175 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
176 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
177 _ = out
178 }
179 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
180 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
181 _ = out
182 }
183 }()
184
185 // errCh receives errors from operations that this function calls in separate goroutines.
186 errCh := make(chan error)
187
188 // Start the git server
189 gitSrv, err := newGitServer(gitRoot)
190 if err != nil {
191 return fmt.Errorf("failed to start git server: %w", err)
192 }
193 defer gitSrv.shutdown(ctx)
194
195 go func() {
196 errCh <- gitSrv.serve(ctx)
197 }()
198
199 // Get the current host git commit
200 var commit string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +0000201 if out, err := combinedOutput(ctx, "git", "rev-parse", config.InitialCommit); err != nil {
202 return fmt.Errorf("git rev-parse %s: %w", config.InitialCommit, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700203 } else {
204 commit = strings.TrimSpace(string(out))
205 }
206 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
207 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
208 }
209
210 relPath, err := filepath.Rel(gitRoot, config.Path)
211 if err != nil {
212 return err
213 }
214
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700215 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
216 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
217 config.Commit = commit
218
Earl Lee2e463fb2025-04-17 11:22:22 -0700219 // Create the sketch container
220 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000221 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700222 }
223
224 // Copy the sketch linux binary into the container
225 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
226 return fmt.Errorf("docker cp: %s, %w", out, err)
227 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700228
229 // Make sure that the webui is built so we can copy the results to the container.
230 _, err = webui.Build()
231 if err != nil {
232 return fmt.Errorf("failed to build webui: %w", err)
233 }
234
David Crawshaw8bff16a2025-04-18 01:16:49 -0700235 webuiZipPath, err := webui.ZipPath()
236 if err != nil {
237 return err
238 }
239 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
240 return fmt.Errorf("docker cp: %s, %w", out, err)
241 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700242
David Crawshaw53786ef2025-04-24 12:52:51 -0700243 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700244
245 // Start the sketch container
246 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
247 return fmt.Errorf("docker start: %s, %w", out, err)
248 }
249
250 // Copies structured logs from the container to the host.
251 copyLogs := func() {
252 if config.ContainerLogDest == "" {
253 return
254 }
255 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
256 if err != nil {
257 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
258 return
259 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700260 prefix := []byte("structured logs:")
261 for line := range bytes.Lines(out) {
262 rest, ok := bytes.CutPrefix(line, prefix)
263 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700264 continue
265 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700266 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700267 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
268 logFileName := filepath.Base(logFile)
269 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
270 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
271 if err != nil {
272 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
273 }
274 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
275 }
276 }
277
278 // NOTE: we want to see what the internal sketch binary prints
279 // regardless of the setting of the verbosity flag on the external
280 // binary, so reading "docker logs", which is the stdout/stderr of
281 // the internal binary is not conditional on the verbose flag.
282 appendInternalErr := func(err error) error {
283 if err == nil {
284 return nil
285 }
286 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000287 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700288 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
289 }
290 out = bytes.TrimSpace(out)
291 if len(out) > 0 {
292 return fmt.Errorf("docker logs: %s;\n%w", out, err)
293 }
294 return err
295 }
296
297 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700298 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700299 if err != nil {
300 return appendInternalErr(err)
301 }
302
Philip Zeyliger00442412025-05-14 11:03:23 -0700303 if config.Verbose {
304 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
305 }
306
Sean McCulloughae3480f2025-04-23 15:28:20 -0700307 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
308 if err != nil {
309 return appendInternalErr(err)
310 }
311 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
312 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700313 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700314 }
Sean McCullough4854c652025-04-24 18:37:02 -0700315
Sean McCullough7013e9e2025-05-14 02:03:58 +0000316 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700317
Sean McCullough078e85a2025-05-08 17:28:34 -0700318 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
319 if err != nil {
320 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
321 }
322
323 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700324 sshAvailable := false
325 sshErrMsg := ""
326 if sshErr != nil {
327 fmt.Println(sshErr.Error())
328 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700329 // continue - ssh config is not required for the rest of sketch to function locally.
330 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700331 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700332 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
333 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700334 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700335🖥️ ssh %s
336🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700337🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700338`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700339 sshUserIdentity = cst.userIdentity
340 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000341
342 // Get the Container CA public key for mutual auth
343 if cst.containerCAPublicKey != nil {
344 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
345 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
346 }
347
348 // Get the host certificate for mutual auth
349 hostCertificate = cst.hostCertificate
350
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700351 defer func() {
352 if err := cst.Cleanup(); err != nil {
353 appendInternalErr(err)
354 }
355 }()
356 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700357
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700358 // Tell the sketch container to Init(), which starts the SSH server
359 // and checks out the right commit.
360 // TODO: I'm trying to move as much configuration as possible into the command-line
361 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
362 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
363 // get the port Docker chose until after the process starts. The SSH config is
364 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
365 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700366 go func() {
367 // TODO: Why is this called in a goroutine? I have found that when I pull this out
368 // of the goroutine and call it inline, then the terminal UI clears itself and all
369 // the scrollback (which is not good, but also not fatal). I can't see why it does this
370 // though, since none of the calls in postContainerInitConfig obviously write to stdout
371 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700372 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700373 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
374 errCh <- appendInternalErr(err)
375 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700376
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700377 // 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 -0700378 ps1URL := "http://" + localAddr
379 if config.SkabandAddr != "" {
380 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700381 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700382 if config.OpenBrowser {
383 browser.Open(ps1URL)
384 }
385 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700386 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700387
388 go func() {
389 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
390 cmd.Stdin = os.Stdin
391 cmd.Stdout = os.Stdout
392 cmd.Stderr = os.Stderr
393 errCh <- run(ctx, "docker attach", cmd)
394 }()
395
396 defer copyLogs()
397
398 for {
399 select {
400 case <-ctx.Done():
401 return ctx.Err()
402 case err := <-errCh:
403 if err != nil {
404 return appendInternalErr(fmt.Errorf("container process: %w", err))
405 }
406 return nil
407 }
408 }
409}
410
411func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
412 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700413 start := time.Now()
414
415 out, err := cmd.CombinedOutput()
416 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700417 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 -0700418 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700419 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 -0700420 }
421 return out, err
422}
423
424func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
425 start := time.Now()
426 err := cmd.Run()
427 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700428 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 -0700429 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700430 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 -0700431 }
432 return err
433}
434
435type gitServer struct {
436 gitLn net.Listener
437 gitPort string
438 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700439 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700440 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700441}
442
443func (gs *gitServer) shutdown(ctx context.Context) {
444 gs.srv.Shutdown(ctx)
445 gs.gitLn.Close()
446}
447
448// Serve a git remote from the host for the container to fetch from and push to.
449func (gs *gitServer) serve(ctx context.Context) error {
450 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
451 return gs.srv.Serve(gs.gitLn)
452}
453
454func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700455 ret := &gitServer{
456 pass: rand.Text(),
457 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700458
Earl Lee2e463fb2025-04-17 11:22:22 -0700459 gitLn, err := net.Listen("tcp4", ":0")
460 if err != nil {
461 return nil, fmt.Errorf("git listen: %w", err)
462 }
463 ret.gitLn = gitLn
464
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700465 browserC := make(chan bool, 1) // channel of browser open requests
466
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000467 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700468 for range browserC {
469 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000470 }
471 }()
472
473 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700474 ret.srv = &srv
475
476 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
477 if err != nil {
478 return nil, fmt.Errorf("git port: %w", err)
479 }
480 ret.gitPort = gitPort
481 return ret, nil
482}
483
484func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700485 cmdArgs := []string{
486 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700487 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700488 "--name", cntrName,
489 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700490 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700491 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700492 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700493 cmdArgs = append(cmdArgs, "-t")
494 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000495
496 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
497 cmdArgs = append(cmdArgs, "-e", envVar)
498 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700499 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700500 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700501 }
502 if config.SketchPubKey != "" {
503 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
504 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700505 if config.SSHPort > 0 {
506 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
507 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700508 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700509 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700510 if relPath != "." {
511 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
512 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700513 // colima does this by default, but Linux docker seems to need this set explicitly
514 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000515
516 // Add volume mounts if specified
517 for _, mount := range config.Mounts {
518 if mount != "" {
519 cmdArgs = append(cmdArgs, "-v", mount)
520 }
521 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700522 cmdArgs = append(
523 cmdArgs,
524 imgName,
525 "/bin/sketch",
526 "-unsafe",
527 "-addr=:80",
528 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000529 "-git-username="+config.GitUsername,
530 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000531 "-outside-hostname="+config.OutsideHostname,
532 "-outside-os="+config.OutsideOS,
533 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000534 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
535 fmt.Sprintf("-max-iterations=%d", config.MaxIterations),
536 fmt.Sprintf("-max-wall-time=%s", config.MaxWallTime.String()),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700537 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700538 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700539 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000540 "-x="+config.ExperimentFlag,
Earl Lee2e463fb2025-04-17 11:22:22 -0700541 )
David Crawshaw5a7b3692025-05-05 16:49:15 -0700542 if config.Model != "" {
543 cmdArgs = append(cmdArgs, "-model="+config.Model)
544 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700545 if config.GitRemoteUrl != "" {
546 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
547 if config.Commit == "" {
548 panic("Commit should have been set when GitRemoteUrl was set")
549 }
550 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
551 }
552 if config.OutsideHTTP != "" {
553 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
554 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000555 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100556 if config.Prompt != "" {
557 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
558 }
559 if config.OneShot {
560 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700561 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000562 if config.ModelURL == "" {
563 // Forward ANTHROPIC_API_KEY for direct use.
564 // TODO: have outtie run an http proxy?
565 // TODO: select and forward the relevant API key based on the model
566 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
567 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000568
569 // Add additional docker arguments if provided
570 if config.DockerArgs != "" {
571 // Parse space-separated docker arguments with support for quotes and escaping
572 args := parseDockerArgs(config.DockerArgs)
573 // Insert arguments after "create" but before other arguments
574 for i := len(args) - 1; i >= 0; i-- {
575 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
576 }
577 }
578
Earl Lee2e463fb2025-04-17 11:22:22 -0700579 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
580 return fmt.Errorf("docker create: %s, %w", out, err)
581 }
582 return nil
583}
584
David Crawshawb5f6a002025-05-05 08:27:16 -0700585func buildLinuxSketchBin(ctx context.Context) (string, error) {
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700586 // Detect if race detector is enabled and use a different cache path
587 raceEnabled := RaceEnabled()
588 cacheSuffix := ""
589 if raceEnabled {
590 cacheSuffix = "-race"
591 }
592
593 homeDir, err := os.UserHomeDir()
594 if err != nil {
595 return "", err
596 }
597
598 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix)
599 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
600 return "", err
601 }
602
603 // When race detector is enabled, use Docker to build the Linux binary
604 if raceEnabled {
605 return buildLinuxSketchBinWithDocker(ctx, linuxGopath)
606 }
607
608 // Standard non-race build using cross-compilation
Pokey Rulea9a786b2025-05-12 10:52:34 +0100609 // Change to directory containing dockerimg.go for module detection
610 _, codeFile, _, _ := runtime.Caller(0)
611 codeDir := filepath.Dir(codeFile)
612 if currentDir, err := os.Getwd(); err != nil {
613 slog.WarnContext(ctx, "could not get current directory", "err", err)
614 } else {
615 if err := os.Chdir(codeDir); err != nil {
616 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
617 } else {
618 defer func() {
619 _ = os.Chdir(currentDir)
620 }()
621 }
622 }
623
David Crawshaw8a617cb2025-04-18 01:28:43 -0700624 verToInstall := "@latest"
625 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
626 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
627 } else {
628 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700629 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700630 verToInstall = ""
631 }
632 }
David Crawshaw69c67312025-04-17 13:42:00 -0700633
Earl Lee2e463fb2025-04-17 11:22:22 -0700634 start := time.Now()
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700635 args := []string{"install"}
636 args = append(args, "sketch.dev/cmd/sketch"+verToInstall)
637
638 cmd := exec.CommandContext(ctx, "go", args...)
David Crawshawb9eaef52025-04-17 15:23:18 -0700639 cmd.Env = append(
640 os.Environ(),
641 "GOOS=linux",
642 "CGO_ENABLED=0",
643 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700644 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700645 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700646 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700647
Earl Lee2e463fb2025-04-17 11:22:22 -0700648 out, err := cmd.CombinedOutput()
649 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700650 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 -0700651 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
652 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700653 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 -0700654 }
655
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700656 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700657 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700658 }
David Crawshawc7e77962025-05-03 13:20:18 -0700659 // If we are already on Linux, there's no extra platform name in the path
660 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700661}
662
Sean McCulloughae3480f2025-04-23 15:28:20 -0700663func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700664 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700665 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700666 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
667 } else {
668 v4, _, found := strings.Cut(string(out), "\n")
669 if !found {
670 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
671 }
672 localAddr = v4
673 if strings.HasPrefix(localAddr, "0.0.0.0") {
674 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
675 }
676 }
677 return localAddr, nil
678}
679
680// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700681func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700682 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700683
684 initMsg, err := json.Marshal(
685 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000686 HostAddr: localAddr,
687 SSHAuthorizedKeys: sshAuthorizedKeys,
688 SSHServerIdentity: sshServerIdentity,
689 SSHContainerCAKey: sshContainerCAKey,
690 SSHHostCertificate: sshHostCertificate,
691 SSHAvailable: sshAvailable,
692 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700693 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700694 if err != nil {
695 return fmt.Errorf("init msg: %w", err)
696 }
697
Earl Lee2e463fb2025-04-17 11:22:22 -0700698 // Note: this /init POST is handled in loop/server/loophttp.go:
699 initMsgByteReader := bytes.NewReader(initMsg)
700 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
701 if err != nil {
702 return err
703 }
704
705 var res *http.Response
706 for i := 0; ; i++ {
707 time.Sleep(100 * time.Millisecond)
708 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
709 initMsgByteReader.Reset(initMsg)
710 res, err = http.DefaultClient.Do(req)
711 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700712 if i < 100 {
713 if i%10 == 0 {
714 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
715 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700716 continue
717 }
718 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
719 }
720 break
721 }
722 resBytes, _ := io.ReadAll(res.Body)
723 if res.StatusCode != http.StatusOK {
724 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
725 }
726 return nil
727}
728
David Crawshaw5a7b3692025-05-05 16:49:15 -0700729func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700730 h := sha256.Sum256([]byte(gitRoot))
731 imgName = "sketch-" + hex.EncodeToString(h[:6])
732
733 var curImgInitFilesHash string
734 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
735 if strings.Contains(string(out), "No such object") {
736 // Image does not exist, continue and build it.
737 curImgInitFilesHash = ""
738 } else {
739 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
740 }
741 } else {
742 m := map[string]string{}
743 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
744 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
745 }
746 curImgInitFilesHash = m["sketch_context"]
747 }
748
749 candidates, err := findRepoDockerfiles(cwd, gitRoot)
750 if err != nil {
751 return "", fmt.Errorf("find dockerfile: %w", err)
752 }
753
754 var initFiles map[string]string
755 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700756 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700757
758 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
759 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
760 dockerfilePath = candidates[0]
761 contents, err := os.ReadFile(dockerfilePath)
762 if err != nil {
763 return "", err
764 }
765 fmt.Printf("using %s as dev env\n", candidates[0])
766 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700767 return imgName, nil
768 }
769 } else {
770 initFiles, err = readInitFiles(os.DirFS(gitRoot))
771 if err != nil {
772 return "", err
773 }
774 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
775 if err != nil {
776 return "", err
777 }
778 initFileHash := hashInitFiles(initFiles)
779 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700780 return imgName, nil
781 }
782
David Crawshaw5a7b3692025-05-05 16:49:15 -0700783 if model == "gemini" {
784 if strings.HasSuffix(modelURL, "/gemmsgs") {
785 // Horrible hack! Switch back to anthropic for container building.
David Crawshaw3659d872025-05-05 17:52:23 -0700786 // We can do this because we are talking to skaband and know the address.
David Crawshaw5a7b3692025-05-05 16:49:15 -0700787 modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1)
788 } else {
789 return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini")
790 }
791 }
792
Earl Lee2e463fb2025-04-17 11:22:22 -0700793 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700794 srv := &ant.Service{
David Crawshaw5a7b3692025-05-05 16:49:15 -0700795 URL: modelURL,
796 APIKey: modelAPIKey,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700797 HTTPC: http.DefaultClient,
798 }
Pokey Rulec31e2962025-05-13 10:53:33 +0000799 generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700800 if err != nil {
801 return "", fmt.Errorf("create dockerfile: %w", err)
802 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000803 // Create a unique temporary directory for the Dockerfile
804 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
805 if err != nil {
806 return "", fmt.Errorf("failed to create temporary directory: %w", err)
807 }
808 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700809 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700810 return "", err
811 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000812 // Remove the temporary directory and all contents when done
813 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700814
David Crawshawb5f6a002025-05-05 08:27:16 -0700815 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700816 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 -0700817 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700818 }
819
820 var gitUserEmail, gitUserName string
821 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
822 return "", fmt.Errorf("git config: %s: %v", out, err)
823 } else {
824 gitUserEmail = strings.TrimSpace(string(out))
825 }
826 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
827 return "", fmt.Errorf("git config: %s: %v", out, err)
828 } else {
829 gitUserName = strings.TrimSpace(string(out))
830 }
831
832 start := time.Now()
833 cmd := exec.CommandContext(ctx,
834 "docker", "build",
835 "-t", imgName,
836 "-f", dockerfilePath,
837 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
838 "--build-arg", "GIT_USER_NAME="+gitUserName,
David Crawshaw31f15242025-05-06 16:03:49 -0700839 ".",
Earl Lee2e463fb2025-04-17 11:22:22 -0700840 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700841 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700842 // We print the docker build output whether or not the user
843 // has selected --verbose. Building an image takes a while
844 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700845 cmd.Stdout = os.Stdout
846 cmd.Stderr = os.Stderr
847 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700848
849 err = run(ctx, "docker build", cmd)
850 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700851 var msg string
852 if generatedDockerfile != "" {
853 if !verbose {
854 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
855 }
856 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
857 }
858 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700859 }
860 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
861 return imgName, nil
862}
863
864func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
865 files, err := findDirDockerfiles(cwd)
866 if err != nil {
867 return nil, err
868 }
869 if len(files) > 0 {
870 return files, nil
871 }
872
873 path := cwd
874 for path != gitRoot {
875 path = filepath.Dir(path)
876 files, err := findDirDockerfiles(path)
877 if err != nil {
878 return nil, err
879 }
880 if len(files) > 0 {
881 return files, nil
882 }
883 }
884 return files, nil
885}
886
887// findDirDockerfiles finds all "Dockerfile*" files in a directory.
888func findDirDockerfiles(root string) (res []string, err error) {
889 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
890 if err != nil {
891 return err
892 }
893 if info.IsDir() && root != path {
894 return filepath.SkipDir
895 }
896 name := strings.ToLower(info.Name())
897 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
898 res = append(res, path)
899 }
900 return nil
901 })
902 if err != nil {
903 return nil, err
904 }
905 return res, nil
906}
907
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700908func checkForEmptyGitRepo(ctx context.Context, path string) error {
909 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
910 cmd.Dir = path
911 _, err := cmd.CombinedOutput()
912 if err != nil {
913 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
914 "git commit --allow-empty -m 'initial commit'")
915 }
916 return nil
917}
918
Earl Lee2e463fb2025-04-17 11:22:22 -0700919func findGitRoot(ctx context.Context, path string) (string, error) {
920 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
921 cmd.Dir = path
922 out, err := cmd.CombinedOutput()
923 if err != nil {
924 if strings.Contains(string(out), "not a git repository") {
925 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
926Consider one of the following options:
927 - cd to a different dir that is already part of a git repo first, or
928 - to create a new git repo from this directory (%s), run this command:
929
930 git init . && git commit --allow-empty -m "initial commit"
931
932and try running sketch again.
933`, path, path)
934 }
935 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
936 }
937 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
938 absGitDir := filepath.Join(path, gitDir)
939 return filepath.Dir(absGitDir), err
940}
941
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000942// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
943// from git config using the sketch.envfwd multi-valued key.
944func getEnvForwardingFromGitConfig(ctx context.Context) []string {
945 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
946 out := string(outb)
947 if err != nil {
948 if strings.Contains(out, "key does not exist") {
949 return nil
950 }
951 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
952 return nil
953 }
954
955 var envVars []string
956 for envVar := range strings.Lines(out) {
957 envVar = strings.TrimSpace(envVar)
958 if envVar == "" {
959 continue
960 }
961 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
962 }
963 return envVars
964}
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000965
966// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
967// It handles quoted arguments and escaped characters.
968//
969// Examples:
970//
971// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
972// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
973// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
974func parseDockerArgs(args string) []string {
975 if args = strings.TrimSpace(args); args == "" {
976 return []string{}
977 }
978
979 var result []string
980 var current strings.Builder
981 inQuotes := false
982 escapeNext := false
983 quoteChar := rune(0)
984
985 for _, char := range args {
986 if escapeNext {
987 current.WriteRune(char)
988 escapeNext = false
989 continue
990 }
991
992 if char == '\\' {
993 escapeNext = true
994 continue
995 }
996
997 if char == '"' || char == '\'' {
998 if !inQuotes {
999 inQuotes = true
1000 quoteChar = char
1001 continue
1002 } else if char == quoteChar {
1003 inQuotes = false
1004 quoteChar = rune(0)
1005 continue
1006 }
1007 // Non-matching quote character inside quotes
1008 current.WriteRune(char)
1009 continue
1010 }
1011
1012 // Space outside of quotes is an argument separator
1013 if char == ' ' && !inQuotes {
1014 if current.Len() > 0 {
1015 result = append(result, current.String())
1016 current.Reset()
1017 }
1018 continue
1019 }
1020
1021 current.WriteRune(char)
1022 }
1023
1024 // Add the last argument if there is one
1025 if current.Len() > 0 {
1026 result = append(result, current.String())
1027 }
1028
1029 return result
1030}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001031
1032// buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled.
1033// This avoids cross-compilation issues with CGO which is required for the race detector.
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001034// Mounts host Go module cache and build cache for faster subsequent builds.
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001035func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) {
1036 // Find the git repo root
1037 currentDir, err := os.Getwd()
1038 if err != nil {
1039 return "", fmt.Errorf("could not get current directory: %w", err)
1040 }
1041
1042 gitRoot, err := findGitRoot(ctx, currentDir)
1043 if err != nil {
1044 return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err)
1045 }
1046
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001047 // Get host Go cache directories to mount for faster builds
1048 goCacheDir, err := getHostGoCacheDir(ctx)
1049 if err != nil {
1050 return "", fmt.Errorf("failed to get host GOCACHE: %w", err)
1051 }
1052 goModCacheDir, err := getHostGoModCacheDir(ctx)
1053 if err != nil {
1054 return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err)
1055 }
1056
1057 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 -07001058
1059 // Use the published Docker image tag
1060 imageTag := dockerfileBaseHash()
1061 imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag)
1062
1063 // Create destination directory for the binary
1064 destPath := filepath.Join(linuxGopath, "bin")
1065 if err := os.MkdirAll(destPath, 0o777); err != nil {
1066 return "", fmt.Errorf("failed to create destination directory: %w", err)
1067 }
1068 destFile := filepath.Join(destPath, "sketch")
1069
1070 // Create a unique container name
1071 containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano())
1072
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001073 // Run a container with the repo mounted and Go caches for faster builds
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001074 start := time.Now()
1075 slog.DebugContext(ctx, "running Docker container to build sketch with race detector")
1076
1077 // Use explicit output path for clarity
1078 runArgs := []string{
1079 "run",
1080 "--name", containerID,
1081 "-v", gitRoot + ":/app",
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001082 "-v", goCacheDir + ":/root/.cache/go-build",
1083 "-v", goModCacheDir + ":/go/pkg/mod",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001084 "-w", "/app",
1085 imgName,
Josh Bleecher Snyderf4f929a2025-05-23 17:19:26 +00001086 "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 -07001087 }
1088
1089 out, err := combinedOutput(ctx, "docker", runArgs...)
1090 if err != nil {
1091 // Print the output to help with debugging
1092 slog.ErrorContext(ctx, "docker run for race build failed",
1093 slog.String("output", string(out)),
1094 slog.String("error", err.Error()))
1095 return "", fmt.Errorf("docker run failed: %s: %w", out, err)
1096 }
1097
1098 slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start))
1099
1100 // Copy the binary from the container using the explicit path
1101 out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile)
1102 if err != nil {
1103 return "", fmt.Errorf("docker cp failed: %s: %w", out, err)
1104 }
1105
1106 // Clean up the container
1107 if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil {
1108 slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out))
1109 }
1110
1111 // Make the binary executable
1112 if err := os.Chmod(destFile, 0o755); err != nil {
1113 return "", fmt.Errorf("failed to make binary executable: %w", err)
1114 }
1115
1116 return destFile, nil
1117}
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001118
1119// getHostGoCacheDir returns the host's GOCACHE directory
1120func getHostGoCacheDir(ctx context.Context) (string, error) {
1121 out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput()
1122 if err != nil {
1123 return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err)
1124 }
1125 return strings.TrimSpace(string(out)), nil
1126}
1127
1128// getHostGoModCacheDir returns the host's GOMODCACHE directory
1129func getHostGoModCacheDir(ctx context.Context) (string, error) {
1130 out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput()
1131 if err != nil {
1132 return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err)
1133 }
1134 return strings.TrimSpace(string(out)), nil
1135}