// Package engine turns a list of catalog apps into work: it decides whether an // app needs touching, picks an install route that exists on this machine, and // records what happened in a form both a technician and a script can read. package engine import ( "context" "fmt" "runtime" "strings" "time" "git.starwarslab.us/ATOM_IT/Deployr/internal/catalog" "git.starwarslab.us/ATOM_IT/Deployr/internal/detect" "git.starwarslab.us/ATOM_IT/Deployr/internal/logx" "git.starwarslab.us/ATOM_IT/Deployr/internal/platform" "git.starwarslab.us/ATOM_IT/Deployr/internal/provider" ) // Action is the operation being performed. type Action string // The supported actions. const ( ActionInstall Action = "install" ActionUpdate Action = "update" ActionUninstall Action = "uninstall" ) // Status is the per-app outcome. type Status string // The possible per-app outcomes. const ( // StatusChanged means the machine was modified. StatusChanged Status = "ok" // StatusSkipped means no work was needed. StatusSkipped Status = "skip" // StatusFailed means every route failed. StatusFailed Status = "fail" // StatusUnsupported means the catalog has no recipe for this platform. StatusUnsupported Status = "n/a" ) // Config controls one engine run. type Config struct { Action Action DryRun bool Force bool // act even when the app is already in the desired state Strict bool // stop at the first failing source instead of falling through Timeout time.Duration CacheDir string RequireChecksum bool KeepDownloads bool OnlyProvider string // restrict every app to a single provider Log *logx.Logger } // Attempt records one source that was tried and did not work out. type Attempt struct { Provider string `json:"provider"` Error string `json:"error"` } // Result is the outcome for one app. type Result struct { App string `json:"app"` Name string `json:"name"` Status Status `json:"status"` Provider string `json:"provider,omitempty"` Version string `json:"version,omitempty"` Message string `json:"message,omitempty"` Error string `json:"error,omitempty"` RebootRequired bool `json:"reboot_required,omitempty"` DurationMS int64 `json:"duration_ms"` Attempts []Attempt `json:"attempts,omitempty"` } // Summary is the whole run, and is what --json prints. type Summary struct { Action Action `json:"action"` Host string `json:"host"` OS string `json:"os"` Arch string `json:"arch"` StartedAt string `json:"started_at"` DurationMS int64 `json:"duration_ms"` DryRun bool `json:"dry_run,omitempty"` Total int `json:"total"` Changed int `json:"changed"` Skipped int `json:"skipped"` Failed int `json:"failed"` Unsupported int `json:"unsupported"` RebootRequired bool `json:"reboot_required"` Results []Result `json:"results"` } // ExitCode maps a run onto a process exit status an RMM can branch on: // 0 = nothing went wrong, 1 = at least one app failed. func (s Summary) ExitCode() int { if s.Failed > 0 { return 1 } return 0 } // Run performs the action for every app, in order. Work is deliberately // sequential: package managers take machine-wide locks, and two installers // racing on the same box is how you corrupt an MSI database. func Run(ctx context.Context, apps []*catalog.App, cfg Config) Summary { start := time.Now() sum := Summary{ Action: cfg.Action, Host: platform.Hostname(), OS: runtime.GOOS, Arch: runtime.GOARCH, StartedAt: start.UTC().Format(time.RFC3339), DryRun: cfg.DryRun, Total: len(apps), } for _, app := range apps { res := runOne(ctx, app, cfg) sum.Results = append(sum.Results, res) switch res.Status { case StatusChanged: sum.Changed++ case StatusSkipped: sum.Skipped++ case StatusFailed: sum.Failed++ case StatusUnsupported: sum.Unsupported++ } if res.RebootRequired { sum.RebootRequired = true } if cfg.Log != nil { logResult(cfg.Log, res) } if ctx.Err() != nil { break } } sum.DurationMS = time.Since(start).Milliseconds() return sum } func logResult(log *logx.Logger, r Result) { detail := r.Message if r.Error != "" { detail = r.Error } if r.Provider != "" && r.Status == StatusChanged { via := "via " + r.Provider if r.Version != "" { via += " (" + r.Version + ")" } if detail == "" { detail = via } else { detail = via + " - " + detail } } log.Resultf(string(r.Status), "%-22s %s", r.App, detail) } func runOne(ctx context.Context, app *catalog.App, cfg Config) Result { start := time.Now() res := Result{App: app.ID, Name: app.Name} defer func() { res.DurationMS = time.Since(start).Milliseconds() }() target := app.TargetFor(runtime.GOOS) if target == nil { res.Status = StatusUnsupported res.Message = fmt.Sprintf("no %s recipe in the catalog", runtime.GOOS) return res } installed, version := detect.Installed(target.Detect) // Decide up front whether there is anything to do at all. Detection is // provider-independent, so this is also correct for software a technician // installed by hand. switch cfg.Action { case ActionInstall: if installed && !cfg.Force { res.Status = StatusSkipped res.Version = version res.Message = "already installed" if version != "" { res.Message += " (" + version + ")" } return res } case ActionUpdate, ActionUninstall: if !installed && !cfg.Force && !target.Detect.Empty() { res.Status = StatusSkipped res.Message = "not installed" return res } } opts := provider.Opts{ DryRun: cfg.DryRun, Timeout: cfg.Timeout, Log: cfg.Log, CacheDir: cfg.CacheDir, Arch: runtime.GOARCH, RequireChecksum: cfg.RequireChecksum, KeepDownloads: cfg.KeepDownloads, Detect: target.Detect, } usable := 0 for _, src := range target.Sources { if ctx.Err() != nil { res.Status = StatusFailed res.Error = "cancelled" return res } if !src.SupportsArch(runtime.GOARCH) { continue } if cfg.OnlyProvider != "" && !strings.EqualFold(src.Provider, cfg.OnlyProvider) { continue } p, ok := provider.Get(src.Provider) if !ok { res.Attempts = append(res.Attempts, Attempt{Provider: src.Provider, Error: "unknown provider"}) continue } if !p.Available(ctx, opts) { res.Attempts = append(res.Attempts, Attempt{Provider: src.Provider, Error: "not available on this machine"}) continue } usable++ if cfg.Log != nil { cfg.Log.Debugf("%s: trying %s (%s)", app.ID, src.Provider, src.ID) } var ( out provider.Outcome err error ) switch cfg.Action { case ActionInstall: out, err = p.Install(ctx, src, opts) case ActionUpdate: out, err = p.Update(ctx, src, opts) case ActionUninstall: out, err = p.Uninstall(ctx, src, opts) } if err != nil { res.Attempts = append(res.Attempts, Attempt{Provider: src.Provider, Error: err.Error()}) if cfg.Strict { break } continue } res.Provider = p.Name() res.RebootRequired = out.RebootRequired res.Message = out.Message if out.NoOp { res.Status = StatusSkipped if res.Message == "" { res.Message = "nothing to do" } } else { res.Status = StatusChanged } res.Version = finalVersion(ctx, p, src, opts, out, target, cfg) if out.RebootRequired { res.Message = strings.TrimSpace(res.Message + " (reboot required)") } return res } res.Status = StatusFailed switch { case usable == 0 && len(res.Attempts) > 0: res.Error = "no usable install route on this machine" case len(res.Attempts) == 0: res.Error = "no source matches this machine" default: res.Error = summarizeAttempts(res.Attempts) } return res } // finalVersion reports what is on the machine after the operation, preferring // the provider's own answer and falling back to the catalog's detect rules. func finalVersion(ctx context.Context, p provider.Provider, src catalog.Source, opts provider.Opts, out provider.Outcome, target *catalog.Target, cfg Config) string { if out.Version != "" { return out.Version } if cfg.DryRun || cfg.Action == ActionUninstall { return "" } if v, ok := p.Query(ctx, src, opts); ok && v != "" { return v } if _, v := detect.Installed(target.Detect); v != "" { return v } return "" } func summarizeAttempts(attempts []Attempt) string { parts := make([]string, 0, len(attempts)) for _, a := range attempts { parts = append(parts, a.Provider+": "+a.Error) } return strings.Join(parts, "; ") }