forked from aws-samples/kr-tech-blog-sample-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb-admin.py
More file actions
2268 lines (1954 loc) · 96.1 KB
/
Copy pathdb-admin.py
File metadata and controls
2268 lines (1954 loc) · 96.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
from pathlib import Path
import pandas as pd
import mysql.connector
import boto3
import json
import re
import os
import requests
from datetime import datetime
import csv
from io import StringIO
import datetime
from botocore.exceptions import ClientError
import time
import logging
from langchain_aws import ChatBedrock
from langchain_core.messages import HumanMessage, AIMessage
from streamlit.web import cli as stcli
from streamlit import runtime
import sys
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import pytz
import io
# Initialize logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
st.title("Aurora MySQL Database Management Demo with Claude3")
#이전 질문내용을 여기에 담아둔다.
prv_prompt = '';
def format_text(text):
# 여러 줄의 공백을 하나의 줄바꿈으로 대체
text = re.sub(r"\n\s*\n", "\n", text)
# '•' 기호 앞에 줄바꿈 추가 (첫 번째 '•' 제외)
text = re.sub(r"(?<!^)\s*•", "\n•", text)
# 각 '•' 항목 들여쓰기
lines = text.split("\n")
formatted_lines = []
for line in lines:
if line.strip().startswith("•"):
formatted_lines.append(line)
else:
formatted_lines.append(" " + line)
return "\n".join(formatted_lines)
# ChatBedrock instance creation
@st.cache_resource
def get_chat_model():
return ChatBedrock(
model_id="anthropic.claude-3-sonnet-20240229-v1:0",
model_kwargs={"temperature": 0.7, "max_tokens": 4096},
)
chat = get_chat_model()
# Session state initialization
if "messages" not in st.session_state:
st.session_state.messages = []
if "mode" not in st.session_state:
st.session_state.mode = "context"
if "context_window" not in st.session_state:
st.session_state.context_window = 10
# Sidebar configuration
st.sidebar.title("Chat Settings")
st.session_state.mode = st.sidebar.radio("Chat Mode", ["context", "single"])
st.session_state.context_window = st.sidebar.slider("Context Window Size", 1, 10, 5)
# Reset conversation button
if st.sidebar.button("Reset Conversation"):
st.session_state.messages = []
st.rerun()
prv_prompt =''
# Display chat history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# AWS 리전 목록
regions = ['us-east-1', 'us-west-2', 'ap-northeast-2']
# 사이드바에서 사용자 입력 받기
region_name = st.sidebar.selectbox('AWS Region', regions)
# Initialize AWS clients
rds_client = boto3.client(service_name="rds",region_name=region_name)
pi_client = boto3.client(service_name="pi",region_name=region_name)
cw_client = boto3.client(service_name="cloudwatch",region_name=region_name)
athena_client = boto3.client(service_name="athena",region_name=region_name)
def get_aurora_clusters():
clusters = []
paginator = rds_client.get_paginator('describe_db_clusters')
for page in paginator.paginate():
for cluster in page['DBClusters']:
if cluster['Engine'].startswith('aurora-mysql'):
clusters.append(cluster['DBClusterIdentifier'])
return clusters
# 데이터베이스 선택
clusters = get_aurora_clusters()
selected_clusters = st.sidebar.multiselect('Select DB Clusters', clusters)
# 선택된 클러스터의 인스턴스 목록 가져오기
instances = []
for cluster in selected_clusters:
response = rds_client.describe_db_instances(Filters=[{'Name': 'db-cluster-id', 'Values': [cluster]}])
instances.extend([instance['DBInstanceIdentifier'] for instance in response['DBInstances']])
# Database configuration
database_name = "sales"
pi_table_name = "performance_insights_data"
cw_table_name = "cw_monitoring_data"
s3_bucket_name = "test-s3bucket-fugwilwec8mx"
s3_bucket_path = f"s3://{s3_bucket_name}/{database_name}"
s3_bucket_table_cw_path = f"{s3_bucket_path}/data/cw_monitoring_data"
s3_bucket_table_pi_path = f"{s3_bucket_path}/data/performance_insight_monitoring_data"
s3_bucket_meta_path = f"{s3_bucket_path}/meta"
def interact_with_llm(secret_name, query):
client = boto3.client("bedrock-runtime")
model_Id = "anthropic.claude-3-sonnet-20240229-v1:0"
accept = "application/json"
contentType = "application/json"
# Fetch Database Information Dynamically
schema_context = get_database_info(secret_name)
schema_context += "generate a sql command between <begin sql> and </end sql>"
print("-----interact_with_llm:get_database_info:schema_context: ", schema_context)
prompt_data = f"""Human: 당신은 Aurora MySQL 전문 DBA이며 Aurora MySQL에 관한 모든 질문에 답변할 수 있습니다.
제공된 맥락에서 정보가 없는 경우 '모르겠습니다'라고 응답해 주세요.
<context></context> 태그 안에는 테이블, 컬럼, 인덱스와 같은 스키마 정보가 있습니다.
<context>에 기반하여 정확한 테이블과 컬럼에서 정확한 컬럼명과 테이블명만 작성하세요.
또한 SQL 작성할때, <example></example> 태그에 있는 쿼리들을 참조해주세요.
다른 테이블과 조인할때, 동일한 컬럼명을 가져오면 다른 별칭을 추가하세요. <example>의 별칭 쿼리를 참조하세요.
프롬프트 입력으로 쿼리 또는 쿼리들을 받으면 그대로 반환해 주세요.
데이터베이스 키워드, 예약어, 모든 SQL문 및 AWS CLI를 포함한 명령어를 제외하고는 요청받았을 때 한국어로 설명해 주세요.
<context>
{schema_context}
</context>
<example>
--상위 top 쿼리 (부하가 가장 많은 쿼리)
SELECT digest_text, count_star, sum_rows_examined, sum_created_tmp_disk_tables, sum_no_index_used
FROM performance_schema.events_statements_summary_by_digest
ORDER BY SUM_TIMER_WAIT DESC, count_star DESC,
sum_rows_examined DESC,sum_no_index_used DESC,
sum_created_tmp_disk_tables DESC;
--데이터베이스 전체상태 조회할때 명령어 :현재 접속한 디비의 Queries, Slow_queries, Thread_connected, Thread_running 정보를 보여줌
show global status
--현재 실행중인 모든 쿼리
SELECT *
FROM performance_schema.events_statements_current
WHERE SQL_TEXT IS NOT NULL;
--InnoDB 상태확인 : 트랜잭션 락, 버퍼풀 상태 확인할때 사용
SHOW ENGINE INNODB STATUS;
--테이블 상태 확인: 가장 큰 테이블이 어떤 테이블인지 확인
SELECT TABLE_SCHEMA, TABLE_NAME, ENGINE, ROW_FORMAT, TABLE_ROWS, AVG_ROW_LENGTH, DATA_LENGTH, INDEX_LENGTH
FROM information_schema.TABLES
WHERE TABLE_SCHEMA NOT IN ('mysql', 'information_schema', 'performance_schema')
ORDER BY DATA_LENGTH + INDEX_LENGTH DESC
LIMIT 10;
--인덱스 사용통계 : 사용되지 않는 인덱스 식별
SELECT * FROM performance_schema.table_io_waits_summary_by_index_usage
WHERE INDEX_NAME IS NOT NULL
ORDER BY COUNT_STAR DESC;
--이벤트별 메모리 사용율: 이벤트별 디비안에서 메모리 사용율을 보여준다.
SELECT EVENT_NAME,CURRENT_NUMBER_OF_BYTES_USED/1024/1024 as used_mem_mb
FROM performance_schema.memory_summary_global_by_event_name
ORDER BY 2 desc
limit 20;
</example>
<question>
{query}
</question>
Assistant:"""
claude_input = json.dumps(
{
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": [{"type": "text", "text": prompt_data}]}
],
"temperature": 0.5,
"top_k": 250,
"top_p": 1,
"stop_sequences": [],
}
)
response = client.invoke_model(modelId=model_Id, body=claude_input)
response_body = json.loads(response.get("body").read())
print("------prompt:", prompt_data)
try:
message = response_body.get("content", [])
result = message[0]["text"]
except (KeyError, IndexError):
result = "I'm sorry, I couldn't generate a response."
print("interact_with_llm result:", result)
return result
def interact_with_general_llm(user_request):
client = boto3.client("bedrock-runtime")
model_Id = "anthropic.claude-3-sonnet-20240229-v1:0"
prompt_data = f"""Human: 당신은 Aurora MySQL 전문 DBA이며 Aurora MySQL에 관한 모든 질문에 답변할 수 있으며 다른 주제나 일반적인 대화도 가능합니다.
제공된 컨텍스트에 필요한 정보가 없으며 잘 모르는 경우 '모르겠습니다'라고 응답해 주세요.
스키마 정보를 사용하여 쿼리 실행 계획과 계획의 순서를 쉽게 분석하고 상세히 설명할 수 있습니다.
질문을 받았을 때 데이터베이스 키워드, 예약어, 모든 SQL문 및 AWS CLI를 포함한 명령어를 제외하고는 한글로 설명해주세요.
<question>
{user_request}
</question>
Assistant:"""
claude_input = json.dumps(
{
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 4096,
"messages": [
{"role": "user", "content": [{"type": "text", "text": prompt_data}]}
],
"temperature": 0.5,
"top_k": 250,
"top_p": 1,
"stop_sequences": [],
}
)
response = client.invoke_model(modelId=model_Id, body=claude_input)
response_body = json.loads(response.get("body").read())
print("------prompt:", prompt_data)
try:
message = response_body.get("content", [])
result = message[0]["text"]
except (KeyError, IndexError):
result = "I'm sorry, I couldn't generate a response."
print("interact_with_general llm result:", result)
return result
def interact_with_llm_athena(database_name, query):
print("query:",query)
client = boto3.client("bedrock-runtime")
model_Id = "anthropic.claude-3-sonnet-20240229-v1:0"
# Fetch Database Information Dynamically
schema_context = """TABLE performance_insights_data
cluster_id string,
instance_id string,
metric string,
timestamp string,
value double
TABLE cw_monitoring_data
cluster_id string,
instance_id string,
metric string,
timestamp string,
value double
TABLE cw_monitoring_data' Data: metric column has values like following
CPUUtilization, FreeableMemory, DatabaseConnections,Deadlocks,SelectLatency,ActiveTransactions,DMLLatency,CommitLatency, DDlLatency,RollbackSegmentHistoryListLength
"""
print("schema_context", schema_context)
schema_context += (
"generate a sql command between <begin sql> and </end sql> refer example1,2! Don't use having clause "
)
prompt_data = f"""Human: 당신은 AWS 아테나의 쿼리를 잘 짜는 데이터 분석 전문가입니다. 자연어로 요청을 받으면, 요청받은 내용을 아테나쿼리로 바꿔서 답변해주세요.
두개의 테이블을 조회하게 됩니다. 하나는 cw_monitoring_data 테이블입니다. 다른 하나는 performance_insights_data 테이블입니다.
일반적인 use case로 요청사항이 CPU, Memory, HLL등과 같은 Cloudwatch metric을 물어볼때는 cw_monitoring_data테이블을 조회합니다.
SQL의 키워드와 테이블명, 컬럼명은 모두 영어입니다. 아래 제공되는 <context></context> 사이의 테이블 스키마를 참조해주세요.
쿼리를 작성할때 <example1></example1> 과 같이 example2,example3...의 example tag 사이에 있는 쿼리들을 참조해주세요.
아테나에서는 쿼리할때 SELECT 절의 sum,avg같은 함수를 써서 가공한 컬럼들은 바로 having절에서 사용하지 못합니다.
이런 경우는 쿼리를 select ...(select ...,sum(col1) as sum_col1...) where sum_col1 >=10 과 같은 형태로 쿼리를 만들어서 주세요.
이런 쿼리에 대한 예제로서 <example3>을 참조해주세요.
그리고,요청중에서 몇개만 보여주세요 하면 쿼리 마지막에 limit n(요청한 몇개) 을 붙여주세요
예를 들어 CPU사용율이 높은 디비 2개만 보여주세요 하면 쿼리문 마지막에 limit 2 를 붙여주면 됩니다.
또는 cpu사용율이 60 이상인 값만 보여주세요 하면 where 절에 avg_cpu_per >=60 이렇게 조건절을 붙여서 쿼리를 생성해주세요.
쿼리 생성할때 반드시, <context></context> 사이에 넣은 테이블 스키마정보를 가지고 테이블및 컬럼명에 맞는 쿼리를 만들어주세요.
테이블의 컬럼안의 값이 RollbackSegmentHistoryListLength 는 HLL이라고 alias를 만들어주세요
또한, 성능지표 value값에서 메모리 사용율이 높은순으로, CPU 사용율이 높은순으로 보여달라고 할때는 Order by 절에 Desc를 사용하고
낮은순으로라고 하면 ASC를 써주세요.
만약 쿼리가 여러개를 만들면 가장 적합한 쿼리 한개만 실행해주시거나 union all로 두개이상의 쿼리가 합칠수 있는 쿼리(컬럼갯수와 명칭, 데이터타입이 맞으면)면
union all로 쿼리를 합쳐서 생성해주세요. 기본적으로는 한개의 가장 적합한 쿼리만 만들어주세요.
<context>
{schema_context}
</context>
<example1>
--이 쿼리는 Cloudwatch metric의 특정일시의 구간동안 cpu와 메모리의 평균값을 보여줍니다.
SELECT cluster_id, instance_id,
ROUND(max(CASE WHEN metric = 'CPUUtilization' THEN value else 0 END),2) AS max_cpu_per,
ROUND(min(CASE WHEN metric = 'FreeableMemory' THEN (value/1024/1024/1024) else 0 END),2) AS min_freeMemory_gb
FROM cw_monitoring_data
WHERE timestamp BETWEEN '2024-06-19 22:00' AND '2024-06-19 23:00'
GROUP BY cluster_id, instance_id
ORDER BY max_cpu_per DESC, min_freeMemory_gb ASC;
</example1>
<example2>
--아래 쿼리는 Cloudwatch metric의 특정일시의 구간동안 cpu와 메모리의 평균값을 보여주되, 그중에 cpu평균값이 50 이상인 데이터를 보여줍니다.
SELECT cluster_id, instance_id,avg_cpu_per,avg_freeMemory_gb
FROM (
SELECT cluster_id, instance_id,
ROUND(AVG(CASE WHEN metric = 'CPUUtilization' THEN value else 0 END),2) AS max_cpu_per,
ROUND(AVG(CASE WHEN metric = 'FreeableMemory' THEN (value/1024/1024/1024) else 0 END),2) AS min_freeMemory_gb
FROM cw_monitoring_data
WHERE timestamp BETWEEN '2024-06-19 22:00' AND '2024-06-19 23:00'
GROUP BY cluster_id, instance_id
ORDER BY max_cpu_per DESC, min_freeMemory_gb ASC
)
WHERE max_cpu_per >=50;
</example2>
<example3>
--아래 쿼리는 Cloudwatch metric의 특정일시의 구간동안 cpu와 메모리의 평균값을 보여주고, 그중에서 cpu평균과 메모리 평균값이 높은 2건만 가져옵니다.
SELECT cluster_id, instance_id,max_cpu_per,min_freeMemory_gb
FROM (
SELECT cluster_id, instance_id,
ROUND(max(CASE WHEN metric = 'CPUUtilization' THEN value else 0 END),2) AS max_cpu_per,
ROUND(min(CASE WHEN metric = 'FreeableMemory' THEN (value/1024/1024/1024) else 0 END),2) AS min_freeMemory_gb,
ROUND(max(CASE WHEN metric = 'RollbackSegmentHistoryListLength' THEN value ELSE 0 END), 2) AS max_hll
FROM cw_monitoring_data
WHERE timestamp BETWEEN '2024-06-19 22:00' AND '2024-06-19 23:00'
GROUP BY cluster_id, instance_id
ORDER BY max_cpu_per DESC, min_freeMemory_gb ASC
)
WHERE max_cpu_per >=50
limit 2;
</example3>
<question>
{query}
</question>
Assistant:"""
print("prompt_data:", prompt_data)
claude_input = json.dumps(
{
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": [{"type": "text", "text": prompt_data}]}
],
"temperature": 0.5,
"top_k": 250,
"top_p": 1,
"stop_sequences": [],
}
)
response = client.invoke_model(modelId=model_Id, body=claude_input)
response_body = json.loads(response.get("body").read())
try:
message = response_body.get("content", [])
result = message[0]["text"]
except (KeyError, IndexError):
result = "I'm sorry, I couldn't generate a response."
return result
# New function to interact with Knowledge Base
def query_knowledge_base(kb_id, query):
client = boto3.client("bedrock-agent-runtime")
try:
response = client.retrieve(
knowledgeBaseId=kb_id,
retrievalQuery={"text": query},
retrievalConfiguration={
"vectorSearchConfiguration": {"numberOfResults": 3}
},
)
return response["retrievalResults"]
except Exception as e:
logger.error(f"Error querying Knowledge Base: {str(e)}")
return []
# get_database_info 에서 호출
def connect_to_db(secret_name):
# Fetch the secret values
secret_values = get_secret(secret_name)
connection = mysql.connector.connect(
host=secret_values["host"],
user=secret_values["username"],
password=secret_values["password"],
port=secret_values["port"],
database=secret_values["dbname"],
)
return connection
# get_database_info 에서 호출
def get_secret(secret_name):
# Initialize a session using Amazon Secrets Manager
session = boto3.session.Session()
client = session.client(service_name="secretsmanager")
# Get the secret value
get_secret_value_response = client.get_secret_value(SecretId=secret_name)
secret = get_secret_value_response["SecretString"]
return json.loads(secret)
# get_database_info 에서 호출
def save_to_s3(secret_name, metadata_info):
s3 = boto3.client("s3")
bucket_name = s3_bucket_name # 버킷 이름 설정
folder_name = secret_name
# 데이터베이스 정보를 문자열로 변환
metadata_info_str = "".join(metadata_info)
# 기존 폴더 확인 및 삭제
prefix = f"{folder_name}/"
existing_objects = s3.list_objects(Bucket=bucket_name, Prefix=prefix)
if "Contents" in existing_objects:
for obj in existing_objects["Contents"]:
s3.delete_object(Bucket=bucket_name, Key=obj["Key"])
print(f"Existing folder '{folder_name}' deleted.")
else:
print(f"No existing folder found for '{folder_name}'.")
# S3에 파일 업로드
file_name = f"{folder_name}.txt"
s3.put_object(
Body=metadata_info_str.encode("utf-8"),
Bucket=bucket_name,
Key=f"{folder_name}/{file_name}",
)
print(
f"Database information for {secret_name} uploaded to S3 bucket '{bucket_name}' in folder '{folder_name}'"
)
def get_database_info(secret_name):
secret_values = get_secret(secret_name)
connection = mysql.connector.connect(
host=secret_values["host"],
user=secret_values["username"],
password=secret_values["password"],
port=secret_values["port"],
database=secret_values["dbname"],
)
cursor = connection.cursor()
cursor.execute("SELECT DATABASE();") #
database_name = cursor.fetchone()
# 데이터베이스 내 모든 테이블 정보 가져오기
cursor.execute(
f''' SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '{database_name[0]}'
ORDER BY TABLE_NAME, ORDINAL_POSITION '''
)
table_info = cursor.fetchall()
# 테이블 정보를 문자열로 변환
table_info_str = "Current Database has following tables and columns: \n"
current_table = None
for row in table_info:
table_name, column_name, data_type, column_comment = row
if table_name != current_table:
if current_table:
table_info_str += "\n"
table_info_str += f"{table_name} with columns:\n"
current_table = table_name
table_info_str += f"{column_name} {data_type} {column_comment}\n"
# 인덱스 정보 가져오기
cursor.execute(
f'''SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, NON_UNIQUE, INDEX_COMMENT
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = '{database_name[0]}'
ORDER BY TABLE_NAME, INDEX_NAME'''
)
index_info = cursor.fetchall()
index_info_str = "\nIndexes:\n"
current_table = None
for row in index_info:
table_name, index_name, column_name, non_unique, index_comment = row
if table_name != current_table:
if current_table:
index_info_str += "\n"
index_info_str += f"{table_name}:\n"
current_table = table_name
index_info_str += f" {index_name} ({column_name}) {'' if non_unique else 'UNIQUE'} {index_comment}\n"
# 모든 메타데이터 정보 결합
metadata_info = (
table_info_str
+ index_info_str
)
results = metadata_info.split("'")
print("--------results:", results)
cursor.close()
# S3에 데이터베이스 정보 저장
save_to_s3(secret_name, results)
return metadata_info
def execute_sql(secret_name, user_query):
if user_query:
llm_response = interact_with_llm(secret_name, user_query)
# Extract SQL command from LLM response
sql_command_match = re.search(
r"<begin sql>(.*?)<\s?/end sql>", llm_response, re.DOTALL | re.IGNORECASE
)
if sql_command_match:
sql_command = sql_command_match.group(1).strip()
query_list = [q.strip() for q in sql_command.split(";") if q.strip()]
print(
"------execute_sql:if sql_command_match: ",
sql_command + f" on database : {secret_name}",
)
try:
connection = connect_to_db(secret_name)
if connection:
print("connect")
cursor = connection.cursor()
for i, query in enumerate(query_list):
print(f"Executing query {i+1}:-----")
cursor.execute(query)
if cursor.with_rows:
columns = cursor.column_names
results = cursor.fetchall()
df = pd.DataFrame(results, columns=columns)
st.write(f"Results for Query {i+1}:")
st.write(df)
else:
st.write(
f"Query {i+1} executed successfully: {cursor.rowcount} rows affected."
)
# 너비를 최대 200자리로 설정
pd.set_option("display.max_rows", 200)
# 최대 열 수를 20으로 설정
pd.set_option("display.max_columns", 20)
# 전체 너비를 200자리로 설정
pd.set_option("display.width", 200)
except Exception as e:
print(f"Error executing SQL command: {e}")
else:
st.warning("No SQL command found in LLM response.")
print("No SQL command found in LLM response.")
# execute_sql_multiDatabase 에서 호출
def get_secrets_by_keyword(keyword):
secrets_manager = boto3.client(service_name="secretsmanager")
response = secrets_manager.list_secrets(
Filters=[{"Key": "name", "Values": [keyword]}]
)
return [secret["Name"] for secret in response["SecretList"]]
def execute_sql_multiDatabase(keyword, user_query):
secret_lists = get_secrets_by_keyword(keyword)
for secret_name in secret_lists:
st.write("On the cluster ", secret_name, ", these workloads will be executed: ")
execute_sql(secret_name, user_query)
# compare_database_info 에서 호출
def read_file_from_s3(bucket_name, folder_name, file_name):
s3 = boto3.client("s3")
try:
obj = s3.get_object(Bucket=bucket_name, Key=f"{folder_name}/{file_name}")
file_content = obj["Body"].read().decode("utf-8")
return file_content
except Exception as e:
print(f"Error reading file from S3: {e}")
st.error(f"Error reading file from S3: {e}")
return None
# compare_database_info 에서 호출
def interact_with_llm_for_comparison(query):
client = boto3.client("bedrock-runtime")
model_Id = "anthropic.claude-3-sonnet-20240229-v1:0"
accept = "application/json"
contentType = "application/json"
prompt_data = f"""Human: 주어진 컨텍스트 정보(스키마 정보:테이블,컬럼,인덱스정보)가 없으면 모른다고 대답해주세요.
당신은 데이터베이스 스키마정보를 비교하는 전문가입니다. 각 데이터베이스의 스키마정보를 비교하여 일목요연하게 정리해주세요.
비교한 파일이 들어있는 파일명인 s3://gamedb1-cluster.txt 대신에 "gamedb1-cluster" 라고 말해주세요.
대답에서 "s3://" and ".txt" 와 같은 용어는 사용하지 말고, 데이터베이스 키워드 용어와 스키마정보들 (테이블명,컬럼명,인덱스명등)을 제외하고는
전체 응답은 한글로 대답해주시고, 마지막에 각 비교한 것에 대한 정리를 깔끔히해서 결론을 내주세요.
전체답변은 example에 있는 형식으로 정리해서 답해주세요.
<example>
1.테이블: 데이터베이스 gamedb1-cluster 는 다른 클러스터에 없는 테이블 'customer_product_orders'과 'products_backup' 이 존재합니다.
2.컬럼: 테이블 products는 gamedb2-cluster에는 없는 Description 컬럼이 gamedb1-cluster, gamedb3-cluster에 있습니다.
3.인덱스: 데이터베이스 'gamedb1-cluster' 에는 다른 클러스터에 없는 인덱스 'ix_order_date'가 'orders'테이블의 'OrderDate' 컬럼에 있습니다.
</example>
<question>
{query}
</question>
Assistant:"""
claude_input = json.dumps(
{
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": [{"type": "text", "text": prompt_data}]}
],
"temperature": 0.5,
"top_k": 250,
"top_p": 1,
"stop_sequences": [],
}
)
response = client.invoke_model(modelId=model_Id, body=claude_input)
response_body = json.loads(response.get("body").read())
# print(response_body)
try:
message = response_body.get("content", [])
result = message[0]["text"]
except (KeyError, IndexError):
result = "에러로 인해, 스키마 정보를 비교할수 없습니다."
# print("result:",result)
return result
def compare_database_info(keyword):
bucket_name = s3_bucket_name
file_contents = []
secret_lists = get_secrets_by_keyword(keyword)
print("secret_lists :", secret_lists)
for secret_name in secret_lists:
metainfo = get_database_info(secret_name)
print("metainfo:", metainfo)
folder_name = secret_name
file_name = f"{folder_name}.txt"
file_content = read_file_from_s3(bucket_name, folder_name, file_name)
if file_content:
file_contents.append(f"{file_name}: {file_content}")
else:
print(f"Error reading file for {secret_name}")
if len(file_contents) >= 2:
llm_input = "\n".join(file_contents)
print("file_content: \n", file_content)
llm_response = interact_with_llm_for_comparison(llm_input)
print(llm_response)
st.write(llm_response)
else:
print("Not enough files to compare.")
st.error("Not enough files to compare.")
# CloudWatch cw Monitoring 데이터 가져오기. 2개를 분리해야한다.
def get_cw_monitoring(cluster_id, instance_id, start_time, end_time):
response = cw_client.get_metric_data(
MetricDataQueries=[
{
"Id": "cpu_utilization",
"MetricStat": {
"Metric": {
"Namespace": "AWS/RDS",
"MetricName": "CPUUtilization",
"Dimensions": [
{"Name": "DBInstanceIdentifier", "Value": instance_id}
],
},
"Period": 300,
"Stat": "Maximum",
},
"ReturnData": True,
},
{
"Id": "memory_usage",
"MetricStat": {
"Metric": {
"Namespace": "AWS/RDS",
"MetricName": "FreeableMemory",
"Dimensions": [
{"Name": "DBInstanceIdentifier", "Value": instance_id}
],
},
"Period": 300,
"Stat": "Maximum",
},
"ReturnData": True,
}
],
StartTime=start_time,
EndTime=end_time,
)
return response["MetricDataResults"]
def get_cw_monitoring2(cluster_id, start_time, end_time):
response = cw_client.get_metric_data(
MetricDataQueries=[
{
"Id": "active_transactions",
"MetricStat": {
"Metric": {
"Namespace": "AWS/RDS",
"MetricName": "ActiveTransactions",
"Dimensions": [
{"Name": "DBClusterIdentifier", "Value": cluster_id}
],
},
"Period": 300,
"Stat": "Sum",
},
"ReturnData": True,
},
{
"Id": "database_connections",
"MetricStat": {
"Metric": {
"Namespace": "AWS/RDS",
"MetricName": "DatabaseConnections",
"Dimensions": [
{"Name": "DBClusterIdentifier", "Value": cluster_id}
],
},
"Period": 300,
"Stat": "Maximum",
},
"ReturnData": True,
},
{
"Id": "deadlocks",
"MetricStat": {
"Metric": {
"Namespace": "AWS/RDS",
"MetricName": "Deadlocks",
"Dimensions": [
{"Name": "DBClusterIdentifier", "Value": cluster_id}
],
},
"Period": 300,
"Stat": "Sum",
},
"ReturnData": True,
},
{
"Id": "select_latency",
"MetricStat": {
"Metric": {
"Namespace": "AWS/RDS",
"MetricName": "SelectLatency",
"Dimensions": [
{"Name": "DBClusterIdentifier", "Value": cluster_id}
],
},
"Period": 300,
"Stat": "Average",
},
"ReturnData": True,
},
{
"Id": "commit_latency",
"MetricStat": {
"Metric": {
"Namespace": "AWS/RDS",
"MetricName": "CommitLatency",
"Dimensions": [
{"Name": "DBClusterIdentifier", "Value": cluster_id}
],
},
"Period": 300,
"Stat": "Average",
},
"ReturnData": True,
},
{
"Id": "ddl_latency",
"MetricStat": {
"Metric": {
"Namespace": "AWS/RDS",
"MetricName": "DDLLatency",
"Dimensions": [
{"Name": "DBClusterIdentifier", "Value": cluster_id}
],
},
"Period": 300,
"Stat": "Average",
},
"ReturnData": True,
},
{
"Id": "dml_latency",
"MetricStat": {
"Metric": {
"Namespace": "AWS/RDS",
"MetricName": "DMLLatency",
"Dimensions": [
{"Name": "DBClusterIdentifier", "Value": cluster_id}
],
},
"Period": 300,
"Stat": "Average",
},
"ReturnData": True,
},
{
"Id": "rollback_segment_history_list_length",
"MetricStat": {
"Metric": {
"Namespace": "AWS/RDS",
"MetricName": "RollbackSegmentHistoryListLength",
"Dimensions": [
{"Name": "DBClusterIdentifier", "Value": cluster_id}
],
},
"Period": 300,
"Stat": "Maximum",
},
"ReturnData": True,
},
],
StartTime=start_time,
EndTime=end_time,
)
return response["MetricDataResults"]
def upload_to_s3_cw(cluster_id, instance_id, data, bucket_name, bucket_path, object_key):
s3_client = boto3.client("s3")
# 데이터를 CSV 형식으로 변환
csv_data = StringIO()
writer = csv.writer(csv_data)
# 헤더 작성
header = ["DBClusterIdentifier","DBInstanceIdentifier","metric", "timestamp", "value"]
writer.writerow(header)
for result in data:
metric_name = result["Label"]
timestamps = result["Timestamps"]
values = result["Values"]
for timestamp, value in zip(timestamps, values):
row = [
cluster_id,
instance_id,
metric_name,
timestamp.strftime("%Y-%m-%d %H:%M"),
value,
]
writer.writerow(row)
csv_data.seek(0)
# S3에 업로드
object_path = f"{bucket_path}/{object_key}"
s3_client.put_object(Bucket=bucket_name, Key=object_path, Body=csv_data.getvalue())
print(f"Data {object_key} uploaded to {bucket_name}/{bucket_path}/{object_key}")
def upload_to_s3_pi( cluster_id, instance_id, data, bucket_name, bucket_path, object_key ):
s3_client = boto3.client("s3")
# 데이터를 CSV 형식으로 변환
csv_data = StringIO()
writer = csv.writer(csv_data)
# 헤더 작성
header = ["metric", "timestamp", "value"]
writer.writerow(header)
for result in data:
metric_name = result["Key"]["Metric"]
# print(result['DataPoints'])
timestamps = [dp["Timestamp"] for dp in result["DataPoints"]]
values = [dp.get("Value") for dp in result["DataPoints"] if "Value" in dp]
for timestamp, value in zip(timestamps, values):
row = [
cluster_id,
instance_id,
metric_name,
timestamp.strftime("%Y-%m-%d %H:%M"),
value,
]
writer.writerow(row)
csv_data.seek(0)
# S3에 업로드
object_path = f"{bucket_path}/{object_key}"
s3_client.put_object(Bucket=bucket_name, Key=object_path, Body=csv_data.getvalue())
print(f"Data {object_key} uploaded to {bucket_name}/{bucket_path}/{object_key}")
def check_table_exists(database_name, table_name):
try:
athena_client.get_table_metadata(
CatalogName="AwsDataCatalog", DatabaseName="sales", TableName=table_name
)
return True
except ClientError as e:
if e.response["Error"]["Code"] == "EntityNotFoundException":
athena_client.start_query_execution(
QueryString=f"CREATE EXTERNAL TABLE {table_name}",
ResultConfiguration={"OutputLocation": s3_bucket_meta_path},
)
def retrieve_perf_metric_multiDatabase(keyword, start_time, end_time, user_query):
# 시간세팅 start_time, end_time이 비어있으면
print("start time:",start_time)
print("end time:",end_time)
# 데이터베이스 생성 (존재하지 않는 경우)
try:
athena_client.get_database(
CatalogName="AwsDataCatalog", DatabaseName=database_name
)
print("create database")
except ClientError as e:
if e.response["Error"]["Code"] == "EntityNotFoundException":
athena_client.start_query_execution(
QueryString=f"CREATE DATABASE {database_name}",
ResultConfiguration={"OutputLocation": s3_bucket_meta_path},
)
st.error(f"Error reading file from S3: {e}")
# 테이블이 존재하는 경우 삭제
if check_table_exists(database_name, cw_table_name):
athena_client.start_query_execution(
QueryString=f"DROP TABLE {database_name}.{cw_table_name}",
ResultConfiguration={"OutputLocation": s3_bucket_meta_path},
)
print(f"{database_name}.{cw_table_name} dropped!")
QueryString_input = f"""
CREATE EXTERNAL TABLE {database_name}.{cw_table_name} (
cluster_id string,
instance_id string,
metric string,
timestamp string,
value double
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LOCATION '{s3_bucket_table_cw_path}/'
TBLPROPERTIES ('skip.header.line.count'='1')
"""
print (QueryString_input)
athena_client.start_query_execution(