Esempio n. 1
0
def detailService(request, service_id):
    token = request.session.get('passToken')
    ctrl_header = request.session.get("ctrl_header")
    if request.method == "POST" and request.is_ajax():
        control = ControlEngine(ctrl_header)
        # control = ControllerEngine()  # TODO: debugging용
        service = control.get_service(service_id)
        return JsonResponse(service)
    else:
        if not token:
            response = redirect(
                "/dashboard/domains/?next=/dashboard/telemeter/metering/" +
                service_id)
        else:
            control = ControlEngine(ctrl_header)
            service = control.get_service(service_id)
            if service.get("success"):
                service_detail = service["success"].get("service_detail")
                servers = service_detail.get("vm_list")
                response = render(request, 'telemeter/info.html', {
                    "servers": servers,
                    "service_name": service_detail.get("name")
                })
            else:
                response = render(request, 'telemeter/info.html',
                                  {"error": service})
        logger.info("detailService_end")
        return response
Esempio n. 2
0
def delete_service(request, service_id):
    """
    서비스 삭제
    :param request:
    :param service_id:
    :return:
    """
    logger.info("delete_service")
    ctrl_header = request.session.get("ctrl_header")
    control = ControlEngine(ctrl_header)
    result = control.delete_service(service_id)
    # result = {"success":{"error_msg_list":{"a":"A", "b":"B", "c":"C"}}}
    # if result.get("success"):
    #     관리포탈 동기화용
    #     conn = SOAControlDBConnector.getInstance()
    #
    #     params = (request.session.get("domain_name"), request.session.get("project_name"))
    #     if len(conn.select(SELECT_SOAC_PROJECT, params)) >= 1:
    #     params = (
    #         request.session.get("domain_name"),
    #         request.session.get("project_name"),
    #         service_id,
    #     )
    #     try:
    #         from pprint import pprint
    #         print "=============params============="
    #         pprint(params)
    #         delete_service = conn.delete(DELETE_SOAC_SERVICE, params)
    #         print "================result================ ", delete_service
    #         temp = {"success": {"message": "서비스삭제", "title": "성공"}}
    #     except Exception as e:
    #         temp = {"error": {"message": str(e), "title": "error"}}
    #     동기화용 끝
    return JsonResponse(result)
Esempio n. 3
0
def getChainingList(request, service_id):
    if request.is_ajax() and request.method == 'POST':
        ctrl_header = request.session.get('ctrl_header')

        control = ControlEngine(ctrl_header)
        result = control.get_sfc_list(service_id)
        return JsonResponse(result)
Esempio n. 4
0
def create_dst_routing(request, router_id):
    control = ControlEngine(request.session.get("ctrl_header"))
    data = json.loads(request.POST.get("data"))
    netnodeip = request.POST.get("netnodeip")
    result = control.create_route_dst_rule_path("qrouter-" + router_id,
                                                netnodeip, data)
    return JsonResponse(result)
Esempio n. 5
0
def create_service(request):
    """
    서비스 생성
    :param request:
    :return:
    """
    if request.is_ajax() and request.method == 'POST':
        logger.info("create_service")
        service_template = json.loads(request.POST.get("service_templates"))
        service_template["description"] = unicode(
            service_template.get("description"))
        data_dic = json.loads(request.POST.get("mapData"))
        control = ControlEngine(request.session.get("ctrl_header"))
        result = control.create_service(service_template)

        if result.get("success"):
            logger.info("create_map")
            result["success"]["createMap"] = control.create_map(
                result["success"]["service_id"], json.dumps(data_dic))
            service_info = result["success"]
            # 관리포탈 동기화용
            if request.POST.get("soam_synchronize") == "true":
                try:
                    logger.debug("[synchronize ...]")
                    synchronize_soam(request, service_info, data_dic)
                except Exception as e:
                    error_str = """
                    Title: {}
                    Traceback: {}
                    """.format(e.message,
                               traceback.format_exc().strip())
                    logger.debug("[synchronize fail]\n{}".format(error_str))
                    temp = {"error": {"message": str(e), "title": "error"}}
        return JsonResponse(result)
Esempio n. 6
0
def get_all_service_list(request):
    """
    서비스 전체 조회 페이지
    :param request:
    :return:
    """
    user_name = request.session.get("user_name")
    token = request.session.get('passToken')
    ctrl_header = request.session.get('ctrl_header')
    control = ControlEngine(ctrl_header)
    logger.debug("user_name: {}\nctrl_header: {}".format(
        user_name, ctrl_header))
    if user_name == 'admin':
        logger.debug("true")
        result = control.get_all_service_list()
        logger.debug(result)
        if result.get("success"):
            result = result.get("success")

        if not token:
            return redirect(
                "/dashboard/domains/?next=/dashboard/service/all_service")
        return render(request, 'service/all_index.html', result)
    else:
        return redirect("/dashboard/service")
Esempio n. 7
0
def getPortList(request, service_id):
    if request.is_ajax() and request.method == 'POST':
        resource_type = request.POST.get("resource_type")
        resource_id = request.POST.get("resource_id")
        ctrl_header = request.session.get("ctrl_header")

        control = ControlEngine(ctrl_header)
        result = control.get_port_list(resource_type, resource_id)
        return JsonResponse(result)
