Example #1
0
def get_router_list(request):
    # logger.info("get_router_list")
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    if request.method == 'POST':
        try:
            keystone = KeystoneRestAPI(auth_url, token)
            result_projects = keystone.get_project_list()
            projects = []
            if result_projects.get("success"):
                projects = result_projects["success"].get("projects")

            neutron = NeutronRestAPI(auth_url, token)
            result = neutron.getRouterList()
            if result.get("success"):
                for router in result["success"].get("routers"):
                    if router.get("tenant_id"):
                        for project in projects:
                            if project.get("id") == router.get("tenant_id"):
                                router["project_name"] = project.get("name")
        except Unauthorized as e:
            result = {
                "error": {
                    "title": e.message,
                    "message": e.details,
                    "code": 401
                }
            }
        return JsonResponse(result)
    else:
        token = request.session.get('passToken')
        if not token:
            return redirect(
                "/dashboard/domains/?next=/dashboard/admin/routers")
        return render(request, 'admin/routers/index.html', {})
Example #2
0
def sync_modal(request, network_id):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    neutron = NeutronRestAPI(auth_url, token)
    result = neutron.get_network(network_id)
    return render(request, 'admin/sync_modal.html',
                  {'data': result["success"]["network"]})
Example #3
0
def retrieve_agent_list(request):
    if request.is_ajax() and request.method == 'POST':

        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        neutron = NeutronRestAPI(auth_url, token)
        agent_list = neutron.getAgentList().get("success").get("agents")
        return JsonResponse({"success": {'agentList': agent_list}})
Example #4
0
def get_interface_list_in_router(request, router_id):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    if request.method == 'POST':
        neutron = NeutronRestAPI(auth_url, token)
        ports = neutron.get_port_list({
            "device_id": router_id
        }).get("success").get("ports")
        # interfaceList = get_interface_list_in_router(router_id)
        return JsonResponse({"success": {'interface': ports}})
Example #5
0
def sync_modal(request, router_id):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    neutron = NeutronRestAPI(auth_url, token)
    result = neutron.getRouter(router_id)
    interfaces = neutron.get_port_list({"device_id": router_id})
    if interfaces.get("success") and result.get("success"):
        result["success"]["router"]["interfaces"] = interfaces.get(
            "success").get("ports")
    return render(request, 'admin/sync_modal.html',
                  {'data': result["success"]["router"]})
Example #6
0
def ports_modal(request):
    auth_url = request.session.get("auth_url")
    token = request.session.get("passToken")
    port_id = request.GET.get("port_id")
    data = {"modal_title": request.GET.get("modal_title")}
    if port_id:
        neutron = NeutronRestAPI(auth_url, token)
        result = neutron.getPort(port_id)
        if result.get("success"):
            data["port"] = result["success"].get("port")

    return render(request, 'admin/networks/ports/modal.html', data)
Example #7
0
def create_modal(request):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    modal_title = request.GET.get("modal_title")
    instance_id = request.GET.get("instance_id")
    data = {
        "modal_title": modal_title,
    }
    nova = NovaRestAPI(auth_url, token)
    neutron = NeutronRestAPI(auth_url, token)
    glance = GlanceRestAPI(auth_url, token)

    availability_zone = nova.get_availability_zone()
    if availability_zone.get("success"):
        data["availabilityZoneInfo"] = availability_zone["success"].get("availabilityZoneInfo")

    images = glance.get_image_list()
    if images.get("success"):
        data["images"] = images["success"].get("images")

    flavors = nova.get_flavor_detail_list()
    if flavors.get("success"):
        data["flavors"] = flavors["success"].get("flavors")

    networks = neutron.get_network_list()
    if networks.get("success"):
        data["networks"] = networks["success"].get("networks")
        subnets = neutron.get_subnet_list()
        if subnets.get("success"):  # network["subnets"]에 id만 있어 해당 아이디의 subnet을 찾아 name으로 대체
            subnet_list = subnets["success"].get("subnets")
            for network in data["networks"]:
                network["subnets"] = [
                    subnet.get("name")
                    for subnet_id in network["subnets"]
                    for subnet in subnet_list
                    if subnet.get("id") == subnet_id
                ]

    ports = neutron.get_port_list()
    if ports.get("success"):
        data["ports"] = ports["success"].get("ports")

    if instance_id:  # 수정 시
        data["instance_id"] = instance_id
        result = nova.get_server(instance_id)
        if result.get("success"):
            server = result["success"].get("server")
            data["server"] = server

    return render(request, 'admin/instances/modal.html', data)
