Exemplo n.º 1
0
def del_host(request):
    """删除主机视图"""
    if request.method == 'POST':
        response = WebResponse()
        host_list = request.POST.getlist('host_list')
        try:
            with transaction.atomic():
                for host_id in host_list:
                    host_id = int(host_id)
                    host_obj = models.Host.objects.filter(id=host_id).first()
                    host_obj.delete()
                    # 删除redis中相关数据
                    alert_counter_redis_key = settings.ALERT_COUNTER_REDIS_KEY
                    key_in_redis = '*_%s_*' % host_obj.hostname
                    key_list = REDIS_OBJ.keys(key_in_redis)
                    for key in key_list:  # 循环删除trigger key相关数据
                        REDIS_OBJ.delete(key)
                    alert_counter_data = json.loads(
                        REDIS_OBJ.get(alert_counter_redis_key).decode())
                    for key, value in alert_counter_data.items(
                    ):  # 删除报警计数中相关数据
                        for hostname in list(value.keys()):
                            if hostname == host_obj.hostname:
                                del alert_counter_data[key][hostname]
                    REDIS_OBJ.set(alert_counter_redis_key,
                                  json.dumps(alert_counter_data))
                    Logger().log(message='删除主机成功,%s' % host_obj.hostname,
                                 mode=True)
            response.message = '删除主机成功'
        except Exception as e:
            response.status = False
            response.error = str(e)
            Logger().log(message='删除主机失败,%s' % str(e), mode=False)
        return JsonResponse(response.__dict__)
Exemplo n.º 2
0
def del_trigger(request):
    """删除触发器视图"""
    if request.method == 'POST':
        response = WebResponse()
        trigger_list = request.POST.getlist('trigger_list')
        try:
            with transaction.atomic():
                for trigger_id in trigger_list:
                    trigger_id = int(trigger_id)
                    trigger_obj = models.Trigger.objects.filter(
                        id=trigger_id).first()
                    key_in_redis = '*_trigger_%s' % trigger_obj.id
                    key_list = REDIS_OBJ.keys(key_in_redis)
                    for key in key_list:
                        REDIS_OBJ.delete(key)  # 删除redis中相关监控项
                    alert_counter_redis_key = settings.ALERT_COUNTER_REDIS_KEY
                    alert_counter_data = json.loads(
                        REDIS_OBJ.get(alert_counter_redis_key).decode())
                    for key1, value1 in alert_counter_data.items():
                        for key2, value2 in value1.items():
                            for key3 in list(value2.keys()):
                                if key3 == str(trigger_id):
                                    del alert_counter_data[key1][key2][
                                        key3]  # 删除对应主机下的trigger计数
                    trigger_obj.delete()
                    Logger().log(message='删除触发器成功,%s' % trigger_obj.name,
                                 mode=True)
            response.message = '删除触发器成功'
        except Exception as e:
            response.status = False
            response.error = str(e)
            Logger().log(message='删除触发器失败,%s' % str(e), mode=False)
        return JsonResponse(response.__dict__)
Exemplo n.º 3
0
def get_item(request):
    if request.method == 'POST':
        response = WebResponse()
        application_id = request.POST.get('application_id')
        application_obj = models.Application.objects.filter(id=application_id).first()
        data = list(application_obj.items.all().values('id', 'name', 'key'))
        response.data = data
        return JsonResponse(response.__dict__)
Exemplo n.º 4
0
def get_application(request):
    if request.method == 'POST':
        response = WebResponse()
        template_id = request.POST.get('template_id')
        template_obj = models.Template.objects.filter(id=template_id).first()
        data = list(template_obj.applications.all().values('id', 'name'))
        response.data = data
        return JsonResponse(response.__dict__)
