From 51c21658939cb0c1c0313dca23e53f8b34013edd Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 11 Aug 2026 00:25:38 +0200 Subject: [PATCH 01/19] Say what agyn local is doing while it does it A first `agyn local start` ended with an error and exit 0. Credential provisioning ran the moment the three endpoints answered, which is before the platform has provisioned its own system organization, so the step failed, printed a recovery command, and the run carried on to print endpoints and succeed. The condition the wait tested was not the condition the next step needed, so readiness gains a second signal -- the system organization declaration carrying an assigned id, the same read `agyn local credentials` already performs, moved from a step that fails when early into the thing being waited for. Provisioning then reuses the id the wait read rather than asking again. Everything else in the group reported itself as the tooling underneath phrased it: eight identical AuthorizationPolicy warnings, klog lines with a PID in them, a Helm release listing, a raw byte counter, and three silent minutes that are indistinguishable from a hang. So the long operations are steps now -- animated on a TTY with what they are waiting on, printed once on completion anywhere else -- and limactl, helm and kubectl write to ~/.agyn/local/last-run.log, whose tail a failing step prints. --debug still streams them, and turns the animation off rather than redrawing over it. The upgrade script's stdout becomes a marker protocol and everything else it runs goes to stderr, which is what makes that split possible from inside the VM. It also learns the version it is moving to before it moves, so a release already at the newest chart is reported as such instead of upgraded to itself and reported as a new revision -- and the ingress-port repair is skipped with it, since nothing reverted the port when nothing was upgraded. Its namespace default was still the pre-rename `platform`. Preflight becomes one set of checks with an install offer behind it, reached from `start` and from `doctor --fix`. Two of the checks are new because both are failures the presence check let through: a tool older than the image's lima.yaml needs, which fails later inside limactl naming neither the version nor the fix, and free disk space, which fails halfway through a 4.6 GB decompression after the download has already run. The offer follows --install-ca: prompted on a TTY, --install-deps and --no-install-deps either way, never implied by -y, and it never installs a package manager. isTerminal read a character device rather than a terminal, so /dev/null passed: a command with stdin redirected prompted, took EOF for the default answer, and proceeded -- the opposite of the rule it existed to enforce. The endpoint list at the end becomes one link to the console. Three URLs are a menu, and what a finished install owes the reader is a next step; `agyn local status` still prints them all. --- internal/cmd/local.go | 446 +++++++++++++++------ internal/cmd/local_credentials.go | 42 +- internal/local/deps.go | 251 ++++++++++-- internal/local/deps_test.go | 53 +++ internal/local/download.go | 111 +++-- internal/local/health.go | 183 ++++++++- internal/local/health_test.go | 47 +++ internal/local/lima.go | 2 +- internal/local/preflight.go | 233 +++++++++++ internal/local/scripts/upgrade-platform.sh | 92 +++-- internal/local/upgrade.go | 175 +++++++- internal/local/upgrade_test.go | 76 ++++ internal/terminal/steps.go | 310 ++++++++++++++ internal/terminal/steps_test.go | 102 +++++ 14 files changed, 1866 insertions(+), 257 deletions(-) create mode 100644 internal/local/deps_test.go create mode 100644 internal/local/health_test.go create mode 100644 internal/local/preflight.go create mode 100644 internal/local/upgrade_test.go create mode 100644 internal/terminal/steps.go create mode 100644 internal/terminal/steps_test.go diff --git a/internal/cmd/local.go b/internal/cmd/local.go index 4a62c63..5927f83 100644 --- a/internal/cmd/local.go +++ b/internal/cmd/local.go @@ -16,6 +16,7 @@ import ( "github.com/agynio/agyn-cli/internal/config" "github.com/agynio/agyn-cli/internal/local" "github.com/agynio/agyn-cli/internal/output" + "github.com/agynio/agyn-cli/internal/terminal" "github.com/spf13/cobra" ) @@ -52,7 +53,7 @@ func newLocalCmd() *cobra.Command { }, } - cmd.PersistentFlags().BoolVar(&localDebug, "debug", false, "Show raw VM manager output") + cmd.PersistentFlags().BoolVar(&localDebug, "debug", false, "Stream the raw output of limactl, helm and kubectl instead of the step display") cmd.PersistentFlags().StringVar(&localInstance, "instance", "", "VM to act on (default: the selected one, then \""+config.DefaultInstanceName+"\")") @@ -77,15 +78,17 @@ func newLocalCmd() *cobra.Command { } type localStartFlags struct { - version string - port int - cpus int - memory string - installCA bool - noCA bool - downloadOnly bool - yes bool - profiles localProfileFlags + version string + port int + cpus int + memory string + installCA bool + noCA bool + installDeps bool + noInstallDeps bool + downloadOnly bool + yes bool + profiles localProfileFlags } func newLocalStartCmd() *cobra.Command { @@ -108,6 +111,8 @@ func newLocalStartCmd() *cobra.Command { cmd.Flags().StringVar(&flags.memory, "memory", "", "VM memory (default: from config, then 8GiB)") cmd.Flags().BoolVar(&flags.installCA, "install-ca", false, "Install the local CA into the system trust store (needs sudo)") cmd.Flags().BoolVar(&flags.noCA, "no-ca", false, "Skip certificate handling entirely") + cmd.Flags().BoolVar(&flags.installDeps, "install-deps", false, "Install missing host tools without asking") + cmd.Flags().BoolVar(&flags.noInstallDeps, "no-install-deps", false, "Never install host tools; print what is missing and stop") cmd.Flags().BoolVar(&flags.downloadOnly, "download-only", false, "Download and verify the image without starting the VM") cmd.Flags().BoolVarP(&flags.yes, "yes", "y", false, "Non-interactive: accept defaults, never prompt") addLocalProfileFlags(cmd, &flags.profiles) @@ -119,6 +124,7 @@ func runLocalStart(cmd *cobra.Command, flags localStartFlags) error { stdout := cmd.OutOrStdout() stderr := cmd.ErrOrStderr() interactive := !flags.yes && isTerminal() + steps := newSteps(cmd) cfg, err := config.Load() if err != nil { @@ -128,12 +134,8 @@ func runLocalStart(cmd *cobra.Command, flags localStartFlags) error { _, configured := cfg.Local.Instances[instanceName] firstRun := !configured - deps := local.CheckDependencies() - if missing := local.MissingRequired(deps); len(missing) > 0 { - for _, dep := range missing { - fmt.Fprintf(stderr, "missing dependency: %s (install with: %s)\n", dep.Name, dep.Fix) - } - return fmt.Errorf("install the missing dependencies and retry") + if err := runPreflight(cmd, steps, flags, interactive, firstRun); err != nil { + return err } // Resolve settings: flags > config > defaults, with a first-run wizard. @@ -160,24 +162,21 @@ func runLocalStart(cmd *cobra.Command, flags localStartFlags) error { } if instance.Exists { - if instance.Status == "Running" { - fmt.Fprintln(stdout, "VM is already running.") - finishLocalStart(cmd, flags, settings.Port) - return nil - } - fmt.Fprintln(stdout, "Starting VM (~30s)...") - limaIO, err := openLimaIO(cmd) - if err != nil { - return err - } - defer limaIO.close() - if err := local.Start(limaIO.stdout, limaIO.stderr, vmOptions(settings)); err != nil { - limaIO.reportFailure(cmd) - return err + if instance.Status != "Running" { + step := steps.Start("Starting the VM") + limaIO, err := openRunLog(cmd) + if err != nil { + return step.Fail(err) + } + defer limaIO.close() + if err := local.Start(limaIO.stdout, limaIO.stderr, vmOptions(settings)); err != nil { + step.Fail(err) + limaIO.reportFailure(cmd) + return err + } + step.Done("") } - fmt.Fprintln(stdout, "VM started.") - finishLocalStart(cmd, flags, settings.Port) - return nil + return finishLocalStart(cmd, steps, flags, settings.Port) } if interactive && firstRun && flags.port == 0 { @@ -200,8 +199,7 @@ func runLocalStart(cmd *cobra.Command, flags localStartFlags) error { return err } - fmt.Fprintf(stdout, "Using image version %s (%s)\n", version, arch) - imageDir, err := local.EnsureImage(version, arch, stderr) + imageDir, err := ensureImage(steps, version, arch) if err != nil { return err } @@ -217,83 +215,221 @@ func runLocalStart(cmd *cobra.Command, flags localStartFlags) error { return nil } - fmt.Fprintln(stdout, "Creating and starting VM (first boot takes ~1m)...") - limaIO, err := openLimaIO(cmd) + step := steps.Start("Creating the VM") + step.Detail("first boot takes about a minute") + limaIO, err := openRunLog(cmd) if err != nil { - return err + return step.Fail(err) } defer limaIO.close() if err := local.CreateAndStart(imageDir, vmOptions(settings), limaIO.stdout, limaIO.stderr); err != nil { + step.Fail(err) limaIO.reportFailure(cmd) return err } - fmt.Fprintln(stdout, "VM started.") + step.Done("") if !flags.noCA { - if err := handleCAAfterStart(cmd, flags, interactive); err != nil { - fmt.Fprintf(stderr, "certificate setup incomplete: %v\n", err) - fmt.Fprintln(stderr, "you can finish it later with: agyn local ca install") + if err := handleCAAfterStart(cmd, steps, flags, interactive); err != nil { + return err } } - finishLocalStart(cmd, flags, settings.Port) - return nil + return finishLocalStart(cmd, steps, flags, settings.Port) +} + +// ensureImage downloads and decompresses the image unless this machine already +// has it, reporting each phase as its own step: one is minutes of network with +// a byte count to show, the other minutes of CPU with nothing to show. +func ensureImage(steps *terminal.Steps, version, arch string) (string, error) { + dir, present, err := local.HaveImage(version, arch) + if err != nil { + return "", err + } + if present { + steps.Report("Image "+version, arch+", already downloaded") + return dir, nil + } + + step := steps.Start("Downloading image " + version) + step.Detail(arch) + if err := local.FetchImage(version, arch, step.Detail); err != nil { + return "", step.Fail(err) + } + step.Done(arch) + + step = steps.Start("Decompressing the image") + step.Detail("about 4.6 GB") + dir, err = local.DecompressImage(version, arch) + if err != nil { + return "", step.Fail(err) + } + step.Done("") + return dir, nil } // finishLocalStart waits for the platform, provisions the credentials that make -// the VM usable from the host, and prints the endpoint list. -// -// Provisioning failures are reported rather than returned: the VM is up and the -// endpoints are worth printing, and `agyn local credentials` finishes the job. -func finishLocalStart(cmd *cobra.Command, flags localStartFlags, port int) { - ready := waitForPlatform(cmd, port) +// the VM usable from the host, and closes with the one thing to do next. +func finishLocalStart(cmd *cobra.Command, steps *terminal.Steps, flags localStartFlags, port int) error { + step := steps.Start("Waiting for the platform") + readiness, err := local.WaitForReady(port, platformReadyTimeout, step.Detail) + if err != nil { + step.Fail(err) + fmt.Fprintf(cmd.ErrOrStderr(), + "\nThe VM is running. Watch it with `agyn local status`, and finish setup with:\n agyn local credentials\n") + return err + } + step.Done("") + if !flags.profiles.noProfile { - if !ready { - fmt.Fprintln(cmd.ErrOrStderr(), "skipping credential setup while the platform is still starting") - fmt.Fprintln(cmd.ErrOrStderr(), "run it once the platform is up with: agyn local credentials") - } else if err := provisionLocalProfile(cmd, flags.profiles, port, !flags.noCA); err != nil { - fmt.Fprintf(cmd.ErrOrStderr(), "credential setup incomplete: %v\n", err) - fmt.Fprintln(cmd.ErrOrStderr(), "you can finish it later with: agyn local credentials") + if err := provisionLocalProfile(cmd, steps, flags.profiles, port, !flags.noCA, readiness.Organization); err != nil { + return err } } - printLocalEndpoints(cmd.OutOrStdout(), port) -} -// waitForPlatform blocks until the in-VM ingress actually serves the platform: -// the guest reports "started" well before Istio and the apps are ready. -func waitForPlatform(cmd *cobra.Command, port int) bool { - fmt.Fprint(cmd.OutOrStdout(), "Waiting for the platform to become ready...") - if local.WaitForPlatform(port, 3*time.Minute) { - fmt.Fprintln(cmd.OutOrStdout(), " ready.") - return true - } - fmt.Fprintln(cmd.OutOrStdout(), " not ready yet; check `agyn local status` in a minute.") - return false + steps.CallToAction("Open the console", local.ConsoleURL(port)) + return nil } -func handleCAAfterStart(cmd *cobra.Command, flags localStartFlags, interactive bool) error { +// platformReadyTimeout bounds the wait. A first boot has to start every +// workload in the cluster and then provision the platform's own resources; five +// minutes is past the point where more waiting is the wrong answer. +const platformReadyTimeout = 5 * time.Minute + +func handleCAAfterStart(cmd *cobra.Command, steps *terminal.Steps, flags localStartFlags, interactive bool) error { + step := steps.Start("Reading the VM's certificate authority") if _, err := local.EnsureCA(); err != nil { - return err + return step.Fail(err) } + step.Done("") install := flags.installCA if !install && interactive { + // Asked outside a step: sudo prompts for a password on this terminal, + // and a spinner redrawing over the prompt makes it unreadable. install = promptYesNo(cmd, "Install the Agyn local CA into your system trust store? (asks for sudo)", true) } if !install { - if !flags.installCA { - fmt.Fprintln(cmd.OutOrStdout(), "Skipping CA install; browsers will warn about the certificate.") - fmt.Fprintln(cmd.OutOrStdout(), "Install later with: agyn local ca install") - } + steps.Skipped("Trusting the CA", "browsers will warn; install later with: agyn local ca install") return nil } if err := local.InstallCA(); err != nil { + return steps.Failed("Trusting the CA", + fmt.Errorf("%w — retry with `agyn local ca install`, or start with --no-ca", err)) + } + steps.Report("Trusting the CA", "installed in the system trust store") + return nil +} + +// runPreflight is the dependency and environment check `agyn local doctor` +// reports, run before every start. A host tool that is missing or too old is +// the most common reason a first run fails, and left to limactl the failure +// arrives as a tool error rather than a sentence naming what to install. +func runPreflight(cmd *cobra.Command, steps *terminal.Steps, flags localStartFlags, interactive, firstRun bool) error { + step := steps.Start("Checking prerequisites") + checks := local.Preflight(local.PreflightOptions{Space: firstRun}) + failures := local.BlockingFailures(checks) + if len(failures) == 0 { + step.Done(preflightSummary(checks)) + return nil + } + step.Fail(fmt.Errorf("%s", failureSummary(failures))) + + tools := local.InstallableTools(checks) + if len(tools) == 0 { + return reportUnfixable(cmd, failures) + } + command, installable := local.InstallCommand(tools) + if !installable { + return reportUnfixable(cmd, failures) + } + + install := flags.installDeps + switch { + case flags.noInstallDeps: + install = false + case install: + case interactive: + fmt.Fprintf(cmd.OutOrStdout(), "\n Missing: %s\n Install with: %s\n\n", toolList(tools), command) + install = promptYesNo(cmd, "Run it now?", true) + } + if !install { + return reportUnfixable(cmd, failures) + } + + // Run with the terminal attached rather than under a step: brew reports its + // own progress, and an install that needs sudo has to be able to ask. + steps.Note("$ " + command) + if err := local.InstallTools(tools, cmd.InOrStdin(), cmd.OutOrStdout(), cmd.ErrOrStderr()); err != nil { return err } - fmt.Fprintln(cmd.OutOrStdout(), "CA installed and trusted.") + + step = steps.Start("Re-checking prerequisites") + checks = local.Preflight(local.PreflightOptions{Space: firstRun}) + if failures := local.BlockingFailures(checks); len(failures) > 0 { + step.Fail(fmt.Errorf("%s", failureSummary(failures))) + return reportUnfixable(cmd, failures) + } + step.Done(preflightSummary(checks)) return nil } +// reportUnfixable prints what is wrong and what would fix it, and stops. There +// is nothing further to try: every remaining failure needs a decision, a +// password, or a disk. +func reportUnfixable(cmd *cobra.Command, failures []local.Check) error { + stderr := cmd.ErrOrStderr() + fmt.Fprintln(stderr) + for _, failure := range failures { + fmt.Fprintf(stderr, " %s: %s\n", failure.Name, failure.Detail) + if failure.Fix != "" { + fmt.Fprintf(stderr, " fix: %s\n", failure.Fix) + } + } + fmt.Fprintln(stderr) + return fmt.Errorf("prerequisites are not met") +} + +// preflightSummary names the host tools and their versions. The environment +// checks are deliberately not in it: "virtualization available" says nothing +// once it passed, and the free-space figure would push the line past the width +// of a terminal. `agyn local doctor` is where all of them are listed. +func preflightSummary(checks []local.Check) string { + parts := make([]string, 0, len(checks)) + for _, check := range checks { + if check.Tool() && check.State == local.CheckOK { + parts = append(parts, check.Name+" "+check.Detail) + } + } + return strings.Join(parts, ", ") +} + +func failureSummary(failures []local.Check) string { + parts := make([]string, 0, len(failures)) + for _, failure := range failures { + parts = append(parts, failure.Name+" "+failure.Detail) + } + return strings.Join(parts, "; ") +} + +func toolList(tools []local.Tool) string { + names := make([]string, 0, len(tools)) + for _, tool := range tools { + names = append(names, tool.Label) + } + return strings.Join(names, ", ") +} + +// newSteps renders the progress of one command. --debug streams the tool output +// the steps exist to hide, so it turns the animation off rather than redrawing +// over it. +func newSteps(cmd *cobra.Command) *terminal.Steps { + if localDebug { + return terminal.NewPlainSteps(cmd.OutOrStdout()) + } + return terminal.NewSteps(cmd.OutOrStdout()) +} + func newLocalStopCmd() *cobra.Command { return &cobra.Command{ Use: "stop", @@ -310,7 +446,7 @@ func newLocalStopCmd() *cobra.Command { fmt.Fprintln(cmd.OutOrStdout(), "VM is not running.") return nil } - limaIO, err := openLimaIO(cmd) + limaIO, err := openRunLog(cmd) if err != nil { return err } @@ -334,6 +470,7 @@ func newLocalRestartCmd() *cobra.Command { if err != nil { return err } + steps := newSteps(cmd) settings := resolveInstancePorts(cfg, local.InstanceName(), cfg.InstanceSettings(local.InstanceName())) instance, err := local.GetInstance() if err != nil { @@ -342,31 +479,33 @@ func newLocalRestartCmd() *cobra.Command { if !instance.Exists { return fmt.Errorf("no VM exists; run `agyn local start` first") } - limaIO, err := openLimaIO(cmd) + limaIO, err := openRunLog(cmd) if err != nil { return err } defer limaIO.close() if instance.Status == "Running" { - fmt.Fprintln(cmd.OutOrStdout(), "Stopping VM...") + step := steps.Start("Stopping the VM") if err := local.Stop(limaIO.stdout, limaIO.stderr); err != nil { + step.Fail(err) limaIO.reportFailure(cmd) return err } + step.Done("") } - fmt.Fprintln(cmd.OutOrStdout(), "Starting VM (~30s)...") + step := steps.Start("Starting the VM") if err := local.Start(limaIO.stdout, limaIO.stderr, vmOptions(settings)); err != nil { + step.Fail(err) limaIO.reportFailure(cmd) return err } - fmt.Fprintln(cmd.OutOrStdout(), "VM started.") + step.Done("") // The same finishing work as a start, because a restart is how an // edited port takes effect: the forward is only half of it, and // without repointing the in-VM URLs and the profile the new port // would answer while sign-in bounced to the old one. Idempotent // when nothing changed. - finishLocalStart(cmd, localStartFlags{}, settings.Port) - return nil + return finishLocalStart(cmd, steps, localStartFlags{}, settings.Port) }, } } @@ -468,7 +607,7 @@ func newLocalDeleteCmd() *cobra.Command { } if instance.Exists { - limaIO, err := openLimaIO(cmd) + limaIO, err := openRunLog(cmd) if err != nil { return err } @@ -512,13 +651,24 @@ func newLocalUpgradeCmd() *cobra.Command { "OpenZiti stay as they were baked. To move those — or to get a clean\n" + "machine — recreate the VM with 'agyn local delete' and 'agyn local start'.", RunE: func(cmd *cobra.Command, args []string) error { - // Streamed to the terminal, not the lima log: an upgrade that waits - // on rollouts takes minutes, and the chart versions it reports are - // the whole answer the user asked for. + // Helm's and kubectl's own output goes to the log; what reaches the + // terminal is which releases moved and where to, which is the whole + // answer the user asked for. // No token to put back afterwards: the Gateway reads it from a // Secret the chart reuses rather than from the Deployment spec it // re-renders, so an upgrade leaves this install's token alone. - return local.UpgradePlatform(cmd.OutOrStdout(), cmd.ErrOrStderr(), "") + runLog, err := openRunLog(cmd) + if err != nil { + return err + } + defer runLog.close() + + steps := newSteps(cmd) + if err := local.UpgradePlatform(steps, runLog.stdout, ""); err != nil { + runLog.reportFailure(cmd) + return err + } + return nil }, } } @@ -585,45 +735,96 @@ func loadImages(cmd *cobra.Command, images []string) error { } func newLocalDoctorCmd() *cobra.Command { - return &cobra.Command{ + var fix bool + + cmd := &cobra.Command{ Use: "doctor", - Short: "Check dependencies and environment for the local VM", + Short: "Check host tools and environment for the local VM", + Long: "Runs the same preflight `agyn local start` runs: the host tools and their\n" + + "versions, room on disk, the ports, and whether this machine can run a VM at\n" + + "all. --fix installs the tools that are missing.", RunE: func(cmd *cobra.Command, args []string) error { runContext, err := RunContextFrom(cmd) if err != nil { return err } - deps := local.CheckDependencies() + checks := local.Preflight(doctorOptions()) if runContext.OutputFormat != output.FormatTable { - return output.Print(runContext.OutputFormat, deps) - } - - rows := make([][]string, 0, len(deps)) - ok := true - for _, dep := range deps { - state := "ok" - detail := dep.Version - if !dep.Found { - state = "missing" - detail = "install with: " + dep.Fix - ok = false + return output.Print(runContext.OutputFormat, checks) + } + + if err := printChecks(cmd.OutOrStdout(), checks); err != nil { + return err + } + failures := local.BlockingFailures(checks) + if len(failures) == 0 { + return nil + } + + tools := local.InstallableTools(checks) + command, installable := local.InstallCommand(tools) + if !fix || !installable { + if installable { + fmt.Fprintf(cmd.OutOrStdout(), "\nInstall the missing tools with `agyn local doctor --fix`, or run:\n %s\n", command) } - rows = append(rows, []string{dep.Name, state, detail}) + return fmt.Errorf("%d check(s) failed", len(failures)) } - if err := (output.Table{Headers: []string{"DEPENDENCY", "STATUS", "DETAIL"}, Rows: rows}).Render(cmd.OutOrStdout()); err != nil { + + fmt.Fprintf(cmd.OutOrStdout(), "\n$ %s\n", command) + if err := local.InstallTools(tools, cmd.InOrStdin(), cmd.OutOrStdout(), cmd.ErrOrStderr()); err != nil { return err } - if !ok { - return fmt.Errorf("some dependencies are missing") + fmt.Fprintln(cmd.OutOrStdout()) + checks = local.Preflight(doctorOptions()) + if err := printChecks(cmd.OutOrStdout(), checks); err != nil { + return err + } + if remaining := local.BlockingFailures(checks); len(remaining) > 0 { + return fmt.Errorf("%d check(s) still failing", len(remaining)) } return nil }, } + + cmd.Flags().BoolVar(&fix, "fix", false, "Install the host tools that are missing") + + return cmd } -// limaIO routes limactl output: to the terminal with --debug, otherwise to -// ~/.agyn/local/lima.log with an automatic tail on failure. +// doctorOptions checks everything a start would, minus what would report a +// false failure: a running VM holds its own ports, and finding them taken by +// itself is not a problem to report. +func doctorOptions() local.PreflightOptions { + opts := local.PreflightOptions{Space: true} + cfg, err := config.Load() + if err != nil { + return opts + } + settings := resolveInstancePorts(cfg, local.InstanceName(), cfg.InstanceSettings(local.InstanceName())) + // GetInstance needs limactl, which is one of the things being checked; an + // error here means the tool check is about to report the real problem. + if instance, err := local.GetInstance(); err == nil && !instance.Exists { + opts.Ports = []int{settings.Port, settings.APIPort} + } + return opts +} + +func printChecks(out io.Writer, checks []local.Check) error { + rows := make([][]string, 0, len(checks)) + for _, check := range checks { + detail := check.Detail + if check.Fix != "" { + detail += " — fix: " + check.Fix + } + rows = append(rows, []string{check.Name, string(check.State), detail}) + } + return output.Table{Headers: []string{"CHECK", "STATUS", "DETAIL"}, Rows: rows}.Render(out) +} + +// limaIO routes the output of the tools a command drives — limactl, and the +// helm and kubectl it runs inside the VM. To the terminal with --debug, +// otherwise to ~/.agyn/local/last-run.log with an automatic tail on failure. type limaIO struct { stdout io.Writer stderr io.Writer @@ -631,7 +832,7 @@ type limaIO struct { path string } -func openLimaIO(cmd *cobra.Command) (*limaIO, error) { +func openRunLog(cmd *cobra.Command) (*limaIO, error) { if localDebug { return &limaIO{stdout: cmd.OutOrStdout(), stderr: cmd.ErrOrStderr()}, nil } @@ -643,10 +844,10 @@ func openLimaIO(cmd *cobra.Command) (*limaIO, error) { if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("create %s: %w", dir, err) } - path := filepath.Join(dir, "lima.log") + path := filepath.Join(dir, "last-run.log") file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) if err != nil { - return nil, fmt.Errorf("open lima log: %w", err) + return nil, fmt.Errorf("open run log: %w", err) } return &limaIO{stdout: file, stderr: file, file: file, path: path}, nil } @@ -672,7 +873,7 @@ func (l *limaIO) reportFailure(cmd *cobra.Command) { if len(lines) > 15 { lines = lines[len(lines)-15:] } - fmt.Fprintf(cmd.ErrOrStderr(), "\nVM manager output (last lines; full log: %s):\n%s\n", + fmt.Fprintf(cmd.ErrOrStderr(), "\nTool output (last lines; full log: %s):\n%s\n", l.path, strings.Join(lines, "\n")) reportBootLogs(cmd) } @@ -682,7 +883,7 @@ func (l *limaIO) reportFailure(cmd *cobra.Command) { // A VM that dies early reports only "exiting, status={Running:false … // Errors:[]}" and points at ha.stderr.log for the reason. That file lives in // the instance directory, which the failure path deletes, so local.CreateAndStart -// copies these up beside lima.log first -- read them from there. +// copies these up beside the run log first -- read them from there. func reportBootLogs(cmd *cobra.Command) { dir, err := local.Dir() if err != nil { @@ -707,13 +908,6 @@ func reportBootLogs(cmd *cobra.Command) { } } -func printLocalEndpoints(w interface{ Write([]byte) (int, error) }, port int) { - fmt.Fprintln(w, "\nPlatform endpoints:") - for _, endpoint := range local.Endpoints(port) { - fmt.Fprintf(w, " %-8s %s\n", endpoint.Name+":", endpoint.URL) - } -} - // resolveInstancePorts fills in ports a VM has not been given. // // The default VM keeps the well-known 2496/6445, which is what every doc and @@ -782,12 +976,14 @@ func checkPortAvailable(port int) error { return nil } +// isTerminal reports whether there is a human at stdin to prompt. +// +// A character-device check is not that check: /dev/null is a character device, +// so a command run from cron or a CI job with stdin redirected read as +// interactive, prompted, took EOF for the default answer and proceeded — which +// is exactly the "no prompts without a TTY" rule it was there to enforce. func isTerminal() bool { - info, err := os.Stdin.Stat() - if err != nil { - return false - } - return info.Mode()&os.ModeCharDevice != 0 + return terminal.IsTerminal(os.Stdin) } func promptYesNo(cmd *cobra.Command, question string, defaultYes bool) bool { diff --git a/internal/cmd/local_credentials.go b/internal/cmd/local_credentials.go index 886dee0..7687b71 100644 --- a/internal/cmd/local_credentials.go +++ b/internal/cmd/local_credentials.go @@ -4,11 +4,13 @@ import ( "fmt" "os" "path/filepath" + "strconv" "strings" "github.com/agynio/agyn-cli/internal/auth" "github.com/agynio/agyn-cli/internal/config" "github.com/agynio/agyn-cli/internal/local" + "github.com/agynio/agyn-cli/internal/terminal" "github.com/spf13/cobra" ) @@ -72,7 +74,7 @@ func newLocalCredentialsCmd() *cobra.Command { return fmt.Errorf("the VM is not running; start it with `agyn local start`") } - return provisionLocalProfile(cmd, flags, settings.Port, true) + return provisionLocalProfile(cmd, newSteps(cmd), flags, settings.Port, true, "") }, } @@ -87,58 +89,64 @@ func newLocalCredentialsCmd() *cobra.Command { // // recordCA is false when the caller was told to leave certificates alone; the // profile then trusts whatever the system trust store holds. -func provisionLocalProfile(cmd *cobra.Command, flags localProfileFlags, port int, recordCA bool) error { - stdout := cmd.OutOrStdout() +// +// organization is the id a caller has already read from the VM — the readiness +// wait reads it, because it is one of the two signals that the platform has +// finished starting. Empty means read it here. +func provisionLocalProfile(cmd *cobra.Command, steps *terminal.Steps, flags localProfileFlags, port int, recordCA bool, organization string) error { name := flags.targetProfile() + step := steps.Start("Configuring profile " + name) token, err := localBootstrapToken(name) if err != nil { - return err + return step.Fail(err) } - profile := config.Profile{GatewayURL: local.GatewayURL(port)} + profile := config.Profile{GatewayURL: local.GatewayURL(port), Organization: organization} if recordCA { // Extracted afresh rather than reused from the cache: a recreated or // upgraded VM can carry a different CA, and a stale one fails every // handshake with an error that looks like a network fault. if err := local.ExtractCA(); err != nil { - return err + return step.Fail(err) } caFile, err := local.CAPath() if err != nil { - return err + return step.Fail(err) } profile.CAFile = shortenHomePath(caFile) } - profile.Organization, err = local.OrganizationID() - if err != nil { - return err + if profile.Organization == "" { + profile.Organization, err = local.OrganizationID() + if err != nil { + return step.Fail(err) + } } // Last of the VM work, and the only part that changes the VM: the reads // above fail fast, while these restart workloads when a value differs. - fmt.Fprintln(stdout, "Installing the Gateway bootstrap token (restarts the gateway if it changed)...") + step.Detail("installing the Gateway bootstrap token") if _, err := local.SetBootstrapToken(token); err != nil { - return err + return step.Fail(err) } // The image bakes a default port into the URLs it hands a browser — the // OIDC redirects and the media proxy origin. Whenever this host forwards // something else, signing in would bounce back to a dead port. - fmt.Fprintln(stdout, "Pointing browser-facing URLs at the forwarded port...") + step.Detail("pointing browser-facing URLs at port " + strconv.Itoa(port)) if _, err := local.SetIngressPort(port); err != nil { - return err + return step.Fail(err) } current, err := writeLocalProfile(name, profile, token) if err != nil { - return err + return step.Fail(err) } - fmt.Fprintf(stdout, "Configured profile %s: %s, organization %s.\n", name, profile.GatewayURL, profile.Organization) + step.Done("organization " + profile.Organization) if current != name { - fmt.Fprintf(stdout, "Commands still run under profile %s; switch with: agyn profile use %s\n", current, name) + steps.Note(fmt.Sprintf("commands still run under profile %s; switch with: agyn profile use %s", current, name)) } return nil } diff --git a/internal/local/deps.go b/internal/local/deps.go index 9a1f267..dc2cb33 100644 --- a/internal/local/deps.go +++ b/internal/local/deps.go @@ -1,54 +1,224 @@ package local import ( + "fmt" + "io" + "os" "os/exec" + "regexp" + "runtime" + "strconv" "strings" ) -// Dependency describes one host tool required by `agyn local`. -type Dependency struct { - Name string `json:"name" yaml:"name"` - Found bool `json:"found" yaml:"found"` - Version string `json:"version,omitempty" yaml:"version,omitempty"` - Fix string `json:"fix,omitempty" yaml:"fix,omitempty"` - Optional bool `json:"optional" yaml:"optional"` +// Tool is one host tool `agyn local` needs, and what it takes to get it. +type Tool struct { + // Name is the binary as it must appear on PATH. + Name string `json:"name" yaml:"name"` + // Label is what a person calls it, when that differs from the binary. + Label string `json:"label" yaml:"label"` + // MinVersion is the oldest release the published lima.yaml and this CLI's + // use of the tool are known to work with. + MinVersion string `json:"minVersion,omitempty" yaml:"minVersion,omitempty"` + + // packages names the tool per package manager. A manager absent from the + // map does not package it — lima, for one, is packaged by no distribution. + packages map[string]string + // manual is what to tell someone no package manager can help. + manual string } -// CheckDependencies inspects the host for the tools `agyn local` needs. -func CheckDependencies() []Dependency { - return []Dependency{ - checkTool("limactl", []string{"--version"}, "brew install lima", false), - checkTool("xz", []string{"--version"}, "brew install xz", false), - checkTool("qemu-system-"+qemuArch(), []string{"--version"}, "brew install qemu", false), +// RequiredTools is what `agyn local start` cannot proceed without. +// +// Minimums are the point of the version field: a tool that is present but too +// old passes a presence check and fails later inside limactl, in a message that +// names neither the tool's version nor the fix. +func RequiredTools() []Tool { + return []Tool{ + { + Name: "limactl", + Label: "lima", + MinVersion: "1.0.0", + packages: map[string]string{"brew": "lima"}, + manual: "see https://lima-vm.io/docs/installation/", + }, + { + Name: "xz", + Label: "xz", + MinVersion: "5.0.0", + packages: map[string]string{"brew": "xz", "apt": "xz-utils", "dnf": "xz", "pacman": "xz"}, + }, + { + Name: "qemu-system-" + qemuArch(), + Label: "qemu", + MinVersion: "7.0.0", + packages: map[string]string{"brew": "qemu", "apt": "qemu-system", "dnf": "qemu-system-" + qemuArch(), "pacman": "qemu-base"}, + }, } } -// MissingRequired returns the required dependencies that were not found. -func MissingRequired(deps []Dependency) []Dependency { - var missing []Dependency - for _, dep := range deps { - if !dep.Found && !dep.Optional { - missing = append(missing, dep) +// Installer is the package manager this host has, if it has one. +type Installer struct { + // Key selects package names from a tool's map. + Key string + // Name is what the user calls it. + Name string + // command builds the shell command that installs the given packages. + command func(packages []string) string +} + +// installers are tried in order. Homebrew comes first on either platform: it is +// the only one of these that packages lima, so a machine with brew can be +// fixed in one command whichever OS it runs. +var installers = []Installer{ + {Key: "brew", Name: "Homebrew", command: func(p []string) string { + return "brew install " + strings.Join(p, " ") + }}, + {Key: "apt", Name: "apt", command: func(p []string) string { + return "sudo apt-get update && sudo apt-get install -y " + strings.Join(p, " ") + }}, + {Key: "dnf", Name: "dnf", command: func(p []string) string { + return "sudo dnf install -y " + strings.Join(p, " ") + }}, + {Key: "pacman", Name: "pacman", command: func(p []string) string { + return "sudo pacman -S --needed --noconfirm " + strings.Join(p, " ") + }}, +} + +// installerBinaries maps an installer to the binary that proves it is present. +var installerBinaries = map[string]string{ + "brew": "brew", "apt": "apt-get", "dnf": "dnf", "pacman": "pacman", +} + +// DetectInstaller returns the package manager on this host, or nil. +// +// The CLI never installs a package manager: bootstrapping Homebrew is a +// several-minute, sudo-taking, machine-wide change that a platform CLI has no +// business making on someone's behalf. A machine without one is told what to +// install and by whom. +func DetectInstaller() *Installer { + for index := range installers { + if _, err := exec.LookPath(installerBinaries[installers[index].Key]); err == nil { + return &installers[index] } } - return missing + return nil } -func checkTool(name string, versionArgs []string, fix string, optional bool) Dependency { - dep := Dependency{Name: name, Fix: fix, Optional: optional} +// InstallCommand is the command that would install these tools, and whether the +// detected installer can install all of them. A tool it does not package — lima +// outside Homebrew — leaves the caller to print that tool's own instruction. +func InstallCommand(tools []Tool) (string, bool) { + installer := DetectInstaller() + if installer == nil { + return "", false + } + packages := make([]string, 0, len(tools)) + for _, tool := range tools { + name, ok := tool.packages[installer.Key] + if !ok { + return "", false + } + packages = append(packages, name) + } + if len(packages) == 0 { + return "", false + } + return installer.command(packages), true +} + +// InstallTools runs the install command with the terminal attached, so brew +// reports its own progress and sudo can ask for a password. +func InstallTools(tools []Tool, stdin io.Reader, stdout, stderr io.Writer) error { + command, ok := InstallCommand(tools) + if !ok { + return fmt.Errorf("no package manager on this host installs %s", toolNames(tools)) + } + cmd := exec.Command("sh", "-c", command) + cmd.Stdin = stdin + cmd.Stdout = stdout + cmd.Stderr = stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("%s: %w", command, err) + } + return nil +} - path, err := exec.LookPath(name) +func toolNames(tools []Tool) string { + names := make([]string, 0, len(tools)) + for _, tool := range tools { + names = append(names, tool.Label) + } + return strings.Join(names, ", ") +} + +// fix describes how to get this tool, whether or not a package manager can. +// +// With no package manager on the host there is still something useful to say: +// the package name under the manager most likely to be reachable, so the user +// can map it to whatever theirs is. "install qemu" on its own is not a fix. +func (t Tool) fix() string { + if command, ok := InstallCommand([]Tool{t}); ok { + return command + } + if name, ok := t.packages["brew"]; ok { + return "brew install " + name + " (or your platform's equivalent)" + } + if t.manual != "" { + return t.manual + } + return "install " + t.Label +} + +// inspect reports what the host has of this tool. +func (t Tool) inspect() (found bool, version string) { + path, err := exec.LookPath(t.Name) + if err != nil { + return false, "" + } + out, err := exec.Command(path, "--version").Output() if err != nil { - return dep + // Present but unable to report a version: the presence is what the + // check is for, and an unreadable version is not grounds to refuse. + return true, "" } - dep.Found = true + line := strings.SplitN(strings.TrimSpace(string(out)), "\n", 2)[0] + return true, parseVersion(line) +} - out, err := exec.Command(path, versionArgs...).Output() - if err == nil { - line := strings.SplitN(strings.TrimSpace(string(out)), "\n", 2)[0] - dep.Version = strings.TrimSpace(line) +var versionPattern = regexp.MustCompile(`\d+(?:\.\d+)+`) + +// parseVersion pulls the version out of a --version line. Every tool here +// prints it differently ("limactl version 1.0.4", "xz (XZ Utils) 5.6.2", +// "QEMU emulator version 9.1.0") and all three put it in the first line. +func parseVersion(line string) string { + return versionPattern.FindString(line) +} + +// compareVersions orders two dotted numeric versions. An unparseable or empty +// version compares equal, so a tool that would not say what it is is given the +// benefit of the doubt rather than blocked. +func compareVersions(a, b string) int { + if a == "" || b == "" { + return 0 } - return dep + left, right := strings.Split(a, "."), strings.Split(b, ".") + for i := 0; i < len(left) || i < len(right); i++ { + var l, r int + if i < len(left) { + l, _ = strconv.Atoi(left[i]) + } + if i < len(right) { + r, _ = strconv.Atoi(right[i]) + } + if l != r { + if l < r { + return -1 + } + return 1 + } + } + return 0 } func qemuArch() string { @@ -61,3 +231,24 @@ func qemuArch() string { } return "aarch64" } + +// kvmAvailable reports whether hardware virtualization is usable here. +// +// Linux only: macOS reaches the Hypervisor framework without a device node or a +// group membership. A Linux host without /dev/kvm runs the VM under emulation, +// where a k3s cluster with Istio in it does not finish starting in any time a +// person would wait — so this is a blocking condition, not a slow one. +func kvmAvailable() (bool, string) { + if runtime.GOOS != "linux" { + return true, "" + } + file, err := os.OpenFile("/dev/kvm", os.O_RDWR, 0) + if err == nil { + file.Close() + return true, "" + } + if os.IsNotExist(err) { + return false, "/dev/kvm is missing; enable virtualization in the BIOS or use a host that exposes it" + } + return false, "/dev/kvm is not writable by this user; run: sudo usermod -aG kvm $USER, then log in again" +} diff --git a/internal/local/deps_test.go b/internal/local/deps_test.go new file mode 100644 index 0000000..39f6c2b --- /dev/null +++ b/internal/local/deps_test.go @@ -0,0 +1,53 @@ +package local + +import "testing" + +// Each tool prints its version differently and all three put it in the first +// line. A parser that only handled one of them would silently treat the others +// as unknown, which is the state that never blocks. +func TestParseVersionReadsWhatEachToolActuallyPrints(t *testing.T) { + for _, tc := range []struct{ line, want string }{ + {"limactl version 1.0.4", "1.0.4"}, + {"xz (XZ Utils) 5.6.2", "5.6.2"}, + {"QEMU emulator version 9.1.0", "9.1.0"}, + {"limactl version 2.1.3", "2.1.3"}, + {"some tool with no version", ""}, + } { + if got := parseVersion(tc.line); got != tc.want { + t.Errorf("parseVersion(%q) = %q, want %q", tc.line, got, tc.want) + } + } +} + +func TestCompareVersions(t *testing.T) { + for _, tc := range []struct { + a, b string + want int + }{ + {"1.0.4", "1.0.0", 1}, + {"0.23.0", "1.0.0", -1}, + {"1.0", "1.0.0", 0}, + {"11.0.1", "9.1.0", 1}, + // A tool that would not report a version is given the benefit of the + // doubt: refusing to start over an unreadable --version would be worse + // than the too-old case it is trying to catch. + {"", "1.0.0", 0}, + } { + if got := compareVersions(tc.a, tc.b); got != tc.want { + t.Errorf("compareVersions(%q, %q) = %d, want %d", tc.a, tc.b, got, tc.want) + } + } +} + +// A tool no package manager packages must still say how to get it, or the +// preflight reports a problem with no way out. +func TestEveryRequiredToolHasAFix(t *testing.T) { + for _, tool := range RequiredTools() { + if tool.fix() == "" { + t.Errorf("%s has no fix", tool.Name) + } + if tool.MinVersion == "" { + t.Errorf("%s has no minimum version", tool.Name) + } + } +} diff --git a/internal/local/download.go b/internal/local/download.go index 35350bd..ae80a5c 100644 --- a/internal/local/download.go +++ b/internal/local/download.go @@ -47,44 +47,60 @@ func ResolveVersion(version string) (string, error) { return pointer.Version, nil } -// EnsureImage makes sure the decompressed disk for version/arch exists locally, -// downloading and verifying it if needed. Returns the image directory. -// Progress messages go to progress (may be nil). -func EnsureImage(version, arch string, progress io.Writer) (string, error) { +// HaveImage reports whether the decompressed disk for version/arch is already +// on this machine, and the directory it lives in either way. +func HaveImage(version, arch string) (string, bool, error) { dir, err := ImageDir(version, arch) if err != nil { - return "", err + return "", false, err } if err := os.MkdirAll(dir, 0o755); err != nil { - return "", fmt.Errorf("create image dir: %w", err) + return "", false, fmt.Errorf("create image dir: %w", err) } + _, err = os.Stat(filepath.Join(dir, DiskFileName(arch))) + return dir, err == nil, nil +} - disk := filepath.Join(dir, DiskFileName(arch)) - if _, err := os.Stat(disk); err == nil { - return dir, nil +// FetchImage downloads and verifies the compressed disk and the metadata +// beside it, reporting progress through report (which may be nil). +// +// Download and decompression are separate calls because they are separate +// waits: one is minutes of network with a byte count to show, the other is +// minutes of CPU with nothing to show but that it is running. +func FetchImage(version, arch string, report func(detail string)) error { + dir, _, err := HaveImage(version, arch) + if err != nil { + return err } base := fmt.Sprintf("%s/%s/%s", BaseURL(), version, arch) - diskXZ := disk + ".xz" - for _, name := range []string{"checksums.sha256", "metadata.json", "lima.yaml"} { if err := download(base+"/"+name, filepath.Join(dir, name), nil); err != nil { - return "", err + return err } } - if !verifyChecksum(dir, filepath.Base(diskXZ)) { - if err := download(base+"/"+filepath.Base(diskXZ), diskXZ, progress); err != nil { - return "", err - } - if !verifyChecksum(dir, filepath.Base(diskXZ)) { - return "", fmt.Errorf("checksum mismatch for %s after download", filepath.Base(diskXZ)) - } + name := DiskFileName(arch) + ".xz" + if verifyChecksum(dir, name) { + return nil } + if err := download(base+"/"+name, filepath.Join(dir, name), report); err != nil { + return err + } + if !verifyChecksum(dir, name) { + return fmt.Errorf("checksum mismatch for %s after download", name) + } + return nil +} - if progress != nil { - fmt.Fprintln(progress, "Decompressing image (~4.6 GB)...") +// DecompressImage expands the downloaded archive into the qcow2 disk Lima +// boots, and returns the image directory. +func DecompressImage(version, arch string) (string, error) { + dir, err := ImageDir(version, arch) + if err != nil { + return "", err } + diskXZ := filepath.Join(dir, DiskFileName(arch)+".xz") cmd := exec.Command("xz", "--decompress", "--keep", "--force", diskXZ) if out, err := cmd.CombinedOutput(); err != nil { return "", fmt.Errorf("decompress image: %w: %s", err, strings.TrimSpace(string(out))) @@ -92,7 +108,6 @@ func EnsureImage(version, arch string, progress io.Writer) (string, error) { // The compressed artifact is no longer needed once the disk exists. _ = os.Remove(diskXZ) - return dir, nil } @@ -131,7 +146,7 @@ func verifyChecksum(dir, name string) bool { // download fetches url into path atomically (tmp file + rename), resuming a // previous partial download when the server supports ranges. -func download(url, path string, progress io.Writer) error { +func download(url, path string, report func(detail string)) error { tmp := path + ".partial" var offset int64 @@ -170,12 +185,16 @@ func download(url, path string, progress io.Writer) error { } var writer io.Writer = out - if progress != nil { + if report != nil { writer = io.MultiWriter(out, &progressWriter{ - out: progress, + report: report, total: resp.ContentLength + offset, written: offset, - label: filepath.Base(path), + started: time.Now(), + // Resumed bytes were not transferred now, so they must not count + // toward the rate -- a resume would otherwise open by claiming a + // gigabyte per second and take a minute to settle. + resumed: offset, }) } @@ -188,32 +207,50 @@ func download(url, path string, progress io.Writer) error { return fmt.Errorf("write %s: %w", tmp, closeErr) } - if progress != nil { - fmt.Fprintln(progress) - } if err := os.Rename(tmp, path); err != nil { return fmt.Errorf("finalize %s: %w", path, err) } return nil } +// progressWriter turns the byte stream into the detail line of a step: how much +// of the image has arrived, how fast, and how much longer it will take. type progressWriter struct { - out io.Writer + report func(detail string) total int64 written int64 - label string + resumed int64 + started time.Time lastTick time.Time } func (p *progressWriter) Write(data []byte) (int, error) { p.written += int64(len(data)) - if time.Since(p.lastTick) >= time.Second { - p.lastTick = time.Now() - if p.total > 0 { - fmt.Fprintf(p.out, "\r%s: %d%% (%d/%d MB)", p.label, p.written*100/p.total, p.written>>20, p.total>>20) - } else { - fmt.Fprintf(p.out, "\r%s: %d MB", p.label, p.written>>20) + if time.Since(p.lastTick) < 250*time.Millisecond { + return len(data), nil + } + p.lastTick = time.Now() + + elapsed := time.Since(p.started).Seconds() + rate := float64(p.written-p.resumed) / elapsed + detail := formatBytes(p.written) + if p.total > 0 { + detail += " of " + formatBytes(p.total) + } + if elapsed > 1 && rate > 0 { + detail += fmt.Sprintf(" %s/s", formatBytes(int64(rate))) + if p.total > p.written { + remaining := time.Duration(float64(p.total-p.written)/rate) * time.Second + detail += " " + formatRemaining(remaining) } } + p.report(detail) return len(data), nil } + +func formatRemaining(d time.Duration) string { + if d < time.Minute { + return fmt.Sprintf("%ds left", int(d.Seconds())) + } + return fmt.Sprintf("%dm left", int(d.Minutes())+1) +} diff --git a/internal/local/health.go b/internal/local/health.go index 89c3694..40e6be7 100644 --- a/internal/local/health.go +++ b/internal/local/health.go @@ -4,6 +4,9 @@ import ( "crypto/tls" "fmt" "net/http" + "sort" + "strconv" + "strings" "time" ) @@ -20,6 +23,11 @@ func GatewayURL(port int) string { return fmt.Sprintf("https://gateway.%s:%d", BaseDomain, port) } +// ConsoleURL is where a finished start sends the user. +func ConsoleURL(port int) string { + return fmt.Sprintf("https://console.%s:%d", BaseDomain, port) +} + // Endpoints returns the primary platform endpoints for the configured port. func Endpoints(port int) []Endpoint { names := []string{"console", "chat", "tracing"} @@ -33,25 +41,170 @@ func Endpoints(port int) []Endpoint { return endpoints } -// WaitForPlatform polls the platform endpoints until they all answer or the -// timeout elapses. The VM reports "started" as soon as the guest boots, but -// the in-cluster ingress takes tens of seconds more to serve traffic. -func WaitForPlatform(port int, timeout time.Duration) bool { +// Readiness is the platform's own account of whether it can be used yet. +type Readiness struct { + // Endpoints answering through the host's forwarded port. The ingress + // begins serving tens of seconds after the VM reports itself started. + Endpoints []Endpoint + // Organization is the id the platform assigned to the organization its + // release declares. Provisioning completes after the endpoints answer, so + // an endpoint check alone is not evidence that it has -- and this id is + // what the profile records and every org-scoped command runs against. + Organization string + // Pending names what is not ready yet, for a caller to show. + Pending []string +} + +// Ready reports whether both readiness signals hold. +func (r Readiness) Ready() bool { return len(r.Pending) == 0 } + +// Missing describes what is still outstanding, for a timeout message. +func (r Readiness) Missing() string { + if len(r.Pending) == 0 { + return "" + } + return strings.Join(r.Pending, ", ") +} + +// CheckReadiness probes both signals once. +func CheckReadiness(port int) Readiness { + readiness := Readiness{Endpoints: CheckEndpoints(Endpoints(port))} + + var unhealthy []string + for _, endpoint := range readiness.Endpoints { + if !endpoint.Healthy { + unhealthy = append(unhealthy, endpoint.Name) + } + } + if len(unhealthy) > 0 { + readiness.Pending = append(readiness.Pending, "endpoints: "+strings.Join(unhealthy, ", ")) + return readiness + } + + // Only asked once the ingress answers: before that the API server inside + // the VM is not up either, and the failure would be noise on every poll. + organization, err := OrganizationID() + if err != nil || organization == "" { + readiness.Pending = append(readiness.Pending, "the platform is provisioning its organization") + return readiness + } + readiness.Organization = organization + return readiness +} + +// WaitForReady blocks until the platform can be used, reporting what it is +// waiting on as that changes. +// +// Returning when the endpoints answer is what left credential provisioning +// running against a platform that had not finished starting: the read it needs +// -- the assigned organization id -- lands after the ingress does. +func WaitForReady(port int, timeout time.Duration, progress func(detail string)) (Readiness, error) { deadline := time.Now().Add(timeout) - for time.Now().Before(deadline) { - healthy := 0 - endpoints := CheckEndpoints(Endpoints(port)) - for _, endpoint := range endpoints { - if endpoint.Healthy { - healthy++ - } + var readiness Readiness + for { + readiness = CheckReadiness(port) + if readiness.Ready() { + return readiness, nil + } + if time.Now().After(deadline) { + return readiness, fmt.Errorf("the platform did not become ready within %s (%s)", + timeout.Round(time.Second), readiness.Missing()) } - if healthy == len(endpoints) { - return true + if progress != nil { + progress(waitingDetail(readiness)) } - time.Sleep(5 * time.Second) + time.Sleep(3 * time.Second) + } +} + +// waitingDetail is what to show beside the spinner: the workloads still coming +// up when the VM can be asked, and what is outstanding when it cannot. +func waitingDetail(readiness Readiness) string { + if ready, total, err := WorkloadProgress(); err == nil && total > 0 && ready < total { + return fmt.Sprintf("%d of %d workloads ready", ready, total) + } + return readiness.Missing() +} + +// Workload is one deployment or statefulset and how far its rollout has got. +type Workload struct { + Name string + Ready int + Desired int +} + +// Rolling reports whether the workload is short of its desired replicas. +func (w Workload) Rolling() bool { return w.Ready < w.Desired } + +// Workloads reads the platform's workloads from inside the VM, so a wait can +// say how far along it is rather than only that it is still waiting. +func Workloads() ([]Workload, error) { + out, err := Shell("sudo", "kubectl", "get", "deploy,statefulset", "-A", + "-o", `jsonpath={range .items[*]}{.metadata.name}{" "}{.status.readyReplicas}{" "}{.spec.replicas}{"\n"}{end}`) + if err != nil { + return nil, err + } + return parseWorkloads(out), nil +} + +func parseWorkloads(out string) []Workload { + var workloads []Workload + for _, line := range strings.Split(strings.TrimSpace(out), "\n") { + fields := strings.Fields(line) + if len(fields) < 2 { + continue + } + // readyReplicas is absent rather than zero on a workload with none, so + // a two-field line is "name desired" with nothing ready. + workload := Workload{Name: fields[0]} + if len(fields) == 2 { + workload.Desired, _ = strconv.Atoi(fields[1]) + } else { + workload.Ready, _ = strconv.Atoi(fields[1]) + workload.Desired, _ = strconv.Atoi(fields[2]) + } + if workload.Desired == 0 { + continue + } + workloads = append(workloads, workload) + } + return workloads +} + +// WorkloadProgress counts the workloads that have reached their desired +// replica count. +func WorkloadProgress() (ready, total int, err error) { + workloads, err := Workloads() + if err != nil { + return 0, 0, err + } + for _, workload := range workloads { + total++ + if !workload.Rolling() { + ready++ + } + } + return ready, total, nil +} + +// RollingWorkloads names the workloads still short of their replicas, for the +// detail line of an upgrade waiting on rollouts. +func RollingWorkloads(limit int) []string { + workloads, err := Workloads() + if err != nil { + return nil + } + var rolling []string + for _, workload := range workloads { + if workload.Rolling() { + rolling = append(rolling, workload.Name) + } + } + sort.Strings(rolling) + if limit > 0 && len(rolling) > limit { + return append(rolling[:limit:limit], fmt.Sprintf("and %d more", len(rolling)-limit)) } - return false + return rolling } // CheckEndpoints probes each endpoint. The local CA is typically not in Go's diff --git a/internal/local/health_test.go b/internal/local/health_test.go new file mode 100644 index 0000000..e26abbd --- /dev/null +++ b/internal/local/health_test.go @@ -0,0 +1,47 @@ +package local + +import "testing" + +// kubectl omits readyReplicas entirely on a workload with none, so the line for +// the workload a wait most wants to report is the one with a field missing. +func TestParseWorkloadsHandlesAMissingReadyCount(t *testing.T) { + workloads := parseWorkloads("gateway 3 3\nagents 1\nchat 0 2\nkeycloak 1 1\n") + + if len(workloads) != 4 { + t.Fatalf("expected 4 workloads, got %d: %+v", len(workloads), workloads) + } + if workloads[1].Name != "agents" || workloads[1].Ready != 0 || workloads[1].Desired != 1 { + t.Fatalf("expected agents to be 0 of 1, got %+v", workloads[1]) + } + rolling := 0 + for _, workload := range workloads { + if workload.Rolling() { + rolling++ + } + } + if rolling != 2 { + t.Fatalf("expected 2 rolling workloads, got %d", rolling) + } +} + +// A workload scaled to zero is not one a wait is waiting for. +func TestParseWorkloadsIgnoresScaledDownWorkloads(t *testing.T) { + if got := parseWorkloads("idle 0 0\n"); len(got) != 0 { + t.Fatalf("expected scaled-down workloads to be dropped, got %+v", got) + } +} + +// Readiness is two signals, and the second one is the whole reason the wait +// exists: the endpoints answer before the platform has provisioned itself. +func TestReadinessIsNotReadyUntilBothSignalsHold(t *testing.T) { + pending := Readiness{Pending: []string{"the platform is provisioning its organization"}} + if pending.Ready() { + t.Fatal("expected a platform with no organization id to be not ready") + } + if pending.Missing() == "" { + t.Fatal("expected a timeout to be able to name what is missing") + } + if !(Readiness{Organization: "8f3a"}).Ready() { + t.Fatal("expected both signals holding to be ready") + } +} diff --git a/internal/local/lima.go b/internal/local/lima.go index 6803b88..8792159 100644 --- a/internal/local/lima.go +++ b/internal/local/lima.go @@ -121,7 +121,7 @@ func CreateAndStart(imageDir string, opts VMOptions, stdout, stderr io.Writer) e var BootLogNames = []string{"ha.stderr.log", "serial.log"} // preserveBootLogs copies the instance's boot logs up into the local directory, -// beside lima.log, so they outlive the instance. Best effort throughout: this +// beside the run log, so they outlive the instance. Best effort throughout: this // runs on a path that has already failed and must not fail again. func preserveBootLogs() { limaHome, err := LimaHome() diff --git a/internal/local/preflight.go b/internal/local/preflight.go new file mode 100644 index 0000000..cf5e76e --- /dev/null +++ b/internal/local/preflight.go @@ -0,0 +1,233 @@ +package local + +import ( + "fmt" + "net" + "os" + "path/filepath" + + "golang.org/x/sys/unix" +) + +// CheckState is the outcome of one preflight check. +type CheckState string + +const ( + // CheckOK is a check that passed. + CheckOK CheckState = "ok" + // CheckMissing is a tool that is not installed. + CheckMissing CheckState = "missing" + // CheckOutdated is a tool that is installed but older than the minimum. + CheckOutdated CheckState = "outdated" + // CheckFailed is a non-tool condition that is not satisfied. + CheckFailed CheckState = "failed" + // CheckWarning is worth reporting and not worth refusing to start over. + CheckWarning CheckState = "warning" +) + +// Check is one preflight result. +type Check struct { + Name string `json:"name" yaml:"name"` + State CheckState `json:"state" yaml:"state"` + Detail string `json:"detail,omitempty" yaml:"detail,omitempty"` + Fix string `json:"fix,omitempty" yaml:"fix,omitempty"` + Blocking bool `json:"blocking" yaml:"blocking"` + + // tool is set when the fix is installing a host tool, which is the only + // fix `--install-deps` and `doctor --fix` know how to apply. + tool *Tool +} + +// Passed reports whether a check is one that lets a start proceed. +func (c Check) Passed() bool { return c.State == CheckOK || c.State == CheckWarning } + +// Tool reports whether this check is a host tool, which is the only kind of +// failure `--install-deps` and `doctor --fix` can act on. +func (c Check) Tool() bool { return c.tool != nil } + +// PreflightOptions narrow the checks to what a particular command needs. +type PreflightOptions struct { + // Ports must be free. Only a VM being created needs this: an existing VM + // already holds its own ports, and finding them taken by itself would + // refuse every restart. + Ports []int + // Space checks room for an image and the VM created from it. + Space bool +} + +// Disk space needed under ~/.agyn/local for a first start: the compressed +// download (~1.4 GB) plus the disk it decompresses to (~4.6 GB) plus the copy +// Lima takes into the instance, and then room for the VM to grow. Below the +// minimum a start fails partway through decompression, having already spent the +// download; the recommendation is where it stops being tight. +const ( + minFreeBytes = 12 << 30 + recommendedFreeBytes = 20 << 30 +) + +// Preflight reports what would stop this host from running the platform VM. +// +// It runs on every `agyn local start` and is all of `agyn local doctor`: a +// missing or too-old host tool is the most common reason a first run fails, and +// left to limactl the failure arrives as a tool error rather than a sentence +// naming what to install. +func Preflight(opts PreflightOptions) []Check { + checks := make([]Check, 0, 8) + for _, tool := range RequiredTools() { + checks = append(checks, checkTool(tool)) + } + if opts.Space { + checks = append(checks, checkFreeSpace()) + } + for _, port := range opts.Ports { + checks = append(checks, checkPort(port)) + } + checks = append(checks, checkVirtualization()) + return checks +} + +// BlockingFailures returns the checks that stop a start. +func BlockingFailures(checks []Check) []Check { + var failures []Check + for _, check := range checks { + if !check.Passed() && check.Blocking { + failures = append(failures, check) + } + } + return failures +} + +// InstallableTools returns the tools behind failing checks — what +// `--install-deps` and `doctor --fix` would install. +func InstallableTools(checks []Check) []Tool { + var tools []Tool + for _, check := range checks { + if !check.Passed() && check.tool != nil { + tools = append(tools, *check.tool) + } + } + return tools +} + +func checkTool(tool Tool) Check { + check := Check{Name: tool.Label, Blocking: true, Fix: tool.fix(), tool: &tool} + + found, version := tool.inspect() + switch { + case !found: + check.State = CheckMissing + check.Detail = "not installed" + case compareVersions(version, tool.MinVersion) < 0: + check.State = CheckOutdated + check.Detail = fmt.Sprintf("%s, needs %s or newer", version, tool.MinVersion) + default: + check.State = CheckOK + check.Detail = version + check.Fix = "" + } + return check +} + +func checkFreeSpace() Check { + check := Check{Name: "disk space", Blocking: true} + + dir, err := Dir() + if err != nil { + check.State = CheckWarning + check.Detail = err.Error() + return check + } + free, err := freeSpace(dir) + if err != nil { + // Unmeasurable is not the same as insufficient: report it and let the + // start proceed rather than refuse on a failed syscall. + check.State = CheckWarning + check.Detail = err.Error() + return check + } + + check.Detail = fmt.Sprintf("%s free in %s", formatBytes(free), tildePath(dir)) + switch { + case free < minFreeBytes: + check.State = CheckFailed + check.Detail = fmt.Sprintf("%s free in %s, needs %s", + formatBytes(free), tildePath(dir), formatBytes(minFreeBytes)) + check.Fix = "free up disk space" + case free < recommendedFreeBytes: + check.State = CheckWarning + check.Detail += fmt.Sprintf(" (%s recommended)", formatBytes(recommendedFreeBytes)) + default: + check.State = CheckOK + } + return check +} + +// freeSpace reports the bytes available to this user at path, or at the nearest +// existing ancestor — nothing under ~/.agyn/local exists before a first start. +func freeSpace(path string) (int64, error) { + for { + var stat unix.Statfs_t + err := unix.Statfs(path, &stat) + if err == nil { + return int64(stat.Bavail) * int64(stat.Bsize), nil + } + parent := filepath.Dir(path) + if parent == path { + return 0, fmt.Errorf("measure free space: %w", err) + } + path = parent + } +} + +func checkPort(port int) Check { + check := Check{Name: fmt.Sprintf("port %d", port), Blocking: true} + listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)) + if err != nil { + check.State = CheckFailed + check.Detail = "already in use" + check.Fix = fmt.Sprintf("choose another with --port, or: agyn local config set port ") + return check + } + listener.Close() + check.State = CheckOK + check.Detail = "free" + return check +} + +func checkVirtualization() Check { + check := Check{Name: "virtualization", Blocking: true} + available, detail := kvmAvailable() + if available { + check.State = CheckOK + check.Detail = "available" + return check + } + check.State = CheckFailed + check.Detail = detail + return check +} + +func formatBytes(bytes int64) string { + switch { + case bytes >= 1<<30: + return fmt.Sprintf("%.1f GB", float64(bytes)/(1<<30)) + case bytes >= 1<<20: + return fmt.Sprintf("%d MB", bytes>>20) + default: + return fmt.Sprintf("%d KB", bytes>>10) + } +} + +// tildePath shortens a path under the home directory, which is where +// everything this CLI writes lives. +func tildePath(path string) string { + home, err := os.UserHomeDir() + if err != nil || home == "" { + return path + } + rel, err := filepath.Rel(home, path) + if err != nil || rel == ".." || filepath.IsAbs(rel) { + return path + } + return "~/" + filepath.ToSlash(rel) +} diff --git a/internal/local/scripts/upgrade-platform.sh b/internal/local/scripts/upgrade-platform.sh index 1b38090..12d6ea7 100755 --- a/internal/local/scripts/upgrade-platform.sh +++ b/internal/local/scripts/upgrade-platform.sh @@ -26,10 +26,16 @@ set -euo pipefail # # What this does NOT do: upgrade k3s, Istio, cert-manager, OpenZiti, or Postgres. # Those come from the image, and moving them is what a new image is for. +# +# OUTPUT CONTRACT. stdout carries nothing but AGYN| markers, which the CLI turns +# into the steps a user sees; every tool's own output goes to stderr, which the +# CLI writes to a log. Helm's admission warnings, kubectl's klog lines and the +# release listing answer a different question than the one the user asked, and +# a step that fails prints the tail of that log with its path. export KUBECONFIG=/etc/rancher/k3s/k3s.yaml -NAMESPACE="${AGYN_PLATFORM_NAMESPACE:-platform}" +NAMESPACE="${AGYN_PLATFORM_NAMESPACE:-agyn-platform}" PLATFORM_CHART="${AGYN_PLATFORM_CHART:-oci://ghcr.io/agynio/charts/agyn-platform}" APPS_CHART="${AGYN_APPS_CHART:-oci://ghcr.io/agynio/charts/agyn-apps}" HELM_TIMEOUT="${AGYN_HELM_TIMEOUT:-15m}" @@ -65,12 +71,20 @@ if [ -n "${extra_values}" ] && [ ! -r "${extra_values}" ]; then exit 66 fi -log() { printf '[upgrade-platform] %s\n' "$*"; } - -until kubectl get --raw=/readyz >/dev/null 2>&1; do - log "waiting for the API server" - sleep 5 -done +# The four markers the CLI understands. Anything else on stdout is treated as +# tool output and logged. +step() { printf 'AGYN|step|%s|%s\n' "${1}" "${2:-}"; } +done_() { printf 'AGYN|done|%s\n' "${1:-}"; } +skip() { printf 'AGYN|skip|%s\n' "${1:-}"; } +note() { printf 'AGYN|note|%s\n' "${1}"; } + +if ! kubectl get --raw=/readyz >/dev/null 2>&1; then + step "Waiting for the cluster" "" + until kubectl get --raw=/readyz >/dev/null 2>&1; do + sleep 5 + done + done_ "" +fi # Helm rewrites every Deployment it owns back to what the chart says. Anything # running from source under `devspace dev` is one of those, so an upgrade ends @@ -78,7 +92,7 @@ done # quietly stops reflecting the code someone is editing. if kubectl -n "${NAMESPACE}" get deploy -o jsonpath='{range .items[*]}{.spec.template.spec.containers[0].image}{"\n"}{end}' 2>/dev/null | grep -q 'devcontainer'; then - log "note: services running from source (devspace) will be reset to their chart images" + note "services running from source (devspace) will be reset to their chart images" fi installed_version() { @@ -86,17 +100,42 @@ installed_version() { sed -n 's/.*"chart":"[^"]*-\([0-9][^"]*\)".*/\1/p' | head -1 } +# The version the chart repository would install, so an upgrade can say where it +# is going before it goes there — and can decline to go nowhere. +available_version() { + chart="${1}" + want="${2}" + set -- show chart "${chart}" + if [ -n "${want}" ]; then + set -- "$@" --version "${want}" + fi + helm "$@" 2>/dev/null | sed -n 's/^version: *//p' | head -1 +} + upgrade() { release="${1}" chart="${2}" want="${3}" if ! helm status "${release}" -n "${NAMESPACE}" >/dev/null 2>&1; then - log "${release} is not installed; skipping" return 0 fi before="$(installed_version "${release}")" + target="$(available_version "${chart}" "${want}")" + + # An upgrade to the version already installed still rewrites every workload + # the chart owns and reports a new revision, so "nothing to do" and + # "everything was replaced" would read alike. Say the first one instead. + if [ -z "${extra_values}" ] && [ -n "${before}" ] && [ "${before}" = "${target}" ]; then + step "${release}" + skip "already at ${before}" + return 0 + fi + + upgraded=1 + + step "${release}" "${before:-unknown} → ${target:-latest}" # --reuse-values would carry the old values forward but ignore defaults the # newer chart introduces, so a subchart added since the last release starts @@ -110,22 +149,17 @@ upgrade() { if [ -n "${extra_values}" ]; then set -- "$@" -f "${extra_values}" fi - if [ -n "${want}" ]; then - set -- "$@" --version "${want}" - log "${release}: ${before:-unknown} -> ${want}" - else - log "${release}: ${before:-unknown} -> latest" + if [ -n "${target}" ]; then + set -- "$@" --version "${target}" fi - helm "$@" + helm "$@" >&2 after="$(installed_version "${release}")" - log "${release} now at ${after:-unknown}" - if [ -n "${before}" ] && [ "${before}" = "${after}" ]; then - log "${release} was already up to date" - fi + done_ "${before:-unknown} → ${after:-unknown}" } +upgraded=0 upgrade agyn-platform "${PLATFORM_CHART}" "${platform_version}" upgrade agyn-apps "${APPS_CHART}" "${apps_version}" @@ -139,16 +173,22 @@ upgrade agyn-apps "${APPS_CHART}" "${apps_version}" # The port itself survives, because it lives on the istio-ingressgateway # Service and no chart owns that. So it is read back from there and re-applied. # Idempotent: on a VM still using the default port this changes nothing. +# +# Skipped when nothing was upgraded, because then nothing reverted it: an +# upgrade that did nothing should say so in one line and stop, not perform +# repair work on a cluster it did not touch. +if [ "${upgraded}" -eq 0 ]; then + exit 0 +fi + host_port="$(kubectl -n istio-gateway get svc istio-ingressgateway \ -o jsonpath='{.spec.ports[?(@.name=="https-hostport")].port}' 2>/dev/null || true)" if [ -n "${host_port}" ] && [ -x /opt/agyn/set-ingress-port.sh ]; then - log "re-applying the ingress host port ${host_port}" - /opt/agyn/set-ingress-port.sh "${host_port}" + step "Restoring the browser-facing port" "" + /opt/agyn/set-ingress-port.sh "${host_port}" >&2 + done_ "${host_port}" elif [ -n "${host_port}" ]; then - log "WARNING: host port ${host_port} is in use but /opt/agyn/set-ingress-port.sh is missing;" - log " browser-facing URLs now point at the chart's default port" + note "WARNING: /opt/agyn/set-ingress-port.sh is missing, so browser-facing URLs now point at the chart's default port instead of ${host_port}" fi -log "releases:" -helm list -n "${NAMESPACE}" -log "done" +helm list -n "${NAMESPACE}" >&2 diff --git a/internal/local/upgrade.go b/internal/local/upgrade.go index 3d231eb..25b25d9 100644 --- a/internal/local/upgrade.go +++ b/internal/local/upgrade.go @@ -1,10 +1,15 @@ package local import ( + "bufio" _ "embed" "fmt" "io" "strings" + "sync" + "time" + + "github.com/agynio/agyn-cli/internal/terminal" ) // A chart cannot upgrade itself, so this one script stays outside it. It ships @@ -15,6 +20,10 @@ import ( //go:embed scripts/upgrade-platform.sh var upgradeScript string +// marker prefixes the lines the script writes for the CLI to render. Everything +// else it emits is tool output, and belongs in the log. +const marker = "AGYN|" + // UpgradePlatform moves the platform releases in the running VM to newer chart // versions, leaving the VM and its data alone. // @@ -23,10 +32,11 @@ var upgradeScript string // then start — but the wrong thing for "upgrade" to mean, because it is not // reversible and destroys work the user did not ask to lose. // -// Output is streamed rather than captured: a Helm upgrade that waits for -// rollouts takes minutes, and silence for minutes is indistinguishable from a -// hang. -func UpgradePlatform(stdout, stderr io.Writer, platformVersion string) error { +// The script reports its progress as steps and sends everything Helm and +// kubectl say to log: a Helm upgrade that waits on rollouts takes minutes, and +// what the user asked was which versions moved, not what the admission webhook +// thinks of the release's AuthorizationPolicies. +func UpgradePlatform(steps *terminal.Steps, log io.Writer, platformVersion string) error { instance, err := GetInstance() if err != nil { return err @@ -45,8 +55,161 @@ func UpgradePlatform(stdout, stderr io.Writer, platformVersion string) error { args = append(args, "--platform-version", platformVersion) } - if err := limactlStdin(strings.NewReader(upgradeScript), stdout, stderr, args...); err != nil { - return fmt.Errorf("upgrade the platform in the VM: %w", err) + reader, writer := io.Pipe() + render := &upgradeRenderer{steps: steps, log: log} + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + render.consume(reader) + }() + + runErr := limactlStdin(strings.NewReader(upgradeScript), writer, log, args...) + writer.Close() + wg.Wait() + + if runErr != nil { + return render.fail(fmt.Errorf("upgrade the platform in the VM: %w", runErr)) } + render.finish() return nil } + +// upgradeRenderer turns the script's markers into steps, and everything else +// into log lines. +type upgradeRenderer struct { + steps *terminal.Steps + log io.Writer + + mu sync.Mutex + step *terminal.Step + detail string + stopped chan struct{} +} + +func (r *upgradeRenderer) consume(reader io.Reader) { + scanner := bufio.NewScanner(reader) + scanner.Buffer(make([]byte, 0, 64<<10), 1<<20) + for scanner.Scan() { + line := scanner.Text() + if !strings.HasPrefix(line, marker) { + if strings.TrimSpace(line) != "" { + fmt.Fprintln(r.log, line) + } + continue + } + fields := strings.SplitN(strings.TrimPrefix(line, marker), "|", 3) + switch fields[0] { + case "step": + r.start(field(fields, 1), field(fields, 2)) + case "done": + r.done(field(fields, 1)) + case "skip": + r.skip(field(fields, 1)) + case "note": + r.steps.Note(field(fields, 1)) + } + } +} + +func field(fields []string, index int) string { + if index < len(fields) { + return fields[index] + } + return "" +} + +// start opens a step and begins reporting the rollouts it is waiting on. A Helm +// upgrade with --wait is silent for as long as it takes, and the cluster is the +// only place that knows how far along it is. +func (r *upgradeRenderer) start(title, detail string) { + r.close() + + r.mu.Lock() + defer r.mu.Unlock() + r.step = r.steps.Start(title) + r.detail = detail + if detail != "" { + r.step.Detail(detail) + } + stopped := make(chan struct{}) + r.stopped = stopped + go r.pollRollouts(r.step, detail, stopped) +} + +func (r *upgradeRenderer) pollRollouts(step *terminal.Step, base string, stopped chan struct{}) { + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + for { + select { + case <-stopped: + return + case <-ticker.C: + rolling := RollingWorkloads(2) + if len(rolling) == 0 { + continue + } + detail := "waiting on " + strings.Join(rolling, ", ") + if base != "" { + detail = base + " " + detail + } + step.Detail(detail) + } + } +} + +func (r *upgradeRenderer) done(detail string) { + r.stopPolling() + r.mu.Lock() + defer r.mu.Unlock() + if r.step == nil { + return + } + if detail == "" { + detail = r.detail + } + r.step.Done(detail) + r.step = nil +} + +func (r *upgradeRenderer) skip(detail string) { + r.stopPolling() + r.mu.Lock() + defer r.mu.Unlock() + if r.step == nil { + return + } + r.step.Skip(detail) + r.step = nil +} + +// close ends a step the script left open, which happens when the next step +// begins without one. The work did complete: the script emits a step per unit +// of work, and a failure ends the run rather than moving on. +func (r *upgradeRenderer) close() { r.done("") } + +// fail marks whatever was in progress as the thing that failed, so the error is +// attributed to a step rather than printed after a line that still reads as +// running. +func (r *upgradeRenderer) fail(err error) error { + r.stopPolling() + r.mu.Lock() + defer r.mu.Unlock() + if r.step != nil { + r.step.Fail(err) + r.step = nil + return err + } + return err +} + +func (r *upgradeRenderer) finish() { r.close() } + +func (r *upgradeRenderer) stopPolling() { + r.mu.Lock() + defer r.mu.Unlock() + if r.stopped != nil { + close(r.stopped) + r.stopped = nil + } +} diff --git a/internal/local/upgrade_test.go b/internal/local/upgrade_test.go new file mode 100644 index 0000000..ce6afcb --- /dev/null +++ b/internal/local/upgrade_test.go @@ -0,0 +1,76 @@ +package local + +import ( + "bytes" + "strings" + "testing" + + "github.com/agynio/agyn-cli/internal/terminal" +) + +// The whole point of the marker protocol: Helm's admission warnings, kubectl's +// klog lines and the release listing answer a different question than the one +// the user asked, so they go to the log and the steps go to the terminal. +func TestUpgradeRendererSeparatesStepsFromToolOutput(t *testing.T) { + var out, log bytes.Buffer + renderer := &upgradeRenderer{steps: terminal.NewPlainSteps(&out), log: &log} + + renderer.consume(strings.NewReader(strings.Join([]string{ + `AGYN|note|services running from source (devspace) will be reset to their chart images`, + `AGYN|step|agyn-platform|0.51.0 → 0.52.0`, + `I0810 11:12:21.609992 489181 warnings.go:110] "Warning: configured AuthorizationPolicy will deny all traffic"`, + `Release "agyn-platform" has been upgraded. Happy Helming!`, + `AGYN|done|0.51.0 → 0.52.0`, + `AGYN|step|agyn-apps|`, + `AGYN|skip|already at 0.19.0`, + }, "\n"))) + renderer.finish() + + rendered := out.String() + for _, want := range []string{"agyn-platform", "0.51.0 → 0.52.0", "agyn-apps", "already at 0.19.0"} { + if !strings.Contains(rendered, want) { + t.Errorf("expected %q on the terminal:\n%s", want, rendered) + } + } + for _, unwanted := range []string{"warnings.go", "Happy Helming", "AGYN|"} { + if strings.Contains(rendered, unwanted) { + t.Errorf("expected %q to stay out of the terminal:\n%s", unwanted, rendered) + } + } + for _, want := range []string{"warnings.go", "Happy Helming"} { + if !strings.Contains(log.String(), want) { + t.Errorf("expected %q in the log:\n%s", want, log.String()) + } + } +} + +// An upgrade whose release is already current must read as "nothing to do", +// not as a line that looks exactly like the one that replaced every workload. +func TestUpgradeRendererMarksAnAlreadyCurrentReleaseAsSkipped(t *testing.T) { + var out, log bytes.Buffer + renderer := &upgradeRenderer{steps: terminal.NewPlainSteps(&out), log: &log} + + renderer.consume(strings.NewReader("AGYN|step|agyn-platform|\nAGYN|skip|already at 0.52.0\n")) + renderer.finish() + + if !strings.Contains(out.String(), "already at 0.52.0") { + t.Fatalf("expected the skip reason, got:\n%s", out.String()) + } + if strings.Contains(out.String(), "→") { + t.Fatalf("expected no version transition for an untouched release:\n%s", out.String()) + } +} + +// A step the script leaves open — the last one before the process exits — still +// has to be closed, or the run ends on a line that reads as still running. +func TestUpgradeRendererClosesATrailingStep(t *testing.T) { + var out, log bytes.Buffer + renderer := &upgradeRenderer{steps: terminal.NewPlainSteps(&out), log: &log} + + renderer.consume(strings.NewReader("AGYN|step|Restoring the browser-facing port|\n")) + renderer.finish() + + if !strings.Contains(out.String(), "Restoring the browser-facing port") { + t.Fatalf("expected the trailing step to be closed:\n%s", out.String()) + } +} diff --git a/internal/terminal/steps.go b/internal/terminal/steps.go new file mode 100644 index 0000000..043b328 --- /dev/null +++ b/internal/terminal/steps.go @@ -0,0 +1,310 @@ +package terminal + +import ( + "fmt" + "io" + "os" + "strings" + "sync" + "time" + + "golang.org/x/term" +) + +// Steps renders a sequence of long operations as one line each. +// +// The operations behind `agyn local` take minutes and are driven by tools whose +// own output answers a different question than the user asked: a Helm release +// listing, eight identical admission warnings, a byte counter. Those go to a +// log. What reaches the terminal is what is happening now, and what it cost. +// +// On a terminal the line for the step in progress is animated and carries the +// detail it is waiting on, so a minute of work is visibly work rather than +// possibly a hang. Anywhere else — a pipe, a CI log — each step prints once, on +// completion, with the same content and no control characters. +type Steps struct { + out io.Writer + animate bool + + mu sync.Mutex + active *Step + stopped chan struct{} +} + +// Step is one operation in progress. Its methods are safe to call from another +// goroutine, which is what lets a poller update the detail while the work runs. +type Step struct { + steps *Steps + title string + detail string + started time.Time + frame int + done bool +} + +const ( + symbolDone = "✓" + symbolFail = "✗" + symbolSkip = "·" +) + +// spinnerFrames is the braille cycle: one cell, so the title never shifts. +var spinnerFrames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"} + +// NewSteps writes to out, animating only when out is a terminal. +func NewSteps(out io.Writer) *Steps { + return &Steps{out: out, animate: IsTerminalWriter(out)} +} + +// NewPlainSteps never animates. For --debug, where the tool output the steps +// exist to hide is streaming to the same terminal: a spinner redrawing over it +// would corrupt both. +func NewPlainSteps(out io.Writer) *Steps { + return &Steps{out: out} +} + +// IsTerminalWriter reports whether a writer is an interactive terminal. +// Anything that is not a file — a buffer in a test, a pipe in CI — is not. +func IsTerminalWriter(w io.Writer) bool { + file, ok := w.(*os.File) + return ok && term.IsTerminal(int(file.Fd())) +} + +// Start begins a step. Exactly one step is in progress at a time: a prompt or a +// sudo password arriving under a spinner is unreadable, so callers finish the +// step before asking anything. +func (s *Steps) Start(title string) *Step { + s.mu.Lock() + defer s.mu.Unlock() + + step := &Step{steps: s, title: title, started: time.Now()} + s.active = step + if !s.animate { + return step + } + + s.render(step, "") + stopped := make(chan struct{}) + s.stopped = stopped + go s.animateLoop(step, stopped) + return step +} + +// Report prints a finished step that had no visible duration, or whose work +// wrote to the terminal itself — the sudo prompt of a trust-store install is +// not something to animate over. +func (s *Steps) Report(title, detail string) { + s.instant(title, detail, symbolDone, "\x1b[32m") +} + +// Skipped prints a step that was not run, naming why — and, by convention, the +// command that would run it later. +func (s *Steps) Skipped(title, detail string) { + s.instant(title, detail, symbolSkip, "\x1b[2m") +} + +// Failed prints a step that failed before it started running, and returns the +// error so a caller can write `return steps.Failed(...)`. +func (s *Steps) Failed(title string, err error) error { + s.instant(title, err.Error(), symbolFail, "\x1b[31m") + return err +} + +func (s *Steps) instant(title, detail, symbol, color string) { + s.mu.Lock() + defer s.mu.Unlock() + s.finish(&Step{steps: s, title: title, detail: detail}, symbol, color) +} + +// Note prints a line that is not a step: something the user needs to know that +// no step is responsible for. +func (s *Steps) Note(text string) { + s.mu.Lock() + defer s.mu.Unlock() + fmt.Fprintf(s.out, " %s\n", text) +} + +// CallToAction closes a successful run with the one thing to do next. A +// finished install owes the reader a next step, and three links are a menu. +func (s *Steps) CallToAction(label, url string) { + s.mu.Lock() + defer s.mu.Unlock() + if s.animate { + fmt.Fprintf(s.out, "\n %s \x1b[1;4m%s\x1b[0m\n", label, url) + return + } + fmt.Fprintf(s.out, "\n %s %s\n", label, url) +} + +// Detail replaces the trailing context of a running step — the bytes so far, +// the workloads not yet ready. Ignored once the step has finished, so a poller +// racing the step's completion cannot resurrect its line. +func (st *Step) Detail(detail string) { + st.steps.mu.Lock() + defer st.steps.mu.Unlock() + if st.done { + return + } + st.detail = detail + if st.steps.animate { + st.steps.render(st, spinnerFrames[st.frame]) + } +} + +// Done marks the step complete. detail may be empty. +func (st *Step) Done(detail string) { + st.finish(detail, symbolDone, "\x1b[32m") +} + +// Skip marks a step that was not run, naming why — and, by convention, the +// command that would run it later. +func (st *Step) Skip(detail string) { + st.finish(detail, symbolSkip, "\x1b[2m") +} + +// Fail marks the step failed and returns the error, so a caller can write +// `return step.Fail(err)` and be sure the line was closed. +func (st *Step) Fail(err error) error { + st.finish(err.Error(), symbolFail, "\x1b[31m") + return err +} + +func (st *Step) finish(detail, symbol, color string) { + st.steps.mu.Lock() + defer st.steps.mu.Unlock() + if st.done { + return + } + if detail != "" { + st.detail = detail + } + st.steps.finish(st, symbol, color) +} + +// finish closes a step's line. Callers hold the lock. +func (s *Steps) finish(step *Step, symbol, color string) { + step.done = true + // Only the running step owns the animation. An instantly-reported step is + // not it, and stopping the animation on its behalf would leave the running + // step's line frozen mid-spin and never closed. + if s.active == step { + if s.stopped != nil { + close(s.stopped) + s.stopped = nil + } + s.active = nil + } + + line := " " + symbol + " " + step.title + if s.animate { + line = " " + color + symbol + "\x1b[0m " + step.title + } + if suffix := step.suffix(s.animate); suffix != "" { + line += suffix + } + if s.animate { + fmt.Fprint(s.out, "\r\x1b[2K") + } + fmt.Fprintln(s.out, line) +} + +// animateLoop redraws the running step until it finishes. +func (s *Steps) animateLoop(step *Step, stopped chan struct{}) { + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-stopped: + return + case <-ticker.C: + s.mu.Lock() + if step.done { + s.mu.Unlock() + return + } + step.frame = (step.frame + 1) % len(spinnerFrames) + s.render(step, spinnerFrames[step.frame]) + s.mu.Unlock() + } + } +} + +// render draws the in-progress line. Callers hold the lock. +func (s *Steps) render(step *Step, frame string) { + if frame == "" { + frame = spinnerFrames[0] + } + line := " \x1b[36m" + frame + "\x1b[0m " + step.title + step.suffix(true) + // Truncated rather than wrapped: a wrapped line leaves the carriage return + // on the wrong row and the next redraw paints over the wrong text. + fmt.Fprint(s.out, "\r\x1b[2K"+truncate(line, terminalWidth(s.out)-1)) +} + +// suffix is the dim trailing context: the detail, then how long the step took. +func (st *Step) suffix(color bool) string { + parts := make([]string, 0, 2) + if st.detail != "" { + parts = append(parts, st.detail) + } + if elapsed := formatElapsed(time.Since(st.started)); st.done && elapsed != "" { + parts = append(parts, elapsed) + } + if len(parts) == 0 { + return "" + } + text := " " + strings.Join(parts, " ") + if color { + return "\x1b[2m" + text + "\x1b[0m" + } + return text +} + +// formatElapsed reports a duration worth reporting. Under a second is not: it +// says nothing, and printing "0s" beside every fast step is noise. +func formatElapsed(d time.Duration) string { + switch { + case d < time.Second: + return "" + case d < time.Minute: + return fmt.Sprintf("%ds", int(d.Seconds())) + default: + return fmt.Sprintf("%dm%02ds", int(d.Minutes()), int(d.Seconds())%60) + } +} + +// truncate cuts a line to a printable width, counting runes rather than bytes +// and ignoring the escape sequences, which occupy no columns. +func truncate(line string, width int) string { + if width <= 0 { + return line + } + visible, escape := 0, false + for index, r := range line { + switch { + case escape: + if r == 'm' { + escape = false + } + case r == '\x1b': + escape = true + default: + visible++ + if visible > width { + return line[:index] + "…\x1b[0m" + } + } + } + return line +} + +func terminalWidth(out io.Writer) int { + file, ok := out.(*os.File) + if !ok { + return defaultCols + } + width, _, err := term.GetSize(int(file.Fd())) + if err != nil || width <= 0 { + return defaultCols + } + return width +} diff --git a/internal/terminal/steps_test.go b/internal/terminal/steps_test.go new file mode 100644 index 0000000..06bd252 --- /dev/null +++ b/internal/terminal/steps_test.go @@ -0,0 +1,102 @@ +package terminal + +import ( + "bytes" + "strings" + "testing" +) + +// Piping either command to a file has to yield a readable list of steps: a +// CI log full of carriage returns and cursor escapes is worse than no +// progress reporting at all. +func TestStepsPrintOnceWithoutControlCharactersWhenNotATerminal(t *testing.T) { + var buf bytes.Buffer + steps := NewSteps(&buf) + + step := steps.Start("Downloading image 0.3.0") + step.Detail("1.2 GB of 4.6 GB") + step.Detail("2.4 GB of 4.6 GB") + step.Done("arm64") + steps.Start("Trusting the CA").Skip("skipped; install later with: agyn local ca install") + + got := buf.String() + if strings.ContainsAny(got, "\r\x1b") { + t.Fatalf("expected no control characters in:\n%q", got) + } + lines := strings.Split(strings.TrimRight(got, "\n"), "\n") + if len(lines) != 2 { + t.Fatalf("expected one line per step, got %d:\n%s", len(lines), got) + } + if !strings.Contains(lines[0], symbolDone) || !strings.Contains(lines[0], "arm64") { + t.Fatalf("expected the finished step to carry its detail: %q", lines[0]) + } + // The intermediate details are progress, not history: only the last stands. + if strings.Contains(got, "1.2 GB") { + t.Fatalf("expected superseded progress not to be printed:\n%s", got) + } + if !strings.Contains(lines[1], symbolSkip) { + t.Fatalf("expected a skipped step to be marked as such: %q", lines[1]) + } +} + +// A failed step is the last thing a command does, and the error belongs on its +// line rather than after one that still reads as running. +func TestFailMarksTheStepAndReturnsTheError(t *testing.T) { + var buf bytes.Buffer + steps := NewSteps(&buf) + + step := steps.Start("Waiting for the platform") + err := step.Fail(errTest) + if err != errTest { + t.Fatalf("expected Fail to return the error it was given, got %v", err) + } + if !strings.Contains(buf.String(), symbolFail) || !strings.Contains(buf.String(), errTest.Error()) { + t.Fatalf("expected the failure on the step's line:\n%s", buf.String()) + } +} + +// Detail arriving from a poller after the step closed must not reopen it. +func TestDetailAfterDoneIsIgnored(t *testing.T) { + var buf bytes.Buffer + steps := NewSteps(&buf) + + step := steps.Start("Upgrading") + step.Done("0.51.0 → 0.52.0") + step.Detail("waiting on gateway") + + if strings.Contains(buf.String(), "waiting on gateway") { + t.Fatalf("expected a late detail to be dropped:\n%s", buf.String()) + } +} + +// A finished start ends in exactly one link, and it is the last thing printed. +func TestCallToActionIsOneLine(t *testing.T) { + var buf bytes.Buffer + steps := NewSteps(&buf) + steps.CallToAction("Open the console", "https://console.agyn.dev:2496") + + lines := strings.Split(strings.Trim(buf.String(), "\n"), "\n") + if len(lines) != 1 || strings.Count(lines[0], "https://") != 1 { + t.Fatalf("expected a single link, got:\n%s", buf.String()) + } +} + +func TestTruncateCountsPrintableColumnsOnly(t *testing.T) { + line := "\x1b[36m⠋\x1b[0m Downloading" + if got := truncate(line, 40); got != line { + t.Fatalf("expected a short line to survive, got %q", got) + } + got := truncate(line, 4) + if strings.Contains(got, "Downloading") { + t.Fatalf("expected truncation past the width, got %q", got) + } + if !strings.HasSuffix(got, "\x1b[0m") { + t.Fatalf("expected truncation to reset the styling, got %q", got) + } +} + +var errTest = testError("no route to host") + +type testError string + +func (e testError) Error() string { return string(e) } From 810610d245f3c83e180ee2a40c950ea4429a3ad5 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 11 Aug 2026 01:56:35 +0200 Subject: [PATCH 02/19] Ask about the port only when it is taken, and the CA as three answers The port prompt fired on every first run, including a second VM's -- whose port had just been chosen for being free. A question with one sensible answer in front of every install is not a wizard step, it is a keypress. It now appears only when the port this VM would take is not available, which is the case it was written for. "Ingress port" named the component that terminates the connection. Nobody outside the cluster asked about an ingress; what they are choosing is where the platform answers, so the prompt says so and shows the URL it is completing. The CA question was a yes/no whose no is a dead end: someone who will not hand sudo to a CLI declined and was left with a browser warning and no certificate, though `agyn local ca export` existed the whole time. Three answers now, on the arrow-key picker the group already uses -- install, export, skip -- and export writes the PEM into the working directory and says where. The picker returns a position and the caller switches on a constant, so the rows are built by indexing with those constants and a test holds the two together. A row inserted in the wrong place would install a CA on the machine of someone who chose to skip, and nothing in the output would say so. --- internal/cmd/local.go | 93 +++++++++++++++++++++++++--- internal/cmd/local_ca_choice_test.go | 42 +++++++++++++ 2 files changed, 127 insertions(+), 8 deletions(-) create mode 100644 internal/cmd/local_ca_choice_test.go diff --git a/internal/cmd/local.go b/internal/cmd/local.go index 5927f83..a759376 100644 --- a/internal/cmd/local.go +++ b/internal/cmd/local.go @@ -179,9 +179,10 @@ func runLocalStart(cmd *cobra.Command, flags localStartFlags) error { return finishLocalStart(cmd, steps, flags, settings.Port) } - if interactive && firstRun && flags.port == 0 { - settings.Port = promptPort(cmd, settings.Port) - } + // Asked only when the port this VM would take is not free. A first run was + // asked unconditionally, which put a question with one sensible answer in + // front of every install -- and in front of a second VM, whose port was + // already chosen for being free. if err := checkPortAvailable(settings.Port); err != nil { if !interactive { return err @@ -303,16 +304,27 @@ func handleCAAfterStart(cmd *cobra.Command, steps *terminal.Steps, flags localSt } step.Done("") - install := flags.installCA - if !install && interactive { + choice := caInstall + if !flags.installCA && interactive { // Asked outside a step: sudo prompts for a password on this terminal, // and a spinner redrawing over the prompt makes it unreadable. - install = promptYesNo(cmd, "Install the Agyn local CA into your system trust store? (asks for sudo)", true) + choice = promptCAChoice(cmd) } - if !install { + + switch choice { + case caExport: + path, err := exportCA() + if err != nil { + return steps.Failed("Exporting the CA", err) + } + steps.Report("Exporting the CA", path) + steps.Note("trust it yourself, or later with: agyn local ca install") + return nil + case caSkip: steps.Skipped("Trusting the CA", "browsers will warn; install later with: agyn local ca install") return nil } + if err := local.InstallCA(); err != nil { return steps.Failed("Trusting the CA", fmt.Errorf("%w — retry with `agyn local ca install`, or start with --no-ca", err)) @@ -321,6 +333,67 @@ func handleCAAfterStart(cmd *cobra.Command, steps *terminal.Steps, flags localSt return nil } +// What to do with the CA the VM signs its certificates with. +type caChoice int + +const ( + caInstall caChoice = iota + caExport + caSkip +) + +// caChoiceItems is the picker's rows, in the order the constants above index +// them — the picker returns a position, so the two are one definition split in +// half, and a row inserted without its constant would install a CA on a machine +// whose owner chose to skip. +func caChoiceItems() []terminal.PickItem { + items := make([]terminal.PickItem, 3) + items[caInstall] = terminal.PickItem{ + Label: "Install it in the system trust store", Detail: "asks for sudo; browsers stop warning", Current: true} + items[caExport] = terminal.PickItem{ + Label: "Export it to a file", Detail: "trust it yourself, wherever you need it"} + items[caSkip] = terminal.PickItem{ + Label: "Skip", Detail: "browsers will warn on every platform URL"} + return items +} + +// promptCAChoice offers the three answers there are, rather than a yes/no whose +// no is a dead end. Someone who will not hand sudo to a CLI still needs the +// certificate — declining used to leave them with a browser warning and no +// file, which is the case the export exists for. +func promptCAChoice(cmd *cobra.Command) caChoice { + choice, err := terminal.Pick(os.Stdin, cmd.OutOrStdout(), + "The VM signs its certificates with its own CA. What should happen to it?", caChoiceItems()) + if err != nil { + // Cancelled, or no terminal after all: the safe reading of "no answer" + // is the one that changes nothing on this machine. + return caSkip + } + return caChoice(choice) +} + +// exportCA writes the certificate beside the user, in the directory they ran +// the command from, and returns where it went. +func exportCA() (string, error) { + source, err := local.EnsureCA() + if err != nil { + return "", err + } + data, err := os.ReadFile(source) + if err != nil { + return "", fmt.Errorf("read CA: %w", err) + } + name := fmt.Sprintf("agyn-%s-ca.pem", local.InstanceName()) + if err := os.WriteFile(name, data, 0o644); err != nil { + return "", fmt.Errorf("write %s: %w", name, err) + } + path, err := filepath.Abs(name) + if err != nil { + return name, nil + } + return path, nil +} + // runPreflight is the dependency and environment check `agyn local doctor` // reports, run before every start. A host tool that is missing or too old is // the most common reason a first run fails, and left to limactl the failure @@ -1008,9 +1081,13 @@ func promptYesNo(cmd *cobra.Command, question string, defaultYes bool) bool { } } +// promptPort asks for the one host port the VM publishes. Named for what it +// serves rather than for the component that terminates it: "ingress port" is +// the answer to a question nobody outside the cluster asked. func promptPort(cmd *cobra.Command, suggested int) int { + fmt.Fprintf(cmd.OutOrStdout(), "The platform is served at https://console.%s:PORT\n", local.BaseDomain) for { - fmt.Fprintf(cmd.OutOrStdout(), "Ingress port [%d]: ", suggested) + fmt.Fprintf(cmd.OutOrStdout(), "Port to serve it on [%d]: ", suggested) reader := bufio.NewReader(cmd.InOrStdin()) line, err := reader.ReadString('\n') if err != nil { diff --git a/internal/cmd/local_ca_choice_test.go b/internal/cmd/local_ca_choice_test.go new file mode 100644 index 0000000..dfa4b7c --- /dev/null +++ b/internal/cmd/local_ca_choice_test.go @@ -0,0 +1,42 @@ +package cmd + +import ( + "strings" + "testing" +) + +// The picker returns a position and the caller switches on a constant, so the +// two have to agree. They disagree silently and in the worst direction: a row +// added in the wrong place installs a CA on the machine of someone who chose to +// skip, and nothing in the output would say so. +func TestCAChoiceItemsMatchTheirConstants(t *testing.T) { + items := caChoiceItems() + if len(items) != 3 { + t.Fatalf("expected three answers, got %d", len(items)) + } + for _, tc := range []struct { + choice caChoice + want string + }{ + {caInstall, "Install"}, + {caExport, "Export"}, + {caSkip, "Skip"}, + } { + if !strings.HasPrefix(items[tc.choice].Label, tc.want) { + t.Errorf("choice %d is %q, want it to start with %q", tc.choice, items[tc.choice].Label, tc.want) + } + } +} + +// The default answer is the one that leaves the platform usable in a browser. +func TestCAChoiceOpensOnInstall(t *testing.T) { + items := caChoiceItems() + for index, item := range items { + if item.Current && caChoice(index) != caInstall { + t.Fatalf("expected the picker to open on install, opens on %q", item.Label) + } + } + if !items[caInstall].Current { + t.Fatal("expected install to be marked as the current answer") + } +} From 81cd2ef5b14c6d253cfe97edfff8e1387ec1a50c Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 11 Aug 2026 02:50:07 +0200 Subject: [PATCH 03/19] Carry the scripts that act on a VM, instead of the image carrying them set-bootstrap-token.sh and set-ingress-port.sh move here from the image and are piped into the guest, as upgrade-platform.sh already was. The image's copies are removed in bundle-vm. The reason is the one written beside upgrade-platform.sh: a script in the image can only be corrected by building a new image and recreating the VM, which is what `upgrade` exists to avoid. This week's openziti fix could not reach one existing VM, and upgrade-platform.sh had already been copied here and already diverged from an image copy nothing invoked any more. The token stops being an argument. It was $1 to a process in the guest, so a per-install credential sat in a process list any user of that guest could read. It now goes to a script staged 0700 on the guest's tmpfs, on stdin, and the script fails loudly on an empty read rather than logging "no token supplied" and exiting 0 -- that path would have recorded a profile holding a credential the Gateway never received, surfacing later as a 401 with nothing pointing back. The ingress-port step moves out of the upgrade script into the command, which is the side that knows which port this host forwards. The script says whether anything moved and the CLI does the repair, so no script has to know about another. Two upgrade behaviours found by running it. A release left in flight by an interrupted upgrade is invisible to `helm list` and refuses every later attempt with the lock rather than the way out, so its status is read directly and reported with `--resume`, which drops the in-flight revision and continues forward -- not backward, which would move already-upgraded workloads further than the one version of backward compatibility migrations promise. And under `set -e` with `pipefail`, every `$(helm ... | sed ...)` reader was a place the whole run could die: `helm status` fails routinely for a release that is not installed, and it took the script down mid-recovery. The script is now covered by tests that run it against stub tools, which is what found the second of those. --- internal/cmd/local.go | 42 +- internal/local/credentials.go | 31 +- internal/local/lima.go | 44 ++ internal/local/scripts/set-bootstrap-token.sh | 63 +++ internal/local/scripts/set-ingress-port.sh | 409 ++++++++++++++++++ internal/local/scripts/upgrade-platform.sh | 127 ++++-- internal/local/upgrade.go | 47 +- internal/local/upgrade_script_test.go | 136 ++++++ internal/local/upgrade_test.go | 35 ++ 9 files changed, 873 insertions(+), 61 deletions(-) create mode 100755 internal/local/scripts/set-bootstrap-token.sh create mode 100755 internal/local/scripts/set-ingress-port.sh create mode 100644 internal/local/upgrade_script_test.go diff --git a/internal/cmd/local.go b/internal/cmd/local.go index a759376..5e2e4ea 100644 --- a/internal/cmd/local.go +++ b/internal/cmd/local.go @@ -715,7 +715,9 @@ func newLocalDeleteCmd() *cobra.Command { } func newLocalUpgradeCmd() *cobra.Command { - return &cobra.Command{ + var resume bool + + cmd := &cobra.Command{ Use: "upgrade", Short: "Upgrade the platform in the running VM to the latest charts", Long: "Upgrades the agyn-platform Helm release inside the VM to\n" + @@ -730,6 +732,12 @@ func newLocalUpgradeCmd() *cobra.Command { // No token to put back afterwards: the Gateway reads it from a // Secret the chart reuses rather than from the Deployment spec it // re-renders, so an upgrade leaves this install's token alone. + cfg, err := config.Load() + if err != nil { + return err + } + settings := resolveInstancePorts(cfg, local.InstanceName(), cfg.InstanceSettings(local.InstanceName())) + runLog, err := openRunLog(cmd) if err != nil { return err @@ -737,13 +745,41 @@ func newLocalUpgradeCmd() *cobra.Command { defer runLog.close() steps := newSteps(cmd) - if err := local.UpgradePlatform(steps, runLog.stdout, ""); err != nil { + changed, err := local.UpgradePlatform(steps, runLog.stdout, "", resume) + if err != nil { runLog.reportFailure(cmd) return err } - return nil + if !changed { + return nil + } + + return restoreIngressPort(cmd, steps, settings.Port, runLog) }, } + + cmd.Flags().BoolVar(&resume, "resume", false, + "Continue an upgrade that was interrupted, rather than being refused by the release it left in flight") + + return cmd +} + +// restoreIngressPort points the browser-facing URLs back at the port this host +// forwards. +// +// Helm rewrites every Deployment the charts own, and those URLs are not in the +// charts: they were set with `kubectl set env` when the host chose a port. Left +// reverted, the Gateway fetches OIDC discovery from a port the ingress no +// longer publishes and every sign-in breaks. +func restoreIngressPort(cmd *cobra.Command, steps *terminal.Steps, port int, runLog *limaIO) error { + step := steps.Start("Restoring the browser-facing port") + if _, err := local.SetIngressPort(port); err != nil { + step.Fail(err) + runLog.reportFailure(cmd) + return err + } + step.Done(strconv.Itoa(port)) + return nil } func newLocalLoadImageCmd() *cobra.Command { diff --git a/internal/local/credentials.go b/internal/local/credentials.go index 068ef89..8a596db 100644 --- a/internal/local/credentials.go +++ b/internal/local/credentials.go @@ -2,12 +2,24 @@ package local import ( "crypto/rand" + _ "embed" "encoding/base64" "fmt" "strconv" "strings" ) +// The scripts that act on a running VM ship with the CLI rather than in the +// image. Both carry a value the image cannot know -- a token generated per +// install, and whatever port the host had free -- and both have to be fixable +// without rebuilding an image and recreating every VM booted from one. +// +//go:embed scripts/set-bootstrap-token.sh +var bootstrapTokenScript string + +//go:embed scripts/set-ingress-port.sh +var ingressPortScript string + const ( // BootstrapTokenPrefix marks a token this CLI minted for a local VM, so a // credential stored under the same profile by something else — a remote @@ -18,16 +30,6 @@ const ( // what the rest of the platform uses for service tokens. bootstrapTokenBytes = 32 - // bootstrapTokenScript ships in the image. It installs a host-supplied - // token into the Gateway's environment and restarts the deployment, and is - // idempotent: handing it the token already in place changes nothing. - bootstrapTokenScript = "/opt/agyn/set-bootstrap-token.sh" - - // ingressPortScript ships in the image. It points the browser-facing URLs - // (the OIDC redirects, the media proxy origin, its CORS allowlist) at the - // port this host forwards, and like the token script is idempotent. - ingressPortScript = "/opt/agyn/set-ingress-port.sh" - // platformNamespace holds the platform workloads inside the VM. platformNamespace = "agyn-platform" @@ -62,12 +64,13 @@ func IsBootstrapToken(token string) bool { // SetBootstrapToken installs the token this host holds into the running VM and // returns the script's log output. The value travels over the limactl channel, // never the network, and is never read back: the host keeps the copy it -// generated. +// generated. It is handed over on stdin rather than as an argument, so it is in +// neither machine's process list. func SetBootstrapToken(token string) (string, error) { if strings.TrimSpace(token) == "" { return "", fmt.Errorf("bootstrap token must not be empty") } - out, err := Shell("sudo", bootstrapTokenScript, token) + out, err := RunScriptWithSecret(bootstrapTokenScript, strings.NewReader(token)) if err != nil { return "", fmt.Errorf("install the bootstrap token in the VM: %w", err) } @@ -85,9 +88,9 @@ func SetIngressPort(port int) (string, error) { if port <= 0 || port > 65535 { return "", fmt.Errorf("ingress port %d is out of range", port) } - out, err := Shell("sudo", ingressPortScript, strconv.Itoa(port)) + out, err := RunScript(ingressPortScript, strconv.Itoa(port)) if err != nil { - return "", fmt.Errorf("set the ingress port in the VM: %w", err) + return "", fmt.Errorf("point the platform's URLs at port %d: %w", port, err) } return strings.TrimSpace(out), nil } diff --git a/internal/local/lima.go b/internal/local/lima.go index 8792159..dcf6728 100644 --- a/internal/local/lima.go +++ b/internal/local/lima.go @@ -203,6 +203,50 @@ func Delete(stdout, stderr io.Writer) error { return limactl(stdout, stderr, "delete", "--force", InstanceName()) } +// RunScript pipes a script the CLI carries into the guest and runs it there, +// returning its combined output. +// +// Nothing is installed in the VM and no copy is left behind to drift from this +// caller. That is the whole reason these scripts live with the CLI: one that +// lives in the image can only be corrected by building a new image and +// recreating the VM, which is the operation `upgrade` exists to avoid. +func RunScript(script string, args ...string) (string, error) { + var out bytes.Buffer + shellArgs := append([]string{"shell", InstanceName(), "--", "sudo", "bash", "-s", "--"}, args...) + if err := limactlStdin(strings.NewReader(script), &out, &out, shellArgs...); err != nil { + return out.String(), fmt.Errorf("%w: %s", err, strings.TrimSpace(out.String())) + } + return out.String(), nil +} + +// RunScriptWithSecret runs a script whose input is a credential. +// +// The script is staged into the guest first, because stdin is the one channel +// that carries a secret without putting it in an argument list -- and the +// script itself would otherwise be occupying it. An argument list is readable +// by any user of the guest, and by anyone running ps on the host while the CLI +// works. The staged copy is mode 0700 under /run, which is tmpfs, and is +// removed whether or not the run succeeds. +func RunScriptWithSecret(script string, secret io.Reader, args ...string) (string, error) { + path := "/run/agyn-" + InstanceName() + ".sh" + + var staged bytes.Buffer + stage := []string{"shell", InstanceName(), "--", "sudo", "sh", "-c", "umask 077 && cat > " + path} + if err := limactlStdin(strings.NewReader(script), &staged, &staged, stage...); err != nil { + return "", fmt.Errorf("stage the script in the VM: %w: %s", err, strings.TrimSpace(staged.String())) + } + defer func() { + _ = limactl(io.Discard, io.Discard, "shell", InstanceName(), "--", "sudo", "rm", "-f", path) + }() + + var out bytes.Buffer + runArgs := append([]string{"shell", InstanceName(), "--", "sudo", "bash", path}, args...) + if err := limactlStdin(secret, &out, &out, runArgs...); err != nil { + return out.String(), fmt.Errorf("%w: %s", err, strings.TrimSpace(out.String())) + } + return out.String(), nil +} + // Shell runs a command inside the guest and returns its stdout. func Shell(args ...string) (string, error) { env, err := limaEnv() diff --git a/internal/local/scripts/set-bootstrap-token.sh b/internal/local/scripts/set-bootstrap-token.sh new file mode 100755 index 0000000..83e4e72 --- /dev/null +++ b/internal/local/scripts/set-bootstrap-token.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Installs the Gateway bootstrap token this machine was given. +# +# The platform is installed while the image is built, so whatever token the +# build used would otherwise ship inside every copy of that image: identical on +# every machine running a given published version, present on the CDN, and not +# rotatable without a rebuild. The host generates a token per install and hands +# it here, so the published image carries nothing usable against a running VM. +# +# The token arrives on stdin, never as an argument. An argument is in the +# process list of both machines: readable by any user of the guest, and by +# anyone who can run ps on the host while the CLI is working. +# +# Idempotent: re-running with the same token changes nothing. + +export KUBECONFIG=/etc/rancher/k3s/k3s.yaml + +TOKEN="$(cat)" +NAMESPACE="${AGYN_PLATFORM_NAMESPACE:-agyn-platform}" +SECRET="${AGYN_BOOTSTRAP_TOKEN_SECRET:-gateway-bootstrap-token}" +KEY="${AGYN_BOOTSTRAP_TOKEN_KEY:-token}" + +log() { printf '[set-bootstrap-token] %s\n' "$*"; } + +# Loud rather than quiet. The token now always arrives from the CLI on stdin, so +# an empty read is a broken channel, not a caller declining to set one -- and +# succeeding here would record a profile whose credential the Gateway never got, +# turning into a 401 on the next command with nothing pointing back to here. +if [ -z "${TOKEN}" ]; then + log "no token arrived on stdin" + exit 65 +fi + +until kubectl get --raw=/readyz >/dev/null 2>&1; do + log "waiting for the API server" + sleep 5 +done + +# The chart generates the Secret on install and reuses whatever it finds on +# upgrade, so writing here is what makes the host's token survive an upgrade +# without a step that puts it back afterwards. +until kubectl get secret "${SECRET}" -n "${NAMESPACE}" >/dev/null 2>&1; do + log "waiting for secret ${SECRET}" + sleep 5 +done + +current="$(kubectl get secret "${SECRET}" -n "${NAMESPACE}" \ + -o jsonpath="{.data.${KEY}}" 2>/dev/null | base64 -d 2>/dev/null || true)" +if [ "${current}" = "${TOKEN}" ]; then + log "token already current" + exit 0 +fi + +kubectl patch secret "${SECRET}" -n "${NAMESPACE}" \ + --type merge -p "{\"stringData\":{\"${KEY}\":\"${TOKEN}\"}}" >/dev/null + +# The Gateway reads CLUSTER_ADMIN_TOKEN once, at container start, so a changed +# Secret only takes effect on a restart. +kubectl rollout restart deployment/gateway -n "${NAMESPACE}" >/dev/null +kubectl rollout status deployment/gateway -n "${NAMESPACE}" --timeout=300s +log "done" diff --git a/internal/local/scripts/set-ingress-port.sh b/internal/local/scripts/set-ingress-port.sh new file mode 100755 index 0000000..aa00583 --- /dev/null +++ b/internal/local/scripts/set-ingress-port.sh @@ -0,0 +1,409 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Points the browser-facing URLs at the port this host actually forwards. +# +# The image bakes a default (2496), but the host port is the user's choice — +# 2496 may already be taken, and nothing stops them picking 2498. Most of the VM +# does not care: in-cluster traffic reaches services through cluster DNS. What +# cares is anything the host dials, starting with every URL a browser is handed +# back: +# +# chat-app OIDC_REDIRECT_URI, OIDC_POST_LOGOUT_REDIRECT_URI, MEDIA_PROXY_URL +# media-proxy CORS_ALLOWED_ORIGIN +# terminal-proxy TERMINAL_PROXY_WEBSOCKET_URL +# +# The OIDC issuer is the awkward one, because it is a single URL used from two +# sides. The browser is redirected to it, and the Gateway and Media Proxy fetch +# discovery, JWKS and userinfo from it from inside the cluster — and zitadel/oidc +# rejects a discovery document whose issuer differs from the URL it came from, +# so both sides have to name the same host AND the same port. Moving the port +# therefore also moves: +# +# istio-ingressgateway the Service port in-cluster clients dial +# keycloak KC_HOSTNAME, the issuer it advertises +# gateway, media-proxy OIDC_ISSUER_URL +# the four apps OIDC_AUTHORITY +# keycloak's realm each client's redirectUris and webOrigins +# +# The realm ones cannot be re-imported: --import-realm is create-once, so they +# are updated through the Admin API instead. +# +# The OpenZiti overlay moves too, for the same reason: a tunneler on the host +# dials the address an enrolment JWT names, so an overlay advertising a port the +# host does not forward cannot be reached from the only place devices enrol. +# See move_ziti_port for what that drags along. +# +# A wrong port here fails visibly: the OIDC provider redirects to a dead port +# after login, the browser blocks media on a CORS origin mismatch, and +# `agyn sandbox connect` is handed a ticket for a WebSocket nobody is serving. +# +# Idempotent: re-running with the port already in place changes nothing. The +# guards check every moving part rather than one, because a run that failed part +# way is exactly the state a single check reports as done. + +export KUBECONFIG=/etc/rancher/k3s/k3s.yaml + +PORT="${1:-${AGYN_INGRESS_HOST_PORT:-}}" +NAMESPACE="${AGYN_PLATFORM_NAMESPACE:-agyn-platform}" +BASE_DOMAIN="${AGYN_BASE_DOMAIN:-agyn.dev}" +REALM="${AGYN_KEYCLOAK_REALM:-agyn}" + +log() { printf '[set-ingress-port] %s\n' "$*"; } + +if [ -z "${PORT}" ]; then + log "no port supplied; leaving the image default in place" + exit 0 +fi +case "${PORT}" in +*[!0-9]* | '') + log "not a port number: ${PORT}" + exit 1 + ;; +esac + +until kubectl get --raw=/readyz >/dev/null 2>&1; do + log "waiting for the API server" + sleep 5 +done + +chat_origin="https://chat.${BASE_DOMAIN}:${PORT}" +media_origin="https://media.${BASE_DOMAIN}:${PORT}" +terminal_url="wss://terminal.${BASE_DOMAIN}:${PORT}/terminal" +auth_origin="https://auth.${BASE_DOMAIN}:${PORT}" +issuer="${auth_origin}/realms/${REALM}" + +deployment_env() { + kubectl get deployment "${1}" -n "${NAMESPACE}" \ + -o jsonpath="{.spec.template.spec.containers[0].env[?(@.name=='${2}')].value}" 2>/dev/null || true +} + +# The OpenZiti client API Service port doubles as the advertised port, so it is +# what says whether the overlay has been moved yet. +ziti_port() { + kubectl -n ziti get svc ziti-controller-client \ + -o jsonpath='{.spec.ports[0].port}' 2>/dev/null || true +} + +# The bake adds the openziti repo, but a Helm repository list is builder state +# rather than cluster state and does not survive into the shipped image: every +# booted VM starts with none. The upgrades below name a chart by repo alias, so +# without this they fail with "repo openziti not found" -- which is every VM on +# a port other than the baked default, since only those reach them. +ziti_repo() { + helm repo list 2>/dev/null | grep -q '^openziti[[:space:]]' && return 0 + helm repo add openziti https://openziti.io/helm-charts >/dev/null + helm repo update openziti >/dev/null +} + +# The chart version a release is already on. Pinned explicitly because a repo +# added just now resolves to whatever is newest, and moving a port is not a +# request to upgrade the overlay underneath it. +chart_version() { + helm list -n ziti --filter "^${1}\$" -o json 2>/dev/null | + sed -n "s/.*\"chart\":\"${1}-\([^\"]*\)\".*/\1/p" | head -1 +} + +# Where the passthrough route sends it, which moves separately from the Service +# and so can be left behind by a run that failed part way. +ziti_route_port() { + kubectl -n istio-gateway get virtualservice ziti-controller \ + -o jsonpath='{.spec.tls[0].route[0].destination.port.number}' 2>/dev/null || true +} + +# Where the router caches the controller endpoints it last reached. Empty when +# the PVC has not been bound or the router has never connected. +router_endpoints_file() { + local claim pv path + claim="$(kubectl -n ziti get deploy ziti-router \ + -o jsonpath='{.spec.template.spec.volumes[?(@.name=="config-data")].persistentVolumeClaim.claimName}' 2>/dev/null || true)" + [ -z "${claim}" ] && return 0 + pv="$(kubectl -n ziti get pvc "${claim}" -o jsonpath='{.spec.volumeName}' 2>/dev/null || true)" + [ -z "${pv}" ] && return 0 + path="$(kubectl get pv "${pv}" -o jsonpath='{.spec.local.path}' 2>/dev/null || true)" + [ -n "${path}" ] && [ -f "${path}/endpoints.yml" ] && printf '%s' "${path}/endpoints.yml" +} + +# Four things move independently, so "the overlay is on this port" is only true +# when all four say so. Checking one is how a half-moved VM reports itself done. +ziti_settled() { + local cache + [ "$(ziti_port)" = "${PORT}" ] || return 1 + [ "$(ziti_route_port)" = "${PORT}" ] || return 1 + [ "$(deployment_env ziti-management ZITI_CONTROLLER_URL)" = \ + "https://ziti-mgmt.${BASE_DOMAIN}:${PORT}/edge/management/v1" ] || return 1 + # Settled when the cache names no port other than this one. + cache="$(router_endpoints_file)" + [ -z "${cache}" ] && return 0 + ! grep -oE "tls:ziti\.${BASE_DOMAIN}:[0-9]+" "${cache}" 2>/dev/null | + grep -qv ":${PORT}\$" +} + +# All three are checked: any one alone would call it done on a VM that moved +# only part way -- apps but not the issuer leaves login broken, and everything +# but the overlay leaves a device unable to enrol. +if [ "$(deployment_env chat-app OIDC_POST_LOGOUT_REDIRECT_URI)" = "${chat_origin}" ] && + [ "$(deployment_env gateway OIDC_ISSUER_URL)" = "${issuer}" ] && + ziti_settled; then + log "already serving on port ${PORT}" + exit 0 +fi + +# The Service port in-cluster clients dial for the issuer. 443, 80 and 15021 are +# already published by this Service, so a separate entry would be a duplicate. +patch_ingress_hostport() { + case "${PORT}" in + 443 | 80 | 15021) + log "host port ${PORT} is already published by the ingress Service" + return 0 + ;; + esac + + local line index + line="$(kubectl -n istio-gateway get svc istio-ingressgateway \ + -o jsonpath='{range .spec.ports[*]}{.name}{"\n"}{end}' 2>/dev/null | + grep -n '^https-hostport$' | cut -d: -f1 || true)" + + if [ -n "${line}" ]; then + index=$((line - 1)) + log "moving the ingress Service host port to ${PORT}" + kubectl -n istio-gateway patch svc istio-ingressgateway --type=json \ + -p "[{\"op\":\"replace\",\"path\":\"/spec/ports/${index}/port\",\"value\":${PORT}}]" >/dev/null + else + log "adding the ingress Service host port ${PORT}" + kubectl -n istio-gateway patch svc istio-ingressgateway --type=json \ + -p "[{\"op\":\"add\",\"path\":\"/spec/ports/-\",\"value\":{\"name\":\"https-hostport\",\"port\":${PORT},\"protocol\":\"TCP\",\"targetPort\":443}}]" >/dev/null + fi +} + +# Redirect URIs live in Keycloak's database, and the realm import will not +# revisit them, so they are rewritten in place. +update_keycloak_clients() { + local password kcadm client id origin + password="$(kubectl -n "${NAMESPACE}" get secret keycloak-auth \ + -o jsonpath='{.data.bootstrap-admin-password}' 2>/dev/null | base64 -d || true)" + if [ -z "${password}" ]; then + log "keycloak-auth secret not found; skipping the realm client update" + return 0 + fi + + kcadm="kubectl -n ${NAMESPACE} exec deploy/keycloak -- /opt/keycloak/bin/kcadm.sh" + if ! ${kcadm} config credentials --server http://localhost:8080 \ + --realm master --user admin --password "${password}" >/dev/null 2>&1; then + log "keycloak is not answering; skipping the realm client update" + return 0 + fi + + for client in console chat tracing sandboxes; do + origin="https://${client}.${BASE_DOMAIN}:${PORT}" + id="$(${kcadm} get clients -r "${REALM}" -q "clientId=agyn-${client}" \ + --fields id --format csv --noquotes 2>/dev/null | tr -d '\r' | head -1)" + if [ -z "${id}" ]; then + log " client agyn-${client} is not in the realm; skipped" + continue + fi + log " agyn-${client} -> ${origin}" + ${kcadm} update "clients/${id}" -r "${REALM}" \ + -s "redirectUris=[\"${origin}/*\"]" \ + -s "webOrigins=[\"${origin}\"]" \ + -s "attributes.\"post.logout.redirect.uris\"=\"${origin}/*\"" >/dev/null + done +} + +# The overlay advertises a host:port, and a tunneler on the host dials exactly +# what the enrolment JWT names -- so the advertised port has to be the one the +# host forwards, not an internal constant. Moving it moves four things that have +# to agree: the Service port (which the chart derives from advertisedPort), the +# address the controller advertises, the router's link to it, and the port the +# passthrough VirtualServices route to. +# +# Identities already enrolled carry the old address in their own ztAPI field. +# It is a plain URL beside the client certificate rather than part of what the +# certificate attests, so it is rewritten in place; the alternative is +# re-enrolling, and the one-time token that would take was spent at bake time. +move_ziti_port() { + local current + current="$(ziti_port)" + if [ -z "${current}" ]; then + log "no OpenZiti controller Service; skipping the overlay move" + return 0 + fi + if ziti_settled; then + log "the overlay already advertises port ${PORT}" + return 0 + fi + + # Skipped when only the routes are behind, which is where a run that failed + # part way leaves things -- the charts are already where they should be and + # upgrading them again would restart the controller for nothing. + if [ "${current}" != "${PORT}" ]; then + log "moving the OpenZiti overlay from port ${current} to ${PORT}" + ziti_repo + helm upgrade ziti-controller openziti/ziti-controller -n ziti --reuse-values \ + --version "$(chart_version ziti-controller)" \ + --set "clientApi.advertisedPort=${PORT}" \ + --set "managementApi.advertisedPort=${PORT}" --wait --timeout 5m >/dev/null + helm upgrade ziti-router openziti/ziti-router -n ziti --reuse-values \ + --version "$(chart_version ziti-router)" \ + --set "edge.advertisedPort=${PORT}" \ + --set "ctrl.endpoint=ziti.${BASE_DOMAIN}:${PORT}" --wait --timeout 5m >/dev/null + fi + + # The passthrough routes carry the host's traffic to those Services, so they + # move with the Service port or the hostname stops resolving to anything. + # They match on SNI and hand the connection over untouched, which puts them + # under tls rather than tcp. + local vs + for vs in ziti-controller ziti-controller-mgmt ziti-router; do + kubectl -n istio-gateway patch virtualservice "${vs}" --type=json \ + -p "[{\"op\":\"replace\",\"path\":\"/spec/tls/0/route/0/destination/port/number\",\"value\":${PORT}}]" \ + >/dev/null 2>&1 || + log " virtualservice ${vs} not patched; check its route shape" + done + + # The one platform service that dials the overlay's management API by URL + # rather than reaching it through an identity. + if kubectl -n "${NAMESPACE}" get deployment ziti-management >/dev/null 2>&1; then + log " re-pointing ziti-management at port ${PORT}" + kubectl set env "deployment/ziti-management" -n "${NAMESPACE}" \ + "ZITI_CONTROLLER_URL=https://ziti-mgmt.${BASE_DOMAIN}:${PORT}/edge/management/v1" >/dev/null + fi + + # The provisioning Job's script logs in by URL too. It has already run, so + # this changes nothing today -- but it is what a later re-run would read, + # and a re-run that hangs on an unreachable port is a bad way to find out. + if kubectl -n ziti get cm ziti-provision-script >/dev/null 2>&1; then + kubectl -n ziti get cm ziti-provision-script -o yaml | + sed "s|\(ziti-mgmt\.${BASE_DOMAIN}\):${current}|\1:${PORT}|g" | + kubectl apply -f - >/dev/null + fi + + repoint_router_endpoints + rewrite_enrolled_identities "${current}" + restart_ziti_consumers +} + +# Everything that dials the overlay learned the controller's address when it +# started and holds it for the life of the process, so a moved port leaves them +# retrying one that no longer answers -- visible as services losing their +# terminators and staying unbound. Selected by carrying a ZITI_ variable rather +# than by name, so a release that adds another service is covered by default. +restart_ziti_consumers() { + local names + names="$(kubectl -n "${NAMESPACE}" get deployments -o json 2>/dev/null | + python3 -c ' +import json,sys +try: items = json.load(sys.stdin)["items"] +except Exception: sys.exit(0) +for i in items: + env = [e["name"] for c in i["spec"]["template"]["spec"]["containers"] for e in (c.get("env") or [])] + if any(n.startswith("ZITI_") for n in env): + print(i["metadata"]["name"]) +' 2>/dev/null || true)" + [ -z "${names}" ] && return 0 + + # ziti-management first and on its own: it is what mints the identities the + # others authenticate with, so restarting them alongside it only has them + # retry against a service that is itself still starting. + if printf '%s\n' "${names}" | grep -qx ziti-management; then + log " restarting ziti-management" + kubectl -n "${NAMESPACE}" rollout restart deployment/ziti-management >/dev/null 2>&1 || true + kubectl -n "${NAMESPACE}" rollout status deployment/ziti-management --timeout=180s >/dev/null 2>&1 || true + fi + + local name + for name in ${names}; do + [ "${name}" = "ziti-management" ] && continue + log " restarting ${name}" + kubectl -n "${NAMESPACE}" rollout restart "deployment/${name}" >/dev/null 2>&1 || true + done +} + +# The router caches the controller endpoints it last connected to and prefers +# that file over its config, so setting ctrl.endpoint alone leaves it dialling +# the old port until it gives up ("unable to connect to any controllers before +# timeout"). The file lives on its PVC, which the local-path provisioner backs +# with a directory on this node. +repoint_router_endpoints() { + local cache + cache="$(router_endpoints_file)" + [ -z "${cache}" ] && return 0 + grep -q "tls:ziti\.${BASE_DOMAIN}:${PORT}\$" "${cache}" 2>/dev/null && + ! grep -oE "tls:ziti\.${BASE_DOMAIN}:[0-9]+" "${cache}" | grep -qv ":${PORT}\$" && + return 0 + + log " re-pointing the router's cached controller endpoints at port ${PORT}" + sed -i -E "s|(tls:ziti\.${BASE_DOMAIN}):[0-9]+|\1:${PORT}|g" "${cache}" + kubectl -n ziti rollout restart deployment/ziti-router >/dev/null 2>&1 || true +} + +restart_mounters() { + local ns="${1}" secret="${2}" deployment + for deployment in $(kubectl -n "${ns}" get deployments \ + -o jsonpath="{range .items[?(@.spec.template.spec.volumes[*].secret.secretName=='${secret}')]}{.metadata.name}{\"\n\"}{end}" 2>/dev/null); do + log " restarting ${ns}/${deployment}" + kubectl -n "${ns}" rollout restart "deployment/${deployment}" >/dev/null 2>&1 || true + done +} + +# Every Secret holding an enrolled identity.json, wherever it lives: the set +# differs by which first-party apps a release ships. +rewrite_enrolled_identities() { + local from="${1}" ns name payload updated + while read -r ns name; do + [ -z "${ns}" ] && continue + payload="$(kubectl -n "${ns}" get secret "${name}" \ + -o jsonpath='{.data.identity\.json}' 2>/dev/null | base64 -d || true)" + case "${payload}" in + *":${from}/edge/"*) ;; + *) continue ;; + esac + updated="$(printf '%s' "${payload}" | sed "s|:${from}/edge/|:${PORT}/edge/|g")" + log " re-pointing ${ns}/${name} at port ${PORT}" + kubectl -n "${ns}" patch secret "${name}" --type=json \ + -p "[{\"op\":\"replace\",\"path\":\"/data/identity.json\",\"value\":\"$(printf '%s' "${updated}" | base64 | tr -d '\n')\"}]" \ + >/dev/null + # The identity is read at start, so whoever mounts it has to restart. + # Found by what references the Secret rather than by name: a chart is + # free to prefix its release onto the Deployment and not the Secret. + restart_mounters "${ns}" "${name}" + done <<-EOF + $(kubectl get secrets --all-namespaces \ + -o jsonpath='{range .items[?(@.data.identity\.json)]}{.metadata.namespace}{" "}{.metadata.name}{"\n"}{end}' 2>/dev/null) + EOF +} + +log "pointing browser-facing URLs at port ${PORT}" +patch_ingress_hostport +move_ziti_port + +kubectl set env deployment/chat-app -n "${NAMESPACE}" \ + "OIDC_AUTHORITY=${issuer}" \ + "OIDC_REDIRECT_URI=${chat_origin}/callback" \ + "OIDC_POST_LOGOUT_REDIRECT_URI=${chat_origin}" \ + "MEDIA_PROXY_URL=${media_origin}" >/dev/null +kubectl set env deployment/console-app -n "${NAMESPACE}" \ + "OIDC_AUTHORITY=${issuer}" >/dev/null +kubectl set env deployment/tracing-app -n "${NAMESPACE}" \ + "OIDC_AUTHORITY=${issuer}" >/dev/null +kubectl set env deployment/sandboxes-app -n "${NAMESPACE}" \ + "OIDC_AUTHORITY=${issuer}" >/dev/null +kubectl set env deployment/media-proxy -n "${NAMESPACE}" \ + "OIDC_ISSUER_URL=${issuer}" \ + "CORS_ALLOWED_ORIGIN=${chat_origin}" >/dev/null +kubectl set env deployment/gateway -n "${NAMESPACE}" \ + "OIDC_ISSUER_URL=${issuer}" >/dev/null +kubectl set env deployment/terminal-proxy -n "${NAMESPACE}" \ + "TERMINAL_PROXY_WEBSOCKET_URL=${terminal_url}" >/dev/null +kubectl set env deployment/keycloak -n "${NAMESPACE}" \ + "KC_HOSTNAME=${auth_origin}" >/dev/null + +# Keycloak first: the Gateway fetches discovery on start, and it has to be the +# new issuer that answers or the Gateway comes up rejecting every token. +kubectl rollout status deployment/keycloak -n "${NAMESPACE}" --timeout=300s +update_keycloak_clients + +for deployment in chat-app console-app tracing-app sandboxes-app media-proxy gateway terminal-proxy; do + kubectl rollout status "deployment/${deployment}" -n "${NAMESPACE}" --timeout=300s +done +log "done" diff --git a/internal/local/scripts/upgrade-platform.sh b/internal/local/scripts/upgrade-platform.sh index 12d6ea7..a890754 100755 --- a/internal/local/scripts/upgrade-platform.sh +++ b/internal/local/scripts/upgrade-platform.sh @@ -14,10 +14,10 @@ set -euo pipefail # OpenFGA endpoints), and `agyn local start` has since rewritten the bootstrap # token. Re-rendering would silently revert it. # -# Reusing values does NOT preserve the browser-facing port, because -# set-ingress-port.sh wrote that with `kubectl set env` rather than through the -# release. Helm rewrites those Deployments from chart values, so the port is -# re-applied at the end of this script. +# Reusing values does NOT preserve the browser-facing port: it was written with +# `kubectl set env` rather than through the release, so Helm rewrites those +# Deployments from chart values. This script reports that something moved and +# the CLI points them back afterwards. # # --values overlays a file on top of the reused values, for settings the image # cannot know: an external OIDC issuer instead of the bundled Keycloak, say. It @@ -45,8 +45,13 @@ HELM_TIMEOUT="${AGYN_HELM_TIMEOUT:-15m}" platform_version="" apps_version="" extra_values="" +resume=0 while [ "$#" -gt 0 ]; do case "${1}" in + --resume) + resume=1 + shift + ;; --values) extra_values="${2:-}" shift 2 @@ -77,6 +82,7 @@ step() { printf 'AGYN|step|%s|%s\n' "${1}" "${2:-}"; } done_() { printf 'AGYN|done|%s\n' "${1:-}"; } skip() { printf 'AGYN|skip|%s\n' "${1:-}"; } note() { printf 'AGYN|note|%s\n' "${1}"; } +fail() { printf 'AGYN|fail|%s\n' "${1}"; } if ! kubectl get --raw=/readyz >/dev/null 2>&1; then step "Waiting for the cluster" "" @@ -95,9 +101,26 @@ if kubectl -n "${NAMESPACE}" get deploy -o jsonpath='{range .items[*]}{.spec.tem note "services running from source (devspace) will be reset to their chart images" fi +# The release's own status, which is where a pending or failed state shows. +# `helm list` hides pending releases entirely, so it cannot be asked this. +# +# Every reader here ends in `|| true`. Under `set -e` with `pipefail` a +# substitution whose pipeline fails takes the whole script down, and these +# pipelines fail routinely and harmlessly: helm status errors for a release that +# is not installed, and helm show needs a network. Empty is the answer in both +# cases, and each caller already handles empty. +release_status() { + { + helm status "${1}" -n "${NAMESPACE}" -o json 2>/dev/null | + sed -n 's/.*"info":{[^}]*"status":"\([a-z-]*\)".*/\1/p' | head -1 + } || true +} + installed_version() { - helm list -n "${NAMESPACE}" --filter "^${1}\$" -o json 2>/dev/null | - sed -n 's/.*"chart":"[^"]*-\([0-9][^"]*\)".*/\1/p' | head -1 + { + helm list -n "${NAMESPACE}" --filter "^${1}\$" -o json 2>/dev/null | + sed -n 's/.*"chart":"[^"]*-\([0-9][^"]*\)".*/\1/p' | head -1 + } || true } # The version the chart repository would install, so an upgrade can say where it @@ -109,7 +132,7 @@ available_version() { if [ -n "${want}" ]; then set -- "$@" --version "${want}" fi - helm "$@" 2>/dev/null | sed -n 's/^version: *//p' | head -1 + { helm "$@" 2>/dev/null | sed -n 's/^version: *//p' | head -1; } || true } upgrade() { @@ -121,6 +144,25 @@ upgrade() { return 0 fi + # An upgrade that was interrupted -- a laptop closed, a terminal killed -- + # leaves the release mid-flight, and Helm refuses every later attempt with + # "another operation is in progress". That is true and unactionable, and the + # state is invisible to `helm list`, which hides pending releases. + # --resume is the caller saying they know: it has just cleared the in-flight + # revision, and refusing here would refuse the recovery itself. Checked + # against the flag rather than re-reading the status, so the recovery does + # not depend on a second read agreeing with the first. + status="$(release_status "${release}")" + case "${status}" in + pending-*) + if [ "${resume}" -eq 0 ]; then + step "${release}" + fail "an earlier upgrade was interrupted and left it ${status}; continue it with: agyn local upgrade --resume" + exit 70 + fi + ;; + esac + before="$(installed_version "${release}")" target="$(available_version "${chart}" "${want}")" @@ -159,36 +201,55 @@ upgrade() { done_ "${before:-unknown} → ${after:-unknown}" } -upgraded=0 -upgrade agyn-platform "${PLATFORM_CHART}" "${platform_version}" -upgrade agyn-apps "${APPS_CHART}" "${apps_version}" - -# Helm rewrites every Deployment it owns back to what the chart says, and the -# browser-facing URLs are not in the chart: set-ingress-port.sh wrote them with -# `kubectl set env` when the host chose a port. An upgrade reverts them to the -# chart's default port, which now includes the OIDC issuer — leaving the Gateway -# fetching discovery from a port the ingress no longer publishes, and every -# login broken. +# Clears the revision an interrupted upgrade left in flight, so the upgrade that +# follows is not refused. # -# The port itself survives, because it lives on the istio-ingressgateway -# Service and no chart owns that. So it is read back from there and re-applied. -# Idempotent: on a VM still using the default port this changes nothing. +# Forward rather than back. Helm's own remedy is a rollback to the last deployed +# revision, and that is wrong here: an interruption leaves some workloads on the +# new chart already, and rolling those back moves them by however many versions +# the upgrade spanned. The platform's migrations are forward-only and guarantee +# one version of backward compatibility (see the database-migrations spec), so a +# ten-version step backwards is outside what any service promises to survive. +# Completing the upgrade is the direction the data has already gone. # -# Skipped when nothing was upgraded, because then nothing reverted it: an -# upgrade that did nothing should say so in one line and stop, not perform -# repair work on a cluster it did not touch. -if [ "${upgraded}" -eq 0 ]; then - exit 0 +# The in-flight revision is dropped by deleting its release record; the last +# deployed revision becomes current again in Helm's account, no workload is +# touched, and the upgrade below reconciles everything to the target. +clear_interrupted() { + release="${1}" + status="$(release_status "${release}")" + case "${status}" in + pending-*) ;; + *) return 0 ;; + esac + + revision="$({ + helm history "${release}" -n "${NAMESPACE}" -o json 2>/dev/null | + sed -n 's/.*"revision":\([0-9]*\)[^0-9].*/\1/p' | tail -1 + } || true)" + if [ -z "${revision}" ]; then + return 0 + fi + step "Clearing the interrupted upgrade of ${release}" "revision ${revision}, ${status}" + kubectl delete secret "sh.helm.release.v1.${release}.v${revision}" -n "${NAMESPACE}" >&2 + done_ "" +} + +if [ "${resume}" -eq 1 ]; then + clear_interrupted agyn-platform + clear_interrupted agyn-apps fi -host_port="$(kubectl -n istio-gateway get svc istio-ingressgateway \ - -o jsonpath='{.spec.ports[?(@.name=="https-hostport")].port}' 2>/dev/null || true)" -if [ -n "${host_port}" ] && [ -x /opt/agyn/set-ingress-port.sh ]; then - step "Restoring the browser-facing port" "" - /opt/agyn/set-ingress-port.sh "${host_port}" >&2 - done_ "${host_port}" -elif [ -n "${host_port}" ]; then - note "WARNING: /opt/agyn/set-ingress-port.sh is missing, so browser-facing URLs now point at the chart's default port instead of ${host_port}" +upgraded=0 +upgrade agyn-platform "${PLATFORM_CHART}" "${platform_version}" +upgrade agyn-apps "${APPS_CHART}" "${apps_version}" + +# Whether anything moved. The browser-facing URLs are rewritten from chart +# values by any upgrade, so they have to be pointed back at the host's port +# afterwards -- but only then. The CLI owns that step, because it is the side +# that knows which port this host forwards. +if [ "${upgraded}" -eq 1 ]; then + printf 'AGYN|changed|\n' fi helm list -n "${NAMESPACE}" >&2 diff --git a/internal/local/upgrade.go b/internal/local/upgrade.go index 25b25d9..7c139da 100644 --- a/internal/local/upgrade.go +++ b/internal/local/upgrade.go @@ -36,24 +36,37 @@ const marker = "AGYN|" // kubectl say to log: a Helm upgrade that waits on rollouts takes minutes, and // what the user asked was which versions moved, not what the admission webhook // thinks of the release's AuthorizationPolicies. -func UpgradePlatform(steps *terminal.Steps, log io.Writer, platformVersion string) error { +// Returns whether any release moved. The caller acts on that: an upgrade +// rewrites every Deployment the charts own, including the browser-facing URLs +// that were pointed at this host's port outside the release. +// resume clears the revision an interrupted upgrade left in flight before +// upgrading, which is what stops Helm refusing it. +func UpgradePlatform(steps *terminal.Steps, log io.Writer, platformVersion string, resume bool) (bool, error) { + args := []string{} + if resume { + args = append(args, "--resume") + } + if platformVersion != "" { + args = append(args, "--platform-version", platformVersion) + } + return runUpgradeScript(steps, log, args) +} + +func runUpgradeScript(steps *terminal.Steps, log io.Writer, scriptArgs []string) (bool, error) { instance, err := GetInstance() if err != nil { - return err + return false, err } if !instance.Exists { - return fmt.Errorf("no local VM; create one with 'agyn local start'") + return false, fmt.Errorf("no local VM; create one with 'agyn local start'") } if instance.Status != "Running" { - return fmt.Errorf("the local VM is not running (%s); start it with 'agyn local start'", instance.Status) + return false, fmt.Errorf("the local VM is not running (%s); start it with 'agyn local start'", instance.Status) } // Piped to a shell rather than written into the VM: nothing to install, and - // no baked copy left behind to drift from this caller. Empty means "latest". - args := []string{"shell", InstanceName(), "--", "sudo", "bash", "-s", "--"} - if platformVersion != "" { - args = append(args, "--platform-version", platformVersion) - } + // no baked copy left behind to drift from this caller. + args := append([]string{"shell", InstanceName(), "--", "sudo", "bash", "-s", "--"}, scriptArgs...) reader, writer := io.Pipe() render := &upgradeRenderer{steps: steps, log: log} @@ -69,10 +82,15 @@ func UpgradePlatform(steps *terminal.Steps, log io.Writer, platformVersion strin wg.Wait() if runErr != nil { - return render.fail(fmt.Errorf("upgrade the platform in the VM: %w", runErr)) + // The script's own account of what went wrong, when it gave one: an + // exit status says nothing a user can act on. + if render.failure != "" { + return false, fmt.Errorf("%s", render.failure) + } + return false, render.fail(fmt.Errorf("upgrade the platform in the VM: %w", runErr)) } render.finish() - return nil + return render.changed, nil } // upgradeRenderer turns the script's markers into steps, and everything else @@ -85,6 +103,8 @@ type upgradeRenderer struct { step *terminal.Step detail string stopped chan struct{} + changed bool + failure string } func (r *upgradeRenderer) consume(reader io.Reader) { @@ -108,6 +128,11 @@ func (r *upgradeRenderer) consume(reader io.Reader) { r.skip(field(fields, 1)) case "note": r.steps.Note(field(fields, 1)) + case "changed": + r.changed = true + case "fail": + r.failure = field(fields, 1) + r.fail(fmt.Errorf("%s", r.failure)) } } } diff --git a/internal/local/upgrade_script_test.go b/internal/local/upgrade_script_test.go new file mode 100644 index 0000000..620e0f7 --- /dev/null +++ b/internal/local/upgrade_script_test.go @@ -0,0 +1,136 @@ +package local + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// The upgrade script is executable code that runs where nothing watches it, and +// `set -e` with `pipefail` makes every reader a place the whole run can die: a +// command substitution whose pipeline fails takes the script with it. Both +// readers fail routinely and harmlessly -- `helm status` errors for a release +// that is not installed, `helm show` needs a network -- and when the first of +// them did, a resume cleared the interrupted revision and then exited 1 with +// nothing to say. +func TestUpgradeScriptSurvivesReleasesThatAreNotInstalled(t *testing.T) { + out, err := runUpgradeScriptWithStubs(t, map[string]string{ + // Neither release exists here: every `helm status` fails. + "helm": `case "$1" in + status) exit 1 ;; + list) echo "[]" ;; + show) echo "version: 0.52.0" ;; + history) exit 1 ;; + *) exit 0 ;; + esac`, + "kubectl": `case "$*" in + *readyz*) echo ok ;; + *) exit 0 ;; + esac`, + }, "--resume") + + if err != nil { + t.Fatalf("expected the script to survive uninstalled releases, got %v:\n%s", err, out) + } + if strings.Contains(out, "AGYN|fail") { + t.Fatalf("expected no reported failure:\n%s", out) + } +} + +// The reason --resume exists: an interrupted upgrade leaves a revision in +// flight, and it has to be cleared before anything else is attempted. It is +// cleared forward -- the record is dropped and the upgrade proceeds -- rather +// than rolled back onto workloads the interruption already moved. +func TestUpgradeScriptResumeClearsTheInterruptedRevisionThenUpgrades(t *testing.T) { + out, err := runUpgradeScriptWithStubs(t, map[string]string{ + "helm": `case "$1" in + status) + [ "$2" = "agyn-platform" ] || exit 1 + echo '{"info":{"status":"pending-upgrade"},"name":"agyn-platform"}' ;; + history) echo '[{"revision":1},{"revision":4}]' ;; + list) echo '[{"chart":"agyn-platform-0.42.1"}]' ;; + show) echo "version: 0.52.0" ;; + upgrade) echo "upgraded" >&2 ;; + *) exit 0 ;; + esac`, + "kubectl": `case "$*" in + *readyz*) echo ok ;; + *"delete secret"*) echo "$*" >> "$STUB_LOG" ;; + *) exit 0 ;; + esac`, + }, "--resume") + + if err != nil { + t.Fatalf("resume failed: %v\n%s", err, out) + } + if !strings.Contains(out, "AGYN|step|Clearing the interrupted upgrade") { + t.Fatalf("expected the interrupted revision to be cleared:\n%s", out) + } + // The in-flight revision, not the one before it: dropping the wrong record + // would discard the release's history of what is actually deployed. + if log := stubLog(t); !strings.Contains(log, "sh.helm.release.v1.agyn-platform.v4") { + t.Fatalf("expected revision 4's record to be deleted, got: %s", log) + } + if !strings.Contains(out, "AGYN|changed|") { + t.Fatalf("expected the upgrade to proceed after clearing:\n%s", out) + } +} + +// An interrupted upgrade that is not being resumed has to say so, and say what +// continues it. Helm's own error names the lock and not the way out, and a +// release listing does not show the state at all. +func TestUpgradeScriptRefusesAPendingReleaseWithTheWayOut(t *testing.T) { + out, _ := runUpgradeScriptWithStubs(t, map[string]string{ + "helm": `case "$1" in + status) + [ "$2" = "agyn-platform" ] || exit 1 + echo '{"info":{"status":"pending-upgrade"},"name":"agyn-platform"}' ;; + *) exit 0 ;; + esac`, + "kubectl": `case "$*" in + *readyz*) echo ok ;; + *) exit 0 ;; + esac`, + }) + + if !strings.Contains(out, "AGYN|fail|") || !strings.Contains(out, "--resume") { + t.Fatalf("expected a failure naming the recovery command:\n%s", out) + } +} + +// runUpgradeScriptWithStubs runs the embedded script against stub tools, so the +// shell itself is exercised without a VM. +func runUpgradeScriptWithStubs(t *testing.T, stubs map[string]string, args ...string) (string, error) { + t.Helper() + dir := t.TempDir() + for name, body := range stubs { + script := "#!/usr/bin/env bash\n" + body + "\n" + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o755); err != nil { + t.Fatalf("write stub %s: %v", name, err) + } + } + + cmd := exec.Command("bash", append([]string{"-s", "--"}, args...)...) + cmd.Stdin = strings.NewReader(upgradeScript) + cmd.Env = append(os.Environ(), + "PATH="+dir+string(os.PathListSeparator)+os.Getenv("PATH"), + "STUB_LOG="+filepath.Join(dir, "calls.log")) + stubDir = dir + + output, err := cmd.CombinedOutput() + return string(output), err +} + +// stubDir is where the last stub run recorded its calls. +var stubDir string + +func stubLog(t *testing.T) string { + t.Helper() + data, err := os.ReadFile(filepath.Join(stubDir, "calls.log")) + if err != nil { + return "" + } + return string(data) +} diff --git a/internal/local/upgrade_test.go b/internal/local/upgrade_test.go index ce6afcb..538f9dc 100644 --- a/internal/local/upgrade_test.go +++ b/internal/local/upgrade_test.go @@ -61,6 +61,41 @@ func TestUpgradeRendererMarksAnAlreadyCurrentReleaseAsSkipped(t *testing.T) { } } +// The port repair runs only when something moved, and the script is the only +// side that knows whether anything did. +func TestUpgradeRendererReportsWhetherAnythingChanged(t *testing.T) { + var out, log bytes.Buffer + renderer := &upgradeRenderer{steps: terminal.NewPlainSteps(&out), log: &log} + renderer.consume(strings.NewReader("AGYN|step|agyn-platform|\nAGYN|skip|already at 0.52.0\n")) + if renderer.changed { + t.Fatal("expected a skipped upgrade to report nothing changed") + } + + renderer = &upgradeRenderer{steps: terminal.NewPlainSteps(&out), log: &log} + renderer.consume(strings.NewReader("AGYN|step|agyn-platform|\nAGYN|done|0.42.1 → 0.52.0\nAGYN|changed|\n")) + if !renderer.changed { + t.Fatal("expected an upgrade that moved a release to report a change") + } +} + +// An interrupted upgrade is the one failure whose Helm error states the lock +// and not the way out, so the script's own sentence has to survive to the user +// instead of being replaced by an exit status. +func TestUpgradeRendererKeepsTheScriptsFailureMessage(t *testing.T) { + var out, log bytes.Buffer + renderer := &upgradeRenderer{steps: terminal.NewPlainSteps(&out), log: &log} + + renderer.consume(strings.NewReader( + "AGYN|step|agyn-platform|\nAGYN|fail|an earlier upgrade was interrupted and left it pending-upgrade; recover with: agyn local upgrade --resume\n")) + + if !strings.Contains(renderer.failure, "--resume") { + t.Fatalf("expected the recovery command to be kept, got %q", renderer.failure) + } + if !strings.Contains(out.String(), "pending-upgrade") { + t.Fatalf("expected the reason on the step's line:\n%s", out.String()) + } +} + // A step the script leaves open — the last one before the process exits — still // has to be closed, or the run ends on a line that reads as still running. func TestUpgradeRendererClosesATrailingStep(t *testing.T) { From d237adc1557a779fed9803f00d372575a93197f6 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 11 Aug 2026 02:50:07 +0200 Subject: [PATCH 04/19] Run gofmt over profile.go Struct literal alignment, left behind by an earlier change and picked up by a gofmt -w over the package. No behaviour in it. --- internal/cmd/profile.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/cmd/profile.go b/internal/cmd/profile.go index 9733983..c7b071a 100644 --- a/internal/cmd/profile.go +++ b/internal/cmd/profile.go @@ -317,9 +317,9 @@ func newProfileRemoveCmd() *cobra.Command { func profileOutputFor(cfg *config.Config, name, currentName string) profileOutput { profile := cfg.Profile(name) return profileOutput{ - Name: name, - Current: name == currentName, - GatewayURL: cfg.ResolveGatewayTargetFor(name, "").URL, + Name: name, + Current: name == currentName, + GatewayURL: cfg.ResolveGatewayTargetFor(name, "").URL, Organization: profile.Organization, CAFile: profile.CAFile, SandboxIdleTimeout: profile.SandboxIdleTimeout, From 8de82b75ce3ae1c2b8bc426ef5d9844e8a4834c9 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 11 Aug 2026 03:00:30 +0200 Subject: [PATCH 05/19] One run log per VM, not one for the machine Every command truncated the same ~/.agyn/local/last-run.log, so two running at once wrote into each other's. It showed up as a failure report that made no sense: an upgrade that failed printed the tail of the log, and the tail was a delete running beside it powering a VM down -- which reads as the upgrade having stopped the VM it was upgrading. A log belongs to a VM, like its CA, its profile and its kubeconfig context do. ~/.agyn/local/logs/.log. --- internal/cmd/local.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/internal/cmd/local.go b/internal/cmd/local.go index 5e2e4ea..6c28392 100644 --- a/internal/cmd/local.go +++ b/internal/cmd/local.go @@ -933,7 +933,7 @@ func printChecks(out io.Writer, checks []local.Check) error { // limaIO routes the output of the tools a command drives — limactl, and the // helm and kubectl it runs inside the VM. To the terminal with --debug, -// otherwise to ~/.agyn/local/last-run.log with an automatic tail on failure. +// otherwise to ~/.agyn/local/logs/.log with an automatic tail on failure. type limaIO struct { stdout io.Writer stderr io.Writer @@ -950,10 +950,15 @@ func openRunLog(cmd *cobra.Command) (*limaIO, error) { if err != nil { return nil, err } + // One log per VM. A single shared file is truncated by whichever command + // opens it next, so two commands running at once write into each other's: + // an upgrade's failure printed the tail of a delete running beside it, + // which reads as the upgrade having shut the VM down. + dir = filepath.Join(dir, "logs") if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("create %s: %w", dir, err) } - path := filepath.Join(dir, "last-run.log") + path := filepath.Join(dir, local.InstanceName()+".log") file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) if err != nil { return nil, fmt.Errorf("open run log: %w", err) From d2b256ad4d3e1c597102b8e1d891297d9f7c2aef Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 11 Aug 2026 03:08:43 +0200 Subject: [PATCH 06/19] Say which part of the platform the port move is on On a non-default port, pointing the browser-facing URLs at it restarts most of the platform: two helm upgrades of the OpenZiti charts with --wait, seven deployments re-envd and rolled, Keycloak restarted and its four realm clients rewritten through kcadm, then a rollout wait on each. Minutes, under a step labelled 'Configuring profile' whose profile write is the trivial part of it. The script already logs each phase. Those lines now go to the run log on stderr and to the CLI on stdout as markers, so the step's detail follows the work instead of standing still -- which is the difference between a long step and a hung one. On the default port none of this runs and the step stays a second long, which is why only a second VM ever saw it. --- internal/cmd/local.go | 2 +- internal/cmd/local_credentials.go | 6 ++- internal/local/credentials.go | 4 +- internal/local/lima.go | 44 +++++++++++++++++++++- internal/local/scripts/set-ingress-port.sh | 9 ++++- 5 files changed, 59 insertions(+), 6 deletions(-) diff --git a/internal/cmd/local.go b/internal/cmd/local.go index 6c28392..03d47f7 100644 --- a/internal/cmd/local.go +++ b/internal/cmd/local.go @@ -773,7 +773,7 @@ func newLocalUpgradeCmd() *cobra.Command { // longer publishes and every sign-in breaks. func restoreIngressPort(cmd *cobra.Command, steps *terminal.Steps, port int, runLog *limaIO) error { step := steps.Start("Restoring the browser-facing port") - if _, err := local.SetIngressPort(port); err != nil { + if _, err := local.SetIngressPort(port, step.Detail); err != nil { step.Fail(err) runLog.reportFailure(cmd) return err diff --git a/internal/cmd/local_credentials.go b/internal/cmd/local_credentials.go index 7687b71..df79731 100644 --- a/internal/cmd/local_credentials.go +++ b/internal/cmd/local_credentials.go @@ -134,8 +134,12 @@ func provisionLocalProfile(cmd *cobra.Command, steps *terminal.Steps, flags loca // The image bakes a default port into the URLs it hands a browser — the // OIDC redirects and the media proxy origin. Whenever this host forwards // something else, signing in would bounce back to a dead port. + // On a non-default port this restarts most of the platform -- the OpenZiti + // charts, Keycloak and its realm clients, and every workload holding a + // browser-facing URL -- so it reports which of them it is on rather than + // standing on one label for minutes. step.Detail("pointing browser-facing URLs at port " + strconv.Itoa(port)) - if _, err := local.SetIngressPort(port); err != nil { + if _, err := local.SetIngressPort(port, step.Detail); err != nil { return step.Fail(err) } diff --git a/internal/local/credentials.go b/internal/local/credentials.go index 8a596db..f3215b5 100644 --- a/internal/local/credentials.go +++ b/internal/local/credentials.go @@ -84,11 +84,11 @@ func SetBootstrapToken(token string) (string, error) { // already be taken. Only browser-facing URLs are affected — everything inside // the cluster, the OpenZiti advertised addresses included, uses an internal // port that never changes. -func SetIngressPort(port int) (string, error) { +func SetIngressPort(port int, onDetail func(string)) (string, error) { if port <= 0 || port > 65535 { return "", fmt.Errorf("ingress port %d is out of range", port) } - out, err := RunScript(ingressPortScript, strconv.Itoa(port)) + out, err := RunScriptProgress(ingressPortScript, onDetail, strconv.Itoa(port)) if err != nil { return "", fmt.Errorf("point the platform's URLs at port %d: %w", port, err) } diff --git a/internal/local/lima.go b/internal/local/lima.go index dcf6728..e4c6adf 100644 --- a/internal/local/lima.go +++ b/internal/local/lima.go @@ -211,14 +211,56 @@ func Delete(stdout, stderr io.Writer) error { // lives in the image can only be corrected by building a new image and // recreating the VM, which is the operation `upgrade` exists to avoid. func RunScript(script string, args ...string) (string, error) { + return RunScriptProgress(script, nil, args...) +} + +// RunScriptProgress runs a script that reports where it has got to, calling +// onDetail for each AGYN|detail| line it writes. Everything else is the script's +// own log and is returned. +// +// Scripts that restart the cluster take minutes, and a step with a fixed label +// for that long cannot be told from a hang. +func RunScriptProgress(script string, onDetail func(string), args ...string) (string, error) { var out bytes.Buffer + stdout := io.Writer(&out) + if onDetail != nil { + stdout = &detailScanner{onDetail: onDetail, rest: &out} + } shellArgs := append([]string{"shell", InstanceName(), "--", "sudo", "bash", "-s", "--"}, args...) - if err := limactlStdin(strings.NewReader(script), &out, &out, shellArgs...); err != nil { + if err := limactlStdin(strings.NewReader(script), stdout, &out, shellArgs...); err != nil { return out.String(), fmt.Errorf("%w: %s", err, strings.TrimSpace(out.String())) } return out.String(), nil } +// detailScanner splits a script's stdout into progress markers and everything +// else, line by line as it arrives. +type detailScanner struct { + onDetail func(string) + rest io.Writer + partial []byte +} + +func (d *detailScanner) Write(data []byte) (int, error) { + d.partial = append(d.partial, data...) + for { + index := bytes.IndexByte(d.partial, '\n') + if index < 0 { + return len(data), nil + } + line := string(d.partial[:index]) + d.partial = d.partial[index+1:] + if detail, ok := strings.CutPrefix(line, detailMarker); ok { + d.onDetail(detail) + continue + } + fmt.Fprintln(d.rest, line) + } +} + +// detailMarker prefixes a line a script writes for the CLI to show. +const detailMarker = "AGYN|detail|" + // RunScriptWithSecret runs a script whose input is a credential. // // The script is staged into the guest first, because stdin is the one channel diff --git a/internal/local/scripts/set-ingress-port.sh b/internal/local/scripts/set-ingress-port.sh index aa00583..08a9d48 100755 --- a/internal/local/scripts/set-ingress-port.sh +++ b/internal/local/scripts/set-ingress-port.sh @@ -49,7 +49,14 @@ NAMESPACE="${AGYN_PLATFORM_NAMESPACE:-agyn-platform}" BASE_DOMAIN="${AGYN_BASE_DOMAIN:-agyn.dev}" REALM="${AGYN_KEYCLOAK_REALM:-agyn}" -log() { printf '[set-ingress-port] %s\n' "$*"; } +# Two audiences. The run log gets the full account on stderr; the CLI gets the +# same line on stdout as a marker and shows it beside the spinner, because on a +# non-default port this script restarts most of the platform and a static label +# for several minutes of that is indistinguishable from a hang. +log() { + printf '[set-ingress-port] %s\n' "$*" >&2 + printf 'AGYN|detail|%s\n' "$*" +} if [ -z "${PORT}" ]; then log "no port supplied; leaving the image default in place" From ce7433d8e7df57f7ee24d5e28cb201599ad9a783 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 11 Aug 2026 03:22:38 +0200 Subject: [PATCH 07/19] Three steps, because these are three things 'Configuring profile local-test' covered installing a credential into the Gateway, moving the platform to another port, and writing a file on this machine. Only the last one is a profile, and it is the one that takes no time -- so minutes of cluster reconfiguration ran under the name of the fastest part, and 'moving the OpenZiti overlay' appeared as something configuring a profile does. Now: installing the token, pointing the platform at the port, configuring the profile. Each says what it is doing while it does it -- the token script reports its phases the same way the port script does, because a token that changed restarts the Gateway and waits on its rollout. Reads that used to run first for fail-fast now sit in the third step. Nothing is lost: the organization id is handed over by the readiness wait that already read it, and the two VM steps are idempotent, so a CA extract that fails after them costs a repeat of work that changed nothing. --- internal/cmd/local_credentials.go | 46 ++++++++++--------- internal/local/credentials.go | 4 +- internal/local/credentials_test.go | 6 +-- internal/local/lima.go | 8 +++- internal/local/scripts/set-bootstrap-token.sh | 8 +++- 5 files changed, 42 insertions(+), 30 deletions(-) diff --git a/internal/cmd/local_credentials.go b/internal/cmd/local_credentials.go index df79731..f885f0e 100644 --- a/internal/cmd/local_credentials.go +++ b/internal/cmd/local_credentials.go @@ -95,13 +95,35 @@ func newLocalCredentialsCmd() *cobra.Command { // finished starting. Empty means read it here. func provisionLocalProfile(cmd *cobra.Command, steps *terminal.Steps, flags localProfileFlags, port int, recordCA bool, organization string) error { name := flags.targetProfile() - step := steps.Start("Configuring profile " + name) token, err := localBootstrapToken(name) if err != nil { + return err + } + + // Three steps, because these are three things. Two of them change the VM + // and take as long as the workloads they restart; the third writes a file + // on this machine. Reporting all of it as "configuring a profile" put + // minutes of cluster reconfiguration under the name of the fastest part, + // and left the overlay being moved reading as something a profile does. + step := steps.Start("Installing the Gateway bootstrap token") + if _, err := local.SetBootstrapToken(token, step.Detail); err != nil { return step.Fail(err) } + step.Done("") + // The image bakes a default port into the URLs it hands a browser — the + // OIDC redirects and the media proxy origin. Whenever this host forwards + // something else, signing in would bounce back to a dead port. On a + // non-default port this restarts most of the platform, so it says which + // part it is on. + step = steps.Start("Pointing the platform at port " + strconv.Itoa(port)) + if _, err := local.SetIngressPort(port, step.Detail); err != nil { + return step.Fail(err) + } + step.Done("") + + step = steps.Start("Configuring profile " + name) profile := config.Profile{GatewayURL: local.GatewayURL(port), Organization: organization} if recordCA { // Extracted afresh rather than reused from the cache: a recreated or @@ -116,7 +138,6 @@ func provisionLocalProfile(cmd *cobra.Command, steps *terminal.Steps, flags loca } profile.CAFile = shortenHomePath(caFile) } - if profile.Organization == "" { profile.Organization, err = local.OrganizationID() if err != nil { @@ -124,31 +145,12 @@ func provisionLocalProfile(cmd *cobra.Command, steps *terminal.Steps, flags loca } } - // Last of the VM work, and the only part that changes the VM: the reads - // above fail fast, while these restart workloads when a value differs. - step.Detail("installing the Gateway bootstrap token") - if _, err := local.SetBootstrapToken(token); err != nil { - return step.Fail(err) - } - - // The image bakes a default port into the URLs it hands a browser — the - // OIDC redirects and the media proxy origin. Whenever this host forwards - // something else, signing in would bounce back to a dead port. - // On a non-default port this restarts most of the platform -- the OpenZiti - // charts, Keycloak and its realm clients, and every workload holding a - // browser-facing URL -- so it reports which of them it is on rather than - // standing on one label for minutes. - step.Detail("pointing browser-facing URLs at port " + strconv.Itoa(port)) - if _, err := local.SetIngressPort(port, step.Detail); err != nil { - return step.Fail(err) - } - current, err := writeLocalProfile(name, profile, token) if err != nil { return step.Fail(err) } - step.Done("organization " + profile.Organization) + if current != name { steps.Note(fmt.Sprintf("commands still run under profile %s; switch with: agyn profile use %s", current, name)) } diff --git a/internal/local/credentials.go b/internal/local/credentials.go index f3215b5..f6a4cc3 100644 --- a/internal/local/credentials.go +++ b/internal/local/credentials.go @@ -66,11 +66,11 @@ func IsBootstrapToken(token string) bool { // never the network, and is never read back: the host keeps the copy it // generated. It is handed over on stdin rather than as an argument, so it is in // neither machine's process list. -func SetBootstrapToken(token string) (string, error) { +func SetBootstrapToken(token string, onDetail func(string)) (string, error) { if strings.TrimSpace(token) == "" { return "", fmt.Errorf("bootstrap token must not be empty") } - out, err := RunScriptWithSecret(bootstrapTokenScript, strings.NewReader(token)) + out, err := RunScriptWithSecret(bootstrapTokenScript, strings.NewReader(token), onDetail) if err != nil { return "", fmt.Errorf("install the bootstrap token in the VM: %w", err) } diff --git a/internal/local/credentials_test.go b/internal/local/credentials_test.go index 35b5701..e925368 100644 --- a/internal/local/credentials_test.go +++ b/internal/local/credentials_test.go @@ -48,9 +48,9 @@ func TestIsBootstrapTokenRecognisesOnlyItsOwn(t *testing.T) { } func TestSetBootstrapTokenRejectsAnEmptyValue(t *testing.T) { - // Empty is what the in-VM script reads as "leave the image placeholder in - // place" — silently provisioning nothing while reporting success. - if _, err := SetBootstrapToken(" "); err == nil { + // The script refuses an empty read too, but this check is what keeps the + // VM from being reached at all for a value that cannot be right. + if _, err := SetBootstrapToken(" ", nil); err == nil { t.Fatal("expected an empty token to be rejected before touching the VM") } } diff --git a/internal/local/lima.go b/internal/local/lima.go index e4c6adf..540d75c 100644 --- a/internal/local/lima.go +++ b/internal/local/lima.go @@ -269,7 +269,7 @@ const detailMarker = "AGYN|detail|" // by any user of the guest, and by anyone running ps on the host while the CLI // works. The staged copy is mode 0700 under /run, which is tmpfs, and is // removed whether or not the run succeeds. -func RunScriptWithSecret(script string, secret io.Reader, args ...string) (string, error) { +func RunScriptWithSecret(script string, secret io.Reader, onDetail func(string), args ...string) (string, error) { path := "/run/agyn-" + InstanceName() + ".sh" var staged bytes.Buffer @@ -282,8 +282,12 @@ func RunScriptWithSecret(script string, secret io.Reader, args ...string) (strin }() var out bytes.Buffer + stdout := io.Writer(&out) + if onDetail != nil { + stdout = &detailScanner{onDetail: onDetail, rest: &out} + } runArgs := append([]string{"shell", InstanceName(), "--", "sudo", "bash", path}, args...) - if err := limactlStdin(secret, &out, &out, runArgs...); err != nil { + if err := limactlStdin(secret, stdout, &out, runArgs...); err != nil { return out.String(), fmt.Errorf("%w: %s", err, strings.TrimSpace(out.String())) } return out.String(), nil diff --git a/internal/local/scripts/set-bootstrap-token.sh b/internal/local/scripts/set-bootstrap-token.sh index 83e4e72..a0e1dfe 100755 --- a/internal/local/scripts/set-bootstrap-token.sh +++ b/internal/local/scripts/set-bootstrap-token.sh @@ -22,7 +22,13 @@ NAMESPACE="${AGYN_PLATFORM_NAMESPACE:-agyn-platform}" SECRET="${AGYN_BOOTSTRAP_TOKEN_SECRET:-gateway-bootstrap-token}" KEY="${AGYN_BOOTSTRAP_TOKEN_KEY:-token}" -log() { printf '[set-bootstrap-token] %s\n' "$*"; } +# stderr carries the account for the run log; stdout carries the same line as a +# marker for the CLI, because a token that changed restarts the Gateway and +# waits on its rollout. +log() { + printf '[set-bootstrap-token] %s\n' "$*" >&2 + printf 'AGYN|detail|%s\n' "$*" +} # Loud rather than quiet. The token now always arrives from the CLI on stdin, so # an empty read is a broken channel, not a caller declining to set one -- and From 1419e01c90b653f2af6a07a9de1cdf28c0eb9165 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 11 Aug 2026 04:44:20 +0200 Subject: [PATCH 08/19] Do not wait for pods that are waiting for the repair On a VM serving any port but the baked 2496, every upgrade deadlocked until Helm's 15-minute timeout. An upgrade rewrites the browser-facing URLs back to the chart's default port, because they were set with kubectl set env rather than through the release. The workloads holding those URLs -- gateway, networks, ziti-management, agents-orchestrator -- then crash-loop against a port that publishes nothing. helm upgrade --wait waits for exactly those to become Ready, and the repair that would let them is the step after it. Each side waiting on the other. So the upgrade no longer passes --wait: Helm returns once the manifests are applied, the CLI points the platform back at the host's port, and only then waits for the rollout. --timeout still bounds the chart's hooks. The wait is better where it now is. Helm reports a timeout as 'timed out waiting for the condition'; the CLI's readiness wait names the workloads that are behind and updates as they land. Found by running an upgrade on a second VM, which is the only place it happens: on 2496 there is nothing to revert and nothing to repair. --- internal/cmd/local.go | 15 ++++++++++++++- internal/local/scripts/upgrade-platform.sh | 12 +++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/internal/cmd/local.go b/internal/cmd/local.go index 03d47f7..82f0703 100644 --- a/internal/cmd/local.go +++ b/internal/cmd/local.go @@ -754,7 +754,20 @@ func newLocalUpgradeCmd() *cobra.Command { return nil } - return restoreIngressPort(cmd, steps, settings.Port, runLog) + if err := restoreIngressPort(cmd, steps, settings.Port, runLog); err != nil { + return err + } + + // The rollout is waited on here rather than by Helm, because it can + // only succeed after the repair above: an upgrade reverts the + // browser-facing URLs to the chart's port, and the workloads holding + // them do not start until they are pointed back. + step := steps.Start("Waiting for the platform") + if _, err := local.WaitForReady(settings.Port, platformReadyTimeout, step.Detail); err != nil { + return step.Fail(err) + } + step.Done("") + return nil }, } diff --git a/internal/local/scripts/upgrade-platform.sh b/internal/local/scripts/upgrade-platform.sh index a890754..97403d7 100755 --- a/internal/local/scripts/upgrade-platform.sh +++ b/internal/local/scripts/upgrade-platform.sh @@ -184,8 +184,18 @@ upgrade() { # on its own empty defaults: keycloak arrived this way and looked for its # database on localhost. Resetting first takes the new chart's defaults and # then reapplies what the release actually set. + # + # Deliberately not --wait. An upgrade rewrites the browser-facing URLs back + # to the chart's default port, and on a VM serving any other port the + # workloads holding those URLs cannot start until they are pointed back -- + # which the CLI does after this returns. Waiting here waits for pods that + # are waiting for the repair that is waiting for this: on a non-default port + # the upgrade deadlocked until Helm's timeout, every time. + # + # --timeout still bounds the chart's hooks. The rollout is waited on by the + # CLI afterwards, where it can also say which workloads are behind. set -- upgrade "${release}" "${chart}" -n "${NAMESPACE}" \ - --reset-then-reuse-values --wait --timeout "${HELM_TIMEOUT}" + --reset-then-reuse-values --timeout "${HELM_TIMEOUT}" # Overlaid on top of the reused values, so the caller's file changes only # what it names and everything the bake configured survives. if [ -n "${extra_values}" ]; then From 12a23c526a010d23f46b93ad83b50d6a5ab22498 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 11 Aug 2026 05:02:16 +0200 Subject: [PATCH 09/19] Write the host's port into the release, not over its output The release's values named 2496 on a VM serving 2497 -- in eighteen service URLs and in keycloak.wiring.ingressHostPort.port -- because nothing had ever written the host's choice into them. `agyn local start` patched the rendered Deployments instead, so every upgrade re-applied the baked port, every workload holding those URLs crash-looped against a port publishing nothing, and a second pass had to patch them back. Two rollouts of most of the platform, and a window between them long enough for Kubernetes to back off to five-minute retries. That, not the work, was the eleven minutes. The upgrade now derives an overlay from the release's own values, replacing the port they currently name with the host's, and hands it to Helm. One rollout, rendered right the first time. Derived rather than listed: nineteen keys carry it today and a twentieth added upstream would be missed silently. Only the exact stale number is replaced, so a service port that happens to appear is never touched, and when the values already agree no overlay is produced at all -- which is every VM on the default port. Values that name the wrong port are also their own reason to upgrade now. Skipping on a matching chart version left the release one re-render away from reverting to a port the VM does not serve. Measured on a second VM: a values-only correction took 20s with no workload restarted and the platform never unready, against eleven minutes before. --- internal/cmd/local.go | 2 +- internal/local/scripts/upgrade-platform.sh | 73 +++++++++++++++++++++- internal/local/upgrade.go | 8 ++- 3 files changed, 78 insertions(+), 5 deletions(-) diff --git a/internal/cmd/local.go b/internal/cmd/local.go index 82f0703..d78d423 100644 --- a/internal/cmd/local.go +++ b/internal/cmd/local.go @@ -745,7 +745,7 @@ func newLocalUpgradeCmd() *cobra.Command { defer runLog.close() steps := newSteps(cmd) - changed, err := local.UpgradePlatform(steps, runLog.stdout, "", resume) + changed, err := local.UpgradePlatform(steps, runLog.stdout, "", resume, settings.Port) if err != nil { runLog.reportFailure(cmd) return err diff --git a/internal/local/scripts/upgrade-platform.sh b/internal/local/scripts/upgrade-platform.sh index 97403d7..ca5843b 100755 --- a/internal/local/scripts/upgrade-platform.sh +++ b/internal/local/scripts/upgrade-platform.sh @@ -39,12 +39,14 @@ NAMESPACE="${AGYN_PLATFORM_NAMESPACE:-agyn-platform}" PLATFORM_CHART="${AGYN_PLATFORM_CHART:-oci://ghcr.io/agynio/charts/agyn-platform}" APPS_CHART="${AGYN_APPS_CHART:-oci://ghcr.io/agynio/charts/agyn-apps}" HELM_TIMEOUT="${AGYN_HELM_TIMEOUT:-15m}" +BASE_DOMAIN="${AGYN_BASE_DOMAIN:-agyn.dev}" # Named rather than positional: a values path and a chart version are easy to # transpose, and the failure would be a silent no-op or a wrong chart. platform_version="" apps_version="" extra_values="" +ingress_port="" resume=0 while [ "$#" -gt 0 ]; do case "${1}" in @@ -52,6 +54,10 @@ while [ "$#" -gt 0 ]; do resume=1 shift ;; + --ingress-port) + ingress_port="${2:-}" + shift 2 + ;; --values) extra_values="${2:-}" shift 2 @@ -135,6 +141,47 @@ available_version() { { helm "$@" 2>/dev/null | sed -n 's/^version: *//p' | head -1; } || true } +# The release's values still name the port the image was baked with, because +# nothing has ever written the host's choice into them: `agyn local start` +# patched the rendered Deployments instead. So every upgrade faithfully restores +# the baked port, the workloads holding those URLs crash-loop against a port +# that publishes nothing, and something has to patch them back afterwards -- +# a second rollout of most of the platform, and a window in between long enough +# for Kubernetes to back off to five-minute retries. +# +# Correcting the values means the upgrade renders the host's port to begin with: +# one rollout, no window, and the release finally knows what port it is on. +# +# Derived from the release's own values rather than from a list of keys kept +# here, because there are eighteen of them across the services and a nineteenth +# added upstream would be missed silently. +port_overlay() { + release="${1}" + [ -n "${ingress_port}" ] || return 0 + + current="$(helm get values "${release}" -n "${NAMESPACE}" -o yaml 2>/dev/null || true)" + case "${current}" in + "" | null) return 0 ;; + esac + + # The port the values currently name, taken from the URLs themselves. Every + # rewrite below replaces that exact number and nothing else, so a service + # port that happens to appear -- 50051, 5432 -- is never touched. + stale="$(printf '%s\n' "${current}" | + sed -nE "s#.*://[A-Za-z0-9.-]*${BASE_DOMAIN}:([0-9]+).*#\1#p" | head -1)" + if [ -z "${stale}" ] || [ "${stale}" = "${ingress_port}" ]; then + return 0 + fi + + # Two shapes carry it: the URLs, and keycloak's ingressHostPort.port, which + # is a plain number the chart models on its own. + file="/run/agyn-values-${release}.yaml" + printf '%s\n' "${current}" | sed -E \ + -e "s#(://[A-Za-z0-9.-]*${BASE_DOMAIN}):${stale}#\1:${ingress_port}#g" \ + -e "s#(^[[:space:]]*port:[[:space:]]*)${stale}[[:space:]]*\$#\1${ingress_port}#" >"${file}" + printf '%s' "${file}" +} + upgrade() { release="${1}" chart="${2}" @@ -166,10 +213,17 @@ upgrade() { before="$(installed_version "${release}")" target="$(available_version "${chart}" "${want}")" + overlay="$(port_overlay "${release}")" + # An upgrade to the version already installed still rewrites every workload # the chart owns and reports a new revision, so "nothing to do" and # "everything was replaced" would read alike. Say the first one instead. - if [ -z "${extra_values}" ] && [ -n "${before}" ] && [ "${before}" = "${target}" ]; then + # + # Values that name the wrong port are their own reason to upgrade, chart + # version or not: until they are corrected the release is one re-render away + # from reverting to a port this VM does not serve. + if [ -z "${extra_values}" ] && [ -z "${overlay}" ] && + [ -n "${before}" ] && [ "${before}" = "${target}" ]; then step "${release}" skip "already at ${before}" return 0 @@ -177,7 +231,11 @@ upgrade() { upgraded=1 - step "${release}" "${before:-unknown} → ${target:-latest}" + if [ -n "${overlay}" ] && [ "${before}" = "${target}" ]; then + step "${release}" "${before}, correcting the port to ${ingress_port}" + else + step "${release}" "${before:-unknown} → ${target:-latest}" + fi # --reuse-values would carry the old values forward but ignore defaults the # newer chart introduces, so a subchart added since the last release starts @@ -196,6 +254,11 @@ upgrade() { # CLI afterwards, where it can also say which workloads are behind. set -- upgrade "${release}" "${chart}" -n "${NAMESPACE}" \ --reset-then-reuse-values --timeout "${HELM_TIMEOUT}" + # The host's port first, then the caller's file, so an explicit --values + # can still override what this derived. + if [ -n "${overlay}" ]; then + set -- "$@" -f "${overlay}" + fi # Overlaid on top of the reused values, so the caller's file changes only # what it names and everything the bake configured survives. if [ -n "${extra_values}" ]; then @@ -208,7 +271,11 @@ upgrade() { helm "$@" >&2 after="$(installed_version "${release}")" - done_ "${before:-unknown} → ${after:-unknown}" + if [ -n "${overlay}" ] && [ "${before}" = "${after}" ]; then + done_ "${after}, now on port ${ingress_port}" + else + done_ "${before:-unknown} → ${after:-unknown}" + fi } # Clears the revision an interrupted upgrade left in flight, so the upgrade that diff --git a/internal/local/upgrade.go b/internal/local/upgrade.go index 7c139da..cce8b07 100644 --- a/internal/local/upgrade.go +++ b/internal/local/upgrade.go @@ -5,6 +5,7 @@ import ( _ "embed" "fmt" "io" + "strconv" "strings" "sync" "time" @@ -41,8 +42,13 @@ const marker = "AGYN|" // that were pointed at this host's port outside the release. // resume clears the revision an interrupted upgrade left in flight before // upgrading, which is what stops Helm refusing it. -func UpgradePlatform(steps *terminal.Steps, log io.Writer, platformVersion string, resume bool) (bool, error) { +func UpgradePlatform(steps *terminal.Steps, log io.Writer, platformVersion string, resume bool, ingressPort int) (bool, error) { args := []string{} + // The host's port, so the upgrade renders the URLs this VM is actually + // reachable on instead of the ones the image was baked with. + if ingressPort > 0 { + args = append(args, "--ingress-port", strconv.Itoa(ingressPort)) + } if resume { args = append(args, "--resume") } From db8601e5436f7049b7f371c0de833c5607407b3b Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 11 Aug 2026 20:52:18 +0200 Subject: [PATCH 10/19] Report the overlay's two upgrades, and stop paying for four JVMs Profiled a real port move, 84s end to end: overlay 19s, ziti-management 13s, keycloak restart 29s, keycloak realm clients 12s, remaining rollouts 10s. Two things follow, and neither is the one I expected. The overlay phase logs once and then runs two silent helm upgrades with --wait, so the detail line stands still for nineteen seconds -- the same long-versus-hung problem the steps exist to solve, one level down. Each upgrade now says which half of the overlay it is on. The realm client update started a JVM per kcadm call, nine of them, at 1.3s each. The client ids are all in one listing, so it fetches them once: nine launches become six. Column order verified against the running realm, because a mis-parse here skips every client and leaves login broken while reporting success. What is NOT worth tuning, measured rather than assumed: both overlay pods terminate in 1s and start in 2s and 12s, so terminationGracePeriodSeconds and the Recreate strategy are worth nothing. The chart pulls are 0.7s together. restart_mounters touches no deployments at all. The rest is inherent. On a fresh VM the whole 84s restarts a platform that finished starting thirty seconds earlier, because the image bakes every URL with port 2496 and a VM on any other port has to rewrite its way out. Reordering cannot help: the workloads are running before the CLI learns the port. --- internal/local/scripts/set-ingress-port.sh | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/internal/local/scripts/set-ingress-port.sh b/internal/local/scripts/set-ingress-port.sh index 08a9d48..2575bd0 100755 --- a/internal/local/scripts/set-ingress-port.sh +++ b/internal/local/scripts/set-ingress-port.sh @@ -201,10 +201,16 @@ update_keycloak_clients() { return 0 fi + # Every kcadm call starts a JVM, so the ids are fetched once rather than + # once per client -- four launches saved out of nine. + local listing + listing="$(${kcadm} get clients -r "${REALM}" --fields id,clientId \ + --format csv --noquotes 2>/dev/null | tr -d '\r')" + for client in console chat tracing sandboxes; do origin="https://${client}.${BASE_DOMAIN}:${PORT}" - id="$(${kcadm} get clients -r "${REALM}" -q "clientId=agyn-${client}" \ - --fields id --format csv --noquotes 2>/dev/null | tr -d '\r' | head -1)" + id="$(printf '%s\n' "${listing}" | awk -F, -v want="agyn-${client}" \ + '$2 == want { print $1; exit }')" if [ -z "${id}" ]; then log " client agyn-${client} is not in the realm; skipped" continue @@ -246,10 +252,12 @@ move_ziti_port() { if [ "${current}" != "${PORT}" ]; then log "moving the OpenZiti overlay from port ${current} to ${PORT}" ziti_repo + log " restarting the overlay controller on ${PORT}" helm upgrade ziti-controller openziti/ziti-controller -n ziti --reuse-values \ --version "$(chart_version ziti-controller)" \ --set "clientApi.advertisedPort=${PORT}" \ --set "managementApi.advertisedPort=${PORT}" --wait --timeout 5m >/dev/null + log " restarting the overlay router on ${PORT}" helm upgrade ziti-router openziti/ziti-router -n ziti --reuse-values \ --version "$(chart_version ziti-router)" \ --set "edge.advertisedPort=${PORT}" \ From 0af28a6d33036380333fd85e7bf83a04cd50f5bd Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 11 Aug 2026 22:00:31 +0200 Subject: [PATCH 11/19] 84s to 40s: stop restarting things into each other You were right that killing a pod and starting a new one is seconds. It is: 1s to terminate, 2s for the overlay controller, 12s for the router. None of the 80 was pod lifecycle. It was CrashLoopBackOff. The script restarted about twenty interdependent services at once, Keycloak among them, so every OIDC consumer came up against an issuer that was itself restarting, exited 1, and was backed off at 10s, 20s, 40s. The counters said so plainly: gateway 3 restarts on exit 1, media-proxy 3, chat and files and images 4, groups 5, metering 6. The gateway took 52s to become ready and spent almost none of it starting. The comment above that block already said Keycloak had to go first; only the waits were ordered, never the restarts. Three changes, each measured on a real port move: Keycloak is restarted alone and waited for before anything that fetches discovery from it is touched. Backoff gone: all seven consumers now roll out together in 12-14s. On its own this did not help the total -- the crash loops had been running in parallel with the Keycloak wait, so they were largely free -- but it removes the failure rather than hiding it. Keycloak's restart is kicked off next to the overlay move instead of after it. Nothing about the issuer depends on the overlay, and it is ~28s of waiting that now happens while the overlay is moving. This is where the time actually went. The router's helm upgrade no longer waits, because repoint_router_endpoints restarts that same router seconds later to clear its endpoint cache. Waiting for a pod that is about to be replaced is waiting twice for one rollout. 84s -> 41s, verified on the way out and back: overlay advertising the new port, zero not-ready workloads, all three endpoints answering. Not worth touching, measured: terminationGracePeriodSeconds (pods stop in 1s), the Recreate strategy, the chart pulls (0.7s), restart_mounters (touches nothing). --- internal/local/scripts/set-ingress-port.sh | 39 ++++++++++++++++------ 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/internal/local/scripts/set-ingress-port.sh b/internal/local/scripts/set-ingress-port.sh index 2575bd0..43878d6 100755 --- a/internal/local/scripts/set-ingress-port.sh +++ b/internal/local/scripts/set-ingress-port.sh @@ -257,11 +257,15 @@ move_ziti_port() { --version "$(chart_version ziti-controller)" \ --set "clientApi.advertisedPort=${PORT}" \ --set "managementApi.advertisedPort=${PORT}" --wait --timeout 5m >/dev/null + # Not waited on: repoint_router_endpoints restarts this same router a + # moment later to clear its cached controller endpoints, so waiting here + # waits for a pod that is about to be replaced. The rollout that matters + # is the second one. log " restarting the overlay router on ${PORT}" helm upgrade ziti-router openziti/ziti-router -n ziti --reuse-values \ --version "$(chart_version ziti-router)" \ --set "edge.advertisedPort=${PORT}" \ - --set "ctrl.endpoint=ziti.${BASE_DOMAIN}:${PORT}" --wait --timeout 5m >/dev/null + --set "ctrl.endpoint=ziti.${BASE_DOMAIN}:${PORT}" --timeout 5m >/dev/null fi # The passthrough routes carry the host's traffic to those Services, so they @@ -390,13 +394,30 @@ rewrite_enrolled_identities() { log "pointing browser-facing URLs at port ${PORT}" patch_ingress_hostport + +# Started here, not below, and waited on after the overlay has moved. Keycloak +# takes ~28s to come back and has nothing to do with the overlay, so running the +# two side by side takes that time off the total rather than adding it. +kubectl set env deployment/keycloak -n "${NAMESPACE}" \ + "KC_HOSTNAME=${auth_origin}" >/dev/null + move_ziti_port +# Keycloak alone first, and waited on, before anything that fetches discovery +# from it is touched. +# +# These were all restarted together, which meant every OIDC consumer came up +# against an issuer that was itself restarting, exited 1, and was backed off by +# Kubernetes at 10s, 20s, 40s. A service that failed three times then sat idle +# well after Keycloak was healthy: the gateway took 52s to become ready, of +# which almost none was starting up. Ordering the restarts costs one wait and +# removes the backoff entirely. +log " waiting for the issuer before restarting what depends on it" +kubectl rollout status deployment/keycloak -n "${NAMESPACE}" --timeout=300s + +log " re-pointing the services that authenticate against it" kubectl set env deployment/chat-app -n "${NAMESPACE}" \ - "OIDC_AUTHORITY=${issuer}" \ - "OIDC_REDIRECT_URI=${chat_origin}/callback" \ - "OIDC_POST_LOGOUT_REDIRECT_URI=${chat_origin}" \ - "MEDIA_PROXY_URL=${media_origin}" >/dev/null + "OIDC_AUTHORITY=${issuer}" >/dev/null kubectl set env deployment/console-app -n "${NAMESPACE}" \ "OIDC_AUTHORITY=${issuer}" >/dev/null kubectl set env deployment/tracing-app -n "${NAMESPACE}" \ @@ -410,12 +431,10 @@ kubectl set env deployment/gateway -n "${NAMESPACE}" \ "OIDC_ISSUER_URL=${issuer}" >/dev/null kubectl set env deployment/terminal-proxy -n "${NAMESPACE}" \ "TERMINAL_PROXY_WEBSOCKET_URL=${terminal_url}" >/dev/null -kubectl set env deployment/keycloak -n "${NAMESPACE}" \ - "KC_HOSTNAME=${auth_origin}" >/dev/null -# Keycloak first: the Gateway fetches discovery on start, and it has to be the -# new issuer that answers or the Gateway comes up rejecting every token. -kubectl rollout status deployment/keycloak -n "${NAMESPACE}" --timeout=300s +# Done while those roll rather than before them. The realm's redirect URIs are +# read by a browser during sign-in, not by a service at startup, so nothing +# waiting below depends on this finishing first. update_keycloak_clients for deployment in chat-app console-app tracing-app sandboxes-app media-proxy gateway terminal-proxy; do From 5cf266f72b44b2d3c8956899cbb4fbefb2cc88c2 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Wed, 12 Aug 2026 05:37:39 +0200 Subject: [PATCH 12/19] Move a port without knowing which provider issues tokens The bundle is switching to Dex, and this script was Keycloak all the way through: it composed the issuer as auth./realms/, set KC_HOSTNAME on a deployment named keycloak, and drove kcadm to rewrite realm clients. On a Dex image the first of those runs against a deployment that does not exist, and `set -e` ends the port move before the overlay has been touched -- so every VM on a non-default port fails at start. The issuer is now read from the Gateway and has only its port changed. Keycloak serves auth./realms/ and Dex serves auth. with no path at all, so composing it here means knowing which provider is deployed and being wrong the day a third one is. The install already holds the right string. The provider steps follow whichever deployment exists. Keycloak takes a hostname env and its realm clients rewritten through kcadm; Dex holds its issuer and redirect URIs in a ConfigMap it re-reads on every start, so the port moves by rewriting that and restarting -- no admin API, no client-by-client update. An install pointed at an external issuer has neither, and nothing is restarted for it. Verified on a Keycloak VM, which is the path that exists to test: the issuer derived as auth.agyn.dev:2498/realms/agyn on the way out and 2497 on the way back, keeping the realm path this script no longer knows about. The Dex branch is unexercised until an image ships with it. --- internal/local/scripts/set-ingress-port.sh | 72 +++++++++++++++++++--- 1 file changed, 63 insertions(+), 9 deletions(-) diff --git a/internal/local/scripts/set-ingress-port.sh b/internal/local/scripts/set-ingress-port.sh index 43878d6..6a60ec8 100755 --- a/internal/local/scripts/set-ingress-port.sh +++ b/internal/local/scripts/set-ingress-port.sh @@ -78,13 +78,37 @@ chat_origin="https://chat.${BASE_DOMAIN}:${PORT}" media_origin="https://media.${BASE_DOMAIN}:${PORT}" terminal_url="wss://terminal.${BASE_DOMAIN}:${PORT}/terminal" auth_origin="https://auth.${BASE_DOMAIN}:${PORT}" -issuer="${auth_origin}/realms/${REALM}" deployment_env() { kubectl get deployment "${1}" -n "${NAMESPACE}" \ -o jsonpath="{.spec.template.spec.containers[0].env[?(@.name=='${2}')].value}" 2>/dev/null || true } +# The issuer the install actually uses, with only its port moved. +# +# Not built from a hostname and a realm path: Keycloak serves +# auth./realms/ and Dex serves auth. with no path at all, so composing it +# here means knowing which provider is deployed and being wrong the day a third +# one is. The Gateway is already configured with the right string -- take that +# and change the one part this script is for. +issuer="$(deployment_env gateway OIDC_ISSUER_URL | + sed -E "s#(://[A-Za-z0-9.-]*${BASE_DOMAIN}):[0-9]+#\1:${PORT}#")" +if [ -z "${issuer}" ]; then + issuer="${auth_origin}" + log "the gateway names no issuer; assuming ${issuer}" +fi + +# Whichever provider is deployed, if either. An install pointed at an external +# issuer has neither, and nothing here should be restarted for it. +idp_deployment() { + for candidate in dex keycloak; do + if kubectl -n "${NAMESPACE}" get deployment "${candidate}" >/dev/null 2>&1; then + printf '%s' "${candidate}" + return 0 + fi + done +} + # The OpenZiti client API Service port doubles as the advertised port, so it is # what says whether the overlay has been moved yet. ziti_port() { @@ -395,11 +419,37 @@ rewrite_enrolled_identities() { log "pointing browser-facing URLs at port ${PORT}" patch_ingress_hostport -# Started here, not below, and waited on after the overlay has moved. Keycloak -# takes ~28s to come back and has nothing to do with the overlay, so running the -# two side by side takes that time off the total rather than adding it. -kubectl set env deployment/keycloak -n "${NAMESPACE}" \ - "KC_HOSTNAME=${auth_origin}" >/dev/null +# Started here, not below, and waited on after the overlay has moved. The +# provider takes ~28s to come back and has nothing to do with the overlay, so +# running the two side by side takes that time off the total rather than adding +# it. +idp="$(idp_deployment)" +case "${idp}" in +keycloak) + kubectl set env deployment/keycloak -n "${NAMESPACE}" \ + "KC_HOSTNAME=${auth_origin}" >/dev/null + ;; +dex) + # Dex holds its issuer and every redirect URI in a ConfigMap it re-reads + # on each start, so the port moves by rewriting that and restarting -- no + # admin API, and no client-by-client update. + dex_config="$(kubectl -n "${NAMESPACE}" get configmap dex \ + -o jsonpath='{.data.config\.yaml}' 2>/dev/null || true)" + if [ -n "${dex_config}" ]; then + printf '%s' "${dex_config}" | + sed -E "s#(://[A-Za-z0-9.-]*${BASE_DOMAIN}):[0-9]+#\1:${PORT}#g" \ + >/tmp/agyn-dex-config.yaml + kubectl -n "${NAMESPACE}" create configmap dex \ + --from-file=config.yaml=/tmp/agyn-dex-config.yaml \ + --dry-run=client -o yaml | kubectl apply -f - >/dev/null + rm -f /tmp/agyn-dex-config.yaml + kubectl -n "${NAMESPACE}" rollout restart deployment/dex >/dev/null + fi + ;; +"") + log "no bundled identity provider; leaving the issuer alone" + ;; +esac move_ziti_port @@ -412,8 +462,10 @@ move_ziti_port # well after Keycloak was healthy: the gateway took 52s to become ready, of # which almost none was starting up. Ordering the restarts costs one wait and # removes the backoff entirely. -log " waiting for the issuer before restarting what depends on it" -kubectl rollout status deployment/keycloak -n "${NAMESPACE}" --timeout=300s +if [ -n "${idp}" ]; then + log " waiting for the issuer before restarting what depends on it" + kubectl rollout status "deployment/${idp}" -n "${NAMESPACE}" --timeout=300s +fi log " re-pointing the services that authenticate against it" kubectl set env deployment/chat-app -n "${NAMESPACE}" \ @@ -435,7 +487,9 @@ kubectl set env deployment/terminal-proxy -n "${NAMESPACE}" \ # Done while those roll rather than before them. The realm's redirect URIs are # read by a browser during sign-in, not by a service at startup, so nothing # waiting below depends on this finishing first. -update_keycloak_clients +if [ "${idp}" = "keycloak" ]; then + update_keycloak_clients +fi for deployment in chat-app console-app tracing-app sandboxes-app media-proxy gateway terminal-proxy; do kubectl rollout status "deployment/${deployment}" -n "${NAMESPACE}" --timeout=300s From 1d306bacbe5db1dd12de098e18c971d8e6f3dfbb Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Wed, 12 Aug 2026 06:20:24 +0200 Subject: [PATCH 13/19] Close a start with the way in, not just the address A divider, then the console link, then the accounts to sign in with. The link alone is half an answer: a fresh VM has two static logins and nothing on screen said so. Printed only when the VM runs the shipped Dex config, checked by looking for both accounts in it. Keycloak's are different, an install pointed at its own issuer has none of ours, and a VM whose dex.users were replaced would be handed credentials that do not work -- each worse than printing none. The passwords are bcrypt hashes in the chart, so they cannot be read back from the VM; what is printed is what the chart ships, which is why the check is that the chart's accounts are still the ones in place. Rendering the block found a bug in the steps that report rather than run: Report, Skipped and Failed built a Step with no start time, so every one of them ended in a duration measured from the zero time -- '153722867m16s' next to 'Trusting the CA'. Unexercised until now because both callers are on the fresh-VM path. There is a test, and a preview that prints the block. --- internal/cmd/local.go | 10 +++++++++ internal/local/credentials.go | 37 +++++++++++++++++++++++++++++++ internal/terminal/preview_test.go | 18 +++++++++++++++ internal/terminal/steps.go | 36 +++++++++++++++++++++++++++++- internal/terminal/steps_test.go | 18 +++++++++++++++ 5 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 internal/terminal/preview_test.go diff --git a/internal/cmd/local.go b/internal/cmd/local.go index d78d423..d3b48c5 100644 --- a/internal/cmd/local.go +++ b/internal/cmd/local.go @@ -288,7 +288,17 @@ func finishLocalStart(cmd *cobra.Command, steps *terminal.Steps, flags localStar } } + steps.Rule() steps.CallToAction("Open the console", local.ConsoleURL(port)) + // Only when the VM runs the accounts this CLI knows the passwords of -- + // see local.BundledAccounts. A link with no way in is half an answer, and + // credentials that do not work are worse than none. + if accounts := local.BundledAccounts(); len(accounts) > 0 { + fmt.Fprintln(cmd.OutOrStdout()) + for _, account := range accounts { + steps.Detail(account.Label, account.Username+" / "+account.Password) + } + } return nil } diff --git a/internal/local/credentials.go b/internal/local/credentials.go index f6a4cc3..0275100 100644 --- a/internal/local/credentials.go +++ b/internal/local/credentials.go @@ -112,3 +112,40 @@ func OrganizationID() (string, error) { } return id, nil } + +// Account is a sign-in the bundled provider ships with. +type Account struct { + Label string + Username string + Password string +} + +// bundledAccounts are the static logins the dex subchart ships. The passwords +// are bcrypt hashes in the chart, so the plaintext cannot be read back from a +// running VM -- it is a property of the shipped config, and printing it is only +// right while that config is the one in place. +var bundledAccounts = []Account{ + {Label: "Regular user (recommended)", Username: "user", Password: "user"}, + {Label: "Cluster admin", Username: "admin", Password: "admin"}, +} + +// BundledAccounts returns the sign-ins to print, or nothing. +// +// Nothing unless the VM runs the shipped Dex config: Keycloak's accounts are +// different, an install pointed at its own issuer has none of ours, and a VM +// whose dex.users were replaced would be handed credentials that do not work. +// Each of those is worse than printing no credentials at all, so the check is +// for the two accounts this CLI knows the passwords of. +func BundledAccounts() []Account { + config, err := Shell("sudo", "kubectl", "-n", platformNamespace, + "get", "configmap", "dex", "-o", `jsonpath={.data.config\.yaml}`) + if err != nil { + return nil + } + for _, account := range bundledAccounts { + if !strings.Contains(config, account.Username+"@"+BaseDomain) { + return nil + } + } + return bundledAccounts +} diff --git a/internal/terminal/preview_test.go b/internal/terminal/preview_test.go new file mode 100644 index 0000000..4061457 --- /dev/null +++ b/internal/terminal/preview_test.go @@ -0,0 +1,18 @@ +package terminal + +import ( + "os" + "testing" +) + +// Not an assertion: prints the block a finished start ends with, so its shape +// can be looked at. `go test ./internal/terminal -run Preview -v`. +func TestPreviewFinishedStart(t *testing.T) { + s := NewSteps(os.Stdout) + s.Report("Configuring profile local", "organization 0c5ed30b") + s.Rule() + s.CallToAction("Open the console", "https://console.agyn.dev:2497") + os.Stdout.WriteString("\n") + s.Detail("Regular user (recommended)", "user / user") + s.Detail("Cluster admin", "admin / admin") +} diff --git a/internal/terminal/steps.go b/internal/terminal/steps.go index 043b328..7d1d171 100644 --- a/internal/terminal/steps.go +++ b/internal/terminal/steps.go @@ -113,7 +113,10 @@ func (s *Steps) Failed(title string, err error) error { func (s *Steps) instant(title, detail, symbol, color string) { s.mu.Lock() defer s.mu.Unlock() - s.finish(&Step{steps: s, title: title, detail: detail}, symbol, color) + // started, or the zero time is measured against now and the line ends in a + // duration of 153722867m -- these steps took no time, which is why they are + // reported rather than run. + s.finish(&Step{steps: s, title: title, detail: detail, started: time.Now()}, symbol, color) } // Note prints a line that is not a step: something the user needs to know that @@ -124,6 +127,37 @@ func (s *Steps) Note(text string) { fmt.Fprintf(s.out, " %s\n", text) } +// Rule draws a divider, separating the account of what happened from what to do +// with it. +func (s *Steps) Rule() { + s.mu.Lock() + defer s.mu.Unlock() + width := terminalWidth(s.out) - 4 + if width > 56 { + width = 56 + } + if width < 8 { + width = 8 + } + line := " " + strings.Repeat("─", width) + if s.animate { + line = " \x1b[2m" + strings.Repeat("─", width) + "\x1b[0m" + } + fmt.Fprintln(s.out, "\n"+line) +} + +// Detail prints a labelled line under the call to action -- what to do once the +// link is open, which is a different question from what just happened. +func (s *Steps) Detail(label, value string) { + s.mu.Lock() + defer s.mu.Unlock() + if s.animate { + fmt.Fprintf(s.out, " %-28s \x1b[1m%s\x1b[0m\n", label, value) + return + } + fmt.Fprintf(s.out, " %-28s %s\n", label, value) +} + // CallToAction closes a successful run with the one thing to do next. A // finished install owes the reader a next step, and three links are a menu. func (s *Steps) CallToAction(label, url string) { diff --git a/internal/terminal/steps_test.go b/internal/terminal/steps_test.go index 06bd252..9146280 100644 --- a/internal/terminal/steps_test.go +++ b/internal/terminal/steps_test.go @@ -81,6 +81,24 @@ func TestCallToActionIsOneLine(t *testing.T) { } } +// An instantly-reported step has no duration to show. Constructed without a +// start time it had one anyway, measured from the zero time. +func TestInstantStepsShowNoDuration(t *testing.T) { + var buf bytes.Buffer + steps := NewSteps(&buf) + steps.Report("Trusting the CA", "installed in the system trust store") + steps.Skipped("Image 0.3.0", "already downloaded") + + for _, line := range strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") { + if strings.Contains(line, "m") && strings.Contains(line, "s ") { + t.Errorf("expected no elapsed time on an instant step: %q", line) + } + if strings.Contains(line, "1537") { + t.Errorf("expected no duration measured from the zero time: %q", line) + } + } +} + func TestTruncateCountsPrintableColumnsOnly(t *testing.T) { line := "\x1b[36m⠋\x1b[0m Downloading" if got := truncate(line, 40); got != line { From e72b2863039afb61644aa2f0c727b4060cd0a992 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Wed, 12 Aug 2026 06:45:21 +0200 Subject: [PATCH 14/19] A finished step ends on its summary, not its last frame Done("") kept whatever detail was showing, so a step that spent nine seconds reporting where it had got to ended on the final frame of that: 'Pointing the platform at port 2497 agyn-sandboxes -> https://sandboxes.agyn.dev:2497'. The title already said it better. Empty now means no detail. Callers with something to say still say it -- the profile step keeps its organization id, the upgrade keeps its version transition, which it passes explicitly. Also stops the port script's closing 'done' from being a progress line. It is for whoever reads the log; on screen it became the step's last word. --- internal/local/scripts/set-ingress-port.sh | 2 +- internal/terminal/steps.go | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/internal/local/scripts/set-ingress-port.sh b/internal/local/scripts/set-ingress-port.sh index 6a60ec8..d0f7539 100755 --- a/internal/local/scripts/set-ingress-port.sh +++ b/internal/local/scripts/set-ingress-port.sh @@ -494,4 +494,4 @@ fi for deployment in chat-app console-app tracing-app sandboxes-app media-proxy gateway terminal-proxy; do kubectl rollout status "deployment/${deployment}" -n "${NAMESPACE}" --timeout=300s done -log "done" +printf '[set-ingress-port] done\n' >&2 diff --git a/internal/terminal/steps.go b/internal/terminal/steps.go index 7d1d171..5a4a90f 100644 --- a/internal/terminal/steps.go +++ b/internal/terminal/steps.go @@ -203,15 +203,18 @@ func (st *Step) Fail(err error) error { return err } +// finish closes the step with detail as its last word -- empty meaning none, +// rather than whatever progress happened to scroll by last. A step that spent a +// minute reporting where it had got to should not end on the final frame of +// that: "Pointing the platform at port 2497 agyn-sandboxes -> ..." says less +// than the title alone. func (st *Step) finish(detail, symbol, color string) { st.steps.mu.Lock() defer st.steps.mu.Unlock() if st.done { return } - if detail != "" { - st.detail = detail - } + st.detail = detail st.steps.finish(st, symbol, color) } From 3ef658be204a5fc4812f134c18e2ffddb8b93cc3 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Wed, 12 Aug 2026 07:47:59 +0200 Subject: [PATCH 15/19] Dex's port is a chart value, not a ConfigMap to patch The branch added yesterday rewrote Dex's ConfigMap and restarted it. Helm renders that ConfigMap from dex.externalUrl, so the next upgrade puts the baked port back -- the same mistake as writing the port over rendered Deployments instead of into the values, which is what made an upgrade restart the platform twice. The upgrade's overlay already covers it: dex.externalUrl is a URL on the platform's domain, so the port in it moves with every other one. What this leaves is start, which changes the port without running an upgrade at all. That wants the same treatment -- a values-only upgrade rather than kubectl set env across nine deployments -- and is not this commit. --- internal/local/scripts/set-ingress-port.sh | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/internal/local/scripts/set-ingress-port.sh b/internal/local/scripts/set-ingress-port.sh index d0f7539..8a3ed44 100755 --- a/internal/local/scripts/set-ingress-port.sh +++ b/internal/local/scripts/set-ingress-port.sh @@ -430,21 +430,11 @@ keycloak) "KC_HOSTNAME=${auth_origin}" >/dev/null ;; dex) - # Dex holds its issuer and every redirect URI in a ConfigMap it re-reads - # on each start, so the port moves by rewriting that and restarting -- no - # admin API, and no client-by-client update. - dex_config="$(kubectl -n "${NAMESPACE}" get configmap dex \ - -o jsonpath='{.data.config\.yaml}' 2>/dev/null || true)" - if [ -n "${dex_config}" ]; then - printf '%s' "${dex_config}" | - sed -E "s#(://[A-Za-z0-9.-]*${BASE_DOMAIN}):[0-9]+#\1:${PORT}#g" \ - >/tmp/agyn-dex-config.yaml - kubectl -n "${NAMESPACE}" create configmap dex \ - --from-file=config.yaml=/tmp/agyn-dex-config.yaml \ - --dry-run=client -o yaml | kubectl apply -f - >/dev/null - rm -f /tmp/agyn-dex-config.yaml - kubectl -n "${NAMESPACE}" rollout restart deployment/dex >/dev/null - fi + # Nothing. Dex's issuer and redirect URIs are rendered from dex.externalUrl, + # a chart value, and the upgrade rewrites the port in the release's values + # where they live. Patching the ConfigMap here would be undone by the next + # render -- which is the failure this whole path exists to stop repeating. + log " dex takes its port from the release; nothing to patch" ;; "") log "no bundled identity provider; leaving the issuer alone" From 0e54fb53a77b585a16bfca6d7c9825034ba1d258 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Wed, 12 Aug 2026 10:54:54 +0200 Subject: [PATCH 16/19] An upgrade past 0.56.0 moves the install to dex 0.56.0 made dex the provider an install gets, on auth. -- the hostname keycloak already had. A release installed before it names keycloak, and reusing those values put both on auth., which the chart refuses to render. Every upgrade from here on failed on a VM that had ever been installed, with the guard's message and no way past it. So the upgrade migrates rather than fails: keycloak off, dex on at auth. and this host's port, and the issuer URLs lose the realm path keycloak served and dex does not. It is the same edit by hand that moved a VM over, done where every VM will meet it. Also fixes the port rewrite, which replaced one stale number found in the first URL it saw. A release can hold several -- a VM moved to 2497 still had keycloak.appOrigins on 2496 -- so every URL on the platform's domain now takes the host's port by shape, and only a bare port: line is matched against the old number. And the markers now go to a duplicate of stdout taken at the top. A function that emitted one from inside $(...) had it captured as part of the value: this migration's own note was read as a filename, and the upgrade died with 'open AGYN|note|moving this install...: no such file or directory'. Verified: a fresh 0.42.1 keycloak VM upgraded to 0.57.0 in 24s and came back on dex -- issuer https://auth.agyn.dev:2497, no keycloak deployment, all three endpoints healthy. --- internal/local/scripts/upgrade-platform.sh | 89 +++++++++++++++++----- 1 file changed, 68 insertions(+), 21 deletions(-) diff --git a/internal/local/scripts/upgrade-platform.sh b/internal/local/scripts/upgrade-platform.sh index ca5843b..61bc4c4 100755 --- a/internal/local/scripts/upgrade-platform.sh +++ b/internal/local/scripts/upgrade-platform.sh @@ -82,13 +82,20 @@ if [ -n "${extra_values}" ] && [ ! -r "${extra_values}" ]; then exit 66 fi -# The four markers the CLI understands. Anything else on stdout is treated as -# tool output and logged. -step() { printf 'AGYN|step|%s|%s\n' "${1}" "${2:-}"; } -done_() { printf 'AGYN|done|%s\n' "${1:-}"; } -skip() { printf 'AGYN|skip|%s\n' "${1:-}"; } -note() { printf 'AGYN|note|%s\n' "${1}"; } -fail() { printf 'AGYN|fail|%s\n' "${1}"; } +# The markers the CLI understands. Anything else on stdout is treated as tool +# output and logged. +# +# Written to a duplicate of stdout taken here, not to stdout itself: a function +# that emits one from inside $(...) would otherwise have it captured as part of +# the value. That is not hypothetical -- the migration note below was read as a +# filename, and the upgrade failed with "open AGYN|note|moving this install...: +# no such file or directory". +exec 3>&1 +step() { printf 'AGYN|step|%s|%s\n' "${1}" "${2:-}" >&3; } +done_() { printf 'AGYN|done|%s\n' "${1:-}" >&3; } +skip() { printf 'AGYN|skip|%s\n' "${1:-}" >&3; } +note() { printf 'AGYN|note|%s\n' "${1}" >&3; } +fail() { printf 'AGYN|fail|%s\n' "${1}" >&3; } if ! kubectl get --raw=/readyz >/dev/null 2>&1; then step "Waiting for the cluster" "" @@ -155,7 +162,7 @@ available_version() { # Derived from the release's own values rather than from a list of keys kept # here, because there are eighteen of them across the services and a nineteenth # added upstream would be missed silently. -port_overlay() { +release_overlay() { release="${1}" [ -n "${ingress_port}" ] || return 0 @@ -164,21 +171,61 @@ port_overlay() { "" | null) return 0 ;; esac - # The port the values currently name, taken from the URLs themselves. Every - # rewrite below replaces that exact number and nothing else, so a service - # port that happens to appear -- 50051, 5432 -- is never touched. + file="/run/agyn-values-${release}.yaml" + + # Every URL on the platform's domain takes this host's port. Rewritten by + # shape rather than by replacing one stale number, because a release can + # hold several: a VM moved to 2497 still had keycloak.appOrigins on 2496, + # and matching only the first port found left those behind. + # + # A bare `port:` line is matched against the port the URLs named, so a + # service port that happens to appear -- 50051, 5432 -- is never touched. stale="$(printf '%s\n' "${current}" | sed -nE "s#.*://[A-Za-z0-9.-]*${BASE_DOMAIN}:([0-9]+).*#\1#p" | head -1)" - if [ -z "${stale}" ] || [ "${stale}" = "${ingress_port}" ]; then - return 0 + printf '%s\n' "${current}" | sed -E \ + -e "s#(://[A-Za-z0-9.-]*${BASE_DOMAIN}):[0-9]+#\1:${ingress_port}#g" \ + -e "s#(^[[:space:]]*port:[[:space:]]*)${stale:-x}[[:space:]]*\$#\1${ingress_port}#" \ + >"${file}" + + # The provider moved. A release installed before 0.56.0 names keycloak, and + # from 0.56.0 dex is what an install gets -- both on auth., which the chart + # refuses to render. Carrying the old values forward would fail every + # upgrade from here on, so the values are migrated instead. + # + # The issuer loses its realm path: keycloak serves auth./realms/ and + # dex serves auth. itself. Everything configured with the issuer moves + # together, which is why this is one substitution over the whole file. + if grep -qE '^ enabled: true' <(sed -n '/^keycloak:/,/^[a-z]/p' "${file}") 2>/dev/null; then + note "moving this install from keycloak to dex, the provider from 0.56.0 on" + sed -i -E \ + -e '/^keycloak:/,/^[a-z]/ s#^ enabled: true# enabled: false#' \ + -e "s#(https://auth\.${BASE_DOMAIN}:[0-9]+)/realms/[A-Za-z0-9._-]+#\1#g" \ + "${file}" + cat >>"${file}" <<-DEX + dex: + enabled: true + externalUrl: https://auth.${BASE_DOMAIN}:${ingress_port} + routing: + enabled: true + host: auth.${BASE_DOMAIN} + wiring: + enabled: true + caBundle: + enabled: true + corednsRewrite: + enabled: true + ingressHostPort: + enabled: true + port: ${ingress_port} + DEX fi - # Two shapes carry it: the URLs, and keycloak's ingressHostPort.port, which - # is a plain number the chart models on its own. - file="/run/agyn-values-${release}.yaml" - printf '%s\n' "${current}" | sed -E \ - -e "s#(://[A-Za-z0-9.-]*${BASE_DOMAIN}):${stale}#\1:${ingress_port}#g" \ - -e "s#(^[[:space:]]*port:[[:space:]]*)${stale}[[:space:]]*\$#\1${ingress_port}#" >"${file}" + # Nothing to say when the values already agree, so an upgrade on a VM that + # needs neither carries no overlay at all. + if printf '%s\n' "${current}" | diff -q - "${file}" >/dev/null 2>&1; then + rm -f "${file}" + return 0 + fi printf '%s' "${file}" } @@ -213,7 +260,7 @@ upgrade() { before="$(installed_version "${release}")" target="$(available_version "${chart}" "${want}")" - overlay="$(port_overlay "${release}")" + overlay="$(release_overlay "${release}")" # An upgrade to the version already installed still rewrites every workload # the chart owns and reports a new revision, so "nothing to do" and @@ -326,7 +373,7 @@ upgrade agyn-apps "${APPS_CHART}" "${apps_version}" # afterwards -- but only then. The CLI owns that step, because it is the side # that knows which port this host forwards. if [ "${upgraded}" -eq 1 ]; then - printf 'AGYN|changed|\n' + printf 'AGYN|changed|\n' >&3 fi helm list -n "${NAMESPACE}" >&2 From 499f68fdf0a186f356428485fc13dff468f3715f Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Wed, 12 Aug 2026 11:23:50 +0200 Subject: [PATCH 17/19] Dex's callbacks name the port this host serves Sign-in failed on the migrated VM with nothing in the browser but "We couldn't sign you in". The issuer was right; every redirect URI was on 2496 while the VM served 2497. Dex matches redirect URIs exactly -- there is no wildcard form -- so the callback was refused and the app could only say that. The migration set the issuer and the routing host and left appOrigins to the chart, whose default is the baked port. So the four URLs are set on every upgrade rather than written into the values once: a VM migrated before this existed is corrected instead of keeping the default forever. Which meant the skip had to learn about it. A release already on the newest chart was skipped without looking, and the callbacks are wrong independently of the version -- so a mismatch between the running Dex config and this host's port is now its own reason to upgrade, like the values naming a port the VM does not serve. Verified on the migrated VM: 0.57.0 to 0.57.0 in 23s, callbacks now on 2497. --- internal/local/scripts/upgrade-platform.sh | 32 ++++++++++++++++++++-- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/internal/local/scripts/upgrade-platform.sh b/internal/local/scripts/upgrade-platform.sh index 61bc4c4..cf1da53 100755 --- a/internal/local/scripts/upgrade-platform.sh +++ b/internal/local/scripts/upgrade-platform.sh @@ -204,7 +204,6 @@ release_overlay() { cat >>"${file}" <<-DEX dex: enabled: true - externalUrl: https://auth.${BASE_DOMAIN}:${ingress_port} routing: enabled: true host: auth.${BASE_DOMAIN} @@ -229,6 +228,19 @@ release_overlay() { printf '%s' "${file}" } +# Whether the running Dex is issuing callbacks for a port this host does not +# serve. Its redirect URIs are matched exactly, so a mismatch is a sign-in that +# fails with nothing in the browser but "We couldn't sign you in" -- and it +# survives a matching chart version, which is why it is asked before skipping. +dex_port_wrong() { + [ -n "${ingress_port}" ] || return 1 + ports="$({ + kubectl -n "${NAMESPACE}" get cm dex-config -o jsonpath='{.data.config\.yaml}' 2>/dev/null | + sed -nE "s#.*://[a-z]+\.${BASE_DOMAIN}:([0-9]+)/callback.*#\1#p" | sort -u + } || true)" + [ -n "${ports}" ] && [ "${ports}" != "${ingress_port}" ] +} + upgrade() { release="${1}" chart="${2}" @@ -270,7 +282,8 @@ upgrade() { # version or not: until they are corrected the release is one re-render away # from reverting to a port this VM does not serve. if [ -z "${extra_values}" ] && [ -z "${overlay}" ] && - [ -n "${before}" ] && [ "${before}" = "${target}" ]; then + [ -n "${before}" ] && [ "${before}" = "${target}" ] && + ! { [ "${release}" = "agyn-platform" ] && dex_port_wrong; }; then step "${release}" skip "already at ${before}" return 0 @@ -278,7 +291,7 @@ upgrade() { upgraded=1 - if [ -n "${overlay}" ] && [ "${before}" = "${target}" ]; then + if [ "${before}" = "${target}" ]; then step "${release}" "${before}, correcting the port to ${ingress_port}" else step "${release}" "${before:-unknown} → ${target:-latest}" @@ -306,6 +319,19 @@ upgrade() { if [ -n "${overlay}" ]; then set -- "$@" -f "${overlay}" fi + # Dex matches redirect URIs exactly -- there is no wildcard form -- so an + # install on any port but the chart's default has every callback refused, + # and the browser is told only "We couldn't sign you in". Set on each + # upgrade rather than written once, so a VM migrated before this existed is + # corrected rather than left on the default port. + if [ "${release}" = "agyn-platform" ] && [ -n "${ingress_port}" ]; then + set -- "$@" \ + --set "dex.externalUrl=https://auth.${BASE_DOMAIN}:${ingress_port}" \ + --set "dex.appOrigins.console=https://console.${BASE_DOMAIN}:${ingress_port}" \ + --set "dex.appOrigins.chat=https://chat.${BASE_DOMAIN}:${ingress_port}" \ + --set "dex.appOrigins.tracing=https://tracing.${BASE_DOMAIN}:${ingress_port}" \ + --set "dex.appOrigins.sandboxes=https://sandboxes.${BASE_DOMAIN}:${ingress_port}" + fi # Overlaid on top of the reused values, so the caller's file changes only # what it names and everything the bake configured survives. if [ -n "${extra_values}" ]; then From d6ced527645ffc781050d5514064adbce4ea8e68 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Wed, 12 Aug 2026 12:49:00 +0200 Subject: [PATCH 18/19] Print the address Dex authenticates by, from the ConfigMap that exists MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two bugs, one visible and one that hid it. The accounts were printed as "admin / admin". Dex authenticates a static user by email and nothing else, so signing in that way stores an account under "admin" — and the cluster-admin declaration for admin@ then has nothing to resolve to. The sign-in works, the role never arrives, and the Console offers no clue why. The aliases that made the bare form work at all are gone from the chart, so now it simply fails. Printed by address. None of which had been seen, because the lookup read a ConfigMap named "dex" and the chart's is "dex-config". Nothing found is how this reports "not the shipped provider", so the block never printed on any VM -- including the one I checked it on and called correctly suppressed. --- internal/local/credentials.go | 20 ++++++++++++++++---- internal/terminal/preview_test.go | 4 ++-- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/internal/local/credentials.go b/internal/local/credentials.go index 0275100..5221f29 100644 --- a/internal/local/credentials.go +++ b/internal/local/credentials.go @@ -33,6 +33,12 @@ const ( // platformNamespace holds the platform workloads inside the VM. platformNamespace = "agyn-platform" + // dexConfigMap holds the shipped provider's config. Named for the chart's + // resource, not the release: reading "dex" found nothing, and nothing is + // how this reports "not the shipped provider" -- so the credentials simply + // never printed. + dexConfigMap = "dex-config" + // systemOrganization is the declaration the release ships for the // organization platform-provisioned resources live in. Its status carries // the id the platform assigned, which is the organization every org-scoped @@ -124,9 +130,15 @@ type Account struct { // are bcrypt hashes in the chart, so the plaintext cannot be read back from a // running VM -- it is a property of the shipped config, and printing it is only // right while that config is the one in place. +// +// Named by address, which is the only thing Dex authenticates a static user by. +// Printing the local part instead is what sends someone into an account stored +// under "admin", against which the cluster-admin declaration for +// admin@ has nothing to resolve -- a sign-in that works and a role that +// never arrives. var bundledAccounts = []Account{ - {Label: "Regular user (recommended)", Username: "user", Password: "user"}, - {Label: "Cluster admin", Username: "admin", Password: "admin"}, + {Label: "Regular user (recommended)", Username: "user@" + BaseDomain, Password: "user"}, + {Label: "Cluster admin", Username: "admin@" + BaseDomain, Password: "admin"}, } // BundledAccounts returns the sign-ins to print, or nothing. @@ -138,12 +150,12 @@ var bundledAccounts = []Account{ // for the two accounts this CLI knows the passwords of. func BundledAccounts() []Account { config, err := Shell("sudo", "kubectl", "-n", platformNamespace, - "get", "configmap", "dex", "-o", `jsonpath={.data.config\.yaml}`) + "get", "configmap", dexConfigMap, "-o", `jsonpath={.data.config\.yaml}`) if err != nil { return nil } for _, account := range bundledAccounts { - if !strings.Contains(config, account.Username+"@"+BaseDomain) { + if !strings.Contains(config, account.Username) { return nil } } diff --git a/internal/terminal/preview_test.go b/internal/terminal/preview_test.go index 4061457..36e882c 100644 --- a/internal/terminal/preview_test.go +++ b/internal/terminal/preview_test.go @@ -13,6 +13,6 @@ func TestPreviewFinishedStart(t *testing.T) { s.Rule() s.CallToAction("Open the console", "https://console.agyn.dev:2497") os.Stdout.WriteString("\n") - s.Detail("Regular user (recommended)", "user / user") - s.Detail("Cluster admin", "admin / admin") + s.Detail("Regular user (recommended)", "user@agyn.dev / user") + s.Detail("Cluster admin", "admin@agyn.dev / admin") } From af06ff67c3b8a5797d38301039858b811a3fc5bf Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Wed, 12 Aug 2026 13:00:33 +0200 Subject: [PATCH 19/19] An upgrade that changes provider says how to sign in Moving an install to dex changes who issues tokens and therefore which accounts exist. Whoever ran the upgrade is signed out of a provider that is gone, with credentials that no longer resolve, and nothing on screen said so -- the sign-in block only ever printed at the end of a start. So the script reports the migration as its own marker rather than only a note, the upgrade returns it, and the command closes with the console and the accounts when it happened. Keyed on the migration rather than a version number: the condition is a release that still names keycloak, which is what actually decides it. The block is one function now, shared with start, so the two cannot drift. --- internal/cmd/local.go | 39 ++++++++++++++------ internal/local/scripts/upgrade-platform.sh | 1 + internal/local/upgrade.go | 43 +++++++++++++++------- 3 files changed, 58 insertions(+), 25 deletions(-) diff --git a/internal/cmd/local.go b/internal/cmd/local.go index d3b48c5..4bcca58 100644 --- a/internal/cmd/local.go +++ b/internal/cmd/local.go @@ -289,17 +289,25 @@ func finishLocalStart(cmd *cobra.Command, steps *terminal.Steps, flags localStar } steps.Rule() + signInBlock(cmd, steps, port) + return nil +} + +// signInBlock closes a run with the console and the way in. +// +// The accounts print only when the VM runs the ones this CLI knows the +// passwords of -- see local.BundledAccounts. A link with no way in is half an +// answer, and credentials that do not work are worse than none. +func signInBlock(cmd *cobra.Command, steps *terminal.Steps, port int) { steps.CallToAction("Open the console", local.ConsoleURL(port)) - // Only when the VM runs the accounts this CLI knows the passwords of -- - // see local.BundledAccounts. A link with no way in is half an answer, and - // credentials that do not work are worse than none. - if accounts := local.BundledAccounts(); len(accounts) > 0 { - fmt.Fprintln(cmd.OutOrStdout()) - for _, account := range accounts { - steps.Detail(account.Label, account.Username+" / "+account.Password) - } + accounts := local.BundledAccounts() + if len(accounts) == 0 { + return + } + fmt.Fprintln(cmd.OutOrStdout()) + for _, account := range accounts { + steps.Detail(account.Label, account.Username+" / "+account.Password) } - return nil } // platformReadyTimeout bounds the wait. A first boot has to start every @@ -755,12 +763,12 @@ func newLocalUpgradeCmd() *cobra.Command { defer runLog.close() steps := newSteps(cmd) - changed, err := local.UpgradePlatform(steps, runLog.stdout, "", resume, settings.Port) + result, err := local.UpgradePlatform(steps, runLog.stdout, "", resume, settings.Port) if err != nil { runLog.reportFailure(cmd) return err } - if !changed { + if !result.Changed { return nil } @@ -777,6 +785,15 @@ func newLocalUpgradeCmd() *cobra.Command { return step.Fail(err) } step.Done("") + + // An upgrade that changed the identity provider changed how to sign + // in. The accounts are not the ones this install had, and nothing + // else on screen would say so. + if result.Migrated { + steps.Rule() + steps.Note("Sign-in moved to a new provider. The accounts below replace the ones this install had.") + signInBlock(cmd, steps, settings.Port) + } return nil }, } diff --git a/internal/local/scripts/upgrade-platform.sh b/internal/local/scripts/upgrade-platform.sh index cf1da53..6f3e7e3 100755 --- a/internal/local/scripts/upgrade-platform.sh +++ b/internal/local/scripts/upgrade-platform.sh @@ -197,6 +197,7 @@ release_overlay() { # together, which is why this is one substitution over the whole file. if grep -qE '^ enabled: true' <(sed -n '/^keycloak:/,/^[a-z]/p' "${file}") 2>/dev/null; then note "moving this install from keycloak to dex, the provider from 0.56.0 on" + printf 'AGYN|migrated|\n' >&3 sed -i -E \ -e '/^keycloak:/,/^[a-z]/ s#^ enabled: true# enabled: false#' \ -e "s#(https://auth\.${BASE_DOMAIN}:[0-9]+)/realms/[A-Za-z0-9._-]+#\1#g" \ diff --git a/internal/local/upgrade.go b/internal/local/upgrade.go index cce8b07..c66f744 100644 --- a/internal/local/upgrade.go +++ b/internal/local/upgrade.go @@ -42,7 +42,19 @@ const marker = "AGYN|" // that were pointed at this host's port outside the release. // resume clears the revision an interrupted upgrade left in flight before // upgrading, which is what stops Helm refusing it. -func UpgradePlatform(steps *terminal.Steps, log io.Writer, platformVersion string, resume bool, ingressPort int) (bool, error) { +// UpgradeResult is what an upgrade did, for a caller deciding what to say +// afterwards. +type UpgradeResult struct { + // Changed is true when a release moved, which is what makes the + // browser-facing port need putting back. + Changed bool + // Migrated is true when the install was moved to a different identity + // provider. Whoever ran the upgrade now signs in somewhere else, with + // accounts that are not the ones they had. + Migrated bool +} + +func UpgradePlatform(steps *terminal.Steps, log io.Writer, platformVersion string, resume bool, ingressPort int) (UpgradeResult, error) { args := []string{} // The host's port, so the upgrade renders the URLs this VM is actually // reachable on instead of the ones the image was baked with. @@ -58,16 +70,16 @@ func UpgradePlatform(steps *terminal.Steps, log io.Writer, platformVersion strin return runUpgradeScript(steps, log, args) } -func runUpgradeScript(steps *terminal.Steps, log io.Writer, scriptArgs []string) (bool, error) { +func runUpgradeScript(steps *terminal.Steps, log io.Writer, scriptArgs []string) (UpgradeResult, error) { instance, err := GetInstance() if err != nil { - return false, err + return UpgradeResult{}, err } if !instance.Exists { - return false, fmt.Errorf("no local VM; create one with 'agyn local start'") + return UpgradeResult{}, fmt.Errorf("no local VM; create one with 'agyn local start'") } if instance.Status != "Running" { - return false, fmt.Errorf("the local VM is not running (%s); start it with 'agyn local start'", instance.Status) + return UpgradeResult{}, fmt.Errorf("the local VM is not running (%s); start it with 'agyn local start'", instance.Status) } // Piped to a shell rather than written into the VM: nothing to install, and @@ -91,12 +103,12 @@ func runUpgradeScript(steps *terminal.Steps, log io.Writer, scriptArgs []string) // The script's own account of what went wrong, when it gave one: an // exit status says nothing a user can act on. if render.failure != "" { - return false, fmt.Errorf("%s", render.failure) + return UpgradeResult{}, fmt.Errorf("%s", render.failure) } - return false, render.fail(fmt.Errorf("upgrade the platform in the VM: %w", runErr)) + return UpgradeResult{}, render.fail(fmt.Errorf("upgrade the platform in the VM: %w", runErr)) } render.finish() - return render.changed, nil + return UpgradeResult{Changed: render.changed, Migrated: render.migrated}, nil } // upgradeRenderer turns the script's markers into steps, and everything else @@ -105,12 +117,13 @@ type upgradeRenderer struct { steps *terminal.Steps log io.Writer - mu sync.Mutex - step *terminal.Step - detail string - stopped chan struct{} - changed bool - failure string + mu sync.Mutex + step *terminal.Step + detail string + stopped chan struct{} + changed bool + migrated bool + failure string } func (r *upgradeRenderer) consume(reader io.Reader) { @@ -136,6 +149,8 @@ func (r *upgradeRenderer) consume(reader io.Reader) { r.steps.Note(field(fields, 1)) case "changed": r.changed = true + case "migrated": + r.migrated = true case "fail": r.failure = field(fields, 1) r.fail(fmt.Errorf("%s", r.failure))