Esempio n. 1
0
def edit(sakuya_db, id):

    row = sakuya_db.query(Charts).get(id)
    if row is None:
        abort(404)

    is_haopan = haopan.is_haopan(row.cate_id)
    is_copy = request.params.get('copy') == '1'

    if auth.is_role('sa'):
        warn_only = False
    elif auth.is_role(
            'haopan'
    ) and is_haopan:  # this can be replaced with userid-cid authorization
        warn_only = True
    elif auth.get_user()['username'] == row.owner:
        warn_only = True
    else:
        abort(403)

    if is_copy and (is_haopan or warn_only):
        abort(400)

    rt = _rt(sakuya_db)
    rt['id'] = id
    rt['editing'] = not is_copy
    rt['warn_only'] = warn_only
    rt['is_haopan'] = is_haopan

    forms = {
        'name': haopan.format_title(row.name) if is_haopan else row.name,
        'cid': row.cate_id,
        'owner': row.owner,
        'alert_enable': row.alert_enable
    }

    ext = row.get_ext()
    forms['rule'] = dump_rule(ext.get('rule'))
    forms['warn'] = dump_warn(warn.get_warn(sakuya_db, id))

    forms['owner_name'] = '系统'
    for item in rt['users']:
        if item['username'] == forms['owner']:
            forms['owner_name'] = item['truename']

    rt['forms'] = forms

    return rt
Esempio n. 2
0
def edit(sakuya_db, id):

    row = sakuya_db.query(Charts).get(id)
    if row is None:
        abort(404)

    is_haopan = haopan.is_haopan(row.cate_id)
    is_copy = request.params.get('copy') == '1'

    if auth.is_role('sa'):
        warn_only = False
    elif auth.is_role('haopan') and is_haopan: # this can be replaced with userid-cid authorization
        warn_only = True
    elif auth.get_user()['username'] == row.owner:
        warn_only = True
    else:
        abort(403)

    if is_copy and (is_haopan or warn_only):
        abort(400)

    rt = _rt(sakuya_db)
    rt['id'] = id
    rt['editing'] = not is_copy
    rt['warn_only'] = warn_only
    rt['is_haopan'] = is_haopan

    forms = {
        'name': haopan.format_title(row.name) if is_haopan else row.name,
        'cid': row.cate_id,
        'owner': row.owner,
        'alert_enable': row.alert_enable
    }

    ext = row.get_ext()
    forms['rule'] = dump_rule(ext.get('rule'))
    forms['warn'] = dump_warn(warn.get_warn(sakuya_db, id))

    forms['owner_name'] = '系统'
    for item in rt['users']:
        if item['username'] == forms['owner']:
            forms['owner_name'] = item['truename']

    rt['forms'] = forms

    return rt
Esempio n. 3
0
def get_charts(sakuya_db, cate1=None, cate2=None):
    lv2_list = OrderedDict()
    if cate1 is not None:
        for row in sakuya_db.\
                   query(Categories).\
                   filter_by(parent_cate_id=cate1).\
                   order_by(Categories.id):

            lv2_list[row.id] = {
                'id': row.id,
                'name': row.name
            }

    if cate2 is None:
        cate2 = lv2_list.keys()
    elif cate2 in lv2_list:
        cate2 = [cate2]
    else:
        cate2 = []

    is_admin = auth.is_role('admin')

    if cate2:
        if is_admin:
            rows = sakuya_db.query(Charts).\
                   filter(Charts.cate_id.in_(cate2)).\
                   order_by(Charts.criticals.desc(), Charts.id)
        else:
            rows = sakuya_db.query(Charts).\
                   filter(Charts.cate_id.in_(cate2), Charts.status==1).\
                   order_by(Charts.criticals.desc(), Charts.id)
    else:
        if is_admin:
            rows = sakuya_db.query(Charts).\
                   filter_by(alert_enable=1).\
                   order_by(Charts.criticals.desc(), Charts.id)
        else:
            rows = sakuya_db.query(Charts).\
                   filter_by(alert_enable=1, status=1).\
                   order_by(Charts.criticals.desc(), Charts.id)

    result = []
    for row in rows:
        if haopan.is_haopan(row.cate_id):
            title = haopan.format_title(row.name)
        else:
            title = row.name

        result.append({
            'id': row.id,
            'name': title,
            'critical': row.criticals > 0
        })
    return json.dumps(result)
