<commit_before># Copyright 2011 OpenStack Foundation
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2011 Grid Dynamics
# Copyright 2011 <NAME>, <NAME>, <NAME>
#
#    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.

import netaddr
from oslo_log import log as logging
from oslo_utils import uuidutils
import webob

from nova.api.openstack import common
from nova.api.openstack.compute.schemas import floating_ips
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import compute
from nova.compute import utils as compute_utils
from nova import exception
from nova.i18n import _
from nova.i18n import _LW
from nova import network


LOG = logging.getLogger(__name__)
ALIAS = 'os-floating-ips'
authorize = extensions.os_compute_authorizer(ALIAS)


def _translate_floating_ip_view(floating_ip):
    result = {
        'id': floating_ip['id'],
        'ip': floating_ip['address'],
        'pool': floating_ip['pool'],
    }
    try:
        result['fixed_ip'] = floating_ip['fixed_ip']['address']
    except (TypeError, KeyError, AttributeError):
        result['fixed_ip'] = None
    try:
        result['instance_id'] = floating_ip['fixed_ip']['instance_uuid']
    except (TypeError, KeyError, AttributeError):
        result['instance_id'] = None
    return {'floating_ip': result}


def _translate_floating_ips_view(floating_ips):
    return {'floating_ips': [_translate_floating_ip_view(ip)['floating_ip']
                             for ip in floating_ips]}


def get_instance_by_floating_ip_addr(self, context, address):
    try:
        instance_id =\
            self.network_api.get_instance_id_by_floating_address(
                context, address)
    except exception.FloatingIpNotFoundForAddress as ex:
        raise webob.exc.HTTPNotFound(explanation=ex.format_message())
    except exception.FloatingIpMultipleFoundForAddress as ex:
        raise webob.exc.HTTPConflict(explanation=ex.format_message())

    if instance_id:
        return common.get_instance(self.compute_api, context, instance_id)


def disassociate_floating_ip(self, context, instance, address):
    try:
        self.network_api.disassociate_floating_ip(context, instance, address)
    except exception.Forbidden:
        raise webob.exc.HTTPForbidden()
    except exception.CannotDisassociateAutoAssignedFloatingIP:
        msg = _('Cannot disassociate auto assigned floating IP')
        raise webob.exc.HTTPForbidden(explanation=msg)


class FloatingIPController(object):
    """The Floating IPs API controller for the OpenStack API."""

    def __init__(self):
        self.compute_api = compute.API(skip_policy_check=True)
        self.network_api = network.API(skip_policy_check=True)
        super(FloatingIPController, self).__init__()

    @extensions.expected_errors((400, 404))
    def show(self, req, id):
        """Return data about the given floating IP."""
        context = req.environ['nova.context']
        authorize(context)

        try:
            floating_ip = self.network_api.get_floating_ip(context, id)
        except (exception.NotFound, exception.FloatingIpNotFound):
            msg = _("Floating IP not found for ID %s") % id
            raise webob.exc.HTTPNotFound(explanation=msg)
        except exception.InvalidID as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())

        return _translate_floating_ip_view(floating_ip)

    @extensions.expected_errors(())
    def index(self, req):
        """Return a list of floating IPs allocated to a project."""
        context = req.environ['nova.context']
        authorize(context)

        floating_ips = self.network_api.get_floating_ips_by_project(context)

        return _translate_floating_ips_view(floating_ips)

    @extensions.expected_errors((400, 403, 404))
    def create(self, req, body=None):
        context = req.environ['nova.context']
        authorize(context)

        pool = None
        if body and 'pool' in body:
            pool = body['pool']
        try:
            address = self.network_api.allocate_floating_ip(context, pool)
            ip = self.network_api.get_floating_ip_by_address(context, address)
        except exception.NoMoreFloatingIps:
            if pool:
                msg = _("No more floating IPs in pool %s.") % pool
            else:
                msg = _("No more floating IPs available.")
            raise webob.exc.HTTPNotFound(explanation=msg)
        except exception.FloatingIpLimitExceeded:
            if pool:
                msg = _("IP allocation over quota in pool %s.") % pool
            else:
                msg = _("IP allocation over quota.")
            raise webob.exc.HTTPForbidden(explanation=msg)
        except exception.FloatingIpPoolNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.FloatingIpBadRequest as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())

        return _translate_floating_ip_view(ip)

    @wsgi.response(202)
    @extensions.expected_errors((400, 403, 404, 409))
    def delete(self, req, id):
        context = req.environ['nova.context']
        authorize(context)

        # get the floating ip object
        try:
            floating_ip = self.network_api.get_floating_ip(context, id)
        except (exception.NotFound, exception.FloatingIpNotFound):
            msg = _("Floating IP not found for ID %s") % id
            raise webob.exc.HTTPNotFound(explanation=msg)
        except exception.InvalidID as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())

        address = floating_ip['address']

        # get the associated instance object (if any)
        instance = get_instance_by_floating_ip_addr(self, context, address)
        try:
            self.network_api.disassociate_and_release_floating_ip(
                context, instance, floating_ip)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()
        except exception.CannotDisassociateAutoAssignedFloatingIP:
            msg = _('Cannot disassociate auto assigned floating IP')
            raise webob.exc.HTTPForbidden(explanation=msg)


