示例#1
0
 def test_get_by_project(self):
     self.mox.StubOutWithMock(db, "security_group_get_by_project")
     db.security_group_get_by_project(self.context, "fake-project").AndReturn(fake_secgroups)
     self.mox.ReplayAll()
     secgroup_list = security_group.SecurityGroupList.get_by_project(self.context, "fake-project")
     for i in range(len(fake_secgroups)):
         self.assertIsInstance(secgroup_list[i], security_group.SecurityGroup)
         self.assertEqual(fake_secgroups[i]["id"], secgroup_list[i]["id"])
示例#2
0
 def test_get_by_project(self):
     self.mox.StubOutWithMock(db, 'security_group_get_by_project')
     db.security_group_get_by_project(
         self.context, 'fake-project').AndReturn(fake_secgroups)
     self.mox.ReplayAll()
     secgroup_list = security_group.SecurityGroupList.get_by_project(
         self.context, 'fake-project')
     for i in range(len(fake_secgroups)):
         self.assertTrue(
             isinstance(secgroup_list[i], security_group.SecurityGroup))
         self.assertEqual(fake_secgroups[i]['id'], secgroup_list[i]['id'])
 def test_get_by_project(self):
     self.mox.StubOutWithMock(db, 'security_group_get_by_project')
     db.security_group_get_by_project(self.context,
                                      'fake-project').AndReturn(
                                          fake_secgroups)
     self.mox.ReplayAll()
     secgroup_list = security_group.SecurityGroupList.get_by_project(
         self.context, 'fake-project')
     for i in range(len(fake_secgroups)):
         self.assertTrue(isinstance(secgroup_list[i],
                                    security_group.SecurityGroup))
         self.assertEqual(fake_secgroups[i]['id'],
                          secgroup_list[i]['id'])
示例#4
0
    def index(self, req):
        context = req.environ["nova.context"]
        self.compute_api.ensure_default_security_group(context)
        groups = db.security_group_get_by_project(context, context.project_id)
        groups = [self._format_security_group(context, g) for g in groups]

        return {"security_groups": list(sorted(groups, key=lambda k: (k["tenant_id"], k["name"])))}
示例#5
0
    def _refresh_security_mixins(self, extras):
        """
        Registers security groups as security mixins
        """
        # ensures that preexisting openstack security groups are
        # added and only once.
        # collect these and add them to an exclusion list so they're
        # not created again when listing non-user-defined sec. groups
        excld_grps = []
        for cat in self.registry.get_categories(extras):
            if (isinstance(cat, core_model.Mixin) and
                    os_addon.SEC_GROUP in cat.related):
                excld_grps.append(cat.term)

        groups = db.security_group_get_by_project(extras['nova_ctx'],
                                                  extras['nova_'
                                                         'ctx'].project_id)
        sec_grp = 'http://schemas.openstack.org/infrastructure/security/group#'

        for group in groups:
            if group['name'] not in excld_grps:
                sec_mix = os_mixins.UserSecurityGroupMixin(
                    term=str(group["id"]),
                    scheme=sec_grp,
                    related=[os_addon.SEC_GROUP],
                    attributes=None,
                    title=group['name'],
                    location='/security/' + quote(str(group['name'])) + '/')
                try:
                    self.registry.get_backend(sec_mix, extras)
                except AttributeError:
                    self.register_backend(sec_mix, MIXIN_BACKEND)
示例#6
0
    def _refresh_security_mixins(self, extras):
        """
        Registers security groups as security mixins
        """
        # ensures that preexisting openstack security groups are
        # added and only once.
        # collect these and add them to an exclusion list so they're
        # not created again when listing non-user-defined sec. groups
        excld_grps = []
        for cat in self.registry.get_categories(extras):
            if (isinstance(cat, core_model.Mixin)
                    and os_addon.SEC_GROUP in cat.related):
                excld_grps.append(cat.term)

        groups = db.security_group_get_by_project(
            extras['nova_ctx'], extras['nova_'
                                       'ctx'].project_id)
        sec_grp = 'http://schemas.openstack.org/infrastructure/security/group#'

        for group in groups:
            if group['name'] not in excld_grps:
                sec_mix = os_mixins.UserSecurityGroupMixin(
                    term=str(group["id"]),
                    scheme=sec_grp,
                    related=[os_addon.SEC_GROUP],
                    attributes=None,
                    title=group['name'],
                    location='/security/' + quote(str(group['name'])) + '/')
                try:
                    self.registry.get_backend(sec_mix, extras)
                except AttributeError:
                    self.register_backend(sec_mix, MIXIN_BACKEND)