Exemplo n.º 5
0
def del_host_group(request):
    """删除主机组视图"""
    if request.method == 'POST':
        response = WebResponse()
        host_group_list = request.POST.getlist('host_group_list')
        try:
            with transaction.atomic():
                for host_group_id in host_group_list:
                    host_group_id = int(host_group_id)
                    host_group_obj = models.HostGroup.objects.filter(
                        id=host_group_id).first()
                    # 删除这个主机组所有主机自身不存在的监控配置(主机组的监控配置而主机没有相同配置)
                    alert_counter_redis_key = settings.ALERT_COUNTER_REDIS_KEY
                    host_group_template_obj_set = set(
                        host_group_obj.templates.all())
                    host_obj_list = host_group_obj.host_set.all()
                    for host_obj in host_obj_list:
                        host_template_obj_set = set(host_obj.templates.all())
                        only_template_obj_set = host_group_template_obj_set - host_template_obj_set  # 差集,只有主机组关联的模板
                        for template_obj in only_template_obj_set:  # 循环每个模板
                            application_obj_list = template_obj.applications.all(
                            )
                            for application_obj in application_obj_list:
                                key_in_redis = '*_%s_%s_*' % (
                                    host_obj.hostname, application_obj.name)
                                key_list = REDIS_OBJ.keys(key_in_redis)
                                for key in key_list:
                                    REDIS_OBJ.delete(
                                        key)  # 删除redis中相关监控项和报警trigger的key
                            template_trigger_id_list = []
                            template_trigger_obj_list = template_obj.trigger_set.all(
                            )
                            for trigger_obj in template_trigger_obj_list:
                                template_trigger_id_list.append(
                                    str(trigger_obj.id))
                            alert_counter_data = json.loads(
                                REDIS_OBJ.get(
                                    alert_counter_redis_key).decode())
                            # 删除报警计数中相关数据,key->action_id,value->{\"CentOS-03_172.16.99.25\": {\"3\": {\"last_alert\": 1528083651.9851427, \"counter\": 1}}}
                            for key1, value1 in alert_counter_data.items():
                                # key->hostname,value->{\"3\": {\"last_alert\": 1528083651.9851427, \"counter\": 1}}
                                for key2, value2 in value1.items():
                                    if host_obj.hostname == key2:  # hostname匹配上了
                                        # key->trigger_id,value->{\"last_alert\": 1528083651.9851427, \"counter\": 1}
                                        for key3 in list(value2.keys()):
                                            if key3 in template_trigger_id_list:
                                                del alert_counter_data[key1][
                                                    key2][
                                                        key3]  # 删除对应主机下的trigger计数
                    host_group_obj.delete()
                    Logger().log(message='删除主机组成功,%s' % host_group_obj.name,
                                 mode=True)
            response.message = '删除主机组成功'
        except Exception as e:
            response.status = False
            response.error = str(e)
            Logger().log(message='删除主机组失败,%s' % str(e), mode=False)
        return JsonResponse(response.__dict__)
Exemplo n.º 6
0
def select_host_group_for_show_chart(request):
    """选择主机组"""
    if request.method == 'POST':
        response = WebResponse()
        host_group_id = request.POST.get('host_group_id')
        host_group_obj = models.HostGroup.objects.filter(
            id=host_group_id).first()
        data = list(host_group_obj.host_set.all().values('id', 'ip'))
        response.data = data
        return JsonResponse(response.__dict__)
Exemplo n.º 7
0
def user_info(request):
    """用户信息视图"""
    if request.method == 'POST':
        response = WebResponse()
        form_obj = forms.UserInfoForm(request.POST)
        if form_obj.is_valid():
            password = form_obj.cleaned_data['password1']
            request.user.set_password(password)
            request.user.save()
        else:
            response.status = False
            response.message = '密码修改失败'
        return JsonResponse(response.__dict__)
    return render(request, 'user_info.html')
Exemplo n.º 8
0
def select_item(request):
    """选择监控项"""
    if request.method == 'POST':
        response = WebResponse()
        application_id = request.POST.get('application_id')
        application_obj = models.Application.objects.filter(
            id=application_id).first()
        temp_data = list(application_obj.items.all().values(
            'id', 'name', 'key'))
        data = []
        for item in temp_data:
            name = '%s %s' % (item['name'], item['key'])
            data.append({'id': item['id'], 'name': name})
        response.data = data
        return JsonResponse(response.__dict__)
Exemplo n.º 9
0
def del_chart(request):
    """删除图表视图"""
    if request.method == 'POST':
        response = WebResponse()
        chart_list = request.POST.getlist('chart_list')
        try:
            with transaction.atomic():
                for chart_id in chart_list:
                    chart_id = int(chart_id)
                    chart_obj = models.Chart.objects.filter(id=chart_id).first()
                    chart_obj.delete()
                    Logger().log(message='删除图表成功,%s' % chart_obj.name, mode=True)
            response.message = '删除图表成功'
        except Exception as e:
            response.status = False
            response.error = str(e)
            Logger().log(message='删除图表失败,%s' % str(e), mode=False)
        return JsonResponse(response.__dict__)
