コード例 #1
0
ファイル: views.py プロジェクト: double-jia/Creeper
def allocate_ip_action(request, tenant_id):
    """
    :param request:request object,tenant_id
    :return:view<'virtual_address_manage/index_ip.html'>
    """
    form = AllocateIPForm(request, request.POST)
    if form.is_valid():
        data = form.cleaned_data
        switch_tenants(request, tenant_id)
        try:
            fip = api.network.tenant_floating_ip_allocate(request,
                                                          pool=data.get(
                                                              'pool', None))
        except Unauthorized:
            raise
        except LicenseForbidden:
            raise
        except Exception, exe:
            msg = 'Unable to allocate this ip pool.'
            LOG.error('Unable to allocate this ip pool.the error is %s ' %
                      exe.message)
            return HttpResponse(
                {
                    "message": msg,
                    "statusCode": UI_RESPONSE_DWZ_ERROR
                },
                status=UI_RESPONSE_ERROR)
        try:
            tenant_old = api.keystone.tenant_get(request,
                                                 tenant_id,
                                                 admin=True)
        except Unauthorized:
            raise
        except Exception, exe:
            LOG.error('get tenant error.the error is %s ' % exe.message)
コード例 #2
0
ファイル: views.py プロジェクト: wenjiajia/Creeper
def allocate_ip_action(request , tenant_id):
    """
    :param request:request object,tenant_id
    :return:view<'virtual_address_manage/index_ip.html'>
    """
    form =  AllocateIPForm(request , request.POST)
    if form.is_valid():
        data = form.cleaned_data
        switch_tenants(request , tenant_id)
        try:
            fip = api.network.tenant_floating_ip_allocate(request ,
                pool = data.get('pool' , None))
        except Unauthorized:
            raise
        except LicenseForbidden:
            raise
        except Exception , exe:
            msg = 'Unable to allocate this ip pool.'
            LOG.error('Unable to allocate this ip pool.the error is %s ' % exe.message)
            return HttpResponse({"message":msg , "statusCode":UI_RESPONSE_DWZ_ERROR} , status = UI_RESPONSE_ERROR)
        try:
            tenant_old = api.keystone.tenant_get(request , tenant_id , admin=True)
        except Unauthorized:
            raise
        except Exception , exe:
            LOG.error('get tenant error.the error is %s ' % exe.message)
コード例 #3
0
ファイル: views.py プロジェクト: double-jia/Creeper
def create_router_action_topology(request, tenant_id):
    switch_tenants(request, tenant_id)
    form = CreateRouterForm(request, request.POST)
    if form.is_valid():
        data = form.cleaned_data
        try:
            api.quantum.router_create(request, name=data['name'])

        except Unauthorized:
            raise
        except Exception, exc:
            msg = get_text('Failed to create router :%s.') % data['name']
            LOG.error('Failed to create router :%s,%s.' %
                      (data['name'], exc.message))
            return HttpResponse(
                {
                    "message": msg,
                    "statusCode": UI_RESPONSE_DWZ_ERROR
                },
                status=UI_RESPONSE_ERROR)
        msg = get_text('add router successfully!')

        return HttpResponse(
            {
                "message": msg,
                "statusCode": UI_RESPONSE_DWZ_SUCCESS,
                "object_name": data['name']
            },
            status=UI_RESPONSE_DWZ_SUCCESS)
コード例 #4
0
def delete_network_action(request, tenant_id, network_id):
    """
    :param request:request object, tenant_id, network_id
    :return:view<'virtual_network_manage/networkprojectindex.html'>::delete action of network
    """
    try:
        switch_tenants(request, tenant_id)
        network = api.quantum.network_get(request, network_id)
        api.quantum.network_delete(request, network_id)
    except Unauthorized:
        raise
    except Exception, exe:
        if exe.message.find(
                'There are one or more ports still in use on the network'
        ) != -1:
            msg = get_text(
                'Error! There are one or more ports still in use on the network.'
            )
        else:
            msg = 'Unable to delete network.'
        LOG.error('Unable to delete network,the error is %s' % exe.message)
        return HttpResponse(
            {
                "message": msg,
                "statusCode": UI_RESPONSE_DWZ_ERROR
            },
            status=UI_RESPONSE_ERROR)
