blob: 1fabafcd8a15064171658a73b4cb9d7b608a5eef [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"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070024 "sketch.dev/llm/ant"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070025 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070026 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070027 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070028)
29
30// ContainerConfig holds all configuration for launching a container
31type ContainerConfig struct {
32 // SessionID is the unique identifier for this session
33 SessionID string
34
35 // LocalAddr is the initial address to use (though it may be overwritten later)
36 LocalAddr string
37
38 // SkabandAddr is the address of the skaband service if available
39 SkabandAddr string
40
41 // AntURL is the URL of the LLM service.
42 AntURL string
43
44 // AntAPIKey is the API key for LLM service.
45 AntAPIKey string
46
47 // Path is the local filesystem path to use
48 Path string
49
50 // GitUsername is the username to use for git operations
51 GitUsername string
52
53 // GitEmail is the email to use for git operations
54 GitEmail string
55
56 // OpenBrowser determines whether to open a browser automatically
57 OpenBrowser bool
58
59 // NoCleanup prevents container cleanup when set to true
60 NoCleanup bool
61
62 // ForceRebuild forces rebuilding of the Docker image even if it exists
63 ForceRebuild bool
64
65 // Host directory to copy container logs into, if not set to ""
66 ContainerLogDest string
67
68 // Path to pre-built linux sketch binary, or build a new one if set to ""
69 SketchBinaryLinux string
70
71 // Sketch client public key.
72 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000073
Sean McCulloughbaa2b592025-04-23 10:40:08 -070074 // Host port for the container's ssh server
75 SSHPort int
76
Philip Zeyliger18532b22025-04-23 21:11:46 +000077 // Outside information to pass to the container
78 OutsideHostname string
79 OutsideOS string
80 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070081
Pokey Rule0dcebe12025-04-28 14:51:04 +010082 // If true, exit after the first turn
83 OneShot bool
84
85 // Initial prompt
86 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000087
88 // Initial commit to use as starting point
89 InitialCommit string
Earl Lee2e463fb2025-04-17 11:22:22 -070090}
91
92// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
93// It writes status to stdout.
94func LaunchContainer(ctx context.Context, stdout, stderr io.Writer, config ContainerConfig) error {
95 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -070096 if runtime.GOOS == "darwin" {
97 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
98 } else {
99 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
100 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700101 }
102
103 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
104 // `docker ps` provides a good error message here that can be
105 // easily chatgpt'ed by users, so send it to the user as-is:
106 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
107 return fmt.Errorf("docker ps: %s (%w)", out, err)
108 }
109
110 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
111 if err != nil {
112 return err
113 }
114
115 gitRoot, err := findGitRoot(ctx, config.Path)
116 if err != nil {
117 return err
118 }
119
120 imgName, err := findOrBuildDockerImage(ctx, stdout, stderr, config.Path, gitRoot, config.AntURL, config.AntAPIKey, config.ForceRebuild)
121 if err != nil {
122 return err
123 }
124
125 linuxSketchBin := config.SketchBinaryLinux
126 if linuxSketchBin == "" {
127 linuxSketchBin, err = buildLinuxSketchBin(ctx, config.Path)
128 if err != nil {
129 return err
130 }
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 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700187
188 // Make sure that the webui is built so we can copy the results to the container.
189 _, err = webui.Build()
190 if err != nil {
191 return fmt.Errorf("failed to build webui: %w", err)
192 }
193
David Crawshaw8bff16a2025-04-18 01:16:49 -0700194 webuiZipPath, err := webui.ZipPath()
195 if err != nil {
196 return err
197 }
198 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
199 return fmt.Errorf("docker cp: %s, %w", out, err)
200 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700201
David Crawshaw53786ef2025-04-24 12:52:51 -0700202 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700203
204 // Start the sketch container
205 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
206 return fmt.Errorf("docker start: %s, %w", out, err)
207 }
208
209 // Copies structured logs from the container to the host.
210 copyLogs := func() {
211 if config.ContainerLogDest == "" {
212 return
213 }
214 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
215 if err != nil {
216 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
217 return
218 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700219 prefix := []byte("structured logs:")
220 for line := range bytes.Lines(out) {
221 rest, ok := bytes.CutPrefix(line, prefix)
222 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700223 continue
224 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700225 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700226 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
227 logFileName := filepath.Base(logFile)
228 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
229 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
230 if err != nil {
231 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
232 }
233 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
234 }
235 }
236
237 // NOTE: we want to see what the internal sketch binary prints
238 // regardless of the setting of the verbosity flag on the external
239 // binary, so reading "docker logs", which is the stdout/stderr of
240 // the internal binary is not conditional on the verbose flag.
241 appendInternalErr := func(err error) error {
242 if err == nil {
243 return nil
244 }
245 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000246 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700247 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
248 }
249 out = bytes.TrimSpace(out)
250 if len(out) > 0 {
251 return fmt.Errorf("docker logs: %s;\n%w", out, err)
252 }
253 return err
254 }
255
256 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700257 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700258 if err != nil {
259 return appendInternalErr(err)
260 }
261
Sean McCulloughae3480f2025-04-23 15:28:20 -0700262 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
263 if err != nil {
264 return appendInternalErr(err)
265 }
266 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
267 if err != nil {
Sean McCullough4854c652025-04-24 18:37:02 -0700268 return appendInternalErr(fmt.Errorf("Error splitting ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700269 }
Sean McCullough4854c652025-04-24 18:37:02 -0700270
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700271 var sshServerIdentity, sshUserIdentity []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700272
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700273 if err := CheckForInclude(); err != nil {
274 fmt.Println(err.Error())
275 // continue - ssh config is not required for the rest of sketch to function locally.
276 } else {
277 cst, err := NewSSHTheather(cntrName, sshHost, sshPort)
278 if err != nil {
279 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
280 }
281
Sean McCulloughea3fc202025-04-28 12:53:37 -0700282 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
283 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700284 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700285🖥️ ssh %s
286🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700287🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700288`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700289 sshUserIdentity = cst.userIdentity
290 sshServerIdentity = cst.serverIdentity
291 defer func() {
292 if err := cst.Cleanup(); err != nil {
293 appendInternalErr(err)
294 }
295 }()
296 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700297
Earl Lee2e463fb2025-04-17 11:22:22 -0700298 // Tell the sketch container which git server port and commit to initialize with.
299 go func() {
300 // TODO: Why is this called in a goroutine? I have found that when I pull this out
301 // of the goroutine and call it inline, then the terminal UI clears itself and all
302 // the scrollback (which is not good, but also not fatal). I can't see why it does this
303 // though, since none of the calls in postContainerInitConfig obviously write to stdout
304 // or stderr.
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700305 if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, sshServerIdentity, sshUserIdentity); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700306 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
307 errCh <- appendInternalErr(err)
308 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700309
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700310 // We open the browser after the init config because the above waits for the web server to be serving.
311 if config.OpenBrowser {
312 if config.SkabandAddr != "" {
Josh Bleecher Snydere54b00a2025-04-30 16:48:02 -0700313 browser.Open(fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID))
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700314 } else {
Josh Bleecher Snydere54b00a2025-04-30 16:48:02 -0700315 browser.Open("http://" + localAddr)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700316 }
317 }
318 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700319
320 go func() {
321 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
322 cmd.Stdin = os.Stdin
323 cmd.Stdout = os.Stdout
324 cmd.Stderr = os.Stderr
325 errCh <- run(ctx, "docker attach", cmd)
326 }()
327
328 defer copyLogs()
329
330 for {
331 select {
332 case <-ctx.Done():
333 return ctx.Err()
334 case err := <-errCh:
335 if err != nil {
336 return appendInternalErr(fmt.Errorf("container process: %w", err))
337 }
338 return nil
339 }
340 }
341}
342
343func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
344 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700345 start := time.Now()
346
347 out, err := cmd.CombinedOutput()
348 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700349 slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700350 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700351 slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700352 }
353 return out, err
354}
355
356func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
357 start := time.Now()
358 err := cmd.Run()
359 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700360 slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700361 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700362 slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700363 }
364 return err
365}
366
367type gitServer struct {
368 gitLn net.Listener
369 gitPort string
370 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700371 pass string
Earl Lee2e463fb2025-04-17 11:22:22 -0700372}
373
374func (gs *gitServer) shutdown(ctx context.Context) {
375 gs.srv.Shutdown(ctx)
376 gs.gitLn.Close()
377}
378
379// Serve a git remote from the host for the container to fetch from and push to.
380func (gs *gitServer) serve(ctx context.Context) error {
381 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
382 return gs.srv.Serve(gs.gitLn)
383}
384
385func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700386 ret := &gitServer{
387 pass: rand.Text(),
388 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700389
Earl Lee2e463fb2025-04-17 11:22:22 -0700390 gitLn, err := net.Listen("tcp4", ":0")
391 if err != nil {
392 return nil, fmt.Errorf("git listen: %w", err)
393 }
394 ret.gitLn = gitLn
395
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000396 browserC := make(chan string, 1) // channel of URLs to open in browser
397 go func() {
398 for url := range browserC {
399 browser.Open(url)
400 }
401 }()
402
403 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700404 ret.srv = &srv
405
406 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
407 if err != nil {
408 return nil, fmt.Errorf("git port: %w", err)
409 }
410 ret.gitPort = gitPort
411 return ret, nil
412}
413
414func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
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
Philip Zeyliger6234a8d2025-05-02 14:31:20 -0700420 "-e", "SKETCH_ANTHROPIC_API_KEY=" + config.AntAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700421 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000422
423 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
424 cmdArgs = append(cmdArgs, "-e", envVar)
425 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700426 if config.AntURL != "" {
Philip Zeyliger6234a8d2025-05-02 14:31:20 -0700427 cmdArgs = append(cmdArgs, "-e", "SKETCH_ANT_URL="+config.AntURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700428 }
429 if config.SketchPubKey != "" {
430 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
431 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700432 if config.SSHPort > 0 {
433 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
434 } else {
435 cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700436 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700437 if relPath != "." {
438 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
439 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700440 // colima does this by default, but Linux docker seems to need this set explicitly
441 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700442 cmdArgs = append(
443 cmdArgs,
444 imgName,
445 "/bin/sketch",
446 "-unsafe",
447 "-addr=:80",
448 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000449 "-git-username="+config.GitUsername,
450 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000451 "-outside-hostname="+config.OutsideHostname,
452 "-outside-os="+config.OutsideOS,
453 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700454 "-open=false",
Earl Lee2e463fb2025-04-17 11:22:22 -0700455 )
456 if config.SkabandAddr != "" {
457 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
458 }
Pokey Rule0dcebe12025-04-28 14:51:04 +0100459 if config.Prompt != "" {
460 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
461 }
462 if config.OneShot {
463 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700464 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700465 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
466 return fmt.Errorf("docker create: %s, %w", out, err)
467 }
468 return nil
469}
470
471func buildLinuxSketchBin(ctx context.Context, path string) (string, error) {
David Crawshaw8a617cb2025-04-18 01:28:43 -0700472 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700473 if err != nil {
474 return "", err
475 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700476 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
477 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
478 return "", err
479 }
480
481 verToInstall := "@latest"
482 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
483 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
484 } else {
485 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700486 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700487 verToInstall = ""
488 }
489 }
David Crawshaw69c67312025-04-17 13:42:00 -0700490
Earl Lee2e463fb2025-04-17 11:22:22 -0700491 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700492 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700493 cmd.Env = append(
494 os.Environ(),
495 "GOOS=linux",
496 "CGO_ENABLED=0",
497 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700498 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700499 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700500 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700501
Earl Lee2e463fb2025-04-17 11:22:22 -0700502 out, err := cmd.CombinedOutput()
503 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700504 slog.ErrorContext(ctx, "go", slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700505 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
506 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700507 slog.DebugContext(ctx, "go", slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700508 }
509
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700510 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700511 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700512 }
David Crawshawc7e77962025-05-03 13:20:18 -0700513 // If we are already on Linux, there's no extra platform name in the path
514 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700515}
516
Sean McCulloughae3480f2025-04-23 15:28:20 -0700517func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700518 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700519 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700520 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
521 } else {
522 v4, _, found := strings.Cut(string(out), "\n")
523 if !found {
524 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
525 }
526 localAddr = v4
527 if strings.HasPrefix(localAddr, "0.0.0.0") {
528 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
529 }
530 }
531 return localAddr, nil
532}
533
534// Contact the container and configure it.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700535func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshServerIdentity, sshAuthorizedKeys []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700536 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700537
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000538 // Check if SSH is available by checking for the Include directive in ~/.ssh/config
539 sshAvailable := true
540 sshError := ""
541 if err := CheckForInclude(); err != nil {
542 sshAvailable = false
543 sshError = err.Error()
544 }
545
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700546 initMsg, err := json.Marshal(
547 server.InitRequest{
548 Commit: commit,
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000549 OutsideHTTP: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitPass, gitPort),
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700550 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
551 HostAddr: localAddr,
552 SSHAuthorizedKeys: sshAuthorizedKeys,
553 SSHServerIdentity: sshServerIdentity,
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000554 SSHAvailable: sshAvailable,
555 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700556 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700557 if err != nil {
558 return fmt.Errorf("init msg: %w", err)
559 }
560
Earl Lee2e463fb2025-04-17 11:22:22 -0700561 // Note: this /init POST is handled in loop/server/loophttp.go:
562 initMsgByteReader := bytes.NewReader(initMsg)
563 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
564 if err != nil {
565 return err
566 }
567
568 var res *http.Response
569 for i := 0; ; i++ {
570 time.Sleep(100 * time.Millisecond)
571 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
572 initMsgByteReader.Reset(initMsg)
573 res, err = http.DefaultClient.Do(req)
574 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700575 if i < 100 {
576 if i%10 == 0 {
577 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
578 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700579 continue
580 }
581 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
582 }
583 break
584 }
585 resBytes, _ := io.ReadAll(res.Body)
586 if res.StatusCode != http.StatusOK {
587 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
588 }
589 return nil
590}
591
592func findOrBuildDockerImage(ctx context.Context, stdout, stderr io.Writer, cwd, gitRoot, antURL, antAPIKey string, forceRebuild bool) (imgName string, err error) {
593 h := sha256.Sum256([]byte(gitRoot))
594 imgName = "sketch-" + hex.EncodeToString(h[:6])
595
596 var curImgInitFilesHash string
597 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
598 if strings.Contains(string(out), "No such object") {
599 // Image does not exist, continue and build it.
600 curImgInitFilesHash = ""
601 } else {
602 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
603 }
604 } else {
605 m := map[string]string{}
606 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
607 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
608 }
609 curImgInitFilesHash = m["sketch_context"]
610 }
611
612 candidates, err := findRepoDockerfiles(cwd, gitRoot)
613 if err != nil {
614 return "", fmt.Errorf("find dockerfile: %w", err)
615 }
616
617 var initFiles map[string]string
618 var dockerfilePath string
619
620 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
621 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
622 dockerfilePath = candidates[0]
623 contents, err := os.ReadFile(dockerfilePath)
624 if err != nil {
625 return "", err
626 }
627 fmt.Printf("using %s as dev env\n", candidates[0])
628 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700629 return imgName, nil
630 }
631 } else {
632 initFiles, err = readInitFiles(os.DirFS(gitRoot))
633 if err != nil {
634 return "", err
635 }
636 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
637 if err != nil {
638 return "", err
639 }
640 initFileHash := hashInitFiles(initFiles)
641 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700642 return imgName, nil
643 }
644
645 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700646 srv := &ant.Service{
647 URL: antURL,
648 APIKey: antAPIKey,
649 HTTPC: http.DefaultClient,
650 }
651 dockerfile, err := createDockerfile(ctx, srv, initFiles, subPathWorkingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700652 if err != nil {
653 return "", fmt.Errorf("create dockerfile: %w", err)
654 }
655 dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile")
656 if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil {
657 return "", err
658 }
659 defer os.Remove(dockerfilePath)
660
661 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))
662 }
663
664 var gitUserEmail, gitUserName string
665 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
666 return "", fmt.Errorf("git config: %s: %v", out, err)
667 } else {
668 gitUserEmail = strings.TrimSpace(string(out))
669 }
670 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
671 return "", fmt.Errorf("git config: %s: %v", out, err)
672 } else {
673 gitUserName = strings.TrimSpace(string(out))
674 }
675
676 start := time.Now()
677 cmd := exec.CommandContext(ctx,
678 "docker", "build",
679 "-t", imgName,
680 "-f", dockerfilePath,
681 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
682 "--build-arg", "GIT_USER_NAME="+gitUserName,
683 ".",
684 )
685 cmd.Dir = gitRoot
686 cmd.Stdout = stdout
687 cmd.Stderr = stderr
Josh Bleecher Snyderdf2d3dc2025-04-25 12:31:35 -0700688 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Philip Zeyligere4fa0e32025-04-23 14:15:55 -0700689 dockerfileContent, err := os.ReadFile(dockerfilePath)
690 if err != nil {
691 return "", fmt.Errorf("failed to read Dockerfile: %w", err)
692 }
David Crawshaw5228b582025-05-01 11:18:12 -0700693 // TODO: this is sometimes a repeat of earlier. Remove the earlier call?
Philip Zeyliger5d6af872025-04-23 19:48:34 -0700694 fmt.Fprintf(stdout, "Dockerfile:\n%s\n", string(dockerfileContent))
Earl Lee2e463fb2025-04-17 11:22:22 -0700695
696 err = run(ctx, "docker build", cmd)
697 if err != nil {
698 return "", fmt.Errorf("docker build failed: %v", err)
699 }
700 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
701 return imgName, nil
702}
703
704func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
705 files, err := findDirDockerfiles(cwd)
706 if err != nil {
707 return nil, err
708 }
709 if len(files) > 0 {
710 return files, nil
711 }
712
713 path := cwd
714 for path != gitRoot {
715 path = filepath.Dir(path)
716 files, err := findDirDockerfiles(path)
717 if err != nil {
718 return nil, err
719 }
720 if len(files) > 0 {
721 return files, nil
722 }
723 }
724 return files, nil
725}
726
727// findDirDockerfiles finds all "Dockerfile*" files in a directory.
728func findDirDockerfiles(root string) (res []string, err error) {
729 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
730 if err != nil {
731 return err
732 }
733 if info.IsDir() && root != path {
734 return filepath.SkipDir
735 }
736 name := strings.ToLower(info.Name())
737 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
738 res = append(res, path)
739 }
740 return nil
741 })
742 if err != nil {
743 return nil, err
744 }
745 return res, nil
746}
747
748func findGitRoot(ctx context.Context, path string) (string, error) {
749 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
750 cmd.Dir = path
751 out, err := cmd.CombinedOutput()
752 if err != nil {
753 if strings.Contains(string(out), "not a git repository") {
754 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
755Consider one of the following options:
756 - cd to a different dir that is already part of a git repo first, or
757 - to create a new git repo from this directory (%s), run this command:
758
759 git init . && git commit --allow-empty -m "initial commit"
760
761and try running sketch again.
762`, path, path)
763 }
764 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
765 }
766 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
767 absGitDir := filepath.Join(path, gitDir)
768 return filepath.Dir(absGitDir), err
769}
770
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000771// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
772// from git config using the sketch.envfwd multi-valued key.
773func getEnvForwardingFromGitConfig(ctx context.Context) []string {
774 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
775 out := string(outb)
776 if err != nil {
777 if strings.Contains(out, "key does not exist") {
778 return nil
779 }
780 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
781 return nil
782 }
783
784 var envVars []string
785 for envVar := range strings.Lines(out) {
786 envVar = strings.TrimSpace(envVar)
787 if envVar == "" {
788 continue
789 }
790 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
791 }
792 return envVars
793}