Esempio n. 8
0
def simpleService(request, service_id):
    """
    간략한 서비스 정보
    :param request:
    :param service_id:
    :return:
    """
    if request.is_ajax() and request.method == 'POST':
        logger.info("simpleServicePOST")
        control = ControlEngine(request.session.get("ctrl_header"))
        service_map = control.get_map(service_id)
        # logger.info(service_map)

        logger.info("simpleServicePOST_end")
        if service_map.get("success"):
            try:
                if service_map["success"].get("map_link_list"):
                    map_data = service_map["success"]["map_link_list"]
                    if type(map_data) == str or type(map_data) == unicode:
                        map_data = json.loads(map_data.replace('\\"', '"'))
                    resource_list = map_data.get("resources")
                    links = map_data.get("links")
                    as_links = map_data.get("asLinks")
                    used_security_group_list = map_data.get(
                        "used_security_group_list")
                    security_types = map_data.get("security_types")
                    response = {
                        "success": {
                            "resources": resource_list,
                            "links": links,
                            "as_links": as_links
                        }
                    }
                    if used_security_group_list:
                        response[
                            "used_security_group_list"] = used_security_group_list
                    if security_types:
                        response["security_types"] = security_types
                    return JsonResponse(response)
                else:
                    return JsonResponse({
                        "error": {
                            "message": service_id + u" 연결정보가 없습니다.",
                            "response": service_map
                        }
                    })
            except Exception as e:
                return JsonResponse({
                    "error": {
                        "message": service_id + u" 연결정보가 올바르지 않습니다.",
                        "response": service_map,
                        "exception": e.message
                    }
                })
        else:
            return JsonResponse(service_map)
Esempio n. 9
0
def resume_service(request, service_id):
    """
    서비스 재시작
    :param request:
    :param service_id:
    :return:
    """
    logger.info("resume_service")
    ctrl_header = request.session.get("ctrl_header")
    control = ControlEngine(ctrl_header)
    result = control.resume_service(service_id)
    return redirect("/dashboard/service")
Esempio n. 10
0
def switch_project_with_token(request):
    token = request.session.get("passToken")
    if request.method == 'POST':
        data = json.loads(request.POST.get("data"))
        project_name = data.get("project_name")
        domain_name = request.session.get("domain_name")
        auth_url = request.session.get("auth_url")
        try:
            keystone = KeystoneRestAPI(auth_url, token)
        except Unauthorized as e:
            request.session["error"] = {
                "title": e.message,
                "message": e.details
            }
            return JsonResponse({
                "error": {
                    "title": e.message,
                    "message": e.details,
                    "code": 401
                }
            })
        # result = keystone.get_token_with_scoped_by_token(project_id=project_id)
        result = keystone.get_token_with_scoped_by_token(
            domain_name=domain_name, project_name=project_name)
        if result.get("success"):
            # request.session.set_expiry(SESSION_COOKIE_AGE)
            token = result['success']['token']
            request.session["passToken"] = token
            request.session["project_name"] = project_name

            roles = result["success"].get("roles")
            if roles:
                roles_str = ','.join(role.get("name") for role in roles)
            else:
                roles_str = ""

            user = result["success"].get("user")
            project = result["success"].get("project")
            request.session["user_id"] = user.get("id")
            request.session["user_name"] = user.get("name")
            request.session["project_id"] = project.get("id")

            request.session["roles"] = roles_str
            ctrl_engine = ControlEngine(token=token,
                                        project_id=project.get("id"),
                                        project_name=project_name,
                                        user_id=user.get("id"),
                                        user_name=user.get("name"),
                                        roles=roles_str,
                                        auth_url=auth_url)
            request.session["ctrl_header"] = ctrl_engine.get_header()

        return JsonResponse(result)
Esempio n. 11
0
def list_routing(request, router_id):
    """
    dst_rules, pbr_tables{src_rules}
    :param request:
    :param router_id:
    :return:
    """
    control = ControlEngine(request.session.get("ctrl_header"))
    modal_title = request.GET.get("modal_title")
    dst_rules = control.get_route_dst_rule_list()
    result = {"modal_title": modal_title, "router_id": router_id}
    if dst_rules.get("success"):
        netnodeip = [
            tmp_dst_rule.get("netnodeip")
            for tmp_dst_rule in dst_rules["success"]["result"]
            if tmp_dst_rule.get("router") == "qrouter-" + router_id
        ]
        if len(netnodeip) > 0:
            pbr_table_name = router_id.split("-")[0]
            result["pbr"] = pbr_table_name
            result["netnodeip"] = netnodeip[0]

            dst_rule = control.get_route_dst_rule("qrouter-" + router_id,
                                                  netnodeip[0])
            if dst_rule.get("success"):
                result["dst_rules"] = dst_rule["success"].get("result")

            result_pbr_tables = control.get_route_pbr_tables()
            if result_pbr_tables.get("success") and result_pbr_tables[
                    "success"].get("result") and len(
                        result_pbr_tables["success"]["result"]) > 0:
                pbr_tables = result_pbr_tables["success"].get("result")[0].get(
                    "routers").get("qrouter-" + router_id)
                result["pbr_tables"] = []
                for value in pbr_tables:
                    # logger.debug("\t\t\n{}\t\t\n{}\t\t\n{}".format(pbr_table_name, value.get("PBR_TABLE"),pbr_table_name in value.get("PBR_TABLE")))
                    if pbr_table_name in value.get(
                            "PBR_TABLE"
                    ):  # value.get("PBR_TABLE") in ["local", "main", "default"] or
                        pbr_table = {
                            "PBR_TABLE": value.get("PBR_TABLE"),
                            "order": value.get("order"),
                            "target": value.get("target")
                        }
                        src_rules = control.get_route_src_rules(
                            "qrouter-" + router_id, netnodeip[0],
                            value.get("PBR_TABLE"))
                        if src_rules.get("success"):
                            pbr_table["src_rules"] = src_rules["success"].get(
                                "result")
                        result["pbr_tables"].append(pbr_table)
    return render(request, "service/routing/index.html", result)
