blob: 6164a3143b32d657ae79ad9e8a3fdb058a4749d6 [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"
Josh Bleecher Snyder99570462025-05-05 10:26:14 -070021 "sync/atomic"
Earl Lee2e463fb2025-04-17 11:22:22 -070022 "time"
23
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000024 "sketch.dev/browser"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070025 "sketch.dev/llm/ant"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070026 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070027 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070028 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070029)
30
31// ContainerConfig holds all configuration for launching a container
32type ContainerConfig struct {
33 // SessionID is the unique identifier for this session
34 SessionID string
35
36 // LocalAddr is the initial address to use (though it may be overwritten later)
37 LocalAddr string
38
39 // SkabandAddr is the address of the skaband service if available
40 SkabandAddr string
41
42 // AntURL is the URL of the LLM service.
43 AntURL string
44
45 // AntAPIKey is the API key for LLM service.
46 AntAPIKey string
47
48 // Path is the local filesystem path to use
49 Path string
50
51 // GitUsername is the username to use for git operations
52 GitUsername string
53
54 // GitEmail is the email to use for git operations
55 GitEmail string
56
57 // OpenBrowser determines whether to open a browser automatically
58 OpenBrowser bool
59
60 // NoCleanup prevents container cleanup when set to true
61 NoCleanup bool
62
63 // ForceRebuild forces rebuilding of the Docker image even if it exists
64 ForceRebuild bool
65
66 // Host directory to copy container logs into, if not set to ""
67 ContainerLogDest string
68
69 // Path to pre-built linux sketch binary, or build a new one if set to ""
70 SketchBinaryLinux string
71
72 // Sketch client public key.
73 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000074
Sean McCulloughbaa2b592025-04-23 10:40:08 -070075 // Host port for the container's ssh server
76 SSHPort int
77
Philip Zeyliger18532b22025-04-23 21:11:46 +000078 // Outside information to pass to the container
79 OutsideHostname string
80 OutsideOS string
81 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070082
Pokey Rule0dcebe12025-04-28 14:51:04 +010083 // If true, exit after the first turn
84 OneShot bool
85
86 // Initial prompt
87 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000088
89 // Initial commit to use as starting point
90 InitialCommit string
David Crawshawb5f6a002025-05-05 08:27:16 -070091
92 // Verbose enables verbose output
93 Verbose bool
Earl Lee2e463fb2025-04-17 11:22:22 -070094}
95
96// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
97// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -070098func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Earl Lee2e463fb2025-04-17 11:22:22 -070099 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700100 if runtime.GOOS == "darwin" {
101 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
102 } else {
103 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
104 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700105 }
106
107 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
108 // `docker ps` provides a good error message here that can be
109 // easily chatgpt'ed by users, so send it to the user as-is:
110 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
111 return fmt.Errorf("docker ps: %s (%w)", out, err)
112 }
113
114 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
115 if err != nil {
116 return err
117 }
118
119 gitRoot, err := findGitRoot(ctx, config.Path)
120 if err != nil {
121 return err
122 }
123
David Crawshawb5f6a002025-05-05 08:27:16 -0700124 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.AntURL, config.AntAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700125 if err != nil {
126 return err
127 }
128
129 linuxSketchBin := config.SketchBinaryLinux
130 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700131 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700132 if err != nil {
133 return err
134 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700135 }
136
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000137 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700138 defer func() {
139 if config.NoCleanup {
140 return
141 }
142 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
143 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
144 _ = out
145 }
146 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
147 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
148 _ = out
149 }
150 }()
151
152 // errCh receives errors from operations that this function calls in separate goroutines.
153 errCh := make(chan error)
154
155 // Start the git server
156 gitSrv, err := newGitServer(gitRoot)
157 if err != nil {
158 return fmt.Errorf("failed to start git server: %w", err)
159 }
160 defer gitSrv.shutdown(ctx)
161
162 go func() {
163 errCh <- gitSrv.serve(ctx)
164 }()
165
166 // Get the current host git commit
167 var commit string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +0000168 if out, err := combinedOutput(ctx, "git", "rev-parse", config.InitialCommit); err != nil {
169 return fmt.Errorf("git rev-parse %s: %w", config.InitialCommit, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700170 } else {
171 commit = strings.TrimSpace(string(out))
172 }
173 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
174 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
175 }
176
177 relPath, err := filepath.Rel(gitRoot, config.Path)
178 if err != nil {
179 return err
180 }
181
182 // Create the sketch container
183 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000184 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700185 }
186
187 // Copy the sketch linux binary into the container
188 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
189 return fmt.Errorf("docker cp: %s, %w", out, err)
190 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700191
192 // Make sure that the webui is built so we can copy the results to the container.
193 _, err = webui.Build()
194 if err != nil {
195 return fmt.Errorf("failed to build webui: %w", err)
196 }
197
David Crawshaw8bff16a2025-04-18 01:16:49 -0700198 webuiZipPath, err := webui.ZipPath()
199 if err != nil {
200 return err
201 }
202 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
203 return fmt.Errorf("docker cp: %s, %w", out, err)
204 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700205
David Crawshaw53786ef2025-04-24 12:52:51 -0700206 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700207
208 // Start the sketch container
209 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
210 return fmt.Errorf("docker start: %s, %w", out, err)
211 }
212
213 // Copies structured logs from the container to the host.
214 copyLogs := func() {
215 if config.ContainerLogDest == "" {
216 return
217 }
218 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
219 if err != nil {
220 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
221 return
222 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700223 prefix := []byte("structured logs:")
224 for line := range bytes.Lines(out) {
225 rest, ok := bytes.CutPrefix(line, prefix)
226 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700227 continue
228 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700229 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700230 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
231 logFileName := filepath.Base(logFile)
232 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
233 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
234 if err != nil {
235 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
236 }
237 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
238 }
239 }
240
241 // NOTE: we want to see what the internal sketch binary prints
242 // regardless of the setting of the verbosity flag on the external
243 // binary, so reading "docker logs", which is the stdout/stderr of
244 // the internal binary is not conditional on the verbose flag.
245 appendInternalErr := func(err error) error {
246 if err == nil {
247 return nil
248 }
249 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000250 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700251 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
252 }
253 out = bytes.TrimSpace(out)
254 if len(out) > 0 {
255 return fmt.Errorf("docker logs: %s;\n%w", out, err)
256 }
257 return err
258 }
259
260 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700261 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700262 if err != nil {
263 return appendInternalErr(err)
264 }
265
Sean McCulloughae3480f2025-04-23 15:28:20 -0700266 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
267 if err != nil {
268 return appendInternalErr(err)
269 }
270 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
271 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700272 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700273 }
Sean McCullough4854c652025-04-24 18:37:02 -0700274
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700275 var sshServerIdentity, sshUserIdentity []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700276
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700277 if err := CheckForInclude(); err != nil {
278 fmt.Println(err.Error())
279 // continue - ssh config is not required for the rest of sketch to function locally.
280 } else {
Josh Bleecher Snyder50608b12025-05-03 22:55:49 +0000281 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700282 if err != nil {
283 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
284 }
285
Sean McCulloughea3fc202025-04-28 12:53:37 -0700286 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
287 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700288 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700289🖥️ ssh %s
290🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700291🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700292`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700293 sshUserIdentity = cst.userIdentity
294 sshServerIdentity = cst.serverIdentity
295 defer func() {
296 if err := cst.Cleanup(); err != nil {
297 appendInternalErr(err)
298 }
299 }()
300 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700301
Earl Lee2e463fb2025-04-17 11:22:22 -0700302 // Tell the sketch container which git server port and commit to initialize with.
303 go func() {
304 // TODO: Why is this called in a goroutine? I have found that when I pull this out
305 // of the goroutine and call it inline, then the terminal UI clears itself and all
306 // the scrollback (which is not good, but also not fatal). I can't see why it does this
307 // though, since none of the calls in postContainerInitConfig obviously write to stdout
308 // or stderr.
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700309 if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, sshServerIdentity, sshUserIdentity); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700310 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
311 errCh <- appendInternalErr(err)
312 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700313
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700314 // We open the browser after the init config because the above waits for the web server to be serving.
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700315 ps1URL := "http://" + localAddr
316 if config.SkabandAddr != "" {
317 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700318 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700319 if config.OpenBrowser {
320 browser.Open(ps1URL)
321 }
322 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700323 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700324
325 go func() {
326 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
327 cmd.Stdin = os.Stdin
328 cmd.Stdout = os.Stdout
329 cmd.Stderr = os.Stderr
330 errCh <- run(ctx, "docker attach", cmd)
331 }()
332
333 defer copyLogs()
334
335 for {
336 select {
337 case <-ctx.Done():
338 return ctx.Err()
339 case err := <-errCh:
340 if err != nil {
341 return appendInternalErr(fmt.Errorf("container process: %w", err))
342 }
343 return nil
344 }
345 }
346}
347
348func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
349 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700350 start := time.Now()
351
352 out, err := cmd.CombinedOutput()
353 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700354 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 -0700355 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700356 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 -0700357 }
358 return out, err
359}
360
361func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
362 start := time.Now()
363 err := cmd.Run()
364 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700365 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 -0700366 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700367 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 -0700368 }
369 return err
370}
371
372type gitServer struct {
373 gitLn net.Listener
374 gitPort string
375 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700376 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700377 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700378}
379
380func (gs *gitServer) shutdown(ctx context.Context) {
381 gs.srv.Shutdown(ctx)
382 gs.gitLn.Close()
383}
384
385// Serve a git remote from the host for the container to fetch from and push to.
386func (gs *gitServer) serve(ctx context.Context) error {
387 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
388 return gs.srv.Serve(gs.gitLn)
389}
390
391func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700392 ret := &gitServer{
393 pass: rand.Text(),
394 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700395
Earl Lee2e463fb2025-04-17 11:22:22 -0700396 gitLn, err := net.Listen("tcp4", ":0")
397 if err != nil {
398 return nil, fmt.Errorf("git listen: %w", err)
399 }
400 ret.gitLn = gitLn
401
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700402 browserC := make(chan bool, 1) // channel of browser open requests
403
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000404 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700405 for range browserC {
406 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000407 }
408 }()
409
410 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700411 ret.srv = &srv
412
413 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
414 if err != nil {
415 return nil, fmt.Errorf("git port: %w", err)
416 }
417 ret.gitPort = gitPort
418 return ret, nil
419}
420
421func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700422 cmdArgs := []string{
423 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700424 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700425 "--name", cntrName,
426 "-p", hostPort + ":80", // forward container port 80 to a host port
Philip Zeyliger6234a8d2025-05-02 14:31:20 -0700427 "-e", "SKETCH_ANTHROPIC_API_KEY=" + config.AntAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700428 }
David Crawshaw66cf74e2025-05-05 08:48:39 -0700429 if !config.OneShot {
430 cmdArgs = append(cmdArgs, "-t")
431 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000432
433 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
434 cmdArgs = append(cmdArgs, "-e", envVar)
435 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700436 if config.AntURL != "" {
Philip Zeyliger6234a8d2025-05-02 14:31:20 -0700437 cmdArgs = append(cmdArgs, "-e", "SKETCH_ANT_URL="+config.AntURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700438 }
439 if config.SketchPubKey != "" {
440 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
441 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700442 if config.SSHPort > 0 {
443 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
444 } else {
445 cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700446 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700447 if relPath != "." {
448 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
449 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700450 // colima does this by default, but Linux docker seems to need this set explicitly
451 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700452 cmdArgs = append(
453 cmdArgs,
454 imgName,
455 "/bin/sketch",
456 "-unsafe",
457 "-addr=:80",
458 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000459 "-git-username="+config.GitUsername,
460 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000461 "-outside-hostname="+config.OutsideHostname,
462 "-outside-os="+config.OutsideOS,
463 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700464 "-open=false",
Earl Lee2e463fb2025-04-17 11:22:22 -0700465 )
466 if config.SkabandAddr != "" {
467 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
468 }
Pokey Rule0dcebe12025-04-28 14:51:04 +0100469 if config.Prompt != "" {
470 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
471 }
472 if config.OneShot {
473 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700474 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700475 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
476 return fmt.Errorf("docker create: %s, %w", out, err)
477 }
478 return nil
479}
480
David Crawshawb5f6a002025-05-05 08:27:16 -0700481func buildLinuxSketchBin(ctx context.Context) (string, error) {
David Crawshaw8a617cb2025-04-18 01:28:43 -0700482 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700483 if err != nil {
484 return "", err
485 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700486 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
487 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
488 return "", err
489 }
490
491 verToInstall := "@latest"
492 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
493 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
494 } else {
495 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700496 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700497 verToInstall = ""
498 }
499 }
David Crawshaw69c67312025-04-17 13:42:00 -0700500
Earl Lee2e463fb2025-04-17 11:22:22 -0700501 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700502 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700503 cmd.Env = append(
504 os.Environ(),
505 "GOOS=linux",
506 "CGO_ENABLED=0",
507 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700508 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700509 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700510 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700511
Earl Lee2e463fb2025-04-17 11:22:22 -0700512 out, err := cmd.CombinedOutput()
513 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700514 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 -0700515 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
516 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700517 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 -0700518 }
519
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700520 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700521 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700522 }
David Crawshawc7e77962025-05-03 13:20:18 -0700523 // If we are already on Linux, there's no extra platform name in the path
524 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700525}
526
Sean McCulloughae3480f2025-04-23 15:28:20 -0700527func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700528 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700529 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700530 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
531 } else {
532 v4, _, found := strings.Cut(string(out), "\n")
533 if !found {
534 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
535 }
536 localAddr = v4
537 if strings.HasPrefix(localAddr, "0.0.0.0") {
538 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
539 }
540 }
541 return localAddr, nil
542}
543
544// Contact the container and configure it.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700545func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshServerIdentity, sshAuthorizedKeys []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700546 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700547
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000548 // Check if SSH is available by checking for the Include directive in ~/.ssh/config
549 sshAvailable := true
550 sshError := ""
551 if err := CheckForInclude(); err != nil {
552 sshAvailable = false
553 sshError = err.Error()
554 }
555
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700556 initMsg, err := json.Marshal(
557 server.InitRequest{
558 Commit: commit,
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000559 OutsideHTTP: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitPass, gitPort),
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700560 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
561 HostAddr: localAddr,
562 SSHAuthorizedKeys: sshAuthorizedKeys,
563 SSHServerIdentity: sshServerIdentity,
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000564 SSHAvailable: sshAvailable,
565 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700566 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700567 if err != nil {
568 return fmt.Errorf("init msg: %w", err)
569 }
570
Earl Lee2e463fb2025-04-17 11:22:22 -0700571 // Note: this /init POST is handled in loop/server/loophttp.go:
572 initMsgByteReader := bytes.NewReader(initMsg)
573 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
574 if err != nil {
575 return err
576 }
577
578 var res *http.Response
579 for i := 0; ; i++ {
580 time.Sleep(100 * time.Millisecond)
581 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
582 initMsgByteReader.Reset(initMsg)
583 res, err = http.DefaultClient.Do(req)
584 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700585 if i < 100 {
586 if i%10 == 0 {
587 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
588 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700589 continue
590 }
591 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
592 }
593 break
594 }
595 resBytes, _ := io.ReadAll(res.Body)
596 if res.StatusCode != http.StatusOK {
597 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
598 }
599 return nil
600}
601
David Crawshawb5f6a002025-05-05 08:27:16 -0700602func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, antURL, antAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700603 h := sha256.Sum256([]byte(gitRoot))
604 imgName = "sketch-" + hex.EncodeToString(h[:6])
605
606 var curImgInitFilesHash string
607 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
608 if strings.Contains(string(out), "No such object") {
609 // Image does not exist, continue and build it.
610 curImgInitFilesHash = ""
611 } else {
612 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
613 }
614 } else {
615 m := map[string]string{}
616 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
617 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
618 }
619 curImgInitFilesHash = m["sketch_context"]
620 }
621
622 candidates, err := findRepoDockerfiles(cwd, gitRoot)
623 if err != nil {
624 return "", fmt.Errorf("find dockerfile: %w", err)
625 }
626
627 var initFiles map[string]string
628 var dockerfilePath string
629
630 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
631 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
632 dockerfilePath = candidates[0]
633 contents, err := os.ReadFile(dockerfilePath)
634 if err != nil {
635 return "", err
636 }
637 fmt.Printf("using %s as dev env\n", candidates[0])
638 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700639 return imgName, nil
640 }
641 } else {
642 initFiles, err = readInitFiles(os.DirFS(gitRoot))
643 if err != nil {
644 return "", err
645 }
646 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
647 if err != nil {
648 return "", err
649 }
650 initFileHash := hashInitFiles(initFiles)
651 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700652 return imgName, nil
653 }
654
655 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700656 srv := &ant.Service{
657 URL: antURL,
658 APIKey: antAPIKey,
659 HTTPC: http.DefaultClient,
660 }
661 dockerfile, err := createDockerfile(ctx, srv, initFiles, subPathWorkingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700662 if err != nil {
663 return "", fmt.Errorf("create dockerfile: %w", err)
664 }
665 dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile")
666 if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil {
667 return "", err
668 }
669 defer os.Remove(dockerfilePath)
670
David Crawshawb5f6a002025-05-05 08:27:16 -0700671 if verbose {
672 fmt.Fprintf(os.Stderr, "generated Dockerfile in %s:\n\t%s\n\n", time.Since(start).Round(time.Millisecond), strings.Replace(dockerfile, "\n", "\n\t", -1))
673 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700674 }
675
676 var gitUserEmail, gitUserName string
677 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
678 return "", fmt.Errorf("git config: %s: %v", out, err)
679 } else {
680 gitUserEmail = strings.TrimSpace(string(out))
681 }
682 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
683 return "", fmt.Errorf("git config: %s: %v", out, err)
684 } else {
685 gitUserName = strings.TrimSpace(string(out))
686 }
687
688 start := time.Now()
689 cmd := exec.CommandContext(ctx,
690 "docker", "build",
691 "-t", imgName,
692 "-f", dockerfilePath,
693 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
694 "--build-arg", "GIT_USER_NAME="+gitUserName,
Earl Lee2e463fb2025-04-17 11:22:22 -0700695 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700696 if !verbose {
697 cmd.Args = append(cmd.Args, "--progress=quiet")
Philip Zeyligere4fa0e32025-04-23 14:15:55 -0700698 }
David Crawshawb5f6a002025-05-05 08:27:16 -0700699 cmd.Args = append(cmd.Args, ".")
700 cmd.Dir = gitRoot
701 cmd.Stdout = os.Stdout
702 cmd.Stderr = os.Stderr
703 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700704
705 err = run(ctx, "docker build", cmd)
706 if err != nil {
707 return "", fmt.Errorf("docker build failed: %v", err)
708 }
709 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
710 return imgName, nil
711}
712
713func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
714 files, err := findDirDockerfiles(cwd)
715 if err != nil {
716 return nil, err
717 }
718 if len(files) > 0 {
719 return files, nil
720 }
721
722 path := cwd
723 for path != gitRoot {
724 path = filepath.Dir(path)
725 files, err := findDirDockerfiles(path)
726 if err != nil {
727 return nil, err
728 }
729 if len(files) > 0 {
730 return files, nil
731 }
732 }
733 return files, nil
734}
735
736// findDirDockerfiles finds all "Dockerfile*" files in a directory.
737func findDirDockerfiles(root string) (res []string, err error) {
738 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
739 if err != nil {
740 return err
741 }
742 if info.IsDir() && root != path {
743 return filepath.SkipDir
744 }
745 name := strings.ToLower(info.Name())
746 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
747 res = append(res, path)
748 }
749 return nil
750 })
751 if err != nil {
752 return nil, err
753 }
754 return res, nil
755}
756
757func findGitRoot(ctx context.Context, path string) (string, error) {
758 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
759 cmd.Dir = path
760 out, err := cmd.CombinedOutput()
761 if err != nil {
762 if strings.Contains(string(out), "not a git repository") {
763 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
764Consider one of the following options:
765 - cd to a different dir that is already part of a git repo first, or
766 - to create a new git repo from this directory (%s), run this command:
767
768 git init . && git commit --allow-empty -m "initial commit"
769
770and try running sketch again.
771`, path, path)
772 }
773 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
774 }
775 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
776 absGitDir := filepath.Join(path, gitDir)
777 return filepath.Dir(absGitDir), err
778}
779
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000780// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
781// from git config using the sketch.envfwd multi-valued key.
782func getEnvForwardingFromGitConfig(ctx context.Context) []string {
783 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
784 out := string(outb)
785 if err != nil {
786 if strings.Contains(out, "key does not exist") {
787 return nil
788 }
789 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
790 return nil
791 }
792
793 var envVars []string
794 for envVar := range strings.Lines(out) {
795 envVar = strings.TrimSpace(envVar)
796 if envVar == "" {
797 continue
798 }
799 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
800 }
801 return envVars
802}