run_update_and_commit.sh 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. # --- journald tee: log to journal even when run manually ---
  4. if [[ -z "${INVOCATION_ID:-}" ]] && command -v systemd-cat >/dev/null 2>&1; then
  5. exec > >(tee >(systemd-cat -t vmess-domain-rotator -p info)) \
  6. 2> >(tee >(systemd-cat -t vmess-domain-rotator -p err) >&2)
  7. fi
  8. timestamp() {
  9. date '+%Y-%m-%d %H:%M:%S'
  10. }
  11. log() {
  12. printf '[%s] %s\n' "$(timestamp)" "$*"
  13. }
  14. log_err() {
  15. printf '[%s] %s\n' "$(timestamp)" "$*" >&2
  16. }
  17. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  18. DEFAULT_APP_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
  19. APP_DIR="$(git -C "$DEFAULT_APP_DIR" rev-parse --show-toplevel 2>/dev/null || printf '%s' "$DEFAULT_APP_DIR")"
  20. force_commit="${GIT_FORCE_COMMIT:-0}"
  21. if [[ "${1:-}" == "--force-commit" ]]; then
  22. force_commit="1"
  23. shift
  24. fi
  25. if [[ ! "$force_commit" =~ ^[01]$ ]]; then
  26. log "[vmess-domain-rotator] invalid GIT_FORCE_COMMIT=${force_commit}, expected 0 or 1"
  27. exit 1
  28. fi
  29. CONFIG_PATH="${1:-${APP_DIR}/config.server.json}"
  30. # --- adaptive interval check ---
  31. if [[ "$force_commit" != "1" ]]; then
  32. peak_start=$((10#${PEAK_START_HOUR:-19}))
  33. peak_end=$((10#${PEAK_END_HOUR:-24}))
  34. peak_tz="${PEAK_TZ:-Asia/Shanghai}"
  35. peak_int=$((10#${PEAK_INTERVAL_MIN:-10}))
  36. offpeak_int=$((10#${OFFPEAK_INTERVAL_MIN:-30}))
  37. # Get current hour and minute in peak timezone
  38. curr_hour=$((10#$(TZ="$peak_tz" date '+%H')))
  39. curr_min=$((10#$(TZ="$peak_tz" date '+%M')))
  40. in_peak=0
  41. if [[ "$peak_start" -eq "$peak_end" ]]; then
  42. # start == end: no peak window defined, always off-peak
  43. in_peak=0
  44. elif [[ "$peak_start" -lt "$peak_end" ]]; then
  45. # Normal range (e.g. 8 to 22)
  46. if [[ "$curr_hour" -ge "$peak_start" ]] && [[ "$curr_hour" -lt "$peak_end" ]]; then
  47. in_peak=1
  48. fi
  49. else
  50. # Crossing midnight (e.g. peak-start 22, peak-end 2)
  51. if [[ "$curr_hour" -ge "$peak_start" ]] || [[ "$curr_hour" -lt "$peak_end" ]]; then
  52. in_peak=1
  53. fi
  54. fi
  55. if [[ "$in_peak" -eq 0 ]]; then
  56. # Outside peak hours: only execute near offpeak_int minute boundaries (e.g. 0, 30)
  57. # Allow drift tolerance of half the timer tick (peak_int / 2)
  58. remainder=$((curr_min % offpeak_int))
  59. tolerance=$(( (peak_int + 1) / 2 ))
  60. if [[ $remainder -gt $tolerance ]] && [[ $remainder -lt $((offpeak_int - tolerance)) ]]; then
  61. log "[vmess-domain-rotator] off-peak run skipped: hour=${curr_hour} minute=${curr_min} (remainder=${remainder}m, next at ${offpeak_int}m boundary)"
  62. exit 0
  63. fi
  64. fi
  65. # During peak hours: always execute (timer already fires at peak_int interval)
  66. fi
  67. export GIT_TERMINAL_PROMPT=0
  68. commit_name="${GIT_COMMIT_NAME:-vmess-domain-rotator}"
  69. commit_email="${GIT_COMMIT_EMAIL:-vmess-domain-rotator@localhost}"
  70. runtime_branch="${GIT_RUNTIME_BRANCH:-runtime-state}"
  71. push_remote="${GIT_PUSH_REMOTE:-origin}"
  72. push_enabled="${GIT_PUSH_ENABLED:-1}"
  73. push_required="${GIT_PUSH_REQUIRED:-${push_enabled}}"
  74. http_user="${GIT_HTTP_USERNAME:-git}"
  75. http_token="${GIT_HTTP_TOKEN:-}"
  76. http_token_file="${GIT_HTTP_TOKEN_FILE:-}"
  77. credential_helper="${GIT_CREDENTIAL_HELPER:-}"
  78. ts="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
  79. if [[ -z "$http_token" ]] && [[ -n "$http_token_file" ]] && [[ -r "$http_token_file" ]]; then
  80. http_token="$(tr -d '\r\n' < "$http_token_file")"
  81. fi
  82. git_auth() {
  83. local dir="$1"
  84. shift
  85. local -a env_vars=()
  86. if [[ -n "$http_token" ]]; then
  87. local auth_b64
  88. auth_b64="$(printf '%s:%s' "$http_user" "$http_token" | base64 | tr -d '\n')"
  89. env_vars+=(
  90. "GIT_CONFIG_COUNT=1"
  91. "GIT_CONFIG_KEY_0=http.extraHeader"
  92. "GIT_CONFIG_VALUE_0=Authorization: Basic ${auth_b64}"
  93. )
  94. fi
  95. if [[ -n "$credential_helper" ]]; then
  96. env "${env_vars[@]}" git -C "$dir" -c credential.helper="$credential_helper" "$@"
  97. else
  98. env "${env_vars[@]}" git -C "$dir" "$@"
  99. fi
  100. }
  101. output_settings_json="$(/usr/bin/python3 "${APP_DIR}/scripts/domain_updater.py" --config "$CONFIG_PATH" --print-output-settings)"
  102. mapfile -t output_settings < <(
  103. printf '%s' "$output_settings_json" | /usr/bin/python3 -c '
  104. import json, sys
  105. settings = json.load(sys.stdin)
  106. for key in ["runtime_dir", "selected_text_path", "selected_json_path", "state_path", "vars_path"]:
  107. print(settings[key])
  108. '
  109. )
  110. RUNTIME_DIR="${output_settings[0]}"
  111. SELECTED_TEXT_FILE="${output_settings[1]}"
  112. SELECTED_JSON_FILE="${output_settings[2]}"
  113. STATE_FILE="${output_settings[3]}"
  114. VARS_FILE="${output_settings[4]}"
  115. repo_relpath() {
  116. /usr/bin/python3 - "$APP_DIR" "$1" <<'PY'
  117. import os
  118. import sys
  119. base = os.path.realpath(sys.argv[1])
  120. path = os.path.realpath(sys.argv[2])
  121. try:
  122. common = os.path.commonpath([base, path])
  123. except ValueError:
  124. common = ""
  125. if common != base:
  126. print("")
  127. else:
  128. print(os.path.relpath(path, base))
  129. PY
  130. }
  131. json_field() {
  132. local key="$1"
  133. /usr/bin/python3 -c '
  134. import json
  135. import sys
  136. key = sys.argv[1]
  137. try:
  138. obj = json.load(sys.stdin)
  139. except Exception:
  140. print("")
  141. else:
  142. value = obj.get(key, "")
  143. print("" if value is None else str(value))
  144. ' "$key"
  145. }
  146. tmp_result_json="$(mktemp "${TMPDIR:-/tmp}/vmess_result.XXXXXX")"
  147. trap 'rm -f "$tmp_result_json"' EXIT INT TERM
  148. /usr/bin/python3 "${APP_DIR}/scripts/domain_updater.py" --config "$CONFIG_PATH" --result-json-file "$tmp_result_json"
  149. if [[ -s "$tmp_result_json" ]]; then
  150. updater_status="$(json_field status < "$tmp_result_json" 2>/dev/null || echo "")"
  151. else
  152. updater_status=""
  153. fi
  154. rm -f "$tmp_result_json"
  155. if [[ "$updater_status" == "error_use_last_good" || "$updater_status" == "fallback_last_good" ]]; then
  156. log "[vmess-domain-rotator] warning: updater using fallback value (${updater_status})"
  157. fi
  158. if [[ ! -f "$SELECTED_TEXT_FILE" ]]; then
  159. log "[vmess-domain-rotator] selected value file missing after updater run (${SELECTED_TEXT_FILE}), skip git commit"
  160. exit 0
  161. fi
  162. after="$(tr -d '\r\n' < "$SELECTED_TEXT_FILE")"
  163. if [[ -z "$after" ]]; then
  164. log "[vmess-domain-rotator] empty selected value, skip git commit"
  165. exit 0
  166. fi
  167. selected_rel="$(repo_relpath "$SELECTED_TEXT_FILE")"
  168. selected_json_rel="$(repo_relpath "$SELECTED_JSON_FILE")"
  169. vars_rel="$(repo_relpath "$VARS_FILE")"
  170. if [[ -z "$selected_rel" ]]; then
  171. log "[vmess-domain-rotator] selected value file is outside repo (${SELECTED_TEXT_FILE}), skip git commit"
  172. exit 0
  173. fi
  174. if ! command -v git >/dev/null 2>&1; then
  175. log "[vmess-domain-rotator] git not found, skip git commit"
  176. exit 0
  177. fi
  178. if ! git -C "$APP_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  179. log "[vmess-domain-rotator] not a git repo at ${APP_DIR}, skip git commit"
  180. log "[vmess-domain-rotator] hint: reinstall service from a git clone path"
  181. exit 0
  182. fi
  183. if ! git -C "$APP_DIR" rev-parse --verify HEAD >/dev/null 2>&1; then
  184. log "[vmess-domain-rotator] repo has no commits yet, skip git commit"
  185. exit 0
  186. fi
  187. if ! git -C "$APP_DIR" remote get-url "$push_remote" >/dev/null 2>&1; then
  188. push_remote=""
  189. while IFS= read -r r; do
  190. push_remote="$r"
  191. break
  192. done < <(git -C "$APP_DIR" remote)
  193. fi
  194. work_dir=""
  195. cleanup_worktree="0"
  196. current_branch="$(git -C "$APP_DIR" symbolic-ref --quiet --short HEAD 2>/dev/null || true)"
  197. if [[ "$current_branch" == "$runtime_branch" ]]; then
  198. work_dir="$APP_DIR"
  199. else
  200. work_dir="$(mktemp -d "${TMPDIR:-/tmp}/vmess-runtime-state.XXXXXX")"
  201. cleanup_worktree="1"
  202. if git -C "$APP_DIR" show-ref --verify --quiet "refs/heads/${runtime_branch}"; then
  203. git -C "$APP_DIR" worktree add --force "$work_dir" "$runtime_branch"
  204. else
  205. remote_branch_exists="0"
  206. if [[ -n "$push_remote" ]]; then
  207. set +e
  208. git_auth "$APP_DIR" ls-remote --exit-code --heads "$push_remote" "$runtime_branch" >/dev/null 2>&1
  209. ls_remote_rc=$?
  210. set -e
  211. if [[ $ls_remote_rc -eq 0 ]]; then
  212. remote_branch_exists="1"
  213. elif [[ $ls_remote_rc -eq 2 ]]; then
  214. remote_branch_exists="0"
  215. else
  216. log_err "[vmess-domain-rotator] fatal: git ls-remote failed with exit code ${ls_remote_rc} on remote ${push_remote}"
  217. exit 1
  218. fi
  219. fi
  220. if [[ "$remote_branch_exists" == "1" ]]; then
  221. git_auth "$APP_DIR" fetch "$push_remote" "$runtime_branch:$runtime_branch"
  222. git -C "$APP_DIR" worktree add --force "$work_dir" "$runtime_branch"
  223. else
  224. git -C "$APP_DIR" worktree add --force --detach "$work_dir"
  225. git -C "$work_dir" checkout --orphan "$runtime_branch"
  226. git -C "$work_dir" rm -rf . >/dev/null 2>&1 || true
  227. log "[vmess-domain-rotator] initialized branch ${runtime_branch}"
  228. fi
  229. fi
  230. fi
  231. if [[ "$cleanup_worktree" == "1" ]]; then
  232. cleanup() {
  233. trap - EXIT INT TERM
  234. git -C "$APP_DIR" worktree remove --force "$work_dir" >/dev/null 2>&1 || {
  235. rm -rf "$work_dir"
  236. git -C "$APP_DIR" worktree prune >/dev/null 2>&1 || true
  237. }
  238. }
  239. trap cleanup EXIT
  240. trap 'cleanup; exit 1' INT TERM
  241. fi
  242. work_branch="$(git -C "$work_dir" symbolic-ref --quiet --short HEAD 2>/dev/null || true)"
  243. if [[ "$work_branch" != "$runtime_branch" ]]; then
  244. log "[vmess-domain-rotator] safety check failed: worktree branch is '${work_branch:-detached}', expected '${runtime_branch}'"
  245. exit 1
  246. fi
  247. before=""
  248. if before_raw="$(git -C "$work_dir" show "HEAD:${selected_rel}" 2>/dev/null)"; then
  249. before="$(printf '%s' "$before_raw" | tr -d '\r\n')"
  250. fi
  251. before_status=""
  252. if [[ -n "$selected_json_rel" ]] && before_json_raw="$(git -C "$work_dir" show "HEAD:${selected_json_rel}" 2>/dev/null)"; then
  253. before_status="$(printf '%s' "$before_json_raw" | json_field status 2>/dev/null || echo "")"
  254. fi
  255. before_vars_status=""
  256. if [[ -n "$vars_rel" ]] && before_vars_raw="$(git -C "$work_dir" show "HEAD:${vars_rel}" 2>/dev/null)"; then
  257. before_vars_status="$(printf '%s' "$before_vars_raw" | json_field STATUS 2>/dev/null || echo "")"
  258. fi
  259. status_compared="0"
  260. status_unchanged="0"
  261. if [[ -n "$updater_status" ]]; then
  262. status_unchanged="1"
  263. if [[ -n "$before_status" ]]; then
  264. status_compared="1"
  265. [[ "$updater_status" != "$before_status" ]] && status_unchanged="0"
  266. fi
  267. if [[ -n "$before_vars_status" ]]; then
  268. status_compared="1"
  269. [[ "$updater_status" != "$before_vars_status" ]] && status_unchanged="0"
  270. fi
  271. if [[ "$status_compared" != "1" ]]; then
  272. status_unchanged="0"
  273. fi
  274. fi
  275. is_fallback="0"
  276. if [[ "$updater_status" == "error_use_last_good" || "$updater_status" == "fallback_last_good" ]]; then
  277. is_fallback="1"
  278. fi
  279. if [[ "$force_commit" != "1" ]] && [[ -n "$before" ]] && [[ "$after" == "$before" ]]; then
  280. if [[ "$status_unchanged" == "1" || "$is_fallback" == "1" ]]; then
  281. log "[vmess-domain-rotator] selected value unchanged (${after}) [status=${updater_status:-unknown}], skip git commit and push"
  282. exit 0
  283. fi
  284. fi
  285. tracked_src_files=("$SELECTED_TEXT_FILE" "$SELECTED_JSON_FILE" "$STATE_FILE" "$VARS_FILE")
  286. tracked_rel_files=()
  287. for src in "${tracked_src_files[@]}"; do
  288. rel="$(repo_relpath "$src")"
  289. if [[ -z "$rel" ]]; then
  290. log "[vmess-domain-rotator] skip non-repo output file: ${src}"
  291. continue
  292. fi
  293. tracked_rel_files+=("$rel")
  294. dst="$work_dir/$rel"
  295. mkdir -p "$(dirname "$dst")"
  296. if [[ -f "$src" ]]; then
  297. cp "$src" "$dst"
  298. else
  299. rm -f "$dst"
  300. fi
  301. done
  302. if [[ "${#tracked_rel_files[@]}" -eq 0 ]]; then
  303. log "[vmess-domain-rotator] no repo-local output files from config (${CONFIG_PATH}), skip git commit"
  304. exit 0
  305. fi
  306. git -C "$work_dir" add -A -- "${tracked_rel_files[@]}" || true
  307. staged_changed="1"
  308. if git -C "$work_dir" diff --cached --quiet; then
  309. staged_changed="0"
  310. fi
  311. if [[ "$staged_changed" == "0" ]] && [[ "$force_commit" != "1" ]]; then
  312. log "[vmess-domain-rotator] no staged changes for ${runtime_branch}, skip git commit"
  313. exit 0
  314. fi
  315. commit_extra_args=()
  316. if [[ "$staged_changed" == "0" ]] && [[ "$force_commit" == "1" ]]; then
  317. commit_extra_args+=(--allow-empty)
  318. log "[vmess-domain-rotator] force commit enabled with unchanged content, creating empty commit"
  319. fi
  320. commit_message="chore: rotate preferred value to ${after} (${ts})"
  321. if [[ "$updater_status" == "error_use_last_good" || "$updater_status" == "fallback_last_good" ]]; then
  322. commit_message="chore(fallback): rotate preferred value to ${after} (${ts})"
  323. fi
  324. if [[ "$force_commit" == "1" ]]; then
  325. commit_message="manual: value ${after}, updated at ${ts}"
  326. fi
  327. git -C "$work_dir" \
  328. -c user.name="$commit_name" \
  329. -c user.email="$commit_email" \
  330. commit "${commit_extra_args[@]}" -m "$commit_message"
  331. if [[ "$push_enabled" != "1" ]]; then
  332. log "[vmess-domain-rotator] git push disabled by GIT_PUSH_ENABLED=${push_enabled}"
  333. elif [[ -z "$push_remote" ]]; then
  334. if [[ "$push_required" == "1" ]]; then
  335. log "[vmess-domain-rotator] no remote found but push is required"
  336. exit 1
  337. fi
  338. log "[vmess-domain-rotator] no remote found, skip git push"
  339. else
  340. push_ok="0"
  341. if git -C "$work_dir" rev-parse --abbrev-ref --symbolic-full-name "@{u}" >/dev/null 2>&1; then
  342. if git_auth "$work_dir" push "$push_remote" "$runtime_branch:$runtime_branch"; then
  343. push_ok="1"
  344. log "[vmess-domain-rotator] pushed to ${push_remote}/${runtime_branch}"
  345. fi
  346. else
  347. if git_auth "$work_dir" push -u "$push_remote" "$runtime_branch:$runtime_branch"; then
  348. push_ok="1"
  349. log "[vmess-domain-rotator] pushed to ${push_remote}/${runtime_branch} (set upstream)"
  350. fi
  351. fi
  352. if [[ "$push_ok" != "1" ]]; then
  353. log "[vmess-domain-rotator] git push failed"
  354. log "[vmess-domain-rotator] hint: configure non-interactive auth (credential.helper store, SSH deploy key, or GIT_HTTP_USERNAME/GIT_HTTP_TOKEN)"
  355. if [[ "$push_required" == "1" ]]; then
  356. exit 1
  357. fi
  358. fi
  359. fi
  360. log "[vmess-domain-rotator] committed output changes on ${runtime_branch}: selected value ${after} from ${RUNTIME_DIR}"