コード例 #5
0
ファイル: views.py プロジェクト: wenjiajia/Creeper
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)))
コード例 #6
0
ファイル: views.py プロジェクト: wenjiajia/Creeper
def edit_network_action(request, tenant_id, network_id):
    """
    :param request:request object, tenant_id, network_id
    :return:view<'virtual_network_manage/networkprojectindex.html'>::edit actin for a network info
    """
    form = UpdateNetwork(request, tenant_id,network_id,request.POST)
    if form.is_valid():
        data = form.cleaned_data
        switch_tenants(request, tenant_id)
        try:
            params = {'name': data['name'],
                      'admin_state_up': data['admin_state'],
                      'shared': data['shared'],
                      'router:external': data['external']}
            api.quantum.network_modify(request, network_id,
                **params)
        except Unauthorized:
            raise
        except Exception , exe:
            msg = 'Failed to Update network'
            LOG.error("Failed to Update network,the error is %s" % exe.message)
            return HttpResponse({"message":msg, "statusCode":UI_RESPONSE_DWZ_ERROR}, status = UI_RESPONSE_ERROR)
        msg = get_text('Update network successfully!')

        return HttpResponse({"message":msg,
                             "statusCode":UI_RESPONSE_DWZ_SUCCESS ,
                             "object_name":data['name']}, status = UI_RESPONSE_DWZ_SUCCESS)
コード例 #7
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
コード例 #8
0
 def clean(self):
     data = super(forms.Form, self).clean()
     try:
         switch_tenants(self.request, data['tenant_id'])
         securitygroups = api.security_group_list(self.request)
     except Unauthorized:
         raise
     except Exception, ex:
         LOG.error(ex)
コード例 #9
0
ファイル: views.py プロジェクト: double-jia/Creeper
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)))
コード例 #10
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'}))
コード例 #11
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))
コード例 #12
0
ファイル: views.py プロジェクト: double-jia/Creeper
def fresh_progress_bar(request):
    tenant_id = None
    if request.GET.has_key('tenant_id'):
        tenant_id = request.GET['tenant_id']

    if tenant_id is not None:
        switch_tenants(request, tenant_id)

    try:
        usages = quotas.tenant_quota_usages(request)
    except Unauthorized:
        raise
    except Exception, ex:
        LOG.error("usages not found ,the error is %s" % ex)
        usages = None
コード例 #13
0
ファイル: forms.py プロジェクト: wenjiajia/Creeper
 def clean(self):
     data = super(forms.Form, self).clean()
     tenant_id = data.get('tenant_id', None)
     if 'flavor' in data:
         try:
             switch_tenants(self.request, tenant_id)
             usages = quotas.tenant_quota_usages(self.request)
         except Exception, e:
             LOG.error('can not get the usage info of tenant %s,%s' %
                       (tenant_id, e))
             return data
         if usages['instances']['used'] >= usages['instances']['quota']:
             msg = _(
                 "Exceed instances quotas of tenant,can not create instance!")
             raise ValidationError(msg)
コード例 #14
0
ファイル: views.py プロジェクト: wenjiajia/Creeper
def get_floating_ips_odd(request, tenant_id, floating_ip):
    """
    :param request:request object,tenant_id, floating_ip
    :return:view<'virtual_address_manage/floatingIpsIndex_ip.html'>::list of floatingip
    """
    float_ip = []
    floating_pool = {}
    floating_ips = None
    try:
        if None != switch_tenants(request , tenant_id):
            float_ip = api.tenant_floating_ip_list(request)
            floating_pools = api.network.floating_ip_pools_list(request)
            floating_pool = SortedDict([(pool.id , pool.name) for pool in
                                      floating_pools])

        for floating in float_ip:
            if floating.ip == floating_ip:
                floating_ips = floating
                break

        if floating_pool:
            floating_ips._apidict['pool'] = floating_pool.get(floating_ips.pool,
                                                        get_text("invalid ip pool"))
    except Unauthorized:
        raise
    except Exception , exe:
        LOG.exception("ClientException in floating ip index,the error is %s" % exe.message)
