cdn-preload.sh 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. #!/bin/bash
  2. # cdn-preload.sh — 对 OSS 上传产物批量提交 CDN 预热/刷新,并轮询直到全部完成
  3. set -euo pipefail
  4. CDN_URLS_IN="${CDN_URLS_IN:-/tmp/cdn-urls-*.txt}"
  5. POLL_INTERVAL="${POLL_INTERVAL:-10}"
  6. POLL_TIMEOUT="${POLL_TIMEOUT:-1800}"
  7. PRELOAD_MIN_BYTES="${PRELOAD_MIN_BYTES:-0}"
  8. CDN_OPERATION="${CDN_OPERATION:-preload}"
  9. CDN_PRELOAD_MAX_ATTEMPTS="${CDN_PRELOAD_MAX_ATTEMPTS:-3}"
  10. CDN_PRELOAD_RETRY_SLEEP="${CDN_PRELOAD_RETRY_SLEEP:-5}"
  11. SIGNATURE_NONCE_USED_SENTINEL="__ZCODE_SIGNATURE_NONCE_USED__"
  12. CDN_DOMAIN_RAW="${CDN_DOMAIN:-cdn-zcode.z.ai}"
  13. CDN_PRELOAD_PROFILE_RAW="${CDN_PRELOAD_PROFILE:-${ALIYUN_CDN_PROFILE:-}}"
  14. CDN_DOMAIN_TARGETS=()
  15. CDN_PRELOAD_PROFILE_TARGETS=()
  16. if ! [[ "$CDN_PRELOAD_MAX_ATTEMPTS" =~ ^[1-9][0-9]*$ ]]; then
  17. echo "Error: CDN_PRELOAD_MAX_ATTEMPTS must be a positive integer, got '$CDN_PRELOAD_MAX_ATTEMPTS'"
  18. exit 1
  19. fi
  20. if ! [[ "$CDN_PRELOAD_RETRY_SLEEP" =~ ^[0-9]+$ ]]; then
  21. echo "Error: CDN_PRELOAD_RETRY_SLEEP must be a non-negative integer, got '$CDN_PRELOAD_RETRY_SLEEP'"
  22. exit 1
  23. fi
  24. case "$CDN_OPERATION" in
  25. preload|refresh)
  26. ;;
  27. *)
  28. echo "Error: CDN_OPERATION must be 'preload' or 'refresh', got '$CDN_OPERATION'"
  29. exit 1
  30. ;;
  31. esac
  32. trim_csv_value() {
  33. echo "$1" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
  34. }
  35. parse_csv_values() {
  36. local raw_value="$1"
  37. local value
  38. local -a raw_entries=()
  39. IFS=',' read -r -a raw_entries <<<"$raw_value"
  40. for raw_entry in "${raw_entries[@]+"${raw_entries[@]}"}"; do
  41. value="$(trim_csv_value "$raw_entry")"
  42. [[ -z "$value" ]] && continue
  43. printf '%s\n' "$value"
  44. done
  45. }
  46. while IFS= read -r value; do CDN_DOMAIN_TARGETS+=("$value"); done < <(parse_csv_values "$CDN_DOMAIN_RAW")
  47. while IFS= read -r value; do CDN_PRELOAD_PROFILE_TARGETS+=("$value"); done < <(parse_csv_values "$CDN_PRELOAD_PROFILE_RAW")
  48. if [[ ${#CDN_DOMAIN_TARGETS[@]} -eq 0 ]]; then
  49. echo "Error: CDN_DOMAIN must contain at least one domain" >&2
  50. exit 1
  51. fi
  52. if [[ ${#CDN_PRELOAD_PROFILE_TARGETS[@]} -ne 0 && ${#CDN_PRELOAD_PROFILE_TARGETS[@]} -ne 1 && ${#CDN_PRELOAD_PROFILE_TARGETS[@]} -ne ${#CDN_DOMAIN_TARGETS[@]} ]]; then
  53. echo "Error: CDN_PRELOAD_PROFILE must contain one value or match CDN_DOMAIN count (${#CDN_DOMAIN_TARGETS[@]}), got ${#CDN_PRELOAD_PROFILE_TARGETS[@]}" >&2
  54. exit 1
  55. fi
  56. target_preload_profile_at() {
  57. local index="$1"
  58. if [[ ${#CDN_PRELOAD_PROFILE_TARGETS[@]} -eq 0 ]]; then
  59. echo ""
  60. elif [[ ${#CDN_PRELOAD_PROFILE_TARGETS[@]} -eq 1 ]]; then
  61. echo "${CDN_PRELOAD_PROFILE_TARGETS[0]}"
  62. else
  63. echo "${CDN_PRELOAD_PROFILE_TARGETS[$index]}"
  64. fi
  65. }
  66. extract_url_host() {
  67. local url="$1"
  68. if [[ "$url" =~ ^https?://([^/:?#]+) ]]; then
  69. echo "${BASH_REMATCH[1]}"
  70. return 0
  71. fi
  72. return 1
  73. }
  74. resolve_cdn_target_index() {
  75. local url="$1"
  76. local host
  77. local target_index
  78. if ! host="$(extract_url_host "$url")"; then
  79. echo "Error: invalid CDN URL, cannot resolve host: $url" >&2
  80. exit 1
  81. fi
  82. for target_index in "${!CDN_DOMAIN_TARGETS[@]}"; do
  83. if [[ "$host" == "${CDN_DOMAIN_TARGETS[$target_index]}" ]]; then
  84. echo "$target_index"
  85. return 0
  86. fi
  87. done
  88. # Bugfix: upload 阶段已经按 CDN_DOMAIN 多账号上传,但 preload 之前统一使用默认 aliyun 账号。
  89. # 当配置了 per-domain profile 时,未知域名不能回退默认账号,否则会继续触发 “domain does not belong to you”。
  90. if [[ ${#CDN_PRELOAD_PROFILE_TARGETS[@]} -gt 0 ]]; then
  91. echo "Error: CDN URL host '$host' is not listed in CDN_DOMAIN; cannot choose preload profile for: $url" >&2
  92. exit 1
  93. fi
  94. echo "0"
  95. }
  96. build_aliyun_profile_args() {
  97. local target_index="$1"
  98. local profile
  99. profile="$(target_preload_profile_at "$target_index")"
  100. if [[ -n "$profile" ]]; then
  101. printf '%s\n' "--profile"
  102. printf '%s\n' "$profile"
  103. fi
  104. }
  105. run_aliyun_with_retry() {
  106. local label="$1"
  107. shift
  108. local attempt=1
  109. local stdout_file=""
  110. local stderr_file=""
  111. stdout_file="$(mktemp)"
  112. stderr_file="$(mktemp)"
  113. while true; do
  114. : >"$stdout_file"
  115. : >"$stderr_file"
  116. if "$@" >"$stdout_file" 2>"$stderr_file"; then
  117. cat "$stdout_file"
  118. rm -f "$stdout_file" "$stderr_file"
  119. return 0
  120. fi
  121. # Bugfix: CDN 预热/刷新提交遇到 EOF 后,阿里云可能已经消费了本次签名 nonce 并创建/接收了请求;
  122. # 再重放同一请求会返回 SignatureNonceUsed。此时无法拿到 taskId,但继续失败会误杀已触达服务端的任务。
  123. if [[ "$label" =~ ^aliyun\ cdn\ (PushObjectCache|RefreshObjectCaches)$ ]] && grep -q 'SignatureNonceUsed' "$stderr_file"; then
  124. echo "Warning: $label returned SignatureNonceUsed; treat CDN request as already submitted." >&2
  125. cat "$stderr_file" >&2
  126. echo "$SIGNATURE_NONCE_USED_SENTINEL"
  127. rm -f "$stdout_file" "$stderr_file"
  128. return 0
  129. fi
  130. # Bugfix: 阿里云 CDN API 偶发在传输层返回 EOF,之前受 set -e 影响会让整条发版预热链路直接失败。
  131. # 这里仅重试 CLI 调用本身;如果连续失败仍返回原始 stderr,避免吞掉鉴权、配额或参数错误。
  132. if (( attempt >= CDN_PRELOAD_MAX_ATTEMPTS )); then
  133. cat "$stderr_file" >&2
  134. rm -f "$stdout_file" "$stderr_file"
  135. return 1
  136. fi
  137. echo "Warning: retry $label after failed attempt ${attempt}/${CDN_PRELOAD_MAX_ATTEMPTS}" >&2
  138. cat "$stderr_file" >&2
  139. ((attempt+=1))
  140. sleep "$CDN_PRELOAD_RETRY_SLEEP"
  141. done
  142. }
  143. if [[ ! -f "$CDN_URLS_IN" ]]; then
  144. files=($CDN_URLS_IN)
  145. if [[ ${#files[@]} -gt 0 && -f "${files[0]}" ]]; then
  146. CDN_URL_FILES=("${files[@]}")
  147. echo "Found ${#CDN_URL_FILES[@]} CDN URL file(s):"
  148. printf ' - %s\n' "${CDN_URL_FILES[@]}"
  149. else
  150. echo "Error: No CDN URL files found (tried: $CDN_URLS_IN)"
  151. echo "Available files:"
  152. ls -la cdn-urls*.txt 2>/dev/null || echo " No cdn-urls*.txt files found"
  153. exit 1
  154. fi
  155. else
  156. CDN_URL_FILES=("$CDN_URLS_IN")
  157. fi
  158. echo "==> Collecting and deduplicating CDN URLs..."
  159. ALL_URL_RECORDS=()
  160. for url_file in "${CDN_URL_FILES[@]}"; do
  161. echo "Processing URLs from: $url_file"
  162. while IFS= read -r url_record || [[ -n "$url_record" ]]; do
  163. [[ -z "$url_record" ]] && continue
  164. ALL_URL_RECORDS+=("$url_record")
  165. done < "$url_file"
  166. done
  167. UNIQUE_URL_RECORDS=()
  168. while IFS= read -r url_record; do
  169. [[ -z "$url_record" ]] && continue
  170. UNIQUE_URL_RECORDS+=("$url_record")
  171. done < <(
  172. printf '%s\n' "${ALL_URL_RECORDS[@]}" \
  173. | awk -F '\t' '
  174. {
  175. url = $1
  176. size = $2
  177. if (url == "") {
  178. next
  179. }
  180. if (!(url in record_by_url) || (size_by_url[url] !~ /^[0-9]+$/ && size ~ /^[0-9]+$/)) {
  181. record_by_url[url] = $0
  182. size_by_url[url] = size
  183. }
  184. }
  185. END {
  186. for (url in record_by_url) {
  187. print record_by_url[url]
  188. }
  189. }
  190. ' \
  191. | sort
  192. )
  193. echo "Total URL records: ${#ALL_URL_RECORDS[@]}, Unique URLs: ${#UNIQUE_URL_RECORDS[@]}"
  194. if [[ ${#UNIQUE_URL_RECORDS[@]} -eq 0 ]]; then
  195. echo "Error: No URLs found to ${CDN_OPERATION}"
  196. exit 1
  197. fi
  198. if ! [[ "$PRELOAD_MIN_BYTES" =~ ^[0-9]+$ ]]; then
  199. echo "Error: PRELOAD_MIN_BYTES must be a non-negative integer, got '$PRELOAD_MIN_BYTES'"
  200. exit 1
  201. fi
  202. if [[ "$PRELOAD_MIN_BYTES" == "0" ]]; then
  203. echo "==> Collecting URLs with valid recorded size; no minimum file size threshold is applied..."
  204. else
  205. echo "==> Filtering URLs by size (recorded file size >= ${PRELOAD_MIN_BYTES} bytes)..."
  206. fi
  207. FILTERED_URLS=()
  208. SKIPPED_URLS=0
  209. parse_preload_record() {
  210. local url_record="$1"
  211. PRELOAD_URL=""
  212. PRELOAD_FILE_SIZE=""
  213. IFS=$'\t' read -r PRELOAD_URL PRELOAD_FILE_SIZE _ <<< "$url_record"
  214. }
  215. for url_record in "${UNIQUE_URL_RECORDS[@]}"; do
  216. parse_preload_record "$url_record"
  217. # Bugfix: 文件真实大小已经在 upload 阶段确定,preload 只消费这份显式映射。
  218. # 之前缺失 size 时回退到 CDN HEAD,会把“旧格式/异常记录”误当成可预热对象,导致筛选结果和上传清单不一致;
  219. # 这里统一要求显式 size,缺失就跳过,保证预热行为可预测且与 upload 输出严格一致。
  220. if ! [[ "$PRELOAD_FILE_SIZE" =~ ^[0-9]+$ ]]; then
  221. echo "- skip preload (missing/invalid recorded size): $PRELOAD_URL"
  222. ((SKIPPED_URLS+=1))
  223. continue
  224. fi
  225. # Bugfix: CI 预热默认必须覆盖 upload 清单里的所有有效文件。之前默认 2MB 阈值会跳过小文件,
  226. # 导致发布后小体积对象仍可能首次访问回源;阈值只保留给人工调试时显式配置。
  227. if (( PRELOAD_FILE_SIZE < PRELOAD_MIN_BYTES )); then
  228. echo "- skip preload (${PRELOAD_FILE_SIZE} bytes < ${PRELOAD_MIN_BYTES}): $PRELOAD_URL"
  229. ((SKIPPED_URLS+=1))
  230. continue
  231. fi
  232. FILTERED_URLS+=("$PRELOAD_URL")
  233. done
  234. echo "Filtered URLs: ${#FILTERED_URLS[@]}, Skipped URLs: ${SKIPPED_URLS}"
  235. if [[ ${#FILTERED_URLS[@]} -eq 0 ]]; then
  236. echo "No URLs matched ${CDN_OPERATION} criteria. Skip CDN ${CDN_OPERATION}."
  237. exit 0
  238. fi
  239. if [[ "$CDN_OPERATION" == "refresh" ]]; then
  240. echo "==> Submitting RefreshObjectCaches tasks..."
  241. else
  242. echo "==> Submitting PushObjectCache tasks..."
  243. fi
  244. TASK_RECORDS=()
  245. MAYBE_SUBMITTED_COUNT=0
  246. FAILED_SUBMIT_COUNT=0
  247. FAILED_MONITOR_COUNT=0
  248. FAILED_TASK_COUNT=0
  249. for url in "${FILTERED_URLS[@]}"; do
  250. target_index="$(resolve_cdn_target_index "$url")"
  251. target_profile="$(target_preload_profile_at "$target_index")"
  252. aliyun_profile_args=()
  253. while IFS= read -r aliyun_profile_arg; do
  254. aliyun_profile_args+=("$aliyun_profile_arg")
  255. done < <(build_aliyun_profile_args "$target_index")
  256. # Bugfix: aliyun profile 已承载账号与 endpoint 配置;脚本硬传 region 或 Area 会覆盖
  257. # profile/域名自身的调度语义,多账号 CDN 迁移时可能把预热/刷新请求打到错误控制面。
  258. if [[ "$CDN_OPERATION" == "refresh" ]]; then
  259. if [[ -n "$target_profile" ]]; then
  260. echo "+ aliyun cdn RefreshObjectCaches --profile \"$target_profile\" --ObjectPath \"$url\" --ObjectType File"
  261. else
  262. echo "+ aliyun cdn RefreshObjectCaches --ObjectPath \"$url\" --ObjectType File"
  263. fi
  264. if ! cdn_res="$(
  265. run_aliyun_with_retry "aliyun cdn RefreshObjectCaches" \
  266. aliyun cdn RefreshObjectCaches \
  267. ${aliyun_profile_args[@]+"${aliyun_profile_args[@]}"} \
  268. --ObjectPath "$url" \
  269. --ObjectType File
  270. )"; then
  271. # Bugfix: 旧 stable feed 的 latest*.yml 是同 URL 覆盖,必须刷新边缘缓存才能避免旧包继续命中旧 manifest。
  272. # CDN 控制面偶发失败仍按 best-effort 处理,避免单个刷新请求阻塞整条发版链路。
  273. echo "Warning: failed to submit CDN refresh after ${CDN_PRELOAD_MAX_ATTEMPTS} attempt(s), continue: $url" >&2
  274. ((FAILED_SUBMIT_COUNT+=1))
  275. continue
  276. fi
  277. else
  278. if [[ -n "$target_profile" ]]; then
  279. echo "+ aliyun cdn PushObjectCache --profile \"$target_profile\" --ObjectPath \"$url\" --L2Preload true"
  280. else
  281. echo "+ aliyun cdn PushObjectCache --ObjectPath \"$url\" --L2Preload true"
  282. fi
  283. if ! cdn_res="$(
  284. run_aliyun_with_retry "aliyun cdn PushObjectCache" \
  285. aliyun cdn PushObjectCache \
  286. ${aliyun_profile_args[@]+"${aliyun_profile_args[@]}"} \
  287. --ObjectPath "$url" \
  288. --L2Preload true
  289. )"; then
  290. # Bugfix: CDN 预热只是发布加速步骤,不应因为阿里云临时错误阻塞后续 publish/release。
  291. # 提交重试耗尽后记录并跳过当前 URL,保留输入/配置错误仍在前面硬失败。
  292. echo "Warning: failed to submit CDN preload after ${CDN_PRELOAD_MAX_ATTEMPTS} attempt(s), continue: $url" >&2
  293. ((FAILED_SUBMIT_COUNT+=1))
  294. continue
  295. fi
  296. fi
  297. if [[ "$cdn_res" == "$SIGNATURE_NONCE_USED_SENTINEL" ]]; then
  298. ((MAYBE_SUBMITTED_COUNT+=1))
  299. continue
  300. fi
  301. if [[ "$CDN_OPERATION" == "refresh" ]]; then
  302. tid="$(echo "$cdn_res" | jq -r '.RefreshTaskId // .RefreshTaskID // .TaskId // empty')"
  303. else
  304. tid="$(echo "$cdn_res" | jq -r '.PushTaskId // .PushTaskID // .TaskId // empty')"
  305. fi
  306. if [[ -n "$tid" ]]; then
  307. TASK_RECORDS+=("${target_index}"$'\t'"${tid}")
  308. fi
  309. done
  310. if [[ ${#TASK_RECORDS[@]} -eq 0 ]]; then
  311. if [[ "$MAYBE_SUBMITTED_COUNT" -gt 0 ]]; then
  312. echo "No task IDs returned; ${MAYBE_SUBMITTED_COUNT} CDN ${CDN_OPERATION} request(s) may already be submitted."
  313. exit 0
  314. fi
  315. if [[ "$FAILED_SUBMIT_COUNT" -gt 0 ]]; then
  316. echo "No tasks submitted. CDN ${CDN_OPERATION} is best-effort; continue release flow. failed_submits=${FAILED_SUBMIT_COUNT}"
  317. exit 0
  318. fi
  319. echo "No tasks submitted."
  320. exit 0
  321. fi
  322. echo "------------------------------------------"
  323. echo "==> Monitoring ${#TASK_RECORDS[@]} tasks..."
  324. start_time=$(date +%s)
  325. while [[ ${#TASK_RECORDS[@]} -gt 0 ]]; do
  326. if (( $(date +%s) - start_time > POLL_TIMEOUT )); then
  327. echo "Warning: CDN ${CDN_OPERATION} monitor timeout reached (${POLL_TIMEOUT}s); continue release flow." >&2
  328. break
  329. fi
  330. still_running=()
  331. for task_record in "${TASK_RECORDS[@]}"; do
  332. IFS=$'\t' read -r target_index tid <<< "$task_record"
  333. target_profile="$(target_preload_profile_at "$target_index")"
  334. aliyun_profile_args=()
  335. while IFS= read -r aliyun_profile_arg; do
  336. aliyun_profile_args+=("$aliyun_profile_arg")
  337. done < <(build_aliyun_profile_args "$target_index")
  338. # Bugfix: 查询任务状态必须沿用提交预热时的 profile region,避免查询阶段覆盖 endpoint。
  339. if [[ -n "$target_profile" ]]; then
  340. echo "+ aliyun cdn DescribeRefreshTaskById --profile \"$target_profile\" --TaskId \"$tid\""
  341. else
  342. echo "+ aliyun cdn DescribeRefreshTaskById --TaskId \"$tid\""
  343. fi
  344. if ! res="$(
  345. run_aliyun_with_retry "aliyun cdn DescribeRefreshTaskById" \
  346. aliyun cdn DescribeRefreshTaskById \
  347. ${aliyun_profile_args[@]+"${aliyun_profile_args[@]}"} \
  348. --TaskId "$tid"
  349. )"; then
  350. echo "Warning: failed to query CDN ${CDN_OPERATION} task after ${CDN_PRELOAD_MAX_ATTEMPTS} attempt(s), continue: $tid" >&2
  351. ((FAILED_MONITOR_COUNT+=1))
  352. continue
  353. fi
  354. status=$(echo "$res" | jq -r '.Tasks[0].Status // "Unknown"')
  355. process=$(echo "$res" | jq -r '.Tasks[0].Process // "0%"')
  356. case "$status" in
  357. "Complete")
  358. echo "Result: Task $tid finished (100%)."
  359. ;;
  360. "Failed")
  361. echo "Warning: Task $tid FAILED; CDN ${CDN_OPERATION} is best-effort, continue release flow." >&2
  362. ((FAILED_TASK_COUNT+=1))
  363. ;;
  364. *)
  365. echo "Result: Task $tid is $status ($process)."
  366. still_running+=("$task_record")
  367. ;;
  368. esac
  369. done
  370. TASK_RECORDS=("${still_running[@]+"${still_running[@]}"}")
  371. [[ ${#TASK_RECORDS[@]} -gt 0 ]] && sleep "$POLL_INTERVAL"
  372. done
  373. echo "------------------------------------------"
  374. if [[ "$FAILED_SUBMIT_COUNT" -gt 0 || "$FAILED_MONITOR_COUNT" -gt 0 || "$FAILED_TASK_COUNT" -gt 0 || ${#TASK_RECORDS[@]} -gt 0 ]]; then
  375. echo "CDN ${CDN_OPERATION} finished best-effort: failed_submits=${FAILED_SUBMIT_COUNT}, failed_queries=${FAILED_MONITOR_COUNT}, failed_tasks=${FAILED_TASK_COUNT}, unfinished_tasks=${#TASK_RECORDS[@]}. Continue release flow."
  376. else
  377. echo "SUCCESS: All CDN tasks are Complete."
  378. fi