feat: apply sealed installation plans without interactive setup

This commit is contained in:
Codex
2026-10-06 15:45:18 +02:00
parent c3c9f509bf
commit 8b9a086fd6
31 changed files with 1542 additions and 45 deletions
+98
View File
@@ -0,0 +1,98 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"path/filepath"
"slices"
"time"
"github.com/aritmolab/thothii/tools/tht/internal/compose"
"github.com/aritmolab/thothii/tools/tht/internal/installapply"
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
"github.com/aritmolab/thothii/tools/tht/internal/version"
)
func installationApplyCommand(ctx context.Context, installationPath string, args []string, stdout io.Writer) int {
structured := slices.Contains(args, "--json")
write := func(result installapply.Result) {
if structured {
_ = json.NewEncoder(stdout).Encode(result)
} else {
fmt.Fprintf(stdout, "%s: %s\n", result.Stage, result.Action)
}
}
var planPath string
valid := len(args) > 0 && args[0] == "apply" && filepath.IsAbs(installationPath)
seenJSON := false
for index := 1; index < len(args); index++ {
switch args[index] {
case "--json":
if seenJSON {
valid = false
}
seenJSON = true
case "--plan":
if planPath != "" || index+1 >= len(args) {
valid = false
} else {
index++
planPath = args[index]
}
default:
valid = false
}
}
if !valid || !filepath.IsAbs(planPath) {
write(installapply.Result{SchemaVersion: 1, Stage: "usage", Action: "Use --installation ABS_PATH installation apply --plan ABS_PLAN [--json]."})
return 2
}
runner := compose.NewRunnerWithEnvironment("", installationDockerEnvironment())
check := func(ctx context.Context, p preflight.Plan) error {
if version.Current().Commit != p.Release.Revision || version.Current().Version != p.Release.Version {
return errors.New("use the operator supplied with this release")
}
var documents bytes.Buffer
if installationDocumentsCommand(ctx, installationPath, []string{"validate", "--workspaces", p.WorkspaceDirectory, "--bootstrap", p.BootstrapPath, "--json"}, &documents) != 0 {
return errors.New("prepared documents failed validation")
}
host, err := preflight.InspectHost(p.Installation.ProjectDirectory)
if err != nil || "linux/"+host.Arch != p.Platform {
return errors.New("host platform differs from plan")
}
report := preflight.CheckHost(ctx, runner, host, p.Release.Requirements)
if report.OK {
report.Merge(preflight.CheckImages(ctx, runner, p.Release, p.Platform))
}
if report.OK {
report.Merge(preflight.CheckCompose(ctx, runner, p.Installation, p.Release, p.ManifestPath, p.Platform))
}
if report.OK {
report.Merge(preflight.CheckExternal(ctx, p.Installation))
}
if report.OK {
var out, discarded bytes.Buffer
bound, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
code := workspaceDocumentsCommand(bound, []string{"probe", "--directory", p.WorkspaceDirectory, "--bootstrap", p.BootstrapPath, "--json"}, &out, &discarded)
var probes preflight.Report
if code != 0 || json.Unmarshal(out.Bytes(), &probes) != nil || !probes.OK || len(probes.Checks) == 0 {
return errors.New("current database/evidence probes failed")
}
}
if !report.OK {
return errors.New("current prerequisites failed")
}
return nil
}
result, err := installapply.Run(ctx, installapply.Request{PlanPath: planPath, InstallationPath: installationPath}, runner, check)
write(result)
if err != nil {
return 1
}
return 0
}
+13 -8
View File
@@ -129,14 +129,7 @@ func installationPreflightCommand(ctx context.Context, installationPath string,
}
// Docker connection/trust and executable discovery remain host-owned. Compose parameters
// are exclusively read from the authored env file, not inherited shell overrides.
dockerEnvironment := []string{}
for _, entry := range os.Environ() {
key, _, _ := strings.Cut(entry, "=")
if slices.Contains([]string{"PATH", "HOME", "USERPROFILE", "SystemRoot", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR", "DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"}, key) {
dockerEnvironment = append(dockerEnvironment, entry)
}
}
runner := compose.NewRunnerWithEnvironment("", dockerEnvironment)
runner := compose.NewRunnerWithEnvironment("", installationDockerEnvironment())
if report.OK {
report.Merge(preflight.CheckHost(ctx, runner, host, minimum))
}
@@ -166,6 +159,7 @@ func installationPreflightCommand(ctx context.Context, installationPath string,
} else {
preflight.AddRuntimeObligations(&report)
plan := preflight.Plan{SchemaVersion: 1, ValidatorProtocol: preflight.Protocol, Validator: version.Current(), Installation: installation, Release: manifest, Platform: platform, WorkspaceDirectory: options["--workspaces"], WorkspaceRevision: revision, Inputs: inputs, AbsentInputs: absent, Report: report}
plan.ManifestPath, plan.BootstrapPath = options["--release"], options["--bootstrap"]
if err := preflight.WritePlan(options["--output"], &plan, unchanged); err != nil {
report.Add("plan-output", "error", "output", "Choose a new filename in a private canonical directory; existing plans and key files are never overwritten.")
}
@@ -181,6 +175,17 @@ func installationPreflightCommand(ctx context.Context, installationPath string,
}
return 1
}
func installationDockerEnvironment() []string {
environment := []string{}
for _, entry := range os.Environ() {
key, _, _ := strings.Cut(entry, "=")
if slices.Contains([]string{"PATH", "HOME", "USERPROFILE", "SystemRoot", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR", "DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"}, key) {
environment = append(environment, entry)
}
}
return environment
}
func writePreflight(stdout io.Writer, report preflight.Report, structured bool) {
if structured {
_ = json.NewEncoder(stdout).Encode(report)
@@ -18,6 +18,7 @@ import (
"time"
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
"github.com/aritmolab/thothii/tools/tht/internal/version"
)
func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
@@ -80,6 +81,12 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
}
write(filepath.Join(installation, "database-bootstrap.yaml"), []byte(fmt.Sprintf("schemaVersion: 1\ndatabases:\n - workspaceId: practice\n engine: postgres\n databaseName: practice\n schema: public\n binding: {transport: rest_api, baseUrl: %q, restPath: /health, restAuth: bearer}\n secretFiles: {apiKey: %q}\n", database.URL, filepath.Join(installation, "secrets/database-password"))))
manifest := preflight.Manifest{SchemaVersion: 1, Version: "1.0.0", Revision: strings.Repeat("b", 40), ValidatorProtocol: 1, Requirements: preflight.DefaultRequirements(), Components: []string{"pi", "catalog-migrations", "workspace-maintenance"}, Images: map[string]map[string]string{}, Files: map[string]string{}, Compose: []string{"compose.yaml"}}
code, identityJSON := command("version")
var identity version.Info
if code != 0 || json.Unmarshal([]byte(identityJSON), &identity) != nil {
t.Fatal("compiled operator identity unavailable")
}
manifest.Version, manifest.Revision = identity.Version, identity.Commit
platform := "linux/" + runtime.GOARCH
services := map[string]map[string]string{}
for _, role := range []string{"core", "frontend", "catalog", "qdrant", "embedding"} {
@@ -89,7 +96,7 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
services[service] = map[string]string{"image": manifest.Images[role][platform]}
}
_ = os.Mkdir(filepath.Join(release, "deploy"), 0o700)
for name, contents := range map[string]string{"compose.yaml": "services: {}\n", "deploy/compose.git-https.yaml": "services: {}\n"} {
for name, contents := range map[string]string{"compose.yaml": "services: {}\n", "deploy/compose.local.yaml": "services: {}\n", "deploy/compose.git-https.yaml": "services: {}\n"} {
write(filepath.Join(release, filepath.FromSlash(name)), []byte(contents))
sum := sha256.Sum256([]byte(contents))
manifest.Files[name] = hex.EncodeToString(sum[:])
@@ -99,6 +106,11 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
write(manifestPath, manifestJSON)
effective, _ := json.Marshal(map[string]any{"services": services})
script := fmt.Sprintf("#!/bin/sh\ncase \"$1\" in\ninfo) printf '%%s\\n' '{\"OSType\":\"linux\",\"Architecture\":\"%s\",\"NCPU\":4,\"MemTotal\":17179869184}';;\ncompose) if [ \"$2\" = version ]; then printf '2.39.0\\n'; else printf '%%s\\n' '%s'; fi;;\nmanifest) printf '%%s\\n' '{\"Descriptor\":{\"digest\":\"sha256:%s\",\"platform\":{\"os\":\"linux\",\"architecture\":\"%s\"}}}';;\n*) exit 1;;\nesac\n", runtime.GOARCH, effective, strings.Repeat("a", 64), runtime.GOARCH)
script = strings.Replace(script, "*) exit 1;;", `volume) if [ "$2" = inspect ]; then for last in "$@"; do :; done; printf '{"io.thothii.installation":"%s","io.thothii.volume":"%s"}\n' "${last%%_*}" "${last#*_}"; fi;;
run) case "$*" in *'/etc/passwd') printf 'root:x:0:0:root:/root:/bin/bash\nthoth:x:10001:10001::/home/thoth:/bin/bash\npostgres:x:999:999::/var/lib/postgresql:/bin/bash\n';; esac;;
container) :;;
*) exit 1;;`, 1)
script = strings.Replace(script, "else printf '%s\\n'", `elif case "$*" in *' ps '*) true;; *) false;; esac; then printf '%s\n' '[{"Service":"core","State":"running","Health":"healthy"},{"Service":"frontend","State":"running","Health":"healthy"},{"Service":"qdrant","State":"running","Health":"healthy"},{"Service":"embedding","State":"running","Health":"healthy"},{"Service":"embedding-model-init","State":"exited","ExitCode":0}]'; else printf '%s\n'`, 1)
write(filepath.Join(root, "docker"), []byte(script))
_ = os.Chmod(filepath.Join(root, "docker"), 0o700)
planPath := filepath.Join(installation, "plan.json")
@@ -124,6 +136,16 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
if err := preflight.VerifyPlanInputs(planPath); err != nil {
t.Fatal(err)
}
for attempt := 0; attempt < 2; attempt++ {
code, text := command("--installation", descriptor, "installation", "apply", "--plan", planPath)
var result struct {
PlatformReady bool `json:"platform_ready"`
WorkspaceReady bool `json:"workspace_ready"`
}
if code != 0 || json.Unmarshal([]byte(text), &result) != nil || !result.PlatformReady || result.WorkspaceReady || strings.Contains(text, "PRIVATE_") {
t.Fatalf("noninteractive apply attempt %d: %s", attempt, text)
}
}
write(filepath.Join(installation, "secrets/database-password"), []byte("rotated-invalid"))
if preflight.VerifyPlanInputs(planPath) == nil {
t.Fatal("rotation did not invalidate plan")
+8
View File
@@ -9,6 +9,7 @@ import (
"io"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
@@ -53,6 +54,8 @@ Commands:
Check host prerequisites and optionally the published release, without a stack.
installation plan --workspaces PATH --release MANIFEST --output NEW_PLAN [--bootstrap PATH] [--json]
Validate documents and live dependencies, then seal a private plan; requires --installation.
installation apply --plan ABS_PLAN [--json]
Recheck and apply the released plan without prompts; workspace readiness remains separate.
installation migrate --output PATH --session-default PROVIDER/MODEL
--embedding-id PROVIDER/MODEL --embedding-dimensions N
Create a review-only schema-v2 candidate from all three legacy model sources.
@@ -148,6 +151,11 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
return versionCommand(commandArgs, stdout, stderr)
}
if command == "installation" {
if len(commandArgs) > 0 && commandArgs[0] == "apply" {
bound, stop := signal.NotifyContext(ctx, os.Interrupt)
defer stop()
return installationApplyCommand(bound, installationPath, commandArgs, stdout)
}
if len(commandArgs) > 0 && (commandArgs[0] == "preflight" || commandArgs[0] == "plan") {
return installationPreflightCommand(ctx, installationPath, commandArgs, stdout)
}