Apps are a coreapp.toml; a trusted installer makes the Core side

An app's repository now has only coreapp.toml, its Dockerfile, its code
and an icon: no install scripts or compose file, so installing an app
from someone else's repository can't run their code as root on a Core.

core/coreapps runs on the Core (coreapp deploy puts it in /opt/coreapps).
It checks the manifest, refuses Federated's app names and the Core's
hostnames, picks a free address on that Core, writes the generic app
format from its own templates, sets up the needs (postgres, sso) and
installs through installapp. Updates keep the address, secrets and data,
add settings for new needs and delete old images; dropping a need is
refused. remove rebuilds Superpanel's catalog afterwards.

PLAN.md: the Coreapps direction and steps, and what the Core offers apps
(Superpanel's AI features, mcpserver, hermes, email, PowerDNS).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 13:36:47 -07:00
co-authored by Claude Opus 5.5
parent d8c6d1011f
commit b4d47fb1c5
36 changed files with 1046 additions and 413 deletions
+163 -75
View File
@@ -109,94 +109,182 @@ What we learned provisioning (2026-12-02/03):
- superpanel's catalog lists `services/*/service`, so an app installed this - superpanel's catalog lists `services/*/service`, so an app installed this
way shows up in the Core's dashboard. way shows up in the Core's dashboard.
### Design (proposed) ### Design
An app is a folder in the generic format, kept anywhere on the workstation An app is a folder (its own git repo) on the workstation; `coreapp`, run
(its own git repo). A `coreapp` command, run inside that folder, works inside it, works against the Core in the local VM (`coreapp-vm ip`): `new`,
against the Core in the local VM (`coreapp-vm ip`): `deploy` (build, `docker save | ssh docker load`, install or update),
`check`, `status`, `logs`, `shell`, `list`, `remove`. Since 2026-12-03 the
folder has only `coreapp.toml`, the Dockerfile, the code and an icon; the
Core side is made by the installer (see Coreapps below).
- `coreapp new <name>`: scaffold the folder: `service`, Built 2026-12-03 and tested against dev.fedcom.net: plain apps, a
`docker-compose.yml.in` with the traefik labels, `env.in`, `install`, a database (`--postgres`), sign-in (`--sso`), both. David signed in to
placeholder `icon.png`, a `Dockerfile` with a minimal web server, and a sso-demo and team-visits in a browser.
README. Its `INTERNAL_IP` comes from 192.168.200.0/24, well away from
Federated's 192.168.0.x, and different for each app made on this machine.
- `coreapp deploy`: build the image locally (`docker build`), copy it to the
Core (`docker save | ssh docker load`, no registry needed), copy the folder
to `/federated/services/<name>/`, then `installapp -n <name>` the first
time. Later deploys re-render `docker-compose.yml` but keep `.env` (its
random secrets), and restart the app.
- `coreapp status`, `coreapp logs [-f]`, `coreapp shell`: on the Core.
- `coreapp check`: the app answers at `https://<name>.<domain>/` as its
`MONITOR` line says, with a valid certificate.
- `coreapp remove`: `uninstallapp <name>` and remove its services folder.
Built and tested 2026-12-03 with a test app `hello` (busybox httpd):
new, deploy (first install and redeploy), check, status, logs, remove all
work against dev.fedcom.net; `https://hello.dev.fedcom.net/` answers through
the relay.
What we learned: What we learned:
- `/federated/bin/start <app>` only starts apps in the fixed `CORE_APPS` / - `/federated/bin/start <app>` only starts apps in the fixed `CORE_APPS` /
`EXTRA_APPS` lists in `lib/functions.sh`; for anything else it prints its `EXTRA_APPS` lists in `lib/functions.sh`; for anything else it prints its
usage. So `installapp` installs a new app but doesn't start it, and usage. So `installapp` installs a new app but doesn't start it, and
`start all` skips it. `coreapp deploy` starts it with the same `start all` skips it. The installer starts it with the same
`docker compose ... up -d`; `restart: always` covers reboots `docker compose ... up -d`; `restart: always` covers reboots. `bin/stop`
doesn't know them either, so when a dependency (postgresql, authelia) is
upgraded, coreapps' apps keep running; they reconnect
- `installapp` / `uninstallapp` call `update_monitors`, which registers or - `installapp` / `uninstallapp` call `update_monitors`, which registers or
removes the app's `MONITOR` URL with Federated's external monitoring removes the app's `MONITOR` URL with Federated's external monitoring
(blackboxregistrar.monitoreast.fedcom.net). Dev apps get registered too (blackboxregistrar.monitoreast.fedcom.net). Decided 2026-12-03: apps in
- `uninstallapp` runs with `set -x`; its trace includes the monitoring development aren't registered, so the installer writes no `MONITOR`
registrar's bearer token (in plain text in `lib/functions.sh`) and the - `installapp` and `uninstallapp` run with `set -x`; the trace includes the
Core's email addresses. coreapp keeps the trace in monitoring registrar's bearer token (in plain text in `lib/functions.sh`),
`~/.local/share/coreapp-dev/logs/` (mode 600) the Core's email addresses and the app's secrets. The installer keeps
- `uninstallapp` only stops a generic app if the app has an `uninstall` their output in `/federated/logs/coreapps/` (mode 600)
script (sourced, so no `exit`); the template has one - `uninstallapp` only stops a generic app if it has an `uninstall` script
(sourced, so no `exit`)
- `uninstallapp` makes Superpanel's catalog before the services folder is
deleted, so the installer makes it again afterwards
- Databases: the app's own user and database (`coreapp_<name>`, because
PostgreSQL reserves `pg_*` and Federated's apps have their own names) on
the Core's PostgreSQL, made with `docker exec postgresql psql -U postgres`
as Federated's installers do. `postgresql.<domain>` resolves to the
container on the `core` network (Docker's DNS); outside it, it's the
public IP
- Sign-in: the OIDC client `coreapp-<name>` goes in Authelia's
`idproviders.yml` between `### coreapp-<name> begin/end` markers (secret
hashed with the running Authelia's `authelia crypto hash generate
pbkdf2`), checked with `authelia validate-config` before Authelia
restarts (the old file is put back if the check fails). `installapp`'s
`apply_authelia_2fa_policy` applies the Core's 2FA policy to it. The app
reaches `https://authelia.<domain>` through traefik (`extra_hosts` to
traefik's address; Federated's apps use the public IP, which here would
loop out through the relay)
- Image names must include the registry: `coreapp/x` means Docker Hub, so a
Core that had to pull it (after its boot-time prune, say) would get
whatever is published there. Dev images are `localhost/coreapp/<name>`,
which can't be pulled
- Decided 2026-12-03: apps in development are not registered with ### How Federated adds an app to every Core
Federated's monitoring. `coreapp deploy` drops `MONITOR` from the copy of
`service` on the Core
- [ ] Document the app format fully in the README (done in each app's README)
Databases (2026-12-03): `coreapp new --postgres <name>` adds
`DEPENDS="postgresql"`, DB_* settings in `env.in` (random password), an
`install` that creates the user and database on the Core's PostgreSQL
(`docker exec postgresql psql -U postgres`, as Federated's own installers
do) and an `uninstall` that drops them, and a Python example (psycopg)
that counts visits. Tested with `guest-book`: deploy, the count goes up,
a redeploy and a reboot of the Core keep the data, remove drops the database
and user. `postgresql.<domain>` resolves to the PostgreSQL container on the
`core` network (Docker's DNS); outside it, it's the public IP.
Sign-in (2026-12-03): `coreapp new --sso <name>`. Its `install` registers From the Core repo's history, e.g. immich:
the OIDC client `coreapp-<name>` in Authelia's `idproviders.yml` between - The Core repo (`gitea.federated.computer/Federated_Computer/Core`) gets
`### coreapp-<name> begin/end` markers (secret from `.env`, hashed with the `services/<app>/` in the generic format, with `CONTAINER` a public image
running Authelia's `authelia crypto hash generate pbkdf2`), checks the (most are on Docker Hub; Federated's own under `federatedcomputer/`) and
result with `authelia validate-config`, restores the old file if that fails, an `INTERNAL_IP` in 192.168.0.x not used by another app
and restarts Authelia; `uninstall` removes the block. `installapp`'s - `lib/functions.sh`: the app goes into `EXTRA_APPS`, or `bin/start` and
`apply_authelia_2fa_policy` then applies the Core's 2FA policy to it. `start all` won't start it
The app reaches `https://authelia.<domain>` through traefik - `services/superpanel/tiers.json`: the tiers (good, better, best) that
(`extra_hosts` to `@TRAEFIK_IP@`, which the template's `install` and include it
coreapp's redeploy both provide; Federated's apps use the public IP, which - Work happens on branches with pull requests into `master`; Cores run the
here would loop out through the relay). The example is a standard-library `release` branch, which `upgrade` pulls nightly
Python OIDC client (code flow with PKCE).
Tested with `sso-demo`: install, redeploy, remove and reinstall each leave
one (or no) client block, a valid config, and the other clients and
Nextcloud working; `/login` redirects to Authelia with PKCE.
A real sign-in to sso-demo with a Core account in a browser worked ## Coreapps: apps from the developer's own repository
(2026-12-03, tested by David).
- `bin/stop` and `bin/start` don't know apps outside Federated's lists, so
when a dependency (postgresql, authelia) is upgraded, coreapp apps keep
running instead of being stopped and restarted; they reconnect
Both together (2026-12-03): overlays no longer replace `service`; each
names the Core apps it needs in `.depends`, merged into `DEPENDS`. The
sign-in code is a module (`oidc.py`) any example imports;
`templates/postgres-sso` is the combined example (sign-in, each person's
visits in PostgreSQL). Tested with `team-visits`: database, Authelia client
`coreapp-team-visits`, `DEPENDS="postgresql authelia"`, `/login` to Authelia.
Signing in to team-visits and sso-demo (with the oidc.py code) in a browser Decided 2026-12-03 (David): a developer publishes an app to their own Gitea
worked (2026-12-03, tested by David). repository. A Core's owner installs it in Superpanel, in a new Coreapps
- [ ] Later: apps published for other Cores (registry, submitting to screen (Superpanel doesn't have one yet), by giving the repository's URL.
Federated) A Claude Code skill helps developers make apps that use the Core's
services: Traefik, Authelia, PowerDNS (`<app>.<domain>`), email and the AI
features.
Rules that follow from it:
- An app from any URL must not run code as root on the Core. So the app's
repository has no `install` scripts or compose file: only `coreapp.toml`,
an image and an icon. The installer (`core/coreapps`, trusted, written by
us or Federated) checks the manifest and makes everything else from its
own templates. Values from the manifest go into shell-sourced and YAML
files, so each is limited to safe characters
- Images are built outside the Core (CI in the developer's Gitea, pushed to
its container registry); the Core only pulls `image:version`
- Each Core picks the app's address itself (192.168.200.10-250, free on
that Core)
- Apps live in `/federated/services/<name>/` with a `.coreapp` marker, so
Superpanel's catalog and the Core's `installapp`/`uninstallapp` see them.
That folder is Federated's git checkout; untracked folders survive
`git pull`, but a `git clean` would delete them. Ask Federated
Steps:
1. Done 2026-12-03: `coreapp.toml` and the installer. `coreapp deploy`
puts the installer in `/opt/coreapps` on the Core and runs
`coreapps install`. Tested on dev.fedcom.net: new apps with no needs,
postgres, and postgres + sso (`trial-app`); updates (a new version,
adding a need, the three apps deployed before coreapp.toml); refusals
(Federated's app names, the Core's hostnames, dropping a need, bad
manifest values); remove (database, Authelia client, image and catalog
entry gone)
- [ ] David: sign in to `https://trial-app.dev.fedcom.net/` in a browser
2. [ ] Publishing: a Gitea Actions workflow in new apps that builds the image
on a version tag and pushes it to the repository's Gitea registry; and
`coreapp publish` for developers without a runner. Pin the image by
digest in what the Core installs? Private registries need a pull token
3. [ ] Install from a URL on the Core: `coreapps install <repo-url>[@tag]`
(git clone at the tag, read `coreapp.toml` and `icon.png` only, pull the
image). Show the source and what the app needs before installing
4. [ ] Email and AI needs (findings below), then other services: PowerDNS
records beyond the wildcard, if an app needs other hostnames
5. [ ] The skill: a Claude Code skill in coreapp-dev (installed by
`update.sh`) that teaches `coreapp.toml`, the needs, the `coreapp`
commands and testing against the VM
6. [ ] The Coreapps screen in Superpanel (Federated's code: needs their
agreement). Until then, the installer could run as a small web app behind
Authelia, for admins only
Later:
- [ ] Uninstalling a need without removing the app (now refused)
- [ ] `bin/start` / `bin/stop` don't know coreapps' apps (see "Tell
Federated"); `restart: always` covers reboots
- [ ] Trust: a list of reviewed apps, or signed releases, and a warning in
Superpanel for others
- [ ] Monitoring for published apps (dev apps aren't registered)
### What the Core offers apps (studied 2026-12-03)
Superpanel (`federatedcomputer/superpanel` 26.12.01, a Go binary, at
192.168.0.85; its `.env` has LDAP, SMTP, Authelia client and
`STORE_DB_URL`). Its AI features:
- `/ai/settings` (and `/models`): the LLM provider and model (Anthropic,
OpenAI, OpenRouter, custom), stored in Hermes's `.env`
(`HERMES_LLM_PROVIDER`, `HERMES_LLM_API_KEY`, `HERMES_LLM_MODEL`). The
AI Settings toggle runs `installapp hermes`
- `/ai/terminal` (`/stream`): a chat with Hermes, through Hermes's API
(`HERMES_API_URL=http://192.168.0.92:8642`, `/v1/chat/completions`,
bearer `HERMES_API_KEY`)
- `/api/mcp-apps`: which apps the AI can use; `/api/mcp/validate`: the
forward-auth check for `mcphub.<domain>`, with per-user tokens in
`superpanel/data/mcp_tokens`
- On dev.fedcom.net hermes and mcpserver aren't installed
hermes (`nousresearch/hermes-agent`, 192.168.0.92, no traefik route): the
agent. It uses mcpserver-hub (`http://192.168.0.91:8080/sse`) for tools.
mcpserver (`federatedcomputer/mcpserver` 1.8.8, 192.168.0.90 per-app
endpoints at `mcpserver.<domain>` with basic auth; mcpserver-hub at .91,
`mcphub.<domain>`, one endpoint for all apps, auth through Superpanel). It
only knows a fixed list of apps (`MCPSERVER_APPS` in `lib/mcpserver.sh`,
"keep in sync with APPS in the mcpserver image's entrypoint.py"): listmonk,
nextcloud, espocrm, baserow, bookstack, n8n, immich, gitea, plane, erpnext,
kimai, matomo, wordpress, vaultwarden. An app is linked with
`installapp-mcpserver <app>`, which calls `config_mcpserver_<app>` in the
app's lib file. So a coreapp can't offer tools to the AI today.
What an `ai` need could be:
- The app offers tools: it serves MCP (streamable HTTP) on a path, and the
hub lists it. Needs mcpserver to accept a generic upstream (a URL and a
token per app) instead of its fixed list. Ask Federated
- The app uses the model: through Hermes's OpenAI-compatible API. But that
key is Superpanel's (full agent, all tools); an app would need its own,
limited key, or the provider's key, which is the owner's money. Decide
with Federated
Email (docker-mailserver 16.0.1 at 192.168.0.16, accounts in LDAP): Core
apps send through `mail.<domain>:587` (STARTTLS) as `fcore` (or `admin`)
with the Core's admin password (`MAIL_PASSWORD=$ADMINPASS`, e.g. in
`lib/bookstack.sh`; `SMTPUSER` in `get_appvars`). A coreapp must not get
the admin password, so an `email` need has to create its own mail account
for the app (an LDAP user allowed to send as `<app>@<domain>`). To study:
how `lib/mail.sh` and Superpanel create accounts.
PowerDNS: `*.<domain>` already points every app hostname at the Core, and
traefik gets certificates through the DNS challenge, so apps need nothing
from PowerDNS for `<app>.<domain>`.
## SDK packaging ## SDK packaging
+35 -14
View File
@@ -50,29 +50,47 @@ coreapp deploy # build, copy to the Core, install (or update)
coreapp check # https://my-app.<domain>/ answers, valid certificate coreapp check # https://my-app.<domain>/ answers, valid certificate
``` ```
An app is a folder in the format Federated Core installs apps from An app is a folder (its own git repository) with a `coreapp.toml`, a
(`/federated/services/<app>/` on the Core): `service`, `Dockerfile`, the app's code and an `icon.png`:
`docker-compose.yml.in`, `env.in`, `install`, `uninstall`, `icon.png`, plus
the app's own `Dockerfile`. The README in each new app explains the files. ```toml
name = "my-app" # https://my-app.<domain>
title = "My App"
image = "localhost/coreapp/my-app" # where the Core gets the image
version = "0.1.0"
port = 8080 # the port it serves HTTP on
health = "/" # a path that answers when it's up
needs = ["postgres", "sso"] # its own database; sign-in with Core accounts
```
The app has no scripts or compose file: the Core side is made by
coreapp-dev's installer, `coreapps` (`core/` here, `/opt/coreapps` on the
Core). It checks `coreapp.toml`, picks a free address on that Core, writes
the app in the Core's generic format (`/federated/services/<name>/`), and
sets up what it needs: the traefik route and certificate, its settings and
secrets, its database, its Authelia client. So what an app can do on a Core
is decided by the installer, not by whoever wrote the app. The README in
each new app explains the files and the settings it gets.
| Command | Does | | Command | Does |
|---|---| |---|---|
| `coreapp new <name>` | Make an app in `./<name>`; it gets an address in 192.168.200.x on the Core | | `coreapp new <name>` | Make an app in `./<name>` |
| `coreapp new --postgres <name>` | The same, with its own database on the Core's PostgreSQL (a Python example app that uses it) | | `coreapp new --postgres <name>` | The same, with its own database on the Core's PostgreSQL (a Python example app that uses it) |
| `coreapp new --sso <name>` | The same, with sign-in through the Core's Authelia (OpenID Connect; a Python example app) | | `coreapp new --sso <name>` | The same, with sign-in through the Core's Authelia (OpenID Connect; a Python example app) |
| `coreapp new --postgres --sso <name>` | Both: a database and sign-in (the example counts each person's visits) | | `coreapp new --postgres --sso <name>` | Both: a database and sign-in (the example counts each person's visits) |
| `coreapp deploy` | Build its image, copy it to the Core over SSH, install it, or update it keeping its `.env` | | `coreapp deploy` | Build its image, copy it to the Core over SSH, install it, or update it keeping its settings and data |
| `coreapp check` | It answers at its `MONITOR` URL with a valid certificate | | `coreapp check` | It answers at `https://<name>.<domain><health>` with a valid certificate |
| `coreapp status` / `logs [-f]` / `shell` | Its container, its log, a shell in it | | `coreapp status` / `logs [-f]` / `shell` | Its container, its log, a shell in it |
| `coreapp remove` | Uninstall it from the Core (asks first) | | `coreapp list` | The apps on the Core installed this way |
| `coreapp remove` | Uninstall it from the Core, with its database and sign-in client (asks first) |
`COREAPP_VM` picks the VM (default `coreserver`). `COREAPP_VM` picks the VM (default `coreserver`).
Installing and removing an app go through the Core's own `installapp` and Installing and removing go through the Core's own `installapp` and
`uninstallapp`. Those would also add its `MONITOR` URL to Federated's `uninstallapp`, so the app shows up in Superpanel. The installer gives apps
external monitoring, so `coreapp deploy` copies `service` to the Core without no `MONITOR` line, so they aren't added to Federated's external monitoring.
the `MONITOR` line: apps in development aren't monitored. `coreapp check` The Core's scripts print secrets in their traces; their output is kept in
uses the line from your folder. `/federated/logs/coreapps/` on the Core.
## VM commands ## VM commands
@@ -110,8 +128,11 @@ stay installed.
| `libvirt/network-hook.sh` | NAT and firewall rules for the `coreapp` network | | `libvirt/network-hook.sh` | NAT and firewall rules for the `coreapp` network |
| `bin/coreapp-vm` | Creates and manages CoreServer VMs (`coreapp-vm help`) | | `bin/coreapp-vm` | Creates and manages CoreServer VMs (`coreapp-vm help`) |
| `bin/coreapp` | Makes, deploys and tests apps (`coreapp help`) | | `bin/coreapp` | Makes, deploys and tests apps (`coreapp help`) |
| `core/coreapps` | The installer that runs on the Core (`coreapps help`) |
| `core/templates/` | The Core's generic app files it makes from `coreapp.toml` |
| `core/needs/<need>/` | What each need adds: `env.in` (settings), `setup` and `teardown` (run on the Core), `depends` (the Core app it uses), `compose` (added to the container) |
| `templates/app/` | What `coreapp new` starts from | | `templates/app/` | What `coreapp new` starts from |
| `templates/postgres/`, `templates/sso/` | Laid over it by `--postgres` / `--sso`: their files replace the base's; `*.append` files are added to the base file, `.remove` lists base files to drop, `.depends` the Core apps it needs (merged into `DEPENDS`) | | `templates/postgres/`, `templates/sso/` | Example apps laid over it by `--postgres` / `--sso`: their files replace the base's; `*.append` files are added to the base file, `.remove` lists base files to drop, `.needs` goes into `needs` |
| `templates/postgres-sso/` | The example app when both are used | | `templates/postgres-sso/` | The example app when both are used |
| `uninstall.sh` | Removes what coreapp-dev set up | | `uninstall.sh` | Removes what coreapp-dev set up |
| [PLAN.md](PLAN.md), [TEST.md](TEST.md) | What's next, and how to test it | | [PLAN.md](PLAN.md), [TEST.md](TEST.md) | What's next, and how to test it |
+86 -39
View File
@@ -10,6 +10,7 @@ a temporary folder. Run these on a machine or VM you don't mind changing.
cd ~/Projects/coreapp-dev cd ~/Projects/coreapp-dev
for f in install.sh update.sh uninstall.sh bin/coreapp-vm bin/coreapp libvirt/network-hook.sh; do bash -n "$f"; done for f in install.sh update.sh uninstall.sh bin/coreapp-vm bin/coreapp libvirt/network-hook.sh; do bash -n "$f"; done
shellcheck -x install.sh update.sh uninstall.sh bin/coreapp-vm bin/coreapp libvirt/network-hook.sh shellcheck -x install.sh update.sh uninstall.sh bin/coreapp-vm bin/coreapp libvirt/network-hook.sh
python3 -m py_compile core/coreapps && rm -rf core/__pycache__
``` ```
## install.sh ## install.sh
@@ -140,77 +141,123 @@ On a machine you can rebuild (it removes the network every VM uses):
`~/.config/coreapp-dev`. `~/.config/coreapp-dev`.
4. `bash install.sh` puts everything back. 4. `bash install.sh` puts everything back.
## The installer (coreapps), off the Core
`coreapps manifest <dir>` checks a `coreapp.toml` without a Core. With a
folder holding a valid one (`coreapp new x` makes one), each of these
changes is refused with a message saying what's allowed, and exit 1:
- `port = "8080"` (a string), `port = 0`
- `image = "coreapp/x"` (no registry, which would mean Docker Hub)
- `title = "A $(reboot)"`, a `description` with `"` or `` ` ``
- `name = "x-"`, `name = "X"`, `name = "mail"` (one of the Core's hostnames)
- an unknown setting (`extra = 1`), `needs = ["redis"]`
- a missing `version`
`needs = ["sso", "postgres"]` is accepted and printed in setup order
(`needs=postgres sso`). `coreapps plan <dir>` off the Core (not root) says
to run it as root on the Core.
## Apps (coreapp) ## Apps (coreapp)
Against a Core in the VM (`coreapp-vm list` shows it running). These install Against a Core in the VM (`coreapp-vm list` shows it running). These install
a test app on that Core. It must not be registered with Federated's test apps on that Core. None may be registered with Federated's monitoring:
monitoring: `/federated/services/hello/service` on the Core has no the generated `/federated/services/<name>/service` has no `MONITOR` line.
`MONITOR` line, and `~/.local/share/coreapp-dev/logs/hello-install.log` has The Core's own scripts trace secrets, so their output goes to
no `blackboxregistrar` request. `/federated/logs/coreapps/<name>-<install|update|remove>.log` on the Core
(folder mode 700, files 600), never to the terminal unless a step fails.
1. `cd $(mktemp -d) && coreapp new hello`: `./hello` has `service`, 1. `cd $(mktemp -d) && coreapp new hello`: `./hello` has `coreapp.toml`,
`Dockerfile`, `.dockerignore`, `icon.png`, `www/`, `README.md` and
nothing else, with no `{{...}}` left (`grep -r '{{' hello` prints
nothing). `coreapp new hello` again refuses; so does `coreapp new x-`.
2. `cd hello && coreapp deploy`: updates `/opt/coreapps` on the Core,
builds, copies the image, prints `Installing hello at 192.168.200.x`
(the first free address there) and `Installed: https://hello.<domain>/`.
On the Core, `/federated/services/hello/` has `service`,
`docker-compose.yml.in`, `env.in`, `install`, `uninstall`, `icon.png`, `docker-compose.yml.in`, `env.in`, `install`, `uninstall`, `icon.png`,
`Dockerfile`, `www/`, `README.md`, with no `{{...}}` left `coreapp.toml` and `.coreapp` (`needs=`); `/federated/apps/hello/.env`
(`grep -r '{{' hello` prints nothing). `coreapp new hello` again refuses. is root's, mode 600, with `IMAGE_VERSION` equal to `version` and a
`~/.local/share/coreapp-dev/app-addresses` has `hello 192.168.200.x`. random `APP_SECRET`. Superpanel's catalog
2. `cd hello && coreapp deploy`: builds, copies the image, installs, (`/federated/apps/superpanel/data/catalog.json`) lists `hello`.
prints `Deployed: https://hello.<domain>/`. On the Core,
`/federated/apps/hello/.env` is root's, mode 600, with `IMAGE_VERSION`
equal to `VERSION` and a random `APP_SECRET`.
3. `coreapp check`: `OK: HTTP 200, valid certificate.` (the first 3. `coreapp check`: `OK: HTTP 200, valid certificate.` (the first
certificate can take a minute). certificate can take a minute).
4. Change `www/index.html`, `coreapp deploy`: says "Updating it...", the 4. Change `www/index.html`, `coreapp deploy`: "Updating hello to 0.1.0",
container is recreated, the page shows the change, `APP_SECRET` is the container is recreated, the page shows the change, `.env` is
unchanged. `coreapp deploy` again: "The Core already has this image." unchanged. `coreapp deploy` again: "The Core already has this image."
5. `coreapp status`, `coreapp logs`, `coreapp shell` (exit with `exit`). 5. Raise `version` to 0.2.0, `coreapp deploy`: "Updated"; the container
6. `coreapp remove`, answering y: on the Core, `/federated/apps/hello`, runs `:0.2.0`; `docker image ls localhost/coreapp/hello` on the Core lists
`/federated/services/hello`, the container and the `coreapp/hello` only 0.2.0.
image are gone. Nothing from `uninstallapp`'s trace is printed; it's in 6. `coreapp status` (address and port), `coreapp logs`, `coreapp shell`
`~/.local/share/coreapp-dev/logs/hello-remove.log` (mode 600). (exit with `exit`), `coreapp list` (all apps installed by coreapps).
7. Collisions: an app named like one of Federated's (`coreapp new nextcloud`, 7. `coreapp remove`, answering y: on the Core, `/federated/apps/hello`,
deploy) is refused; so is an `INTERNAL_IP` another container uses. `/federated/services/hello`, the container and the image are gone, and
the catalog no longer lists `hello`.
8. Refused, with nothing changed on the Core:
- `name = "nextcloud"` (one of Federated's apps) or `name = "mail"`
- `image = "localhost/coreapp/nope"` with no such image on the Core
(change `image`, and skip coreapp's build by running
`coreapp-vm ssh /opt/coreapps/coreapps install <dir>` on a copy)
- with the app installed with `needs = ["postgres"]`, deploying with
`needs = []` ("drops needs postgres")
9. On a Core whose tier isn't enterprise, deploying a new app asks before
it's recorded as an add-on; answering no deploys nothing.
### With a database ### With a database
1. `coreapp new --postgres guest-book`: has `app.py`, no `www/`; 1. `coreapp new --postgres guest-book`: has `app.py`, no `www/`;
`service` has `DEPENDS="postgresql"`; `env.in` has `DB_NAME=coreapp_guest_book` `coreapp.toml` has `needs = ["postgres"]` and `health = "/health"`; the
and a random `DB_PASSWORD`; the README has a Database section. README has a Database section.
2. `coreapp deploy`, `coreapp check`. Loading the page several times 2. `coreapp deploy`, `coreapp check`. Loading the page several times
(`curl -s https://guest-book.<domain>/ | grep visits`) counts up. On the (`curl -s https://guest-book.<domain>/ | grep visits`) counts up. On the
Core, `docker exec postgresql psql -U postgres -l` lists `coreapp_guest_book`, Core, `docker exec postgresql psql -U postgres -l` lists `coreapp_guest_book`,
owned by `coreapp_guest_book`. owned by `coreapp_guest_book`; `.env` has `DB_*`.
3. Change `app.py`, `coreapp deploy`: the change shows, the count continues. 3. Change `app.py`, `coreapp deploy`: the change shows, the count continues.
4. `virsh -c qemu:///system reboot coreserver`: once the Core is up, the 4. `virsh -c qemu:///system reboot coreserver`: once the Core is up, the
app answers and the count continues (its log may show "Waiting for the app answers and the count continues (its log may show "Waiting for the
database" first). database" first).
5. `coreapp remove`: the `coreapp_guest_book` database and user are gone too. 5. `coreapp remove`: the `coreapp_guest_book` database and user are gone too.
Adding a need later: install `coreapp new notes` (no needs), then set
`needs = ["postgres"]` and deploy: "Updating", `.env` gains `DB_*` (the
other values unchanged), the database `coreapp_notes` exists, the container
has the `DB_*` variables, `.coreapp` says `needs=postgres`.
### With sign-in ### With sign-in
1. `coreapp new --sso sso-demo`: has `app.py`, no `www/`; `service` has 1. `coreapp new --sso sso-demo`: has `app.py` and `oidc.py`, no `www/`;
`DEPENDS="authelia"`; `docker-compose.yml.in` has `extra_hosts` with `needs = ["sso"]`; the README has a Sign-in section.
`@TRAEFIK_IP@`; `env.in` has `OIDC_*`; `app.py` and `oidc.py`; the README
has a Sign-in section.
2. `coreapp deploy`, `coreapp check`. On the Core, `idproviders.yml` has one 2. `coreapp deploy`, `coreapp check`. On the Core, `idproviders.yml` has one
`### coreapp-sso-demo begin` block; Authelia is healthy; `### coreapp-sso-demo begin` block; Authelia is healthy;
`docker exec authelia authelia validate-config` is OK; no `*.bak` is `docker exec authelia authelia validate-config` is OK; no `*.bak` is
left; the rendered compose file maps `authelia.<domain>` to traefik's left; `/federated/apps/sso-demo/docker-compose.yml` maps
address. `authelia.<domain>` to traefik's address (`extra_hosts`).
3. `https://sso-demo.<domain>/login` redirects to 3. `https://sso-demo.<domain>/login` redirects to
`https://authelia.<domain>/api/oidc/authorization?...client_id=coreapp-sso-demo...code_challenge_method=S256`. `https://authelia.<domain>/api/oidc/authorization?...client_id=coreapp-sso-demo...code_challenge_method=S256`.
4. In a browser, sign in with a Core account: the page says "Signed in as 4. In a browser, sign in with a Core account: the page says "Signed in as
..." with the account's email and groups. "Sign out" goes back to the ..." with the account's email and groups. "Sign out" goes back to the
sign-in link. sign-in link.
5. Redeploy: still one client block. `coreapp remove`: none, Authelia 5. Redeploy: still one client block, and Authelia isn't restarted
healthy, other clients (Nextcloud) still work. Deploy again: one block. (`docker inspect -f '{{.State.StartedAt}}' authelia` unchanged).
`coreapp remove`: no block, Authelia healthy, other clients (Nextcloud)
still work. Deploy again: one block.
### With both ### With both
1. `coreapp new --postgres --sso team-visits`: `service` has 1. `coreapp new --postgres --sso team-visits`: `needs = ["postgres",
`DEPENDS="postgresql authelia"`; `env.in` has `DB_*` and `OIDC_*`; "sso"]`; `app.py` imports `oidc` and `psycopg`.
`install` creates the database and registers the client; `uninstall` 2. `coreapp deploy`, `coreapp check`. On the Core, `service` has
undoes both; `app.py` imports `oidc` and `psycopg`. `DEPENDS="postgresql authelia"`, `.env` has `DB_*` and `OIDC_*`. In a
2. `coreapp deploy`, `coreapp check`. In a browser, sign in: the page shows browser, sign in: the page shows your name and "Your visits", which
your name and "Your visits", which counts up on reload. Another account counts up on reload. Another account gets its own count; "people who have
gets its own count; "people who have visited" counts both. visited" counts both.
3. `coreapp remove`: the database, user and Authelia client are gone. 3. `coreapp remove`: the database, user and Authelia client are gone.
### Apps deployed before coreapp.toml
An app deployed by an older coreapp (its own `service`, `install`, ... and
an empty `.coreapp` marker on the Core) moves over by replacing those files
with a `coreapp.toml` with the same name, image and needs. `coreapp deploy`
then updates it: same address, `.env` and data unchanged, no needs set up
again (they're read from its `DEPENDS`), Authelia not restarted; `.coreapp`
then says which needs it has.
+93 -170
View File
@@ -12,26 +12,23 @@
# coreapp logs [-f] its log # coreapp logs [-f] its log
# coreapp shell a shell in its container # coreapp shell a shell in its container
# coreapp remove uninstall it from the Core (asks first) # coreapp remove uninstall it from the Core (asks first)
# coreapp list the apps on the Core installed this way
# #
# Run everything but `new` in the app's folder. COREAPP_VM picks the VM # Run everything but `new` and `list` in the app's folder (the one with
# (default coreserver). # coreapp.toml). COREAPP_VM picks the VM (default coreserver).
set -euo pipefail set -euo pipefail
SELF_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)" SELF_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
TEMPLATES="$(dirname "$SELF_DIR")/templates" TEMPLATES="$(dirname "$SELF_DIR")/templates"
TEMPLATE="$TEMPLATES/app" TEMPLATE="$TEMPLATES/app"
# The installer that runs on the Core (coreapps), and where it goes there
INSTALLER="$(dirname "$SELF_DIR")/core"
REMOTE_INSTALLER=/opt/coreapps
DATA="$HOME/.local/share/coreapp-dev" DATA="$HOME/.local/share/coreapp-dev"
# The INTERNAL_IP given to each app made on this machine: "name ip" lines
ADDRESSES="$DATA/app-addresses"
# Apps get addresses here, away from Federated's apps in 192.168.0.x (both
# are in the Core's 192.168.0.0/16 network)
PREFIX=192.168.200
SSH_KEY="$DATA/ssh/id_ed25519" SSH_KEY="$DATA/ssh/id_ed25519"
KNOWN_HOSTS="$DATA/ssh/known_hosts" KNOWN_HOSTS="$DATA/ssh/known_hosts"
VM="${COREAPP_VM:-coreserver}" VM="${COREAPP_VM:-coreserver}"
# What the Core installs an app from; the rest of the folder stays here
CORE_FILES=(service docker-compose.yml.in env.in install uninstall icon.png timers services upgrade)
die() { echo "$*" >&2; exit 1; } die() { echo "$*" >&2; exit 1; }
@@ -77,45 +74,57 @@ core_domain() {
# --- The app in the current folder --------------------------------------- # --- The app in the current folder ---------------------------------------
# NAME is the app's id (its folder on the Core); TITLE is NAME in service # From coreapp.toml, as checked by the installer
NAME="" TITLE="" CONTAINER="" VERSION="" INTERNAL_IP="" MONITOR="" HIDDEN="" PORTS="" NAME="" TITLE="" VERSION="" IMAGE="" PORT="" HEALTH="" NEEDS=""
load_app() { load_app() {
[[ -f service && -f install ]] \ local values key value
|| die "No app here: run this in an app's folder (one with service and install), or make one with coreapp new <name>." [[ -f coreapp.toml ]] \
# service is shell variables, as the Core reads it || die "No app here: run this in an app's folder (one with coreapp.toml), or make one with coreapp new <name>."
set +u values="$(python3 "$INSTALLER/coreapps" manifest .)" || exit 1
# shellcheck source=/dev/null while IFS='=' read -r key value; do
. ./service case "$key" in
set -u name) NAME="$value" ;;
TITLE="$NAME" title) TITLE="$value" ;;
NAME="$(sed -n 's/^installGeneric[[:space:]]\{1,\}\([a-z0-9-]*\).*/\1/p' install | head -n 1)" version) VERSION="$value" ;;
[[ -n "$NAME" ]] || die "install doesn't say which app it is (installGeneric <name>)." image) IMAGE="$value" ;;
[[ -n "$CONTAINER" && -n "$VERSION" && -n "$INTERNAL_IP" ]] \ port) PORT="$value" ;;
|| die "service needs CONTAINER, VERSION and INTERNAL_IP." health) HEALTH="$value" ;;
needs) NEEDS="$value" ;;
esac
done <<< "$values"
init_core init_core
} }
image() { echo "$CONTAINER:$VERSION"; } image() { echo "$IMAGE:$VERSION"; }
# Put the installer on the Core, as this coreapp-dev has it
sync_installer() {
tar -C "$INSTALLER" --exclude=__pycache__ --exclude=.claude -cf - . | core "
set -e
rm -rf $REMOTE_INSTALLER.new && mkdir -p $REMOTE_INSTALLER.new
tar --no-same-owner -xf - -C $REMOTE_INSTALLER.new
rm -rf $REMOTE_INSTALLER && mv $REMOTE_INSTALLER.new $REMOTE_INSTALLER"
}
# Run the installer on the Core with this app's coreapp.toml and icon.png,
# copied to a temporary folder there: coreapps <command> [options] <folder>
installer() {
local files=(coreapp.toml)
[[ -f icon.png ]] && files+=(icon.png)
tar -cf - "${files[@]}" | core "
d=\$(mktemp -d) && tar --no-same-owner -xf - -C \$d || exit 1
$REMOTE_INSTALLER/coreapps $* \$d; status=\$?
rm -rf \$d; exit \$status"
}
# --- new -------------------------------------------------------------------- # --- new --------------------------------------------------------------------
next_address() {
local n
for n in $(seq 10 250); do
if ! grep -qs " $PREFIX\.$n\$" "$ADDRESSES"; then
echo "$PREFIX.$n"
return
fi
done
die "All addresses in $PREFIX.10-250 are taken (see $ADDRESSES)."
}
# Lay an overlay over the app in $1: its files replace the app's, except # Lay an overlay over the app in $1: its files replace the app's, except
# *.append (added to the end of the app's file), .remove (app files it # *.append (added to the end of the app's file), .remove (app files it
# doesn't use) and .depends (apps it needs, for DEPENDS in service) # doesn't use) and .needs (what it needs from the Core, for coreapp.toml)
apply_overlay() { apply_overlay() {
local app="$1" overlay="$2" f local app="$1" overlay="$2" f
tar -C "$overlay" --exclude=.claude --exclude=.remove --exclude=.depends \ tar -C "$overlay" --exclude=.claude --exclude=.remove --exclude=.needs \
--exclude='*.append' -cf - . | tar -C "$app" -xf - --exclude='*.append' -cf - . | tar -C "$app" -xf -
for f in "$overlay"/*.append; do for f in "$overlay"/*.append; do
[[ -e "$f" ]] && cat "$f" >> "$app/$(basename "$f" .append)" [[ -e "$f" ]] && cat "$f" >> "$app/$(basename "$f" .append)"
@@ -126,7 +135,7 @@ apply_overlay() {
} }
cmd_new() { cmd_new() {
local name="" postgres="" sso="" title ip dbname f depends="" what="" local name="" postgres="" sso="" title dbname f needs="" what=""
local overlays=() local overlays=()
while [[ $# -gt 0 ]]; do while [[ $# -gt 0 ]]; do
case "$1" in case "$1" in
@@ -139,8 +148,8 @@ cmd_new() {
done done
[[ -d "$TEMPLATE" ]] || die "The app template is missing: $TEMPLATE" [[ -d "$TEMPLATE" ]] || die "The app template is missing: $TEMPLATE"
[[ -n "$name" ]] || die "Usage: coreapp new [--postgres] [--sso] <name> (lowercase letters, digits and -)" [[ -n "$name" ]] || die "Usage: coreapp new [--postgres] [--sso] <name> (lowercase letters, digits and -)"
[[ "$name" =~ ^[a-z][a-z0-9-]{1,30}$ ]] \ [[ "$name" =~ ^[a-z]([a-z0-9-]{0,29}[a-z0-9])$ ]] \
|| die "'$name': use 2-31 lowercase letters, digits and -, starting with a letter. It becomes https://$name.<domain>." || die "'$name': use 2-31 lowercase letters, digits and -, starting with a letter and not ending with -. It becomes https://$name.<domain>."
[[ ! -e "$name" ]] || die "./$name already exists." [[ ! -e "$name" ]] || die "./$name already exists."
# In this order; with both, the combined example app goes on top # In this order; with both, the combined example app goes on top
@@ -151,15 +160,7 @@ cmd_new() {
[[ -d "$f" ]] || die "The template $f is missing." [[ -d "$f" ]] || die "The template $f is missing."
done done
ip="$(grep -s "^$name " "$ADDRESSES" | cut -d' ' -f2 || true)" # "my-app" -> "My App". The database name is the installer's (coreapps)
if [[ -z "$ip" ]]; then
ip="$(next_address)"
mkdir -p "$DATA"
echo "$name $ip" >> "$ADDRESSES"
fi
# "my-app" -> "My App". Database names: no "-", and a prefix, because
# PostgreSQL reserves names starting with pg_ and Federated's apps have
# their own databases (nextcloud, superpanel, ...)
title="$(echo "$name" | sed -E 's/-/ /g; s/(^| )([a-z])/\1\u\2/g')" title="$(echo "$name" | sed -E 's/-/ /g; s/(^| )([a-z])/\1\u\2/g')"
dbname="coreapp_${name//-/_}" dbname="coreapp_${name//-/_}"
@@ -167,61 +168,47 @@ cmd_new() {
tar -C "$TEMPLATE" --exclude=.claude -cf - . | tar -C "$name" -xf - tar -C "$TEMPLATE" --exclude=.claude -cf - . | tar -C "$name" -xf -
for f in "${overlays[@]}"; do for f in "${overlays[@]}"; do
apply_overlay "$name" "$f" apply_overlay "$name" "$f"
[[ -f "$f/.depends" ]] && depends="$depends $(cat "$f/.depends")" [[ -f "$f/.needs" ]] && needs="$needs, \"$(cat "$f/.needs")\""
done done
depends="${depends# }" sed -i "s/^needs = .*/needs = [${needs#, }]/" "$name/coreapp.toml"
sed -i "s/^DEPENDS=.*/DEPENDS=\"$depends\"/" "$name/service" # The example apps with a database or sign-in have a /health path
[[ ${#overlays[@]} -gt 0 ]] && sed -i 's|^health = .*|health = "/health"|' "$name/coreapp.toml"
while IFS= read -r -d '' f; do while IFS= read -r -d '' f; do
sed -i -e "s/{{NAME}}/$name/g" -e "s/{{TITLE}}/$title/g" -e "s/{{IP}}/$ip/g" \ sed -i -e "s/{{NAME}}/$name/g" -e "s/{{TITLE}}/$title/g" -e "s/{{DBNAME}}/$dbname/g" "$f"
-e "s/{{DBNAME}}/$dbname/g" "$f"
done < <(find "$name" -type f ! -name '*.png' -print0) done < <(find "$name" -type f ! -name '*.png' -print0)
[[ -n "$postgres" ]] && what=", database $dbname" [[ -n "$postgres" ]] && what=", with a database"
[[ -n "$sso" ]] && what="$what, sign-in through Authelia" [[ -n "$sso" ]] && what="$what, with sign-in through Authelia"
echo "Made $title in ./$name (address on the Core: $ip$what)." echo "Made $title in ./$name$what."
echo "Next: cd $name && coreapp deploy" echo "Next: cd $name && coreapp deploy"
} }
# --- deploy ----------------------------------------------------------------- # --- deploy -----------------------------------------------------------------
cmd_deploy() { cmd_deploy() {
local domain info state theirs tier used local_id core_id f log files=() local plan state tier answer local_id core_id addon=""
load_app load_app
domain="$(core_domain)"
# What the Core has: is the app installed, is the name or address taken? echo "Updating the installer on the Core ($REMOTE_INSTALLER)..."
info="$(core " sync_installer
. /etc/federated # What installing would do (and whether the Core refuses it: name taken...)
echo \"tier \$TIER\" plan="$(installer plan)" || exit 1
[ -d /federated/apps/$NAME ] && echo installed || echo new state="$(sed -n 's/^state=//p' <<< "$plan")"
if [ -f /federated/services/$NAME/service ]; then tier="$(sed -n 's/^tier=//p' <<< "$plan")"
echo \"theirs \$(sed -n 's/^CONTAINER=//p' /federated/services/$NAME/service)\" if grep -qx 'addon=yes' <<< "$plan"; then
fi
docker network inspect core -f '{{range .Containers}}{{.Name}} {{.IPv4Address}}{{println}}{{end}}' \
| grep ' $INTERNAL_IP/' | sed 's/^/used /' || true
")"
tier="$(sed -n 's/^tier //p' <<< "$info")"
state="$(grep -xE 'installed|new' <<< "$info")"
theirs="$(sed -n 's/^theirs //p' <<< "$info")"
used="$(sed -n 's/^used \([^ ]*\) .*/\1/p' <<< "$info" | grep -vx "$NAME" || true)"
if [[ -n "$theirs" && "$theirs" != "$CONTAINER" ]]; then
die "The Core already has an app called '$NAME' ($theirs). Pick another name."
fi
if [[ -n "$used" ]]; then
die "$INTERNAL_IP is already used on the Core by: $used. Change INTERNAL_IP in service (and docker-compose.yml.in)."
fi
if [[ "$state" == new && "${tier,,}" != enterprise && "$HIDDEN" != true ]]; then
echo "This Core's tier is '$tier'. Installing records '$NAME' as an add-on app" echo "This Core's tier is '$tier'. Installing records '$NAME' as an add-on app"
echo "(ADDON_APPS in /etc/federated), which Federated may bill for." echo "(ADDON_APPS in /etc/federated), which Federated may bill for."
read -r -p "Install anyway? [y/N] " f read -r -p "Install anyway? [y/N] " answer
[[ "$f" =~ ^[Yy] ]] || die "Not deployed. HIDDEN=true in service keeps an app off that list." [[ "$answer" =~ ^[Yy] ]] || die "Not deployed."
addon=--addon-ok
fi fi
echo "Building $(image)..." echo "Building $(image)..."
docker build -q -t "$(image)" . > /dev/null docker build -q -t "$(image)" . > /dev/null
# localhost/ images exist only where they're copied; others the Core can
# pull, but while developing, the one just built is the one to test
local_id="$(docker image inspect -f '{{.Id}}' "$(image)")" local_id="$(docker image inspect -f '{{.Id}}' "$(image)")"
core_id="$(core "docker image inspect -f '{{.Id}}' $(image) 2> /dev/null || true")" core_id="$(core "docker image inspect -f '{{.Id}}' $(image) 2> /dev/null || true")"
if [[ "$local_id" != "$core_id" ]]; then if [[ "$local_id" != "$core_id" ]]; then
@@ -231,82 +218,21 @@ cmd_deploy() {
echo "The Core already has this image." echo "The Core already has this image."
fi fi
echo "Copying the app to /federated/services/$NAME..." # Install, or update (which recreates the container if the image changed,
for f in "${CORE_FILES[@]}"; do [[ -e "$f" ]] && files+=("$f"); done # even under the same version)
tar -cf - "${files[@]}" | core " installer install $addon || exit 1
set -e [[ "$state" == new ]] && echo "(coreapp check tests it from the internet.)"
d=/federated/services/$NAME return 0
rm -rf \$d.new && mkdir -p \$d.new && tar --no-same-owner -xf - -C \$d.new
# No MONITOR on the Core: installapp would register it with Federated's
# external monitoring, which apps in development shouldn't be in
sed -i '/^MONITOR=/d' \$d.new/service
rm -rf \$d && mv \$d.new \$d"
if [[ "$state" == new ]]; then
echo "Installing it (the Core's installapp)..."
mkdir -p "$DATA/logs"
log="$DATA/logs/$NAME-install.log"
# installapp traces what it runs, tokens included: keep that private
: > "$log" && chmod 600 "$log"
if ! core "/federated/bin/installapp -n $NAME" > "$log" 2>&1; then
tail -n 20 "$log" >&2
die "installapp failed (whole log: $log)."
fi
# installapp's start step only knows Federated's own apps (the list in
# /federated/lib/functions.sh), so start it the way the Core does
core "docker compose -f /federated/apps/$NAME/docker-compose.yml -p $NAME up -d 2>&1 | grep -v '^ *Container ' || true"
else
# Keep .env (its random secrets); redo the compose file, which may have
# changed, and the version
echo "Updating it..."
core "
set -e
cd /federated
. /etc/federated
. lib/helpers.sh
. services/$NAME/service
# The same extra values the template's install provides
TRAEFIK_IP=\"\$(sed -n 's/^INTERNAL_IP=//p' services/traefik/service)\"
templatize services/$NAME/docker-compose.yml.in > apps/$NAME/docker-compose.yml
sed -i 's/^IMAGE_VERSION=.*/IMAGE_VERSION=$VERSION/' apps/$NAME/.env
docker compose -f apps/$NAME/docker-compose.yml -p $NAME up -d --remove-orphans 2>&1 | grep -v '^ *Container .* Running\$' || true"
fi
if [[ "$(core "docker inspect -f '{{.State.Status}}' $NAME 2> /dev/null || true")" != running ]]; then
core "docker logs --tail 20 $NAME 2>&1" >&2 || true
die "$NAME isn't running on the Core (its log is above, if it has one)."
fi
# Running isn't answering: wait until it answers on its own address and
# port (PORTS in service), from the Core, as traefik reaches it
if [[ -n "$PORTS" ]]; then
echo -n "Waiting for it to answer on $INTERNAL_IP:${PORTS%% *}..."
if ! core "for i in \$(seq 1 30); do
curl -s -o /dev/null --max-time 2 http://$INTERNAL_IP:${PORTS%% *}/ && exit 0
sleep 2
done; exit 1"; then
echo
core "docker logs --tail 20 $NAME 2>&1" >&2 || true
die "$NAME runs but doesn't answer on port ${PORTS%% *} after a minute (its log is above)."
fi
echo " it does."
fi
echo "Deployed: https://$NAME.$domain/ (coreapp check tests it)"
} }
# --- check, status, logs, shell, remove ------------------------------------ # --- check, status, logs, shell, remove ------------------------------------
cmd_check() { cmd_check() {
local domain url expect result code verify tries=24 local domain url result code verify tries=24
load_app load_app
domain="$(core_domain)" domain="$(core_domain)"
url="https://$NAME.$domain/" url="https://$NAME.$domain$HEALTH"
expect="http_2xx" echo "Checking $url (expecting HTTP 2xx and a valid certificate)..."
if [[ -n "$MONITOR" ]]; then
url="${MONITOR%%|*}"
url="${url//@DOMAIN@/$domain}"
[[ "$MONITOR" == *"|"* ]] && expect="${MONITOR#*|}"
fi
echo "Checking $url (expecting $expect)..."
# A new app's certificate can take a minute: traefik gets it from Let's # A new app's certificate can take a minute: traefik gets it from Let's
# Encrypt through the Core's DNS # Encrypt through the Core's DNS
while true; do while true; do
@@ -335,8 +261,9 @@ cmd_status() {
domain="$(core_domain)" domain="$(core_domain)"
core "docker ps -a --filter name='^$NAME\$' --format 'Container: {{.Names}} {{.Status}} image {{.Image}}' core "docker ps -a --filter name='^$NAME\$' --format 'Container: {{.Names}} {{.Status}} image {{.Image}}'
[ -n \"\$(docker ps -aq --filter name='^$NAME\$')\" ] || echo 'Not installed on the Core.'" [ -n \"\$(docker ps -aq --filter name='^$NAME\$')\" ] || echo 'Not installed on the Core.'"
echo "App: $TITLE $VERSION ($CONTAINER)" echo "App: $TITLE $(image)"
echo "Address on the Core: $INTERNAL_IP" echo "Address on the Core: $(core "sed -n 's/^INTERNAL_IP=//p' /federated/services/$NAME/service 2> /dev/null"), port $PORT"
echo "Needs: ${NEEDS:-nothing}"
echo "URL: https://$NAME.$domain/" echo "URL: https://$NAME.$domain/"
} }
@@ -355,25 +282,20 @@ cmd_shell() {
} }
cmd_remove() { cmd_remove() {
local answer log local answer
load_app load_app
echo "This uninstalls $NAME from the Core in '$VM', with its settings and data" echo "This uninstalls $NAME from the Core in '$VM', with its settings and data"
echo "there. This folder stays as it is." echo "there${NEEDS:+ (and what it has in: $NEEDS)}. This folder stays as it is."
read -r -p "Remove it? [y/N] " answer read -r -p "Remove it? [y/N] " answer
[[ "$answer" =~ ^[Yy] ]] || die "Not removed." [[ "$answer" =~ ^[Yy] ]] || die "Not removed."
mkdir -p "$DATA/logs" sync_installer
log="$DATA/logs/$NAME-remove.log" core "$REMOTE_INSTALLER/coreapps remove $NAME"
# uninstallapp traces what it runs, tokens included: keep that private }
: > "$log" && chmod 600 "$log"
if ! core " cmd_list() {
set -e init_core
if [ -d /federated/apps/$NAME ]; then /federated/bin/uninstallapp $NAME; fi sync_installer
rm -rf /federated/services/$NAME core "$REMOTE_INSTALLER/coreapps list"
docker image ls -q '$CONTAINER' | xargs -r docker image rm -f" > "$log" 2>&1; then
tail -n 20 "$log" >&2
die "Removing failed (whole log: $log)."
fi
echo "Removed $NAME from the Core."
} }
cmd="${1:-help}" cmd="${1:-help}"
@@ -386,6 +308,7 @@ case "$cmd" in
logs) cmd_logs "$@" ;; logs) cmd_logs "$@" ;;
shell) cmd_shell ;; shell) cmd_shell ;;
remove | rm) cmd_remove ;; remove | rm) cmd_remove ;;
list | ls) cmd_list ;;
help | -h | --help) usage ;; help | -h | --help) usage ;;
*) usage >&2; exit 1 ;; *) usage >&2; exit 1 ;;
esac esac
Executable
+541
View File
@@ -0,0 +1,541 @@
#!/usr/bin/env python3
"""Install apps described by a coreapp.toml on this Federated Core.
Runs on the Core as root (coreapp-dev puts it in /opt/coreapps). An app is
a coreapp.toml, an icon.png and an image: the app's repository has no
scripts or compose file of its own. This program checks the manifest and
makes the Core's generic app format (/federated/services/<name>/) from its
own templates, so what an app can do on the Core is decided here, not by
whoever wrote the app.
coreapps manifest <dir> check <dir>/coreapp.toml, print its values
coreapps plan <dir> what install would do on this Core
coreapps install [--addon-ok] <dir> install the app, or update it
coreapps remove <name> uninstall an app installed by coreapps
coreapps list the apps installed by coreapps
`manifest` also works off the Core. install exits with 3 if this Core's
tier would record the app as a billable add-on and --addon-ok isn't given.
"""
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import tomllib
import urllib.error
import urllib.request
HERE = os.path.dirname(os.path.realpath(__file__))
TEMPLATES = os.path.join(HERE, "templates")
NEEDS_DIR = os.path.join(HERE, "needs")
FEDERATED = "/federated"
SERVICES = FEDERATED + "/services"
APPS = FEDERATED + "/apps"
LOGS = FEDERATED + "/logs/coreapps"
# Marks a services folder as made by coreapps (and holds what it set up)
MARKER = ".coreapp"
# Addresses for apps, away from Federated's 192.168.0.x (all in the core
# network's 192.168.0.0/16)
PREFIX = "192.168.200."
FIRST, LAST = 10, 250
# Hostnames on the Core that aren't apps in /federated/services or lib
RESERVED = {"www", "mail", "ns1", "ns2", "autodiscover", "autoconfig",
"panel", "dashboard", "mcphub", "api", "admin"}
# What an app can ask for, in the order they're set up
NEEDS = ["postgres", "sso"]
# What coreapp.toml may contain. Values end up in shell-sourced and YAML
# files on the Core, so each is limited to characters that are safe there.
FIELDS = {
"name": r"[a-z](?:[a-z0-9-]{0,29}[a-z0-9])",
"title": r"[A-Za-z0-9][A-Za-z0-9 .,!?()&+_-]{0,39}",
"description": r"[^\"$`\\@\x00-\x1f\x7f]{0,200}",
"version": r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}",
# The registry is part of the name (localhost/... for images that only
# exist on this Core), so it's never Docker Hub by accident
"image": (r"(?:localhost|[a-z0-9-]+(?:\.[a-z0-9-]+)+)(?::[0-9]{1,5})?"
r"(?:/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)+"),
"port": None,
"health": r"/[A-Za-z0-9._~/-]{0,100}",
"docs": r"(?:https://[A-Za-z0-9.-]+(?::[0-9]{1,5})?(?:/[A-Za-z0-9._~/%+-]*)?)?",
"needs": None,
}
REQUIRED = ["name", "title", "version", "image", "port"]
class Refused(Exception):
"""The app can't be installed as it is; the message says why."""
def say(*args):
print(*args, flush=True)
# --- coreapp.toml -------------------------------------------------------------
def read_manifest(folder):
"""coreapp.toml in folder, checked, with defaults filled in."""
path = os.path.join(folder, "coreapp.toml")
try:
with open(path, "rb") as f:
data = tomllib.load(f)
except FileNotFoundError:
raise Refused(f"No coreapp.toml in {folder}.")
except tomllib.TOMLDecodeError as e:
raise Refused(f"coreapp.toml isn't valid TOML: {e}")
unknown = sorted(set(data) - set(FIELDS))
if unknown:
raise Refused(f"coreapp.toml: unknown setting(s) {', '.join(unknown)} "
f"(it knows {', '.join(FIELDS)}).")
missing = [k for k in REQUIRED if k not in data]
if missing:
raise Refused(f"coreapp.toml needs {', '.join(missing)}.")
m = {"description": "", "health": "/", "docs": "", "needs": []}
for key, value in data.items():
if key == "port":
if not isinstance(value, int) or isinstance(value, bool) or not 1 <= value <= 65535:
raise Refused("coreapp.toml: port must be a number from 1 to 65535.")
elif key == "needs":
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
raise Refused('coreapp.toml: needs must be a list, like needs = ["postgres", "sso"].')
bad = [v for v in value if v not in NEEDS]
if bad:
raise Refused(f"coreapp.toml: needs: unknown {', '.join(bad)} "
f"(it knows {', '.join(NEEDS)}).")
value = [n for n in NEEDS if n in value]
else:
if not isinstance(value, str) or not re.fullmatch(FIELDS[key], value):
raise Refused(f"coreapp.toml: {key} = {value!r} isn't allowed. "
+ HINTS.get(key, ""))
m[key] = value
if m["name"] in RESERVED:
raise Refused(f"'{m['name']}' is one of the Core's own hostnames. Pick another name.")
m["dbname"] = "coreapp_" + m["name"].replace("-", "_")
return m
HINTS = {
"name": "Use 2-31 lowercase letters, digits and -, starting with a letter "
"and not ending with -. It becomes https://<name>.<domain>.",
"title": "Up to 40 letters, digits, spaces and . , ! ? ( ) & + _ -",
"description": "Up to 200 characters, without \" $ ` \\ @ or line breaks.",
"version": "Letters, digits, . _ and - (it's the image's tag).",
"image": "Include the registry: localhost/coreapp/<name> for an image you "
"copy to the Core, or e.g. gitea.example.com/owner/<name>.",
"health": "A path, like /health.",
"docs": "An https:// address.",
}
# --- This Core ------------------------------------------------------------------
def run(cmd, **kw):
return subprocess.run(cmd, text=True, capture_output=True, **kw)
def federated_settings():
"""/etc/federated's values (it's shell, so let bash read it)."""
out = run(["bash", "-c", '. /etc/federated; echo "$DOMAIN"; echo "$TIER"'])
if out.returncode != 0:
raise Refused("This isn't a Federated Core (no /etc/federated).")
domain, tier = (out.stdout.splitlines() + ["", ""])[:2]
return domain, tier
def service_value(path, key):
"""A value from a generic app's service file, without running it."""
try:
with open(path) as f:
for line in f:
m = re.match(rf'{key}=(["\']?)(.*)\1\s*$', line.strip())
if m:
return m.group(2)
except OSError:
pass
return ""
def is_ours(name):
folder = os.path.join(SERVICES, name)
if os.path.exists(os.path.join(folder, MARKER)):
return True
return False
def marker_needs(name):
"""What coreapps set up for an installed app (from its marker)."""
folder = os.path.join(SERVICES, name)
try:
with open(os.path.join(folder, MARKER)) as f:
for line in f:
if line.startswith("needs="):
return line.split("=", 1)[1].split()
except OSError:
return []
# Folders deployed before coreapp.toml: tell from DEPENDS
depends = service_value(os.path.join(folder, "service"), "DEPENDS").split()
return [n for n in NEEDS if read_text(NEEDS_DIR, n, "depends").strip() in depends]
def used_addresses():
used = set()
out = run(["docker", "network", "inspect", "core", "-f",
"{{range .Containers}}{{.IPv4Address}} {{end}}"])
for cidr in out.stdout.split():
used.add(cidr.split("/")[0])
for name in os.listdir(SERVICES):
ip = service_value(os.path.join(SERVICES, name, "service"), "INTERNAL_IP")
if ip:
used.add(ip)
return used
def pick_address(name):
"""The app's address: the one it has, or the first free one."""
if is_ours(name):
ip = service_value(os.path.join(SERVICES, name, "service"), "INTERNAL_IP")
if ip:
return ip
used = used_addresses()
for n in range(FIRST, LAST + 1):
if PREFIX + str(n) not in used:
return PREFIX + str(n)
raise Refused(f"No free address left in {PREFIX}{FIRST}-{LAST}.")
def plan(m):
"""What installing m would do here, or Refused."""
name = m["name"]
domain, tier = federated_settings()
if not domain:
raise Refused("This Core isn't provisioned yet (no DOMAIN in /etc/federated).")
if os.path.exists(os.path.join(SERVICES, name)) and not is_ours(name):
raise Refused(f"This Core already has an app called '{name}' "
f"({service_value(os.path.join(SERVICES, name, 'service'), 'CONTAINER') or 'Federated'}). "
"Pick another name.")
if os.path.exists(os.path.join(FEDERATED, "lib", name + ".sh")):
raise Refused(f"'{name}' is the name of one of Federated's apps. Pick another name.")
installed = os.path.isdir(os.path.join(APPS, name))
if installed and not is_ours(name):
raise Refused(f"/federated/apps/{name} exists but wasn't installed by coreapps.")
p = {
"state": "update" if installed else "new",
"domain": domain,
"tier": tier,
"address": pick_address(name),
"url": f"https://{name}.{domain}/",
}
p["addon"] = "yes" if p["state"] == "new" and tier.lower() != "enterprise" else "no"
if installed:
before = marker_needs(name)
dropped = [n for n in before if n not in m["needs"]]
if dropped:
raise Refused(f"The new coreapp.toml drops needs {', '.join(dropped)}; "
"removing them would delete what the app keeps there. "
"Remove the app and install it again to do that.")
p["new_needs"] = [n for n in m["needs"] if n not in before]
else:
p["new_needs"] = list(m["needs"])
return p
# --- Making the app's files ---------------------------------------------------
def read_text(*parts):
try:
with open(os.path.join(*parts)) as f:
return f.read()
except FileNotFoundError:
return ""
def fill(text, values):
for key, value in values.items():
text = text.replace("{{" + key + "}}", value)
return text
def write(path, text, mode=0o644):
with open(path, "w") as f:
f.write(text)
os.chmod(path, mode)
def icon_from(folder):
"""The app's icon.png if it's a reasonable PNG, else the default."""
path = os.path.join(folder, "icon.png")
try:
if os.path.getsize(path) <= 1024 * 1024:
with open(path, "rb") as f:
if f.read(8) == b"\x89PNG\r\n\x1a\n":
return path
except OSError:
pass
return os.path.join(TEMPLATES, "icon.png")
def make_service_folder(m, p, source):
"""/federated/services/<name>/ in the Core's generic format, from m."""
values = {
"NAME": m["name"], "TITLE": m["title"], "DESCRIPTION": m["description"],
"DOCS": m["docs"], "IMAGE": m["image"], "VERSION": m["version"],
"IP": p["address"], "PORT": str(m["port"]), "DBNAME": m["dbname"],
"DEPENDS": " ".join(read_text(NEEDS_DIR, n, "depends").strip() for n in m["needs"]),
}
compose_extra = "".join(read_text(NEEDS_DIR, n, "compose") for n in m["needs"])
compose = read_text(TEMPLATES, "docker-compose.yml.in").replace(
"{{COMPOSE_EXTRA}}\n", compose_extra)
env = read_text(TEMPLATES, "env.in") + "".join(
read_text(NEEDS_DIR, n, "env.in") for n in m["needs"])
final = os.path.join(SERVICES, m["name"])
new = final + ".new"
shutil.rmtree(new, ignore_errors=True)
os.makedirs(new)
write(os.path.join(new, "service"), fill(read_text(TEMPLATES, "service"), values))
write(os.path.join(new, "docker-compose.yml.in"), fill(compose, values))
write(os.path.join(new, "env.in"), fill(env, values))
write(os.path.join(new, "install"), fill(read_text(TEMPLATES, "install"), values), 0o755)
write(os.path.join(new, "uninstall"), fill(read_text(TEMPLATES, "uninstall"), values), 0o755)
for need in m["needs"]:
os.makedirs(os.path.join(new, "needs", need))
for step in ("setup", "teardown"):
write(os.path.join(new, "needs", need, step),
fill(read_text(NEEDS_DIR, need, step), values))
shutil.copyfile(icon_from(source), os.path.join(new, "icon.png"))
shutil.copyfile(os.path.join(source, "coreapp.toml"), os.path.join(new, "coreapp.toml"))
write(os.path.join(new, MARKER),
"# Installed by coreapps; delete with coreapps remove\n"
f"needs={' '.join(m['needs'])}\n")
shutil.rmtree(final, ignore_errors=True)
os.rename(new, final)
# --- install, update, remove ----------------------------------------------------
def log_path(name, what):
os.makedirs(LOGS, mode=0o700, exist_ok=True)
path = os.path.join(LOGS, f"{name}-{what}.log")
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
os.close(fd)
return path
def run_logged(cmd, log, failure):
"""Run cmd with its output in log (the Core's scripts trace secrets)."""
with open(log, "a") as f:
result = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT, cwd=FEDERATED)
if result.returncode != 0:
with open(log) as f:
tail = f.readlines()[-20:]
sys.stderr.write("".join(tail))
raise Refused(f"{failure} (whole log on the Core: {log}).")
def ensure_image(m):
ref = f"{m['image']}:{m['version']}"
if run(["docker", "image", "inspect", ref]).returncode == 0:
return
if m["image"].startswith("localhost/"):
raise Refused(f"The image {ref} isn't on this Core, and localhost/ images "
"can't be pulled. coreapp deploy copies it here.")
say(f"Pulling {ref}...")
out = run(["docker", "pull", "-q", ref])
if out.returncode != 0:
raise Refused(f"Couldn't pull {ref}: {out.stderr.strip()}")
def compose_up(name, log):
run_logged(["docker", "compose", "-f", f"{APPS}/{name}/docker-compose.yml",
"-p", name, "up", "-d", "--remove-orphans"], log,
f"Starting {name} failed")
# Run on update: the same values the generated install provides, then the
# compose file again (it may have changed), settings the new version adds,
# and the setup of needs that are new. Arguments: name, version, needs.
# (service sets NAME to the app's title, so the name is also in NAME_ID.)
UPDATE_SCRIPT = r'''
cd /federated
. /etc/federated
. lib/functions.sh
. lib/helpers.sh
set -e
. services/$1/service
TRAEFIK_IP="$(sed -n 's/^INTERNAL_IP=//p' services/traefik/service)"
templatize services/$1/docker-compose.yml.in > apps/$1/docker-compose.yml
fresh="$(mktemp)"
templatize services/$1/env.in > "$fresh"
while IFS= read -r line; do
case "$line" in [A-Za-z_]*=*) ;; *) continue ;; esac
grep -q "^${line%%=*}=" apps/$1/.env || echo "$line" >> apps/$1/.env
done < "$fresh"
rm -f "$fresh"
sed -i "s/^IMAGE_VERSION=.*/IMAGE_VERSION=$2/" apps/$1/.env
chmod 600 apps/$1/.env
shift 2
for need in "$@"; do . services/$NAME_ID/needs/$need/setup; done
'''
def install(folder, addon_ok):
m = read_manifest(folder)
p = plan(m)
name = m["name"]
if p["addon"] == "yes" and not addon_ok:
say(f"This Core's tier is '{p['tier']}': installing records '{name}' as an "
"add-on app (ADDON_APPS in /etc/federated), which Federated may bill for. "
"Run again with --addon-ok to install anyway.")
return 3
ensure_image(m)
make_service_folder(m, p, folder)
if p["state"] == "new":
say(f"Installing {name} at {p['address']} (the Core's installapp)...")
log = log_path(name, "install")
run_logged([FEDERATED + "/bin/installapp", "-n", name], log, "installapp failed")
# installapp's start step only knows Federated's own apps
compose_up(name, log)
else:
say(f"Updating {name} to {m['version']}...")
log = log_path(name, "update")
env = dict(os.environ, NAME_ID=name)
with open(log, "a") as f:
result = subprocess.run(["bash", "-c", UPDATE_SCRIPT, "update", name,
m["version"], *p["new_needs"]],
stdout=f, stderr=subprocess.STDOUT, env=env)
if result.returncode != 0:
raise Refused(f"Updating failed (whole log on the Core: {log}).")
compose_up(name, log)
wait_until_answering(m, p)
if p["state"] == "update":
remove_old_images(m)
say(f"{'Installed' if p['state'] == 'new' else 'Updated'}: {p['url']}")
return 0
def remove_old_images(m):
"""The app's images with other versions, now that this one runs."""
out = run(["docker", "image", "ls", "--format", "{{.Repository}}:{{.Tag}}", m["image"]])
for ref in out.stdout.split():
if ref != f"{m['image']}:{m['version']}":
run(["docker", "image", "rm", ref])
def wait_until_answering(m, p):
name = m["name"]
url = f"http://{p['address']}:{m['port']}{m['health']}"
say(f"Waiting for it to answer at {url}...")
for _ in range(30):
state = run(["docker", "inspect", "-f", "{{.State.Status}}", name]).stdout.strip()
if state not in ("running", "created", "restarting"):
break
try:
with urllib.request.urlopen(url, timeout=2) as r:
if 200 <= r.status < 400:
return
except urllib.error.HTTPError as e:
if e.code < 500:
return
except (urllib.error.URLError, OSError):
pass
time.sleep(2)
logs = run(["docker", "logs", "--tail", "20", name])
sys.stderr.write(logs.stdout + logs.stderr)
raise Refused(f"{name} doesn't answer at {url} (state: {state or 'missing'}; "
"its log is above).")
def remove(name):
if not re.fullmatch(FIELDS["name"], name):
raise Refused(f"'{name}' isn't an app name.")
folder = os.path.join(SERVICES, name)
if not os.path.isdir(folder):
raise Refused(f"No app called '{name}' on this Core.")
if not is_ours(name):
raise Refused(f"'{name}' wasn't installed by coreapps; it's not removed here.")
image = service_value(os.path.join(folder, "service"), "CONTAINER")
log = log_path(name, "remove")
if os.path.isdir(os.path.join(APPS, name)):
say(f"Uninstalling {name} (the Core's uninstallapp)...")
run_logged([FEDERATED + "/bin/uninstallapp", name], log, "uninstallapp failed")
shutil.rmtree(folder)
if image:
ids = run(["docker", "image", "ls", "-q", image]).stdout.split()
for image_id in sorted(set(ids)):
run(["docker", "image", "rm", "-f", image_id])
# uninstallapp made superpanel's catalog while the folder was still
# there, so it would still offer the app: make it again, as installapp
# does
if os.path.exists(APPS + "/superpanel/.env"):
run_logged([FEDERATED + "/bin/superpanel-generate-catalog"], log,
"Updating superpanel's app catalog failed")
run(["docker", "exec", "superpanel", "pkill", "-HUP", "superpanel"])
say(f"Removed {name}.")
return 0
def list_apps():
rows = []
for name in sorted(os.listdir(SERVICES)):
if not is_ours(name):
continue
service = os.path.join(SERVICES, name, "service")
state = run(["docker", "inspect", "-f", "{{.State.Status}}", name]).stdout.strip()
rows.append((name, service_value(service, "VERSION"),
service_value(service, "INTERNAL_IP"), state or "not running"))
if not rows:
say("No apps installed by coreapps.")
for row in rows:
say("%-24s %-12s %-16s %s" % row)
return 0
# --- Command line -----------------------------------------------------------------
def main(args):
if not args or args[0] in ("-h", "--help", "help"):
print(__doc__.split("\n\n", 2)[2].strip())
return 0
cmd, rest = args[0], args[1:]
if cmd == "manifest" and len(rest) == 1:
m = read_manifest(rest[0])
for key in ("name", "title", "description", "version", "image", "port",
"health", "docs", "dbname"):
print(f"{key}={m[key]}")
print(f"needs={' '.join(m['needs'])}")
return 0
if os.geteuid() != 0:
raise Refused("Run coreapps as root on the Core.")
if cmd == "plan" and len(rest) == 1:
p = plan(read_manifest(rest[0]))
for key, value in p.items():
print(f"{key}={' '.join(value) if isinstance(value, list) else value}")
return 0
if cmd == "install" and rest:
addon_ok = "--addon-ok" in rest
folders = [a for a in rest if a != "--addon-ok"]
if len(folders) == 1:
return install(folders[0], addon_ok)
if cmd == "remove" and len(rest) == 1:
return remove(rest[0])
if cmd == "list" and not rest:
return list_apps()
sys.stderr.write(__doc__.split("\n\n", 2)[2].strip() + "\n")
return 2
if __name__ == "__main__":
try:
sys.exit(main(sys.argv[1:]))
except Refused as e:
sys.stderr.write(f"{e}\n")
sys.exit(1)
@@ -1,4 +1,4 @@
# Its database on the Core's PostgreSQL, made by install # Its database on the Core's PostgreSQL, made by needs/postgres/setup
DB_HOST=postgresql.@DOMAIN@ DB_HOST=postgresql.@DOMAIN@
DB_PORT=5432 DB_PORT=5432
DB_NAME={{DBNAME}} DB_NAME={{DBNAME}}
@@ -1,5 +1,4 @@
# Its own database and user on the Core's PostgreSQL,
# Its own database and user on the Core's PostgreSQL (DEPENDS=postgresql),
# with the password from .env. Safe to run again: an existing user gets the # with the password from .env. Safe to run again: an existing user gets the
# password, an existing database is kept. # password, an existing database is kept.
DB_PASSWORD="$(sed -n 's/^DB_PASSWORD=//p' /federated/apps/{{NAME}}/.env)" DB_PASSWORD="$(sed -n 's/^DB_PASSWORD=//p' /federated/apps/{{NAME}}/.env)"
@@ -1,3 +1,3 @@
# ...and its database # Drop its database and user from the Core's PostgreSQL
docker exec postgresql psql -U postgres -qc "DROP DATABASE IF EXISTS {{DBNAME}}" docker exec postgresql psql -U postgres -qc "DROP DATABASE IF EXISTS {{DBNAME}}"
docker exec postgresql psql -U postgres -qc "DROP USER IF EXISTS {{DBNAME}}" docker exec postgresql psql -U postgres -qc "DROP USER IF EXISTS {{DBNAME}}"
+4
View File
@@ -0,0 +1,4 @@
# Reach Authelia's https address through traefik on the core network
# (inside it, authelia.@DOMAIN@ is Authelia's own plain-http container)
extra_hosts:
- "authelia.@DOMAIN@:@TRAEFIK_IP@"
@@ -1,5 +1,5 @@
# Sign-in through the Core's Authelia (OpenID Connect); install registers # Sign-in through the Core's Authelia (OpenID Connect); needs/sso/setup
# the client # registers the client
OIDC_ISSUER=https://authelia.@DOMAIN@ OIDC_ISSUER=https://authelia.@DOMAIN@
OIDC_CLIENT_ID=coreapp-{{NAME}} OIDC_CLIENT_ID=coreapp-{{NAME}}
OIDC_CLIENT_SECRET=@OIDC_CLIENT_SECRET:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@ OIDC_CLIENT_SECRET=@OIDC_CLIENT_SECRET:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@
@@ -1,4 +1,3 @@
# Register it with the Core's Authelia as an OpenID Connect client, with the # Register it with the Core's Authelia as an OpenID Connect client, with the
# secret from .env (hashed), between markers so uninstall can remove it. # secret from .env (hashed), between markers so uninstall can remove it.
# Safe to run again. Authelia is checked with the new client before it # Safe to run again. Authelia is checked with the new client before it
@@ -1,4 +1,4 @@
# ...and its Authelia client # Remove its OpenID Connect client from the Core's Authelia
sed -i '/^ ### coreapp-{{NAME}} begin$/,/^ ### coreapp-{{NAME}} end$/d' \ sed -i '/^ ### coreapp-{{NAME}} begin$/,/^ ### coreapp-{{NAME}} end$/d' \
/federated/apps/authelia/data/config/idproviders.yml /federated/apps/authelia/data/config/idproviders.yml
restart_service authelia restart_service authelia
@@ -1,12 +1,13 @@
services: services:
{{NAME}}: {{NAME}}:
image: coreapp/{{NAME}}:${IMAGE_VERSION} image: @CONTAINER@:${IMAGE_VERSION}
container_name: {{NAME}} container_name: {{NAME}}
hostname: {{NAME}}.@DOMAIN@ hostname: {{NAME}}.@DOMAIN@
restart: always restart: always
networks: networks:
core: core:
ipv4_address: {{IP}} ipv4_address: {{IP}}
{{COMPOSE_EXTRA}}
env_file: env_file:
- ./.env - ./.env
volumes: volumes:
@@ -16,7 +17,7 @@ services:
- "traefik.http.routers.{{NAME}}.rule=Host(`{{NAME}}.@DOMAIN@`)" - "traefik.http.routers.{{NAME}}.rule=Host(`{{NAME}}.@DOMAIN@`)"
- "traefik.http.routers.{{NAME}}.entrypoints=websecure" - "traefik.http.routers.{{NAME}}.entrypoints=websecure"
- "traefik.http.routers.{{NAME}}.tls.certresolver=letsencrypt" - "traefik.http.routers.{{NAME}}.tls.certresolver=letsencrypt"
- "traefik.http.services.{{NAME}}.loadbalancer.server.port=8080" - "traefik.http.services.{{NAME}}.loadbalancer.server.port={{PORT}}"
networks: networks:
core: core:
+5
View File
@@ -0,0 +1,5 @@
# The app's settings, filled in when it's installed. Updates keep the values
# (secrets don't change) and add settings a new version needs.
IMAGE_VERSION=@VERSION@
APP_URL=https://{{NAME}}.@DOMAIN@
APP_SECRET=@APP_SECRET:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@
Binary file not shown.