Esempio n. 4
0
def get_charts(sakuya_db, cate1=None, cate2=None):
    lv2_list = OrderedDict()
    if cate1 is not None:
        for row in sakuya_db.\
                   query(Categories).\
                   filter_by(parent_cate_id=cate1).\
                   order_by(Categories.id):

            lv2_list[row.id] = {'id': row.id, 'name': row.name}

    if cate2 is None:
        cate2 = lv2_list.keys()
    elif cate2 in lv2_list:
        cate2 = [cate2]
    else:
        cate2 = []

    is_admin = auth.is_role('admin')

    if cate2:
        if is_admin:
            rows = sakuya_db.query(Charts).\
                   filter(Charts.cate_id.in_(cate2)).\
                   order_by(Charts.criticals.desc(), Charts.id)
        else:
            rows = sakuya_db.query(Charts).\
                   filter(Charts.cate_id.in_(cate2), Charts.status==1).\
                   order_by(Charts.criticals.desc(), Charts.id)
    else:
        if is_admin:
            rows = sakuya_db.query(Charts).\
                   filter_by(alert_enable=1).\
                   order_by(Charts.criticals.desc(), Charts.id)
        else:
            rows = sakuya_db.query(Charts).\
                   filter_by(alert_enable=1, status=1).\
                   order_by(Charts.criticals.desc(), Charts.id)

    result = []
    for row in rows:
        if haopan.is_haopan(row.cate_id):
            title = haopan.format_title(row.name)
        else:
            title = row.name

        result.append({
            'id': row.id,
            'name': title,
            'critical': row.criticals > 0
        })
    return json.dumps(result)
Esempio n. 5
0
def hide(sakuya_db, id):
    try:
        
        if auth.is_role('admin') is False:
            return util.output('error', msg='Role Error.')

        chart = sakuya_db.query(Charts).get(id)
        if chart is None:
            return util.output('error', msg='Chart not found.')

        status = int(request.params['status'])

        chart.status = status
        sakuya_db.commit()

        return util.output('ok')

    except Exception:
        traceback.print_exc()
        sakuya_db.rollback()
        return util.output('error', msg='隐藏失败')
Esempio n. 6
0
def hide(sakuya_db, id):
    try:

        if auth.is_role('admin') is False:
            return util.output('error', msg='Role Error.')

        chart = sakuya_db.query(Charts).get(id)
        if chart is None:
            return util.output('error', msg='Chart not found.')

        status = int(request.params['status'])

        chart.status = status
        sakuya_db.commit()

        return util.output('ok')

    except Exception:
        traceback.print_exc()
        sakuya_db.rollback()
        return util.output('error', msg='隐藏失败')
