Ejemplo n.º 1
0
    def create(self, creator_name, title, describe, status, end_time,
               strategy_confs):
        strategy_obj = Strategys()

        new_strategy_confs = []
        for name, strategy_uuids, control, custom, weight in strategy_confs:
            strategy_uuids = strategy_uuids.split(';')

            new_strategy_confs.append({
                'name':
                name,
                'custom':
                custom,
                'control':
                control,
                'weight':
                weight,
                'strategy_list': [[
                    strategy_uuid,
                    strategy_obj.get_thresholds(strategy_uuid),
                    strategy_obj.get_strategy_name(strategy_uuid)
                ] for strategy_uuid in strategy_uuids]
            })

        strategy_list = sorted(new_strategy_confs,
                               key=lambda x: int(x["weight"]),
                               reverse=True)

        rule_uuid = str(uuid.uuid4())

        payload = {
            'uuid': rule_uuid,
            'user': creator_name,
            'update_time': str(int(time.time())),
            'end_time': datetime.strftime(end_time, '%Y-%m-%d %H:%M:%S'),
            'title': title,
            'describe': describe,
            'status': status,
            'strategys': json.dumps(strategy_list)
        }

        client = get_redis_client()
        rule_id = client.incr(settings.LAST_RULE_ID_KEY)
        payload['id'] = rule_id

        rule_key = 'rule:{}'.format(rule_uuid)
        client.hmset(rule_key, payload)
        return str(rule_id), rule_uuid
Ejemplo n.º 2
0
    def post(self, request, *args, **kwargs):

        try:
            data = json.loads(request.POST.get('data', '{}'))
            # 从参数中获取需要修改的规则uuid
            rule_uuid = data.get('rule_uuid', None)
            # 从参数中获取需要修改的策略组的下标
            strategy_index = data.get('strategy_index', None)
            # 从参数中获取前端传参过来的策略列表
            new_strategy_confs = data.get('strategy_list', None)
            assert strategy_index is not None
            assert isinstance(strategy_index, int) and strategy_index >= 0
            assert all((rule_uuid, new_strategy_confs))
        except (AssertionError, TypeError, ValueError):
            return self.render_json_response({'state': False, 'msg': '参数校验失败'})

        client = get_redis_client()

        try:
            # 从redis中获取需要修改的规则所有数据
            rule_conf = client.hgetall("rule:{}".format(rule_uuid))
            # 从规则数据中获取策略组数据列表
            strategy_confs = json.loads(rule_conf.get('strategys'))
            # 从策略组列表中找出需要编辑的策略组
            strategy_conf = strategy_confs[strategy_index]
        except (TypeError, ValueError, IndexError, RedisError):
            return self.render_json_response({'state': False, 'msg': '配置读取失败'})

        strategys_obj = Strategys()
        strategy_conf['strategy_list'] = [[
            x['strategy_uuid'], x['threshold_list'],
            strategys_obj.build_strategy_name_from_thresholds(
                x['strategy_uuid'], x['threshold_list'])
        ] for x in new_strategy_confs]  # 构造编辑后的策略组

        strategy_confs[strategy_index] = strategy_conf  # 回写策略组
        rule_conf["strategys"] = json.dumps(strategy_confs)
        rule_conf['user'] = request.user.username
        rule_conf['update_time'] = str(int(time.time()))
        try:
            client.hmset("rule:{}".format(rule_uuid), rule_conf)  # 回写规则数据
        except RedisError:
            return self.render_json_response({'state': False, 'msg': '配置回写失败'})

        return self.render_json_response({'state': True})
Ejemplo n.º 3
0
 def _get_all_strategys(cls):
     return Strategys().get_all_strategy_uuid_and_name()
Ejemplo n.º 4
0
Archivo: views.py Proyecto: onisama/-
    def _parse_data(self, request):
        now = str(int(time.time()))
        origin = request.POST
        uuid_ = origin.get('id')
        status = origin.get('status')

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

        ret = {
            "uuid": uuid_,
            "status": status,
            'user': request.user.username,
            'update_time': now
        }

        end_time = origin.get('end_time')
        #  仅修改状态
        if not end_time:
            return ret

        try:
            datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
        except (ValueError, TypeError):
            raise ValueError(u"结束时间格式不合法")

        ret['end_time'] = end_time

        try:
            title = origin['title']
        except KeyError:
            raise ValueError(u"规则名称必须填写")
        try:
            describe = origin['describe']
        except KeyError:
            raise ValueError(u"规则描述必须填写")

        names = origin.get('names', '').split(':::')
        weights = origin.get('weights', '').split(',')
        strategys = origin.get('strategys', '').split('|')
        controls = origin.get('controls', '').split(',')
        customs = origin.get('customs', '').split(':::')
        lst = [names, weights, strategys, controls, customs]

        for elem in lst[1:]:
            if len(elem) != len(lst[0]):
                raise ValueError(u"数据长度不匹配")
        for weight in weights:
            if not weight.isdigit():
                raise ValueError(u"权重不是整数")
        strategys_list = []
        for strategy_str in strategys:
            try:
                strategy = json.loads(strategy_str)
            except ValueError:
                strategy = strategy_str
            if isinstance(strategy, list):
                strategys_list.append(strategy)
            else:
                strategy_obj = Strategys()
                lst = []
                for uuid_ in strategy.split(';'):
                    lst.append([
                        uuid_,
                        strategy_obj.get_thresholds(uuid_),
                        strategy_obj.get_strategy_name(uuid_)
                    ])
                strategys_list.append(lst)
        strategys = strategys_list
        strategy_uuids = []
        for strategy in strategys:
            item = [x[0] for x in strategy]
            item.sort()
            strategy_uuids.append("".join(item))
        if len(set(strategy_uuids)) < len(strategy_uuids):
            raise ValueError(u"策略原子有重复")
        for key in ('title', 'describe', 'names', 'weights', 'strategys',
                    'controls', 'customs'):
            ret[key] = locals()[key]
        return ret
