Beispiel #1
0
def change_user_password_action(request, user_id):
    if request.user.username == "admin":
        return HttpResponse(jsonutils.dumps(
            ui_response(status_code=UI_RESPONSE_DWZ_ERROR,
                        message="admin can't change password")))

    username = request.user.username

    form = ChangePasswordForm(request, user_id, request.POST)
    if form.is_valid():
        old_password = request.POST.get('oldpassword', '')
        password = request.POST.get('password', '')
        try:
            api.user_update_own_password(request, old_password, password)
        except Unauthorized:
            return HttpResponse(jsonutils.dumps(
                ui_response(status_code=UI_RESPONSE_DWZ_ERROR,
                            message="The old password is wrong.")))
        except Exception, e:
            LOG.error('Change password error. %s' % e)
            return HttpResponse(jsonutils.dumps(
                ui_response(status_code=UI_RESPONSE_DWZ_ERROR,
                            message="change password error")))

        try:
            create_token(request, username, password)
        except Exception:
            pass

        return HttpResponse(jsonutils.dumps(
            ui_response(status_code=UI_RESPONSE_OK,
                        message="change password success.",
                        object_name=username)))
Beispiel #2
0
def export_logs_count(request):
    log_lists = logs_list_same(request)
    log_list_len = len(log_lists)
    if log_list_len < 1:
        return HttpResponse(jsonutils.dumps(
            {"message": get_text('Can not export logs'), "statusCode": 300}))
    return HttpResponse(jsonutils.dumps({"message": '', "statusCode": 200}))
Beispiel #3
0
def update_notice_action(request):
    """
    :param request: request Object
    :return:
    """
    notice_form = NoticeForm(request, request.POST)
    if notice_form.is_valid():
        data = notice_form.cleaned_data
# maybe unused add by yangzhi 2013.11.13
#        user_id = request.user.id
#        operater_id = data['operater_id']
#        if user_id != operater_id and get_user_role_name(request) != ROLE_ADMIN:
#            msg = "Sorry , you do not have this permissions"
#            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
        title = data['title']
        notice_uuid = data['uuid']
        try:
            notice = Notice.objects.get(uuid=notice_uuid)
            notice.title = title
            notice.content = data['content']
            notice.level = data['level']
            notice.release = data['release']
            notice.update_time = datetime.datetime.now(tz=utc)
            notice.save()
        except Notice.DoesNotExist:
            msg = 'Can not get notice (uuid=%s) information' % notice_uuid
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
        except Exception, e:
            LOG.error('Can not update notice uuid=%s,error is %s' % (
                notice_uuid, e.message))
            msg = 'update notice uuid=%s failed, please retry later.' % notice_uuid
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
        return HttpResponse(
            {"message": "Update notice Success", "statusCode": UI_RESPONSE_OK,
             "object_name": title}, status=UI_RESPONSE_OK)
Beispiel #4
0
def export_logs_count(request):
    log_lists = logs_list_same(request)
    log_list_len = len(log_lists)
    if log_list_len < 1:
        return HttpResponse(
            jsonutils.dumps({
                "message": get_text('Can not export logs'),
                "statusCode": 300
            }))
    return HttpResponse(jsonutils.dumps({"message": '', "statusCode": 200}))
Beispiel #5
0
def get_port_info(request, port_id):
    """
    :param request:request object, port_id
    :return:view<'virtual_network_manage/portinfo.html'>::get a port info
    """
    tenant_choices = []
    try:
        port = api.quantum.port_get(request, port_id)
        network = api.quantum.network_get(request, port.network_id)
        tenants = api.tenant_list_not_filter(request, admin=True)
        for tenant in tenants:
            tenant_choices.append((tenant.id, tenant.name))

        return shortcuts.render(request,
                                'virtual_network_manage/portinfo.html', {
                                    'network': network,
                                    'port': port,
                                    'tenants': tenant_choices
                                })
    except Unauthorized:
        raise
    except Exception, exe:
        msg = 'get port info error.'
        LOG.error('get port info error,the error is %s' % exe.message)
        return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
Beispiel #6
0
def edit_securitygrouprules(request, security_group_id):
    try:
        securitygroup = api.security_group_get(request, security_group_id)

        number_per_page = NUMBERS_PER_PAGE
        if request.GET.has_key("numPerPage"):
            number_per_page = request.GET['numPerPage']
        paginator = Paginator(securitygroup.rules, number_per_page)
        page = request.GET.get('pageNum', 1)
        try:
            page_obj = paginator.page(page)  #page obj
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            page_obj = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            page_obj = paginator.page(paginator.num_pages)

        return shortcuts.render(request, 'securitygroup_manage/rules.html',
            {'page_obj': page_obj, 'security_group_id': security_group_id})
    except Unauthorized:
        raise
    except Exception, ex:
        msg = 'get security group rules info error.'
        LOG.error("the error is %s" % ex.message)
        return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
Beispiel #7
0
def get_host_tree(request):
    """

    :param request:
    :return:
    """
    json_object = {}
    nodes = get_nodes(request)
    if nodes:
        available_nodes, host_tree = get_available_nodes(nodes)
        instances = get_instances(request)
        if instances:
            for instance in instances:
                host_name = getattr(instance, 'OS-EXT-SRV-ATTR:host', None)
                if host_name and available_nodes.has_key(host_name):
                    tree_data = get_instance_simple_express(instance,
                                                            available_nodes[
                                                            host_name])
                    host_tree.append(tree_data)

        json_object['host_tree'] = host_tree
        client = VoyageMonitor()
        host_cache = client.get_host_list(request.user.tenant_id,
                                          request.user.token.id)
        json_object['host_cache'] = host_cache
        return HttpResponse(jsonutils.dumps(json_object))
    else:
        return HttpResponse('Not Found')
Beispiel #8
0
def edit_port_action(request, port_id):
    """
    :param request:request object, port_id
    :return:view<'virtual_network_manage/networkprojectindex.html'>::action for edit a port
    """
    form = UpdatePort(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        try:
            api.quantum.port_modify(request, port_id,
            name = data['name'],
            admin_state_up = data['admin_state'],
            device_id = data['device_id'],
            device_owner = data['device_owner'])
        except Unauthorized:
            raise
        except Exception as exe:
            msg = ('Failed to edit port %s' % data['name'])
            LOG.error('Failed to edit port,the error is %s' % exe.message)
            return HttpResponse(jsonutils.dumps(ui_response(message = msg)))

        return HttpResponse({"message":"Edit port successfully!",
                             "statusCode":UI_RESPONSE_DWZ_SUCCESS ,
                             "object_name":data['name']}, status = UI_RESPONSE_DWZ_SUCCESS)
    else:
        return HttpResponse({"form" : form,
                             "message" : "",
                             "statusCode" : UI_RESPONSE_DWZ_ERROR}, status = UI_RESPONSE_ERROR)
Beispiel #9
0
def get_network_info(request, tenant_id, network_id):
    """
    :param request:request object, tenant_id, network_id
    :return:view<'virtual_network_manage/networkinfo.html'>::get a network info
    """
    try:
        switch_tenants(request, tenant_id)
        network = api.quantum.network_get(request, network_id)
        network.set_id_as_name_if_empty(length = NETWORK_NAME_EMPTY_LENGTH)

        ports = api.quantum.port_list(request, network_id = network_id)

        for p in ports:
            p.set_id_as_name_if_empty()

        subnets = api.quantum.subnet_list(request,
             network_id = network.id)

        for s in subnets:
            s.set_id_as_name_if_empty()

        tenant_choices = []
        tenants = api.tenant_list_not_filter(request, admin = True)
        for tenant in tenants:
            tenant_choices.append((tenant.id, tenant.name))

        return shortcuts.render(request, 'virtual_network_manage/networkinfo.html', {'network': network, 'subnets':subnets, "ports":ports, "tenants":tenant_choices})
    except Unauthorized:
        raise
    except Exception , exe:
        msg = 'get network info error.'
        LOG.error('get network info error,the error is %s' % exe.message)
        return HttpResponse(jsonutils.dumps(ui_response(message = msg)))
Beispiel #10
0
def edit_subnet_action(request, subnet_id):
    """
    :param request:request object, subnet_id
    :return:view<'virtual_network_manage/networkprojectindex.html'>::action for edit subnet
    """
    form =  UpdateSubnet(request, subnet_id, request.POST)
    if form.is_valid():
        data = form.cleaned_data
        params = {}
        try:
            params['name'] = data['subnet_name']
            if data['no_gateway']:
                params['gateway_ip'] = None
            elif data['gateway_ip']:
                params['gateway_ip'] = data['gateway_ip']

            setup_subnet_parameters(params, data, is_create = False)

            api.quantum.subnet_modify(request, subnet_id, **params)
        except Unauthorized:
            raise
        except Exception as exe:
            msg = ('Failed to edit subnet: %s' % data['subnet_name'])
            LOG.error('Failed to edit subnet,the error is %s' % exe.message)
            return HttpResponse(jsonutils.dumps(ui_response(message = msg)))

        return HttpResponse({"message":"Edit subnet successfully!", "statusCode":UI_RESPONSE_DWZ_SUCCESS , "object_name":data['subnet_name']}, status = UI_RESPONSE_DWZ_SUCCESS)
    else:
        return HttpResponse({"form":form, "message":"", "statusCode":UI_RESPONSE_DWZ_ERROR}, status = UI_RESPONSE_ERROR)
Beispiel #11
0
def create_port_action(request, network_id):
    """
    :param request:request object, network_id
    :return:view<'virtual_network_manage/networkprojectindex.html'>::action for create a port
    """
    form = CreatePort(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        try:
            network = api.quantum.network_get(request, network_id)
            data['tenant_id'] = network.tenant_id
            data['admin_state_up'] = data['admin_state']
            del data['admin_state']

            api.quantum.port_create(request, **data)
        except Unauthorized:
            raise
        except Exception as exe:
            msg = get_text('Failed to create a port for network %s')\
                  % data['network_name']
            LOG.error('Failed to create port,the error is %s' % exe.message)
            return HttpResponse(jsonutils.dumps(ui_response(message = msg)))

        return HttpResponse({"message" : "Create port successfully!",
                             "statusCode" : UI_RESPONSE_DWZ_SUCCESS ,
                             "object_name" : data['name']}, status = UI_RESPONSE_DWZ_SUCCESS)
    else:
        return HttpResponse({"form":form,
                             "message":"",
                             "statusCode":UI_RESPONSE_DWZ_ERROR }, status = UI_RESPONSE_ERROR)
Beispiel #12
0
def get_client_instance_power(request, project_id, instance_id):
    """
    :param request: request object
    :param instance_id: the instance id
    :return: the instance's power
    """
    if request.is_ajax():
        switch_tenants(request, project_id)
        try:
            instance = api.server_get(request, instance_id)
        except Unauthorized:
            raise
        except exceptions.ClientException:
            return HttpResponse(content=instance_id, status=UI_RESPONSE_NOTFOUND)
        if 1 == getattr(instance, 'OS-EXT-STS:power_state', 'None'):
            setattr(instance, 'power_state', 'Running')
        elif 3 == getattr(instance, 'OS-EXT-STS:power_state', 'None'):
            setattr(instance, 'power_state', 'Paused')
        elif 5 == getattr(instance, 'OS-EXT-STS:power_state', 'None'):
            setattr(instance, 'power_state', 'Suspended')
        else:
            setattr(instance, 'power_state', 'No state')
        return HttpResponse(jsonutils.dumps(
            {instance_id: getattr(instance, 'power_state', 'None')}))
    raise NotFound
Beispiel #13
0
def get_software_status(request, software_uuid):
    try:
        software = Software.objects.get(uuid=software_uuid)
    except Exception, e:
        LOG.error('Can not get software uuid=%s. %s' % (software_uuid, e))
        return HttpResponse(jsonutils.dumps(
            ui_response(message="this software not exited")))
Beispiel #14
0
def index_controller(request, type='menu'):
    """
    :param request:
    :param type:
    :return: The menu list
    """
    role = get_user_role_name(request)
    if not role:
        return HttpResponse('Not Found')
    try:
        if type == 'menu':
            controllers = Controller.objects.filter(action_type='menu',
                role=role)
        elif type == 'action':
            controllers = Controller.objects.filter(action_type='menu',
                role=role)
        else:
            if role == ROLE_ADMIN:
                controllers = Controller.objects.all()
            else:
                controllers = Controller.objects.filter(role=role)

        if request.is_ajax():
            return HttpResponse(jsonutils.dumps(controllers))
    except Exception, e:
        LOG.error('Can not get list of controllers,error is %s' % e)
Beispiel #15
0
def get_node_monitor_info_item(request, node_uuid, host_id):
    """
    :param request:
    :param node_uuid:
    :param host_id:
    :return:
    """
    try:
        node = Node.objects.get(uuid=node_uuid)
        client = VoyageMonitor()
        try:
            all_services_status = client.check_load(request.user.tenant_id,
                                                    request.user.token.id,
                                                    host_id, node_uuid)
            return HttpResponse(
                jsonutils.dumps({
                    node_uuid: all_services_status,
                    "name": node.name
                }))
        except VoyageClientException:
            LOG.error('Voyage service can not connect.')
            return HttpResponse('Not Found')
    except Exception, exp:
        msg = 'Get monitor info error, reason: %s' % (exp)
        LOG.error(msg)
        return HttpResponse('Not Found')
Beispiel #16
0
def update_user_password_action(request, user_id):
    """
    :param request: request object
    :param user_id: the user's id
    :return view<'get_user_list'>::update successfully
            view<'user_manage/update.html'>::failed
    """
    form = UpdateUserPasswordForm(request, user_id, request.POST)
    if form.is_valid():
        iRet, msg = handle_update_password(request, user_id, form.cleaned_data)
        if iRet:
            return HttpResponse(jsonutils.dumps(
                ui_response(form,
                            message="Update User Password Success",
                            object_name=form.cleaned_data['name'])))
        else:
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
    else:
        return HttpResponse(jsonutils.dumps(ui_response(form)))
Beispiel #17
0
def get_facility_info(request):
    json_obj = []
    try:
        client = VoyageMonitor()
        facilitys = api.nova.get_hypervisors_list(request)
        facilitys.extend(api.cinder.get_all_hosts_resources(request))
        node_type_dict = {node.name: node.type for node in get_nodes(request)}
        nagios_host_dict = client.get_host_dict(
            tenant_id=request.user.tenant_id, token=request.user.token.id)
        nagios_host_state = client.get_host_status(
            tenant_id=request.user.tenant_id, token=request.user.token.id)
        show_set = set()
        i = 0
        for facility in facilitys:
            if i < 5:
                instance_name = facility.hypervisor_hostname
                if instance_name not in show_set:
                    show_set.add(instance_name)
                else:
                    continue

                if instance_name not in nagios_host_dict \
                    or instance_name not in node_type_dict:
                    continue

                memory_mb = facility.memory_mb * 1.5
                memory_mb_used = facility.memory_mb_used
                memory_mb_per = int((memory_mb_used * 100) / memory_mb)
                instance_online = getattr(facility, 'num_vm_active', 0)
                num_instances = getattr(facility, 'num_instances', 0)
                cpu_use = facility.cpu_usage
                if nagios_host_dict and nagios_host_state:
                    host_state = nagios_host_state[
                                 nagios_host_dict[instance_name]]
                else:
                    host_state = "offline"

                facility_obj = {"instance_name": instance_name,
                                "memory_mb_per": memory_mb_per,
                                "instance_online": instance_online,
                                "instance_offline": num_instances -
                                                    instance_online,
                                "host_type": get_text(
                                    node_type_dict[instance_name]),
                                "host_state": get_text(host_state),
                                "cpu_use": cpu_use}
                json_obj.append(facility_obj)
                i += 1

        return HttpResponse(jsonutils.dumps(json_obj))
    except Unauthorized:
        raise
    except Exception, e:
        LOG.error('Can not get hypervisors list , error is %s' % e)
        return HttpResponse('Not Found')
Beispiel #18
0
def create_gateway_action(request, router_id):

    try:
        myrouterproject = api.quantum.router_get(request, router_id)

    except Unauthorized:
        raise
    except Exception, exc:
        msg = get_text('Failed to retrieve the router.')
        LOG.error('Failed to retrieve the router %s' % exc.message)
        return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
Beispiel #19
0
def change_tenant_form(request):
    """
    :param request: request object
    :return dict: the tenant's security group list
    """
    group_list = ''
    if 'tenantId' in request.GET:
        tenant_id = request.GET['tenantId']
        if tenant_id != "" and tenant_id is not None:
            switch_tenants(request, tenant_id)
            group_list = security_group_list(request)
    return HttpResponse(jsonutils.dumps(group_list))
Beispiel #20
0
def img_fresh_progress(request):
    tenant_id = None
    if request.GET.has_key('img_tenant_id'):
        tenant_id = request.GET['img_tenant_id']

    try:
        if tenant_id is not None:
            switch_tenants(request, tenant_id)
    except Exception, exc:
        LOG.error('Error is :%s.' % exc)
        return HttpResponse(
            jsonutils.dumps({"status": '2'}))
Beispiel #21
0
def create_routerprojectdetail(request, tenant_id, routerproject_id):

    try:
        switch_tenants(request, tenant_id)
        myrouterproject = api.quantum.router_get(request, routerproject_id)

    except Unauthorized:
        raise
    except Exception, exc:
        msg = get_text('Failed to retrieve the router.')
        LOG.error('Failed to retrieve the router:%s' % exc.message)
        return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
Beispiel #22
0
def create_subnet_action(request, network_id):
    """
    :param request:request object, network_id
    :return:view<'virtual_network_manage/networkprojectindex.html'>::action for create subnet
    """

    form = CreateSubnet(request, network_id,request.POST)
    if form.is_valid():
        data = form.cleaned_data
        network = None
        try:
            network = api.quantum.network_get(request, network_id)
        except Unauthorized:
            raise
        except Exception as exe:
            LOG.error('Failed to get network,the error is %s' % exe.message)
        if network:
            network_id = network.id
        else:
            network_id = network_id
        try:
            params = {'network_id': network_id,
                      'name': data['subnet_name'],
                      'cidr': data['cidr'],
                      'ip_version': int(data['ip_version'])}
            if network.tenant_id:
                params['tenant_id'] = network.tenant_id
            if data['no_gateway']:
                params['gateway_ip'] = None
            elif data['gateway_ip']:
                params['gateway_ip'] = data['gateway_ip']

            setup_subnet_parameters(params, data)

            api.quantum.subnet_create(request, **params)
        except Unauthorized:
            raise
        except LicenseForbidden:
            raise
        except Exception as exe:
            if exe.message.find('overlaps with another subnet') != -1:
                msg = ('Failed! Overlaps with another subnet.')
            else:
                msg = ('Failed to create subnet')
            LOG.error('Failed to create subnet,the error is %s' % exe.message)
            return HttpResponse(jsonutils.dumps(ui_response(message = msg)))

        return HttpResponse({"message" : "Create subnet successfully!",
                             "statusCode" : UI_RESPONSE_DWZ_SUCCESS ,
                             "object_name" : data['subnet_name']}, status = UI_RESPONSE_DWZ_SUCCESS)
    else:
        return HttpResponse({"form" : form, "message" : "", "statusCode" : UI_RESPONSE_DWZ_ERROR }, status = UI_RESPONSE_ERROR)
Beispiel #23
0
def update_notice_action(request):
    """
    :param request: request Object
    :return:
    """
    notice_form = NoticeForm(request, request.POST)
    if notice_form.is_valid():
        data = notice_form.cleaned_data
        # maybe unused add by yangzhi 2013.11.13
        #        user_id = request.user.id
        #        operater_id = data['operater_id']
        #        if user_id != operater_id and get_user_role_name(request) != ROLE_ADMIN:
        #            msg = "Sorry , you do not have this permissions"
        #            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
        title = data['title']
        notice_uuid = data['uuid']
        try:
            notice = Notice.objects.get(uuid=notice_uuid)
            notice.title = title
            notice.content = data['content']
            notice.level = data['level']
            notice.release = data['release']
            notice.update_time = datetime.datetime.now(tz=utc)
            notice.save()
        except Notice.DoesNotExist:
            msg = 'Can not get notice (uuid=%s) information' % notice_uuid
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
        except Exception, e:
            LOG.error('Can not update notice uuid=%s,error is %s' %
                      (notice_uuid, e.message))
            msg = 'update notice uuid=%s failed, please retry later.' % notice_uuid
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
        return HttpResponse(
            {
                "message": "Update notice Success",
                "statusCode": UI_RESPONSE_OK,
                "object_name": title
            },
            status=UI_RESPONSE_OK)
Beispiel #24
0
def get_host_metadata(request):
    """
    :param request:
    :return:
    """
    client = VoyageMonitor()
    try:
        hosts = client.get_host_list(tenant_id=request.user.tenant_id,
                                     token=request.user.token.id)
        return HttpResponse(jsonutils.dumps(hosts))
    except VoyageClientException:
        LOG.error('Voyage service can not connect.')
        return HttpResponse('Not Found')
Beispiel #25
0
def software_download(request, software_uuid):
    """
    Get binary file of Software with uuid
    :param request:
    :param software_uuid:
    :return:
    """
    try:
        software = Software.objects.get(uuid=software_uuid)
    except Exception, e:
        LOG.error('Can not get software uuid=%s. %s' % (software_uuid, e))
        return HttpResponse(jsonutils.dumps(
            ui_response(message="this software not exited")))
Beispiel #26
0
def get_host_metadata(request):
    """
    :param request:
    :return:
    """
    client = VoyageMonitor()
    try:
        hosts = client.get_host_list(tenant_id=request.user.tenant_id,
                                     token=request.user.token.id)
        return HttpResponse(jsonutils.dumps(hosts))
    except VoyageClientException:
        LOG.error('Voyage service can not connect.')
        return HttpResponse('Not Found')
Beispiel #27
0
def update_node_action(request, node_uuid):
    """
    :param request: request Object
    :param node_uuid: the uuid of node whichj will be updated
    :return:
    """
    node_form = NodeForm(request, node_uuid, request.POST)
    if node_form.is_valid():
        data = node_form.cleaned_data
        control_nodes = Node.objects.filter(type='control_node').exclude(
            uuid=node_uuid)
        if control_nodes.__len__() > 0 and data['type'] == 'control_node':
            msg = 'control node has already exist'
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))

        try:
            node = Node.objects.get(uuid=node_uuid)
            node.name = data['name']
            node.passwd = data['passwd']
            node.ip = data['ip']
            node.type = data['type']
            node.save()
        except Node.DoesNotExist:
            msg = 'Can not get node (uuid=%s) information' % node_uuid
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))

        except Exception, exp:
            err_msg = 'Can not update node uuid=%s,error is %s' % (node_uuid,
                                                                   exp)
            LOG.error(err_msg)
            msg = 'update node uuid=%s failed, please retry later.' % node_uuid
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))

        return HttpResponse(
            jsonutils.dumps(
                ui_response(node_form,
                            message="Update node Success",
                            object_name=node.name)))
Beispiel #28
0
def update_node_action(request, node_uuid):
    """
    :param request: request Object
    :param node_uuid: the uuid of node whichj will be updated
    :return:
    """
    node_form = NodeForm(request, node_uuid, request.POST)
    if node_form.is_valid():
        data = node_form.cleaned_data
        control_nodes = Node.objects.filter(type='control_node').exclude(
            uuid=node_uuid)
        if control_nodes.__len__() > 0 and data['type'] == 'control_node':
            msg = 'control node has already exist'
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))

        try:
            node = Node.objects.get(uuid=node_uuid)
            node.name = data['name']
            node.passwd = data['passwd']
            node.ip = data['ip']
            node.type = data['type']
            node.save()
        except Node.DoesNotExist:
            msg = 'Can not get node (uuid=%s) information' % node_uuid
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))

        except Exception, exp:
            err_msg = 'Can not update node uuid=%s,error is %s' % (node_uuid,
                                                                   exp)
            LOG.error(err_msg)
            msg = 'update node uuid=%s failed, please retry later.' % node_uuid
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))

        return HttpResponse(jsonutils.dumps(
            ui_response(node_form, message="Update node Success",
                        object_name=node.name)))
Beispiel #29
0
def delete_routerif_action(request, routerproject_id, interface_id):
    try:
        port = api.quantum.port_get(request, interface_id)
        if port['device_owner'] == 'network:router_gateway':
            api.quantum.router_remove_gateway(request, routerproject_id)
        else:
            api.quantum.router_remove_interface(request,
                                                routerproject_id,
                                                port_id=interface_id)
    except Unauthorized:
        raise
    except Exception, exc:
        msg = get_text('Failed to delete interface')
        LOG.error('Failed to delete interface :%s' % exc.message)
        return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
Beispiel #30
0
def reboot_instance_client(request, project_id ,instance_id):
    if request.is_ajax():
        switch_tenants(request, project_id)
        try:
            instance = api.server_get(request, instance_id)
            instance_status = instance.status
            if instance_status.lower() in ('active', 'suspend', 'shutoff',):
                api.server_reboot(request, instance_id)
                instance_next = api.server_get(request, instance_id)
                return HttpResponse(jsonutils.dumps({instance_id: 'success',
                                                     "status": getattr(instance_next, 'status', 'None')}))
            else:
                LOG.info('Can not reboot instance,the status is wrong!')
                return HttpResponse(jsonutils.dumps({instance_id: 'failed'}))
        except Unauthorized:
            raise
        except exceptions.NotFound, e:
            msg = _('Can not found instance (%s)') % instance_id
            LOG.error(msg)
            return HttpResponse(jsonutils.dumps({instance_id: 'failed'}))

        except Exception, e:
            LOG.error('Can not reboot instance!')
            return HttpResponse(jsonutils.dumps({instance_id: 'failed'}))
Beispiel #31
0
def get_tenant_usage_details(request, tenant_id):
    """

    :param request:
    :param tenant_id:
    :return:
    """
    try:
        start, end = get_date_range()
        usage = api.usage_get(request, tenant_id, start, end)
        return HttpResponse(jsonutils.dumps(usage))
    except Exception, exp:
        msg = 'Can not get usage of tenant, reason: %s' % (exp.message)
        LOG.error(msg)
        return HttpResponse('Not Found')
Beispiel #32
0
def get_rights_relation(request):
    role = get_user_role_name(request)
    role_id = None
    if "role_id" in request.GET:
        role_id = request.GET['role_id']
    if not role:
        return HttpResponse('Not Found')
    try:
        role_right_list = Role_right.objects.filter(role_id=role_id)
        d = []
        for rrl in role_right_list:
            d.append(rrl.right_key)
        if request.is_ajax() and len(d) > 0:
            return HttpResponse(jsonutils.dumps(d))
    except Exception, e:
        LOG.error('Can not get list of right,error is %s' % e)
Beispiel #33
0
def create_software_form(request):
    """
    :param request:
    :return:
    """
    softwares = []
    uploading_cnt = Software.objects.filter(Q(status=SOFTWARE_STATE_UPLOADING)
                                            | Q(status=SOFTWARE_STATE_CREATING)).count()
    if uploading_cnt >= settings.SOFTWARE_UPLOADING_MAX_NUM:
        return HttpResponse(jsonutils.dumps(
            ui_response(message="uploading count is beyond max limit.")))
    try:
        softwares_cnt = Software.objects.count()
        license_cnt = cache.get('CreeperQuotas').get('SoftwareMaxNum')
    except Exception, e:
        LOG.error('Can not get total of softwares. %s' % e)
Beispiel #34
0
def get_rights_relation(request):
    role = get_user_role_name(request)
    role_id = None
    if "role_id" in request.GET:
        role_id = request.GET['role_id']
    if not role:
        return HttpResponse('Not Found')
    try:
        role_right_list = Role_right.objects.filter(role_id=role_id)
        d = []
        for rrl in role_right_list:
            d.append(rrl.right_key)
        if request.is_ajax() and len(d) > 0:
            return HttpResponse(jsonutils.dumps(d))
    except Exception, e:
        LOG.error('Can not get list of right,error is %s' % e)
Beispiel #35
0
def get_subnet_info(request, subnet_id):
    """
    :param request:request object, network_id
    :return:view<'virtual_network_manage/subnetinfo.html'>::get a subnet info
    """
    try:
        subnet = api.quantum.subnet_get(request, subnet_id)
        network = api.quantum.network_get(request, subnet.network_id)

        return shortcuts.render(request, 'virtual_network_manage/subnetinfo.html', {'network': network, 'subnet':subnet})
    except Unauthorized:
        raise
    except Exception , exe:
        msg = 'get subnet info error.'
        LOG.error('get subnet and network info error,the error is %s' % exe.message)
        return HttpResponse(jsonutils.dumps(ui_response(message = msg)))
Beispiel #36
0
def get_client_instance_task(request,project_id, instance_id):
    """
    :param request: request object
    :param instance_id: the instance id
    :return: the instance's task
    """
    if request.is_ajax():
        switch_tenants(request, project_id)
        try:
            instance = api.server_get(request, instance_id)
        except Unauthorized:
            raise
        except exceptions.ClientException:
            return HttpResponse(content=instance_id, status=UI_RESPONSE_NOTFOUND)
        return HttpResponse(jsonutils.dumps(
            {instance_id: getattr(instance, 'OS-EXT-STS:task_state', 'None')}))
    raise NotFound
Beispiel #37
0
def get_system_usage(request):
    """

    :param request:
    :return:
    """
    try:
        start, end = get_date_range()
        usage_list = api.usage_list(request, start, end)
        return HttpResponse(
            jsonutils.dumps(get_simple_express(request, usage_list)))
    except Unauthorized:
        raise
    except Exception, exp:
        msg = 'Cat not get system usage, reason: %s' % (exp.message)
        LOG.error(msg)
        return HttpResponse('Not Found')
Beispiel #38
0
def search_image_status(request, instance_id):
    """
     :param request: request object
     :return view<'image_template_manage/create.html'>: the view create image form
     """

    try:
        instance = api.server_get(request, instance_id)
        instance_id = getattr(instance, 'id', None)
        instance_name = getattr(instance, 'name', None)
        console = api.nova.server_spice_console(request, instance_id)

    except Unauthorized:
        raise
    except exceptions.NotFound, exc:
        msg = _('Can not retrieve spice url!')
        LOG.error('Can not retrieve spice url!error is %s.' % exc)
        return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
Beispiel #39
0
def get_network_list(request):
    """
    :param request: request object
    :return: the tenant's network
    """
    net_list = []
    if 'tenantId' in request.GET:
        tenant_id = request.GET['tenantId']
        if tenant_id:
            try:
                net_list = Instance_Manage.views.get_server_net(request,
                                                                tenant_id)
            except Exception, e:
                LOG.error(
                    'The method instance_get_network_list raise exception: '
                    '%s' % e)
                return HttpResponse({'message': 'Can not get net list'})
        return HttpResponse(jsonutils.dumps(net_list))
Beispiel #40
0
def get_floatingip_count_info(request):
    """
    get the total count of floating ip and the count of used ips
    :param request:
    :return:
    """

    try:
        vip_per = 0
        total = 0
        subnet_ids = []
        used = 0

        floating_pools = api.network.floating_ip_pools_list(request)

        for pool in floating_pools:
            for subnet_id in pool.subnets:
                subnet_ids.append(
                    subnet_id)  # all subnet ids in floating_pools
                subnet = api.quantum.subnet_get(request, subnet_id)
                for allocation_pool in subnet.allocation_pools:
                    start = IPAddress(allocation_pool.get("start")).value
                    end = IPAddress(allocation_pool.get("end")).value
                    total += end - start

        ports = api.quantum.port_list(request)
        for port in ports:
            for ip in port.fixed_ips:
                if ip["subnet_id"] in subnet_ids:
                    used += 1

        if total != 0:
            vip_per = (used * 100) / total

        json_obj = {"vip_per": vip_per}
        return HttpResponse(jsonutils.dumps(json_obj))
    except Unauthorized:
        raise
    except Exception, exe:
        LOG.exception(
            "Cann't get the percent of used floating ip for home page,the error is %s "
            % exe.message)
        return HttpResponse('Not Found')
Beispiel #41
0
def get_hardware_info(request):
    try:
        hardware = api.nova.get_hypervisors_statistics(request)
        vcpus = hardware.vcpus
        vcpus_used = hardware.vcpus_used
        memory_mb = hardware.memory_mb
        memory_mb_used = hardware.memory_mb_used
        local_gb = hardware.local_gb
        local_gb_used = hardware.local_gb_used
        vcpus_per = (vcpus_used * 100) / vcpus
        memory_mb_per = (memory_mb_used * 100) / memory_mb
        local_gb_per = (local_gb_used * 100) / local_gb
        json_obj = {"vcpus_per": vcpus_per, "memory_mb_per": memory_mb_per,
                    "local_gb_per": local_gb_per}
        return HttpResponse(jsonutils.dumps(json_obj))
    except Unauthorized:
        raise
    except Exception, e:
        LOG.error('Can not get hypervisors statistics , error is %s' % e)
        return HttpResponse('Not Found')
Beispiel #42
0
def edit_subnet_action(request, subnet_id):
    """
    :param request:request object, subnet_id
    :return:view<'virtual_network_manage/networkprojectindex.html'>::action for edit subnet
    """
    form = UpdateSubnet(request, subnet_id, request.POST)
    if form.is_valid():
        data = form.cleaned_data
        params = {}
        try:
            params['name'] = data['subnet_name']
            if data['no_gateway']:
                params['gateway_ip'] = None
            elif data['gateway_ip']:
                params['gateway_ip'] = data['gateway_ip']

            setup_subnet_parameters(params, data, is_create=False)

            api.quantum.subnet_modify(request, subnet_id, **params)
        except Unauthorized:
            raise
        except Exception as exe:
            msg = ('Failed to edit subnet: %s' % data['subnet_name'])
            LOG.error('Failed to edit subnet,the error is %s' % exe.message)
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))

        return HttpResponse(
            {
                "message": "Edit subnet successfully!",
                "statusCode": UI_RESPONSE_DWZ_SUCCESS,
                "object_name": data['subnet_name']
            },
            status=UI_RESPONSE_DWZ_SUCCESS)
    else:
        return HttpResponse(
            {
                "form": form,
                "message": "",
                "statusCode": UI_RESPONSE_DWZ_ERROR
            },
            status=UI_RESPONSE_ERROR)
Beispiel #43
0
def get_subnet_info(request, subnet_id):
    """
    :param request:request object, network_id
    :return:view<'virtual_network_manage/subnetinfo.html'>::get a subnet info
    """
    try:
        subnet = api.quantum.subnet_get(request, subnet_id)
        network = api.quantum.network_get(request, subnet.network_id)

        return shortcuts.render(request,
                                'virtual_network_manage/subnetinfo.html', {
                                    'network': network,
                                    'subnet': subnet
                                })
    except Unauthorized:
        raise
    except Exception, exe:
        msg = 'get subnet info error.'
        LOG.error('get subnet and network info error,the error is %s' %
                  exe.message)
        return HttpResponse(jsonutils.dumps(ui_response(message=msg)))
