Files
maptool/docs/deployment.adoc
T

475 lines
24 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
= Deployment
:toc:
:toclevels: 2
MapTool deploys as a Podman container (via `podman compose`, driven by a
`podman-compose@.service` systemd template — see below) on the same server
the Gitea Actions runners run on. Two separate runners are registered
against the Gitea instance:
* The existing Docker-based runner (`gitea/runner:3`), label
`brick-build` — runs the `check` and `renovate` jobs in a fresh,
isolated container per job. Every label on this runner (including
`ubuntu-latest`/`ubuntu-24.04`/`ubuntu-22.04`, still registered but no
longer what `check`/`renovate` pin to) now maps to Gitea's own
official runner image (`docker.gitea.com/runner-images:ubuntu-latest`,
has Node out of the box) — an earlier `opensuse/leap:16.0` mapping for
`brick-build` specifically had no Node, which every step in
`check`/`renovate` needs (they're JS-based Actions), and briefly broke
both jobs (2026-09-12) until reverted to the shared `ubuntu-latest`
label; now that the image itself is fixed, both are pinned back to
`brick-build` — this machine specifically, not whichever runner
happens to answer to the shared label (e.g. "Gitea Runner on Cube").
* A dedicated native runner, installed directly on the host (no Docker
around it), label `brick-host` — runs only the `deploy` job.
They're separate because the Docker-based runner's jobs (whether in
its usual isolated per-job containers, or tried directly inside its
own container via a `host`-scheme label) have no reliable access to
the host's filesystem, `systemctl`, or even a full toolset (its own
container image is missing `rsync`, `docker` CLI, Node.js — it's built
for spawning per-job containers via its `docker.sock` mount, not for
running arbitrary host commands). The native runner sidesteps all of
that: it *is* a host process, so `docker`, `git`, etc. are just
whatever's installed on the server.
== Layout on the server
`/srv/podman/maptool/` (`/srv/podman` is a symlink to `/srv/docker`, a
leftover from before the Docker → Podman migration — kept around so
existing paths/tooling that still assume `/srv/docker` keep working;
expect this to flip the other way, `/srv/docker` symlinked to
`/srv/podman`, once nothing depends on the old name anymore) holds:
* `build/` — a checkout of this repository (kept in sync by the
deploy job, see below), wiped and fully replaced every deploy —
`Dockerfile`, `docker-compose.yaml`, application code.
* `docker-compose.yaml` — a relative symlink to `build/docker-compose.yaml`,
purely so it's where a human poking around expects to find it, at
the top rather than a level down. Also what makes the layout work at
all: `podman compose`/`docker compose` resolve a relative volume
path (`./data` below) against the *symlink's own* directory, not
where it points — confirmed against plain `docker-compose config`,
not assumed — so `./data:/app/data` in the compose file keeps
meaning `/srv/podman/maptool/data`, and
`podman-compose@.service`'s `WorkingDirectory=/srv/podman/maptool`
needs no change either.
* `data/`, *not* part of the checkout sync (nothing in `build/`
references it, and the sync step doesn't need to special-case it
the way an earlier version of this layout did) — uploaded GPX
files, `offline.pmtiles`, `terrain.pmtiles`, and
`kiwix/wikipedia.zim` (see `docs/development.adoc` for each), and
`routing/` (the offline routing graph, built and served by the
`valhalla` compose service, see `docs/routing-design.adoc`).
Persisted via that bind mount, so a redeploy never touches it.
Also where a private import plugin belongs (`data/plugins/<name>/`,
see `lib/maptool/plugins.rb`'s `PLUGINS_DIRS`) — `build/plugins/`
only holds what's checked into this public repo, and gets wiped and
replaced by the checkout sync on every deploy same as the rest of
`build/`.
`data/` (and the kiwix ZIM path) carries a `:Z` SELinux relabel in
`docker-compose.yaml`'s bind mounts — without it, Podman on an
SELinux-enforcing host denies the container write access to the
bind-mounted directory regardless of its Unix permissions (surfaces
as a plain `Permission denied` in the app's own logs, nothing
SELinux-labeled unless you go looking in `audit.log`); harmless/
ignored on a host where SELinux isn't enforcing.
* `.env` — regenerated every deploy (see below), lives here rather
than in `build/` for the same reason as the symlink: `docker
compose`/`podman compose` auto-load `.env` from the compose file's
own directory (as invoked, i.e. following the symlink's location,
same story as the volume path above).
== The native deploy runner
Installed from the official binary (see
https://docs.gitea.com/runner/installation/binary/), running as a
systemd service (`gitea-runner.service`) under a dedicated
`gitea-runner` system user, which needs:
* Passwordless `sudo` for managing any `podman-compose@` instance —
`/etc/sudoers.d/gitea-runner-podman` grants `NOPASSWD` on
`systemctl {start,stop,restart} podman-compose@*.service` and
`podman rmi -f *` (root-owned systemd units, same idea as the
`docker` group membership gitea-runner already has for
`docker-compose@` services, just scoped explicitly since Podman has
no daemon/socket-group equivalent to grant blanket access through).
* Write access to `/srv/podman/maptool`.
Its `config.yaml` (`/etc/gitea-runner/config.yaml`) declares a single
label:
[source,yaml]
----
runner:
labels:
- "brick-host"
----
The `host` scheme means jobs run directly via the runner process's own
shell — no container spawned — which is exactly what a plain, single
purpose deploy runner needs.
== Puma's bind address
`config/puma.rb` binds to `127.0.0.1` by default (see
`docs/architecture.adoc`) — fine for local dev, but inside a container
that would make the app unreachable through the published port
(loopback is scoped to the container's own network namespace).
`docker-compose.yaml` sets `BIND_HOST="[::]"` to override that for the
deployed container specifically — the IPv6 wildcard, which (dual-stack
being the Linux default) also accepts IPv4 connections, covering both
with a single listener; the compose file's own port publishing
(`ports:`) is the network boundary there instead of Puma's bind
address.
== Secrets (`.env`)
`docker-compose.yaml` reads `SESSION_SECRET`, `GITEA_OAUTH_CLIENT_ID`,
`GITEA_OAUTH_CLIENT_SECRET` and `MAPTOOL_ALLOWED_GITEA_USER` from the
environment (see `docs/architecture.adoc` for what they're for) —
`podman compose` loads these automatically from a `.env` file next to
`docker-compose.yaml`, i.e. `/srv/podman/maptool/.env`. That file is
gitignored and dockerignored on purpose: nothing here ever puts
secrets in the repository or a built image layer.
It's not created by hand on the server — the deploy job's "Write
.env" step regenerates it on every deploy from repo-level Gitea
Actions secrets (*Settings → Actions → Secrets*): `SESSION_SECRET`,
`OAUTH_CLIENT_ID`, `OAUTH_CLIENT_SECRET`, `MAPTOOL_ALLOWED_GITEA_USER`.
The non-secret ones — `OAUTH_CLIENT_ID`, `MAPTOOL_ALLOWED_GITEA_USER`,
`P4N_USER`, `MQTT_URL`, `MQTT_USERNAME` — may be Actions *Variables*
instead (the step reads `vars.X || secrets.X`); the rest stay Secrets.
The OAuth2 ones aren't named `GITEA_OAUTH_CLIENT_*` to match the `.env`
var names 1:1 — Gitea rejects secret names starting with `GITEA_` or
`GITHUB_` as reserved — but the workflow step maps them to the right
`.env` var names regardless. Gitea masks secret values in the job log
automatically. Set these once in the repo settings and every deploy
since keeps `.env` in sync — no server-side step needed beyond the
first-time OAuth2 application registration below.
`SESSION_SECRET` must stay the same value across deploys (regenerating
it every push would silently log everyone out every time `main`
changes) — generate it once (`openssl rand -hex 32`) and store that
same value as the secret from then on, don't regenerate per-deploy.
Register the OAuth2 application once, under any one Gitea account
(doesn't need to be an allowed user itself — any Gitea account can
authenticate through it, `MAPTOOL_ALLOWED_GITEA_USER` is what actually
decides who gets write access): *Settings → Applications → Manage
OAuth2 Applications → Create a new OAuth2 Application*, with redirect
URI `https://map.priesol.net/auth/callback`. That gives you the client
id/secret to store as the two `OAUTH_CLIENT_*` secrets above.
`MAPTOOL_ALLOWED_GITEA_USER` itself is a comma-separated list of Gitea
usernames, e.g. `randy,friend1,friend2` — not their emails, the
`login` field from Gitea's `/api/v1/user`.
Optional: `MQTT_URL`, `MQTT_USERNAME`, `MQTT_PASSWORD` (same names in
`.env`; the URL and username aren't secret and may be Actions
*Variables* instead of Secrets, the password a Secret) — the home MQTT broker the car's ESPHome nodes
publish to, read by `/api/live` (the "Vehicle & ITS-G5" overlay): the
GNSS tracker's `mcu-tracker/location` and the ITS-G5 receiver's
`mcu-its-g5/decoded`. Use a read-only broker user limited to those
topics. Blank `MQTT_URL` turns it off. The URL needs a name the
container can resolve — `ha.local` (mDNS) doesn't resolve inside it,
`mqtt://ha.priesol.net:1883` does.
== The car's server (rpi-dev, later the van's CM5)
A second maptool on a Raspberry Pi (Debian, arm64, rootful podman +
podman-compose), laid out like brick's: `/srv/podman/maptool/{build,data,.env}`,
the same `podman-compose@.service` unit. Deployed by hand for now (the
working tree rsynced into `build/`), not by CI.
Its `.env` adds:
* `TRUSTED_NETWORKS=connected` — requests from the subnets the Pi is
directly on (whichever Wi-Fi/LAN, looked up per request; loopback too)
count as logged in, since Gitea's OAuth needs internet and its redirect
URL is brick's. Comma-separated CIDRs work too, also next to `connected`. Only on a server no reverse proxy sits in front of —
never on brick, where every request comes from the proxy.
* `TAKEOUT_HOST_DIR` — an empty directory (the Takeout import is brick's).
* `SYNC_SERVER_URL` (`https://map.priesol.net`) and `SYNC_TOKEN`: it's a sync client.
* `SELF_UPDATE=1` — the update button (below).
=== Updates (a button, not CI)
CI deploys brick only: the car's server is often offline, and a deploy
mustn't restart it mid-drive. Instead it checks Gitea itself (every
10 min while online; the repo is public, no token): when `main` has a
newer commit whose CI passed, a ⟳ button shows in the topbar; a click
writes `data/update/request.json`, `maptool-update.path` starts
`bin/update-maptool.sh` (as root — the container writes `data/` as root),
which downloads that commit's archive from Gitea, stages it as
`build.new/` (next to `build/`, the same filesystem — `/tmp` is RAM on the
Pi, a move from there would be a copy), swaps it in with two renames (the
previous one stays as `build.old/`), restarts maptool and waits up to
15 min for `/api/health` to answer with the new revision — if it doesn't
(the image didn't build, the app crashes), it moves the new tree to
`build.bad/`, puts the old one back and restarts again. It reports in
`data/update/status.json`; the page reloads on the new revision. Asked
twice for the same commit, the second run does nothing.
What survives what: a reload or a closed page — the update runs on the
host; a power cut while downloading — `build/` untouched, the button shows
again; a cut between the two renames (milliseconds) — `maptool-recover`
puts `build.new/` (complete by then) or `build.old/` back at boot; a cut
after them — the new tree is in place, maptool builds and starts at boot.
----
# /etc/systemd/system/maptool-update.path
[Unit]
Description=Update maptool when the app asks
[Path]
PathExists=/srv/podman/maptool/data/update/request.json
[Install]
WantedBy=multi-user.target
# /etc/systemd/system/maptool-update.service
[Unit]
Description=Update maptool to the commit the app asked for
After=network-online.target
[Service]
Type=oneshot
TimeoutStartSec=30min
ExecStart=/srv/podman/maptool/build/bin/update-maptool.sh
# /etc/systemd/system/maptool-recover.service
[Unit]
Description=Put maptool's build/ back if a power cut fell into an update's swap
Before=podman-compose@maptool.service
[Service]
Type=oneshot
ExecStart=/bin/sh -c 'cd /srv/podman/maptool && [ -d build ] || { [ -f build.new/app.rb ] && mv build.new build || mv build.old build; }'
[Install]
WantedBy=multi-user.target
----
`systemctl enable --now maptool-update.path maptool-recover.service`. Back by hand:
`mv build build.bad && mv build.old build`, restart.
=== Library sync (both ways, OsmAnd-style)
brick is the server, the car's maptool a client: the client's Sync button
(Tracks & Points header, shown only where `SYNC_SERVER_URL` is set) pulls
the server's changes, then pushes its own (`lib/maptool/sync.rb`; the
server's `GET /api/sync/changes`, `GET`/`PUT /api/sync/source/:id`,
`POST /api/sync/apply`, all guarded by the shared `SYNC_TOKEN`). Newer
`updated_at` wins, source files come along, progress in the client's
`data/sync_state.json`. Over the public URL, so no VPN is needed for it.
On brick the CI deploy writes `SYNC_TOKEN` (a Gitea secret) into `.env`.
=== CAN (GNSS node)
SocketCAN interfaces live in the host's network namespace, so on the car's
server maptool runs with host networking: a `docker-compose.override.yaml`
next to the compose symlink (podman-compose picks it up), with kiwix and
Valhalla published on loopback since their service names no longer resolve
from maptool:
----
services:
maptool:
network_mode: host
environment:
KIWIX_URL: "http://127.0.0.1:8080"
VALHALLA_URL: "http://127.0.0.1:8002"
kiwix:
ports: ["127.0.0.1:8080:8080"]
valhalla:
ports: ["127.0.0.1:8002:8002"]
----
Our esphome-canopen nodes describe themselves: on a node's first heartbeat
maptool reads over SDO its TPDOs (`0x1800+n`, `0x1A00+n`) and, per mapped
entity, its type, name, unit and range (`canopen_entities`' OD, its
`OBJECT_DICTIONARY.md`) and decodes them with no hand-written signals
(`lib/maptool/can_discovery.rb`); cached in `data/can_nodes/<node>.json`
by the TPDO layout hash (`0x3002`:1, checked every 10 min — read again after
an OTA that changed the layout). Signals are named `<node name>.<entity
name>` (the ESPHome name, e.g. `mcu-stm32-xiao-c5-2.Latitude`, as
`/can.html` lists them); `data/can.json` only maps the ones the app uses to
its names, with a unit conversion where needed (the node's km/h → m/s).
`"signals"` stays for devices that don't describe themselves (the car
bridge), `"discover": false` turns it off:
----
{ "interfaces": ["can0"],
"aliases": {
"mcu-stm32-xiao-c5-2.Latitude": "gnss.lat",
"mcu-stm32-xiao-c5-2.Longitude": "gnss.lon",
"mcu-stm32-xiao-c5-2.Altitude": "gnss.alt",
"mcu-stm32-xiao-c5-2.Speed": { "name": "gnss.speed", "scale": 0.2777777777777778, "unit": "m/s" },
"mcu-stm32-xiao-c5-2.HDOP": "gnss.hdop",
"mcu-stm32-xiao-c5-2.Satellites": "gnss.satellites",
"mcu-stm32-xiao-c5-2.Pitch": "imu.pitch",
"mcu-stm32-xiao-c5-2.Roll": "imu.roll",
"mcu-stm32-xiao-c5-2.IMU Temperature": "imu.temperature",
"mcu-stm32-xiao-c5-2.Field Strength X": "mag.x",
"mcu-stm32-xiao-c5-2.Field Strength Y": "mag.y",
"mcu-stm32-xiao-c5-2.Field Strength Z": "mag.z",
"mcu-stm32-xiao-c5-2.Heading": "imu.heading" } }
----
What node 0x21 sends (read from it, 2026-11-30): TPDO1 0x2A1 pitch, roll
(-180..180°) and the IMU's temperature, Sensor16; TPDO2 0x3A1
latitude/longitude, REAL32; TPDO3 0x4A1 altitude, speed (km/h), HDOP
(Sensor16) and satellites (Sensor8); TPDO4 0x221 the HMC5883L, the field
±200 µT and the heading 0..360° (ESPHome's plain `atan2(-x, y)` is
−180..180, the node adds 360 to the negatives — a filter on `heading:`).
No tilt compensation or hard-iron calibration yet, so only roughly right
standing level. The node goes operational by itself, so no `nmt_start`.
Sensor16/8: `value = wire * (max - min) / (2^n - 2) + min`, all ones unknown.
The node sends no course: `App.gnss_update` (where every fix lands, the
node's and the GNSS simulation's) works it out from the fix ≥ 5 m back
while moving ≥ 1.5 m/s and keeps the last one standing still, so
`/api/gnss/position` has `track` and following in 3D turns heading-up.
The simulation (Dashboard settings, `POST`/`DELETE /api/sim/gnss`) drives
random trips over the local Valhalla and stands in for the node's `gnss.*`
meanwhile — on the car's server only for trying things out.
=== Map data (one way)
`bin/pull-maps.sh`, run by `maptool-pull-maps.timer` (10 min after boot,
then every 6 h) as `randy`: pulls the pmtiles, routing, places, hiking
trails, the ZIM kiwix serves (`kiwix/wikipedia.zim`, not other ZIMs there) and the NPS maps from brick over HTTPS — the same public
URL and `SYNC_TOKEN` as the library sync (read from `.env`), so no SSH or
VPN. brick lists them (`GET /api/sync/maps`: size, mtime, path; the list
of files is app.rb's `MAP_SYNC_FILES`/`MAP_SYNC_DIRS`) and serves each
(`GET /api/sync/maps/file?path=`); a cut-off download resumes (Range) on
the next try or run, files gone on brick are removed, maptool restarts
when something changed. They're GBs, so only at home by default (brick's
LAN address `HOME_HOST` answers); `HOME_HOST=` pulls anywhere.
== Garmin LiveTrack session webhook
`POST /api/livetrack/session` (`session_id`, `session_token`, `secret` form
params) records a Garmin LiveTrack session to `data/livetrack.json`; `GET
/api/livetrack/sessions` lists them, newest first. Intended caller: a Google
Apps Script bound to the Gmail account that receives LiveTrack emails,
triggered on a timer, extracting the session id/token from the email and
posting them here — the endpoint itself doesn't know anything about email or
Garmin's API, just those two strings.
`GET /api/livetrack/sessions/:id/track` fetches and returns that session's
track as GeoJSON (a `LineString` plus a `Point` at the latest position) —
see `LiveTrackClient` (`lib/maptool/livetrack_client.rb`) for how, since
there's no usable REST call for this: Garmin's own API
(`livetrack.garmin.com/api/v2/...`) 403s a plain server-side HTTP request no
matter what headers it's given (Cloudflare bot protection, fingerprinting
at the TLS/HTTP level rather than anything header-based) — but the session
page itself isn't blocked, and Garmin's Next.js frontend renders the full
track server-side into it (as React Server Component data, not a follow-up
API call), so the client fetches that page and pulls the track out of the
embedded payload instead.
`secret` must match the `LIVETRACK_WEBHOOK_SECRET` repo secret (added to
`.env` the same way as the others above). Unlike the other secrets, this one
is optional — leaving it unset simply disables the endpoint (`halt 403` on
every call) rather than failing the deploy, since LiveTrack tracking isn't
core to the app.
The caller side is a Google Apps Script bound to the Gmail account that
receives the LiveTrack emails (script.google.com, "New project"), run on a
time-driven trigger:
[source,javascript]
----
const WEBHOOK_URL = "https://map.priesol.net/api/livetrack/session";
const WEBHOOK_SECRET = "PASTE_SAME_VALUE_AS_LIVETRACK_WEBHOOK_SECRET_IN_.env";
const PROCESSED_LABEL = "livetrack-processed";
function checkLiveTrackEmail() {
const label = GmailApp.getUserLabelByName(PROCESSED_LABEL) || GmailApp.createLabel(PROCESSED_LABEL);
const threads = GmailApp.search(`from:noreply@garmin.com -label:${PROCESSED_LABEL}`);
threads.forEach(thread => {
// getBody() (raw HTML), not getPlainBody(): the email has no text/plain
// part, only text/html, and the link only exists as an href attribute
// — the auto-generated plain-text conversion isn't reliable for it.
const body = thread.getMessages()[0].getBody();
const match = body.match(/https:\/\/livetrack\.garmin\.com\/session\/([\w-]+)\/token\/([\w-]+)/);
if (match) {
UrlFetchApp.fetch(WEBHOOK_URL, {
method: "post",
payload: { session_id: match[1], session_token: match[2], secret: WEBHOOK_SECRET }
});
}
thread.addLabel(label); // stops it being reprocessed next run
});
}
----
The Gmail label (rather than marking the message read/unread) tracks which
threads are already handled without touching the user's own inbox state.
No `subject:LiveTrack` filter on the search — despite Gmail's own
substring-match documentation for `subject:`, that filter empirically
returned zero threads against a real, currently-arriving LiveTrack email
whose subject does contain the word ("Sledujte LiveTrack používateľa
...", confirmed 2026-09-20), so it's left out entirely — the regex match
below is what actually narrows this down to real LiveTrack emails with a
usable session link, `from:noreply@garmin.com` alone is deliberately
broad.
Set the trigger from the editor: clock icon on the left (Triggers) → *Add
Trigger* → function `checkLiveTrackEmail`, time-driven, "Minutes timer",
every 5 minutes.
Verified against a real "started an activity" LiveTrack email
(2026-09-06): sender `noreply@garmin.com`, link
`https://livetrack.garmin.com/session/<uuid>/token/<token>`, and against
the resulting session page/track fetch (`LiveTrackClient`, same day).
Garmin also sends other LiveTrack notifications (e.g. activity ended) that
weren't checked — if one turns out to use a different link shape, the
webhook simply won't receive that session; nothing breaks.
== CI deploy job
`.gitea/workflows/ci.yml`'s `deploy` job runs after `check` passes, only
on a push to `main`, with `runs-on: brick-host`:
. Checks out the repo with plain `git` (`fetch` + `checkout`,
authenticated via a one-off `http.extraHeader`) rather than
`actions/checkout@v4` — a leftover from when this job ran in a
Node-less container; kept as-is since there's no reason to bring
Node back in for something this already does.
. Wipes and replaces `/srv/podman/maptool/build/` with the fresh
checkout (plain `cp`/`rm`, dropping the copied `.git`), then
`ln -sf`s `docker-compose.yaml` up to it — self-healing (harmless
to redo every deploy) and, being a fresh checkout each time, nothing
in `build/` needs preserving the way `data/`/`.env` (both a level
up, see "Layout on the server" above) do.
. `sudo systemctl restart podman-compose@maptool.service`. The service
(`/etc/systemd/system/podman-compose@.service`, a systemd template
instantiated as `podman-compose@maptool.service`) owns the actual
container lifecycle — its `ExecStartPre` tears down the previous
containers/networks/volumes on every start, and its `ExecStart` runs
`podman compose up --build` (mirroring `docker-compose@.service`'s
own `--build`), so a plain restart always rebuilds from the code
just synced above while still reusing any layer whose inputs didn't
change (base image, `apt-get install`, `bundle install` when
`Gemfile`/`Gemfile.lock` are unchanged) as cache.
+
CAUTION: An earlier version of this step explicitly removed the
`maptool:latest` image (`podman rmi -f`) before restarting, to force a
rebuild against a service whose `ExecStart` didn't have `--build` yet.
That "worked" but also destroyed the build cache along with the image
— since nothing else referenced those layers, Podman fully deleted
them rather than leaving them as reusable cache the way Docker leaves
a retagged image's old layers behind — turning every deploy into a
full `apt-get`/`bundle install` from scratch (~3 minutes measured,
vs. ~20s before). Fixed by adding `--build` to the unit instead (see
above); don't reintroduce the `podman rmi` step.
. Polls `http://localhost:4567/api/health` for *this deploy's own*
revision (up to 5 minutes, the job fails if it never shows up)
before calling the deploy done — the restart above only confirms
`podman compose up --build` was launched (`Type=simple` has no
readiness protocol), not that the build actually succeeded and the
new code is what's answering; checking the revision specifically,
not just any 200, also catches a stuck old container that never got
torn down.