示例#7
0
 def scrub(self, project_id):
     """Deletes data associated with project."""
     admin_context = context.get_admin_context()
     networks = db.project_get_networks(admin_context, project_id)
     for network in networks:
         db.network_disassociate(admin_context, network['id'])
     groups = db.security_group_get_by_project(admin_context, project_id)
     for group in groups:
         db.security_group_destroy(admin_context, group['id'])
示例#8
0
    def index(self, req):
        context = req.environ['nova.context']
        self.compute_api.ensure_default_security_group(context)
        groups = db.security_group_get_by_project(context,
                                                  context.project_id)
        groups = [self._format_security_group(context, g) for g in groups]

        return {'security_groups':
                list(sorted(groups,
                            key=lambda k: (k['tenant_id'], k['name'])))}
示例#9
0
    def index(self, req):
        """Returns a list of security groups"""
        context = req.environ["nova.context"]
        authorize(context)

        self.compute_api.ensure_default_security_group(context)
        groups = db.security_group_get_by_project(context, context.project_id)
        limited_list = common.limited(groups, req)
        result = [self._format_security_group(context, group) for group in limited_list]

        return {"security_groups": list(sorted(result, key=lambda k: (k["tenant_id"], k["name"])))}
示例#10
0
    def index(self, req):
        context = req.environ['nova.context']
        self.compute_api.ensure_default_security_group(context)
        if context.is_admin:
            groups = db.security_group_get_all(context)
        else:
            groups = db.security_group_get_by_project(context,
                                                      context.project_id)
        groups = [self._format_security_group(context, g) for g in groups]

        return {'security_groups':
                list(sorted(groups,
                            key=lambda k: (k['tenant_id'], k['name'])))}
示例#11
0
    def index(self, req):
        """Returns a list of security groups"""
        context = req.environ['nova.context']

        self.compute_api.ensure_default_security_group(context)
        groups = db.security_group_get_by_project(context,
                                                  context.project_id)
        limited_list = common.limited(groups, req)
        result = [self._format_security_group(context, group)
                     for group in limited_list]

        return {'security_groups':
                list(sorted(result,
                            key=lambda k: (k['tenant_id'], k['name'])))}
示例#12
0
    def describe_security_groups(self, context, group_name=None, **kwargs):
        self.compute_api.ensure_default_security_group(context)
        if context.is_admin:
            groups = db.security_group_get_all(context)
        else:
            groups = db.security_group_get_by_project(context,
                                                      context.project_id)
        groups = [self._format_security_group(context, g) for g in groups]
        if not group_name is None:
            groups = [g for g in groups if g.name in group_name]

        return {'securityGroupInfo':
                list(sorted(groups,
                            key=lambda k: (k['ownerId'], k['groupName'])))}
def fix_usage(cntxt, tenant):

    # Get per-user data for this tenant since usage is now per-user
    filter_object = {'project_id': tenant}
    instance_info = db.instance_get_all_by_filters(cntxt, filter_object)

    usage_by_resource = {}
    #resource_types = ['instances', 'cores', 'ram', 'security_groups']
    states_to_ignore = ['error', 'deleted', 'building']

    for instance in instance_info:
        user = instance['user_id']
        # We need to build a list of users who have launched vm's even if the user
        # no longer exists. We can't use keystone here.
        if not usage_by_resource.has_key(user):
            usage_by_resource[user] = {
            }  # Record that this user has once used resources
        if not instance['vm_state'] in states_to_ignore:
            user_resource = usage_by_resource[user]
            user_resource['instances'] = user_resource.get('instances', 0) + 1
            user_resource['cores'] = user_resource.get('cores',
                                                       0) + instance['vcpus']
            user_resource['ram'] = user_resource.get('ram',
                                                     0) + instance['memory_mb']

    secgroup_list = db.security_group_get_by_project(cntxt, tenant)
    for group in secgroup_list:
        user = group.user_id
        if not usage_by_resource.has_key(user):
            usage_by_resource[user] = {
            }  # Record that this user has once used resources
        user_resource = usage_by_resource[user]
        user_resource['security_groups'] = user_resource.get(
            'security_groups', 0) + 1

    # Correct the quota usage in the database
    for user in usage_by_resource:
        for resource in resource_types:
            usage = usage_by_resource[user].get(resource, 0)
            try:
                db.quota_usage_update(cntxt,
                                      tenant,
                                      user,
                                      resource,
                                      in_use=usage)
            except exception.QuotaUsageNotFound as e:
                print e
                print 'db.quota_usage_update(cntxt, %s, %s, %s, in_use=%s)' % \
                      (tenant, user, resource, usage)
