| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 1 | // Package dockerimg |
| 2 | package dockerimg |
| 3 | |
| 4 | import ( |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 5 | "archive/tar" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 6 | "bytes" |
| 7 | "context" |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 8 | "crypto/rand" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 9 | "crypto/sha256" |
| 10 | "encoding/hex" |
| 11 | "encoding/json" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "log/slog" |
| 15 | "net" |
| 16 | "net/http" |
| 17 | "os" |
| 18 | "os/exec" |
| 19 | "path/filepath" |
| 20 | "runtime" |
| 21 | "strings" |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 22 | "sync/atomic" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 23 | "time" |
| 24 | |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 25 | "golang.org/x/crypto/ssh" |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 26 | "sketch.dev/browser" |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 27 | "sketch.dev/embedded" |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 28 | "sketch.dev/loop/server" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 29 | "sketch.dev/skribe" |
| 30 | ) |
| 31 | |
| 32 | // ContainerConfig holds all configuration for launching a container |
| 33 | type ContainerConfig struct { |
| 34 | // SessionID is the unique identifier for this session |
| 35 | SessionID string |
| 36 | |
| 37 | // LocalAddr is the initial address to use (though it may be overwritten later) |
| 38 | LocalAddr string |
| 39 | |
| 40 | // SkabandAddr is the address of the skaband service if available |
| 41 | SkabandAddr string |
| 42 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 43 | // Model is the name of the LLM model to use. |
| 44 | Model string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 45 | |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 46 | // ModelURL is the URL of the LLM service. |
| 47 | ModelURL string |
| 48 | |
| 49 | // ModelAPIKey is the API key for LLM service. |
| 50 | ModelAPIKey string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 51 | |
| 52 | // Path is the local filesystem path to use |
| 53 | Path string |
| 54 | |
| 55 | // GitUsername is the username to use for git operations |
| 56 | GitUsername string |
| 57 | |
| 58 | // GitEmail is the email to use for git operations |
| 59 | GitEmail string |
| 60 | |
| 61 | // OpenBrowser determines whether to open a browser automatically |
| 62 | OpenBrowser bool |
| 63 | |
| 64 | // NoCleanup prevents container cleanup when set to true |
| 65 | NoCleanup bool |
| 66 | |
| 67 | // ForceRebuild forces rebuilding of the Docker image even if it exists |
| 68 | ForceRebuild bool |
| 69 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 70 | // BaseImage is the base Docker image to use for layering the repo |
| 71 | BaseImage string |
| 72 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 73 | // Host directory to copy container logs into, if not set to "" |
| 74 | ContainerLogDest string |
| 75 | |
| 76 | // Path to pre-built linux sketch binary, or build a new one if set to "" |
| 77 | SketchBinaryLinux string |
| 78 | |
| 79 | // Sketch client public key. |
| 80 | SketchPubKey string |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 81 | |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 82 | // Host port for the container's ssh server |
| 83 | SSHPort int |
| 84 | |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 85 | // Outside information to pass to the container |
| 86 | OutsideHostname string |
| 87 | OutsideOS string |
| 88 | OutsideWorkingDir string |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 89 | |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 90 | // If true, exit after the first turn |
| 91 | OneShot bool |
| 92 | |
| 93 | // Initial prompt |
| 94 | Prompt string |
| Philip Zeyliger | 1b47aa2 | 2025-04-28 19:25:38 +0000 | [diff] [blame] | 95 | |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 96 | // Verbose enables verbose output |
| 97 | Verbose bool |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 98 | |
| 99 | // DockerArgs are additional arguments to pass to the docker create command |
| 100 | DockerArgs string |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 101 | |
| Josh Bleecher Snyder | ac761c9 | 2025-05-16 18:58:45 +0000 | [diff] [blame] | 102 | // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container |
| 103 | Mounts []string |
| 104 | |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 105 | // ExperimentFlag contains the experimental features to enable |
| 106 | ExperimentFlag string |
| Philip Zeyliger | 613c0f5 | 2025-05-15 16:36:22 -0700 | [diff] [blame] | 107 | |
| 108 | // TermUI enables terminal UI |
| 109 | TermUI bool |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 110 | |
| Josh Bleecher Snyder | 33032d3 | 2025-05-30 16:28:21 +0000 | [diff] [blame] | 111 | // Budget configuration |
| Philip Zeyliger | e6c294d | 2025-06-04 16:55:21 +0000 | [diff] [blame] | 112 | MaxDollars float64 |
| Josh Bleecher Snyder | 33032d3 | 2025-05-30 16:28:21 +0000 | [diff] [blame] | 113 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 114 | GitRemoteUrl string |
| 115 | |
| Josh Bleecher Snyder | 664404e | 2025-06-04 21:56:42 +0000 | [diff] [blame] | 116 | // Upstream branch for git work |
| 117 | Upstream string |
| 118 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 119 | // Commit hash to checkout from GetRemoteUrl |
| 120 | Commit string |
| 121 | |
| 122 | // Outtie's HTTP server |
| 123 | OutsideHTTP string |
| Philip Zeyliger | be7802a | 2025-06-04 20:15:25 +0000 | [diff] [blame] | 124 | |
| 125 | // Prefix for git branches created by sketch |
| 126 | BranchPrefix string |
| philip.zeyliger | 6d3de48 | 2025-06-10 19:38:14 -0700 | [diff] [blame] | 127 | |
| 128 | // LinkToGitHub enables GitHub branch linking in UI |
| 129 | LinkToGitHub bool |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 130 | |
| 131 | // SubtraceToken enables running sketch under subtrace.dev (development only) |
| 132 | SubtraceToken string |
| Philip Zeyliger | 194bfa8 | 2025-06-24 06:03:06 -0700 | [diff] [blame] | 133 | |
| 134 | // MCPServers contains MCP server configurations |
| 135 | MCPServers []string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 136 | } |
| 137 | |
| 138 | // LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it. |
| 139 | // It writes status to stdout. |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 140 | func LaunchContainer(ctx context.Context, config ContainerConfig) error { |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 141 | slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 142 | if _, err := exec.LookPath("docker"); err != nil { |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 143 | if runtime.GOOS == "darwin" { |
| 144 | return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start") |
| 145 | } else { |
| 146 | return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)") |
| 147 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 148 | } |
| 149 | |
| 150 | if out, err := combinedOutput(ctx, "docker", "ps"); err != nil { |
| 151 | // `docker ps` provides a good error message here that can be |
| 152 | // easily chatgpt'ed by users, so send it to the user as-is: |
| 153 | // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? |
| 154 | return fmt.Errorf("docker ps: %s (%w)", out, err) |
| 155 | } |
| 156 | |
| 157 | _, hostPort, err := net.SplitHostPort(config.LocalAddr) |
| 158 | if err != nil { |
| 159 | return err |
| 160 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 161 | gitRoot, err := findGitRoot(ctx, config.Path) |
| 162 | if err != nil { |
| 163 | return err |
| 164 | } |
| Philip Zeyliger | d6d12d1 | 2025-05-19 19:19:21 -0700 | [diff] [blame] | 165 | err = checkForEmptyGitRepo(ctx, config.Path) |
| 166 | if err != nil { |
| 167 | return err |
| 168 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 169 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 170 | imgName, err := findOrBuildDockerImage(ctx, gitRoot, config.BaseImage, config.ForceRebuild, config.Verbose) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 171 | if err != nil { |
| 172 | return err |
| 173 | } |
| 174 | |
| Philip Zeyliger | c72fff5 | 2025-04-29 20:17:54 +0000 | [diff] [blame] | 175 | cntrName := "sketch-" + config.SessionID |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 176 | defer func() { |
| 177 | if config.NoCleanup { |
| 178 | return |
| 179 | } |
| 180 | if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil { |
| 181 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 182 | _ = out |
| 183 | } |
| 184 | if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil { |
| 185 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 186 | _ = out |
| 187 | } |
| 188 | }() |
| 189 | |
| 190 | // errCh receives errors from operations that this function calls in separate goroutines. |
| 191 | errCh := make(chan error) |
| 192 | |
| 193 | // Start the git server |
| 194 | gitSrv, err := newGitServer(gitRoot) |
| 195 | if err != nil { |
| 196 | return fmt.Errorf("failed to start git server: %w", err) |
| 197 | } |
| 198 | defer gitSrv.shutdown(ctx) |
| 199 | |
| 200 | go func() { |
| 201 | errCh <- gitSrv.serve(ctx) |
| 202 | }() |
| 203 | |
| 204 | // Get the current host git commit |
| 205 | var commit string |
| Philip Zeyliger | a347b17 | 2025-06-04 16:18:57 +0000 | [diff] [blame] | 206 | if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil { |
| 207 | return fmt.Errorf("git rev-parse HEAD: %w", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 208 | } else { |
| 209 | commit = strings.TrimSpace(string(out)) |
| 210 | } |
| Josh Bleecher Snyder | 664404e | 2025-06-04 21:56:42 +0000 | [diff] [blame] | 211 | |
| 212 | var upstream string |
| 213 | if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil { |
| 214 | slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err) |
| 215 | } else { |
| 216 | upstream = strings.TrimSpace(string(out)) |
| 217 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 218 | if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil { |
| 219 | return fmt.Errorf("git config http.receivepack true: %s: %w", out, err) |
| 220 | } |
| 221 | |
| 222 | relPath, err := filepath.Rel(gitRoot, config.Path) |
| 223 | if err != nil { |
| 224 | return err |
| 225 | } |
| 226 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 227 | config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort) |
| 228 | config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort) |
| Josh Bleecher Snyder | 664404e | 2025-06-04 21:56:42 +0000 | [diff] [blame] | 229 | config.Upstream = upstream |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 230 | config.Commit = commit |
| 231 | |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 232 | // Create the sketch container, copy over linux sketch |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 233 | if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil { |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 234 | return fmt.Errorf("failed to create docker container: %w", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 235 | } |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 236 | if err := copyEmbeddedLinuxBinaryToContainer(ctx, cntrName); err != nil { |
| 237 | return fmt.Errorf("failed to copy linux binary to container: %w", err) |
| David Crawshaw | 8bff16a | 2025-04-18 01:16:49 -0700 | [diff] [blame] | 238 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 239 | |
| David Crawshaw | 53786ef | 2025-04-24 12:52:51 -0700 | [diff] [blame] | 240 | fmt.Printf("📦 running in container %s\n", cntrName) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 241 | |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 242 | // Setup subtrace if token is provided (development only) - after container creation, before start |
| 243 | if config.SubtraceToken != "" { |
| 244 | fmt.Println("🔍 Setting up subtrace (development only)") |
| 245 | if err := setupSubtraceBeforeStart(ctx, cntrName, config.SubtraceToken); err != nil { |
| 246 | return fmt.Errorf("failed to setup subtrace: %w", err) |
| 247 | } |
| 248 | } |
| 249 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 250 | // Start the sketch container |
| 251 | if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil { |
| 252 | return fmt.Errorf("docker start: %s, %w", out, err) |
| 253 | } |
| 254 | |
| 255 | // Copies structured logs from the container to the host. |
| 256 | copyLogs := func() { |
| 257 | if config.ContainerLogDest == "" { |
| 258 | return |
| 259 | } |
| 260 | out, err := combinedOutput(ctx, "docker", "logs", cntrName) |
| 261 | if err != nil { |
| 262 | fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err) |
| 263 | return |
| 264 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 265 | prefix := []byte("structured logs:") |
| 266 | for line := range bytes.Lines(out) { |
| 267 | rest, ok := bytes.CutPrefix(line, prefix) |
| 268 | if !ok { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 269 | continue |
| 270 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 271 | logFile := string(bytes.TrimSpace(rest)) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 272 | srcPath := fmt.Sprintf("%s:%s", cntrName, logFile) |
| 273 | logFileName := filepath.Base(logFile) |
| 274 | dstPath := filepath.Join(config.ContainerLogDest, logFileName) |
| 275 | _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath) |
| 276 | if err != nil { |
| 277 | fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err) |
| 278 | } |
| 279 | fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | // NOTE: we want to see what the internal sketch binary prints |
| 284 | // regardless of the setting of the verbosity flag on the external |
| 285 | // binary, so reading "docker logs", which is the stdout/stderr of |
| 286 | // the internal binary is not conditional on the verbose flag. |
| 287 | appendInternalErr := func(err error) error { |
| 288 | if err == nil { |
| 289 | return nil |
| 290 | } |
| 291 | out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName) |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 292 | if logsErr != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 293 | return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr) |
| 294 | } |
| 295 | out = bytes.TrimSpace(out) |
| 296 | if len(out) > 0 { |
| 297 | return fmt.Errorf("docker logs: %s;\n%w", out, err) |
| 298 | } |
| 299 | return err |
| 300 | } |
| 301 | |
| 302 | // Get the sketch server port from the container |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 303 | localAddr, err := getContainerPort(ctx, cntrName, "80") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 304 | if err != nil { |
| 305 | return appendInternalErr(err) |
| 306 | } |
| 307 | |
| Philip Zeyliger | 0044241 | 2025-05-14 11:03:23 -0700 | [diff] [blame] | 308 | if config.Verbose { |
| 309 | fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr) |
| 310 | } |
| 311 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 312 | localSSHAddr, err := getContainerPort(ctx, cntrName, "22") |
| 313 | if err != nil { |
| 314 | return appendInternalErr(err) |
| 315 | } |
| 316 | sshHost, sshPort, err := net.SplitHostPort(localSSHAddr) |
| 317 | if err != nil { |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 318 | return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err)) |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 319 | } |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 320 | |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 321 | var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 322 | |
| banksean | 29d689f | 2025-06-23 15:41:26 +0000 | [diff] [blame] | 323 | cst, err := NewLocalSSHimmer(cntrName, sshHost, sshPort) |
| Sean McCullough | 078e85a | 2025-05-08 17:28:34 -0700 | [diff] [blame] | 324 | if err != nil { |
| 325 | return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err)) |
| 326 | } |
| 327 | |
| 328 | sshErr := CheckSSHReachability(cntrName) |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 329 | sshAvailable := false |
| 330 | sshErrMsg := "" |
| 331 | if sshErr != nil { |
| 332 | fmt.Println(sshErr.Error()) |
| 333 | sshErrMsg = sshErr.Error() |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 334 | // continue - ssh config is not required for the rest of sketch to function locally. |
| 335 | } else { |
| Sean McCullough | 15c9528 | 2025-05-08 16:48:38 -0700 | [diff] [blame] | 336 | sshAvailable = true |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 337 | // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find: |
| 338 | // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878 |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 339 | fmt.Printf(`Connect to this container via any of these methods: |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 340 | 🖥️ ssh %s |
| 341 | 🖥️ code --remote ssh-remote+root@%s /app -n |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 342 | 🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 343 | `, cntrName, cntrName, cntrName) |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 344 | sshUserIdentity = cst.userIdentity |
| 345 | sshServerIdentity = cst.serverIdentity |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 346 | |
| 347 | // Get the Container CA public key for mutual auth |
| 348 | if cst.containerCAPublicKey != nil { |
| 349 | containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey) |
| 350 | fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)") |
| 351 | } |
| 352 | |
| 353 | // Get the host certificate for mutual auth |
| 354 | hostCertificate = cst.hostCertificate |
| 355 | |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 356 | defer func() { |
| 357 | if err := cst.Cleanup(); err != nil { |
| 358 | appendInternalErr(err) |
| 359 | } |
| 360 | }() |
| 361 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 362 | |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 363 | // Tell the sketch container to Init(), which starts the SSH server |
| 364 | // and checks out the right commit. |
| 365 | // TODO: I'm trying to move as much configuration as possible into the command-line |
| 366 | // arguments to avoid splitting them up. "localAddr" is the only difficult one: |
| 367 | // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't |
| 368 | // get the port Docker chose until after the process starts. The SSH config is |
| 369 | // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg") |
| 370 | // may also empirically need to be done after the SSH server is up and running. |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 371 | go func() { |
| 372 | // TODO: Why is this called in a goroutine? I have found that when I pull this out |
| 373 | // of the goroutine and call it inline, then the terminal UI clears itself and all |
| 374 | // the scrollback (which is not good, but also not fatal). I can't see why it does this |
| 375 | // though, since none of the calls in postContainerInitConfig obviously write to stdout |
| 376 | // or stderr. |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 377 | if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 378 | slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error())) |
| 379 | errCh <- appendInternalErr(err) |
| 380 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 381 | |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 382 | // We open the browser after the init config because the above waits for the web server to be serving. |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 383 | ps1URL := "http://" + localAddr |
| 384 | if config.SkabandAddr != "" { |
| 385 | ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID) |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 386 | } |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 387 | if config.OpenBrowser { |
| 388 | browser.Open(ps1URL) |
| 389 | } |
| 390 | gitSrv.ps1URL.Store(&ps1URL) |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 391 | }() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 392 | |
| 393 | go func() { |
| 394 | cmd := exec.CommandContext(ctx, "docker", "attach", cntrName) |
| 395 | cmd.Stdin = os.Stdin |
| 396 | cmd.Stdout = os.Stdout |
| 397 | cmd.Stderr = os.Stderr |
| 398 | errCh <- run(ctx, "docker attach", cmd) |
| 399 | }() |
| 400 | |
| 401 | defer copyLogs() |
| 402 | |
| 403 | for { |
| 404 | select { |
| 405 | case <-ctx.Done(): |
| 406 | return ctx.Err() |
| 407 | case err := <-errCh: |
| 408 | if err != nil { |
| 409 | return appendInternalErr(fmt.Errorf("container process: %w", err)) |
| 410 | } |
| 411 | return nil |
| 412 | } |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) { |
| 417 | cmd := exec.CommandContext(ctx, cmdName, args...) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 418 | start := time.Now() |
| 419 | |
| 420 | out, err := cmd.CombinedOutput() |
| 421 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 422 | 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 423 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 424 | 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 425 | } |
| 426 | return out, err |
| 427 | } |
| 428 | |
| 429 | func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error { |
| 430 | start := time.Now() |
| 431 | err := cmd.Run() |
| 432 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 433 | 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 434 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 435 | 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 436 | } |
| 437 | return err |
| 438 | } |
| 439 | |
| 440 | type gitServer struct { |
| 441 | gitLn net.Listener |
| 442 | gitPort string |
| 443 | srv *http.Server |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 444 | pass string |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 445 | ps1URL atomic.Pointer[string] |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 446 | } |
| 447 | |
| 448 | func (gs *gitServer) shutdown(ctx context.Context) { |
| 449 | gs.srv.Shutdown(ctx) |
| 450 | gs.gitLn.Close() |
| 451 | } |
| 452 | |
| 453 | // Serve a git remote from the host for the container to fetch from and push to. |
| 454 | func (gs *gitServer) serve(ctx context.Context) error { |
| 455 | slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git")) |
| 456 | return gs.srv.Serve(gs.gitLn) |
| 457 | } |
| 458 | |
| 459 | func newGitServer(gitRoot string) (*gitServer, error) { |
| Josh Bleecher Snyder | 9f6a998 | 2025-04-22 17:34:15 -0700 | [diff] [blame] | 460 | ret := &gitServer{ |
| 461 | pass: rand.Text(), |
| 462 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 463 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 464 | gitLn, err := net.Listen("tcp4", ":0") |
| 465 | if err != nil { |
| 466 | return nil, fmt.Errorf("git listen: %w", err) |
| 467 | } |
| 468 | ret.gitLn = gitLn |
| 469 | |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 470 | browserC := make(chan bool, 1) // channel of browser open requests |
| 471 | |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 472 | go func() { |
| Josh Bleecher Snyder | 9957046 | 2025-05-05 10:26:14 -0700 | [diff] [blame] | 473 | for range browserC { |
| 474 | browser.Open(*ret.ps1URL.Load()) |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 475 | } |
| 476 | }() |
| 477 | |
| 478 | srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 479 | ret.srv = &srv |
| 480 | |
| 481 | _, gitPort, err := net.SplitHostPort(gitLn.Addr().String()) |
| 482 | if err != nil { |
| 483 | return nil, fmt.Errorf("git port: %w", err) |
| 484 | } |
| 485 | ret.gitPort = gitPort |
| 486 | return ret, nil |
| 487 | } |
| 488 | |
| 489 | func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error { |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 490 | cmdArgs := []string{ |
| 491 | "create", |
| David Crawshaw | 66cf74e | 2025-05-05 08:48:39 -0700 | [diff] [blame] | 492 | "-i", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 493 | "--name", cntrName, |
| 494 | "-p", hostPort + ":80", // forward container port 80 to a host port |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 495 | "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 496 | } |
| Philip Zeyliger | 3d2eff0 | 2025-05-27 09:30:31 -0700 | [diff] [blame] | 497 | if !(config.OneShot || !config.TermUI) { |
| David Crawshaw | 66cf74e | 2025-05-05 08:48:39 -0700 | [diff] [blame] | 498 | cmdArgs = append(cmdArgs, "-t") |
| 499 | } |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 500 | |
| 501 | for _, envVar := range getEnvForwardingFromGitConfig(ctx) { |
| 502 | cmdArgs = append(cmdArgs, "-e", envVar) |
| 503 | } |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 504 | if config.ModelURL != "" { |
| David Crawshaw | 3659d87 | 2025-05-05 17:52:23 -0700 | [diff] [blame] | 505 | cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 506 | } |
| 507 | if config.SketchPubKey != "" { |
| 508 | cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey) |
| 509 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 510 | if config.SSHPort > 0 { |
| 511 | cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port |
| 512 | } else { |
| Philip Zeyliger | 87d29ef | 2025-05-16 20:25:28 -0700 | [diff] [blame] | 513 | cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh. |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 514 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 515 | if relPath != "." { |
| 516 | cmdArgs = append(cmdArgs, "-w", "/app/"+relPath) |
| 517 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 518 | // colima does this by default, but Linux docker seems to need this set explicitly |
| 519 | cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway") |
| Josh Bleecher Snyder | ac761c9 | 2025-05-16 18:58:45 +0000 | [diff] [blame] | 520 | |
| David Crawshaw | 1bd636c | 2025-06-13 19:56:27 +0000 | [diff] [blame] | 521 | // Add seccomp profile to prevent killing PID 1 (the sketch process itself) |
| 522 | // Write the seccomp profile to cache directory if it doesn't exist |
| 523 | seccompPath, err := ensureSeccompProfile(ctx) |
| 524 | if err != nil { |
| 525 | return fmt.Errorf("failed to create seccomp profile: %w", err) |
| 526 | } |
| 527 | cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath) |
| 528 | |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 529 | // Add subtrace environment variable if token is provided |
| 530 | if config.SubtraceToken != "" { |
| 531 | cmdArgs = append(cmdArgs, "-e", "SUBTRACE_TOKEN="+config.SubtraceToken) |
| 532 | cmdArgs = append(cmdArgs, "-e", "SUBTRACE_HTTP2=1") |
| 533 | } |
| 534 | |
| Josh Bleecher Snyder | ac761c9 | 2025-05-16 18:58:45 +0000 | [diff] [blame] | 535 | // Add volume mounts if specified |
| 536 | for _, mount := range config.Mounts { |
| 537 | if mount != "" { |
| 538 | cmdArgs = append(cmdArgs, "-v", mount) |
| 539 | } |
| 540 | } |
| Philip Zeyliger | d4be7a2 | 2025-06-15 09:39:00 -0700 | [diff] [blame] | 541 | cmdArgs = append(cmdArgs, imgName) |
| 542 | |
| 543 | // Add command: either [sketch] or [subtrace run -- sketch] |
| 544 | if config.SubtraceToken != "" { |
| 545 | cmdArgs = append(cmdArgs, "/usr/local/bin/subtrace", "run", "--", "/bin/sketch") |
| 546 | } else { |
| 547 | cmdArgs = append(cmdArgs, "/bin/sketch") |
| 548 | } |
| 549 | |
| 550 | // Add all sketch arguments |
| 551 | cmdArgs = append(cmdArgs, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 552 | "-unsafe", |
| 553 | "-addr=:80", |
| 554 | "-session-id="+config.SessionID, |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 555 | "-git-username="+config.GitUsername, |
| 556 | "-git-email="+config.GitEmail, |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 557 | "-outside-hostname="+config.OutsideHostname, |
| 558 | "-outside-os="+config.OutsideOS, |
| 559 | "-outside-working-dir="+config.OutsideWorkingDir, |
| Josh Bleecher Snyder | 33032d3 | 2025-05-30 16:28:21 +0000 | [diff] [blame] | 560 | fmt.Sprintf("-max-dollars=%f", config.MaxDollars), |
| Josh Bleecher Snyder | 3cae7d9 | 2025-04-30 09:54:29 -0700 | [diff] [blame] | 561 | "-open=false", |
| Philip Zeyliger | 613c0f5 | 2025-05-15 16:36:22 -0700 | [diff] [blame] | 562 | "-termui="+fmt.Sprintf("%t", config.TermUI), |
| Philip Zeyliger | cabfa55 | 2025-05-19 16:14:28 -0700 | [diff] [blame] | 563 | "-verbose="+fmt.Sprintf("%t", config.Verbose), |
| Josh Bleecher Snyder | b1cca6f | 2025-05-06 01:52:55 +0000 | [diff] [blame] | 564 | "-x="+config.ExperimentFlag, |
| Philip Zeyliger | be7802a | 2025-06-04 20:15:25 +0000 | [diff] [blame] | 565 | "-branch-prefix="+config.BranchPrefix, |
| philip.zeyliger | 6d3de48 | 2025-06-10 19:38:14 -0700 | [diff] [blame] | 566 | "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub), |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 567 | ) |
| philip.zeyliger | 8773e68 | 2025-06-11 21:36:21 -0700 | [diff] [blame] | 568 | // Set SSH connection string based on session ID for SSH Theater |
| 569 | cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID) |
| David Crawshaw | 5a7b369 | 2025-05-05 16:49:15 -0700 | [diff] [blame] | 570 | if config.Model != "" { |
| 571 | cmdArgs = append(cmdArgs, "-model="+config.Model) |
| 572 | } |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 573 | if config.GitRemoteUrl != "" { |
| 574 | cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl) |
| 575 | if config.Commit == "" { |
| 576 | panic("Commit should have been set when GitRemoteUrl was set") |
| 577 | } |
| 578 | cmdArgs = append(cmdArgs, "-commit="+config.Commit) |
| Josh Bleecher Snyder | 664404e | 2025-06-04 21:56:42 +0000 | [diff] [blame] | 579 | cmdArgs = append(cmdArgs, "-upstream="+config.Upstream) |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 580 | } |
| 581 | if config.OutsideHTTP != "" { |
| 582 | cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP) |
| 583 | } |
| Josh Bleecher Snyder | e3c2f22 | 2025-05-15 20:54:52 +0000 | [diff] [blame] | 584 | cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr) |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 585 | if config.Prompt != "" { |
| 586 | cmdArgs = append(cmdArgs, "-prompt", config.Prompt) |
| 587 | } |
| 588 | if config.OneShot { |
| 589 | cmdArgs = append(cmdArgs, "-one-shot") |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 590 | } |
| Josh Bleecher Snyder | e3c2f22 | 2025-05-15 20:54:52 +0000 | [diff] [blame] | 591 | if config.ModelURL == "" { |
| 592 | // Forward ANTHROPIC_API_KEY for direct use. |
| 593 | // TODO: have outtie run an http proxy? |
| 594 | // TODO: select and forward the relevant API key based on the model |
| 595 | cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY")) |
| 596 | } |
| Philip Zeyliger | 194bfa8 | 2025-06-24 06:03:06 -0700 | [diff] [blame] | 597 | // Add MCP server configurations |
| 598 | for _, mcpServer := range config.MCPServers { |
| 599 | cmdArgs = append(cmdArgs, "-mcp", mcpServer) |
| 600 | } |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 601 | |
| 602 | // Add additional docker arguments if provided |
| 603 | if config.DockerArgs != "" { |
| 604 | // Parse space-separated docker arguments with support for quotes and escaping |
| 605 | args := parseDockerArgs(config.DockerArgs) |
| 606 | // Insert arguments after "create" but before other arguments |
| 607 | for i := len(args) - 1; i >= 0; i-- { |
| 608 | cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...) |
| 609 | } |
| 610 | } |
| 611 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 612 | if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil { |
| 613 | return fmt.Errorf("docker create: %s, %w", out, err) |
| 614 | } |
| 615 | return nil |
| 616 | } |
| 617 | |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 618 | func buildLinuxSketchBin(ctx context.Context) (string, error) { |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 619 | // Detect if race detector is enabled and use a different cache path |
| 620 | raceEnabled := RaceEnabled() |
| 621 | cacheSuffix := "" |
| 622 | if raceEnabled { |
| 623 | cacheSuffix = "-race" |
| 624 | } |
| 625 | |
| 626 | homeDir, err := os.UserHomeDir() |
| 627 | if err != nil { |
| 628 | return "", err |
| 629 | } |
| 630 | |
| 631 | linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix) |
| 632 | if err := os.MkdirAll(linuxGopath, 0o777); err != nil { |
| 633 | return "", err |
| 634 | } |
| 635 | |
| 636 | // When race detector is enabled, use Docker to build the Linux binary |
| 637 | if raceEnabled { |
| 638 | return buildLinuxSketchBinWithDocker(ctx, linuxGopath) |
| 639 | } |
| 640 | |
| 641 | // Standard non-race build using cross-compilation |
| Pokey Rule | a9a786b | 2025-05-12 10:52:34 +0100 | [diff] [blame] | 642 | // Change to directory containing dockerimg.go for module detection |
| 643 | _, codeFile, _, _ := runtime.Caller(0) |
| 644 | codeDir := filepath.Dir(codeFile) |
| 645 | if currentDir, err := os.Getwd(); err != nil { |
| 646 | slog.WarnContext(ctx, "could not get current directory", "err", err) |
| 647 | } else { |
| 648 | if err := os.Chdir(codeDir); err != nil { |
| 649 | slog.WarnContext(ctx, "could not change to code directory for module check", "err", err) |
| 650 | } else { |
| 651 | defer func() { |
| 652 | _ = os.Chdir(currentDir) |
| 653 | }() |
| 654 | } |
| 655 | } |
| 656 | |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 657 | verToInstall := "@latest" |
| 658 | if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil { |
| 659 | return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err) |
| 660 | } else { |
| 661 | if strings.TrimSpace(string(out)) == "sketch.dev" { |
| David Crawshaw | 094e4d2 | 2025-04-24 11:35:14 -0700 | [diff] [blame] | 662 | slog.DebugContext(ctx, "built linux agent from currently checked out module") |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 663 | verToInstall = "" |
| 664 | } |
| 665 | } |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 666 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 667 | start := time.Now() |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 668 | args := []string{"install"} |
| 669 | args = append(args, "sketch.dev/cmd/sketch"+verToInstall) |
| 670 | |
| 671 | cmd := exec.CommandContext(ctx, "go", args...) |
| David Crawshaw | b9eaef5 | 2025-04-17 15:23:18 -0700 | [diff] [blame] | 672 | cmd.Env = append( |
| 673 | os.Environ(), |
| 674 | "GOOS=linux", |
| 675 | "CGO_ENABLED=0", |
| 676 | "GOTOOLCHAIN=auto", |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 677 | "GOPATH="+linuxGopath, |
| Josh Bleecher Snyder | fae1757 | 2025-04-21 11:48:05 -0700 | [diff] [blame] | 678 | "GOBIN=", |
| David Crawshaw | b9eaef5 | 2025-04-17 15:23:18 -0700 | [diff] [blame] | 679 | ) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 680 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 681 | out, err := cmd.CombinedOutput() |
| 682 | if err != nil { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 683 | 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 684 | return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err) |
| 685 | } else { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 686 | 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 687 | } |
| 688 | |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 689 | if runtime.GOOS != "linux" { |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 690 | return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 691 | } |
| David Crawshaw | c7e7796 | 2025-05-03 13:20:18 -0700 | [diff] [blame] | 692 | // If we are already on Linux, there's no extra platform name in the path |
| 693 | return filepath.Join(linuxGopath, "bin", "sketch"), nil |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 694 | } |
| 695 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 696 | func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 697 | localAddr := "" |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 698 | if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 699 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 700 | } else { |
| 701 | v4, _, found := strings.Cut(string(out), "\n") |
| 702 | if !found { |
| 703 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 704 | } |
| 705 | localAddr = v4 |
| 706 | if strings.HasPrefix(localAddr, "0.0.0.0") { |
| 707 | localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0") |
| 708 | } |
| 709 | } |
| 710 | return localAddr, nil |
| 711 | } |
| 712 | |
| 713 | // Contact the container and configure it. |
| Philip Zeyliger | bc8c8dc | 2025-05-21 13:19:13 -0700 | [diff] [blame] | 714 | func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 715 | localURL := "http://" + localAddr |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 716 | |
| 717 | initMsg, err := json.Marshal( |
| 718 | server.InitRequest{ |
| Sean McCullough | 7013e9e | 2025-05-14 02:03:58 +0000 | [diff] [blame] | 719 | HostAddr: localAddr, |
| 720 | SSHAuthorizedKeys: sshAuthorizedKeys, |
| 721 | SSHServerIdentity: sshServerIdentity, |
| 722 | SSHContainerCAKey: sshContainerCAKey, |
| 723 | SSHHostCertificate: sshHostCertificate, |
| 724 | SSHAvailable: sshAvailable, |
| 725 | SSHError: sshError, |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 726 | }) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 727 | if err != nil { |
| 728 | return fmt.Errorf("init msg: %w", err) |
| 729 | } |
| 730 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 731 | // Note: this /init POST is handled in loop/server/loophttp.go: |
| 732 | initMsgByteReader := bytes.NewReader(initMsg) |
| 733 | req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader) |
| 734 | if err != nil { |
| 735 | return err |
| 736 | } |
| 737 | |
| 738 | var res *http.Response |
| 739 | for i := 0; ; i++ { |
| 740 | time.Sleep(100 * time.Millisecond) |
| 741 | // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes. |
| 742 | initMsgByteReader.Reset(initMsg) |
| 743 | res, err = http.DefaultClient.Do(req) |
| 744 | if err != nil { |
| David Crawshaw | 99231ba | 2025-05-03 10:48:26 -0700 | [diff] [blame] | 745 | if i < 100 { |
| 746 | if i%10 == 0 { |
| 747 | slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error())) |
| 748 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 749 | continue |
| 750 | } |
| 751 | return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err) |
| 752 | } |
| 753 | break |
| 754 | } |
| 755 | resBytes, _ := io.ReadAll(res.Body) |
| 756 | if res.StatusCode != http.StatusOK { |
| 757 | return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes) |
| 758 | } |
| 759 | return nil |
| 760 | } |
| 761 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 762 | func findOrBuildDockerImage(ctx context.Context, gitRoot, baseImage string, forceRebuild, verbose bool) (imgName string, err error) { |
| 763 | // Default to the published sketch image if no base image is specified |
| 764 | if baseImage == "" { |
| 765 | imageTag := dockerfileBaseHash() |
| 766 | baseImage = fmt.Sprintf("%s:%s", dockerImgName, imageTag) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 767 | } |
| 768 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 769 | // Ensure the base image exists locally, pull if necessary |
| 770 | if err := ensureBaseImageExists(ctx, baseImage); err != nil { |
| 771 | return "", fmt.Errorf("failed to ensure base image %s exists: %w", baseImage, err) |
| 772 | } |
| 773 | |
| 774 | // Get the base image container ID for caching |
| 775 | baseImageID, err := getDockerImageID(ctx, baseImage) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 776 | if err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 777 | return "", fmt.Errorf("failed to get base image ID for %s: %w", baseImage, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 778 | } |
| 779 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 780 | // Create a cache key based on base image ID and working directory |
| 781 | // Docker naming conventions restrict you to 20 characters per path component |
| 782 | // and only allow lowercase letters, digits, underscores, and dashes, so encoding |
| 783 | // the hash and the repo directory is sadly a bit of a non-starter. |
| 784 | cacheKey := createCacheKey(baseImageID, gitRoot) |
| 785 | imgName = "sketch-" + cacheKey |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 786 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 787 | // Check if the cached image exists and is up to date |
| 788 | if !forceRebuild { |
| 789 | if exists, err := dockerImageExists(ctx, imgName); err != nil { |
| 790 | return "", fmt.Errorf("failed to check if image exists: %w", err) |
| 791 | } else if exists { |
| 792 | if verbose { |
| 793 | fmt.Printf("using cached image %s\n", imgName) |
| Kilian Lackhove | 23772f4 | 2025-06-18 20:28:58 +0200 | [diff] [blame] | 794 | } |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 795 | return imgName, nil |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 796 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 797 | } |
| 798 | |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 799 | // Build the layered image |
| 800 | if err := buildLayeredImage(ctx, imgName, baseImage, gitRoot, verbose); err != nil { |
| 801 | return "", fmt.Errorf("failed to build layered image: %w", err) |
| 802 | } |
| 803 | |
| 804 | return imgName, nil |
| 805 | } |
| 806 | |
| 807 | // ensureBaseImageExists checks if the base image exists locally and pulls it if not |
| 808 | func ensureBaseImageExists(ctx context.Context, imageName string) error { |
| 809 | exists, err := dockerImageExists(ctx, imageName) |
| 810 | if err != nil { |
| 811 | return fmt.Errorf("failed to check if image exists: %w", err) |
| 812 | } |
| 813 | |
| 814 | if !exists { |
| 815 | fmt.Printf("🐋 pulling base image %s...\n", imageName) |
| 816 | if out, err := combinedOutput(ctx, "docker", "pull", imageName); err != nil { |
| 817 | return fmt.Errorf("docker pull %s failed: %s: %w", imageName, out, err) |
| 818 | } |
| 819 | fmt.Printf("✅ successfully pulled %s\n", imageName) |
| 820 | } |
| 821 | |
| 822 | return nil |
| 823 | } |
| 824 | |
| 825 | // getDockerImageID gets the container ID for a Docker image |
| 826 | func getDockerImageID(ctx context.Context, imageName string) (string, error) { |
| 827 | out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{.Id}}", imageName) |
| 828 | if err != nil { |
| 829 | return "", err |
| 830 | } |
| 831 | return strings.TrimSpace(string(out)), nil |
| 832 | } |
| 833 | |
| 834 | // createCacheKey creates a cache key from base image ID and working directory |
| 835 | func createCacheKey(baseImageID, gitRoot string) string { |
| 836 | h := sha256.New() |
| 837 | h.Write([]byte(baseImageID)) |
| 838 | h.Write([]byte(gitRoot)) |
| 839 | return hex.EncodeToString(h.Sum(nil))[:12] // Use first 12 chars for shorter name |
| 840 | } |
| 841 | |
| 842 | // dockerImageExists checks if a Docker image exists locally |
| 843 | func dockerImageExists(ctx context.Context, imageName string) (bool, error) { |
| 844 | out, err := combinedOutput(ctx, "docker", "inspect", imageName) |
| 845 | if err != nil { |
| 846 | if strings.Contains(strings.ToLower(string(out)), "no such object") || |
| 847 | strings.Contains(strings.ToLower(string(out)), "no such image") { |
| 848 | return false, nil |
| 849 | } |
| 850 | return false, err |
| 851 | } |
| 852 | return true, nil |
| 853 | } |
| 854 | |
| 855 | // buildLayeredImage builds a new Docker image by layering the repo on top of the base image |
| 856 | // TODO: git config stuff could be environment variables at runtime for email and username. |
| 857 | // The git docs seem to say that http.postBuffer is a bug in our git proxy more than a thing |
| 858 | // that's needed, but we haven't found the bug yet! |
| Philip Zeyliger | 882b1d1 | 2025-07-02 20:04:08 -0700 | [diff] [blame] | 859 | // |
| 860 | // TODO: There is a caching tension. A base image is great for tools (like, some version |
| 861 | // of Go). Then you want a git repo, which is much faster to incrementally fetch rather |
| 862 | // than cloning every time. Then you want some build artifacts, like perhaps the |
| 863 | // "go mod download" cache, or the "go build" cache or the "npm install" cache. |
| 864 | // The implementation here copies the working directory (not just the git repo!), |
| 865 | // and runs "go mod download". This is an ok compromise, but a power user might want |
| 866 | // less caching or more caching, depending on their use case. One approach we could take |
| 867 | // is to punt entirely if /app/.git already exists. If the user has provided a -base-image with |
| 868 | // their git repo, let's assume they know what they're doing, and they've customized their image |
| 869 | // for their use case. On the other side of the spectrum is cloning their repo every time, |
| 870 | // or running git clean -xdf, which minimizes surprises but slows down builds. |
| 871 | // Note that buildx has some support for conditional COPY, but without buildx, which |
| 872 | // we can't reliably depend on, we have to run the base image to inspect its file system, |
| 873 | // and then we can decide what to do. |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 874 | func buildLayeredImage(ctx context.Context, imgName, baseImage, gitRoot string, _ bool) error { |
| 875 | dockerfileContent := fmt.Sprintf(`FROM %s |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 876 | COPY . /app |
| 877 | WORKDIR /app |
| 878 | RUN if [ -f go.mod ]; then go mod download; fi |
| 879 | CMD ["/bin/sketch"] |
| 880 | `, baseImage) |
| 881 | |
| 882 | // Create a temporary directory for the Dockerfile |
| 883 | tmpDir, err := os.MkdirTemp("", "sketch-docker-*") |
| 884 | if err != nil { |
| 885 | return fmt.Errorf("failed to create temporary directory: %w", err) |
| 886 | } |
| 887 | defer os.RemoveAll(tmpDir) |
| 888 | |
| 889 | dockerfilePath := filepath.Join(tmpDir, "Dockerfile") |
| 890 | if err := os.WriteFile(dockerfilePath, []byte(dockerfileContent), 0o666); err != nil { |
| 891 | return fmt.Errorf("failed to write Dockerfile: %w", err) |
| 892 | } |
| 893 | |
| 894 | // Get git user info |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 895 | var gitUserEmail, gitUserName string |
| 896 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 897 | return fmt.Errorf("git user.email is not set. Please run 'git config --global user.email \"your.email@example.com\"' to set your email address") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 898 | } else { |
| 899 | gitUserEmail = strings.TrimSpace(string(out)) |
| 900 | } |
| 901 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 902 | return fmt.Errorf("git user.name is not set. Please run 'git config --global user.name \"Your Name\"' to set your name") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 903 | } else { |
| 904 | gitUserName = strings.TrimSpace(string(out)) |
| 905 | } |
| 906 | |
| 907 | start := time.Now() |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 908 | cmdArgs := []string{ |
| 909 | "build", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 910 | "-t", imgName, |
| 911 | "-f", dockerfilePath, |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 912 | "--build-arg", "GIT_USER_EMAIL=" + gitUserEmail, |
| 913 | "--build-arg", "GIT_USER_NAME=" + gitUserName, |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 914 | ".", |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 915 | } |
| 916 | |
| Philip Zeyliger | 2343f8a | 2025-06-17 06:16:19 -0700 | [diff] [blame] | 917 | cmd := exec.CommandContext(ctx, "docker", cmdArgs...) |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 918 | cmd.Dir = gitRoot |
| David Crawshaw | 31f1524 | 2025-05-06 16:03:49 -0700 | [diff] [blame] | 919 | // We print the docker build output whether or not the user |
| 920 | // has selected --verbose. Building an image takes a while |
| 921 | // and this gives good context. |
| David Crawshaw | b5f6a00 | 2025-05-05 08:27:16 -0700 | [diff] [blame] | 922 | cmd.Stdout = os.Stdout |
| 923 | cmd.Stderr = os.Stderr |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 924 | fmt.Printf("🏗️ building docker image %s from base %s...\n", imgName, baseImage) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 925 | |
| 926 | err = run(ctx, "docker build", cmd) |
| 927 | if err != nil { |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 928 | return fmt.Errorf("docker build failed: %v", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 929 | } |
| 930 | fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond)) |
| Philip Zeyliger | 983b58a | 2025-07-02 19:42:08 -0700 | [diff] [blame] | 931 | return nil |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 932 | } |
| 933 | |
| Philip Zeyliger | d6d12d1 | 2025-05-19 19:19:21 -0700 | [diff] [blame] | 934 | func checkForEmptyGitRepo(ctx context.Context, path string) error { |
| 935 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD") |
| 936 | cmd.Dir = path |
| 937 | _, err := cmd.CombinedOutput() |
| 938 | if err != nil { |
| 939 | return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s", |
| 940 | "git commit --allow-empty -m 'initial commit'") |
| 941 | } |
| 942 | return nil |
| 943 | } |
| 944 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 945 | func findGitRoot(ctx context.Context, path string) (string, error) { |
| Marc-Antoine Ruel | 467c396 | 2025-06-29 13:32:59 -0400 | [diff] [blame] | 946 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 947 | cmd.Dir = path |
| 948 | out, err := cmd.CombinedOutput() |
| 949 | if err != nil { |
| 950 | if strings.Contains(string(out), "not a git repository") { |
| 951 | return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo. |
| 952 | Consider one of the following options: |
| 953 | - cd to a different dir that is already part of a git repo first, or |
| 954 | - to create a new git repo from this directory (%s), run this command: |
| 955 | |
| 956 | git init . && git commit --allow-empty -m "initial commit" |
| 957 | |
| 958 | and try running sketch again. |
| 959 | `, path, path) |
| 960 | } |
| Marc-Antoine Ruel | 467c396 | 2025-06-29 13:32:59 -0400 | [diff] [blame] | 961 | return "", fmt.Errorf("git rev-parse --show-toplevel: %s: %w", out, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 962 | } |
| Marc-Antoine Ruel | 467c396 | 2025-06-29 13:32:59 -0400 | [diff] [blame] | 963 | // The returned path is absolute. |
| 964 | return strings.TrimSpace(string(out)), nil |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 965 | } |
| 966 | |
| Josh Bleecher Snyder | 2772f63 | 2025-05-01 21:42:35 +0000 | [diff] [blame] | 967 | // getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker |
| 968 | // from git config using the sketch.envfwd multi-valued key. |
| 969 | func getEnvForwardingFromGitConfig(ctx context.Context) []string { |
| 970 | outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput() |
| 971 | out := string(outb) |
| 972 | if err != nil { |
| 973 | if strings.Contains(out, "key does not exist") { |
| 974 | return nil |
| 975 | } |
| 976 | slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out) |
| 977 | return nil |
| 978 | } |
| 979 | |
| 980 | var envVars []string |
| 981 | for envVar := range strings.Lines(out) { |
| 982 | envVar = strings.TrimSpace(envVar) |
| 983 | if envVar == "" { |
| 984 | continue |
| 985 | } |
| 986 | envVars = append(envVars, envVar+"="+os.Getenv(envVar)) |
| 987 | } |
| 988 | return envVars |
| 989 | } |
| Philip Zeyliger | 1dc2137 | 2025-05-05 19:54:44 +0000 | [diff] [blame] | 990 | |
| 991 | // parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings. |
| 992 | // It handles quoted arguments and escaped characters. |
| 993 | // |
| 994 | // Examples: |
| 995 | // |
| 996 | // --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"] |
| 997 | // --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"] |
| 998 | // --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""] |
| 999 | func parseDockerArgs(args string) []string { |
| 1000 | if args = strings.TrimSpace(args); args == "" { |
| 1001 | return []string{} |
| 1002 | } |
| 1003 | |
| 1004 | var result []string |
| 1005 | var current strings.Builder |
| 1006 | inQuotes := false |
| 1007 | escapeNext := false |
| 1008 | quoteChar := rune(0) |
| 1009 | |
| 1010 | for _, char := range args { |
| 1011 | if escapeNext { |
| 1012 | current.WriteRune(char) |
| 1013 | escapeNext = false |
| 1014 | continue |
| 1015 | } |
| 1016 | |
| 1017 | if char == '\\' { |
| 1018 | escapeNext = true |
| 1019 | continue |
| 1020 | } |
| 1021 | |
| 1022 | if char == '"' || char == '\'' { |
| 1023 | if !inQuotes { |
| 1024 | inQuotes = true |
| 1025 | quoteChar = char |
| 1026 | continue |
| 1027 | } else if char == quoteChar { |
| 1028 | inQuotes = false |
| 1029 | quoteChar = rune(0) |
| 1030 | continue |
| 1031 | } |
| 1032 | // Non-matching quote character inside quotes |
| 1033 | current.WriteRune(char) |
| 1034 | continue |
| 1035 | } |
| 1036 | |
| 1037 | // Space outside of quotes is an argument separator |
| 1038 | if char == ' ' && !inQuotes { |
| 1039 | if current.Len() > 0 { |
| 1040 | result = append(result, current.String()) |
| 1041 | current.Reset() |
| 1042 | } |
| 1043 | continue |
| 1044 | } |
| 1045 | |
| 1046 | current.WriteRune(char) |
| 1047 | } |
| 1048 | |
| 1049 | // Add the last argument if there is one |
| 1050 | if current.Len() > 0 { |
| 1051 | result = append(result, current.String()) |
| 1052 | } |
| 1053 | |
| 1054 | return result |
| 1055 | } |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1056 | |
| 1057 | // buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled. |
| 1058 | // This avoids cross-compilation issues with CGO which is required for the race detector. |
| Josh Bleecher Snyder | 3e6a4c4 | 2025-05-23 17:29:57 +0000 | [diff] [blame] | 1059 | // Mounts host Go module cache and build cache for faster subsequent builds. |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1060 | func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) { |
| 1061 | // Find the git repo root |
| 1062 | currentDir, err := os.Getwd() |
| 1063 | if err != nil { |
| 1064 | return "", fmt.Errorf("could not get current directory: %w", err) |
| 1065 | } |
| 1066 | |
| 1067 | gitRoot, err := findGitRoot(ctx, currentDir) |
| 1068 | if err != nil { |
| 1069 | return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err) |
| 1070 | } |
| 1071 | |
| Josh Bleecher Snyder | 3e6a4c4 | 2025-05-23 17:29:57 +0000 | [diff] [blame] | 1072 | // Get host Go cache directories to mount for faster builds |
| 1073 | goCacheDir, err := getHostGoCacheDir(ctx) |
| 1074 | if err != nil { |
| 1075 | return "", fmt.Errorf("failed to get host GOCACHE: %w", err) |
| 1076 | } |
| 1077 | goModCacheDir, err := getHostGoModCacheDir(ctx) |
| 1078 | if err != nil { |
| 1079 | return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err) |
| 1080 | } |
| 1081 | |
| 1082 | slog.DebugContext(ctx, "building Linux sketch binary with race detector using Docker", "git_root", gitRoot, "gocache", goCacheDir, "gomodcache", goModCacheDir) |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1083 | |
| 1084 | // Use the published Docker image tag |
| 1085 | imageTag := dockerfileBaseHash() |
| 1086 | imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag) |
| 1087 | |
| 1088 | // Create destination directory for the binary |
| 1089 | destPath := filepath.Join(linuxGopath, "bin") |
| 1090 | if err := os.MkdirAll(destPath, 0o777); err != nil { |
| 1091 | return "", fmt.Errorf("failed to create destination directory: %w", err) |
| 1092 | } |
| 1093 | destFile := filepath.Join(destPath, "sketch") |
| 1094 | |
| 1095 | // Create a unique container name |
| 1096 | containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano()) |
| 1097 | |
| Josh Bleecher Snyder | 3e6a4c4 | 2025-05-23 17:29:57 +0000 | [diff] [blame] | 1098 | // Run a container with the repo mounted and Go caches for faster builds |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1099 | start := time.Now() |
| 1100 | slog.DebugContext(ctx, "running Docker container to build sketch with race detector") |
| 1101 | |
| 1102 | // Use explicit output path for clarity |
| 1103 | runArgs := []string{ |
| 1104 | "run", |
| 1105 | "--name", containerID, |
| 1106 | "-v", gitRoot + ":/app", |
| Josh Bleecher Snyder | 3e6a4c4 | 2025-05-23 17:29:57 +0000 | [diff] [blame] | 1107 | "-v", goCacheDir + ":/root/.cache/go-build", |
| 1108 | "-v", goModCacheDir + ":/go/pkg/mod", |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1109 | "-w", "/app", |
| 1110 | imgName, |
| Josh Bleecher Snyder | f4f929a | 2025-05-23 17:19:26 +0000 | [diff] [blame] | 1111 | "sh", "-c", "cd /app && mkdir -p /tmp/sketch-out && go build -buildvcs=false -race -o /tmp/sketch-out/sketch sketch.dev/cmd/sketch", |
| Philip Zeyliger | 4acf006 | 2025-05-22 13:53:46 -0700 | [diff] [blame] | 1112 | } |
| 1113 | |
| 1114 | out, err := combinedOutput(ctx, "docker", runArgs...) |
| 1115 | if err != nil { |
| 1116 | // Print the output to help with debugging |
| 1117 | slog.ErrorContext(ctx, "docker run for race build failed", |
| 1118 | slog.String("output", string(out)), |
| 1119 | slog.String("error", err.Error())) |
| 1120 | return "", fmt.Errorf("docker run failed: %s: %w", out, err) |
| 1121 | } |
| 1122 | |
| 1123 | slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start)) |
| 1124 | |
| 1125 | // Copy the binary from the container using the explicit path |
| 1126 | out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile) |
| 1127 | if err != nil { |
| 1128 | return "", fmt.Errorf("docker cp failed: %s: %w", out, err) |
| 1129 | } |
| 1130 | |
| 1131 | // Clean up the container |
| 1132 | if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil { |
| 1133 | slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out)) |
| 1134 | } |
| 1135 | |
| 1136 | // Make the binary executable |
| 1137 | if err := os.Chmod(destFile, 0o755); err != nil { |
| 1138 | return "", fmt.Errorf("failed to make binary executable: %w", err) |
| 1139 | } |
| 1140 | |
| 1141 | return destFile, nil |
| 1142 | } |
| Josh Bleecher Snyder | 3e6a4c4 | 2025-05-23 17:29:57 +0000 | [diff] [blame] | 1143 | |
| 1144 | // getHostGoCacheDir returns the host's GOCACHE directory |
| 1145 | func getHostGoCacheDir(ctx context.Context) (string, error) { |
| 1146 | out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput() |
| 1147 | if err != nil { |
| 1148 | return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err) |
| 1149 | } |
| 1150 | return strings.TrimSpace(string(out)), nil |
| 1151 | } |
| 1152 | |
| 1153 | // getHostGoModCacheDir returns the host's GOMODCACHE directory |
| 1154 | func getHostGoModCacheDir(ctx context.Context) (string, error) { |
| 1155 | out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput() |
| 1156 | if err != nil { |
| 1157 | return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err) |
| 1158 | } |
| 1159 | return strings.TrimSpace(string(out)), nil |
| 1160 | } |
| David Crawshaw | 1bd636c | 2025-06-13 19:56:27 +0000 | [diff] [blame] | 1161 | |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1162 | // copyEmbeddedLinuxBinaryToContainer copies the embedded linux binary to the container |
| 1163 | func copyEmbeddedLinuxBinaryToContainer(ctx context.Context, containerName string) error { |
| Josh Bleecher Snyder | 5ae245b | 2025-07-08 22:00:24 +0000 | [diff] [blame^] | 1164 | out, err := combinedOutput(ctx, "docker", "version", "--format", "{{.Server.Arch}}") |
| 1165 | if err != nil { |
| 1166 | return fmt.Errorf("failed to detect Docker server architecture: %s: %w", out, err) |
| 1167 | } |
| 1168 | arch := strings.TrimSpace(string(out)) |
| 1169 | |
| 1170 | bin := embedded.LinuxBinary(arch) |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1171 | if bin == nil { |
| Josh Bleecher Snyder | 5ae245b | 2025-07-08 22:00:24 +0000 | [diff] [blame^] | 1172 | return fmt.Errorf("no embedded linux binary for architecture %q", arch) |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1173 | } |
| 1174 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1175 | // Stream a tarball to docker cp. |
| 1176 | pr, pw := io.Pipe() |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1177 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1178 | errCh := make(chan error, 1) |
| 1179 | go func() { |
| 1180 | defer pw.Close() |
| 1181 | tw := tar.NewWriter(pw) |
| 1182 | |
| 1183 | hdr := &tar.Header{ |
| 1184 | Name: "bin/sketch", // final path inside the container |
| 1185 | Mode: 0o700, |
| 1186 | Size: int64(len(bin)), |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1187 | } |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1188 | if err := tw.WriteHeader(hdr); err != nil { |
| 1189 | errCh <- fmt.Errorf("failed to write tar header: %w", err) |
| 1190 | return |
| 1191 | } |
| 1192 | if _, err := tw.Write(bin); err != nil { |
| 1193 | errCh <- fmt.Errorf("failed to write binary to tar: %w", err) |
| 1194 | return |
| 1195 | } |
| 1196 | if err := tw.Close(); err != nil { |
| 1197 | errCh <- fmt.Errorf("failed to close tar writer: %w", err) |
| 1198 | return |
| 1199 | } |
| 1200 | errCh <- nil |
| 1201 | }() |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1202 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1203 | cmd := exec.CommandContext(ctx, "docker", "cp", "-", containerName+":/") |
| 1204 | cmd.Stdin = pr |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1205 | |
| Josh Bleecher Snyder | c9898fd | 2025-07-08 21:09:18 +0000 | [diff] [blame] | 1206 | out, cmdErr := cmd.CombinedOutput() |
| 1207 | |
| 1208 | if tarErr := <-errCh; tarErr != nil { |
| 1209 | return tarErr |
| 1210 | } |
| 1211 | if cmdErr != nil { |
| 1212 | return fmt.Errorf("docker cp failed: %s: %w", out, cmdErr) |
| 1213 | } |
| Josh Bleecher Snyder | 1c18ec9 | 2025-07-08 10:55:54 -0700 | [diff] [blame] | 1214 | return nil |
| 1215 | } |
| 1216 | |
| David Crawshaw | 1bd636c | 2025-06-13 19:56:27 +0000 | [diff] [blame] | 1217 | const seccompProfile = `{ |
| 1218 | "defaultAction": "SCMP_ACT_ALLOW", |
| 1219 | "syscalls": [ |
| 1220 | { |
| 1221 | "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"], |
| 1222 | "action": "SCMP_ACT_ERRNO", |
| 1223 | "args": [ |
| 1224 | { |
| 1225 | "index": 0, |
| 1226 | "value": 1, |
| 1227 | "op": "SCMP_CMP_EQ" |
| 1228 | } |
| 1229 | ] |
| 1230 | } |
| 1231 | ] |
| 1232 | }` |
| 1233 | |
| 1234 | // ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist. |
| 1235 | func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) { |
| 1236 | homeDir, err := os.UserHomeDir() |
| 1237 | if err != nil { |
| 1238 | return "", fmt.Errorf("failed to get home directory: %w", err) |
| 1239 | } |
| 1240 | cacheDir := filepath.Join(homeDir, ".cache", "sketch") |
| 1241 | if err := os.MkdirAll(cacheDir, 0o755); err != nil { |
| 1242 | return "", fmt.Errorf("failed to create cache directory: %w", err) |
| 1243 | } |
| 1244 | seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json") |
| 1245 | |
| 1246 | curBytes, err := os.ReadFile(seccompPath) |
| 1247 | if err != nil && !os.IsNotExist(err) { |
| 1248 | return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err) |
| 1249 | } |
| 1250 | if string(curBytes) == seccompProfile { |
| 1251 | return seccompPath, nil // File already exists and matches the expected profile |
| 1252 | } |
| 1253 | |
| 1254 | if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil { |
| 1255 | return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err) |
| 1256 | } |
| 1257 | slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath) |
| 1258 | return seccompPath, nil |
| 1259 | } |