示例#1
0
 def host_detail(cc_biz_id, ip, plat_id):
     result = dict()
     with ignored(Exception):
         result = client.cc.get_host_list_by_ip(ip=ip,
                                                app_id=cc_biz_id,
                                                plat_id=plat_id)
     return result.get("data") or []
示例#2
0
 def modules(cc_biz_id, set_id_list=None):
     """获取业务下的模块列表,按机器数量排序"""
     with ignored(Exception):
         ips = set([])
         if set_id_list and (not hasattr(set_id_list, "__iter__")):
             set_id_list = [set_id_list]
         if set_id_list is not None:
             set_id_list = ";".join(map(str, set_id_list))
         module_list = client.cc.get_modules_by_property(
             app_id=cc_biz_id, set_id=set_id_list).get("data") or []
         module_id_list = [
             module_item["ModuleID"] for module_item in module_list
         ]
         host_list = CCBiz._hosts(cc_biz_id).get("data") or []
         if module_id_list:
             module_info = collections.defaultdict(set)
             for host in host_list:
                 if host["ModuleID"] in module_id_list:
                     module_info[host["ModuleID"]].add(host_key(host))
                     module_info["0"].add(host_key(host))
             for set_item in module_list:
                 set_item["host_count"] = len(
                     module_info[set_item["ModuleID"]])
                 set_item["ModuleName"] += ' [%s]' % set_item["host_count"]
             module_list = sorted(module_list,
                                  key=lambda x: x['host_count'],
                                  reverse=True)
             return module_list, len(module_info["0"])
     return [], 0
示例#3
0
 def agent_status(cc_biz_id, host_id_list):
     """获取agent状态信息
     agent状态详细分成4个状态:正常,离线,未安装。已安装,无数据。
     """
     result = collections.defaultdict(int)
     with ignored(Exception):
         ip_info_list = list()
         if not hasattr(host_id_list, "__iter__"):
             host_id_list = [host_id_list]
         for host_id in host_id_list:
             ip, plat_id = parse_host_id(host_id)
             plat_id = plat_id if plat_id != "1" else "0"
             ip_info_list.append({"ip": ip, "plat_id": plat_id})
         if not ip_info_list:
             return {}
         status_list = client.job.get_agent_status(
             app_id=cc_biz_id, ip_infos=ip_info_list,
             is_real_time=1).get("data") or []
         for info in status_list:
             plat_id = info["plat_id"]
             ip = info["ip"]
             host_id = host_key(ip=ip, plat_id=plat_id)
             exist = bool(info["status"])
             if not exist:
                 result[host_id] = AGENT_STATUS.NOT_EXIST
                 continue
             else:
                 result[host_id] = AGENT_STATUS.ON
     return result
示例#4
0
 def ips(cc_biz_id, plat_id=None):
     """获取业务下的ip列表,按IP排序"""
     ips = []
     with ignored(Exception):
         result = CCBiz._hosts(cc_biz_id)
         if result["result"]:
             for data in (result.get("data") or []):
                 if data["Source"] == "0":
                     data["Source"] = "1"
                 if plat_id is not None and plat_id == data["Source"]:
                     ips.append(data["InnerIP"])
     return sorted(ips)
示例#5
0
 def set_module_ips(cc_biz_id, set_id="", module_id=""):
     """获取业务下大区下模块的ip列表,根据平台id和ip组合去重"""
     ips = set(list())
     with ignored(Exception):
         if module_id:
             result = client.cc.get_module_host_list(app_id=cc_biz_id,
                                                     module_id=module_id)
         else:
             result = client.cc.get_hosts_by_property(app_id=cc_biz_id,
                                                      set_id=set_id)
         if result["result"]:
             for host in (result.get("data") or []):
                 ips.add(host_key(host))
     return sorted(list(set(ips)))
