コード例 #1
0
def create_flavor(request):
    if request.method == "POST":
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        data = json.loads(request.POST.get("data"))
        try:
            nova = NovaRestAPI(auth_url, token)
            flavor = nova.create_flavor({"flavor": data.get("flavor")})
            if flavor.get("success"):
                if data.get("flavor_access"):
                    result = nova.add_flavor_access(
                        flavor.get("success").get("flavor").get("id"),
                        data["flavor_access"])
                    if result.get("error"):
                        flavor["error"] = {
                            "title": "flavor access Fail",
                            "message": "Flavor는 생성되었으나 access 설정에 실패하였습니다."
                        }
        except Unauthorized as e:
            request.session["error"] = {
                "title": e.message,
                "message": e.details
            }
            flavor = {"error": request.session.get("error")}
        return JsonResponse(flavor)
コード例 #2
0
def create_aggregate(request):
    if request.method == "POST":
        data = json.loads(request.POST.get("data"))
        add_hosts = json.loads(request.POST.get("add_hosts"))
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        nova = NovaRestAPI(auth_url, token)
        result = nova.create_aggregate(data)
        add_fail_list = []
        error_message = ""
        if result.get("success"):
            aggregate_id = result["success"]["aggregate"].get("id")
            for add_host_id in add_hosts:
                add_result = nova.add_host_to_aggregate(
                    aggregate_id, add_host_id)
                if add_result.get("error"):
                    add_fail_list.append(add_host_id)
                    error_message = add_result["error"].get("message")
                    if not error_message:
                        if add_result["error"].get("badRequest"):
                            error_message = add_result["error"][
                                "badRequest"].get("message")
                        elif add_result["error"].get("conflictingRequest"):
                            error_message = add_result["error"][
                                "conflictingRequest"].get("message")
            if len(add_fail_list) > 0:
                result["error"] = {
                    "message":
                    error_message + "<br/>add fail: " + str(add_fail_list),
                    "title":
                    "Add Host fail"
                }
        return JsonResponse(result)
コード例 #3
0
def flavor_modal(request):
    data = {}
    auth_url = request.session.get("auth_url")
    token = request.session.get("passToken")
    flavor_id = request.GET.get("flavor_id")
    domain_id = request.session.get("domain_id")

    keystone = KeystoneRestAPI(auth_url, token)

    projects = keystone.get_project_list({"domain_id": domain_id})
    if projects.get("success"):
        data["projects"] = projects["success"].get("projects")

    if flavor_id:
        nova = NovaRestAPI(auth_url, token)
        flavor = nova.get_flavor(flavor_id)
        if flavor.get("success"):
            data["flavor"] = flavor["success"].get("flavor")
            access_projects = nova.get_flavor_access(flavor_id)
            if access_projects.get("success"):
                data["access_projects"] = [
                    project for project in data["projects"] for flavor_access
                    in access_projects["success"].get("flavor_access")
                    if project.get("id") == flavor_access.get("tenant_id")
                ]
                for idx in data["access_projects"]:
                    data["projects"].remove(idx)

    return render(request, 'admin/flavors/modal.html', data)
コード例 #4
0
ファイル: views.py プロジェクト: jaehoonpaul/i2nsf-soa
def get_instance_by_id(request):
    token = request.session.get('passToken')
    domain_name = request.session.get("domain_name")
    project_name = request.session.get("project_name")
    description = request.session.get("description")
    auth_url = request.session.get("auth_url")
    vm_id = request.POST.get("vm_id")

    nova = NovaRestAPI(auth_url, token)
    glance = GlanceRestAPI(auth_url, token)
    keystone = KeystoneRestAPI(auth_url, token)

    instance = nova.get_server(vm_id)
    flavor = nova.get_flavor(
        instance.get("success").get("server").get("flavor")["id"])
    if instance.get("success").get("server").get("image"):
        image = glance.get_image(
            instance.get("success").get("server").get("image").get("id"))
    else:
        image = {"success": {}}

    instance["success"]["server"]["flavor"] = flavor.get("success").get(
        "flavor")
    instance["success"]["server"]["image"] = image.get("success")
    instance["success"]["server"]["project_name"] = keystone.get_project(
        instance.get("success").get("server").get("tenant_id")).get(
            "success").get("project").get("name")
    result = instance
    return JsonResponse(result)
