-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathrun.sh
More file actions
executable file
·1576 lines (1349 loc) · 47.2 KB
/
run.sh
File metadata and controls
executable file
·1576 lines (1349 loc) · 47.2 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
#!/bin/bash
# Default inputs
WARMUP_OPCODES_PATH="warmup-tests"
CLIENTS="nethermind,geth,reth,besu,erigon,nimbus,ethrex"
RUNS=1
OPCODES_WARMUP_COUNT=1
FILTER=""
IMAGES='{"nethermind":"default","geth":"default","reth":"default","erigon":"default","besu":"default","nimbus":"default","ethrex":"default"}'
EXECUTIONS_FILE="executions.json"
TEST_PATHS_JSON=""
LEGACY_TEST_PATH="eest_tests"
LEGACY_GENESIS_PATH="zkevmgenesis.json"
NETWORK=""
SNAPSHOT_ROOT="snapshots"
OVERLAY_TMP_ROOT="overlay-runtime"
USE_SNAPSHOT_BACKEND=false
SNAPSHOT_BACKEND="overlay"
ZFS_RUNTIME_DATASET_ROOT="gasbench-runtime"
ZFS_SNAPSHOT_PREFIX="gasbench_tmp"
PREPARATION_RESULTS_DIR="prepresults"
RESTART_BEFORE_TESTING=false
SKIP_FORKCHOICE=false
FORK_NAME="osaka"
SKIP_EMPTY=true
RPC_READINESS_MAX_ATTEMPTS="${RPC_READINESS_MAX_ATTEMPTS:-50}"
OVERLAY_MOUNT_EXTRA_OPTS="${OVERLAY_MOUNT_EXTRA_OPTS:-}"
OVERLAY_USE_VOLATILE="${OVERLAY_USE_VOLATILE:-false}"
EXTRA_CLIENT_FLAGS=""
# Prevent inherited low API pin from older docker clients/wrappers.
unset DOCKER_API_VERSION
if [ -f "scripts/common/wait_for_rpc.sh" ]; then
# shellcheck source=/dev/null
source "scripts/common/wait_for_rpc.sh"
fi
if [ -f "scripts/common/docker_compose.sh" ]; then
# shellcheck source=/dev/null
source "scripts/common/docker_compose.sh"
fi
if ! declare -f compose_cmd >/dev/null 2>&1; then
compose_cmd() { docker compose "$@"; }
fi
if ! declare -f docker_cmd >/dev/null 2>&1; then
docker_cmd() { docker "$@"; }
fi
if ! declare -f resolve_docker_bin >/dev/null 2>&1; then
resolve_docker_bin() { command -v docker 2>/dev/null || true; }
fi
if ! declare -f compose_detect >/dev/null 2>&1; then
compose_detect() { command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; }
fi
declare -A ACTIVE_OVERLAY_MOUNTS
declare -A ACTIVE_OVERLAY_UPPERS
declare -A ACTIVE_OVERLAY_WORKS
declare -A ACTIVE_OVERLAY_ROOTS
declare -A ACTIVE_OVERLAY_CLIENTS
declare -A ACTIVE_ZFS_DATASETS
declare -A ACTIVE_ZFS_SNAPSHOTS
declare -A ACTIVE_ZFS_MOUNTS
declare -A ACTIVE_ZFS_CLIENTS
declare -A RUNNING_CLIENTS
abspath() {
python3 - <<'PY' "$1"
import os
import sys
print(os.path.abspath(sys.argv[1]))
PY
}
is_stateful_directory() {
local dir="$1"
[ -d "$dir" ] || return 1
[ -d "$dir/testing" ] || return 1
return 0
}
collect_stateful_directory() {
local dir="$1"
python3 - <<'PY' "$dir"
import sys
from pathlib import Path
root = Path(sys.argv[1])
if not root.exists():
sys.exit(0)
def try_append(path, bucket):
if path.is_file() and path.suffix == ".txt":
bucket.append(str(path))
ordered = []
for name in ("gas-bump.txt", "funding.txt", "setup-global-test.txt"):
try_append(root / name, ordered)
phase_to_files = {}
for phase in ("setup", "testing", "cleanup"):
phase_dir = root / phase
per_name = {}
if phase_dir.is_dir():
for file in sorted(phase_dir.rglob("*.txt")):
# If multiple files with the same stem exist (legacy leftovers),
# keep a deterministic choice.
existing = per_name.get(file.stem)
if existing is None or str(file) < str(existing):
per_name[file.stem] = file
phase_to_files[phase] = per_name
scenario_names = sorted(
set(phase_to_files["setup"].keys())
| set(phase_to_files["testing"].keys())
| set(phase_to_files["cleanup"].keys())
)
for name in scenario_names:
for phase in ("setup", "testing", "cleanup"):
path = phase_to_files[phase].get(name)
if path is not None:
ordered.append(str(path))
elif phase == "testing":
sys.stderr.write(f"[WARN] Missing {phase} file for scenario {name}\n")
for name in ("teardown-global-test.txt", "current-last-global-test.txt"):
try_append(root / name, ordered)
extra_root = []
for file in sorted(root.glob("*.txt")):
extra_root.append(str(file))
final = []
seen = set()
for path in ordered + extra_root:
if path not in seen:
seen.add(path)
final.append(path)
# Ensure a trailing NUL so bash read -d '' doesn't drop the last entry.
if final:
sys.stdout.write("\0".join(final) + "\0")
PY
}
dir_has_content() {
local dir="$1"
[ -d "$dir" ] || return 1
find "$dir" -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null | grep -q .
}
resolve_snapshot_root_for_client() {
local client="$1"
local network="$2"
local root_template="$SNAPSHOT_ROOT"
local original_template="$SNAPSHOT_ROOT"
if [[ -z "$root_template" ]]; then
echo ""
return
fi
local client_lower="${client,,}"
local network_lower="${network,,}"
root_template="${root_template//<<CLIENT>>/$client}"
root_template="${root_template//<<client>>/$client_lower}"
root_template="${root_template//<<Client>>/$client}"
root_template="${root_template//<<NETWORK>>/$network}"
root_template="${root_template//<<network>>/$network_lower}"
root_template="${root_template//<<Network>>/$network}"
# Enforce per-network snapshot selection even if caller omitted <<NETWORK>>.
if [ -n "$network_lower" ] && [[ "$original_template" != *"<<NETWORK>>"* ]] && [[ "$original_template" != *"<<network>>"* ]] && [[ "$original_template" != *"<<Network>>"* ]]; then
root_template="${root_template%/}/$network_lower"
fi
echo "$root_template"
}
restart_client_containers() {
local client_base="$1"
local compose_dir="scripts/$client_base"
local compose_file="$compose_dir/docker-compose.yaml"
local env_file="$compose_dir/.env"
if [ ! -f "$compose_file" ]; then
echo "[WARN] Compose file not found for $client_base" >&2
return 1
fi
if [ -f "$env_file" ]; then
if ! compose_cmd -f "$compose_file" --env-file "$env_file" restart >/dev/null 2>&1; then
if ! compose_cmd -f "$compose_file" --env-file "$env_file" restart; then
echo "[ERROR] Failed to restart services for $client_base" >&2
return 1
fi
fi
else
if ! (
cd "$compose_dir" && compose_cmd restart
); then
echo "[ERROR] Failed to restart services for $client_base" >&2
return 1
fi
fi
if declare -f wait_for_rpc >/dev/null 2>&1; then
wait_for_rpc "http://127.0.0.1:8545" "$RPC_READINESS_MAX_ATTEMPTS"
else
sleep 5
fi
}
is_measured_file() {
local file_path="$1"
local normalized="${file_path//\\/\/}"
local filename="${file_path##*/}"
case "$filename" in
gas-bump.txt|funding.txt|setup-global-test.txt|teardown-global-test.txt)
return 1 ;;
esac
if [[ "$normalized" == */setup/* ]] || [[ "$normalized" == */cleanup/* ]]; then
return 1
fi
if [[ "$normalized" == */testing/* ]]; then
return 0
fi
return 0
}
# ---------------------------------------------------------------------------
# Bootstrap FCU – send a forkchoiceUpdated to drive the client to the
# expected head block via p2p. Used when a snapshot is a few blocks behind.
# Args: $1 = head_block_hash, $2 = max_retries (default 60),
# $3 = backoff_seconds (default 30)
# ---------------------------------------------------------------------------
bootstrap_fcu() {
local head_block_hash="$1"
local max_retries="${2:-60}"
local backoff="${3:-30}"
local jwt_secret_path="/tmp/jwtsecret"
local engine_url="http://127.0.0.1:8551"
echo "[INFO] Bootstrap FCU: driving head to $head_block_hash (max_retries=$max_retries, backoff=${backoff}s)"
python3 - "$head_block_hash" "$max_retries" "$backoff" "$jwt_secret_path" "$engine_url" <<'PYEOF'
import sys, time, json, urllib.request, urllib.error, hmac, hashlib, base64, math
head_hash = sys.argv[1]
max_retries = int(sys.argv[2])
backoff_secs = int(sys.argv[3])
jwt_path = sys.argv[4]
engine_url = sys.argv[5]
with open(jwt_path) as f:
jwt_secret = bytes.fromhex(f.read().strip())
def make_jwt():
header = base64.urlsafe_b64encode(b'{"alg":"HS256","typ":"JWT"}').rstrip(b'=')
payload = base64.urlsafe_b64encode(
json.dumps({"iat": int(time.time())}).encode()
).rstrip(b'=')
msg = header + b'.' + payload
sig = base64.urlsafe_b64encode(
hmac.new(jwt_secret, msg, hashlib.sha256).digest()
).rstrip(b'=')
return (msg + b'.' + sig).decode()
fcu_payload = json.dumps({
"jsonrpc": "2.0",
"method": "engine_forkchoiceUpdatedV3",
"params": [
{
"headBlockHash": head_hash,
"safeBlockHash": head_hash,
"finalizedBlockHash": head_hash,
},
None,
],
"id": 1,
}).encode()
for attempt in range(1, max_retries + 1):
try:
token = make_jwt()
req = urllib.request.Request(
engine_url,
data=fcu_payload,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
},
)
with urllib.request.urlopen(req, timeout=10) as resp:
body = json.loads(resp.read())
status = (body.get("result") or {}).get("payloadStatus", {}).get("status", "")
print(f"[INFO] Bootstrap FCU attempt {attempt}/{max_retries}: status={status}", flush=True)
if status == "VALID":
print("[INFO] Bootstrap FCU succeeded – head is VALID", flush=True)
sys.exit(0)
except Exception as exc:
print(f"[WARN] Bootstrap FCU attempt {attempt}/{max_retries} failed: {exc}", flush=True)
if attempt < max_retries:
time.sleep(backoff_secs)
print("[ERROR] Bootstrap FCU exhausted all retries", file=sys.stderr, flush=True)
sys.exit(1)
PYEOF
}
append_tests_for_path() {
local base_path="$1"
local genesis="$2"
if [ -f "$base_path" ]; then
TEST_FILES+=("$base_path")
TEST_TO_GENESIS+=("$genesis")
return
fi
if [ -d "$base_path" ]; then
if is_stateful_directory "$base_path"; then
while IFS= read -r -d '' file; do
TEST_FILES+=("$file")
TEST_TO_GENESIS+=("$genesis")
done < <(collect_stateful_directory "$base_path")
else
while IFS= read -r -d '' file; do
TEST_FILES+=("$file")
TEST_TO_GENESIS+=("$genesis")
done < <(find "$base_path" -type f -name '*.txt' -print0 | sort -z)
fi
return
fi
echo "[WARN] Test path not found: $base_path" >&2
}
is_mounted() {
local mount_point="$1"
local abs_path
abs_path=$(abspath "$mount_point")
grep -q " $abs_path " /proc/mounts 2>/dev/null
}
resolve_snapshot_lower_for_client() {
local client="$1"
local network="$2"
local snapshot_root="$3"
local lower=""
if [ -n "$network" ] && dir_has_content "$snapshot_root/$network/$client"; then
lower="$snapshot_root/$network/$client"
fi
if [ -z "$lower" ] && [ -n "$network" ] && dir_has_content "$snapshot_root/$network" && [ ! -d "$snapshot_root/$network/$client" ]; then
lower="$snapshot_root/$network"
fi
if [ -z "$lower" ] && dir_has_content "$snapshot_root/$client"; then
lower="$snapshot_root/$client"
fi
if [ -z "$lower" ] && dir_has_content "$snapshot_root"; then
lower="$snapshot_root"
fi
if [ -z "$lower" ]; then
echo "Unable to locate snapshot directory for $client under $snapshot_root" >&2
return 1
fi
echo "$lower"
}
overlay_base_from_lower() {
local abs_lower="$1"
if [[ "$OVERLAY_TMP_ROOT" = /* ]]; then
echo "$OVERLAY_TMP_ROOT"
return
fi
local lower_parent
lower_parent=$(dirname "$abs_lower")
echo "$lower_parent/$OVERLAY_TMP_ROOT"
}
run_zfs() {
if zfs "$@" 2>/dev/null; then
return 0
fi
if command -v sudo >/dev/null 2>&1; then
sudo zfs "$@"
return $?
fi
return 1
}
overlay_mount_with_fallback() {
local client="$1"
local abs_lower="$2"
local abs_upper="$3"
local abs_work="$4"
local merged="$5"
local base_opts="lowerdir=$abs_lower,upperdir=$abs_upper,workdir=$abs_work"
local volatile_suffix=""
if [ "${OVERLAY_USE_VOLATILE,,}" = "true" ]; then
volatile_suffix=",volatile"
fi
local candidate_opts=()
if [ -n "$OVERLAY_MOUNT_EXTRA_OPTS" ]; then
candidate_opts+=("$base_opts,$OVERLAY_MOUNT_EXTRA_OPTS")
fi
candidate_opts+=("$base_opts,metacopy=on,xino=auto,index=off,redirect_dir=off$volatile_suffix")
candidate_opts+=("$base_opts,metacopy=on,xino=auto,redirect_dir=off$volatile_suffix")
candidate_opts+=("$base_opts,xino=auto,redirect_dir=off$volatile_suffix")
candidate_opts+=("$base_opts,redirect_dir=on$volatile_suffix")
candidate_opts+=("$base_opts")
local mount_opts
for mount_opts in "${candidate_opts[@]}"; do
if mount -t overlay overlay -o "$mount_opts" "$merged" 2>/dev/null; then
echo "[INFO] Overlay mount options for $client: $mount_opts" >&2
return 0
fi
if command -v sudo >/dev/null 2>&1 && sudo mount -t overlay overlay -o "$mount_opts" "$merged" >/dev/null 2>&1; then
echo "[INFO] Overlay mount options for $client: $mount_opts (via sudo)" >&2
return 0
fi
done
return 1
}
resolve_zfs_dataset_for_path() {
local target_path="$1"
local target_abs
target_abs=$(abspath "$target_path")
local best_dataset=""
local best_mount=""
local best_len=0
local dataset mountpoint
while IFS=$'\t' read -r dataset mountpoint; do
if [ -z "$dataset" ] || [ -z "$mountpoint" ] || [ "$mountpoint" = "-" ]; then
continue
fi
case "$target_abs" in
"$mountpoint"|"$mountpoint"/*)
if [ "${#mountpoint}" -gt "$best_len" ]; then
best_dataset="$dataset"
best_mount="$mountpoint"
best_len=${#mountpoint}
fi
;;
esac
done < <(run_zfs list -H -o name,mountpoint -t filesystem 2>/dev/null)
if [ -z "$best_dataset" ] || [ -z "$best_mount" ]; then
return 1
fi
echo "$best_dataset|$best_mount"
}
prepare_overlay_for_client() {
local client="$1"
local network="$2"
local snapshot_root="$3"
if ! dir_has_content "$snapshot_root"; then
echo "[ERROR] Snapshot directory for $client is missing or empty: $snapshot_root" >&2
return 1
fi
local lower="$snapshot_root"
local abs_lower
abs_lower=$(abspath "$lower")
echo "[INFO] Overlay snapshot source for $client (network=${network:-none}): $abs_lower" >&2
local overlay_base
overlay_base=$(overlay_base_from_lower "$abs_lower")
mkdir -p "$overlay_base"
local client_root="$overlay_base/$client"
mkdir -p "$client_root"
local overlay_id
overlay_id="$(date +%s%N)_$RANDOM"
local overlay_root="$client_root/$overlay_id"
local merged="$overlay_root/merged"
local upper="$overlay_root/upper"
local work="$overlay_root/work"
mkdir -p "$overlay_root"
if is_mounted "$merged"; then
if ! umount "$merged" 2>/dev/null; then
if command -v sudo >/dev/null 2>&1; then
sudo umount "$merged"
else
echo "[ERROR] Failed to unmount previous overlay for $client" >&2
return 1
fi
fi
fi
rm -rf "$merged" "$upper" "$work"
mkdir -p "$merged" "$upper" "$work"
local abs_upper abs_work
abs_upper=$(abspath "$upper")
abs_work=$(abspath "$work")
if ! overlay_mount_with_fallback "$client" "$abs_lower" "$abs_upper" "$abs_work" "$merged"; then
echo "[ERROR] Failed to mount overlay for $client (all mount option profiles failed)" >&2
return 1
fi
ACTIVE_OVERLAY_MOUNTS["$client"]="$merged"
ACTIVE_OVERLAY_UPPERS["$client"]="$upper"
ACTIVE_OVERLAY_WORKS["$client"]="$work"
ACTIVE_OVERLAY_ROOTS["$client"]="$overlay_root"
ACTIVE_OVERLAY_CLIENTS["$client"]=1
echo "$merged"
}
cleanup_overlay_for_client() {
local client="$1"
local merged="${ACTIVE_OVERLAY_MOUNTS[$client]}"
local upper="${ACTIVE_OVERLAY_UPPERS[$client]}"
local work="${ACTIVE_OVERLAY_WORKS[$client]}"
local root="${ACTIVE_OVERLAY_ROOTS[$client]}"
local base_dir
local unmounted=true
if [ -n "$merged" ] && is_mounted "$merged"; then
# Try regular unmount first
if ! umount "$merged" 2>/dev/null; then
if command -v sudo >/dev/null 2>&1; then
sudo -n umount "$merged" >/dev/null 2>&1 || sudo -n umount "$merged"
fi
fi
# Fallback to lazy unmount if still mounted
if is_mounted "$merged"; then
if ! umount -l "$merged" 2>/dev/null; then
if command -v sudo >/dev/null 2>&1; then
sudo -n umount -l "$merged" >/dev/null 2>&1 || sudo -n umount -l "$merged"
fi
fi
fi
# As a last resort, kill lingering processes and try again
if is_mounted "$merged" && command -v fuser >/dev/null 2>&1; then
fuser -km "$merged" >/dev/null 2>&1 || true
if is_mounted "$merged" && command -v sudo >/dev/null 2>&1; then
sudo -n fuser -km "$merged" >/dev/null 2>&1 || true
fi
sleep 1
if is_mounted "$merged"; then
umount "$merged" 2>/dev/null || true
if is_mounted "$merged" && command -v sudo >/dev/null 2>&1; then
sudo -n umount "$merged" >/dev/null 2>&1 || true
fi
fi
fi
if is_mounted "$merged"; then
echo "[WARN] Unable to unmount overlay for $client ($merged); leaving mount in place" >&2
unmounted=false
fi
fi
if [ "$unmounted" = true ]; then
[ -n "$merged" ] && rm -rf "$merged"
[ -n "$upper" ] && rm -rf "$upper"
[ -n "$work" ] && rm -rf "$work"
[ -n "$root" ] && rm -rf "$root"
fi
if [ "$unmounted" = true ] && [ -n "$root" ]; then
local client_root
client_root=$(dirname "$root")
if [ -d "$client_root" ] && [ -z "$(ls -A "$client_root" 2>/dev/null)" ]; then
rmdir "$client_root" 2>/dev/null || true
fi
base_dir=$(dirname "$client_root")
if [ -d "$base_dir" ] && [ -z "$(ls -A "$base_dir" 2>/dev/null)" ]; then
rmdir "$base_dir" 2>/dev/null || true
fi
fi
unset ACTIVE_OVERLAY_MOUNTS["$client"]
unset ACTIVE_OVERLAY_UPPERS["$client"]
unset ACTIVE_OVERLAY_WORKS["$client"]
unset ACTIVE_OVERLAY_ROOTS["$client"]
unset ACTIVE_OVERLAY_CLIENTS["$client"]
}
cleanup_all_overlays() {
local client
for client in "${!ACTIVE_OVERLAY_CLIENTS[@]}"; do
cleanup_overlay_for_client "$client"
done
}
ensure_zfs_runtime_parent_datasets() {
local pool_name="$1"
local client="$2"
local base_dataset="$pool_name/$ZFS_RUNTIME_DATASET_ROOT"
local client_dataset="$base_dataset/$client"
if ! run_zfs list -H -o name "$base_dataset" >/dev/null 2>&1; then
run_zfs create -o mountpoint=none "$base_dataset" >/dev/null 2>&1 || true
fi
if ! run_zfs list -H -o name "$client_dataset" >/dev/null 2>&1; then
run_zfs create -o mountpoint=none "$client_dataset" >/dev/null 2>&1 || true
fi
}
prepare_zfs_clone_for_client() {
local client="$1"
local network="$2"
local snapshot_root="$3"
local lower=""
lower=$(resolve_snapshot_lower_for_client "$client" "$network" "$snapshot_root") || return 1
if ! command -v zfs >/dev/null 2>&1; then
echo "[ERROR] zfs command is not available but zfs backend was requested" >&2
return 1
fi
local abs_lower
abs_lower=$(abspath "$lower")
local dataset_info=""
dataset_info=$(resolve_zfs_dataset_for_path "$abs_lower") || {
echo "[ERROR] Could not resolve ZFS dataset for snapshot path: $abs_lower" >&2
return 1
}
local source_dataset="${dataset_info%%|*}"
local source_mount="${dataset_info#*|}"
local lower_suffix=""
if [ "$abs_lower" != "$source_mount" ]; then
lower_suffix="${abs_lower#"$source_mount"/}"
fi
local runtime_base
runtime_base=$(overlay_base_from_lower "$abs_lower")
local clone_id
clone_id="$(date +%s%N)_$RANDOM"
local zfs_mount_root="$runtime_base/$client/$clone_id"
mkdir -p "$zfs_mount_root"
local pool_name="${source_dataset%%/*}"
ensure_zfs_runtime_parent_datasets "$pool_name" "$client"
local clone_dataset="$pool_name/$ZFS_RUNTIME_DATASET_ROOT/$client/$clone_id"
local snapshot_name="${source_dataset}@${ZFS_SNAPSHOT_PREFIX}_${client}_${clone_id}"
if ! run_zfs snapshot "$snapshot_name"; then
echo "[ERROR] Failed to create ZFS snapshot $snapshot_name" >&2
return 1
fi
if ! run_zfs clone -o "mountpoint=$zfs_mount_root" "$snapshot_name" "$clone_dataset"; then
echo "[ERROR] Failed to create ZFS clone $clone_dataset from $snapshot_name" >&2
run_zfs destroy "$snapshot_name" >/dev/null 2>&1 || true
return 1
fi
local data_dir="$zfs_mount_root"
if [ -n "$lower_suffix" ]; then
data_dir="$zfs_mount_root/$lower_suffix"
fi
if [ ! -d "$data_dir" ]; then
echo "[ERROR] ZFS clone data directory not found: $data_dir" >&2
run_zfs destroy -r -f "$clone_dataset" >/dev/null 2>&1 || true
run_zfs destroy "$snapshot_name" >/dev/null 2>&1 || true
return 1
fi
ACTIVE_ZFS_DATASETS["$client"]="$clone_dataset"
ACTIVE_ZFS_SNAPSHOTS["$client"]="$snapshot_name"
ACTIVE_ZFS_MOUNTS["$client"]="$zfs_mount_root"
ACTIVE_ZFS_CLIENTS["$client"]=1
echo "$data_dir"
}
cleanup_zfs_clone_for_client() {
local client="$1"
local clone_dataset="${ACTIVE_ZFS_DATASETS[$client]}"
local snapshot_name="${ACTIVE_ZFS_SNAPSHOTS[$client]}"
local mount_root="${ACTIVE_ZFS_MOUNTS[$client]}"
if [ -n "$clone_dataset" ]; then
run_zfs destroy -r -f "$clone_dataset" >/dev/null 2>&1 || true
fi
if [ -n "$snapshot_name" ]; then
run_zfs destroy "$snapshot_name" >/dev/null 2>&1 || true
fi
if [ -n "$mount_root" ] && [ -d "$mount_root" ]; then
rm -rf "$mount_root" >/dev/null 2>&1 || true
fi
unset ACTIVE_ZFS_DATASETS["$client"]
unset ACTIVE_ZFS_SNAPSHOTS["$client"]
unset ACTIVE_ZFS_MOUNTS["$client"]
unset ACTIVE_ZFS_CLIENTS["$client"]
}
cleanup_all_zfs_clones() {
local client
for client in "${!ACTIVE_ZFS_CLIENTS[@]}"; do
cleanup_zfs_clone_for_client "$client"
done
}
cleanup_all_stale_zfs_clones() {
if ! command -v zfs >/dev/null 2>&1; then
return
fi
local stale_dataset
while IFS= read -r stale_dataset; do
if [ -z "$stale_dataset" ]; then
continue
fi
run_zfs destroy -r -f "$stale_dataset" >/dev/null 2>&1 || true
done < <(run_zfs list -H -o name -t filesystem 2>/dev/null | grep "/$ZFS_RUNTIME_DATASET_ROOT/" | sort -r)
local stale_snapshot
while IFS= read -r stale_snapshot; do
if [ -z "$stale_snapshot" ]; then
continue
fi
run_zfs destroy "$stale_snapshot" >/dev/null 2>&1 || true
done < <(run_zfs list -H -o name -t snapshot 2>/dev/null | grep "@${ZFS_SNAPSHOT_PREFIX}_" || true)
}
cleanup_stale_overlay_mounts() {
local base="$1"
if [ -z "$base" ]; then
base="$OVERLAY_TMP_ROOT"
fi
if [[ "$base" != /* ]]; then
base=$(abspath "$base")
fi
if [ ! -d "$base" ]; then
return
fi
mapfile -t stale_mounts < <(mount | awk -v base="$base" '$3 ~ "^" base {print $3}' | sort -r)
local mount_point
for mount_point in "${stale_mounts[@]}"; do
if [ -z "$mount_point" ]; then
continue
fi
if [[ ! "$mount_point" =~ /merged$ ]]; then
continue
fi
if ! umount "$mount_point" 2>/dev/null; then
if command -v sudo >/dev/null 2>&1; then
sudo umount "$mount_point" >/dev/null 2>&1 || sudo umount "$mount_point"
fi
fi
if is_mounted "$mount_point"; then
if ! umount -l "$mount_point" 2>/dev/null; then
if command -v sudo >/dev/null 2>&1; then
sudo umount -l "$mount_point" >/dev/null 2>&1 || sudo umount -l "$mount_point"
fi
fi
fi
if is_mounted "$mount_point" && command -v fuser >/dev/null 2>&1; then
fuser -km "$mount_point" >/dev/null 2>&1 || true
if command -v sudo >/dev/null 2>&1; then
sudo fuser -km "$mount_point" >/dev/null 2>&1 || true
fi
sleep 1
if is_mounted "$mount_point"; then
umount "$mount_point" 2>/dev/null || true
if is_mounted "$mount_point" && command -v sudo >/dev/null 2>&1; then
sudo umount "$mount_point" >/dev/null 2>&1 || sudo umount -l "$mount_point" >/dev/null 2>&1 || true
fi
fi
fi
if is_mounted "$mount_point"; then
echo "[WARN] Unable to unmount stale overlay mount $mount_point" >&2
continue
fi
local run_dir
run_dir=$(dirname "$mount_point")
rm -rf "$run_dir" 2>/dev/null || true
local client_dir
client_dir=$(dirname "$run_dir")
if [ -d "$client_dir" ] && [ -z "$(ls -A "$client_dir" 2>/dev/null)" ]; then
rmdir "$client_dir" 2>/dev/null || true
fi
done
find "$base" -mindepth 1 -type d -empty -delete 2>/dev/null || true
}
collect_overlay_bases() {
local bases=()
if [ -z "$OVERLAY_TMP_ROOT" ]; then
return
fi
if [[ "$OVERLAY_TMP_ROOT" = /* ]]; then
bases+=("$OVERLAY_TMP_ROOT")
else
if [ "${#CLIENT_ARRAY[@]}" -gt 0 ]; then
local client_spec client_base snapshot_root_for_client abs_snapshot parent
for client_spec in "${CLIENT_ARRAY[@]}"; do
if [ -z "$client_spec" ]; then
continue
fi
client_base=$(echo "$client_spec" | cut -d '_' -f 1)
snapshot_root_for_client=$(resolve_snapshot_root_for_client "$client_base" "$NETWORK")
if [ -z "$snapshot_root_for_client" ]; then
continue
fi
abs_snapshot=$(abspath "$snapshot_root_for_client")
parent=$(dirname "$abs_snapshot")
bases+=("$parent/$OVERLAY_TMP_ROOT")
done
fi
if [ "${#bases[@]}" -eq 0 ]; then
bases+=("$(abspath "$OVERLAY_TMP_ROOT")")
fi
fi
local b
declare -A seen
for b in "${bases[@]}"; do
if [ -n "$b" ] && [ -z "${seen[$b]}" ]; then
seen[$b]=1
echo "$b"
fi
done
}
cleanup_all_stale_overlay_mounts() {
local base
while IFS= read -r base; do
cleanup_stale_overlay_mounts "$base"
done < <(collect_overlay_bases)
}
drop_host_caches() {
local status=0
if command -v sync >/dev/null 2>&1; then
sync || status=$?
fi
if [ -w /proc/sys/vm/drop_caches ]; then
echo 3 > /proc/sys/vm/drop_caches 2>/dev/null || status=$?
return $status
fi
if command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1; then
echo 3 | sudo -n tee /proc/sys/vm/drop_caches >/dev/null 2>&1 || status=$?
return $status
fi
return 1
}
docker_compose_down_for_client() {
local client_base="$1"
local compose_dir="scripts/$client_base"
if ! compose_detect >/dev/null 2>&1; then
return
fi
if [ -f "$compose_dir/docker-compose.yaml" ]; then
compose_cmd -f "$compose_dir/docker-compose.yaml" down --volumes >/dev/null 2>&1 || \
compose_cmd -f "$compose_dir/docker-compose.yaml" down --volumes
elif [ -d "$compose_dir" ]; then
(
cd "$compose_dir" && compose_cmd down --volumes >/dev/null 2>&1 || compose_cmd down --volumes
)
fi
}
docker_container_exists() {
local name="$1"
docker_cmd ps -a --format '{{.Names}}' | grep -Fxq "$name"
}
dump_client_logs() {
local client_base="$1"
if [ -z "$(resolve_docker_bin)" ]; then
return
fi
mkdir -p logs
local ts=$(date +%s)
if docker_container_exists "gas-execution-client"; then
docker_cmd logs gas-execution-client &> "logs/docker_${client_base}_${ts}.log" || true
fi
if docker_container_exists "gas-execution-client-sync"; then
docker_cmd logs gas-execution-client-sync &> "logs/docker_sync_${client_base}_${ts}.log" || true
fi
}
cleanup_on_exit() {
local exit_status=$?
trap - EXIT INT TERM
if [ -n "$(resolve_docker_bin)" ]; then
local client_base client_spec
if [ "${#RUNNING_CLIENTS[@]}" -gt 0 ]; then
for client_base in "${!RUNNING_CLIENTS[@]}"; do
dump_client_logs "$client_base"
docker_compose_down_for_client "$client_base"
done
elif [ "${#CLIENT_ARRAY[@]}" -gt 0 ]; then
for client_spec in "${CLIENT_ARRAY[@]}"; do
client_base=$(echo "$client_spec" | cut -d '_' -f 1)
dump_client_logs "$client_base"
docker_compose_down_for_client "$client_base"
done
fi
fi
if [ "$USE_SNAPSHOT_BACKEND" = true ]; then
if [ "$SNAPSHOT_BACKEND" = "zfs" ]; then
if declare -F cleanup_all_zfs_clones >/dev/null 2>&1; then
cleanup_all_zfs_clones
fi
if declare -F cleanup_all_stale_zfs_clones >/dev/null 2>&1; then
cleanup_all_stale_zfs_clones
fi
else
if declare -F cleanup_all_overlays >/dev/null 2>&1; then
cleanup_all_overlays
fi
if declare -F cleanup_all_stale_overlay_mounts >/dev/null 2>&1; then
cleanup_all_stale_overlay_mounts
fi
fi
fi
exit $exit_status
}
# Function to initialize executions.json if it doesn't exist
init_executions_file() {
if [ ! -f "$EXECUTIONS_FILE" ]; then
echo "{}" > "$EXECUTIONS_FILE"
echo "Created $EXECUTIONS_FILE"
fi
}
# Function to check if client was executed today
was_executed_today() {
local client=$1
local today=$(date +%Y-%m-%d)
if [ ! -f "$EXECUTIONS_FILE" ]; then return 1; fi
local last_execution=$(jq -r --arg client "$client" '.[$client] // empty' "$EXECUTIONS_FILE" 2>/dev/null | cut -d'T' -f1)
[ "$last_execution" = "$today" ]