-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
1906 lines (1732 loc) · 79.6 KB
/
Copy pathtest.py
File metadata and controls
1906 lines (1732 loc) · 79.6 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
# 运行目录:在项目根目录下运行
import subprocess
import time
import os
import io
import sys
import atexit
import paramiko
import matplotlib.pyplot as plt
import numpy as np
import json
import threading
import logging
import sys
import shutil
import argparse
import csv
import shlex
import re
import signal
# Set LD_LIBRARY_PATH for YashanDB client
lib_path = os.path.expanduser("~/yashandb-client/lib")
if "LD_LIBRARY_PATH" in os.environ:
os.environ["LD_LIBRARY_PATH"] = lib_path + ":" + os.environ["LD_LIBRARY_PATH"]
else:
os.environ["LD_LIBRARY_PATH"] = lib_path
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger("paramiko").setLevel(logging.WARNING)
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', line_buffering=True)
def kill_server():
os.makedirs(os.path.dirname(output), exist_ok=True)
with open(output, "w", encoding="utf-8") as outfile:
subprocess.run(["pkill", "-9", "-x", "run"], stdout=outfile, stderr=outfile, check=False)
subprocess.run("rm ./output.txt", stdout=outfile, stderr=outfile, shell=True)
time.sleep(1)
def build():
os.makedirs(os.path.dirname(output), exist_ok=True)
with open(output, "w", encoding="utf-8") as outfile:
build_type = "Release" if RouterOnly else "Debug (project default)"
logging.info(f"Rebuilding MP-Router binary with {build_type} configuration.")
build_dir = os.path.join(workspace, "build")
shutil.rmtree(build_dir, ignore_errors=True)
os.makedirs(build_dir, exist_ok=True)
cmake_cmd = ["cmake"]
if RouterOnly:
cmake_cmd.append("-DCMAKE_BUILD_TYPE=Release")
cmake_cmd.append("..")
subprocess.run(cmake_cmd, cwd=build_dir, stdout=outfile,
stderr=subprocess.STDOUT, check=True)
subprocess.run(["make", "-j8"], cwd=build_dir, stdout=outfile,
stderr=subprocess.STDOUT, check=True)
time.sleep(1)
original_config_h_text = None
current_built_mlp_mode = None
def set_mlp_prediction(enabled):
global original_config_h_text
config_path = os.path.join(workspace, "config.h")
with open(config_path, "r", encoding="utf-8") as f:
text = f.read()
if original_config_h_text is None:
original_config_h_text = text
value = "1" if int(enabled) else "0"
new_text, count = re.subn(
r"^#define\s+MLP_PREDICTION\s+\d+(\s*//.*)?$",
lambda m: f"#define MLP_PREDICTION {value}{m.group(1) or ''}",
text,
count=1,
flags=re.MULTILINE,
)
if count != 1:
raise RuntimeError("Unable to find MLP_PREDICTION definition in config.h")
if new_text != text:
logging.info(f"Setting MLP_PREDICTION={value} in config.h")
with open(config_path, "w", encoding="utf-8") as f:
f.write(new_text)
def restore_config_h():
if original_config_h_text is None or not RestoreConfigAfterRun:
return
config_path = os.path.join(workspace, "config.h")
with open(config_path, "w", encoding="utf-8") as f:
f.write(original_config_h_text)
logging.info("Restored original config.h")
def ensure_build_for_mlp(mlp_enabled):
global current_built_mlp_mode
if current_built_mlp_mode == int(mlp_enabled):
return
if not RebuildForMLP and current_built_mlp_mode is not None:
raise RuntimeError("EnableMLP contains multiple values but RebuildForMLP is disabled.")
kill_server()
set_mlp_prediction(mlp_enabled)
build()
current_built_mlp_mode = int(mlp_enabled)
logging.info(f"Built MP-Router with MLP_PREDICTION={current_built_mlp_mode}")
def run_cmd(cmd, check=True):
logging.info(f"Executing: {cmd}")
result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
if check and result.returncode != 0:
logging.error(f"Command failed: {cmd}\nError: {result.stderr}")
raise Exception(f"Command failed: {cmd}")
return result
def wait_for_process_stopped(process, timeout):
logging.info(f"Waiting for process {process.pid} to reach the post-load stop point...")
deadline = time.time() + timeout
status_path = f"/proc/{process.pid}/status"
while time.time() < deadline:
return_code = process.poll()
if return_code is not None:
raise RuntimeError(
f"Process exited with code {return_code} before reaching the post-load stop point."
)
try:
with open(status_path, "r", encoding="utf-8") as status_file:
for line in status_file:
if line.startswith("State:"):
state = line.split()[1]
if state in ("T", "t"):
logging.info(f"Process {process.pid} is stopped after loading data.")
return
break
except FileNotFoundError:
pass
time.sleep(0.1)
raise TimeoutError(
f"Process {process.pid} did not reach the post-load stop point within {timeout}s."
)
def run_remote_cmd(cmd, check=True, max_retries=3, allowed_exit_codes=[0], display_cmd=None, host=None):
remote_host = host or kwr_report_ip
logging.info(f"Executing Remote on {remote_host}: {display_cmd or cmd}")
last_exception = None
for attempt in range(1, max_retries + 1):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 增加 timeout 防止连接卡死
ssh.connect(remote_host, username="root", password=kwr_ip_password, timeout=30)
# 开启 keepalive 防止长时间无数据传输导致连接断开 (特别是在 rsync 过程中)
ssh.get_transport().set_keepalive(60)
stdin, stdout, stderr = ssh.exec_command(cmd)
exit_status = stdout.channel.recv_exit_status()
out = stdout.read().decode('utf-8')
err = stderr.read().decode('utf-8')
if check and exit_status not in allowed_exit_codes:
logging.error(f"Remote command failed: {cmd}\nExit Code: {exit_status}\nError: {err}")
raise Exception(f"Remote command failed: {cmd}")
# 如果是 rsync 返回 24,打印一个警告但视为成功
if exit_status == 24:
logging.warning(f"Rsync warning (code 24): Some files vanished during transfer. This is usually safe to ignore.")
class Result:
def __init__(self, stdout, stderr, returncode):
self.stdout = stdout
self.stderr = stderr
self.returncode = returncode
return Result(out, err, exit_status)
except Exception as e:
logging.warning(f"Remote execution failed (Attempt {attempt}/{max_retries}): {e}")
last_exception = e
if attempt < max_retries:
time.sleep(remote_retry_sleep_seconds)
finally:
ssh.close()
logging.error(f"All {max_retries} attempts failed for command: {cmd}")
raise last_exception
def run_remote_cmd_streaming(cmd, check=True, allowed_exit_codes=(0, 24)):
logging.info(f"Executing Remote with live progress on {kwr_report_ip}: {cmd}")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(kwr_report_ip, username="root", password=kwr_ip_password, timeout=30)
ssh.get_transport().set_keepalive(60)
_, stdout, stderr = ssh.exec_command(cmd, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
text = stdout.channel.recv(4096).decode("utf-8", errors="replace")
print(text, end="", flush=True)
if stdout.channel.recv_stderr_ready():
text = stdout.channel.recv_stderr(4096).decode("utf-8", errors="replace")
print(text, end="", file=sys.stderr, flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(4096).decode("utf-8", errors="replace"), end="", flush=True)
while stdout.channel.recv_stderr_ready():
print(stdout.channel.recv_stderr(4096).decode("utf-8", errors="replace"), end="", file=sys.stderr, flush=True)
exit_status = stdout.channel.recv_exit_status()
if check and exit_status not in allowed_exit_codes:
raise Exception(f"Remote command failed with exit code {exit_status}: {cmd}")
return exit_status
finally:
ssh.close()
def get_remote_dir_size(path):
# 获取目录大小 (KB)
res = run_remote_cmd(f"du -s {shlex.quote(path)} | awk '{{print $1}}'", check=False)
if res.returncode != 0:
return -1
try:
return int(res.stdout.strip())
except:
return -1
def check_remote_exists(path):
res = run_remote_cmd(f"test -e {shlex.quote(path)}", check=False)
return res.returncode == 0
def wait_for_remote_path(path, timeout=30, interval=2):
logging.info(f"Waiting for remote path to be available: {path}")
start_time = time.time()
while time.time() - start_time < timeout:
if check_remote_exists(path):
return True
time.sleep(interval)
return False
def parse_conninfo(conninfo):
parsed = {}
for item in shlex.split(conninfo):
if "=" not in item:
continue
key, value = item.split("=", 1)
parsed[key] = value
return parsed
def is_postgres_like_db():
return int(DBType) == 0
def sync_remote_servers_after_case():
if not is_postgres_like_db():
return
hosts = []
seen = set()
for conninfo in db_ready_probe_conninfos:
host = parse_conninfo(conninfo).get("host")
if host and host not in seen:
hosts.append(host)
seen.add(host)
if not hosts:
hosts = [kwr_report_ip]
for host in hosts:
run_remote_cmd("sync", check=False, max_retries=1, host=host, display_cmd="sync")
def configured_db_conninfos():
if int(DBType) == 1:
return yashan_db_conninfos
if is_postgres_like_db():
return db_ready_probe_conninfos
return []
def build_db_connection_args(node_count=None):
conninfos = configured_db_conninfos()
if not conninfos:
return ""
if node_count is None:
node_count = len(conninfos)
if node_count < 1 or node_count > len(conninfos):
raise ValueError(
f"compute node count {node_count} is outside the configured connection range "
f"[1, {len(conninfos)}] for DB_TYPE={DBType}"
)
return "".join(
f" --db-connection {shlex.quote(conninfo)}"
for conninfo in conninfos[:node_count]
)
def drop_public_tables():
if not shutil.which("psql"):
raise RuntimeError("psql is required to drop tables after each config group.")
drop_tables_sql = """
DO $$
DECLARE
r record;
BEGIN
FOR r IN
SELECT schemaname, tablename
FROM pg_tables
WHERE schemaname = 'public'
LOOP
EXECUTE format('DROP TABLE IF EXISTS %I.%I CASCADE', r.schemaname, r.tablename);
END LOOP;
END $$;
"""
for conninfo in db_ready_probe_conninfos:
parsed = parse_conninfo(conninfo)
env = os.environ.copy()
if parsed.get("password"):
env["PGPASSWORD"] = parsed["password"]
logging.info(f"Dropping public tables on {mask_conninfo_password(conninfo)}")
res = subprocess.run(
build_local_sql_exec_command(conninfo, drop_tables_sql),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
env=env,
timeout=db_drop_tables_timeout_seconds,
)
if res.returncode != 0:
logging.error(
f"Failed to drop public tables on {mask_conninfo_password(conninfo)}: "
f"stdout={res.stdout.strip()}, stderr={res.stderr.strip()}"
)
raise RuntimeError("Failed to drop public tables after config group.")
def truncate_kwr_tables():
if not shutil.which("psql"):
raise RuntimeError("psql is required to truncate KWR tables.")
truncate_kwr_sql = """
TRUNCATE TABLE perf.kwr_last_sql_stmt_all;
TRUNCATE TABLE perf.kwr_stmt_list;
"""
for conninfo in db_ready_probe_conninfos:
parsed = parse_conninfo(conninfo)
env = os.environ.copy()
if parsed.get("password"):
env["PGPASSWORD"] = parsed["password"]
logging.info(f"Truncating KWR tables on {mask_conninfo_password(conninfo)}")
res = subprocess.run(
build_local_sql_exec_command(conninfo, truncate_kwr_sql),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
env=env,
timeout=db_drop_tables_timeout_seconds,
)
if res.returncode != 0:
logging.error(
f"Failed to truncate KWR tables on {mask_conninfo_password(conninfo)}: "
f"stdout={res.stdout.strip()}, stderr={res.stderr.strip()}"
)
raise RuntimeError("Failed to truncate KWR tables.")
def build_db_probe_command(conninfo):
parsed = parse_conninfo(conninfo)
host = parsed.get("host", "127.0.0.1")
port = parsed.get("port", "5432")
user = parsed.get("user", "system")
password = parsed.get("password", "")
dbname = parsed.get("dbname", parsed.get("database", workload))
return (
"if command -v ksql >/dev/null 2>&1; then client=ksql; "
"elif command -v psql >/dev/null 2>&1; then client=psql; "
"else exit 127; fi; "
f"PGPASSWORD={shlex.quote(password)} timeout 5 \"$client\" "
f"-h {shlex.quote(host)} -p {shlex.quote(str(port))} "
f"-U {shlex.quote(user)} -d {shlex.quote(dbname)} "
"-Atqc 'select 1' >/dev/null 2>&1"
)
def build_local_pg_isready_command(conninfo):
parsed = parse_conninfo(conninfo)
host = parsed.get("host", "127.0.0.1")
port = parsed.get("port", "5432")
user = parsed.get("user", "system")
dbname = parsed.get("dbname", parsed.get("database", workload))
return [
"pg_isready",
"-h", host,
"-p", str(port),
"-U", user,
"-d", dbname,
"-t", str(db_pg_isready_timeout_seconds),
]
def build_local_sql_probe_command(conninfo):
parsed = parse_conninfo(conninfo)
host = parsed.get("host", "127.0.0.1")
port = parsed.get("port", "5432")
user = parsed.get("user", "system")
dbname = parsed.get("dbname", parsed.get("database", workload))
return [
"psql",
"-h", host,
"-p", str(port),
"-U", user,
"-d", dbname,
"-Atqc", "select 1",
]
def build_local_sql_exec_command(conninfo, sql):
parsed = parse_conninfo(conninfo)
host = parsed.get("host", "127.0.0.1")
port = parsed.get("port", "5432")
user = parsed.get("user", "system")
dbname = parsed.get("dbname", parsed.get("database", workload))
return [
"psql",
"-v", "ON_ERROR_STOP=1",
"-h", host,
"-p", str(port),
"-U", user,
"-d", dbname,
"-Atqc", sql,
]
def build_tcp_probe_command(conninfo):
parsed = parse_conninfo(conninfo)
host = parsed.get("host", "127.0.0.1")
port = parsed.get("port", "5432")
return (
f"timeout {db_tcp_probe_timeout_seconds} "
f"bash -lc '</dev/tcp/{shlex.quote(host)}/{shlex.quote(str(port))}'"
)
def mask_conninfo_password(conninfo):
return re.sub(r"password=[^ ]+", "password=***", conninfo)
def local_database_probe_ready(conninfo, verbose=False):
parsed = parse_conninfo(conninfo)
password = parsed.get("password", "")
env = os.environ.copy()
if password:
env["PGPASSWORD"] = password
if shutil.which("pg_isready"):
cmd = build_local_pg_isready_command(conninfo)
if verbose:
logging.info(f"Local pg_isready probe: {mask_conninfo_password(conninfo)}")
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env)
if res.returncode != 0:
logging.info(f"pg_isready not ready yet: rc={res.returncode}, stdout={res.stdout.strip()}, stderr={res.stderr.strip()}")
return False, True
if shutil.which("psql"):
cmd = build_local_sql_probe_command(conninfo)
if verbose:
logging.info(f"Local SQL readiness probe: {mask_conninfo_password(conninfo)}")
try:
res = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
env=env,
timeout=db_sql_probe_timeout_seconds,
)
except subprocess.TimeoutExpired:
logging.info(
f"SQL probe timed out after {db_sql_probe_timeout_seconds}s: "
f"{mask_conninfo_password(conninfo)}"
)
return False, True
if res.returncode != 0:
logging.info(f"SQL probe not ready yet: rc={res.returncode}, stdout={res.stdout.strip()}, stderr={res.stderr.strip()}")
return False, True
return True, True
return False, False
def probe_database_ready(verbose=False):
if not db_ready_probe_conninfos:
logging.warning("No db_ready_probe_conninfos configured; using CRM status only.")
return True, True
if use_local_db_readiness_probe:
for conninfo in db_ready_probe_conninfos:
ready, probe_available = local_database_probe_ready(conninfo, verbose=verbose)
if not probe_available:
logging.warning("Neither pg_isready nor psql was found locally; falling back to remote TCP readiness probe.")
break
if not ready:
return False, True
else:
return True, True
for conninfo in db_ready_probe_conninfos:
cmd = build_tcp_probe_command(conninfo)
res = run_remote_cmd(
cmd,
check=False,
max_retries=1,
display_cmd=f"db tcp probe: {mask_conninfo_password(conninfo)}",
)
if res.returncode != 0:
return False, True
if not enable_sql_readiness_probe:
return True, True
probe_available = True
for conninfo in db_ready_probe_conninfos:
cmd = build_db_probe_command(conninfo)
res = run_remote_cmd(
cmd,
check=False,
max_retries=1,
display_cmd=f"db readiness probe: {mask_conninfo_password(conninfo)}",
)
if res.returncode == 127:
probe_available = False
break
if res.returncode != 0:
return False, True
return True, probe_available
def wait_for_db_start(timeout=3000):
if not is_postgres_like_db():
logging.info("Skipping PostgreSQL/KES database readiness probe for non-PostgreSQL DB_TYPE.")
return
logging.info("Waiting for database to start...")
start_time = time.time()
probe_attempt = 0
while time.time() - start_time < timeout:
# 检查数据库资源状态
res = run_remote_cmd(f"crm resource status {db_resource_name}", check=False)
# 根据实际 crm 输出调整,通常 running 表示已启动
status_text = res.stdout + res.stderr
if res.returncode == 0 and "is NOT running" not in status_text and "not found" not in status_text.lower():
probe_attempt += 1
ready, probe_available = probe_database_ready(verbose=False)
if ready:
logging.info(f"Database connection probe succeeded ({len(db_ready_probe_conninfos)} endpoints).")
return
if not probe_available:
logging.warning("Neither ksql nor psql was found on remote host; falling back to a short grace wait after CRM start.")
time.sleep(db_start_probe_fallback_sleep_seconds)
return
logging.info("Database resource is running, but SQL connection is not ready yet.")
time.sleep(db_status_poll_seconds)
raise Exception("Database failed to start within timeout")
def wait_for_db_stop(timeout=3000):
if not is_postgres_like_db():
return
logging.info("Waiting for database to stop...")
start_time = time.time()
while time.time() - start_time < timeout:
# 检查数据库资源状态
res = run_remote_cmd(f"crm resource status {db_resource_name}", check=False)
# 如果不包含 "is running on",则认为已停止
status_text = res.stdout + res.stderr
if "is running on" not in status_text and "Started:" not in status_text:
logging.info("Database resource appears to be stopped.")
return
time.sleep(db_status_poll_seconds)
raise Exception("Database failed to stop within timeout")
def restart_database_resource(reason="between config groups"):
if not is_postgres_like_db():
logging.info(f"Skipping PostgreSQL/KES resource restart for DB_TYPE={DBType}.")
return
logging.info(f"Restarting database resource {reason}...")
run_remote_cmd(f"crm resource stop {db_resource_name}")
wait_for_db_stop()
sync_remote_servers_after_case()
run_remote_cmd(f"crm resource start {db_resource_name}")
wait_for_db_start()
logging.info("Database resource restart completed.")
def is_tpcc_workload(workload_name):
return workload_name in ("tpcc", "tpcc-standard")
def restart_database_before_tpcc_mode(case):
if UseDataCache or not RestartDBBeforeEachTPCCMode or not is_tpcc_workload(case["workload"]):
return
logging.info(
f"Restarting database before TPC-C mode {case['run_mode']} "
f"(case {case['case_id']})."
)
restart_database_resource("before TPC-C mode")
def reset_db_data(backup_path):
logging.info(f">>> Resetting Database Data from {backup_path} <<<")
if backup_path.rstrip("/") == database_data_path.rstrip("/"):
raise Exception("Data source directory must differ from the active database data directory.")
# Check backup size first
backup_size = get_remote_dir_size(backup_path)
logging.info(f"Backup size: {backup_size} KB")
# 修复:空目录大小通常为4KB,原先 <= 0 的判断会导致空目录被当作有效备份
# 从而导致 rsync --delete 删空数据库。这里设置一个最小阈值,例如 100MB (102400 KB)
min_backup_size = 100 * 1024
if backup_size < min_backup_size:
error_msg = f"Critical Error: Backup size at {backup_path} is too small ({backup_size} KB). Refusing to restore to avoid data loss."
logging.error(error_msg)
raise Exception(error_msg)
# 1. Stop Database
run_remote_cmd(f"crm resource stop {db_resource_name}")
wait_for_db_stop()
# 2. Restore Data (使用 rsync 保证权限和完整性)
# --delete 确保目标目录中多余的文件被删除,保持与源目录完全一致
# -a 归档模式,保留权限、所有者等
logging.info("Restoring data from backup...")
# Check disk space before restore (optional debug)
run_remote_cmd(f"df -h {shlex.quote(database_data_path)}", check=False)
source = shlex.quote(backup_path.rstrip("/") + "/")
destination = shlex.quote(database_data_path)
run_remote_cmd_streaming(
f"rsync -a --delete --info=progress2 --human-readable --timeout=3000 {source} {destination}"
)
# Verify restore
restored_size = get_remote_dir_size(database_data_path)
logging.info(f"Restored size: {restored_size} KB")
if abs(restored_size - backup_size) > backup_size * 0.1:
logging.error(f"CRITICAL: Restore size mismatch! Backup: {backup_size}, Restored: {restored_size}")
# raise Exception("Restore failed: Size mismatch")
# Fix permissions just in case (assuming kingbase user)
run_remote_cmd(f"chown -R kingbase:kingbase {database_data_path}", check=False)
run_remote_cmd("sync", check=False)
# 3. Start Database
run_remote_cmd(f"crm resource start {db_resource_name}")
# 4. Wait for startup
wait_for_db_start()
logging.info(">>> Database Reset Complete <<<")
def workload_scale_value(workload_name, account_count=None, warehouse_count=None):
if workload_name in ("tpcc", "tpcc-standard"):
return warehouse_count
return account_count
def workload_scale_arg(workload_name, account_count=None, warehouse_count=None):
if workload_name in ("tpcc", "tpcc-standard"):
return f"--warehouse-count {warehouse_count}"
return f"--account-count {account_count}"
def workload_scale_label(workload_name, account_count=None, warehouse_count=None):
if workload_name in ("tpcc", "tpcc-standard"):
return f"wh{warehouse_count}"
return f"acc{account_count}"
def data_cache_path(workload_name, account_count=None, warehouse_count=None):
scale_value = workload_scale_value(workload_name, account_count, warehouse_count)
if workload_name == "smallbank":
return f"/sharedata/kingbase/{workload_name}_{scale_value}"
return f"/sharedata/kingbase/{workload_name}_{workload_scale_label(workload_name, account_count, warehouse_count)}"
def data_cache_is_valid(backup_path):
if not check_remote_exists(backup_path):
return False
backup_size = get_remote_dir_size(backup_path)
min_backup_size = 100 * 1024
if backup_size < min_backup_size:
logging.warning(
f"Ignoring invalid data cache {backup_path}: size is only {backup_size} KB"
)
return False
return True
def ensure_data_cache(case, force_reload=False):
backup_path = case.get("data_cache_path") or data_cache_path(
case["workload"], case.get("account_count"), case.get("warehouse_count")
)
if force_reload or not data_cache_is_valid(backup_path):
reason = "--force-reload" if force_reload else "no valid cache was detected"
logging.info(f"Preparing data cache {backup_path}: {reason}")
prepare_backup_data(case, backup_path)
else:
logging.info(f"Automatically using existing data cache: {backup_path}")
return backup_path
def list_for_workload(mapping, workload_name, default_values):
if isinstance(mapping, dict):
return mapping.get(workload_name, default_values)
return default_values
def access_patterns_for_workload(workload_name):
return list_for_workload(WorkloadAccessPatterns, workload_name, AccessPattern)
def default_access_pattern_for_workload(workload_name):
if isinstance(DefaultAccessPattern, dict):
return DefaultAccessPattern.get(workload_name, access_patterns_for_workload(workload_name)[0])
return DefaultAccessPattern
def default_scale_for_workload(workload_name):
if workload_name in ("tpcc", "tpcc-standard"):
return None, list_for_workload(WarehouseCount, workload_name, WarehouseCount)[0]
return list_for_workload(AccountCount, workload_name, AccountCount)[0], None
def scale_values_for_workload(workload_name):
if workload_name in ("tpcc", "tpcc-standard"):
for warehouse_count in list_for_workload(WarehouseCount, workload_name, WarehouseCount):
yield None, warehouse_count
else:
account_counts = list_for_workload(AccountCount, workload_name, AccountCount)
if SweepMode == "axis":
account_counts = account_counts[:1]
for account_count in account_counts:
yield account_count, None
def default_access_config(workload_name):
access_pattern = default_access_pattern_for_workload(workload_name)
if access_pattern == 1:
return {
"access_pattern": access_pattern,
"zipfian_theta": DefaultZipfianTheta,
"zipfian_generator": ZipfianGenerator,
"hotspot_fraction": None,
"hotspot_prob": None,
}
if access_pattern == 2:
return {
"access_pattern": access_pattern,
"zipfian_theta": None,
"zipfian_generator": None,
"hotspot_fraction": DefaultHotspotFraction,
"hotspot_prob": DefaultHotspotProb,
}
return {
"access_pattern": access_pattern,
"zipfian_theta": None,
"zipfian_generator": None,
"hotspot_fraction": None,
"hotspot_prob": None,
}
def access_configs_for_workload(workload_name):
configs = []
for access_pattern in access_patterns_for_workload(workload_name):
if access_pattern == 1:
for theta in ZipfianTheta:
configs.append({
"access_pattern": access_pattern,
"zipfian_theta": theta,
"zipfian_generator": ZipfianGenerator,
"hotspot_fraction": None,
"hotspot_prob": None,
})
elif access_pattern == 2:
for hotspot_fraction in HotspotFraction:
for hotspot_prob in HotspotProb:
configs.append({
"access_pattern": access_pattern,
"zipfian_theta": None,
"zipfian_generator": None,
"hotspot_fraction": hotspot_fraction,
"hotspot_prob": hotspot_prob,
})
else:
configs.append({
"access_pattern": access_pattern,
"zipfian_theta": None,
"zipfian_generator": None,
"hotspot_fraction": None,
"hotspot_prob": None,
})
return configs
def base_case_config(workload_name, account_count=None, warehouse_count=None):
case = {
"workload": workload_name,
"account_count": account_count,
"warehouse_count": warehouse_count,
"worker_threads": DefaultWorkerThreads,
"affinity_txn_ratio": DefaultAffinityTxnRatio,
"batch_size": DefaultBatchSize,
"num_bucket": DefaultNumBucket,
"compute_node_count": DefaultComputeNodeCount,
"tpcc_partition_warehouses": DefaultTPCCPartitionWarehouses if workload_name in ("tpcc", "tpcc-standard") else 0,
"long_txn_length": DefaultLongTxnLength if EnableLongTxn else None,
"long_txn_write_pct": LongTxnWritePct if EnableLongTxn else None,
"key_page_ratio": DefaultKeyPageMapCapacity,
"mlp_enabled": DefaultEnableMLP,
"use_data_cache": UseDataCache,
"scan_axis": "base",
}
case.update(default_access_config(workload_name))
return case
def dedupe_case_configs(configs):
deduped = []
seen = set()
for case in configs:
key = (
case["workload"],
case.get("account_count"),
case.get("warehouse_count"),
case["access_pattern"],
case.get("zipfian_theta"),
case.get("zipfian_generator"),
case.get("hotspot_fraction"),
case.get("hotspot_prob"),
case["worker_threads"],
case["affinity_txn_ratio"],
case["batch_size"],
case["num_bucket"],
case["compute_node_count"],
case.get("tpcc_partition_warehouses"),
case.get("long_txn_length"),
case.get("long_txn_write_pct"),
case.get("key_page_ratio"),
case.get("mlp_enabled"),
)
if key not in seen:
seen.add(key)
deduped.append(case)
return deduped
def values_except_default(values, default_value):
return [value for value in values if value != default_value]
def contains_int_value(values, target_value):
return any(int(value) == int(target_value) for value in values)
def access_config_key(config):
return (
config["access_pattern"],
config.get("zipfian_theta"),
config.get("zipfian_generator"),
config.get("hotspot_fraction"),
config.get("hotspot_prob"),
)
def build_axis_case_configs(workload_name, account_count=None, warehouse_count=None):
base = base_case_config(workload_name, account_count, warehouse_count)
include_baseline_cases = contains_int_value(EnableMLP, DefaultEnableMLP)
configs = [base] if include_baseline_cases else []
if include_baseline_cases:
default_access_key = access_config_key(default_access_config(workload_name))
for access_config in access_configs_for_workload(workload_name):
if access_config_key(access_config) == default_access_key:
continue
case = dict(base)
case.update(access_config)
case["scan_axis"] = "access"
configs.append(case)
for compute_node_count in values_except_default(ComputeNodeCounts, DefaultComputeNodeCount):
case = dict(base)
case["compute_node_count"] = compute_node_count
case["scan_axis"] = "compute_node_count"
configs.append(case)
if workload_name != "smallbank":
if include_baseline_cases and workload_name in ("tpcc", "tpcc-standard"):
for partition_warehouses in values_except_default(TPCCPartitionWarehouse, DefaultTPCCPartitionWarehouses):
case = dict(base)
case["tpcc_partition_warehouses"] = partition_warehouses
case["scan_axis"] = "tpcc_partition_warehouses"
configs.append(case)
return dedupe_case_configs(configs)
if include_baseline_cases:
for account_count_value in values_except_default(
list_for_workload(AccountCount, workload_name, AccountCount),
account_count,
):
case = dict(base)
case["account_count"] = account_count_value
case["scan_axis"] = "account_count"
configs.append(case)
for worker_threads in values_except_default(WorkerThreadCount, DefaultWorkerThreads):
case = dict(base)
case["worker_threads"] = worker_threads
case["scan_axis"] = "worker_threads"
configs.append(case)
for affinity_ratio in values_except_default(AffinityTxnRatio, DefaultAffinityTxnRatio):
case = dict(base)
case["affinity_txn_ratio"] = affinity_ratio
case["scan_axis"] = "affinity_txn_ratio"
configs.append(case)
for batch_size in values_except_default(BatchSize, DefaultBatchSize):
case = dict(base)
case["batch_size"] = batch_size
case["scan_axis"] = "batch_size"
configs.append(case)
for num_bucket in values_except_default(NumBucket, DefaultNumBucket):
case = dict(base)
case["num_bucket"] = num_bucket
case["scan_axis"] = "num_bucket"
configs.append(case)
if EnableLongTxn:
for long_txn_length in values_except_default(LongTxnSize, DefaultLongTxnLength):
case = dict(base)
case["long_txn_length"] = long_txn_length
case["scan_axis"] = "long_txn_length"
configs.append(case)
for key_page_ratio in values_except_default(KeyPageMapCapacity, DefaultKeyPageMapCapacity):
case = dict(base)
case["key_page_ratio"] = key_page_ratio
case["scan_axis"] = "key_page_capacity"
configs.append(case)
for mlp_enabled in values_except_default(EnableMLP, DefaultEnableMLP):
for theta in ZipfianTheta:
case = dict(base)
case.update({
"access_pattern": 1,
"zipfian_theta": theta,
"zipfian_generator": ZipfianGenerator,
"hotspot_fraction": None,
"hotspot_prob": None,
})
case["mlp_enabled"] = mlp_enabled
case["scan_axis"] = "mlp_zipfian"
configs.append(case)
return dedupe_case_configs(configs)
def build_full_case_configs(workload_name, account_count=None, warehouse_count=None):
configs = []
long_txn_sizes = LongTxnSize if EnableLongTxn else [None]
tpcc_partition_values = TPCCPartitionWarehouse if workload_name in ("tpcc", "tpcc-standard") else [0]
for access_config in access_configs_for_workload(workload_name):
for worker_threads in WorkerThreadCount:
for batch_size in BatchSize:
for key_page_ratio in KeyPageMapCapacity:
for mlp_enabled in EnableMLP:
for affinity_ratio in AffinityTxnRatio:
for num_bucket in NumBucket:
for compute_node_count in ComputeNodeCounts:
for partition_warehouses in tpcc_partition_values:
for long_txn_length in long_txn_sizes:
case = {
"workload": workload_name,
"account_count": account_count,
"warehouse_count": warehouse_count,
"worker_threads": worker_threads,
"affinity_txn_ratio": affinity_ratio,
"batch_size": batch_size,
"num_bucket": num_bucket,
"compute_node_count": compute_node_count,
"tpcc_partition_warehouses": partition_warehouses,
"long_txn_length": long_txn_length,
"long_txn_write_pct": LongTxnWritePct if EnableLongTxn else None,
"key_page_ratio": key_page_ratio,
"mlp_enabled": mlp_enabled,
"use_data_cache": UseDataCache,
"scan_axis": "full",
}
case.update(access_config)
configs.append(case)
return dedupe_case_configs(configs)
def build_case_configs_for_workload(workload_name, account_count=None, warehouse_count=None):
if SweepMode == "axis":
return build_axis_case_configs(workload_name, account_count, warehouse_count)
if SweepMode == "full":
return build_full_case_configs(workload_name, account_count, warehouse_count)
raise ValueError(f"Unknown SweepMode: {SweepMode}")
def build_case_plan():
main_case_pairs = []
mlp_case_pairs = []
seen = set()
baseline_mlp = int(DefaultEnableMLP)
mlp_run_modes = MLPRunModeType if MLPRunModeType else RunModeType
key_page_capacity_run_modes = KeyPageCapacityRunModeType if KeyPageCapacityRunModeType else RunModeType
batch_size_run_modes = BatchSizeRunModeType if BatchSizeRunModeType else RunModeType
def case_key(case_config, run_mode):
return (
case_config["workload"],
case_config.get("account_count"),
case_config.get("warehouse_count"),
case_config["access_pattern"],
case_config.get("zipfian_theta"),
case_config.get("zipfian_generator"),
case_config.get("hotspot_fraction"),
case_config.get("hotspot_prob"),
case_config["worker_threads"],
case_config["affinity_txn_ratio"],
case_config["batch_size"],
case_config["num_bucket"],
case_config["compute_node_count"],
case_config.get("tpcc_partition_warehouses"),