<commit_before># Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""The security groups extension."""

import netaddr
import urllib
from webob import exc
import webob

from nova import compute
from nova import db
from nova import exception
from nova import flags
from nova import log as logging
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi


from xml.dom import minidom


LOG = logging.getLogger("nova.api.contrib.security_groups")
FLAGS = flags.FLAGS


class SecurityGroupController(object):
    """The Security group API controller for the OpenStack API."""

    def __init__(self):
        self.compute_api = compute.API()
        super(SecurityGroupController, self).__init__()

    def _format_security_group_rule(self, context, rule):
        sg_rule = {}
        sg_rule['id'] = rule.id
        sg_rule['parent_group_id'] = rule.parent_group_id
        sg_rule['ip_protocol'] = rule.protocol
        sg_rule['from_port'] = rule.from_port
        sg_rule['to_port'] = rule.to_port
        sg_rule['group'] = {}
        sg_rule['ip_range'] = {}
        if rule.group_id:
            source_group = db.security_group_get(context, rule.group_id)
            sg_rule['group'] = {'name': source_group.name,
                             'tenant_id': source_group.project_id}
        else:
            sg_rule['ip_range'] = {'cidr': rule.cidr}
        return sg_rule

    def _format_security_group(self, context, group):
        security_group = {}
        security_group['id'] = group.id
        security_group['description'] = group.description
        security_group['name'] = group.name
        security_group['tenant_id'] = group.project_id
        security_group['rules'] = []
        for rule in group.rules:
            security_group['rules'] += [self._format_security_group_rule(
                    context, rule)]
        return security_group

    def show(self, req, id):
        """Return data about the given security group."""
        context = req.environ['nova.context']
        try:
            id = int(id)
            security_group = db.security_group_get(context, id)
        except ValueError:
            msg = _("Security group id is not integer")
            return exc.HTTPBadRequest(explanation=msg)
        except exception.NotFound as exp:
            return exc.HTTPNotFound(explanation=unicode(exp))

        return {'security_group': self._format_security_group(context,
                                                              security_group)}

    def delete(self, req, id):
        """Delete a security group."""
        context = req.environ['nova.context']
        try:
            id = int(id)
            security_group = db.security_group_get(context, id)
        except ValueError:
            msg = _("Security group id is not integer")
            return exc.HTTPBadRequest(explanation=msg)
        except exception.SecurityGroupNotFound as exp:
            return exc.HTTPNotFound(explanation=unicode(exp))

        LOG.audit(_("Delete security group %s"), id, context=context)
        db.security_group_destroy(context, security_group.id)

        return exc.HTTPAccepted()

    def index(self, req):
        """Returns a list of security groups"""
        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)

        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'])))}

    def create(self, req, body):
        """Creates a new security group."""
        context = req.environ['nova.context']
        if not body:
            return exc.HTTPUnprocessableEntity()

        security_group = body.get('security_group', None)

        if security_group is None:
            return exc.HTTPUnprocessableEntity()

        group_name = security_group.get('name', None)
        group_description = security_group.get('description', None)

        self._validate_security_group_property(group_name, "name")
        self._validate_security_group_property(group_description,
                                               "description")
        group_name = group_name.strip()<commit_msg>List security groups project wise for admin users same as other users<commit_after># Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""The security groups extension."""

import netaddr
import urllib
from webob import exc
import webob

from nova import compute
from nova import db
from nova import exception
from nova import flags
from nova import log as logging
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi


from xml.dom import minidom


LOG = logging.getLogger("nova.api.contrib.security_groups")
FLAGS = flags.FLAGS


class SecurityGroupController(object):
    """The Security group API controller for the OpenStack API."""

    def __init__(self):
        self.compute_api = compute.API()
        super(SecurityGroupController, self).__init__()

    def _format_security_group_rule(self, context, rule):
        sg_rule = {}
        sg_rule['id'] = rule.id
        sg_rule['parent_group_id'] = rule.parent_group_id
        sg_rule['ip_protocol'] = rule.protocol
        sg_rule['from_port'] = rule.from_port
        sg_rule['to_port'] = rule.to_port
        sg_rule['group'] = {}
        sg_rule['ip_range'] = {}
        if rule.group_id:
            source_group = db.security_group_get(context, rule.group_id)
            sg_rule['group'] = {'name': source_group.name,
                             'tenant_id': source_group.project_id}
        else:
            sg_rule['ip_range'] = {'cidr': rule.cidr}
        return sg_rule

    def _format_security_group(self, context, group):
        security_group = {}
        security_group['id'] = group.id
        security_group['description'] = group.description
        security_group['name'] = group.name
        security_group['tenant_id'] = group.project_id
        security_group['rules'] = []
        for rule in group.rules:
            security_group['rules'] += [self._format_security_group_rule(
                    context, rule)]
        return security_group

    def show(self, req, id):
        """Return data about the given security group."""
        context = req.environ['nova.context']
        try:
            id = int(id)
            security_group = db.security_group_get(context, id)
        except ValueError:
            msg = _("Security group id is not integer")
            return exc.HTTPBadRequest(explanation=msg)
        except exception.NotFound as exp:
            return exc.HTTPNotFound(explanation=unicode(exp))

        return {'security_group': self._format_security_group(context,
                                                              security_group)}

    def delete(self, req, id):
        """Delete a security group."""
        context = req.environ['nova.context']
        try:
            id = int(id)
            security_group = db.security_group_get(context, id)
        except ValueError:
            msg = _("Security group id is not integer")
            return exc.HTTPBadRequest(explanation=msg)
        except exception.SecurityGroupNotFound as exp:
            return exc.HTTPNotFound(explanation=unicode(exp))

        LOG.audit(_("Delete security group %s"), id, context=context)
        db.security_group_destroy(context, security_group.id)

        return exc.HTTPAccepted()

    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'])))}

    def create(self, req, body):
        """Creates a new security group."""
        context = req.environ['nova.context']
        if not body:
            return exc.HTTPUnprocessableEntity()

        security_group = body.get('security_group', None)

        if security_group is None:
            return exc.HTTPUnprocessableEntity()

        group_name = security_group.get('name', None)
        group_description = security_group.get('description', None)

        self._validate_security_group_property(group_name, "name")
        self._validate_security_group_property(group_description,
                                               "description")
        group_name = group_name.strip()
{'fraction_non_alphanumeric': 0.09298516091732512, 'fraction_numerical': 0.0015417228753131624, 'mean_word_length': 2.4424543946932005, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4814491', 'n_tokens_mistral': 2786, 'n_tokens_neox': 2726, 'n_words': 751}