コード例 #5
0
ファイル: views.py プロジェクト: jaehoonpaul/i2nsf-soa
def availabilityZone(request):
    """
    availabilityZone 얻기
    :param request:
    :return:
    """
    if request.is_ajax() and request.method == 'POST':
        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")
        auth_url = request.session.get("auth_url")
        try:
            nova = NovaRestAPI(auth_url, token)
            result = nova.get_availability_zone()
        except Unauthorized as e:
            result = {
                "error": {
                    "title": e.message,
                    "message": e.details,
                    "code": 401
                }
            }
        # print result
        # result["success"]["detail"] = control.getAvailabilityZoneDetail(token, domain_name, project_name, user_name)
        return JsonResponse(result)
コード例 #6
0
def action_server(request, server_id):
    if request.method == 'POST':
        token = request.session.get('passToken')
        domain_name = request.session.get("domain_name")
        data = json.loads(request.POST.get("data"))
        auth_url = request.session.get("auth_url")
        description = request.session.get("description")
        try:
            nova = NovaRestAPI(auth_url, token)
        except Unauthorized as e:
            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)
        result = nova.action_server(server_id, data)
        if type(result) == str:
            result = {"success": "reload"}
        elif result.get("success"):
            if result["success"].get("console"):
                console_url = result["success"]["console"].get("url")
                if "controller" in console_url:
                    console_url = console_url.replace("http://controller", auth_url.replace(":35357/v3", ""))
                    result["success"]["console"]["url"] = console_url
            else:
                result = {"success": "reload"}
        return JsonResponse(result)
コード例 #7
0
def delete_server(request, server_id):
    if request.method == 'POST':
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        nova = NovaRestAPI(auth_url, token)
        result = nova.delete_server(server_id)
        return JsonResponse(result)
コード例 #8
0
def getAggregateList(request):

    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    domain_name = request.session.get("domain_name")
    description = request.session.get("description")
    nova = NovaRestAPI(auth_url, token)
    if request.is_ajax() and request.method == 'POST':
        pass
    else:
        token = request.session.get('passToken')
        if not token:
            return redirect("/dashboard/login/?auth_url=" + auth_url +
                            "&domain_name=" + domain_name + "&description=" +
                            description + "&next=/dashboard/admin/aggregates")

        data = {}

        result_ag = nova.get_aggregate_list()
        if result_ag.get("success"):
            aggregates = result_ag["success"].get("aggregates")
            data["aggregates"] = aggregates
            if len(aggregates) < 4:
                data["ag_cnt"] = range(len(aggregates), 4)

        result_az = nova.get_availability_zone_detail()
        if result_az.get("success"):
            availability_zone_info = result_az["success"].get(
                "availabilityZoneInfo")
            data['availabilityZoneInfo'] = availability_zone_info
            if len(availability_zone_info) < 4:
                data["az_cnt"] = range(len(availability_zone_info), 4)

        return render(request, 'admin/aggregates/index.html', data)
コード例 #9
0
def update_flavor(request, flavor_id):
    if request.method == "POST":
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        data = json.loads(request.POST.get("data"))
        try:
            nova = NovaRestAPI(auth_url, token)
            flavor = nova.update_flavor(flavor_id,
                                        {"flavor": data.get("flavor")})
            if flavor.get("success"):
                if data.get("flavor_access"):
                    add_project = data["flavor_access"].get("add_project")
                    remove_project = data["flavor_access"].get(
                        "remove_project")
                    if add_project:
                        result = nova.add_flavor_access(flavor_id, add_project)
                        if result.get("error"):
                            flavor["error"] = result["error"]
                    if remove_project:
                        result = nova.remove_flavor_access(
                            flavor_id, remove_project)
                        if result.get("error"):
                            if flavor.get("error"):
                                flavor["error"]["message"] += result["error"][
                                    "message"]
                            else:
                                flavor["error"] = result["error"]
        except Unauthorized as e:
            request.session["error"] = {
                "title": e.message,
                "message": e.details
            }
            flavor = {"error": request.session.get("error")}
        return JsonResponse(flavor)
