-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabs.sh
More file actions
executable file
·1766 lines (1624 loc) · 67.1 KB
/
Copy pathabs.sh
File metadata and controls
executable file
·1766 lines (1624 loc) · 67.1 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 -Eeuo pipefail
export LC_ALL=C
VERSION="0.5.1"
TIME_START_EPOCH="$(date +%s)"
TIME_START_UTC="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
VCPU="$(nproc 2>/dev/null || echo 1)"
PROFILE="${PROFILE:-default}"
D="${D:-}"
T="${T:-$VCPU}"
SIZE="${SIZE:-auto}"
DIR="${DIR:-$PWD/.abs}"
CPU_PRIME="${CPU_PRIME:-20000}"
DIRECT="${DIRECT:-1}"
FIO_ENGINE="${FIO_ENGINE:-libaio}"
JOBS_ENV="${JOBS-}"
DEPTH="${DEPTH:-32}"
INSTALL="${INSTALL:-1}"
NET_INFO="${NET_INFO:-0}"
NETWORK="${NETWORK:-1}"
NETWORK_PROFILE="${NETWORK_PROFILE:-cloudflare}"
IPERF_SERVER="${IPERF_SERVER:-}"
IPERF_TIME="${IPERF_TIME:-5}"
IPERF_PARALLEL="${IPERF_PARALLEL:-2}"
VERBOSE="${VERBOSE:-0}"
JSON_PRINT="${JSON_PRINT:-0}"
JSON_FILE="${JSON_FILE:-}"
ABS_LANG="${ABS_LANG:-zh}"
NETWORK_TIMEOUT="${NETWORK_TIMEOUT:-45}"
NETWORK_DOWNLOAD_BYTES="${NETWORK_DOWNLOAD_BYTES:-10000000}"
NETWORK_UPLOAD_BYTES="${NETWORK_UPLOAD_BYTES:-5000000}"
LOGDIR_OVERRIDE="${LOGDIR-}"
LOGDIR=""
RESULTS=""
JSON_RESULT=""
COMPONENTS_FILE=""
RUN_DIR=""
FIO_FILE=""
FIO_BIN=""
JOBS=""
LAST_LOG=""
LAST_JSON=""
SCORE_TEXT="n/a"
LOCAL_SCORE_TEXT="n/a"
NETWORK_SCORE_TEXT="skipped"
VERDICT_TEXT="n/a"
INSTALL_ATTEMPTED="0"
MISSING_AFTER_INSTALL=""
INSTALL_ERROR_LOG=""
FINAL_STATUS=0
is_zh() { [ "$ABS_LANG" = "zh" ]; }
say() {
if is_zh; then printf '%s\n' "$1"; else printf '%s\n' "$2"; fi
}
die() {
say "$1" "$2" >&2
exit 2
}
usage() {
if is_zh; then
cat <<EOF
ABS v$VERSION — AskClaw VPS 跑分脚本
一键运行:
curl -fsSL https://raw.githubusercontent.com/getaskclaw/abs/main/abs.sh | bash
默认测试约 3 分钟,包含简短网络检查,不上传结果。
选项:
--quick 快速检查,约 60 秒
--full 更完整的测试,约 5–8 分钟
-d, --duration SEC 每项测试时长
-z, --size SIZE fio 测试文件大小,如 512M、2G、8G
-t, --threads N CPU/内存测试线程数
-n, --no-install 不安装缺失工具
--lang zh|en 输出语言,默认 zh
--net-info 查询 IPv4/IPv6 和外部 IP/ASN
--no-net-info 不查询外部 IP/ASN(默认)
--network Cloudflare 简短网络检查(默认)
--network-full Cloudflare + 3 个公共 iperf3 区域
--network-yabs Cloudflare + YABS 公共 iperf3 列表
--no-network 跳过网络测速
--iperf HOST[:PORT] 添加自定义 iperf3 服务器
--verbose 显示完整系统信息
--json 在结尾打印 JSON
--json-file PATH 另存 JSON 到指定路径
-h, --help 帮助
示例:
curl -fsSL https://raw.githubusercontent.com/getaskclaw/abs/main/abs.sh | bash
curl -fsSL https://raw.githubusercontent.com/getaskclaw/abs/main/abs.sh | bash -s -- --quick -n
curl -fsSL https://raw.githubusercontent.com/getaskclaw/abs/main/abs.sh | bash -s -- --lang en
也可使用环境变量:ABS_LANG=en PROFILE=full SIZE=8G INSTALL=0 bash abs.sh
EOF
else
cat <<EOF
ABS v$VERSION — AskClaw Benchmark Script
One-line run:
curl -fsSL https://raw.githubusercontent.com/getaskclaw/abs/main/abs.sh | bash
wget -qO- https://raw.githubusercontent.com/getaskclaw/abs/main/abs.sh | bash
Default profile targets under 3 minutes and includes a short network sanity check. No result upload.
Options:
--quick ~60s smoke profile
--full stronger 5–8 min profile
-d, --duration SEC seconds per timed test
-z, --size SIZE fio test file size, e.g. 512M, 2G, 8G; default auto
-t, --threads N CPU/memory threads; default detected vCPU ($T)
-n, --no-install do not install missing packages
--lang zh|en output language; default zh
--net-info check IPv4/IPv6 and external IP/ASN
--no-net-info skip external IP/ASN lookup (default)
--network run Cloudflare HTTP network sanity test (default)
--network-full Cloudflare + 3 public iperf3 regions
--network-yabs Cloudflare + full YABS public iperf3 list
--no-network skip network speed sanity test
--iperf HOST[:PORT] optional iperf3 send/recv; use [IPv6]:PORT for IPv6
--verbose print full system/tool header
--json print JSON result at the end
--json-file PATH write JSON result to PATH as well as logdir
-h, --help help
Examples:
curl -fsSL https://raw.githubusercontent.com/getaskclaw/abs/main/abs.sh | bash
curl -fsSL https://raw.githubusercontent.com/getaskclaw/abs/main/abs.sh | bash -s -- --quick -n
curl -fsSL https://raw.githubusercontent.com/getaskclaw/abs/main/abs.sh | bash -s -- --full -z 8G --json
Env overrides also work: ABS_LANG=en PROFILE=full SIZE=8G INSTALL=0 bash abs.sh
EOF
fi
}
D_SET=0
SIZE_SET=0
[ -n "$D" ] && D_SET=1
[ "$SIZE" != "auto" ] && SIZE_SET=1
while [ "$#" -gt 0 ]; do
case "$1" in
--quick) PROFILE="quick" ;;
--full) PROFILE="full" ;;
-d|--duration)
shift; [ "$#" -gt 0 ] || die "缺少参数值:-d/--duration" "Missing value for -d/--duration"
D="$1"; D_SET=1 ;;
-z|--size)
shift; [ "$#" -gt 0 ] || die "缺少参数值:-z/--size" "Missing value for -z/--size"
SIZE="$1"; SIZE_SET=1 ;;
-t|--threads)
shift; [ "$#" -gt 0 ] || die "缺少参数值:-t/--threads" "Missing value for -t/--threads"
T="$1" ;;
-n|--no-install) INSTALL=0 ;;
--lang)
shift; [ "$#" -gt 0 ] || die "缺少参数值:--lang" "Missing value for --lang"
ABS_LANG="$1" ;;
--net-info) NET_INFO=1 ;;
--no-net-info) NET_INFO=0 ;;
--network) NETWORK=1; NETWORK_PROFILE="cloudflare" ;;
--network-full) NETWORK=1; NETWORK_PROFILE="full" ;;
--network-yabs) NETWORK=1; NETWORK_PROFILE="yabs" ;;
--no-network) NETWORK=0; NETWORK_PROFILE="none" ;;
--iperf)
shift; [ "$#" -gt 0 ] || die "缺少参数值:--iperf" "Missing value for --iperf"
IPERF_SERVER="$1"; NETWORK=1 ;;
--verbose) VERBOSE=1 ;;
--json) JSON_PRINT=1 ;;
--json-file)
shift; [ "$#" -gt 0 ] || die "缺少参数值:--json-file" "Missing value for --json-file"
JSON_FILE="$1" ;;
-h|--help) usage; exit 0 ;;
*) say "未知选项:$1" "Unknown option: $1" >&2; usage >&2; exit 2 ;;
esac
shift
done
case "$PROFILE" in
quick)
PROFILE_TARGET="60s"
[ "$D_SET" -eq 1 ] || D=5
[ "$SIZE_SET" -eq 1 ] || SIZE=512M
;;
default)
PROFILE_TARGET="under 3 minutes"
[ "$D_SET" -eq 1 ] || D=8
;;
full)
PROFILE_TARGET="5–8 minutes"
[ "$D_SET" -eq 1 ] || D=30
;;
*) die "PROFILE 无效:$PROFILE" "Invalid PROFILE: $PROFILE" ;;
esac
is_pos_int() { [[ "${1:-}" =~ ^[1-9][0-9]*$ ]]; }
valid_port_range() {
local range="${1:-}" low high
[[ "$range" =~ ^([0-9]{1,5})(-([0-9]{1,5}))?$ ]] || return 1
low=$(( 10#${BASH_REMATCH[1]} ))
high="$low"
[ -n "${BASH_REMATCH[3]:-}" ] && high=$(( 10#${BASH_REMATCH[3]} ))
[ "$low" -ge 1 ] && [ "$high" -le 65535 ] && [ "$low" -le "$high" ]
}
IPERF_CUSTOM_HOST=""
IPERF_CUSTOM_PORT=""
parse_custom_iperf() {
local endpoint="$1" host port rest
if [[ "$endpoint" =~ ^\[([^][]+)\](:([0-9]{1,5}))?$ ]]; then
host="${BASH_REMATCH[1]}"
port="${BASH_REMATCH[3]:-5201}"
elif [[ "$endpoint" == *:* ]]; then
host="${endpoint%%:*}"
rest="${endpoint#*:}"
if [[ "$rest" == *:* ]]; then
# Raw IPv6 literal without brackets; use the default port.
host="$endpoint"
port=5201
else
port="$rest"
fi
else
host="$endpoint"
port=5201
fi
[ -n "$host" ] && [[ "$host" != -* ]] && [[ ! "$host" =~ [[:space:]] ]] || return 1
valid_port_range "$port" || return 1
IPERF_CUSTOM_HOST="$host"
IPERF_CUSTOM_PORT="$port"
}
if ! is_pos_int "$D"; then die "测试时长无效:$D" "Invalid duration: $D"; fi
if ! is_pos_int "$T"; then die "线程数无效:$T" "Invalid threads: $T"; fi
if ! is_pos_int "$DEPTH"; then die "DEPTH 无效:$DEPTH" "Invalid DEPTH: $DEPTH"; fi
if ! is_pos_int "$IPERF_TIME"; then die "IPERF_TIME 无效:$IPERF_TIME" "Invalid IPERF_TIME: $IPERF_TIME"; fi
if ! is_pos_int "$IPERF_PARALLEL"; then die "IPERF_PARALLEL 无效:$IPERF_PARALLEL" "Invalid IPERF_PARALLEL: $IPERF_PARALLEL"; fi
if [ "$DIRECT" != "0" ] && [ "$DIRECT" != "1" ]; then die "DIRECT 无效:$DIRECT" "Invalid DIRECT: $DIRECT"; fi
case "$ABS_LANG" in zh|en) ;; *) echo "Invalid --lang: $ABS_LANG (expected zh or en)" >&2; exit 2 ;; esac
if ! is_pos_int "$NETWORK_TIMEOUT"; then die "NETWORK_TIMEOUT 无效:$NETWORK_TIMEOUT" "Invalid NETWORK_TIMEOUT: $NETWORK_TIMEOUT"; fi
if ! is_pos_int "$NETWORK_DOWNLOAD_BYTES"; then die "NETWORK_DOWNLOAD_BYTES 无效:$NETWORK_DOWNLOAD_BYTES" "Invalid NETWORK_DOWNLOAD_BYTES: $NETWORK_DOWNLOAD_BYTES"; fi
if ! is_pos_int "$NETWORK_UPLOAD_BYTES"; then die "NETWORK_UPLOAD_BYTES 无效:$NETWORK_UPLOAD_BYTES" "Invalid NETWORK_UPLOAD_BYTES: $NETWORK_UPLOAD_BYTES"; fi
if [ "$NET_INFO" != "0" ] && [ "$NET_INFO" != "1" ]; then die "NET_INFO 无效:$NET_INFO" "Invalid NET_INFO: $NET_INFO"; fi
if [ "$NETWORK" != "0" ] && [ "$NETWORK" != "1" ]; then die "NETWORK 无效:$NETWORK" "Invalid NETWORK: $NETWORK"; fi
case "$NETWORK_PROFILE" in cloudflare|full|yabs|none) ;; *) die "NETWORK_PROFILE 无效:$NETWORK_PROFILE" "Invalid NETWORK_PROFILE: $NETWORK_PROFILE" ;; esac
if [ "$VERBOSE" != "0" ] && [ "$VERBOSE" != "1" ]; then die "VERBOSE 无效:$VERBOSE" "Invalid VERBOSE: $VERBOSE"; fi
if [ -n "$IPERF_SERVER" ] && ! parse_custom_iperf "$IPERF_SERVER"; then
die "--iperf 地址无效:$IPERF_SERVER" "Invalid --iperf endpoint: $IPERF_SERVER (expected HOST[:PORT], [IPv6]:PORT, or IPv6)"
fi
if [ -n "$JOBS_ENV" ]; then
JOBS="$JOBS_ENV"
else
JOBS=$(( T < 4 ? T : 4 ))
fi
if ! is_pos_int "$JOBS"; then die "JOBS 无效:$JOBS" "Invalid JOBS: $JOBS"; fi
mkdir -p -- "$DIR"
if [ -n "$LOGDIR_OVERRIDE" ]; then
LOGDIR="$LOGDIR_OVERRIDE"
mkdir -p -- "$LOGDIR"
else
LOGDIR="$(mktemp -d "${TMPDIR:-/tmp}/abs.XXXXXXXX")"
fi
RESULTS="$LOGDIR/results.tsv"
JSON_RESULT="$LOGDIR/result.json"
COMPONENTS_FILE="$LOGDIR/components.tsv"
printf 'Metric\tResult\n' > "$RESULTS"
have() { command -v "$1" >/dev/null 2>&1; }
sudo_cmd() {
if [ "${EUID:-$(id -u)}" -eq 0 ]; then
"$@"
elif have sudo; then
# `curl | bash` feeds the script through stdin, so sudo cannot read a
# password from stdin. When a controlling terminal exists, explicitly
# attach it so normal interactive sudo authentication still works. In
# cron/CI or other headless runs, stay non-interactive and fail quickly.
if [ -r /dev/tty ]; then
sudo "$@" </dev/tty
else
sudo -n "$@"
fi
else
return 1
fi
}
human_kib() {
awk -v kib="${1:-0}" 'BEGIN {
n=kib+0; split("KiB MiB GiB TiB PiB", u, " "); i=1;
while (n >= 1024 && i < 5) { n/=1024; i++ }
if (i == 1) printf "%.0f %s", n, u[i]; else printf "%.1f %s", n, u[i]
}'
}
auto_size() {
local avail_kb avail_mib target_mib
avail_kb="$(df -Pk "$DIR" 2>/dev/null | awk 'NR==2 {print $4+0}')"
avail_mib=$(( ${avail_kb:-0} / 1024 ))
# Default: about 1/10 free disk, bounded for sane one-line VPS runs.
# Floor: 512M. Cap: default 1G, full 8G. Rounded down to a common fio size.
local cap_mib=1024
[ "$PROFILE" = "full" ] && cap_mib=8192
target_mib=$(( avail_mib / 10 ))
[ "$target_mib" -lt 512 ] && target_mib=512
[ "$target_mib" -gt "$cap_mib" ] && target_mib="$cap_mib"
if [ "$target_mib" -lt 1024 ]; then
printf '512M\n'
elif [ "$target_mib" -lt 2048 ]; then
printf '1G\n'
elif [ "$target_mib" -lt 4096 ]; then
printf '2G\n'
elif [ "$target_mib" -lt 8192 ]; then
printf '4G\n'
else
printf '8G\n'
fi
}
if [ "$SIZE" = "auto" ]; then
SIZE="$(auto_size)"
fi
find_fio_bin() {
local p
for p in "$(command -v fio 2>/dev/null || true)" /usr/bin/fio /usr/local/bin/fio; do
if [ -z "$p" ] || [ ! -x "$p" ]; then
continue
fi
if "$p" --version 2>/dev/null | grep -q '^fio-'; then
printf '%s\n' "$p"
return 0
fi
done
return 1
}
have_fio() {
FIO_BIN="$(find_fio_bin 2>/dev/null || true)"
[ -n "$FIO_BIN" ]
}
missing_tools() {
local missing=()
have sysbench || missing+=(sysbench)
have_fio || missing+=(fio)
have python3 || missing+=(python3)
if [ "$NETWORK" = "1" ] || [ "$NET_INFO" = "1" ]; then
have curl || missing+=(curl)
fi
if [ "$NETWORK" = "1" ] && { [ -n "$IPERF_SERVER" ] || [ "$NETWORK_PROFILE" = "full" ] || [ "$NETWORK_PROFILE" = "yabs" ]; }; then
have iperf3 || missing+=(iperf3)
fi
printf '%s\n' "${missing[@]}"
}
run_package_command() {
local out="$1" err="$2"
shift 2
if sudo_cmd "$@" >"$out" 2>"$err"; then
return 0
fi
INSTALL_ERROR_LOG="$err"
return 1
}
install_error_summary() {
local log="$1"
[ -s "$log" ] || return 0
awk 'BEGIN {IGNORECASE=1}
/dpkg was interrupted|^E:|error:|failed/ {print; found=1; exit}
NF {last=$0}
END {if (!found && last != "") print last}' "$log"
}
show_install_error() {
local summary
[ -n "$INSTALL_ERROR_LOG" ] || return 0
summary="$(install_error_summary "$INSTALL_ERROR_LOG")"
if [[ "$summary" == *"dpkg was interrupted"* ]]; then
say "依赖安装失败:dpkg 上次操作被中断。" "Dependency installation failed: dpkg was interrupted."
say "请先运行:sudo dpkg --configure -a" "Run this first: sudo dpkg --configure -a"
elif [[ "$summary" =~ [Pp]assword[[:space:]]+is[[:space:]]+required|[Tt]erminal[[:space:]]+is[[:space:]]+required|[Pp]ermission[[:space:]]+denied|[Mm]ust[[:space:]]+be[[:space:]]+run[[:space:]]+as[[:space:]]+root ]]; then
say "依赖安装未执行:当前用户没有可用的 sudo 权限,或 sudo 密码验证未完成。" "Dependency installation was not performed: sudo permission is unavailable or password authentication did not complete."
say "在交互式终端中重新运行 ABS 会自动询问 sudo 密码;无终端运行请先配置免密 sudo,或加 -n 跳过自动安装。" "Rerun ABS from an interactive terminal to allow a sudo password prompt; headless runs need passwordless sudo or -n to skip automatic installation."
elif [ -n "$summary" ]; then
say "依赖安装失败:$summary" "Dependency installation failed: $summary"
else
say "依赖安装失败,详见:$INSTALL_ERROR_LOG" "Dependency installation failed; see $INSTALL_ERROR_LOG"
fi
say "安装日志:$INSTALL_ERROR_LOG" "Install log: $INSTALL_ERROR_LOG"
}
install_tools() {
local missing
missing="$(missing_tools | xargs 2>/dev/null || true)"
[ -z "$missing" ] && return 0
if [ "$INSTALL" != "1" ]; then
MISSING_AFTER_INSTALL="$missing"
return 0
fi
INSTALL_ATTEMPTED="1"
say "缺少工具:$missing" "Missing tools: $missing"
say "正在尝试安装;使用 -n/--no-install 可跳过安装。" "Installing missing tools when possible... use -n/--no-install to skip installation."
local curl_pkg="" iperf_pkg=""
if [ "$NETWORK" = "1" ] || [ "$NET_INFO" = "1" ]; then
curl_pkg="curl"
fi
if [ "$NETWORK" = "1" ] && { [ -n "$IPERF_SERVER" ] || [ "$NETWORK_PROFILE" = "full" ] || [ "$NETWORK_PROFILE" = "yabs" ]; }; then
iperf_pkg="iperf3"
fi
if have apt-get; then
run_package_command "$LOGDIR/install-apt-update.log" "$LOGDIR/install-apt-update.err" \
env DEBIAN_FRONTEND=noninteractive apt-get update -y || true
run_package_command "$LOGDIR/install-apt.log" "$LOGDIR/install-apt.err" \
env DEBIAN_FRONTEND=noninteractive apt-get install -y sysbench fio python3 ca-certificates procps $curl_pkg $iperf_pkg || true
elif have dnf; then
run_package_command "$LOGDIR/install-dnf.log" "$LOGDIR/install-dnf.err" \
dnf install -y sysbench fio python3 procps-ng $curl_pkg $iperf_pkg || true
elif have yum; then
run_package_command "$LOGDIR/install-yum-epel.log" "$LOGDIR/install-yum-epel.err" \
yum install -y epel-release || true
run_package_command "$LOGDIR/install-yum.log" "$LOGDIR/install-yum.err" \
yum install -y sysbench fio python3 procps-ng $curl_pkg $iperf_pkg || true
elif have pacman; then
# Do not use `pacman -Sy`: syncing package metadata without a full upgrade
# creates an unsupported partial-upgrade state on Arch Linux.
run_package_command "$LOGDIR/install-pacman.log" "$LOGDIR/install-pacman.err" \
pacman -S --needed --noconfirm sysbench fio python procps $curl_pkg $iperf_pkg || true
elif have apk; then
run_package_command "$LOGDIR/install-apk.log" "$LOGDIR/install-apk.err" \
apk add --no-cache sysbench fio python3 procps $curl_pkg $iperf_pkg || true
fi
have_fio || true
missing="$(missing_tools | xargs 2>/dev/null || true)"
MISSING_AFTER_INSTALL="$missing"
if [ -n "$missing" ]; then
say "安装后仍缺少:$missing;相关测试将跳过。" "Still missing after install attempt: $missing; affected tests will be skipped."
show_install_error
fi
}
zh_metric() {
local metric="$1" suffix
case "$metric" in
"Install mode") printf '依赖工具' ;;
"CPU single thread") printf 'CPU 单线程' ;;
"CPU all threads ("*")")
suffix="${metric#CPU all threads (}"; suffix="${suffix%)}"; printf 'CPU 全线程(%s)' "$suffix" ;;
"Memory read ("*" threads)")
suffix="${metric#Memory read (}"; suffix="${suffix% threads)}"; printf '内存读取(%s 线程)' "$suffix" ;;
"Memory write ("*" threads)")
suffix="${metric#Memory write (}"; suffix="${suffix% threads)}"; printf '内存写入(%s 线程)' "$suffix" ;;
"Memory read") printf '内存读取' ;;
"Memory write") printf '内存写入' ;;
"sysbench CPU/memory") printf 'sysbench CPU/内存测试' ;;
"fio disk tests") printf 'fio 磁盘测试' ;;
"fio prepare") printf 'fio 测试文件准备' ;;
"Disk sequential write") printf '磁盘顺序写入' ;;
"Disk sequential read") printf '磁盘顺序读取' ;;
"Disk random read 4K QD1") printf '磁盘 4K QD1 随机读取' ;;
"Disk random write 4K QD1") printf '磁盘 4K QD1 随机写入' ;;
"Disk random read 4K pressure") printf '磁盘 4K 随机读取(压力)' ;;
"Disk random write 4K pressure") printf '磁盘 4K 随机写入(压力)' ;;
"Disk random mixed 4K 60r/40w") printf '磁盘 4K 混合随机(60%%读/40%%写)' ;;
"Disk durable write 4K fsync") printf '磁盘 4K 持久化写入(fsync)' ;;
"Disk fallback dd") printf '磁盘 dd 备用测试' ;;
"Disk fallback dd write") printf '磁盘 dd 备用写入' ;;
"Disk fallback dd read") printf '磁盘 dd 备用读取' ;;
"Network sanity") printf '网络简测' ;;
"Network Cloudflare TTFB") printf '网络 Cloudflare TTFB' ;;
"Network Cloudflare download") printf '网络 Cloudflare 下载' ;;
"Network Cloudflare upload") printf '网络 Cloudflare 上传' ;;
"Network iperf3") printf '网络 iperf3' ;;
"Network iperf3 send "*) printf '网络 iperf3 发送 %s' "${metric#Network iperf3 send }" ;;
"Network iperf3 recv "*) printf '网络 iperf3 接收 %s' "${metric#Network iperf3 recv }" ;;
"cpu component score") printf 'CPU 分项得分' ;;
"mem component score") printf '内存分项得分' ;;
"disk component score") printf '磁盘分项得分' ;;
"fsync component score") printf 'fsync 分项得分' ;;
"ABS SCORE") printf '综合得分' ;;
"Local component") printf '本地得分' ;;
"Network component") printf '网络参考' ;;
"ABS VERDICT") printf '结论' ;;
"Score note") printf '评分说明' ;;
"Privacy note") printf '隐私说明' ;;
"JSON result") printf 'JSON 结果' ;;
"JSON copy") printf 'JSON 副本' ;;
*) printf '%s' "$metric" ;;
esac
}
zh_components() {
local text="$1"
text="${text//disk-buffered/磁盘(缓存模式)}"
text="${text//fsync-buffered/fsync(缓存模式)}"
text="${text//memory/内存}"
text="${text//cpu/CPU}"
text="${text//mem/内存}"
text="${text//disk/磁盘}"
printf '%s' "$text"
}
zh_reason() {
local reason="$1"
reason="${reason//practical VPS profile looks acceptable/本地性能整体良好}"
reason="${reason//usable, but has notable weaknesses/可以使用,但存在明显短板}"
reason="${reason//weak practical VPS performance/本地性能较弱}"
reason="${reason//critical CPU bottleneck (component score /CPU 严重瓶颈(分项得分 }"
reason="${reason//critical memory bottleneck (component score /内存严重瓶颈(分项得分 }"
reason="${reason//critical disk bottleneck (component score /磁盘严重瓶颈(分项得分 }"
reason="${reason//critical fsync bottleneck (component score /fsync 严重瓶颈(分项得分 }"
reason="${reason//CPU component is weak (component score /CPU 分项偏弱(得分 }"
reason="${reason//memory component is weak (component score /内存分项偏弱(得分 }"
reason="${reason//disk component is weak (component score /磁盘性能偏弱(得分 }"
reason="${reason//fsync component is weak (component score /fsync 性能偏弱(得分 }"
reason="${reason//weak durable-write\/fsync/持久化写入\/fsync 偏弱}"
reason="${reason//OpenVZ\/container storage can be cache-inflated/OpenVZ\/容器磁盘数据可能受缓存影响}"
reason="${reason//very high write\/fsync numbers; verify with --full before buying/写入\/fsync 数值异常高,购买前请用 --full 复测}"
reason="${reason//; /;}"
reason="${reason//)/)}"
printf '%s' "$reason"
}
zh_verdict() {
local text="$1" code reason label
code="${text%% - *}"
reason="${text#* - }"
case "$code" in
KEEP) label="保留" ;;
MAYBE) label="谨慎保留" ;;
AVOID) label="不建议保留" ;;
INCOMPLETE) label="测试不完整" ;;
*) printf '%s' "$text"; return ;;
esac
# Keep the terminal verdict concise. Full machine-readable details remain in
# TSV/JSON and in English mode.
reason="${reason%%; *}"
case "$reason" in
"missing required benchmark sections") reason="缺少必要测试项目" ;;
"python3 missing") reason="缺少 python3" ;;
*)
reason="$(zh_reason "$reason")"
reason="${reason%%(得分 *}"
reason="${reason%%(分项得分 *}"
;;
esac
printf '%s — %s' "$label" "$reason"
}
zh_result() {
local text="$1" score network missing
case "$text" in
KEEP\ -*|MAYBE\ -*|AVOID\ -*|INCOMPLETE\ -*) zh_verdict "$text"; return ;;
FULL\ *)
score="$(printf '%s' "$text" | awk '{print $2}')"
if [[ "$text" == *"network reference "* ]]; then
network="${text##*network reference }"; network="${network%%)*}"
printf '完整,得分 %s(仅本地;网络参考分 %s)' "$score" "$network"
else
printf '完整,得分 %s(仅本地;网络不计分)' "$score"
fi
return ;;
PARTIAL\ -\ not\ comparable:*)
score="$(printf '%s' "$text" | awk '{for(i=1;i<=NF;i++) if($i ~ /^[0-9]+$/){print $i; exit}}')"
missing="${text##*missing }"; missing="${missing%%;*}"; missing="${missing%%)*}"
if [ -n "$score" ]; then
printf '不完整,不能比较(当前分数 %s;缺少 %s)' "$score" "$(zh_components "$missing")"
else
printf '不完整,不能比较'
fi
return ;;
SANITY\ *)
score="$(printf '%s' "$text" | awk '{print $2}')"
printf '参考分 %s(Cloudflare HTTP,仅供参考,不计分)' "$score"
return ;;
"N/A - skipped"*) printf '未测试(网络不计分;本地分数独立有效)'; return ;;
"n/a (python3 missing)") printf '不可用(缺少 python3)'; return ;;
"all required tools available; no installation needed") printf '已齐全(无需安装)'; return ;;
"missing tools installed successfully") printf '已成功安装'; return ;;
"missing tools; installation disabled: "*) printf '缺少 %s(安装已禁用)' "${text#missing tools; installation disabled: }"; return ;;
"installation failed; still missing: "*) printf '安装失败,仍缺少 %s' "${text#installation failed; still missing: }"; return ;;
FAILED\ \(timeout\ after\ *\)\;\ see\ *)
printf '超时;详见 %s' "${text##*; see }"; return ;;
"FAILED; see "*) printf '失败;详见 %s' "${text#FAILED; see }"; return ;;
"FAILED: "*) printf '失败:%s' "${text#FAILED: }"; return ;;
"sysbench not installed; skipped") printf '未安装 sysbench,已跳过'; return ;;
"fio or python3 not installed; skipped") printf '未安装 fio 或 python3,已跳过'; return ;;
"curl not installed; skipped") printf '未安装 curl,已跳过'; return ;;
"iperf3 missing; skipped") printf '未安装 iperf3,已跳过'; return ;;
"dd not installed; skipped") printf '未安装 dd,已跳过'; return ;;
"invalid SIZE="*) printf 'SIZE 无效,已跳过:%s' "${text#invalid }"; return ;;
"not enough free space for "*) printf '可用空间不足,已跳过:%s' "${text#not enough free space for }"; return ;;
"ABS score is LOCAL-only:"*) printf 'ABS 总分仅计算本地 CPU、内存、磁盘和 fsync;网络仅供参考,不影响总分。'; return ;;
"No result upload."*) printf '不上传结果;网络检查会访问 Cloudflare,安装依赖会访问软件源。'; return ;;
esac
text="${text//events\/s/事件\/秒}"
text="${text//writes\/s/次写入\/秒}"
text="${text//write p95/写入 P95}"
text="${text//sync p95/同步 P95}"
text="${text//p95/P95}"
[[ "$text" == R\ * ]] && text="读 ${text#R }"
text="${text// \/ W / \/ 写 }"
text="${text//(not scored)/(不计分)}"
text="${text//(buffered; not scored)/(缓存模式,不计分)}"
printf '%s' "$text"
}
add() {
if is_zh; then
printf '%s:%s\n' "$(zh_metric "$1")" "$(zh_result "$2")"
else
printf '%-48s %s\n' "$1" "$2"
fi
printf '%s\t%s\n' "$1" "$2" >> "$RESULTS"
}
add_note() {
if is_zh; then
printf '%s:%s\n' "$(zh_metric "$1")" "$(zh_result "$2")"
else
printf '%-48s %s\n' "$1" "$2"
fi
}
field() { awk -v key="$1" '$0 ~ key {print $NF; exit}' "$2"; }
eps() { field 'events per second' "$1"; }
p95() { field '95th percentile' "$1"; }
memspeed() { awk -F'[()]' '/MiB transferred/ {print $2; exit}' "$1"; }
run_log() {
local name="$1"
shift
LAST_LOG="$LOGDIR/$name.log"
if "$@" >"$LAST_LOG" 2>&1; then
return 0
fi
return 1
}
fio_run() {
local name="$1" rw="$2" bs="$3" jobs="$4" depth="$5"
shift 5
LAST_JSON="$LOGDIR/$name.json"
local err="$LOGDIR/$name.err"
local fio_rw="$rw"
local test_size="$SIZE" segment_bytes=""
[ "$rw" = "prepare" ] && fio_rw="write"
if [ "$jobs" -gt 1 ]; then
local total_bytes
total_bytes="$(size_bytes "$SIZE")"
segment_bytes=$(( total_bytes / jobs / 4096 * 4096 ))
if [ "$segment_bytes" -lt 4096 ]; then
printf 'SIZE=%s is too small for %s fio jobs\n' "$SIZE" "$jobs" >"$err"
return 1
fi
test_size="$segment_bytes"
fi
local args=(
--name="$name"
--filename="$FIO_FILE"
--size="$test_size"
--rw="$fio_rw"
--bs="$bs"
--numjobs="$jobs"
--iodepth="$depth"
--group_reporting
--eta=never
--direct="$DIRECT"
--ioengine="$FIO_ENGINE"
--output-format=json
)
# With an explicit filename, fio clones otherwise hit the same byte range.
# Split the prepared file into disjoint regions so overlapping writes cannot
# be coalesced and falsely inflate pressure-test throughput.
[ -n "$segment_bytes" ] && args+=(--offset_increment="$segment_bytes")
if [ "$rw" != "prepare" ]; then
args+=(--runtime="$D" --time_based)
else
args+=(--end_fsync=1)
fi
args+=("$@")
if "$FIO_BIN" "${args[@]}" >"$LAST_JSON" 2>"$err"; then
return 0
fi
return 1
}
size_bytes() {
python3 - "$1" <<'PY'
import re, sys
s = sys.argv[1].strip()
m = re.fullmatch(r'([0-9]+)([KMGTP]?)(i?B?)?', s, re.I)
if not m:
print(-1); raise SystemExit
n = int(m.group(1)); unit = m.group(2).upper()
mult = {'':1,'K':1024,'M':1024**2,'G':1024**3,'T':1024**4,'P':1024**5}[unit]
print(n * mult)
PY
}
fio_metric() {
local metric="$1"
python3 - "$LAST_JSON" "$metric" <<'PY'
import json, sys
path, metric = sys.argv[1], sys.argv[2]
try:
with open(path, 'r', encoding='utf-8', errors='replace') as f:
data = json.load(f)
except Exception:
print('0.00')
raise SystemExit
jobs = data.get('jobs') or []
def nums(path):
out = []
for job in jobs:
cur = job
for key in path:
if not isinstance(cur, dict) or key not in cur:
break
cur = cur[key]
else:
if isinstance(cur, (int, float)):
out.append(float(cur))
return out
def sum_path(path):
return sum(nums(path))
def max_p95(section, lat='clat_ns'):
vals = []
for job in jobs:
p = (((job.get(section) or {}).get(lat) or {}).get('percentile') or {})
v = p.get('95.000000') or p.get('95')
if isinstance(v, (int, float)):
vals.append(float(v) / 1_000_000)
return max(vals) if vals else 0.0
def sync_p95():
vals = []
for job in jobs:
sync = job.get('sync') or {}
for lat_key in ('lat_ns', 'clat_ns'):
p = ((sync.get(lat_key) or {}).get('percentile') or {})
v = p.get('95.000000') or p.get('95')
if isinstance(v, (int, float)):
vals.append(float(v) / 1_000_000)
return max(vals) if vals else None
if metric == 'read_mib':
val = sum_path(['read', 'bw_bytes']) / 1048576
elif metric == 'write_mib':
val = sum_path(['write', 'bw_bytes']) / 1048576
elif metric == 'read_iops':
val = sum_path(['read', 'iops'])
elif metric == 'write_iops':
val = sum_path(['write', 'iops'])
elif metric == 'read_p95_ms':
val = max_p95('read')
elif metric == 'write_p95_ms':
val = max_p95('write')
elif metric == 'mixed_p95_ms':
val = max(max_p95('read'), max_p95('write'))
elif metric == 'sync_p95_ms':
val = sync_p95()
if val is None:
print('n/a')
raise SystemExit
else:
val = 0.0
print(f'{val:.2f}')
PY
}
abs_local_score() {
ABS_COMPONENTS_FILE="$COMPONENTS_FILE" python3 - "$RESULTS" "$T" "$DIRECT" <<'PY'
import csv, math, os, re, sys
path = sys.argv[1]
threads = float(sys.argv[2]) if len(sys.argv) > 2 else 1.0
direct_io = len(sys.argv) > 3 and sys.argv[3] == '1'
rows = {}
try:
with open(path, newline='', encoding='utf-8', errors='replace') as f:
for row in csv.reader(f, delimiter='\t'):
if len(row) >= 2 and row[0] != 'Metric':
rows[row[0]] = row[1]
except Exception:
print('n/a')
raise SystemExit
def first_num(text):
text = text or ''
low = text.lower()
if any(word in low for word in ('failed', 'skipped', 'invalid', 'not enough', 'not installed')):
return None
m = re.search(r'[0-9]+(?:\.[0-9]+)?', text)
return float(m.group(0)) if m else None
def metric(prefix):
for k, v in rows.items():
if k.startswith(prefix):
return v
return None
def clamp(x, lo=0, hi=3000):
return max(lo, min(hi, x))
components = []
missing = []
single = first_num(metric('CPU single thread'))
all_cpu = first_num(metric('CPU all threads'))
if single and all_cpu and threads > 0:
per_thread = all_cpu / threads
cpu = 1000 * math.sqrt((single / 400.0) * (per_thread / 400.0))
components.append(('cpu', clamp(cpu), 0.40))
else:
missing.append('cpu')
mem_read = first_num(metric('Memory read'))
mem_write = first_num(metric('Memory write'))
if mem_read and mem_write:
mem = 1000 * math.sqrt((mem_read / 30000.0) * (mem_write / 20000.0))
components.append(('mem', clamp(mem), 0.15))
else:
missing.append('mem')
if direct_io:
qd1_read = first_num(metric('Disk random read 4K QD1'))
qd1_write = first_num(metric('Disk random write 4K QD1'))
if qd1_read and qd1_write:
disk = 1000 * math.sqrt((qd1_read / 10000.0) * (qd1_write / 5000.0))
components.append(('disk', clamp(disk), 0.30))
else:
missing.append('disk')
fsync = first_num(metric('Disk durable write 4K fsync'))
if fsync:
dur = 1000 * math.sqrt(fsync / 2000.0)
components.append(('fsync', clamp(dur), 0.15))
else:
missing.append('fsync')
else:
missing.extend(('disk-buffered', 'fsync-buffered'))
if not components:
print('n/a')
raise SystemExit
total_w = sum(w for _, _, w in components)
score = round(sum(v * w for _, v, w in components) / total_w)
parts = ','.join(name for name, _, _ in components)
with open(os.environ['ABS_COMPONENTS_FILE'], 'w', encoding='utf-8') as f:
for name, value, _ in components:
f.write(f'{name}\t{round(value)}\n')
if missing:
print(f'PARTIAL - not comparable: {score} (local only: {parts}; missing {",".join(missing)}; network excluded)')
else:
print(f'FULL {score} (local only: {parts}; network excluded)')
PY
}
network_score() {
if [ "$NETWORK" != "1" ]; then
printf 'N/A - skipped (network excluded; local score is standalone)'
return 0
fi
NETWORK_PROFILE_IN="$NETWORK_PROFILE" IPERF_SERVER_IN="$IPERF_SERVER" python3 - "$RESULTS" <<'PY'
import csv, math, os, re, statistics, sys
rows = {}
try:
with open(sys.argv[1], newline='', encoding='utf-8', errors='replace') as f:
for row in csv.reader(f, delimiter='\t'):
if len(row) >= 2 and row[0] != 'Metric':
rows[row[0]] = row[1]
except Exception:
print('n/a')
raise SystemExit
def parse_num(v):
low = (v or '').lower()
if any(w in low for w in ('failed', 'skipped', 'not installed', 'missing')):
return None
m = re.search(r'[0-9]+(?:\.[0-9]+)?', v or '')
return float(m.group(0)) if m else None
def first_num(prefix):
for k, v in rows.items():
if k.startswith(prefix):
return parse_num(v)
return None
def nums(prefix):
out = []
for k, v in rows.items():
if k.startswith(prefix):
n = parse_num(v)
if n is not None:
out.append(n)
return out
lat = first_num('Network Cloudflare TTFB')
down = first_num('Network Cloudflare download')
up = first_num('Network Cloudflare upload')
missing = []
if lat is None: missing.append('ttfb')
if down is None: missing.append('download')
if up is None: missing.append('upload')
if missing:
print('PARTIAL - not comparable: missing ' + ','.join(missing))
raise SystemExit
lat_component = min(3.0, max(0.1, 100.0 / max(lat, 1.0)))
down_component = min(3.0, max(0.1, down / 100.0))
up_component = min(3.0, max(0.1, up / 50.0))
cf_score = round(1000 * (lat_component * down_component * up_component) ** (1/3))
send_vals = nums('Network iperf3 send')
recv_vals = nums('Network iperf3 recv')
profile = os.environ.get('NETWORK_PROFILE_IN', 'cloudflare')
custom = bool(os.environ.get('IPERF_SERVER_IN', ''))
expected = {'full': 3, 'yabs': 7}.get(profile, 0) + (1 if custom else 0)
requires_iperf = expected > 0
if send_vals and recv_vals and (not requires_iperf or (len(send_vals) >= expected and len(recv_vals) >= expected)):
send = statistics.median(send_vals)
recv = statistics.median(recv_vals)
send_component = min(3.0, max(0.1, send / 500.0))
recv_component = min(3.0, max(0.1, recv / 500.0))
iperf_score = round(1000 * math.sqrt(send_component * recv_component))
score = round(cf_score * 0.6 + iperf_score * 0.4)
if profile == 'yabs':
label = 'current YABS iperf3 list'
elif profile == 'full':
label = '3-region public iperf3'
else:
label = 'custom iperf3'
print(f'FULL {score} (Cloudflare + {label}; cf {cf_score}, iperf {iperf_score})')
elif requires_iperf:
pairs = min(len(send_vals), len(recv_vals))
print(f'PARTIAL - not comparable: iperf3 results {pairs}/{expected} pairs')
else:
print(f'SANITY {cf_score} (Cloudflare HTTP; reference only, not in score)')
PY
}
abs_score() {
python3 - "$LOCAL_SCORE_TEXT" "$NETWORK_SCORE_TEXT" <<'PY'
import re, sys
local_text, net_text = sys.argv[1], sys.argv[2]
if (local_text or '').startswith('PARTIAL'):
print(local_text)
raise SystemExit
ml = re.search(r'FULL\s+(\d+)', local_text or '')
if not ml:
print('PARTIAL - not comparable: missing local core')
raise SystemExit
local = int(ml.group(1))
# VERDICT: local score stands on its own. Network is informational only and
# does NOT mix into the headline score (avoids a noisy single-point Cloudflare
# sample dragging down a solid local profile). Network line is appended purely
# as a reference note for the user.
mn = re.search(r'(?:FULL|SANITY)\s+(\d+)', net_text or '')
if not mn:
print(f'FULL {local} (local only; network excluded from score)')
else:
network = int(mn.group(1))
print(f'FULL {local} (local only; network reference {network})')
PY
}
abs_verdict() {
python3 - "$SCORE_TEXT" "$RESULTS" "$VM_TYPE" "$T" <<'PY'
import csv, math, re, sys
score_text, results, vm_type = sys.argv[1], sys.argv[2], (sys.argv[3] or '').lower()
threads = float(sys.argv[4]) if len(sys.argv) > 4 else 1.0