#!/bin/sh # Usage: docker run [web|worker|sandbox|] (default: web) # # Started as root (the default), it prepares the folders, then drops to PUID:PGID (default # 1000:1000) and runs as that user. Started as a user already (`user:` in compose), it skips that. set -e role="${1:-web}" models="${MODELS_DIR:-/models}" if [ "$(id -u)" = 0 ] && [ "$role" != sandbox ]; then uid="${PUID:-1000}" gid="${PGID:-1000}" as_user() { setpriv --reuid="$uid" --regid="$gid" --clear-groups "$@"; } # /data is Kaname's own (database, results): take it over if a new or old mount belongs to someone else. if [ -d /data ] && [ "$(stat -c %u:%g /data)" != "$uid:$gid" ]; then echo "Taking over /data for $uid:$gid" chown -R "$uid:$gid" /data fi # The models folder may be a NAS share with other files: only a new, empty one is taken over. if [ "$role" = worker ] && [ -d "$models" ] && ! as_user sh -c 'touch "$1/.write-test" && rm -f "$1/.write-test"' _ "$models" 2>/dev/null; then if [ -z "$(ls -A "$models")" ]; then echo "Taking over the empty models folder for $uid:$gid" chown "$uid:$gid" "$models" fi fi # The exchange folder with the sandbox (which runs as nobody); volumes from before 0.15.2 are 0755. if [ "$role" = worker ] && [ -d "${SANDBOX_DIR:-/sandbox}" ]; then chmod 0777 "${SANDBOX_DIR:-/sandbox}"; fi export HOME=/home/app exec setpriv --reuid="$uid" --regid="$gid" --clear-groups "$0" "$@" fi require_writable() { if ! touch "$1/.write-test" 2>/dev/null; then echo "ERROR: $1 is not writable by uid $(id -u). Give that user access on the host (e.g. chown -R $(id -u):$(id -g) ), or set PUID/PGID in .env to the folder's owner." >&2 exit 1 fi rm -f "$1/.write-test" } case "$role" in web|worker) echo "$role" > /tmp/kaname-role require_writable /data if [ "$role" = worker ]; then require_writable "$models"; fi # Without AUTH_SECRET, one is generated on first start and kept in /data. if [ "$role" = web ] && [ -z "$AUTH_SECRET" ]; then [ -s /data/.auth-secret ] || (umask 077 && head -c 33 /dev/urandom | base64 > /data/.auth-secret) AUTH_SECRET="$(cat /data/.auth-secret)" export AUTH_SECRET fi # web and worker usually start together; the lock makes sure only one runs the migrations. flock /data/.migrate.lock node dist/migrate.mjs ;; esac case "$role" in web) exec node server.js ;; # Next.js standalone server (see Dockerfile) worker) exec node dist/worker.mjs ;; sandbox) # It runs code written by the model under test: never as root (compose gives it `user:`). if [ "$(id -u)" = 0 ]; then echo "ERROR: the sandbox must not run as root; give the service a user, e.g. user: \"65534:65534\"." >&2 exit 1 fi echo sandbox > /tmp/kaname-role require_writable "${SANDBOX_DIR:-/sandbox}" exec node dist/sandbox.mjs ;; *) exec "$@" ;; esac