示例#6
0
def render_star_panel(request, cc_biz_id):
    """
    渲染关注面板
    :param request:
    :param cc_biz_id:
    :return:
    """
    # 每页9张图
    num_per_page = 9
    try:
        current_page = int(request.GET.get("page", "1"))
    except:
        current_page = 1
    star_menu = ScenarioMenu.objects.filter(system_menu=u"favorite",
                                            biz_id=cc_biz_id)
    if not star_menu.exists():
        menus = ScenarioMenu.objects.init_biz_scenario_menu(cc_biz_id)
        locations = []
        for menu in menus:
            if menu.system_menu == u"favorite":
                star_menu = menu
    else:
        star_menu = star_menu[0]
        locations = MonitorLocation.objects.filter(
            menu_id=star_menu.id, biz_id=cc_biz_id).order_by("graph_index")
    filter_loctaions = []
    for l in locations:
        if not l.monitor or l.monitor.is_deleted:
            l.is_deleted = True
            l.save()
        else:
            filter_loctaions.append(l)
    obs_count = len(filter_loctaions) + 1
    total_pages = obs_count / num_per_page + (1 if obs_count % num_per_page > 0
                                              else 0)
    filter_loctaions = filter_loctaions[num_per_page *
                                        (current_page - 1):num_per_page *
                                        current_page]
    monitor_count = 0
    with ignored(Exception):
        monitor_count = len(
            Monitor.objects.filter(is_deleted=False,
                                   is_enabled=True,
                                   biz_id=cc_biz_id))
    return render_mako_context(request,
                               '/monitor/overview/star_chart_panel.html',
                               locals())
示例#7
0
 def sets(cc_biz_id):
     """获取业务下SET列表,按机器数量排序"""
     # 获取set列表
     with ignored(Exception):
         ips = set([])
         set_list = client.cc.get_sets_by_property(
             app_id=cc_biz_id).get("data") or []
         set_id_list = [set_item["SetID"] for set_item in set_list]
         host_list = CCBiz._hosts(cc_biz_id).get("data") or []
         if set_id_list:
             set_info = collections.defaultdict(set)
             for host in host_list:
                 if host["SetID"] in set_id_list:
                     set_info[host["SetID"]].add(host_key(host))
                     set_info["0"].add(host_key(host))
             for set_item in set_list:
                 set_item["host_count"] = len(set_info[set_item["SetID"]])
                 set_item["SetName"] += ' [%s]' % set_item["host_count"]
             set_list = sorted(set_list,
                               key=lambda x: x['host_count'],
                               reverse=True)
             return set_list, len(set_info["0"])
     return [], 0
示例#8
0
def pre_save_models(sender, instance, **kwargs):
    if isinstance(instance, MODELS_TO_LOG):
        if (not hasattr(instance, 'id')) or instance.id < 1:
            return
        with ignored(Exception):
            before_save_obj = instance
            # 如果是alarm_def 则比较麻烦, 需要在pre_save的时候把收敛,处理,通知
            if isinstance(instance, AlarmDef):
                from monitor.models import AlarmStrategy
                try:
                    converge = instance.converge
                except:
                    converge = False
                if converge:
                    setattr(before_save_obj, 'converge_string',
                            AlarmStrategy.gen_converge_str(instance.converge))
                else:
                    setattr(before_save_obj, 'converge_string', u'无')

                notify_way = []
                try:
                    notify = json.loads(instance.notify)
                    for key in notify:
                        if 'notify_' in key:
                            notify_way.append(key.replace('notify_', ''))
                except:
                    notify = {}
                setattr(before_save_obj, 'notify_string',
                        AlarmStrategy.gen_notify_final_str(notify_way, notify))

            before_save_obj = serialize_object(before_save_obj)
            request = get_request()
            # 把保存前的信息存入session
            if not request.session.get('model_operation_cache', False):
                request.session['model_operation_cache'] = {}
            key = "%s_%s" % (sender.__name__, instance.id)
            request.session['model_operation_cache'][key] = before_save_obj