Example #8
0
def get_network_list(request):
    # logger.info("get_network_list")
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    if request.method == "GET":
        if not token:
            return redirect(
                "/dashboard/domains/?next=/dashboard/admin/networks")
    neutron = NeutronRestAPI(auth_url, token)
    query = {}
    if request.method == "GET" and request.GET.get("project_id"):
        query["tenant_id"] = request.GET.get("project_id")
    elif request.method == "POST" and request.POST.get("project_id"):
        query["tenant_id"] = request.POST.get("project_id")
    result = neutron.get_network_list(q=query)

    if result.get("success"):
        keystone = KeystoneRestAPI(auth_url, token)
        projects = keystone.get_project_list(fields={"fields": ["id", "name"]})
        subnets = neutron.get_subnet_list(fields=["id", "name", "cidr"])
        for network in result["success"].get("networks"):
            # project id로 project_name 추가
            if projects.get("success"):
                for project in projects["success"].get("projects"):
                    if project.get("id") == network.get("tenant_id"):
                        network["project_name"] = project.get("name")
            # project id로 project_name 추가끝
            # subnet id로 subnetList 추가
            if subnets.get("success"):
                network["subnets"] = [
                    subnet for subnet_id in network.get("subnets")
                    for subnet in subnets["success"].get("subnets")
                    if subnet.get("id") == subnet_id
                ]
            # subnet id로 subnetList 추가끝
        result = result.get("success")
    if request.is_ajax():
        return JsonResponse(result)
    else:
        if request.method == "GET":
            try:
                soam_sync = bool(
                    config.get("SETTINGS", "PORTAL_SYNC") == "True")
            except Exception as e:
                soam_sync = False
            result["sync"] = soam_sync  # TODO: soam sync delete
            return render(request, 'admin/networks/index.html', result)
Example #9
0
def actionPort(request, port_id, action):
    token = request.session.get('passToken')
    domain_name = request.session.get("domain_name")
    project_name = request.session.get("project_name")
    auth_url = request.session.get("auth_url")

    if request.method == 'POST':
        try:
            neutron = NeutronRestAPI(auth_url, token)
            if action == "detail":
                result = neutron.getPort(port_id)

            elif action == "update":
                data = json.loads(request.POST.get("data"))
                result = neutron.updatePort(port_id, data)

            elif action == "delete":
                result = neutron.delete_port(port_id)

            else:
                result = {
                    "error": {
                        "title": "Not Found",
                        "message": "지원하지 않는 기능입니다.",
                        "code": 404
                    }
                }

        except Unauthorized as e:
            result = {
                "error": {
                    "title": e.message,
                    "message": e.details,
                    "code": 401
                }
            }
        return JsonResponse(result)
    else:
        if not token:
            return redirect(
                "/dashboard/domains/?next=/dashboard/admin/networks/ports/" +
                port_id)

        if action == "detail":
            return render(request, 'admin/networks/ports/info.html',
                          {'port_id': port_id})
Example #10
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', {})
Example #11
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
        })
Example #12
0
def create_subnet(request):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")

    if request.method == 'POST':
        data = json.loads(request.POST.get("data"))
        try:
            neutron = NeutronRestAPI(auth_url, token)
            result = neutron.createSubnet(data)
        except Unauthorized as e:
            result = {
                "error": {
                    "title": e.message,
                    "message": e.details,
                    "code": 401
                }
            }
        return JsonResponse(result)
Example #13
0
def get_subnet_list(request):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")

    if request.method == 'POST':
        try:
            neutron = NeutronRestAPI(auth_url, token)
            fields = ["name", "id"]
            result = neutron.get_subnet_list(fields=fields)
        except Unauthorized as e:
            result = {
                "error": {
                    "title": e.message,
                    "message": e.details,
                    "code": 401
                }
            }
        return JsonResponse(result)
Example #14
0
def delete_network(request, network_id):
    # logger.info("delete_network")
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")

    if request.method == 'POST':
        try:
            neutron = NeutronRestAPI(auth_url, token)
            result = neutron.deleteNetwork(network_id)
            return JsonResponse(result)
        except Unauthorized as e:
            result = {
                "error": {
                    "title": e.message,
                    "message": e.details,
                    "code": 401
                }
            }
        return JsonResponse(result)
Example #15
0
def get_metadata_for_create_router(request):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")

    if request.method == 'POST':
        try:
            neutron = NeutronRestAPI(auth_url, token)
            q = {"router:external": True}
            fields = ["id", "name"]
            result = neutron.get_network_list(q, fields)
        except Unauthorized as e:
            result = {
                "error": {
                    "title": e.message,
                    "message": e.details,
                    "code": 401
                }
            }
        return JsonResponse(result)
Example #16
0
def subnet_modal(request, subnet_id=None):
    data = {"modal_title": request.GET.get("modal_title")}
    auth_url = request.session.get("auth_url")
    token = request.session.get('passToken')

    if subnet_id:
        try:
            neutron = NeutronRestAPI(auth_url, token)
            result = neutron.get_subnet(subnet_id)
            if result.get("success"):
                subnet = result["success"].get("subnet")
                allocation_pools_str = ""
                for idx, allocation_pool in enumerate(
                        subnet.get("allocation_pools")):
                    if idx != 0:
                        allocation_pools_str += "\n"
                    allocation_pools_str += allocation_pool.get(
                        "start") + ", " + allocation_pool.get("end")
                subnet["allocation_pools"] = allocation_pools_str

                dns_nameservers_str = "\n".join(subnet.get("dns_nameservers"))
                subnet["dns_nameservers"] = dns_nameservers_str

                host_routes_str = ""
                for idx, host_route in enumerate(subnet.get("host_routes")):
                    if idx != 0:
                        host_routes_str += "\n"
                        host_routes_str += host_route.get(
                            "destination") + ", " + host_route.get("nexthop")
                subnet["host_routes"] = host_routes_str
                data["subnet"] = subnet
        except Unauthorized as e:
            return JsonResponse({
                "error": {
                    "title": e.message,
                    "message": e.details,
                    "code": 401
                }
            })

    return render(request, 'admin/networks/subnets/modal.html', data)
