Repository navigation
Expand file tree
/
Copy pathrustfs_pool_expand.sh
More file actions
executable file
·1892 lines (1783 loc) · 79.8 KB
/
Copy pathrustfs_pool_expand.sh
File metadata and controls
executable file
·1892 lines (1783 loc) · 79.8 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
#
# rustfs-pool-expand.sh
# RustFS multi-pool expansion & pool decommission test script
#
# Based on the Obsidian note "RustFS Pool Expansion Script". Full workflow:
# 1. Download the RustFS package on all nodes
# 2. Install the RustFS service on all nodes (dpkg -i)
# 3. Start the first pool on node 0 and verify it
# 4. Write data (warp) and monitor storage usage up to a threshold
# 5. Expand to a second pool (node 0 + node 1), start rebalance
# 6. Wait for rebalance to finish
# 7. Expand to a third pool (all nodes), start rebalance again
# 8. Wait for rebalance to finish
# 9. Decommission pool 0 and wait for it to complete
#
# The script is driven from an admin host (e.g. a jumpbox or a GitHub
# self-hosted runner) and operates on the target nodes over SSH.
#
# Usage:
# ./rustfs-pool-expand.sh --all # run all steps 1-9
# ./rustfs-pool-expand.sh --step 5 # run a single step
# ./rustfs-pool-expand.sh --steps 5,7,9 # run selected steps
# ./rustfs-pool-expand.sh --all --dry-run # preview only
# ./rustfs-pool-expand.sh --all -y --version 1.0.0-rc.3
#
# Notes:
# - SSH user defaults to azureuser (passwordless sudo on the nodes);
# pass --ssh-user root if your nodes accept root login.
# - The script talks to the RustFS admin API directly with SigV4-signed
# requests (no rc required). jq, openssl and curl must be installed on the
# admin host; warp is only needed for --with-warp.
# - RUSTFS_VOLUMES must keep existing pool expressions unchanged and in
# order when expanding.
#
set -Eeuo pipefail
POOL_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# ==================== Configuration (adjust to your environment) ====================
# Target nodes; pool N is enabled by NODES[N-1] (index order matters)
if [ -n "${RUSTFS_NODES:-}" ]; then
read -r -a NODES <<<"${RUSTFS_NODES}"
else
NODES=(vm000 vm001 vm002 vm003)
fi
# SSH user configured on the nodes (azureuser has passwordless sudo on heal's nodes)
SSH_USER="${RUSTFS_SSH_USER:-azureuser}"
SSH_PORT="${RUSTFS_SSH_PORT:-22}"
SSH_OPTS=(-o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new -p "${SSH_PORT}")
# Package: version is a GitHub release tag such as "1.0.0-rc.3".
# PACKAGE_URL is derived from RUSTFS_VERSION unless --package-url / PACKAGE_URL is given.
RUSTFS_VERSION="${RUSTFS_VERSION:-1.0.0-rc.3}"
PACKAGE_URL="${PACKAGE_URL:-}"
ARCH="${RUSTFS_ARCH:-amd64}"
PACKAGES_DIR="/home/rustfs/packages"
PACKAGE_FILE="rustfs.deb"
PACKAGE_SHA256="${PACKAGE_SHA256:-}"
# Endpoint fallback and credentials (SigV4-signed requests, no rc needed).
# The legacy endpoint remains a fallback for existing setups, while pool tests
# can pin control and data traffic to a live node and probe a load balancer
# independently.
LEGACY_ENDPOINT="${RUSTFS_API_ENDPOINT:-${RUSTFS_RC_ENDPOINT:-http://rustfs-node1:9000}}"
ADMIN_ENDPOINT="${RUSTFS_ADMIN_ENDPOINT:-${RUSTFS_CONTROL_ENDPOINT:-}}"
WARP_ENDPOINT="${RUSTFS_WARP_ENDPOINT:-}"
PROXY_ENDPOINT="${RUSTFS_PROXY_ENDPOINT:-}"
PROXY_STAGE_HOOK="${RUSTFS_PROXY_STAGE_HOOK:-}"
ACCESS_KEY="${RUSTFS_ACCESS_KEY:-rustfs@test}"
SECRET_KEY="${RUSTFS_SECRET_KEY:-rustfs@test}"
SIGV4_REGION="us-east-1"
SIGV4_SERVICE="s3"
API_REQUEST_TIMEOUT=60
# API helpers write status and timing data here so callers can read it after a
# command-substitution subshell exits ($$ is identical inside the subshell).
ADMIN_API_CODE_FILE="${TMPDIR:-/tmp}/rustfs-pool-expand-api-code.$$"
ADMIN_API_TIMING_FILE="${TMPDIR:-/tmp}/rustfs-pool-expand-api-timing.$$"
PROXY_API_CODE_FILE="${TMPDIR:-/tmp}/rustfs-pool-expand-proxy-code.$$"
PROXY_API_TIMING_FILE="${TMPDIR:-/tmp}/rustfs-pool-expand-proxy-timing.$$"
ADMIN_ANOMALY_FILE="${TMPDIR:-/tmp}/rustfs-pool-expand-admin-anomaly.$$"
PROXY_ANOMALY_FILE="${TMPDIR:-/tmp}/rustfs-pool-expand-proxy-anomaly.$$"
STORAGEINFO_PROBE_RETRIES="${RUSTFS_STORAGEINFO_PROBE_RETRIES:-3}"
STORAGEINFO_PROBE_RETRY_DELAY="${RUSTFS_STORAGEINFO_PROBE_RETRY_DELAY:-1}"
# Complete RUSTFS_VOLUMES value per stage (one space-separated expression per pool)
VOLUMES_1="http://rustfs-node1:9000/data/rustfs{1...4}/mnmd"
VOLUMES_2="http://rustfs-node1:9000/data/rustfs{1...4}/mnmd http://rustfs-node2:9000/data/rustfs{1...4}/mnmd"
VOLUMES_3="http://rustfs-node1:9000/data/rustfs{1...4}/mnmd http://rustfs-node2:9000/data/rustfs{1...4}/mnmd http://rustfs-node3:9000/data/rustfs{1...4}/mnmd"
VOLUMES_4="${VOLUMES_3} http://rustfs-node4:9000/data/rustfs{1...4}/mnmd"
# Topology after decommissioning pool 0 (used by --finalize-decommission)
VOLUMES_AFTER_DECOMMISSION="http://rustfs-node2:9000/data/rustfs{1...4}/mnmd http://rustfs-node3:9000/data/rustfs{1...4}/mnmd"
# 4x4 topology: after decommissioning pool 0, pools 2-4 remain
VOLUMES_AFTER_DECOMMISSION_4="${VOLUMES_AFTER_DECOMMISSION} http://rustfs-node4:9000/data/rustfs{1...4}/mnmd"
read -r -a NODE_ENDPOINTS <<<"${RUSTFS_NODE_ENDPOINTS:-http://rustfs-node1:9000 http://rustfs-node2:9000 http://rustfs-node3:9000 http://rustfs-node4:9000}"
# RustFS service configuration (written to /etc/default/rustfs)
RUSTFS_CONFIG_FILE="/etc/default/rustfs"
RUSTFS_SERVICE="rustfs"
RUSTFS_PACKAGE_NAME="rustfs"
RUSTFS_USER="rustfs"
RUSTFS_ADDRESS=":9000"
RUSTFS_CONSOLE_ADDRESS=":9001"
RUSTFS_CONSOLE_ENABLE=true
RUSTFS_OBS_LOGGER_LEVEL=error
RUSTFS_OBS_LOG_DIRECTORY="/var/log/rustfs/"
# Data writing & monitoring (step 4)
WARP_BUCKET="test-10mb"
WARP_OBJ_SIZE="${RUSTFS_WARP_OBJ_SIZE:-100MiB}"
WARP_CONCURRENT="${RUSTFS_WARP_CONCURRENT:-32}"
WARP_DURATION="5m"
WARP_ROUNDS="${RUSTFS_WARP_ROUNDS:-1}"
# Warp log path; empty = auto-created unique temp file (the runner user may
# not be able to write a shared /tmp path owned by another user).
WARP_LOG_FILE="${RUSTFS_WARP_LOG_FILE:-}"
STORAGE_THRESHOLD=85 # stop writing when usage reaches N% (note suggests 80-85)
POLL_INTERVAL=30 # status polling interval (seconds)
CAPACITY_POLL_INTERVAL="${RUSTFS_CAPACITY_POLL_INTERVAL:-2}"
CAPACITY_SAMPLE_TIMEOUT="${RUSTFS_CAPACITY_SAMPLE_TIMEOUT:-3}"
CAPACITY_MIN_FREE_BYTES="${RUSTFS_CAPACITY_MIN_FREE_BYTES:-536870912}"
CAPACITY_MAX_DISK_PERCENT="${RUSTFS_CAPACITY_MAX_DISK_PERCENT:-95}"
WARP_STOP_GRACE="${RUSTFS_WARP_STOP_GRACE:-5}"
CAPACITY_PREVIOUS_SAMPLE=""
CAPACITY_LOG_FILE=""
CAPACITY_EMERGENCY=0
WARP_TRANSPORT_FAILURE_PATTERN='502 Bad Gateway|504 Gateway Time-out|HTTP([^0-9]+)?50(2|4)|status([^0-9]+)?50(2|4)|connection (closed|reset|refused)|unexpected EOF|broken pipe|timeout awaiting response headers|context deadline exceeded|i/o timeout|Client\.Timeout exceeded|The service is unavailable|We encountered an internal error'
# Timeouts (seconds)
REBALANCE_TIMEOUT=86400
DECOMMISSION_TIMEOUT=86400
SERVICE_TIMEOUT=300
DECOMMISSION_RETRIES=3 # auto clear+retry attempts after a failed decommission
DECOMMISSION_RETRY_DELAY=30 # delay between retries (seconds)
REBALANCE_START_RETRIES=6 # rebalance start retries (fleet proof may take ~10-20s after a topology change)
REBALANCE_START_RETRY_DELAY=20 # delay between rebalance start retries (seconds)
# Pool to decommission (zero-based; 0 in the note)
DECOMMISSION_POOL_ID=0
# ==================== Runtime options (set by CLI) ====================
DRY_RUN=0
ASSUME_YES=0
WITH_WARP=0
SKIP_DOWNLOAD=0
FINALIZE_DECOMMISSION=0
PREFLIGHT=0
RESET=0
LOG_FILE=""
SELECTED_STEPS=()
ACTIVE_WARP_PID=""
# Set by run_steps; used by the ERR trap to attribute the failure.
CURRENT_STEP_NUM=""
CURRENT_STEP_DESC=""
# ==================== Helpers ====================
log() { printf '\033[1;36m[INFO]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[WARN]\033[0m %s\n' "$*"; }
die() { printf '\033[1;31m[ERROR]\033[0m %s\n' "$*" >&2; exit 1; }
# Machine-readable line for the workflow report generator. One per step:
# [POOL-STEP] <n> <desc> PASS|FAIL|SKIP
emit_step_result() {
local n="$1" desc="$2" status="$3"
printf '[POOL-STEP] %s %s %s\n' "${n}" "${desc}" "${status}"
}
on_step_err() {
# ERR trap: emit the failing step's result and the overall verdict before
# the shell exits, so the report always shows where the run died.
local rc=$?
[ -n "${CURRENT_STEP_NUM}" ] || return "${rc}"
emit_step_result "${CURRENT_STEP_NUM}" "${CURRENT_STEP_DESC:-step ${CURRENT_STEP_NUM}}" "FAIL"
printf '[POOL-RESULT] FAIL step %s failed\n' "${CURRENT_STEP_NUM}"
return "${rc}"
}
node_rustfs_version() {
# Version reported by the installed rustfs binary on a node, e.g.
# "rustfs 1.0.0-rc.3 (built ...)" -> "1.0.0-rc.3"; falls back to the dpkg
# package version when the binary is not on the ssh PATH.
local node="$1" out
out="$(ssh "${SSH_OPTS[@]}" "${SSH_USER}@${node}" '
if command -v rustfs >/dev/null 2>&1; then
rustfs --version 2>/dev/null || true
elif [ -x /usr/local/bin/rustfs ]; then
/usr/local/bin/rustfs --version 2>/dev/null || true
elif [ -x /opt/rustfs/bin/rustfs ]; then
/opt/rustfs/bin/rustfs --version 2>/dev/null || true
fi
' 2>/dev/null || true)"
if [ -z "${out}" ]; then
out="$(ssh "${SSH_OPTS[@]}" "${SSH_USER}@${node}" \
"dpkg-query -W -f='\${Version}' rustfs 2>/dev/null" 2>/dev/null || true)"
fi
[ -n "${out}" ] || out="unknown"
out="$(printf '%s' "${out}" | head -1)"
if [[ "${out}" == rustfs\ * ]]; then
out="$(printf '%s' "${out}" | awk '{print $2}')"
[ -n "${out}" ] || out="unknown"
fi
printf '%s' "${out}"
}
emit_version_line() {
# [POOL-VERSION] <version> — captured from the first node that has the
# binary installed (after step 2 in a normal run).
local node out
for node in "${NODES[@]}"; do
out="$(node_rustfs_version "${node}")"
if [ "${out}" != "unknown" ]; then
printf '[POOL-VERSION] %s (node %s)\n' "${out}" "${node}"
return 0
fi
done
printf '[POOL-VERSION] unknown\n'
}
confirm() {
# $1: prompt text; bypassed with --yes
if [ "${ASSUME_YES}" -eq 1 ]; then
return 0
fi
printf '\033[1;33m[CONFIRM]\033[0m %s (y/N) ' "$1"
read -r answer
case "${answer}" in
y|Y|yes|YES) return 0 ;;
*) die "cancelled" ;;
esac
}
need_cmd() {
# $1: command name; $2: description
if [ "${DRY_RUN}" -eq 1 ]; then return 0; fi
command -v "$1" >/dev/null 2>&1 || die "missing command: $1 ($2); install it first"
}
normalize_http_endpoint() {
local endpoint="${1%/}" authority port
case "${endpoint}" in
http://*) ;;
https://*) die "HTTPS endpoint is not supported by this test yet: ${endpoint} (warp would require --tls)" ;;
*) die "endpoint must start with http://: ${endpoint}" ;;
esac
authority="${endpoint#http://}"
if ! [[ "${authority}" =~ ^[A-Za-z0-9._-]+(:[1-9][0-9]{0,4})?$ ]]; then
die "endpoint must contain only an HTTP authority (host[:port]): ${endpoint}"
fi
if [[ "${authority}" == *:* ]]; then
port="${authority##*:}"
[ "${port}" -le 65535 ] || die "invalid endpoint port: ${endpoint}"
fi
printf '%s' "${endpoint}"
}
resolve_endpoints() {
local capacity_value
for capacity_value in "${CAPACITY_POLL_INTERVAL}" "${CAPACITY_SAMPLE_TIMEOUT}" "${CAPACITY_MIN_FREE_BYTES}" "${WARP_STOP_GRACE}"; do
[[ "${capacity_value}" =~ ^[1-9][0-9]*$ ]] || die "capacity bounds must be positive integers: ${capacity_value}"
done
[[ "${WARP_CONCURRENT}" =~ ^[1-9][0-9]*$ ]] \
|| die "warp concurrency must be a positive integer: ${WARP_CONCURRENT}"
[[ "${WARP_ROUNDS}" =~ ^[1-9][0-9]*$ ]] \
|| die "warp rounds must be a positive integer: ${WARP_ROUNDS}"
[[ "${STORAGEINFO_PROBE_RETRIES}" =~ ^[1-9][0-9]*$ ]] \
|| die "storageinfo probe retries must be a positive integer: ${STORAGEINFO_PROBE_RETRIES}"
[[ "${STORAGEINFO_PROBE_RETRY_DELAY}" =~ ^[0-9]+$ ]] \
|| die "storageinfo probe retry delay must be a non-negative integer: ${STORAGEINFO_PROBE_RETRY_DELAY}"
ADMIN_ENDPOINT="$(normalize_http_endpoint "${ADMIN_ENDPOINT:-${LEGACY_ENDPOINT}}")"
WARP_ENDPOINT="$(normalize_http_endpoint "${WARP_ENDPOINT:-${LEGACY_ENDPOINT}}")"
if [ -n "${PROXY_ENDPOINT}" ]; then
PROXY_ENDPOINT="$(normalize_http_endpoint "${PROXY_ENDPOINT}")"
fi
if [ -n "${PROXY_STAGE_HOOK}" ]; then
[ -n "${PROXY_ENDPOINT}" ] || die "a proxy stage hook requires --proxy-endpoint"
[ -x "${PROXY_STAGE_HOOK}" ] || die "proxy stage hook is not executable: ${PROXY_STAGE_HOOK}"
fi
[ "${#NODE_ENDPOINTS[@]}" -ge "${#NODES[@]}" ] \
|| die "RUSTFS_NODE_ENDPOINTS must provide at least ${#NODES[@]} direct node endpoints"
local i
for ((i=0; i<${#NODE_ENDPOINTS[@]}; i++)); do
NODE_ENDPOINTS[i]="$(normalize_http_endpoint "${NODE_ENDPOINTS[i]}")"
done
}
endpoint_authority() {
local endpoint="$1"
printf '%s' "${endpoint#http://}"
}
cleanup_runtime() {
if [ -n "${ACTIVE_WARP_PID}" ]; then
kill "${ACTIVE_WARP_PID}" 2>/dev/null || true
fi
rm -f "${ADMIN_API_CODE_FILE}" "${ADMIN_API_TIMING_FILE}" \
"${ADMIN_API_CODE_FILE}.headers" "${PROXY_API_CODE_FILE}.headers" \
"${PROXY_API_CODE_FILE}" "${PROXY_API_TIMING_FILE}" \
"${ADMIN_ANOMALY_FILE}" "${PROXY_ANOMALY_FILE}"
}
# ==================== Admin API (SigV4-signed) ====================
sha256_hex() {
# $1: ascii data
printf '%s' "$1" | openssl dgst -sha256 -hex 2>/dev/null | awk '{print $NF}'
}
hmac_sha256_hex() {
# $1: key in hex, $2: ascii data
printf '%s' "$2" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$1" -hex 2>/dev/null | awk '{print $NF}'
}
hex_of_ascii() {
# $1: ascii string -> hex
printf '%s' "$1" | od -An -vtx1 | tr -d ' \n'
}
# Sort a "k=v&k2=v2" query string by key (values are used verbatim, matching
# the RustFS signer). The same canonical form is used in the URL and in the
# SigV4 canonical request so the server-side verification always agrees.
# SigV4 URI-encode one query name or value: keep RFC 3986 unreserved
# characters, percent-encode every other byte as uppercase %XX.
sigv4_uri_encode() {
local LC_ALL=C
local s="$1" out="" i c
for (( i = 0; i < ${#s}; i++ )); do
c="${s:i:1}"
case "${c}" in
[A-Za-z0-9_.~-]) out+="${c}" ;;
*) out+="$(printf '%%%02X' "$(( $(printf '%d' "'${c}") & 255 ))")" ;;
esac
done
printf '%s' "${out}"
}
canonical_query() {
local q="$1"
[ -z "${q}" ] && return 0
# The server percent-decodes the raw query and re-encodes every pair for
# the canonical request (name and value, RFC 3986 unreserved only), and a
# valueless param (?flag) comes back as "flag=". Callers pass raw values,
# so encode here and send the same encoded string on the wire; anything
# signed verbatim (e.g. "@" in an access key, ":" in an ARN) fails with
# SignatureDoesNotMatch.
local pairs=() pair name value
IFS='&' read -r -a pairs <<< "${q}"
for pair in "${pairs[@]}"; do
[ -n "${pair}" ] || continue
name="${pair%%=*}"
if [ "${name}" = "${pair}" ]; then value=""; else value="${pair#*=}"; fi
printf '%s=%s\n' "$(sigv4_uri_encode "${name}")" "$(sigv4_uri_encode "${value}")"
done | LC_ALL=C sort | paste -sd '&' -
}
# Issue a SigV4 API request. Prints the response body on stdout and writes the
# HTTP status (000 on transport failure) and curl timing data to caller-owned
# files so direct and proxy probes cannot overwrite each other.
api_request() {
# $1: endpoint, $2: status file, $3: timing file, $4: method, $5: path, $6: query string
local endpoint="$1" code_file="$2" timing_file="$3" method="$4" path="$5" query="$6"
local amz_date date_stamp host_port
local canonical_headers signed_headers canonical_request string_to_sign
local scope k_date k_region k_service k_signing signature auth
local url tmp header_tmp metrics code connect_time starttransfer_time total_time curl_exit=0
if [ "${DRY_RUN}" -eq 1 ]; then
log "DRY-RUN: API ${method} ${endpoint}${path}${query:+?${query}}"
printf '200' > "${code_file}"
: > "${code_file}.headers"
printf 'http=200 connect=0 ttfb=0 total=0 curl_exit=0' > "${timing_file}"
return 0
fi
host_port="$(endpoint_authority "${endpoint}")"
amz_date="$(date -u +%Y%m%dT%H%M%SZ)"
date_stamp="${amz_date:0:8}"
query="$(canonical_query "${query}")"
canonical_headers="host:${host_port}
x-amz-content-sha256:UNSIGNED-PAYLOAD
x-amz-date:${amz_date}
"
signed_headers="host;x-amz-content-sha256;x-amz-date"
canonical_request="${method}
${path}
${query}
${canonical_headers}
${signed_headers}
UNSIGNED-PAYLOAD"
scope="${date_stamp}/${SIGV4_REGION}/${SIGV4_SERVICE}/aws4_request"
string_to_sign="AWS4-HMAC-SHA256
${amz_date}
${scope}
$(sha256_hex "${canonical_request}")"
k_date="$(hmac_sha256_hex "$(hex_of_ascii "AWS4${SECRET_KEY}")" "${date_stamp}")"
k_region="$(hmac_sha256_hex "${k_date}" "${SIGV4_REGION}")"
k_service="$(hmac_sha256_hex "${k_region}" "${SIGV4_SERVICE}")"
k_signing="$(hmac_sha256_hex "${k_service}" "aws4_request")"
signature="$(hmac_sha256_hex "${k_signing}" "${string_to_sign}")"
auth="AWS4-HMAC-SHA256 Credential=${ACCESS_KEY}/${scope}, SignedHeaders=${signed_headers}, Signature=${signature}"
url="${endpoint}${path}${query:+?${query}}"
tmp="$(mktemp)"
header_tmp="$(mktemp)"
if metrics="$(curl -sS --max-time "${API_REQUEST_TIMEOUT}" -o "${tmp}" -D "${header_tmp}" \
-w $'%{http_code}\t%{time_connect}\t%{time_starttransfer}\t%{time_total}' \
-H "Host: ${host_port}" \
-H "x-amz-content-sha256: UNSIGNED-PAYLOAD" \
-H "x-amz-date: ${amz_date}" \
-H "Authorization: ${auth}" \
-X "${method}" "${url}")"; then
curl_exit=0
else
curl_exit=$?
fi
IFS=$'\t' read -r code connect_time starttransfer_time total_time <<<"${metrics:-}"
if [ "${curl_exit}" -ne 0 ]; then
code="000"
fi
code="${code:-000}"
printf '%s' "${code}" > "${code_file}"
# Only retain diagnostic response headers. Never publish Authorization,
# cookies or the full AWS debug stream to collect an error cause.
awk 'tolower($0) ~ /^(http\/|x-rustfs-error-cause:|x-amz-request-id:|x-amz-id-2:|retry-after:)/ {sub(/\r$/, ""); print}' \
"${header_tmp}" > "${code_file}.headers"
printf 'http=%s connect=%s ttfb=%s total=%s curl_exit=%s' \
"${code}" "${connect_time:-unknown}" "${starttransfer_time:-unknown}" \
"${total_time:-unknown}" "${curl_exit}" > "${timing_file}"
cat "${tmp}"
rm -f "${tmp}" "${header_tmp}"
}
admin_api() {
api_request "${ADMIN_ENDPOINT}" "${ADMIN_API_CODE_FILE}" "${ADMIN_API_TIMING_FILE}" "$@"
}
proxy_api() {
api_request "${PROXY_ENDPOINT}" "${PROXY_API_CODE_FILE}" "${PROXY_API_TIMING_FILE}" "$@"
}
# Read the HTTP status written by the last admin_api call
admin_api_code() {
cat "${ADMIN_API_CODE_FILE}"
}
admin_api_timing() {
cat "${ADMIN_API_TIMING_FILE}"
}
admin_api_headers() {
[ ! -f "${ADMIN_API_CODE_FILE}.headers" ] || cat "${ADMIN_API_CODE_FILE}.headers"
}
proxy_api_code() {
cat "${PROXY_API_CODE_FILE}"
}
proxy_api_timing() {
cat "${PROXY_API_TIMING_FILE}"
}
# Run an admin API request and fail loudly (with the full response body) on a
# non-success status. Prints the body on stdout.
admin_api_assert() {
# $1: method, $2: path, $3: query, $4: description
local method="$1" path="$2" query="$3" desc="$4" body code
body="$(admin_api "${method}" "${path}" "${query}")"
code="$(admin_api_code)"
if [ "${code}" != "200" ] && [ "${code}" != "201" ] && [ "${code}" != "204" ]; then
printf '\033[1;31m[ERROR]\033[0m %s failed (HTTP %s)\n' "${desc}" "${code}" >&2
printf '%s\n' "${body}" >&2
die "admin API ${method} ${path} -> HTTP ${code}"
fi
printf '%s' "${body}"
}
# Build the GitHub release download URL from a release tag.
# "1.0.0-rc.3" -> https://github.com/rustfs/rustfs/releases/download/1.0.0-rc.3/rustfs_1.0.0.rc.3_amd64.deb
build_package_url() {
local tag="${RUSTFS_VERSION#v}" asset
asset="${tag//-/.}"
printf 'https://github.com/rustfs/rustfs/releases/download/%s/rustfs_%s_%s.deb' "${tag}" "${asset}" "${ARCH}"
}
resolve_package_url() {
if [ -n "${PACKAGE_URL}" ]; then
printf '%s' "${PACKAGE_URL}"
else
build_package_url
fi
}
# Run a remote script on a single node (script is read from stdin)
run_remote() {
local node="$1"
local script
script="$(cat)"
if [ "${DRY_RUN}" -eq 1 ]; then
log "DRY-RUN: ssh ${SSH_USER}@${node} <<'REMOTE'"
printf '%s\n' "${script}" \
| sed -E 's/^(RUSTFS_(ACCESS_KEY|SECRET_KEY)=).*/\1[REDACTED]/' \
| sed 's/^/ | /'
log "DRY-RUN: ----"
return 0
fi
log "==> ${node}: executing remote script"
ssh "${SSH_OPTS[@]}" "${SSH_USER}@${node}" 'bash -s' <<<"${script}"
}
# Run the same remote script on all nodes in parallel (script from stdin)
run_remote_all() {
local script
script="$(cat)"
local pids=() i=0 fail=0
for node in "${NODES[@]}"; do
if [ "${DRY_RUN}" -eq 1 ]; then
log "DRY-RUN: ssh ${SSH_USER}@${node} <<'REMOTE'"
printf '%s\n' "${script}" \
| sed -E 's/^(RUSTFS_(ACCESS_KEY|SECRET_KEY)=).*/\1[REDACTED]/' \
| sed 's/^/ | /'
log "DRY-RUN: ----"
else
log "==> ${node}: executing remote script"
( ssh "${SSH_OPTS[@]}" "${SSH_USER}@${node}" 'bash -s' <<<"${script}" ) &
pids[$i]=$!
i=$((i+1))
fi
done
if [ "${#pids[@]}" -gt 0 ]; then
for pid in "${pids[@]}"; do
wait "${pid}" || fail=1
done
fi
[ "${fail}" -eq 0 ] || die "one or more nodes failed"
}
# Wait for the systemd service to become active on a node
wait_service_active() {
local node="$1" waited=0
if [ "${DRY_RUN}" -eq 1 ]; then
log "DRY-RUN: waiting for ${RUSTFS_SERVICE} on ${node} to become active"
return 0
fi
while [ "${waited}" -lt "${SERVICE_TIMEOUT}" ]; do
if ssh "${SSH_OPTS[@]}" "${SSH_USER}@${node}" \
"systemctl is-active --quiet ${RUSTFS_SERVICE}" 2>/dev/null; then
log "${node}: ${RUSTFS_SERVICE} is active"
return 0
fi
sleep 5
waited=$((waited + 5))
done
diagnose_node_start_failure "${node}"
die "${node}: timed out waiting for ${RUSTFS_SERVICE} (${SERVICE_TIMEOUT}s)"
}
# Known server-side issues the test can hit. Format:
# "<error signature>|<tracking>|<hint>"
KNOWN_SERVER_ISSUES=(
"pool activation requires a live fleet capability proof|rustfs/backlog#2031|server-side cold-start recovery is covered by this PR; if this appears, collect node journals and treat it as a regression"
)
# Print a hint when $1 matches a known server-side issue signature.
hint_server_issue() {
local text="$1" entry sig tracking hint
for entry in "${KNOWN_SERVER_ISSUES[@]}"; do
sig="${entry%%|*}"
tracking="${entry#*|}"
hint="${tracking#*|}"
tracking="${tracking%%|*}"
if printf '%s' "${text}" | grep -qiF "${sig}"; then
printf '\033[1;33m[KNOWN SERVER ISSUE]\033[0m %s (%s): %s\n' "${sig}" "${tracking}" "${hint}" >&2
return 0
fi
done
return 1
}
# Fetch the journal tail from a node whose service failed to start and
# annotate known server-side issues.
diagnose_node_start_failure() {
local node="$1" journal
if ! journal="$(ssh "${SSH_OPTS[@]}" "${SSH_USER}@${node}" \
"SUDO=\"\"; [ \"\$(id -u)\" -ne 0 ] && SUDO=\"sudo -n\"; \${SUDO} journalctl -u ${RUSTFS_SERVICE} --no-pager -n 60 2>/dev/null || true")"; then
journal="unable to collect journal (SSH command failed)"
fi
printf '%s\n' "--- ${node}: ${RUSTFS_SERVICE} journal (last 60 lines) ---" >&2
printf '%s\n' "${journal}" >&2
hint_server_issue "${journal}" || true
}
# Generate the /etc/default/rustfs content
rustfs_config_body() {
local volumes="$1"
cat <<EOF
RUSTFS_ACCESS_KEY=${ACCESS_KEY}
RUSTFS_SECRET_KEY=${SECRET_KEY}
RUSTFS_VOLUMES="${volumes}"
RUSTFS_ADDRESS="${RUSTFS_ADDRESS}"
RUSTFS_CONSOLE_ADDRESS="${RUSTFS_CONSOLE_ADDRESS}"
RUSTFS_CONSOLE_ENABLE=${RUSTFS_CONSOLE_ENABLE}
RUSTFS_OBS_LOGGER_LEVEL=${RUSTFS_OBS_LOGGER_LEVEL}
RUSTFS_OBS_LOG_DIRECTORY="${RUSTFS_OBS_LOG_DIRECTORY}"
EOF
if [ "${RUSTFS_POOL_VALIDATION_MODE:-0}" = 1 ]; then
printf 'RUST_LOG=warn,rustfs::ecstore=info,rustfs::rebalance=debug\n'
printf 'RUSTFS_SCANNER_ENABLED=true\nRUSTFS_SCANNER_START_DELAY_SECS=0\nRUSTFS_SCANNER_CYCLE=2\n'
printf 'HTTP_PROXY=\nHTTPS_PROXY=\nALL_PROXY=\nhttp_proxy=\nhttps_proxy=\nall_proxy=\n'
fi
}
# Expand a volume expression's {N...M} range into concrete local paths, e.g.:
# http://rustfs-node1:9000/data/rustfs{1...4}/mnmd
# -> /data/rustfs1/mnmd /data/rustfs2/mnmd /data/rustfs3/mnmd /data/rustfs4/mnmd
volume_dirs() {
local volumes="$1" expr path prefix suffix i start end
for expr in ${volumes}; do
path="${expr#*://}"
path="${path#*/}"
path="/${path}"
if [[ "${path}" =~ \{([0-9]+)\.\.\.([0-9]+)\} ]]; then
start="${BASH_REMATCH[1]}"
end="${BASH_REMATCH[2]}"
prefix="${path%%\{*}"
suffix="${path#*\}}"
for ((i=start; i<=end; i++)); do
printf '%s%s%s\n' "${prefix}" "${i}" "${suffix}"
done
else
printf '%s\n' "${path}"
fi
done
}
# Ensure the volume directories exist on a node and are owned by the service user
ensure_volume_dirs() {
local node="$1" volumes="$2"
local -a dirs
dirs=()
while IFS= read -r d; do dirs+=("${d}"); done < <(volume_dirs "${volumes}" | sort -u)
log "${node}: ensuring data dirs exist and are owned by ${RUSTFS_USER} (${dirs[*]})"
{
printf 'set -euo pipefail\n'
printf 'SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO="sudo -n"\n'
for d in "${dirs[@]}"; do
printf '${SUDO} mkdir -p %s\n' "${d}"
printf '${SUDO} chown -R %s:%s %s\n' "${RUSTFS_USER}" "${RUSTFS_USER}" "${d}"
done
} | run_remote "${node}"
}
# Write the RustFS config on a single node (with a timestamped backup first)
write_rustfs_config() {
local node="$1" volumes="$2"
local body
body="$(rustfs_config_body "${volumes}")"
log "${node}: writing config ${RUSTFS_CONFIG_FILE} (volumes=${volumes})"
{
printf 'set -euo pipefail\n'
printf 'SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO="sudo -n"\n'
printf 'if [ -f %s ]; then ${SUDO} cp -a %s %s.bak.$(date +%%Y%%m%%d%%H%%M%%S); fi\n' \
"${RUSTFS_CONFIG_FILE}" "${RUSTFS_CONFIG_FILE}" "${RUSTFS_CONFIG_FILE}"
printf '%s tee %s >/dev/null <<RUSTFS_EOF\n' '${SUDO}' "${RUSTFS_CONFIG_FILE}"
printf '%s' "${body}"
printf '\nRUSTFS_EOF\n'
printf '${SUDO} systemctl daemon-reload\n'
} | run_remote "${node}"
}
# Start/stop the service on one node (uses sudo automatically when not root)
service_action() {
local action="$1" node="$2"
log "${node}: systemctl ${action} ${RUSTFS_SERVICE}"
if [ "${DRY_RUN}" -eq 1 ]; then return 0; fi
local remote_command
if [ "${action}" = "stop" ]; then
remote_command="if ! systemctl cat ${RUSTFS_SERVICE} >/dev/null 2>&1; then echo '${RUSTFS_SERVICE} is not installed; stop skipped'; exit 0; fi; if [ \"\$(id -u)\" -ne 0 ]; then sudo -n systemctl stop ${RUSTFS_SERVICE}; else systemctl stop ${RUSTFS_SERVICE}; fi"
else
remote_command="if [ \"\$(id -u)\" -ne 0 ]; then sudo -n systemctl ${action} ${RUSTFS_SERVICE}; else systemctl ${action} ${RUSTFS_SERVICE}; fi"
fi
if ! ssh "${SSH_OPTS[@]}" "${SSH_USER}@${node}" \
"${remote_command}"; then
if [ "${action}" = "start" ]; then
diagnose_node_start_failure "${node}"
fi
die "${node}: systemctl ${action} failed"
fi
}
service_action_all() {
local action="$1" pids=() i=0 fail=0
if [ "${DRY_RUN}" -eq 1 ]; then
for node in "${NODES[@]}"; do
service_action "${action}" "${node}"
done
return 0
fi
for node in "${NODES[@]}"; do
service_action "${action}" "${node}" &
pids[$i]=$!
i=$((i+1))
done
if [ "${#pids[@]}" -gt 0 ]; then
for pid in "${pids[@]}"; do
wait "${pid}" || fail=1
done
fi
[ "${fail}" -eq 0 ] || die "systemctl ${action} failed on one or more nodes"
}
# Start nodes in parallel. With multiple pools all nodes MUST start
# simultaneously, otherwise the first node fails with "not first disk".
start_and_wait_nodes() {
local nodes=("$@") pids=() i=0 fail=0
for node in "${nodes[@]}"; do
service_action start "${node}" &
pids[$i]=$!
i=$((i+1))
done
if [ "${#pids[@]}" -gt 0 ]; then
for pid in "${pids[@]}"; do
wait "${pid}" || fail=1
done
fi
[ "${fail}" -eq 0 ] || die "systemctl start failed on one or more nodes"
for node in "${nodes[@]}"; do
wait_service_active "${node}"
done
}
wait_node_ready() {
local index="$1" endpoint="${NODE_ENDPOINTS[$1]}" waited=0
if [ "${DRY_RUN}" -eq 1 ]; then
log "DRY-RUN: waiting for ${NODES[$index]} readiness at ${endpoint}/health/ready"
return 0
fi
while [ "${waited}" -lt "${SERVICE_TIMEOUT}" ]; do
if curl -fsS --connect-timeout 5 --max-time 10 "${endpoint}/health/ready" >/dev/null 2>&1; then
log "${NODES[$index]}: ready at ${endpoint}"
return 0
fi
sleep 5
waited=$((waited + 5))
done
diagnose_node_start_failure "${NODES[$index]}"
die "${NODES[$index]}: timed out waiting for ${endpoint}/health/ready (${SERVICE_TIMEOUT}s)"
}
assert_node_not_ready() {
local index="$1" endpoint="${NODE_ENDPOINTS[$1]}" code
if [ "${DRY_RUN}" -eq 1 ]; then
log "DRY-RUN: asserting ${NODES[$index]} is not ready at ${endpoint}/health/ready"
return 0
fi
code="$(curl -sS --connect-timeout 2 --max-time 5 -o /dev/null -w '%{http_code}' \
"${endpoint}/health/ready" 2>/dev/null)" || code="000"
case "${code}" in
2??) die "${NODES[$index]} unexpectedly reports ready at ${endpoint} during this topology stage" ;;
*) log "${NODES[$index]}: intentionally inactive (ready probe HTTP ${code})" ;;
esac
}
# A topology stage is usable only after every intended member is directly
# ready and every future member is still unavailable. This prevents a shared
# proxy from hiding stale processes or routing to nodes the test has not yet
# activated.
verify_stage_readiness() {
local active_count="$1" i
[ "${active_count}" -le "${#NODES[@]}" ] || die "invalid active node count: ${active_count}"
for ((i=0; i<active_count; i++)); do
wait_node_ready "${i}"
done
for ((i=active_count; i<${#NODES[@]}; i++)); do
assert_node_not_ready "${i}"
done
}
configure_proxy_stage() {
local active_count="$1"
[ -n "${PROXY_STAGE_HOOK}" ] || return 0
local -a active_endpoints=("${NODE_ENDPOINTS[@]:0:active_count}")
if [ "${DRY_RUN}" -eq 1 ]; then
log "DRY-RUN: ${PROXY_STAGE_HOOK} apply ${active_count} ${active_endpoints[*]}"
return 0
fi
log "configuring the dedicated proxy for ${active_count} active node(s): ${active_endpoints[*]}"
"${PROXY_STAGE_HOOK}" apply "${active_count}" "${active_endpoints[@]}"
}
record_endpoint_anomaly() {
local file="$1" message="$2"
printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${message}" >> "${file}"
}
log_storageinfo_failure() {
local label="$1" endpoint="$2" attempt="$3" code="$4" timing="$5" body="$6"
printf '\033[1;31m[ERROR]\033[0m %s %s storageinfo attempt %s failed at %s (HTTP %s; %s)\n' \
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${label}" "${attempt}" "${endpoint}" "${code}" "${timing}" >&2
printf '%s\n' "${body}" >&2
}
log_storageinfo_success() {
local label="$1" endpoint="$2" attempt="$3" code="$4" timing="$5" body="$6"
printf '\033[1;36m[PROBE]\033[0m %s %s storageinfo attempt %s succeeded at %s (HTTP %s; %s)\n' \
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${label}" "${attempt}" "${endpoint}" "${code}" "${timing}" >&2
printf '%s\n' "${body}" >&2
}
# Print a successful storageinfo response on stdout. Failures are recorded in
# a sticky file before bounded retries so a later 200 cannot turn the run into
# a clean pass.
storageinfo_with_retry() {
local kind="$1" endpoint request_fn code_fn timing_fn anomaly_file label
local attempt=1 body code timing
case "${kind}" in
admin)
endpoint="${ADMIN_ENDPOINT}"
request_fn=admin_api
code_fn=admin_api_code
timing_fn=admin_api_timing
anomaly_file="${ADMIN_ANOMALY_FILE}"
label="direct admin"
;;
proxy)
endpoint="${PROXY_ENDPOINT}"
request_fn=proxy_api
code_fn=proxy_api_code
timing_fn=proxy_api_timing
anomaly_file="${PROXY_ANOMALY_FILE}"
label="proxy"
;;
*) die "unknown storageinfo probe kind: ${kind}" ;;
esac
while [ "${attempt}" -le "${STORAGEINFO_PROBE_RETRIES}" ]; do
body="$(${request_fn} GET /rustfs/admin/v3/storageinfo "")"
code="$(${code_fn})"
timing="$(${timing_fn})"
if [ "${code}" = "200" ]; then
log_storageinfo_success "${label}" "${endpoint}" \
"${attempt}/${STORAGEINFO_PROBE_RETRIES}" "${code}" "${timing}" "${body}"
printf '%s' "${body}"
return 0
fi
log_storageinfo_failure "${label}" "${endpoint}" "${attempt}/${STORAGEINFO_PROBE_RETRIES}" \
"${code}" "${timing}" "${body}"
record_endpoint_anomaly "${anomaly_file}" \
"${label} storageinfo ${endpoint} HTTP ${code} ${timing}"
case "${code}" in
000|502|503|504) ;;
*) return 1 ;;
esac
if [ "${attempt}" -lt "${STORAGEINFO_PROBE_RETRIES}" ]; then
sleep "${STORAGEINFO_PROBE_RETRY_DELAY}"
fi
attempt=$((attempt + 1))
done
return 1
}
probe_proxy_storageinfo() {
local body
[ -n "${PROXY_ENDPOINT}" ] || return 0
if ! body="$(storageinfo_with_retry proxy)"; then
warn "proxy storageinfo remained unavailable; continuing the direct pool flow to preserve diagnostics" >&2
return 0
fi
if ! printf '%s' "${body}" | jq -e '(.info.disks // .disks // []) | length' >/dev/null 2>&1; then
printf '\033[1;31m[ERROR]\033[0m proxy storageinfo returned HTTP 200 with an unexpected body:\n%s\n' "${body}" >&2
record_endpoint_anomaly "${PROXY_ANOMALY_FILE}" \
"proxy storageinfo ${PROXY_ENDPOINT} returned HTTP 200 with invalid JSON"
fi
}
assert_no_endpoint_anomalies() {
local failed=0
if [ -s "${ADMIN_ANOMALY_FILE}" ]; then
printf '%s\n' "--- recovered or persistent direct admin anomalies ---" >&2
cat "${ADMIN_ANOMALY_FILE}" >&2
failed=1
fi
if [ -s "${PROXY_ANOMALY_FILE}" ]; then
printf '%s\n' "--- recovered or persistent proxy anomalies ---" >&2
cat "${PROXY_ANOMALY_FILE}" >&2
failed=1
fi
[ "${failed}" -eq 0 ] \
|| die "endpoint anomalies occurred; retries preserved diagnostics but do not qualify as a clean pass"
}
# Storage sampling while a writer is active must be bounded: no long proxy
# probe or retry loop can delay the capacity stop decision.
storage_capacity_sample() {
local body sample_time
if [ "${DRY_RUN}" -eq 1 ]; then
log "DRY-RUN: GET ${ADMIN_ENDPOINT}/rustfs/admin/v3/storageinfo (storage usage)"
printf '{"usage_percent":0}\n'
return 0
fi
sample_time="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
printf '\033[1;36m[PROBE]\033[0m %s storageinfo sample direct=%s proxy=%s\n' \
"${sample_time}" "${ADMIN_ENDPOINT}" "${PROXY_ENDPOINT:-disabled}" >&2
body="$(API_REQUEST_TIMEOUT="${CAPACITY_SAMPLE_TIMEOUT}" STORAGEINFO_PROBE_RETRIES=1 storageinfo_with_retry admin)" \
|| return 1
printf '%s' "${body}" | python3 "${POOL_SCRIPT_DIR}/scripts/storage_capacity.py" sample
}
storage_usage_percent() {
storage_capacity_sample | jq -r '.usage_percent'
}
assess_capacity() {
local sample="$1" threshold="$2" assessment
assessment="$(printf '%s' "${sample}" | python3 "${POOL_SCRIPT_DIR}/scripts/storage_capacity.py" assess \
--previous "${CAPACITY_PREVIOUS_SAMPLE}" --threshold "${threshold}" \
--max-disk-percent "${CAPACITY_MAX_DISK_PERCENT}" --min-free-bytes "${CAPACITY_MIN_FREE_BYTES}" \
--object-size "${WARP_OBJ_SIZE}" --concurrent "${WARP_CONCURRENT}" \
--poll-seconds "${CAPACITY_POLL_INTERVAL}" --stop-seconds "$((WARP_STOP_GRACE + 3))" \
--sample-timeout "${CAPACITY_SAMPLE_TIMEOUT}")" || return 1
[ -z "${CAPACITY_LOG_FILE}" ] || printf '%s\n' "${assessment}" >> "${CAPACITY_LOG_FILE}"
printf '%s' "${assessment}"
}
check_capacity_before_write() {
local assessment
CAPACITY_PREVIOUS_SAMPLE="$(storage_capacity_sample)" || return 1
assessment="$(assess_capacity "${CAPACITY_PREVIOUS_SAMPLE}" "${STORAGE_THRESHOLD}")" || return 1
if [ "$(printf '%s' "${assessment}" | jq -r '.action')" = capacity_guard ]; then
warn "[ENVIRONMENT-CAPACITY] refusing to start warp: ${assessment}"
return 4
fi
}
# Poll storage usage until it reaches the threshold
monitor_storage() {
local threshold="${1:-${STORAGE_THRESHOLD}}" warp_pid="${2:-}" sample assessment action usage
log "monitoring storage usage until ${threshold}% (every ${CAPACITY_POLL_INTERVAL}s, with per-disk reserves)"
while :; do
sample="$(storage_capacity_sample)" || return 1
assessment="$(assess_capacity "${sample}" "${threshold}")" || return 1
CAPACITY_PREVIOUS_SAMPLE="${sample}"
usage="$(printf '%s' "${assessment}" | jq -r '.usage_percent')"
action="$(printf '%s' "${assessment}" | jq -r '.action')"
log "capacity sample: ${assessment}"
if [ "${action}" = capacity_guard ]; then
[ "$(printf '%s' "${assessment}" | jq -r '.emergency')" != true ] || CAPACITY_EMERGENCY=1
warn "[ENVIRONMENT-CAPACITY] stopping before a disk exhausts its reserved space"
return 4
fi
[ "${action}" != target_reached ] || break
if [ -n "${warp_pid}" ] && ! kill -0 "${warp_pid}" 2>/dev/null; then
warn "warp finished at ${usage}%, below the required storage threshold of ${threshold}%"
return 3
fi
sleep "${CAPACITY_POLL_INTERVAL}"
done
log "storage usage reached ${usage}%, stopping writes"
}
warp_log_has_transport_failure() {
local warp_log="$1"
grep -Eiq "${WARP_TRANSPORT_FAILURE_PATTERN}" "${warp_log}"
}
report_warp_errors() {
local warp_log="$1" slowdown_count
[ -r "${warp_log}" ] || die "warp log is unavailable: ${warp_log}"
slowdown_count="$(grep -Eic 'SlowDown|foreground write concurrency limit reached' "${warp_log}" || true)"
if [ "${slowdown_count}" -gt 0 ]; then
log "warp recorded ${slowdown_count} admission SlowDown response(s); capacity tuning remains tracked separately"
fi
if warp_log_has_transport_failure "${warp_log}"; then
printf '\033[1;31m[ERROR]\033[0m warp encountered forbidden proxy/transport failures:\n' >&2
grep -Ein "${WARP_TRANSPORT_FAILURE_PATTERN}" "${warp_log}" | head -n 50 >&2 || true
return 1
fi
return 0
}
# Verify the expected number of pools via the admin API (JSON + jq assertions)
verify_pools() {
local expected="$1"
local body code count nonactive
log "verifying pools via admin API (expect exactly ${expected} active): GET ${ADMIN_ENDPOINT}/rustfs/admin/v3/pools/list"
if [ "${DRY_RUN}" -eq 1 ]; then return 0; fi
body="$(admin_api GET /rustfs/admin/v3/pools/list "")"
code="$(admin_api_code)"
if [ "${code}" != "200" ]; then
printf '\033[1;31m[ERROR]\033[0m pools/list returned HTTP %s\n' "${code}" >&2
printf '%s\n' "${body}" >&2
die "pools/list failed"
fi
if ! count="$(printf '%s' "${body}" | jq -e 'length' 2>/dev/null)"; then
printf '\033[1;31m[ERROR]\033[0m pools/list returned an unexpected (non-JSON) body:\n%s\n' "${body}" >&2
die "pools/list response could not be parsed as JSON"