Ejemplo n.º 5
0
from hashlib import md5
from copy import deepcopy
from datetime import datetime
from collections import defaultdict

import redis
import gevent

from log import hit_logger
from risk_models.exceptions import RuleNotExistsException
from risk_models.strategy import Strategys
from clients import get_config_redis_client

logger = logging.getLogger(__name__)

strategys = Strategys()


class Rule(object):
    def __init__(self, d):
        self.id = d['id']
        self.uuid = d['uuid']
        self.name = d['title']
        self.strategy_group_list = []
        origin_strategy_group_list = json.loads(d['strategys'])
        for strategy_group in origin_strategy_group_list:
            weight = int(strategy_group['weight'])
            control = strategy_group['control']
            custom = strategy_group['custom']
            group_name = strategy_group['name']
            strategy_list = []
Ejemplo n.º 6
0
    def _parse_data(self, request, *args, **kwargs):
        now = str(int(time.time()))
        origin = request.POST
        uuid_ = origin.get('id')
        status = origin.get('status')

        if status not in ('on', 'off'):
            raise ValueError(_("Status is not legal."))

        ret = {
            "uuid": uuid_,
            "status": status,
            'user': self.request.user.username,
            'update_time': now
        }

        end_time = origin.get('end_time')
        #  Modify Status only
        if not end_time:
            return ret

        try:
            datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
        except (ValueError, TypeError):
            raise ValueError(_("End time format is not legal"))

        ret['end_time'] = end_time

        try:
            title = origin['title']
        except KeyError:
            raise ValueError(_("RuleName must be filled in"))
        try:
            describe = origin['describe']
        except KeyError:
            raise ValueError(_("Rule description must be filled in"))

        names = origin.get('names', '').split(':::')
        weights = origin.get('weights', '').split(',')
        strategys = origin.get('strategys', '').split('|')
        controls = origin.get('controls', '').split(',')
        customs = origin.get('customs', '').split(':::')
        lst = [names, weights, strategys, controls, customs]

        for elem in lst[1:]:
            if len(elem) != len(lst[0]):
                raise ValueError(_("Data length mismatch"))
        for weight in weights:
            if not weight.isdigit():
                raise ValueError(_("Weight is not an integer"))
        strategys_list = []
        for strategy_str in strategys:
            try:
                strategy = json.loads(strategy_str)
            except ValueError:
                strategy = strategy_str
            if isinstance(strategy, list):
                strategys_list.append(strategy)
            else:
                strategy_obj = Strategys()
                lst = []
                for uuid_ in strategy.split(';'):
                    lst.append([
                        uuid_,
                        strategy_obj.get_thresholds(uuid_),
                        strategy_obj.get_strategy_name(uuid_)
                    ])
                strategys_list.append(lst)
        strategys = strategys_list
        strategy_uuids = []
        for strategy in strategys:
            item = [x[0] for x in strategy]
            item.sort()
            strategy_uuids.append("".join(item))
        if len(set(strategy_uuids)) < len(strategy_uuids):
            raise ValueError(_("Policy has a repeat."))
        for key in ('title', 'describe', 'names', 'weights', 'strategys',
                    'controls', 'customs'):
            ret[key] = locals()[key]
        return ret
Ejemplo n.º 7
0
    def post(self, request, *args, **kwargs):

        try:
            data = json.loads(request.POST.get('data', '{}'))
            # Get the rule uuid from the parameters that need to be modified
            rule_uuid = data.get('rule_uuid', None)
            # Get the subscript of the policy group that needs to be modified from the parameters
            strategy_index = data.get('strategy_index', None)
            # Get a list of policies from the parameters that the front end passes through
            new_strategy_confs = data.get('strategy_list', None)

            assert strategy_index is not None
            assert isinstance(strategy_index, int) and strategy_index >= 0
            assert all((rule_uuid, new_strategy_confs))

        except (AssertionError, TypeError, ValueError):
            return self.render_json_response({
                'state': False,
                'msg': 'Argument check failed'
            })

        client = get_redis_client()

        try:
            # Get all the data from redis rules that need to be modified
            rule_conf = client.hgetall("rule:{}".format(rule_uuid))
            # Get a list of policy group data from rule data
            strategy_confs = json.loads(rule_conf.get('strategys'))
            # Find the policy group that needs to be edited from the Strategy Group list
            strategy_conf = strategy_confs[strategy_index]
        except (TypeError, ValueError, IndexError, RedisError):
            return self.render_json_response({
                'state':
                False,
                'msg':
                _('Configuration read failed')
            })

        strategys_obj = Strategys()
        strategy_conf['strategy_list'] = [
            [
                x['strategy_uuid'], x['threshold_list'],
                strategys_obj.build_strategy_name_from_thresholds(
                    x['strategy_uuid'], x['threshold_list'])
            ] for x in new_strategy_confs
        ]  # Constructing the edited strategy group

        strategy_confs[
            strategy_index] = strategy_conf  # Write Back Strategy Group
        rule_conf["strategys"] = json.dumps(strategy_confs)
        rule_conf["user"] = request.user.username
        rule_conf["update_time"] = str(int(time.time()))
        try:
            client.hmset("rule:{}".format(rule_uuid),
                         rule_conf)  # Write back rule data
        except RedisError:
            return self.render_json_response({
                'state':
                False,
                'msg':
                _('Configuration write-back failed')
            })

        return self.render_json_response({'state': True})