Example #17
0
def get_network(request, network_id):
    if request.method == 'GET' and request.is_ajax():
        # logger.info("get_network")
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")

        neutron = NeutronRestAPI(auth_url, token)
        result = neutron.get_network(network_id)
        if result.get("success"):
            network = result["success"].get("network")
            # subnet id로 subnetList 추가
            subnets = []
            for subnet_id in network.get("subnets"):
                subnet = neutron.get_subnet(subnet_id)
                if subnet.get("success"):
                    subnets.append(subnet.get("success").get("subnet"))
            network["subnets"] = subnets
            # subnet id로 subnetList 추가끝
            # network id로 portList 추가
            ports = neutron.get_port_list({"network_id": network.get("id")})
            if ports.get("success"):
                network["ports"] = ports.get("success").get("ports")
            # network id로 portList 추가끝
            dhcpAgents = neutron.getDHCPAgentHostingNetworkList(network_id)
            if dhcpAgents.get("success"):
                network["dhcpAgents"] = dhcpAgents.get("success").get("agents")
            return render(request, 'admin/networks/info.html',
                          {'network': network})
        return JsonResponse(result)
    else:
        return redirect("/dashboard/admin/networks?network_id=" + network_id)
Example #18
0
def new_service(request):
    """
    서비스 생성 페이지
    :param request:
    :return:
    """
    if request.is_ajax() and request.method == 'POST':
        logger.info("newServicePOST")
        token = request.session.get("passToken")
        auth_url = request.session.get("auth_url")

        logger.info("newServicePOST_end_getpublic_network")
        neutron = NeutronRestAPI(auth_url, token)
        result = neutron.get_network_list()
        if result.get("success"):
            public_network = filter(lambda network: network["router:external"],
                                    result["success"]["networks"])
            return JsonResponse({
                'success': {
                    "service_detail": {}
                },
                "public_network": public_network
            })
        else:
            return JsonResponse(result)

    else:
        logger.info("newService_end")
        token = request.session.get('passToken')
        if not token:
            return redirect(
                "/dashboard/domains/?next=/dashboard/service/new_service")
        try:
            soam_sync = bool(config.get("SETTINGS", "PORTAL_SYNC") == "True")
        except Exception as e:
            soam_sync = False
        return render(request, 'service/info.html',
                      {"sync": soam_sync})  # TODO: soam sync delete
Example #19
0
def sync(request, router_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
    try:
        m_conn = SOAManagerDBConnector.getInstance()
        m_conn.insert_router(auth_url, neutron, service_id, router_id)
        result = True
    except Exception as e:
        from sdsec.settings import logger
        logger.debug(e.message)
        result = False
    return JsonResponse({"result": result})
Example #20
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})
Example #21
0
def action_router(request, router_id, action):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")

    if request.method == 'POST':
        try:
            neutron = NeutronRestAPI(auth_url, token)
            if action == "detail":
                result = neutron.getRouter(router_id)
                interfaces = neutron.get_port_list({"device_id": router_id})
                if interfaces.get("success") and result.get("success"):
                    result["success"]["router"]["interfaces"] = interfaces.get(
                        "success").get("ports")

            elif action == "update":
                data = json.loads(request.POST.get("data"))
                result = neutron.updateRouter(router_id, data)

            elif action == "delete":
                result = neutron.deleteRouter(router_id)

            else:
                result = {
                    "error": {
                        "title": "Not Found",
                        "message": "지원하지 않는 기능입니다.",
                        "code": 404
                    }
                }

        except Unauthorized as e:
            result = {
                "error": {
                    "title": e.message,
                    "message": e.details,
                    "code": 401
                }
            }
        return JsonResponse(result)
    else:
        if not token:
            return redirect(
                "/dashboard/domains/?next=/dashboard/admin/routers/" +
                router_id + "/detail")

        if action == "detail":
            return render(request, 'admin/routers/info.html',
                          {'router_id': router_id})