Esempio n. 7
0
def update(sakuya_db, id):

    row = sakuya_db.query(Charts).get(id)
    if row is None:
        abort(404)

    is_haopan = haopan.is_haopan(row.cate_id)

    if auth.is_role('sa'):
        warn_only = False
    elif auth.is_role('haopan') and is_haopan:
        warn_only = True
    elif auth.get_user()['username'] == row.owner:
        warn_only = True
    else:
        abort(403)

    rule = None
    warn = None

    def error(msg):
        rt = _rt(sakuya_db)
        rt['id'] = id
        rt['editing'] = True
        rt['warn_only'] = warn_only
        rt['is_haopan'] = is_haopan
        rt['forms'] = request.forms
        rt['forms']['rule'] = dump_rule(rule)
        rt['forms']['warn'] = dump_warn(warn)
        rt['error_msg'] = msg
        return rt

    try:

        alert_enable = request.forms['alert_enable'] == '1'
        warn = make_warn()
        if alert_enable and not warn:
            raise ValueError

        if not warn_only and not is_haopan:

            use_storm = request.forms['use_storm'] == '1'
            if use_storm:
                rule = make_rule()
                if not rule['datasource'] or not rule['filters']:
                    raise ValueError

            name = request.forms['name']
            if not name:
                raise ValueError

            cid = int(request.forms['cid'])
            if not sakuya_db.\
                   query(Categories).\
                   filter_by(id=cid, is_parent=False).\
                   count():
                raise ValueError

            owner = request.forms['owner']
            if not sakuya_db.\
                   query(Users).\
                   filter_by(username=owner).\
                   count():
                raise ValueError

    except Exception:
        return error('参数错误。')

    try:
        row.alert_enable = int(alert_enable)
        row.warnings = 0
        row.criticals = 0
        process_warn_rules(sakuya_db, id, warn)

        if not warn_only and not is_haopan:
            row.name = name
            row.cate_id = cid
            row.root_category = get_parent_category(sakuya_db, cid)
            row.owner = owner

            ext = row.get_ext()
            if use_storm:
                ext['rule'] = rule
                storm.set_rule(id, json.dumps(rule))
            else:
                ext.pop('rule', None)
                storm.delete_rule(id)
            row.ext_info = json.dumps(ext)

        sakuya_db.commit()

    except Exception:
        traceback.print_exc()
        sakuya_db.rollback()
        return error('图表更新失败。')

    if warn_only or is_haopan:
        redirect('/chart/%d' % id)
    redirect('/admin/category/%d' % cid)
Esempio n. 8
0
def chart(sakuya_db, id, id2=None):

    chart_info = sakuya_db.query(Charts).get(id)
    if chart_info is None:
        abort(404)

    chart_info2 =[]
    if id2:
        chart_info2 = sakuya_db.query(Charts).get(id2)

    title = chart_info.name 
    is_haopan = haopan.is_haopan(chart_info.cate_id)
    
    rt = {
        'id': str(id),
        'is_haopan': is_haopan,
        'createtime': chart_info.createtime.strftime('%Y-%m-%d %H:%M:%S')
    }

    rt['is_admin'] = auth.is_role('admin')
    rt['is_admin'] = True
    rt['status'] = chart_info.status
    '''
    more chart line
    '''
    if is_haopan is False:
        if chart_info2:
            is_haopan = True

            title = chart_info2.name
            rt['is_haopan'] = True
            rt['t1_title'] = u'当日'+chart_info.name
            rt['t2_title'] = u'当日'+chart_info2.name
            rt['t3_title'] = u'上周'+chart_info.name
            rt['t4_title'] = u'上周'+chart_info2.name

    else:
        title=haopan.format_title(chart_info.name)
        rt['t1_title'] = u'当日有效点击'
        rt['t2_title'] = u'当日无效点击'
        rt['t3_title'] = u'上周有效点击'
        rt['t4_title'] = u'上周无效点击'
        id2 = haopan.get_id2(chart_info.id)

    if is_haopan:
        rt['title'] = title#haopan.format_title(chart_info.name)
        rt['id2'] = id2#haopan.get_id2(chart_info.id)
        rt['owner'] = '系统'

    else:
        rt['title'] = title

        # owner
        owner = sakuya_db.query(Users).filter_by(username=chart_info.owner).first()
        if owner is not None:
            rt['owner'] = owner.truename
        else:
            rt['owner'] = '未知'

        # datasource
        try:
            ext_info = json.loads(chart_info.ext_info)
            if 'rule' in ext_info:
                ruc = ext_info['rule']
                storm_info = {
                    'datasource': ruc['datasource'],
                    'rule_type': storm.rule_types[ruc['rule_type']][0]
                }
                if storm.rule_types[ruc['rule_type']][1]:
                    storm_info['field'] = ruc['field']

                storm_info['filters'] = []
                for item in ruc['filters']:

                    storm_info['filters'].append({
                        'field': item[0],
                        'operator': storm.operators[storm.datasources[ruc['datasource']][item[0]][0]][0][item[1]],
                        'negative': item[2],
                        'content': item[3]
                    })

                rt['storm_info'] = storm_info

            elif chart_info.api_ip and chart_info.api_ts:
                rt['api_ip'] = util.long2ip(chart_info.api_ip)
                rt['api_ts'] = datetime.datetime.fromtimestamp(chart_info.api_ts).strftime('%Y-%m-%d %H:%M:%S')

        except Exception, e:
            pass
