oficina / alta Public

Clone
git clone https://amadan.net/oficina/alta

Plain git — no account needed to clone.

Download

Download this file

1// Command alta-adopt is the existing-team adoption runner (Home
2// implementation/existing-team-adoption.md): a local operator command
3// that adopts the canonical Oficina apps into the Home directory team
4// labelled oficina. It is never built into or deployed with alta.
5//
6// Home's half runs in Alta's own engine, on Alta's one operator signer,
7// stream and journal; CARLOS's half is package adopt, over an Admin
8// credential that lives in this process's memory only. Without --apply,
9// every command shows what it would do and writes nothing anywhere: not
10// Home, not CARLOS, not the adoption journal.
11package main
12
13import (
14 "bufio"
15 "context"
16 "database/sql"
17 "errors"
18 "flag"
19 "fmt"
20 "io"
21 "log/slog"
22 "net/http"
23 "os"
24 "slices"
25 "strconv"
26 "strings"
27 "time"
28
29 "amadan.net/oficina/alta/adopt"
30 "amadan.net/oficina/alta/carlosop"
31 "amadan.net/oficina/alta/console"
32 "amadan.net/oficina/alta/homeop"
33 "amadan.net/oficina/alta/provision"
34)
35
36// version is stamped by make adopt.
37var version = "dev"
38
39// env is what a run reaches beyond its arguments. main fills the first
40// three; tests fill the rest, to reach fakes.
41type env struct {
42 stdin io.Reader
43 stdout, stderr io.Writer
44 // now is the clock (Home's windows and plans are measured by it).
45 now func() time.Time
46 // public reaches the apps' own origins (the delivery probes).
47 public *http.Client
48 // homeURL is where each Home role is reached, when not its origin.
49 homeURL map[string]string
50 // tokenRead sees the buffer the CARLOS token was read into, so a
51 // test can check it was zeroed.
52 tokenRead func([]byte)
53}
54
55func main() {
56 os.Exit(run(context.Background(), os.Args[1:], env{stdin: os.Stdin, stdout: os.Stdout, stderr: os.Stderr}))
57}
58
59// command is one subcommand: its flags, and whether it writes (and so
60// takes --apply).
61type command struct {
62 writes bool
63 flags func(fs *flag.FlagSet, o *opts)
64 do func(r *runner, ctx context.Context) error
65}
66
67// opts are every command's flags.
68type opts struct {
69 config string
70 tokenFD int
71 apply bool
72 phase string
73 app string
74 apps string
75 run int64
76}
77
78var commands = map[string]command{
79 "home-preflight": {writes: true, flags: func(fs *flag.FlagSet, o *opts) {
80 fs.StringVar(&o.phase, "phase", "", "")
81 }, do: (*runner).homePreflight},
82 "preflight": {flags: func(fs *flag.FlagSet, o *opts) {
83 fs.StringVar(&o.app, "app", "", "")
84 }, do: (*runner).preflight},
85 "initialize": {writes: true, do: (*runner).initialize},
86 "plan-a": {writes: true, do: (*runner).planA},
87 "advance": {writes: true, flags: func(fs *flag.FlagSet, o *opts) {
88 fs.Int64Var(&o.run, "run", 0, "")
89 }, do: (*runner).advance},
90 "configure": {writes: true, flags: appFlag, do: (*runner).configure},
91 "activate": {writes: true, flags: func(fs *flag.FlagSet, o *opts) {
92 fs.StringVar(&o.apps, "apps", "", "")
93 }, do: (*runner).activate},
94 "rollback-config": {writes: true, flags: appFlag, do: (*runner).rollback},
95 "disable": {writes: true, flags: appFlag, do: (*runner).disable},
96 "status": {do: (*runner).status},
97}
98
99func appFlag(fs *flag.FlagSet, o *opts) { fs.StringVar(&o.app, "app", "", "") }
100
101// run is the command. It answers the exit code: 0 done, 1 refused or
102// failed, 2 a usage error.
103func run(ctx context.Context, args []string, e env) int {
104 if e.now == nil {
105 e.now = time.Now
106 }
107 if len(args) == 0 || args[0] == "help" || args[0] == "-h" || args[0] == "--help" {
108 fmt.Fprint(e.stdout, adopt.Usage)
109 return 2
110 }
111 if args[0] == "version" {
112 fmt.Fprintln(e.stdout, version)
113 return 0
114 }
115 cmd, ok := commands[args[0]]
116 if !ok {
117 fmt.Fprint(e.stderr, adopt.Usage)
118 return 2
119 }
120 o := &opts{tokenFD: -1}
121 fs := flag.NewFlagSet("alta-adopt "+args[0], flag.ContinueOnError)
122 fs.SetOutput(io.Discard)
123 fs.StringVar(&o.config, "config", "", "")
124 fs.IntVar(&o.tokenFD, "carlos-token-fd", -1, "")
125 if cmd.writes {
126 fs.BoolVar(&o.apply, "apply", false, "")
127 }
128 if cmd.flags != nil {
129 cmd.flags(fs, o)
130 }
131 if err := fs.Parse(args[1:]); err != nil || fs.NArg() > 0 {
132 // The flag package's message can quote an argument: only the
133 // usage is printed.
134 fmt.Fprintln(e.stderr, "alta-adopt: "+args[0]+": "+adopt.RefuseFlag)
135 fmt.Fprint(e.stderr, adopt.Usage)
136 return 2
137 }
138 r := &runner{e: e, o: o, in: bufio.NewReader(e.stdin)}
139 defer r.close()
140 if err := r.open(ctx); err != nil {
141 fmt.Fprintln(e.stderr, "alta-adopt: "+err.Error())
142 return 1
143 }
144 if err := cmd.do(r, ctx); err != nil {
145 fmt.Fprintln(e.stderr, "alta-adopt: "+err.Error())
146 if h := hintFor(err); h != "" {
147 fmt.Fprintln(e.stderr, h)
148 }
149 return 1
150 }
151 return 0
152}
153
154// refusal is a fixed code the command refuses with, and what comes first.
155type refusal struct{ code, hint string }
156
157func (r *refusal) Error() string { return "refused: " + r.code }
158
159func refuse(code, hint string) error { return &refusal{code, hint} }
160
161func hintFor(err error) string {
162 var r *refusal
163 if errors.As(err, &r) {
164 return r.hint
165 }
166 return ""
167}
168
169// runner is one command's process: its config, stores and clients. The
170// CARLOS token is in memory only, and zeroed by close.
171type runner struct {
172 e env
173 o *opts
174 in *bufio.Reader
175 cfg *config
176
177 db *sql.DB
178 ps *provision.Store
179 js *adopt.Store
180 home *homeop.Client
181
182 buf []byte // the whole buffer the token was read into
183 token []byte // the token: a slice of buf, never a copy
184 carlos *carlosop.Client
185 public *http.Client
186}
187
188// open reads the token first, so its descriptor is closed whatever
189// follows, then the config, then the state.
190func (r *runner) open(ctx context.Context) error {
191 if r.o.tokenFD != -1 {
192 if err := r.readToken(r.o.tokenFD); err != nil {
193 return err
194 }
195 }
196 cfg, err := loadConfig(r.o.config)
197 if err != nil {
198 return err
199 }
200 r.cfg = cfg
201 if r.o.apply {
202 r.db, err = provision.OpenDB(cfg.state)
203 } else {
204 // A dry run (and every read-only command) works on a copy in
205 // memory: the state file is never opened by SQLite, so nothing
206 // in it moves, not its WAL mode, a pending migration or its
207 // mtime. With no state yet, the copy is an empty database.
208 r.db, err = snapshot(ctx, cfg.state)
209 }
210 if err != nil {
211 return errors.New(adopt.RefuseStateOpen)
212 }
213 if r.ps, err = provision.NewStore(ctx, r.db, cfg.dek, r.e.now, adopt.Schema); err != nil {
214 return err
215 }
216 if r.js, err = adopt.NewStore(r.ps); err != nil {
217 return err
218 }
219 httpc := &http.Client{Timeout: 30 * time.Second}
220 roles := map[string]homeop.Role{}
221 for name, origin := range map[string]string{homeop.Credential: cfg.issuer, homeop.Directory: cfg.directory} {
222 roles[name] = homeop.Role{Name: name, Origin: origin, URL: r.e.homeURL[name], Installation: cfg.installation, Registry: cfg.registry, Device: cfg.dev}
223 }
224 r.home = &homeop.Client{HTTP: httpc, Key: cfg.key, Prefilter: cfg.prefilter, Roles: roles, Now: r.e.now}
225 r.public = r.e.public
226 if r.public == nil {
227 r.public = &http.Client{Timeout: 15 * time.Second}
228 }
229 if r.token != nil {
230 r.carlos = carlosop.New(cfg.console, cfg.account, r.token)
231 }
232 return nil
233}
234
235// tokenLimit bounds the token: a CARLOS Admin token is under 100 bytes.
236const tokenLimit = 4096
237
238// readToken reads the CARLOS token from descriptor fd into one buffer,
239// never copied: carlosop takes a slice of it, and close zeroes it all.
240// The standard streams are refused: the terminal answers prompts.
241func (r *runner) readToken(fd int) error {
242 if fd < 3 {
243 return errors.New(adopt.RefuseTokenFD)
244 }
245 f := os.NewFile(uintptr(fd), "carlos-token")
246 if f == nil {
247 return errors.New(adopt.RefuseTokenFDClosed)
248 }
249 defer f.Close()
250 r.buf = make([]byte, tokenLimit)
251 if r.e.tokenRead != nil {
252 r.e.tokenRead(r.buf)
253 }
254 n := 0
255 for n < len(r.buf) {
256 m, err := f.Read(r.buf[n:])
257 n += m
258 if errors.Is(err, io.EOF) {
259 break
260 }
261 if err != nil {
262 return errors.New(adopt.RefuseTokenFDRead)
263 }
264 }
265 if n == len(r.buf) {
266 return errors.New(adopt.RefuseTokenLong)
267 }
268 r.token = trimSpace(r.buf[:n:n])
269 if len(r.token) == 0 {
270 return errors.New(adopt.RefuseTokenEmpty)
271 }
272 return nil
273}
274
275// trimSpace is bytes.TrimSpace for ASCII space, as a subslice: the token
276// is never copied.
277func trimSpace(b []byte) []byte {
278 for len(b) > 0 && strings.ContainsRune(" \t\r\n", rune(b[0])) {
279 b = b[1:]
280 }
281 for len(b) > 0 && strings.ContainsRune(" \t\r\n", rune(b[len(b)-1])) {
282 b = b[:len(b)-1]
283 }
284 return b
285}
286
287// close zeroes the token and closes everything open.
288func (r *runner) close() {
289 if r.carlos != nil {
290 r.carlos.Close()
291 }
292 clear(r.buf)
293 if r.db != nil {
294 r.db.Close()
295 }
296}
297
298func (r *runner) say(lines ...string) {
299 for _, l := range lines {
300 fmt.Fprintln(r.e.stdout, l)
301 }
302}
303
304// ask prints prompt and reads one line from the terminal, without its
305// line ending.
306func (r *runner) ask(prompt string) (string, error) {
307 fmt.Fprint(r.e.stdout, prompt)
308 line, err := r.in.ReadString('\n')
309 if err != nil && (!errors.Is(err, io.EOF) || line == "") {
310 return "", refuse("no-answer", "")
311 }
312 return strings.TrimRight(line, "\r\n"), nil
313}
314
315// needCarlos is the console client, or a refusal naming the flag.
316func (r *runner) needCarlos() (*carlosop.Client, error) {
317 if r.carlos == nil {
318 return nil, refuse("carlos-token-needed", adopt.HintToken)
319 }
320 return r.carlos, nil
321}
322
323// offline answers nothing: the console and the apps as Alta's engine
324// meets them in an adoption, which never touches either.
325type offline struct{}
326
327func (offline) RoundTrip(*http.Request) (*http.Response, error) {
328 return nil, errors.New("alta-adopt: " + adopt.RefuseConsoleReached)
329}
330
331// engine is Alta's engine as alta-adopt runs it: Alta's one signer and
332// stream, no console credential and no network beyond Home, and obs as
333// the activation gate (nil for none).
334func (r *runner) engine(obs provision.Observer) *provision.Engine {
335 none := &http.Client{Transport: offline{}}
336 cfg := provision.Config{
337 Store: r.ps,
338 Home: r.home,
339 Console: &console.Client{HTTP: none, Base: "https://console.invalid", Account: r.cfg.account, Tokens: map[string]string{}},
340 Public: none,
341 HomeCfg: provision.HomeConfig{Issuer: r.cfg.issuer, Directory: r.cfg.directory, Provisioner: r.cfg.provisioner},
342 Account: r.cfg.account,
343 Now: r.e.now,
344 Logger: slog.New(slog.NewTextHandler(r.e.stderr, nil)),
345 }
346 if obs != nil {
347 cfg.Observer = obs
348 }
349 return provision.New(cfg)
350}
351
352// observer is the activation gate over the console client.
353func (r *runner) observer() (*adopt.Observer, error) {
354 c, err := r.needCarlos()
355 if err != nil {
356 return nil, err
357 }
358 return &adopt.Observer{C: c, H: r.public, S: r.js, Artifacts: r.cfg.artifacts, Now: r.e.now}, nil
359}
360
361func (r *runner) app() (provision.App, error) {
362 a, ok := provision.AppBySlug(r.o.app)
363 if !ok {
364 return provision.App{}, refuse("unknown-app", "")
365 }
366 return a, nil
367}
368
369// team is the adoption team's SQID, once seeded.
370func (r *runner) team(ctx context.Context) (string, error) {
371 used, err := r.ps.LabelUsed(ctx, provision.AdoptionLabel)
372 if err != nil {
373 return "", err
374 }
375 if !used {
376 return "", refuse("team-not-seeded", "")
377 }
378 t, err := r.ps.Team(ctx, provision.AdoptionLabel)
379 if err != nil {
380 return "", err
381 }
382 if t.TeamSQID == "" {
383 return "", refuse("team-not-seeded", "")
384 }
385 return t.TeamSQID, nil
386}
387
388func (r *runner) needPreflight(ctx context.Context, phase, hint string) error {
389 _, ok, err := r.js.HomePreflight(ctx, phase)
390 if err != nil {
391 return err
392 }
393 if !ok {
394 return refuse("home-preflight-missing", hint)
395 }
396 return nil
397}
398
399// ---- the commands ----
400
401// homePreflight prints Home's read-only queries, takes the counts Paul
402// pastes back, inspects both roles and checks it all against the phase.
403// Only with --apply, and only when nothing is refused, is it recorded.
404func (r *runner) homePreflight(ctx context.Context) error {
405 phase := r.o.phase
406 if phase != adopt.PhasePreInitialize && phase != adopt.PhasePrePlanA {
407 return refuse("unknown-phase", "")
408 }
409 r.say(adopt.SayHomeQueries)
410 counts := map[string]int64{}
411 for _, q := range adopt.HomeQueries() {
412 line, err := r.ask(adopt.SayHomeQuery(q))
413 if err != nil {
414 return err
415 }
416 n, err := strconv.ParseInt(strings.TrimSpace(line), 10, 64)
417 if err != nil || n < 0 {
418 return refuse("count-not-a-number", "")
419 }
420 counts[q[strings.LastIndex(q, " ")+1:]] = n
421 }
422 rec, codes, err := adopt.CheckHome(ctx, r.home, r.ps, counts, phase)
423 if err != nil {
424 return err
425 }
426 if len(codes) > 0 {
427 r.say(adopt.SayHomeRefused(codes))
428 return refuse("home-preflight-refused", "")
429 }
430 r.say(adopt.SayHomeReady)
431 if !r.o.apply {
432 r.say(adopt.SayDryRun)
433 return nil
434 }
435 if err := r.js.SaveHomePreflight(ctx, rec); err != nil {
436 return err
437 }
438 r.say(adopt.SayDone)
439 return nil
440}
441
442// preflight is CARLOS preflight for each app (or one), read-only.
443func (r *runner) preflight(ctx context.Context) error {
444 c, err := r.needCarlos()
445 if err != nil {
446 return err
447 }
448 apps := provision.Apps
449 if r.o.app != "" {
450 a, err := r.app()
451 if err != nil {
452 return err
453 }
454 apps = []provision.App{a}
455 }
456 refused := false
457 for _, a := range apps {
458 var mine map[string]string
459 if w, ok, err := r.js.Write(ctx, a.Slug); err != nil {
460 return err
461 } else if ok {
462 mine = w.Sent
463 }
464 snap, codes, err := adopt.Preflight(ctx, c, r.public, a, mine)
465 if err != nil {
466 return err
467 }
468 if code := adopt.ReviewedRelease(snap.Delivery, r.cfg.artifacts[a.Slug]); code != "" {
469 codes = append(codes, code)
470 }
471 refused = refused || len(codes) > 0
472 r.say(adopt.SayActivateApp(a.Slug, codes))
473 }
474 if refused {
475 return refuse("preflight-refused", "")
476 }
477 return nil
478}
479
480// initialize opens Home's directory initialize plan, once the
481// pre-initialize Home preflight is recorded.
482func (r *runner) initialize(ctx context.Context) error {
483 if err := r.needPreflight(ctx, adopt.PhasePreInitialize, adopt.HintPreInitialize); err != nil {
484 return err
485 }
486 if !r.o.apply {
487 r.say(adopt.SayInitializeWould, provision.InitializeAttestation, adopt.SayDryRun)
488 return nil
489 }
490 r.say(adopt.SayInitializeType, provision.InitializeAttestation)
491 typed, err := r.ask("> ")
492 if err != nil {
493 return err
494 }
495 id, err := r.engine(nil).StartInitialize(ctx, typed)
496 if err != nil {
497 return err
498 }
499 r.say(adopt.SayConfirm(id, []string{homeop.Directory}))
500 return nil
501}
502
503// planA opens Plan A, once the pre-plan-a Home preflight is recorded. A
504// Plan A whose window closed after the seed continues under add-apps
505// (ContinueAdoption); one whose plan lapsed before the seed is signed
506// again (Resubmit).
507func (r *runner) planA(ctx context.Context) error {
508 if err := r.needPreflight(ctx, adopt.PhasePrePlanA, adopt.HintPrePlanA); err != nil {
509 return err
510 }
511 used, err := r.ps.LabelUsed(ctx, provision.AdoptionLabel)
512 if err != nil {
513 return err
514 }
515 both := []string{homeop.Directory, homeop.Credential}
516 e := r.engine(nil)
517 if !used {
518 if !r.o.apply {
519 r.say(adopt.SayPlanAWould, adopt.SayDryRun)
520 return nil
521 }
522 owner, err := r.ask(adopt.SayPlanAOwner + " ")
523 if err != nil {
524 return err
525 }
526 id, err := e.StartAdoption(ctx, "Oficina", strings.TrimSpace(owner))
527 if err != nil {
528 return err
529 }
530 r.say(adopt.SayConfirm(id, both))
531 return nil
532 }
533 t, err := r.ps.Team(ctx, provision.AdoptionLabel)
534 if err != nil {
535 return err
536 }
537 if t.TeamSQID != "" {
538 var missing []string
539 for _, a := range provision.Slugs() {
540 if _, ok, err := r.ps.Done(ctx, provision.AdoptionLabel, a, provision.StepRegister); err != nil {
541 return err
542 } else if !ok {
543 missing = append(missing, a)
544 }
545 }
546 if len(missing) == 0 {
547 return refuse("plan-a-complete", "")
548 }
549 r.say(adopt.SayPlanAContinue(missing))
550 if !r.o.apply {
551 r.say(adopt.SayDryRun)
552 return nil
553 }
554 id, err := e.ContinueAdoption(ctx)
555 if err != nil {
556 return err
557 }
558 r.say(adopt.SayConfirm(id, both))
559 return nil
560 }
561 runs, err := r.ps.Runs(ctx, provision.AdoptionLabel)
562 if err != nil {
563 return err
564 }
565 for _, run := range runs {
566 if run.Adoption && run.Kind == homeop.KindCreateTeam {
567 r.say(adopt.SayPlanAResubmit)
568 if !r.o.apply {
569 r.say(adopt.SayDryRun)
570 return nil
571 }
572 if err := e.Resubmit(ctx, run.ID); err != nil {
573 return err
574 }
575 r.say(adopt.SayConfirm(run.ID, both))
576 return nil
577 }
578 }
579 return refuse("no-plan-a", "")
580}
581
582// advancePasses bounds one advance: each pass goes as far as Home allows
583// now, so a run that stops moving is left for the next advance.
584const advancePasses = 10
585
586// advance takes an initialize or adoption run as far as it can go now.
587// Plans B and C need the console: their activation re-observes each app.
588func (r *runner) advance(ctx context.Context) error {
589 run, err := r.ps.Run(ctx, r.o.run)
590 if err != nil {
591 return refuse("no-such-run", "")
592 }
593 if !run.Adoption && run.Kind != homeop.KindInitialize {
594 return refuse("not-an-adoption-run", "")
595 }
596 var obs provision.Observer
597 if run.Adoption && run.Kind == homeop.KindAddApps {
598 o, err := r.observer()
599 if err != nil {
600 return err
601 }
602 obs = o
603 }
604 r.say(adopt.SayRun(run.ID, run.State, run.Code))
605 if !r.o.apply {
606 r.say(adopt.SayAdvanceWould, adopt.SayDryRun)
607 return nil
608 }
609 e := r.engine(obs)
610 for range advancePasses {
611 if err := e.Advance(ctx, run.ID); err != nil {
612 var fl *provision.Fail
613 if !errors.As(err, &fl) {
614 return err
615 }
616 }
617 next, err := r.ps.Run(ctx, run.ID)
618 if err != nil {
619 return err
620 }
621 moved := next.State != run.State || next.Code != run.Code
622 run = next
623 if run.State == "done" || run.State == "failed" || !moved {
624 break
625 }
626 }
627 r.say(adopt.SayRun(run.ID, run.State, run.Code))
628 if run.State == "failed" {
629 return refuse(run.Code, "")
630 }
631 return nil
632}
633
634// configure writes app's two agent keys, restarts its canonical host
635// until it serves them, captures the after snapshot (Task 9's order) and
636// records the delivery check (Paul, 2026-11-17: the runner's check in
637// place of his witnessed sign-in). A resume continues from the journal:
638// an app already captured is not restarted again, and its delivery check
639// is made again, so a lost or voided check is redone by running
640// configure again.
641func (r *runner) configure(ctx context.Context) error {
642 a, err := r.app()
643 if err != nil {
644 return err
645 }
646 c, err := r.needCarlos()
647 if err != nil {
648 return err
649 }
650 sqid, err := r.team(ctx)
651 if err != nil {
652 return err
653 }
654 summary, err := adopt.WriteAgentKeys(ctx, c, r.public, r.js, a, sqid, r.cfg.artifacts[a.Slug], r.o.apply)
655 if err != nil {
656 return err
657 }
658 r.say(summary)
659 host := adopt.CanonicalHost(a)
660 if !r.o.apply {
661 // The restart's dry run: the scoped door must resolve the
662 // canonical host alone.
663 id, err := r.identity(ctx, c, a)
664 if err != nil {
665 return err
666 }
667 if _, err := adopt.RestartAndWait(ctx, c, r.public, a, id, func(adopt.Delivery) error { return nil }, false); err != nil {
668 return err
669 }
670 r.say(adopt.SayConfigureWould(host), adopt.SayDryRun)
671 return nil
672 }
673 if _, ok, err := r.js.After(ctx, a.Slug); err != nil {
674 return err
675 } else if !ok {
676 base, ok, err := r.js.Baseline(ctx, a.Slug)
677 if err != nil {
678 return err
679 }
680 if !ok {
681 return errors.New("adopt: " + adopt.RefuseNoJournalBase)
682 }
683 until := func(d adopt.Delivery) error { return adopt.Delivered(a, base.Delivery, d) }
684 if _, err := adopt.RestartAndWait(ctx, c, r.public, a, base.Identity, until, true); err != nil {
685 return err
686 }
687 if _, err := adopt.CaptureAfter(ctx, c, r.public, r.js, a); err != nil {
688 return err
689 }
690 }
691 if err := adopt.CheckDelivery(ctx, r.js, c, r.public, a, r.cfg.artifacts[a.Slug]); err != nil {
692 return err
693 }
694 r.say(adopt.SayConfigured(host))
695 return nil
696}
697
698// identity is the canonical record's identity: the baseline's once there
699// is one, otherwise a fresh read's.
700func (r *runner) identity(ctx context.Context, c *carlosop.Client, a provision.App) (adopt.Identity, error) {
701 if base, ok, err := r.js.Baseline(ctx, a.Slug); err != nil || ok {
702 return base.Identity, err
703 }
704 snap, err := adopt.Observe(ctx, c, r.public, a)
705 return snap.Identity, err
706}
707
708// activate opens Plan B or C. Every app but the canary must pass Plan
709// C's gate, the canary activated by Plan B (Store.CanaryGate, the
710// Observer's own rule), and every app must pass the Observer now, before
711// a window is asked for; the engine observes again, at activation.
712func (r *runner) activate(ctx context.Context) error {
713 var apps []string
714 for _, a := range strings.Split(r.o.apps, ",") {
715 if a = strings.TrimSpace(a); a != "" {
716 apps = append(apps, a)
717 }
718 }
719 sorted := provision.SortApps(apps)
720 if len(apps) == 0 || len(sorted) != len(apps) {
721 return refuse("unknown-app", "")
722 }
723 for _, a := range sorted {
724 if err := r.js.CanaryGate(ctx, a); errors.Is(err, adopt.ErrCanaryNotActive) {
725 return refuse(err.Error(), adopt.HintCanary)
726 } else if err != nil {
727 return err
728 }
729 }
730 obs, err := r.observer()
731 if err != nil {
732 return err
733 }
734 sqid, err := r.team(ctx)
735 if err != nil {
736 return err
737 }
738 refused := false
739 for _, a := range sorted {
740 var codes []string
741 if _, err := obs.Observe(ctx, a, sqid); err != nil {
742 var rf *adopt.Refusal
743 if !errors.As(err, &rf) {
744 return err
745 }
746 codes = rf.Codes
747 }
748 refused = refused || len(codes) > 0
749 r.say(adopt.SayActivateApp(a, codes))
750 }
751 if refused {
752 return refuse("activate-refused", "")
753 }
754 if !r.o.apply {
755 r.say(adopt.SayActivateWould(sorted), adopt.SayDryRun)
756 return nil
757 }
758 id, err := r.engine(obs).ActivateAdopted(ctx, sorted)
759 if err != nil {
760 return err
761 }
762 r.say(adopt.SayConfirm(id, []string{homeop.Directory, homeop.Credential}))
763 return nil
764}
765
766// rollback removes the two agent keys configure wrote and restarts the
767// app on its baseline.
768func (r *runner) rollback(ctx context.Context) error {
769 a, err := r.app()
770 if err != nil {
771 return err
772 }
773 c, err := r.needCarlos()
774 if err != nil {
775 return err
776 }
777 if err := adopt.RollbackAgentKeys(ctx, c, r.public, r.js, a, r.o.apply); err != nil {
778 return err
779 }
780 if !r.o.apply {
781 preview, err := r.rollbackPreview(ctx, c, a)
782 if err != nil {
783 return err
784 }
785 r.say(preview, adopt.SayDryRun)
786 return nil
787 }
788 r.say(adopt.SayRolledBack(adopt.CanonicalHost(a)))
789 return nil
790}
791
792// rollbackPreview says what a rollback would do now, from the journal
793// and a fresh read of the write layer, classified as RollbackAgentKeys
794// classifies it. It writes nothing. RollbackAgentKeys's own dry run has
795// already refused every stop.
796func (r *runner) rollbackPreview(ctx context.Context, c *carlosop.Client, a provision.App) (string, error) {
797 keys, host := adopt.AgentKeys(a), adopt.CanonicalHost(a)
798 rb, have, err := r.js.Rollback(ctx, a.Slug)
799 if err != nil {
800 return "", err
801 }
802 switch {
803 case have && rb.State == "restarted":
804 return adopt.SayRollbackNothing(host), nil
805 case have && rb.State == "unset":
806 return adopt.SayRollbackRestartOnly(keys, host), nil
807 }
808 base, okBase, err := r.js.Baseline(ctx, a.Slug)
809 if err != nil {
810 return "", err
811 }
812 w, okWrite, err := r.js.Write(ctx, a.Slug)
813 if err != nil {
814 return "", err
815 }
816 if !okBase || !okWrite {
817 return "", refuse("rollback-nothing-written", "")
818 }
819 read, err := c.Config(ctx, a.Slug, base.WriteLayer)
820 if err != nil {
821 return "", err
822 }
823 switch adopt.ClassifyRollback(base.Layer, read, w.Sent) {
824 case adopt.RetryUnset:
825 return adopt.SayRollbackWould(keys, base.Layer.Bundle, host), nil
826 case adopt.RolledBack:
827 return adopt.SayRollbackRestartOnly(keys, host), nil
828 }
829 return "", refuse("rollback-refused", "")
830}
831
832// disable opens a directory-only plan disabling app's team binding. The
833// label is typed on the terminal.
834func (r *runner) disable(ctx context.Context) error {
835 a, err := r.app()
836 if err != nil {
837 return err
838 }
839 if _, err := r.team(ctx); err != nil {
840 return err
841 }
842 if !r.o.apply {
843 r.say(adopt.SayDisableWould(a.Slug), adopt.SayDisableAsk, adopt.SayDryRun)
844 return nil
845 }
846 typed, err := r.ask(adopt.SayDisableType(a.Slug) + " ")
847 if err != nil {
848 return err
849 }
850 id, err := r.engine(nil).DisableAdopted(ctx, a.Slug, strings.TrimSpace(typed))
851 if err != nil {
852 return err
853 }
854 r.say(adopt.SayConfirm(id, []string{homeop.Directory}))
855 return nil
856}
857
858// status shows where the adoption is: Home's preflights, the team, the
859// runs, and each app's Home steps and journal.
860func (r *runner) status(ctx context.Context) error {
861 for _, phase := range []string{adopt.PhasePreInitialize, adopt.PhasePrePlanA} {
862 _, ok, err := r.js.HomePreflight(ctx, phase)
863 if err != nil {
864 return err
865 }
866 r.say(adopt.SayStatusPreflight(phase, ok))
867 }
868 _, err := r.team(ctx)
869 var rf *refusal
870 if err != nil && !errors.As(err, &rf) {
871 return err
872 }
873 r.say(adopt.SayStatusTeam(err == nil))
874 var runs []provision.Run
875 for _, label := range []string{"", provision.AdoptionLabel} {
876 rs, err := r.ps.Runs(ctx, label)
877 if err != nil {
878 return err
879 }
880 runs = append(runs, rs...)
881 }
882 slices.SortFunc(runs, func(a, b provision.Run) int { return int(a.ID - b.ID) })
883 for _, run := range runs {
884 r.say(adopt.SayRun(run.ID, run.Kind+" "+run.State, run.Code))
885 }
886 steps, err := r.ps.Steps(ctx, provision.AdoptionLabel)
887 if err != nil {
888 return err
889 }
890 for _, a := range provision.Slugs() {
891 var parts []string
892 for _, st := range steps {
893 if st.App == a {
894 parts = append(parts, strings.TrimSpace(st.Name+" "+st.State+" "+st.Code))
895 }
896 }
897 journal, err := r.journal(ctx, a)
898 if err != nil {
899 return err
900 }
901 parts = append(parts, journal...)
902 if len(parts) == 0 {
903 parts = []string{adopt.SayStatusNothing}
904 }
905 r.say(adopt.SayStatusApp(a, parts))
906 }
907 return nil
908}
909
910// journal is app's adoption journal as states and codes.
911func (r *runner) journal(ctx context.Context, app string) ([]string, error) {
912 var out []string
913 if _, ok, err := r.js.Baseline(ctx, app); err != nil {
914 return nil, err
915 } else if ok {
916 out = append(out, "baseline")
917 }
918 if w, ok, err := r.js.Write(ctx, app); err != nil {
919 return nil, err
920 } else if ok {
921 out = append(out, strings.TrimSpace("write "+w.State+" "+w.Code))
922 }
923 if _, ok, err := r.js.After(ctx, app); err != nil {
924 return nil, err
925 } else if ok {
926 out = append(out, "after")
927 }
928 if _, ok, err := r.js.DeliveryCheck(ctx, app); err != nil {
929 return nil, err
930 } else if ok {
931 out = append(out, adopt.SayStatusDeliveryCheck)
932 }
933 if rb, ok, err := r.js.Rollback(ctx, app); err != nil {
934 return nil, err
935 } else if ok {
936 out = append(out, strings.TrimSpace("rollback "+rb.State+" "+rb.Code))
937 }
938 return out, nil
939}
940