Esempio n. 12
0
def get_console_url(request):
    """
    가상머신 vnc console 주소 얻기
    :param request:
    :return:
    """
    if request.is_ajax() and request.method == 'POST':
        ctrl_header = request.session.get("ctrl_header")
        control = ControlEngine(ctrl_header)

        vm_id = request.POST.get("vm_id")
        result = control.get_vnc_console(vm_id)
        return JsonResponse(result)
Esempio n. 13
0
def get_resource_data(request):
    """
    각 자원 조회
    :param request:
    :return:
    """
    # if request.is_ajax() and request.method == 'POST':
    ctrl_header = request.session.get("ctrl_header")
    auth_url = request.session.get("auth_url")
    token = request.session.get("passToken")
    control = ControlEngine(ctrl_header)

    resource_type = request.GET.get("resource_type")
    resource_id = request.GET.get("resource_id")

    if resource_type == "AUTOSCALING" or resource_type == "LB" or resource_type == "AS_SERVER":
        data = json.loads(request.GET.get("data"))
        return render(
            request, 'service/include/right_pop_' + resource_type.lower() +
            '_info.html', {"data": data})
    else:
        result = control.get_resource(resource_type, resource_id)
        if result.get("success"):
            if resource_type == "SERVER":
                if result["success"]["server"].get("flavor"):
                    nova = NovaRestAPI(auth_url, token)
                    result_flavor = nova.get_flavor(
                        result["success"]["server"]["flavor"]["id"])
                    if result_flavor.get("success"):
                        result["success"]["server"]["flavor"][
                            "added_data"] = result_flavor["success"]["flavor"]
                    else:
                        logger.error(result_flavor)
                if result["success"]["server"].get("image"):
                    glance = GlanceRestAPI(auth_url, token)
                    result_image = glance.get_image(
                        result["success"]["server"]["image"]["id"])
                    if result_image.get("success"):
                        result["success"]["server"]["image"][
                            "added_data"] = result_image["success"]
                    else:
                        logger.error(result_image)
            else:
                logger.info("showResource(" + resource_type + ")")
                # logger.info(result)
            return render(
                request, 'service/include/right_pop_' + resource_type.lower() +
                '_info.html', result.get("success"))
        else:
            return JsonResponse(result)
Esempio n. 14
0
def create_dst_pop(request):
    modal_title = request.GET.get("modal_title")
    router_id = request.GET.get("router_id")
    netnodeip = request.GET.get("netnodeip")
    control = ControlEngine(request.session.get("ctrl_header"))
    result_interfaces = control.get_route_devices("qrouter-" + router_id,
                                                  netnodeip)
    if result_interfaces.get("success"):
        interfaces = result_interfaces["success"].get("result")
    else:
        interfaces = []
    return render(request, "service/routing/dst_create_modal.html", {
        "modal_title": modal_title,
        "interfaces": interfaces
    })
Esempio n. 15
0
def execChaining(request, service_id):
    if request.is_ajax() and request.method == 'POST':
        ctrl_header = request.session.get('ctrl_header')
        order = request.POST.get("order")
        sfc_id = request.POST.get("sfc_id")

        control = ControlEngine(ctrl_header)
        result = {}

        if order == 'pause':
            result = control.pause_sfc(service_id, sfc_id)
        elif order == 'resume':
            result = control.resume_sfc(service_id, sfc_id)
        elif order == 'delete':
            result = control.delete_sfc(service_id, sfc_id)

        return JsonResponse(result)
Esempio n. 16
0
def createChaining(request, service_id):
    if request.is_ajax() and request.method == 'POST':
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        ctrl_header = request.session.get('ctrl_header')

        control = ControlEngine(ctrl_header)
        service_detail = control.get_service(service_id)
        response = {"success": {}, "error_msg_list": []}
        if service_detail.get("success"):
            response["success"]["service"] = service_detail["success"]
        else:
            response["error_msg_list"].append(service_detail.get("error"))

        map_data = control.get_map(service_id)
        if map_data.get("success"):
            response["success"]["links"] = map_data["success"][
                "map_link_list"].get("links")
            response["success"]["asLinks"] = map_data["success"][
                "map_link_list"].get("asLinks")
            response["success"]["resources"] = map_data["success"][
                "map_link_list"].get("resources")
        else:
            response["error_msg_list"].append(map_data.get("error"))

        neutron = NeutronRestAPI(auth_url, token)
        public_network = neutron.get_external_network(
            {"router:external": True})
        if public_network.get("success"):
            response["success"]["public_network"] = public_network[
                "success"].get("networks")
        else:
            response["error_msg_list"].append(public_network.get("error"))

        return JsonResponse(response)

    elif request.method == 'POST':
        jsonData = request.POST.get("jsonData")
        return render(request, 'service/create_chaining.html',
                      {'service_detail': jsonData})
    else:
        token = request.session.get('passToken')
        if not token:
            return redirect("/dashboard/domains/?next=/dashboard/service/" +
                            service_id + "/chaining/create")
        return render(request, 'service/create_chaining.html', {})
Esempio n. 17
0
def createChainingDev(request, service_id):
    if request.is_ajax() and request.method == 'POST':
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        ctrl_header = request.session.get("ctrl_header")

        control = ControlEngine(ctrl_header)
        neutron = NeutronRestAPI(auth_url, token)

        service_detail, map_data = control.get_service_detail_and_link_list(
            service_id)

        # rel
        map_data = control.get_map(service_id)
        public_network = neutron.get_external_network(
            {"router:external": True})

        #dev        # {'success':{'id':"",'chain_id':""}}
        return JsonResponse({
            'success': {
                'service': {
                    "service_detail":
                    service_detail["success"]["service_detail"]
                },
                "links": map_data["success"]["map_link_list"],
                "public_network": public_network
            }
        })