Esempio n. 9
0
    if user is not None:
        follow = sakuya_db.query(Follows).filter_by(cid=id, follower=user['userid']).first()
        if follow is not None:
            rt['following'] = True
            if follow.recv_warning:
                rt['recv_warning'] = True
                rt['recv_rules'] = follow.get_recv_rules()
            else:
                rt['recv_warning'] = False
        else:
            rt['following'] = False
    else:
        rt['following'] = False

    # authorization
    if auth.is_role('sa'):
        rt['editable'] = True
        rt['deletable'] = not is_haopan
    elif auth.is_role('haopan') and is_haopan:
        rt['editable'] = True
        rt['deletable'] = False
    elif user and user['username'] == chart_info.owner:
        rt['editable'] = True
        rt['deletable'] = False
    else:
        rt['editable'] = False

    # breadcrumbs
    rt['active_tab'] = None
    rt['breadcrumbs'] = []
    category_path = libchart.get_category_path(sakuya_db, chart_info.cate_id)
Esempio n. 10
0
def monitor(sakuya_db, tab, cate1=None, cate2=None):

    lv1_list = OrderedDict()
    for row in sakuya_db.\
               query(Categories).\
               filter_by(parent_cate_id=TAB_PID_D[tab]).\
               order_by(Categories.id):

        lv1_list[row.id] = {
            'id': row.id,
            'name': row.name
        }

    if not lv1_list:
        redirect('/')

    if cate1 is None:
        cate1 = lv1_list.keys()[0]
    elif cate1 not in lv1_list:
        return abort(404)

    rt = {
        'lv1_list': lv1_list.values(),
        'cate1': lv1_list[cate1]
    }

    lv2_list = OrderedDict()
    for row in sakuya_db.\
               query(Categories).\
               filter_by(parent_cate_id=cate1).\
               order_by(Categories.id):

        lv2_list[row.id] = {
            'id': row.id,
            'name': row.name
        }

    if not lv2_list:
        redirect('/')

    if cate2 is None:
        cate2 = lv2_list.keys()[0]
    elif cate2 not in lv2_list:
        return abort(404)

    rt['lv2_list'] = lv2_list.values()
    rt['cate2'] = lv2_list[cate2]

    chart_list = []
    is_admin = auth.is_role('admin')

    if is_admin:
        rows = sakuya_db.query(Charts).filter_by(cate_id=cate2).order_by(Charts.id)
    else:
        rows = sakuya_db.query(Charts).filter_by(cate_id=cate2,status=1).order_by(Charts.id)

    for row in rows:

        chart_list.append({
            'id': row.id,
            'name': row.name
        })

    rt['chart_list'] = chart_list
    rt['millitime'] = util.millitime()
    rt['anjuke_cid'] = ANJUKE_CID
    rt['tab'] = tab

    if cate1 == libchart.OPS_PID:
        _, rt['ops_list'] = libchart.get_category_tab(sakuya_db, [libchart.SUITE_PID], 1)

    return rt
