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