示例#14
0
    def describe_security_groups(self, context, group_name=None, **kwargs):
        self.compute_api.ensure_default_security_group(context)
        if group_name:
            groups = []
            for name in group_name:
                group = db.security_group_get_by_name(context,
                                                      context.project_id, name)
                groups.append(group)
        elif context.is_admin:
            groups = db.security_group_get_all(context)
        else:
            groups = db.security_group_get_by_project(context,
                                                      context.project_id)
        groups = [self._format_security_group(context, g) for g in groups]

        return {
            'securityGroupInfo':
            list(sorted(groups, key=lambda k: (k['ownerId'], k['groupName'])))
        }
def fix_usage(cntxt, tenant):

    # Get per-user data for this tenant since usage is now per-user
    filter_object = {'project_id': tenant}
    instance_info = db.instance_get_all_by_filters(cntxt, filter_object)

    usage_by_resource = {}
    #resource_types = ['instances', 'cores', 'ram', 'security_groups']
    states_to_ignore = ['error', 'deleted', 'building']

    for instance in instance_info:
        user = instance['user_id']
        # We need to build a list of users who have launched vm's even if the user
        # no longer exists. We can't use keystone here.
        if not usage_by_resource.has_key(user):
            usage_by_resource[user] = {} # Record that this user has once used resources
        if not instance['vm_state'] in states_to_ignore:
            user_resource = usage_by_resource[user]
            user_resource['instances'] = user_resource.get('instances', 0) + 1
            user_resource['cores'] = user_resource.get('cores', 0) + instance['vcpus']
            user_resource['ram'] = user_resource.get('ram', 0) + instance['memory_mb']

    secgroup_list = db.security_group_get_by_project(cntxt, tenant)
    for group in secgroup_list:
        user = group.user_id
        if not usage_by_resource.has_key(user):
            usage_by_resource[user] = {} # Record that this user has once used resources
        user_resource = usage_by_resource[user]
        user_resource['security_groups'] = user_resource.get('security_groups', 0) + 1

    # Correct the quota usage in the database
    for user in usage_by_resource:
        for resource in resource_types:
            usage = usage_by_resource[user].get(resource, 0)
            try:
                db.quota_usage_update(cntxt, tenant, user, resource, in_use=usage)
            except exception.QuotaUsageNotFound as e:
                print e
                print 'db.quota_usage_update(cntxt, %s, %s, %s, in_use=%s)' % \
                      (tenant, user, resource, usage)
def get_actual_usage(cntxt, tenant):
    filter_object = {'deleted': '', 'project_id': tenant}
    instances = db.instance_get_all_by_filters(cntxt, filter_object)

    # calculate actual usage
    actual_instance_count = len(instances)
    actual_core_count = 0
    actual_ram_count = 0

    for instance in instances:
        actual_core_count += instance['vcpus']
        actual_ram_count += instance['memory_mb']

    actual_secgroup_count = len(db.security_group_get_by_project(
        cntxt, tenant))
    if actual_secgroup_count == 0:
        actual_secgroup_count = 1  # Every tenant uses quota for default security group

    return OrderedDict(
        (("actual_instance_count",
          actual_instance_count), ("actual_core_count", actual_core_count),
         ("actual_ram_count", actual_ram_count), ("actual_secgroup_count",
                                                  actual_secgroup_count)))
def get_actual_usage(cntxt, tenant):
    filter_object = {'deleted': '',
                     'project_id': tenant}
    instances = db.instance_get_all_by_filters(cntxt, filter_object)

    # calculate actual usage
    actual_instance_count = len(instances)
    actual_core_count = 0
    actual_ram_count = 0

    for instance in instances:
        actual_core_count += instance['vcpus']
        actual_ram_count += instance['memory_mb']

    actual_secgroup_count = len(db.security_group_get_by_project(cntxt, tenant))
    if actual_secgroup_count == 0:
        actual_secgroup_count = 1 # Every tenant uses quota for default security group

    return OrderedDict((
        ("actual_instance_count", actual_instance_count),
        ("actual_core_count", actual_core_count),
        ("actual_ram_count", actual_ram_count),
        ("actual_secgroup_count", actual_secgroup_count)
    ))
示例#18
0
 def get_by_project(cls, context, project_id):
     return _make_secgroup_list(context, cls(),
                                db.security_group_get_by_project(
                                    context, project_id))
示例#19
0
 def get_by_project(cls, context, project_id):
     groups = db.security_group_get_by_project(context, project_id)
     return base.obj_make_list(context, cls(context), objects.SecurityGroup,
                               groups)
示例#20
0
 def get_by_project(cls, context, project_id):
     return _make_secgroup_list(context, cls(),
                                db.security_group_get_by_project(
                                    context, project_id))
示例#21
0
 def get_by_project(cls, context, project_id):
     groups = db.security_group_get_by_project(context, project_id)
     return base.obj_make_list(context, cls(context),
                               objects.SecurityGroup, groups)