After

Width:  |  Height:  |  Size: 566 B

+14
View File
@@ -0,0 +1,14 @@
# Made by coreapps from the app's coreapp.toml. Sourced by the Core's
# installapp.
. /federated/lib/helpers.sh
# Besides /etc/federated's and service's values, the templates use
# @TRAEFIK_IP@, traefik's address on the core network
TRAEFIK_IP="$(sed -n 's/^INTERNAL_IP=//p' /federated/services/traefik/service)"
installGeneric {{NAME}}
# .env holds secrets
chmod 600 /federated/apps/{{NAME}}/.env
# What the app needs from the Core (its database, its sign-in client)
for setup in /federated/services/{{NAME}}/needs/*/setup; do
[ -e "$setup" ] && . "$setup"
done
unset setup
+8
View File
@@ -0,0 +1,8 @@
NAME="{{TITLE}}"
DESCRIPTION="{{DESCRIPTION}}"
DOCS={{DOCS}}
CONTAINER={{IMAGE}}
VERSION={{VERSION}}
INTERNAL_IP={{IP}}
DEPENDS="{{DEPENDS}}"
PORTS={{PORT}}
+9
View File
@@ -0,0 +1,9 @@
# Made by coreapps from the app's coreapp.toml. Sourced by the Core's
# uninstallapp (so no `exit` here): stop the app, undo what it needed from
# the Core, delete its settings and data.
docker compose -f /federated/apps/{{NAME}}/docker-compose.yml -p {{NAME}} down
for teardown in /federated/services/{{NAME}}/needs/*/teardown; do
[ -e "$teardown" ] && . "$teardown"
done
unset teardown
rm -rf /federated/apps/{{NAME}}
+2 -4
View File
@@ -1,7 +1,5 @@
.git .git
service .gitea
*.in coreapp.toml
install
uninstall
icon.png icon.png
README.md README.md
+3 -3
View File
@@ -1,6 +1,6 @@
# The app's image. coreapp deploy builds it as coreapp/{{NAME}}:<VERSION> # The app's image. coreapp deploy builds it as image:version (from
# and copies it to the Core. Replace this with your own app; keep it # coreapp.toml) and copies it to the Core. Replace this with your own app;
# listening on the port in docker-compose.yml.in (8080). # keep it listening on the port in coreapp.toml (8080).
FROM busybox:stable FROM busybox:stable
COPY www /www COPY www /www
EXPOSE 8080 EXPOSE 8080
+27 -19
View File
@@ -18,28 +18,36 @@ coreapp remove # uninstall it from the Core
## Files ## Files
The app is in the format Federated Core installs apps from
(`/federated/services/{{NAME}}/` on the Core):
| File | What it is | | File | What it is |
|---|---| |---|---|
| `service` | Name, description, image (`CONTAINER`), `VERSION`, `INTERNAL_IP`, apps it needs (`DEPENDS`, e.g. `postgresql`), and how to check it's up (`MONITOR`) | | `coreapp.toml` | What the Core needs to know: name, title, image and version, port, health path, and what it needs from the Core (`needs`) |
| `docker-compose.yml.in` | The container(s), on the Core's `core` network at `INTERNAL_IP`, with the traefik labels that give it `https://{{NAME}}.<domain>` | | `Dockerfile`, `www/` | The app itself |
| `env.in` | Its settings, as the `.env` file next to the compose file | | `icon.png` | Its icon in the Core's dashboard (a PNG, up to 1 MB) |
| `install` | Run by the Core's `installapp`; fills in the templates |
| `icon.png` | Its icon in the Core's dashboard |
| `Dockerfile`, `www/` | The app itself (not copied to the Core) |
In `docker-compose.yml.in` and `env.in`, the Core replaces, once at install: That's all an app has. The Core's side (the container on the Core's `core`
network, the traefik route to `https://{{NAME}}.<domain>`, its settings and
secrets, its database or sign-in client) is made by coreapp-dev's installer,
`coreapps`, from `coreapp.toml`. The app can't run scripts on the Core.
- `@DOMAIN@`: the Core's domain, and any other variable in `/etc/federated` ## What the app gets
- `@VERSION@`, `@CONTAINER@`, `@INTERNAL_IP@`: from `service`
- `@SECRET:RANDOM:LLLLLLLL@`: a random value (`L` a letter or digit, `a`
lowercase, `A` uppercase, `0` a digit, `x` hex), also available as
`@SECRET@` further down
`${...}` is left for Docker Compose, which reads it from `.env`. Its environment (the `.env` file on the Core, made once at install; updates
keep its values and add new ones):
Raise `VERSION` in `service` for each release. The Core's nightly upgrade | Variable | Value |
only redeploys an app when `VERSION` differs from `IMAGE_VERSION` in its |---|---|
`.env`. | `APP_URL` | `https://{{NAME}}.<domain>` |
| `APP_SECRET` | A random secret, for signing cookies and such |
| `IMAGE_VERSION` | The version that's installed |
`needs = ["postgres"]` adds `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER` and
`DB_PASSWORD`; `needs = ["sso"]` adds `OIDC_ISSUER`, `OIDC_CLIENT_ID` and
`OIDC_CLIENT_SECRET`.
Its files: `/data` in the container is kept on the Core
(`/federated/apps/{{NAME}}/data`) across updates and restarts.
The app serves plain HTTP on its `port`; traefik on the Core handles HTTPS
and the certificate.
Raise `version` in `coreapp.toml` for each release.
+23
View File
@@ -0,0 +1,23 @@
# What a Federated Core needs to know to install {{TITLE}}. coreapp-dev's
# installer (coreapps) makes the rest from it: the container on the Core's
# network, https://{{NAME}}.<domain>, its settings and secrets.
# Its id and hostname: https://{{NAME}}.<domain>
name = "{{NAME}}"
title = "{{TITLE}}"
description = "{{TITLE}}, made with coreapp-dev"
# docs = "https://..."
# The image, as image:version. localhost/... images only exist where
# coreapp deploy copies them; a published app names its registry, e.g.
# gitea.example.com/owner/{{NAME}}. Raise the version for each release.
image = "localhost/coreapp/{{NAME}}"
version = "0.1.0"
# The port the app serves HTTP on, and a path that answers when it's up
port = 8080
health = "/"
# What it needs from the Core: "postgres" (its own database), "sso"
# (sign-in with Core accounts through Authelia)
needs = []
-5
View File
@@ -1,5 +0,0 @@
# Filled in once, when the app is installed (see README.md). Redeploying
# keeps the result, so secrets don't change.
IMAGE_VERSION=@VERSION@
APP_URL=https://{{NAME}}.@DOMAIN@
APP_SECRET=@APP_SECRET:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@
-7
View File
@@ -1,7 +0,0 @@
. /federated/lib/helpers.sh
# Values the templates can use besides /etc/federated's and service's:
# @TRAEFIK_IP@, traefik's address on the core network
TRAEFIK_IP="$(sed -n 's/^INTERNAL_IP=//p' /federated/services/traefik/service)"
installGeneric {{NAME}}
# .env holds secrets
chmod 600 /federated/apps/{{NAME}}/.env
-9
View File
@@ -1,9 +0,0 @@
NAME="{{TITLE}}"
DESCRIPTION="{{TITLE}}, made with coreapp-dev"
DOCS=
CONTAINER=coreapp/{{NAME}}
VERSION=0.1.0
INTERNAL_IP={{IP}}
DEPENDS=""
PORTS=8080
MONITOR="https://{{NAME}}.@DOMAIN@|http_2xx"
-4
View File
@@ -1,4 +0,0 @@
# Sourced by the Core's uninstallapp (so no `exit` here): stop the app and
# delete its settings and data
docker compose -f /federated/apps/{{NAME}}/docker-compose.yml -p {{NAME}} down
rm -rf /federated/apps/{{NAME}}
+3 -3
View File
@@ -1,6 +1,6 @@
# The app's image. coreapp deploy builds it as coreapp/{{NAME}}:<VERSION> # The app's image. coreapp deploy builds it as image:version (from
# and copies it to the Core. Replace this with your own app; keep it # coreapp.toml) and copies it to the Core. Replace this with your own app;
# listening on the port in docker-compose.yml.in (8080). # keep it listening on the port in coreapp.toml (8080).
FROM python:3.13-slim FROM python:3.13-slim
RUN pip install --no-cache-dir "psycopg[binary]==3.2.*" RUN pip install --no-cache-dir "psycopg[binary]==3.2.*"
COPY app.py oidc.py /app/ COPY app.py oidc.py /app/
+1
View File
@@ -0,0 +1 @@
postgres
+3 -3
View File
@@ -1,6 +1,6 @@
# The app's image. coreapp deploy builds it as coreapp/{{NAME}}:<VERSION> # The app's image. coreapp deploy builds it as image:version (from
# and copies it to the Core. Replace this with your own app; keep it # coreapp.toml) and copies it to the Core. Replace this with your own app;
# listening on the port in docker-compose.yml.in (8080). # keep it listening on the port in coreapp.toml (8080).
FROM python:3.13-slim FROM python:3.13-slim
RUN pip install --no-cache-dir "psycopg[binary]==3.2.*" RUN pip install --no-cache-dir "psycopg[binary]==3.2.*"
COPY app.py /app/app.py COPY app.py /app/app.py
+5 -5
View File
@@ -1,12 +1,12 @@
## Database ## Database
The app has its own database on the Core's shared PostgreSQL `needs = ["postgres"]`: the app has its own database on the Core's shared
(`DEPENDS="postgresql"` in `service`): PostgreSQL.
- `install` creates the user and database `{{DBNAME}}`, with the random - At install, the user and database `{{DBNAME}}` are created, with the
`DB_PASSWORD` from `.env`; `uninstall` drops both (`coreapp remove` random `DB_PASSWORD` from `.env`. `coreapp remove` drops both, with the
deletes the data). data.
- The app reads `DB_HOST` (`postgresql.<domain>`, which only resolves on the - The app reads `DB_HOST` (`postgresql.<domain>`, which only resolves on the
Core's `core` network), `DB_PORT`, `DB_NAME`, `DB_USER` and `DB_PASSWORD` Core's `core` network), `DB_PORT`, `DB_NAME`, `DB_USER` and `DB_PASSWORD`
from its environment. `app.py` shows how, with `psycopg`. from its environment. `app.py` shows how, with `psycopg`.
+1
View File
@@ -0,0 +1 @@
sso
+3 -3
View File
@@ -1,6 +1,6 @@
# The app's image. coreapp deploy builds it as coreapp/{{NAME}}:<VERSION> # The app's image. coreapp deploy builds it as image:version (from
# and copies it to the Core. Replace this with your own app; keep it # coreapp.toml) and copies it to the Core. Replace this with your own app;
# listening on the port in docker-compose.yml.in (8080). # keep it listening on the port in coreapp.toml (8080).
FROM python:3.13-slim FROM python:3.13-slim
COPY app.py oidc.py /app/ COPY app.py oidc.py /app/
USER nobody USER nobody
+8 -13
View File
@@ -1,20 +1,15 @@
## Sign-in ## Sign-in
People sign in with their Core account, through the Core's Authelia `needs = ["sso"]`: people sign in with their Core account, through the
(OpenID Connect, authorization code flow with PKCE): Core's Authelia (OpenID Connect, authorization code flow with PKCE).
- `install` registers the client `coreapp-{{NAME}}` in Authelia's - At install, the client `coreapp-{{NAME}}` is registered in Authelia, with
`idproviders.yml` (between `### coreapp-{{NAME}} begin/end` markers), with the random `OIDC_CLIENT_SECRET` from `.env`. `coreapp remove` removes it.
the random `OIDC_CLIENT_SECRET` from `.env`, hashed. It checks Authelia's - Its redirect URI is `https://{{NAME}}.<domain>/auth/callback`, so the app
configuration before restarting it and puts the old one back if the check has to handle that path.
fails. `uninstall` removes the client. - Authelia decides whether a second factor is needed (the Core's 2FA
- Its redirect URI is `https://{{NAME}}.<domain>/auth/callback`. Change it in policy).
`install` if your app uses another path.
- Authelia decides whether a second factor is needed (the Core's 2FA policy
is applied to every client after each install).
- The app reaches `https://authelia.<domain>` through traefik
(`extra_hosts` in `docker-compose.yml.in`).
- `oidc.py` does the whole flow with Python's standard library, and `app.py` - `oidc.py` does the whole flow with Python's standard library, and `app.py`
uses it for `/login`, `/auth/callback` and `/logout`. For a real app, use uses it for `/login`, `/auth/callback` and `/logout`. For a real app, use
your framework's OpenID Connect library with `OIDC_ISSUER`, your framework's OpenID Connect library with `OIDC_ISSUER`,
-27
View File
@@ -1,27 +0,0 @@
services:
{{NAME}}:
image: coreapp/{{NAME}}:${IMAGE_VERSION}
container_name: {{NAME}}
hostname: {{NAME}}.@DOMAIN@
restart: always
networks:
core:
ipv4_address: {{IP}}
# Reach Authelia's https address through traefik on the core network
# (inside it, authelia.@DOMAIN@ is Authelia's own plain-http container)
extra_hosts:
- "authelia.@DOMAIN@:@TRAEFIK_IP@"
env_file:
- ./.env
volumes:
- ./data:/data
labels:
- "traefik.enable=true"
- "traefik.http.routers.{{NAME}}.rule=Host(`{{NAME}}.@DOMAIN@`)"
- "traefik.http.routers.{{NAME}}.entrypoints=websecure"
- "traefik.http.routers.{{NAME}}.tls.certresolver=letsencrypt"
- "traefik.http.services.{{NAME}}.loadbalancer.server.port=8080"
networks:
core:
external: true