Beispiel #44
0
def checkbox_right_cancel(request):
    """
    :param request:
    :param type:
    :return: The menu list
    """
    role = get_user_role_name(request)
    right_id = None
    if "right_id" in request.GET:
        right_id = request.GET['right_id']
    if not role:
        return HttpResponse('Not Found')
    try:
        rights = Right.objects.all()
        ch_depend = {}
        dict_depend = []
        for rr in rights:
            depend = simplejson.loads(rr.depends)
            if '' != depend:
                for dep in depend['depend_keys']:
                    if dep in ['2002', '2006']:
                        continue
                    if dep == right_id:
                        if rr.parent_id == -1:
                            ch_depend[rr.id] = rr.key
                        dict_depend.append(rr.key)

        for rr in rights:
            if dict_depend.count(rr.key) == 0:
                if rr.key in ['2002', '2006']:
                    continue
                if ch_depend.has_key(rr.parent_id):
                    dict_depend.append(rr.key)

        if request.is_ajax() and len(rights) > 0:
            return HttpResponse(jsonutils.dumps(dict_depend))
    except Exception, e:
        LOG.error('Can not get list of right,error is %s' % e)
Beispiel #45
0
def all_checkbox_right(request):
    """
    :param request:
    :param type:
    :return: The menu list
    """
    role = get_user_role_name(request)
    right_id = None
    if "right_id" in request.GET:
        right_id = request.GET['right_id']
    if not role:
        return HttpResponse('Not Found')
    try:
        rights = Right.objects.filter(key=right_id)
        right = rights[0]
        dict_depend = []
        depend = simplejson.loads(right.depends)
        if '' != depend:
            for dep in depend['depend_keys']:
                if dep in ['2002', '2006']:
                    continue
                if dict_depend.count(dep) == 0:
                    dict_depend.append(dep)
        parent_id = right.id
        rights = Right.objects.filter(parent_id=parent_id)
        for rr in rights:
            depend = simplejson.loads(rr.depends)
            if '' != depend:
                for dep in depend['depend_keys']:
                    if dep in ['2002', '2006']:
                        continue
                    if dict_depend.count(dep) == 0:
                        dict_depend.append(dep)

        if request.is_ajax() and len(rights) > 0:
            return HttpResponse(jsonutils.dumps(dict_depend))
    except Exception, e:
        LOG.error('Can not get list of right,error is %s' % e)
Beispiel #46
0
def create_port_action(request, network_id):
    """
    :param request:request object, network_id
    :return:view<'virtual_network_manage/networkprojectindex.html'>::action for create a port
    """
    form = CreatePort(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        try:
            network = api.quantum.network_get(request, network_id)
            data['tenant_id'] = network.tenant_id
            data['admin_state_up'] = data['admin_state']
            del data['admin_state']

            api.quantum.port_create(request, **data)
        except Unauthorized:
            raise
        except Exception as exe:
            msg = get_text('Failed to create a port for network %s')\
                  % data['network_name']
            LOG.error('Failed to create port,the error is %s' % exe.message)
            return HttpResponse(jsonutils.dumps(ui_response(message=msg)))

        return HttpResponse(
            {
                "message": "Create port successfully!",
                "statusCode": UI_RESPONSE_DWZ_SUCCESS,
                "object_name": data['name']
            },
            status=UI_RESPONSE_DWZ_SUCCESS)
    else:
        return HttpResponse(
            {
                "form": form,
                "message": "",
                "statusCode": UI_RESPONSE_DWZ_ERROR
            },
            status=UI_RESPONSE_ERROR)
Beispiel #47
0
def get_network_info(request, tenant_id, network_id):
    """
    :param request:request object, tenant_id, network_id
    :return:view<'virtual_network_manage/networkinfo.html'>::get a network info
    """
    try:
        switch_tenants(request, tenant_id)
        network = api.quantum.network_get(request, network_id)
        network.set_id_as_name_if_empty(length=NETWORK_NAME_EMPTY_LENGTH)

        ports = api.quantum.port_list(request, network_id=network_id)

        for p in ports:
            p.set_id_as_name_if_empty()

        subnets = api.quantum.subnet_list(request, network_id=network.id)

        for s in subnets:
            s.set_id_as_name_if_empty()

        tenant_choices = []
        tenants = api.tenant_list_not_filter(request, admin=True)
        for tenant in tenants:
            tenant_choices.append((tenant.id, tenant.name))

        return shortcuts.render(
            request, 'virtual_network_manage/networkinfo.html', {
                'network': network,
                'subnets': subnets,
                "ports": ports,
                "tenants": tenant_choices
            })
    except Unauthorized:
        raise
    except Exception, exe:
        msg = 'get network info error.'
        LOG.error('get network info error,the error is %s' % exe.message)
        return HttpResponse(jsonutils.dumps(ui_response(message=msg)))