Esempio n. 11
0
def update(sakuya_db, id):

    row = sakuya_db.query(Charts).get(id)
    if row is None:
        abort(404)

    is_haopan = haopan.is_haopan(row.cate_id)

    if auth.is_role('sa'):
        warn_only = False
    elif auth.is_role('haopan') and is_haopan:
        warn_only = True
    elif auth.get_user()['username'] == row.owner:
        warn_only = True
    else:
        abort(403)

    rule = None
    warn = None

    def error(msg):
        rt = _rt(sakuya_db)
        rt['id'] = id
        rt['editing'] = True
        rt['warn_only'] = warn_only
        rt['is_haopan'] = is_haopan
        rt['forms'] = request.forms
        rt['forms']['rule'] = dump_rule(rule)
        rt['forms']['warn'] = dump_warn(warn)
        rt['error_msg'] = msg
        return rt

    try:

        alert_enable = request.forms['alert_enable'] == '1'
        warn = make_warn()
        if alert_enable and not warn:
            raise ValueError

        if not warn_only and not is_haopan:

            use_storm = request.forms['use_storm'] == '1'
            if use_storm:
                rule = make_rule()
                if not rule['datasource'] or not rule['filters']:
                    raise ValueError

            name = request.forms['name']
            if not name:
                raise ValueError

            cid = int(request.forms['cid'])
            if not sakuya_db.\
                   query(Categories).\
                   filter_by(id=cid, is_parent=False).\
                   count():
                raise ValueError

            owner = request.forms['owner']
            if not sakuya_db.\
                   query(Users).\
                   filter_by(username=owner).\
                   count():
                raise ValueError

    except Exception:
        return error('参数错误。')

    try:
        row.alert_enable = int(alert_enable)
        row.warnings = 0
        row.criticals = 0
        process_warn_rules(sakuya_db, id, warn)

        if not warn_only and not is_haopan:
            row.name = name
            row.cate_id = cid
            row.root_category = get_parent_category(sakuya_db, cid)
            row.owner = owner

            ext = row.get_ext()
            if use_storm:
                ext['rule'] = rule
                storm.set_rule(id, json.dumps(rule))
            else:
                ext.pop('rule', None)
                storm.delete_rule(id)
            row.ext_info = json.dumps(ext)

        sakuya_db.commit()

    except Exception:
        traceback.print_exc()
        sakuya_db.rollback()
        return error('图表更新失败。')

    if warn_only or is_haopan:
        redirect('/chart/%d' % id)
    redirect('/admin/category/%d' % cid)
Esempio n. 12
0
def chart(sakuya_db, id, id2=None):

    chart_info = sakuya_db.query(Charts).get(id)
    if chart_info is None:
        abort(404)

    chart_info2 = []
    if id2:
        chart_info2 = sakuya_db.query(Charts).get(id2)

    title = chart_info.name
    is_haopan = haopan.is_haopan(chart_info.cate_id)

    rt = {
        'id': str(id),
        'is_haopan': is_haopan,
        'createtime': chart_info.createtime.strftime('%Y-%m-%d %H:%M:%S')
    }

    rt['is_admin'] = auth.is_role('admin')
    rt['is_admin'] = True
    rt['status'] = chart_info.status
    '''
    more chart line
    '''
    if is_haopan is False:
        if chart_info2:
            is_haopan = True

            title = chart_info2.name
            rt['is_haopan'] = True
            rt['t1_title'] = u'当日' + chart_info.name
            rt['t2_title'] = u'当日' + chart_info2.name
            rt['t3_title'] = u'上周' + chart_info.name
            rt['t4_title'] = u'上周' + chart_info2.name

    else:
        title = haopan.format_title(chart_info.name)
        rt['t1_title'] = u'当日有效点击'
        rt['t2_title'] = u'当日无效点击'
        rt['t3_title'] = u'上周有效点击'
        rt['t4_title'] = u'上周无效点击'
        id2 = haopan.get_id2(chart_info.id)

    if is_haopan:
        rt['title'] = title  #haopan.format_title(chart_info.name)
        rt['id2'] = id2  #haopan.get_id2(chart_info.id)
        rt['owner'] = '系统'

    else:
        rt['title'] = title

        # owner
        owner = sakuya_db.query(Users).filter_by(
            username=chart_info.owner).first()
        if owner is not None:
            rt['owner'] = owner.truename
        else:
            rt['owner'] = '未知'

        # datasource
        try:
            ext_info = json.loads(chart_info.ext_info)
            if 'rule' in ext_info:
                ruc = ext_info['rule']
                storm_info = {
                    'datasource': ruc['datasource'],
                    'rule_type': storm.rule_types[ruc['rule_type']][0]
                }
                if storm.rule_types[ruc['rule_type']][1]:
                    storm_info['field'] = ruc['field']

                storm_info['filters'] = []
                for item in ruc['filters']:

                    storm_info['filters'].append({
                        'field':
                        item[0],
                        'operator':
                        storm.operators[storm.datasources[ruc['datasource']][
                            item[0]][0]][0][item[1]],
                        'negative':
                        item[2],
                        'content':
                        item[3]
                    })

                rt['storm_info'] = storm_info

            elif chart_info.api_ip and chart_info.api_ts:
                rt['api_ip'] = util.long2ip(chart_info.api_ip)
                rt['api_ts'] = datetime.datetime.fromtimestamp(
                    chart_info.api_ts).strftime('%Y-%m-%d %H:%M:%S')

        except Exception, e:
            pass
