blob: e708745a14a683ca2c109aaa5195e0c4a365d6aa [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
philip.zeyliger6d3de482025-06-10 19:38:14 -0700124
125 // LinkToGitHub enables GitHub branch linking in UI
126 LinkToGitHub bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700127}
128
129// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
130// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700131func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700132 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700133 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700134 if runtime.GOOS == "darwin" {
135 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
136 } else {
137 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
138 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700139 }
140
141 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
142 // `docker ps` provides a good error message here that can be
143 // easily chatgpt'ed by users, so send it to the user as-is:
144 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
145 return fmt.Errorf("docker ps: %s (%w)", out, err)
146 }
147
148 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
149 if err != nil {
150 return err
151 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700152 gitRoot, err := findGitRoot(ctx, config.Path)
153 if err != nil {
154 return err
155 }
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700156 err = checkForEmptyGitRepo(ctx, config.Path)
157 if err != nil {
158 return err
159 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700160
David Crawshaw5a7b3692025-05-05 16:49:15 -0700161 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700162 if err != nil {
163 return err
164 }
165
166 linuxSketchBin := config.SketchBinaryLinux
167 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700168 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700169 if err != nil {
170 return err
171 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700172 }
173
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000174 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700175 defer func() {
176 if config.NoCleanup {
177 return
178 }
179 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
180 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
181 _ = out
182 }
183 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
184 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
185 _ = out
186 }
187 }()
188
189 // errCh receives errors from operations that this function calls in separate goroutines.
190 errCh := make(chan error)
191
192 // Start the git server
193 gitSrv, err := newGitServer(gitRoot)
194 if err != nil {
195 return fmt.Errorf("failed to start git server: %w", err)
196 }
197 defer gitSrv.shutdown(ctx)
198
199 go func() {
200 errCh <- gitSrv.serve(ctx)
201 }()
202
203 // Get the current host git commit
204 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000205 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
206 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700207 } else {
208 commit = strings.TrimSpace(string(out))
209 }
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000210
211 var upstream string
212 if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil {
213 slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err)
214 } else {
215 upstream = strings.TrimSpace(string(out))
216 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700217 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
218 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
219 }
220
221 relPath, err := filepath.Rel(gitRoot, config.Path)
222 if err != nil {
223 return err
224 }
225
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700226 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
227 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000228 config.Upstream = upstream
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700229 config.Commit = commit
230
Earl Lee2e463fb2025-04-17 11:22:22 -0700231 // Create the sketch container
232 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000233 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700234 }
235
236 // Copy the sketch linux binary into the container
237 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
238 return fmt.Errorf("docker cp: %s, %w", out, err)
239 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700240
241 // Make sure that the webui is built so we can copy the results to the container.
242 _, err = webui.Build()
243 if err != nil {
244 return fmt.Errorf("failed to build webui: %w", err)
245 }
246
David Crawshaw8bff16a2025-04-18 01:16:49 -0700247 webuiZipPath, err := webui.ZipPath()
248 if err != nil {
249 return err
250 }
251 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
252 return fmt.Errorf("docker cp: %s, %w", out, err)
253 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700254
David Crawshaw53786ef2025-04-24 12:52:51 -0700255 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700256
257 // Start the sketch container
258 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
259 return fmt.Errorf("docker start: %s, %w", out, err)
260 }
261
262 // Copies structured logs from the container to the host.
263 copyLogs := func() {
264 if config.ContainerLogDest == "" {
265 return
266 }
267 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
268 if err != nil {
269 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
270 return
271 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700272 prefix := []byte("structured logs:")
273 for line := range bytes.Lines(out) {
274 rest, ok := bytes.CutPrefix(line, prefix)
275 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700276 continue
277 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700278 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700279 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
280 logFileName := filepath.Base(logFile)
281 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
282 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
283 if err != nil {
284 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
285 }
286 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
287 }
288 }
289
290 // NOTE: we want to see what the internal sketch binary prints
291 // regardless of the setting of the verbosity flag on the external
292 // binary, so reading "docker logs", which is the stdout/stderr of
293 // the internal binary is not conditional on the verbose flag.
294 appendInternalErr := func(err error) error {
295 if err == nil {
296 return nil
297 }
298 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000299 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700300 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
301 }
302 out = bytes.TrimSpace(out)
303 if len(out) > 0 {
304 return fmt.Errorf("docker logs: %s;\n%w", out, err)
305 }
306 return err
307 }
308
309 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700310 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700311 if err != nil {
312 return appendInternalErr(err)
313 }
314
Philip Zeyliger00442412025-05-14 11:03:23 -0700315 if config.Verbose {
316 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
317 }
318
Sean McCulloughae3480f2025-04-23 15:28:20 -0700319 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
320 if err != nil {
321 return appendInternalErr(err)
322 }
323 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
324 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700325 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700326 }
Sean McCullough4854c652025-04-24 18:37:02 -0700327
Sean McCullough7013e9e2025-05-14 02:03:58 +0000328 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700329
Sean McCullough078e85a2025-05-08 17:28:34 -0700330 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
331 if err != nil {
332 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
333 }
334
335 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700336 sshAvailable := false
337 sshErrMsg := ""
338 if sshErr != nil {
339 fmt.Println(sshErr.Error())
340 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700341 // continue - ssh config is not required for the rest of sketch to function locally.
342 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700343 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700344 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
345 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700346 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700347🖥️ ssh %s
348🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700349🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700350`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700351 sshUserIdentity = cst.userIdentity
352 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000353
354 // Get the Container CA public key for mutual auth
355 if cst.containerCAPublicKey != nil {
356 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
357 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
358 }
359
360 // Get the host certificate for mutual auth
361 hostCertificate = cst.hostCertificate
362
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700363 defer func() {
364 if err := cst.Cleanup(); err != nil {
365 appendInternalErr(err)
366 }
367 }()
368 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700369
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700370 // Tell the sketch container to Init(), which starts the SSH server
371 // and checks out the right commit.
372 // TODO: I'm trying to move as much configuration as possible into the command-line
373 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
374 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
375 // get the port Docker chose until after the process starts. The SSH config is
376 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
377 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700378 go func() {
379 // TODO: Why is this called in a goroutine? I have found that when I pull this out
380 // of the goroutine and call it inline, then the terminal UI clears itself and all
381 // the scrollback (which is not good, but also not fatal). I can't see why it does this
382 // though, since none of the calls in postContainerInitConfig obviously write to stdout
383 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700384 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700385 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
386 errCh <- appendInternalErr(err)
387 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700388
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700389 // 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 -0700390 ps1URL := "http://" + localAddr
391 if config.SkabandAddr != "" {
392 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700393 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700394 if config.OpenBrowser {
395 browser.Open(ps1URL)
396 }
397 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700398 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700399
Sean McCullough138ec242025-06-02 22:42:06 +0000400 // Start automatic port tunneling if SSH is available
401 if sshAvailable {
402 go func() {
403 containerURL := "http://" + localAddr
404 tunnelManager := NewTunnelManager(containerURL, cntrName, 10) // Allow up to 10 concurrent tunnels
405 tunnelManager.Start(ctx)
406 slog.InfoContext(ctx, "Started automatic port tunnel manager", "container", cntrName)
407 }()
408 }
409
Earl Lee2e463fb2025-04-17 11:22:22 -0700410 go func() {
411 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
412 cmd.Stdin = os.Stdin
413 cmd.Stdout = os.Stdout
414 cmd.Stderr = os.Stderr
415 errCh <- run(ctx, "docker attach", cmd)
416 }()
417
418 defer copyLogs()
419
420 for {
421 select {
422 case <-ctx.Done():
423 return ctx.Err()
424 case err := <-errCh:
425 if err != nil {
426 return appendInternalErr(fmt.Errorf("container process: %w", err))
427 }
428 return nil
429 }
430 }
431}
432
433func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
434 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700435 start := time.Now()
436
437 out, err := cmd.CombinedOutput()
438 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700439 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 -0700440 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700441 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 -0700442 }
443 return out, err
444}
445
446func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
447 start := time.Now()
448 err := cmd.Run()
449 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700450 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 -0700451 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700452 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 -0700453 }
454 return err
455}
456
457type gitServer struct {
458 gitLn net.Listener
459 gitPort string
460 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700461 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700462 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700463}
464
465func (gs *gitServer) shutdown(ctx context.Context) {
466 gs.srv.Shutdown(ctx)
467 gs.gitLn.Close()
468}
469
470// Serve a git remote from the host for the container to fetch from and push to.
471func (gs *gitServer) serve(ctx context.Context) error {
472 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
473 return gs.srv.Serve(gs.gitLn)
474}
475
476func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700477 ret := &gitServer{
478 pass: rand.Text(),
479 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700480
Earl Lee2e463fb2025-04-17 11:22:22 -0700481 gitLn, err := net.Listen("tcp4", ":0")
482 if err != nil {
483 return nil, fmt.Errorf("git listen: %w", err)
484 }
485 ret.gitLn = gitLn
486
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700487 browserC := make(chan bool, 1) // channel of browser open requests
488
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000489 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700490 for range browserC {
491 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000492 }
493 }()
494
495 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700496 ret.srv = &srv
497
498 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
499 if err != nil {
500 return nil, fmt.Errorf("git port: %w", err)
501 }
502 ret.gitPort = gitPort
503 return ret, nil
504}
505
506func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700507 cmdArgs := []string{
508 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700509 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700510 "--name", cntrName,
511 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700512 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700513 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700514 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700515 cmdArgs = append(cmdArgs, "-t")
516 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000517
518 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
519 cmdArgs = append(cmdArgs, "-e", envVar)
520 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700521 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700522 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700523 }
524 if config.SketchPubKey != "" {
525 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
526 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700527 if config.SSHPort > 0 {
528 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
529 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700530 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700531 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700532 if relPath != "." {
533 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
534 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700535 // colima does this by default, but Linux docker seems to need this set explicitly
536 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000537
David Crawshaw1bd636c2025-06-13 19:56:27 +0000538 // Add seccomp profile to prevent killing PID 1 (the sketch process itself)
539 // Write the seccomp profile to cache directory if it doesn't exist
540 seccompPath, err := ensureSeccompProfile(ctx)
541 if err != nil {
542 return fmt.Errorf("failed to create seccomp profile: %w", err)
543 }
544 cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath)
545
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000546 // Add volume mounts if specified
547 for _, mount := range config.Mounts {
548 if mount != "" {
549 cmdArgs = append(cmdArgs, "-v", mount)
550 }
551 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700552 cmdArgs = append(
553 cmdArgs,
554 imgName,
555 "/bin/sketch",
556 "-unsafe",
557 "-addr=:80",
558 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000559 "-git-username="+config.GitUsername,
560 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000561 "-outside-hostname="+config.OutsideHostname,
562 "-outside-os="+config.OutsideOS,
563 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000564 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700565 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700566 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700567 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000568 "-x="+config.ExperimentFlag,
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000569 "-branch-prefix="+config.BranchPrefix,
philip.zeyliger6d3de482025-06-10 19:38:14 -0700570 "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub),
Earl Lee2e463fb2025-04-17 11:22:22 -0700571 )
philip.zeyliger8773e682025-06-11 21:36:21 -0700572 // Set SSH connection string based on session ID for SSH Theater
573 cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID)
David Crawshaw5a7b3692025-05-05 16:49:15 -0700574 if config.Model != "" {
575 cmdArgs = append(cmdArgs, "-model="+config.Model)
576 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700577 if config.GitRemoteUrl != "" {
578 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
579 if config.Commit == "" {
580 panic("Commit should have been set when GitRemoteUrl was set")
581 }
582 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000583 cmdArgs = append(cmdArgs, "-upstream="+config.Upstream)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700584 }
585 if config.OutsideHTTP != "" {
586 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
587 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000588 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100589 if config.Prompt != "" {
590 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
591 }
592 if config.OneShot {
593 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700594 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000595 if config.ModelURL == "" {
596 // Forward ANTHROPIC_API_KEY for direct use.
597 // TODO: have outtie run an http proxy?
598 // TODO: select and forward the relevant API key based on the model
599 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
600 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000601
602 // Add additional docker arguments if provided
603 if config.DockerArgs != "" {
604 // Parse space-separated docker arguments with support for quotes and escaping
605 args := parseDockerArgs(config.DockerArgs)
606 // Insert arguments after "create" but before other arguments
607 for i := len(args) - 1; i >= 0; i-- {
608 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
609 }
610 }
611
Earl Lee2e463fb2025-04-17 11:22:22 -0700612 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
613 return fmt.Errorf("docker create: %s, %w", out, err)
614 }
615 return nil
616}
617
David Crawshawb5f6a002025-05-05 08:27:16 -0700618func buildLinuxSketchBin(ctx context.Context) (string, error) {
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700619 // Detect if race detector is enabled and use a different cache path
620 raceEnabled := RaceEnabled()
621 cacheSuffix := ""
622 if raceEnabled {
623 cacheSuffix = "-race"
624 }
625
626 homeDir, err := os.UserHomeDir()
627 if err != nil {
628 return "", err
629 }
630
631 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix)
632 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
633 return "", err
634 }
635
636 // When race detector is enabled, use Docker to build the Linux binary
637 if raceEnabled {
638 return buildLinuxSketchBinWithDocker(ctx, linuxGopath)
639 }
640
641 // Standard non-race build using cross-compilation
Pokey Rulea9a786b2025-05-12 10:52:34 +0100642 // Change to directory containing dockerimg.go for module detection
643 _, codeFile, _, _ := runtime.Caller(0)
644 codeDir := filepath.Dir(codeFile)
645 if currentDir, err := os.Getwd(); err != nil {
646 slog.WarnContext(ctx, "could not get current directory", "err", err)
647 } else {
648 if err := os.Chdir(codeDir); err != nil {
649 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
650 } else {
651 defer func() {
652 _ = os.Chdir(currentDir)
653 }()
654 }
655 }
656
David Crawshaw8a617cb2025-04-18 01:28:43 -0700657 verToInstall := "@latest"
658 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
659 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
660 } else {
661 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700662 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700663 verToInstall = ""
664 }
665 }
David Crawshaw69c67312025-04-17 13:42:00 -0700666
Earl Lee2e463fb2025-04-17 11:22:22 -0700667 start := time.Now()
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700668 args := []string{"install"}
669 args = append(args, "sketch.dev/cmd/sketch"+verToInstall)
670
671 cmd := exec.CommandContext(ctx, "go", args...)
David Crawshawb9eaef52025-04-17 15:23:18 -0700672 cmd.Env = append(
673 os.Environ(),
674 "GOOS=linux",
675 "CGO_ENABLED=0",
676 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700677 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700678 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700679 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700680
Earl Lee2e463fb2025-04-17 11:22:22 -0700681 out, err := cmd.CombinedOutput()
682 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700683 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 -0700684 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
685 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700686 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 -0700687 }
688
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700689 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700690 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700691 }
David Crawshawc7e77962025-05-03 13:20:18 -0700692 // If we are already on Linux, there's no extra platform name in the path
693 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700694}
695
Sean McCulloughae3480f2025-04-23 15:28:20 -0700696func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700697 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700698 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700699 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
700 } else {
701 v4, _, found := strings.Cut(string(out), "\n")
702 if !found {
703 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
704 }
705 localAddr = v4
706 if strings.HasPrefix(localAddr, "0.0.0.0") {
707 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
708 }
709 }
710 return localAddr, nil
711}
712
713// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700714func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700715 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700716
717 initMsg, err := json.Marshal(
718 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000719 HostAddr: localAddr,
720 SSHAuthorizedKeys: sshAuthorizedKeys,
721 SSHServerIdentity: sshServerIdentity,
722 SSHContainerCAKey: sshContainerCAKey,
723 SSHHostCertificate: sshHostCertificate,
724 SSHAvailable: sshAvailable,
725 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700726 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700727 if err != nil {
728 return fmt.Errorf("init msg: %w", err)
729 }
730
Earl Lee2e463fb2025-04-17 11:22:22 -0700731 // Note: this /init POST is handled in loop/server/loophttp.go:
732 initMsgByteReader := bytes.NewReader(initMsg)
733 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
734 if err != nil {
735 return err
736 }
737
738 var res *http.Response
739 for i := 0; ; i++ {
740 time.Sleep(100 * time.Millisecond)
741 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
742 initMsgByteReader.Reset(initMsg)
743 res, err = http.DefaultClient.Do(req)
744 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700745 if i < 100 {
746 if i%10 == 0 {
747 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
748 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700749 continue
750 }
751 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
752 }
753 break
754 }
755 resBytes, _ := io.ReadAll(res.Body)
756 if res.StatusCode != http.StatusOK {
757 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
758 }
759 return nil
760}
761
David Crawshaw5a7b3692025-05-05 16:49:15 -0700762func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700763 h := sha256.Sum256([]byte(gitRoot))
764 imgName = "sketch-" + hex.EncodeToString(h[:6])
765
766 var curImgInitFilesHash string
767 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
768 if strings.Contains(string(out), "No such object") {
769 // Image does not exist, continue and build it.
770 curImgInitFilesHash = ""
771 } else {
772 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
773 }
774 } else {
775 m := map[string]string{}
776 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
777 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
778 }
779 curImgInitFilesHash = m["sketch_context"]
780 }
781
782 candidates, err := findRepoDockerfiles(cwd, gitRoot)
783 if err != nil {
784 return "", fmt.Errorf("find dockerfile: %w", err)
785 }
786
787 var initFiles map[string]string
788 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700789 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700790
Jon Friesend27921f2025-06-05 13:15:56 +0000791 // Prioritize Dockerfile.sketch over Dockerfile, then fall back to generated dockerfile
792 if len(candidates) > 0 {
793 dockerfilePath = prioritizeDockerfiles(candidates)
Earl Lee2e463fb2025-04-17 11:22:22 -0700794 contents, err := os.ReadFile(dockerfilePath)
795 if err != nil {
796 return "", err
797 }
Jon Friesend27921f2025-06-05 13:15:56 +0000798 fmt.Printf("using %s as dev env\n", dockerfilePath)
Earl Lee2e463fb2025-04-17 11:22:22 -0700799 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700800 return imgName, nil
801 }
802 } else {
803 initFiles, err = readInitFiles(os.DirFS(gitRoot))
804 if err != nil {
805 return "", err
806 }
807 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
808 if err != nil {
809 return "", err
810 }
811 initFileHash := hashInitFiles(initFiles)
812 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700813 return imgName, nil
814 }
815
David Crawshaw5a7b3692025-05-05 16:49:15 -0700816 if model == "gemini" {
817 if strings.HasSuffix(modelURL, "/gemmsgs") {
818 // Horrible hack! Switch back to anthropic for container building.
David Crawshaw3659d872025-05-05 17:52:23 -0700819 // We can do this because we are talking to skaband and know the address.
David Crawshaw5a7b3692025-05-05 16:49:15 -0700820 modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1)
821 } else {
822 return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini")
823 }
824 }
825
Earl Lee2e463fb2025-04-17 11:22:22 -0700826 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700827 srv := &ant.Service{
David Crawshaw5a7b3692025-05-05 16:49:15 -0700828 URL: modelURL,
829 APIKey: modelAPIKey,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700830 HTTPC: http.DefaultClient,
831 }
Pokey Rulec31e2962025-05-13 10:53:33 +0000832 generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700833 if err != nil {
834 return "", fmt.Errorf("create dockerfile: %w", err)
835 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000836 // Create a unique temporary directory for the Dockerfile
837 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
838 if err != nil {
839 return "", fmt.Errorf("failed to create temporary directory: %w", err)
840 }
841 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700842 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700843 return "", err
844 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000845 // Remove the temporary directory and all contents when done
846 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700847
David Crawshawb5f6a002025-05-05 08:27:16 -0700848 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700849 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 -0700850 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700851 }
852
853 var gitUserEmail, gitUserName string
854 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
Sean McCullough8ad17ba2025-06-09 00:43:57 +0000855 return "", fmt.Errorf("git user.email is not set. Please run 'git config --global user.email \"your.email@example.com\"' to set your email address")
Earl Lee2e463fb2025-04-17 11:22:22 -0700856 } else {
857 gitUserEmail = strings.TrimSpace(string(out))
858 }
859 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
Sean McCullough8ad17ba2025-06-09 00:43:57 +0000860 return "", fmt.Errorf("git user.name is not set. Please run 'git config --global user.name \"Your Name\"' to set your name")
Earl Lee2e463fb2025-04-17 11:22:22 -0700861 } else {
862 gitUserName = strings.TrimSpace(string(out))
863 }
864
865 start := time.Now()
866 cmd := exec.CommandContext(ctx,
867 "docker", "build",
868 "-t", imgName,
869 "-f", dockerfilePath,
870 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
871 "--build-arg", "GIT_USER_NAME="+gitUserName,
David Crawshaw31f15242025-05-06 16:03:49 -0700872 ".",
Earl Lee2e463fb2025-04-17 11:22:22 -0700873 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700874 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700875 // We print the docker build output whether or not the user
876 // has selected --verbose. Building an image takes a while
877 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700878 cmd.Stdout = os.Stdout
879 cmd.Stderr = os.Stderr
880 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700881
882 err = run(ctx, "docker build", cmd)
883 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700884 var msg string
885 if generatedDockerfile != "" {
886 if !verbose {
887 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
888 }
889 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
890 }
891 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700892 }
893 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
894 return imgName, nil
895}
896
897func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
898 files, err := findDirDockerfiles(cwd)
899 if err != nil {
900 return nil, err
901 }
902 if len(files) > 0 {
903 return files, nil
904 }
905
906 path := cwd
907 for path != gitRoot {
908 path = filepath.Dir(path)
909 files, err := findDirDockerfiles(path)
910 if err != nil {
911 return nil, err
912 }
913 if len(files) > 0 {
914 return files, nil
915 }
916 }
917 return files, nil
918}
919
Jon Friesend27921f2025-06-05 13:15:56 +0000920// prioritizeDockerfiles returns the highest priority dockerfile from a list of candidates.
921// Priority order: Dockerfile.sketch > Dockerfile > other Dockerfile.*
922func prioritizeDockerfiles(candidates []string) string {
923 if len(candidates) == 0 {
924 return ""
925 }
926 if len(candidates) == 1 {
927 return candidates[0]
928 }
929
930 // Look for Dockerfile.sketch first (case insensitive)
931 for _, candidate := range candidates {
932 basename := strings.ToLower(filepath.Base(candidate))
933 if basename == "dockerfile.sketch" {
934 return candidate
935 }
936 }
937
938 // Look for Dockerfile second (case insensitive)
939 for _, candidate := range candidates {
940 basename := strings.ToLower(filepath.Base(candidate))
941 if basename == "dockerfile" {
942 return candidate
943 }
944 }
945
946 // Return first remaining candidate
947 return candidates[0]
948}
949
Earl Lee2e463fb2025-04-17 11:22:22 -0700950// findDirDockerfiles finds all "Dockerfile*" files in a directory.
951func findDirDockerfiles(root string) (res []string, err error) {
952 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
953 if err != nil {
954 return err
955 }
956 if info.IsDir() && root != path {
957 return filepath.SkipDir
958 }
959 name := strings.ToLower(info.Name())
Josh Bleecher Snydera9fd88f2025-06-05 10:43:22 -0700960 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") || strings.HasSuffix(name, ".dockerfile") {
Earl Lee2e463fb2025-04-17 11:22:22 -0700961 res = append(res, path)
962 }
963 return nil
964 })
965 if err != nil {
966 return nil, err
967 }
968 return res, nil
969}
970
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700971func checkForEmptyGitRepo(ctx context.Context, path string) error {
972 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
973 cmd.Dir = path
974 _, err := cmd.CombinedOutput()
975 if err != nil {
976 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
977 "git commit --allow-empty -m 'initial commit'")
978 }
979 return nil
980}
981
Earl Lee2e463fb2025-04-17 11:22:22 -0700982func findGitRoot(ctx context.Context, path string) (string, error) {
983 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
984 cmd.Dir = path
985 out, err := cmd.CombinedOutput()
986 if err != nil {
987 if strings.Contains(string(out), "not a git repository") {
988 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
989Consider one of the following options:
990 - cd to a different dir that is already part of a git repo first, or
991 - to create a new git repo from this directory (%s), run this command:
992
993 git init . && git commit --allow-empty -m "initial commit"
994
995and try running sketch again.
996`, path, path)
997 }
998 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
999 }
1000 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
1001 absGitDir := filepath.Join(path, gitDir)
1002 return filepath.Dir(absGitDir), err
1003}
1004
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +00001005// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
1006// from git config using the sketch.envfwd multi-valued key.
1007func getEnvForwardingFromGitConfig(ctx context.Context) []string {
1008 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
1009 out := string(outb)
1010 if err != nil {
1011 if strings.Contains(out, "key does not exist") {
1012 return nil
1013 }
1014 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
1015 return nil
1016 }
1017
1018 var envVars []string
1019 for envVar := range strings.Lines(out) {
1020 envVar = strings.TrimSpace(envVar)
1021 if envVar == "" {
1022 continue
1023 }
1024 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
1025 }
1026 return envVars
1027}
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001028
1029// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
1030// It handles quoted arguments and escaped characters.
1031//
1032// Examples:
1033//
1034// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
1035// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
1036// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
1037func parseDockerArgs(args string) []string {
1038 if args = strings.TrimSpace(args); args == "" {
1039 return []string{}
1040 }
1041
1042 var result []string
1043 var current strings.Builder
1044 inQuotes := false
1045 escapeNext := false
1046 quoteChar := rune(0)
1047
1048 for _, char := range args {
1049 if escapeNext {
1050 current.WriteRune(char)
1051 escapeNext = false
1052 continue
1053 }
1054
1055 if char == '\\' {
1056 escapeNext = true
1057 continue
1058 }
1059
1060 if char == '"' || char == '\'' {
1061 if !inQuotes {
1062 inQuotes = true
1063 quoteChar = char
1064 continue
1065 } else if char == quoteChar {
1066 inQuotes = false
1067 quoteChar = rune(0)
1068 continue
1069 }
1070 // Non-matching quote character inside quotes
1071 current.WriteRune(char)
1072 continue
1073 }
1074
1075 // Space outside of quotes is an argument separator
1076 if char == ' ' && !inQuotes {
1077 if current.Len() > 0 {
1078 result = append(result, current.String())
1079 current.Reset()
1080 }
1081 continue
1082 }
1083
1084 current.WriteRune(char)
1085 }
1086
1087 // Add the last argument if there is one
1088 if current.Len() > 0 {
1089 result = append(result, current.String())
1090 }
1091
1092 return result
1093}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001094
1095// buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled.
1096// This avoids cross-compilation issues with CGO which is required for the race detector.
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001097// Mounts host Go module cache and build cache for faster subsequent builds.
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001098func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) {
1099 // Find the git repo root
1100 currentDir, err := os.Getwd()
1101 if err != nil {
1102 return "", fmt.Errorf("could not get current directory: %w", err)
1103 }
1104
1105 gitRoot, err := findGitRoot(ctx, currentDir)
1106 if err != nil {
1107 return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err)
1108 }
1109
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001110 // Get host Go cache directories to mount for faster builds
1111 goCacheDir, err := getHostGoCacheDir(ctx)
1112 if err != nil {
1113 return "", fmt.Errorf("failed to get host GOCACHE: %w", err)
1114 }
1115 goModCacheDir, err := getHostGoModCacheDir(ctx)
1116 if err != nil {
1117 return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err)
1118 }
1119
1120 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 -07001121
1122 // Use the published Docker image tag
1123 imageTag := dockerfileBaseHash()
1124 imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag)
1125
1126 // Create destination directory for the binary
1127 destPath := filepath.Join(linuxGopath, "bin")
1128 if err := os.MkdirAll(destPath, 0o777); err != nil {
1129 return "", fmt.Errorf("failed to create destination directory: %w", err)
1130 }
1131 destFile := filepath.Join(destPath, "sketch")
1132
1133 // Create a unique container name
1134 containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano())
1135
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001136 // Run a container with the repo mounted and Go caches for faster builds
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001137 start := time.Now()
1138 slog.DebugContext(ctx, "running Docker container to build sketch with race detector")
1139
1140 // Use explicit output path for clarity
1141 runArgs := []string{
1142 "run",
1143 "--name", containerID,
1144 "-v", gitRoot + ":/app",
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001145 "-v", goCacheDir + ":/root/.cache/go-build",
1146 "-v", goModCacheDir + ":/go/pkg/mod",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001147 "-w", "/app",
1148 imgName,
Josh Bleecher Snyderf4f929a2025-05-23 17:19:26 +00001149 "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 -07001150 }
1151
1152 out, err := combinedOutput(ctx, "docker", runArgs...)
1153 if err != nil {
1154 // Print the output to help with debugging
1155 slog.ErrorContext(ctx, "docker run for race build failed",
1156 slog.String("output", string(out)),
1157 slog.String("error", err.Error()))
1158 return "", fmt.Errorf("docker run failed: %s: %w", out, err)
1159 }
1160
1161 slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start))
1162
1163 // Copy the binary from the container using the explicit path
1164 out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile)
1165 if err != nil {
1166 return "", fmt.Errorf("docker cp failed: %s: %w", out, err)
1167 }
1168
1169 // Clean up the container
1170 if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil {
1171 slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out))
1172 }
1173
1174 // Make the binary executable
1175 if err := os.Chmod(destFile, 0o755); err != nil {
1176 return "", fmt.Errorf("failed to make binary executable: %w", err)
1177 }
1178
1179 return destFile, nil
1180}
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001181
1182// getHostGoCacheDir returns the host's GOCACHE directory
1183func getHostGoCacheDir(ctx context.Context) (string, error) {
1184 out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput()
1185 if err != nil {
1186 return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err)
1187 }
1188 return strings.TrimSpace(string(out)), nil
1189}
1190
1191// getHostGoModCacheDir returns the host's GOMODCACHE directory
1192func getHostGoModCacheDir(ctx context.Context) (string, error) {
1193 out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput()
1194 if err != nil {
1195 return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err)
1196 }
1197 return strings.TrimSpace(string(out)), nil
1198}
David Crawshaw1bd636c2025-06-13 19:56:27 +00001199
1200const seccompProfile = `{
1201 "defaultAction": "SCMP_ACT_ALLOW",
1202 "syscalls": [
1203 {
1204 "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"],
1205 "action": "SCMP_ACT_ERRNO",
1206 "args": [
1207 {
1208 "index": 0,
1209 "value": 1,
1210 "op": "SCMP_CMP_EQ"
1211 }
1212 ]
1213 }
1214 ]
1215}`
1216
1217// ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist.
1218func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) {
1219 homeDir, err := os.UserHomeDir()
1220 if err != nil {
1221 return "", fmt.Errorf("failed to get home directory: %w", err)
1222 }
1223 cacheDir := filepath.Join(homeDir, ".cache", "sketch")
1224 if err := os.MkdirAll(cacheDir, 0o755); err != nil {
1225 return "", fmt.Errorf("failed to create cache directory: %w", err)
1226 }
1227 seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json")
1228
1229 curBytes, err := os.ReadFile(seccompPath)
1230 if err != nil && !os.IsNotExist(err) {
1231 return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err)
1232 }
1233 if string(curBytes) == seccompProfile {
1234 return seccompPath, nil // File already exists and matches the expected profile
1235 }
1236
1237 if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil {
1238 return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err)
1239 }
1240 slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath)
1241 return seccompPath, nil
1242}