Exemplo n.º 10
0
def del_template(request):
    """删除视图模板"""
    if request.method == 'POST':
        response = WebResponse()
        template_list = request.POST.getlist('template_list')
        try:
            with transaction.atomic():
                for template_id in template_list:
                    template_id = int(template_id)
                    template_obj = models.Template.objects.filter(
                        id=template_id).first()
                    # 删除redis中相关监控项及触发器、报警计数
                    alert_counter_redis_key = settings.ALERT_COUNTER_REDIS_KEY
                    application_obj_list = template_obj.applications.all()
                    for application_obj in application_obj_list:
                        key_in_redis = '*_%s_*' % application_obj.name
                        key_list = REDIS_OBJ.keys(key_in_redis)
                        for key in key_list:
                            REDIS_OBJ.delete(
                                key)  # 删除redis中相关监控项和报警trigger的key
                    template_trigger_id_list = []
                    template_trigger_obj_list = template_obj.trigger_set.all()
                    for trigger_obj in template_trigger_obj_list:
                        template_trigger_id_list.append(str(trigger_obj.id))
                    alert_counter_data = json.loads(
                        REDIS_OBJ.get(alert_counter_redis_key).decode())
                    # 删除报警计数中相关数据,key->action_id,value->{\"CentOS-03_172.16.99.25\": {\"3\": {\"last_alert\": 1528083651.9851427, \"counter\": 1}}}
                    for key1, value1 in alert_counter_data.items():
                        # key->hostname,value->{\"3\": {\"last_alert\": 1528083651.9851427, \"counter\": 1}}
                        for key2, value2 in value1.items():
                            # key->trigger_id,value->{\"last_alert\": 1528083651.9851427, \"counter\": 1}
                            for key3 in list(value2.keys()):
                                if key3 in template_trigger_id_list:
                                    del alert_counter_data[key1][key2][
                                        key3]  # 删除对应主机下的trigger计数
                    template_obj.delete()
                    Logger().log(message='删除模板成功,%s' % template_obj.name,
                                 mode=True)
            response.message = '删除模板成功'
        except Exception as e:
            response.status = False
            response.error = str(e)
            Logger().log(message='删除模板失败,%s' % str(e), mode=False)
        return JsonResponse(response.__dict__)
Exemplo n.º 11
0
def del_item(request):
    """删除监控项视图"""
    if request.method == 'POST':
        response = WebResponse()
        item_list = request.POST.getlist('item_list')
        try:
            with transaction.atomic():
                for item_id in item_list:
                    item_id = int(item_id)
                    item_obj = models.Item.objects.filter(id=item_id).first()
                    item_obj.delete()
                    Logger().log(message='删除监控项成功,%s' % item_obj.key,
                                 mode=True)
            response.message = '删除监控项成功'
        except Exception as e:
            response.status = False
            response.error = str(e)
            Logger().log(message='删除监控项失败,%s' % str(e), mode=False)
        return JsonResponse(response.__dict__)
Exemplo n.º 12
0
def select_host_for_show_chart(request):
    """选择主机"""
    if request.method == 'POST':
        response = WebResponse()
        host_id = request.POST.get('host_id')
        host_group_id = request.POST.get('host_group_id')
        host_obj = models.Host.objects.filter(id=host_id).first()
        host_group_obj = models.HostGroup.objects.filter(
            id=host_group_id).first()
        template_obj_list = list(host_obj.templates.all())
        if host_group_obj:
            for item in list(host_group_obj.templates.all()):
                if item not in template_obj_list:
                    template_obj_list.append(item)
        chart_list = []
        # [{'id': 1, 'name': 'CPU负载'}, {'id': 2, 'name': '硬盘空间使用'}, {'id': 3, 'name': '网络流量'}]
        for template_obj in template_obj_list:
            for chart_obj in template_obj.chart_set.all():
                if chart_obj.auto:  # 自动需要获取redis
                    redis_key_name = 'Data_%s_%s_latest' % (
                        host_obj.hostname, chart_obj.applications.name)
                    last_point = json.loads(
                        REDIS_OBJ.lrange(redis_key_name, -1, -1)[-1].decode())
                    # [{'data': {'ens33': {'t_in': 0.28, 't_out': 0.1}, 'lo': {'t_in': 0.0, 't_out': 0.0}}}, 1529472380.8842905]
                    name_list = []
                    for k1, v1 in last_point[0].items():
                        if k1 == 'data':
                            for k2, v2 in v1.items():
                                name_list.append(k2)
                    for name in name_list:
                        chart_list.append({
                            'id':
                            chart_obj.id,
                            'name':
                            '%s %s' % (chart_obj.name, name)
                        })
                else:
                    chart_list.append({
                        'id': chart_obj.id,
                        'name': chart_obj.name
                    })
        response.data = chart_list
        return JsonResponse(response.__dict__)
