This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

core / spindle / engines / microvm / engine.go
18 kB 574 lines
1package microvm 2 3import ( 4 "context" 5 "encoding/json" 6 "errors" 7 "fmt" 8 "io" 9 "log/slog" 10 "net/http" 11 "os" 12 "path/filepath" 13 "slices" 14 "sync" 15 "sync/atomic" 16 "time" 17 18 "gopkg.in/yaml.v3" 19 20 "tangled.org/core/api/tangled" 21 "tangled.org/core/log" 22 "tangled.org/core/spindle/agentproto" 23 agentv1 "tangled.org/core/spindle/agentproto/gen" 24 "tangled.org/core/spindle/config" 25 "tangled.org/core/spindle/db" 26 "tangled.org/core/spindle/engine" 27 "tangled.org/core/spindle/models" 28 "tangled.org/core/spindle/secrets" 29) 30 31const ( 32 guestWorkDir = "/workspace/repo" 33 guestBasePATH = "/run/current-system/sw/bin:/nix/var/nix/profiles/default/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" 34 guestDevShellEnvPath = "/run/spindle/devshell-env.sh" 35 activationStepAction = "activate-config" 36 agentAcceptTimeout = 2 * time.Minute 37 agentHandshakeTimeout = 30 * time.Second 38 cacheDrainTimeout = 5 * time.Minute 39 vmShutdownTimeout = 10 * time.Second 40 guestTimeoutGrace = 5 * time.Second 41) 42 43type cleanupFunc func(context.Context) error 44 45type Engine struct { 46 l *slog.Logger 47 cfg *config.Config 48 db *db.DB 49 agent *agentHub 50 scheduler *engine.ResourceScheduler[Resources] 51 cgroupParent *CgroupParent 52 53 cleanupMu sync.Mutex 54 cleanup map[string][]cleanupFunc 55} 56 57type Step struct { 58 name string 59 kind models.StepKind 60 command string 61 environment map[string]string 62 action string 63 config manifestConfig 64 configKey string 65} 66 67func (s Step) Name() string { return s.name } 68func (s Step) Command() string { return s.command } 69func (s Step) Kind() models.StepKind { return s.kind } 70 71func New(ctx context.Context, cfg *config.Config, d *db.DB) (*Engine, error) { 72 l := log.FromContext(ctx).With("component", "engine.microvm") 73 port := cfg.MicroVMPipelines.AgentPort 74 if port == 0 { 75 port = agentproto.DefaultPort 76 } 77 agent, err := newAgentHub(port, l) 78 if err != nil { 79 return nil, err 80 } 81 budget, max, agingThreshold := newVMBudgetConfig(cfg.MicroVMPipelines) 82 l.Info("initialized microVM workflow budget", "budget", budget.String(), "maxWorkflow", max.String(), "agingThreshold", agingThreshold) 83 84 var cgroupParent *CgroupParent 85 if cfg.MicroVMPipelines.EnableCgroups { 86 cgroupParent, err = initCgroupParent(cfg.MicroVMPipelines.CgroupParent, cfg.MicroVMPipelines.CgroupSupervisorMemoryMinMiB, l) 87 if err != nil { 88 return nil, err 89 } 90 } 91 92 return &Engine{ 93 l: l, 94 cfg: cfg, 95 db: d, 96 agent: agent, 97 scheduler: engine.NewResourceScheduler(budget, max, agingThreshold), 98 cgroupParent: cgroupParent, 99 cleanup: make(map[string][]cleanupFunc), 100 }, nil 101} 102 103func (e *Engine) InitWorkflow(twf tangled.Pipeline_Workflow, tpl tangled.Pipeline) (*models.Workflow, error) { 104 swf := &models.Workflow{} 105 var dwf manifestWorkflow 106 107 if err := engine.DescribeManifestError(twf.Raw, manifestWorkflow{}); err != nil { 108 return nil, err 109 } 110 if err := yaml.Unmarshal([]byte(twf.Raw), &dwf); err != nil { 111 return nil, err 112 } 113 114 for _, dstep := range dwf.Steps { 115 swf.Steps = append(swf.Steps, Step{ 116 name: dstep.Name, 117 kind: models.StepKindUser, 118 command: dstep.Command, 119 environment: dstep.Environment, 120 }) 121 } 122 swf.Name = twf.Name 123 swf.Environment = dwf.Environment 124 125 if tpl.TriggerMetadata != nil { 126 if clone := models.BuildCloneStep(twf, *tpl.TriggerMetadata, e.cfg.Server.Dev); clone.Command() != "" { 127 swf.Steps = append([]models.Step{clone}, swf.Steps...) 128 } 129 } 130 131 imageSpec, imageSpecPath, imageName, err := e.resolveImage(dwf.Image) 132 if err != nil { 133 return nil, err 134 } 135 configKey := "" 136 config := manifestConfig{ 137 Services: dwf.Services, 138 Virtualisation: dwf.Virtualisation, 139 Dependencies: dwf.Dependencies, 140 Registry: dwf.Registry, 141 } 142 if config.Enabled() { 143 if !imageSpec.SupportsConfigActivation() { 144 return nil, fmt.Errorf( 145 "microVM image %q is not a NixOS image: services, virtualisation, dependencies and registry workflow options require a NixOS image", 146 imageName, 147 ) 148 } 149 var err error 150 configKey, err = buildConfigKey(imageSpec, config) 151 if err != nil { 152 return nil, fmt.Errorf("build config key: %w", err) 153 } 154 activationStep := Step{ 155 name: "NixOS config activation", 156 kind: models.StepKindSystem, 157 command: "activate nixos config", 158 action: activationStepAction, 159 config: config, 160 configKey: configKey, 161 } 162 163 insertAt := 0 164 if len(swf.Steps) > 0 && swf.Steps[0].Kind() == models.StepKindSystem { 165 insertAt = 1 166 } 167 swf.Steps = append(swf.Steps, nil) 168 copy(swf.Steps[insertAt+1:], swf.Steps[insertAt:]) 169 swf.Steps[insertAt] = activationStep 170 } 171 172 cacheURLs, cacheKeys, err := workflowCaches(dwf.Caches) 173 if err != nil { 174 return nil, err 175 } 176 177 swf.Data = &workflowState{ 178 ImageSpec: imageSpec, 179 ImageSpecPath: imageSpecPath, 180 Config: config, 181 ConfigKey: configKey, 182 Image: imageName, 183 CacheReadURLs: cacheURLs, 184 CacheTrustedPublicKeys: cacheKeys, 185 NixOSToplevelCache: newNixOSToplevelCacheStore(e.db), 186 } 187 return swf, nil 188} 189 190func (e *Engine) SetupWorkflow(ctx context.Context, wid models.WorkflowId, wf *models.Workflow, wfLogger models.WorkflowLogger) error { 191 l := e.l.With("workflow", wid) 192 setupStep := Step{name: "microVM setup", kind: models.StepKindSystem} 193 194 wfLogger.ControlWriter(-1, setupStep, models.StepStatusStart).Write([]byte{0}) 195 defer wfLogger.ControlWriter(-1, setupStep, models.StepStatusEnd).Write([]byte{0}) 196 197 state, ok := wf.Data.(*workflowState) 198 if !ok || state == nil { 199 return fmt.Errorf("workflow state is not initialized") 200 } 201 202 cid, err := AllocateCID() 203 if err != nil { 204 return err 205 } 206 connCh, unregister, err := e.agent.expect(cid) 207 if err != nil { 208 return err 209 } 210 defer unregister() 211 212 workDirBase := e.cfg.MicroVMPipelines.OverlayDir 213 if workDirBase == "" { 214 workDirBase = os.TempDir() 215 } 216 workDir, err := os.MkdirTemp(workDirBase, "spindle-microvm-"+wid.String()+"-*") 217 if err != nil { 218 return fmt.Errorf("create workflow microVM directory: %w", err) 219 } 220 state.WorkDir = workDir 221 222 setupDone := false 223 defer func() { 224 if setupDone { 225 return 226 } 227 if detail := vmCrashLog(state.VM); detail != "" { 228 l.Error("microVM setup failed", "detail", detail) 229 } 230 if err := e.cleanupState(context.Background(), wid, state); err != nil { 231 l.Error("failed to cleanup failed setup", "error", err) 232 } 233 }() 234 235 upstreams, err := BuildCacheUpstreams(e.cfg.NixCache.ReadURLs, state.CacheReadURLs) 236 if err != nil { 237 return err 238 } 239 readCache, err := StartReadCacheProxy(ctx, cid, upstreams, l) 240 if err != nil { 241 return err 242 } 243 state.ReadCache = readCache 244 stagingDir := filepath.Join(workDir, "upload-cache") 245 uploadCache, err := StartUploadCacheProxy(ctx, cid, e.cfg.NixCache.UploadURL, upstreams, stagingDir, l) 246 if err != nil { 247 return err 248 } 249 state.UploadCache = uploadCache 250 dnsProxy, err := StartDNSProxy(ctx, cid, l) 251 if err != nil { 252 return err 253 } 254 state.DNSProxy = dnsProxy 255 256 port := e.cfg.MicroVMPipelines.AgentPort 257 if port == 0 { 258 port = agentproto.DefaultPort 259 } 260 state.ImageSpec.BootArgs = fmt.Sprintf("%s shuttle.vsock_port=%d", state.ImageSpec.BootArgs, port) 261 262 fmt.Fprintf(wfLogger.DataWriter(-1, "stdout"), "starting microVM image %s\n", state.Image) 263 l.Info("starting microVM workflow", "image", state.Image, "imageSpec", state.ImageSpecPath, "cid", cid, "workDir", workDir) 264 265 var vm VMHandle 266 vm, err = StartVM(ctx, VMConfig{ 267 Image: state.ImageSpec, 268 CID: cid, 269 EnableKVM: e.cfg.MicroVMPipelines.EnableKVM, 270 WorkDir: workDir, 271 Cgroup: e.cgroupLimits(wid, state.ImageSpec), 272 Dev: e.cfg.Server.Dev, 273 }, l) 274 if err != nil { 275 return err 276 } 277 state.VM = vm 278 279 acceptCtx, cancelAccept := context.WithTimeout(ctx, agentAcceptTimeout) 280 defer cancelAccept() 281 conn, err := waitAgentConn(acceptCtx, connCh) 282 if err != nil { 283 return err 284 } 285 286 agentSession := NewAgentSession(conn, l) 287 initCtx, cancelInit := context.WithTimeout(ctx, agentHandshakeTimeout) 288 defer cancelInit() 289 if err := agentSession.Init(initCtx, &agentv1.Init{ 290 JobId: wid.String(), 291 CacheTrustedPublicKeys: append(slices.Clone(e.cfg.NixCache.TrustedPublicKeys), state.CacheTrustedPublicKeys...), 292 CacheReadProxyPort: readCache.Port(), 293 CacheUploadProxyPort: uploadCache.Port(), 294 DnsProxyPort: dnsProxy.Port(), 295 }); err != nil { 296 _ = agentSession.Close() 297 return err 298 } 299 state.Agent = agentSession 300 wf.Data = state 301 302 e.registerCleanup(wid, func(ctx context.Context) error { 303 return e.cleanupState(ctx, wid, state) 304 }) 305 setupDone = true 306 307 fmt.Fprintf(wfLogger.DataWriter(-1, "stdout"), 308 "agent connected; serial log: %s\n", vm.Logs().Serial, 309 ) 310 return nil 311} 312 313func applyDepsSource(command string) string { 314 return fmt.Sprintf( 315 // check if it exists because not all images have this 316 `if [ -f %s ]; then . %s; export PATH="$PATH:%s"; fi; %s`, 317 guestDevShellEnvPath, guestDevShellEnvPath, guestBasePATH, command, 318 ) 319} 320 321func (e *Engine) RunStep(ctx context.Context, wid models.WorkflowId, w *models.Workflow, idx int, secrets []secrets.UnlockedSecret, wfLogger models.WorkflowLogger) error { 322 state, ok := w.Data.(*workflowState) 323 if !ok || state == nil || state.Agent == nil { 324 return fmt.Errorf("microVM workflow is not connected to agent") 325 } 326 327 stderr := wfLogger.DataWriter(idx, "stderr") 328 329 execCtx, vmExited, cancelWatch := watchVMExit(ctx, state.VM) 330 defer cancelWatch() 331 332 step := w.Steps[idx] 333 if s, ok := step.(Step); ok && s.action == activationStepAction { 334 err := e.activateConfig(execCtx, wid, state, s, wfLogger.DataWriter(idx, "stdout")) 335 return e.classifyStepError(ctx, wid, step, state, stderr, vmExited, err) 336 } 337 env := []string{ 338 "HOME=/workspace", 339 "LOGNAME=" + guestWorkflowUser, 340 "PATH=" + guestBasePATH, 341 "USER=" + guestWorkflowUser, 342 } 343 for k, v := range w.Environment { 344 env = append(env, k+"="+v) 345 } 346 for _, s := range secrets { 347 env = append(env, s.Key+"="+s.Value) 348 } 349 if s, ok := step.(Step); ok { 350 for k, v := range s.environment { 351 env = append(env, k+"="+v) 352 } 353 } 354 355 stdout := wfLogger.DataWriter(idx, "stdout") 356 exitCode, err := state.Agent.Exec(execCtx, AgentExec{ 357 ID: fmt.Sprintf("%s-%d", wid.String(), idx), 358 ExecStart: &agentv1.ExecStart{ 359 Argv: []string{state.ImageSpec.Shell, "-lc", applyDepsSource(step.Command())}, 360 Env: env, 361 Cwd: guestWorkDir, 362 User: guestWorkflowUser, 363 // timeout not set here, Exec will fill it 364 }, 365 Stdout: stdout, 366 Stderr: stderr, 367 }) 368 if err != nil { 369 return e.classifyStepError(ctx, wid, step, state, stderr, vmExited, err) 370 } 371 372 if exitCode != 0 { 373 e.l.Debug("step exited non-zero", "workflow", wid, "step", step.Name(), "exitCode", exitCode) 374 return engine.ErrWorkflowFailed 375 } 376 return nil 377} 378 379// reads the vm serial logs so we report the tail of that as an error instead of 380// just "guest agent connection lost: EOF" 381func (e *Engine) classifyStepError(ctx context.Context, wid models.WorkflowId, step models.Step, state *workflowState, stderr io.Writer, vmExited *atomic.Bool, err error) error { 382 if err == nil { 383 return nil 384 } 385 l := e.l.With("workflow", wid, "step", step.Name()) 386 387 if vmExited != nil && vmExited.Load() { 388 reason := "microVM exited unexpectedly" 389 oom := state.VM != nil && state.VM.OOMKilled() 390 if oom { 391 reason = "microVM killed by OOM (cgroup memory limit exceeded)" 392 } 393 if detail := vmCrashLog(state.VM); detail != "" { 394 fmt.Fprintf(stderr, "%s:\n%s\n", reason, detail) 395 l.Error(reason, "oom", oom, "detail", detail) 396 } else { 397 fmt.Fprintln(stderr, reason) 398 l.Error(reason, "oom", oom) 399 } 400 return errors.New(reason + "; see workflow logs for serial output") 401 } 402 403 if errors.Is(err, errGuestTimedOut) || ctx.Err() != nil { 404 l.Debug("step timed out", "guestReported", errors.Is(err, errGuestTimedOut)) 405 return engine.ErrTimedOut 406 } 407 408 // the agent connection dropped while qemu stayed up (eg. the guest kernel 409 // OOM-killed the agent or a guest panic), so surface serial logs, those 410 // will be more helpful. 411 if detail := vmCrashLog(state.VM); detail != "" { 412 fmt.Fprintf(stderr, "step failed (%v):\n%s\n", err, detail) 413 l.Error("step failed", "error", err, "detail", detail) 414 } else { 415 l.Error("step failed", "error", err) 416 } 417 return err 418} 419 420func (e *Engine) activateConfig(ctx context.Context, wid models.WorkflowId, state *workflowState, step Step, out io.Writer) error { 421 cfg := step.config 422 if !cfg.Enabled() { 423 return nil 424 } 425 426 configKey := step.configKey 427 if configKey == "" { 428 configKey = state.ConfigKey 429 } 430 431 userConfigJSON, err := json.Marshal(cfg) 432 if err != nil { 433 return fmt.Errorf("encode user config: %w", err) 434 } 435 436 var cachedToplevel string 437 if configKey != "" { 438 if record, ok, err := state.NixOSToplevelCache.Lookup(configKey); err != nil { 439 return err 440 } else if ok { 441 // todo(dawn): we should probably use gc roots to eliminate TOCTOU 442 // the spindle will have to manage the gc roots, and for remote we have to 443 // ssh in to the host and add / remove gc root. 444 // we need to have this check anyway since the only check http caches can 445 // use is this one, since we cant manage gc roots there... 446 if e.anyCacheHasPath(ctx, state, record.Toplevel) { 447 cachedToplevel = record.Toplevel 448 fmt.Fprintf(out, "realizing cached NixOS config %s\n", cachedToplevel) 449 } 450 } 451 } 452 if cachedToplevel == "" { 453 fmt.Fprintf(out, "building NixOS config from user config\n") 454 } 455 456 baseHash, err := BaseConfigHash(state.ImageSpec) 457 if err != nil { 458 return fmt.Errorf("calculate base config hash: %w", err) 459 } 460 461 result, err := state.Agent.ActivateConfig(ctx, fmt.Sprintf("%s-config", wid.String()), &agentv1.ActivateConfig{ 462 ConfigKey: configKey, 463 BaseConfigHash: baseHash, 464 UserConfig: string(userConfigJSON), 465 Toplevel: cachedToplevel, 466 }, out) 467 if err != nil { 468 return err 469 } 470 fmt.Fprintf(out, "activated NixOS config toplevel %s\n", result.Toplevel) 471 472 if cachedToplevel != "" || configKey == "" { 473 return nil 474 } 475 if e.cfg.NixCache.UploadURL == "" { 476 e.l.Warn("not committing config cache metadata: no upload URL configured", "workflow", wid, "configKey", configKey, "toplevel", result.Toplevel) 477 return nil 478 } 479 480 if err := e.drainNixCache(ctx, state); err != nil { 481 // a partial upload would leave the cache unable to realize this toplevel, 482 // so skip the metadata commit rather than poison it with an un-realizable 483 // key. the config still activated fine, so don't fail the workflow. 484 e.l.Warn("cache drain failed; skipping config cache metadata commit", "workflow", wid, "configKey", configKey, "toplevel", result.Toplevel, "error", err) 485 return nil 486 } 487 if err := state.NixOSToplevelCache.Commit(configKey, result.Toplevel); err != nil { 488 return err 489 } 490 fmt.Fprintf(out, "committed config cache metadata %s -> %s\n", configKey, result.Toplevel) 491 return nil 492} 493 494func (e *Engine) anyCacheHasPath(ctx context.Context, state *workflowState, storePath string) bool { 495 upstreams, err := BuildCacheUpstreams(e.cfg.NixCache.ReadURLs, state.CacheReadURLs) 496 if err != nil { 497 e.l.Warn("config cache check: build upstreams failed; treating as absent", "path", storePath, "error", err) 498 return false 499 } 500 if len(upstreams) == 0 { 501 return false 502 } 503 hash, _, err := parseStorePath(storePath) 504 if err != nil { 505 e.l.Warn("config cache check: invalid toplevel path; treating as absent", "path", storePath, "error", err) 506 return false 507 } 508 req, err := http.NewRequestWithContext(ctx, http.MethodHead, "http://upstream/"+hash+".narinfo", nil) 509 if err != nil { 510 e.l.Warn("config cache check: build request failed; treating as absent", "path", storePath, "error", err) 511 return false 512 } 513 resp, err := newNarinfoExistenceTransport(upstreams, e.l).RoundTrip(req) 514 if err != nil { 515 e.l.Warn("config cache check: narinfo probe failed; treating as absent", "path", storePath, "error", err) 516 return false 517 } 518 defer resp.Body.Close() 519 _, _ = io.Copy(io.Discard, resp.Body) 520 return resp.StatusCode == http.StatusOK 521} 522 523func (e *Engine) DestroyWorkflow(ctx context.Context, wid models.WorkflowId) error { 524 fns := e.drainCleanups(wid) 525 526 var cleanupErr error 527 for i := len(fns) - 1; i >= 0; i-- { 528 if err := fns[i](ctx); err != nil { 529 e.l.Error("failed to cleanup workflow resource", "workflowId", wid, "error", err) 530 cleanupErr = errors.Join(cleanupErr, err) 531 } 532 } 533 return cleanupErr 534} 535 536func (e *Engine) FinalizeWorkflow(ctx context.Context, wid models.WorkflowId, w *models.Workflow, wfLogger models.WorkflowLogger) error { 537 return nil 538} 539 540func (e *Engine) WorkflowTimeout() time.Duration { 541 d, err := time.ParseDuration(e.cfg.MicroVMPipelines.WorkflowTimeout) 542 if err != nil { 543 d = 5 * time.Minute 544 } 545 return d + guestTimeoutGrace 546} 547 548func (e *Engine) registerCleanup(wid models.WorkflowId, fn cleanupFunc) { 549 e.cleanupMu.Lock() 550 defer e.cleanupMu.Unlock() 551 key := wid.String() 552 e.cleanup[key] = append(e.cleanup[key], fn) 553} 554 555func (e *Engine) drainCleanups(wid models.WorkflowId) []cleanupFunc { 556 e.cleanupMu.Lock() 557 defer e.cleanupMu.Unlock() 558 key := wid.String() 559 fns := e.cleanup[key] 560 delete(e.cleanup, key) 561 return fns 562} 563 564func (e *Engine) cgroupLimits(wid models.WorkflowId, spec ImageSpec) CgroupLimits { 565 cfg := e.cfg.MicroVMPipelines 566 return CgroupLimits{ 567 Enabled: cfg.EnableCgroups, 568 Parent: e.cgroupParent, 569 Name: "workflow-" + wid.String(), 570 MemoryMaxMiB: resourcesForImage(spec).MemoryMiB, 571 SwapMaxMiB: cfg.CgroupSwapMaxMiB, 572 PidsMax: cfg.CgroupPidsMax, 573 } 574}