class FloatingIPActionController(wsgi.Controller):
    def __init__(self, *args, **kwargs):
        super(FloatingIPActionController, self).__init__(*args, **kwargs)
        self.compute_api = compute.API(skip_policy_check=True)
        self.network_api = network.API(skip_policy_check=True)

    @extensions.expected_errors((400, 403, 404))
    @wsgi.action('addFloatingIp')
    @validation.schema(floating_ips.add_floating_ip)
    def _add_floating_ip(self, req, id, body):
        """Associate floating_ip to an instance."""
        context = req.environ['nova.context']
        authorize(context)

        address = body['addFloatingIp']['address']

        instance = common.get_instance(self.compute_api, context, id)
        cached_nwinfo = compute_utils.get_nw_info_for_instance(instance)<commit_msg>Optimize the instance fetched by floating_ips API<commit_after># Copyright 2011 OpenStack Foundation
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2011 Grid Dynamics
# Copyright 2011 <NAME>, <NAME>, <NAME>
#
#    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.

import netaddr
from oslo_log import log as logging
from oslo_utils import uuidutils
import webob

from nova.api.openstack import common
from nova.api.openstack.compute.schemas import floating_ips
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import compute
from nova.compute import utils as compute_utils
from nova import exception
from nova.i18n import _
from nova.i18n import _LW
from nova import network


LOG = logging.getLogger(__name__)
ALIAS = 'os-floating-ips'
authorize = extensions.os_compute_authorizer(ALIAS)


def _translate_floating_ip_view(floating_ip):
    result = {
        'id': floating_ip['id'],
        'ip': floating_ip['address'],
        'pool': floating_ip['pool'],
    }
    try:
        result['fixed_ip'] = floating_ip['fixed_ip']['address']
    except (TypeError, KeyError, AttributeError):
        result['fixed_ip'] = None
    try:
        result['instance_id'] = floating_ip['fixed_ip']['instance_uuid']
    except (TypeError, KeyError, AttributeError):
        result['instance_id'] = None
    return {'floating_ip': result}


def _translate_floating_ips_view(floating_ips):
    return {'floating_ips': [_translate_floating_ip_view(ip)['floating_ip']
                             for ip in floating_ips]}


def get_instance_by_floating_ip_addr(self, context, address):
    try:
        instance_id =\
            self.network_api.get_instance_id_by_floating_address(
                context, address)
    except exception.FloatingIpNotFoundForAddress as ex:
        raise webob.exc.HTTPNotFound(explanation=ex.format_message())
    except exception.FloatingIpMultipleFoundForAddress as ex:
        raise webob.exc.HTTPConflict(explanation=ex.format_message())

    if instance_id:
        return common.get_instance(self.compute_api, context, instance_id,
                                   expected_attrs=['flavor'])


def disassociate_floating_ip(self, context, instance, address):
    try:
        self.network_api.disassociate_floating_ip(context, instance, address)
    except exception.Forbidden:
        raise webob.exc.HTTPForbidden()
    except exception.CannotDisassociateAutoAssignedFloatingIP:
        msg = _('Cannot disassociate auto assigned floating IP')
        raise webob.exc.HTTPForbidden(explanation=msg)