Exemplo n.º 13
0
def del_user(request):
    """删除用户视图"""
    if request.method == 'POST':
        response = WebResponse()
        user_list = request.POST.getlist('user_list')
        try:
            with transaction.atomic():
                for uid in user_list:
                    uid = int(uid)
                    user_obj = models.UserProfile.objects.filter(
                        id=uid).first()
                    user_obj.delete()
                    Logger().log(message='删除用户成功,%s' % user_obj.email,
                                 mode=True)
            response.message = '删除用户成功'
        except Exception as e:
            response.status = False
            response.error = str(e)
            Logger().log(message='删除用户失败,%s' % str(e), mode=False)
        return JsonResponse(response.__dict__)
Exemplo n.º 14
0
def del_action(request):
    """删除报警策略视图"""
    if request.method == 'POST':
        response = WebResponse()
        action_list = request.POST.getlist('action_list')
        try:
            with transaction.atomic():
                for action_id in action_list:
                    action_id = int(action_id)
                    action_obj = models.Action.objects.filter(
                        id=action_id).first()
                    action_obj.delete()
                    Logger().log(message='删除报警策略成功,%s' % action_obj.name,
                                 mode=True)
            response.message = '删除报警策略成功'
        except Exception as e:
            response.status = False
            response.error = str(e)
            Logger().log(message='删除报警策略失败,%s' % str(e), mode=False)
        return JsonResponse(response.__dict__)
Exemplo n.º 15
0
def del_application(request):
    """删除应用集视图"""
    if request.method == 'POST':
        response = WebResponse()
        application_list = request.POST.getlist('application_list')
        try:
            with transaction.atomic():
                for application_id in application_list:
                    application_id = int(application_id)
                    application_obj = models.Application.objects.filter(id=application_id).first()
                    key_in_redis = '*_%s_*' % application_obj.name
                    key_list = REDIS_OBJ.keys(key_in_redis)
                    for key in key_list:
                        REDIS_OBJ.delete(key)  # 删除redis中相关监控项
                    application_obj.delete()
                    # 删除redis中相关数据

                    Logger().log(message='删除应用集成功,%s' % application_obj.name, mode=True)
            response.message = '删除应用集成功'
        except Exception as e:
            response.status = False
            response.error = str(e)
            Logger().log(message='删除应用集失败,%s' % str(e), mode=False)
        return JsonResponse(response.__dict__)