#rel
# return JsonResponse({'service': service_detail["success"], 'instance_list':instanceList, "links": map_data["success"]["map_link_list"], "public_network": public_network})
    else:

        sfc_name = request.POST.get("sfc_name")
        sfc_desc = request.POST.get("sfc_desc")

        # print "~~~~~~~~~~~~~~~"
        # print sfc_name
        # print sfc_desc

        return render(request, 'service/create_chaining.html', {
            'sfc_name': sfc_name,
            'sfc_desc': sfc_desc
        })
Esempio n. 18
0
def sync(request, network_id):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    neutron = NeutronRestAPI(auth_url, token)
    service_id = request.POST.get("service_id")
    from sdsecgui.db.soa_db_connector import SOAManagerDBConnector
    from sdsecgui.tools.ctrlengine import ControlEngine
    control = ControlEngine(request.session.get("ctrl_header"))
    try:
        m_conn = SOAManagerDBConnector.getInstance()
        m_conn.insert_network(auth_url, control, neutron, service_id,
                              network_id)
        result = True
    except Exception as e:
        from sdsec.settings import logger
        logger.debug(e.message)
        result = False
    return JsonResponse({"result": result})
Esempio n. 19
0
def updateService(request, service_id):
    """
    서비스 수정
    :param request:
    :param service_id:
    :return:
    """
    if request.is_ajax() and request.method == 'POST':
        service_template = json.loads(request.POST.get("service_templates"))
        service_template["description"] = unicode(
            service_template.get("description"))
        dataDic = request.POST.get("mapData")
        # logger.info(dataDic)
        control = ControlEngine(request.session.get("ctrl_header"))
        result = control.update_service(service_template, service_id)

        if result.get("success"):
            # service_info = result["success"]
            result["success"]["update_map"] = control.update_map(
                service_id, dataDic.replace('\\', ''))
            # 관리포탈 동기화용
            # conn = SOAControlDBConnector.getInstance()

            # params = (request.session.get("domain_name"), request.session.get("project_name"))
            # if len(conn.select(SELECT_SOAC_PROJECT, params)) >= 1:
            #     params = (
            #         service_info.get("name"),
            #         service_info.get("status"),
            #         request.session.get("domain_name"),
            #         request.session.get("project_name"),
            #         service_id,
            #     )
            #     try:
            #         from pprint import pprint
            #         TODO: 관리포탈 전용
            #         print "=============params============="
            #         pprint(params)
            #         delete_service = conn.delete(DELETE_SOA_SERVICE, params)
            #         print "================result================ ", delete_service
            #         temp = {"success": {"message": "서비스삭제", "title": "성공"}}
            #     except Exception as e:
            #         temp = {"error": {"message": str(e), "title": "error"}}
            # 동기화용 끝
        return JsonResponse(result)
Esempio n. 20
0
def create_src_routing(request, router_id):
    control = ControlEngine(request.session.get("ctrl_header"))
    data = json.loads(request.POST.get("data"))
    netnodeip = request.POST.get("netnodeip")
    create_type = request.POST.get("type")

    if create_type == "type1":
        type1 = {
            "type": "type1",
            "src": data.get("src"),
            "pbr": data.get("pbr")
        }
        result_pbr_tables = control.get_route_pbr_tables()
        if result_pbr_tables.get("success") and result_pbr_tables[
                "success"].get("result") and len(
                    result_pbr_tables["success"]["result"]) > 0:
            pbr_tables = result_pbr_tables["success"].get("result")[0].get(
                "routers").get("qrouter-" + router_id)
            for value in pbr_tables:
                if type1["pbr"] == value.get("PBR_TABLE"):
                    return JsonResponse({
                        "error": {
                            "message": "exist pbr_table name: " + type1["pbr"],
                            "title": "exist pbr_table name"
                        }
                    })
        result = control.create_route_src_rule_path("qrouter-" + router_id,
                                                    netnodeip, type1)

    elif create_type == "type2":
        type2 = {
            "type": "type2",
            "dest": data.get("dest"),
            "via": data.get("via"),
            "dev": data.get("dev"),
            "pbr": data.get("pbr")
        }
        result = control.create_route_src_rule_path("qrouter-" + router_id,
                                                    netnodeip, type2)
    else:
        result = {"error": {"message": "not support", "title": ""}}
    return JsonResponse(result)
Esempio n. 21
0
def saveChaining(request, service_id):
    if request.is_ajax() and request.method == 'POST':
        sfc_name = request.POST.get("sfc_name")
        sfc_desc = request.POST.get("sfc_desc")
        fc_list = json.loads(request.POST.get("fc_list"))
        sfg_list = json.loads(request.POST.get("sfg_list"))

        token = request.session.get('passToken')
        domain_name = request.session.get('domain_name')
        project_name = request.session.get('project_name')
        user_name = request.session.get('user_name')
        ctrl_header = request.session.get('ctrl_header')
        # print "=========================createSFC()=============================="
        # print "=========================fc_list=============================="
        # pprint.pprint(fc_list)
        # print "=========================sfg_list=============================="
        # pprint.pprint(sfg_list)

        control = ControlEngine(ctrl_header)
        sfc_template = {}
        sfc_template["service_function_group_list"] = sfg_list
        sfc_template["flow_classifier_list"] = fc_list
        sfc_template["sfc_name"] = sfc_name
        sfc_template["sfc_desc"] = sfc_desc
        result = control.create_sfc(service_id, sfc_template)
        if result.get("NeutronError"):
            result = {
                "error": {
                    "message": result["NeutronError"]["message"],
                    "title": result["NeutronError"]["type"]
                }
            }
        # print "=========================result=============================="
        # pprint.pprint(result)
        # if result.get('success'):
        # result['success']['chain_id']
        # else:

        # {"error":{'message':""}}
        # {'success':{'id':"",'chain_id':""}}
        return JsonResponse(result)
