blob: 0759b22d364eae80396ce001ea3f7266ae41a6dd [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package dockerimg
2package dockerimg
3
4import (
5 "bytes"
6 "context"
Philip Zeyliger5e227dd2025-04-21 15:55:29 -07007 "crypto/rand"
Earl Lee2e463fb2025-04-17 11:22:22 -07008 "crypto/sha256"
9 "encoding/hex"
10 "encoding/json"
11 "fmt"
12 "io"
13 "log/slog"
14 "net"
15 "net/http"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "runtime"
20 "strings"
Josh Bleecher Snyder99570462025-05-05 10:26:14 -070021 "sync/atomic"
Earl Lee2e463fb2025-04-17 11:22:22 -070022 "time"
23
Sean McCullough7013e9e2025-05-14 02:03:58 +000024 "golang.org/x/crypto/ssh"
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000025 "sketch.dev/browser"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070026 "sketch.dev/llm/ant"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070027 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070028 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070029 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070030)
31
32// ContainerConfig holds all configuration for launching a container
33type ContainerConfig struct {
34 // SessionID is the unique identifier for this session
35 SessionID string
36
37 // LocalAddr is the initial address to use (though it may be overwritten later)
38 LocalAddr string
39
40 // SkabandAddr is the address of the skaband service if available
41 SkabandAddr string
42
David Crawshaw5a7b3692025-05-05 16:49:15 -070043 // Model is the name of the LLM model to use.
44 Model string
Earl Lee2e463fb2025-04-17 11:22:22 -070045
David Crawshaw5a7b3692025-05-05 16:49:15 -070046 // ModelURL is the URL of the LLM service.
47 ModelURL string
48
49 // ModelAPIKey is the API key for LLM service.
50 ModelAPIKey string
Earl Lee2e463fb2025-04-17 11:22:22 -070051
52 // Path is the local filesystem path to use
53 Path string
54
55 // GitUsername is the username to use for git operations
56 GitUsername string
57
58 // GitEmail is the email to use for git operations
59 GitEmail string
60
61 // OpenBrowser determines whether to open a browser automatically
62 OpenBrowser bool
63
64 // NoCleanup prevents container cleanup when set to true
65 NoCleanup bool
66
67 // ForceRebuild forces rebuilding of the Docker image even if it exists
68 ForceRebuild bool
69
70 // Host directory to copy container logs into, if not set to ""
71 ContainerLogDest string
72
73 // Path to pre-built linux sketch binary, or build a new one if set to ""
74 SketchBinaryLinux string
75
76 // Sketch client public key.
77 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000078
Sean McCulloughbaa2b592025-04-23 10:40:08 -070079 // Host port for the container's ssh server
80 SSHPort int
81
Philip Zeyliger18532b22025-04-23 21:11:46 +000082 // Outside information to pass to the container
83 OutsideHostname string
84 OutsideOS string
85 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070086
Pokey Rule0dcebe12025-04-28 14:51:04 +010087 // If true, exit after the first turn
88 OneShot bool
89
90 // Initial prompt
91 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000092
David Crawshawb5f6a002025-05-05 08:27:16 -070093 // Verbose enables verbose output
94 Verbose bool
Philip Zeyliger1dc21372025-05-05 19:54:44 +000095
96 // DockerArgs are additional arguments to pass to the docker create command
97 DockerArgs string
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +000098
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +000099 // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container
100 Mounts []string
101
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000102 // ExperimentFlag contains the experimental features to enable
103 ExperimentFlag string
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700104
105 // TermUI enables terminal UI
106 TermUI bool
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700107
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000108 // Budget configuration
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000109 MaxDollars float64
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000110
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700111 GitRemoteUrl string
112
113 // Commit hash to checkout from GetRemoteUrl
114 Commit string
115
116 // Outtie's HTTP server
117 OutsideHTTP string
Earl Lee2e463fb2025-04-17 11:22:22 -0700118}
119
120// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
121// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700122func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700123 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700124 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700125 if runtime.GOOS == "darwin" {
126 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
127 } else {
128 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
129 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700130 }
131
132 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
133 // `docker ps` provides a good error message here that can be
134 // easily chatgpt'ed by users, so send it to the user as-is:
135 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
136 return fmt.Errorf("docker ps: %s (%w)", out, err)
137 }
138
139 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
140 if err != nil {
141 return err
142 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700143 gitRoot, err := findGitRoot(ctx, config.Path)
144 if err != nil {
145 return err
146 }
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700147 err = checkForEmptyGitRepo(ctx, config.Path)
148 if err != nil {
149 return err
150 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700151
David Crawshaw5a7b3692025-05-05 16:49:15 -0700152 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700153 if err != nil {
154 return err
155 }
156
157 linuxSketchBin := config.SketchBinaryLinux
158 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700159 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700160 if err != nil {
161 return err
162 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700163 }
164
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000165 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700166 defer func() {
167 if config.NoCleanup {
168 return
169 }
170 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
171 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
172 _ = out
173 }
174 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
175 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
176 _ = out
177 }
178 }()
179
180 // errCh receives errors from operations that this function calls in separate goroutines.
181 errCh := make(chan error)
182
183 // Start the git server
184 gitSrv, err := newGitServer(gitRoot)
185 if err != nil {
186 return fmt.Errorf("failed to start git server: %w", err)
187 }
188 defer gitSrv.shutdown(ctx)
189
190 go func() {
191 errCh <- gitSrv.serve(ctx)
192 }()
193
194 // Get the current host git commit
195 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000196 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
197 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700198 } else {
199 commit = strings.TrimSpace(string(out))
200 }
201 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
202 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
203 }
204
205 relPath, err := filepath.Rel(gitRoot, config.Path)
206 if err != nil {
207 return err
208 }
209
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700210 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
211 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
212 config.Commit = commit
213
Earl Lee2e463fb2025-04-17 11:22:22 -0700214 // Create the sketch container
215 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000216 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700217 }
218
219 // Copy the sketch linux binary into the container
220 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
221 return fmt.Errorf("docker cp: %s, %w", out, err)
222 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700223
224 // Make sure that the webui is built so we can copy the results to the container.
225 _, err = webui.Build()
226 if err != nil {
227 return fmt.Errorf("failed to build webui: %w", err)
228 }
229
David Crawshaw8bff16a2025-04-18 01:16:49 -0700230 webuiZipPath, err := webui.ZipPath()
231 if err != nil {
232 return err
233 }
234 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
235 return fmt.Errorf("docker cp: %s, %w", out, err)
236 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700237
David Crawshaw53786ef2025-04-24 12:52:51 -0700238 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700239
240 // Start the sketch container
241 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
242 return fmt.Errorf("docker start: %s, %w", out, err)
243 }
244
245 // Copies structured logs from the container to the host.
246 copyLogs := func() {
247 if config.ContainerLogDest == "" {
248 return
249 }
250 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
251 if err != nil {
252 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
253 return
254 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700255 prefix := []byte("structured logs:")
256 for line := range bytes.Lines(out) {
257 rest, ok := bytes.CutPrefix(line, prefix)
258 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700259 continue
260 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700261 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700262 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
263 logFileName := filepath.Base(logFile)
264 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
265 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
266 if err != nil {
267 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
268 }
269 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
270 }
271 }
272
273 // NOTE: we want to see what the internal sketch binary prints
274 // regardless of the setting of the verbosity flag on the external
275 // binary, so reading "docker logs", which is the stdout/stderr of
276 // the internal binary is not conditional on the verbose flag.
277 appendInternalErr := func(err error) error {
278 if err == nil {
279 return nil
280 }
281 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000282 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700283 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
284 }
285 out = bytes.TrimSpace(out)
286 if len(out) > 0 {
287 return fmt.Errorf("docker logs: %s;\n%w", out, err)
288 }
289 return err
290 }
291
292 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700293 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700294 if err != nil {
295 return appendInternalErr(err)
296 }
297
Philip Zeyliger00442412025-05-14 11:03:23 -0700298 if config.Verbose {
299 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
300 }
301
Sean McCulloughae3480f2025-04-23 15:28:20 -0700302 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
303 if err != nil {
304 return appendInternalErr(err)
305 }
306 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
307 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700308 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700309 }
Sean McCullough4854c652025-04-24 18:37:02 -0700310
Sean McCullough7013e9e2025-05-14 02:03:58 +0000311 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700312
Sean McCullough078e85a2025-05-08 17:28:34 -0700313 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
314 if err != nil {
315 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
316 }
317
318 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700319 sshAvailable := false
320 sshErrMsg := ""
321 if sshErr != nil {
322 fmt.Println(sshErr.Error())
323 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700324 // continue - ssh config is not required for the rest of sketch to function locally.
325 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700326 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700327 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
328 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700329 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700330🖥️ ssh %s
331🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700332🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700333`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700334 sshUserIdentity = cst.userIdentity
335 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000336
337 // Get the Container CA public key for mutual auth
338 if cst.containerCAPublicKey != nil {
339 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
340 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
341 }
342
343 // Get the host certificate for mutual auth
344 hostCertificate = cst.hostCertificate
345
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700346 defer func() {
347 if err := cst.Cleanup(); err != nil {
348 appendInternalErr(err)
349 }
350 }()
351 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700352
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700353 // Tell the sketch container to Init(), which starts the SSH server
354 // and checks out the right commit.
355 // TODO: I'm trying to move as much configuration as possible into the command-line
356 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
357 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
358 // get the port Docker chose until after the process starts. The SSH config is
359 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
360 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700361 go func() {
362 // TODO: Why is this called in a goroutine? I have found that when I pull this out
363 // of the goroutine and call it inline, then the terminal UI clears itself and all
364 // the scrollback (which is not good, but also not fatal). I can't see why it does this
365 // though, since none of the calls in postContainerInitConfig obviously write to stdout
366 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700367 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700368 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
369 errCh <- appendInternalErr(err)
370 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700371
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700372 // 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 -0700373 ps1URL := "http://" + localAddr
374 if config.SkabandAddr != "" {
375 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700376 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700377 if config.OpenBrowser {
378 browser.Open(ps1URL)
379 }
380 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700381 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700382
Sean McCullough138ec242025-06-02 22:42:06 +0000383 // Start automatic port tunneling if SSH is available
384 if sshAvailable {
385 go func() {
386 containerURL := "http://" + localAddr
387 tunnelManager := NewTunnelManager(containerURL, cntrName, 10) // Allow up to 10 concurrent tunnels
388 tunnelManager.Start(ctx)
389 slog.InfoContext(ctx, "Started automatic port tunnel manager", "container", cntrName)
390 }()
391 }
392
Earl Lee2e463fb2025-04-17 11:22:22 -0700393 go func() {
394 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
395 cmd.Stdin = os.Stdin
396 cmd.Stdout = os.Stdout
397 cmd.Stderr = os.Stderr
398 errCh <- run(ctx, "docker attach", cmd)
399 }()
400
401 defer copyLogs()
402
403 for {
404 select {
405 case <-ctx.Done():
406 return ctx.Err()
407 case err := <-errCh:
408 if err != nil {
409 return appendInternalErr(fmt.Errorf("container process: %w", err))
410 }
411 return nil
412 }
413 }
414}
415
416func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
417 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700418 start := time.Now()
419
420 out, err := cmd.CombinedOutput()
421 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700422 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 -0700423 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700424 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 -0700425 }
426 return out, err
427}
428
429func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
430 start := time.Now()
431 err := cmd.Run()
432 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700433 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 -0700434 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700435 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 -0700436 }
437 return err
438}
439
440type gitServer struct {
441 gitLn net.Listener
442 gitPort string
443 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700444 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700445 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700446}
447
448func (gs *gitServer) shutdown(ctx context.Context) {
449 gs.srv.Shutdown(ctx)
450 gs.gitLn.Close()
451}
452
453// Serve a git remote from the host for the container to fetch from and push to.
454func (gs *gitServer) serve(ctx context.Context) error {
455 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
456 return gs.srv.Serve(gs.gitLn)
457}
458
459func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700460 ret := &gitServer{
461 pass: rand.Text(),
462 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700463
Earl Lee2e463fb2025-04-17 11:22:22 -0700464 gitLn, err := net.Listen("tcp4", ":0")
465 if err != nil {
466 return nil, fmt.Errorf("git listen: %w", err)
467 }
468 ret.gitLn = gitLn
469
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700470 browserC := make(chan bool, 1) // channel of browser open requests
471
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000472 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700473 for range browserC {
474 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000475 }
476 }()
477
478 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700479 ret.srv = &srv
480
481 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
482 if err != nil {
483 return nil, fmt.Errorf("git port: %w", err)
484 }
485 ret.gitPort = gitPort
486 return ret, nil
487}
488
489func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700490 cmdArgs := []string{
491 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700492 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700493 "--name", cntrName,
494 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700495 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700496 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700497 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700498 cmdArgs = append(cmdArgs, "-t")
499 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000500
501 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
502 cmdArgs = append(cmdArgs, "-e", envVar)
503 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700504 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700505 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700506 }
507 if config.SketchPubKey != "" {
508 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
509 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700510 if config.SSHPort > 0 {
511 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
512 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700513 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700514 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700515 if relPath != "." {
516 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
517 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700518 // colima does this by default, but Linux docker seems to need this set explicitly
519 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000520
521 // Add volume mounts if specified
522 for _, mount := range config.Mounts {
523 if mount != "" {
524 cmdArgs = append(cmdArgs, "-v", mount)
525 }
526 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700527 cmdArgs = append(
528 cmdArgs,
529 imgName,
530 "/bin/sketch",
531 "-unsafe",
532 "-addr=:80",
533 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000534 "-git-username="+config.GitUsername,
535 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000536 "-outside-hostname="+config.OutsideHostname,
537 "-outside-os="+config.OutsideOS,
538 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000539 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700540 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700541 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700542 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000543 "-x="+config.ExperimentFlag,
Earl Lee2e463fb2025-04-17 11:22:22 -0700544 )
David Crawshaw5a7b3692025-05-05 16:49:15 -0700545 if config.Model != "" {
546 cmdArgs = append(cmdArgs, "-model="+config.Model)
547 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700548 if config.GitRemoteUrl != "" {
549 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
550 if config.Commit == "" {
551 panic("Commit should have been set when GitRemoteUrl was set")
552 }
553 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
554 }
555 if config.OutsideHTTP != "" {
556 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
557 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000558 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100559 if config.Prompt != "" {
560 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
561 }
562 if config.OneShot {
563 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700564 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000565 if config.ModelURL == "" {
566 // Forward ANTHROPIC_API_KEY for direct use.
567 // TODO: have outtie run an http proxy?
568 // TODO: select and forward the relevant API key based on the model
569 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
570 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000571
572 // Add additional docker arguments if provided
573 if config.DockerArgs != "" {
574 // Parse space-separated docker arguments with support for quotes and escaping
575 args := parseDockerArgs(config.DockerArgs)
576 // Insert arguments after "create" but before other arguments
577 for i := len(args) - 1; i >= 0; i-- {
578 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
579 }
580 }
581
Earl Lee2e463fb2025-04-17 11:22:22 -0700582 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
583 return fmt.Errorf("docker create: %s, %w", out, err)
584 }
585 return nil
586}
587
David Crawshawb5f6a002025-05-05 08:27:16 -0700588func buildLinuxSketchBin(ctx context.Context) (string, error) {
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700589 // Detect if race detector is enabled and use a different cache path
590 raceEnabled := RaceEnabled()
591 cacheSuffix := ""
592 if raceEnabled {
593 cacheSuffix = "-race"
594 }
595
596 homeDir, err := os.UserHomeDir()
597 if err != nil {
598 return "", err
599 }
600
601 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix)
602 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
603 return "", err
604 }
605
606 // When race detector is enabled, use Docker to build the Linux binary
607 if raceEnabled {
608 return buildLinuxSketchBinWithDocker(ctx, linuxGopath)
609 }
610
611 // Standard non-race build using cross-compilation
Pokey Rulea9a786b2025-05-12 10:52:34 +0100612 // Change to directory containing dockerimg.go for module detection
613 _, codeFile, _, _ := runtime.Caller(0)
614 codeDir := filepath.Dir(codeFile)
615 if currentDir, err := os.Getwd(); err != nil {
616 slog.WarnContext(ctx, "could not get current directory", "err", err)
617 } else {
618 if err := os.Chdir(codeDir); err != nil {
619 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
620 } else {
621 defer func() {
622 _ = os.Chdir(currentDir)
623 }()
624 }
625 }
626
David Crawshaw8a617cb2025-04-18 01:28:43 -0700627 verToInstall := "@latest"
628 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
629 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
630 } else {
631 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700632 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700633 verToInstall = ""
634 }
635 }
David Crawshaw69c67312025-04-17 13:42:00 -0700636
Earl Lee2e463fb2025-04-17 11:22:22 -0700637 start := time.Now()
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700638 args := []string{"install"}
639 args = append(args, "sketch.dev/cmd/sketch"+verToInstall)
640
641 cmd := exec.CommandContext(ctx, "go", args...)
David Crawshawb9eaef52025-04-17 15:23:18 -0700642 cmd.Env = append(
643 os.Environ(),
644 "GOOS=linux",
645 "CGO_ENABLED=0",
646 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700647 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700648 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700649 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700650
Earl Lee2e463fb2025-04-17 11:22:22 -0700651 out, err := cmd.CombinedOutput()
652 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700653 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 -0700654 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
655 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700656 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 -0700657 }
658
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700659 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700660 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700661 }
David Crawshawc7e77962025-05-03 13:20:18 -0700662 // If we are already on Linux, there's no extra platform name in the path
663 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700664}
665
Sean McCulloughae3480f2025-04-23 15:28:20 -0700666func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700667 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700668 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700669 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
670 } else {
671 v4, _, found := strings.Cut(string(out), "\n")
672 if !found {
673 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
674 }
675 localAddr = v4
676 if strings.HasPrefix(localAddr, "0.0.0.0") {
677 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
678 }
679 }
680 return localAddr, nil
681}
682
683// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700684func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700685 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700686
687 initMsg, err := json.Marshal(
688 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000689 HostAddr: localAddr,
690 SSHAuthorizedKeys: sshAuthorizedKeys,
691 SSHServerIdentity: sshServerIdentity,
692 SSHContainerCAKey: sshContainerCAKey,
693 SSHHostCertificate: sshHostCertificate,
694 SSHAvailable: sshAvailable,
695 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700696 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700697 if err != nil {
698 return fmt.Errorf("init msg: %w", err)
699 }
700
Earl Lee2e463fb2025-04-17 11:22:22 -0700701 // Note: this /init POST is handled in loop/server/loophttp.go:
702 initMsgByteReader := bytes.NewReader(initMsg)
703 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
704 if err != nil {
705 return err
706 }
707
708 var res *http.Response
709 for i := 0; ; i++ {
710 time.Sleep(100 * time.Millisecond)
711 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
712 initMsgByteReader.Reset(initMsg)
713 res, err = http.DefaultClient.Do(req)
714 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700715 if i < 100 {
716 if i%10 == 0 {
717 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
718 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700719 continue
720 }
721 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
722 }
723 break
724 }
725 resBytes, _ := io.ReadAll(res.Body)
726 if res.StatusCode != http.StatusOK {
727 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
728 }
729 return nil
730}
731
David Crawshaw5a7b3692025-05-05 16:49:15 -0700732func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700733 h := sha256.Sum256([]byte(gitRoot))
734 imgName = "sketch-" + hex.EncodeToString(h[:6])
735
736 var curImgInitFilesHash string
737 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
738 if strings.Contains(string(out), "No such object") {
739 // Image does not exist, continue and build it.
740 curImgInitFilesHash = ""
741 } else {
742 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
743 }
744 } else {
745 m := map[string]string{}
746 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
747 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
748 }
749 curImgInitFilesHash = m["sketch_context"]
750 }
751
752 candidates, err := findRepoDockerfiles(cwd, gitRoot)
753 if err != nil {
754 return "", fmt.Errorf("find dockerfile: %w", err)
755 }
756
757 var initFiles map[string]string
758 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700759 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700760
761 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
762 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
763 dockerfilePath = candidates[0]
764 contents, err := os.ReadFile(dockerfilePath)
765 if err != nil {
766 return "", err
767 }
768 fmt.Printf("using %s as dev env\n", candidates[0])
769 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700770 return imgName, nil
771 }
772 } else {
773 initFiles, err = readInitFiles(os.DirFS(gitRoot))
774 if err != nil {
775 return "", err
776 }
777 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
778 if err != nil {
779 return "", err
780 }
781 initFileHash := hashInitFiles(initFiles)
782 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700783 return imgName, nil
784 }
785
David Crawshaw5a7b3692025-05-05 16:49:15 -0700786 if model == "gemini" {
787 if strings.HasSuffix(modelURL, "/gemmsgs") {
788 // Horrible hack! Switch back to anthropic for container building.
David Crawshaw3659d872025-05-05 17:52:23 -0700789 // We can do this because we are talking to skaband and know the address.
David Crawshaw5a7b3692025-05-05 16:49:15 -0700790 modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1)
791 } else {
792 return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini")
793 }
794 }
795
Earl Lee2e463fb2025-04-17 11:22:22 -0700796 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700797 srv := &ant.Service{
David Crawshaw5a7b3692025-05-05 16:49:15 -0700798 URL: modelURL,
799 APIKey: modelAPIKey,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700800 HTTPC: http.DefaultClient,
801 }
Pokey Rulec31e2962025-05-13 10:53:33 +0000802 generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700803 if err != nil {
804 return "", fmt.Errorf("create dockerfile: %w", err)
805 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000806 // Create a unique temporary directory for the Dockerfile
807 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
808 if err != nil {
809 return "", fmt.Errorf("failed to create temporary directory: %w", err)
810 }
811 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700812 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700813 return "", err
814 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000815 // Remove the temporary directory and all contents when done
816 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700817
David Crawshawb5f6a002025-05-05 08:27:16 -0700818 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700819 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 -0700820 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700821 }
822
823 var gitUserEmail, gitUserName string
824 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
825 return "", fmt.Errorf("git config: %s: %v", out, err)
826 } else {
827 gitUserEmail = strings.TrimSpace(string(out))
828 }
829 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
830 return "", fmt.Errorf("git config: %s: %v", out, err)
831 } else {
832 gitUserName = strings.TrimSpace(string(out))
833 }
834
835 start := time.Now()
836 cmd := exec.CommandContext(ctx,
837 "docker", "build",
838 "-t", imgName,
839 "-f", dockerfilePath,
840 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
841 "--build-arg", "GIT_USER_NAME="+gitUserName,
David Crawshaw31f15242025-05-06 16:03:49 -0700842 ".",
Earl Lee2e463fb2025-04-17 11:22:22 -0700843 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700844 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700845 // We print the docker build output whether or not the user
846 // has selected --verbose. Building an image takes a while
847 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700848 cmd.Stdout = os.Stdout
849 cmd.Stderr = os.Stderr
850 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700851
852 err = run(ctx, "docker build", cmd)
853 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700854 var msg string
855 if generatedDockerfile != "" {
856 if !verbose {
857 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
858 }
859 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
860 }
861 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700862 }
863 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
864 return imgName, nil
865}
866
867func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
868 files, err := findDirDockerfiles(cwd)
869 if err != nil {
870 return nil, err
871 }
872 if len(files) > 0 {
873 return files, nil
874 }
875
876 path := cwd
877 for path != gitRoot {
878 path = filepath.Dir(path)
879 files, err := findDirDockerfiles(path)
880 if err != nil {
881 return nil, err
882 }
883 if len(files) > 0 {
884 return files, nil
885 }
886 }
887 return files, nil
888}
889
890// findDirDockerfiles finds all "Dockerfile*" files in a directory.
891func findDirDockerfiles(root string) (res []string, err error) {
892 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
893 if err != nil {
894 return err
895 }
896 if info.IsDir() && root != path {
897 return filepath.SkipDir
898 }
899 name := strings.ToLower(info.Name())
900 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
901 res = append(res, path)
902 }
903 return nil
904 })
905 if err != nil {
906 return nil, err
907 }
908 return res, nil
909}
910
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700911func checkForEmptyGitRepo(ctx context.Context, path string) error {
912 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
913 cmd.Dir = path
914 _, err := cmd.CombinedOutput()
915 if err != nil {
916 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
917 "git commit --allow-empty -m 'initial commit'")
918 }
919 return nil
920}
921
Earl Lee2e463fb2025-04-17 11:22:22 -0700922func findGitRoot(ctx context.Context, path string) (string, error) {
923 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
924 cmd.Dir = path
925 out, err := cmd.CombinedOutput()
926 if err != nil {
927 if strings.Contains(string(out), "not a git repository") {
928 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
929Consider one of the following options:
930 - cd to a different dir that is already part of a git repo first, or
931 - to create a new git repo from this directory (%s), run this command:
932
933 git init . && git commit --allow-empty -m "initial commit"
934
935and try running sketch again.
936`, path, path)
937 }
938 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
939 }
940 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
941 absGitDir := filepath.Join(path, gitDir)
942 return filepath.Dir(absGitDir), err
943}
944
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000945// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
946// from git config using the sketch.envfwd multi-valued key.
947func getEnvForwardingFromGitConfig(ctx context.Context) []string {
948 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
949 out := string(outb)
950 if err != nil {
951 if strings.Contains(out, "key does not exist") {
952 return nil
953 }
954 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
955 return nil
956 }
957
958 var envVars []string
959 for envVar := range strings.Lines(out) {
960 envVar = strings.TrimSpace(envVar)
961 if envVar == "" {
962 continue
963 }
964 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
965 }
966 return envVars
967}
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000968
969// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
970// It handles quoted arguments and escaped characters.
971//
972// Examples:
973//
974// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
975// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
976// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
977func parseDockerArgs(args string) []string {
978 if args = strings.TrimSpace(args); args == "" {
979 return []string{}
980 }
981
982 var result []string
983 var current strings.Builder
984 inQuotes := false
985 escapeNext := false
986 quoteChar := rune(0)
987
988 for _, char := range args {
989 if escapeNext {
990 current.WriteRune(char)
991 escapeNext = false
992 continue
993 }
994
995 if char == '\\' {
996 escapeNext = true
997 continue
998 }
999
1000 if char == '"' || char == '\'' {
1001 if !inQuotes {
1002 inQuotes = true
1003 quoteChar = char
1004 continue
1005 } else if char == quoteChar {
1006 inQuotes = false
1007 quoteChar = rune(0)
1008 continue
1009 }
1010 // Non-matching quote character inside quotes
1011 current.WriteRune(char)
1012 continue
1013 }
1014
1015 // Space outside of quotes is an argument separator
1016 if char == ' ' && !inQuotes {
1017 if current.Len() > 0 {
1018 result = append(result, current.String())
1019 current.Reset()
1020 }
1021 continue
1022 }
1023
1024 current.WriteRune(char)
1025 }
1026
1027 // Add the last argument if there is one
1028 if current.Len() > 0 {
1029 result = append(result, current.String())
1030 }
1031
1032 return result
1033}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001034
1035// buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled.
1036// This avoids cross-compilation issues with CGO which is required for the race detector.
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001037// Mounts host Go module cache and build cache for faster subsequent builds.
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001038func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) {
1039 // Find the git repo root
1040 currentDir, err := os.Getwd()
1041 if err != nil {
1042 return "", fmt.Errorf("could not get current directory: %w", err)
1043 }
1044
1045 gitRoot, err := findGitRoot(ctx, currentDir)
1046 if err != nil {
1047 return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err)
1048 }
1049
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001050 // Get host Go cache directories to mount for faster builds
1051 goCacheDir, err := getHostGoCacheDir(ctx)
1052 if err != nil {
1053 return "", fmt.Errorf("failed to get host GOCACHE: %w", err)
1054 }
1055 goModCacheDir, err := getHostGoModCacheDir(ctx)
1056 if err != nil {
1057 return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err)
1058 }
1059
1060 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 -07001061
1062 // Use the published Docker image tag
1063 imageTag := dockerfileBaseHash()
1064 imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag)
1065
1066 // Create destination directory for the binary
1067 destPath := filepath.Join(linuxGopath, "bin")
1068 if err := os.MkdirAll(destPath, 0o777); err != nil {
1069 return "", fmt.Errorf("failed to create destination directory: %w", err)
1070 }
1071 destFile := filepath.Join(destPath, "sketch")
1072
1073 // Create a unique container name
1074 containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano())
1075
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001076 // Run a container with the repo mounted and Go caches for faster builds
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001077 start := time.Now()
1078 slog.DebugContext(ctx, "running Docker container to build sketch with race detector")
1079
1080 // Use explicit output path for clarity
1081 runArgs := []string{
1082 "run",
1083 "--name", containerID,
1084 "-v", gitRoot + ":/app",
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001085 "-v", goCacheDir + ":/root/.cache/go-build",
1086 "-v", goModCacheDir + ":/go/pkg/mod",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001087 "-w", "/app",
1088 imgName,
Josh Bleecher Snyderf4f929a2025-05-23 17:19:26 +00001089 "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 -07001090 }
1091
1092 out, err := combinedOutput(ctx, "docker", runArgs...)
1093 if err != nil {
1094 // Print the output to help with debugging
1095 slog.ErrorContext(ctx, "docker run for race build failed",
1096 slog.String("output", string(out)),
1097 slog.String("error", err.Error()))
1098 return "", fmt.Errorf("docker run failed: %s: %w", out, err)
1099 }
1100
1101 slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start))
1102
1103 // Copy the binary from the container using the explicit path
1104 out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile)
1105 if err != nil {
1106 return "", fmt.Errorf("docker cp failed: %s: %w", out, err)
1107 }
1108
1109 // Clean up the container
1110 if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil {
1111 slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out))
1112 }
1113
1114 // Make the binary executable
1115 if err := os.Chmod(destFile, 0o755); err != nil {
1116 return "", fmt.Errorf("failed to make binary executable: %w", err)
1117 }
1118
1119 return destFile, nil
1120}
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001121
1122// getHostGoCacheDir returns the host's GOCACHE directory
1123func getHostGoCacheDir(ctx context.Context) (string, error) {
1124 out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput()
1125 if err != nil {
1126 return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err)
1127 }
1128 return strings.TrimSpace(string(out)), nil
1129}
1130
1131// getHostGoModCacheDir returns the host's GOMODCACHE directory
1132func getHostGoModCacheDir(ctx context.Context) (string, error) {
1133 out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput()
1134 if err != nil {
1135 return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err)
1136 }
1137 return strings.TrimSpace(string(out)), nil
1138}