示例#9
0
def graph_point(request, cc_biz_id):
    """
    获取图表数据
    """
    args = request.GET
    time_range = None
    single_graph_date = args.get("graph_date")
    host_id = request.GET.get("host_id", "")
    index_id = args.get("index_id", "")
    ip = plat_id = index_obj = ""
    with ignored(Exception):
        # 主机信息
        ip, plat_id = parse_host_id(host_id)
        # 需要转换平台id(gse的0 等于 cc的1)........................
        plat_id = "0" if plat_id == "1" else plat_id
        index_obj = HostIndex.get(id=index_id)
        # 时间解析
        if single_graph_date:
            start = datetime.datetime.strptime(single_graph_date, "%Y-%m-%d")
            end = start + datetime.timedelta(days=1)
            time_range = "%s -- %s" % (start.strftime("%Y-%m-%d %H:%M"),
                                       end.strftime("%Y-%m-%d %H:%M"))
    if not all([ip, plat_id, index_obj]):
        return render_json(failed(u"无效的请求"))
    try:
        unit = index_obj.unit_display
        conversion = float(index_obj.conversion)
        ext_kw = {
            "unit": unit,
            "conversion": conversion,
            "series_label_show": index_obj.desc
        }
        kwargs = {"time_range": time_range, "ip": ip, "cloud_id": str(plat_id)}
        result_table_id = index_obj.result_table_id
        value_field = index_obj.item
        group_field = index_obj.dimension_field
        rt_id = "%s_%s" % (cc_biz_id, result_table_id)
        if group_field:
            ext_kw["group_field"] = group_field
        series_suffix = ""
        dimension_field = args.get("dimension_field",
                                   index_obj.dimension_field)
        dimension_value = args.get("dimension_field_value", "")
        if dimension_field and dimension_value:
            kwargs[dimension_field] = dimension_value
        series_name_list = []
        series_list = []
        from utils.trt import trans_bkcloud_rt_bizid
        rt_id = trans_bkcloud_rt_bizid(rt_id)
        data = DataProcessor.base_performance_data(rt_id, value_field, kwargs,
                                                   **ext_kw)
        for series_name in data["series_name_list"]:
            series_name_list.append(series_name + series_suffix)
        for series in data["series"]:
            if series["name"] in [u"本周期"]:
                series["zIndex"] = 5
            series["name"] += series_suffix
            series_list.append(series)
        data["series"] = series_list
        data["series_name_list"] = series_name_list
        data["min_y"] = min(data["min_y"], 0)
        data["max_y"] = max(data["max_y"], 0)
        if data["min_y"] == data["max_y"]:
            if data["max_y"] == 0:
                data["yaxis_range"] = "0:1"
            if data["max_y"] > 0:
                data["yaxis_range"] = "0:"
            if data["max_y"] < 0:
                data["yaxis_range"] = ":0"
        data = {'data': data, 'echo_sql': data['echo_sql']}
        del data["data"]["echo_sql"]
        data["update_time"] = datetime.datetime.now()
        return render_json(ok_data(data))
    except EmptyQueryException:
        return render_json(
            failed_data(u"查询无数据,请确认该主机(%s)的数据上报是否正常!" % ip, {
                'echo_sql': "",
                'error_class': 'info'
            }))
    except SqlQueryException as e:
        logger.exception(u"查询失败,原因: %s" % e)
        return render_json(
            failed_data(u"查询失败,原因: %s" % e, {
                'echo_sql': "",
                'error_class': 'warning'
            }))
    except TableNotExistException as e:
        logger.exception(e)
        return render_json(
            failed_data(
                u"查询无数据!", {
                    'echo_sql': "",
                    'error_class': 'info',
                    'need_access': "need_access"
                }))
    except Exception as e:
        logger.exception(u"后台异常: %s" % e)
        return render_json(
            failed_data(u"生成图表异常", {
                'echo_sql': "",
                'error_class': 'critical'
            }))
示例#10
0
 def host_property_list(cc_biz_id):
     result = dict()
     with ignored(Exception):
         result = client.cc.get_property_list(app_id=cc_biz_id, type=4)
     return result.get("data", {})