Esempio n. 22
0
def list_service(request):
    """
    서비스 목록 페이지
    :param request:
    :return:
    """
    if request.method == 'POST':
        logger.info("listService_ajax")
        control = ControlEngine(request.session.get("ctrl_header"))
        # TODO: 알람을 위해 가데이터 받아오기
        # control = ControllerEngine()  # TODO: debugging 용
        service_list = control.get_service_list()
        logger.info("listService_ajax_end")
        return JsonResponse(service_list)
    else:
        token = request.session.get('passToken')
        if not token:
            return redirect("/dashboard/domains/?next=/dashboard/service")
        logger.info("listService_end")
        if request.GET.get("error_msg_list"):
            error_msg_list = request.GET.get("error_msg_list")
            return render(request, 'service/index.html',
                          {"error_msg_list": error_msg_list})
        return render(request, 'service/index.html', {})
Esempio n. 23
0
    def insert_service_resource(self, params, service_template, request):
        auth_url = params[0]
        service_id = params[2]
        token = request.session.get("passToken")
        ctrl_header = request.session.get("ctrl_header")

        neutron = NeutronRestAPI(auth_url, token)
        nova = NovaRestAPI(auth_url, token)
        glance = GlanceRestAPI(auth_url, token)
        cinder = CinderRestAPI(auth_url, token)

        control = ControlEngine(ctrl_header)

        # router
        routers = service_template.get("vrouter_list")
        for router in routers:
            self.insert_router(auth_url, neutron, service_id,
                               router.get("vrouter_id"))

        # network
        networks = service_template.get("network_list")
        for network in networks:
            self.insert_network(auth_url, control, neutron, service_id,
                                network.get("network_id"))

        # server
        servers = service_template.get("vm_list")
        for server in servers:
            self.insert_server(auth_url, nova, service_id, server.get("vm_id"),
                               glance)

        # volume
        volumes = service_template.get("volume_list")
        for volume in volumes:
            self.insert_volume(auth_url, cinder, service_id,
                               volume.get("volume_id"))
Esempio n. 24
0
def login_soa(request):
    data = None
    try:
        data = json.loads(request.POST.get("data"))
    except ValueError as e:
        result = {
            "error": {
                "title": e.message,
                "message": "json malformed error"
            }
        }
    else:
        auth_url = data.get("auth_url")
        user_name = data.get("user_name")
        password = data.get("pass")
        project_name = data.get("project_name")
        soac_conn = SOAControlDBConnector.getInstance()
        if auth_url == request.session.get("auth_url"):
            domain_name = request.session.get("domain_name")
        else:
            domain = soac_conn.select_one(SELECT_SOAC_DOMAINS, auth_url)
            domain_name = domain.get("domain_name")

        token = None
        roles = None
        roles_str = None
        project_id = None
        user_id = None
        keystone = None

        # =================================Scope Login==================================
        result = KeystoneRestAPI.get_token(auth_url, user_name, password,
                                           domain_name, project_name)
        # if type(result) == str:
        #     result = ast.literal_eval(result)  # str 타입을 dictionary 타입으로 바꿈
        if result.get('success'):
            user = result["success"].get("user")
            domain_id = user["domain"].get("id")
            if not roles:
                roles = result["success"].get("roles")
            request.session["domain_id"] = domain_id
            token = result['success']['token']
            user_id = user.get("id")
            if keystone is None:
                keystone = KeystoneRestAPI(auth_url, token)
            keystone.update_token(token)

            roles_str = ','.join(role.get("name") for role in roles)

            ctrl_engine = ControlEngine(token=token,
                                        project_id=project_id,
                                        project_name=project_name,
                                        user_id=user_id,
                                        user_name=user_name,
                                        roles=roles_str,
                                        auth_url=auth_url)
            request.session["ctrl_header"] = ctrl_engine.get_header()
        # ================================================
        request.session["passToken"] = token
        request.session["user_name"] = user_name
        request.session["domain_name"] = domain_name
        request.session["project_name"] = project_name
        request.session["auth_url"] = auth_url
        if roles_str:
            request.session["roles"] = roles_str
        else:
            request.session["roles"] = None
        if user_id:
            request.session["user_id"] = user_id
        if project_id:
            request.session["project_id"] = project_id

    return result, data
