Skip to content

Commit d53e1ed

Browse files
committed
sql工单执行操作迁移至api
1 parent b34cdd0 commit d53e1ed

File tree

7 files changed

+231
-230
lines changed

7 files changed

+231
-230
lines changed

sql/sql_workflow.py

Lines changed: 0 additions & 148 deletions
Original file line numberDiff line numberDiff line change
@@ -97,154 +97,6 @@ def passed(request):
9797
return HttpResponseRedirect(reverse("sql:detail", args=(workflow_id,)))
9898

9999

100-
def execute(request):
101-
"""
102-
执行SQL
103-
:param request:
104-
:return:
105-
"""
106-
# 校验多个权限
107-
if not (
108-
request.user.has_perm("sql.sql_execute")
109-
or request.user.has_perm("sql.sql_execute_for_resource_group")
110-
):
111-
raise PermissionDenied
112-
workflow_id = int(request.POST.get("workflow_id", 0))
113-
if workflow_id == 0:
114-
context = {"errMsg": "workflow_id参数为空."}
115-
return render(request, "error.html", context)
116-
117-
if can_execute(request.user, workflow_id) is False:
118-
context = {"errMsg": "你无权操作当前工单!"}
119-
return render(request, "error.html", context)
120-
121-
if on_correct_time_period(workflow_id) is False:
122-
context = {"errMsg": "不在可执行时间范围内,如果需要修改执行时间请重新提交工单!"}
123-
return render(request, "error.html", context)
124-
# 获取审核信息
125-
audit_id = Audit.detail_by_workflow_id(
126-
workflow_id=workflow_id, workflow_type=WorkflowDict.workflow_type["sqlreview"]
127-
).audit_id
128-
# 根据执行模式进行对应修改
129-
mode = request.POST.get("mode")
130-
# 交由系统执行
131-
if mode == "auto":
132-
# 修改工单状态为排队中
133-
SqlWorkflow(id=workflow_id, status="workflow_queuing").save(
134-
update_fields=["status"]
135-
)
136-
# 删除定时执行任务
137-
schedule_name = f"sqlreview-timing-{workflow_id}"
138-
del_schedule(schedule_name)
139-
# 加入执行队列
140-
async_task(
141-
"sql.utils.execute_sql.execute",
142-
workflow_id,
143-
request.user,
144-
hook="sql.utils.execute_sql.execute_callback",
145-
timeout=-1,
146-
task_name=f"sqlreview-execute-{workflow_id}",
147-
)
148-
# 增加工单日志
149-
Audit.add_log(
150-
audit_id=audit_id,
151-
operation_type=5,
152-
operation_type_desc="执行工单",
153-
operation_info="工单执行排队中",
154-
operator=request.user.username,
155-
operator_display=request.user.display,
156-
)
157-
158-
# 线下手工执行
159-
elif mode == "manual":
160-
# 将流程状态修改为执行结束
161-
SqlWorkflow(
162-
id=workflow_id,
163-
status="workflow_finish",
164-
finish_time=datetime.datetime.now(),
165-
).save(update_fields=["status", "finish_time"])
166-
# 增加工单日志
167-
Audit.add_log(
168-
audit_id=audit_id,
169-
operation_type=6,
170-
operation_type_desc="手工工单",
171-
operation_info="确认手工执行结束",
172-
operator=request.user.username,
173-
operator_display=request.user.display,
174-
)
175-
# 开启了Execute阶段通知参数才发送消息通知
176-
sys_config = SysConfig()
177-
is_notified = (
178-
"Execute" in sys_config.get("notify_phase_control").split(",")
179-
if sys_config.get("notify_phase_control")
180-
else True
181-
)
182-
if is_notified:
183-
notify_for_execute(SqlWorkflow.objects.get(id=workflow_id))
184-
return HttpResponseRedirect(reverse("sql:detail", args=(workflow_id,)))
185-
186-
187-
def timing_task(request):
188-
"""
189-
定时执行SQL
190-
:param request:
191-
:return:
192-
"""
193-
# 校验多个权限
194-
if not (
195-
request.user.has_perm("sql.sql_execute")
196-
or request.user.has_perm("sql.sql_execute_for_resource_group")
197-
):
198-
raise PermissionDenied
199-
workflow_id = request.POST.get("workflow_id")
200-
run_date = request.POST.get("run_date")
201-
if run_date is None or workflow_id is None:
202-
context = {"errMsg": "时间不能为空"}
203-
return render(request, "error.html", context)
204-
elif run_date < datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"):
205-
context = {"errMsg": "时间不能小于当前时间"}
206-
return render(request, "error.html", context)
207-
workflow_detail = SqlWorkflow.objects.get(id=workflow_id)
208-
209-
if can_timingtask(request.user, workflow_id) is False:
210-
context = {"errMsg": "你无权操作当前工单!"}
211-
return render(request, "error.html", context)
212-
213-
run_date = datetime.datetime.strptime(run_date, "%Y-%m-%d %H:%M")
214-
schedule_name = f"sqlreview-timing-{workflow_id}"
215-
216-
if on_correct_time_period(workflow_id, run_date) is False:
217-
context = {"errMsg": "不在可执行时间范围内,如果需要修改执 行时间请重新提交工单!"}
218-
return render(request, "error.html", context)
219-
220-
# 使用事务保持数据一致性
221-
try:
222-
with transaction.atomic():
223-
# 将流程状态修改为定时执行
224-
workflow_detail.status = "workflow_timingtask"
225-
workflow_detail.save()
226-
# 调用添加定时任务
227-
add_sql_schedule(schedule_name, run_date, workflow_id)
228-
# 增加工单日志
229-
audit_id = Audit.detail_by_workflow_id(
230-
workflow_id=workflow_id,
231-
workflow_type=WorkflowDict.workflow_type["sqlreview"],
232-
).audit_id
233-
Audit.add_log(
234-
audit_id=audit_id,
235-
operation_type=4,
236-
operation_type_desc="定时执行",
237-
operation_info="定时执行时间:{}".format(run_date),
238-
operator=request.user.username,
239-
operator_display=request.user.display,
240-
)
241-
except Exception as msg:
242-
logger.error(f"定时执行工单报错,错误信息:{traceback.format_exc()}")
243-
context = {"errMsg": msg}
244-
return render(request, "error.html", context)
245-
return HttpResponseRedirect(reverse("sql:detail", args=(workflow_id,)))
246-
247-
248100
def cancel(request):
249101
"""
250102
终止流程

sql/templates/detail.html

Lines changed: 45 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@ <h4 style="display: inline;">
99
</h4>
1010
<!--只允许发起人提交其他实例-->
1111
{% if user.username == workflow_detail.engineer %}
12-
<a type='button' id="btnSubmitOtherCluster" class='btn btn-warning' href="/submitotherinstance/">上线其他实例</a>
12+
<a type='button' id="btnSubmitOtherCluster" class='btn btn-warning'
13+
href="/submitotherinstance/">上线其他实例</a>
1314
{% endif %}
1415
{% if is_can_review or is_can_execute or is_can_rollback or user.is_superuser %}
15-
<a type='button' id="btnViewSql" class='btn btn-default' onclick="loading(this)" href="/editsql/">查看提交信息</a>
16+
<a type='button' id="btnViewSql" class='btn btn-default' onclick="loading(this)"
17+
href="/editsql/">查看提交信息</a>
1618
{% endif %}
1719
</div>
1820
<input type="hidden" id="sqlMaxRowNumber" value="{{ rows|length }}">
@@ -194,29 +196,18 @@ <h4 style="display: inline;">
194196
{% endif %}
195197
<!--立即执行按钮-->
196198
{% if is_can_execute %}
197-
<form id="from-execute" action="/execute/" method="post" style="display:inline-block;">
198-
{% csrf_token %}
199-
<input type="hidden" name="mode" value="auto">
200-
<input type="hidden" name="workflow_id" value="{{ workflow_detail.id }}">
201-
<input type="button" id="btnExecuteOnly" class="btn btn-danger"
202-
value="立即执行"/>
203-
</form>
199+
<input type="button" id="btnExecuteOnly" class="btn btn-danger" value="立即执行"/>
204200
{% if manual %}
205-
<form id="from-execute-manual" action="/execute/" method="post" style="display:inline-block;">
206-
{% csrf_token %}
207-
<input type="hidden" name="mode" value="manual">
208-
<input type="hidden" name="workflow_id" value="{{ workflow_detail.id }}">
209-
<input type="button" id="btnExecuteOnly-manual" class="btn btn-warning"
210-
value="已手动完成"/>
211-
</form>
201+
<input type="button" id="btnExecuteOnly-manual" class="btn btn-warning" value="已手动完成"/>
212202
{% endif %}
213203
{% endif %}
214204
<!--定时执行按钮-->
215205
{% if is_can_timingtask %}
216206
{% if workflow_detail.status == 'workflow_review_pass' %}
217207
<input type="button" class="btn btn-info" data-toggle="modal" data-target="#cronComfirm" value="定时执行"/>
218208
{% elif workflow_detail.status == 'workflow_timingtask' %}
219-
<input type="button" class="btn btn-info" data-toggle="modal" data-target="#cronComfirm" value="执行时间变更"/>
209+
<input type="button" class="btn btn-info" data-toggle="modal" data-target="#cronComfirm"
210+
value="执行时间变更"/>
220211
{% endif %}
221212
{% endif %}
222213
<!--终止执行按钮-->
@@ -279,8 +270,6 @@ <h4 class="modal-title text-danger">定时执行SQL</h4>
279270
</div>
280271
<div class="modal-footer">
281272
<button type="button" class="btn btn-info" data-dismiss="modal">取消</button>
282-
283-
<input type="hidden" name="workflow_id" value="{{ workflow_detail.id }}">
284273
<input type="button" id="btnAddsqlcronjob" class="btn btn-danger" value="确认提交"/>
285274
</div>
286275

@@ -465,20 +454,22 @@ <h4 class="modal-title text-danger">修改可执行时间</h4>
465454
} else {
466455
var isContinue = confirm("请确认是否立即执行?");
467456
}
468-
var formExecuteOnly = $("#from-execute");
469457
if (isContinue) {
470-
formExecuteOnly.submit();
471-
loading(this)
458+
sqlWorkflowAction('post', 'execute', JSON.stringify({
459+
"mode": "auto",
460+
}, $(this).attr('id')
461+
))
472462
}
473463
});
474464

475465
// 执行确认手工执行
476466
$("#btnExecuteOnly-manual").click(function () {
477467
var isContinue = confirm("请确认是否已经手工执行结束?");
478-
var formExecuteOnly = $("#from-execute-manual");
479468
if (isContinue) {
480-
formExecuteOnly.submit();
481-
loading(this)
469+
sqlWorkflowAction('post', 'execute', JSON.stringify({
470+
"mode": "manual",
471+
}, $(this).attr('id')
472+
))
482473
}
483474
});
484475

@@ -506,33 +497,47 @@ <h4 class="modal-title text-danger">修改可执行时间</h4>
506497

507498
// 定时时间校验
508499
$("#btnAddsqlcronjob").click(function () {
509-
//获取form对象,判断输入,通过则提交
510-
var formAddsqlcronjo = $("#from-addsqlcronjob");
511-
if ($("#run_date").val()) {
512-
loading(this);
513-
formAddsqlcronjo.submit();
500+
let run_date = $("#run_date").val()
501+
if (run_date) {
502+
sqlWorkflowAction('post', 'timing_task', JSON.stringify({
503+
"run_date": run_date,
504+
}, $(this).attr('id')
505+
))
514506
} else {
515507
alert('请填写定时执行时间')
516508
}
517509
});
518510

519511
// 修改可执行时间
520512
$("#btnalterExecutabletime").click(function () {
513+
sqlWorkflowAction('patch', 'alter_run_date', JSON.stringify({
514+
run_date_start: $("#run_date_start").val(),
515+
run_date_end: $("#run_date_end").val(),
516+
}, $(this).attr('id')
517+
))
518+
});
519+
520+
// 按钮禁用
521+
function loading(obj) {
522+
$(obj).button('loading').delay(2500).queue(function () {
523+
$(obj).button('reset');
524+
$(obj).dequeue();
525+
});
526+
}
527+
528+
// 工单操作
529+
function sqlWorkflowAction(http_method ,action, data, btnAttrId) {
521530
$.ajax({
522-
type: "patch",
523-
url: "/api/v2/workflow/sql/{{ workflow_detail.id }}/alter_run_date/",
531+
type: http_method,
532+
url: "/api/v2/workflow/sql/{{ workflow_detail.id }}/" + action + "/",
524533
dataType: "json",
525534
contentType: 'application/json;',
526-
data: JSON.stringify({
527-
run_date_start: $("#run_date_start").val(),
528-
run_date_end: $("#run_date_end").val(),
529-
}
530-
),
535+
data: data,
531536
beforeSend: function (xhr) {
532-
$('#btnalterExecutabletime').button('loading')
537+
$('#' + btnAttrId).button('loading')
533538
},
534539
complete: function () {
535-
$('#btnalterExecutabletime').button('reset')
540+
$('#' + btnAttrId).button('reset')
536541
},
537542
success: function (data) {
538543
window.location.reload();
@@ -545,15 +550,8 @@ <h4 class="modal-title text-danger">修改可执行时间</h4>
545550
}
546551
}
547552
});
548-
});
549-
550-
// 按钮禁用
551-
function loading(obj) {
552-
$(obj).button('loading').delay(2500).queue(function () {
553-
$(obj).button('reset');
554-
$(obj).dequeue();
555-
});
556553
}
554+
557555
</script>
558556
<!--表格初始化 -->
559557
<script>

sql/tests.py

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1502,23 +1502,6 @@ def testWorkflowPassedView(self, _can_review, _audit, _detail_by_id):
15021502
self.wf1.refresh_from_db()
15031503
self.assertEqual(self.wf1.status, "workflow_review_pass")
15041504

1505-
@patch("sql.sql_workflow.Audit.add_log")
1506-
@patch("sql.sql_workflow.Audit.detail_by_workflow_id")
1507-
@patch("sql.sql_workflow.can_execute")
1508-
def test_workflow_execute(self, mock_can_excute, mock_detail_by_id, mock_add_log):
1509-
"""测试工单执行"""
1510-
c = Client()
1511-
c.force_login(self.executor1)
1512-
r = c.post("/execute/")
1513-
self.assertContains(r, "workflow_id参数为空.")
1514-
mock_can_excute.return_value = False
1515-
r = c.post("/execute/", data={"workflow_id": self.wf2.id})
1516-
self.assertContains(r, "你无权操作当前工单!")
1517-
mock_can_excute.return_value = True
1518-
mock_detail_by_id = 123
1519-
r = c.post("/execute/", data={"workflow_id": self.wf2.id, "mode": "manual"})
1520-
self.wf2.refresh_from_db()
1521-
self.assertEqual("workflow_finish", self.wf2.status)
15221505

15231506
@patch("sql.sql_workflow.Audit.add_log")
15241507
@patch("sql.sql_workflow.Audit.detail_by_workflow_id")

sql/urls.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,6 @@
4141
path("submitotherinstance/", views.submit_sql),
4242
path("detail/<int:workflow_id>/", views.detail, name="detail"),
4343
path("passed/", sql_workflow.passed),
44-
path("execute/", sql_workflow.execute),
45-
path("timingtask/", sql_workflow.timing_task),
4644
path("cancel/", sql_workflow.cancel),
4745
path("rollback/", views.rollback),
4846
path("sqlanalyze/", views.sqlanalyze),

0 commit comments

Comments
 (0)