예제 #1
0
def create_security_group(context, group_name, group_description,
                          vpc_id=None):
    if group_name == DEFAULT_GROUP_NAME:
        if vpc_id:
            raise exception.InvalidParameterValue(
                _('Cannot use reserved security group name: %s')
                % DEFAULT_GROUP_NAME)
        else:
            raise exception.InvalidGroupReserved(group_name=group_name)
    filter = [{'name': 'group-name',
               'value': [group_name]}]
    if not vpc_id and CONF.disable_ec2_classic:
        vpc_id = ec2utils.get_default_vpc(context)['id']
    if vpc_id and group_name != vpc_id:
        filter.append({'name': 'vpc-id',
                       'value': [vpc_id]})
    security_groups = describe_security_groups(
        context, filter=filter)['securityGroupInfo']
    if not vpc_id:
        # TODO(andrey-mp): remove it when fitering by None will be implemented
        security_groups = [sg for sg in security_groups
                           if sg.get('vpcId') is None]
    if security_groups:
        raise exception.InvalidGroupDuplicate(name=group_name)
    return _create_security_group(context, group_name, group_description,
                                  vpc_id)
def create_security_group(context, group_name, group_description, vpc_id=None):
    nova = clients.nova(context)
    if vpc_id and group_name != vpc_id:
        security_groups = describe_security_groups(context,
                                                   filter=[{
                                                       'name': 'vpc-id',
                                                       'value': [vpc_id]
                                                   }, {
                                                       'name':
                                                       'group-name',
                                                       'value': [group_name]
                                                   }])['securityGroupInfo']
        if security_groups:
            raise exception.InvalidGroupDuplicate(name=group_name)
    with common.OnCrashCleaner() as cleaner:
        try:
            # TODO(Alex): Shouldn't allow creation of groups with existing
            # name if in the same VPC or in EC2-Classic.
            os_security_group = nova.security_groups.create(
                group_name, group_description)
        except nova_exception.OverLimit:
            raise exception.ResourceLimitExceeded(resource='security groups')
        cleaner.addCleanup(nova.security_groups.delete, os_security_group.id)
        if vpc_id:
            # NOTE(Alex) Check if such vpc exists
            ec2utils.get_db_item(context, vpc_id)
            security_group = db_api.add_item(context, 'sg', {
                'vpc_id': vpc_id,
                'os_id': os_security_group.id
            })
            return {'return': 'true', 'groupId': security_group['id']}
    return {'return': 'true'}