diff --git a/iiab-android b/iiab-android index e66defc70..887614cb5 100644 --- a/iiab-android +++ b/iiab-android @@ -676,6 +676,14 @@ else log "Not Full tier: Code on the Go build assets left off." ;; esac + + # K2GO-427: the cx_core role (content-exchange core) ships as an overlay with no + # 6-generic-apps include, so the main install does not run it; it runs on demand via + # runrole (the post-install step below does the bake-time install). Enabled on every + # tier: a tiny Python stdlib service, not a heavy mirror, and no internet needed. + sed -i -E '/^[[:space:]]*cx_core_(install|enabled)[[:space:]]*:/d' "$LOCAL_VARS_DEST" + echo "cx_core_install: True" >> "$LOCAL_VARS_DEST" + echo "cx_core_enabled: True" >> "$LOCAL_VARS_DEST" fi #----------------------------- @@ -843,6 +851,18 @@ install_welcome_zim # Install dashboard install_iiaboa_dashboard +#----------------------------- +# K2GO-427: install and start the content-exchange core (cx-core) via its role. The cx_core +# role ships as an overlay with no 6-generic-apps include, so the main install does not run it; +# run it here via runrole (the same path the app uses for on-demand installs). The role copies +# the source, registers the PDSM service (proot) and writes the IIAB flags. Pure Python stdlib, +# no internet needed. Non-fatal: a failure leaves the box without cx-core but does not fail the bake. +#----------------------------- +if is_role_enabled cx_core; then + log "Installing the content-exchange core (runrole cx_core)..." + ( cd /opt/iiab/iiab && ./runrole cx_core ) || warn "cx_core runrole failed; box will lack the content-exchange core" +fi + #----------------------------- # Reclaim disk: drop downloaded .deb archives #----------------------------- diff --git a/static/dashboard/CHANGELOG.md b/static/dashboard/CHANGELOG.md index 54ce3feef..7fe6e9f4f 100644 --- a/static/dashboard/CHANGELOG.md +++ b/static/dashboard/CHANGELOG.md @@ -4,6 +4,7 @@ One line per version, newest first. Every REST-facing change bumps the version i (the app surfaces it via `/system/dashboard/update-check` and the "Update available" pill), so this file is the human record of what each bump enables. Keep entries short: `version - change (TICKET)`. +- **1.4.5** - Relay to the content-exchange core (cx-core). dash-node now forwards `/v1/*` (reached externally at `/k2go-api/v1/*`) to the in-box cx-core REST service on `127.0.0.1:9500`: GET and POST, including the streamed `GET /v1/export/item`. dash-node only relays; the core owns the content state (one owner per fact). No proxy library (Node core `http`); the core's port is env-overridable via `CX_PORT`. Localhost-only. (K2GO-427) - **1.4.4** - Overall progress + total ETA for the content download jobs (K2GO-503). `downloadWithAria2` now aggregates progress across the WHOLE job through aria2's RPC (piece-accurate `completedLength` summed over tellActive/Waiting/Stopped) instead of reporting the last file's percent, so a multi-file download (code-addons / code-assets) shows one monotonic bar. `GET /:type/jobs/:id` gains an `eta` field (whole-job seconds remaining, -1 unknown) alongside `percent`/`speed`. The code-addons runner passes its staged-catalog total as the denominator so the bar and ETA are accurate from the first tick; code-assets uses aria2's learned totals. aria2 is started with `--enable-rpc` on an ephemeral localhost port and shut down on queue drain (it does not exit on its own under RPC); the console readout stays as the fallback when RPC is unreachable, and pause/cancel still kill the process directly. Localhost-only. (K2GO-503) - **1.4.3** - The offline Kolibri subtree reports each topic's size as its DISTINCT files (`subtree_bytes`), measured over the whole range. A file used by several topics counted once per topic before, which inflated folders 1.2x-1.7x; a truncated subtree now also has exact folder sizes. Same rule as the catalog generator. (K2GO-476) - **1.4.2** - A Kolibri job waits for Kolibri to come up (up to 10 min) instead of failing at once when Kolibri is unreachable. After a box restart the engine relaunches the job while Kolibri is still starting, so the job, and the app that re-attaches to it, no longer fail and lose the order. A Kolibri that answers 5xx while starting now counts as not reachable yet, not as a protocol error. (K2GO-475) diff --git a/static/dashboard/package.json b/static/dashboard/package.json index 1f295903a..c7bc8bf5d 100644 --- a/static/dashboard/package.json +++ b/static/dashboard/package.json @@ -1,10 +1,10 @@ { "name": "dashboard-console", - "version": "1.4.4", + "version": "1.4.5", "description": "", "main": "index.js", "scripts": { - "test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts sockets/kolibri.session.test.ts sockets/credentials.test.ts sockets/net-retry.test.ts sockets/services.test.ts sockets/log-rotate.test.ts sockets/rebuild-status.test.ts", + "test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts sockets/kolibri.session.test.ts sockets/credentials.test.ts sockets/net-retry.test.ts sockets/services.test.ts sockets/log-rotate.test.ts sockets/rebuild-status.test.ts sockets/cx-proxy.test.ts", "test:db": "node --require ts-node/register --test sockets/jobs.test.ts", "typecheck": "tsc --noEmit", "build": "tsc", diff --git a/static/dashboard/routes.ts b/static/dashboard/routes.ts index e80227f21..c50bda432 100644 --- a/static/dashboard/routes.ts +++ b/static/dashboard/routes.ts @@ -25,6 +25,7 @@ import { import { isRestartableService, restartService } from './sockets/services'; import { getFirehoseState } from './sockets/log-rotate'; import { resolveRebuildState } from './sockets/rebuild-status'; +import { cxProxy } from './sockets/cx-proxy'; // ADFA-4879: FQR helpers reached from the app (in-app region download/delete instead of the // copy-paste-into-a-terminal flow). tile-extract.py is installed on the box by the upstream maps @@ -72,6 +73,11 @@ function toApi(job: Job) { export const apiRouter: Router = express.Router(); +// --- Content-exchange core (cx-core) relay ------------------------------------------------- +// K2GO-427. Forward /v1/* to the in-box cx-core service (127.0.0.1:9500). Reached externally +// at /k2go-api/v1/*. dash-node only relays; the core owns the content state (ADR D1b). +apiRouter.use('/v1', cxProxy); + // --- Books: direct (non-job) queries over the offline catalog + Calibre-Web library --------- // ADFA-4850. Ported from the socket.io handlers; the download itself stays a durable job // (POST /books/download). These paths don't collide with the generic /:type/* routes below. diff --git a/static/dashboard/sockets/cx-proxy.test.ts b/static/dashboard/sockets/cx-proxy.test.ts new file mode 100644 index 000000000..338d625eb --- /dev/null +++ b/static/dashboard/sockets/cx-proxy.test.ts @@ -0,0 +1,141 @@ +/// +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'http'; +import express from 'express'; +import { cxProxy } from './cx-proxy'; + +// End-to-end over real sockets: a stub "core" plus a dash-node app mounting the proxy at +// '/v1', exactly as routes.ts does. This catches path, method, body and streaming relay +// (the pieces a mock would not). + +function listen(server: http.Server): Promise { + return new Promise((resolve) => server.listen(0, '127.0.0.1', () => { + resolve((server.address() as import('net').AddressInfo).port); + })); +} + +// A minimal HTTP client that returns status, headers and the raw body. +function get(port: number, path: string, method = 'GET', body?: string): Promise<{ status: number; body: string; headers: http.IncomingHttpHeaders }> { + return new Promise((resolve, reject) => { + const req = http.request({ host: '127.0.0.1', port, path, method, + headers: body ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) } : {} }, + (res) => { + let data = ''; + res.on('data', (c) => { data += c; }); + res.on('end', () => resolve({ status: res.statusCode || 0, body: data, headers: res.headers })); + }); + req.on('error', reject); + if (body) req.write(body); + req.end(); + }); +} + +// Build the dash-node side: express.json() then the proxy at '/v1', mirroring server.ts. +async function startProxyApp(): Promise<{ port: number; close: () => void }> { + const app = express(); + app.use(express.json()); + app.use('/v1', cxProxy); + const server = http.createServer(app); + const port = await listen(server); + return { port, close: () => server.close() }; +} + +test('cxProxy relays a GET with path + query and the core status/body', async () => { + const core = http.createServer((req, res) => { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ seen: req.url, method: req.method })); + }); + const corePort = await listen(core); + process.env.CX_PORT = String(corePort); + const app = await startProxyApp(); + try { + const r = await get(app.port, '/v1/content?app=kiwix'); + assert.equal(r.status, 200); + const j = JSON.parse(r.body); + // The core must see the full /v1 path and the query, not the mount-stripped path. + assert.equal(j.seen, '/v1/content?app=kiwix'); + assert.equal(j.method, 'GET'); + } finally { + app.close(); core.close(); + } +}); + +test('cxProxy forwards a POST JSON body to the core', async () => { + const core = http.createServer((req, res) => { + let data = ''; + req.on('data', (c) => { data += c; }); + req.on('end', () => { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ echo: JSON.parse(data || '{}'), path: req.url })); + }); + }); + const corePort = await listen(core); + process.env.CX_PORT = String(corePort); + const app = await startProxyApp(); + try { + const r = await get(app.port, '/v1/export/plan', 'POST', JSON.stringify({ items: ['a', 'b'] })); + assert.equal(r.status, 200); + const j = JSON.parse(r.body); + assert.deepEqual(j.echo, { items: ['a', 'b'] }); + assert.equal(j.path, '/v1/export/plan'); + } finally { + app.close(); core.close(); + } +}); + +test('cxProxy streams a chunked response intact (the export path)', async () => { + const payload = 'Z'.repeat(50000); // bigger than one write block + const core = http.createServer((req, res) => { + res.writeHead(200, { 'content-type': 'application/octet-stream' }); // no content-length -> chunked + res.write(payload.slice(0, 25000)); + res.write(payload.slice(25000)); + res.end(); + }); + const corePort = await listen(core); + process.env.CX_PORT = String(corePort); + const app = await startProxyApp(); + try { + const r = await get(app.port, '/v1/export/item/kiwix/foo.zim'); + assert.equal(r.status, 200); + assert.equal(r.body.length, payload.length); + assert.equal(r.body, payload); + } finally { + app.close(); core.close(); + } +}); + +test('cxProxy passes Content-Disposition through (the export filename)', async () => { + const core = http.createServer((req, res) => { + res.writeHead(200, { + 'content-type': 'application/octet-stream', + 'content-disposition': 'attachment; filename="foo.zim"', + }); + res.end('zim-bytes'); + }); + const corePort = await listen(core); + process.env.CX_PORT = String(corePort); + const app = await startProxyApp(); + try { + const r = await get(app.port, '/v1/export/item/kiwix/foo.zim'); + assert.equal(r.status, 200); + assert.equal(r.headers['content-disposition'], 'attachment; filename="foo.zim"'); + } finally { + app.close(); core.close(); + } +}); + +test('cxProxy returns 502 when the core is unreachable', async () => { + // Point at a port with nothing listening. + const dead = http.createServer(); + const deadPort = await listen(dead); + dead.close(); + process.env.CX_PORT = String(deadPort); + const app = await startProxyApp(); + try { + const r = await get(app.port, '/v1/apps'); + assert.equal(r.status, 502); + } finally { + app.close(); + } +}); diff --git a/static/dashboard/sockets/cx-proxy.ts b/static/dashboard/sockets/cx-proxy.ts new file mode 100644 index 000000000..bb2771934 --- /dev/null +++ b/static/dashboard/sockets/cx-proxy.ts @@ -0,0 +1,61 @@ +// cx-proxy.ts - K2GO-427 +// +// Thin relay from dash-node to the content-exchange core (cx-core), a separate in-box +// REST service on 127.0.0.1:9500. The app reaches dash-node (its BFF); dash-node forwards +// /v1/* to the core and streams the answer back. dash-node is a relay here, NOT a second +// brain: it owns none of the content state (one owner per fact, ADR Decision 1 / D1b). No +// proxy library: Node's core http is enough for a localhost passthrough. +import { Request, Response } from 'express'; +import http from 'http'; + +const CX_HOST = '127.0.0.1'; + +// The core's port, env-overridable to match its own CX_PORT default (9500). +function cxPort(): number { + return Number(process.env.CX_PORT) || 9500; +} + +// Forward one request to the core and pipe the response back. Mounted at '/v1', so req.url +// is the path after it (e.g. '/apps', '/export/item/kiwix/foo.zim?x=1'), query included. +// The streaming endpoint (GET /v1/export/item) returns chunked; piping handles it. +export function cxProxy(req: Request, res: Response): void { + const corePath = '/v1' + req.url; + + // express.json() already parsed any JSON body upstream of this handler, so re-serialize + // it. The cx-core contract carries only small JSON bodies (export/plan, import/validate, + // import/item with a payloadPath); item payloads never pass through dash-node. + const isWrite = req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH'; + const hasBody = isWrite && req.body && Object.keys(req.body).length > 0; + const payload = hasBody ? Buffer.from(JSON.stringify(req.body)) : null; + + const headers: Record = {}; + if (payload) { + headers['content-type'] = 'application/json'; + headers['content-length'] = String(payload.length); + } + + const upstream = http.request( + { host: CX_HOST, port: cxPort(), method: req.method, path: corePath, headers }, + (up) => { + res.status(up.statusCode || 502); + // Pass through the headers the client needs: content type, the download filename + // (GET /v1/export/item sets Content-Disposition), and the length when the core knows + // it. A streamed (chunked) export has no content-length, so Node frames it as chunked. + const ct = up.headers['content-type']; + if (ct) res.setHeader('content-type', ct); + const cd = up.headers['content-disposition']; + if (cd) res.setHeader('content-disposition', cd); + const cl = up.headers['content-length']; + if (cl) res.setHeader('content-length', cl); + up.pipe(res); + }, + ); + + upstream.on('error', () => { + if (!res.headersSent) res.status(502).json({ error: 'cx-core unreachable' }); + else res.end(); + }); + + if (payload) upstream.write(payload); + upstream.end(); +} diff --git a/static/pdsm/cx-core b/static/pdsm/cx-core new file mode 100755 index 000000000..62c6ad968 --- /dev/null +++ b/static/pdsm/cx-core @@ -0,0 +1,108 @@ +#!/bin/sh +# /usr/local/pdsm/services-available/cx-core +# PDSM service wrapper for the content-exchange core (Python stdlib REST service). +# K2GO-427: run `python3 -m cx_core` from the install dir, with a respawn supervisor +# and a health probe. Same shape as the dash-node wrapper; the core is identical on +# every environment, only the supervisor differs (pdsm here, systemd on IIAB). + +PDSM_COMMON="/usr/local/pdsm/lib/pdsm-common.sh" +[ -r "$PDSM_COMMON" ] && . "$PDSM_COMMON" + +SERVICE_NAME="cx-core" +APP_DIR="/opt/cx-core" +# The port the health probe and the service agree on. The service reads CX_PORT from +# the environment (default 9500); keep this one value so the probe cannot drift. +CX_PORT="${CX_PORT:-9500}" +export CX_PORT +LOGFILE="/var/log/cx-core.log" +SUP_PIDFILE="/var/run/cx-core.sup.pid" + +running() { + # Liveness-approximate: this also matches the supervisor shell, not only the server. + # health() (curl GET /v1/apps) is the authoritative liveness gate. Kept identical to the + # dash-node wrapper on purpose; unifying the two is a follow-up, not a per-service fix. + pgrep -f "python3 -m cx_core" >/dev/null 2>&1 +} + +start() { + if running; then + echo "[pdsm:$SERVICE_NAME] already running" + return 0 + fi + + echo "[pdsm:$SERVICE_NAME] starting..." + cd "$APP_DIR" || return 1 + + # Supervisor: respawn the server if it exits. Its PID is recorded so stop() can end + # the respawn loop before killing the server. LOGFILE is passed via the env so the + # inner shell expands it at runtime (avoids brittle nested quoting). + LOGFILE="$LOGFILE" nohup sh -c \ + 'while :; do python3 -m cx_core >> "$LOGFILE" 2>&1; echo "[cx-core] exited ($?); respawning in 2s" >> "$LOGFILE"; sleep 2; done' \ + >/dev/null 2>&1 & + echo $! > "$SUP_PIDFILE" + + for i in $(seq 1 "${PDSM_START_TIMEOUT:-8}"); do + if running; then + echo "[pdsm:$SERVICE_NAME] started" + return 0 + fi + sleep 1 + done + + echo "[pdsm:$SERVICE_NAME] failed to start" >&2 + return 1 +} + +stop() { + # Kill the supervisor first so it stops respawning, then the server itself. + if [ -f "$SUP_PIDFILE" ]; then + kill "$(cat "$SUP_PIDFILE")" 2>/dev/null || true + rm -f "$SUP_PIDFILE" + fi + + if ! running; then + echo "[pdsm:$SERVICE_NAME] already stopped" + return 0 + fi + + echo "[pdsm:$SERVICE_NAME] stopping..." + pkill -f "python3 -m cx_core" 2>/dev/null || true + + for i in $(seq 1 "${PDSM_START_TIMEOUT:-5}"); do + if ! running; then + echo "[pdsm:$SERVICE_NAME] stopped" + return 0 + fi + sleep 1 + done + + pkill -9 -f "python3 -m cx_core" 2>/dev/null || true + echo "[pdsm:$SERVICE_NAME] forced stop" + return 1 +} + +status() { + if running; then + echo "[pdsm:$SERVICE_NAME] running (PID: $(pgrep -f "python3 -m cx_core" | head -n 1))" + return 0 + fi + echo "[pdsm:$SERVICE_NAME] not running" + return 3 +} + +health() { + # Liveness: the REST API answers 2xx on loopback (the apps list is always 200). + if command -v curl >/dev/null 2>&1 && \ + curl -fs -o /dev/null "http://127.0.0.1:${CX_PORT}/v1/apps"; then + echo "[pdsm:$SERVICE_NAME] healthy" + return 0 + fi + echo "[pdsm:$SERVICE_NAME] unhealthy" + return 1 +} + +case "$1" in + start|stop|status|health) "$1" ;; + restart) stop; start ;; + *) echo "Usage: $0 {start|stop|restart|status|health}" >&2; exit 1 ;; +esac diff --git a/tools/rootfs-builder/build-iiab-rootfs.sh b/tools/rootfs-builder/build-iiab-rootfs.sh index e2d5f7f44..b9e0fa7a1 100755 --- a/tools/rootfs-builder/build-iiab-rootfs.sh +++ b/tools/rootfs-builder/build-iiab-rootfs.sh @@ -720,6 +720,8 @@ chk "PDSM installed (/usr/local/bin/pdsm)" "test -e '$ROOTFS/usr/local/bin/p chk "flag_install_ready present" "test -e '$ROOTFS/usr/local/pdsm/flag_install_ready'" chk "local_vars.yml has is_proot: True" "grep -qiE '^[[:space:]]*is_proot[[:space:]]*:[[:space:]]*True' '$ROOTFS/etc/iiab/local_vars.yml'" chk "IIAB-oA repo cloned (/opt/iiab-android)" "test -d '$ROOTFS/opt/iiab-android'" +chk "cx-core installed (/opt/cx-core/cx_core)" "test -d '$ROOTFS/opt/cx-core/cx_core'" +chk "cx-core PDSM service registered" "test -x '$ROOTFS/usr/local/pdsm/services-available/cx-core'" # Ansible result: use the PLAY RECAP (authoritative). We do NOT count loose # 'fatal:'/'FAILED!' lines, because block/rescue tasks (e.g. the WiFi-AP probe diff --git a/tools/upstream-patches/overlays/roles/cx_core/defaults/main.yml b/tools/upstream-patches/overlays/roles/cx_core/defaults/main.yml new file mode 100644 index 000000000..9b7f2e344 --- /dev/null +++ b/tools/upstream-patches/overlays/roles/cx_core/defaults/main.yml @@ -0,0 +1,28 @@ +# cx_core_install: True +# cx_core_enabled: True + +# The content-exchange core: an in-box REST service (Python stdlib, no third-party +# deps) that lists, exports and imports content per item across Kiwix, Kolibri and +# Calibre. It is client-agnostic: dash-node (K2Go) or the IIAB Console reach it over +# its localhost REST API. Design: controller/docs/ADR-content-exchange.md (K2GO-427). +# +# The core code is identical on every environment; only the supervisor differs. Under +# proot (K2Go) it runs as a PDSM service; on a systemd host (IIAB) it runs as a systemd +# unit. This role installs the source and the right wrapper, chosen by is_proot. + +# Where the source tree is copied FROM. Default is the K2Go repo path on the box +# (/opt/iiab-android). An IIAB deploy overrides this to wherever it stages the source. +cx_core_src_dir: /opt/iiab-android/static/cx-core + +# Where the core is installed TO (app code, a fixed path). `python3 -m cx_core` runs +# from here. The CX_* runtime paths (zims, kolibri db, staging) default to the box +# layout inside the core itself, so this role sets none of them. +cx_core_serve_path: /opt/cx-core + +# The localhost port the core binds. Matches the core's own default and the health +# probe in the service wrappers. +cx_core_port: 9500 + +# The PDSM service wrapper to install under proot. Ships in the repo next to the +# dash-node wrapper; both drivers (this role and the iiab-android bootstrap) copy it. +cx_core_pdsm_src: "{{ cx_core_src_dir }}/../pdsm/cx-core" diff --git a/tools/upstream-patches/overlays/roles/cx_core/tasks/enable-or-disable.yml b/tools/upstream-patches/overlays/roles/cx_core/tasks/enable-or-disable.yml new file mode 100644 index 000000000..ff291548d --- /dev/null +++ b/tools/upstream-patches/overlays/roles/cx_core/tasks/enable-or-disable.yml @@ -0,0 +1,23 @@ +# Reflect cx_core_enabled on the running service. Idempotent verbs (pdsm start reports +# "already running"; systemd state=started does not bounce a live unit), so this runs on +# every play without churning the service. install.yml already did the first start. + +- name: Start cx-core via PDSM (proot) + command: pdsm start cx-core + when: is_proot and cx_core_enabled + +- name: Stop cx-core via PDSM (proot) + command: pdsm stop cx-core + when: is_proot and not cx_core_enabled + +- name: Start cx-core via systemd (not proot) + systemd: + name: cx-core + state: started + when: not is_proot and cx_core_enabled + +- name: Stop cx-core via systemd (not proot) + systemd: + name: cx-core + state: stopped + when: not is_proot and not cx_core_enabled diff --git a/tools/upstream-patches/overlays/roles/cx_core/tasks/install.yml b/tools/upstream-patches/overlays/roles/cx_core/tasks/install.yml new file mode 100644 index 000000000..b220988ba --- /dev/null +++ b/tools/upstream-patches/overlays/roles/cx_core/tasks/install.yml @@ -0,0 +1,81 @@ +# Install the content-exchange core and its launch wrapper. The core is pure Python 3 +# stdlib (no pip install), so "install" is a file copy plus registering a supervisor. +# The supervisor is PDSM under proot and systemd otherwise, chosen by is_proot. + +- name: Create the install dir {{ cx_core_serve_path }} + file: + path: "{{ cx_core_serve_path }}" # /opt/cx-core + state: directory + mode: "0755" + +- name: Copy the core source into {{ cx_core_serve_path }} + copy: + src: "{{ cx_core_src_dir }}/" # trailing slash: copy the contents + dest: "{{ cx_core_serve_path }}/" + remote_src: yes + mode: preserve + +- name: Create the export staging dir (on the content volume, not /tmp) + file: + path: "{{ content_base }}/.cx-staging" # /library/.cx-staging (core CX_STAGING_DIR default) + state: directory + mode: "0755" + + +# ---- Launch wrapper: PDSM under proot ---- + +- name: Install the PDSM service wrapper (proot) + copy: + src: "{{ cx_core_pdsm_src }}" # static/pdsm/cx-core + dest: /usr/local/pdsm/services-available/cx-core + remote_src: yes + mode: "0755" + when: is_proot + +- name: Enable + start cx-core via PDSM (proot) + command: "pdsm {{ item }} cx-core" + with_items: + - enable + - restart + when: is_proot + + +# ---- Launch wrapper: systemd otherwise (IIAB) ---- + +- name: Install the systemd unit (not proot) + template: + src: cx-core.service.j2 + dest: /etc/systemd/system/cx-core.service + mode: "0644" + when: not is_proot + +- name: Enable + start cx-core via systemd (not proot) + systemd: + name: cx-core + enabled: yes + state: restarted + daemon_reload: yes + when: not is_proot + + +# ---- Health check: the REST API answers on loopback ---- + +- name: Wait for the core to answer GET /v1/apps on 127.0.0.1:{{ cx_core_port }} + uri: + url: "http://127.0.0.1:{{ cx_core_port }}/v1/apps" + status_code: 200 + register: cx_core_health + until: cx_core_health.status == 200 + retries: 10 + delay: 2 + + +- name: "Set 'cx_core_installed: True'" + set_fact: + cx_core_installed: True + +- name: "Add 'cx_core_installed: True' to {{ iiab_state_file }}" + lineinfile: + path: "{{ iiab_state_file }}" # /etc/iiab/iiab_state.yml + regexp: '^cx_core_installed' + line: 'cx_core_installed: True' diff --git a/tools/upstream-patches/overlays/roles/cx_core/tasks/main.yml b/tools/upstream-patches/overlays/roles/cx_core/tasks/main.yml new file mode 100644 index 000000000..33b3e9d89 --- /dev/null +++ b/tools/upstream-patches/overlays/roles/cx_core/tasks/main.yml @@ -0,0 +1,46 @@ +- name: Assert that "cx_core_install is sameas true" (boolean not string etc) + assert: + that: cx_core_install is sameas true + fail_msg: "PLEASE SET 'cx_core_install: True' e.g. IN: /etc/iiab/local_vars.yml" + quiet: yes + +- name: Assert that "cx_core_enabled | type_debug == 'bool'" (boolean not string etc) + assert: + that: cx_core_enabled | type_debug == 'bool' + fail_msg: "PLEASE GIVE VARIABLE 'cx_core_enabled' A PROPER (UNQUOTED) ANSIBLE BOOLEAN VALUE e.g. IN: /etc/iiab/local_vars.yml" + quiet: yes + + +- block: + + - name: Install the content-exchange core if 'cx_core_installed' not defined, e.g. in {{ iiab_state_file }} + include_tasks: install.yml + when: cx_core_installed is undefined + + - name: Enable/Disable the content-exchange core service + include_tasks: enable-or-disable.yml + + - name: Add 'cx_core' variable values to {{ iiab_ini_file }} + ini_file: + path: "{{ iiab_ini_file }}" # /etc/iiab/iiab.ini + section: cx_core + option: "{{ item.option }}" + value: "{{ item.value | string }}" + with_items: + - option: name + value: Content exchange core + - option: description + value: 'In-box REST service for granular content exchange (Kiwix, Kolibri, Calibre).' + - option: cx_core_install + value: "{{ cx_core_install }}" + - option: cx_core_enabled + value: "{{ cx_core_enabled }}" + - option: cx_core_port + value: "{{ cx_core_port }}" + + rescue: + + - name: 'SEE ERROR ABOVE (skip_role_on_error: {{ skip_role_on_error }})' + fail: + msg: "" + when: not skip_role_on_error diff --git a/tools/upstream-patches/overlays/roles/cx_core/templates/cx-core.service.j2 b/tools/upstream-patches/overlays/roles/cx_core/templates/cx-core.service.j2 new file mode 100644 index 000000000..a2e81e602 --- /dev/null +++ b/tools/upstream-patches/overlays/roles/cx_core/templates/cx-core.service.j2 @@ -0,0 +1,16 @@ +# cx-core: content-exchange core (K2GO-427). systemd unit for IIAB hosts; the proot +# (K2Go) path uses the PDSM wrapper instead. The core is Python stdlib, localhost-only. +[Unit] +Description=Content exchange core (REST service for Kiwix/Kolibri/Calibre) +After=network.target + +[Service] +Type=simple +WorkingDirectory={{ cx_core_serve_path }} +Environment=CX_PORT={{ cx_core_port }} +ExecStart=/usr/bin/python3 -m cx_core +Restart=always +RestartSec=2 + +[Install] +WantedBy=multi-user.target