blob: 1d6237b1b843eb49c2247d046cfb3ee62861aa94 [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
Pokey Rule0dcebe12025-04-28 14:51:04 +010080 // If true, exit after the first turn
81 OneShot bool
82
83 // Initial prompt
84 Prompt string
Earl Lee2e463fb2025-04-17 11:22:22 -070085}
86
87// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
88// It writes status to stdout.
89func LaunchContainer(ctx context.Context, stdout, stderr io.Writer, config ContainerConfig) error {
90 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -070091 if runtime.GOOS == "darwin" {
92 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
93 } else {
94 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
95 }
Earl Lee2e463fb2025-04-17 11:22:22 -070096 }
97
98 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
99 // `docker ps` provides a good error message here that can be
100 // easily chatgpt'ed by users, so send it to the user as-is:
101 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
102 return fmt.Errorf("docker ps: %s (%w)", out, err)
103 }
104
105 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
106 if err != nil {
107 return err
108 }
109
110 gitRoot, err := findGitRoot(ctx, config.Path)
111 if err != nil {
112 return err
113 }
114
115 imgName, err := findOrBuildDockerImage(ctx, stdout, stderr, config.Path, gitRoot, config.AntURL, config.AntAPIKey, config.ForceRebuild)
116 if err != nil {
117 return err
118 }
119
120 linuxSketchBin := config.SketchBinaryLinux
121 if linuxSketchBin == "" {
122 linuxSketchBin, err = buildLinuxSketchBin(ctx, config.Path)
123 if err != nil {
124 return err
125 }
Josh Bleecher Snyder5544d142025-04-23 14:15:45 -0700126 defer os.Remove(linuxSketchBin) // in case of errors
Earl Lee2e463fb2025-04-17 11:22:22 -0700127 }
128
129 cntrName := imgName + "-" + config.SessionID
130 defer func() {
131 if config.NoCleanup {
132 return
133 }
134 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
135 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
136 _ = out
137 }
138 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
139 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
140 _ = out
141 }
142 }()
143
144 // errCh receives errors from operations that this function calls in separate goroutines.
145 errCh := make(chan error)
146
147 // Start the git server
148 gitSrv, err := newGitServer(gitRoot)
149 if err != nil {
150 return fmt.Errorf("failed to start git server: %w", err)
151 }
152 defer gitSrv.shutdown(ctx)
153
154 go func() {
155 errCh <- gitSrv.serve(ctx)
156 }()
157
158 // Get the current host git commit
159 var commit string
160 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
161 return fmt.Errorf("git rev-parse HEAD: %w", err)
162 } else {
163 commit = strings.TrimSpace(string(out))
164 }
165 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
166 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
167 }
168
169 relPath, err := filepath.Rel(gitRoot, config.Path)
170 if err != nil {
171 return err
172 }
173
174 // Create the sketch container
175 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
176 return err
177 }
178
179 // Copy the sketch linux binary into the container
180 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
181 return fmt.Errorf("docker cp: %s, %w", out, err)
182 }
Josh Bleecher Snyder5544d142025-04-23 14:15:45 -0700183 os.Remove(linuxSketchBin) // in normal operations, the code below blocks, so actively delete now
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700184
185 // Make sure that the webui is built so we can copy the results to the container.
186 _, err = webui.Build()
187 if err != nil {
188 return fmt.Errorf("failed to build webui: %w", err)
189 }
190
David Crawshaw8bff16a2025-04-18 01:16:49 -0700191 webuiZipPath, err := webui.ZipPath()
192 if err != nil {
193 return err
194 }
195 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
196 return fmt.Errorf("docker cp: %s, %w", out, err)
197 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700198
David Crawshaw53786ef2025-04-24 12:52:51 -0700199 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700200
201 // Start the sketch container
202 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
203 return fmt.Errorf("docker start: %s, %w", out, err)
204 }
205
206 // Copies structured logs from the container to the host.
207 copyLogs := func() {
208 if config.ContainerLogDest == "" {
209 return
210 }
211 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
212 if err != nil {
213 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
214 return
215 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700216 prefix := []byte("structured logs:")
217 for line := range bytes.Lines(out) {
218 rest, ok := bytes.CutPrefix(line, prefix)
219 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700220 continue
221 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700222 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700223 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
224 logFileName := filepath.Base(logFile)
225 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
226 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
227 if err != nil {
228 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
229 }
230 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
231 }
232 }
233
234 // NOTE: we want to see what the internal sketch binary prints
235 // regardless of the setting of the verbosity flag on the external
236 // binary, so reading "docker logs", which is the stdout/stderr of
237 // the internal binary is not conditional on the verbose flag.
238 appendInternalErr := func(err error) error {
239 if err == nil {
240 return nil
241 }
242 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000243 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700244 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
245 }
246 out = bytes.TrimSpace(out)
247 if len(out) > 0 {
248 return fmt.Errorf("docker logs: %s;\n%w", out, err)
249 }
250 return err
251 }
252
253 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700254 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700255 if err != nil {
256 return appendInternalErr(err)
257 }
258
Sean McCulloughae3480f2025-04-23 15:28:20 -0700259 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
260 if err != nil {
261 return appendInternalErr(err)
262 }
263 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
264 if err != nil {
Sean McCullough4854c652025-04-24 18:37:02 -0700265 return appendInternalErr(fmt.Errorf("Error splitting ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700266 }
Sean McCullough4854c652025-04-24 18:37:02 -0700267
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700268 var sshServerIdentity, sshUserIdentity []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700269
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700270 if err := CheckForInclude(); err != nil {
271 fmt.Println(err.Error())
272 // continue - ssh config is not required for the rest of sketch to function locally.
273 } else {
274 cst, err := NewSSHTheather(cntrName, sshHost, sshPort)
275 if err != nil {
276 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
277 }
278
279 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700280🖥️ ssh %s
281🖥️ code --remote ssh-remote+root@%s /app -n
282🔗 vscode://vscode-remote/ssh-remote+root@%s/app?n=true
283`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700284 sshUserIdentity = cst.userIdentity
285 sshServerIdentity = cst.serverIdentity
286 defer func() {
287 if err := cst.Cleanup(); err != nil {
288 appendInternalErr(err)
289 }
290 }()
291 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700292
Earl Lee2e463fb2025-04-17 11:22:22 -0700293 // Tell the sketch container which git server port and commit to initialize with.
294 go func() {
295 // TODO: Why is this called in a goroutine? I have found that when I pull this out
296 // of the goroutine and call it inline, then the terminal UI clears itself and all
297 // the scrollback (which is not good, but also not fatal). I can't see why it does this
298 // though, since none of the calls in postContainerInitConfig obviously write to stdout
299 // or stderr.
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700300 if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, sshServerIdentity, sshUserIdentity); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700301 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
302 errCh <- appendInternalErr(err)
303 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700304
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700305 // We open the browser after the init config because the above waits for the web server to be serving.
306 if config.OpenBrowser {
307 if config.SkabandAddr != "" {
308 OpenBrowser(ctx, fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID))
309 } else {
310 OpenBrowser(ctx, "http://"+localAddr)
311 }
312 }
313 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700314
315 go func() {
316 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
317 cmd.Stdin = os.Stdin
318 cmd.Stdout = os.Stdout
319 cmd.Stderr = os.Stderr
320 errCh <- run(ctx, "docker attach", cmd)
321 }()
322
323 defer copyLogs()
324
325 for {
326 select {
327 case <-ctx.Done():
328 return ctx.Err()
329 case err := <-errCh:
330 if err != nil {
331 return appendInternalErr(fmt.Errorf("container process: %w", err))
332 }
333 return nil
334 }
335 }
336}
337
338func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
339 cmd := exec.CommandContext(ctx, cmdName, args...)
340 // Really only needed for the "go build" command for the linux sketch binary
341 cmd.Env = append(os.Environ(), "GOOS=linux", "CGO_ENABLED=0")
342 start := time.Now()
343
344 out, err := cmd.CombinedOutput()
345 if err != nil {
346 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))))
347 } else {
348 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))))
349 }
350 return out, err
351}
352
353func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
354 start := time.Now()
355 err := cmd.Run()
356 if err != nil {
357 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))))
358 } else {
359 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))))
360 }
361 return err
362}
363
364type gitServer struct {
365 gitLn net.Listener
366 gitPort string
367 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700368 pass string
Earl Lee2e463fb2025-04-17 11:22:22 -0700369}
370
371func (gs *gitServer) shutdown(ctx context.Context) {
372 gs.srv.Shutdown(ctx)
373 gs.gitLn.Close()
374}
375
376// Serve a git remote from the host for the container to fetch from and push to.
377func (gs *gitServer) serve(ctx context.Context) error {
378 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
379 return gs.srv.Serve(gs.gitLn)
380}
381
382func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700383 ret := &gitServer{
384 pass: rand.Text(),
385 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700386
Earl Lee2e463fb2025-04-17 11:22:22 -0700387 gitLn, err := net.Listen("tcp4", ":0")
388 if err != nil {
389 return nil, fmt.Errorf("git listen: %w", err)
390 }
391 ret.gitLn = gitLn
392
393 srv := http.Server{
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700394 Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass)},
Earl Lee2e463fb2025-04-17 11:22:22 -0700395 }
396 ret.srv = &srv
397
398 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
399 if err != nil {
400 return nil, fmt.Errorf("git port: %w", err)
401 }
402 ret.gitPort = gitPort
403 return ret, nil
404}
405
406func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
407 //, config.SessionID, config.GitUsername, config.GitEmail, config.SkabandAddr
408 // sessionID, gitUsername, gitEmail, skabandAddr string
David Crawshaw69c67312025-04-17 13:42:00 -0700409 cmdArgs := []string{
410 "create",
Earl Lee2e463fb2025-04-17 11:22:22 -0700411 "-it",
412 "--name", cntrName,
413 "-p", hostPort + ":80", // forward container port 80 to a host port
414 "-e", "ANTHROPIC_API_KEY=" + config.AntAPIKey,
415 }
416 if config.AntURL != "" {
417 cmdArgs = append(cmdArgs, "-e", "ANT_URL="+config.AntURL)
418 }
419 if config.SketchPubKey != "" {
420 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
421 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700422 if config.SSHPort > 0 {
423 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
424 } else {
425 cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700426 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700427 if relPath != "." {
428 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
429 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700430 // colima does this by default, but Linux docker seems to need this set explicitly
431 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700432 cmdArgs = append(
433 cmdArgs,
434 imgName,
435 "/bin/sketch",
436 "-unsafe",
437 "-addr=:80",
438 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000439 "-git-username="+config.GitUsername,
440 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000441 "-outside-hostname="+config.OutsideHostname,
442 "-outside-os="+config.OutsideOS,
443 "-outside-working-dir="+config.OutsideWorkingDir,
Earl Lee2e463fb2025-04-17 11:22:22 -0700444 )
445 if config.SkabandAddr != "" {
446 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
447 }
Pokey Rule0dcebe12025-04-28 14:51:04 +0100448 if config.Prompt != "" {
449 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
450 }
451 if config.OneShot {
452 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700453 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700454 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
455 return fmt.Errorf("docker create: %s, %w", out, err)
456 }
457 return nil
458}
459
460func buildLinuxSketchBin(ctx context.Context, path string) (string, error) {
David Crawshaw8a617cb2025-04-18 01:28:43 -0700461 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700462 if err != nil {
463 return "", err
464 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700465 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
466 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
467 return "", err
468 }
469
470 verToInstall := "@latest"
471 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
472 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
473 } else {
474 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700475 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700476 verToInstall = ""
477 }
478 }
David Crawshaw69c67312025-04-17 13:42:00 -0700479
Earl Lee2e463fb2025-04-17 11:22:22 -0700480 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700481 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700482 cmd.Env = append(
483 os.Environ(),
484 "GOOS=linux",
485 "CGO_ENABLED=0",
486 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700487 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700488 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700489 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700490
Earl Lee2e463fb2025-04-17 11:22:22 -0700491 out, err := cmd.CombinedOutput()
492 if err != nil {
493 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))))
494 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
495 } else {
496 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))))
497 }
498
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700499 var src string
500 if runtime.GOOS != "linux" {
501 src = filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch")
502 } else {
503 // If we are already on Linux, there's no extra platform name in the path
504 src = filepath.Join(linuxGopath, "bin", "sketch")
505 }
506
David Crawshaw69c67312025-04-17 13:42:00 -0700507 dst := filepath.Join(path, "tmp-sketch-binary-linux")
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700508 if err := moveFile(src, dst); err != nil {
David Crawshaw69c67312025-04-17 13:42:00 -0700509 return "", err
510 }
511
David Crawshaw69c67312025-04-17 13:42:00 -0700512 return dst, nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700513}
514
Sean McCulloughae3480f2025-04-23 15:28:20 -0700515func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700516 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700517 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700518 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
519 } else {
520 v4, _, found := strings.Cut(string(out), "\n")
521 if !found {
522 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
523 }
524 localAddr = v4
525 if strings.HasPrefix(localAddr, "0.0.0.0") {
526 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
527 }
528 }
529 return localAddr, nil
530}
531
532// Contact the container and configure it.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700533func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshServerIdentity, sshAuthorizedKeys []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700534 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700535
536 initMsg, err := json.Marshal(
537 server.InitRequest{
538 Commit: commit,
539 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
540 HostAddr: localAddr,
541 SSHAuthorizedKeys: sshAuthorizedKeys,
542 SSHServerIdentity: sshServerIdentity,
543 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700544 if err != nil {
545 return fmt.Errorf("init msg: %w", err)
546 }
547
Earl Lee2e463fb2025-04-17 11:22:22 -0700548 // Note: this /init POST is handled in loop/server/loophttp.go:
549 initMsgByteReader := bytes.NewReader(initMsg)
550 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
551 if err != nil {
552 return err
553 }
554
555 var res *http.Response
556 for i := 0; ; i++ {
557 time.Sleep(100 * time.Millisecond)
558 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
559 initMsgByteReader.Reset(initMsg)
560 res, err = http.DefaultClient.Do(req)
561 if err != nil {
562 // In addition to "connection refused", we also occasionally see "EOF" errors that can succeed on retries.
563 if i < 100 && (strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "EOF")) {
564 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
565 continue
566 }
567 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
568 }
569 break
570 }
571 resBytes, _ := io.ReadAll(res.Body)
572 if res.StatusCode != http.StatusOK {
573 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
574 }
575 return nil
576}
577
578func findOrBuildDockerImage(ctx context.Context, stdout, stderr io.Writer, cwd, gitRoot, antURL, antAPIKey string, forceRebuild bool) (imgName string, err error) {
579 h := sha256.Sum256([]byte(gitRoot))
580 imgName = "sketch-" + hex.EncodeToString(h[:6])
581
582 var curImgInitFilesHash string
583 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
584 if strings.Contains(string(out), "No such object") {
585 // Image does not exist, continue and build it.
586 curImgInitFilesHash = ""
587 } else {
588 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
589 }
590 } else {
591 m := map[string]string{}
592 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
593 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
594 }
595 curImgInitFilesHash = m["sketch_context"]
596 }
597
598 candidates, err := findRepoDockerfiles(cwd, gitRoot)
599 if err != nil {
600 return "", fmt.Errorf("find dockerfile: %w", err)
601 }
602
603 var initFiles map[string]string
604 var dockerfilePath string
605
606 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
607 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
608 dockerfilePath = candidates[0]
609 contents, err := os.ReadFile(dockerfilePath)
610 if err != nil {
611 return "", err
612 }
613 fmt.Printf("using %s as dev env\n", candidates[0])
614 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700615 return imgName, nil
616 }
617 } else {
618 initFiles, err = readInitFiles(os.DirFS(gitRoot))
619 if err != nil {
620 return "", err
621 }
622 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
623 if err != nil {
624 return "", err
625 }
626 initFileHash := hashInitFiles(initFiles)
627 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700628 return imgName, nil
629 }
630
631 start := time.Now()
632 dockerfile, err := createDockerfile(ctx, http.DefaultClient, antURL, antAPIKey, initFiles, subPathWorkingDir)
633 if err != nil {
634 return "", fmt.Errorf("create dockerfile: %w", err)
635 }
636 dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile")
637 if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil {
638 return "", err
639 }
640 defer os.Remove(dockerfilePath)
641
642 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))
643 }
644
645 var gitUserEmail, gitUserName string
646 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
647 return "", fmt.Errorf("git config: %s: %v", out, err)
648 } else {
649 gitUserEmail = strings.TrimSpace(string(out))
650 }
651 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
652 return "", fmt.Errorf("git config: %s: %v", out, err)
653 } else {
654 gitUserName = strings.TrimSpace(string(out))
655 }
656
657 start := time.Now()
658 cmd := exec.CommandContext(ctx,
659 "docker", "build",
660 "-t", imgName,
661 "-f", dockerfilePath,
662 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
663 "--build-arg", "GIT_USER_NAME="+gitUserName,
664 ".",
665 )
666 cmd.Dir = gitRoot
667 cmd.Stdout = stdout
668 cmd.Stderr = stderr
Josh Bleecher Snyderdf2d3dc2025-04-25 12:31:35 -0700669 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Philip Zeyligere4fa0e32025-04-23 14:15:55 -0700670 dockerfileContent, err := os.ReadFile(dockerfilePath)
671 if err != nil {
672 return "", fmt.Errorf("failed to read Dockerfile: %w", err)
673 }
Philip Zeyliger5d6af872025-04-23 19:48:34 -0700674 fmt.Fprintf(stdout, "Dockerfile:\n%s\n", string(dockerfileContent))
Earl Lee2e463fb2025-04-17 11:22:22 -0700675
676 err = run(ctx, "docker build", cmd)
677 if err != nil {
678 return "", fmt.Errorf("docker build failed: %v", err)
679 }
680 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
681 return imgName, nil
682}
683
684func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
685 files, err := findDirDockerfiles(cwd)
686 if err != nil {
687 return nil, err
688 }
689 if len(files) > 0 {
690 return files, nil
691 }
692
693 path := cwd
694 for path != gitRoot {
695 path = filepath.Dir(path)
696 files, err := findDirDockerfiles(path)
697 if err != nil {
698 return nil, err
699 }
700 if len(files) > 0 {
701 return files, nil
702 }
703 }
704 return files, nil
705}
706
707// findDirDockerfiles finds all "Dockerfile*" files in a directory.
708func findDirDockerfiles(root string) (res []string, err error) {
709 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
710 if err != nil {
711 return err
712 }
713 if info.IsDir() && root != path {
714 return filepath.SkipDir
715 }
716 name := strings.ToLower(info.Name())
717 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
718 res = append(res, path)
719 }
720 return nil
721 })
722 if err != nil {
723 return nil, err
724 }
725 return res, nil
726}
727
728func findGitRoot(ctx context.Context, path string) (string, error) {
729 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
730 cmd.Dir = path
731 out, err := cmd.CombinedOutput()
732 if err != nil {
733 if strings.Contains(string(out), "not a git repository") {
734 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
735Consider one of the following options:
736 - cd to a different dir that is already part of a git repo first, or
737 - to create a new git repo from this directory (%s), run this command:
738
739 git init . && git commit --allow-empty -m "initial commit"
740
741and try running sketch again.
742`, path, path)
743 }
744 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
745 }
746 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
747 absGitDir := filepath.Join(path, gitDir)
748 return filepath.Dir(absGitDir), err
749}
750
751func OpenBrowser(ctx context.Context, url string) {
752 var cmd *exec.Cmd
753 switch runtime.GOOS {
754 case "darwin":
755 cmd = exec.CommandContext(ctx, "open", url)
756 case "windows":
757 cmd = exec.CommandContext(ctx, "cmd", "/c", "start", url)
758 default: // Linux and other Unix-like systems
759 cmd = exec.CommandContext(ctx, "xdg-open", url)
760 }
761 if b, err := cmd.CombinedOutput(); err != nil {
762 fmt.Fprintf(os.Stderr, "failed to open browser: %v: %s\n", err, b)
763 }
764}
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700765
766// moveFile is like Python's shutil.move, in that it tries a rename, and, if that fails,
767// copies and deletes
768func moveFile(src, dst string) error {
769 if err := os.Rename(src, dst); err == nil {
770 return nil
771 }
772
773 stat, err := os.Stat(src)
774 if err != nil {
775 return err
776 }
777
778 sourceFile, err := os.Open(src)
779 if err != nil {
780 return err
781 }
782 defer sourceFile.Close()
783
784 destFile, err := os.Create(dst)
785 if err != nil {
786 return err
787 }
788 defer destFile.Close()
789
790 _, err = io.Copy(destFile, sourceFile)
791 if err != nil {
792 return err
793 }
794
795 sourceFile.Close()
796 destFile.Close()
797
798 os.Chmod(dst, stat.Mode())
799
800 return os.Remove(src)
801}