コード例 #15
0
ファイル: views.py プロジェクト: double-jia/Creeper
def create_volume_snapshot(request):
    snapshot_form = CreateVolumeSnapshot(request.POST.copy())
    msg = "Create Volume Snapshot Failed!"
    _status_code = UI_RESPONSE_DWZ_ERROR
    snapshot_name = ''
    if snapshot_form.is_valid():
        data = snapshot_form.cleaned_data
        snapshot_name = data['name']
        try:
            tenant_id = data['tenant_id']
            if switch_tenants(request, tenant_id) is not None:
                api.volume_snapshot_create(request, data['volume_id'],
                                           snapshot_name, data['description'])
                _status_code = UI_RESPONSE_DWZ_SUCCESS
                msg = "Create Volume Snapshot Successfully!"
        except Unauthorized:
            raise
        except LicenseForbidden:
            raise
        except Exception, ex:
            LOG.error("create volume snapshot %s" % ex)

            if ex.message.count(
                    "'NoneType' object has no attribute 'iteritems'") > 0:
                msg = get_text(
                    "Not enough server resources,Volume Snapshot %s has been created failed!"
                ) % snapshot_name
コード例 #16
0
ファイル: forms.py プロジェクト: double-jia/Creeper
 def clean(self):
     data = super(forms.Form, self).clean()
     tenant_id = data.get('tenant_id', None)
     if 'flavor' in data:
         try:
             switch_tenants(self.request, tenant_id)
             usages = quotas.tenant_quota_usages(self.request)
         except Exception, e:
             LOG.error('can not get the usage info of tenant %s,%s' %
                       (tenant_id, e))
             return data
         if usages['instances']['used'] >= usages['instances']['quota']:
             msg = _(
                 "Exceed instances quotas of tenant,can not create instance!"
             )
             raise ValidationError(msg)
コード例 #17
0
class CreateVirtualRouterPrepare(BasePrepare):
    """
     'TYPE_SECOND_CREATE_TENANT': {
        'title': 'Please create your first router and organizing the first gateway',
        'content': '',
        'work_func': '',
        'category': 'virtual_router_manage',
        'role' = 'ROLE_ADMIN',
        'tenant_id' = ''},
    """
    def update_status(self, request, tenant_id, parameters):
        tenants = []
        try:
            tenants = api.tenant_list(request, admin=True)
        except Exception, exc:
            msg = 'Unable to retrieve project list,%s.' % exc
            LOG.error(msg)
            return False
        router_projects = []
        for project in tenants:
            if project.enabled and None != switch_tenants(request, project.id):
                router_project_list = api.quantum.router_list(request)
                if router_project_list:
                    for routerProject in router_project_list:
                        if project.id == routerProject.tenant_id:
                            router_projects.append(routerProject)

        if len(router_projects) > 0:
            return True

        return False
コード例 #18
0
ファイル: views.py プロジェクト: double-jia/Creeper
def get_floating_ips_odd(request, tenant_id, floating_ip):
    """
    :param request:request object,tenant_id, floating_ip
    :return:view<'virtual_address_manage/floatingIpsIndex_ip.html'>::list of floatingip
    """
    float_ip = []
    floating_pool = {}
    floating_ips = None
    try:
        if None != switch_tenants(request, tenant_id):
            float_ip = api.tenant_floating_ip_list(request)
            floating_pools = api.network.floating_ip_pools_list(request)
            floating_pool = SortedDict([(pool.id, pool.name)
                                        for pool in floating_pools])

        for floating in float_ip:
            if floating.ip == floating_ip:
                floating_ips = floating
                break

        if floating_pool:
            floating_ips._apidict['pool'] = floating_pool.get(
                floating_ips.pool, get_text("invalid ip pool"))
    except Unauthorized:
        raise
    except Exception, exe:
        LOG.exception("ClientException in floating ip index,the error is %s" %
                      exe.message)
コード例 #19
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
コード例 #20
0
ファイル: views.py プロジェクト: wenjiajia/Creeper
def create_securitygrouprules_index(request, tenant_id, security_group_id):
    try:
        if None != switch_tenants(request, tenant_id):
            groups = api.security_group_list(request)
    except Unauthorized:
        raise
    except Exception, ex:
        groups = []
        LOG.error("Unable to retrieve security groups. The error is %s" % ex.message)
