Files
ThothII/tools/tht/internal/installapply/run.go
T

272 lines
11 KiB
Go

// Package installapply applies a sealed installation plan without interactive input.
package installapply
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"time"
"github.com/aritmolab/thothii/tools/tht/internal/compose"
"github.com/aritmolab/thothii/tools/tht/internal/config"
"github.com/aritmolab/thothii/tools/tht/internal/lifecycle"
"github.com/aritmolab/thothii/tools/tht/internal/modelprojection"
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
"github.com/aritmolab/thothii/tools/tht/internal/service"
)
type Request struct{ PlanPath, InstallationPath string }
type Result struct {
SchemaVersion int `json:"schema_version"`
PlatformReady bool `json:"platform_ready"`
WorkspaceReady bool `json:"workspace_ready"`
BindingsReady bool `json:"bindings_ready"`
BindingImport *BindingReport `json:"binding_import,omitempty"`
Stage string `json:"stage"`
Action string `json:"action"`
Journal string `json:"journal,omitempty"`
}
type journal struct {
SchemaVersion int `json:"schema_version"`
Installation string `json:"installation"`
ReleaseRevision string `json:"release_revision"`
PlanSeal string `json:"plan_seal"`
Stage string `json:"stage"`
Status string `json:"status"`
}
// Check must repeat document validation and live prerequisite probes at the public CLI boundary.
// It is mandatory; historical success in the plan never authorizes skipping current checks.
type Check func(context.Context, preflight.Plan) error
func Run(ctx context.Context, request Request, runner compose.Runner, check Check) (result Result, err error) {
result = Result{SchemaVersion: 1, Stage: "plan", Action: "Produce a current plan from complete prepared documents."}
fail := func(stage, action string) (Result, error) {
result.Stage = stage
result.Action = action
return result, errors.New(action)
}
plan, err := preflight.ReadExecutionPlan(request.PlanPath)
if err != nil || plan.Installation.Path != request.InstallationPath || plan.ManifestPath == "" || plan.BootstrapPath == "" || runner == nil || check == nil {
return fail("plan", "Use a matching protected execution plan; older plans must be regenerated.")
}
installation, err := config.LoadPrepared(request.InstallationPath)
if err != nil || !reflect.DeepEqual(installation, plan.Installation) || installation.Profile != "local" {
return fail("plan", "Correct and validate the local installation documents before execution.")
}
manifest, err := preflight.LoadManifest(plan.ManifestPath)
if err != nil || !reflect.DeepEqual(manifest, plan.Release) {
return fail("release", "Restore the exact verified release bundle and generate a new plan if its identity changed.")
}
if err := safeio.EnsurePrivateDirectory(filepath.Join(installation.ProjectDirectory, ".tht")); err != nil {
return fail("lock", "The installation control directory must be private and canonical.")
}
if err := safeio.EnsurePrivateDirectory(installation.ControlDirectory()); err != nil {
return fail("lock", "The installation control directory must be private and canonical.")
}
lock, err := lifecycle.Acquire(installation)
if err != nil {
return fail("lock", "Another lifecycle operation owns the installation lock; wait for it to finish. Inspect a stale owner after a terminated process before explicitly removing its lock.")
}
defer func() {
if releaseErr := lock.Release(); releaseErr != nil {
result.PlatformReady = false
result.Stage = "lock"
result.Action = "Installation lock ownership changed; inspect the private control directory."
err = errors.New(result.Action)
}
}()
if err := check(ctx, plan); err != nil {
return fail("validation", "Current document or prerequisite checks failed; correct the documents and repeat planning. No platform operation was started.")
}
if _, err := preflight.ReadExecutionPlan(request.PlanPath); err != nil {
return fail("validation", "Inputs changed during checks; repeat planning before execution.")
}
payload, err := bindingPayload(plan)
if err != nil {
return fail("bootstrap-input", err.Error())
}
defer clear(payload)
result.Journal = filepath.Join(installation.ControlDirectory(), "installation-apply.json")
state := journal{SchemaVersion: 1, Installation: installation.Path, ReleaseRevision: plan.Release.Revision, PlanSeal: plan.InputSeal}
if _, err := os.Lstat(result.Journal); err == nil {
data, readErr := safeio.ReadCanonicalPrivateRegular(result.Journal, 16<<10)
var previous journal
if readErr != nil || json.Unmarshal(data, &previous) != nil || previous.SchemaVersion != 1 || previous.Installation != installation.Path || previous.ReleaseRevision != plan.Release.Revision {
return fail("journal", "The existing installation journal is invalid or belongs to another release; this command is not a product upgrade.")
}
} else if !os.IsNotExist(err) {
return fail("journal", "Cannot safely read the installation journal.")
}
persist := func() error {
data, _ := json.MarshalIndent(state, "", " ")
data = append(data, '\n')
if _, err := os.Lstat(result.Journal); os.IsNotExist(err) {
return safeio.PublishCanonicalNewFile(result.Journal, data, 0o600)
}
return safeio.ReplaceCanonicalRegular(result.Journal, data, 0o600)
}
operation := func(stage string, fn func() error) error {
result.Stage = stage
state.Stage = stage
state.Status = "running"
if err := persist(); err != nil {
return errors.New("Cannot persist the private installation journal.")
}
if _, err := preflight.ReadExecutionPlan(request.PlanPath); err != nil {
state.Status = "failed"
_ = persist()
return errors.New("Prepared inputs changed; correct the documents and produce a new plan.")
}
if err := ctx.Err(); err != nil {
state.Status = "interrupted"
_ = persist()
return errors.New("Execution interrupted; repeat the same command to reconcile the existing platform.")
}
if err := fn(); err != nil {
state.Status = "failed"
if ctx.Err() != nil {
state.Status = "interrupted"
}
if saveErr := persist(); saveErr != nil {
return errors.New("Operation stopped and the private journal could not be updated.")
}
return fmt.Errorf("Stage %s failed; correct its prerequisites and repeat apply. No source build or volume reset was attempted.", stage)
}
state.Status = "complete"
return persist()
}
docker := func(timeout time.Duration, command ...string) error {
bound, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
value, err := runner.Run(bound, installation.ComposeArgs(command...), nil)
if err != nil || value.ExitCode != 0 {
return errors.New("Docker operation failed")
}
return nil
}
stages := []struct {
name string
run func() error
}{
{"assets", func() error { return installAssets(installation, plan) }},
{"configuration", func() error {
if err := prepareIdentity(installation); err != nil {
return err
}
if err := modelprojection.Generate(installation); err != nil {
return err
}
if !preflight.CheckInstalledCompose(ctx, runner, installation, plan.Release, plan.Platform).OK {
return errors.New("Effective runtime configuration differs from the release")
}
return nil
}},
{"pull", func() error {
return docker(30*time.Minute, "--profile", "catalog-maintenance", "--profile", "workspace-maintenance", "pull", "--policy", "always")
}},
{"runtime-identity", func() error {
return initializeIdentity(ctx, runner, installation, plan.Release, plan.Platform)
}},
{"catalog", func() error {
return docker(5*time.Minute, "up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout", "240", "catalog-db")
}},
{"migrations", func() error {
name, err := compose.NewOneShotContainerName(installation.ProjectName() + "-migrate")
if err != nil {
return err
}
return docker(5*time.Minute, "run", "--rm", "-T", "--no-deps", "--pull", "never", "--name", name, "catalog-migrate")
}},
{"services", func() error {
return docker(30*time.Minute, "up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout", "1500", "core", "frontend", "qdrant", "embedding", "embedding-model-init")
}},
{"health", func() error {
bound, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
value, err := runner.Run(bound, installation.ComposeArgs("ps", "--all", "--format", "json"), nil)
if err != nil || value.ExitCode != 0 {
return errors.New("Cannot inspect services")
}
if err := service.Healthy(value.Stdout); err != nil {
return err
}
return docker(time.Minute, "exec", "-T", "core", "node", "--input-type=module", "-e", runtimeCheck)
}},
{"bindings", func() error {
result.PlatformReady = true
report, err := importBindings(ctx, plan, runner, payload)
result.BindingImport = &report
result.BindingsReady = err == nil
return err
}},
}
// Reconcile each idempotent stage against Docker/migration authority on every retry.
// A journal entry alone is never proof that a container or migration still exists.
for _, stage := range stages {
if err := operation(stage.name, stage.run); err != nil {
return fail(stage.name, err.Error())
}
}
result.PlatformReady = true
result.Stage = "bindings-ready"
result.Action = "Platform and prepared database bindings are ready. Complete workspace readiness before a human-reviewed question."
return result, nil
}
func installAssets(installation config.Installation, plan preflight.Plan) error {
names := make([]string, 0, len(plan.Release.Files))
for name := range plan.Release.Files {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
source := filepath.Join(filepath.Dir(plan.ManifestPath), filepath.FromSlash(name))
target := filepath.Join(installation.ProjectDirectory, filepath.FromSlash(name))
data, err := safeio.ReadCanonicalRegular(source, 32<<20)
if err != nil || fmt.Sprintf("%x", sha256.Sum256(data)) != plan.Release.Files[name] {
return errors.New("Release asset changed")
}
if existing, err := safeio.ReadCanonicalRegular(target, 32<<20); err == nil {
if fmt.Sprintf("%x", sha256.Sum256(existing)) != plan.Release.Files[name] {
return errors.New("Existing release asset differs")
}
continue
}
if _, err := os.Lstat(target); !os.IsNotExist(err) {
return errors.New("Existing release target is unsafe")
}
relative, _ := filepath.Rel(installation.ProjectDirectory, filepath.Dir(target))
parent := installation.ProjectDirectory
if relative != "." {
for _, part := range strings.Split(relative, string(filepath.Separator)) {
parent = filepath.Join(parent, part)
if err := safeio.EnsurePrivateDirectory(parent); err != nil {
return err
}
}
}
if err := safeio.PublishCanonicalNewFile(target, data, 0o644); err != nil {
return err
}
}
return nil
}
const runtimeCheck = `
const base='http://127.0.0.1:8787';
const health=await fetch(base+'/health',{signal:AbortSignal.timeout(10000)});
const auth=await fetch(base+'/auth/config',{signal:AbortSignal.timeout(10000)});
const protectedRoute=await fetch(base+'/workspaces',{signal:AbortSignal.timeout(10000)});
if(!health.ok||!auth.ok||(await auth.json()).mode!=='local'||protectedRoute.status!==401)process.exit(1);
console.log(JSON.stringify({ok:true}));
`