Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add rule break support #73

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions risk_models/rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def __init__(self, d):
self.id = d['id']
self.uuid = d['uuid']
self.name = d['title']
self.allow_break = d.get('allow_break', False)
self.strategy_group_list = []
origin_strategy_group_list = json.loads(d['strategys'])
for strategy_group in origin_strategy_group_list:
Expand Down Expand Up @@ -60,7 +61,7 @@ def get_callable_list(self):
for uuid_, threshold_list in strategy_list:
funcs.append(strategys.get_callable(uuid_, threshold_list))
callable_list.append([funcs, control, custom, group_name,
group_uuid, weight])
group_uuid, weight, self.allow_break])
return callable_list

def __str__(self):
Expand Down Expand Up @@ -215,30 +216,24 @@ def calculate_rule(id_, req_body, rules=None, ac=None):

rv_control, rv_weight, result_seted, hit_number = 'pass', 0, False, 0

for (funcs, control, custom, group_name, group_uuid,
weight) in rules.get_callable_list(id_):
for (funcs, control, custom, group_name, group_uuid, weight, allow_break) in rules.get_callable_list(id_):
results = []
for func in funcs:
try:
ret = func(req_body)
except Exception:
logger.error(
'run func error, rule_id: {}, weight: {}'.format(id_,
weight),
exc_info=True)
except Exception as ex:
logger.error('run func error, rule_id: {}, weight: {}'.format(id_,weight), ex, exc_info=True)
ret = False
results.append(ret)
if not ret:
break

# 目前策略为过全部策略原子组以积累数据,若无此需求,可自行进行短路
if all(results):
if not result_seted:
rv_control, rv_weight, result_seted = control, weight, True

# 当前命中的策略组在此规则中是第几个命中的
hit_number += 1

# 记录命中日志
msg = json.dumps(dict(rule_id=id_,
kwargs={},
req_body=req_body,
Expand All @@ -247,5 +242,14 @@ def calculate_rule(id_, req_body, rules=None, ac=None):
group_name=group_name,
group_uuid=group_uuid,
hit_number=hit_number))

# 允许策略短路, 命中权重高的策略后, 之后的策略就不走了
if allow_break:
hit_logger.info(msg)
return control, weight

hit_logger.info(msg)