Esempio n. 25
0
def get_alarm_list(request):
    """
    :param request:
    :return:  {
        u'alarm_actions': [
            u'http://192.168.10.25:8080/alarm'
        ],
        u'project_id': u'227c72fcda1241b59b1241548649700c',
        u'ok_actions': [],
        u'이름 name': u'InstanceStatusAlarm',
        u'생성일 - 9시간 timestamp': u'2017-07-20T04:17:29.392703',
        u'설명 description': u'An event alarm kkkk',
        u'time_constraints': [],
        u'enabled': True,
        u'state_timestamp': u'2017-07-20T04:17:29.392703',
        u'이름에 링크 주소 alarm_id': u'0f276622-a037-4b9d-b7af-3014b52352f2',
        u'state': u'ok',
        u'insufficient_data_actions': [u'http://192.168.10.25:8080/nodata'],
        u'repeat_actions': False,
        u'user_id': u'f266e9e2e0fe43dfb2f9492851d470cd',
        u'event_rule': {
            u'query': [
                {
                    u'field': u'traits.instance_id',
                    u'type': u'string',
                    u'value': u'9d3f7a1a-fd78-43d3-8294-5ae0789bf76e',
                    u'op': u'eq'
                }, {
                    u'field': u'traits.state',
                    u'type': u'string',
                    u'임계값1 value': u'error',
                    u'임계값2 op': u'eq'
                }
            ],
            u'타입1 event_type': u'compute.instance.update'
        },
        u'type': u'event',
        u'severity': u'moderate'
    }
    """
    domain_name = request.session.get("domain_name")
    description = request.session.get("description")
    token = request.session.get('passToken')
    project_id = request.session.get('project_id')
    auth_url = request.session.get("auth_url")
    ctrl_header = request.session.get("ctrl_header")
    control = ControlEngine(ctrl_header)
    aodh = AodhRestAPI(auth_url, token)
    query = {
        "query": [
            {
                "field": "project",
                "op": "eq",
                "value": project_id
            },
        ]
    }
    if request.method == 'GET':
        service_id = request.GET.get("service_id")
    else:
        service_id = request.POST.get("service_id")
    result_vms = control.get_service_vm(service_id)
    result_alarms = aodh.get_alarm_list(query)
    alarm_list = []
    if result_vms.get("success") and result_alarms.get("success"):
        for alarm in result_alarms["success"]:
            for vm in result_vms["success"].get("vm_list"):
                if vm.get("vm_id") in alarm["threshold_rule"]["query"][0]["value"] or "image" in alarm["threshold_rule"]["meter_name"]:
                    alarm_list.append(alarm)

    # try:
    #     pass
    #     for alarm in alarmList:
    #         queryList = alarm.event_rule.get("query")
    #         alarm.event_rule["target"] = filter(lambda x: x.get("field") in targetList, queryList)[0]  # TODO: 우선 instance만
    #         threshold = filter(lambda x: x.get("field") in meterNameList, queryList)[0]
    #         alarm.event_rule["target"]["meter_name"] = threshold.get("field")  # TODO: 전부 넣어야함 memory등등
    #         alarm.event_rule["target"]["op"] = threshold.get("op")
    #         alarm.event_rule["target"]["threshold"] = threshold.get("value")
    #         del alarm.event_rule["target"]["type"]
    #         del alarm.event_rule["query"]
    # except Unauthorized as e:
    #     request.session["error"] = {"title":e.message, "message":e.details}
    #     if request.method == 'POST':
    #         return JsonResponse({"error":{"title":e.message, "message":e.details}})
    #     else:
    #         request.session["error"] = {"title": e.message, "message": e.details, "code":401}
    #         return redirect("/dashboard/login/?auth_url=" + auth_url + "&domain_name=" + domain_name + "&description=" + description)
    if request.method == 'POST':
        return JsonResponse({"success": {'alarmList': alarm_list}})
    else:
        token = request.session.get('passToken')
        if not token:
            return redirect("/dashboard/domains/?next=/dashboard/telemeter/alarms")
        return render(request, 'telemeter/alarms/index.html', {"alarmList": alarm_list})
Esempio n. 26
0
def common_login(request,
                 auth_url,
                 user_name,
                 password,
                 domain_name,
                 project_name=None):
    available_projects = None
    token = None
    roles = None
    roles_str = None
    project = None
    user = None
    keystone = None
    domain_id = None
    # =================================UnScope Login==================================
    if not project_name:
        result = KeystoneRestAPI.get_token(auth_url, user_name, password,
                                           domain_name)
        if result.get("success"):
            # request.session.set_expiry(SESSION_COOKIE_AGE)
            token = result['success'].get('token')
            roles = result["success"].get("roles")
            user = result["success"].get("user")
            if user:
                user_name = user.get("name")
            keystone = KeystoneRestAPI(auth_url, token)
            available_projects = keystone.get_available_project_scopes()
            # =================================Default 프로젝트==================================
            if result["success"].get("project"):
                project = result["success"].get("project")
            # =================================접근 가능 프로젝트==================================
            if not project and available_projects.get("success"):
                if not available_projects["success"].get("projects"):
                    return {
                        "error": {
                            "title": "Forbidden",
                            "message": "모든 프로젝트에 접근 권한이 없습니다."
                        }
                    }
                else:
                    project = available_projects["success"].get("projects")[0]
            if project:
                project_name = project.get("name")

    # =================================Scope Login==================================
    result = KeystoneRestAPI.get_token(auth_url, user_name, password,
                                       domain_name, project_name)
    # logger.info("""################## Scope Login ############
    # auth_url: {}
    # user_name: {}
    # password: {}
    # domain_name: {}
    # project_name: {}
    # result: {}""".format(auth_url, user_name, password, domain_name, project_name, result))
    if result.get('success'):
        request.session["domain_admin"] = False
        # request.session.set_expiry(SESSION_COOKIE_AGE)
        token = result['success'].get('token')
        user = result["success"].get("user")
        domain_id = user["domain"].get("id")
        roles = result["success"].get("roles")
        project = result["success"].get("project")
        request.session["project_id"] = project.get("id")
        request.session["project_name"] = project.get("name")
        if not keystone:
            keystone = KeystoneRestAPI(auth_url, token)
        keystone.update_token(token)
        if not available_projects:
            available_projects = keystone.get_available_project_scopes()
        request.session["available_projects"] = [{
            "name":
            available_project.get("name"),
            "id":
            available_project.get("id")
        } for available_project in available_projects["success"].get(
            "projects")]
        if roles:
            roles_str = ','.join(role.get("name") for role in roles)
        elif user.get("name") == 'admin':
            roles_str = user.get("name")

        ctrl_engine = ControlEngine(token=token,
                                    project_id=project.get("id"),
                                    project_name=project.get("name"),
                                    user_id=user.get("id"),
                                    user_name=user_name,
                                    roles=roles_str,
                                    auth_url=auth_url)
        request.session["ctrl_header"] = ctrl_engine.get_header()
        # ================================================
        request.session["passToken"] = token
        request.session["user_name"] = user_name
        request.session["domain_name"] = domain_name
        request.session["auth_url"] = auth_url
        request.session["domain_id"] = domain_id
        request.session["roles"] = roles_str
        if user:
            request.session["user_id"] = user.get("id")
        else:
            request.session["user_id"] = None
        if not project:
            request.session["project_id"] = None
            request.session["project_name"] = None

    return result