Example #22
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"))
Example #23
0
def project_modal(request):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    modal_title = request.GET.get("modal_title")
    project_id = request.GET.get("project_id")
    domain_id = request.session.get("domain_id")
    domain_name = request.session.get("domain_name")
    data = {
        "modal_title": modal_title,
        "input_domain_id": domain_id,
        "input_domain_name": domain_name,
        "project_id": project_id
    }

    keystone = KeystoneRestAPI(auth_url, token)

    u_result = keystone.get_user_list({"domain_id": domain_id})
    if u_result.get("success"):
        data["users"] = u_result["success"].get("users")

    g_result = keystone.get_group_list()
    if g_result.get("success"):
        data["groups"] = g_result["success"].get("groups")

    r_result = keystone.get_role_list()
    if r_result.get("success"):
        data["roles"] = r_result["success"].get("roles")

    if project_id:
        p_result = keystone.get_project(project_id)
        if p_result.get("success"):
            project = p_result["success"].get("project")
            data["project_name"] = project.get("name")
            data["description"] = project.get("description")
            data["enabled"] = project.get("enabled")
        ra_result = keystone.get_role_assignments(
            {"scope.project.id": project_id})
        if ra_result.get("success"):
            role_assignments = ra_result["success"].get("role_assignments")
            response_role_assignments = {"users": [], "groups": []}
            for role_assignment in role_assignments:  # role_assignment_role 루프
                role_assignment_user = role_assignment.get("user")
                if role_assignment_user:
                    select_user = filter(
                        lambda user: user.get("id") == role_assignment_user.
                        get("id"), data["users"])
                    if select_user:
                        role_assignment_user["name"] = select_user[0].get(
                            "name")
                        data["users"][data["users"].index(
                            select_user[0])]["assigned"] = True

                role_assignment_group = role_assignment.get("group")
                if role_assignment_group:
                    select_group = filter(
                        lambda group: group.get("id") == role_assignment_group.
                        get("id"), data["groups"])
                    if select_group:
                        role_assignment_group["name"] = select_group[0].get(
                            "name")
                        data["groups"][data["groups"].index(
                            select_group[0])]["assigned"] = True

                role_assignment_role = role_assignment.get("role")
                if role_assignment_role:
                    select_role = filter(
                        lambda role: role.get("id") == role_assignment_role.
                        get("id"), data["roles"])
                    if select_role:
                        role_assignment_role["name"] = select_role[0].get(
                            "name")

                if role_assignment_role:
                    if role_assignment_user:
                        select_user = [
                            user for user in response_role_assignments["users"]
                            if user.get("id") == role_assignment_user.get("id")
                        ]  # 이미 있는지 확인
                        if len(select_user) == 0:  # 없으면 만들기
                            response_role_assignments["users"].append({
                                "name":
                                role_assignment_user.get("name"),
                                "id":
                                role_assignment_user.get("id"),
                                "roles": [role_assignment_role],
                                "roles_display":
                                role_assignment_role.get("name")
                            })
                        elif len(select_user) == 1:  # 있으면 role 추가
                            select_user[0]["roles"].append(
                                role_assignment_role)
                            select_user[0][
                                "roles_display"] += ", " + role_assignment_role.get(
                                    "name")

                    if role_assignment_group:
                        select_group = [
                            group
                            for group in response_role_assignments["groups"] if
                            group.get("id") == role_assignment_group.get("id")
                        ]  # 이미 있는지 확인
                        if len(select_group) == 0:  # 없으면 만들기
                            response_role_assignments["groups"].append({
                                "name":
                                role_assignment_group.get("name"),
                                "id":
                                role_assignment_group.get("id"),
                                "roles": [role_assignment_role],
                                "roles_display":
                                role_assignment_role.get("name")
                            })
                        elif len(select_group) == 1:  # 있으면 role 추가
                            select_group[0]["roles"].append(
                                role_assignment_role)
                            select_group[0][
                                "roles_display"] += ", " + role_assignment_role.get(
                                    "name")

            data["role_assignments"] = response_role_assignments
            data["role_assignments_json"] = json.dumps(
                response_role_assignments)

        nova = NovaRestAPI(auth_url, token)
        cinder = CinderRestAPI(auth_url, token)
        neutron = NeutronRestAPI(auth_url, token)
        result_nova_quota_set = nova.get_quotas(project_id)
        result_neutron_quotas = neutron.get_quotas(project_id)
        result_cinder_quotas = cinder.get_cinder_quotas(project_id)
        # result_cinder_limits = cinder.get_limits(project_id)
        if result_nova_quota_set.get("success"):
            nova_quota_set = result_nova_quota_set["success"].get("quota_set")
            data["nova_quota_set"] = nova_quota_set
        if result_neutron_quotas.get("success"):
            neutron_quotas = result_neutron_quotas["success"].get("quota")
            data["neutron_quotas"] = neutron_quotas
        # if result_cinder_limits.get("success"):
        #     cinder_limits = result_cinder_limits["success"]["limits"].get("absolute")
        #     data["cinder_limits"] = cinder_limits
        if result_cinder_quotas.get("success"):
            cinder_quotas = result_cinder_quotas["success"].get("quota_set")
            data["cinder_quotas"] = cinder_quotas

    return render(request, 'identity/projects/modal.html', data)
