64 lines
2.2 KiB
Bash
Executable File
64 lines
2.2 KiB
Bash
Executable File
#!/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}"
|
|
systemctl reset-failed "${service_name}" || true
|
|
|
|
readonly id=$(id -u $SUDO_USER)
|
|
readonly ubuntu_version=$(lsb_release -rs)
|
|
|
|
if [[ "${ubuntu_version}" == "16.04" ]]; then
|
|
options="-p MemoryLimit=${memory_limit_mb}M --remain-after-exit"
|
|
else
|
|
options="-p MemoryMax=${memory_limit_mb}M --pipe --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.
|
|
# BindsTo does not work on ubuntu 16, this means that even if box is stopped, the tasks keep running
|
|
[[ "$BOX_ENV" == "cloudron" ]] && options="${options} -p BindsTo=box.service"
|
|
fi
|
|
|
|
# DEBUG has to be hardcoded because it is not set in the tests. --setenv is required for ubuntu 16 (-E does not work)
|
|
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}"
|
|
exit_code=$?
|
|
|
|
if [[ "${ubuntu_version}" == "16.04" ]]; then
|
|
sleep 3
|
|
# we cannot use systemctl is-active because unit is always active until stopped with RemainAfterExit
|
|
while [[ "$(systemctl show -p SubState ${service_name})" == *"running"* ]]; do
|
|
echo "Waiting for service ${service_name} to finish"
|
|
sleep 3
|
|
done
|
|
exit_code=$(systemctl show "${service_name}" -p ExecMainStatus | sed 's/ExecMainStatus=//g')
|
|
systemctl stop "${service_name}" || true # because of remain-after-exit we have to deactivate the service
|
|
fi
|
|
|
|
echo "Service ${service_name} finished with exit code ${exit_code}"
|
|
exit "${exit_code}"
|