Esempio n. 13
0
        follow = sakuya_db.query(Follows).filter_by(
            cid=id, follower=user['userid']).first()
        if follow is not None:
            rt['following'] = True
            if follow.recv_warning:
                rt['recv_warning'] = True
                rt['recv_rules'] = follow.get_recv_rules()
            else:
                rt['recv_warning'] = False
        else:
            rt['following'] = False
    else:
        rt['following'] = False

    # authorization
    if auth.is_role('sa'):
        rt['editable'] = True
        rt['deletable'] = not is_haopan
    elif auth.is_role('haopan') and is_haopan:
        rt['editable'] = True
        rt['deletable'] = False
    elif user and user['username'] == chart_info.owner:
        rt['editable'] = True
        rt['deletable'] = False
    else:
        rt['editable'] = False

    # breadcrumbs
    rt['active_tab'] = None
    rt['breadcrumbs'] = []
    category_path = libchart.get_category_path(sakuya_db, chart_info.cate_id)
Esempio n. 14
0
def monitor(sakuya_db, tab, cate1=None, cate2=None):

    lv1_list = OrderedDict()
    for row in sakuya_db.\
               query(Categories).\
               filter_by(parent_cate_id=TAB_PID_D[tab]).\
               order_by(Categories.id):

        lv1_list[row.id] = {'id': row.id, 'name': row.name}

    if not lv1_list:
        redirect('/')

    if cate1 is None:
        cate1 = lv1_list.keys()[0]
    elif cate1 not in lv1_list:
        return abort(404)

    rt = {'lv1_list': lv1_list.values(), 'cate1': lv1_list[cate1]}

    lv2_list = OrderedDict()
    for row in sakuya_db.\
               query(Categories).\
               filter_by(parent_cate_id=cate1).\
               order_by(Categories.id):

        lv2_list[row.id] = {'id': row.id, 'name': row.name}

    if not lv2_list:
        redirect('/')

    if cate2 is None:
        cate2 = lv2_list.keys()[0]
    elif cate2 not in lv2_list:
        return abort(404)

    rt['lv2_list'] = lv2_list.values()
    rt['cate2'] = lv2_list[cate2]

    chart_list = []
    is_admin = auth.is_role('admin')

    if is_admin:
        rows = sakuya_db.query(Charts).filter_by(cate_id=cate2).order_by(
            Charts.id)
    else:
        rows = sakuya_db.query(Charts).filter_by(cate_id=cate2,
                                                 status=1).order_by(Charts.id)

    for row in rows:

        chart_list.append({'id': row.id, 'name': row.name})

    rt['chart_list'] = chart_list
    rt['millitime'] = util.millitime()
    rt['anjuke_cid'] = ANJUKE_CID
    rt['tab'] = tab

    if cate1 == libchart.OPS_PID:
        _, rt['ops_list'] = libchart.get_category_tab(sakuya_db,
                                                      [libchart.SUITE_PID], 1)

    return rt