blob: 8d656d87da428a4c48ae326da9c1323178f1d948 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package dockerimg
2package dockerimg
3
4import (
5 "bytes"
6 "context"
Philip Zeyliger5e227dd2025-04-21 15:55:29 -07007 "crypto/rand"
Earl Lee2e463fb2025-04-17 11:22:22 -07008 "crypto/sha256"
9 "encoding/hex"
10 "encoding/json"
11 "fmt"
12 "io"
13 "log/slog"
14 "net"
15 "net/http"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "runtime"
20 "strings"
Josh Bleecher Snyder99570462025-05-05 10:26:14 -070021 "sync/atomic"
Earl Lee2e463fb2025-04-17 11:22:22 -070022 "time"
23
Sean McCullough7013e9e2025-05-14 02:03:58 +000024 "golang.org/x/crypto/ssh"
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000025 "sketch.dev/browser"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070026 "sketch.dev/llm/ant"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070027 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070028 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070029 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070030)
31
32// ContainerConfig holds all configuration for launching a container
33type ContainerConfig struct {
34 // SessionID is the unique identifier for this session
35 SessionID string
36
37 // LocalAddr is the initial address to use (though it may be overwritten later)
38 LocalAddr string
39
40 // SkabandAddr is the address of the skaband service if available
41 SkabandAddr string
42
David Crawshaw5a7b3692025-05-05 16:49:15 -070043 // Model is the name of the LLM model to use.
44 Model string
Earl Lee2e463fb2025-04-17 11:22:22 -070045
David Crawshaw5a7b3692025-05-05 16:49:15 -070046 // ModelURL is the URL of the LLM service.
47 ModelURL string
48
49 // ModelAPIKey is the API key for LLM service.
50 ModelAPIKey string
Earl Lee2e463fb2025-04-17 11:22:22 -070051
52 // Path is the local filesystem path to use
53 Path string
54
55 // GitUsername is the username to use for git operations
56 GitUsername string
57
58 // GitEmail is the email to use for git operations
59 GitEmail string
60
61 // OpenBrowser determines whether to open a browser automatically
62 OpenBrowser bool
63
64 // NoCleanup prevents container cleanup when set to true
65 NoCleanup bool
66
67 // ForceRebuild forces rebuilding of the Docker image even if it exists
68 ForceRebuild bool
69
70 // Host directory to copy container logs into, if not set to ""
71 ContainerLogDest string
72
73 // Path to pre-built linux sketch binary, or build a new one if set to ""
74 SketchBinaryLinux string
75
76 // Sketch client public key.
77 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000078
Sean McCulloughbaa2b592025-04-23 10:40:08 -070079 // Host port for the container's ssh server
80 SSHPort int
81
Philip Zeyliger18532b22025-04-23 21:11:46 +000082 // Outside information to pass to the container
83 OutsideHostname string
84 OutsideOS string
85 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070086
Pokey Rule0dcebe12025-04-28 14:51:04 +010087 // If true, exit after the first turn
88 OneShot bool
89
90 // Initial prompt
91 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000092
David Crawshawb5f6a002025-05-05 08:27:16 -070093 // Verbose enables verbose output
94 Verbose bool
Philip Zeyliger1dc21372025-05-05 19:54:44 +000095
96 // DockerArgs are additional arguments to pass to the docker create command
97 DockerArgs string
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +000098
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +000099 // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container
100 Mounts []string
101
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000102 // ExperimentFlag contains the experimental features to enable
103 ExperimentFlag string
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700104
105 // TermUI enables terminal UI
106 TermUI bool
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700107
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000108 // Budget configuration
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000109 MaxDollars float64
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000110
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700111 GitRemoteUrl string
112
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000113 // Upstream branch for git work
114 Upstream string
115
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700116 // Commit hash to checkout from GetRemoteUrl
117 Commit string
118
119 // Outtie's HTTP server
120 OutsideHTTP string
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000121
122 // Prefix for git branches created by sketch
123 BranchPrefix string
Earl Lee2e463fb2025-04-17 11:22:22 -0700124}
125
126// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
127// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700128func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700129 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700130 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700131 if runtime.GOOS == "darwin" {
132 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
133 } else {
134 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
135 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700136 }
137
138 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
139 // `docker ps` provides a good error message here that can be
140 // easily chatgpt'ed by users, so send it to the user as-is:
141 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
142 return fmt.Errorf("docker ps: %s (%w)", out, err)
143 }
144
145 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
146 if err != nil {
147 return err
148 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700149 gitRoot, err := findGitRoot(ctx, config.Path)
150 if err != nil {
151 return err
152 }
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700153 err = checkForEmptyGitRepo(ctx, config.Path)
154 if err != nil {
155 return err
156 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700157
David Crawshaw5a7b3692025-05-05 16:49:15 -0700158 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700159 if err != nil {
160 return err
161 }
162
163 linuxSketchBin := config.SketchBinaryLinux
164 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700165 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700166 if err != nil {
167 return err
168 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700169 }
170
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000171 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700172 defer func() {
173 if config.NoCleanup {
174 return
175 }
176 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
177 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
178 _ = out
179 }
180 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
181 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
182 _ = out
183 }
184 }()
185
186 // errCh receives errors from operations that this function calls in separate goroutines.
187 errCh := make(chan error)
188
189 // Start the git server
190 gitSrv, err := newGitServer(gitRoot)
191 if err != nil {
192 return fmt.Errorf("failed to start git server: %w", err)
193 }
194 defer gitSrv.shutdown(ctx)
195
196 go func() {
197 errCh <- gitSrv.serve(ctx)
198 }()
199
200 // Get the current host git commit
201 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000202 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
203 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700204 } else {
205 commit = strings.TrimSpace(string(out))
206 }
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000207
208 var upstream string
209 if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil {
210 slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err)
211 } else {
212 upstream = strings.TrimSpace(string(out))
213 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700214 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
215 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
216 }
217
218 relPath, err := filepath.Rel(gitRoot, config.Path)
219 if err != nil {
220 return err
221 }
222
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700223 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
224 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000225 config.Upstream = upstream
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700226 config.Commit = commit
227
Earl Lee2e463fb2025-04-17 11:22:22 -0700228 // Create the sketch container
229 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000230 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700231 }
232
233 // Copy the sketch linux binary into the container
234 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
235 return fmt.Errorf("docker cp: %s, %w", out, err)
236 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700237
238 // Make sure that the webui is built so we can copy the results to the container.
239 _, err = webui.Build()
240 if err != nil {
241 return fmt.Errorf("failed to build webui: %w", err)
242 }
243
David Crawshaw8bff16a2025-04-18 01:16:49 -0700244 webuiZipPath, err := webui.ZipPath()
245 if err != nil {
246 return err
247 }
248 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
249 return fmt.Errorf("docker cp: %s, %w", out, err)
250 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700251
David Crawshaw53786ef2025-04-24 12:52:51 -0700252 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700253
254 // Start the sketch container
255 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
256 return fmt.Errorf("docker start: %s, %w", out, err)
257 }
258
259 // Copies structured logs from the container to the host.
260 copyLogs := func() {
261 if config.ContainerLogDest == "" {
262 return
263 }
264 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
265 if err != nil {
266 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
267 return
268 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700269 prefix := []byte("structured logs:")
270 for line := range bytes.Lines(out) {
271 rest, ok := bytes.CutPrefix(line, prefix)
272 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700273 continue
274 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700275 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700276 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
277 logFileName := filepath.Base(logFile)
278 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
279 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
280 if err != nil {
281 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
282 }
283 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
284 }
285 }
286
287 // NOTE: we want to see what the internal sketch binary prints
288 // regardless of the setting of the verbosity flag on the external
289 // binary, so reading "docker logs", which is the stdout/stderr of
290 // the internal binary is not conditional on the verbose flag.
291 appendInternalErr := func(err error) error {
292 if err == nil {
293 return nil
294 }
295 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000296 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700297 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
298 }
299 out = bytes.TrimSpace(out)
300 if len(out) > 0 {
301 return fmt.Errorf("docker logs: %s;\n%w", out, err)
302 }
303 return err
304 }
305
306 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700307 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700308 if err != nil {
309 return appendInternalErr(err)
310 }
311
Philip Zeyliger00442412025-05-14 11:03:23 -0700312 if config.Verbose {
313 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
314 }
315
Sean McCulloughae3480f2025-04-23 15:28:20 -0700316 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
317 if err != nil {
318 return appendInternalErr(err)
319 }
320 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
321 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700322 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700323 }
Sean McCullough4854c652025-04-24 18:37:02 -0700324
Sean McCullough7013e9e2025-05-14 02:03:58 +0000325 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700326
Sean McCullough078e85a2025-05-08 17:28:34 -0700327 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
328 if err != nil {
329 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
330 }
331
332 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700333 sshAvailable := false
334 sshErrMsg := ""
335 if sshErr != nil {
336 fmt.Println(sshErr.Error())
337 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700338 // continue - ssh config is not required for the rest of sketch to function locally.
339 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700340 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700341 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
342 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700343 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700344🖥️ ssh %s
345🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700346🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700347`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700348 sshUserIdentity = cst.userIdentity
349 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000350
351 // Get the Container CA public key for mutual auth
352 if cst.containerCAPublicKey != nil {
353 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
354 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
355 }
356
357 // Get the host certificate for mutual auth
358 hostCertificate = cst.hostCertificate
359
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700360 defer func() {
361 if err := cst.Cleanup(); err != nil {
362 appendInternalErr(err)
363 }
364 }()
365 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700366
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700367 // Tell the sketch container to Init(), which starts the SSH server
368 // and checks out the right commit.
369 // TODO: I'm trying to move as much configuration as possible into the command-line
370 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
371 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
372 // get the port Docker chose until after the process starts. The SSH config is
373 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
374 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700375 go func() {
376 // TODO: Why is this called in a goroutine? I have found that when I pull this out
377 // of the goroutine and call it inline, then the terminal UI clears itself and all
378 // the scrollback (which is not good, but also not fatal). I can't see why it does this
379 // though, since none of the calls in postContainerInitConfig obviously write to stdout
380 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700381 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700382 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
383 errCh <- appendInternalErr(err)
384 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700385
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700386 // 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 -0700387 ps1URL := "http://" + localAddr
388 if config.SkabandAddr != "" {
389 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700390 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700391 if config.OpenBrowser {
392 browser.Open(ps1URL)
393 }
394 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700395 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700396
Sean McCullough138ec242025-06-02 22:42:06 +0000397 // Start automatic port tunneling if SSH is available
398 if sshAvailable {
399 go func() {
400 containerURL := "http://" + localAddr
401 tunnelManager := NewTunnelManager(containerURL, cntrName, 10) // Allow up to 10 concurrent tunnels
402 tunnelManager.Start(ctx)
403 slog.InfoContext(ctx, "Started automatic port tunnel manager", "container", cntrName)
404 }()
405 }
406
Earl Lee2e463fb2025-04-17 11:22:22 -0700407 go func() {
408 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
409 cmd.Stdin = os.Stdin
410 cmd.Stdout = os.Stdout
411 cmd.Stderr = os.Stderr
412 errCh <- run(ctx, "docker attach", cmd)
413 }()
414
415 defer copyLogs()
416
417 for {
418 select {
419 case <-ctx.Done():
420 return ctx.Err()
421 case err := <-errCh:
422 if err != nil {
423 return appendInternalErr(fmt.Errorf("container process: %w", err))
424 }
425 return nil
426 }
427 }
428}
429
430func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
431 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700432 start := time.Now()
433
434 out, err := cmd.CombinedOutput()
435 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700436 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 -0700437 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700438 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 -0700439 }
440 return out, err
441}
442
443func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
444 start := time.Now()
445 err := cmd.Run()
446 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700447 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 -0700448 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700449 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 -0700450 }
451 return err
452}
453
454type gitServer struct {
455 gitLn net.Listener
456 gitPort string
457 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700458 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700459 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700460}
461
462func (gs *gitServer) shutdown(ctx context.Context) {
463 gs.srv.Shutdown(ctx)
464 gs.gitLn.Close()
465}
466
467// Serve a git remote from the host for the container to fetch from and push to.
468func (gs *gitServer) serve(ctx context.Context) error {
469 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
470 return gs.srv.Serve(gs.gitLn)
471}
472
473func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700474 ret := &gitServer{
475 pass: rand.Text(),
476 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700477
Earl Lee2e463fb2025-04-17 11:22:22 -0700478 gitLn, err := net.Listen("tcp4", ":0")
479 if err != nil {
480 return nil, fmt.Errorf("git listen: %w", err)
481 }
482 ret.gitLn = gitLn
483
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700484 browserC := make(chan bool, 1) // channel of browser open requests
485
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000486 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700487 for range browserC {
488 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000489 }
490 }()
491
492 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700493 ret.srv = &srv
494
495 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
496 if err != nil {
497 return nil, fmt.Errorf("git port: %w", err)
498 }
499 ret.gitPort = gitPort
500 return ret, nil
501}
502
503func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700504 cmdArgs := []string{
505 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700506 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700507 "--name", cntrName,
508 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700509 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700510 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700511 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700512 cmdArgs = append(cmdArgs, "-t")
513 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000514
515 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
516 cmdArgs = append(cmdArgs, "-e", envVar)
517 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700518 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700519 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700520 }
521 if config.SketchPubKey != "" {
522 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
523 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700524 if config.SSHPort > 0 {
525 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
526 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700527 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700528 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700529 if relPath != "." {
530 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
531 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700532 // colima does this by default, but Linux docker seems to need this set explicitly
533 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000534
535 // Add volume mounts if specified
536 for _, mount := range config.Mounts {
537 if mount != "" {
538 cmdArgs = append(cmdArgs, "-v", mount)
539 }
540 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700541 cmdArgs = append(
542 cmdArgs,
543 imgName,
544 "/bin/sketch",
545 "-unsafe",
546 "-addr=:80",
547 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000548 "-git-username="+config.GitUsername,
549 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000550 "-outside-hostname="+config.OutsideHostname,
551 "-outside-os="+config.OutsideOS,
552 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000553 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700554 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700555 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700556 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000557 "-x="+config.ExperimentFlag,
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000558 "-branch-prefix="+config.BranchPrefix,
Earl Lee2e463fb2025-04-17 11:22:22 -0700559 )
David Crawshaw5a7b3692025-05-05 16:49:15 -0700560 if config.Model != "" {
561 cmdArgs = append(cmdArgs, "-model="+config.Model)
562 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700563 if config.GitRemoteUrl != "" {
564 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
565 if config.Commit == "" {
566 panic("Commit should have been set when GitRemoteUrl was set")
567 }
568 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000569 cmdArgs = append(cmdArgs, "-upstream="+config.Upstream)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700570 }
571 if config.OutsideHTTP != "" {
572 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
573 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000574 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100575 if config.Prompt != "" {
576 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
577 }
578 if config.OneShot {
579 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700580 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000581 if config.ModelURL == "" {
582 // Forward ANTHROPIC_API_KEY for direct use.
583 // TODO: have outtie run an http proxy?
584 // TODO: select and forward the relevant API key based on the model
585 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
586 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000587
588 // Add additional docker arguments if provided
589 if config.DockerArgs != "" {
590 // Parse space-separated docker arguments with support for quotes and escaping
591 args := parseDockerArgs(config.DockerArgs)
592 // Insert arguments after "create" but before other arguments
593 for i := len(args) - 1; i >= 0; i-- {
594 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
595 }
596 }
597
Earl Lee2e463fb2025-04-17 11:22:22 -0700598 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
599 return fmt.Errorf("docker create: %s, %w", out, err)
600 }
601 return nil
602}
603
David Crawshawb5f6a002025-05-05 08:27:16 -0700604func buildLinuxSketchBin(ctx context.Context) (string, error) {
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700605 // Detect if race detector is enabled and use a different cache path
606 raceEnabled := RaceEnabled()
607 cacheSuffix := ""
608 if raceEnabled {
609 cacheSuffix = "-race"
610 }
611
612 homeDir, err := os.UserHomeDir()
613 if err != nil {
614 return "", err
615 }
616
617 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix)
618 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
619 return "", err
620 }
621
622 // When race detector is enabled, use Docker to build the Linux binary
623 if raceEnabled {
624 return buildLinuxSketchBinWithDocker(ctx, linuxGopath)
625 }
626
627 // Standard non-race build using cross-compilation
Pokey Rulea9a786b2025-05-12 10:52:34 +0100628 // Change to directory containing dockerimg.go for module detection
629 _, codeFile, _, _ := runtime.Caller(0)
630 codeDir := filepath.Dir(codeFile)
631 if currentDir, err := os.Getwd(); err != nil {
632 slog.WarnContext(ctx, "could not get current directory", "err", err)
633 } else {
634 if err := os.Chdir(codeDir); err != nil {
635 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
636 } else {
637 defer func() {
638 _ = os.Chdir(currentDir)
639 }()
640 }
641 }
642
David Crawshaw8a617cb2025-04-18 01:28:43 -0700643 verToInstall := "@latest"
644 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
645 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
646 } else {
647 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700648 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700649 verToInstall = ""
650 }
651 }
David Crawshaw69c67312025-04-17 13:42:00 -0700652
Earl Lee2e463fb2025-04-17 11:22:22 -0700653 start := time.Now()
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700654 args := []string{"install"}
655 args = append(args, "sketch.dev/cmd/sketch"+verToInstall)
656
657 cmd := exec.CommandContext(ctx, "go", args...)
David Crawshawb9eaef52025-04-17 15:23:18 -0700658 cmd.Env = append(
659 os.Environ(),
660 "GOOS=linux",
661 "CGO_ENABLED=0",
662 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700663 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700664 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700665 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700666
Earl Lee2e463fb2025-04-17 11:22:22 -0700667 out, err := cmd.CombinedOutput()
668 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700669 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 -0700670 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
671 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700672 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 -0700673 }
674
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700675 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700676 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700677 }
David Crawshawc7e77962025-05-03 13:20:18 -0700678 // If we are already on Linux, there's no extra platform name in the path
679 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700680}
681
Sean McCulloughae3480f2025-04-23 15:28:20 -0700682func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700683 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700684 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700685 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
686 } else {
687 v4, _, found := strings.Cut(string(out), "\n")
688 if !found {
689 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
690 }
691 localAddr = v4
692 if strings.HasPrefix(localAddr, "0.0.0.0") {
693 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
694 }
695 }
696 return localAddr, nil
697}
698
699// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700700func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700701 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700702
703 initMsg, err := json.Marshal(
704 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000705 HostAddr: localAddr,
706 SSHAuthorizedKeys: sshAuthorizedKeys,
707 SSHServerIdentity: sshServerIdentity,
708 SSHContainerCAKey: sshContainerCAKey,
709 SSHHostCertificate: sshHostCertificate,
710 SSHAvailable: sshAvailable,
711 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700712 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700713 if err != nil {
714 return fmt.Errorf("init msg: %w", err)
715 }
716
Earl Lee2e463fb2025-04-17 11:22:22 -0700717 // Note: this /init POST is handled in loop/server/loophttp.go:
718 initMsgByteReader := bytes.NewReader(initMsg)
719 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
720 if err != nil {
721 return err
722 }
723
724 var res *http.Response
725 for i := 0; ; i++ {
726 time.Sleep(100 * time.Millisecond)
727 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
728 initMsgByteReader.Reset(initMsg)
729 res, err = http.DefaultClient.Do(req)
730 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700731 if i < 100 {
732 if i%10 == 0 {
733 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
734 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700735 continue
736 }
737 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
738 }
739 break
740 }
741 resBytes, _ := io.ReadAll(res.Body)
742 if res.StatusCode != http.StatusOK {
743 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
744 }
745 return nil
746}
747
David Crawshaw5a7b3692025-05-05 16:49:15 -0700748func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700749 h := sha256.Sum256([]byte(gitRoot))
750 imgName = "sketch-" + hex.EncodeToString(h[:6])
751
752 var curImgInitFilesHash string
753 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
754 if strings.Contains(string(out), "No such object") {
755 // Image does not exist, continue and build it.
756 curImgInitFilesHash = ""
757 } else {
758 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
759 }
760 } else {
761 m := map[string]string{}
762 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
763 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
764 }
765 curImgInitFilesHash = m["sketch_context"]
766 }
767
768 candidates, err := findRepoDockerfiles(cwd, gitRoot)
769 if err != nil {
770 return "", fmt.Errorf("find dockerfile: %w", err)
771 }
772
773 var initFiles map[string]string
774 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700775 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700776
Jon Friesend27921f2025-06-05 13:15:56 +0000777 // Prioritize Dockerfile.sketch over Dockerfile, then fall back to generated dockerfile
778 if len(candidates) > 0 {
779 dockerfilePath = prioritizeDockerfiles(candidates)
Earl Lee2e463fb2025-04-17 11:22:22 -0700780 contents, err := os.ReadFile(dockerfilePath)
781 if err != nil {
782 return "", err
783 }
Jon Friesend27921f2025-06-05 13:15:56 +0000784 fmt.Printf("using %s as dev env\n", dockerfilePath)
Earl Lee2e463fb2025-04-17 11:22:22 -0700785 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700786 return imgName, nil
787 }
788 } else {
789 initFiles, err = readInitFiles(os.DirFS(gitRoot))
790 if err != nil {
791 return "", err
792 }
793 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
794 if err != nil {
795 return "", err
796 }
797 initFileHash := hashInitFiles(initFiles)
798 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700799 return imgName, nil
800 }
801
David Crawshaw5a7b3692025-05-05 16:49:15 -0700802 if model == "gemini" {
803 if strings.HasSuffix(modelURL, "/gemmsgs") {
804 // Horrible hack! Switch back to anthropic for container building.
David Crawshaw3659d872025-05-05 17:52:23 -0700805 // We can do this because we are talking to skaband and know the address.
David Crawshaw5a7b3692025-05-05 16:49:15 -0700806 modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1)
807 } else {
808 return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini")
809 }
810 }
811
Earl Lee2e463fb2025-04-17 11:22:22 -0700812 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700813 srv := &ant.Service{
David Crawshaw5a7b3692025-05-05 16:49:15 -0700814 URL: modelURL,
815 APIKey: modelAPIKey,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700816 HTTPC: http.DefaultClient,
817 }
Pokey Rulec31e2962025-05-13 10:53:33 +0000818 generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700819 if err != nil {
820 return "", fmt.Errorf("create dockerfile: %w", err)
821 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000822 // Create a unique temporary directory for the Dockerfile
823 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
824 if err != nil {
825 return "", fmt.Errorf("failed to create temporary directory: %w", err)
826 }
827 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700828 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700829 return "", err
830 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000831 // Remove the temporary directory and all contents when done
832 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700833
David Crawshawb5f6a002025-05-05 08:27:16 -0700834 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700835 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 -0700836 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700837 }
838
839 var gitUserEmail, gitUserName string
840 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
841 return "", fmt.Errorf("git config: %s: %v", out, err)
842 } else {
843 gitUserEmail = strings.TrimSpace(string(out))
844 }
845 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
846 return "", fmt.Errorf("git config: %s: %v", out, err)
847 } else {
848 gitUserName = strings.TrimSpace(string(out))
849 }
850
851 start := time.Now()
852 cmd := exec.CommandContext(ctx,
853 "docker", "build",
854 "-t", imgName,
855 "-f", dockerfilePath,
856 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
857 "--build-arg", "GIT_USER_NAME="+gitUserName,
David Crawshaw31f15242025-05-06 16:03:49 -0700858 ".",
Earl Lee2e463fb2025-04-17 11:22:22 -0700859 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700860 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700861 // We print the docker build output whether or not the user
862 // has selected --verbose. Building an image takes a while
863 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700864 cmd.Stdout = os.Stdout
865 cmd.Stderr = os.Stderr
866 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700867
868 err = run(ctx, "docker build", cmd)
869 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700870 var msg string
871 if generatedDockerfile != "" {
872 if !verbose {
873 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
874 }
875 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
876 }
877 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700878 }
879 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
880 return imgName, nil
881}
882
883func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
884 files, err := findDirDockerfiles(cwd)
885 if err != nil {
886 return nil, err
887 }
888 if len(files) > 0 {
889 return files, nil
890 }
891
892 path := cwd
893 for path != gitRoot {
894 path = filepath.Dir(path)
895 files, err := findDirDockerfiles(path)
896 if err != nil {
897 return nil, err
898 }
899 if len(files) > 0 {
900 return files, nil
901 }
902 }
903 return files, nil
904}
905
Jon Friesend27921f2025-06-05 13:15:56 +0000906// prioritizeDockerfiles returns the highest priority dockerfile from a list of candidates.
907// Priority order: Dockerfile.sketch > Dockerfile > other Dockerfile.*
908func prioritizeDockerfiles(candidates []string) string {
909 if len(candidates) == 0 {
910 return ""
911 }
912 if len(candidates) == 1 {
913 return candidates[0]
914 }
915
916 // Look for Dockerfile.sketch first (case insensitive)
917 for _, candidate := range candidates {
918 basename := strings.ToLower(filepath.Base(candidate))
919 if basename == "dockerfile.sketch" {
920 return candidate
921 }
922 }
923
924 // Look for Dockerfile second (case insensitive)
925 for _, candidate := range candidates {
926 basename := strings.ToLower(filepath.Base(candidate))
927 if basename == "dockerfile" {
928 return candidate
929 }
930 }
931
932 // Return first remaining candidate
933 return candidates[0]
934}
935
Earl Lee2e463fb2025-04-17 11:22:22 -0700936// findDirDockerfiles finds all "Dockerfile*" files in a directory.
937func findDirDockerfiles(root string) (res []string, err error) {
938 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
939 if err != nil {
940 return err
941 }
942 if info.IsDir() && root != path {
943 return filepath.SkipDir
944 }
945 name := strings.ToLower(info.Name())
Josh Bleecher Snydera9fd88f2025-06-05 10:43:22 -0700946 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") || strings.HasSuffix(name, ".dockerfile") {
Earl Lee2e463fb2025-04-17 11:22:22 -0700947 res = append(res, path)
948 }
949 return nil
950 })
951 if err != nil {
952 return nil, err
953 }
954 return res, nil
955}
956
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700957func checkForEmptyGitRepo(ctx context.Context, path string) error {
958 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
959 cmd.Dir = path
960 _, err := cmd.CombinedOutput()
961 if err != nil {
962 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
963 "git commit --allow-empty -m 'initial commit'")
964 }
965 return nil
966}
967
Earl Lee2e463fb2025-04-17 11:22:22 -0700968func findGitRoot(ctx context.Context, path string) (string, error) {
969 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
970 cmd.Dir = path
971 out, err := cmd.CombinedOutput()
972 if err != nil {
973 if strings.Contains(string(out), "not a git repository") {
974 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
975Consider one of the following options:
976 - cd to a different dir that is already part of a git repo first, or
977 - to create a new git repo from this directory (%s), run this command:
978
979 git init . && git commit --allow-empty -m "initial commit"
980
981and try running sketch again.
982`, path, path)
983 }
984 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
985 }
986 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
987 absGitDir := filepath.Join(path, gitDir)
988 return filepath.Dir(absGitDir), err
989}
990
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000991// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
992// from git config using the sketch.envfwd multi-valued key.
993func getEnvForwardingFromGitConfig(ctx context.Context) []string {
994 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
995 out := string(outb)
996 if err != nil {
997 if strings.Contains(out, "key does not exist") {
998 return nil
999 }
1000 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
1001 return nil
1002 }
1003
1004 var envVars []string
1005 for envVar := range strings.Lines(out) {
1006 envVar = strings.TrimSpace(envVar)
1007 if envVar == "" {
1008 continue
1009 }
1010 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
1011 }
1012 return envVars
1013}
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001014
1015// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
1016// It handles quoted arguments and escaped characters.
1017//
1018// Examples:
1019//
1020// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
1021// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
1022// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
1023func parseDockerArgs(args string) []string {
1024 if args = strings.TrimSpace(args); args == "" {
1025 return []string{}
1026 }
1027
1028 var result []string
1029 var current strings.Builder
1030 inQuotes := false
1031 escapeNext := false
1032 quoteChar := rune(0)
1033
1034 for _, char := range args {
1035 if escapeNext {
1036 current.WriteRune(char)
1037 escapeNext = false
1038 continue
1039 }
1040
1041 if char == '\\' {
1042 escapeNext = true
1043 continue
1044 }
1045
1046 if char == '"' || char == '\'' {
1047 if !inQuotes {
1048 inQuotes = true
1049 quoteChar = char
1050 continue
1051 } else if char == quoteChar {
1052 inQuotes = false
1053 quoteChar = rune(0)
1054 continue
1055 }
1056 // Non-matching quote character inside quotes
1057 current.WriteRune(char)
1058 continue
1059 }
1060
1061 // Space outside of quotes is an argument separator
1062 if char == ' ' && !inQuotes {
1063 if current.Len() > 0 {
1064 result = append(result, current.String())
1065 current.Reset()
1066 }
1067 continue
1068 }
1069
1070 current.WriteRune(char)
1071 }
1072
1073 // Add the last argument if there is one
1074 if current.Len() > 0 {
1075 result = append(result, current.String())
1076 }
1077
1078 return result
1079}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001080
1081// buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled.
1082// This avoids cross-compilation issues with CGO which is required for the race detector.
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001083// Mounts host Go module cache and build cache for faster subsequent builds.
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001084func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) {
1085 // Find the git repo root
1086 currentDir, err := os.Getwd()
1087 if err != nil {
1088 return "", fmt.Errorf("could not get current directory: %w", err)
1089 }
1090
1091 gitRoot, err := findGitRoot(ctx, currentDir)
1092 if err != nil {
1093 return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err)
1094 }
1095
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001096 // Get host Go cache directories to mount for faster builds
1097 goCacheDir, err := getHostGoCacheDir(ctx)
1098 if err != nil {
1099 return "", fmt.Errorf("failed to get host GOCACHE: %w", err)
1100 }
1101 goModCacheDir, err := getHostGoModCacheDir(ctx)
1102 if err != nil {
1103 return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err)
1104 }
1105
1106 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 -07001107
1108 // Use the published Docker image tag
1109 imageTag := dockerfileBaseHash()
1110 imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag)
1111
1112 // Create destination directory for the binary
1113 destPath := filepath.Join(linuxGopath, "bin")
1114 if err := os.MkdirAll(destPath, 0o777); err != nil {
1115 return "", fmt.Errorf("failed to create destination directory: %w", err)
1116 }
1117 destFile := filepath.Join(destPath, "sketch")
1118
1119 // Create a unique container name
1120 containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano())
1121
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001122 // Run a container with the repo mounted and Go caches for faster builds
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001123 start := time.Now()
1124 slog.DebugContext(ctx, "running Docker container to build sketch with race detector")
1125
1126 // Use explicit output path for clarity
1127 runArgs := []string{
1128 "run",
1129 "--name", containerID,
1130 "-v", gitRoot + ":/app",
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001131 "-v", goCacheDir + ":/root/.cache/go-build",
1132 "-v", goModCacheDir + ":/go/pkg/mod",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001133 "-w", "/app",
1134 imgName,
Josh Bleecher Snyderf4f929a2025-05-23 17:19:26 +00001135 "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 -07001136 }
1137
1138 out, err := combinedOutput(ctx, "docker", runArgs...)
1139 if err != nil {
1140 // Print the output to help with debugging
1141 slog.ErrorContext(ctx, "docker run for race build failed",
1142 slog.String("output", string(out)),
1143 slog.String("error", err.Error()))
1144 return "", fmt.Errorf("docker run failed: %s: %w", out, err)
1145 }
1146
1147 slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start))
1148
1149 // Copy the binary from the container using the explicit path
1150 out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile)
1151 if err != nil {
1152 return "", fmt.Errorf("docker cp failed: %s: %w", out, err)
1153 }
1154
1155 // Clean up the container
1156 if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil {
1157 slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out))
1158 }
1159
1160 // Make the binary executable
1161 if err := os.Chmod(destFile, 0o755); err != nil {
1162 return "", fmt.Errorf("failed to make binary executable: %w", err)
1163 }
1164
1165 return destFile, nil
1166}
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001167
1168// getHostGoCacheDir returns the host's GOCACHE directory
1169func getHostGoCacheDir(ctx context.Context) (string, error) {
1170 out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput()
1171 if err != nil {
1172 return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err)
1173 }
1174 return strings.TrimSpace(string(out)), nil
1175}
1176
1177// getHostGoModCacheDir returns the host's GOMODCACHE directory
1178func getHostGoModCacheDir(ctx context.Context) (string, error) {
1179 out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput()
1180 if err != nil {
1181 return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err)
1182 }
1183 return strings.TrimSpace(string(out)), nil
1184}