Files
wekan/snap-src/bin/migration-control
T
Lauri Ojansivu 7d271413bf Snap: make database setting authoritative + wekan.database command + no-downtime on failure
Problem: the control scripts force-switched to FerretDB whenever a *.sqlite file existed, so
`snap set wekan database=mongodb` did not stick and a failed migration caused downtime with no
way to keep WeKan running on MongoDB while fixing it.

- The `database` snap setting is now AUTHORITATIVE. Removed the "FerretDB SQLite present ->
  force ferretdb / disable mongodb" overrides from wekan-control, ferretdb-control and
  mongodb-control. wekan-control keeps only the safety guard (never start an EMPTY FerretDB
  while MongoDB has data).

- New `snap run wekan.database mongodb|ferretdb` command (bin/wekan-database): switch which
  database WeKan runs on. `mongodb` also pauses auto-migration (migrate=off) so it does not
  switch back; `ferretdb` requires a non-empty SQLite first.

- Auto-migration can be paused: migration-pending now also returns "not pending" when
  `snap get migrate` == off. A migration that FAILS now runs fail_and_run_mongodb: delete the
  partial SQLite, set migrate=off, and exec mongodb-control so WeKan keeps working on MongoDB
  (no downtime, no retry loop). fall_back_to_mongodb likewise sets migrate=off instead of the
  done marker. `snap run wekan.migrate` re-enables migrate and retries.

- finish_success now restarts wekan.wekan so it reconnects to FerretDB after a successful
  migration instead of waiting for the now-stopped MongoDB.

Registered the `database` app in snapcraft.yaml and snapcraft-core26.yaml (also added the
previously-missing migrate/maintenance apps to core26).

Thanks to xet7.
2026-07-15 08:58:36 +03:00

313 lines
17 KiB
Bash
Executable File