Example #24
0
def index(request):
    token = request.session.get("passToken")
    auth_url = request.session.get("auth_url")
    project_id = request.session.get("project_id")
    auth = ZabbixRestAPI.get_auth("Admin", "zabbix")
    zabbix = ZabbixRestAPI(auth)
    if request.method == "POST" and request.is_ajax():
        groupids = request.POST.get("groupids")
        groupname = request.POST.get("groupname")
        hostids = request.POST.get("hosts")
        if groupname or groupids:
            if "Template" in groupname:
                if groupname == "Templates":
                    result_hosts = zabbix.get_template(output="extend")
                else:
                    result_hosts = zabbix.get_template(output="extend", groupids=groupids)
            else:
                result_hosts = zabbix.get_hosts(output=["hostid", "host"], groupids=groupids)
        else:
            host_ping_list = []
            for hostid in json.loads(hostids):
                result_item = zabbix.get_item({"hostid": hostid, "name": "Agent ping"}, output=["lastvalue"])
                if result_item.get("result"):
                    host_ping_list.append({"hostid": hostid, "ping": result_item["result"][0].get("lastvalue")})
            result_hosts = {"host_ping_list": host_ping_list}
        return JsonResponse(result_hosts)
    else:
        """
         1. openstack - floating_ip 목록 조회
         2. zabbix - host 목록 조회
         floating_ip 목록 중 등록되지 않은 vm이 있으면 host 생성(floating_ip-port조회)
         3. openstack - vm조회
         4. zabbix - hostgroup조회
         5. zabbix - host 생성
         6. zabbix - hostinterface 조회
         7. zabbix - application 생성
         8. zabbix - item 생성
         9. zabbix - trigger 생성
        10. zabbix - mediatype 생성
        11. zabbix - action 생성
        12. zabbix - host 목록 조회
        13. zabbix - hostinterface 조회
        floating_ip 목록 중 등록되지 않은 vm이 없거나 생성 완료후
         1. host목록, hostinterface목록, vm목록 매칭
         2. host목록 반환
        
        """
        neutron = NeutronRestAPI(auth_url, token)
        # openstack의 floating_ip 목록 가져오기
        response_data = {"hosts": [], "vm_list": []}
        q = {"project_id": project_id}
        result_floating_ips = neutron.get_floating_ips(None, q)
        create_host_flag = False
        # host목록 가져오기
        result_hosts = zabbix.get_hosts(output=["hostid", "host", "status", "name"])
        if result_hosts.get("result") and result_floating_ips.get("success"):
            floating_ips = result_floating_ips["success"].get("floatingips")  # 중요1
            hosts = result_hosts.get("result")
            # floating_ips 목록이 Zabbix에 전부 등록되있는지 확인
            # TODO: javascript에서 서버 상태(ICMP Ping)를 실시간으로 변경
            recovery_list = []  # 중요3
            for floating_ip in floating_ips:
                if floating_ip.get("port_id"):
                    # floatingip - port 조회
                    result_port = neutron.getPort(floating_ip["port_id"])
                    if result_port.get("success"):
                        port = result_port["success"].get("port")
                        floating_ip["port_details"] = port
                        server_id = port.get("device_id")
                        host_names = [temp_host.get("host") for temp_host in hosts]
                        # 각 가상머신의 호스트가 등록되있지 않다면 등록
                        if server_id and "compute" in port.get("device_owner") and server_id not in host_names:
                            # floatingip - port - device(서버) 조회
                            recovery_info = {
                                "server": {
                                    "vm_id": server_id,
                                    "floating_ip_id": floating_ip.get("id"),
                                    "floating_ip_address": floating_ip.get("floating_ip_address")
                                },
                                "auth_url": auth_url,
                                "project_name": request.session.get("project_name")
                            }
                            recovery_list.append(recovery_info)

            # host의 interface 목록 가져오기
            result_host_interfaces = zabbix.get_host_interfaces(output=["hostid", "ip", "port"])
            if result_host_interfaces.get("result"):
                host_interfaces = result_host_interfaces["result"]
                for host in hosts:
                    for host_interface in host_interfaces:
                        # host와 interface 매칭
                        if host.get("hostid") == host_interface.get("hostid"):
                            host["interface"] = host_interface
                            # host중 interface의 ip가 127.0.0.1이거나 localhost인 경우
                            if "127.0.0.1" in host_interface.get("ip") or "localhost" in host_interface.get("ip"):
                                for floating_ip in floating_ips:
                                    #  floating_ip의 device_id와 host의 host(hostname)이 같을때만 리스트에 담아 보여주기
                                    if floating_ip.get("port_details"):
                                        result_item = zabbix.get_item({"hostid": host.get("hostid"), "name": "ICMP ping"})
                                        if result_item.get("result"):
                                            item = result_item["result"][0]
                                            if host.get("host") == floating_ip["port_details"]["device_id"]:
                                                host["floatingip_info"] = floating_ip
                                                host["ping"] = item.get("lastvalue")
                                                response_data["vm_list"].append(host)
                                                # logger.debug("\n\n\n\nfloating_ip: {}\nctrl_header: {}\n\n\n\n".format(floating_ip, request.session.get("ctrl_header")))
                                            else:
                                                check_recovered_vm_host(zabbix, host, item, floating_ip)
                            elif "admin" in request.session["roles"]:
                                result_item = zabbix.get_item({"hostid": host.get("hostid"), "name": "Agent ping"})
                                if result_item.get("result"):
                                    host["ping"] = result_item["result"][0].get("lastvalue")
                                response_data["hosts"].append(host)

            if len(recovery_list) > 0:
                response_data["synchronize_flag"] = False
            else:
                response_data["synchronize_flag"] = True

        else:
            response_data["error"] = {}
            if result_floating_ips.get("error"):
                response_data["error"]["openstack"] = result_floating_ips["error"]
            if not result_hosts.get("result"):
                response_data["error"]["zabbix"] = result_hosts
        return render(request, "monitoring/index.html", response_data)