Exemplo n.º 16
0
def select_chart_for_show_chart(request):
    """选择图表"""
    if request.method == 'POST':
        response = WebResponse()
        data = {
            'chart_name': None,
            'chart_type': None,
            'chart_data': None,
            'chart_data_unit': None
        }
        chart_id = request.POST.get('chart_id')
        chart_name = request.POST.get('chart_name')
        if len(chart_name.split()) >= 2:
            special_key = chart_name.split()[-1]
        else:
            special_key = None
        search_time = int(request.POST.get('search_time'))
        host_id = request.POST.get('host_id')
        chart_obj = models.Chart.objects.filter(id=chart_id).first()
        host_obj = models.Host.objects.filter(id=host_id).first()
        if special_key:
            data['chart_name'] = '%s %s' % (chart_obj.name, special_key)
        else:
            data['chart_name'] = chart_obj.name
        data['chart_type'] = chart_obj.chart_type
        chart_data_unit = chart_obj.items.all().first().data_unit
        data['chart_data_unit'] = chart_data_unit
        if search_time <= 604800:
            time_tag = 'latest'
        elif 604800 < search_time <= 2592000:
            time_tag = '10min'
        elif 2592000 < search_time <= 7776000:
            time_tag = '30min'
        else:
            time_tag = '1hour'
        application_obj = chart_obj.applications
        redis_key_name = 'Data_%s_%s_%s' % (host_obj.hostname,
                                            application_obj.name, time_tag)
        item_obj_list = chart_obj.items.all()
        item_name_list = []
        for item_obj in item_obj_list:
            item_name_list.append(item_obj.key)
        approximate_data_point = int(
            (search_time + 60) / application_obj.interval)
        approximate_data_list = [
            json.loads(i.decode()) for i in REDIS_OBJ.lrange(
                redis_key_name, -approximate_data_point, -1)
        ]
        data_list = []
        for point in approximate_data_list:
            value_dict, save_time = point
            if time.time() - save_time < search_time:
                data_list.append(point)
        # data: [[1529396379937.173, 2.11]] 最后数据
        # 无data redis数据 [[{'load5': 0.01, 'load1': 0.0, 'load15': 0.05}, 1529474049.0319276], [{'load5': 0.01, 'load1': 0.0, 'load15': 0.05}, 1529474108.3643043]]
        # 有data redis数据 [[{'data': {'/': {'Size': 48097, 'Used': 2034, 'Avail': 46063, 'Use': 5}, '/boot': {'Size': 1014, 'Used': 155, 'Avail': 860, 'Use': 16}}}, 1529474108.3532693]]
        chart_data = []
        if data_list:
            last_point = data_list[-1][0]
        else:
            last_point = None
        if last_point:
            if 'data' in last_point:  # 有data
                if chart_obj.chart_type == 'line' or chart_obj.chart_type == 'area':  # 线型图或面积图
                    for item_name in item_name_list:
                        chart_data.append({'name': item_name, 'data': []})
                    for data_point in data_list:
                        data_dict = data_point[
                            0]  # {'data': {'lo': {'t_out': 0.0, 't_in': 0.0}, 'ens33': {'t_out': 0.07, 't_in': 0.17}}
                        save_time = data_point[1]
                        for k1, v1 in data_dict['data'].items():
                            if k1 == special_key:  # 字段对上了
                                for k2, v2 in v1.items():
                                    temp_list = []
                                    temp_list.append(save_time * 1000)
                                    temp_list.append(v2)
                                    for item in chart_data:
                                        if item['name'] == k2:
                                            item['data'].append(temp_list)
                else:  # 饼图
                    # {'data': {'/boot': {'Use': 16, 'Avail': 860, 'Used': 155, 'Size': 1014}, '/': {'Use': 5, 'Avail': 46055, 'Used': 2043, 'Size': 48097}}}
                    for k, v in last_point['data'].items():
                        if k == special_key:  # 对上了
                            key = item_name_list[0]
                            # [{'data': 5, 'name': '已使用'}]
                            chart_data.append({'name': '已使用', 'data': v[key]})
            else:  # 无data
                if time_tag == 'latest':  # 无优化值
                    if chart_obj.chart_type == 'line' or chart_obj.chart_type == 'area':  # 线型图或面积图
                        for item_name in item_name_list:
                            chart_data.append({'name': item_name, 'data': []})
                        for data_point in data_list:
                            data_dict = data_point[0]
                            save_time = data_point[1]
                            for k, v in data_dict.items():
                                temp_list = []
                                temp_list.append(save_time * 1000)
                                temp_list.append(v)
                                for item in chart_data:
                                    if item['name'] == k:
                                        item['data'].append(temp_list)
                    else:  # 饼图
                        for k, v in last_point.items():
                            key = item_name_list[0]
                            if k == key:  # 对上了
                                # [{'data': 5, 'name': '已使用'}]
                                chart_data.append({'name': '已使用', 'data': v})
                else:  # 优化值
                    if chart_obj.chart_type == 'line' or chart_obj.chart_type == 'area':  # 线型图或面积图
                        for item_name in item_name_list:
                            chart_data.append({'name': item_name, 'data': []})
                        for data_point in data_list:
                            data_dict = data_point[0]
                            save_time = data_point[1]
                            if data_dict is not None:
                                for k, v in data_dict.items():
                                    temp_list = []
                                    temp_list.append(save_time * 1000)
                                    if special_key:
                                        if special_key == k:
                                            for item_key, item_value in v.items(
                                            ):
                                                for item in chart_data:
                                                    if item['name'] == item_key:
                                                        temp_list.append(
                                                            item_value[0])
                                                        item['data'].append(
                                                            temp_list)
                                    else:
                                        temp_list.append(v[0])
                                        for item in chart_data:
                                            if item['name'] == k:
                                                item['data'].append(temp_list)
        data['chart_data'] = chart_data
        response.data = data
        return JsonResponse(response.__dict__)