コード例 #21
0
ファイル: views.py プロジェクト: wenjiajia/Creeper
def delete_network_action(request, tenant_id, network_id):
    """
    :param request:request object, tenant_id, network_id
    :return:view<'virtual_network_manage/networkprojectindex.html'>::delete action of network
    """
    try:
        switch_tenants(request, tenant_id)
        network = api.quantum.network_get(request, network_id)
        api.quantum.network_delete(request, network_id)
    except Unauthorized:
        raise
    except Exception , exe:
        if exe.message.find('There are one or more ports still in use on the network') != -1:
            msg = get_text('Error! There are one or more ports still in use on the network.')
        else:
            msg = 'Unable to delete network.'
        LOG.error('Unable to delete network,the error is %s' % exe.message)
        return HttpResponse({ "message":msg, "statusCode":UI_RESPONSE_DWZ_ERROR }, status = UI_RESPONSE_ERROR)
コード例 #22
0
ファイル: views.py プロジェクト: double-jia/Creeper
def get_snapshot_index(request):
    snapshots = []
    tenants_dic = {}
    args = {}

    if request.GET.has_key('tenant_id'):
        tenant_id = request.GET['tenant_id']
        switch_tenants(request, tenant_id)
    else:
        tenant_id = None

    try:
        tenants = api.tenant_list(request,
                                  getattr(request.user, 'is_superuser', True))

        snapshots = api.volume_snapshot_list(request)

        volumes = api.volume_list(request)

        volumes_dic = SortedDict([(volume.id, volume) for volume in volumes])

        tenants_dic = SortedDict([(tenant.id, tenant.name)
                                  for tenant in tenants])

        for snapshot in snapshots:
            volume_name = None
            tenant_name = None
            try:
                volume_name = volumes_dic[snapshot.volume_id].display_name

                tenant_name = tenants_dic[snapshot.project_id]
            except Exception, ex:
                LOG.error("volume is not found the error is %s" % ex)
            setattr(snapshot, 'volume_name', volume_name)
            setattr(snapshot, 'project_name', tenant_name)
            setattr(snapshot, 'tenant_id', snapshot.project_id)
    except Unauthorized:
        raise
    except Exception, ex:
        LOG.error("snapshots is not found the error is %s" % ex)
コード例 #23
0
ファイル: views.py プロジェクト: double-jia/Creeper
def attach_volume_form(request, tenant_id, volume_id):
    instances = []
    try:
        if switch_tenants(request, tenant_id):
            instance_list = api.server_list(request)
            for instance in instance_list:
                if instance.status in ACTIVE_STATES:
                    instances.append((instance.id, '%s' % instance.name))
    except Unauthorized:
        raise
    except Exception, ex:
        instances = []
        LOG.error("Can not get instance list %s" % ex)
コード例 #24
0
def create_network_action(request, tenant_id):
    """
    :param request:request object, tenant_id
    :return:view<'virtual_network_manage/networkprojectindex.html'>::create action of network
    """
    form = CreateNetwork(request, tenant_id, request.POST)
    if form.is_valid():
        data = form.cleaned_data
        switch_tenants(request, tenant_id)
        try:
            params = {
                'name': data['name'],
                'tenant_id': data['tenant_id'],
                'admin_state_up': data['admin_state'],
                'shared': data['shared'],
                'router:external': data['external']
            }
            api.quantum.network_create(request, **params)
        except Unauthorized:
            raise
        except LicenseForbidden:
            raise
        except Exception, exe:
            msg = 'Failed to create network'
            LOG.error("Failed to create network,the error is %s" % exe.message)
            return HttpResponse(
                {
                    "message": msg,
                    "statusCode": UI_RESPONSE_DWZ_ERROR
                },
                status=UI_RESPONSE_ERROR)

        return HttpResponse(
            {
                "message": "Create network successfully!",
                "statusCode": UI_RESPONSE_DWZ_SUCCESS,
                "object_name": data['name']
            },
            status=UI_RESPONSE_DWZ_SUCCESS)
コード例 #25
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)))
コード例 #26
0
ファイル: views.py プロジェクト: wenjiajia/Creeper
def create_securitygroup_action(request, tenant_id):
    form = CreateSecurityGroupForm(request, request.POST)
    if form.is_valid():
        data = form.cleaned_data
        switch_tenants(request, tenant_id)
        try:
            api.security_group_create(request, data['name'],
                data['description'])
        except Unauthorized:
            raise
        except Exception, ex:
            msg = ' Unable to create security group.'
            LOG.error("the error is %s" % ex.message)
            if ex.message.count(
                u'Quota exceeded, too many security groups.') > 0:
                msg = 'Quota exceeded, too many security groups.'
            return HttpResponse(
                {"message": msg, "statusCode": UI_RESPONSE_DWZ_ERROR},
                status=UI_RESPONSE_ERROR)
        return HttpResponse({"message": "Create security group successfully!",
                             "statusCode": UI_RESPONSE_DWZ_SUCCESS,
                             "object_name": data['name']},
            status=UI_RESPONSE_DWZ_SUCCESS)