Esempio n. 27
0
def getServerListInService(request, service_id):
    """
    해당 서비스의 서버 리스트
    :param request:
    :param service_id:
    :return:
    """
    control = ControlEngine(request.session.get("ctrl_header"))
    # control = ControllerEngine()  # TODO: debugging 용
    vm_list = control.get_service_vm(service_id)
    if vm_list.get("success"):

        auth_url = request.session.get("auth_url")
        token = request.session.get("passToken")
        stack_id = vm_list.get("success").get("stack_id")
        # stack_name = vm_list.get("success").get("service_detail").get("name")

        nova = NovaRestAPI(auth_url, token)
        result_servers = nova.get_server_detail_list(
            fields=["id", "name", "metadata"])
        if result_servers.get("success"):
            servers = [
                result_server
                for result_server in result_servers["success"].get("servers")
                if result_server.get("metadata")
                and result_server["metadata"].get("metering.stack") == stack_id
            ]
            for temp_server in servers:
                server = {
                    "vm_name": temp_server.get("name"),
                    "vm_id": temp_server.get("id"),
                    "addresses": [],
                }
                for network_name, network in temp_server.get(
                        "addresses").items():
                    for address in network:
                        server["addresses"].append(address.get("addr"))
                vm_list["success"]["vm_list"].append(server)
        else:
            vm_list = result_servers

        # heat = HeatRestAPI(auth_url, token)
        # result = heat.get_resource_in_stack(stack_name, stack_id, {"type": "OS::Heat::AutoScalingGroup"})
        # if result.get("success"):
        #     as_groups = result["success"].get("resources")
        #     nova = NovaRestAPI(auth_url, token)
        #     for as_group in as_groups:
        #         asg_stack_id = as_group.get("physical_resource_id")
        #         result = heat.find_server_in_autoscaling(asg_stack_id)
        #         if result.get("success"):
        #             asg_stack_resources = result["success"]["resources"]
        #             for asg_stack_resource in asg_stack_resources:
        #                 server_name = "." + asg_stack_resource.get("logical_resource_id") + "."
        #                 result_servers = nova.get_server_detail_list({"name": server_name})
        #                 if result_servers.get("success"):
        #                     servers = result_servers["success"].get("servers")
        #                     for temp_server in servers:
        #                         server = {
        #                             "vm_name": temp_server.get("name"),
        #                             "vm_id": temp_server.get("id"),
        #                             "addresses": [],
        #                         }
        #                         for network_name, network in temp_server.get("addresses").items():
        #                             for address in network:
        #                                 server["addresses"].append(address.get("addr"))
        #                         vm_list["success"]["vm_list"].append(server)

    return JsonResponse(vm_list, safe=False)
Esempio n. 28
0
def synchronize_soam(request, service_info, data_dic):
    # 관리포탈 동기화용
    conn = SOAControlDBConnector.getInstance()

    user_name = request.session.get("user_name")
    # 도메인명, 프로젝트 아이디, 서비스 아이디, 서비스명, 서비스 상태,
    # 동기화 상태{동기화전 I, 동기화중 S, 동기화완료 C, 동기화실패 F}, 동기화 날짜
    auth_url = request.session.get("auth_url")
    project_id = request.session.get("project_id")
    params = (auth_url, project_id, service_info.get("service_id"),
              service_info.get("name"), service_info.get("status"), user_name,
              user_name)

    logger.debug("[soac db insert service for sync]")
    # conn.insert(INSERT_SOAC_SERVICE, params)  # sync를 위해 soacDB에 넣기

    control = ControlEngine(request.session.get("ctrl_header"))
    s_result = control.get_service(service_info.get("service_id"))
    if s_result.get("success"):
        # used_security_group_list 상세정보 조회, security_group_list 생성
        select_security_groups = conn.select(
            SELECT_SECURITY_RESOURCE_GROUP_LIST)

        security_groups = data_dic.get("used_security_group_list")
        security_group_list = []
        for security_group in security_groups:
            for select_security_group in select_security_groups:
                if select_security_group.get(
                        "security_id") == security_group.get("security_id"):
                    select_security_group[
                        "security_type"] = security_group.get("security_type")
                    security_group_list.append(select_security_group)

        m_conn = SOAManagerDBConnector.getInstance()
        # security_group
        # TODO: seccurity_type => 관리포탈에서 코드조회후 코드로 넣을것
        # TODO: manufacture_icon
        # TODO: 보안장비가 이미 등록되 있을시 무시
        for security_group in security_group_list:
            params = (security_group.get("security_type"),
                      security_group.get("security_name"),
                      security_group.get("security_icon"),
                      security_group.get("manufacture_name"),
                      security_group.get("manufacture_icon"),
                      security_group.get("software_version"),
                      security_group.get("description"))

            logger.debug("[soam db insert equipment]")
            m_conn.insert(INSERT_SOAM_EQUIPMENT, params)

        params = (auth_url, project_id, service_info.get("service_id"),
                  service_info.get("name"),
                  service_info.get("service_description"))
        logger.debug("[soam db insert service]")
        m_conn.insert_service(params, data_dic)

        scheduler = Scheduler()

        def check_service_status():
            logger.debug("[check service status]")
            create_status = False
            # 서비스 상태 확인
            result = control.get_service(service_info.get("service_id"))
            if result.get("success"):
                try:
                    service_template = result["success"].get("service_detail")

                    # 생성중이면 1분뒤 다시 확인
                    if service_template.get("status") == "CREATE_IN_PROGRESS":
                        logger.debug("[wait CREATE_IN_PROGRESS]")
                        return
                    # 생성 완료면 자원 데이터 저장
                    elif service_template.get("status") == "CREATE_COMPLETE":
                        logger.debug("[soam db insert resources]")
                        params = (auth_url, project_id,
                                  service_info.get("service_id"),
                                  service_info.get("name"),
                                  service_info.get("service_description"))
                        m_conn.insert_service_resource(params,
                                                       service_template,
                                                       request)

                    # 생성 실패면
                    else:
                        pass

                    # 생성 완료 or 실패 시 soac db 수정
                    logger.debug("[soac db update service for sync complete]")
                    # params = (service_template.get("name"), service_template.get("status"), "C", user_name, auth_url,
                    #           request.session.get("project_name"), service_info.get("service_id"))
                    # conn.update(UPDATE_SOAC_SERVICE, params)
                    scheduler.kill_scheduler("check_service")
                except Exception as e:
                    error_str = """
                    Title: {}
                    Traceback: {}
                    """.format(e.message,
                               traceback.format_exc().strip())
                    logger.error(error_str)
                    scheduler.kill_scheduler("check_service")
            else:
                scheduler.kill_scheduler("check_service")

        logger.debug("[wait CREATE_IN_PROGRESS]")
        scheduler.schedule_interval(check_service_status,
                                    "check_service",
                                    seconds=30)