コード例 #10
0
ファイル: views.py プロジェクト: jaehoonpaul/i2nsf-soa
def alarms(request):
    """
    알람 수신
    :param request:
    :return:
    """
    if request.method == 'POST':
        logger.debug("[POST] alarm\n{}".format(request.body))
        data = json.loads(request.body)
        sendto = data.get("sendto")
        subject = data.get("subject")
        recovery_info = data.get("message")
        message = json.dumps(recovery_info)
        data = (
            subject,
            message,
            sendto
        )
        conn = SOAControlDBConnector()

        domain = conn.select_one(SELECT_DOMAINS_ONE_BY_AUTH_URL, recovery_info.get("auth_url"))
        db_user = domain.get("db_user")
        db_pass = domain.get("db_password")
        db_ip = domain.get("db_ip")
        db_port = domain.get("db_port")
        auth_url = domain.get("auth_url")
        d_conn = SOAControlDomainDBConnector(db_nm="soacgui", db_user=db_user, db_pass=db_pass, db_ip=db_ip, db_port=db_port)
        d_conn.insert(INSERT_ALARM, data)
        err_msg_list = []
        domain["os_admin_id"] = "admin"
        domain["os_admin_pass"] = "******"
        result_token = KeystoneRestAPI.get_token(auth_url, domain.get("os_admin_id"), domain.get("os_admin_pass"), domain.get("domain_name"), recovery_info.get("project_name"))
        if result_token.get("success"):
            if recovery_info.get("server"):
                nova = NovaRestAPI(auth_url, result_token["success"].get("token"))
                vm_id = recovery_info["server"].get("vm_id")
                result_is_exist_vm = nova.get_server(vm_id, ["id", "name"])
                if result_is_exist_vm.get("error") and result_is_exist_vm["error"].get("code") == 404:
                    message = "not Found vm(" + vm_id + ")"
                    data = (subject, message, sendto)
                    conn.insert(INSERT_ALARM, data)
                    return JsonResponse({"result": message})
                ctrl_header = get_ctrl_header_for_recorvery(auth_url, result_token["success"])
                result = recover_vm(recovery_info["server"], ctrl_header, domain)
                if result.get("success"):
                    recovery_info["recovery"] = True
                    conn.insert(INSERT_ALARM, (
                        subject, json.dumps(recovery_info), sendto
                    ))
                elif result.get("error"):
                    err_msg_list = result["error"]
        else:
            err_msg_list.append(result_token.get("error"))
        if len(err_msg_list) > 0:
            data = (
                subject, json.dumps(err_msg_list), sendto
            )
            d_conn.insert(INSERT_ALARM, data)
    return JsonResponse({"result": True})
コード例 #11
0
def update_server(request, server_id):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    nova = NovaRestAPI(auth_url, token)
    if request.method == 'POST':
        data = json.loads(request.POST.get("data"))
        result = nova.update_server(server_id, data)
        return JsonResponse(result)
コード例 #12
0
def update_aggregate(request, aggregate_id):
    if request.method == "POST":
        data = json.loads(request.POST.get("data"))
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        nova = NovaRestAPI(auth_url, token)
        result = nova.update_aggregate(aggregate_id, data)
        return JsonResponse(result)
コード例 #13
0
def delete_aggregate(request, aggregate_id):
    if request.method == "POST":
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        nova = NovaRestAPI(auth_url, token)
        result = nova.delete_aggregate(aggregate_id)
        if type(result) == str:
            result = {"success": True}
        return JsonResponse(result)
コード例 #14
0
def get_flavor_list(request):
    token = request.session.get('passToken')
    domain_name = request.session.get("domain_name")
    auth_url = request.session.get("auth_url")
    description = request.session.get("description")
    data = {}
    nova = NovaRestAPI(auth_url, token)
    flavors = nova.get_flavor_detail_list()
    if flavors.get("success"):
        data["flavors"] = flavors["success"].get("flavors")

    return render(request, 'admin/flavors/index.html', data)
コード例 #15
0
ファイル: views.py プロジェクト: jaehoonpaul/i2nsf-soa
def get_vm_in_asg(request):
    if request.is_ajax() and request.method == 'POST':
        auth_url = request.session.get("auth_url")
        token = request.session.get("passToken")
        stack_id = request.POST.get("stack_id")
        volume_search = request.POST.get("volume_search")
        # stack_name = request.POST.get("name")
        nova = NovaRestAPI(auth_url, token)
        cinder = CinderRestAPI(auth_url, token)
        result_servers = nova.get_server_detail_list(
            fields=["id", "name", "metadata"])
        result_volumes = {}
        if volume_search:
            result_volumes = cinder.get_volume_detail_list()
        result = {"success": {"servers": [], "volumes": []}}
        if result_servers.get("success"):
            for result_server in result_servers["success"].get("servers"):
                if result_server.get("metadata") and result_server[
                        "metadata"].get("metering.stack") == stack_id:
                    if volume_search and result_volumes.get("success"):
                        for result_volume in result_volumes["success"].get(
                                "volumes"):
                            for attachment in result_volume.get("attachments"):
                                if attachment.get("server_id"
                                                  ) == result_server.get("id"):
                                    volumes = [result_volume]
                                    result["success"]["volumes"].extend(
                                        volumes)
                    servers = [result_server]
                    result["success"]["servers"].extend(servers)
        else:
            result = 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")
        #     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"]
        #             result = {"success": {"servers": [], "error_msg_list": []}}
        #             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 server in servers:
        #                         server["asg_name"] = asg_stack_resource.get("logical_resource_id")
        #                     result["success"]["servers"].extend(servers)
        #                 else:
        #                     result["success"]["error_msg_list"].append(result_servers.get("error"))
        return JsonResponse(result)
コード例 #16
0
def get_hypervisors(request):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    data = {}
    nova = NovaRestAPI(auth_url, token)
    hypervisors = nova.get_hypervisor_detail_list()
    hosts = nova.get_compute_service({"binary": "nova-compute"})
    if hypervisors.get("success"):
        data["hypervisors"] = hypervisors["success"].get("hypervisors")
    if hosts.get("success"):
        data["services"] = hosts["success"].get("services")

    return render(request, 'admin/hypervisors/index.html', data)
コード例 #17
0
ファイル: views.py プロジェクト: jaehoonpaul/i2nsf-soa
def retrieve_nova_service_list(request):
    if request.is_ajax() and request.method == 'POST':

        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        nova = NovaRestAPI(auth_url, token)
        nova_service_list = nova.get_nova_service_list()
        return JsonResponse({
            "success": {
                'novaServiceList':
                nova_service_list.get("success").get("services")
            }
        })
コード例 #18
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)
コード例 #19
0
ファイル: views.py プロジェクト: jaehoonpaul/i2nsf-soa
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)
コード例 #20
0
def retrieveQuotaList(request):
    if request.is_ajax() and request.method == 'POST':
        # sess = login("admin", "chiron", "admin", "http://192.168.10.6/identity/v3", 'default')
        token = request.session.get('passToken')
        domain_name = request.session.get("domain_name")
        project_id = request.session.get("project_id")
        auth_url = request.session.get("auth_url")
        description = request.session.get("description")
        # sess = login(token, domain_name, project_name)
        try:
            nova = NovaRestAPI(auth_url, token)
        except Unauthorized as e:
            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)
        resultNovaQuotaList = nova.get_nova_default_quotas(project_id).get(
            "success").get("quota_set")
        quotaList = []

        for key in resultNovaQuotaList.keys():
            if key == "id" or key == "floating_ips" or key == "security_group_rules" or key == "fixed_ips" or key == "security_groups":
                continue
            quota = {"name": key, "limit": resultNovaQuotaList[key]}
            quotaList.append(quota)

        cinder = CinderRestAPI(auth_url, token)

        resultCinderQuotaList = cinder.get_cinder_quotas_defulat(
            project_id).get("success")
        if resultCinderQuotaList:
            for key in resultCinderQuotaList:
                if key == "id" or key == "floating_ips" or key == "security_group_rules" or key == "fixed_ips" or key == "security_groups":
                    continue
                quota = {"name": key, "limit": resultCinderQuotaList[key]}
                quotaList.append(quota)

        return JsonResponse({"success": {'quotaList': quotaList}})
    else:
        token = request.session.get('passToken')
        if not token:
            return redirect(
                "/dashboard/domains/?next=/dashboard/admin/defaults")
        return render(request, 'admin/defaults/index.html',
                      {'instanceList': ""})
コード例 #21
0
def delete_flavor(request, flavor_id):
    if request.method != "POST":
        return redirect("/dashboard/domains")
    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")
    try:
        nova = NovaRestAPI(auth_url, token)
        result = nova.delete_flavor(flavor_id)
        if not result:
            result = {"success": "deleted"}
    except Unauthorized as e:
        request.session["error"] = {"title": e.message, "message": e.details}
        result = {"error": request.session.get("error")}
    return JsonResponse(result)
コード例 #22
0
def action_aggregate(request, aggregate_id):
    if request.method == "POST":
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        add_hosts = json.loads(request.POST.get("add_hosts"))
        remove_hosts = json.loads(request.POST.get("remove_hosts"))
        nova = NovaRestAPI(auth_url, token)
        add_fail_list = []
        error_message = ""
        result = {}
        for add_host in add_hosts:
            result = nova.add_host_to_aggregate(aggregate_id, add_host)
            if result.get("error"):
                add_fail_list.append(add_host)
                error_message = result["error"].get("message")
                if not error_message:
                    if result["error"].get("badRequest"):
                        error_message = result["error"]["badRequest"].get(
                            "message")
                    elif result["error"].get("conflictingRequest"):
                        error_message = result["error"][
                            "conflictingRequest"].get("message")

        for remove_host in remove_hosts:
            result = nova.remove_host_to_aggregate(aggregate_id, remove_host)
            if result.get("error"):
                add_fail_list.append(remove_host)
                error_message = result["error"].get("message")
                if not error_message:
                    if result["error"].get("badRequest"):
                        error_message = result["error"]["badRequest"].get(
                            "message")
                    elif result["error"].get("conflictingRequest"):
                        error_message = result["error"][
                            "conflictingRequest"].get("message")
        if len(add_fail_list) > 0:
            result["error"] = {
                "message":
                error_message + "<br/>add fail: " + str(add_fail_list),
                "title": "Add Host fail"
            }
        if not result.get("error") and not result.get("success"):
            result = {"success": True}
        return JsonResponse(result)
コード例 #23
0
def aggregate_modal(request):
    modal_title = request.GET.get("modal_title")
    action = request.GET.get("action")
    aggregate_id = request.GET.get("id")
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    nova = NovaRestAPI(auth_url, token)
    result = nova.get_compute_service({"binary": "nova-compute"})
    result_data = {"modal_title": modal_title}
    if result.get("success"):
        result_data["services"] = result["success"].get("services")

    if aggregate_id:
        result = nova.get_aggregate(aggregate_id)
        if result.get("success"):
            result_data["aggregate"] = result["success"].get("aggregate")
            result_data["action"] = action

    return render(request, 'admin/aggregates/modal.html', result_data)
コード例 #24
0
def get_alarm_detail(request, alarm_id):
    token = request.session.get('passToken')
    domain_name = request.session.get("domain_name")
    auth_url = request.session.get("auth_url")
    description = request.session.get("description")
    aodh = AodhRestAPI(auth_url, token)

    try:
        alarm = aodh.get_alarm(alarm_id).get("success")
        resource_query = filter(lambda query: query["field"] == "resource_id" or query["field"] == "metadata.user_metadata.stack", alarm["threshold_rule"]["query"])
        if len(resource_query) > 0:
            resource_id = resource_query[0].get("value")
            server_result = NovaRestAPI(auth_url, token).get_server(resource_id)
            if server_result.get("success"):
                server = server_result["success"].get("server")
                alarm["threshold_rule"]["resource_name"] = server.get("name")
            else:
                alarm["threshold_rule"]["resource_name"] = resource_id
        # alarm["threshold_rule"]["query"][0]["name"] = NovaRestAPI(auth_url, token).get_server(
        #     alarm["threshold_rule"]["query"][0]["value"], {"fields": ["name"]})
        q = request.POST.get("q")
        if q:
            q = json.loads(q)
        aodh = AodhRestAPI(auth_url, token)
        histories = aodh.get_alarm_history(alarm_id, q)
        if histories.get("success"):
            histories = histories["success"]
        # TODO: user_name줘야함
    except Unauthorized as e:
        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": {'alarm': alarm, 'histories': histories}})
    else:
        token = request.session.get('passToken')
        if not token:
            return redirect("/dashboard/domains/?next=/dashboard/telemeter/alarms/" + alarm_id)
        modal_title = request.GET.get("modal_title")
        return render(request, 'telemeter/alarms/info.html', {"alarm": alarm, "modal_title": modal_title, 'histories': histories})