Example #25
0
def new_service(request):
    if request.method == "GET":
        return render(request, "service/intent/new_service.html", {})
    elif request.is_ajax() and request.method == 'POST':
        logger.info("newIntentServicePOST")
        token = request.session.get("passToken")
        auth_url = request.session.get("auth_url")
        domain_name = request.session.get("domain_name")
        rule_key = request.POST.get("rule_key")

        neutron = NeutronRestAPI(auth_url, token)
        result = neutron.get_network_list()
        if result.get("success"):
            public_network = filter(lambda network: network["router:external"],
                                    result["success"]["networks"])

            conn = SOAControlDBConnector.getInstance()
            # rule
            params = (domain_name, rule_key)
            rule = conn.select_one(SELECT_FW_RULE, params)
            # source target
            params = (domain_name, rule.get("source_target"))
            src = conn.select_one(SELECT_ENDPOINT, params)
            # destination target
            params = (domain_name, rule.get("destination_target"))
            dest = conn.select_one(SELECT_ENDPOINT, params)

            json_param = {
                "ietf-i2nsf-cfi-policy:policy": {
                    "policy-name":
                    rule.get("policy_name"),
                    "rule": [{
                        "rule-name": "rule_name",
                        "condition": {
                            "firewall-condition": {
                                "source-target": {
                                    "src-target": src.get("name")
                                }
                            },
                            "custom-condition": {
                                "destination-target": {
                                    "dest-target": dest.get("name")
                                }
                            }
                        },
                        "action": {
                            "primary-action": rule.get("action_data")
                        }
                    }]
                }
            }

            if rule.get("start_time") and rule.get("end_time"):
                json_param["ietf-i2nsf-cfi-policy:policy"]["rule"][0][
                    "event"] = {
                        "time-information": {
                            "begin-time": rule.get("start_time"),
                            "end-time": rule.get("end_time")
                        }
                    }

            # sec_ctrl = SecurityControllerRestAPI()
            # result = sec_ctrl.get_service_template_by_rule(json_param)  # {"nsf_names": ["time_based_firewall", "url_filtering"]}
            # result = {"nsf_names": ["url_filtering"]}
            # result = {"nsf_names": ["time_based_firewall", "url_filtering"]}
            nsf_names = result.get("nsf_names")
            service_template = conn.select_service_template_by_nsf_names(
                nsf_names)
            logger.info("\n\n\n\nservice: {}\n\n\n".format(service_template))
            # params = (template_key, domain_name)
            # security_types = conn.select_one(SELECT_SECURITY_RESOURCE_GROUP_BY_TEMPLATE_KEY, params)
            link_json = json.loads(
                service_template.get("link_json").replace("\\", ""))
            links = link_json.get("links", [])
            as_links = link_json.get("asLinks", [])
            resources = link_json.get("resources", [])
            security_types = link_json.get("security_types", [])

            json_data = {
                'success': {
                    "service_detail":
                    json.loads(service_template.get("topology_json"))
                },
                "asLinks": as_links,
                "public_network": public_network,
                "service_template": service_template,
                "security_types": security_types,
                "links": links
            }

            return JsonResponse(json_data)
        else:
            return JsonResponse(result)