if not result_seted:
rv_control, rv_weight, result_seted = control, weight, True
return rv_control, rv_weight
2 changes: 2 additions & 0 deletions www/rule/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class RulesForm(BaseForm):
describe = forms.CharField(required=False, label=_(u"规则描述"),
widget=forms.Textarea)
status = forms.ChoiceField(label=_(u"状态"), choices=STATUS_CHOICES)
allow_break = forms.BooleanField(label=_(u"允许策略短路"), initial=True, required=True)
end_time = forms.DateTimeField()
strategy = forms.ChoiceField(label=_("策略原子"), required=False)
control = forms.ChoiceField(label=_("管控原子"), choices=CONTROL_CHOICES,
Expand Down Expand Up @@ -131,6 +132,7 @@ def save(self, *args, **kwargs):
return RuleModel.create(creator_name=self.request.user.username,
title=cd['title'],
describe=cd['describe'], status=cd['status'],
allow_break=cd['allow_break'],
end_time=cd['end_time'],
strategy_confs=zip(names, strategys, controls,
customs,
Expand Down
3 changes: 2 additions & 1 deletion www/rule/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
class RuleModel(object):

@classmethod
def create(self, creator_name, title, describe, status, end_time,
def create(self, creator_name, title, describe, status, allow_break, end_time,
strategy_confs):
strategy_obj = Strategys()

Expand Down Expand Up @@ -46,6 +46,7 @@ def create(self, creator_name, title, describe, status, end_time,
'title': title,
'describe': describe,
'status': status,
'allow_break': allow_break,
'strategys': json.dumps(strategy_list)
}

Expand Down
1 change: 1 addition & 0 deletions www/rule/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class RulesTable(tables.Table):
id = columns.Column(verbose_name=_(u"规则ID"), orderable=False)
title = columns.Column(verbose_name=_(u"规则名称"), orderable=False)
status = columns.Column(verbose_name=_(u"状态"), orderable=False)
allow_break = columns.Column(verbose_name=_(u"允许策略短路"), orderable=False, default=False)
update_time = columns.Column(verbose_name=_(u"更新时间"), orderable=False)
user = columns.Column(verbose_name=_(u"更新人"), orderable=False)
action = columns.TemplateColumn("""
Expand Down
11 changes: 10 additions & 1 deletion www/rule/templates/rule/rules_create.html
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<label class="col-sm-2 control-label">允许策略短路</label>
<div class="col-sm-10">
{{ form.allow_break }}
<span id="id-allow_break-error" class="help-block" style="color:darkred"></span>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<label class="col-sm-2 control-label">结束时间</label>
<div class="col-sm-10">
Expand Down Expand Up @@ -181,6 +189,7 @@ <h3>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
var title = $('#id_title').val()
var describe = $('#id_describe').val()
var status = $('#id_status').val()
var allow_break = $('#id_allow_break').val()
var end_time = $('#id_end_time').val()

var names = $(".group-name:visible").map(function () {
Expand All @@ -189,7 +198,6 @@ <h3>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
var weights = $(".weight:visible").map(function () {
return $(this).val();
});
console.log(weights);
var strategys = $("#rule-list label.strategy:visible").map(function () {
return $(this).val();
});
Expand Down Expand Up @@ -267,6 +275,7 @@ <h3>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
'title': title,
'describe': describe,
'status': status,
'allow_break': allow_break,
'end_time': end_time,
'strategys': strategy_arr.join(","),
'controls': control_arr.join(","),
Expand Down
3 changes: 2 additions & 1 deletion www/rule/templates/rule/rules_detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,15 @@
<address>
<strong>规则名称:</strong> {{ rule.title }}<br>
<strong>规则描述:</strong> {{ rule.describe }}<br>
<strong>规则状态:</strong> {% if rule.status == "on" %} 开启 {% else %} 关闭 {% endif %}<br>
<strong>规则状态:</strong> <label class="text-danger">{% if rule.status == "on" %} 开启 {% else %} 关闭 {% endif %}</label><br>
</address>
</div>

<div class="col-sm-6">
<address>
<strong>规则ID:</strong> <label class="text-danger">{{ rule.id }}</label><br>
<strong>规则结束时间:</strong> <label class="text-danger">{{ rule.end_time }}</label><br>
<strong>允许策略短路:</strong> <label class="text-danger">{{ rule.allow_break }}</label><br>
</address>
</div>
</div>
Expand Down
13 changes: 13 additions & 0 deletions www/rule/templates/rule/rules_edit.html
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@
<span id="id-status-error" class="help-block" style="color:darkred"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">允许策略短路</label>
<div class="col-sm-10">
{% if rule.allow_break == "True" %}
<input type="checkbox" name="allow_interrupt" id="id_allow_break" checked="checked">
{% else %}
<input type="checkbox" name="allow_interrupt" id="id_allow_break">
{% endif %}
<span id="id-allow_break-error" class="help-block" style="color:darkred"></span>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<label class="col-sm-2 control-label">结束时间</label>
Expand Down Expand Up @@ -246,6 +257,7 @@ <h3>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
var title = $('#id_title').val()
var describe = $('#id_describe').val()
var status = $('#id_status').val()
var allow_break = $('#id_allow_break').prop('checked')?'True':'False'
var end_time = $('#id_end_time').val()

var names = $(".group-name:visible").map(function () {
Expand Down Expand Up @@ -332,6 +344,7 @@ <h3>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
'title': title,
'describe': describe,
'status': status,
'allow_break': allow_break,
'end_time': end_time,
'strategys': strategy_arr.join('|'),
'controls': control_arr.join(","),
Expand Down
7 changes: 6 additions & 1 deletion www/rule/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,15 @@ def _parse_data(self, request):
origin = request.POST
uuid_ = origin.get('id')
status = origin.get('status')
allow_break = origin.get('allow_break', False)

if status not in ('on', 'off'):
raise ValueError(u"状态不合法")

ret = {
"uuid": uuid_,
"status": status,
"allow_break": allow_break,
'user': request.user.username,
'update_time': now
}
Expand All @@ -128,6 +130,7 @@ def _parse_data(self, request):
raise ValueError(u"结束时间格式不合法")

ret['end_time'] = end_time
ret['allow_break'] = allow_break

try:
title = origin['title']
Expand Down Expand Up @@ -194,7 +197,7 @@ def _build_key_value(self, data):
items.append([key, value])
return items

for key in ('title', 'describe', 'status', 'end_time'):
for key in ('title', 'allow_break', 'describe', 'status', 'end_time'):
items.append([key, data[key]])
strategy_list = []
datas = zip(data['names'], data['strategys'], data['controls'],
Expand Down Expand Up @@ -262,6 +265,7 @@ def get_rule(self):
x[2] for x in rule['strategy_list'] if len(x) == 3)
rule['strategy_list_str'] = json.dumps(rule['strategy_list'])
data['rule_list'] = rule_list
data['allow_break'] = d.get('allow_break', False)
return data


Expand Down Expand Up @@ -473,6 +477,7 @@ def get_rule(self):
x[2] for x in rule['strategy_list'] if len(x) == 3)
rule['strategy_list_str'] = json.dumps(rule['strategy_list'])
data['rule_list'] = rule_list
data['allow_break'] = d.get('allow_break', False)
return data

@classmethod
Expand Down
6 changes: 6 additions & 0 deletions www/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@
<link href="{% static 'css/plugins/sweetalert/sweetalert.css' %}" rel="stylesheet">
<link href="{% static 'css/jquery.searchableSelect.css' %}" rel="stylesheet">
<link href="{% static 'css/main.css' %}?v=3" rel="stylesheet">
<style>
/* 解决默认checkbox长度太长导致变形的问题 */
.form-control[type=checkbox] {
width: auto;
}
</style>
</head>

<body class="fixed-sidebar full-height-layout extra-main-bg" style="overflow:hidden">
Expand Down