Open setup screens or a console when llmgw runs bare in a terminal
With nothing installed, sudo llmgw asks for one machine or three, takes how to reach the other two (ssh agent, key or password, and a sudo password used only for the install), checks every machine first, shows the plan and its command line, and installs. On a control plane it opens a console with the cluster's state and the next steps. Machines are reached with Go's ssh so a password works; the store's etcd and access rules use this machine's routed address rather than a client-facing name. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
975c93994f
commit
38f2671ed9
13 files changed
+1954
-5
No files matched your search
@@ -30,6 +30,14 @@ func Root() *cobra.Command {
|
||||
PersistentPreRun: func(_ *cobra.Command, _ []string) {
|
||||
obs.Setup(obs.Options{Level: global.logLevel, Format: global.logFormat})
|
||||
},
|
||||
// Bare, in a terminal: the setup screens or the console. Otherwise
|
||||
// the help, as before.
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
if interactive(cmd) {
|
||||
return runHome(cmd)
|
||||
}
|
||||
return cmd.Help()
|
||||
},
|
||||
}
|
||||
|
||||
pf := root.PersistentFlags()
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/account"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/config"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/pgha"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/tlsconf"
|
||||
)
|
||||
@@ -72,6 +73,10 @@ type serverInit struct {
|
||||
// patroni are user@host of the machines to keep the store on under
|
||||
// Patroni, replicated; this machine is the third etcd vote for two.
|
||||
patroni []string
|
||||
// patroniNodes are the same machines already connected to, which the
|
||||
// setup screen does with the password it was given; when set, patroni
|
||||
// only names them.
|
||||
patroniNodes []pgha.Node
|
||||
// noMirror, noNode and noModel turn off the parts of a first install that
|
||||
// make it serve something: a mirror, this machine as a node, and a small
|
||||
// model on it.
|
||||
@@ -89,14 +94,19 @@ type serverInit struct {
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newServerInitCmd() *cobra.Command {
|
||||
in := serverInit{
|
||||
// newDefaultServerInit is init as it sets up a real machine.
|
||||
func newDefaultServerInit() serverInit {
|
||||
return serverInit{
|
||||
etcDir: "/etc/llmgw",
|
||||
stateDir: "/var/lib/llmgw",
|
||||
pkiDir: defaultPKIDir,
|
||||
unitPath: "/etc/systemd/system/llmgw-server.service",
|
||||
user: "llmgw",
|
||||
}
|
||||
}
|
||||
|
||||
func newServerInitCmd() *cobra.Command {
|
||||
in := newDefaultServerInit()
|
||||
var plain bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "init",
|
||||
|
||||
@@ -26,7 +26,11 @@ func (in *serverInit) ensurePatroni(ctx context.Context) (err error) {
|
||||
in.kept("%s: %s", step, detail)
|
||||
}
|
||||
}}
|
||||
setup.DB = in.patroniNodes
|
||||
for _, t := range in.patroni {
|
||||
if len(in.patroniNodes) > 0 {
|
||||
break
|
||||
}
|
||||
user, host, ok := strings.Cut(t, "@")
|
||||
if !ok {
|
||||
user, host = "", t
|
||||
@@ -46,7 +50,7 @@ func (in *serverInit) ensurePatroni(ctx context.Context) (err error) {
|
||||
Remote: remote,
|
||||
})
|
||||
}
|
||||
self, err := ipv4Of(in.reachableAddr())
|
||||
self, err := sourceIPToward(setup.DB[0].IP)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -146,6 +150,19 @@ func (in *serverInit) moveInto(ctx context.Context, from, to string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// sourceIPToward is this machine's address on the route to another: the one
|
||||
// the other machine sees it connect from, which is what etcd advertises and
|
||||
// what the database lets in. Not the first --host, which names the gateway
|
||||
// for its clients and may not resolve yet, or resolve to a floating address.
|
||||
func sourceIPToward(ip string) (string, error) {
|
||||
c, err := net.Dial("udp", net.JoinHostPort(ip, "5432"))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("no route from this machine to %s: %w", ip, err)
|
||||
}
|
||||
defer c.Close()
|
||||
return c.LocalAddr().(*net.UDPAddr).IP.String(), nil
|
||||
}
|
||||
|
||||
// ipv4Of is the address a host name or address stands for, as the other
|
||||
// machines will be told to reach it.
|
||||
func ipv4Of(host string) (string, error) {
|
||||
|
||||
@@ -44,7 +44,7 @@ func (in *serverInit) storeAddress() string {
|
||||
// means reissuing every key and being unable to say which was which; and the
|
||||
// administrator init created a minute ago would be gone too.
|
||||
func (in *serverInit) ensureDatabase(ctx context.Context) (err error) {
|
||||
if len(in.patroni) > 0 {
|
||||
if len(in.patroni) > 0 || len(in.patroniNodes) > 0 {
|
||||
if in.postgres {
|
||||
return fmt.Errorf("--postgres keeps the store on this machine and --patroni on others: give one")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/mattn/go-isatty"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/config"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/control/adminapi"
|
||||
)
|
||||
|
||||
// A bare `llmgw` in a terminal: the setup screens on a machine with nothing
|
||||
// installed, the console on a control plane. Anywhere else — a pipe, a
|
||||
// script, another operating system — it prints its help, as it always did.
|
||||
|
||||
func interactive(cmd *cobra.Command) bool {
|
||||
return isTerminal(cmd.OutOrStdout()) && isatty.IsTerminal(os.Stdin.Fd())
|
||||
}
|
||||
|
||||
func runHome(cmd *cobra.Command) error {
|
||||
out := cmd.OutOrStdout()
|
||||
if runtime.GOOS != "linux" {
|
||||
fmt.Fprintln(out, "The setup and console screens run on the Linux machine they manage.")
|
||||
fmt.Fprintln(out)
|
||||
return cmd.Help()
|
||||
}
|
||||
if os.Geteuid() != 0 {
|
||||
return errors.New("run it as root — sudo llmgw — since it installs software and holds the certificate authority")
|
||||
}
|
||||
switch {
|
||||
// Installed is the service in place, not only its configuration: a setup
|
||||
// that stopped halfway has written server.yaml and nothing that runs, and
|
||||
// the setup screens are what finish it.
|
||||
case exists("/etc/llmgw/server.yaml") && exists("/etc/systemd/system/llmgw-server.service"):
|
||||
return runConsole(cmd.Context(), out)
|
||||
case exists("/etc/llmgw/agent.yaml"):
|
||||
fmt.Fprintln(out, "This machine is a node. Its cluster is managed from the control plane:")
|
||||
fmt.Fprintln(out, "run llmgw there. Here, `llmgw doctor` checks the machine.")
|
||||
return nil
|
||||
}
|
||||
return runSetupTUI(cmd.Context(), out)
|
||||
}
|
||||
|
||||
func exists(p string) bool {
|
||||
_, err := os.Stat(p)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// What the console asks to be done once its screen closes: each runs its own
|
||||
// screen, and the console comes back after.
|
||||
type consoleAction struct {
|
||||
kind string // "", "node", "patroni"
|
||||
targets []string
|
||||
}
|
||||
|
||||
type summaryMsg struct {
|
||||
text string
|
||||
store bool
|
||||
err error
|
||||
}
|
||||
|
||||
type consoleItem struct {
|
||||
label, command, ask string
|
||||
kind string
|
||||
n int // how many targets to ask for
|
||||
}
|
||||
|
||||
type consoleModel struct {
|
||||
client *ctlClient
|
||||
summary string
|
||||
store bool
|
||||
err error
|
||||
focus int
|
||||
asking bool
|
||||
asked []string
|
||||
prompt textField
|
||||
action consoleAction
|
||||
width int
|
||||
spin spinnerModel
|
||||
loaded bool
|
||||
}
|
||||
|
||||
func (m consoleModel) items() []consoleItem {
|
||||
its := []consoleItem{{label: "Add a node", kind: "node", n: 1,
|
||||
ask: "user@address of the machine", command: "sudo llmgw node add <user>@<address>"}}
|
||||
if !m.store {
|
||||
its = append(its, consoleItem{label: "Replicate the store across two machines (Patroni)", kind: "patroni", n: 2,
|
||||
ask: "user@address of database machine",
|
||||
command: "sudo --preserve-env=SSH_AUTH_SOCK llmgw server init --patroni <user>@<a> --patroni <user>@<b> --no-mirror --no-node --no-model"})
|
||||
}
|
||||
return append(its, consoleItem{label: "Leave", kind: "quit"})
|
||||
}
|
||||
|
||||
func (m consoleModel) fetch() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
var s adminapi.Summary
|
||||
if err := m.client.get(ctx, "/api/v1/summary", &s); err != nil {
|
||||
return summaryMsg{err: err}
|
||||
}
|
||||
var b bytes.Buffer
|
||||
c := &cobra.Command{}
|
||||
c.SetOut(&b)
|
||||
printSummary(c, s)
|
||||
return summaryMsg{text: b.String(), store: len(s.Store) > 0}
|
||||
}
|
||||
|
||||
func (m consoleModel) Init() tea.Cmd { return tea.Batch(m.fetch, m.spin.Tick) }
|
||||
|
||||
func (m consoleModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case tea.WindowSizeMsg:
|
||||
m.width = msg.Width
|
||||
case spinTickMsg:
|
||||
var cmd tea.Cmd
|
||||
m.spin, cmd = m.spin.Update(msg)
|
||||
return m, cmd
|
||||
case summaryMsg:
|
||||
m.loaded = true
|
||||
m.err = msg.err
|
||||
if msg.err == nil {
|
||||
m.summary, m.store = msg.text, msg.store
|
||||
}
|
||||
return m, tea.Tick(5*time.Second, func(time.Time) tea.Msg { return m.fetch() })
|
||||
case tea.KeyMsg:
|
||||
if msg.Type == tea.KeyCtrlC {
|
||||
return m, tea.Quit
|
||||
}
|
||||
its := m.items()
|
||||
if m.asking {
|
||||
switch msg.Type {
|
||||
case tea.KeyEsc:
|
||||
m.asking, m.asked = false, nil
|
||||
case tea.KeyEnter:
|
||||
v := strings.TrimSpace(m.prompt.Value())
|
||||
if v == "" {
|
||||
return m, nil
|
||||
}
|
||||
m.asked = append(m.asked, v)
|
||||
m.prompt.SetValue("")
|
||||
if it := its[m.focus]; len(m.asked) == it.n {
|
||||
m.action = consoleAction{kind: it.kind, targets: m.asked}
|
||||
return m, tea.Quit
|
||||
}
|
||||
default:
|
||||
var cmd tea.Cmd
|
||||
m.prompt, cmd = m.prompt.Update(msg)
|
||||
return m, cmd
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
switch msg.String() {
|
||||
case "up", "k", "shift+tab":
|
||||
m.focus = (m.focus - 1 + len(its)) % len(its)
|
||||
case "down", "j", "tab":
|
||||
m.focus = (m.focus + 1) % len(its)
|
||||
case "q":
|
||||
return m, tea.Quit
|
||||
case "enter":
|
||||
it := its[m.focus]
|
||||
if it.kind == "quit" {
|
||||
return m, tea.Quit
|
||||
}
|
||||
m.asking, m.asked = true, nil
|
||||
m.prompt = newTextField()
|
||||
m.prompt.Placeholder, m.prompt.Width = "ubuntu@10.0.0.20", 40
|
||||
m.prompt.Focus()
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (m consoleModel) View() string {
|
||||
var b strings.Builder
|
||||
host, _ := os.Hostname()
|
||||
b.WriteString(sTitle.Render("llmgw · console") + " " + sDim.Render(host) + "\n\n")
|
||||
switch {
|
||||
case !m.loaded:
|
||||
b.WriteString(" " + m.spin.View() + " asking the control plane…\n")
|
||||
case m.err != nil:
|
||||
b.WriteString(sBad.Render("The control plane does not answer: ") + m.err.Error() + "\n" +
|
||||
sDim.Render("systemctl status llmgw-server says why.") + "\n")
|
||||
default:
|
||||
b.WriteString(m.summary)
|
||||
}
|
||||
b.WriteString("\n" + lipgloss.NewStyle().Bold(true).Render("Do") + "\n")
|
||||
for i, it := range m.items() {
|
||||
line := " " + it.label
|
||||
if i == m.focus {
|
||||
line = sTitle.Render("› " + it.label)
|
||||
}
|
||||
b.WriteString(line + "\n")
|
||||
if i == m.focus && it.command != "" {
|
||||
b.WriteString(" " + sDim.Render(it.command) + "\n")
|
||||
}
|
||||
}
|
||||
if m.asking {
|
||||
it := m.items()[m.focus]
|
||||
ask := it.ask
|
||||
if it.n > 1 {
|
||||
ask = fmt.Sprintf("%s %d of %d", ask, len(m.asked)+1, it.n)
|
||||
}
|
||||
b.WriteString("\n" + ask + "\n " + m.prompt.View() + "\n" + sDim.Render("enter · esc to cancel") + "\n")
|
||||
} else {
|
||||
b.WriteString("\n" + sDim.Render("↑↓ to choose · enter · q to leave · refreshed every five seconds") + "\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// runConsole shows the console, runs what is chosen on it, and comes back.
|
||||
func runConsole(ctx context.Context, out io.Writer) error {
|
||||
addr := "127.0.0.1:9090"
|
||||
if cfg, err := config.Load("/etc/llmgw/server.yaml"); err == nil && cfg.AdminListen != "" {
|
||||
addr = cfg.AdminListen
|
||||
if strings.HasPrefix(addr, ":") {
|
||||
addr = "127.0.0.1" + addr
|
||||
}
|
||||
}
|
||||
for {
|
||||
m := consoleModel{client: newCtlClient(addr), spin: newSpinner(), width: 100}
|
||||
final, err := tea.NewProgram(m, tea.WithOutput(out)).Run()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
act := final.(consoleModel).action
|
||||
switch act.kind {
|
||||
case "":
|
||||
return nil
|
||||
case "node":
|
||||
c := newNodeAddCmd()
|
||||
c.SetArgs(act.targets)
|
||||
c.SetOut(out)
|
||||
err = c.ExecuteContext(ctx)
|
||||
case "patroni":
|
||||
in := newDefaultServerInit()
|
||||
in.patroni = act.targets
|
||||
// Already set up: only the store changes.
|
||||
in.noMirror, in.noNode, in.noModel = true, true, true
|
||||
err = in.runInitTUI(ctx, out)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(out, sBad.Render("✗ ")+err.Error())
|
||||
}
|
||||
fmt.Fprint(out, "\n"+sDim.Render("enter to go back to the console")+" ")
|
||||
_, _ = bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,741 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/mail"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/onboard"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/pgha"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/preflight"
|
||||
)
|
||||
|
||||
// The setup screens: what a bare `llmgw` shows on a machine with nothing
|
||||
// installed. One machine, or three for high availability — this one as the
|
||||
// control plane and etcd's third vote, two more for the store under Patroni —
|
||||
// with every machine checked before anything is installed on any of them.
|
||||
//
|
||||
// The other machines are reached with Go's own ssh rather than the system's,
|
||||
// so a password can be typed here when there is no key; it is held in memory
|
||||
// for the run and written nowhere. A sudo password, likewise, is used once to
|
||||
// let the user sudo for the length of the install, and that is taken back
|
||||
// when it finishes.
|
||||
|
||||
type setupPage int
|
||||
|
||||
const (
|
||||
pWelcome setupPage = iota
|
||||
pAdmin
|
||||
pMachines
|
||||
pCheck
|
||||
pPlan
|
||||
pRun
|
||||
)
|
||||
|
||||
// How a database machine is logged into.
|
||||
const (
|
||||
authAgent = iota
|
||||
authKey
|
||||
authPassword
|
||||
authCount
|
||||
)
|
||||
|
||||
var authNames = [authCount]string{"ssh agent", "key file", "password"}
|
||||
|
||||
// Fields of one database machine, in order.
|
||||
const (
|
||||
mfAddr = iota
|
||||
mfUser
|
||||
mfAuth
|
||||
mfSecret
|
||||
mfSudo
|
||||
mfCount
|
||||
)
|
||||
|
||||
type dbMachine struct {
|
||||
addr, user, secret, sudo textField
|
||||
auth int
|
||||
}
|
||||
|
||||
func newDBMachine(n int) dbMachine {
|
||||
f := func(ph string, mask bool) textField {
|
||||
t := newTextField()
|
||||
t.Placeholder, t.Mask, t.CharLimit, t.Width = ph, mask, 200, 34
|
||||
return t
|
||||
}
|
||||
m := dbMachine{
|
||||
addr: f(fmt.Sprintf("10.0.0.%d or db%d.internal", 10+n, n), false),
|
||||
user: f("ubuntu", false),
|
||||
secret: f("", true),
|
||||
sudo: f("only if sudo asks for one", true),
|
||||
}
|
||||
if os.Getenv("SSH_AUTH_SOCK") == "" {
|
||||
m.auth = authKey
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// field is the text field at a machine's position, nil for the selector.
|
||||
func (d *dbMachine) field(i int) *textField {
|
||||
switch i {
|
||||
case mfAddr:
|
||||
return &d.addr
|
||||
case mfUser:
|
||||
return &d.user
|
||||
case mfSecret:
|
||||
return &d.secret
|
||||
case mfSudo:
|
||||
return &d.sudo
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Messages from the work behind the screens.
|
||||
type (
|
||||
checkDoneMsg struct{ rep preflight.Report }
|
||||
setupRunMsg struct{}
|
||||
)
|
||||
|
||||
// progRef lets work started from Update send to the program it runs in.
|
||||
type progRef struct{ p *tea.Program }
|
||||
|
||||
type setupModel struct {
|
||||
ref *progRef
|
||||
|
||||
page setupPage
|
||||
host string
|
||||
ips []string
|
||||
choice int // 0 one machine, 1 high availability
|
||||
|
||||
admin, names textField
|
||||
afocus int // admin, names, next
|
||||
|
||||
db [2]dbMachine
|
||||
mfocus int // over both machines' fields, then the check button
|
||||
|
||||
remotes []*onboard.GoSSH
|
||||
report preflight.Report
|
||||
checking bool
|
||||
|
||||
in *serverInit
|
||||
run initModel
|
||||
finished bool
|
||||
log *[]string
|
||||
logMu *sync.Mutex
|
||||
|
||||
spin spinnerModel
|
||||
formErr string
|
||||
width int
|
||||
quit bool
|
||||
// single is the choice of one machine: the screen closes and init's own
|
||||
// form takes over.
|
||||
single bool
|
||||
}
|
||||
|
||||
func newSetupModel(host string, ips []string) setupModel {
|
||||
admin := newTextField()
|
||||
admin.Placeholder, admin.CharLimit, admin.Width = "you@example.com", 200, 40
|
||||
names := newTextField()
|
||||
names.Placeholder, names.CharLimit, names.Width = "llm.example.com, 203.0.113.10", 400, 40
|
||||
return setupModel{
|
||||
ref: &progRef{}, host: host, ips: ips, admin: admin, names: names,
|
||||
db: [2]dbMachine{newDBMachine(1), newDBMachine(2)}, spin: newSpinner(), width: 100,
|
||||
log: &[]string{}, logMu: &sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
func (m setupModel) Init() tea.Cmd { return m.spin.Tick }
|
||||
|
||||
func (m setupModel) thisAddr() string {
|
||||
if len(m.ips) > 0 {
|
||||
return m.ips[0]
|
||||
}
|
||||
return m.host
|
||||
}
|
||||
|
||||
func (m setupModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case tea.WindowSizeMsg:
|
||||
m.width = msg.Width
|
||||
m.run.width = msg.Width
|
||||
case spinTickMsg:
|
||||
var cmd tea.Cmd
|
||||
m.spin, cmd = m.spin.Update(msg)
|
||||
m.run.spin = m.spin
|
||||
return m, cmd
|
||||
case checkDoneMsg:
|
||||
m.checking, m.report = false, msg.rep
|
||||
case initLineMsg:
|
||||
m.run.addLine(string(msg))
|
||||
case initDoneMsg:
|
||||
m.run.done, m.run.err, m.finished = true, msg.err, true
|
||||
case tea.KeyMsg:
|
||||
if msg.Type == tea.KeyCtrlC {
|
||||
m.quit = true
|
||||
return m, tea.Quit
|
||||
}
|
||||
return m.key(msg)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (m setupModel) key(k tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||
if k.Type == tea.KeyEsc && m.page > pWelcome && m.page < pRun && !m.checking {
|
||||
m.page--
|
||||
if m.page == pMachines && m.choice == 0 {
|
||||
m.page = pAdmin
|
||||
}
|
||||
m.formErr = ""
|
||||
return m, nil
|
||||
}
|
||||
switch m.page {
|
||||
case pWelcome:
|
||||
switch k.String() {
|
||||
case "up", "down", "tab", "k", "j":
|
||||
m.choice = 1 - m.choice
|
||||
case "enter":
|
||||
if m.choice == 0 {
|
||||
m.single = true
|
||||
return m, tea.Quit
|
||||
}
|
||||
m.page = pAdmin
|
||||
m.afocus = 0
|
||||
m.admin.Focus()
|
||||
}
|
||||
case pAdmin:
|
||||
return m.adminKey(k)
|
||||
case pMachines:
|
||||
return m.machinesKey(k)
|
||||
case pCheck:
|
||||
switch k.String() {
|
||||
case "r":
|
||||
if !m.checking {
|
||||
cmd := m.startCheck()
|
||||
return m, cmd
|
||||
}
|
||||
case "enter":
|
||||
if !m.checking && m.report.Worst() < preflight.Fail {
|
||||
m.page = pPlan
|
||||
}
|
||||
}
|
||||
case pPlan:
|
||||
if k.String() == "enter" {
|
||||
m.page = pRun
|
||||
cmd := m.startRun()
|
||||
return m, cmd
|
||||
}
|
||||
case pRun:
|
||||
if m.finished && (k.String() == "q" || k.String() == "enter") {
|
||||
return m, tea.Quit
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (m setupModel) adminKey(k tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||
move := func(d int) {
|
||||
m.afocus = (m.afocus + d + 3) % 3
|
||||
m.admin.Blur()
|
||||
m.names.Blur()
|
||||
switch m.afocus {
|
||||
case 0:
|
||||
m.admin.Focus()
|
||||
case 1:
|
||||
m.names.Focus()
|
||||
}
|
||||
}
|
||||
switch k.Type {
|
||||
case tea.KeyTab, tea.KeyDown:
|
||||
move(1)
|
||||
return m, nil
|
||||
case tea.KeyShiftTab, tea.KeyUp:
|
||||
move(-1)
|
||||
return m, nil
|
||||
case tea.KeyEnter:
|
||||
if m.afocus < 2 {
|
||||
move(1)
|
||||
return m, nil
|
||||
}
|
||||
if _, err := mail.ParseAddress(strings.TrimSpace(m.admin.Value())); err != nil {
|
||||
m.formErr = "the administrator's email is needed, and that is not one"
|
||||
m.afocus = 0
|
||||
move(0)
|
||||
return m, nil
|
||||
}
|
||||
m.formErr = ""
|
||||
m.page, m.mfocus = pMachines, 0
|
||||
m.db[0].addr.Focus()
|
||||
return m, nil
|
||||
}
|
||||
var cmd tea.Cmd
|
||||
switch m.afocus {
|
||||
case 0:
|
||||
m.admin, cmd = m.admin.Update(k)
|
||||
case 1:
|
||||
m.names, cmd = m.names.Update(k)
|
||||
}
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
func (m *setupModel) focusMachine() {
|
||||
for i := range m.db {
|
||||
for f := 0; f < mfCount; f++ {
|
||||
if t := m.db[i].field(f); t != nil {
|
||||
t.Blur()
|
||||
}
|
||||
}
|
||||
}
|
||||
if m.mfocus < 2*mfCount {
|
||||
if t := m.db[m.mfocus/mfCount].field(m.mfocus % mfCount); t != nil {
|
||||
t.Focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m setupModel) machinesKey(k tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||
n := 2*mfCount + 1
|
||||
switch k.Type {
|
||||
case tea.KeyTab, tea.KeyDown:
|
||||
m.mfocus = (m.mfocus + 1) % n
|
||||
if m.mfocus < 2*mfCount && m.mfocus%mfCount == mfSecret && m.db[m.mfocus/mfCount].auth == authAgent {
|
||||
m.mfocus++
|
||||
}
|
||||
m.focusMachine()
|
||||
return m, nil
|
||||
case tea.KeyShiftTab, tea.KeyUp:
|
||||
m.mfocus = (m.mfocus - 1 + n) % n
|
||||
if m.mfocus < 2*mfCount && m.mfocus%mfCount == mfSecret && m.db[m.mfocus/mfCount].auth == authAgent {
|
||||
m.mfocus--
|
||||
}
|
||||
m.focusMachine()
|
||||
return m, nil
|
||||
case tea.KeyEnter:
|
||||
if m.mfocus < 2*mfCount {
|
||||
m.mfocus++
|
||||
m.focusMachine()
|
||||
return m, nil
|
||||
}
|
||||
if err := m.validateMachines(); err != "" {
|
||||
m.formErr = err
|
||||
return m, nil
|
||||
}
|
||||
m.formErr = ""
|
||||
m.page = pCheck
|
||||
cmd := m.startCheck()
|
||||
return m, cmd
|
||||
}
|
||||
if m.mfocus == 2*mfCount {
|
||||
return m, nil
|
||||
}
|
||||
d := &m.db[m.mfocus/mfCount]
|
||||
if m.mfocus%mfCount == mfAuth {
|
||||
switch k.String() {
|
||||
case "left", "h":
|
||||
d.auth = (d.auth + authCount - 1) % authCount
|
||||
case "right", "l", " ":
|
||||
d.auth = (d.auth + 1) % authCount
|
||||
}
|
||||
d.secret.SetValue("")
|
||||
d.secret.Mask = d.auth == authPassword
|
||||
d.secret.Placeholder = map[int]string{authKey: "/root/.ssh/id_ed25519", authPassword: "the user's ssh password"}[d.auth]
|
||||
return m, nil
|
||||
}
|
||||
var cmd tea.Cmd
|
||||
t := d.field(m.mfocus % mfCount)
|
||||
*t, cmd = t.Update(k)
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
func (m setupModel) validateMachines() string {
|
||||
seen := map[string]bool{m.thisAddr(): true, m.host: true}
|
||||
for i, d := range m.db {
|
||||
addr := strings.TrimSpace(d.addr.Value())
|
||||
switch {
|
||||
case addr == "":
|
||||
return fmt.Sprintf("database machine %d has no address", i+1)
|
||||
case seen[addr]:
|
||||
return fmt.Sprintf("%s is given twice, or is this machine: the three must be different machines", addr)
|
||||
case strings.TrimSpace(d.user.Value()) == "":
|
||||
return fmt.Sprintf("database machine %d has no user to log in as", i+1)
|
||||
case d.auth != authAgent && d.secret.Value() == "":
|
||||
return fmt.Sprintf("database machine %d needs its %s", i+1, authNames[d.auth])
|
||||
}
|
||||
seen[addr] = true
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// startCheck connects to the database machines and runs the checks on all
|
||||
// three, this one included.
|
||||
func (m *setupModel) startCheck() tea.Cmd {
|
||||
for _, r := range m.remotes {
|
||||
_ = r.Close()
|
||||
}
|
||||
m.remotes = nil
|
||||
machines := []preflight.Machine{{
|
||||
Name: m.host + " (this machine)", Addr: m.thisAddr(), Local: true, Remote: pgha.Local{},
|
||||
Roles: []preflight.Role{preflight.RoleControl, preflight.RoleWitness},
|
||||
}}
|
||||
for _, d := range m.db {
|
||||
g := &onboard.GoSSH{
|
||||
Addr: strings.TrimSpace(d.addr.Value()), User: strings.TrimSpace(d.user.Value()),
|
||||
UseAgent: d.auth == authAgent, SudoPassword: d.sudo.Value(),
|
||||
}
|
||||
switch d.auth {
|
||||
case authKey:
|
||||
g.KeyFile = strings.TrimSpace(d.secret.Value())
|
||||
case authPassword:
|
||||
g.Password = d.secret.Value()
|
||||
}
|
||||
m.remotes = append(m.remotes, g)
|
||||
machines = append(machines, preflight.Machine{Name: g.Addr, Addr: g.Addr,
|
||||
Roles: []preflight.Role{preflight.RoleDatabase}, Remote: g})
|
||||
}
|
||||
m.checking = true
|
||||
m.report = preflight.Report{}
|
||||
remotes := m.remotes
|
||||
return func() tea.Msg {
|
||||
rep := preflight.Run(context.Background(), machines)
|
||||
// A sudo that asks for a password is fine with one given: the
|
||||
// install grants itself sudo with it.
|
||||
for i := range rep.Findings {
|
||||
f := &rep.Findings[i]
|
||||
if f.Check == "sudo" && f.Level == preflight.Warn {
|
||||
for _, g := range remotes {
|
||||
switch {
|
||||
case g.Addr != f.Machine:
|
||||
case g.SudoPassword == "":
|
||||
f.Level = preflight.Fail
|
||||
f.Fix = "give this user's sudo password on the previous screen"
|
||||
default:
|
||||
f.Level = preflight.OK
|
||||
f.Detail = "with the password given"
|
||||
f.Fix = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return checkDoneMsg{rep}
|
||||
}
|
||||
}
|
||||
|
||||
// targets are the database machines as user@address, for the command line.
|
||||
func (m setupModel) targets() []string {
|
||||
var out []string
|
||||
for _, d := range m.db {
|
||||
out = append(out, strings.TrimSpace(d.user.Value())+"@"+strings.TrimSpace(d.addr.Value()))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (m setupModel) namesList() []string {
|
||||
var out []string
|
||||
for _, h := range strings.Split(m.names.Value(), ",") {
|
||||
if h = strings.TrimSpace(h); h != "" {
|
||||
out = append(out, h)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// command is what this setup is on the command line, for doing it again
|
||||
// from a script — with keys in place, since a password cannot be given there.
|
||||
func (m setupModel) command() string {
|
||||
parts := []string{"sudo --preserve-env=SSH_AUTH_SOCK llmgw server init",
|
||||
"--admin " + strings.TrimSpace(m.admin.Value())}
|
||||
for _, h := range m.namesList() {
|
||||
parts = append(parts, "--host "+h)
|
||||
}
|
||||
for _, t := range m.targets() {
|
||||
parts = append(parts, "--patroni "+t)
|
||||
}
|
||||
parts = append(parts, "--no-node", "--no-model")
|
||||
return strings.Join(parts, " \\\n ")
|
||||
}
|
||||
|
||||
// startRun installs: sudo granted where it asks for a password, the control
|
||||
// plane here, the store on the other two, then sudo taken back.
|
||||
func (m *setupModel) startRun() tea.Cmd {
|
||||
in := newDefaultServerInit()
|
||||
in.admin = strings.TrimSpace(m.admin.Value())
|
||||
in.hosts = m.namesList()
|
||||
in.patroni = m.targets()
|
||||
// The control plane of a replicated setup is not where models run;
|
||||
// nodes are added once it is up.
|
||||
in.noNode, in.noModel = true, true
|
||||
m.in = &in
|
||||
m.run = newInitModel(&in, nil, false)
|
||||
m.run.running, m.run.width, m.run.spin = true, m.width, m.spin
|
||||
ref, remotes, logp, mu := m.ref, m.remotes, m.log, m.logMu
|
||||
return func() tea.Msg {
|
||||
send := func(l string) {
|
||||
mu.Lock()
|
||||
*logp = append(*logp, l)
|
||||
mu.Unlock()
|
||||
ref.p.Send(initLineMsg(l))
|
||||
}
|
||||
in.out = &lineWriter{send: send}
|
||||
err := func() error {
|
||||
ctx := context.Background()
|
||||
for _, g := range remotes {
|
||||
fmt.Fprintf(in.out, " .. sudo on %s\n", g.Addr)
|
||||
if err := g.PrepareSudo(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
out, err := g.Run(ctx, "hostname", nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %v", g.Addr, err)
|
||||
}
|
||||
ip, err := ipv4Of(g.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
in.patroniNodes = append(in.patroniNodes, pgha.Node{
|
||||
Member: pgha.Member{Name: strings.TrimSpace(string(out)), IP: ip}, Remote: g})
|
||||
}
|
||||
return in.run(ctx)
|
||||
}()
|
||||
for _, g := range remotes {
|
||||
// The grant is taken back whatever happened.
|
||||
_ = g.Close()
|
||||
}
|
||||
return initDoneMsg{err}
|
||||
}
|
||||
}
|
||||
|
||||
func (m setupModel) View() string {
|
||||
var b strings.Builder
|
||||
b.WriteString(sTitle.Render("llmgw · setup") + " " + sDim.Render(m.crumbs()) + "\n\n")
|
||||
switch m.page {
|
||||
case pWelcome:
|
||||
b.WriteString(m.welcomeView())
|
||||
case pAdmin:
|
||||
b.WriteString(m.adminView())
|
||||
case pMachines:
|
||||
b.WriteString(m.machinesView())
|
||||
case pCheck:
|
||||
b.WriteString(m.checkView())
|
||||
case pPlan:
|
||||
b.WriteString(m.planView())
|
||||
case pRun:
|
||||
v := m.run.View()
|
||||
if i := strings.Index(v, "\n\n"); i >= 0 {
|
||||
v = v[i+2:] // its own title; this screen has one
|
||||
}
|
||||
b.WriteString(v)
|
||||
if m.finished {
|
||||
if m.run.err == nil {
|
||||
b.WriteString("\n" + sDim.Render("The same, from a script, with ssh keys in place:") + "\n" + m.command() + "\n")
|
||||
}
|
||||
b.WriteString("\n" + sDim.Render("enter or q to leave") + "\n")
|
||||
}
|
||||
}
|
||||
if m.formErr != "" {
|
||||
b.WriteString("\n" + sBad.Render(m.formErr) + "\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m setupModel) crumbs() string {
|
||||
steps := []string{"start", "administrator", "machines", "checks", "plan", "install"}
|
||||
if m.choice == 0 {
|
||||
return steps[0]
|
||||
}
|
||||
var out []string
|
||||
for i, s := range steps {
|
||||
if setupPage(i) == m.page {
|
||||
s = lipgloss.NewStyle().Bold(true).Render(s)
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return strings.Join(out, " › ")
|
||||
}
|
||||
|
||||
func (m setupModel) welcomeView() string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "Nothing of llmgw is installed on %s (%s).\n\n", m.host, strings.Join(m.ips, ", "))
|
||||
opt := func(i int, title, detail string) {
|
||||
mark := "( )"
|
||||
if m.choice == i {
|
||||
mark = "(" + sOK.Render("•") + ")"
|
||||
title = sTitle.Render(title)
|
||||
}
|
||||
fmt.Fprintf(&b, " %s %s\n %s\n\n", mark, title, sDim.Render(detail))
|
||||
}
|
||||
opt(0, "One machine", "this machine runs everything: the control plane, a model mirror, and models if it has room.")
|
||||
opt(1, "High availability — three machines",
|
||||
"this one is the control plane; two more keep the store, replicated, so losing any one loses nothing.")
|
||||
b.WriteString(sDim.Render("↑↓ to choose · enter to go on · ctrl+c to leave") + "\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m setupModel) adminView() string {
|
||||
var b strings.Builder
|
||||
label := func(i int, s string) string {
|
||||
if m.afocus == i {
|
||||
return sTitle.Render("› " + s)
|
||||
}
|
||||
return " " + s
|
||||
}
|
||||
fmt.Fprintf(&b, "%s\n %s\n %s\n\n", label(0, "Administrator's email"), m.admin.View(),
|
||||
sDim.Render("A password is generated and shown once, at the end."))
|
||||
fmt.Fprintf(&b, "%s\n %s\n %s\n\n", label(1, "Other names nodes will reach this machine by"), m.names.View(),
|
||||
sDim.Render("Already known: "+strings.Join(append([]string{m.host}, m.ips...), ", ")+". Add a DNS name or a floating address."))
|
||||
b.WriteString(label(2, lipgloss.NewStyle().Bold(true).Render("Next")) + "\n\n")
|
||||
b.WriteString(sDim.Render("tab or ↑↓ to move · enter on Next · esc back") + "\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m setupModel) machinesView() string {
|
||||
var b strings.Builder
|
||||
b.WriteString("The two machines that keep the store. They need ssh, a user that can sudo, and\n" +
|
||||
"Ubuntu 22.04/24.04 or Debian 12; PostgreSQL, Patroni and etcd are installed on them.\n\n")
|
||||
for i, d := range m.db {
|
||||
base := i * mfCount
|
||||
// Padded before it is coloured: the colour's escape codes count
|
||||
// toward a width and threw the focused row out of line.
|
||||
label := func(f int, s string) string {
|
||||
s = fmt.Sprintf("%-16s", s)
|
||||
if m.mfocus == base+f {
|
||||
return sTitle.Render("› " + s)
|
||||
}
|
||||
return " " + s
|
||||
}
|
||||
fmt.Fprintf(&b, "%s\n", lipgloss.NewStyle().Bold(true).Render(fmt.Sprintf("Database machine %d", i+1)))
|
||||
fmt.Fprintf(&b, " %s %s\n", label(mfAddr, "address"), d.addr.View())
|
||||
fmt.Fprintf(&b, " %s %s\n", label(mfUser, "user"), d.user.View())
|
||||
var auth []string
|
||||
for a := 0; a < authCount; a++ {
|
||||
if a == d.auth {
|
||||
auth = append(auth, sOK.Render("["+authNames[a]+"]"))
|
||||
} else {
|
||||
auth = append(auth, sDim.Render(" "+authNames[a]+" "))
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&b, " %s %s\n", label(mfAuth, "log in with"), strings.Join(auth, " "))
|
||||
if d.auth != authAgent {
|
||||
fmt.Fprintf(&b, " %s %s\n", label(mfSecret, authNames[d.auth]), d.secret.View())
|
||||
}
|
||||
fmt.Fprintf(&b, " %s %s\n\n", label(mfSudo, "sudo password"), d.sudo.View())
|
||||
}
|
||||
btn := lipgloss.NewStyle().Bold(true).Render("Check the three machines")
|
||||
if m.mfocus == 2*mfCount {
|
||||
btn = sTitle.Render("› " + btn)
|
||||
} else {
|
||||
btn = " " + btn
|
||||
}
|
||||
b.WriteString(btn + "\n\n")
|
||||
b.WriteString(sDim.Render("tab or ↑↓ to move · ←→ to choose how to log in · passwords are kept in memory only · esc back") + "\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m setupModel) checkView() string {
|
||||
var b strings.Builder
|
||||
if m.checking {
|
||||
b.WriteString(" " + m.spin.View() + " checking the three machines…\n")
|
||||
return b.String()
|
||||
}
|
||||
machine := ""
|
||||
for _, f := range m.report.Findings {
|
||||
if f.Machine != machine {
|
||||
machine = f.Machine
|
||||
b.WriteString("\n" + lipgloss.NewStyle().Bold(true).Render(machine) + "\n")
|
||||
}
|
||||
mark := sOK.Render("✓")
|
||||
switch f.Level {
|
||||
case preflight.Warn:
|
||||
mark = sWarn.Render("!")
|
||||
case preflight.Fail:
|
||||
mark = sBad.Render("✗")
|
||||
}
|
||||
line := fmt.Sprintf(" %s %-13s %s", mark, f.Check, truncate(f.Detail, max(20, m.width-22)))
|
||||
if f.Level != preflight.OK && f.Fix != "" {
|
||||
line += "\n " + sDim.Render(truncate(f.Fix, max(20, m.width-20)))
|
||||
}
|
||||
b.WriteString(line + "\n")
|
||||
}
|
||||
b.WriteString("\n")
|
||||
switch m.report.Worst() {
|
||||
case preflight.Fail:
|
||||
b.WriteString(sBad.Render("Fix what is marked ✗, then check again.") + "\n" +
|
||||
sDim.Render("r to check again · esc to change the machines") + "\n")
|
||||
case preflight.Warn:
|
||||
b.WriteString(sWarn.Render("It can go ahead; what is marked ! is worth a look.") + "\n" +
|
||||
sDim.Render("enter to see the plan · r to check again · esc back") + "\n")
|
||||
default:
|
||||
b.WriteString(sOK.Render("All three are ready.") + "\n" + sDim.Render("enter to see the plan · esc back") + "\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m setupModel) planView() string {
|
||||
var b strings.Builder
|
||||
b.WriteString("What will be installed:\n\n")
|
||||
fmt.Fprintf(&b, " %s %s\n %s\n", lipgloss.NewStyle().Bold(true).Render(m.host), sDim.Render(m.thisAddr()),
|
||||
"control plane and gateway, model mirror, etcd (the third vote), administrator "+strings.TrimSpace(m.admin.Value()))
|
||||
granted := false
|
||||
for _, d := range m.db {
|
||||
fmt.Fprintf(&b, " %s\n %s\n", lipgloss.NewStyle().Bold(true).Render(strings.TrimSpace(d.addr.Value())),
|
||||
"PostgreSQL under Patroni, etcd")
|
||||
granted = granted || d.sudo.Value() != ""
|
||||
}
|
||||
b.WriteString("\n The store is replicated from the first to the second; if the primary is lost the\n" +
|
||||
" standby takes over in about thirty seconds, and the control plane follows it.\n")
|
||||
if granted {
|
||||
b.WriteString(" " + sDim.Render("Where a sudo password was given, the user may sudo without it until the install\n finishes, and not after.") + "\n")
|
||||
}
|
||||
b.WriteString("\n" + sDim.Render("The same from a script, with ssh keys in place:") + "\n" + m.command() + "\n\n")
|
||||
b.WriteString(lipgloss.NewStyle().Bold(true).Render("enter to install") + sDim.Render(" · esc back · ctrl+c to leave") + "\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// runSetupTUI is the setup screens, until they finish or hand over to init's
|
||||
// own form for one machine.
|
||||
func runSetupTUI(ctx context.Context, out io.Writer) error {
|
||||
host, _ := os.Hostname()
|
||||
var ips []string
|
||||
for _, ip := range localAddrs() {
|
||||
if ip.To4() != nil {
|
||||
ips = append(ips, ip.String())
|
||||
}
|
||||
}
|
||||
m := newSetupModel(host, ips)
|
||||
p := tea.NewProgram(m, tea.WithOutput(out))
|
||||
m.ref.p = p
|
||||
final, err := p.Run()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fm := final.(setupModel)
|
||||
if fm.single {
|
||||
in := newDefaultServerInit()
|
||||
in.out = out
|
||||
return in.runInitTUI(ctx, out)
|
||||
}
|
||||
if fm.page < pRun {
|
||||
return nil
|
||||
}
|
||||
fmt.Fprintln(out)
|
||||
if fm.run.err != nil {
|
||||
fm.logMu.Lock()
|
||||
fmt.Fprintln(out, strings.Join(*fm.log, "\n"))
|
||||
fm.logMu.Unlock()
|
||||
return fm.run.err
|
||||
}
|
||||
if !fm.finished {
|
||||
return fmt.Errorf("left while installing; running llmgw again finishes what was started")
|
||||
}
|
||||
if fm.run.password != "" {
|
||||
fmt.Fprintf(out, "Administrator %s, password %s (shown once)\n\n", fm.in.admin, fm.run.password)
|
||||
}
|
||||
fmt.Fprintln(out, "Next: add nodes from the console — run llmgw again — or with")
|
||||
fmt.Fprintln(out, " sudo llmgw node add <user>@<address>")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/control/adminapi"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/preflight"
|
||||
)
|
||||
|
||||
func press(m tea.Model, keys ...string) tea.Model {
|
||||
for _, k := range keys {
|
||||
var msg tea.KeyMsg
|
||||
switch k {
|
||||
case "enter":
|
||||
msg = tea.KeyMsg{Type: tea.KeyEnter}
|
||||
case "tab":
|
||||
msg = tea.KeyMsg{Type: tea.KeyTab}
|
||||
case "down":
|
||||
msg = tea.KeyMsg{Type: tea.KeyDown}
|
||||
case "esc":
|
||||
msg = tea.KeyMsg{Type: tea.KeyEsc}
|
||||
case "right":
|
||||
msg = tea.KeyMsg{Type: tea.KeyRight}
|
||||
default:
|
||||
msg = tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(k)}
|
||||
}
|
||||
m, _ = m.Update(msg)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestTheSetupAsksForWhatHighAvailabilityNeedsAndRefusesWhatWillNotDo(t *testing.T) {
|
||||
m := tea.Model(newSetupModel("ctl", []string{"10.0.0.5"}))
|
||||
m = press(m, "down", "enter")
|
||||
if s := m.(setupModel); s.page != pAdmin {
|
||||
t.Fatalf("high availability did not lead to the administrator: page %d", s.page)
|
||||
}
|
||||
// No email: refused, with a reason.
|
||||
m = press(m, "tab", "tab", "enter")
|
||||
if s := m.(setupModel); s.page != pAdmin || !strings.Contains(s.formErr, "email") {
|
||||
t.Fatalf("went on without an administrator: %+v", s.formErr)
|
||||
}
|
||||
// The refusal puts the cursor back on the email.
|
||||
m = press(m, "a@example.com", "tab", "tab", "enter")
|
||||
s := m.(setupModel)
|
||||
if s.page != pMachines {
|
||||
t.Fatalf("page %d: %s", s.page, s.formErr)
|
||||
}
|
||||
// This machine's own address is not a database machine.
|
||||
s.db[0].addr.SetValue("10.0.0.5")
|
||||
s.db[0].user.SetValue("ubuntu")
|
||||
s.db[0].auth = authAgent
|
||||
s.db[1].addr.SetValue("10.0.0.7")
|
||||
s.db[1].user.SetValue("ubuntu")
|
||||
s.db[1].auth = authPassword
|
||||
if err := s.validateMachines(); !strings.Contains(err, "this machine") {
|
||||
t.Errorf("this machine as a database machine: %q", err)
|
||||
}
|
||||
s.db[0].addr.SetValue("10.0.0.6")
|
||||
if err := s.validateMachines(); !strings.Contains(err, "password") {
|
||||
t.Errorf("a password login with no password: %q", err)
|
||||
}
|
||||
s.db[1].secret.SetValue("pw")
|
||||
if err := s.validateMachines(); err != "" {
|
||||
t.Errorf("a valid pair refused: %s", err)
|
||||
}
|
||||
cmd := s.command()
|
||||
for _, want := range []string{"--admin a@example.com", "--patroni ubuntu@10.0.0.6", "--patroni ubuntu@10.0.0.7", "--no-node"} {
|
||||
if !strings.Contains(cmd, want) {
|
||||
t.Errorf("command lacks %q:\n%s", want, cmd)
|
||||
}
|
||||
}
|
||||
if strings.Contains(cmd, "pw") {
|
||||
t.Error("the password is in the command line")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChoosingOneMachineHandsOverToInit(t *testing.T) {
|
||||
m := press(tea.Model(newSetupModel("ctl", nil)), "enter").(setupModel)
|
||||
if !m.single {
|
||||
t.Error("one machine did not hand over")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheChecksHoldTheSetupBackOnlyForAFailure(t *testing.T) {
|
||||
m := newSetupModel("ctl", nil)
|
||||
m.choice, m.page = 1, pCheck
|
||||
m.report = preflight.Report{Findings: []preflight.Finding{{Machine: "a", Check: "disk", Level: preflight.Fail, Fix: "more"}}}
|
||||
if s := press(m, "enter").(setupModel); s.page != pCheck {
|
||||
t.Error("went on past a failed check")
|
||||
}
|
||||
m.report.Findings[0].Level = preflight.Warn
|
||||
if s := press(m, "enter").(setupModel); s.page != pPlan {
|
||||
t.Error("a warning held it back")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheConsoleOffersToReplicateOnlyAStoreThatIsNot(t *testing.T) {
|
||||
m := consoleModel{}
|
||||
if !strings.Contains(m.items()[1].label, "Replicate") {
|
||||
t.Error("a single store is not offered replication")
|
||||
}
|
||||
m.store = true
|
||||
for _, it := range m.items() {
|
||||
if strings.Contains(it.label, "Replicate") {
|
||||
t.Error("a replicated store is offered replication")
|
||||
}
|
||||
}
|
||||
// A node is asked for, then the console closes with it to do.
|
||||
var mm tea.Model = consoleModel{summary: "x", loaded: true}
|
||||
mm = press(mm, "enter", "ubuntu@10.0.0.9", "enter")
|
||||
if a := mm.(consoleModel).action; a.kind != "node" || a.targets[0] != "ubuntu@10.0.0.9" {
|
||||
t.Errorf("%+v", a)
|
||||
}
|
||||
_ = adminapi.Summary{}
|
||||
}
|
||||
@@ -47,6 +47,8 @@ type textField struct {
|
||||
Placeholder string
|
||||
CharLimit int
|
||||
Width int
|
||||
// Mask shows a dot for every character: a password.
|
||||
Mask bool
|
||||
}
|
||||
|
||||
func newTextField() textField { return textField{Prompt: "> "} }
|
||||
@@ -84,6 +86,9 @@ func (f textField) Update(msg tea.Msg) (textField, tea.Cmd) {
|
||||
|
||||
func (f textField) View() string {
|
||||
text := string(f.value)
|
||||
if f.Mask {
|
||||
text = strings.Repeat("•", len(f.value))
|
||||
}
|
||||
shown := text
|
||||
if text == "" && f.Placeholder != "" {
|
||||
shown = sDim.Render(f.Placeholder)
|
||||
|
||||
Reference in new issue
Block a user