コード例 #27
0
ファイル: views.py プロジェクト: double-jia/Creeper
def get_routers_projects_list(request, tenant_id):
    """
    :param request:request object
    :return:view<'user_manage/index.html'>::list of users
    """
    args = {}
    resultrouterlist = []
    try:
        switch_tenants(request, tenant_id)
        routerprojectlist = api.quantum.router_list(request)

        for routerProject in routerprojectlist:
            if routerProject.tenant_id == tenant_id:

                resultrouterlist.append(routerProject)

                if routerProject.external_gateway_info:
                    ext_net_id = routerProject.external_gateway_info[
                        'network_id']
                    try:
                        ext_net = api.quantum.network_get(request,
                                                          ext_net_id,
                                                          expand_subnet=False)
                        ext_net.set_id_as_name_if_empty(length=0)
                        routerProject.external_gateway_info[
                            'network'] = ext_net.name

                    except Unauthorized:
                        raise
                    except Exception, exc:
                        msg = 'Unable to retrieve an external network %s.%s' % (
                            ext_net_id, exc)
                        LOG.error(msg)
                        routerProject.external_gateway_info[
                            'network'] = ext_net_id

        tenant_name = api.tenant_get(request, tenant_id, admin=True)
コード例 #28
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'}))
コード例 #29
0
ファイル: views.py プロジェクト: wenjiajia/Creeper
def get_floating_ips_list(request , tenant_id):
    """
    :param request:request object,tenant_id
    :return:view<'virtual_address_manage/floatingIpsIndex.html'>::list of floatingIp
    """
    args = {}
    floating_ips = []
    floating_pool = {}
    floatingips = []
    try:
        if None != switch_tenants(request , tenant_id):
            floating_ips = api.network.tenant_floating_ip_list(request)
            floating_pools = api.network.floating_ip_pools_list(request)
            floating_pool = SortedDict([(pool.id , pool.name) for pool in
                                      floating_pools])


        for floating_ip in floating_ips:
            if tenant_id == floating_ip.tenant_id :
                floating_ip._apidict['pool'] = floating_pool.get(floating_ip.pool,
                                                                get_text("invalid ip pool"))
                floatingips.append(floating_ip)

        instances = []
        tenant_quota = api.nova.nova_tenant_quota_get(request , tenant_id)
        for item in tenant_quota:
            if item.name == "floating_ips":
                ip_num = item.limit
        servers = api.server_list(request)
        for server in servers:
        # to be removed when nova can support unique names
            server_name = server.name
            if any(s.id != server.id and
                   s.name == server.name for s in servers):
                # duplicate instance name
                server_name = "%s [%s]" % (server.name, server.id)
            instances.append((server.id , server_name))
    except Unauthorized:
        raise
    except Exception , exe:
        LOG.exception("ClientException in floating ip index,the error is %s "
                      % exe.message)
コード例 #30
0
ファイル: views.py プロジェクト: wenjiajia/Creeper
def get_securitygroup_list(request, tenant_id):
    """
    :param request:request object
    :return:view<'user_manage/index.html'>::list of users
    """
    args = {}
    securitygroups = []
    tenant_choices = []
    try:
        if None != switch_tenants(request, tenant_id):
            securitygroups = api.security_group_list(request)

        tenants = api.tenant_list_not_filter(request, admin=True)
        for tenant in tenants:
            tenant_choices.append((tenant.id, tenant.name))
    except Unauthorized:
        raise
    except Exception, ex:
        msg = 'Unable to retrieve security group list.%s' % ex
        LOG.error(msg)
