2020-08-06 14:36:25 -07:00
|
|
|
#!/bin/bash
|
|
|
|
|
|
|
|
|
|
set -eu -o pipefail
|
|
|
|
|
|
2020-08-06 22:04:46 -07:00
|
|
|
readonly script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
|
|
|
readonly task_worker="${script_dir}/../taskworker.js"
|
|
|
|
|
|
2020-08-06 14:36:25 -07:00
|
|
|
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"
|
2020-08-10 21:53:07 -07:00
|
|
|
readonly memory_limit_mb="$4"
|
2020-08-06 14:36:25 -07:00
|
|
|
|
2020-08-09 07:07:19 -07:00
|
|
|
readonly service_name="box-task-${task_id}"
|
2020-09-01 11:14:29 -07:00
|
|
|
systemctl reset-failed "${service_name}" 2>/dev/null || true
|
2020-08-06 14:36:25 -07:00
|
|
|
|
2020-08-06 22:04:46 -07:00
|
|
|
readonly id=$(id -u $SUDO_USER)
|
2020-08-07 00:15:24 -07:00
|
|
|
readonly ubuntu_version=$(lsb_release -rs)
|
2020-08-08 11:10:02 -07:00
|
|
|
|
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-08-06 22:04:46 -07:00
|
|
|
|
2020-09-01 11:14:29 -07:00
|
|
|
# systemd 237 on ubuntu 18.04 does not apply --nice
|
2020-08-26 17:24:41 -07:00
|
|
|
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
|
|
|
|
|
|
2020-08-08 11:10:02 -07:00
|
|
|
# DEBUG has to be hardcoded because it is not set in the tests. --setenv is required for ubuntu 16 (-E does not work)
|
2021-05-14 09:36:00 -07:00
|
|
|
# NODE_OPTIONS is used because env -S does not work in ubuntu 16/18.
|
2020-08-08 11:10:02 -07:00
|
|
|
systemd-run --unit "${service_name}" --nice "${nice}" --uid=${id} --gid=${id} ${options} \
|
2021-05-14 09:36:00 -07:00
|
|
|
--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 \
|
2021-05-14 11:13:52 +02:00
|
|
|
"${task_worker}" "${task_id}" "${logfile}"
|
2020-08-08 11:10:02 -07:00
|
|
|
exit_code=$?
|
|
|
|
|
|
|
|
|
|
echo "Service ${service_name} finished with exit code ${exit_code}"
|
|
|
|
|
exit "${exit_code}"
|