Example #26
0
def synchronize_floating_server_host(request):
    if request.method == 'POST' and request.is_ajax():
        token = request.session.get("passToken")
        auth_url = request.session.get("auth_url")
        project_id = request.session.get("project_id")
        auth = ZabbixRestAPI.get_auth("Admin", "zabbix")
        zabbix = ZabbixRestAPI(auth)
        neutron = NeutronRestAPI(auth_url, token)
        err_msg_list = []
        # openstack의 floating_ip 목록 가져오기
        q = {"project_id": project_id}
        result_floating_ips = neutron.get_floating_ips(None, q)
        create_host_flag = False
        # host목록 가져오기
        result_hosts = zabbix.get_hosts(output=["hostid", "host", "status", "name"])
        if result_hosts.get("result") and result_floating_ips.get("success"):
            floating_ips = result_floating_ips["success"].get("floatingips")  # 중요1
            hosts = result_hosts.get("result")
            # floating_ips 목록이 Zabbix에 전부 등록되있는지 확인
            # TODO: zabbix에 등록된 host중 floatingip연결을 해제시키거나 삭제된 server가 있으면 제거
            recovery_list = []  # 중요3
            for floating_ip in floating_ips:
                if floating_ip.get("port_id"):
                    # floatingip - port 조회
                    result_port = neutron.getPort(floating_ip["port_id"])
                    if result_port.get("success"):
                        port = result_port["success"].get("port")
                        floating_ip["port_details"] = port
                        server_id = port.get("device_id")
                        host_names = [temp_host.get("host") for temp_host in hosts]
                        # 각 가상머신의 호스트가 등록되있지 않다면 등록 중요3
                        if server_id and "compute" in port.get("device_owner") and server_id not in host_names:
                            # floatingip - port - device(서버) 조회
                            recovery_info = {
                                "server": {
                                    "vm_id": server_id,
                                    "floating_ip_id": floating_ip.get("id"),
                                    "floating_ip_address": floating_ip.get("floating_ip_address"),
                                    "fixed_ips": port.get("fixed_ips")
                                },
                                "auth_url": auth_url,
                                "project_name": request.session.get("project_name")
                            }
                            recovery_list.append(recovery_info)
                    if result_port.get("error"):
                        err_msg_list.append(result_port["error"])

            if len(recovery_list) > 0:
                # 서비스 리스트 조회 -> 서비스 조회 -> vm_list에서 같은아이디 있는지 확인
                ctrl_header = request.session.get("ctrl_header")
                control = ControlEngine(ctrl_header)
                result_service_list = control.get_service_list()
                if result_service_list.get("success"):
                    for service in result_service_list["success"].get("service_list"):
                        service_id = service.get("service_id")
                        result_service = control.get_service(service_id)
                        if result_service.get("success"):
                            for recovery_info in recovery_list:
                                for vm in result_service["success"]["service_detail"].get("vm_list"):
                                    # 서비스내에 해당 server가 있는지 확인
                                    if vm.get("vm_id") == recovery_info["server"].get("vm_id"):
                                        recovery_info["server"]["vm_name"] = vm.get("vm_name")
                                        recovery_info["server"]["service_id"] = service_id
                        if result_service.get("error"):
                            err_msg_list.append(result_service["error"])
                if result_service_list.get("error"):
                    err_msg_list.append(result_service_list["error"])
                            # service_list 조회끝
            for recovery_info in recovery_list:
                logger.debug("\n\n\n\n" + json.dumps(recovery_info) + "\n\n\n\n")
                # hostgroup 조회
                result_hostgroup = zabbix.get_hostgroups({"name": "Linux servers"}, ["groupid"])
                if result_hostgroup.get("result"):
                    hostgroup_id = result_hostgroup["result"][0].get("groupid")
                    result_create_host = create_host(request, zabbix, recovery_info, hostgroup_id)
                    if len(result_create_host) < 1:
                        create_host_flag = True
                    else:
                        err_msg_list.append(result_create_host)
                if not result_hostgroup.get("result"):
                    err_msg_list.append(result_hostgroup)

            # 호스트 생성시 호스트 목록 다시조회
            if create_host_flag:
                result_hosts = zabbix.get_hosts(output=["hostid", "host", "status", "name"])
                if result_hosts.get("result"):
                    hosts = result_hosts["result"]
        if not result_hosts.get("result"):
            err_msg_list.append(result_hosts)
        if result_floating_ips.get("error"):
            err_msg_list.append(result_floating_ips["error"])
        return JsonResponse({"success": {"err_msg_list": err_msg_list}})
Example #27
0
def recover_vm(recovery_server_info, ctrl_header, domain):
    """
    가상머신 장애 복구 process
    :param recovery_server_info:
    :param ctrl_header:
    :param domain:
    :return:
    """
    floating_ip_id = recovery_server_info.get("floating_ip_id")
    vm_id = recovery_server_info.get("vm_id")
    vm_name = recovery_server_info.get("vm_name")
    service_id = recovery_server_info.get("service_id")
    token = ctrl_header.get("X-Auth-Token")
    auth_url = ctrl_header.get("X-Host-Uri")
    project_name = ctrl_header.get("X-Tenant-Name")
    result = {}
    err_msg_list = []
    neutron = NeutronRestAPI(auth_url, token)
    nova = NovaRestAPI(auth_url, token)
    # floatingip 필요한 정보 추출, 삭제
    result_info_or_delete_floating_ip, floating_ip = get_floating_info_and_delete(neutron, floating_ip_id)
    # port 필요한 정보 추출, 삭제
    result_info_or_delete_port_list, port_list = get_port_list_and_delete(neutron, vm_id)
    # vm 삭제
    result_delete_server = nova.delete_server(vm_id)
    if result_info_or_delete_floating_ip:
        err_msg_list.append(result_info_or_delete_floating_ip)
    err_msg_list.extend(result_info_or_delete_port_list)
    if result_delete_server.get("error"):
        err_msg_list.append(result_delete_server["error"])

    # error 가 없으면
    if len(err_msg_list) < 1:
        control = ControlEngine(ctrl_header)
        result_template = control.get_template(service_id)
        result_map = control.get_map(service_id)

        if result_template.get("success") and result_map.get("success"):
            template = get_recovery_template(result_template["success"].get("user_template"), vm_name, port_list)
            map_data = get_recovery_map(result_map["success"], vm_name)

            result_update_map = control.update_map(service_id, map_data.replace('\\', ''))
            result_update_service = control.update_service(template, service_id)
            if result_update_service.get("success"):
                result_check = check_update_status(control, auth_url, domain, project_name, service_id)
                if result_check.get("success"):
                    vm_list = result_check["success"]["service_detail"]["vm_list"]
                    recovery_vm_name = vm_name
                    if "_recovery" in vm_name:
                        p = re.compile("_recovery\[(\d)\]")
                        m = p.search(vm_name)
                        if m:
                            recovery_cnt = m.group(1)
                            recovery_cnt = str(int(recovery_cnt) + 1)
                            recovery_vm_name = vm_name.replace("_recovery[" + m.group(1) + "]",
                                                               "_recovery[" + recovery_cnt + "]")
                    else:
                        recovery_vm_name = vm_name + "_recovery[1]"
                    vm_id = [vm.get("vm_id") for vm in vm_list if vm.get("vm_name") == recovery_vm_name][0]
                    neutron.update_token(result_check["success"]["ctrl_header"].get("X-Auth-Token"))
                    result_create_floting_ip = create_floating_ip_for_recovery(neutron, recovery_server_info, vm_id)
                    if result_create_floting_ip.get("error"):
                        err_msg_list.extend(result_create_floting_ip["error"].get("err_msg_list"))
                    else:
                        result["success"] = True
                else:
                    err_msg_list.append(result_check.get("error"))
            if result_update_service.get("error"):
                err_msg_list.append(result_update_service["error"])
            if result_update_map.get("error"):
                err_msg_list.append(result_update_map["error"])
        if result_template.get("error"):
            err_msg_list.append(result_template["error"])
        if result_map.get("error"):
            err_msg_list.append(result_map["error"])
    if len(err_msg_list) > 0:
        result["error"] = {"err_msg_list": err_msg_list}
    return result