コード例 #31
0
ファイル: views.py プロジェクト: double-jia/Creeper
def get_floating_ips_list(request, tenant_id):
    """
    :param request:request object,tenant_id
    :return:view<'virtual_address_manage/floatingIpsIndex.html'>::list of floatingIp
    """
    args = {}
    floating_ips = []
    floating_pool = {}
    floatingips = []
    try:
        if None != switch_tenants(request, tenant_id):
            floating_ips = api.network.tenant_floating_ip_list(request)
            floating_pools = api.network.floating_ip_pools_list(request)
            floating_pool = SortedDict([(pool.id, pool.name)
                                        for pool in floating_pools])

        for floating_ip in floating_ips:
            if tenant_id == floating_ip.tenant_id:
                floating_ip._apidict['pool'] = floating_pool.get(
                    floating_ip.pool, get_text("invalid ip pool"))
                floatingips.append(floating_ip)

        instances = []
        tenant_quota = api.nova.nova_tenant_quota_get(request, tenant_id)
        for item in tenant_quota:
            if item.name == "floating_ips":
                ip_num = item.limit
        servers = api.server_list(request)
        for server in servers:
            # to be removed when nova can support unique names
            server_name = server.name
            if any(s.id != server.id and s.name == server.name
                   for s in servers):
                # duplicate instance name
                server_name = "%s [%s]" % (server.name, server.id)
            instances.append((server.id, server_name))
    except Unauthorized:
        raise
    except Exception, exe:
        LOG.exception("ClientException in floating ip index,the error is %s " %
                      exe.message)
コード例 #32
0
ファイル: views.py プロジェクト: double-jia/Creeper
def get_project_summary(request):
    project_summary = {}
    INSTANCE_ON_STATUS = ('active', )
    try:
        projects = api.tenant_list(request, admin=True)
        for project in projects:
            if not project.enabled:
                continue

            users = api.user_list(request, project.id)
            networks = api.network_list_for_tenant(request, project.id)

            instance_on_cnt = 0
            instance_off_cnt = 0
            instances = []
            if switch_tenants(request, project.id):
                instances = api.server_list(request)

            for instance in instances:
                if instance.status.lower() in INSTANCE_ON_STATUS:
                    instance_on_cnt += 1
                else:
                    instance_off_cnt += 1

            summary = {
                'project_name': project.name,
                'user_cnt': len(users),
                'network_cnt': len(networks),
                'instance_on_cnt': instance_on_cnt,
                'instance_off_cnt': instance_off_cnt
            }

            project_summary[project.id] = summary
    except Unauthorized:
        raise
    except Exception, e:
        LOG.error(e)
コード例 #33
0
ファイル: forms.py プロジェクト: wenjiajia/Creeper
                if flavor_id is not None and flavor_id.disk < int(
                    data['min_disk']):
                    msg = 'Instance flavor disk less-than Image min disk!'
                    raise ValidationError(_(msg))
                if flavor_id is not None and flavor_id.ram < int(
                    data['min_ram']):
                    msg = 'Instance flavor ram less-than Image min ram!'
                    raise ValidationError(_(msg))
            except Unauthorized:
                raise
            except Exception, e:
                LOG.error('can not get the usage info of tenant %s,%s' %
                          (tenant_id, e))
                return data
        try:
            switch_tenants(self.request, tenant_id)
            usages = quotas.tenant_quota_usages(self.request)
        except Exception, e:
            LOG.error(
                'can not get the usage info of tenant %s,%s' % (tenant_id, e))
            return data
        if usages['instances']['used'] >= usages['instances']['quota']:
            msg = _(
                "Exceed instances quotas of tenant,can not create instance!")
            raise ValidationError(msg)

        return data

