// Package install puts catalogue apps onto the CARLOS Platform account Base // runs on, and takes them off again. package install import ( "context" "crypto/sha256" "database/sql" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "log/slog" "net/http" "sync" "time" "amadan.net/rastrillo/rastrillo/crypto" "amadan.net/oficina/base/internal/catalog" "amadan.net/oficina/base/internal/config" "amadan.net/oficina/base/internal/platform" "amadan.net/oficina/base/internal/store" ) const ( probeEvery = 2 * time.Second probeTimeout = 5 * time.Minute ) // Messages stored on install rows and shown to people. const ( msgSettings = "Platform refused the app settings" msgCreate = "Platform refused to create the instance" msgNoAnswer = "The app did not start answering" msgNotRecorded = "The install could not be recorded" msgRemove = "Platform refused to remove the instance" ) // ErrBusy is returned by Uninstall while the app is still being installed. // //lint:ignore ST1005 the text is shown to people as written var ErrBusy = errors.New("This app is still installing. Try again in a moment.") // Installer installs and uninstalls apps. It satisfies web.Installer. type Installer struct { db *sql.DB cfg config.Config pc platform.Client probe func(ctx context.Context, origin string) error logger *slog.Logger // locks serializes work per app. Base is one process, so this is enough. mu sync.Mutex locks map[string]*sync.Mutex } // lockFor returns app's lock. func (in *Installer) lockFor(app string) *sync.Mutex { in.mu.Lock() defer in.mu.Unlock() if in.locks == nil { in.locks = map[string]*sync.Mutex{} } l := in.locks[app] if l == nil { l = new(sync.Mutex) in.locks[app] = l } return l } // New returns an Installer. db must be the writer handle. probe waits until // a new instance answers at origin. func New(db *sql.DB, cfg config.Config, pc platform.Client, probe func(ctx context.Context, origin string) error, logger *slog.Logger) *Installer { return &Installer{db: db, cfg: cfg, pc: pc, probe: probe, logger: logger} } // HostFor returns the instance's host label (also its config environment // name) and full host. func HostFor(cfg config.Config, app string) (label, host string) { label = cfg.Slug + "-" + app return label, label + "." + cfg.AppsDomain } // KeySet returns the key id and public key an app uses to verify Base's // assertions. The kid is the lowercase hex SHA-256 of the 65-byte SignPub. func KeySet(kp *crypto.Keypair) (kid string, pub []byte) { pub = kp.SignPub() sum := sha256.Sum256(pub) return hex.EncodeToString(sum[:]), pub } // AppVars returns the four variables every installed app reads. func AppVars(cfg config.Config, app, origin string) map[string]string { kid, pub := KeySet(cfg.AssertionKey) keys, _ := json.Marshal(map[string]string{kid: base64.StdEncoding.EncodeToString(pub)}) return map[string]string{ "BASE_APP_ORIGIN": origin, "BASE_APP_ISSUER": cfg.Origin, "BASE_APP_CONSUMER_ID": app, "BASE_APP_KEYS": base64.StdEncoding.EncodeToString(keys), } } // localWriteTimeout bounds a state write that must land after the caller's // context is gone: Platform has already acted, so Base records it regardless. const localWriteTimeout = 10 * time.Second // finishing returns a context for such a write: ctx's values without its // cancellation, bounded by localWriteTimeout. func finishing(ctx context.Context) (context.Context, context.CancelFunc) { return context.WithTimeout(context.WithoutCancel(ctx), localWriteTimeout) } // Install claims app, configures and creates its instance, waits for it to // answer, and records the result. It blocks until then. If the app is // already installed or being installed it does nothing and returns nil. // A failure is recorded as a short message on the install row; the returned // error carries the same text. Installing a default app the owner removed // clears that removal. func (in *Installer) Install(ctx context.Context, app string) error { run, err := in.claim(ctx, app, false) if run == nil { return err } return run(ctx) } // Start is Install for a request that must answer at once. It claims app // before it returns, so a page loaded next already shows the app // installing, and does the rest in the background. The background work // keeps ctx's values but not its cancellation: it outlives the request. // Failures after the claim are recorded on the install row and logged. func (in *Installer) Start(ctx context.Context, app string) error { run, err := in.claim(ctx, app, false) if run == nil { return err } bg := context.WithoutCancel(ctx) go func() { if err := run(bg); err != nil { in.logger.Error("install", "app", app, "err", err) } }() return nil } // claim takes app's lock and moves its row to "installing". It returns the // rest of the install, which releases the lock when it ends, or a nil func // when there is nothing to do: another install or uninstall of app holds the // lock, the app is already installed or installing, or (asDefault) the owner // removed this default app. Without asDefault it first clears any such // removal: someone chose to install the app. func (in *Installer) claim(ctx context.Context, app string, asDefault bool) (func(context.Context) error, error) { if _, ok := catalog.Get(app); !ok { return nil, fmt.Errorf("unknown app %q", app) } if in.cfg.AssertionKey == nil { return nil, errors.New("BASE_ASSERTION_KEY is not set") } lock := in.lockFor(app) if !lock.TryLock() { return nil, nil // another Install or Uninstall of this app is running } held := true defer func() { if held { lock.Unlock() } }() if asDefault { removed, err := store.DefaultRemoved(ctx, in.db, app) if err != nil || removed { return nil, err } } else if err := store.ClearDefaultRemoved(ctx, in.db, app); err != nil { return nil, err } label, host := HostFor(in.cfg, app) claimed, err := store.ClaimInstall(ctx, in.db, app, host) if err != nil || !claimed { return nil, err } held = false // the returned func owns the lock now return func(ctx context.Context) error { defer lock.Unlock() return in.provision(ctx, app, label, host) }, nil } // provision does the claimed install's remote work and records the result. func (in *Installer) provision(ctx context.Context, app, label, host string) error { origin := "https://" + host if err := in.pc.SetEnv(ctx, app, label, AppVars(in.cfg, app, origin)); err != nil { return in.fail(ctx, app, msgSettings, err) } if err := in.pc.CreateInstance(ctx, app, host, label); err != nil { return in.fail(ctx, app, msgCreate, err) } if err := in.probe(ctx, origin); err != nil { return in.fail(ctx, app, msgNoAnswer, err) } // The final write must land even if ctx was cancelled meanwhile. bg, cancel := finishing(ctx) defer cancel() if err := store.SetInstallState(bg, in.db, app, "installed", ""); err != nil { in.logger.Error("recording install", "app", app, "err", err) _ = store.SetInstallState(bg, in.db, app, "failed", msgNotRecorded) return err } return nil } // fail records a short message (never the underlying error text, which may // carry a response body) and logs the detail. func (in *Installer) fail(ctx context.Context, app, msg string, cause error) error { in.logger.Error("install failed", "app", app, "err", cause) // The caller's context may be what failed; record the state regardless. bg, cancel := finishing(ctx) defer cancel() if err := store.SetInstallState(bg, in.db, app, "failed", msg); err != nil { in.logger.Error("recording install failure", "app", app, "err", err) } return errors.New(msg) } // Uninstall removes the instance Base recorded for app, then forgets the // install. The app's data is kept by Platform. It returns ErrBusy, touching // nothing, while the app is installing, and store.ErrNoInstall if it is not // installed. Uninstalling a default app records that the owner removed it, // so EnsureDefaults leaves it off. func (in *Installer) Uninstall(ctx context.Context, app string) error { lock := in.lockFor(app) if !lock.TryLock() { return ErrBusy } defer lock.Unlock() all, err := store.Installs(ctx, in.db) if err != nil { return err } var row *store.Install for i := range all { if all[i].App == app { row = &all[i] } } if row == nil { return store.ErrNoInstall } if row.State == "installing" { return ErrBusy } // The host the instance was made at, not what config would name now: a // changed slug or apps domain must not send the delete elsewhere. if err := in.pc.DeleteInstance(ctx, app, row.Host); err != nil { in.logger.Error("uninstall failed", "app", app, "err", err) //lint:ignore ST1005 the text is shown to people as written return errors.New(msgRemove) } // Platform has removed it; record that even if the caller has gone. bg, cancel := finishing(ctx) defer cancel() e, _ := catalog.Get(app) // The store refuses an installing row too, as a second guard. busy, err := store.DeleteInstall(bg, in.db, app, e.Default) if err != nil { return err } if busy { return ErrBusy } return nil } // EnsureDefaults installs every default catalogue app that is not already // installed and that the owner has not uninstalled. Apps that fail are // retried on the next call; the first error is returned after every default // has been tried. func (in *Installer) EnsureDefaults(ctx context.Context) error { var first error for _, e := range catalog.All() { if !e.Default { continue } run, err := in.claim(ctx, e.ID, true) if run != nil { err = run(ctx) } if err != nil && first == nil { first = err } } return first } // ProbeVersion polls GET {origin}/api/version every 2 s until it gets a 200, // and gives up after 5 minutes. func ProbeVersion(hc *http.Client) func(ctx context.Context, origin string) error { return probeVersion(hc, probeEvery, probeTimeout) } func probeVersion(hc *http.Client, every, timeout time.Duration) func(context.Context, string) error { return func(ctx context.Context, origin string) error { ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() for { req, err := http.NewRequestWithContext(ctx, http.MethodGet, origin+"/api/version", nil) if err != nil { return err } if resp, err := hc.Do(req); err == nil { resp.Body.Close() if resp.StatusCode == http.StatusOK { return nil } } select { case <-ctx.Done(): return fmt.Errorf("no answer from %s: %w", origin, ctx.Err()) case <-time.After(every): } } } }