#!/bin/bash
# ─────────────────────────────────────────────────────────────────────────────
# One-time MongoDB → FerretDB v1 (SQLite) migration for the WeKan snap.
#
# Runs on startup (called by mongodb-control) BEFORE mongod starts. The WeKan snap
# moves EVERY existing MongoDB database — MongoDB 3, MongoDB 7, or any other real
# MongoDB — onto FerretDB (SQLite): text data into SQLite and the CollectionFS +
# Meteor-Files GridFS attachments/avatars onto the filesystem. Afterwards MongoDB is
# shut down and only WeKan (Node.js) + FerretDB (SQLite) run. The MongoDB version
# only decides HOW the source is read.
#
# Flow:
# 1. If the bundled mongod 7 can open the existing $SNAP_COMMON data, it is a
# modern MongoDB (6/7, incl. a DB earlier migrated up from 3.x). Keep that
# mongod running as the source and migrate with the modern driver importer
# (migrate-mongodb-to-ferretdb.mjs) into a temporary FerretDB v1 (SQLite at
# <files>/db), extracting GridFS files to <files>/attachments and
# <files>/avatars.
# 2. Otherwise, if the bundled migratemongo mongod 3.2 can open it, it is old
# MongoDB 3.x: run migrate-mongo3-to-ferretdb.mjs, which reads the source with
# the legacy mongo CLI (mongoexport — the modern Node driver can't talk to 3.2)
# and inserts into FerretDB with the Node driver, extracting GridFS the same
# way. NO mongodump/mongorestore and no intermediate MongoDB 7.
# 3. On success it switches the snap to database=ferretdb (MongoDB is then stopped
# and disabled by mongodb-control). Progress is shown at ROOT_URL.
# 4. If neither mongod can open the data (unusual/corrupt) or the tools are
# missing, it falls back to a normal MongoDB start so the service is never left
# dead, and retries next boot.
#
# Idempotent (completion marker), never deletes or modifies the source MongoDB
# data, only switches on success.
#
# IMPORTANT: the amd64 6.09/MongoDB-3.2 path has NOT been exercised end-to-end
# against a real 6.09 snap here — test on a copy first.
# ─────────────────────────────────────────────────────────────────────────────
set -u
if [[ "${PATH:-}" != *"${SNAP_INSTANCE_NAME:-wekan}"* ]]; then
export PATH="${PATH/\/snap\/wekan\//\/snap\/${SNAP_INSTANCE_NAME:-wekan}\/}"
fi
MARKER="$SNAP_COMMON/.migration-to-ferretdb-done"
DBPATH="$SNAP_COMMON" # old snap's mongod --dbpath
FILES_DIR="$SNAP_COMMON/files" # attachments/, avatars/, db/
SQLITE_DIR="$FILES_DIR/db" # FerretDB SQLite lives here
SRC_PORT=27099 # temp source mongod
TGT_PORT=27098 # temp target FerretDB
NODE="$SNAP/bin/node"
IMPORTER="$SNAP/bin/migrate-mongo3-to-ferretdb.mjs" # MongoDB 3.2 (legacy CLI)
IMPORTER_MODERN="$SNAP/bin/migrate-mongodb-to-ferretdb.mjs" # MongoDB 6/7 (driver)
FERRETDB="$SNAP/ferretdb"
DB_EVAL="$SNAP/bin/db-eval" # Node + `mongodb` driver
SRC_URL="mongodb://127.0.0.1:$SRC_PORT/?directConnection=true"
MM="$SNAP/migratemongo" # MongoDB 3.2 tools (amd64)
MM_LIB="$MM/lib/x86_64-linux-gnu" # old libs for those tools
LOGF="$SNAP_COMMON/migration-mongod.log"
SRC_PIDFILE="$SNAP_COMMON/migration-src-mongod.pid" # temp source mongod pid
log() { echo "[migration] $*"; }
[ -f "$MARKER" ] && { log "already handled (marker present)."; exit 0; }
if [ ! -f "$DBPATH/WiredTiger" ] && ! ls "$DBPATH"/collection-*.wt >/dev/null 2>&1; then
log "no existing MongoDB data in $DBPATH; nothing to migrate."
touch "$MARKER" 2>/dev/null || true
exit 0
fi
export LC_ALL=C
# Base library path so the snap's own mongod 7 finds its libraries
# (docs/Backup/Backup.md: $SNAP/lib/<arch>-linux-gnu).
export LD_LIBRARY_PATH="$SNAP/lib:$SNAP/lib/x86_64-linux-gnu:$SNAP/lib/aarch64-linux-gnu:${LD_LIBRARY_PATH:-}"
# RAM-aware WiredTiger cache for the TEMPORARY source mongod we start to READ the existing
# data during migration. mongod's own default (~50% of RAM) is too much HERE because the
# target FerretDB and the Node importer run at the SAME time and also need RAM - and an
# oversized cache is exactly what OOM-kills mongod on small boxes (#6454). Use a
# conservative quarter of (RAM - 1 GB), min 1 GB, cap 8 GB. Override with
# MIGRATION_MONGOD_CACHE_GB. (Applied only to the mongod 7 read below, which is
# WiredTiger-only; the legacy mongod 3.2 read keeps its own RAM-aware default so the flag
# can never clash with an MMAPv1 3.x dbpath.)
if [ -n "${MIGRATION_MONGOD_CACHE_GB:-}" ]; then
SRC_WT_CACHE_GB="${MIGRATION_MONGOD_CACHE_GB}"
else
_mem_kb=$(awk '/^MemTotal:/{print $2}' /proc/meminfo 2>/dev/null)
[ -z "${_mem_kb:-}" ] && _mem_kb=2097152 # assume 2 GB if MemTotal is unreadable
_mem_gb=$(( _mem_kb / 1024 / 1024 ))
SRC_WT_CACHE_GB=$(( (_mem_gb - 1) / 4 ))
[ "${SRC_WT_CACHE_GB}" -lt 1 ] && SRC_WT_CACHE_GB=1
[ "${SRC_WT_CACHE_GB}" -gt 8 ] && SRC_WT_CACHE_GB=8
fi
log "Temporary source mongod WiredTiger cache: ${SRC_WT_CACHE_GB} GB (RAM-aware; leaves room for FerretDB + importer)"
start_mongod() { # $1 = mongod binary, $2 = LD_LIBRARY_PATH prefix (may be empty), $3 = extra args (optional)
rm -f "$SRC_PIDFILE"
# --pidfilepath records the forked daemon's PID so force_stop_src can kill
# exactly this temporary mongod before we hand back to the normal mongod start
# — otherwise a lingering probe mongod would still hold the WiredTiger dbpath
# lock and the real start would fail with "Unable to lock the lock file".
LD_LIBRARY_PATH="${2:+$2:}$LD_LIBRARY_PATH" "$1" \
--dbpath "$DBPATH" --bind_ip 127.0.0.1 --port "$SRC_PORT" \
--logpath "$LOGF" --logappend --fork --pidfilepath "$SRC_PIDFILE" ${3:-} >/dev/null 2>&1
}
# Guarantee no temporary source mongod is left holding the dbpath lock.
force_stop_src() {
if [ -f "$SRC_PIDFILE" ]; then
local p; p="$(cat "$SRC_PIDFILE" 2>/dev/null)"
if [ -n "$p" ]; then
kill "$p" 2>/dev/null || true
sleep 1
kill -9 "$p" 2>/dev/null || true
fi
rm -f "$SRC_PIDFILE"
fi
sleep 1
}
# Readiness/shutdown for the modern mongod 7 use db-eval (Node + `mongodb` driver).
ready_via_node() {
# Up to 45s: a healthy MongoDB 6/7 database can need time to replay its journal
# / recover a large oplog on first open, and a false "not ready" here used to be
# misread as "this is MongoDB 3.x" (#6454). BUT fast-fail if the temporary mongod has
# already EXITED (e.g. mongod 7 cannot open old MongoDB 3.x data): keep waiting only while
# the process is alive, so a doomed probe drops straight to the 3.2 reader instead of
# pinging a dead process for the full timeout. (With --fork, start_mongod usually already
# returns non-zero when mongod cannot open the data; this also covers a mongod that started
# then died mid-probe.)
local i=0 p
while [ $i -lt 45 ]; do
"$DB_EVAL" ping "$SRC_URL" >/dev/null 2>&1 && return 0
p="$(cat "$SRC_PIDFILE" 2>/dev/null)"
if [ -n "$p" ] && ! kill -0 "$p" 2>/dev/null; then
log "Temporary mongod (pid $p) has exited — it could not open this data. Not waiting further; will try the MongoDB 3.x reader."
return 1
fi
i=$((i+1)); sleep 1
done
return 1
}
stop_via_node() {
"$DB_EVAL" shutdown "$SRC_URL" >/dev/null 2>&1 || true
sleep 2
}
# The legacy MongoDB 3.2 client (migratemongo `mongo`) still uses --eval: the
# modern driver cannot speak to a 3.2 server, and mongosh is no longer bundled.
ready_via() { # $1 = shell binary (legacy mongo), $2 = LD_LIBRARY_PATH prefix
local i=0
while [ $i -lt 20 ]; do
LD_LIBRARY_PATH="${2:+$2:}$LD_LIBRARY_PATH" "$1" --port "$SRC_PORT" --quiet \
--eval 'db.adminCommand({ping:1}).ok' 2>/dev/null | grep -q 1 && return 0
i=$((i+1)); sleep 1
done
return 1
}
stop_via() { # $1 = shell binary (legacy mongo), $2 = LD_LIBRARY_PATH prefix
LD_LIBRARY_PATH="${2:+$2:}$LD_LIBRARY_PATH" "$1" --port "$SRC_PORT" --quiet \
--eval 'db.getSiblingDB("admin").shutdownServer()' >/dev/null 2>&1 || true
sleep 2
}
WEKAN_PORT="${PORT:-8080}"
# Start a temporary FerretDB v1 (SQLite at <files>/db) as the migration TARGET, and
# arm an EXIT trap that stops it and the source mongod. $1 = the source-mongod stop
# command to run in the trap.
FPID=""
start_target_ferretdb() { # $1 = source-stop shell command
mkdir -p "$SQLITE_DIR"
export DO_NOT_TRACK=1 FERRETDB_TELEMETRY=disable
"$FERRETDB" --handler=sqlite --sqlite-url="file:$SQLITE_DIR/" \
--listen-addr="127.0.0.1:$TGT_PORT" --telemetry=disable \
>"$SNAP_COMMON/migration-ferretdb.log" 2>&1 &
FPID=$!
trap "kill \"$FPID\" 2>/dev/null || true; $1; force_stop_src" EXIT INT TERM
}
# On a successful migration: mark done and switch the snap to FerretDB. The MongoDB
# source mongod (temporary) is stopped by the EXIT trap, and mongodb-control, seeing
# database=ferretdb on the next activation, stops+disables the MongoDB service — so
# afterwards only WeKan (Node.js) + FerretDB (SQLite) run.
finish_success() {
# VERIFY the migration actually produced a non-empty FerretDB SQLite database before
# switching. The importer returning 0 is not enough: if it wrote nothing (e.g. it connected
# but a bug left the target empty), switching would point WeKan at an EMPTY FerretDB. Require
# a *.sqlite file bigger than 0 bytes (ferretdb-has-data); the -wal/-shm sidecars are present
# too right after migration, so log them as extra confirmation. On failure, do NOT switch or
# mark done — keep the MongoDB data and let it retry on the next start.
if ! bash "$SNAP/bin/ferretdb-has-data" "$SQLITE_DIR"; then
log "ERROR: importer reported success but no non-empty FerretDB SQLite database exists in $SQLITE_DIR. NOT switching to FerretDB; MongoDB data kept; will retry next start."
return 1
fi
local sq wal
sq="$(ls -la "$SQLITE_DIR"/*.sqlite 2>/dev/null | head -n1)"
wal="$(ls "$SQLITE_DIR"/*.sqlite-wal 2>/dev/null | head -n1)"
log "FerretDB SQLite verified (${sq:-?})${wal:+; WAL log present}."
log "Migration succeeded. Switching to FerretDB (SQLite); MongoDB will be shut down."
touch "$MARKER"
snapctl set database=ferretdb 2>/dev/null || true
# CRUCIAL: an INTERNAL `snapctl set` does NOT re-run the configure hook, so we must flip
# the database services here ourselves — exactly as snap/hooks/configure's ferretdb
# branch does. Otherwise FerretDB (which disabled its own service while database=mongodb)
# is never enabled/started, MongoDB stays enabled, and WeKan is left with no database to
# talk to ("MongoDB not ready yet, retrying in 5 seconds..." forever). Enable+start
# FerretDB FIRST (so a DB is running before we stop MongoDB, and before disabling THIS
# service can terminate us). Use the instance name so parallel snaps (wekan_customer, …)
# target their own services.
local svc="${SNAP_INSTANCE_NAME:-${SNAP_NAME:-wekan}}"
snapctl start --enable "${svc}.ferretdb" 2>/dev/null || true
snapctl restart "${svc}.ferretdb" 2>/dev/null || true
snapctl stop --disable "${svc}.mongodb" 2>/dev/null || true
# WeKan (wekan.wekan) was waiting for MongoDB (which is now gone); restart it so it re-reads
# database=ferretdb and connects to FerretDB, instead of waiting forever for MongoDB.
snapctl restart "${svc}.wekan" 2>/dev/null || true
log "FerretDB (SQLite) service enabled and started; MongoDB stopped/disabled; WeKan restarted onto FerretDB."
}
# A FAILED migration may have written a PARTIAL FerretDB SQLite (some collections copied before
# the error). Left in place it looks "non-empty" to ferretdb-has-data and would wrongly make the
# snap use an incomplete FerretDB and disable MongoDB. On any failure, stop the temporary target
# FerretDB and delete the partial SQLite so the snap cleanly stays on MongoDB and retries next
# start. The source MongoDB data is never touched.
discard_partial_ferretdb() {
[ -n "${FPID:-}" ] && kill "$FPID" 2>/dev/null || true
sleep 1
rm -rf "${SQLITE_DIR:?}/"* 2>/dev/null || true
log "Removed any partial FerretDB SQLite from $SQLITE_DIR; the snap stays on MongoDB."
}
# A migration FAILURE must NOT cause downtime. Delete any partial FerretDB SQLite, PAUSE
# auto-migration (`migrate=off`) so it does not loop and re-hijack every start, and hand back to
# mongodb-control to start MongoDB normally — so WeKan keeps working on MongoDB while the admin
# fixes the problem and reruns `snap run wekan.migrate` (which re-enables migrate). The source
# MongoDB data is never modified or deleted.
fail_and_run_mongodb() {
discard_partial_ferretdb
snapctl set migrate=off 2>/dev/null || true
log "Auto-migration PAUSED (snap set wekan migrate=off) so WeKan keeps working on MongoDB."
log "Fix the problem, then retry with: snap run wekan.migrate"
force_stop_src
exec bash "$SNAP/bin/mongodb-control"
}
# Last resort when the data can be read by neither mongod 7 nor mongod 3.2 (unusual / corrupt),
# or the migration tools are missing: don't loop with nothing running — pause auto-migration and
# hand back to mongodb-control so mongod starts normally. Data is never modified or deleted.
fall_back_to_mongodb() { # $1 = human-readable reason
log "$1"
log "Starting MongoDB normally (no migration this run). Pausing auto-migration (migrate=off)."
force_stop_src
snapctl set migrate=off 2>/dev/null || true
exec bash "$SNAP/bin/mongodb-control"
}
# ── Any modern MongoDB (6/7, incl. a DB earlier migrated from 3.x)? ───────────
# The WeKan snap moves every existing MongoDB database — MongoDB 3, MongoDB 7, or any
# other real MongoDB — onto FerretDB (SQLite): text data into SQLite and the
# CollectionFS + Meteor-Files GridFS attachments/avatars onto the filesystem
# (files/attachments, files/avatars). Version only decides HOW we read the source.
log "Checking whether mongod 7 can open the existing data ..."
if start_mongod "$SNAP/bin/mongod" "" "--wiredTigerCacheSizeGB ${SRC_WT_CACHE_GB}" && ready_via_node; then
if [ ! -x "$FERRETDB" ] || [ ! -x "$NODE" ] || [ ! -f "$IMPORTER_MODERN" ]; then
fall_back_to_mongodb "Migration tools unavailable; cannot migrate this modern MongoDB to FerretDB."
fi
log "Detected modern MongoDB (mongod 7 opened it). Migrating to FerretDB (SQLite) ..."
start_target_ferretdb "stop_via_node"
log "Migrating MongoDB → FerretDB (driver). Progress at ${ROOT_URL:-http://localhost:$WEKAN_PORT}"
# The modern importer reads the running source mongod with the `mongodb` driver and
# extracts GridFS files to WRITABLE_PATH/files/{attachments,avatars}. NODE_PATH lets
# it resolve its `mongodb`/`bson` imports from the WeKan bundle.
NODE_PATH="$SNAP/programs/server/node_modules" \
SOURCE_MONGO_URL="mongodb://127.0.0.1:$SRC_PORT/wekan?directConnection=true" \
TARGET_MONGO_URL="mongodb://127.0.0.1:$TGT_PORT/wekan" \
WRITABLE_PATH="$SNAP_COMMON" \
MIGRATION_PORT="$WEKAN_PORT" \
"$NODE" "$IMPORTER_MODERN"
rc=$?
if [ "$rc" -eq 0 ] && finish_success; then exit 0; fi
log "ERROR: migration did not complete (importer rc=$rc). Keeping WeKan on MongoDB."
fail_and_run_mongodb
fi
stop_via_node
force_stop_src
# ── Otherwise, old MongoDB 3.x? Read it with the bundled migratemongo 3.2 CLI. ─
if [ ! -x "$MM/bin/mongod" ] || [ ! -x "$MM/bin/mongo" ] || [ ! -x "$FERRETDB" ] || [ ! -x "$NODE" ] || [ ! -f "$IMPORTER" ]; then
fall_back_to_mongodb "Migration tools unavailable; cannot migrate MongoDB 3.x to FerretDB."
fi
log "mongod 7 could not open the data; checking whether it is MongoDB 3.x ..."
if ! start_mongod "$MM/bin/mongod" "$MM_LIB" || ! ready_via "$MM/bin/mongo" "$MM_LIB"; then
stop_via "$MM/bin/mongo" "$MM_LIB"
fall_back_to_mongodb "Data is not readable as modern MongoDB or MongoDB 3.x; not migrating."
fi
log "Detected MongoDB 3.x. Migrating to FerretDB (SQLite) via the migratemongo CLI ..."
start_target_ferretdb "stop_via \"$MM/bin/mongo\" \"$MM_LIB\""
log "Migrating MongoDB 3 → FerretDB (CLI read + driver insert). Progress at ${ROOT_URL:-http://localhost:$WEKAN_PORT}"
# NODE_PATH lets the standalone importer resolve its `mongodb`/`bson` imports from
# the WeKan bundle. MONGO_BIN_DIR/MONGO_LIB point at the migratemongo 3.2 tools.
NODE_PATH="$SNAP/programs/server/node_modules" \
MONGO_BIN_DIR="$MM/bin" \
MONGO_LIB="$MM_LIB" \
SRC_PORT="$SRC_PORT" \
SRC_DB="wekan" \
TARGET_MONGO_URL="mongodb://127.0.0.1:$TGT_PORT/wekan" \
FILES_DIR="$FILES_DIR" \
MIGRATION_PORT="$WEKAN_PORT" \
"$NODE" "$IMPORTER"
rc=$?
if [ "$rc" -eq 0 ] && finish_success; then :
else
log "ERROR: migration did not complete (importer rc=$rc). Keeping WeKan on MongoDB."
fail_and_run_mongodb
fi
# temp FerretDB + source mongod are stopped by the EXIT trap.
exit 0