blob: e40a77b4ce9e538a8f5d76f83817d0aaf76cf047 [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"
21 "time"
22
Sean McCulloughbaa2b592025-04-23 10:40:08 -070023 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070024 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070025 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070026)
27
28// ContainerConfig holds all configuration for launching a container
29type ContainerConfig struct {
30 // SessionID is the unique identifier for this session
31 SessionID string
32
33 // LocalAddr is the initial address to use (though it may be overwritten later)
34 LocalAddr string
35
36 // SkabandAddr is the address of the skaband service if available
37 SkabandAddr string
38
39 // AntURL is the URL of the LLM service.
40 AntURL string
41
42 // AntAPIKey is the API key for LLM service.
43 AntAPIKey string
44
45 // Path is the local filesystem path to use
46 Path string
47
48 // GitUsername is the username to use for git operations
49 GitUsername string
50
51 // GitEmail is the email to use for git operations
52 GitEmail string
53
54 // OpenBrowser determines whether to open a browser automatically
55 OpenBrowser bool
56
57 // NoCleanup prevents container cleanup when set to true
58 NoCleanup bool
59
60 // ForceRebuild forces rebuilding of the Docker image even if it exists
61 ForceRebuild bool
62
63 // Host directory to copy container logs into, if not set to ""
64 ContainerLogDest string
65
66 // Path to pre-built linux sketch binary, or build a new one if set to ""
67 SketchBinaryLinux string
68
69 // Sketch client public key.
70 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000071
Sean McCulloughbaa2b592025-04-23 10:40:08 -070072 // Host port for the container's ssh server
73 SSHPort int
74
Philip Zeyliger18532b22025-04-23 21:11:46 +000075 // Outside information to pass to the container
76 OutsideHostname string
77 OutsideOS string
78 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070079
80 // If not empty, handle this message and exit
81 OneShot string
Earl Lee2e463fb2025-04-17 11:22:22 -070082}
83
84// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
85// It writes status to stdout.
86func LaunchContainer(ctx context.Context, stdout, stderr io.Writer, config ContainerConfig) error {
87 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -070088 if runtime.GOOS == "darwin" {
89 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
90 } else {
91 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
92 }
Earl Lee2e463fb2025-04-17 11:22:22 -070093 }
94
95 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
96 // `docker ps` provides a good error message here that can be
97 // easily chatgpt'ed by users, so send it to the user as-is:
98 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
99 return fmt.Errorf("docker ps: %s (%w)", out, err)
100 }
101
102 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
103 if err != nil {
104 return err
105 }
106
107 gitRoot, err := findGitRoot(ctx, config.Path)
108 if err != nil {
109 return err
110 }
111
112 imgName, err := findOrBuildDockerImage(ctx, stdout, stderr, config.Path, gitRoot, config.AntURL, config.AntAPIKey, config.ForceRebuild)
113 if err != nil {
114 return err
115 }
116
117 linuxSketchBin := config.SketchBinaryLinux
118 if linuxSketchBin == "" {
119 linuxSketchBin, err = buildLinuxSketchBin(ctx, config.Path)
120 if err != nil {
121 return err
122 }
Josh Bleecher Snyder5544d142025-04-23 14:15:45 -0700123 defer os.Remove(linuxSketchBin) // in case of errors
Earl Lee2e463fb2025-04-17 11:22:22 -0700124 }
125
126 cntrName := imgName + "-" + config.SessionID
127 defer func() {
128 if config.NoCleanup {
129 return
130 }
131 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
132 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
133 _ = out
134 }
135 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
136 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
137 _ = out
138 }
139 }()
140
141 // errCh receives errors from operations that this function calls in separate goroutines.
142 errCh := make(chan error)
143
144 // Start the git server
145 gitSrv, err := newGitServer(gitRoot)
146 if err != nil {
147 return fmt.Errorf("failed to start git server: %w", err)
148 }
149 defer gitSrv.shutdown(ctx)
150
151 go func() {
152 errCh <- gitSrv.serve(ctx)
153 }()
154
155 // Get the current host git commit
156 var commit string
157 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
158 return fmt.Errorf("git rev-parse HEAD: %w", err)
159 } else {
160 commit = strings.TrimSpace(string(out))
161 }
162 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
163 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
164 }
165
166 relPath, err := filepath.Rel(gitRoot, config.Path)
167 if err != nil {
168 return err
169 }
170
171 // Create the sketch container
172 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
173 return err
174 }
175
176 // Copy the sketch linux binary into the container
177 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
178 return fmt.Errorf("docker cp: %s, %w", out, err)
179 }
Josh Bleecher Snyder5544d142025-04-23 14:15:45 -0700180 os.Remove(linuxSketchBin) // in normal operations, the code below blocks, so actively delete now
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700181
182 // Make sure that the webui is built so we can copy the results to the container.
183 _, err = webui.Build()
184 if err != nil {
185 return fmt.Errorf("failed to build webui: %w", err)
186 }
187
David Crawshaw8bff16a2025-04-18 01:16:49 -0700188 webuiZipPath, err := webui.ZipPath()
189 if err != nil {
190 return err
191 }
192 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
193 return fmt.Errorf("docker cp: %s, %w", out, err)
194 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700195
David Crawshaw53786ef2025-04-24 12:52:51 -0700196 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700197
198 // Start the sketch container
199 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
200 return fmt.Errorf("docker start: %s, %w", out, err)
201 }
202
203 // Copies structured logs from the container to the host.
204 copyLogs := func() {
205 if config.ContainerLogDest == "" {
206 return
207 }
208 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
209 if err != nil {
210 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
211 return
212 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700213 prefix := []byte("structured logs:")
214 for line := range bytes.Lines(out) {
215 rest, ok := bytes.CutPrefix(line, prefix)
216 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700217 continue
218 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700219 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700220 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
221 logFileName := filepath.Base(logFile)
222 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
223 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
224 if err != nil {
225 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
226 }
227 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
228 }
229 }
230
231 // NOTE: we want to see what the internal sketch binary prints
232 // regardless of the setting of the verbosity flag on the external
233 // binary, so reading "docker logs", which is the stdout/stderr of
234 // the internal binary is not conditional on the verbose flag.
235 appendInternalErr := func(err error) error {
236 if err == nil {
237 return nil
238 }
239 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000240 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700241 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
242 }
243 out = bytes.TrimSpace(out)
244 if len(out) > 0 {
245 return fmt.Errorf("docker logs: %s;\n%w", out, err)
246 }
247 return err
248 }
249
250 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700251 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700252 if err != nil {
253 return appendInternalErr(err)
254 }
255
Sean McCulloughae3480f2025-04-23 15:28:20 -0700256 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
257 if err != nil {
258 return appendInternalErr(err)
259 }
260 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
261 if err != nil {
Sean McCullough4854c652025-04-24 18:37:02 -0700262 return appendInternalErr(fmt.Errorf("Error splitting ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700263 }
Sean McCullough4854c652025-04-24 18:37:02 -0700264
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700265 var sshServerIdentity, sshUserIdentity []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700266
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700267 if err := CheckForInclude(); err != nil {
268 fmt.Println(err.Error())
269 // continue - ssh config is not required for the rest of sketch to function locally.
270 } else {
271 cst, err := NewSSHTheather(cntrName, sshHost, sshPort)
272 if err != nil {
273 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
274 }
275
276 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700277🖥️ ssh %s
278🖥️ code --remote ssh-remote+root@%s /app -n
279🔗 vscode://vscode-remote/ssh-remote+root@%s/app?n=true
280`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700281 sshUserIdentity = cst.userIdentity
282 sshServerIdentity = cst.serverIdentity
283 defer func() {
284 if err := cst.Cleanup(); err != nil {
285 appendInternalErr(err)
286 }
287 }()
288 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700289
Earl Lee2e463fb2025-04-17 11:22:22 -0700290 // Tell the sketch container which git server port and commit to initialize with.
291 go func() {
292 // TODO: Why is this called in a goroutine? I have found that when I pull this out
293 // of the goroutine and call it inline, then the terminal UI clears itself and all
294 // the scrollback (which is not good, but also not fatal). I can't see why it does this
295 // though, since none of the calls in postContainerInitConfig obviously write to stdout
296 // or stderr.
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700297 if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, sshServerIdentity, sshUserIdentity); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700298 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
299 errCh <- appendInternalErr(err)
300 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700301
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700302 // We open the browser after the init config because the above waits for the web server to be serving.
303 if config.OpenBrowser {
304 if config.SkabandAddr != "" {
305 OpenBrowser(ctx, fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID))
306 } else {
307 OpenBrowser(ctx, "http://"+localAddr)
308 }
309 }
310 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700311
312 go func() {
313 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
314 cmd.Stdin = os.Stdin
315 cmd.Stdout = os.Stdout
316 cmd.Stderr = os.Stderr
317 errCh <- run(ctx, "docker attach", cmd)
318 }()
319
320 defer copyLogs()
321
322 for {
323 select {
324 case <-ctx.Done():
325 return ctx.Err()
326 case err := <-errCh:
327 if err != nil {
328 return appendInternalErr(fmt.Errorf("container process: %w", err))
329 }
330 return nil
331 }
332 }
333}
334
335func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
336 cmd := exec.CommandContext(ctx, cmdName, args...)
337 // Really only needed for the "go build" command for the linux sketch binary
338 cmd.Env = append(os.Environ(), "GOOS=linux", "CGO_ENABLED=0")
339 start := time.Now()
340
341 out, err := cmd.CombinedOutput()
342 if err != nil {
343 slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
344 } else {
345 slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
346 }
347 return out, err
348}
349
350func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
351 start := time.Now()
352 err := cmd.Run()
353 if err != nil {
354 slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
355 } else {
356 slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
357 }
358 return err
359}
360
361type gitServer struct {
362 gitLn net.Listener
363 gitPort string
364 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700365 pass string
Earl Lee2e463fb2025-04-17 11:22:22 -0700366}
367
368func (gs *gitServer) shutdown(ctx context.Context) {
369 gs.srv.Shutdown(ctx)
370 gs.gitLn.Close()
371}
372
373// Serve a git remote from the host for the container to fetch from and push to.
374func (gs *gitServer) serve(ctx context.Context) error {
375 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
376 return gs.srv.Serve(gs.gitLn)
377}
378
379func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700380 ret := &gitServer{
381 pass: rand.Text(),
382 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700383
Earl Lee2e463fb2025-04-17 11:22:22 -0700384 gitLn, err := net.Listen("tcp4", ":0")
385 if err != nil {
386 return nil, fmt.Errorf("git listen: %w", err)
387 }
388 ret.gitLn = gitLn
389
390 srv := http.Server{
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700391 Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass)},
Earl Lee2e463fb2025-04-17 11:22:22 -0700392 }
393 ret.srv = &srv
394
395 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
396 if err != nil {
397 return nil, fmt.Errorf("git port: %w", err)
398 }
399 ret.gitPort = gitPort
400 return ret, nil
401}
402
403func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
404 //, config.SessionID, config.GitUsername, config.GitEmail, config.SkabandAddr
405 // sessionID, gitUsername, gitEmail, skabandAddr string
David Crawshaw69c67312025-04-17 13:42:00 -0700406 cmdArgs := []string{
407 "create",
Earl Lee2e463fb2025-04-17 11:22:22 -0700408 "-it",
409 "--name", cntrName,
410 "-p", hostPort + ":80", // forward container port 80 to a host port
411 "-e", "ANTHROPIC_API_KEY=" + config.AntAPIKey,
412 }
413 if config.AntURL != "" {
414 cmdArgs = append(cmdArgs, "-e", "ANT_URL="+config.AntURL)
415 }
416 if config.SketchPubKey != "" {
417 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
418 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700419 if config.SSHPort > 0 {
420 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
421 } else {
422 cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700423 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700424 if relPath != "." {
425 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
426 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700427 // colima does this by default, but Linux docker seems to need this set explicitly
428 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700429 cmdArgs = append(
430 cmdArgs,
431 imgName,
432 "/bin/sketch",
433 "-unsafe",
434 "-addr=:80",
435 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000436 "-git-username="+config.GitUsername,
437 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000438 "-outside-hostname="+config.OutsideHostname,
439 "-outside-os="+config.OutsideOS,
440 "-outside-working-dir="+config.OutsideWorkingDir,
Earl Lee2e463fb2025-04-17 11:22:22 -0700441 )
442 if config.SkabandAddr != "" {
443 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
444 }
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700445 if config.OneShot != "" {
446 cmdArgs = append(cmdArgs, "-one-shot", config.OneShot)
447 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700448 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
449 return fmt.Errorf("docker create: %s, %w", out, err)
450 }
451 return nil
452}
453
454func buildLinuxSketchBin(ctx context.Context, path string) (string, error) {
David Crawshaw8a617cb2025-04-18 01:28:43 -0700455 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700456 if err != nil {
457 return "", err
458 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700459 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
460 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
461 return "", err
462 }
463
464 verToInstall := "@latest"
465 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
466 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
467 } else {
468 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700469 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700470 verToInstall = ""
471 }
472 }
David Crawshaw69c67312025-04-17 13:42:00 -0700473
Earl Lee2e463fb2025-04-17 11:22:22 -0700474 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700475 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700476 cmd.Env = append(
477 os.Environ(),
478 "GOOS=linux",
479 "CGO_ENABLED=0",
480 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700481 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700482 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700483 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700484
Earl Lee2e463fb2025-04-17 11:22:22 -0700485 out, err := cmd.CombinedOutput()
486 if err != nil {
487 slog.ErrorContext(ctx, "go", slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
488 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
489 } else {
490 slog.DebugContext(ctx, "go", slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
491 }
492
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700493 var src string
494 if runtime.GOOS != "linux" {
495 src = filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch")
496 } else {
497 // If we are already on Linux, there's no extra platform name in the path
498 src = filepath.Join(linuxGopath, "bin", "sketch")
499 }
500
David Crawshaw69c67312025-04-17 13:42:00 -0700501 dst := filepath.Join(path, "tmp-sketch-binary-linux")
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700502 if err := moveFile(src, dst); err != nil {
David Crawshaw69c67312025-04-17 13:42:00 -0700503 return "", err
504 }
505
David Crawshaw69c67312025-04-17 13:42:00 -0700506 return dst, nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700507}
508
Sean McCulloughae3480f2025-04-23 15:28:20 -0700509func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700510 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700511 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700512 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
513 } else {
514 v4, _, found := strings.Cut(string(out), "\n")
515 if !found {
516 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
517 }
518 localAddr = v4
519 if strings.HasPrefix(localAddr, "0.0.0.0") {
520 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
521 }
522 }
523 return localAddr, nil
524}
525
526// Contact the container and configure it.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700527func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshServerIdentity, sshAuthorizedKeys []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700528 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700529
530 initMsg, err := json.Marshal(
531 server.InitRequest{
532 Commit: commit,
533 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
534 HostAddr: localAddr,
535 SSHAuthorizedKeys: sshAuthorizedKeys,
536 SSHServerIdentity: sshServerIdentity,
537 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700538 if err != nil {
539 return fmt.Errorf("init msg: %w", err)
540 }
541
Earl Lee2e463fb2025-04-17 11:22:22 -0700542 // Note: this /init POST is handled in loop/server/loophttp.go:
543 initMsgByteReader := bytes.NewReader(initMsg)
544 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
545 if err != nil {
546 return err
547 }
548
549 var res *http.Response
550 for i := 0; ; i++ {
551 time.Sleep(100 * time.Millisecond)
552 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
553 initMsgByteReader.Reset(initMsg)
554 res, err = http.DefaultClient.Do(req)
555 if err != nil {
556 // In addition to "connection refused", we also occasionally see "EOF" errors that can succeed on retries.
557 if i < 100 && (strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "EOF")) {
558 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
559 continue
560 }
561 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
562 }
563 break
564 }
565 resBytes, _ := io.ReadAll(res.Body)
566 if res.StatusCode != http.StatusOK {
567 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
568 }
569 return nil
570}
571
572func findOrBuildDockerImage(ctx context.Context, stdout, stderr io.Writer, cwd, gitRoot, antURL, antAPIKey string, forceRebuild bool) (imgName string, err error) {
573 h := sha256.Sum256([]byte(gitRoot))
574 imgName = "sketch-" + hex.EncodeToString(h[:6])
575
576 var curImgInitFilesHash string
577 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
578 if strings.Contains(string(out), "No such object") {
579 // Image does not exist, continue and build it.
580 curImgInitFilesHash = ""
581 } else {
582 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
583 }
584 } else {
585 m := map[string]string{}
586 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
587 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
588 }
589 curImgInitFilesHash = m["sketch_context"]
590 }
591
592 candidates, err := findRepoDockerfiles(cwd, gitRoot)
593 if err != nil {
594 return "", fmt.Errorf("find dockerfile: %w", err)
595 }
596
597 var initFiles map[string]string
598 var dockerfilePath string
599
600 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
601 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
602 dockerfilePath = candidates[0]
603 contents, err := os.ReadFile(dockerfilePath)
604 if err != nil {
605 return "", err
606 }
607 fmt.Printf("using %s as dev env\n", candidates[0])
608 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700609 return imgName, nil
610 }
611 } else {
612 initFiles, err = readInitFiles(os.DirFS(gitRoot))
613 if err != nil {
614 return "", err
615 }
616 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
617 if err != nil {
618 return "", err
619 }
620 initFileHash := hashInitFiles(initFiles)
621 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700622 return imgName, nil
623 }
624
625 start := time.Now()
626 dockerfile, err := createDockerfile(ctx, http.DefaultClient, antURL, antAPIKey, initFiles, subPathWorkingDir)
627 if err != nil {
628 return "", fmt.Errorf("create dockerfile: %w", err)
629 }
630 dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile")
631 if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil {
632 return "", err
633 }
634 defer os.Remove(dockerfilePath)
635
636 fmt.Fprintf(stderr, "generated Dockerfile in %s:\n\t%s\n\n", time.Since(start).Round(time.Millisecond), strings.Replace(dockerfile, "\n", "\n\t", -1))
637 }
638
639 var gitUserEmail, gitUserName string
640 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
641 return "", fmt.Errorf("git config: %s: %v", out, err)
642 } else {
643 gitUserEmail = strings.TrimSpace(string(out))
644 }
645 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
646 return "", fmt.Errorf("git config: %s: %v", out, err)
647 } else {
648 gitUserName = strings.TrimSpace(string(out))
649 }
650
651 start := time.Now()
652 cmd := exec.CommandContext(ctx,
653 "docker", "build",
654 "-t", imgName,
655 "-f", dockerfilePath,
656 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
657 "--build-arg", "GIT_USER_NAME="+gitUserName,
658 ".",
659 )
660 cmd.Dir = gitRoot
661 cmd.Stdout = stdout
662 cmd.Stderr = stderr
Josh Bleecher Snyderdf2d3dc2025-04-25 12:31:35 -0700663 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Philip Zeyligere4fa0e32025-04-23 14:15:55 -0700664 dockerfileContent, err := os.ReadFile(dockerfilePath)
665 if err != nil {
666 return "", fmt.Errorf("failed to read Dockerfile: %w", err)
667 }
Philip Zeyliger5d6af872025-04-23 19:48:34 -0700668 fmt.Fprintf(stdout, "Dockerfile:\n%s\n", string(dockerfileContent))
Earl Lee2e463fb2025-04-17 11:22:22 -0700669
670 err = run(ctx, "docker build", cmd)
671 if err != nil {
672 return "", fmt.Errorf("docker build failed: %v", err)
673 }
674 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
675 return imgName, nil
676}
677
678func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
679 files, err := findDirDockerfiles(cwd)
680 if err != nil {
681 return nil, err
682 }
683 if len(files) > 0 {
684 return files, nil
685 }
686
687 path := cwd
688 for path != gitRoot {
689 path = filepath.Dir(path)
690 files, err := findDirDockerfiles(path)
691 if err != nil {
692 return nil, err
693 }
694 if len(files) > 0 {
695 return files, nil
696 }
697 }
698 return files, nil
699}
700
701// findDirDockerfiles finds all "Dockerfile*" files in a directory.
702func findDirDockerfiles(root string) (res []string, err error) {
703 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
704 if err != nil {
705 return err
706 }
707 if info.IsDir() && root != path {
708 return filepath.SkipDir
709 }
710 name := strings.ToLower(info.Name())
711 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
712 res = append(res, path)
713 }
714 return nil
715 })
716 if err != nil {
717 return nil, err
718 }
719 return res, nil
720}
721
722func findGitRoot(ctx context.Context, path string) (string, error) {
723 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
724 cmd.Dir = path
725 out, err := cmd.CombinedOutput()
726 if err != nil {
727 if strings.Contains(string(out), "not a git repository") {
728 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
729Consider one of the following options:
730 - cd to a different dir that is already part of a git repo first, or
731 - to create a new git repo from this directory (%s), run this command:
732
733 git init . && git commit --allow-empty -m "initial commit"
734
735and try running sketch again.
736`, path, path)
737 }
738 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
739 }
740 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
741 absGitDir := filepath.Join(path, gitDir)
742 return filepath.Dir(absGitDir), err
743}
744
745func OpenBrowser(ctx context.Context, url string) {
746 var cmd *exec.Cmd
747 switch runtime.GOOS {
748 case "darwin":
749 cmd = exec.CommandContext(ctx, "open", url)
750 case "windows":
751 cmd = exec.CommandContext(ctx, "cmd", "/c", "start", url)
752 default: // Linux and other Unix-like systems
753 cmd = exec.CommandContext(ctx, "xdg-open", url)
754 }
755 if b, err := cmd.CombinedOutput(); err != nil {
756 fmt.Fprintf(os.Stderr, "failed to open browser: %v: %s\n", err, b)
757 }
758}
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700759
760// moveFile is like Python's shutil.move, in that it tries a rename, and, if that fails,
761// copies and deletes
762func moveFile(src, dst string) error {
763 if err := os.Rename(src, dst); err == nil {
764 return nil
765 }
766
767 stat, err := os.Stat(src)
768 if err != nil {
769 return err
770 }
771
772 sourceFile, err := os.Open(src)
773 if err != nil {
774 return err
775 }
776 defer sourceFile.Close()
777
778 destFile, err := os.Create(dst)
779 if err != nil {
780 return err
781 }
782 defer destFile.Close()
783
784 _, err = io.Copy(destFile, sourceFile)
785 if err != nil {
786 return err
787 }
788
789 sourceFile.Close()
790 destFile.Close()
791
792 os.Chmod(dst, stat.Mode())
793
794 return os.Remove(src)
795}