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