forked from jly8866/archer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.py
1023 lines (899 loc) · 48.3 KB
/
query.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 re
import simplejson as json
from django.core.urlresolvers import reverse
from django.db.models import Q, Min, F, Sum
from django.db import connection
from django.conf import settings
from django.db.models.functions import Concat
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.core import serializers
from django.db import transaction
from datetime import date
from django.db.models import Value as V
import datetime
import time
from sql.extend_json_encoder import ExtendJSONEncoder
from .aes_decryptor import Prpcrypt
from .sendmail import MailSender
from .dao import Dao
from .const import WorkflowDict
from .inception import InceptionDao
from .models import users, master_config, slave_config, QueryPrivilegesApply, QueryPrivileges, QueryLog, SlowQuery, \
SlowQueryHistory, AliyunRdsConfig
from .data_masking import Masking
from .workflow import Workflow
from .permission import role_required, superuser_required
if settings.ALIYUN_RDS_MANAGE:
from .aliyun_function import slowquery_review as aliyun_rds_slowquery_review, \
slowquery_review_history as aliyun_rds_slowquery_review_history
dao = Dao()
prpCryptor = Prpcrypt()
inceptionDao = InceptionDao()
datamasking = Masking()
workflowOb = Workflow()
mailSenderOb = MailSender()
# 查询权限申请用于工作流审核回调
def query_audit_call_back(workflow_id, workflow_status):
# 更新业务表状态
apply_info = QueryPrivilegesApply()
apply_info.apply_id = workflow_id
apply_info.status = workflow_status
apply_info.save(update_fields=['status'])
# 审核通过插入权限信息,批量插入,减少性能消耗
if workflow_status == WorkflowDict.workflow_status['audit_success']:
apply_queryset = QueryPrivilegesApply.objects.get(apply_id=workflow_id)
# 库权限
if apply_queryset.priv_type == 1:
insertlist = [QueryPrivileges(
user_name=apply_queryset.user_name,
cluster_name=apply_queryset.cluster_name, db_name=db_name,
table_name=apply_queryset.table_list, valid_date=apply_queryset.valid_date,
limit_num=apply_queryset.limit_num, priv_type=apply_queryset.priv_type) for db_name in
apply_queryset.db_list.split(',')]
# 表权限
elif apply_queryset.priv_type == 2:
insertlist = [QueryPrivileges(
user_name=apply_queryset.user_name,
cluster_name=apply_queryset.cluster_name, db_name=apply_queryset.db_list,
table_name=table_name, valid_date=apply_queryset.valid_date,
limit_num=apply_queryset.limit_num, priv_type=apply_queryset.priv_type) for table_name in
apply_queryset.table_list.split(',')]
QueryPrivileges.objects.bulk_create(insertlist)
# 查询权限校验
def query_priv_check(loginUserOb, cluster_name, dbName, sqlContent, limit_num):
finalResult = {'status': 0, 'msg': 'ok', 'data': {}}
# 检查用户是否有该数据库/表的查询权限
loginUser = loginUserOb.username
if loginUserOb.is_superuser == 1 or loginUserOb.role == 'DBA':
user_limit_num = getattr(settings, 'ADMIN_QUERY_LIMIT')
if int(limit_num) == 0:
limit_num = int(user_limit_num)
else:
limit_num = min(int(limit_num), int(user_limit_num))
pass
# 查看表结构和执行计划,inception会报错,故单独处理,explain直接跳过不做校验
elif re.match(r"^show\s+create\s+table", sqlContent.lower()):
tb_name = re.sub('^show\s+create\s+table', '', sqlContent, count=1, flags=0).strip()
# 先判断是否有整库权限
db_privileges = QueryPrivileges.objects.filter(user_name=loginUser, cluster_name=cluster_name,
db_name=dbName, priv_type=1,
valid_date__gte=datetime.datetime.now(), is_deleted=0)
# 无整库权限再验证表权限
if len(db_privileges) == 0:
tb_privileges = QueryPrivileges.objects.filter(user_name=loginUser, cluster_name=cluster_name,
db_name=dbName, table_name=tb_name, priv_type=2,
valid_date__gte=datetime.datetime.now(), is_deleted=0)
if len(tb_privileges) == 0:
finalResult['status'] = 1
finalResult['msg'] = '你无' + dbName + '.' + tb_name + '表的查询权限!请先到查询权限管理进行申请'
return finalResult
# sql查询, 可以校验到表级权限
else:
# 首先使用inception的语法树打印获取查询涉及的的表
table_ref_result = datamasking.query_table_ref(sqlContent + ';', cluster_name, dbName)
# 正确解析拿到表数据,可以校验表权限
if table_ref_result['status'] == 0:
table_ref = table_ref_result['data']
# 获取表信息,校验是否拥有全部表查询权限
QueryPrivilegesOb = QueryPrivileges.objects.filter(user_name=loginUser, cluster_name=cluster_name)
# 先判断是否有整库权限
for table in table_ref:
db_privileges = QueryPrivilegesOb.filter(db_name=table['db'], priv_type=1,
valid_date__gte=datetime.datetime.now(),
is_deleted=0)
# 无整库权限再验证表权限
if len(db_privileges) == 0:
tb_privileges = QueryPrivilegesOb.filter(db_name=table['db'], table_name=table['table'],
valid_date__gte=datetime.datetime.now(), is_deleted=0)
if len(tb_privileges) == 0:
finalResult['status'] = 1
finalResult['msg'] = '你无' + table['db'] + '.' + table['table'] + '表的查询权限!请先到查询权限管理进行申请'
return finalResult
# 获取表数据报错,检查配置文件是否允许继续执行,并进行库权限校验
else:
table_ref = None
# 校验库权限,防止inception的语法树打印错误时连库权限也未做校验
privileges = QueryPrivileges.objects.filter(user_name=loginUser, cluster_name=cluster_name, db_name=dbName,
valid_date__gte=datetime.datetime.now(),
is_deleted=0)
if len(privileges) == 0:
finalResult['status'] = 1
finalResult['msg'] = '你无' + dbName + '数据库的查询权限!请先到查询权限管理进行申请'
return finalResult
if settings.CHECK_QUERY_ON_OFF:
return table_ref_result
else:
pass
# 获取查询涉及表的最小limit限制
if table_ref:
db_list = [table_info['db'] for table_info in table_ref]
table_list = [table_info['table'] for table_info in table_ref]
user_limit_num = QueryPrivileges.objects.filter(user_name=loginUser,
cluster_name=cluster_name,
db_name__in=db_list,
table_name__in=table_list,
valid_date__gte=datetime.datetime.now(),
is_deleted=0).aggregate(Min('limit_num'))['limit_num__min']
if user_limit_num is None:
# 如果表没获取到则获取涉及库的最小limit限制
user_limit_num = QueryPrivileges.objects.filter(user_name=loginUser,
cluster_name=cluster_name,
db_name=dbName,
valid_date__gte=datetime.datetime.now(),
is_deleted=0).aggregate(Min('limit_num'))[
'limit_num__min']
else:
# 如果表没获取到则获取涉及库的最小limit限制
user_limit_num = QueryPrivileges.objects.filter(user_name=loginUser,
cluster_name=cluster_name,
db_name=dbName,
valid_date__gte=datetime.datetime.now(),
is_deleted=0).aggregate(Min('limit_num'))['limit_num__min']
if int(limit_num) == 0:
limit_num = user_limit_num
else:
limit_num = min(int(limit_num), user_limit_num)
finalResult['data'] = limit_num
return finalResult
# 获取所有集群名称
@csrf_exempt
def getClusterList(request):
slaves = slave_config.objects.all().order_by('cluster_name')
result = {'status': 0, 'msg': 'ok', 'data': []}
# 获取所有集群名称
listAllClusterName = [slave.cluster_name for slave in slaves]
result['data'] = listAllClusterName
return HttpResponse(json.dumps(result), content_type='application/json')
# 获取集群里面的数据库集合
@csrf_exempt
def getdbNameList(request):
clusterName = request.POST.get('cluster_name')
is_master = request.POST.get('is_master')
result = {'status': 0, 'msg': 'ok', 'data': []}
if is_master:
try:
master_info = master_config.objects.get(cluster_name=clusterName)
except Exception:
result['status'] = 1
result['msg'] = '找不到对应的主库配置信息,请配置'
return HttpResponse(json.dumps(result), content_type='application/json')
try:
# 取出该集群主库的连接方式,为了后面连进去获取所有databases
listDb = dao.getAlldbByCluster(master_info.master_host, master_info.master_port, master_info.master_user,
prpCryptor.decrypt(master_info.master_password))
# 要把result转成JSON存进数据库里,方便SQL单子详细信息展示
result['data'] = listDb
except Exception as msg:
result['status'] = 1
result['msg'] = str(msg)
else:
try:
slave_info = slave_config.objects.get(cluster_name=clusterName)
except Exception:
result['status'] = 1
result['msg'] = '找不到对应的从库配置信息,请配置'
return HttpResponse(json.dumps(result), content_type='application/json')
try:
# 取出该集群的连接方式,为了后面连进去获取所有databases
listDb = dao.getAlldbByCluster(slave_info.slave_host, slave_info.slave_port, slave_info.slave_user,
prpCryptor.decrypt(slave_info.slave_password))
# 要把result转成JSON存进数据库里,方便SQL单子详细信息展示
result['data'] = listDb
except Exception as msg:
result['status'] = 1
result['msg'] = str(msg)
return HttpResponse(json.dumps(result), content_type='application/json')
# 获取数据库的表集合
@csrf_exempt
def getTableNameList(request):
clusterName = request.POST.get('cluster_name')
db_name = request.POST.get('db_name')
is_master = request.POST.get('is_master')
result = {'status': 0, 'msg': 'ok', 'data': []}
if is_master:
try:
master_info = master_config.objects.get(cluster_name=clusterName)
except Exception:
result['status'] = 1
result['msg'] = '找不到对应的主库配置信息,请配置'
return HttpResponse(json.dumps(result), content_type='application/json')
try:
# 取出该集群主库的连接方式,为了后面连进去获取所有的表
listTb = dao.getAllTableByDb(master_info.master_host, master_info.master_port, master_info.master_user,
prpCryptor.decrypt(master_info.master_password), db_name)
# 要把result转成JSON存进数据库里,方便SQL单子详细信息展示
result['data'] = listTb
except Exception as msg:
result['status'] = 1
result['msg'] = str(msg)
else:
try:
slave_info = slave_config.objects.get(cluster_name=clusterName)
except Exception:
result['status'] = 1
result['msg'] = '找不到对应的从库配置信息,请配置'
return HttpResponse(json.dumps(result), content_type='application/json')
try:
# 取出该集群从库的连接方式,为了后面连进去获取所有的表
listTb = dao.getAllTableByDb(slave_info.slave_host, slave_info.slave_port, slave_info.slave_user,
prpCryptor.decrypt(slave_info.slave_password), db_name)
# 要把result转成JSON存进数据库里,方便SQL单子详细信息展示
result['data'] = listTb
except Exception as msg:
result['status'] = 1
result['msg'] = str(msg)
return HttpResponse(json.dumps(result), content_type='application/json')
# 获取表里面的字段集合
@csrf_exempt
def getColumnNameList(request):
clusterName = request.POST.get('cluster_name')
db_name = request.POST.get('db_name')
tb_name = request.POST.get('tb_name')
is_master = request.POST.get('is_master')
result = {'status': 0, 'msg': 'ok', 'data': []}
if is_master:
try:
master_info = master_config.objects.get(cluster_name=clusterName)
except Exception:
result['status'] = 1
result['msg'] = '找不到对应的主库配置信息,请配置'
return HttpResponse(json.dumps(result), content_type='application/json')
try:
# 取出该集群主库的连接方式,为了后面连进去获取所有字段
listCol = dao.getAllColumnsByTb(master_info.master_host, master_info.master_port, master_info.master_user,
prpCryptor.decrypt(master_info.master_password), db_name, tb_name)
# 要把result转成JSON存进数据库里,方便SQL单子详细信息展示
result['data'] = listCol
except Exception as msg:
result['status'] = 1
result['msg'] = str(msg)
else:
try:
slave_info = slave_config.objects.get(cluster_name=clusterName)
except Exception:
result['status'] = 1
result['msg'] = '找不到对应的从库配置信息,请配置'
return HttpResponse(json.dumps(result), content_type='application/json')
try:
# 取出该集群的连接方式,为了后面连进去获取表的所有字段
listCol = dao.getAllColumnsByTb(slave_info.slave_host, slave_info.slave_port, slave_info.slave_user,
prpCryptor.decrypt(slave_info.slave_password), db_name, tb_name)
# 要把result转成JSON存进数据库里,方便SQL单子详细信息展示
result['data'] = listCol
except Exception as msg:
result['status'] = 1
result['msg'] = str(msg)
return HttpResponse(json.dumps(result), content_type='application/json')
# 获取查询权限申请列表
@csrf_exempt
def getqueryapplylist(request):
# 获取用户信息
loginUser = request.session.get('login_username', False)
loginUserOb = users.objects.get(username=loginUser)
limit = int(request.POST.get('limit'))
offset = int(request.POST.get('offset'))
limit = offset + limit
# 获取搜索参数
search = request.POST.get('search')
if search is None:
search = ''
# 获取列表数据,申请人只能查看自己申请的数据,管理员可以看到全部数据
if loginUserOb.is_superuser == 1 or loginUserOb.role == 'DBA':
applylist = QueryPrivilegesApply.objects.all().filter(title__contains=search).order_by('-apply_id')[
offset:limit].values(
'apply_id', 'title', 'cluster_name', 'db_list', 'priv_type', 'table_list', 'limit_num', 'valid_date',
'user_name', 'status', 'create_time'
)
applylistCount = QueryPrivilegesApply.objects.all().filter(title__contains=search).count()
else:
applylist = QueryPrivilegesApply.objects.filter(user_name=loginUserOb.username).filter(
title__contains=search).order_by('-apply_id')[offset:limit].values(
'apply_id', 'title', 'cluster_name', 'db_list', 'priv_type', 'table_list', 'limit_num', 'valid_date',
'user_name', 'status', 'create_time'
)
applylistCount = QueryPrivilegesApply.objects.filter(user_name=loginUserOb.username).filter(
title__contains=search).count()
# QuerySet 序列化
rows = [row for row in applylist]
result = {"total": applylistCount, "rows": rows}
# 返回查询结果
return HttpResponse(json.dumps(result, cls=ExtendJSONEncoder, bigint_as_string=True),
content_type='application/json')
# 申请查询权限
@csrf_exempt
def applyforprivileges(request):
title = request.POST['title']
cluster_name = request.POST['cluster_name']
priv_type = request.POST['priv_type']
db_name = request.POST['db_name']
valid_date = request.POST['valid_date']
limit_num = request.POST['limit_num']
try:
workflow_remark = request.POST['apply_remark']
except Exception:
workflow_remark = ''
# 获取用户信息
loginUser = request.session.get('login_username', False)
# 服务端参数校验
result = {'status': 0, 'msg': 'ok', 'data': []}
if int(priv_type) == 1:
db_list = request.POST['db_list']
if title is None or cluster_name is None or db_list is None or valid_date is None or limit_num is None:
result['status'] = 1
result['msg'] = '请填写完整'
return HttpResponse(json.dumps(result), content_type='application/json')
elif int(priv_type) == 2:
table_list = request.POST['table_list']
if title is None or cluster_name is None or db_name is None or valid_date is None or table_list is None or limit_num is None:
result['status'] = 1
result['msg'] = '请填写完整'
return HttpResponse(json.dumps(result), content_type='application/json')
# 判断是否需要限制到表级别的权限
# 库权限
if int(priv_type) == 1:
db_list = db_list.split(',')
# 检查申请账号是否已拥整个库的查询权限
own_dbs = QueryPrivileges.objects.filter(cluster_name=cluster_name, user_name=loginUser, db_name__in=db_list,
valid_date__gte=datetime.datetime.now(), priv_type=1,
is_deleted=0).values('db_name')
own_db_list = [table_info['db_name'] for table_info in own_dbs]
if own_db_list is None:
pass
else:
for db_name in db_list:
if db_name in own_db_list:
result['status'] = 1
result['msg'] = '你已拥有' + cluster_name + '集群' + db_name + '库的全部查询权限,不能重复申请'
return HttpResponse(json.dumps(result), content_type='application/json')
# 表权限
elif int(priv_type) == 2:
table_list = table_list.split(',')
# 检查申请账号是否已拥有该表的查询权限
own_tables = QueryPrivileges.objects.filter(cluster_name=cluster_name, user_name=loginUser, db_name=db_name,
table_name__in=table_list, valid_date__gte=datetime.datetime.now(),
priv_type=2, is_deleted=0).values('table_name')
own_table_list = [table_info['table_name'] for table_info in own_tables]
if own_table_list is None:
pass
else:
for table_name in table_list:
if table_name in own_table_list:
result['status'] = 1
result['msg'] = '你已拥有' + cluster_name + '集群' + db_name + '.' + table_name + '表的查询权限,不能重复申请'
return HttpResponse(json.dumps(result), content_type='application/json')
# 使用事务保持数据一致性
try:
with transaction.atomic():
# 保存申请信息到数据库
applyinfo = QueryPrivilegesApply()
applyinfo.title = title
applyinfo.user_name = loginUser
applyinfo.cluster_name = cluster_name
if int(priv_type) == 1:
applyinfo.db_list = ','.join(db_list)
applyinfo.table_list = ''
elif int(priv_type) == 2:
applyinfo.db_list = db_name
applyinfo.table_list = ','.join(table_list)
applyinfo.priv_type = int(priv_type)
applyinfo.valid_date = valid_date
applyinfo.status = WorkflowDict.workflow_status['audit_wait'] # 待审核
applyinfo.limit_num = limit_num
applyinfo.create_user = loginUser
applyinfo.save()
apply_id = applyinfo.apply_id
# 调用工作流插入审核信息,查询权限申请workflow_type=2
auditresult = workflowOb.addworkflowaudit(request, WorkflowDict.workflow_type['query'], apply_id,
title, loginUser, workflow_remark)
if auditresult['status'] == 0:
# 更新业务表审核状态,判断是否插入权限信息
query_audit_call_back(apply_id, auditresult['data']['workflow_status'])
except Exception as msg:
result['status'] = 1
result['msg'] = str(msg)
else:
result = auditresult
return HttpResponse(json.dumps(result), content_type='application/json')
# 用户的查询权限管理
@csrf_exempt
def getuserprivileges(request):
user_name = request.POST.get('user_name')
limit = int(request.POST.get('limit'))
offset = int(request.POST.get('offset'))
limit = offset + limit
# 获取搜索参数
search = request.POST.get('search')
if search is None:
search = ''
# 判断权限,除了管理员外其他人只能查看自己的权限信息
result = {'status': 0, 'msg': 'ok', 'data': []}
loginUser = request.session.get('login_username', False)
loginUserOb = users.objects.get(username=loginUser)
# 获取用户的权限数据
if loginUserOb.is_superuser == 1 or loginUserOb.role == 'DBA':
if user_name != 'all':
privilegeslist = QueryPrivileges.objects.all().filter(user_name=user_name, is_deleted=0,
table_name__contains=search,
valid_date__gte=datetime.datetime.now()).order_by(
'-privilege_id')[offset:limit]
privilegeslistCount = QueryPrivileges.objects.all().filter(user_name=user_name, is_deleted=0,
table_name__contains=search,
valid_date__gte=datetime.datetime.now()).count()
else:
privilegeslist = QueryPrivileges.objects.all().filter(is_deleted=0, table_name__contains=search,
valid_date__gte=datetime.datetime.now()).order_by(
'-privilege_id')[offset:limit]
privilegeslistCount = QueryPrivileges.objects.all().filter(is_deleted=0,
table_name__contains=search,
valid_date__gte=datetime.datetime.now()).count()
else:
privilegeslist = QueryPrivileges.objects.filter(user_name=loginUserOb.username, is_deleted=0).filter(
table_name__contains=search).order_by('-privilege_id')[offset:limit]
privilegeslistCount = QueryPrivileges.objects.filter(user_name=loginUserOb.username, is_deleted=0).filter(
table_name__contains=search).count()
# QuerySet 序列化
privilegeslist = serializers.serialize("json", privilegeslist)
privilegeslist = json.loads(privilegeslist)
privilegeslist_result = []
for i in range(len(privilegeslist)):
privilegeslist[i]['fields']['id'] = privilegeslist[i]['pk']
privilegeslist_result.append(privilegeslist[i]['fields'])
result = {"total": privilegeslistCount, "rows": privilegeslist_result}
# 返回查询结果
return HttpResponse(json.dumps(result), content_type='application/json')
# 变更权限信息
@csrf_exempt
@superuser_required
def modifyqueryprivileges(request):
privilege_id = request.POST.get('privilege_id')
type = request.POST.get('type')
result = {'status': 0, 'msg': 'ok', 'data': []}
# type=1删除权限,type=2变更权限
privileges = QueryPrivileges()
if int(type) == 1:
# 删除权限
privileges.privilege_id = int(privilege_id)
privileges.is_deleted = 1
privileges.save(update_fields=['is_deleted'])
return HttpResponse(json.dumps(result), content_type='application/json')
elif int(type) == 2:
# 变更权限
valid_date = request.POST.get('valid_date')
limit_num = request.POST.get('limit_num')
privileges.privilege_id = int(privilege_id)
privileges.valid_date = valid_date
privileges.limit_num = limit_num
privileges.save(update_fields=['valid_date', 'limit_num'])
return HttpResponse(json.dumps(result), content_type='application/json')
# 查询权限审核
@csrf_exempt
def queryprivaudit(request):
apply_id = int(request.POST['apply_id'])
audit_status = int(request.POST['audit_status'])
audit_remark = request.POST.get('audit_remark')
if audit_remark is None:
audit_remark = ''
# 获取用户信息
loginUser = request.session.get('login_username', False)
# 使用事务保持数据一致性
try:
with transaction.atomic():
# 获取audit_id
audit_id = workflowOb.auditinfobyworkflow_id(workflow_id=apply_id,
workflow_type=WorkflowDict.workflow_type['query']).audit_id
# 调用工作流接口审核
auditresult = workflowOb.auditworkflow(audit_id, audit_status, loginUser, audit_remark)
# 按照审核结果更新业务表审核状态
auditInfo = workflowOb.auditinfo(audit_id)
if auditInfo.workflow_type == WorkflowDict.workflow_type['query']:
# 更新业务表审核状态,插入权限信息
query_audit_call_back(auditInfo.workflow_id, auditresult['data']['workflow_status'])
# 给拒绝和审核通过的申请人发送邮件
if settings.MAIL_ON_OFF == "on":
email_reciver = users.objects.get(username=auditInfo.create_user).email
email_content = "发起人:" + auditInfo.create_user + "\n审核人:" + auditInfo.audit_users \
+ "\n工单地址:" + request.scheme + "://" + request.get_host() + "/workflowdetail/" \
+ str(audit_id) + "\n工单名称: " + auditInfo.workflow_title \
+ "\n审核备注: " + audit_remark
if auditresult['data']['workflow_status'] == WorkflowDict.workflow_status['audit_success']:
email_title = "工单审核通过 # " + str(auditInfo.audit_id)
mailSenderOb.sendEmail(email_title, email_content, [email_reciver])
elif auditresult['data']['workflow_status'] == WorkflowDict.workflow_status['audit_reject']:
email_title = "工单被驳回 # " + str(auditInfo.audit_id)
mailSenderOb.sendEmail(email_title, email_content, [email_reciver])
except Exception as msg:
context = {'errMsg': msg}
return render(request, 'error.html', context)
return HttpResponseRedirect(reverse('sql:queryapplydetail', args=(apply_id,)))
# 获取SQL查询结果
@csrf_exempt
def query(request):
cluster_name = request.POST.get('cluster_name')
sqlContent = request.POST.get('sql_content')
dbName = request.POST.get('db_name')
limit_num = request.POST.get('limit_num')
finalResult = {'status': 0, 'msg': 'ok', 'data': {}}
# 服务器端参数验证
if sqlContent is None or dbName is None or cluster_name is None or limit_num is None:
finalResult['status'] = 1
finalResult['msg'] = '页面提交参数可能为空'
return HttpResponse(json.dumps(finalResult), content_type='application/json')
sqlContent = sqlContent.strip()
if sqlContent[-1] != ";":
finalResult['status'] = 1
finalResult['msg'] = 'SQL语句结尾没有以;结尾,请重新修改并提交!'
return HttpResponse(json.dumps(finalResult), content_type='application/json')
# 获取用户信息
loginUser = request.session.get('login_username', False)
loginUserOb = users.objects.get(username=loginUser)
# 过滤注释语句和非查询的语句
sqlContent = ''.join(
map(lambda x: re.compile(r'(^--\s+.*|^/\*.*\*/;\s*$)').sub('', x, count=1),
sqlContent.splitlines(1))).strip()
# 去除空行
sqlContent = re.sub('[\r\n\f]{2,}', '\n', sqlContent)
sql_list = sqlContent.strip().split('\n')
for sql in sql_list:
if re.match(r"^select|^show|^explain", sql.lower()):
break
else:
finalResult['status'] = 1
finalResult['msg'] = '仅支持^select|^show|^explain语法,请联系管理员!'
return HttpResponse(json.dumps(finalResult), content_type='application/json')
# 取出该集群的连接方式,查询只读账号,按照分号截取第一条有效sql执行
slave_info = slave_config.objects.get(cluster_name=cluster_name)
sqlContent = sqlContent.strip().split(';')[0]
# 查询权限校验,以及limit_num获取
priv_check_info = query_priv_check(loginUserOb, cluster_name, dbName, sqlContent, limit_num)
if priv_check_info['status'] == 0:
limit_num = priv_check_info['data']
else:
return HttpResponse(json.dumps(priv_check_info), content_type='application/json')
if re.match(r"^explain", sqlContent.lower()):
limit_num = 0
# 对查询sql增加limit限制
if re.match(r"^select", sqlContent.lower()):
if re.search(r"limit\s+(\d+)$", sqlContent.lower()) is None:
if re.search(r"limit\s+\d+\s*,\s*(\d+)$", sqlContent.lower()) is None:
sqlContent = sqlContent + ' limit ' + str(limit_num)
sqlContent = sqlContent + ';'
# 执行查询语句,统计执行时间
t_start = time.time()
sql_result = dao.mysql_query(slave_info.slave_host, slave_info.slave_port, slave_info.slave_user,
prpCryptor.decrypt(slave_info.slave_password), str(dbName), sqlContent, limit_num)
t_end = time.time()
cost_time = "%5s" % "{:.4f}".format(t_end - t_start)
sql_result['cost_time'] = cost_time
# 数据脱敏,同样需要检查配置,是否开启脱敏,语法树解析是否允许出错继续执行
t_start = time.time()
if settings.DATA_MASKING_ON_OFF:
# 仅对查询语句进行脱敏
if re.match(r"^select", sqlContent.lower()):
try:
masking_result = datamasking.data_masking(cluster_name, dbName, sqlContent, sql_result)
except Exception:
if settings.CHECK_QUERY_ON_OFF:
finalResult['status'] = 1
finalResult['msg'] = '脱敏数据报错,请联系管理员'
return HttpResponse(json.dumps(finalResult), content_type='application/json')
else:
if masking_result['status'] != 0:
if settings.CHECK_QUERY_ON_OFF:
return HttpResponse(json.dumps(masking_result), content_type='application/json')
t_end = time.time()
masking_cost_time = "%5s" % "{:.4f}".format(t_end - t_start)
sql_result['masking_cost_time'] = masking_cost_time
finalResult['data'] = sql_result
# 成功的查询语句记录存入数据库
if sql_result.get('Error'):
pass
else:
query_log = QueryLog()
query_log.username = loginUser
query_log.db_name = dbName
query_log.cluster_name = cluster_name
query_log.sqllog = sqlContent
if int(limit_num) == 0:
limit_num = int(sql_result['effect_row'])
else:
limit_num = min(int(limit_num), int(sql_result['effect_row']))
query_log.effect_row = limit_num
query_log.cost_time = cost_time
# 防止查询超时
try:
query_log.save()
except:
connection.close()
query_log.save()
# 返回查询结果
return HttpResponse(json.dumps(finalResult, cls=ExtendJSONEncoder, bigint_as_string=True),
content_type='application/json')
# 获取sql查询记录
@csrf_exempt
def querylog(request):
# 获取用户信息
loginUser = request.session.get('login_username', False)
loginUserOb = users.objects.get(username=loginUser)
limit = int(request.POST.get('limit'))
offset = int(request.POST.get('offset'))
limit = offset + limit
# 获取搜索参数
search = request.POST.get('search')
if search is None:
search = ''
# 查询个人记录,超管查看所有数据
if loginUserOb.is_superuser == 1 or loginUserOb.role == 'DBA':
sql_log_count = QueryLog.objects.all().filter(Q(sqllog__contains=search) | Q(username__contains=search)).count()
sql_log_list = QueryLog.objects.all().filter(
Q(sqllog__contains=search) | Q(username__contains=search)).order_by(
'-id')[offset:limit]
else:
sql_log_count = QueryLog.objects.filter(username=loginUser).filter(
Q(sqllog__contains=search) | Q(username__contains=search)).count()
sql_log_list = QueryLog.objects.filter(username=loginUser).filter(
Q(sqllog__contains=search) | Q(username__contains=search)).order_by('-id')[offset:limit]
# QuerySet 序列化
sql_log_list = serializers.serialize("json", sql_log_list)
sql_log_list = json.loads(sql_log_list)
sql_log = [log_info['fields'] for log_info in sql_log_list]
result = {"total": sql_log_count, "rows": sql_log}
# 返回查询结果
return HttpResponse(json.dumps(result), content_type='application/json')
# 获取SQL执行计划
@csrf_exempt
def explain(request):
if request.is_ajax():
sqlContent = request.POST.get('sql_content')
clusterName = request.POST.get('cluster_name')
dbName = request.POST.get('db_name')
else:
sqlContent = request.POST['sql_content']
clusterName = request.POST['cluster_name']
dbName = request.POST.get('db_name')
finalResult = {'status': 0, 'msg': 'ok', 'data': []}
# 服务器端参数验证
if sqlContent is None or clusterName is None:
finalResult['status'] = 1
finalResult['msg'] = '页面提交参数可能为空'
return HttpResponse(json.dumps(finalResult), content_type='application/json')
sqlContent = sqlContent.rstrip()
if sqlContent[-1] != ";":
finalResult['status'] = 1
finalResult['msg'] = 'SQL语句结尾没有以;结尾,请重新修改并提交!'
return HttpResponse(json.dumps(finalResult), content_type='application/json')
# 过滤非查询的语句
if re.match(r"^explain", sqlContent.lower()):
pass
else:
finalResult['status'] = 1
finalResult['msg'] = '仅支持explain开头的语句,请检查'
return HttpResponse(json.dumps(finalResult), content_type='application/json')
# 取出该集群的连接方式,按照分号截取第一条有效sql执行
masterInfo = master_config.objects.get(cluster_name=clusterName)
sqlContent = sqlContent.strip().split(';')[0]
# 执行获取执行计划语句
sql_result = dao.mysql_query(masterInfo.master_host, masterInfo.master_port, masterInfo.master_user,
prpCryptor.decrypt(masterInfo.master_password), str(dbName), sqlContent)
finalResult['data'] = sql_result
# 返回查询结果
return HttpResponse(json.dumps(finalResult, cls=ExtendJSONEncoder, bigint_as_string=True),
content_type='application/json')
# 获取SQL慢日志统计
@csrf_exempt
def slowquery_review(request):
cluster_name = request.POST.get('cluster_name')
# 判断是RDS还是其他实例
cluster_info = master_config.objects.get(cluster_name=cluster_name)
if len(AliyunRdsConfig.objects.filter(cluster_name=cluster_name)) > 0:
if settings.ALIYUN_RDS_MANAGE:
# 调用阿里云慢日志接口
result = aliyun_rds_slowquery_review(request)
else:
raise Exception('未开启rds管理,无法查看rds数据!')
else:
StartTime = request.POST.get('StartTime')
EndTime = request.POST.get('EndTime')
DBName = request.POST.get('db_name')
limit = int(request.POST.get('limit'))
offset = int(request.POST.get('offset'))
limit = offset + limit
# 时间处理
EndTime = datetime.datetime.strptime(EndTime, '%Y-%m-%d') + datetime.timedelta(days=1)
# DBName非必传
if DBName:
# 获取慢查数据
slowsql_obj = SlowQuery.objects.filter(
slowqueryhistory__hostname_max=(cluster_info.master_host + ':' + str(cluster_info.master_port)),
slowqueryhistory__db_max=DBName,
slowqueryhistory__ts_min__range=(StartTime, EndTime),
last_seen__range=(StartTime, EndTime)
).annotate(CreateTime=F('last_seen'),
SQLId=F('checksum'),
DBName=F('slowqueryhistory__db_max'), # 数据库
SQLText=F('fingerprint'), # SQL语句
).values(
'CreateTime', 'SQLId', 'DBName', 'SQLText'
).annotate(
MySQLTotalExecutionCounts=Sum('slowqueryhistory__ts_cnt'), # 执行总次数
MySQLTotalExecutionTimes=Sum('slowqueryhistory__query_time_sum'), # 执行总时长
ParseTotalRowCounts=Sum('slowqueryhistory__rows_examined_sum'), # 扫描总行数
ReturnTotalRowCounts=Sum('slowqueryhistory__rows_sent_sum'), # 返回总行数
).order_by('-MySQLTotalExecutionCounts')[offset:limit] # 执行总次数倒序排列
slowsql_obj_count = SlowQuery.objects.filter(
slowqueryhistory__hostname_max=(cluster_info.master_host + ':' + str(cluster_info.master_port)),
slowqueryhistory__db_max=DBName,
slowqueryhistory__ts_min__range=(StartTime, EndTime),
last_seen__range=(StartTime, EndTime)
).annotate(CreateTime=F('last_seen'),
SQLId=F('checksum'),
DBName=F('slowqueryhistory__db_max'), # 数据库
SQLText=F('fingerprint'), # SQL语句
).values(
'CreateTime', 'SQLId', 'DBName', 'SQLText'
).annotate(
MySQLTotalExecutionCounts=Sum('slowqueryhistory__ts_cnt'), # 执行总次数
MySQLTotalExecutionTimes=Sum('slowqueryhistory__query_time_sum'), # 执行总时长
ParseTotalRowCounts=Sum('slowqueryhistory__rows_examined_sum'), # 扫描总行数
ReturnTotalRowCounts=Sum('slowqueryhistory__rows_sent_sum'), # 返回总行数
).count()
else:
# 获取慢查数据
slowsql_obj = SlowQuery.objects.filter(
slowqueryhistory__hostname_max=(cluster_info.master_host + ':' + str(cluster_info.master_port)),
slowqueryhistory__ts_min__range=(StartTime, EndTime),
last_seen__range=(StartTime, EndTime)
).annotate(CreateTime=F('last_seen'),
SQLId=F('checksum'),
DBName=F('slowqueryhistory__db_max'), # 数据库
SQLText=F('fingerprint'), # SQL语句
).values(
'CreateTime', 'SQLId', 'DBName', 'SQLText'
).annotate(
MySQLTotalExecutionCounts=Sum('slowqueryhistory__ts_cnt'), # 执行总次数
MySQLTotalExecutionTimes=Sum('slowqueryhistory__query_time_sum'), # 执行总时长
ParseTotalRowCounts=Sum('slowqueryhistory__rows_examined_sum'), # 扫描总行数
ReturnTotalRowCounts=Sum('slowqueryhistory__rows_sent_sum'), # 返回总行数
).order_by('-MySQLTotalExecutionCounts')[offset:limit] # 执行总次数倒序排列
slowsql_obj_count = SlowQuery.objects.filter(
slowqueryhistory__hostname_max=(cluster_info.master_host + ':' + str(cluster_info.master_port)),
slowqueryhistory__ts_min__range=(StartTime, EndTime),
last_seen__range=(StartTime, EndTime)
).annotate(CreateTime=F('last_seen'),
SQLId=F('checksum'),
DBName=F('slowqueryhistory__db_max'), # 数据库
SQLText=F('fingerprint'), # SQL语句
).values(
'CreateTime', 'SQLId', 'DBName', 'SQLText'
).annotate(
MySQLTotalExecutionCounts=Sum('slowqueryhistory__ts_cnt'), # 执行总次数
MySQLTotalExecutionTimes=Sum('slowqueryhistory__query_time_sum'), # 执行总时长
ParseTotalRowCounts=Sum('slowqueryhistory__rows_examined_sum'), # 扫描总行数
ReturnTotalRowCounts=Sum('slowqueryhistory__rows_sent_sum'), # 返回总行数
).count()
# QuerySet 序列化
SQLSlowLog = [SlowLog for SlowLog in slowsql_obj]
result = {"total": slowsql_obj_count, "rows": SQLSlowLog}
# 返回查询结果
return HttpResponse(json.dumps(result, cls=ExtendJSONEncoder, bigint_as_string=True),
content_type='application/json')
# 获取SQL慢日志明细
@csrf_exempt
def slowquery_review_history(request):
cluster_name = request.POST.get('cluster_name')
# 判断是RDS还是其他实例
cluster_info = master_config.objects.get(cluster_name=cluster_name)
if len(AliyunRdsConfig.objects.filter(cluster_name=cluster_name)) > 0:
if settings.ALIYUN_RDS_MANAGE:
# 调用阿里云慢日志接口
result = aliyun_rds_slowquery_review_history(request)
else:
raise Exception('未开启rds管理,无法查看rds数据!')
else:
StartTime = request.POST.get('StartTime')
EndTime = request.POST.get('EndTime')
DBName = request.POST.get('db_name')
SQLId = request.POST.get('SQLId')
limit = int(request.POST.get('limit'))
offset = int(request.POST.get('offset'))
# 时间处理
EndTime = datetime.datetime.strptime(EndTime, '%Y-%m-%d') + datetime.timedelta(days=1)
limit = offset + limit
# SQLId、DBName非必传
if SQLId:
# 获取慢查明细数据
slowsql_record_obj = SlowQueryHistory.objects.filter(
hostname_max=(cluster_info.master_host + ':' + str(cluster_info.master_port)),
checksum=SQLId,
ts_min__range=(StartTime, EndTime)
).annotate(ExecutionStartTime=F('ts_min'), # 执行开始时间
DBName=F('db_max'), # 数据库名
HostAddress=Concat(V('\''), 'user_max', V('\''), V('@'), V('\''), 'client_max', V('\'')), # 用户名
SQLText=F('sample'), # SQL语句
QueryTimes=F('query_time_sum'), # 执行时长(秒)
LockTimes=F('lock_time_sum'), # 锁定时长(秒)
ParseRowCounts=F('rows_examined_sum'), # 解析行数
ReturnRowCounts=F('rows_sent_sum') # 返回行数
).values(
'ExecutionStartTime', 'DBName', 'HostAddress', 'SQLText', 'QueryTimes', 'LockTimes', 'ParseRowCounts',
'ReturnRowCounts'
)[offset:limit]
slowsql_obj_count = SlowQueryHistory.objects.filter(
hostname_max=(cluster_info.master_host + ':' + str(cluster_info.master_port)),
checksum=SQLId,
ts_min__range=(StartTime, EndTime)
).count()
else:
if DBName:
# 获取慢查明细数据
slowsql_record_obj = SlowQueryHistory.objects.filter(
hostname_max=(cluster_info.master_host + ':' + str(cluster_info.master_port)),
db_max=DBName,
ts_min__range=(StartTime, EndTime)
).annotate(ExecutionStartTime=F('ts_min'), # 执行开始时间
DBName=F('db_max'), # 数据库名
HostAddress=Concat(V('\''), 'user_max', V('\''), V('@'), V('\''), 'client_max', V('\'')), # 用户名
SQLText=F('sample'), # SQL语句
QueryTimes=F('query_time_sum'), # 执行时长(秒)
LockTimes=F('lock_time_sum'), # 锁定时长(秒)
ParseRowCounts=F('rows_examined_sum'), # 解析行数
ReturnRowCounts=F('rows_sent_sum') # 返回行数
).values(
'ExecutionStartTime', 'DBName', 'HostAddress', 'SQLText', 'QueryTimes', 'LockTimes',
'ParseRowCounts',
'ReturnRowCounts'
)[offset:limit] # 执行总次数倒序排列
slowsql_obj_count = SlowQueryHistory.objects.filter(
hostname_max=(cluster_info.master_host + ':' + str(cluster_info.master_port)),
db_max=DBName,
ts_min__range=(StartTime, EndTime)
).count()
else:
# 获取慢查明细数据
slowsql_record_obj = SlowQueryHistory.objects.filter(
hostname_max=(cluster_info.master_host + ':' + str(cluster_info.master_port)),
ts_min__range=(StartTime, EndTime)
).annotate(ExecutionStartTime=F('ts_min'), # 执行开始时间
DBName=F('db_max'), # 数据库名