Esempio n. 29
0
def detail_service(request, service_id):
    """
    서비스 상세조회
    :param request:
    :param service_id:
    :return:
    """
    token = request.session.get("passToken")
    auth_url = request.session.get("auth_url")
    if request.method == 'POST':
        logger.info("detailServicePOST")
        control = ControlEngine(request.session.get("ctrl_header"))
        # control = ControllerEngine()  # TODO: debugging 용
        service_detail, map_data = control.get_service_detail_and_link_list(
            service_id)

        public_network = []
        logger.info("detailServicePOST_end_public_network")
        try:
            neutron = NeutronRestAPI(auth_url, token)
            result = neutron.get_network_list({"router:external": True})
        except Exception as e:
            logger.warning("get public_network fail" + str(e))
            return JsonResponse(service_detail)
        else:
            if result.get("success"):
                public_network = filter(
                    lambda network: network["router:external"],
                    result["success"]["networks"])
        if service_detail.get("success"):
            # print service_detail["success"], map_data, public_network
            jsonDic = {
                "success": service_detail["success"],
                "links": {},
                "security_types": {},
                "public_network": public_network
            }

            template = control.get_template(service_id)
            if template.get("success"):
                user_template = template["success"].get("user_template")
                if user_template:
                    # print "user_template: {}\nservice_id: {}".format(user_template, service_id)
                    user_template["service_id"] = service_id
                    jsonDic["success"]["template"] = user_template
            else:
                jsonDic.get("success").get("service_detail").get(
                    "error_msg_list").push(template.get("error"))
            if map_data.get("success"):
                map_link_list = map_data["success"].get("map_link_list")
                if map_link_list:
                    jsonDic["links"] = map_link_list.get("links")
                    jsonDic["asLinks"] = map_link_list.get("asLinks")
                    jsonDic["security_types"] = map_link_list.get(
                        "security_types")
                    jsonDic["used_security_group_list"] = map_link_list.get(
                        "used_security_group_list")
            # request.session["service_dic"] = jsonDic
            return JsonResponse(jsonDic)
        else:
            return JsonResponse(service_detail)
    else:
        token = request.session.get('passToken')
        if not token:
            return redirect("/dashboard/domains/?next=/dashboard/service/" +
                            service_id + "/detail")
        logger.info("detailService_end")
        response = render(request, 'service/info.html', {})
        return response
Esempio n. 30
0
def modifyService(request, service_id):
    """
    서비스 수정 페이지
    :param request:
    :param service_id:
    :return:
    """
    if request.method == 'POST':
        logger.info("detailServicePOST")
        control = ControlEngine(request.session.get("ctrl_header"))
        token = request.session.get("passToken")
        auth_url = request.session.get("auth_url")

        template = control.get_template(service_id)
        if template.get("success"):
            user_template = template["success"].get("user_template")
            user_template["service_id"] = service_id
            service_detail = {"success": {"service_detail": user_template}}
        else:
            service_detail = template
        map_data = control.get_map(service_id)

        public_network = []
        logger.info("detailServicePOST_end_public_network")
        try:
            neutron = NeutronRestAPI(auth_url, token)
            result = neutron.get_network_list()
        except:
            logger.warning("get public_network fail")
            return JsonResponse(service_detail)
        else:
            if result.get("success"):
                public_network = filter(
                    lambda network: network["router:external"],
                    result["success"]["networks"])

        if service_detail.get("success"):
            json_dic = {
                "success": service_detail["success"],
                "public_network": public_network
            }
            if map_data["success"].get("map_link_list"):
                links = map_data["success"]["map_link_list"].get("links")
                as_links = map_data["success"]["map_link_list"].get("asLinks")
                resources = map_data["success"]["map_link_list"].get(
                    "resources")
                security_types = map_data["success"]["map_link_list"].get(
                    "security_types")
                json_dic.update({
                    "links": links,
                    "asLinks": as_links,
                    "resources": resources,
                    "security_types": security_types
                })

            return JsonResponse(json_dic)
        else:
            return JsonResponse(service_detail)
    else:
        token = request.session.get('passToken')
        if not token:
            return redirect("/dashboard/domains/?next=/dashboard/service/" +
                            service_id + "/detail")
        logger.info("detailService_end")
        response = render(request, 'service/info.html', {})
        return response