| 1 | // Package install puts catalogue apps onto the CARLOS Platform account Base |
| 2 | // runs on, and takes them off again. |
| 3 | package install |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "database/sql" |
| 9 | "encoding/base64" |
| 10 | "encoding/hex" |
| 11 | "encoding/json" |
| 12 | "errors" |
| 13 | "fmt" |
| 14 | "log/slog" |
| 15 | "net/http" |
| 16 | "sync" |
| 17 | "time" |
| 18 | |
| 19 | "amadan.net/rastrillo/rastrillo/crypto" |
| 20 | |
| 21 | "amadan.net/oficina/base/internal/catalog" |
| 22 | "amadan.net/oficina/base/internal/config" |
| 23 | "amadan.net/oficina/base/internal/platform" |
| 24 | "amadan.net/oficina/base/internal/store" |
| 25 | ) |
| 26 | |
| 27 | const ( |
| 28 | probeEvery = 2 * time.Second |
| 29 | probeTimeout = 5 * time.Minute |
| 30 | ) |
| 31 | |
| 32 | // Messages stored on install rows and shown to people. |
| 33 | const ( |
| 34 | msgSettings = "Platform refused the app settings" |
| 35 | msgCreate = "Platform refused to create the instance" |
| 36 | msgNoAnswer = "The app did not start answering" |
| 37 | msgNotRecorded = "The install could not be recorded" |
| 38 | msgRemove = "Platform refused to remove the instance" |
| 39 | ) |
| 40 | |
| 41 | // ErrBusy is returned by Uninstall while the app is still being installed. |
| 42 | // |
| 43 | //lint:ignore ST1005 the text is shown to people as written |
| 44 | var ErrBusy = errors.New("This app is still installing. Try again in a moment.") |
| 45 | |
| 46 | // Installer installs and uninstalls apps. It satisfies web.Installer. |
| 47 | type Installer struct { |
| 48 | db *sql.DB |
| 49 | cfg config.Config |
| 50 | pc platform.Client |
| 51 | probe func(ctx context.Context, origin string) error |
| 52 | logger *slog.Logger |
| 53 | |
| 54 | // locks serializes work per app. Base is one process, so this is enough. |
| 55 | mu sync.Mutex |
| 56 | locks map[string]*sync.Mutex |
| 57 | } |
| 58 | |
| 59 | // lockFor returns app's lock. |
| 60 | func (in *Installer) lockFor(app string) *sync.Mutex { |
| 61 | in.mu.Lock() |
| 62 | defer in.mu.Unlock() |
| 63 | if in.locks == nil { |
| 64 | in.locks = map[string]*sync.Mutex{} |
| 65 | } |
| 66 | l := in.locks[app] |
| 67 | if l == nil { |
| 68 | l = new(sync.Mutex) |
| 69 | in.locks[app] = l |
| 70 | } |
| 71 | return l |
| 72 | } |
| 73 | |
| 74 | // New returns an Installer. db must be the writer handle. probe waits until |
| 75 | // a new instance answers at origin. |
| 76 | func New(db *sql.DB, cfg config.Config, pc platform.Client, probe func(ctx context.Context, origin string) error, logger *slog.Logger) *Installer { |
| 77 | return &Installer{db: db, cfg: cfg, pc: pc, probe: probe, logger: logger} |
| 78 | } |
| 79 | |
| 80 | // HostFor returns the instance's host label (also its config environment |
| 81 | // name) and full host. |
| 82 | func HostFor(cfg config.Config, app string) (label, host string) { |
| 83 | label = cfg.Slug + "-" + app |
| 84 | return label, label + "." + cfg.AppsDomain |
| 85 | } |
| 86 | |
| 87 | // KeySet returns the key id and public key an app uses to verify Base's |
| 88 | // assertions. The kid is the lowercase hex SHA-256 of the 65-byte SignPub. |
| 89 | func KeySet(kp *crypto.Keypair) (kid string, pub []byte) { |
| 90 | pub = kp.SignPub() |
| 91 | sum := sha256.Sum256(pub) |
| 92 | return hex.EncodeToString(sum[:]), pub |
| 93 | } |
| 94 | |
| 95 | // AppVars returns the four variables every installed app reads. |
| 96 | func AppVars(cfg config.Config, app, origin string) map[string]string { |
| 97 | kid, pub := KeySet(cfg.AssertionKey) |
| 98 | keys, _ := json.Marshal(map[string]string{kid: base64.StdEncoding.EncodeToString(pub)}) |
| 99 | return map[string]string{ |
| 100 | "BASE_APP_ORIGIN": origin, |
| 101 | "BASE_APP_ISSUER": cfg.Origin, |
| 102 | "BASE_APP_CONSUMER_ID": app, |
| 103 | "BASE_APP_KEYS": base64.StdEncoding.EncodeToString(keys), |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | // localWriteTimeout bounds a state write that must land after the caller's |
| 108 | // context is gone: Platform has already acted, so Base records it regardless. |
| 109 | const localWriteTimeout = 10 * time.Second |
| 110 | |
| 111 | // finishing returns a context for such a write: ctx's values without its |
| 112 | // cancellation, bounded by localWriteTimeout. |
| 113 | func finishing(ctx context.Context) (context.Context, context.CancelFunc) { |
| 114 | return context.WithTimeout(context.WithoutCancel(ctx), localWriteTimeout) |
| 115 | } |
| 116 | |
| 117 | // Install claims app, configures and creates its instance, waits for it to |
| 118 | // answer, and records the result. It blocks until then. If the app is |
| 119 | // already installed or being installed it does nothing and returns nil. |
| 120 | // A failure is recorded as a short message on the install row; the returned |
| 121 | // error carries the same text. Installing a default app the owner removed |
| 122 | // clears that removal. |
| 123 | func (in *Installer) Install(ctx context.Context, app string) error { |
| 124 | run, err := in.claim(ctx, app, false) |
| 125 | if run == nil { |
| 126 | return err |
| 127 | } |
| 128 | return run(ctx) |
| 129 | } |
| 130 | |
| 131 | // Start is Install for a request that must answer at once. It claims app |
| 132 | // before it returns, so a page loaded next already shows the app |
| 133 | // installing, and does the rest in the background. The background work |
| 134 | // keeps ctx's values but not its cancellation: it outlives the request. |
| 135 | // Failures after the claim are recorded on the install row and logged. |
| 136 | func (in *Installer) Start(ctx context.Context, app string) error { |
| 137 | run, err := in.claim(ctx, app, false) |
| 138 | if run == nil { |
| 139 | return err |
| 140 | } |
| 141 | bg := context.WithoutCancel(ctx) |
| 142 | go func() { |
| 143 | if err := run(bg); err != nil { |
| 144 | in.logger.Error("install", "app", app, "err", err) |
| 145 | } |
| 146 | }() |
| 147 | return nil |
| 148 | } |
| 149 | |
| 150 | // claim takes app's lock and moves its row to "installing". It returns the |
| 151 | // rest of the install, which releases the lock when it ends, or a nil func |
| 152 | // when there is nothing to do: another install or uninstall of app holds the |
| 153 | // lock, the app is already installed or installing, or (asDefault) the owner |
| 154 | // removed this default app. Without asDefault it first clears any such |
| 155 | // removal: someone chose to install the app. |
| 156 | func (in *Installer) claim(ctx context.Context, app string, asDefault bool) (func(context.Context) error, error) { |
| 157 | if _, ok := catalog.Get(app); !ok { |
| 158 | return nil, fmt.Errorf("unknown app %q", app) |
| 159 | } |
| 160 | if in.cfg.AssertionKey == nil { |
| 161 | return nil, errors.New("BASE_ASSERTION_KEY is not set") |
| 162 | } |
| 163 | lock := in.lockFor(app) |
| 164 | if !lock.TryLock() { |
| 165 | return nil, nil // another Install or Uninstall of this app is running |
| 166 | } |
| 167 | held := true |
| 168 | defer func() { |
| 169 | if held { |
| 170 | lock.Unlock() |
| 171 | } |
| 172 | }() |
| 173 | if asDefault { |
| 174 | removed, err := store.DefaultRemoved(ctx, in.db, app) |
| 175 | if err != nil || removed { |
| 176 | return nil, err |
| 177 | } |
| 178 | } else if err := store.ClearDefaultRemoved(ctx, in.db, app); err != nil { |
| 179 | return nil, err |
| 180 | } |
| 181 | label, host := HostFor(in.cfg, app) |
| 182 | claimed, err := store.ClaimInstall(ctx, in.db, app, host) |
| 183 | if err != nil || !claimed { |
| 184 | return nil, err |
| 185 | } |
| 186 | held = false // the returned func owns the lock now |
| 187 | return func(ctx context.Context) error { |
| 188 | defer lock.Unlock() |
| 189 | return in.provision(ctx, app, label, host) |
| 190 | }, nil |
| 191 | } |
| 192 | |
| 193 | // provision does the claimed install's remote work and records the result. |
| 194 | func (in *Installer) provision(ctx context.Context, app, label, host string) error { |
| 195 | origin := "https://" + host |
| 196 | if err := in.pc.SetEnv(ctx, app, label, AppVars(in.cfg, app, origin)); err != nil { |
| 197 | return in.fail(ctx, app, msgSettings, err) |
| 198 | } |
| 199 | if err := in.pc.CreateInstance(ctx, app, host, label); err != nil { |
| 200 | return in.fail(ctx, app, msgCreate, err) |
| 201 | } |
| 202 | if err := in.probe(ctx, origin); err != nil { |
| 203 | return in.fail(ctx, app, msgNoAnswer, err) |
| 204 | } |
| 205 | // The final write must land even if ctx was cancelled meanwhile. |
| 206 | bg, cancel := finishing(ctx) |
| 207 | defer cancel() |
| 208 | if err := store.SetInstallState(bg, in.db, app, "installed", ""); err != nil { |
| 209 | in.logger.Error("recording install", "app", app, "err", err) |
| 210 | _ = store.SetInstallState(bg, in.db, app, "failed", msgNotRecorded) |
| 211 | return err |
| 212 | } |
| 213 | return nil |
| 214 | } |
| 215 | |
| 216 | // fail records a short message (never the underlying error text, which may |
| 217 | // carry a response body) and logs the detail. |
| 218 | func (in *Installer) fail(ctx context.Context, app, msg string, cause error) error { |
| 219 | in.logger.Error("install failed", "app", app, "err", cause) |
| 220 | // The caller's context may be what failed; record the state regardless. |
| 221 | bg, cancel := finishing(ctx) |
| 222 | defer cancel() |
| 223 | if err := store.SetInstallState(bg, in.db, app, "failed", msg); err != nil { |
| 224 | in.logger.Error("recording install failure", "app", app, "err", err) |
| 225 | } |
| 226 | return errors.New(msg) |
| 227 | } |
| 228 | |
| 229 | // Uninstall removes the instance Base recorded for app, then forgets the |
| 230 | // install. The app's data is kept by Platform. It returns ErrBusy, touching |
| 231 | // nothing, while the app is installing, and store.ErrNoInstall if it is not |
| 232 | // installed. Uninstalling a default app records that the owner removed it, |
| 233 | // so EnsureDefaults leaves it off. |
| 234 | func (in *Installer) Uninstall(ctx context.Context, app string) error { |
| 235 | lock := in.lockFor(app) |
| 236 | if !lock.TryLock() { |
| 237 | return ErrBusy |
| 238 | } |
| 239 | defer lock.Unlock() |
| 240 | all, err := store.Installs(ctx, in.db) |
| 241 | if err != nil { |
| 242 | return err |
| 243 | } |
| 244 | var row *store.Install |
| 245 | for i := range all { |
| 246 | if all[i].App == app { |
| 247 | row = &all[i] |
| 248 | } |
| 249 | } |
| 250 | if row == nil { |
| 251 | return store.ErrNoInstall |
| 252 | } |
| 253 | if row.State == "installing" { |
| 254 | return ErrBusy |
| 255 | } |
| 256 | // The host the instance was made at, not what config would name now: a |
| 257 | // changed slug or apps domain must not send the delete elsewhere. |
| 258 | if err := in.pc.DeleteInstance(ctx, app, row.Host); err != nil { |
| 259 | in.logger.Error("uninstall failed", "app", app, "err", err) |
| 260 | //lint:ignore ST1005 the text is shown to people as written |
| 261 | return errors.New(msgRemove) |
| 262 | } |
| 263 | // Platform has removed it; record that even if the caller has gone. |
| 264 | bg, cancel := finishing(ctx) |
| 265 | defer cancel() |
| 266 | e, _ := catalog.Get(app) |
| 267 | // The store refuses an installing row too, as a second guard. |
| 268 | busy, err := store.DeleteInstall(bg, in.db, app, e.Default) |
| 269 | if err != nil { |
| 270 | return err |
| 271 | } |
| 272 | if busy { |
| 273 | return ErrBusy |
| 274 | } |
| 275 | return nil |
| 276 | } |
| 277 | |
| 278 | // EnsureDefaults installs every default catalogue app that is not already |
| 279 | // installed and that the owner has not uninstalled. Apps that fail are |
| 280 | // retried on the next call; the first error is returned after every default |
| 281 | // has been tried. |
| 282 | func (in *Installer) EnsureDefaults(ctx context.Context) error { |
| 283 | var first error |
| 284 | for _, e := range catalog.All() { |
| 285 | if !e.Default { |
| 286 | continue |
| 287 | } |
| 288 | run, err := in.claim(ctx, e.ID, true) |
| 289 | if run != nil { |
| 290 | err = run(ctx) |
| 291 | } |
| 292 | if err != nil && first == nil { |
| 293 | first = err |
| 294 | } |
| 295 | } |
| 296 | return first |
| 297 | } |
| 298 | |
| 299 | // ProbeVersion polls GET {origin}/api/version every 2 s until it gets a 200, |
| 300 | // and gives up after 5 minutes. |
| 301 | func ProbeVersion(hc *http.Client) func(ctx context.Context, origin string) error { |
| 302 | return probeVersion(hc, probeEvery, probeTimeout) |
| 303 | } |
| 304 | |
| 305 | func probeVersion(hc *http.Client, every, timeout time.Duration) func(context.Context, string) error { |
| 306 | return func(ctx context.Context, origin string) error { |
| 307 | ctx, cancel := context.WithTimeout(ctx, timeout) |
| 308 | defer cancel() |
| 309 | for { |
| 310 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, origin+"/api/version", nil) |
| 311 | if err != nil { |
| 312 | return err |
| 313 | } |
| 314 | if resp, err := hc.Do(req); err == nil { |
| 315 | resp.Body.Close() |
| 316 | if resp.StatusCode == http.StatusOK { |
| 317 | return nil |
| 318 | } |
| 319 | } |
| 320 | select { |
| 321 | case <-ctx.Done(): |
| 322 | return fmt.Errorf("no answer from %s: %w", origin, ctx.Err()) |
| 323 | case <-time.After(every): |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | |