-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathrun_compose.sh
More file actions
executable file
·2187 lines (1854 loc) · 62.7 KB
/
Copy pathrun_compose.sh
File metadata and controls
executable file
·2187 lines (1854 loc) · 62.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
set -euo pipefail
# 统一 Docker 启动脚本。
# 用法:
# ./run_compose.sh # 使用本地源码构建镜像
# ./run_compose.sh local # 使用本地源码构建镜像
# ./run_compose.sh local docker-compose.local.yml
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
REPO_ROOT="$SCRIPT_DIR"
cd "$REPO_ROOT"
LOG_DIR="data/docker-logs"
ENV_FILE=${DOCKER_ENV_FILE:-.env}
DEPLOY_MODE=""
RUN_ACTION=""
COMPOSE_FILE=""
COMPOSE_CMD=()
_RANKED_DIR=""
ENSURE_DB=0
PREPARE_DB_BEFORE_UP=0
POSTGRES_CONTAINER_NAME=${POSTGRES_CONTAINER_NAME:-wharttest-postgres}
mkdir -p "$LOG_DIR"
usage() {
cat <<'USAGE'
用法:
./run_compose.sh [local] [up|db-check|db-upgrade|db-init] [compose-file] [--ensure-db]
模式:
local 本地源码构建镜像(默认 compose: docker-compose.local.yml)
动作(通过参数或 DOCKER_RUN_ACTION 指定;未指定时默认 up):
up 正常启动服务
db-check 检测数据库连通性与目标数据库是否存在
db-upgrade 检测并执行 Django migrations 升级数据库结构
db-init 检测/创建数据库 + migrations + 初始化数据(管理员、技能、默认提示词)
选项:
--ensure-db 当目标 PostgreSQL 数据库不存在时,自动创建后再升级
环境变量:
DOCKER_DEPLOY_MODE=local
DOCKER_RUN_ACTION=up|db-check|db-upgrade|db-init
DOCKER_ENSURE_DB=0|1
DOCKER_PREPARE_DB_BEFORE_UP=0|1
DOCKER_SOURCE_PROFILE=auto|native|mirror
DOCKER_BUILD_NO_CACHE=1 # local 模式下不使用缓存,适用于版本升级
DOCKER_BUILD_PULL=1
DOCKER_LOCAL_PULL_RUNTIME=0|1
DOCKER_PIP_INDEX_FALLBACKS="url1 url2"
DOCKER_*_CANDIDATES_EXTRA="name|base_url|probe_url;name2|base_url|probe_url"
USAGE
}
load_env_file() {
if [ -f "$ENV_FILE" ]; then
echo "检测到环境文件: $ENV_FILE"
set -a
# shellcheck disable=SC1090
source <(sed 's/\r$//' "$ENV_FILE")
set +a
fi
}
prompt_local_build_mode() {
local choice=""
if [ "$DEPLOY_MODE" != "local" ]; then
return 0
fi
if [ -n "${DOCKER_BUILD_NO_CACHE+x}" ]; then
if [ "${DOCKER_BUILD_NO_CACHE:-0}" = "1" ]; then
echo "本地构建方式: 从 0 构建 / 不使用缓存(由 DOCKER_BUILD_NO_CACHE=1 指定)"
else
echo "本地构建方式: 使用缓存构建(由 DOCKER_BUILD_NO_CACHE=${DOCKER_BUILD_NO_CACHE:-0} 指定)"
fi
return 0
fi
echo "请选择本地构建方式:"
echo " 1) 使用缓存构建(默认,速度更快)"
echo " 2) 从 0 构建 / 不使用缓存(适用于版本升级)"
echo " 3) 先检测/修复数据库,再使用缓存构建并启动服务"
echo " 4) 仅迁移数据库并初始化数据(不构建/不启动服务)"
while true; do
read -r -p "请输入 1、2、3 或 4(默认 1): " choice
choice=${choice:-1}
case "$choice" in
1|cache)
DOCKER_BUILD_NO_CACHE=0
export DOCKER_BUILD_NO_CACHE
echo "构建策略: 使用缓存构建"
return 0
;;
2|no-cache|rebuild|clean)
DOCKER_BUILD_NO_CACHE=1
export DOCKER_BUILD_NO_CACHE
if [ -z "${DOCKER_BUILD_PULL+x}" ]; then
DOCKER_BUILD_PULL=1
export DOCKER_BUILD_PULL
fi
echo "构建策略: 从 0 构建 / 不使用缓存"
echo "说明: 已自动启用 DOCKER_BUILD_PULL=${DOCKER_BUILD_PULL:-1},用于拉取最新基础镜像。"
return 0
;;
3|db|db-upgrade|prepare-db|ensure-db)
DOCKER_BUILD_NO_CACHE=0
DOCKER_PREPARE_DB_BEFORE_UP=1
PREPARE_DB_BEFORE_UP=1
ENSURE_DB=1
export DOCKER_BUILD_NO_CACHE DOCKER_PREPARE_DB_BEFORE_UP
echo "构建策略: 先检测/修复数据库,再使用缓存构建"
echo "说明: 若 PostgreSQL 数据库不存在会自动创建;随后会执行 Django migrations 修正表结构。"
return 0
;;
4|init|migrate|db-init)
RUN_ACTION="db-init"
ENSURE_DB=1
echo "执行模式: 仅迁移数据库并初始化数据"
echo "说明: 若数据库不存在会自动创建;执行 migrations 后运行初始化脚本。"
return 0
;;
*)
echo "输入无效,请输入 1、2、3 或 4。"
;;
esac
done
}
resolve_mode_and_compose() {
while [ "$#" -gt 0 ]; do
case "$1" in
-h|--help)
usage
exit 0
;;
up|db-check|db-upgrade|db-init)
RUN_ACTION="$1"
;;
--ensure-db)
ENSURE_DB=1
;;
remote)
echo "错误:remote 模式已移除,请使用 local(默认)。" >&2
exit 1
;;
init-models|init|models)
echo "错误:模型初始化模式已移除,请使用 local(默认)。" >&2
exit 1
;;
local)
DEPLOY_MODE="$1"
;;
*.yml|*.yaml)
COMPOSE_FILE="$1"
;;
*)
echo "错误:无法识别参数 '$1'" >&2
usage >&2
exit 1
;;
esac
shift
done
if [ -z "$RUN_ACTION" ] && [ -n "${DOCKER_RUN_ACTION:-}" ]; then
RUN_ACTION="$DOCKER_RUN_ACTION"
fi
if [ "$ENSURE_DB" -eq 0 ] && [ "${DOCKER_ENSURE_DB:-0}" = "1" ]; then
ENSURE_DB=1
fi
if [ "${DOCKER_PREPARE_DB_BEFORE_UP:-0}" = "1" ]; then
PREPARE_DB_BEFORE_UP=1
ENSURE_DB=1
fi
if [ -z "$DEPLOY_MODE" ] && [ -n "${DOCKER_DEPLOY_MODE:-}" ]; then
DEPLOY_MODE="$DOCKER_DEPLOY_MODE"
fi
if [ -z "$DEPLOY_MODE" ]; then
DEPLOY_MODE="local"
fi
case "$DEPLOY_MODE" in
local)
COMPOSE_FILE=${COMPOSE_FILE:-${DOCKER_LOCAL_COMPOSE_FILE:-docker-compose.local.yml}}
;;
init|models|init-models)
echo "错误:DOCKER_DEPLOY_MODE=$DEPLOY_MODE 已不再支持,请改用 local。" >&2
exit 1
;;
remote)
echo "错误:DOCKER_DEPLOY_MODE=remote 已不再支持,请改用 local。" >&2
exit 1
;;
*)
echo "错误:DOCKER_DEPLOY_MODE 仅支持 local,当前值为 '$DEPLOY_MODE'" >&2
exit 1
;;
esac
if [ ! -f "$COMPOSE_FILE" ]; then
echo "错误:compose 文件不存在: $COMPOSE_FILE" >&2
exit 1
fi
if [ -z "$RUN_ACTION" ]; then
RUN_ACTION="up"
fi
case "$RUN_ACTION" in
up|db-check|db-upgrade|db-init)
;;
*)
echo "错误:DOCKER_RUN_ACTION 仅支持 up、db-check、db-upgrade、db-init,当前值为 '$RUN_ACTION'" >&2
exit 1
;;
esac
if [ "$DEPLOY_MODE" = "local" ] && [ "$RUN_ACTION" != "db-check" ] && [ -t 0 ] && [ -t 1 ]; then
prompt_local_build_mode
fi
echo "部署模式: $DEPLOY_MODE"
echo "使用的 compose 文件: $COMPOSE_FILE"
echo "执行动作: $RUN_ACTION"
if [ "$PREPARE_DB_BEFORE_UP" -eq 1 ]; then
echo "启动前数据库预检: 启用"
fi
}
normalize_branch_data_variant() {
case "$1" in
ce|pe|dev|auto)
printf '%s' "$1"
;;
*)
printf '%s' ""
;;
esac
}
get_current_branch_name() {
git rev-parse --abbrev-ref HEAD 2>/dev/null || true
}
get_branch_data_variant() {
local branch_name="${1:-}"
if [[ "$branch_name" == *-ce ]]; then
printf '%s' "ce"
return 0
fi
if [[ "$branch_name" == *-pe ]]; then
printf '%s' "pe"
return 0
fi
printf '%s' "dev"
}
build_postgres_db_name() {
local variant="$1"
if [ "$variant" = "dev" ]; then
printf '%s' "wharttest_dev"
else
printf 'wharttest_%s' "$variant"
fi
}
is_default_postgres_db_name() {
case "$1" in
""|wharttest|wharttest_dev|wharttest_ce|wharttest_pe)
return 0
;;
*)
return 1
;;
esac
}
is_default_sqlite_path() {
case "$1" in
""|/app/data/db.sqlite3|db.sqlite3)
return 0
;;
*)
return 1
;;
esac
}
is_default_checkpoint_sqlite_path() {
case "$1" in
""|/app/data/chat_history.sqlite|chat_history.sqlite)
return 0
;;
*)
return 1
;;
esac
}
configure_branch_data_variant() {
if [ "$DEPLOY_MODE" != "local" ]; then
return 0
fi
if [ "${WHARTTEST_AUTO_BRANCH_DATA:-1}" != "1" ]; then
echo "本地开发数据自动切换已禁用(WHARTTEST_AUTO_BRANCH_DATA=${WHARTTEST_AUTO_BRANCH_DATA:-0})"
return 0
fi
local branch_name=""
local variant=""
local explicit_variant=""
local sqlite_path=""
local checkpoint_path=""
branch_name=$(get_current_branch_name)
explicit_variant=$(normalize_branch_data_variant "${POSTGRES_DB_VARIANT:-}")
if [ -n "$explicit_variant" ] && [ "$explicit_variant" != "auto" ]; then
variant="$explicit_variant"
else
variant=$(get_branch_data_variant "$branch_name")
fi
export POSTGRES_DB_VARIANT="$variant"
if is_default_postgres_db_name "${POSTGRES_DB:-}"; then
export POSTGRES_DB
POSTGRES_DB=$(build_postgres_db_name "$variant")
fi
if is_default_sqlite_path "${DATABASE_PATH:-}"; then
export DATABASE_PATH
if [ "$variant" = "dev" ]; then
DATABASE_PATH="/app/data/db.sqlite3"
else
DATABASE_PATH="/app/data/db_${variant}.sqlite3"
fi
fi
if is_default_checkpoint_sqlite_path "${LANGGRAPH_CHECKPOINT_SQLITE_PATH:-}"; then
export LANGGRAPH_CHECKPOINT_SQLITE_PATH
if [ "$variant" = "dev" ]; then
LANGGRAPH_CHECKPOINT_SQLITE_PATH="/app/data/chat_history.sqlite"
else
LANGGRAPH_CHECKPOINT_SQLITE_PATH="/app/data/chat_history_${variant}.sqlite"
fi
fi
echo "本地开发数据变体: $variant"
if [ -n "$branch_name" ]; then
echo "当前 Git 分支: $branch_name"
fi
echo "- POSTGRES_DB: ${POSTGRES_DB:-}"
echo "- DATABASE_PATH: ${DATABASE_PATH:-}"
echo "- LANGGRAPH_CHECKPOINT_SQLITE_PATH: ${LANGGRAPH_CHECKPOINT_SQLITE_PATH:-}"
}
probe_url() {
local url="$1"
local timeout="${2:-3}"
if command -v curl >/dev/null 2>&1; then
curl -fsS -o /dev/null -w '%{time_total}' \
--connect-timeout "$timeout" \
--max-time "$timeout" \
"$url" 2>/dev/null || return 1
return 0
fi
if command -v python3 >/dev/null 2>&1; then
python3 - "$url" "$timeout" <<'PY'
import sys
import time
import urllib.request
url = sys.argv[1]
timeout = float(sys.argv[2])
start = time.perf_counter()
with urllib.request.urlopen(url, timeout=timeout) as response:
response.read(1)
print(f"{time.perf_counter() - start:.3f}")
PY
return $?
fi
return 1
}
probe_url_relaxed() {
local url="$1"
local timeout="${2:-3}"
local result=""
local code=""
local time_total=""
if command -v curl >/dev/null 2>&1; then
result=$(curl -L -s -o /dev/null -w '%{http_code} %{time_total}' \
--connect-timeout "$timeout" \
--max-time "$timeout" \
"$url" 2>/dev/null || true)
code=${result%% *}
time_total=${result#* }
case "$code" in
200|204|301|302|307|308|401|403|404)
printf '%s' "$time_total"
return 0
;;
*)
return 1
;;
esac
fi
if command -v python3 >/dev/null 2>&1; then
python3 - "$url" "$timeout" <<'PY'
import sys
import time
import urllib.request
import urllib.error
url = sys.argv[1]
timeout = float(sys.argv[2])
start = time.perf_counter()
try:
with urllib.request.urlopen(url, timeout=timeout) as response:
response.read(1)
except urllib.error.HTTPError as exc:
if exc.code not in {401, 403, 404}:
raise
print(f"{time.perf_counter() - start:.3f}")
PY
return $?
fi
return 1
}
is_faster() {
local left="$1"
local right="$2"
if [ -z "$right" ]; then
return 0
fi
if command -v python3 >/dev/null 2>&1; then
python3 - "$left" "$right" <<'PY'
import sys
left = float(sys.argv[1])
right = float(sys.argv[2])
sys.exit(0 if left < right else 1)
PY
return $?
fi
awk -v left="$left" -v right="$right" 'BEGIN { exit !(left < right) }'
}
format_speed() {
local speed_kbps="$1"
awk -v s="$speed_kbps" 'BEGIN { if (s >= 1024) printf "%.2f MB/s", s/1024; else printf "%.1f KB/s", s }'
}
probe_url_speed() {
local url="$1"
local timeout="${2:-5}"
local max_bytes="${3:-1048576}"
if command -v curl >/dev/null 2>&1; then
curl -sS -o /dev/null \
-H "User-Agent: Mozilla/5.0" \
--connect-timeout "$timeout" \
--max-time "$timeout" \
-r "0-$((max_bytes - 1))" \
-w '%{speed_download}' \
"$url" 2>/dev/null | awk '{
speed_bytes = $1
if (speed_bytes > 0) {
printf "%.1f", speed_bytes / 1024
} else {
exit 1
}
}'
return "${PIPESTATUS[1]:-$?}"
fi
if command -v python3 >/dev/null 2>&1; then
python3 - "$url" "$timeout" "$max_bytes" <<'PY'
import sys, time, urllib.error, urllib.request
url, timeout, max_bytes = sys.argv[1], float(sys.argv[2]), int(sys.argv[3])
total = 0
start = time.perf_counter()
try:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=timeout) as r:
while total < max_bytes:
chunk = r.read(min(65536, max_bytes - total))
if not chunk:
break
total += len(chunk)
except urllib.error.HTTPError as e:
try:
total = max(1, len(e.read(4096)))
except Exception:
total = 1
except Exception:
pass
elapsed = time.perf_counter() - start
if elapsed > 0 and total > 0:
print(f"{total / 1024 / elapsed:.1f}")
else:
sys.exit(1)
PY
return $?
fi
return 1
}
normalize_source_profile() {
case "${DOCKER_SOURCE_PROFILE:-auto}" in
native|origin|official)
printf '%s' "native"
;;
mirror|cn|accelerated)
printf '%s' "mirror"
;;
auto|"")
printf '%s' "auto"
;;
*)
echo "警告:未知 DOCKER_SOURCE_PROFILE=${DOCKER_SOURCE_PROFILE:-},回退到 auto" >&2
printf '%s' "auto"
;;
esac
}
get_default_candidates() {
case "$1" in
APT)
cat <<'EOF2'
official|http://deb.debian.org|http://deb.debian.org/debian/dists/bookworm/main/binary-amd64/Packages.gz
tsinghua|https://mirrors.tuna.tsinghua.edu.cn|https://mirrors.tuna.tsinghua.edu.cn/debian/dists/bookworm/main/binary-amd64/Packages.gz
ustc|https://mirrors.ustc.edu.cn|https://mirrors.ustc.edu.cn/debian/dists/bookworm/main/binary-amd64/Packages.gz
aliyun|https://mirrors.aliyun.com|https://mirrors.aliyun.com/debian/dists/bookworm/main/binary-amd64/Packages.gz
tencent|https://mirrors.cloud.tencent.com|https://mirrors.cloud.tencent.com/debian/dists/bookworm/main/binary-amd64/Packages.gz
huaweicloud|https://mirrors.huaweicloud.com|https://mirrors.huaweicloud.com/debian/dists/bookworm/main/binary-amd64/Packages.gz
bfsu|https://mirrors.bfsu.edu.cn|https://mirrors.bfsu.edu.cn/debian/dists/bookworm/main/binary-amd64/Packages.gz
sjtug|https://mirror.sjtu.edu.cn|https://mirror.sjtu.edu.cn/debian/dists/bookworm/main/binary-amd64/Packages.gz
EOF2
;;
PyPI)
cat <<'EOF2'
official|https://pypi.org/simple|https://pypi.org/simple/pip/
tsinghua|https://pypi.tuna.tsinghua.edu.cn/simple|https://pypi.tuna.tsinghua.edu.cn/simple/pip/
ustc|https://mirrors.ustc.edu.cn/pypi/simple|https://mirrors.ustc.edu.cn/pypi/simple/pip/
aliyun|https://mirrors.aliyun.com/pypi/simple|https://mirrors.aliyun.com/pypi/simple/pip/
tencent|https://mirrors.cloud.tencent.com/pypi/simple|https://mirrors.cloud.tencent.com/pypi/simple/pip/
huaweicloud|https://mirrors.huaweicloud.com/repository/pypi/simple|https://mirrors.huaweicloud.com/repository/pypi/simple/pip/
bfsu|https://mirrors.bfsu.edu.cn/pypi/web/simple|https://mirrors.bfsu.edu.cn/pypi/web/simple/pip/
sjtug|https://mirror.sjtu.edu.cn/pypi/web/simple|https://mirror.sjtu.edu.cn/pypi/web/simple/pip/
EOF2
;;
npm)
cat <<'EOF2'
official|https://registry.npmjs.org|https://registry.npmjs.org/npm
npmmirror|https://registry.npmmirror.com|https://registry.npmmirror.com/npm
tencent|https://mirrors.cloud.tencent.com/npm|https://mirrors.cloud.tencent.com/npm/npm
huaweicloud|https://mirrors.huaweicloud.com/repository/npm|https://mirrors.huaweicloud.com/repository/npm/npm
sjtug|https://mirror.sjtu.edu.cn/npm-registry|https://mirror.sjtu.edu.cn/npm-registry/npm
EOF2
;;
HuggingFace)
cat <<'EOF2'
official|https://huggingface.co|https://huggingface.co/api/models/Qdrant/bm25
hf-mirror|https://hf-mirror.com|https://hf-mirror.com/api/models/Qdrant/bm25
EOF2
;;
Playwright)
cat <<'EOF2'
official|https://playwright.azureedge.net|https://playwright.azureedge.net/builds/
npmmirror|https://registry.npmmirror.com/-/binary/playwright|https://registry.npmmirror.com/-/binary/playwright/builds/
EOF2
;;
*)
return 1
;;
esac
}
get_extra_candidates() {
local env_name="$1"
local raw="${!env_name:-}"
if [ -z "$raw" ]; then
return 0
fi
printf '%s' "$raw" | tr ';' '\n' | sed '/^[[:space:]]*$/d'
}
select_source_from_candidates() {
local label="$1"
local extra_env_name="$2"
local profile="$3"
local candidates=""
local candidate_name=""
local candidate_value=""
local candidate_probe=""
local official_value=""
candidates="$({ get_default_candidates "$label"; get_extra_candidates "$extra_env_name"; } | sed '/^[[:space:]]*$/d')"
# native 模式直接使用官方源
while IFS='|' read -r candidate_name candidate_value candidate_probe; do
if [ "$candidate_name" = "official" ]; then
official_value="$candidate_value"
if [ "$profile" = "native" ]; then
echo "$label: 直接使用官方源 => $official_value" >&2
printf '%s' "$official_value"
return 0
fi
break
fi
done <<< "$candidates"
# 并行带宽测速(下载最多 5MB 实际数据)
local tmpdir=""
tmpdir=$(mktemp -d)
local pids=()
local max_parallel=5
local running=0
echo "$label: 并行带宽测速..." >&2
while IFS='|' read -r candidate_name candidate_value candidate_probe; do
[ -n "$candidate_name" ] || continue
[ -n "$candidate_value" ] || continue
[ -n "$candidate_probe" ] || continue
if [ "$profile" = "mirror" ] && [ "$candidate_name" = "official" ]; then
continue
fi
(
local speed=""
speed=$(probe_url_speed "$candidate_probe" 12 5242880 2>/dev/null) || true
if [ -n "$speed" ]; then
echo "$candidate_name|$candidate_value|$speed" > "$tmpdir/$candidate_name"
local display=""
display=$(format_speed "$speed")
echo "$label/$candidate_name: $display => $candidate_value" >&2
else
echo "$label/$candidate_name: 探测失败" >&2
fi
) &
pids+=($!)
running=$((running + 1))
if [ "$running" -ge "$max_parallel" ]; then
wait -n 2>/dev/null || true
running=$((running - 1))
fi
done <<< "$candidates"
wait "${pids[@]}" 2>/dev/null || true
# 按速度排序选最快
local results=""
local f=""
for f in "$tmpdir"/*; do
[ -f "$f" ] || continue
results+="$(cat "$f")"$'\n'
done
rm -rf "$tmpdir"
if [ -n "$results" ]; then
local best_line=""
best_line=$(printf '%s' "$results" | sort -t '|' -k 3,3rn | head -n 1)
local best_name="" best_value="" best_speed=""
IFS='|' read -r best_name best_value best_speed <<< "$best_line"
local display=""
display=$(format_speed "$best_speed")
echo "$label: 选择 $best_name ($display) => $best_value" >&2
printf '%s' "$best_value"
return 0
fi
if [ -n "$official_value" ]; then
echo "$label: 候选源测速失败,回退官方源 => $official_value" >&2
printf '%s' "$official_value"
return 0
fi
echo "$label: 未找到可用候选源" >&2
return 1
}
build_source_fallbacks() {
local label="$1"
local extra_env_name="$2"
local profile="$3"
local primary_value="$4"
local candidates=""
local candidate_name=""
local candidate_value=""
local candidate_probe=""
local fallbacks=""
if [ "$profile" = "native" ]; then
return 0
fi
candidates="$({ get_default_candidates "$label"; get_extra_candidates "$extra_env_name"; } | sed '/^[[:space:]]*$/d')"
while IFS='|' read -r candidate_name candidate_value candidate_probe; do
[ -n "$candidate_name" ] || continue
[ -n "$candidate_value" ] || continue
if [ "$profile" = "mirror" ] && [ "$candidate_name" = "official" ]; then
continue
fi
if [ "$candidate_value" = "$primary_value" ]; then
continue
fi
case " $fallbacks " in
*" $candidate_value "*)
continue
;;
esac
if [ -n "$fallbacks" ]; then
fallbacks="$fallbacks $candidate_value"
else
fallbacks="$candidate_value"
fi
done <<< "$candidates"
printf '%s' "$fallbacks"
}
configure_download_sources() {
local profile=""
profile=$(normalize_source_profile)
echo "下载源策略: $profile"
if [ -z "${DOCKER_APT_BASE_URL:-}" ]; then
export DOCKER_APT_BASE_URL
DOCKER_APT_BASE_URL=$(select_source_from_candidates "APT" "DOCKER_APT_CANDIDATES_EXTRA" "$profile")
else
echo "APT: 使用手动配置 $DOCKER_APT_BASE_URL"
fi
if [ -z "${DOCKER_PIP_INDEX_URL:-}" ]; then
export DOCKER_PIP_INDEX_URL
DOCKER_PIP_INDEX_URL=$(select_source_from_candidates "PyPI" "DOCKER_PIP_CANDIDATES_EXTRA" "$profile")
else
echo "PyPI: 使用手动配置 $DOCKER_PIP_INDEX_URL"
fi
if [ -z "${DOCKER_PIP_INDEX_FALLBACKS:-}" ]; then
export DOCKER_PIP_INDEX_FALLBACKS
DOCKER_PIP_INDEX_FALLBACKS=$(build_source_fallbacks "PyPI" "DOCKER_PIP_CANDIDATES_EXTRA" "$profile" "$DOCKER_PIP_INDEX_URL")
else
echo "PyPI fallback: 使用手动配置 $DOCKER_PIP_INDEX_FALLBACKS"
fi
if [ -z "${DOCKER_NPM_REGISTRY:-}" ]; then
export DOCKER_NPM_REGISTRY
DOCKER_NPM_REGISTRY=$(select_source_from_candidates "npm" "DOCKER_NPM_CANDIDATES_EXTRA" "$profile")
else
echo "npm: 使用手动配置 $DOCKER_NPM_REGISTRY"
fi
if [ -z "${DOCKER_HF_ENDPOINT:-}" ]; then
export DOCKER_HF_ENDPOINT
DOCKER_HF_ENDPOINT=$(select_source_from_candidates "HuggingFace" "DOCKER_HF_CANDIDATES_EXTRA" "$profile")
else
echo "HuggingFace: 使用手动配置 $DOCKER_HF_ENDPOINT"
fi
if [ -z "${DOCKER_PLAYWRIGHT_DOWNLOAD_HOST:-}" ]; then
export DOCKER_PLAYWRIGHT_DOWNLOAD_HOST
DOCKER_PLAYWRIGHT_DOWNLOAD_HOST=$(select_source_from_candidates "Playwright" "DOCKER_PLAYWRIGHT_CANDIDATES_EXTRA" "$profile")
else
echo "Playwright: 使用手动配置 $DOCKER_PLAYWRIGHT_DOWNLOAD_HOST"
fi
echo "已选择下载源:"
echo "- APT: $DOCKER_APT_BASE_URL"
echo "- PyPI: $DOCKER_PIP_INDEX_URL"
if [ -n "${DOCKER_PIP_INDEX_FALLBACKS:-}" ]; then
echo "- PyPI fallback: $DOCKER_PIP_INDEX_FALLBACKS"
fi
echo "- npm: $DOCKER_NPM_REGISTRY"
echo "- HuggingFace: $DOCKER_HF_ENDPOINT"
echo "- Playwright: $DOCKER_PLAYWRIGHT_DOWNLOAD_HOST"
}
normalize_image_ref() {
local image="$1"
local registry=""
local remainder=""
local repo=""
local tag=""
local first_segment=""
first_segment=${image%%/*}
if [ "$first_segment" != "$image" ] && { [[ "$first_segment" == *.* ]] || [[ "$first_segment" == *:* ]] || [ "$first_segment" = "localhost" ]; }; then
registry="$first_segment"
remainder=${image#*/}
else
registry="docker.io"
remainder="$image"
fi
if [[ "$remainder" == *:* ]]; then
repo=${remainder%:*}
tag=${remainder##*:}
else
repo="$remainder"
tag="latest"
fi
if [ "$registry" = "docker.io" ] && [[ "$repo" != */* ]]; then
repo="library/$repo"
fi
printf '%s/%s:%s' "$registry" "$repo" "$tag"
}
get_remote_registry_candidates() {
case "$1" in
dockerhub)
cat <<'EOF2'
official|official|https://registry-1.docker.io/v2/
panel|dockerhub_host:docker.1panel.live|https://docker.1panel.live/v2/
one_ms|dockerhub_host:docker.1ms.run|https://docker.1ms.run/v2/
xuanyuan|dockerhub_host:docker.xuanyuan.me|https://docker.xuanyuan.me/v2/
daocloud|dockerhub_host:docker.m.daocloud.io|https://docker.m.daocloud.io/v2/
rat|dockerhub_host:hub.rat.dev|https://hub.rat.dev/v2/
atomhub|dockerhub_host:atomhub.openatom.cn|https://atomhub.openatom.cn/v2/
timeweb|dockerhub_host:dockerhub.timeweb.cloud|https://dockerhub.timeweb.cloud/v2/
anyhub|dockerhub_host:docker.anyhub.us.kg|https://docker.anyhub.us.kg/v2/
uuuadc|dockerhub_host:hub.uuuadc.top|https://hub.uuuadc.top/v2/
ckyl|dockerhub_host:docker.ckyl.me|https://docker.ckyl.me/v2/
rainbond|dockerhub_host:docker.rainbond.cc|https://docker.rainbond.cc/v2/
hpcloud|dockerhub_host:docker.hpcloud.cloud|https://docker.hpcloud.cloud/v2/
dockerproxy|dockerhub_host:dockerproxy.cn|https://dockerproxy.cn/v2/
panel_proxy|dockerhub_host:docker.1panelproxy.com|https://docker.1panelproxy.com/v2/
kejilion|dockerhub_host:docker.kejilion.pro|https://docker.kejilion.pro/v2/
kubesre|dockerhub_host:dhub.kubesre.xyz|https://dhub.kubesre.xyz/v2/
nastool|dockerhub_host:docker.nastool.de|https://docker.nastool.de/v2/
noohub|dockerhub_host:noohub.ru|https://noohub.ru/v2/
huecker|dockerhub_host:huecker.io|https://huecker.io/v2/
EOF2
;;
ghcr)
cat <<'EOF2'
official|official|https://ghcr.io/v2/
one_ms|ghcr_host:ghcr.1ms.run|https://ghcr.1ms.run/v2/
nju|ghcr_host:ghcr.nju.edu.cn|https://ghcr.nju.edu.cn/v2/
daocloud|ghcr_host:ghcr.m.daocloud.io|https://ghcr.m.daocloud.io/v2/
lank8s|ghcr_host:ghcr.lank8s.cn|https://ghcr.lank8s.cn/v2/
dockerproxy|ghcr_host:ghcr.dockerproxy.cn|https://ghcr.dockerproxy.cn/v2/
EOF2
;;
mcr)
cat <<'EOF2'
official|official|https://mcr.microsoft.com/v2/
azure_cn|mcr_host:mcr.azure.cn|https://mcr.azure.cn/v2/
daocloud|mcr_host:mcr.m.daocloud.io|https://mcr.m.daocloud.io/v2/
one_ms|mcr_host:mcr.1ms.run|https://mcr.1ms.run/v2/
dockerproxy|mcr_host:mcr.dockerproxy.cn|https://mcr.dockerproxy.cn/v2/
EOF2
;;
*)
return 1
;;
esac
}
get_remote_registry_validation_images() {
case "$1" in
dockerhub)
cat <<'EOF2'
postgres:16-alpine
redis:7-alpine
qdrant/qdrant:latest
EOF2
;;
ghcr)
cat <<'EOF2'
ghcr.io/mgdaaslab/wharttest-backend:latest
ghcr.io/mgdaaslab/wharttest-frontend:latest
ghcr.io/mgdaaslab/wharttest-mcp:latest
EOF2
;;
mcr)
cat <<'EOF2'
mcr.microsoft.com/playwright/mcp
EOF2
;;
*)
return 1
;;
esac
}
probe_remote_image_manifest() {
local image="$1"
local candidate_kind="$2"
local timeout="${3:-5}"
local selected_image=""
local normalized=""
local registry=""
local registry_host=""
local remainder=""
local repo=""
local tag=""
local url=""
local accept_header="application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json"
selected_image=$(rewrite_remote_image "$image" "$candidate_kind")
normalized=$(normalize_image_ref "$selected_image")
registry=${normalized%%/*}
remainder=${normalized#*/}
repo=${remainder%:*}
tag=${remainder##*:}
case "$registry" in
docker.io)
registry_host="registry-1.docker.io"
;;
*)
registry_host="$registry"
;;
esac
url="https://$registry_host/v2/$repo/manifests/$tag"
if command -v curl >/dev/null 2>&1; then
local result=""
local http_code=""
local time_total=""
local auth_header=""
local realm=""
local service=""
local scope=""
local token_response=""
local token=""
local -a token_cmd=()
result=$(curl -I -sS -D - -o /dev/null \
-w '\nCURL_HTTP_CODE=%{http_code}\nCURL_TIME_TOTAL=%{time_total}\n' \
--connect-timeout "$timeout" \
--max-time "$timeout" \
-H "Accept: $accept_header" \
"$url" 2>/dev/null || true)
http_code=$(printf '%s\n' "$result" | sed -n 's/^CURL_HTTP_CODE=//p' | tail -n 1)
time_total=$(printf '%s\n' "$result" | sed -n 's/^CURL_TIME_TOTAL=//p' | tail -n 1)
case "$http_code" in
200|204|301|302|307|308)
printf '%s' "$time_total"
return 0
;;
esac
if [ "$http_code" != "401" ]; then
return 1
fi
auth_header=$(printf '%s\n' "$result" | tr -d '\r' | awk 'BEGIN { IGNORECASE = 1 } /^www-authenticate:/ { sub(/^[^:]*:[[:space:]]*/, ""); value = $0 } END { print value }')
realm=$(printf '%s' "$auth_header" | sed -n 's/.*realm="\([^"]*\)".*/\1/p')
service=$(printf '%s' "$auth_header" | sed -n 's/.*service="\([^"]*\)".*/\1/p')
scope=$(printf '%s' "$auth_header" | sed -n 's/.*scope="\([^"]*\)".*/\1/p')
if [ -z "$realm" ]; then
return 1
fi