blob: 292c8b6e021b83354935c3d2b7e3d8edafb1db02 [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 {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000180 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700181 }
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 Snydere54b00a2025-04-30 16:48:02 -0700314 browser.Open(fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID))
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700315 } else {
Josh Bleecher Snydere54b00a2025-04-30 16:48:02 -0700316 browser.Open("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
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000399 browserC := make(chan string, 1) // channel of URLs to open in browser
400 go func() {
401 for url := range browserC {
402 browser.Open(url)
403 }
404 }()
405
406 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700407 ret.srv = &srv
408
409 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
410 if err != nil {
411 return nil, fmt.Errorf("git port: %w", err)
412 }
413 ret.gitPort = gitPort
414 return ret, nil
415}
416
417func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700418 cmdArgs := []string{
419 "create",
Earl Lee2e463fb2025-04-17 11:22:22 -0700420 "-it",
421 "--name", cntrName,
422 "-p", hostPort + ":80", // forward container port 80 to a host port
423 "-e", "ANTHROPIC_API_KEY=" + config.AntAPIKey,
424 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000425
426 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
427 cmdArgs = append(cmdArgs, "-e", envVar)
428 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700429 if config.AntURL != "" {
430 cmdArgs = append(cmdArgs, "-e", "ANT_URL="+config.AntURL)
431 }
432 if config.SketchPubKey != "" {
433 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
434 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700435 if config.SSHPort > 0 {
436 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
437 } else {
438 cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700439 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700440 if relPath != "." {
441 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
442 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700443 // colima does this by default, but Linux docker seems to need this set explicitly
444 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700445 cmdArgs = append(
446 cmdArgs,
447 imgName,
448 "/bin/sketch",
449 "-unsafe",
450 "-addr=:80",
451 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000452 "-git-username="+config.GitUsername,
453 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000454 "-outside-hostname="+config.OutsideHostname,
455 "-outside-os="+config.OutsideOS,
456 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700457 "-open=false",
Earl Lee2e463fb2025-04-17 11:22:22 -0700458 )
459 if config.SkabandAddr != "" {
460 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
461 }
Pokey Rule0dcebe12025-04-28 14:51:04 +0100462 if config.Prompt != "" {
463 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
464 }
465 if config.OneShot {
466 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700467 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700468 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
469 return fmt.Errorf("docker create: %s, %w", out, err)
470 }
471 return nil
472}
473
474func buildLinuxSketchBin(ctx context.Context, path string) (string, error) {
David Crawshaw8a617cb2025-04-18 01:28:43 -0700475 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700476 if err != nil {
477 return "", err
478 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700479 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
480 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
481 return "", err
482 }
483
484 verToInstall := "@latest"
485 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
486 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
487 } else {
488 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700489 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700490 verToInstall = ""
491 }
492 }
David Crawshaw69c67312025-04-17 13:42:00 -0700493
Earl Lee2e463fb2025-04-17 11:22:22 -0700494 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700495 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700496 cmd.Env = append(
497 os.Environ(),
498 "GOOS=linux",
499 "CGO_ENABLED=0",
500 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700501 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700502 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700503 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700504
Earl Lee2e463fb2025-04-17 11:22:22 -0700505 out, err := cmd.CombinedOutput()
506 if err != nil {
507 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))))
508 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
509 } else {
510 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))))
511 }
512
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700513 var src string
514 if runtime.GOOS != "linux" {
515 src = filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch")
516 } else {
517 // If we are already on Linux, there's no extra platform name in the path
518 src = filepath.Join(linuxGopath, "bin", "sketch")
519 }
520
David Crawshaw69c67312025-04-17 13:42:00 -0700521 dst := filepath.Join(path, "tmp-sketch-binary-linux")
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700522 if err := moveFile(src, dst); err != nil {
David Crawshaw69c67312025-04-17 13:42:00 -0700523 return "", err
524 }
525
David Crawshaw69c67312025-04-17 13:42:00 -0700526 return dst, nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700527}
528
Sean McCulloughae3480f2025-04-23 15:28:20 -0700529func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700530 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700531 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700532 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
533 } else {
534 v4, _, found := strings.Cut(string(out), "\n")
535 if !found {
536 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
537 }
538 localAddr = v4
539 if strings.HasPrefix(localAddr, "0.0.0.0") {
540 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
541 }
542 }
543 return localAddr, nil
544}
545
546// Contact the container and configure it.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700547func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshServerIdentity, sshAuthorizedKeys []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700548 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700549
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000550 // Check if SSH is available by checking for the Include directive in ~/.ssh/config
551 sshAvailable := true
552 sshError := ""
553 if err := CheckForInclude(); err != nil {
554 sshAvailable = false
555 sshError = err.Error()
556 }
557
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700558 initMsg, err := json.Marshal(
559 server.InitRequest{
560 Commit: commit,
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000561 OutsideHTTP: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitPass, gitPort),
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700562 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
563 HostAddr: localAddr,
564 SSHAuthorizedKeys: sshAuthorizedKeys,
565 SSHServerIdentity: sshServerIdentity,
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000566 SSHAvailable: sshAvailable,
567 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700568 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700569 if err != nil {
570 return fmt.Errorf("init msg: %w", err)
571 }
572
Earl Lee2e463fb2025-04-17 11:22:22 -0700573 // Note: this /init POST is handled in loop/server/loophttp.go:
574 initMsgByteReader := bytes.NewReader(initMsg)
575 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
576 if err != nil {
577 return err
578 }
579
580 var res *http.Response
581 for i := 0; ; i++ {
582 time.Sleep(100 * time.Millisecond)
583 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
584 initMsgByteReader.Reset(initMsg)
585 res, err = http.DefaultClient.Do(req)
586 if err != nil {
587 // In addition to "connection refused", we also occasionally see "EOF" errors that can succeed on retries.
588 if i < 100 && (strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "EOF")) {
589 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
590 continue
591 }
592 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
593 }
594 break
595 }
596 resBytes, _ := io.ReadAll(res.Body)
597 if res.StatusCode != http.StatusOK {
598 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
599 }
600 return nil
601}
602
603func findOrBuildDockerImage(ctx context.Context, stdout, stderr io.Writer, cwd, gitRoot, antURL, antAPIKey string, forceRebuild bool) (imgName string, err error) {
604 h := sha256.Sum256([]byte(gitRoot))
605 imgName = "sketch-" + hex.EncodeToString(h[:6])
606
607 var curImgInitFilesHash string
608 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
609 if strings.Contains(string(out), "No such object") {
610 // Image does not exist, continue and build it.
611 curImgInitFilesHash = ""
612 } else {
613 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
614 }
615 } else {
616 m := map[string]string{}
617 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
618 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
619 }
620 curImgInitFilesHash = m["sketch_context"]
621 }
622
623 candidates, err := findRepoDockerfiles(cwd, gitRoot)
624 if err != nil {
625 return "", fmt.Errorf("find dockerfile: %w", err)
626 }
627
628 var initFiles map[string]string
629 var dockerfilePath string
630
631 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
632 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
633 dockerfilePath = candidates[0]
634 contents, err := os.ReadFile(dockerfilePath)
635 if err != nil {
636 return "", err
637 }
638 fmt.Printf("using %s as dev env\n", candidates[0])
639 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700640 return imgName, nil
641 }
642 } else {
643 initFiles, err = readInitFiles(os.DirFS(gitRoot))
644 if err != nil {
645 return "", err
646 }
647 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
648 if err != nil {
649 return "", err
650 }
651 initFileHash := hashInitFiles(initFiles)
652 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700653 return imgName, nil
654 }
655
656 start := time.Now()
657 dockerfile, err := createDockerfile(ctx, http.DefaultClient, antURL, antAPIKey, initFiles, subPathWorkingDir)
658 if err != nil {
659 return "", fmt.Errorf("create dockerfile: %w", err)
660 }
661 dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile")
662 if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil {
663 return "", err
664 }
665 defer os.Remove(dockerfilePath)
666
667 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))
668 }
669
670 var gitUserEmail, gitUserName string
671 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
672 return "", fmt.Errorf("git config: %s: %v", out, err)
673 } else {
674 gitUserEmail = strings.TrimSpace(string(out))
675 }
676 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
677 return "", fmt.Errorf("git config: %s: %v", out, err)
678 } else {
679 gitUserName = strings.TrimSpace(string(out))
680 }
681
682 start := time.Now()
683 cmd := exec.CommandContext(ctx,
684 "docker", "build",
685 "-t", imgName,
686 "-f", dockerfilePath,
687 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
688 "--build-arg", "GIT_USER_NAME="+gitUserName,
689 ".",
690 )
691 cmd.Dir = gitRoot
692 cmd.Stdout = stdout
693 cmd.Stderr = stderr
Josh Bleecher Snyderdf2d3dc2025-04-25 12:31:35 -0700694 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Philip Zeyligere4fa0e32025-04-23 14:15:55 -0700695 dockerfileContent, err := os.ReadFile(dockerfilePath)
696 if err != nil {
697 return "", fmt.Errorf("failed to read Dockerfile: %w", err)
698 }
David Crawshaw5228b582025-05-01 11:18:12 -0700699 // TODO: this is sometimes a repeat of earlier. Remove the earlier call?
Philip Zeyliger5d6af872025-04-23 19:48:34 -0700700 fmt.Fprintf(stdout, "Dockerfile:\n%s\n", string(dockerfileContent))
Earl Lee2e463fb2025-04-17 11:22:22 -0700701
702 err = run(ctx, "docker build", cmd)
703 if err != nil {
704 return "", fmt.Errorf("docker build failed: %v", err)
705 }
706 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
707 return imgName, nil
708}
709
710func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
711 files, err := findDirDockerfiles(cwd)
712 if err != nil {
713 return nil, err
714 }
715 if len(files) > 0 {
716 return files, nil
717 }
718
719 path := cwd
720 for path != gitRoot {
721 path = filepath.Dir(path)
722 files, err := findDirDockerfiles(path)
723 if err != nil {
724 return nil, err
725 }
726 if len(files) > 0 {
727 return files, nil
728 }
729 }
730 return files, nil
731}
732
733// findDirDockerfiles finds all "Dockerfile*" files in a directory.
734func findDirDockerfiles(root string) (res []string, err error) {
735 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
736 if err != nil {
737 return err
738 }
739 if info.IsDir() && root != path {
740 return filepath.SkipDir
741 }
742 name := strings.ToLower(info.Name())
743 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
744 res = append(res, path)
745 }
746 return nil
747 })
748 if err != nil {
749 return nil, err
750 }
751 return res, nil
752}
753
754func findGitRoot(ctx context.Context, path string) (string, error) {
755 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
756 cmd.Dir = path
757 out, err := cmd.CombinedOutput()
758 if err != nil {
759 if strings.Contains(string(out), "not a git repository") {
760 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
761Consider one of the following options:
762 - cd to a different dir that is already part of a git repo first, or
763 - to create a new git repo from this directory (%s), run this command:
764
765 git init . && git commit --allow-empty -m "initial commit"
766
767and try running sketch again.
768`, path, path)
769 }
770 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
771 }
772 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
773 absGitDir := filepath.Join(path, gitDir)
774 return filepath.Dir(absGitDir), err
775}
776
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700777// moveFile is like Python's shutil.move, in that it tries a rename, and, if that fails,
778// copies and deletes
779func moveFile(src, dst string) error {
780 if err := os.Rename(src, dst); err == nil {
781 return nil
782 }
783
784 stat, err := os.Stat(src)
785 if err != nil {
786 return err
787 }
788
789 sourceFile, err := os.Open(src)
790 if err != nil {
791 return err
792 }
793 defer sourceFile.Close()
794
795 destFile, err := os.Create(dst)
796 if err != nil {
797 return err
798 }
799 defer destFile.Close()
800
801 _, err = io.Copy(destFile, sourceFile)
802 if err != nil {
803 return err
804 }
805
806 sourceFile.Close()
807 destFile.Close()
808
809 os.Chmod(dst, stat.Mode())
810
811 return os.Remove(src)
812}
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000813
814// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
815// from git config using the sketch.envfwd multi-valued key.
816func getEnvForwardingFromGitConfig(ctx context.Context) []string {
817 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
818 out := string(outb)
819 if err != nil {
820 if strings.Contains(out, "key does not exist") {
821 return nil
822 }
823 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
824 return nil
825 }
826
827 var envVars []string
828 for envVar := range strings.Lines(out) {
829 envVar = strings.TrimSpace(envVar)
830 if envVar == "" {
831 continue
832 }
833 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
834 }
835 return envVars
836}