blob: c97c98980d60d20fd12e528878baf10c62e84224 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package dockerimg
2package dockerimg
3
4import (
Philip Zeyligerd0131312025-04-23 21:14:01 +00005 "bufio"
Earl Lee2e463fb2025-04-17 11:22:22 -07006 "bytes"
7 "context"
Philip Zeyliger5e227dd2025-04-21 15:55:29 -07008 "crypto/rand"
Earl Lee2e463fb2025-04-17 11:22:22 -07009 "crypto/sha256"
10 "encoding/hex"
11 "encoding/json"
12 "fmt"
13 "io"
14 "log/slog"
15 "net"
16 "net/http"
17 "os"
18 "os/exec"
19 "path/filepath"
20 "runtime"
21 "strings"
22 "time"
23
Sean McCulloughbaa2b592025-04-23 10:40:08 -070024 "sketch.dev/loop/server"
David Crawshaw8bff16a2025-04-18 01:16:49 -070025 "sketch.dev/loop/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070026 "sketch.dev/skribe"
27)
28
29// ContainerConfig holds all configuration for launching a container
30type ContainerConfig struct {
31 // SessionID is the unique identifier for this session
32 SessionID string
33
34 // LocalAddr is the initial address to use (though it may be overwritten later)
35 LocalAddr string
36
37 // SkabandAddr is the address of the skaband service if available
38 SkabandAddr string
39
40 // AntURL is the URL of the LLM service.
41 AntURL string
42
43 // AntAPIKey is the API key for LLM service.
44 AntAPIKey string
45
46 // Path is the local filesystem path to use
47 Path string
48
49 // GitUsername is the username to use for git operations
50 GitUsername string
51
52 // GitEmail is the email to use for git operations
53 GitEmail string
54
55 // OpenBrowser determines whether to open a browser automatically
56 OpenBrowser bool
57
58 // NoCleanup prevents container cleanup when set to true
59 NoCleanup bool
60
61 // ForceRebuild forces rebuilding of the Docker image even if it exists
62 ForceRebuild bool
63
64 // Host directory to copy container logs into, if not set to ""
65 ContainerLogDest string
66
67 // Path to pre-built linux sketch binary, or build a new one if set to ""
68 SketchBinaryLinux string
69
70 // Sketch client public key.
71 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000072
Sean McCulloughbaa2b592025-04-23 10:40:08 -070073 // Host port for the container's ssh server
74 SSHPort int
75
76 // Public keys authorized to connect to the container's ssh server
77 SSHAuthorizedKeys []byte
78
79 // Private key used to identify the container's ssh server
80 SSHServerIdentity []byte
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
Earl Lee2e463fb2025-04-17 11:22:22 -070086}
87
88// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
89// It writes status to stdout.
90func LaunchContainer(ctx context.Context, stdout, stderr io.Writer, config ContainerConfig) error {
91 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -070092 if runtime.GOOS == "darwin" {
93 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
94 } else {
95 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
96 }
Earl Lee2e463fb2025-04-17 11:22:22 -070097 }
98
99 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
100 // `docker ps` provides a good error message here that can be
101 // easily chatgpt'ed by users, so send it to the user as-is:
102 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
103 return fmt.Errorf("docker ps: %s (%w)", out, err)
104 }
105
106 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
107 if err != nil {
108 return err
109 }
110
111 gitRoot, err := findGitRoot(ctx, config.Path)
112 if err != nil {
113 return err
114 }
115
116 imgName, err := findOrBuildDockerImage(ctx, stdout, stderr, config.Path, gitRoot, config.AntURL, config.AntAPIKey, config.ForceRebuild)
117 if err != nil {
118 return err
119 }
120
121 linuxSketchBin := config.SketchBinaryLinux
122 if linuxSketchBin == "" {
123 linuxSketchBin, err = buildLinuxSketchBin(ctx, config.Path)
124 if err != nil {
125 return err
126 }
Josh Bleecher Snyder5544d142025-04-23 14:15:45 -0700127 defer os.Remove(linuxSketchBin) // in case of errors
Earl Lee2e463fb2025-04-17 11:22:22 -0700128 }
129
130 cntrName := imgName + "-" + config.SessionID
131 defer func() {
132 if config.NoCleanup {
133 return
134 }
135 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
136 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
137 _ = out
138 }
139 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
140 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
141 _ = out
142 }
143 }()
144
145 // errCh receives errors from operations that this function calls in separate goroutines.
146 errCh := make(chan error)
147
148 // Start the git server
149 gitSrv, err := newGitServer(gitRoot)
150 if err != nil {
151 return fmt.Errorf("failed to start git server: %w", err)
152 }
153 defer gitSrv.shutdown(ctx)
154
155 go func() {
156 errCh <- gitSrv.serve(ctx)
157 }()
158
159 // Get the current host git commit
160 var commit string
161 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
162 return fmt.Errorf("git rev-parse HEAD: %w", err)
163 } else {
164 commit = strings.TrimSpace(string(out))
165 }
166 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
167 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
168 }
169
170 relPath, err := filepath.Rel(gitRoot, config.Path)
171 if err != nil {
172 return err
173 }
174
175 // Create the sketch container
176 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
177 return err
178 }
179
180 // Copy the sketch linux binary into the container
181 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
182 return fmt.Errorf("docker cp: %s, %w", out, err)
183 }
Josh Bleecher Snyder5544d142025-04-23 14:15:45 -0700184 os.Remove(linuxSketchBin) // in normal operations, the code below blocks, so actively delete now
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700185
186 // Make sure that the webui is built so we can copy the results to the container.
187 _, err = webui.Build()
188 if err != nil {
189 return fmt.Errorf("failed to build webui: %w", err)
190 }
191
David Crawshaw8bff16a2025-04-18 01:16:49 -0700192 webuiZipPath, err := webui.ZipPath()
193 if err != nil {
194 return err
195 }
196 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
197 return fmt.Errorf("docker cp: %s, %w", out, err)
198 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700199
200 fmt.Printf("starting container %s\ncommits made by the agent will be pushed to \033[1msketch/*\033[0m\n", cntrName)
201
202 // Start the sketch container
203 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
204 return fmt.Errorf("docker start: %s, %w", out, err)
205 }
206
207 // Copies structured logs from the container to the host.
208 copyLogs := func() {
209 if config.ContainerLogDest == "" {
210 return
211 }
212 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
213 if err != nil {
214 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
215 return
216 }
Philip Zeyligerd0131312025-04-23 21:14:01 +0000217 scanner := bufio.NewScanner(bytes.NewReader(out))
218 for scanner.Scan() {
219 logLine := scanner.Text()
Earl Lee2e463fb2025-04-17 11:22:22 -0700220 if !strings.HasPrefix(logLine, "structured logs:") {
221 continue
222 }
223 logFile := strings.TrimSpace(strings.TrimPrefix(logLine, "structured logs:"))
224 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
225 logFileName := filepath.Base(logFile)
226 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
227 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
228 if err != nil {
229 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
230 }
231 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
232 }
233 }
234
235 // NOTE: we want to see what the internal sketch binary prints
236 // regardless of the setting of the verbosity flag on the external
237 // binary, so reading "docker logs", which is the stdout/stderr of
238 // the internal binary is not conditional on the verbose flag.
239 appendInternalErr := func(err error) error {
240 if err == nil {
241 return nil
242 }
243 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000244 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700245 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
246 }
247 out = bytes.TrimSpace(out)
248 if len(out) > 0 {
249 return fmt.Errorf("docker logs: %s;\n%w", out, err)
250 }
251 return err
252 }
253
254 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700255 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700256 if err != nil {
257 return appendInternalErr(err)
258 }
259
Sean McCulloughae3480f2025-04-23 15:28:20 -0700260 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
261 if err != nil {
262 return appendInternalErr(err)
263 }
264 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
265 if err != nil {
266 fmt.Println("Error splitting ssh host and port:", err)
267 }
268 fmt.Printf("ssh into this container with: ssh root@%s -p %s\n", sshHost, sshPort)
269
Earl Lee2e463fb2025-04-17 11:22:22 -0700270 // Tell the sketch container which git server port and commit to initialize with.
271 go func() {
272 // TODO: Why is this called in a goroutine? I have found that when I pull this out
273 // of the goroutine and call it inline, then the terminal UI clears itself and all
274 // the scrollback (which is not good, but also not fatal). I can't see why it does this
275 // though, since none of the calls in postContainerInitConfig obviously write to stdout
276 // or stderr.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700277 if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, config.SSHServerIdentity, config.SSHAuthorizedKeys); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700278 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
279 errCh <- appendInternalErr(err)
280 }
281 }()
282
283 if config.OpenBrowser {
284 OpenBrowser(ctx, "http://"+localAddr)
285 }
286
287 go func() {
288 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
289 cmd.Stdin = os.Stdin
290 cmd.Stdout = os.Stdout
291 cmd.Stderr = os.Stderr
292 errCh <- run(ctx, "docker attach", cmd)
293 }()
294
295 defer copyLogs()
296
297 for {
298 select {
299 case <-ctx.Done():
300 return ctx.Err()
301 case err := <-errCh:
302 if err != nil {
303 return appendInternalErr(fmt.Errorf("container process: %w", err))
304 }
305 return nil
306 }
307 }
308}
309
310func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
311 cmd := exec.CommandContext(ctx, cmdName, args...)
312 // Really only needed for the "go build" command for the linux sketch binary
313 cmd.Env = append(os.Environ(), "GOOS=linux", "CGO_ENABLED=0")
314 start := time.Now()
315
316 out, err := cmd.CombinedOutput()
317 if err != nil {
318 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))))
319 } else {
320 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))))
321 }
322 return out, err
323}
324
325func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
326 start := time.Now()
327 err := cmd.Run()
328 if err != nil {
329 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))))
330 } else {
331 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))))
332 }
333 return err
334}
335
336type gitServer struct {
337 gitLn net.Listener
338 gitPort string
339 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700340 pass string
Earl Lee2e463fb2025-04-17 11:22:22 -0700341}
342
343func (gs *gitServer) shutdown(ctx context.Context) {
344 gs.srv.Shutdown(ctx)
345 gs.gitLn.Close()
346}
347
348// Serve a git remote from the host for the container to fetch from and push to.
349func (gs *gitServer) serve(ctx context.Context) error {
350 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
351 return gs.srv.Serve(gs.gitLn)
352}
353
354func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700355 ret := &gitServer{
356 pass: rand.Text(),
357 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700358
Earl Lee2e463fb2025-04-17 11:22:22 -0700359 gitLn, err := net.Listen("tcp4", ":0")
360 if err != nil {
361 return nil, fmt.Errorf("git listen: %w", err)
362 }
363 ret.gitLn = gitLn
364
365 srv := http.Server{
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700366 Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass)},
Earl Lee2e463fb2025-04-17 11:22:22 -0700367 }
368 ret.srv = &srv
369
370 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
371 if err != nil {
372 return nil, fmt.Errorf("git port: %w", err)
373 }
374 ret.gitPort = gitPort
375 return ret, nil
376}
377
378func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
379 //, config.SessionID, config.GitUsername, config.GitEmail, config.SkabandAddr
380 // sessionID, gitUsername, gitEmail, skabandAddr string
David Crawshaw69c67312025-04-17 13:42:00 -0700381 cmdArgs := []string{
382 "create",
Earl Lee2e463fb2025-04-17 11:22:22 -0700383 "-it",
384 "--name", cntrName,
385 "-p", hostPort + ":80", // forward container port 80 to a host port
386 "-e", "ANTHROPIC_API_KEY=" + config.AntAPIKey,
387 }
388 if config.AntURL != "" {
389 cmdArgs = append(cmdArgs, "-e", "ANT_URL="+config.AntURL)
390 }
391 if config.SketchPubKey != "" {
392 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
393 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700394 if config.SSHPort > 0 {
395 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
396 } else {
397 cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700398 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700399 if relPath != "." {
400 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
401 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700402 // colima does this by default, but Linux docker seems to need this set explicitly
403 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700404 cmdArgs = append(
405 cmdArgs,
406 imgName,
407 "/bin/sketch",
408 "-unsafe",
409 "-addr=:80",
410 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000411 "-git-username="+config.GitUsername,
412 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000413 "-outside-hostname="+config.OutsideHostname,
414 "-outside-os="+config.OutsideOS,
415 "-outside-working-dir="+config.OutsideWorkingDir,
Earl Lee2e463fb2025-04-17 11:22:22 -0700416 )
417 if config.SkabandAddr != "" {
418 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
419 }
420 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
421 return fmt.Errorf("docker create: %s, %w", out, err)
422 }
423 return nil
424}
425
426func buildLinuxSketchBin(ctx context.Context, path string) (string, error) {
David Crawshaw8a617cb2025-04-18 01:28:43 -0700427 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700428 if err != nil {
429 return "", err
430 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700431 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
432 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
433 return "", err
434 }
435
436 verToInstall := "@latest"
437 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
438 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
439 } else {
440 if strings.TrimSpace(string(out)) == "sketch.dev" {
441 fmt.Printf("building linux agent from currently checked out module\n")
442 verToInstall = ""
443 }
444 }
David Crawshaw69c67312025-04-17 13:42:00 -0700445
Earl Lee2e463fb2025-04-17 11:22:22 -0700446 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700447 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700448 cmd.Env = append(
449 os.Environ(),
450 "GOOS=linux",
451 "CGO_ENABLED=0",
452 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700453 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700454 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700455 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700456
457 fmt.Printf("building linux agent binary...\n")
458 out, err := cmd.CombinedOutput()
459 if err != nil {
460 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))))
461 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
462 } else {
463 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))))
464 }
465
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700466 var src string
467 if runtime.GOOS != "linux" {
468 src = filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch")
469 } else {
470 // If we are already on Linux, there's no extra platform name in the path
471 src = filepath.Join(linuxGopath, "bin", "sketch")
472 }
473
David Crawshaw69c67312025-04-17 13:42:00 -0700474 dst := filepath.Join(path, "tmp-sketch-binary-linux")
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700475 if err := moveFile(src, dst); err != nil {
David Crawshaw69c67312025-04-17 13:42:00 -0700476 return "", err
477 }
478
Earl Lee2e463fb2025-04-17 11:22:22 -0700479 fmt.Printf("built linux agent binary in %s\n", time.Since(start).Round(100*time.Millisecond))
480
David Crawshaw69c67312025-04-17 13:42:00 -0700481 return dst, nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700482}
483
Sean McCulloughae3480f2025-04-23 15:28:20 -0700484func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700485 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700486 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700487 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
488 } else {
489 v4, _, found := strings.Cut(string(out), "\n")
490 if !found {
491 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
492 }
493 localAddr = v4
494 if strings.HasPrefix(localAddr, "0.0.0.0") {
495 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
496 }
497 }
498 return localAddr, nil
499}
500
501// Contact the container and configure it.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700502func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshServerIdentity, sshAuthorizedKeys []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700503 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700504
505 initMsg, err := json.Marshal(
506 server.InitRequest{
507 Commit: commit,
508 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
509 HostAddr: localAddr,
510 SSHAuthorizedKeys: sshAuthorizedKeys,
511 SSHServerIdentity: sshServerIdentity,
512 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700513 if err != nil {
514 return fmt.Errorf("init msg: %w", err)
515 }
516
Earl Lee2e463fb2025-04-17 11:22:22 -0700517 // Note: this /init POST is handled in loop/server/loophttp.go:
518 initMsgByteReader := bytes.NewReader(initMsg)
519 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
520 if err != nil {
521 return err
522 }
523
524 var res *http.Response
525 for i := 0; ; i++ {
526 time.Sleep(100 * time.Millisecond)
527 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
528 initMsgByteReader.Reset(initMsg)
529 res, err = http.DefaultClient.Do(req)
530 if err != nil {
531 // In addition to "connection refused", we also occasionally see "EOF" errors that can succeed on retries.
532 if i < 100 && (strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "EOF")) {
533 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
534 continue
535 }
536 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
537 }
538 break
539 }
540 resBytes, _ := io.ReadAll(res.Body)
541 if res.StatusCode != http.StatusOK {
542 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
543 }
544 return nil
545}
546
547func findOrBuildDockerImage(ctx context.Context, stdout, stderr io.Writer, cwd, gitRoot, antURL, antAPIKey string, forceRebuild bool) (imgName string, err error) {
548 h := sha256.Sum256([]byte(gitRoot))
549 imgName = "sketch-" + hex.EncodeToString(h[:6])
550
551 var curImgInitFilesHash string
552 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
553 if strings.Contains(string(out), "No such object") {
554 // Image does not exist, continue and build it.
555 curImgInitFilesHash = ""
556 } else {
557 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
558 }
559 } else {
560 m := map[string]string{}
561 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
562 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
563 }
564 curImgInitFilesHash = m["sketch_context"]
565 }
566
567 candidates, err := findRepoDockerfiles(cwd, gitRoot)
568 if err != nil {
569 return "", fmt.Errorf("find dockerfile: %w", err)
570 }
571
572 var initFiles map[string]string
573 var dockerfilePath string
574
575 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
576 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
577 dockerfilePath = candidates[0]
578 contents, err := os.ReadFile(dockerfilePath)
579 if err != nil {
580 return "", err
581 }
582 fmt.Printf("using %s as dev env\n", candidates[0])
583 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
584 fmt.Printf("using existing docker image %s\n", imgName)
585 return imgName, nil
586 }
587 } else {
588 initFiles, err = readInitFiles(os.DirFS(gitRoot))
589 if err != nil {
590 return "", err
591 }
592 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
593 if err != nil {
594 return "", err
595 }
596 initFileHash := hashInitFiles(initFiles)
597 if curImgInitFilesHash == initFileHash && !forceRebuild {
598 fmt.Printf("using existing docker image %s\n", imgName)
599 return imgName, nil
600 }
601
602 start := time.Now()
603 dockerfile, err := createDockerfile(ctx, http.DefaultClient, antURL, antAPIKey, initFiles, subPathWorkingDir)
604 if err != nil {
605 return "", fmt.Errorf("create dockerfile: %w", err)
606 }
607 dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile")
608 if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil {
609 return "", err
610 }
611 defer os.Remove(dockerfilePath)
612
613 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))
614 }
615
616 var gitUserEmail, gitUserName string
617 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
618 return "", fmt.Errorf("git config: %s: %v", out, err)
619 } else {
620 gitUserEmail = strings.TrimSpace(string(out))
621 }
622 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
623 return "", fmt.Errorf("git config: %s: %v", out, err)
624 } else {
625 gitUserName = strings.TrimSpace(string(out))
626 }
627
628 start := time.Now()
629 cmd := exec.CommandContext(ctx,
630 "docker", "build",
631 "-t", imgName,
632 "-f", dockerfilePath,
633 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
634 "--build-arg", "GIT_USER_NAME="+gitUserName,
635 ".",
636 )
637 cmd.Dir = gitRoot
638 cmd.Stdout = stdout
639 cmd.Stderr = stderr
Philip Zeyligercc3ba222025-04-23 14:52:21 -0700640 fmt.Printf("building docker image %s... (use -verbose to see build output)\n", imgName)
Philip Zeyligere4fa0e32025-04-23 14:15:55 -0700641 dockerfileContent, err := os.ReadFile(dockerfilePath)
642 if err != nil {
643 return "", fmt.Errorf("failed to read Dockerfile: %w", err)
644 }
Philip Zeyligercc3ba222025-04-23 14:52:21 -0700645 fmt.Printf("Dockerfile:\n%s\n", string(dockerfileContent))
Earl Lee2e463fb2025-04-17 11:22:22 -0700646
647 err = run(ctx, "docker build", cmd)
648 if err != nil {
649 return "", fmt.Errorf("docker build failed: %v", err)
650 }
651 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
652 return imgName, nil
653}
654
655func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
656 files, err := findDirDockerfiles(cwd)
657 if err != nil {
658 return nil, err
659 }
660 if len(files) > 0 {
661 return files, nil
662 }
663
664 path := cwd
665 for path != gitRoot {
666 path = filepath.Dir(path)
667 files, err := findDirDockerfiles(path)
668 if err != nil {
669 return nil, err
670 }
671 if len(files) > 0 {
672 return files, nil
673 }
674 }
675 return files, nil
676}
677
678// findDirDockerfiles finds all "Dockerfile*" files in a directory.
679func findDirDockerfiles(root string) (res []string, err error) {
680 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
681 if err != nil {
682 return err
683 }
684 if info.IsDir() && root != path {
685 return filepath.SkipDir
686 }
687 name := strings.ToLower(info.Name())
688 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
689 res = append(res, path)
690 }
691 return nil
692 })
693 if err != nil {
694 return nil, err
695 }
696 return res, nil
697}
698
699func findGitRoot(ctx context.Context, path string) (string, error) {
700 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
701 cmd.Dir = path
702 out, err := cmd.CombinedOutput()
703 if err != nil {
704 if strings.Contains(string(out), "not a git repository") {
705 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
706Consider one of the following options:
707 - cd to a different dir that is already part of a git repo first, or
708 - to create a new git repo from this directory (%s), run this command:
709
710 git init . && git commit --allow-empty -m "initial commit"
711
712and try running sketch again.
713`, path, path)
714 }
715 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
716 }
717 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
718 absGitDir := filepath.Join(path, gitDir)
719 return filepath.Dir(absGitDir), err
720}
721
722func OpenBrowser(ctx context.Context, url string) {
723 var cmd *exec.Cmd
724 switch runtime.GOOS {
725 case "darwin":
726 cmd = exec.CommandContext(ctx, "open", url)
727 case "windows":
728 cmd = exec.CommandContext(ctx, "cmd", "/c", "start", url)
729 default: // Linux and other Unix-like systems
730 cmd = exec.CommandContext(ctx, "xdg-open", url)
731 }
732 if b, err := cmd.CombinedOutput(); err != nil {
733 fmt.Fprintf(os.Stderr, "failed to open browser: %v: %s\n", err, b)
734 }
735}
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700736
737// moveFile is like Python's shutil.move, in that it tries a rename, and, if that fails,
738// copies and deletes
739func moveFile(src, dst string) error {
740 if err := os.Rename(src, dst); err == nil {
741 return nil
742 }
743
744 stat, err := os.Stat(src)
745 if err != nil {
746 return err
747 }
748
749 sourceFile, err := os.Open(src)
750 if err != nil {
751 return err
752 }
753 defer sourceFile.Close()
754
755 destFile, err := os.Create(dst)
756 if err != nil {
757 return err
758 }
759 defer destFile.Close()
760
761 _, err = io.Copy(destFile, sourceFile)
762 if err != nil {
763 return err
764 }
765
766 sourceFile.Close()
767 destFile.Close()
768
769 os.Chmod(dst, stat.Mode())
770
771 return os.Remove(src)
772}