#class CreateImageAndLaunchForm(forms.Form):
#    name = forms.CharField(max_length=50, label=_("Name"), required=False)
#    u_uid = forms.CharField(max_length=100, label=_("Uuid"))
コード例 #34
0
ファイル: views.py プロジェクト: double-jia/Creeper
                        flavor_id = instance_obj.flavor['id']
                        for flavor in flavors:
                            if flavor.id == flavor_id:
                                cores_used = cores_used + flavor.vcpus
                                ram_used = ram_used + flavor.ram
                                gigabytes_used = gigabytes_used + flavor.disk
                        try:
                            intance_volumes = api.nova.instance_volumes_list(
                                request, instance_obj.id)
                            volumes_used += len(intance_volumes)
                        except Exception, e:
                            msg = 'Can not found instance (%s) , error is %s.' % (
                                instance_obj.id, e.message)
                            LOG.error(msg)
            try:
                if project.enabled and None != switch_tenants(
                        request, tenant_id):
                    floating_ipsObj = api.network.tenant_floating_ip_list(
                        request)
                    for floating_ipObj in floating_ipsObj:
                        if floating_ipObj.instance_id != None and floating_ipObj.tenant_id == tenant_id:
                            floating_ips_used += 1
            except Unauthorized:
                raise
            except Exception, e:
                floating_ips_used = 0
                LOG.exception("ClientException in floating ip index")
                LOG.error('error is %s.' % e.message)

            project_resource = {
                'project_name': project_name,
                'cores': cores,
コード例 #35
0
ファイル: forms.py プロジェクト: double-jia/Creeper
                if flavor_id is not None and flavor_id.disk < int(
                        data['min_disk']):
                    msg = 'Instance flavor disk less-than Image min disk!'
                    raise ValidationError(_(msg))
                if flavor_id is not None and flavor_id.ram < int(
                        data['min_ram']):
                    msg = 'Instance flavor ram less-than Image min ram!'
                    raise ValidationError(_(msg))
            except Unauthorized:
                raise
            except Exception, e:
                LOG.error('can not get the usage info of tenant %s,%s' %
                          (tenant_id, e))
                return data
        try:
            switch_tenants(self.request, tenant_id)
            usages = quotas.tenant_quota_usages(self.request)
        except Exception, e:
            LOG.error('can not get the usage info of tenant %s,%s' %
                      (tenant_id, e))
            return data
        if usages['instances']['used'] >= usages['instances']['quota']:
            msg = _(
                "Exceed instances quotas of tenant,can not create instance!")
            raise ValidationError(msg)

        return data


#class CreateImageAndLaunchForm(forms.Form):
#    name = forms.CharField(max_length=50, label=_("Name"), required=False)
コード例 #36
0
ファイル: views.py プロジェクト: double-jia/Creeper
        tenants = api.tenant_list(request,
                                  getattr(request.user, 'is_superuser', True))
    except Unauthorized:
        raise
    except Exception, ex:
        LOG.error('tenants not found,the error is %s' % ex)
        tenants = []

    tenants_dic = SortedDict([(tenant.id, getattr(tenant, "name"))
                              for tenant in tenants if tenant.enabled])

    current_tenant = getattr(request.user, 'tenant_id', None)

    try:
        if tenant_id != 'tenant':
            if switch_tenants(request, tenant_id):
                usages = quotas.tenant_quota_usages(request)
        else:
            usages = quotas.tenant_quota_usages(request)
    except Unauthorized:
        raise
    except Exception, ex:
        LOG.error("usages not found ,the error is %s" % ex)
        usages = None

    snapshots = []
    if snapshot_id == vu.uuid:
        snapshot = None
        snapshots = []
        try:
            if switch_tenants(request, current_tenant):
コード例 #37
0
def get_authorized_instances(request, tenant_id):
    instances = None
    if switch_tenants(request, tenant_id):
        instances = server_list(request)
    return instances
コード例 #38
0
ファイル: views.py プロジェクト: wenjiajia/Creeper
def get_securitygroup_ips_list(request):
    """
    :param request:request object
    :return:json :the tree of floatingip
    """
    project_menus = []
    projects = []
    try:
        projects = api.tenant_list(request, admin=True)
    except Unauthorized:
        raise
    except Exception , exe:
        LOG.error('Unable to retrieve project list,%s.' % exe)
    for project in projects:
        project_floating_ips = []
        if project.enabled and None != switch_tenants(request , project.id):
            floating_ips = api.tenant_floating_ip_list(request)
            if floating_ips:
                for floating in floating_ips:
                    if floating.tenant_id == project.id:
                        floating_obj = {
                            'floating_ip':floating.ip,
                            'floating_id':floating.id
                        }
                        project_floating_ips.append(floating_obj)
        project_menu = {
            'project_name': project.name,
            'project_id': project.id,
            'project_enabled': project.enabled,
            'project_floating': project_floating_ips
        }
コード例 #39
0
def create_instance_thread(self, image_instance_status_thr, img_status):
    user_id = None
    dist_user_id = None
    if 'user' in self.request.POST:
        user_id = self.request.POST['user']
    if self.data[
       'name_launch'] != ''  and img_status.status == UI_IMAGE_STATUS_ACTIVE:
        image_instance_status_thr.status = UI_CREATE_PER_INSTANCE_CREATING
        image_instance_status_thr.save()
        try:
            instance = None
            if len(self.data['volume']) > PARAMETER_NUMBER_ZERO:
                if self.data['delete_on_terminate']:
                    delete_on_terminate = PARAMETER_NUMBER_ONE
                else:
                    delete_on_terminate = PARAMETER_NUMBER_ZERO
                dev_mapping = {self.data['device_name']: (
                    "%s::%s" % (self.data['volume'], delete_on_terminate))}
            else:
                dev_mapping = None
            networks = self.data['networks']
            if networks:
                nic_s = [{"net-id": net_id, "v4-fixed-ip": ""}
                         for net_id in networks]
            else:
                nic_s = None

            switch_tenants(self.request, self.data['tenant_id'])
            instance_test = api.server_create(self.request,
                                              dist_user_id,
                                              self.data['name_launch'],
                                              img_status.id,
                                              self.data['flavor'],
                                              self.data.get('keypair'),
                                              normalize_newlines(
                                                  self.data.get('user_data')),
                                              self.data.get('security_groups'),
                                              dev_mapping, nics=nic_s,
                                              instance_count=self.data.get(
                                                  'count'))
            if user_id:
                if Distribution.objects.filter(
                    user_id=user_id).count() >= INSTANCE_LIMIT_PER_USER:
                    _msg = _("Current user's instances reach limit %d.") % (
                        INSTANCE_LIMIT_PER_USER)
                else:
                    _relationship = Distribution(instance_id=instance_test.id,
                                                 user_id=user_id)
                    try:
                        _relationship.save()
                    except Exception, e:
                        LOG.error(
                            'create instance-user relationship failed.%s' % e)
                        _msg = 'Can not create instance-user relationship.'
#            if_con = UI_CYCLE_IMG_INSTANCE_TIME
#            while if_con > PARAMETER_NUMBER_ZERO:
#                instance = api.server_get(self.request, instance_test.id)
#                if_con -= PARAMETER_NUMBER_ONE
#                if instance.status == UI_INSTANCE_STATUS_ACTIVE:
#                    if_con = PARAMETER_NEGATIVE_ONE
#                    image_instance_status_thr.instance_id = instance.id
#                    image_instance_status_thr.save()
#                    break
#                if instance.status == UI_INSTANCE_STATUS_ERROR:
#                    if_con = PARAMETER_NEGATIVE_TWO
#                    break
#                if instance.status == UI_INSTANCE_STATUS_RESOURCE_IS_NOT_ENOUGH:
#                    if_con = PARAMETER_NEGATIVE_THREE
#                    break
#                time.sleep(TIME_CHECK_PER_IMAGE_STATUS_SECONDS)

#            if PARAMETER_NEGATIVE_THREE == if_con:
#                try:
#                    image = api.glance.image_get(self.request, img_status.id)
#                    image.delete()
#                except Unauthorized:
#                    raise
#                except Exception, exc:
#                    msg = _('Can not delete image !')
#                    LOG.error('%s,%s' % (msg, exc))
#                image_instance_status_thr.status = UI_INSTANCE_RESOURCE_NOT_ENOUGH
#                image_instance_status_thr.save()
#                return None

#            if PARAMETER_NEGATIVE_TWO == if_con:
#                try:
#                    image = api.glance.image_get(self.request, img_status.id)
#                    image.delete()
#                except Unauthorized:
#                    raise
#                except Exception, exc:
#                    msg = _('Can not delete image !')
#                    LOG.error('%s,%s' % (msg, exc))
#                image_instance_status_thr.status = UI_CREATE_PER_INSTANCE_FAILED
#                image_instance_status_thr.save()
#                return None

#            if PARAMETER_NEGATIVE_ONE != if_con:
#                image_instance_status_thr.status = UI_CREATE_PER_INSTANCE_TIMEOUT
#                image_instance_status_thr.save()
#                return None
            if instance_test == True:
                image_instance_status_thr.status = UI_CREATE_PER_INSTANCE_CREATED
#            image_instance_status_thr.instance_id = instance_test.id
                image_instance_status_thr.save()
                LOG.info('Instance "%s" has submit to check.' % self.data["name"])
            else:
                image_instance_status_thr.status = UI_CREATE_IMAGE_AND_INSTANCE_FAILED
                image_instance_status_thr.save()
#            return instance
        except Unauthorized:
            raise
コード例 #40
0
ファイル: utils.py プロジェクト: wenjiajia/Creeper
def get_authorized_instances(request, tenant_id):
    instances = None
    if switch_tenants(request, tenant_id):
        instances = server_list(request)
    return instances