class FloatingIPController(object):
    """The Floating IPs API controller for the OpenStack API."""

    def __init__(self):
        self.compute_api = compute.API(skip_policy_check=True)
        self.network_api = network.API(skip_policy_check=True)
        super(FloatingIPController, self).__init__()

    @extensions.expected_errors((400, 404))
    def show(self, req, id):
        """Return data about the given floating IP."""
        context = req.environ['nova.context']
        authorize(context)

        try:
            floating_ip = self.network_api.get_floating_ip(context, id)
        except (exception.NotFound, exception.FloatingIpNotFound):
            msg = _("Floating IP not found for ID %s") % id
            raise webob.exc.HTTPNotFound(explanation=msg)
        except exception.InvalidID as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())

        return _translate_floating_ip_view(floating_ip)

    @extensions.expected_errors(())
    def index(self, req):
        """Return a list of floating IPs allocated to a project."""
        context = req.environ['nova.context']
        authorize(context)

        floating_ips = self.network_api.get_floating_ips_by_project(context)

        return _translate_floating_ips_view(floating_ips)

    @extensions.expected_errors((400, 403, 404))
    def create(self, req, body=None):
        context = req.environ['nova.context']
        authorize(context)

        pool = None
        if body and 'pool' in body:
            pool = body['pool']
        try:
            address = self.network_api.allocate_floating_ip(context, pool)
            ip = self.network_api.get_floating_ip_by_address(context, address)
        except exception.NoMoreFloatingIps:
            if pool:
                msg = _("No more floating IPs in pool %s.") % pool
            else:
                msg = _("No more floating IPs available.")
            raise webob.exc.HTTPNotFound(explanation=msg)
        except exception.FloatingIpLimitExceeded:
            if pool:
                msg = _("IP allocation over quota in pool %s.") % pool
            else:
                msg = _("IP allocation over quota.")
            raise webob.exc.HTTPForbidden(explanation=msg)
        except exception.FloatingIpPoolNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.FloatingIpBadRequest as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())

        return _translate_floating_ip_view(ip)

    @wsgi.response(202)
    @extensions.expected_errors((400, 403, 404, 409))
    def delete(self, req, id):
        context = req.environ['nova.context']
        authorize(context)

        # get the floating ip object
        try:
            floating_ip = self.network_api.get_floating_ip(context, id)
        except (exception.NotFound, exception.FloatingIpNotFound):
            msg = _("Floating IP not found for ID %s") % id
            raise webob.exc.HTTPNotFound(explanation=msg)
        except exception.InvalidID as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())

        address = floating_ip['address']

        # get the associated instance object (if any)
        instance = get_instance_by_floating_ip_addr(self, context, address)
        try:
            self.network_api.disassociate_and_release_floating_ip(
                context, instance, floating_ip)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()
        except exception.CannotDisassociateAutoAssignedFloatingIP:
            msg = _('Cannot disassociate auto assigned floating IP')
            raise webob.exc.HTTPForbidden(explanation=msg)


class FloatingIPActionController(wsgi.Controller):
    def __init__(self, *args, **kwargs):
        super(FloatingIPActionController, self).__init__(*args, **kwargs)
        self.compute_api = compute.API(skip_policy_check=True)
        self.network_api = network.API(skip_policy_check=True)

    @extensions.expected_errors((400, 403, 404))
    @wsgi.action('addFloatingIp')
    @validation.schema(floating_ips.add_floating_ip)
    def _add_floating_ip(self, req, id, body):
        """Associate floating_ip to an instance."""
        context = req.environ['nova.context']
        authorize(context)

        address = body['addFloatingIp']['address']

        instance = common.get_instance(self.compute_api, context, id,
                                       expected_attrs=['flavor'])
        cached_nwinfo = compute_utils.get_nw_info_for_instance(instance)
{'fraction_non_alphanumeric': 0.09099216710182767, 'fraction_numerical': 0.008224543080939948, 'mean_word_length': 3.093240716003206, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1203340', 'n_tokens_mistral': 4604, 'n_tokens_neox': 4359, 'n_words': 1083}