コード例 #25
0
def get_resources(request):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    if request.method == 'POST':
        nova = NovaRestAPI(auth_url, token)
        glance = GlanceRestAPI(auth_url, token)
        ceilometer = CeilometerRestAPI(auth_url, token)

        result = {"success": {}, "error": {"err_msg_list": []}}
        result_servers = nova.get_server_list(fields=["id", "name"])
        result_images = glance.get_image_list()
        result_resources = ceilometer.get_resource_list()
        resources = result_resources.get("success")

        if type(result_resources) == str:
            message = ast.literal_eval(result_resources.replace("null", "None")).get("error_message").get("faultstring")
            result["error"]["err_msg_list"].append({"title": "Not Found", "message": message, "code": 404})
        elif resources and result_servers.get("success"):
            for server in result_servers["success"].get("servers"):
                network_interfaces = [
                    {"id": sample.get('resource_id'), "name": sample.get("name")}
                    for sample in resources
                    if server.get("id") in sample.get('resource_id') and "tap" in sample.get('resource_id')
                ]
                server['networkInterfaceList'] = network_interfaces
        elif not resources and result_servers.get("success"):
            result["error"]["err_msg_list"].append({"error": {"message": "not found networkList", "title": "Not Found", "code": 404}})

        if result_servers.get("success"):
            result["success"].update(result_servers.get("success"))
        if result_images.get("success"):
            result["success"].update(result_images.get("success"))
        if result_servers.get("error"):
            result["error"]["err_msg_list"].append(result_servers.get("error"))
        if result_images.get("error"):
            result["error"]["err_msg_list"].append(result_images.get("error"))
        logger.debug(result)
        return JsonResponse(result)
コード例 #26
0
ファイル: views.py プロジェクト: jaehoonpaul/i2nsf-soa
def flavor_list(request):
    """
    가상머신 사양 목록
    :param request:
    :return:
    """
    if request.is_ajax() and request.method == 'POST':
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")

        nova = NovaRestAPI(auth_url, token)
        resultFlavorList = nova.get_flavor_detail_list()

        # if resultFlavorList.get("success"):
        #     for resultFlavors in resultFlavorList["success"]["flavors"]:
        #         resultFlavor = control.getFlavorDetails(token, domain_name, project_name, user_name, resultFlavors.get("id"))
        #         if resultFlavor.get("success"):
        #             flavor_list.append(resultFlavor["success"]["flavor"])
        #         else:
        #             logger.info(resultFlavor)
        # else:
        #     logger.info(resultFlavorList)
        # return JsonResponse({"success":{"flavor_list": flavor_list}})
        return JsonResponse(resultFlavorList)
コード例 #27
0
def sync(request, server_id):
    token = request.session.get('passToken')
    auth_url = request.session.get("auth_url")
    service_id = request.POST.get("service_id")
    nova = NovaRestAPI(auth_url, token)
    glance = GlanceRestAPI(auth_url, token)
    try:
        from sdsecgui.db.soa_db_connector import SOAManagerDBConnector
        m_conn = SOAManagerDBConnector.getInstance()
        m_conn.insert_server(auth_url, nova, service_id, server_id, glance)
        result = True
    except Exception as e:
        from sdsec.settings import logger
        logger.debug(e.message)
        result = False
    return JsonResponse({"result": result})
