Files
cloudron-box/src/scripts/starttask.sh

54 lines
1.8 KiB
Bash
Raw Normal View History

#!/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"
readonly service_name="box-task-${task_id}"
2020-09-01 11:14:29 -07:00
systemctl reset-failed "${service_name}" 2>/dev/null || true
readonly id=$(id -u $SUDO_USER)
2020-08-07 00:15:24 -07:00
readonly ubuntu_version=$(lsb_release -rs)
2022-11-02 21:22:42 +01:00
options="-p TimeoutStopSec=10s -p MemoryMax=${memory_limit_mb}M --pipe --wait"
2020-08-07 00:15:24 -07:00
2022-11-02 21:22:42 +01:00
# 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"
2020-09-01 11:14:29 -07:00
# systemd 237 on ubuntu 18.04 does not apply --nice
if [[ "${ubuntu_version}" == "18.04" ]]; then
(sleep 1; pid=$(systemctl show "${service_name}" -p MainPID | sed 's/MainPID=//g'); renice -n ${nice} -g ${pid} || true) &
fi
# DEBUG has to be hardcoded because it is not set in the tests. --setenv is required for ubuntu 16 (-E does not work)
# NODE_OPTIONS is used because env -S does not work in ubuntu 16/18.
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 --setenv NODE_OPTIONS=--unhandled-rejections=strict \
"${task_worker}" "${task_id}" "${logfile}"
exit_code=$?
echo "Service ${service_name} finished with exit code ${exit_code}"
exit "${exit_code}"