Files
YXC0915 01ec599088 Merge main and resolve plugin runtime compatibility
Preserve plugin navigation and generate the runtime warning messages. Read startup overrides using the canonical VM settings key and keep set_env action order.
2026-12-04 15:52:08 +08:00

284 lines
8.1 KiB
Go

package plugin
import (
"context"
"fmt"
"slices"
"strings"
"github.com/Nwflower/reims-go/internal/i18n"
)
// RuleCondition is a declarative, non-Turing-complete predicate over host, VM,
// and runtime facts (§5.4).
type RuleCondition struct {
Fact string `json:"fact"` // e.g. "host.needs_cold_reboot", "host.whpx", "vm.driver", "runtime.kind", "runtime.capabilities"
Operator string `json:"operator"` // "eq" | "neq" | "contains" | "not_contains" | "exists"
Value any `json:"value,omitempty"`
}
// RuleAction is a constrained action emitted when all conditions match (§5.4).
type RuleAction struct {
Kind string `json:"kind"` // "append_args" | "set_env" | "warn" | "post_start"
Key string `json:"key,omitempty"` // fragment key for append_args
Tokens []string `json:"tokens,omitempty"` // QEMU arg tokens
Env map[string]string `json:"env,omitempty"` // env overrides
EnvFromSettings map[string]string `json:"envFromSettings,omitempty"` // environment key to plugin setting
Message LocalizedText `json:"message,omitempty"` // localized warning text (accepts string or {"zh-CN":..., "en-US":...})
Action string `json:"action,omitempty"` // post_start kind
Params map[string]any `json:"params,omitempty"`
}
// RuleHook is an L1 declarative hook rule contributed via plugin.json (§5.4).
type RuleHook struct {
ID string `json:"id"`
Event string `json:"event"` // "vm.beforeStart" | "host.preflight"
Priority int `json:"priority,omitempty"`
Conditions []RuleCondition `json:"conditions,omitempty"`
Actions []RuleAction `json:"actions"`
}
// EvaluateRuleConditions checks whether all declarative conditions hold against facts.
func EvaluateRuleConditions(conds []RuleCondition, facts map[string]any) bool {
for _, c := range conds {
val, exists := facts[c.Fact]
switch strings.ToLower(strings.TrimSpace(c.Operator)) {
case "exists":
if !exists || val == nil {
return false
}
case "eq", "==":
if !exists || !factEquals(val, c.Value) {
return false
}
case "neq", "!=":
if exists && factEquals(val, c.Value) {
return false
}
case "contains":
if !exists || !factContains(val, c.Value) {
return false
}
case "not_contains":
if exists && factContains(val, c.Value) {
return false
}
default:
return false
}
}
return true
}
func factEquals(actual, expected any) bool {
return strings.EqualFold(fmt.Sprint(actual), fmt.Sprint(expected))
}
func factContains(actual, needle any) bool {
sNeedle := strings.ToLower(fmt.Sprint(needle))
switch v := actual.(type) {
case []string:
for _, item := range v {
if strings.EqualFold(item, sNeedle) {
return true
}
}
return false
case []any:
for _, item := range v {
if strings.EqualFold(fmt.Sprint(item), sNeedle) {
return true
}
}
return false
default:
return strings.Contains(strings.ToLower(fmt.Sprint(actual)), sNeedle)
}
}
func (r *Registry) registerRuleHooks(sc *Scope, pluginID string, rules []RuleHook, schema *SettingsSchema) {
for _, rule := range rules {
rl := rule
switch rl.Event {
case EventVMBeforeStart:
r.hooks.Subscribe(sc, HookRegistration{
PluginID: pluginID,
Event: EventVMBeforeStart,
Priority: rl.Priority,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(BeforeStartPayload)
if !ok {
return nil, nil
}
facts := buildStartFacts(p)
if !EvaluateRuleConditions(rl.Conditions, facts) {
return nil, nil
}
return r.buildRuleStartIntent(pluginID, rl, string(r.currentLocale()), schema, p.VMSettingsKey), nil
},
})
case EventHostPreflight:
r.hooks.Subscribe(sc, HookRegistration{
PluginID: pluginID,
Event: EventHostPreflight,
Priority: rl.Priority,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(PreflightPayload)
if !ok {
return nil, nil
}
if !EvaluateRuleConditions(rl.Conditions, p.HostFacts) {
return nil, nil
}
var res PreflightResult
loc := string(r.currentLocale())
for _, act := range rl.Actions {
if act.Kind == "warn" {
if msg := act.Message.Get(loc); msg != "" {
res.Warnings = append(res.Warnings, msg)
}
}
}
return res, nil
},
})
}
}
}
// RuntimeUnavailableSettings reports settings guarded by rules that depend only
// on runtime capabilities. VM-specific rules cannot be assessed on the plugin page.
func RuntimeUnavailableSettings(m Manifest, caps []string, loc i18n.Locale) []string {
if m.Settings == nil {
return nil
}
facts := map[string]any{"runtime.capabilities": caps}
unavailable := make(map[string]bool)
available := make(map[string]bool)
for _, rule := range m.Contributes.RuleHooks {
if rule.Event != EventVMBeforeStart || slices.ContainsFunc(rule.Conditions, func(c RuleCondition) bool {
return c.Fact != "runtime.capabilities"
}) {
continue
}
matches := EvaluateRuleConditions(rule.Conditions, facts)
for _, action := range rule.Actions {
if action.Kind != "set_env" {
continue
}
for envKey, settingKey := range action.EnvFromSettings {
prop, ok := m.Settings.Properties[settingKey]
if !ok || prop.Secret || !ValidateEnvKey(m.ID, envKey) {
continue
}
if matches {
available[settingKey] = true
} else {
unavailable[settingKey] = true
}
}
}
}
var labels []string
for key := range unavailable {
if available[key] {
continue
}
label := m.Settings.Properties[key].Title.Get(string(loc))
if label == "" {
label = key
}
labels = append(labels, label)
}
slices.Sort(labels)
return slices.Compact(labels)
}
func (r *Registry) applyRuleEnvSettings(intent *StartIntent, action RuleAction, schema *SettingsSchema, vmKey string) {
if schema == nil || r.ruleSettings == nil {
return
}
for envKey, settingKey := range action.EnvFromSettings {
prop, ok := schema.Properties[settingKey]
if !ok || prop.Secret || !ValidateEnvKey(intent.PluginID, envKey) {
continue
}
scope := prop.Scope
if scope == "" {
scope = schema.Scope
}
settingsVM := ""
if scope == "vm" || scope == "both" {
settingsVM = vmKey
}
value := r.ruleSettings(intent.PluginID, settingsVM, true)[settingKey]
switch value := value.(type) {
case string, bool:
if intent.Env == nil {
intent.Env = make(map[string]string)
}
intent.Env[envKey] = fmt.Sprint(value)
}
}
}
func buildStartFacts(p BeforeStartPayload) map[string]any {
facts := make(map[string]any, len(p.HostFacts)+8)
for k, v := range p.HostFacts {
facts[k] = v
}
facts["vm.name"] = p.VMName
facts["vm.driver"] = p.DriverID
facts["vm.capabilities"] = p.VMCaps
facts["vm.state"] = p.State
facts["vm.has_installer"] = p.HasInstaller
facts["runtime.kind"] = p.RuntimeKind
facts["runtime.capabilities"] = p.RuntimeCaps
return facts
}
func (r *Registry) buildRuleStartIntent(pluginID string, rule RuleHook, loc string, schema *SettingsSchema, vmKey string) StartIntent {
intent := StartIntent{PluginID: pluginID}
for i, act := range rule.Actions {
switch act.Kind {
case "append_args":
if len(act.Tokens) == 0 {
continue
}
key := act.Key
if key == "" {
key = fmt.Sprintf("%s:%s:%d", pluginID, rule.ID, i)
}
intent.Args = append(intent.Args, ArgFragment{
PluginID: pluginID,
Key: key,
Tokens: append([]string(nil), act.Tokens...),
Priority: rule.Priority,
})
case "set_env":
if len(act.Env) > 0 {
if intent.Env == nil {
intent.Env = make(map[string]string, len(act.Env))
}
for k, v := range act.Env {
intent.Env[k] = v
}
}
r.applyRuleEnvSettings(&intent, act, schema, vmKey)
case "warn":
if msg := act.Message.Get(loc); msg != "" {
intent.Warnings = append(intent.Warnings, msg)
}
case "post_start":
if act.Action != "" {
intent.PostStart = append(intent.PostStart, PostStartAction{
PluginID: pluginID,
Kind: act.Action,
Params: act.Params,
})
}
}
}
return intent
}