blob: 03fc4000a17aef001f69525eb9756d09dcd62950 [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
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000023 "sketch.dev/browser"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070024 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070025 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070026 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070027)
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
Philip Zeyliger18532b22025-04-23 21:11:46 +000076 // Outside information to pass to the container
77 OutsideHostname string
78 OutsideOS string
79 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070080
Pokey Rule0dcebe12025-04-28 14:51:04 +010081 // If true, exit after the first turn
82 OneShot bool
83
84 // Initial prompt
85 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000086
87 // Initial commit to use as starting point
88 InitialCommit string
Earl Lee2e463fb2025-04-17 11:22:22 -070089}
90
91// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
92// It writes status to stdout.
93func LaunchContainer(ctx context.Context, stdout, stderr io.Writer, config ContainerConfig) error {
94 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -070095 if runtime.GOOS == "darwin" {
96 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
97 } else {
98 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
99 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700100 }
101
102 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
103 // `docker ps` provides a good error message here that can be
104 // easily chatgpt'ed by users, so send it to the user as-is:
105 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
106 return fmt.Errorf("docker ps: %s (%w)", out, err)
107 }
108
109 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
110 if err != nil {
111 return err
112 }
113
114 gitRoot, err := findGitRoot(ctx, config.Path)
115 if err != nil {
116 return err
117 }
118
119 imgName, err := findOrBuildDockerImage(ctx, stdout, stderr, config.Path, gitRoot, config.AntURL, config.AntAPIKey, config.ForceRebuild)
120 if err != nil {
121 return err
122 }
123
124 linuxSketchBin := config.SketchBinaryLinux
125 if linuxSketchBin == "" {
126 linuxSketchBin, err = buildLinuxSketchBin(ctx, config.Path)
127 if err != nil {
128 return err
129 }
Josh Bleecher Snyder5544d142025-04-23 14:15:45 -0700130 defer os.Remove(linuxSketchBin) // in case of errors
Earl Lee2e463fb2025-04-17 11:22:22 -0700131 }
132
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000133 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700134 defer func() {
135 if config.NoCleanup {
136 return
137 }
138 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
139 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
140 _ = out
141 }
142 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
143 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
144 _ = out
145 }
146 }()
147
148 // errCh receives errors from operations that this function calls in separate goroutines.
149 errCh := make(chan error)
150
151 // Start the git server
152 gitSrv, err := newGitServer(gitRoot)
153 if err != nil {
154 return fmt.Errorf("failed to start git server: %w", err)
155 }
156 defer gitSrv.shutdown(ctx)
157
158 go func() {
159 errCh <- gitSrv.serve(ctx)
160 }()
161
162 // Get the current host git commit
163 var commit string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +0000164 if out, err := combinedOutput(ctx, "git", "rev-parse", config.InitialCommit); err != nil {
165 return fmt.Errorf("git rev-parse %s: %w", config.InitialCommit, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700166 } else {
167 commit = strings.TrimSpace(string(out))
168 }
169 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
170 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
171 }
172
173 relPath, err := filepath.Rel(gitRoot, config.Path)
174 if err != nil {
175 return err
176 }
177
178 // Create the sketch container
179 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
180 return err
181 }
182
183 // Copy the sketch linux binary into the container
184 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
185 return fmt.Errorf("docker cp: %s, %w", out, err)
186 }
Josh Bleecher Snyder5544d142025-04-23 14:15:45 -0700187 os.Remove(linuxSketchBin) // in normal operations, the code below blocks, so actively delete now
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700188
189 // Make sure that the webui is built so we can copy the results to the container.
190 _, err = webui.Build()
191 if err != nil {
192 return fmt.Errorf("failed to build webui: %w", err)
193 }
194
David Crawshaw8bff16a2025-04-18 01:16:49 -0700195 webuiZipPath, err := webui.ZipPath()
196 if err != nil {
197 return err
198 }
199 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
200 return fmt.Errorf("docker cp: %s, %w", out, err)
201 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700202
David Crawshaw53786ef2025-04-24 12:52:51 -0700203 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700204
205 // Start the sketch container
206 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
207 return fmt.Errorf("docker start: %s, %w", out, err)
208 }
209
210 // Copies structured logs from the container to the host.
211 copyLogs := func() {
212 if config.ContainerLogDest == "" {
213 return
214 }
215 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
216 if err != nil {
217 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
218 return
219 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700220 prefix := []byte("structured logs:")
221 for line := range bytes.Lines(out) {
222 rest, ok := bytes.CutPrefix(line, prefix)
223 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700224 continue
225 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700226 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700227 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
228 logFileName := filepath.Base(logFile)
229 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
230 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
231 if err != nil {
232 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
233 }
234 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
235 }
236 }
237
238 // NOTE: we want to see what the internal sketch binary prints
239 // regardless of the setting of the verbosity flag on the external
240 // binary, so reading "docker logs", which is the stdout/stderr of
241 // the internal binary is not conditional on the verbose flag.
242 appendInternalErr := func(err error) error {
243 if err == nil {
244 return nil
245 }
246 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000247 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700248 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
249 }
250 out = bytes.TrimSpace(out)
251 if len(out) > 0 {
252 return fmt.Errorf("docker logs: %s;\n%w", out, err)
253 }
254 return err
255 }
256
257 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700258 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700259 if err != nil {
260 return appendInternalErr(err)
261 }
262
Sean McCulloughae3480f2025-04-23 15:28:20 -0700263 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
264 if err != nil {
265 return appendInternalErr(err)
266 }
267 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
268 if err != nil {
Sean McCullough4854c652025-04-24 18:37:02 -0700269 return appendInternalErr(fmt.Errorf("Error splitting ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700270 }
Sean McCullough4854c652025-04-24 18:37:02 -0700271
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700272 var sshServerIdentity, sshUserIdentity []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700273
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700274 if err := CheckForInclude(); err != nil {
275 fmt.Println(err.Error())
276 // continue - ssh config is not required for the rest of sketch to function locally.
277 } else {
278 cst, err := NewSSHTheather(cntrName, sshHost, sshPort)
279 if err != nil {
280 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
281 }
282
Sean McCulloughea3fc202025-04-28 12:53:37 -0700283 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
284 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700285 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700286🖥️ ssh %s
287🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700288🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700289`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700290 sshUserIdentity = cst.userIdentity
291 sshServerIdentity = cst.serverIdentity
292 defer func() {
293 if err := cst.Cleanup(); err != nil {
294 appendInternalErr(err)
295 }
296 }()
297 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700298
Earl Lee2e463fb2025-04-17 11:22:22 -0700299 // Tell the sketch container which git server port and commit to initialize with.
300 go func() {
301 // TODO: Why is this called in a goroutine? I have found that when I pull this out
302 // of the goroutine and call it inline, then the terminal UI clears itself and all
303 // the scrollback (which is not good, but also not fatal). I can't see why it does this
304 // though, since none of the calls in postContainerInitConfig obviously write to stdout
305 // or stderr.
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700306 if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, sshServerIdentity, sshUserIdentity); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700307 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
308 errCh <- appendInternalErr(err)
309 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700310
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700311 // We open the browser after the init config because the above waits for the web server to be serving.
312 if config.OpenBrowser {
313 if config.SkabandAddr != "" {
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +0000314 browser.Open(ctx, fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID))
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700315 } else {
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +0000316 browser.Open(ctx, "http://"+localAddr)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700317 }
318 }
319 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700320
321 go func() {
322 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
323 cmd.Stdin = os.Stdin
324 cmd.Stdout = os.Stdout
325 cmd.Stderr = os.Stderr
326 errCh <- run(ctx, "docker attach", cmd)
327 }()
328
329 defer copyLogs()
330
331 for {
332 select {
333 case <-ctx.Done():
334 return ctx.Err()
335 case err := <-errCh:
336 if err != nil {
337 return appendInternalErr(fmt.Errorf("container process: %w", err))
338 }
339 return nil
340 }
341 }
342}
343
344func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
345 cmd := exec.CommandContext(ctx, cmdName, args...)
346 // Really only needed for the "go build" command for the linux sketch binary
347 cmd.Env = append(os.Environ(), "GOOS=linux", "CGO_ENABLED=0")
348 start := time.Now()
349
350 out, err := cmd.CombinedOutput()
351 if err != nil {
352 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))))
353 } else {
354 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))))
355 }
356 return out, err
357}
358
359func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
360 start := time.Now()
361 err := cmd.Run()
362 if err != nil {
363 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))))
364 } else {
365 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))))
366 }
367 return err
368}
369
370type gitServer struct {
371 gitLn net.Listener
372 gitPort string
373 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700374 pass string
Earl Lee2e463fb2025-04-17 11:22:22 -0700375}
376
377func (gs *gitServer) shutdown(ctx context.Context) {
378 gs.srv.Shutdown(ctx)
379 gs.gitLn.Close()
380}
381
382// Serve a git remote from the host for the container to fetch from and push to.
383func (gs *gitServer) serve(ctx context.Context) error {
384 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
385 return gs.srv.Serve(gs.gitLn)
386}
387
388func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700389 ret := &gitServer{
390 pass: rand.Text(),
391 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700392
Earl Lee2e463fb2025-04-17 11:22:22 -0700393 gitLn, err := net.Listen("tcp4", ":0")
394 if err != nil {
395 return nil, fmt.Errorf("git listen: %w", err)
396 }
397 ret.gitLn = gitLn
398
399 srv := http.Server{
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700400 Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass)},
Earl Lee2e463fb2025-04-17 11:22:22 -0700401 }
402 ret.srv = &srv
403
404 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
405 if err != nil {
406 return nil, fmt.Errorf("git port: %w", err)
407 }
408 ret.gitPort = gitPort
409 return ret, nil
410}
411
412func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
413 //, config.SessionID, config.GitUsername, config.GitEmail, config.SkabandAddr
414 // sessionID, gitUsername, gitEmail, skabandAddr string
David Crawshaw69c67312025-04-17 13:42:00 -0700415 cmdArgs := []string{
416 "create",
Earl Lee2e463fb2025-04-17 11:22:22 -0700417 "-it",
418 "--name", cntrName,
419 "-p", hostPort + ":80", // forward container port 80 to a host port
420 "-e", "ANTHROPIC_API_KEY=" + config.AntAPIKey,
421 }
422 if config.AntURL != "" {
423 cmdArgs = append(cmdArgs, "-e", "ANT_URL="+config.AntURL)
424 }
425 if config.SketchPubKey != "" {
426 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
427 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700428 if config.SSHPort > 0 {
429 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
430 } else {
431 cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700432 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700433 if relPath != "." {
434 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
435 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700436 // colima does this by default, but Linux docker seems to need this set explicitly
437 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700438 cmdArgs = append(
439 cmdArgs,
440 imgName,
441 "/bin/sketch",
442 "-unsafe",
443 "-addr=:80",
444 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000445 "-git-username="+config.GitUsername,
446 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000447 "-outside-hostname="+config.OutsideHostname,
448 "-outside-os="+config.OutsideOS,
449 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700450 "-open=false",
Earl Lee2e463fb2025-04-17 11:22:22 -0700451 )
452 if config.SkabandAddr != "" {
453 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
454 }
Pokey Rule0dcebe12025-04-28 14:51:04 +0100455 if config.Prompt != "" {
456 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
457 }
458 if config.OneShot {
459 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700460 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700461 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
462 return fmt.Errorf("docker create: %s, %w", out, err)
463 }
464 return nil
465}
466
467func buildLinuxSketchBin(ctx context.Context, path string) (string, error) {
David Crawshaw8a617cb2025-04-18 01:28:43 -0700468 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700469 if err != nil {
470 return "", err
471 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700472 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
473 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
474 return "", err
475 }
476
477 verToInstall := "@latest"
478 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
479 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
480 } else {
481 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700482 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700483 verToInstall = ""
484 }
485 }
David Crawshaw69c67312025-04-17 13:42:00 -0700486
Earl Lee2e463fb2025-04-17 11:22:22 -0700487 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700488 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700489 cmd.Env = append(
490 os.Environ(),
491 "GOOS=linux",
492 "CGO_ENABLED=0",
493 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700494 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700495 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700496 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700497
Earl Lee2e463fb2025-04-17 11:22:22 -0700498 out, err := cmd.CombinedOutput()
499 if err != nil {
500 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))))
501 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
502 } else {
503 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))))
504 }
505
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700506 var src string
507 if runtime.GOOS != "linux" {
508 src = filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch")
509 } else {
510 // If we are already on Linux, there's no extra platform name in the path
511 src = filepath.Join(linuxGopath, "bin", "sketch")
512 }
513
David Crawshaw69c67312025-04-17 13:42:00 -0700514 dst := filepath.Join(path, "tmp-sketch-binary-linux")
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700515 if err := moveFile(src, dst); err != nil {
David Crawshaw69c67312025-04-17 13:42:00 -0700516 return "", err
517 }
518
David Crawshaw69c67312025-04-17 13:42:00 -0700519 return dst, nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700520}
521
Sean McCulloughae3480f2025-04-23 15:28:20 -0700522func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700523 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700524 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700525 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
526 } else {
527 v4, _, found := strings.Cut(string(out), "\n")
528 if !found {
529 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
530 }
531 localAddr = v4
532 if strings.HasPrefix(localAddr, "0.0.0.0") {
533 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
534 }
535 }
536 return localAddr, nil
537}
538
539// Contact the container and configure it.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700540func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshServerIdentity, sshAuthorizedKeys []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700541 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700542
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000543 // Check if SSH is available by checking for the Include directive in ~/.ssh/config
544 sshAvailable := true
545 sshError := ""
546 if err := CheckForInclude(); err != nil {
547 sshAvailable = false
548 sshError = err.Error()
549 }
550
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700551 initMsg, err := json.Marshal(
552 server.InitRequest{
553 Commit: commit,
554 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
555 HostAddr: localAddr,
556 SSHAuthorizedKeys: sshAuthorizedKeys,
557 SSHServerIdentity: sshServerIdentity,
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000558 SSHAvailable: sshAvailable,
559 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700560 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700561 if err != nil {
562 return fmt.Errorf("init msg: %w", err)
563 }
564
Earl Lee2e463fb2025-04-17 11:22:22 -0700565 // Note: this /init POST is handled in loop/server/loophttp.go:
566 initMsgByteReader := bytes.NewReader(initMsg)
567 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
568 if err != nil {
569 return err
570 }
571
572 var res *http.Response
573 for i := 0; ; i++ {
574 time.Sleep(100 * time.Millisecond)
575 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
576 initMsgByteReader.Reset(initMsg)
577 res, err = http.DefaultClient.Do(req)
578 if err != nil {
579 // In addition to "connection refused", we also occasionally see "EOF" errors that can succeed on retries.
580 if i < 100 && (strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "EOF")) {
581 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
582 continue
583 }
584 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
585 }
586 break
587 }
588 resBytes, _ := io.ReadAll(res.Body)
589 if res.StatusCode != http.StatusOK {
590 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
591 }
592 return nil
593}
594
595func findOrBuildDockerImage(ctx context.Context, stdout, stderr io.Writer, cwd, gitRoot, antURL, antAPIKey string, forceRebuild bool) (imgName string, err error) {
596 h := sha256.Sum256([]byte(gitRoot))
597 imgName = "sketch-" + hex.EncodeToString(h[:6])
598
599 var curImgInitFilesHash string
600 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
601 if strings.Contains(string(out), "No such object") {
602 // Image does not exist, continue and build it.
603 curImgInitFilesHash = ""
604 } else {
605 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
606 }
607 } else {
608 m := map[string]string{}
609 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
610 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
611 }
612 curImgInitFilesHash = m["sketch_context"]
613 }
614
615 candidates, err := findRepoDockerfiles(cwd, gitRoot)
616 if err != nil {
617 return "", fmt.Errorf("find dockerfile: %w", err)
618 }
619
620 var initFiles map[string]string
621 var dockerfilePath string
622
623 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
624 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
625 dockerfilePath = candidates[0]
626 contents, err := os.ReadFile(dockerfilePath)
627 if err != nil {
628 return "", err
629 }
630 fmt.Printf("using %s as dev env\n", candidates[0])
631 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700632 return imgName, nil
633 }
634 } else {
635 initFiles, err = readInitFiles(os.DirFS(gitRoot))
636 if err != nil {
637 return "", err
638 }
639 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
640 if err != nil {
641 return "", err
642 }
643 initFileHash := hashInitFiles(initFiles)
644 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700645 return imgName, nil
646 }
647
648 start := time.Now()
649 dockerfile, err := createDockerfile(ctx, http.DefaultClient, antURL, antAPIKey, initFiles, subPathWorkingDir)
650 if err != nil {
651 return "", fmt.Errorf("create dockerfile: %w", err)
652 }
653 dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile")
654 if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil {
655 return "", err
656 }
657 defer os.Remove(dockerfilePath)
658
659 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))
660 }
661
662 var gitUserEmail, gitUserName string
663 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
664 return "", fmt.Errorf("git config: %s: %v", out, err)
665 } else {
666 gitUserEmail = strings.TrimSpace(string(out))
667 }
668 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
669 return "", fmt.Errorf("git config: %s: %v", out, err)
670 } else {
671 gitUserName = strings.TrimSpace(string(out))
672 }
673
674 start := time.Now()
675 cmd := exec.CommandContext(ctx,
676 "docker", "build",
677 "-t", imgName,
678 "-f", dockerfilePath,
679 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
680 "--build-arg", "GIT_USER_NAME="+gitUserName,
681 ".",
682 )
683 cmd.Dir = gitRoot
684 cmd.Stdout = stdout
685 cmd.Stderr = stderr
Josh Bleecher Snyderdf2d3dc2025-04-25 12:31:35 -0700686 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Philip Zeyligere4fa0e32025-04-23 14:15:55 -0700687 dockerfileContent, err := os.ReadFile(dockerfilePath)
688 if err != nil {
689 return "", fmt.Errorf("failed to read Dockerfile: %w", err)
690 }
Philip Zeyliger5d6af872025-04-23 19:48:34 -0700691 fmt.Fprintf(stdout, "Dockerfile:\n%s\n", string(dockerfileContent))
Earl Lee2e463fb2025-04-17 11:22:22 -0700692
693 err = run(ctx, "docker build", cmd)
694 if err != nil {
695 return "", fmt.Errorf("docker build failed: %v", err)
696 }
697 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
698 return imgName, nil
699}
700
701func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
702 files, err := findDirDockerfiles(cwd)
703 if err != nil {
704 return nil, err
705 }
706 if len(files) > 0 {
707 return files, nil
708 }
709
710 path := cwd
711 for path != gitRoot {
712 path = filepath.Dir(path)
713 files, err := findDirDockerfiles(path)
714 if err != nil {
715 return nil, err
716 }
717 if len(files) > 0 {
718 return files, nil
719 }
720 }
721 return files, nil
722}
723
724// findDirDockerfiles finds all "Dockerfile*" files in a directory.
725func findDirDockerfiles(root string) (res []string, err error) {
726 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
727 if err != nil {
728 return err
729 }
730 if info.IsDir() && root != path {
731 return filepath.SkipDir
732 }
733 name := strings.ToLower(info.Name())
734 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
735 res = append(res, path)
736 }
737 return nil
738 })
739 if err != nil {
740 return nil, err
741 }
742 return res, nil
743}
744
745func findGitRoot(ctx context.Context, path string) (string, error) {
746 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
747 cmd.Dir = path
748 out, err := cmd.CombinedOutput()
749 if err != nil {
750 if strings.Contains(string(out), "not a git repository") {
751 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
752Consider one of the following options:
753 - cd to a different dir that is already part of a git repo first, or
754 - to create a new git repo from this directory (%s), run this command:
755
756 git init . && git commit --allow-empty -m "initial commit"
757
758and try running sketch again.
759`, path, path)
760 }
761 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
762 }
763 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
764 absGitDir := filepath.Join(path, gitDir)
765 return filepath.Dir(absGitDir), err
766}
767
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700768// moveFile is like Python's shutil.move, in that it tries a rename, and, if that fails,
769// copies and deletes
770func moveFile(src, dst string) error {
771 if err := os.Rename(src, dst); err == nil {
772 return nil
773 }
774
775 stat, err := os.Stat(src)
776 if err != nil {
777 return err
778 }
779
780 sourceFile, err := os.Open(src)
781 if err != nil {
782 return err
783 }
784 defer sourceFile.Close()
785
786 destFile, err := os.Create(dst)
787 if err != nil {
788 return err
789 }
790 defer destFile.Close()
791
792 _, err = io.Copy(destFile, sourceFile)
793 if err != nil {
794 return err
795 }
796
797 sourceFile.Close()
798 destFile.Close()
799
800 os.Chmod(dst, stat.Mode())
801
802 return os.Remove(src)
803}