Example #28
0
def update_project(request, project_id):
    if request.is_ajax() and request.method == 'POST':
        token = request.session.get('passToken')
        auth_url = request.session.get('auth_url')
        project = json.loads(request.POST.get("project"))
        quota = json.loads(request.POST.get("quotas"))
        data = {
            "project": {
                "description": project.get("description"),
                "domain_id": project.get("domain_id"),
                "name": project.get("name"),
                "enabled": project.get("enabled"),
                "is_domain": False,
            }
        }
        keystone = KeystoneRestAPI(auth_url, token)
        result = keystone.update_project(project_id, data)
        err_msg_list = []

        if result.get("success"):
            assign_list = json.loads(request.POST.get("assignList"))
            unassign_list = json.loads(request.POST.get("unassignList"))
            # 사용자 역할 할당
            for assign in assign_list.get("users"):
                user_id = assign.get("user_id")
                role_id_list = assign.get("role_id_list")
                for role_id in role_id_list:
                    assign_result = keystone.assign_role_to_user_on_projects(
                        project_id, user_id, role_id)
                    if assign_result.get("error"):
                        if not result.get("error"):
                            result["error"] = []
                        result["error"].append(assign_result["error"])
            # 사용자 역할 제거
            for unassign in unassign_list.get("users"):
                user_id = unassign.get("user_id")
                role_id_list = unassign.get("role_id_list")
                for role_id in role_id_list:
                    unassign_result = keystone.unassign_role_to_user_on_projects(
                        project_id, user_id, role_id)
                    if unassign_result.get("error"):
                        if not result.get("error"):
                            result["error"] = []
                        result["error"].append(unassign_result["error"])
            # 그룹 역할 할당
            for assign in assign_list.get("groups"):
                group_id = assign.get("group_id")
                role_id_list = assign.get("role_id_list")
                for role_id in role_id_list:
                    assign_result = keystone.assign_role_to_group_on_projects(
                        project_id, group_id, role_id)
                    if assign_result.get("error"):
                        if not result.get("error"):
                            result["error"] = []
                        result["error"].append(assign_result["error"])
            # 그룹 역할 제거
            for unassign in unassign_list.get("groups"):
                group_id = unassign.get("group_id")
                role_id_list = unassign.get("role_id_list")
                for role_id in role_id_list:
                    unassign_result = keystone.unassign_role_to_group_on_projects(
                        project_id, group_id, role_id)
                    if unassign_result.get("error"):
                        if not result.get("error"):
                            result["error"] = []
                        result["error"].append(unassign_result["error"])
            if quota["nova"].get("quota_set"):
                nova = NovaRestAPI(auth_url, token)
                result = nova.update_quotas(project_id, quota["nova"])
                if result.get("error"):
                    err_msg_list.append(result["error"])
            if quota["neutron"].get("quota"):
                neutron = NeutronRestAPI(auth_url, token)
                result = neutron.update_quotas(project_id, quota["neutron"])
                if result.get("error"):
                    err_msg_list.append(result["error"])
            if quota["cinder"].get("quota_set"):
                cinder = CinderRestAPI(auth_url, token)
                result = cinder.update_quotas(project_id, quota["cinder"])
                if result.get("error"):
                    err_msg_list.append(result["error"])

        return JsonResponse(result)
Example #29
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
Example #30
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