package plugin import ( "context" "fmt" "slices" "sort" "strings" "sync" "sync/atomic" "time" ) // Lifecycle hook event names (§4.3). const ( EventHostPreflight = "host.preflight" EventVMBeforeCreate = "vm.beforeCreate" EventVMAfterCreate = "vm.afterCreate" EventVMBeforeStart = "vm.beforeStart" EventVMAfterStart = "vm.afterStart" EventVMBeforeStop = "vm.beforeStop" EventVMAfterStop = "vm.afterStop" EventVMDeleted = "vm.deleted" EventLogOnLine = "log.onLine" ) // HookHandler is invoked when an event fires. Its payload and return type depend // on the event contract (§4.3). type HookHandler func(ctx context.Context, payload any) (any, error) // HookRegistration configures one subscribed handler on the HookBus. type HookRegistration struct { PluginID string Event string Builtin bool Priority int Blocking bool // only honored on vm.beforeStart if BlockingAllowed is true BlockingAllowed bool Handler HookHandler } // PreflightPayload is passed to host.preflight handlers. type PreflightPayload struct { HostFacts map[string]any `json:"host_facts"` } // PreflightResult is returned by host.preflight handlers. type PreflightResult struct { Warnings []string `json:"warnings,omitempty"` Advices []string `json:"advices,omitempty"` } // BeforeCreatePayload is passed to vm.beforeCreate handlers. type BeforeCreatePayload struct { VMName string `json:"vm_name"` DriverID string `json:"driver_id"` Options map[string]any `json:"options,omitempty"` } // BeforeCreateResult is returned by vm.beforeCreate handlers. type BeforeCreateResult struct { Errors []string `json:"errors,omitempty"` Patches map[string]any `json:"patches,omitempty"` } // HasCap reports whether a runtime declares the capability want. func HasCap(caps []string, want string) bool { return slices.ContainsFunc(caps, func(c string) bool { return strings.EqualFold(c, want) }) } // BeforeStartPayload is passed to vm.beforeStart handlers. type BeforeStartPayload struct { VMName string `json:"vm_name"` VMSettingsKey string `json:"-"` // driver-qualified key for declarative rules VMDir string `json:"vm_dir"` DriverID string `json:"driver_id"` ExtraArgs string `json:"extra_args"` HasInstaller bool `json:"has_installer"` InstallerPath string `json:"installer_path,omitempty"` RuntimeKind string `json:"runtime_kind"` RuntimeCaps []string `json:"runtime_caps,omitempty"` HostFacts map[string]any `json:"host_facts,omitempty"` VMCaps []string `json:"vm_caps,omitempty"` State string `json:"state,omitempty"` } // VMEventPayload is passed to vm.afterCreate / vm.afterStart / vm.beforeStop / vm.afterStop / vm.deleted. type VMEventPayload struct { VMName string `json:"vm_name"` VMDir string `json:"vm_dir,omitempty"` DriverID string `json:"driver_id,omitempty"` PID int `json:"pid,omitempty"` QMPAddr string `json:"qmp_addr,omitempty"` SSHPort int `json:"ssh_port,omitempty"` Extra map[string]any `json:"extra,omitempty"` } // LogLineEvent is one log line queued for log.onLine batch subscribers. type LogLineEvent struct { VMName string `json:"vm_name"` Source string `json:"source"` // "serial" | "qemu" | "app" Line string `json:"line"` } // HookBus dispatches lifecycle events respecting builtin-first ordering, // per-event timeouts, fail-open/blocking policies, and zero-cost fast paths (§4.3, §8.1). type HookBus struct { reg *Registry mu sync.RWMutex handlers map[string][]*HookRegistration // Zero-overhead counter for log.onLine (§8.1): checked with atomic load // before constructing LogLineEvent objects. logSubCount atomic.Int32 logCh chan LogLineEvent logOnce sync.Once } func NewHookBus(reg *Registry) *HookBus { return &HookBus{ reg: reg, handlers: make(map[string][]*HookRegistration), } } // Subscribe attaches a hook handler to scope so disposal unregisters it cleanly. func (b *HookBus) Subscribe(sc *Scope, hr HookRegistration) { if sc == nil || hr.Event == "" || hr.Handler == nil { return } hr.PluginID = sc.PluginID() ptr := &hr b.mu.Lock() b.handlers[hr.Event] = append(b.handlers[hr.Event], ptr) b.sortLocked(hr.Event) if hr.Event == EventLogOnLine { b.logSubCount.Add(1) b.startLogBatcherLocked() } b.mu.Unlock() sc.OnDispose(func() { b.mu.Lock() list := b.handlers[hr.Event] kept := list[:0] for _, item := range list { if item != ptr { kept = append(kept, item) } } if len(kept) == 0 { delete(b.handlers, hr.Event) } else { b.handlers[hr.Event] = kept } if hr.Event == EventLogOnLine { b.logSubCount.Add(-1) } b.mu.Unlock() }) } func (b *HookBus) sortLocked(event string) { list := b.handlers[event] sort.SliceStable(list, func(i, j int) bool { if list[i].Builtin != list[j].Builtin { return list[i].Builtin } if list[i].Priority != list[j].Priority { return list[i].Priority > list[j].Priority } return list[i].PluginID < list[j].PluginID }) } // HasSubscribers returns whether any plugin is subscribed to event (zero-cost gate, §8.1). func (b *HookBus) HasSubscribers(event string) bool { if event == EventLogOnLine { return b.logSubCount.Load() > 0 } b.mu.RLock() n := len(b.handlers[event]) b.mu.RUnlock() return n > 0 } func (b *HookBus) snapshot(event string) []*HookRegistration { b.mu.RLock() list := b.handlers[event] if len(list) == 0 { b.mu.RUnlock() return nil } cp := make([]*HookRegistration, len(list)) copy(cp, list) b.mu.RUnlock() return cp } // DispatchPreflight runs host.preflight (collect; builtin runs synchronously on // parent ctx, external plugins get 500ms timeout and fail-open). func (b *HookBus) DispatchPreflight(ctx context.Context, payload PreflightPayload) PreflightResult { subs := b.snapshot(EventHostPreflight) if len(subs) == 0 { return PreflightResult{} } var merged PreflightResult for _, hr := range subs { var ( res any err error ) if hr.Builtin { res, err = b.invokeBuiltin(ctx, hr, payload) } else { res, err = b.invokeWithTimeout(ctx, hr, payload, 500*time.Millisecond) } if err != nil { continue } if pr, ok := res.(PreflightResult); ok { merged.Warnings = append(merged.Warnings, pr.Warnings...) merged.Advices = append(merged.Advices, pr.Advices...) } else if prp, ok := res.(*PreflightResult); ok && prp != nil { merged.Warnings = append(merged.Warnings, prp.Warnings...) merged.Advices = append(merged.Advices, prp.Advices...) } } return merged } // DispatchBeforeCreate runs vm.beforeCreate (intercept; builtin runs // synchronously on parent ctx, external plugins get 2s timeout and fail-open). func (b *HookBus) DispatchBeforeCreate(ctx context.Context, payload BeforeCreatePayload) BeforeCreateResult { subs := b.snapshot(EventVMBeforeCreate) if len(subs) == 0 { return BeforeCreateResult{} } out := BeforeCreateResult{Patches: map[string]any{}} for _, hr := range subs { var ( res any err error ) if hr.Builtin { res, err = b.invokeBuiltin(ctx, hr, payload) } else { res, err = b.invokeWithTimeout(ctx, hr, payload, 2*time.Second) } if err != nil { continue } var r BeforeCreateResult switch v := res.(type) { case BeforeCreateResult: r = v case *BeforeCreateResult: if v != nil { r = *v } default: continue } out.Errors = append(out.Errors, r.Errors...) for k, v := range r.Patches { out.Patches[k] = v } } return out } // DispatchBeforeStart runs vm.beforeStart (intercept). Builtin prep hooks run // synchronously on parent ctx without external timeouts so disk/OpenCore I/O // always completes before QEMU starts. External plugin hooks share a 10s // chain budget with 2s per plugin. func (b *HookBus) DispatchBeforeStart(ctx context.Context, payload BeforeStartPayload) ([]StartIntent, error) { subs := b.snapshot(EventVMBeforeStart) if len(subs) == 0 { return nil, nil } hasExternal := false for _, hr := range subs { if !hr.Builtin { hasExternal = true break } } extChainCtx := ctx if hasExternal { var extChainCancel context.CancelFunc extChainCtx, extChainCancel = context.WithTimeout(ctx, 10*time.Second) defer extChainCancel() } var ( extPayload BeforeStartPayload extPayloadInit bool ) var intents []StartIntent for _, hr := range subs { var ( res any err error ) if hr.Builtin { res, err = b.invokeBuiltin(ctx, hr, payload) } else { if extChainCtx.Err() != nil { break } // Never leak raw host paths, raw ExtraArgs (may contain MACs), or // sensitive HostFacts to external plugins. if !extPayloadInit { extPayload = redactBeforeStartPayload(payload) extPayloadInit = true } res, err = b.invokeWithTimeout(extChainCtx, hr, extPayload, 2*time.Second) } if err != nil { continue } var intent StartIntent switch v := res.(type) { case StartIntent: intent = v case *StartIntent: if v != nil { intent = *v } else { continue } default: continue } intent.PluginID = hr.PluginID // Enforce vm:intent permission for external plugins producing start intents. if !hr.Builtin && b.reg != nil && (len(intent.Args) > 0 || len(intent.Env) > 0 || len(intent.PostStart) > 0 || intent.BlockReason != "") { if !b.reg.PluginHasPermission(hr.PluginID, "vm:intent") { continue } } if intent.BlockReason != "" && hr.Blocking && hr.BlockingAllowed { return intents, fmt.Errorf("blocked by %s: %s", hr.PluginID, intent.BlockReason) } intents = append(intents, intent) } return intents, nil } // DispatchBeforeStop waits for built-in cleanup hooks before a VM stops. External // observation hooks remain asynchronous so they cannot delay VM shutdown. func (b *HookBus) DispatchBeforeStop(ctx context.Context, payload VMEventPayload) { subs := b.snapshot(EventVMBeforeStop) for _, hr := range subs { if hr.Builtin { _, _ = b.invokeBuiltin(ctx, hr, payload) continue } go func(hr *HookRegistration) { _, _ = b.invokeWithTimeout(context.Background(), hr, payload, 10*time.Second) }(hr) } } // DispatchObserve asynchronously fires observation events (vm.afterCreate, // vm.afterStart, vm.afterStop, vm.deleted), logging errors only. func (b *HookBus) DispatchObserve(event string, payload VMEventPayload) { subs := b.snapshot(event) if len(subs) == 0 { return } timeout := 10 * time.Second if event == EventVMAfterCreate { timeout = 30 * time.Second } go func() { for _, hr := range subs { _, _ = b.invokeWithTimeout(context.Background(), hr, payload, timeout) } }() } // EmitLogLine queues a log line for batched log.onLine delivery. When no // subscribers exist, this is a single atomic load without allocation. // Under backpressure, lines are dropped silently so logging is never blocked. func (b *HookBus) EmitLogLine(vmName, source, line string) { if b.logSubCount.Load() <= 0 { return } b.mu.RLock() ch := b.logCh b.mu.RUnlock() if ch == nil { return } select { case ch <- LogLineEvent{VMName: vmName, Source: source, Line: line}: default: // Backpressure: drop without blocking VM log pipeline. } } func (b *HookBus) startLogBatcherLocked() { b.logOnce.Do(func() { ch := make(chan LogLineEvent, 256) b.logCh = ch go b.runLogBatcher(ch) }) } func (b *HookBus) runLogBatcher(ch <-chan LogLineEvent) { const maxBatch = 32 ticker := time.NewTicker(150 * time.Millisecond) defer ticker.Stop() var batch []LogLineEvent flush := func() { if len(batch) == 0 { return } subs := b.snapshot(EventLogOnLine) if len(subs) == 0 { batch = batch[:0] return } deliver := make([]LogLineEvent, len(batch)) copy(deliver, batch) batch = batch[:0] for _, hr := range subs { _, _ = b.invokeWithTimeout(context.Background(), hr, deliver, 500*time.Millisecond) } } for { select { case ev := <-ch: batch = append(batch, ev) if len(batch) >= maxBatch { flush() } case <-ticker.C: flush() } } } // redactBeforeStartPayload removes host paths, raw ExtraArgs, and sensitive // keys before handing a BeforeStartPayload to any external plugin. func redactBeforeStartPayload(p BeforeStartPayload) BeforeStartPayload { return BeforeStartPayload{ VMName: p.VMName, VMSettingsKey: p.VMSettingsKey, DriverID: p.DriverID, HasInstaller: p.HasInstaller, RuntimeKind: p.RuntimeKind, RuntimeCaps: append([]string(nil), p.RuntimeCaps...), HostFacts: StripSensitiveFields(p.HostFacts), VMCaps: append([]string(nil), p.VMCaps...), State: p.State, } } // invokeBuiltin runs a trusted built-in handler synchronously on parent ctx // (with panic recovery) so I/O-heavy prep steps never time out or race QEMU. func (b *HookBus) invokeBuiltin(ctx context.Context, hr *HookRegistration, payload any) (val any, err error) { defer func() { if rec := recover(); rec != nil { val = nil err = fmt.Errorf("hook panic: %v", rec) } if b.reg != nil { b.reg.RecordHookOutcome(hr.PluginID, err) } }() return hr.Handler(ctx, payload) } func (b *HookBus) invokeWithTimeout(parent context.Context, hr *HookRegistration, payload any, limit time.Duration) (any, error) { callCtx, cancel := context.WithTimeout(parent, limit) defer cancel() type result struct { val any err error } done := make(chan result, 1) go func() { defer func() { if rec := recover(); rec != nil { done <- result{err: fmt.Errorf("hook panic: %v", rec)} } }() v, err := hr.Handler(callCtx, payload) done <- result{val: v, err: err} }() select { case r := <-done: if b.reg != nil { b.reg.RecordHookOutcome(hr.PluginID, r.err) } return r.val, r.err case <-callCtx.Done(): err := fmt.Errorf("hook %s/%s timed out (%v)", hr.PluginID, hr.Event, limit) if b.reg != nil { b.reg.RecordHookOutcome(hr.PluginID, err) } return nil, err } }