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 1 commit
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
9 changes: 6 additions & 3 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['allow_break'],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里多了一个 ,

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

另外是,需要兼容一下旧配置,此处应该给个默认值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 @@ -216,7 +217,7 @@ 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_):
weight, allow_break) in rules.get_callable_list(id_):
results = []
for func in funcs:
try:
Expand Down Expand Up @@ -248,4 +249,6 @@ def calculate_rule(id_, req_body, rules=None, ac=None):
group_uuid=group_uuid,
hit_number=hit_number))
hit_logger.info(msg)
return rv_control, rv_weight
if allow_break and hit_number > 0:
flyer5200 marked this conversation as resolved.
Show resolved Hide resolved
return rv_control, rv_weight, custom
return rv_control, rv_weight, custom
4 changes: 2 additions & 2 deletions server/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ def query_handler(req_body):
try:
assert rule_id
rule_id = str(rule_id)
control, weight = calculate_rule(rule_id, req_body, rules=rules, ac=ac)
result = {'control': control, 'weight': weight}
control, weight, custom = calculate_rule(rule_id, req_body, rules=rules, ac=ac)
result = {'control': control, 'weight': weight, 'custom': custom}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个custom在目前的设计中不应该返回给业务方,这个主要是后续客服人员看的

except AssertionError:
error = 'must contain rule_id'
ec = 100
Expand Down
32 changes: 32 additions & 0 deletions www/rule/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
import json

from django import forms
from django.forms import BooleanField
from django.forms.utils import flatatt
from django.utils import timezone
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _

from core.forms import BaseFilterForm, BaseForm
Expand All @@ -30,11 +34,38 @@
}


class PrettyCheckboxWidget(forms.widgets.CheckboxInput):
def render(self, name, value, attrs=None):
attrs = {type: 'checkbox', name: name}
final_attrs = self.build_attrs(attrs)
if self.check_test(value):
final_attrs['checked'] = 'checked'
if not (value is True or value is False or value is None or value == ''):
final_attrs['value'] = force_text(value)
if 'prettycheckbox-label' in final_attrs:
label = _(final_attrs.pop('prettycheckbox-label'))
else:
label = ''
return format_html('<label for="{0}"><input{1} /> {2}</label>', attrs['id'], flatatt(final_attrs), label)


class PrettyCheckboxField(BooleanField):
widget = PrettyCheckboxWidget

def __init__(self, *args, **kwargs):
if kwargs['label']:
kwargs['widget'].attrs['prettycheckbox-label'] = kwargs['label']
kwargs['label'] = ''
super(PrettyCheckboxField, self).__init__(*args, **kwargs)


class RulesForm(BaseForm):
title = forms.CharField(label=_(u"规则名称"))
describe = forms.CharField(required=False, label=_(u"规则描述"),
widget=forms.Textarea)
status = forms.ChoiceField(label=_(u"状态"), choices=STATUS_CHOICES)
#allow_break = PrettyCheckboxField(label=_(u"允许策略短路"), widget=PrettyCheckboxWidget())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个 PrettyCheckboxField 如果没有用到的话,连同上面的一起全部删掉吧,减少无效代码量

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 +162,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)
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
9 changes: 6 additions & 3 deletions 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')

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 @@ -247,7 +250,7 @@ def get_rule(self):
d = client.hgetall(name)
if not d:
raise Http404
for key in ('status', 'title', 'describe', 'end_time', 'id', 'uuid'):
for key in ('status', 'allow_break', 'title', 'describe', 'end_time', 'id', 'uuid'):
data[key] = d[key]
try:
rule_list = json.loads(d["strategys"])
Expand Down Expand Up @@ -457,7 +460,7 @@ def get_rule(self):
raise Http404

data = {}
for key in ('status', 'title', 'describe', 'end_time', 'id', 'uuid'):
for key in ('status', 'allow_break', 'title', 'describe', 'end_time', 'id', 'uuid'):
data[key] = d[key]

try:
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