Files
easyai/scripts/install-infrastructure-update-task.sh
T
wangbo 89a4ccd7e7
Test deployment public URL (Linux) / test-linux (push) Canceled after 0s
Test start.ps1 (Windows) / test-windows (push) Canceled after 0s
feat(deploy): 为更新组件增加定时维护与双保险
2026-10-08 09:23:25 +08:00

58 lines
2.5 KiB
Bash
Executable File

#!/bin/bash
set -euo pipefail
PROJECT_ROOT="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
PROJECT_ROOT="$(cd "$PROJECT_ROOT" && pwd)"
. "$PROJECT_ROOT/scripts/init-security-env.sh"
# A path is shell-quoted and percent-escaped before embedding it in crontab.
[[ "$PROJECT_ROOT" != *$'\n'* ]] || { echo '部署目录不能包含换行'; exit 1; }
task_id="$(printf '%s' "$PROJECT_ROOT" | cksum | awk '{print $1}')"
marker="# easyai-infrastructure-update-$task_id"
job="$(printf '%q' "$PROJECT_ROOT/scripts/update-infrastructure.sh")"
job="${job//%/\\%}"
entry="17 */6 * * * PATH=/usr/local/bin:/opt/homebrew/bin:/usr/sbin:/usr/bin:/sbin:/bin /bin/bash $job >/dev/null 2>&1 $marker"
if [ "${2:-}" = --dry-run ]; then
if [ "$(read_env_value "$PROJECT_ROOT/.env" INFRASTRUCTURE_AUTO_UPDATE_ENABLED)" = false ]; then echo "更新组件定时任务(dry-run):已关闭"; exit 0; fi
printf 'Watchtower 和 updater 定时任务(dry-run):%s\n' "$entry"
exit 0
fi
cron() {
if [ "$(id -u)" -eq 0 ]; then crontab "$@"; else sudo crontab "$@"; fi
}
if ! command -v crontab >/dev/null; then
[ "$(read_env_value "$PROJECT_ROOT/.env" INFRASTRUCTURE_AUTO_UPDATE_ENABLED)" != false ] || exit 0
if command -v apt-get >/dev/null; then
sudo apt-get update -qq
sudo apt-get install -y cron
else
echo '缺少 crontab,无法安装更新组件定时任务' >&2
exit 1
fi
fi
if [ "$(uname -s)" = Linux ]; then
if [ -d /run/systemd/system ]; then
sudo systemctl enable --now cron
elif command -v service >/dev/null; then
sudo service cron start
fi
fi
error_file="$(mktemp)"
trap 'rm -f "$error_file"' EXIT
if ! current="$(LC_ALL=C cron -l 2>"$error_file")"; then
if ! grep -qi 'no crontab for' "$error_file"; then
echo '无法读取现有定时任务,未修改任务配置' >&2
exit 1
fi
current=""
fi
# Keep all unrelated tasks and replace this deployment's single entry.
next="$(printf '%s\n' "$current" | awk -v marker="$marker" 'substr($0, length($0)-length(marker)+1) != marker')"
if [ "$(read_env_value "$PROJECT_ROOT/.env" INFRASTRUCTURE_AUTO_UPDATE_ENABLED)" != false ]; then
next="${next:+$next$'\n'}$entry"
fi
printf '%s\n' "$next" | cron -
if [ "$(read_env_value "$PROJECT_ROOT/.env" INFRASTRUCTURE_AUTO_UPDATE_ENABLED)" = false ]; then
echo '已移除本部署的更新组件定时任务'
else
echo '已配置 Watchtower 和 updater 定时任务:每六小时检查一次'
fi