forked from awslabs/amazon-redshift-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreplay.py
2318 lines (2009 loc) · 85.7 KB
/
replay.py
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 argparse
import copy
import csv
import datetime
import hashlib
import json
import logging
import multiprocessing
import os
import random
import re
import signal
import boto3
import sqlparse
import string
import sys
import threading
import time
import traceback
import yaml
from boto3 import client, resource
from botocore.exceptions import NoCredentialsError
from collections import OrderedDict
from contextlib import contextmanager
from multiprocessing.managers import SyncManager
from pathlib import Path
from queue import Empty, Full
from urllib.parse import urlparse
from util import (
init_logging,
set_log_level,
prepend_ids_to_logs,
add_logfile,
log_version,
db_connect,
cluster_dict,
load_config,
load_file,
retrieve_compressed_json,
get_secret,
parse_error,
bucket_dict,
)
from replay_analysis import run_replay_analysis
import redshift_connector
import dateutil.parser
logger = None
g_total_connections = 0
g_queries_executed = 0
# map username to credential strings and timestamp
g_credentials_cache = {}
g_workers = []
g_exit = False
g_copy_replacements_filename = "copy_replacements.csv"
g_config = {}
g_replay_timestamp = None
g_is_serverless = False
g_serverless_cluster_endpoint_pattern = (
r"(.+)\.(.+)\.(.+).redshift-serverless(-dev)?\.amazonaws\.com:[0-9]{4,5}\/(.)+"
)
g_cluster_endpoint_pattern = (
r"(.+)\.(.+)\.(.+).redshift(-serverless)?\.amazonaws\.com:[0-9]{4,5}\/(.)+"
)
class ConnectionLog:
def __init__(
self,
session_initiation_time,
disconnection_time,
application_name,
database_name,
username,
pid,
time_interval_between_transactions,
time_interval_between_queries,
connection_key,
):
self.session_initiation_time = session_initiation_time
self.disconnection_time = disconnection_time
self.application_name = application_name
self.database_name = database_name
self.username = username
self.pid = pid
self.query_index = 0
self.time_interval_between_transactions = time_interval_between_transactions
self.time_interval_between_queries = time_interval_between_queries
self.connection_key = connection_key
self.transactions = []
def __str__(self):
return (
"Session initiation time: %s, Disconnection time: %s, Application name: %s, Database name: %s, "
"Username; %s, PID: %s, Time interval between transactions: %s, Time interval between queries: %s, "
"Number of transactions: %s"
% (
self.session_initiation_time.isoformat(),
self.disconnection_time.isoformat(),
self.application_name,
self.database_name,
self.username,
self.pid,
self.time_interval_between_transactions,
self.time_interval_between_queries,
len(self.transactions),
)
)
def offset_ms(self, ref_time):
return (self.session_initiation_time - ref_time).total_seconds() * 1000.0
@staticmethod
def supported_filters():
return {"database_name", "username", "pid"}
class Transaction:
def __init__(
self, time_interval, database_name, username, pid, xid, queries, transaction_key
):
self.time_interval = time_interval
self.database_name = database_name
self.username = username
self.pid = pid
self.xid = xid
self.queries = queries
self.transaction_key = transaction_key
def __str__(self):
return (
"Time interval: %s, Database name: %s, Username: %s, PID: %s, XID: %s, Num queries: %s"
% (
self.time_interval,
self.database_name,
self.username,
self.pid,
self.xid,
len(self.queries),
)
)
def get_base_filename(self):
return (
self.database_name + "-" + self.username + "-" + self.pid + "-" + self.xid
)
def start_time(self):
return self.queries[0].start_time
def end_time(self):
return self.queries[-1].end_time
def offset_ms(self, replay_start_time):
return self.queries[0].offset_ms(replay_start_time)
@staticmethod
def supported_filters():
return {"database_name", "username", "pid"}
class Query:
def __init__(self, start_time, end_time, text):
self.start_time = start_time
self.end_time = end_time
self.time_interval = 0
self.text = text
def __str__(self):
return "Start time: %s, End time: %s, Time interval: %s, Text: %s" % (
self.start_time.isoformat(),
self.end_time.isoformat(),
self.time_interval,
self.text.strip(),
)
def offset_ms(self, ref_time):
return (self.start_time - ref_time).total_seconds() * 1000.0
class ConnectionThread(threading.Thread):
def __init__(
self,
process_idx,
job_id,
connection_log,
default_interface,
odbc_driver,
replay_start,
first_event_time,
error_logger,
thread_stats,
num_connections,
peak_connections,
connection_semaphore,
perf_lock,
):
threading.Thread.__init__(self)
self.process_idx = process_idx
self.job_id = job_id
self.connection_log = connection_log
self.default_interface = default_interface
self.odbc_driver = odbc_driver
self.replay_start = replay_start
self.first_event_time = first_event_time
self.error_logger = error_logger
self.thread_stats = thread_stats
self.num_connections = num_connections
self.peak_connections = peak_connections
self.connection_semaphore = connection_semaphore
self.perf_lock = perf_lock
prepend_ids_to_logs(self.process_idx, self.job_id + 1)
@contextmanager
def initiate_connection(self, username):
conn = None
# check if this connection is happening at the right time
expected_elapsed_sec = (
self.connection_log.session_initiation_time - self.first_event_time
).total_seconds()
elapsed_sec = (
datetime.datetime.now(tz=datetime.timezone.utc) - self.replay_start
).total_seconds()
connection_diff_sec = elapsed_sec - expected_elapsed_sec
connection_duration_sec = (
self.connection_log.disconnection_time
- self.connection_log.session_initiation_time
).total_seconds()
logger.debug(
f"Establishing connection {self.job_id + 1} of {g_total_connections} at {elapsed_sec:.3f} "
f"(expected: {expected_elapsed_sec:.3f}, {connection_diff_sec:+.3f}). "
f"Pid: {self.connection_log.pid}, Connection times: {self.connection_log.session_initiation_time} "
f"to {self.connection_log.disconnection_time}, {connection_duration_sec} sec"
)
# save the connection difference
self.thread_stats["connection_diff_sec"] = connection_diff_sec
# and emit a warning if we're behind
if abs(connection_diff_sec) > g_config.get("connection_tolerance_sec", 300):
logger.warning(
"Connection at {} offset by {:+.3f} sec".format(
self.connection_log.session_initiation_time, connection_diff_sec
)
)
interface = self.default_interface
if "psql" in self.connection_log.application_name.lower():
interface = "psql"
elif (
"odbc" in self.connection_log.application_name.lower()
and self.odbc_driver is not None
):
interface = "odbc"
elif self.default_interface == "odbc" and self.odbc_driver is None:
logger.warning(
"Default driver is set to ODBC. But no ODBC DSN provided. Replay will use PSQL as "
"default driver."
)
interface = "psql"
else:
interface = "psql"
credentials = get_connection_credentials(
username, database=self.connection_log.database_name
)
try:
try:
conn = db_connect(
interface,
host=credentials["host"],
port=int(credentials["port"]),
username=credentials["username"],
password=credentials["password"],
database=credentials["database"],
odbc_driver=credentials["odbc_driver"],
drop_return=g_config.get("drop_return"),
)
logger.debug(
f"Connected using {interface} for PID: {self.connection_log.pid}"
)
self.num_connections.value += 1
except Exception as err:
hashed_cluster_url = copy.deepcopy(credentials)
hashed_cluster_url["password"] = "***"
logger.error(
f"({self.job_id + 1}) Failed to initiate connection for {self.connection_log.database_name}-"
f"{self.connection_log.username}-{self.connection_log.pid} ({hashed_cluster_url}): {err}"
)
self.thread_stats["connection_error_log"][
f"{self.connection_log.database_name}-{self.connection_log.username}-{self.connection_log.pid}"
] = f"{self.connection_log}\n\n{err}"
yield conn
except Exception as e:
logger.error(f"Exception in connect: {e}")
finally:
logger.debug(f"Context closing for pid: {self.connection_log.pid}")
if conn is not None:
conn.close()
logger.debug(f"Disconnected for PID: {self.connection_log.pid}")
self.num_connections.value -= 1
if self.connection_semaphore is not None:
logger.debug(
f"Releasing semaphore ({self.num_connections.value} / "
f"{g_config['limit_concurrent_connections']} active connections)"
)
self.connection_semaphore.release()
def run(self):
try:
with self.initiate_connection(self.connection_log.username) as connection:
if connection:
self.execute_transactions(connection)
if self.connection_log.time_interval_between_transactions is True:
disconnect_offset_sec = (
self.connection_log.disconnection_time
- self.first_event_time
).total_seconds()
if disconnect_offset_sec > current_offset_ms(self.replay_start):
logger.debug(
f"Waiting to disconnect {time_until_disconnect_sec} sec (pid "
f"{self.connection_log.pid})"
)
time.sleep(time_until_disconnect_sec)
else:
logger.warning("Failed to connect")
except Exception as e:
logger.error(f"Exception thrown for pid {self.connection_log.pid}: {e}")
def execute_transactions(self, connection):
if self.connection_log.time_interval_between_transactions is True:
for idx, transaction in enumerate(self.connection_log.transactions):
# we can use this if we want to run transactions based on their offset from the start of the replay
# time_until_start_ms = transaction.offset_ms(self.first_event_time) -
# current_offset_ms(self.replay_start)
# or use this to preserve the time between transactions
if idx == 0:
time_until_start_ms = (
transaction.start_time()
- self.connection_log.session_initiation_time
).total_seconds() * 1000.0
else:
prev_transaction = self.connection_log.transactions[idx - 1]
time_until_start_ms = (
transaction.start_time() - prev_transaction.end_time()
).total_seconds() * 1000.0
# wait for the transaction to start
if time_until_start_ms > 10:
logger.debug(
f"Waiting {time_until_start_ms / 1000:.1f} sec for transaction to start"
)
time.sleep(time_until_start_ms / 1000.0)
self.execute_transaction(transaction, connection)
else:
for transaction in self.connection_log.transactions:
self.execute_transaction(transaction, connection)
def save_query_stats(self, starttime, endtime, xid, query_idx):
with self.perf_lock:
sr_dir = (
g_config.get("logging_dir", "simplereplay_logs")
+ "/"
+ g_replay_timestamp.isoformat()
)
Path(sr_dir).mkdir(parents=True, exist_ok=True)
filename = f"{sr_dir}/{self.process_idx}_times.csv"
elapsed_sec = 0
if endtime is not None:
elapsed_sec = "{:.6f}".format((endtime - starttime).total_seconds())
with open(filename, "a+") as fp:
if fp.tell() == 0:
fp.write("# process,query,start_time,end_time,elapsed_sec,rows\n")
query_id = f"{xid}-{query_idx}"
fp.write(
"{},{},{},{},{},{}\n".format(
self.process_idx, query_id, starttime, endtime, elapsed_sec, 0
)
)
def get_tagged_sql(self, query_text, idx, transaction, connection):
json_tags = {
"xid": transaction.xid,
"query_idx": idx,
"replay_start": g_replay_timestamp.isoformat(),
"source": g_config.get("source_tag", "SimpleReplay"),
}
return "/* {} */ {}".format(json.dumps(json_tags), query_text)
def execute_transaction(self, transaction, connection):
errors = []
cursor = connection.cursor()
transaction_query_idx = 0
for idx, query in enumerate(transaction.queries):
time_until_start_ms = query.offset_ms(
self.first_event_time
) - current_offset_ms(self.replay_start)
truncated_query = (
query.text[:60] + "..." if len(query.text) > 60 else query.text
).replace("\n", " ")
logger.debug(
f"Executing [{truncated_query}] in {time_until_start_ms/1000.0:.1f} sec"
)
if time_until_start_ms > 10:
time.sleep(time_until_start_ms / 1000.0)
if g_config.get("split_multi", True):
split_statements = sqlparse.split(query.text)
# exclude empty statements. Some customers' queries have been
# found to end in multiple ; characters;
split_statements = [_ for _ in split_statements if _ != ";"]
else:
split_statements = [query.text]
if len(split_statements) > 1:
self.thread_stats["multi_statements"] += 1
self.thread_stats["executed_queries"] += len(split_statements)
success = True
for s_idx, sql_text in enumerate(split_statements):
sql_text = self.get_tagged_sql(
sql_text, transaction_query_idx, transaction, connection
)
transaction_query_idx += 1
substatement_txt = ""
if len(split_statements) > 1:
substatement_txt = (
f", Multistatement: {s_idx+1}/{len(split_statements)}"
)
exec_start = datetime.datetime.now(tz=datetime.timezone.utc)
exec_end = None
try:
status = ""
if (
g_config["execute_copy_statements"] == "true"
and "from 's3:" in sql_text.lower()
):
cursor.execute(sql_text)
elif (
g_config["execute_unload_statements"] == "true"
and "to 's3:" in sql_text.lower()
and g_config["replay_output"] is not None
):
cursor.execute(sql_text)
elif ("from 's3:" not in sql_text.lower()) and (
"to 's3:" not in sql_text.lower()
): ## removed condition to exclude bind variables
cursor.execute(sql_text)
else:
status = "Not "
exec_end = datetime.datetime.now(tz=datetime.timezone.utc)
exec_sec = (exec_end - exec_start).total_seconds()
logger.debug(
f"{status}Replayed DB={transaction.database_name}, USER={transaction.username}, PID={transaction.pid}, XID:{transaction.xid}, Query: {idx+1}/{len(transaction.queries)}{substatement_txt} ({exec_sec} sec)"
)
success = success & True
except Exception as err:
success = False
errors.append([sql_text, str(err)])
logger.debug(
f"Failed DB={transaction.database_name}, USER={transaction.username}, PID={transaction.pid}, "
f"XID:{transaction.xid}, Query: {idx + 1}/{len(transaction.queries)}{substatement_txt}: {err}"
)
self.error_logger.append(
parse_error(
err,
transaction.username,
g_config["target_cluster_endpoint"].split("/")[-1],
query.text,
)
)
self.save_query_stats(
exec_start, exec_end, transaction.xid, transaction_query_idx
)
if success:
self.thread_stats["query_success"] += 1
else:
self.thread_stats["query_error"] += 1
if query.time_interval > 0.0:
logger.debug(f"Waiting {query.time_interval} sec between queries")
time.sleep(query.time_interval)
cursor.close()
connection.commit()
if self.thread_stats["query_error"] == 0:
self.thread_stats["transaction_success"] += 1
else:
self.thread_stats["transaction_error"] += 1
self.thread_stats["transaction_error_log"][
transaction.get_base_filename()
] = errors
# exception thrown if any filters are invalid
class InvalidFilterException(Exception):
pass
# exception thrown if credentials can't be retrieved
class CredentialsException(Exception):
pass
# exception thrown if cluster doesn't exist
class ClusterNotExist(Exception):
pass
def validate_and_normalize_filters(object, filters):
"""validate filters and set defaults. The object just needs to
provide a supported_filters() function."""
normalized_filters = copy.deepcopy(filters)
if "include" not in normalized_filters:
normalized_filters["include"] = {}
if "exclude" not in normalized_filters:
normalized_filters["exclude"] = {}
for f in object.supported_filters():
normalized_filters["include"].setdefault(f, ["*"])
normalized_filters["exclude"].setdefault(f, [])
include_overlap = set(normalized_filters["include"].keys()) - set(
object.supported_filters()
)
if len(include_overlap) > 0:
raise InvalidFilterException(f"Unknown filters: {include_overlap}")
exclude_overlap = set(normalized_filters["exclude"].keys()) - set(
object.supported_filters()
)
if len(exclude_overlap) > 0:
raise InvalidFilterException(f"Unknown filters: {exclude_overlap}")
for f in object.supported_filters():
include = normalized_filters["include"][f]
exclude = normalized_filters["exclude"][f]
if len(include) == 0:
raise InvalidFilterException("Include filter must not be empty")
overlap = set(include).intersection(set(exclude))
if len(overlap) > 0:
raise InvalidFilterException(
f"Can't include the same values in both include and exclude for filter: "
f"{overlap}"
)
for x in (include, exclude):
if len(x) > 1 and "*" in x:
raise InvalidFilterException(
"'*' can not be used with other filter values filter"
)
return normalized_filters
def matches_filters(object, filters):
"""Check if the object matches the filters. The object just needs to
provide a supported_filters() function. This also assumes filters has already
been validated"""
included = 0
for field in object.supported_filters():
include = filters["include"][field]
exclude = filters["exclude"][field]
# if include values were passed and its not a wildcard, check against it
if "*" in include or getattr(object, field) in include:
included += 1
# if include = * and the user is in the exclude list, reject
if getattr(object, field) in exclude:
return False
# otherwise include = * and there's no exclude, so continue checking
if included == len(object.supported_filters()):
return True
else:
return False
def current_offset_ms(ref_time):
return (
datetime.datetime.now(tz=datetime.timezone.utc) - ref_time
).total_seconds() * 1000.0
def parse_connections(
workload_directory,
time_interval_between_transactions,
time_interval_between_queries,
):
connections = []
# total number of connections before filters are applied
total_connections = 0
if workload_directory.startswith("s3://"):
workload_s3_location = workload_directory[5:].partition("/")
bucket_name = workload_s3_location[0]
prefix = workload_s3_location[2]
s3_object = client("s3").get_object(
Bucket=bucket_name, Key=prefix.rstrip("/") + "/connections.json"
)
connections_json = json.loads(s3_object["Body"].read())
else:
connections_file = open(workload_directory + "/connections.json", "r")
connections_json = json.loads(connections_file.read())
connections_file.close()
for connection_json in connections_json:
is_time_interval_between_transactions = {
"": connection_json["time_interval_between_transactions"],
"all on": True,
"all off": False,
}[time_interval_between_transactions]
is_time_interval_between_queries = {
"": connection_json["time_interval_between_queries"],
"all on": "all on",
"all off": "all off",
}[time_interval_between_queries]
try:
if connection_json["session_initiation_time"]:
session_initiation_time = dateutil.parser.isoparse(
connection_json["session_initiation_time"]
).replace(tzinfo=datetime.timezone.utc)
else:
session_initiation_time = None
if connection_json["disconnection_time"]:
disconnection_time = dateutil.parser.isoparse(
connection_json["disconnection_time"]
).replace(tzinfo=datetime.timezone.utc)
else:
disconnection_time = None
connection_key = (
f'{connection_json["database_name"]}_{connection_json["username"]}_'
f'{connection_json["pid"]}'
)
connection = ConnectionLog(
session_initiation_time,
disconnection_time,
connection_json["application_name"],
connection_json["database_name"],
connection_json["username"],
connection_json["pid"],
is_time_interval_between_transactions,
is_time_interval_between_queries,
connection_key,
)
if matches_filters(connection, g_config["filters"]):
connections.append(connection)
total_connections += 1
except Exception as err:
logger.error(f"Could not parse connection: \n{str(connection_json)}\n{err}")
connections.sort(
key=lambda connection: connection.session_initiation_time
or datetime.datetime.utcfromtimestamp(0).replace(tzinfo=datetime.timezone.utc)
)
return connections, total_connections
def parse_transactions(workload_directory):
transactions = []
gz_path = workload_directory.rstrip("/") + "/SQLs.json.gz"
sql_json = retrieve_compressed_json(gz_path)
for xid, transaction_dict in sql_json["transactions"].items():
transaction = parse_transaction(transaction_dict)
if transaction.start_time() and matches_filters(
transaction, g_config["filters"]
):
transactions.append(transaction)
transactions.sort(
key=lambda transaction: (transaction.start_time(), transaction.xid)
)
return transactions
def parse_transactions_old(workload_directory):
transactions = []
if workload_directory.startswith("s3://"):
workload_s3_location = workload_directory[5:].partition("/")
bucket_name = workload_s3_location[0]
prefix = workload_s3_location[2]
conn = client("s3")
s3 = resource("s3")
paginator = conn.get_paginator("list_objects_v2")
page_iterator = paginator.paginate(
Bucket=bucket_name, Prefix=prefix.rstrip("/") + "/SQLs/"
)
for page in page_iterator:
for log in page.get("Contents"):
filename = log["Key"].split("/")[-1]
if filename.endswith(".sql"):
sql_file_text = (
s3.Object(bucket_name, log["Key"])
.get()["Body"]
.read()
.decode("utf-8")
)
transaction = parse_transaction(filename, sql_file_text)
if transaction.start_time() and matches_filters(
transaction, g_config["filters"]
):
transactions.append(transaction)
else:
sqls_directory = os.listdir(workload_directory + "/SQLs/")
for sql_filename in sqls_directory:
if sql_filename.endswith(".sql"):
sql_file_text = open(
workload_directory + "/SQLs/" + sql_filename, "r"
).read()
transaction = parse_transaction(sql_filename, sql_file_text)
if transaction.start_time() and matches_filters(
transaction, g_config["filters"]
):
transactions.append(transaction)
transactions.sort(
key=lambda transaction: (transaction.start_time(), transaction.xid)
)
return transactions
def get_connection_key(database_name, username, pid):
return f"{database_name}_{username}_{pid}"
def parse_transaction(transaction_dict):
queries = []
for q in transaction_dict["queries"]:
start_time = dateutil.parser.isoparse(q["record_time"])
if q["start_time"] is not None:
start_time = dateutil.parser.isoparse(q["start_time"])
end_time = dateutil.parser.isoparse(q["record_time"])
if q["end_time"] is not None:
end_time = dateutil.parser.isoparse(q["end_time"])
queries.append(Query(start_time, end_time, q["text"]))
queries.sort(key=lambda query: query.start_time)
transaction_key = get_connection_key(
transaction_dict["db"], transaction_dict["user"], transaction_dict["pid"]
)
return Transaction(
transaction_dict["time_interval"],
transaction_dict["db"],
transaction_dict["user"],
transaction_dict["pid"],
transaction_dict["xid"],
queries,
transaction_key,
)
def parse_transaction_old(sql_filename, sql_file_text):
queries = []
time_interval = True
database_name = None
username = None
pid = None
xid = None
query_start_time = ""
query_end_time = ""
query_text = ""
for line in sql_file_text.splitlines():
if line.startswith("--Time interval"):
time_interval = line.split("--Time interval: ")[1].strip()
elif line.startswith("--Record time"):
if query_text.strip():
query = Query(query_start_time, query_end_time, query_text.strip())
queries.append(query)
query_text = ""
query_start_time = dateutil.parser.isoparse(line.split(": ")[1].strip())
query_end_time = query_start_time
elif line.startswith("--Start time"):
query_start_time = dateutil.parser.isoparse(line.split(": ")[1].strip())
elif line.startswith("--End time"):
query_end_time = dateutil.parser.isoparse(line.split(": ")[1].strip())
elif line.startswith("--Database"):
database_name = line.split(": ")[1].strip()
elif line.startswith("--Username"):
username = line.split(": ")[1].strip()
elif line.startswith("--Pid"):
pid = line.split(": ")[1].strip()
elif line.startswith("--Xid"):
xid = line.split(": ")[1].strip()
# remove all other comments
elif not line.startswith("--"):
query_text += " " + line
# fallback to using the filename to retrieve the query details. This should only happen if
# replay is run over an old extraction.
if not all([database_name, username, pid, xid]):
database_name, username, pid, xid = parse_filename(sql_filename)
if not all([database_name, username, pid, xid]):
logger.error(f"Failed to parse filename {sql_filename}")
queries.append(Query(query_start_time, query_end_time, query_text.strip()))
queries.sort(key=lambda query: query.start_time)
transaction_key = get_connection_key(database_name, username, pid)
return Transaction(
time_interval, database_name, username, pid, xid, queries, transaction_key
)
def parse_filename(filename):
# Try to parse the info from the filename. Filename format is:
# {database_name}-{username}-{pid}-{xid}
# Both database_name and username can contain "-" characters. In that case, we'll
# take a guess that the - is in the username rather than the database name.
match = re.search(r"^([^-]+)-(.+)-(\d+)-(\d+)", filename)
if not match:
return None, None, None, None
return match.groups()
def parse_copy_replacements(workload_directory):
copy_replacements = {}
copy_replacements_reader = None
replacements_path = workload_directory.rstrip("/") + "/" + g_copy_replacements_filename
if replacements_path.startswith("s3://"):
workload_s3_location = replacements_path[5:].partition("/")
bucket_name = workload_s3_location[0]
prefix = workload_s3_location[2]
s3_object = client("s3").get_object(Bucket=bucket_name, Key=prefix)
csv_string = s3_object["Body"].read().decode("utf-8")
copy_replacements_reader = csv.reader(csv_string.splitlines())
next(copy_replacements_reader) # Skip header
for row in copy_replacements_reader:
if len(row) == 3 and row[2]:
copy_replacements[row[0]] = [row[1], row[2]]
else:
with open(replacements_path, "r") as csvfile:
copy_replacements_reader = csv.reader(csvfile)
next(copy_replacements_reader) # Skip header
for idx, row in enumerate(copy_replacements_reader):
if len(row) != 3:
logger.error(
f"Replacements file {replacements_path} is malformed (row {idx}, line:\n{row}"
)
sys.exit()
copy_replacements[row[0]] = [row[1], row[2]]
logger.info(
f"Loaded {len(copy_replacements)} COPY replacements from {replacements_path}"
)
return copy_replacements
def collect_stats(aggregated_stats, stats):
"""Aggregate the per-thread stats into the overall stats for this aggregated process"""
if not stats:
return
# take the maximum absolute connection difference between actual and expected
if abs(stats["connection_diff_sec"]) >= abs(
aggregated_stats.get("connection_diff_sec", 0)
):
aggregated_stats["connection_diff_sec"] = stats["connection_diff_sec"]
# for each aggregated, add up these scalars across all threads
for stat in (
"transaction_success",
"transaction_error",
"query_success",
"query_error",
):
aggregated_stats[stat] += stats[stat]
# same for arrays.
for stat in ("transaction_error_log", "connection_error_log"):
# note that per the Manager python docs, this extra copy is required to
# get manager to notice the update
new_stats = aggregated_stats[stat]
new_stats.update(stats[stat])
aggregated_stats[stat] = new_stats
def percent(num, den):
if den == 0:
return 0
return float(num) / den * 100.0
def init_stats(stats_dict):
# init by key to ensure Manager is notified of change, if applicable
stats_dict["connection_diff_sec"] = 0
stats_dict["transaction_success"] = 0
stats_dict["transaction_error"] = 0
stats_dict["query_success"] = 0
stats_dict["query_error"] = 0
stats_dict[
"connection_error_log"
] = {} # map filename to array of connection errors
stats_dict[
"transaction_error_log"
] = {} # map filename to array of transaction errors
stats_dict["multi_statements"] = 0
stats_dict["executed_queries"] = 0 # includes multi-statement queries
return stats_dict
def display_stats(
stats, total_connections, total_transactions, total_queries, peak_connections
):
stats_str = ""
stats_str += (
f"Queries executed: {stats['query_success'] + stats['query_error']} of {total_queries} "
f"({percent(stats['query_success'] + stats['query_error'], total_queries):.1f}%)"
)
stats_str += " ["
stats_str += f"Success: {stats['query_success']} ({percent(stats['query_success'], stats['query_success'] + stats['query_error']):.1f}%), "
stats_str += f"Failed: {stats['query_error']} ({percent(stats['query_error'], stats['query_success'] + stats['query_error']):.1f}%), "
stats_str += f"Peak connections: {peak_connections.value}"
stats_str += "]"
logger.info(f"{stats_str}")
def join_finished_threads(connection_threads, worker_stats, wait=False):
# join any finished threads
finished_threads = []
for t in connection_threads:
if not t.is_alive() or wait:
logger.debug(f"Joining thread {t.connection_log.session_initiation_time}")
t.join()
collect_stats(worker_stats, connection_threads[t])
finished_threads.append(t)
# remove the joined threads from the list of active ones
for t in finished_threads:
del connection_threads[t]
logger.debug(
f"Joined {len(finished_threads)} threads, {len(connection_threads)} still active."
)
return len(finished_threads)
def replay_worker(
process_idx,
replay_start_time,
first_event_time,
queue,
error_logger,
worker_stats,
default_interface,
odbc_driver,
connection_semaphore,
num_connections,
peak_connections,