#!/bin/bash set -eu -o pipefail readonly script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" readonly task_worker="${script_dir}/../taskworker.js" if [[ ${EUID} -ne 0 ]]; then echo "This script should be run as root." > /dev/stderr exit 1 fi if [[ $# -eq 0 ]]; then echo "No arguments supplied" exit 1 fi if [[ "$1" == "--check" ]]; then echo "OK" exit 0 fi readonly task_id="$1" readonly logfile="$2" readonly nice="$3" readonly memory_limit_mb="$4" # SI units readonly oom_score_adjust="$5" readonly service_name="box-task-${task_id}" systemctl reset-failed "${service_name}" 2>/dev/null || true readonly id=$(id -u $SUDO_USER) options="-p TimeoutStopSec=10s -p MemoryMax=${memory_limit_mb}M -p OOMScoreAdjust=${oom_score_adjust} --wait" # Note: BindsTo will kill this task when the box is stopped. but will not kill this task when restarted! # For this reason, we have code to kill the tasks both on shutdown and startup. [[ "$BOX_ENV" == "cloudron" ]] && options="${options} -p BindsTo=box.service" # DEBUG has to be hardcoded because it is not set in the tests. --setenv is required for ubuntu 16 (-E does not work) # it seems systemd-run does not return the exit status of the process despite --wait if ! systemd-run --unit "${service_name}" --nice "${nice}" --uid=${id} --gid=${id} ${options} --setenv HOME=${HOME} --setenv USER=${SUDO_USER} --setenv DEBUG=box:* --setenv BOX_ENV=${BOX_ENV} --setenv NODE_ENV=production "${task_worker}" "${task_id}" "${logfile}"; then echo "Service ${service_name} failed to run" # this only happens if the path to task worker itself is wrong fi exit_code=$(systemctl show "${service_name}" -p ExecMainCode | sed 's/ExecMainCode=//g') echo "Service ${service_name} finished with exit code ${exit_code}" exit "${exit_code}"