run_update_and_commit.sh 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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_opts=()
  83. if [[ -n "$http_token" ]]; then
  84. auth_b64="$(printf '%s:%s' "$http_user" "$http_token" | base64 | tr -d '\n')"
  85. git_auth_opts=(-c "http.extraHeader=Authorization: Basic ${auth_b64}")
  86. fi
  87. git_auth() {
  88. local dir="$1"
  89. shift
  90. if [[ -n "$credential_helper" ]]; then
  91. git -C "$dir" -c credential.helper="$credential_helper" "${git_auth_opts[@]}" "$@"
  92. else
  93. git -C "$dir" "${git_auth_opts[@]}" "$@"
  94. fi
  95. }
  96. output_settings_json="$(/usr/bin/python3 "${APP_DIR}/scripts/domain_updater.py" --config "$CONFIG_PATH" --print-output-settings)"
  97. mapfile -t output_settings < <(
  98. printf '%s' "$output_settings_json" | /usr/bin/python3 -c '
  99. import json, sys
  100. settings = json.load(sys.stdin)
  101. for key in ["runtime_dir", "selected_text_path", "selected_json_path", "state_path", "vars_path"]:
  102. print(settings[key])
  103. '
  104. )
  105. RUNTIME_DIR="${output_settings[0]}"
  106. SELECTED_TEXT_FILE="${output_settings[1]}"
  107. SELECTED_JSON_FILE="${output_settings[2]}"
  108. STATE_FILE="${output_settings[3]}"
  109. VARS_FILE="${output_settings[4]}"
  110. repo_relpath() {
  111. /usr/bin/python3 - "$APP_DIR" "$1" <<'PY'
  112. import os
  113. import sys
  114. base = os.path.realpath(sys.argv[1])
  115. path = os.path.realpath(sys.argv[2])
  116. try:
  117. common = os.path.commonpath([base, path])
  118. except ValueError:
  119. common = ""
  120. if common != base:
  121. print("")
  122. else:
  123. print(os.path.relpath(path, base))
  124. PY
  125. }
  126. updater_output="$(/usr/bin/python3 "${APP_DIR}/scripts/domain_updater.py" --config "$CONFIG_PATH")"
  127. printf '%s\n' "$updater_output"
  128. updater_status="$(printf '%s' "$updater_output" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("status",""))' 2>/dev/null || echo "")"
  129. if [[ "$updater_status" == "error_use_last_good" ]]; then
  130. log "[vmess-domain-rotator] warning: updater using fallback value (source error)"
  131. fi
  132. if [[ ! -f "$SELECTED_TEXT_FILE" ]]; then
  133. log "[vmess-domain-rotator] selected value file missing after updater run (${SELECTED_TEXT_FILE}), skip git commit"
  134. exit 0
  135. fi
  136. after="$(tr -d '\r\n' < "$SELECTED_TEXT_FILE")"
  137. if [[ -z "$after" ]]; then
  138. log "[vmess-domain-rotator] empty selected value, skip git commit"
  139. exit 0
  140. fi
  141. selected_rel="$(repo_relpath "$SELECTED_TEXT_FILE")"
  142. if [[ -z "$selected_rel" ]]; then
  143. log "[vmess-domain-rotator] selected value file is outside repo (${SELECTED_TEXT_FILE}), skip git commit"
  144. exit 0
  145. fi
  146. if ! command -v git >/dev/null 2>&1; then
  147. log "[vmess-domain-rotator] git not found, skip git commit"
  148. exit 0
  149. fi
  150. if ! git -C "$APP_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  151. log "[vmess-domain-rotator] not a git repo at ${APP_DIR}, skip git commit"
  152. log "[vmess-domain-rotator] hint: reinstall service from a git clone path"
  153. exit 0
  154. fi
  155. if ! git -C "$APP_DIR" rev-parse --verify HEAD >/dev/null 2>&1; then
  156. log "[vmess-domain-rotator] repo has no commits yet, skip git commit"
  157. exit 0
  158. fi
  159. if ! git -C "$APP_DIR" remote get-url "$push_remote" >/dev/null 2>&1; then
  160. push_remote=""
  161. while IFS= read -r r; do
  162. push_remote="$r"
  163. break
  164. done < <(git -C "$APP_DIR" remote)
  165. fi
  166. work_dir=""
  167. cleanup_worktree="0"
  168. current_branch="$(git -C "$APP_DIR" symbolic-ref --quiet --short HEAD 2>/dev/null || true)"
  169. if [[ "$current_branch" == "$runtime_branch" ]]; then
  170. work_dir="$APP_DIR"
  171. else
  172. work_dir="$(mktemp -d "${TMPDIR:-/tmp}/vmess-runtime-state.XXXXXX")"
  173. cleanup_worktree="1"
  174. if git -C "$APP_DIR" show-ref --verify --quiet "refs/heads/${runtime_branch}"; then
  175. git -C "$APP_DIR" worktree add --force "$work_dir" "$runtime_branch"
  176. else
  177. if [[ -n "$push_remote" ]] && git_auth "$APP_DIR" ls-remote --exit-code --heads "$push_remote" "$runtime_branch" >/dev/null 2>&1; then
  178. git_auth "$APP_DIR" fetch "$push_remote" "$runtime_branch:$runtime_branch"
  179. git -C "$APP_DIR" worktree add --force "$work_dir" "$runtime_branch"
  180. else
  181. git -C "$APP_DIR" worktree add --force --detach "$work_dir"
  182. git -C "$work_dir" checkout --orphan "$runtime_branch"
  183. git -C "$work_dir" rm -rf . >/dev/null 2>&1 || true
  184. log "[vmess-domain-rotator] initialized branch ${runtime_branch}"
  185. fi
  186. fi
  187. fi
  188. if [[ "$cleanup_worktree" == "1" ]]; then
  189. cleanup() {
  190. trap - EXIT INT TERM
  191. git -C "$APP_DIR" worktree remove --force "$work_dir" >/dev/null 2>&1 || {
  192. rm -rf "$work_dir"
  193. git -C "$APP_DIR" worktree prune >/dev/null 2>&1 || true
  194. }
  195. }
  196. trap cleanup EXIT
  197. trap 'cleanup; exit 1' INT TERM
  198. fi
  199. work_branch="$(git -C "$work_dir" symbolic-ref --quiet --short HEAD 2>/dev/null || true)"
  200. if [[ "$work_branch" != "$runtime_branch" ]]; then
  201. log "[vmess-domain-rotator] safety check failed: worktree branch is '${work_branch:-detached}', expected '${runtime_branch}'"
  202. exit 1
  203. fi
  204. before=""
  205. if before_raw="$(git -C "$work_dir" show "HEAD:${selected_rel}" 2>/dev/null)"; then
  206. before="$(printf '%s' "$before_raw" | tr -d '\r\n')"
  207. fi
  208. if [[ "$force_commit" != "1" ]] && [[ -n "$before" ]] && [[ "$after" == "$before" ]]; then
  209. log "[vmess-domain-rotator] selected value unchanged (${after}), skip git commit and push"
  210. exit 0
  211. fi
  212. tracked_src_files=("$SELECTED_TEXT_FILE" "$SELECTED_JSON_FILE" "$STATE_FILE" "$VARS_FILE")
  213. tracked_rel_files=()
  214. for src in "${tracked_src_files[@]}"; do
  215. rel="$(repo_relpath "$src")"
  216. if [[ -z "$rel" ]]; then
  217. log "[vmess-domain-rotator] skip non-repo output file: ${src}"
  218. continue
  219. fi
  220. tracked_rel_files+=("$rel")
  221. dst="$work_dir/$rel"
  222. mkdir -p "$(dirname "$dst")"
  223. if [[ -f "$src" ]]; then
  224. cp "$src" "$dst"
  225. else
  226. rm -f "$dst"
  227. fi
  228. done
  229. if [[ "${#tracked_rel_files[@]}" -eq 0 ]]; then
  230. log "[vmess-domain-rotator] no repo-local output files from config (${CONFIG_PATH}), skip git commit"
  231. exit 0
  232. fi
  233. git -C "$work_dir" add -A -- "${tracked_rel_files[@]}" || true
  234. staged_changed="1"
  235. if git -C "$work_dir" diff --cached --quiet; then
  236. staged_changed="0"
  237. fi
  238. if [[ "$staged_changed" == "0" ]] && [[ "$force_commit" != "1" ]]; then
  239. log "[vmess-domain-rotator] no staged changes for ${runtime_branch}, skip git commit"
  240. exit 0
  241. fi
  242. commit_extra_args=()
  243. if [[ "$staged_changed" == "0" ]] && [[ "$force_commit" == "1" ]]; then
  244. commit_extra_args+=(--allow-empty)
  245. log "[vmess-domain-rotator] force commit enabled with unchanged content, creating empty commit"
  246. fi
  247. commit_message="chore: rotate preferred value to ${after} (${ts})"
  248. if [[ "$updater_status" == "error_use_last_good" ]]; then
  249. commit_message="chore(fallback): rotate preferred value to ${after} (${ts})"
  250. fi
  251. if [[ "$force_commit" == "1" ]]; then
  252. commit_message="manual: value ${after}, updated at ${ts}"
  253. fi
  254. git -C "$work_dir" \
  255. -c user.name="$commit_name" \
  256. -c user.email="$commit_email" \
  257. commit "${commit_extra_args[@]}" -m "$commit_message"
  258. if [[ "$push_enabled" != "1" ]]; then
  259. log "[vmess-domain-rotator] git push disabled by GIT_PUSH_ENABLED=${push_enabled}"
  260. elif [[ -z "$push_remote" ]]; then
  261. if [[ "$push_required" == "1" ]]; then
  262. log "[vmess-domain-rotator] no remote found but push is required"
  263. exit 1
  264. fi
  265. log "[vmess-domain-rotator] no remote found, skip git push"
  266. else
  267. push_ok="0"
  268. if git -C "$work_dir" rev-parse --abbrev-ref --symbolic-full-name "@{u}" >/dev/null 2>&1; then
  269. if git_auth "$work_dir" push "$push_remote" "$runtime_branch:$runtime_branch"; then
  270. push_ok="1"
  271. log "[vmess-domain-rotator] pushed to ${push_remote}/${runtime_branch}"
  272. fi
  273. else
  274. if git_auth "$work_dir" push -u "$push_remote" "$runtime_branch:$runtime_branch"; then
  275. push_ok="1"
  276. log "[vmess-domain-rotator] pushed to ${push_remote}/${runtime_branch} (set upstream)"
  277. fi
  278. fi
  279. if [[ "$push_ok" != "1" ]]; then
  280. log "[vmess-domain-rotator] git push failed"
  281. log "[vmess-domain-rotator] hint: configure non-interactive auth (credential.helper store, SSH deploy key, or GIT_HTTP_USERNAME/GIT_HTTP_TOKEN)"
  282. if [[ "$push_required" == "1" ]]; then
  283. exit 1
  284. fi
  285. fi
  286. fi
  287. log "[vmess-domain-rotator] committed output changes on ${runtime_branch}: selected value ${after} from ${RUNTIME_DIR}"