コード例 #28
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"))
コード例 #29
0
ファイル: views.py プロジェクト: jaehoonpaul/i2nsf-soa
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)
コード例 #30
0
ファイル: views.py プロジェクト: jaehoonpaul/i2nsf-soa
def retrieve_useage_list(request):
    if request.is_ajax() and request.method == 'POST':
        pass
    else:
        token = request.session.get('passToken')
        auth_url = request.session.get("auth_url")
        start_str = request.GET.get("start")
        end_str = request.GET.get("end")
        if start_str is None:
            yesterday = datetime.fromtimestamp(time.time() - 3600 * 24 * 2)
            start_date = datetime(yesterday.year, yesterday.month, yesterday.day, 0, 0, 0)
        else:
            date = start_str.split("-")
            start_date = datetime(int(date[0]), int(date[1]), int(date[2]), 0, 0, 0)
        if end_str is None:
            today = datetime.fromtimestamp(time.time() + 3600 * 24 * 0)
            end_date = datetime(today.year, today.month, today.day, 23, 59, 59)
        else:
            date = end_str.split("-")
            end_date = datetime(int(date[0]), int(date[1]), int(date[2]), 23, 59, 59)
        nova = NovaRestAPI(auth_url, token)
        start = start_date.isoformat()
        end = end_date.isoformat()
        result_usage_list = nova.get_usages(start, end)
        total_usage = {
            "instance_cnt": 0,
            "total_memory_mb": 0,
            "total_vcpus_usage": 0,
            "total_local_gb_usage": 0,
            "total_memory_mb_usage": 0,
            "vcpus": 0,
            "local_gb": 0,
            "memory_mb": 0
        }
        if result_usage_list.get("success"):
            usage_list = result_usage_list["success"].get("tenant_usages")
            keystone = KeystoneRestAPI(auth_url, token)
            projects = []
            p_result = keystone.get_project_list({"domain_id": request.session.get("domain_id")})
            if p_result.get("success"):
                projects = p_result["success"].get("projects")
            for usage in usage_list:
                server_usages = {"vcpus": 0, "local_gb": 0, "memory_mb": 0}
                for server_usage in usage.get("server_usages"):
                    for k, v in server_usage.items():
                        if k in ["vcpus", "local_gb", "memory_mb"]:
                            if "gb" in k:
                                v = v * 1024**3
                            elif "mb" in k:
                                v = v * 1024**2
                            server_usages[k] += v
                            total_usage[k] += v
                for key in ["total_vcpus_usage", "total_local_gb_usage", "total_memory_mb_usage"]:
                    total_usage[key] += usage.get(key)
                total_usage["instance_cnt"] += 1
                usage["server_usages_time"] = server_usages
                names = [project["name"] for project in projects if project["id"] == usage["tenant_id"]]
                if len(names) == 1:
                    name = names[0]
                else:
                    name = usage["tenant_id"]
                usage["project"] = {"id": usage["tenant_id"], "name": name}
        else:
            usage_list = result_usage_list

        return render(request, 'admin/index.html', {"total_usage": total_usage, 'usage_list': usage_list, "start_date": start_date.strftime('%Y-%m-%d'), "end_date": end_date.strftime('%Y-%m-%d')})

# def retrieve_useage_list(request, startStr=None, endStr=None):
#     if request.is_ajax() and request.method == 'POST':
#         sess = login("admin", "chiron", "admin", "http://192.168.10.6/identity/v3", 'default')
#         # sess = login(auth_url="http://129.254.173.151:5000/v3")
#         if startStr == None:
#             start = datetime.fromtimestamp(time.time() - 3600 * 24 * 1)
#         else:
#             date = startStr.split("-")
#             start = datetime(int(date[0]), int(date[1]), int(date[2]))
#         if endStr == None:
#             end = datetime.fromtimestamp(time.time() - 3600 * 24 * 0)
#         else:
#             date = endStr.split("-")
#             end = datetime(int(date[0]), int(date[1]), int(date[2]))
#         resultUsageList = get_usages(sess, start, end)
#         usageList = []
#         for resultUsage in resultUsageList:
#             usageList.append(resultUsage._info)
#         return JsonResponse({ 'usageList' : usageList })
#     else:
#         return render(request, 'admin/index.html', {})