<commit_before># Copyright 2012 New Dream Network, LLC (DreamHost)
#
#    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 httplib2
from oslo_config import cfg
from oslo_log import log as logging
import six.moves.urllib.parse as urlparse
import webob

from neutron.agent.linux import daemon
from neutron.agent.linux import utils as agent_utils
from neutron.common import config
from neutron.common import utils
from neutron.i18n import _LE
from neutron import wsgi
from oslo_serialization import jsonutils

LOG = logging.getLogger(__name__)


class NetworkMetadataProxyHandler(object):
    """Proxy AF_INET metadata request through Unix Domain socket.

    The Unix domain socket allows the proxy access resource that are not
    accessible within the isolated tenant context.
    """

    def __init__(self, network_id=None, router_id=None, domain_id=None):
        self.network_id = network_id
        self.router_id = router_id
        self.domain_id = domain_id

        if network_id is None and router_id is None and domain_id is None:
            msg = _('network_id, router_id, and domain_id are None. '
                    'One of them must be provided.')
            raise ValueError(msg)

    @webob.dec.wsgify(RequestClass=webob.Request)
    def __call__(self, req):
        LOG.debug("Request: %s", req)
        try:
            return self._proxy_request(req.remote_addr,
                                       req.method,
                                       req.path_info,
                                       req.query_string,
                                       req.body)
        except Exception:
            LOG.exception(_LE("Unexpected error."))
            msg = _('An unknown error has occurred. '
                    'Please try your request again.')
            return webob.exc.HTTPInternalServerError(explanation=unicode(msg))

    def get_network_id(self, domain_id, remote_address):
        filedir = '/var/lib/neutron/opflex_agent'
        filename = 'domain_nets.state'
        fqfn = '%s/%s.state' % (filedir, filename)

        nets = None
        try:
            with open(fqfn, "r") as f:
                nets = jsonutils.load(f)
        except Exception as e:
            LOG.warn("Exception in reading file: %s" % str(e))

        if nets:
            if domain_id in nets:
                if remote_address in nets[domain_id]:
                    return nets[domain_id][remote_address]
        LOG.warn("IP address not found: domain=%s, addr=%s" % (
                 domain_id, remote_address))
        return None

    def _proxy_request(self, remote_address, method, path_info,
                       query_string, body):
        headers = {
            'X-Forwarded-For': remote_address,
        }

        if self.domain_id:
            network_id = self.get_network_id(self.domain_id, remote_address)
            if network_id:
                headers['X-Neutron-Network-ID'] = network_id
            else:
                return webob.exc.HTTPNotFound()
        elif self.router_id:
            headers['X-Neutron-Router-ID'] = self.router_id
        else:<commit_msg>Fixed state filename in namespace proxy<commit_after># Copyright 2012 New Dream Network, LLC (DreamHost)
#
#    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 httplib2
from oslo_config import cfg
from oslo_log import log as logging
import six.moves.urllib.parse as urlparse
import webob

from neutron.agent.linux import daemon
from neutron.agent.linux import utils as agent_utils
from neutron.common import config
from neutron.common import utils
from neutron.i18n import _LE
from neutron import wsgi
from oslo_serialization import jsonutils

LOG = logging.getLogger(__name__)


class NetworkMetadataProxyHandler(object):
    """Proxy AF_INET metadata request through Unix Domain socket.

    The Unix domain socket allows the proxy access resource that are not
    accessible within the isolated tenant context.
    """

    def __init__(self, network_id=None, router_id=None, domain_id=None):
        self.network_id = network_id
        self.router_id = router_id
        self.domain_id = domain_id

        if network_id is None and router_id is None and domain_id is None:
            msg = _('network_id, router_id, and domain_id are None. '
                    'One of them must be provided.')
            raise ValueError(msg)

    @webob.dec.wsgify(RequestClass=webob.Request)
    def __call__(self, req):
        LOG.debug("Request: %s", req)
        try:
            return self._proxy_request(req.remote_addr,
                                       req.method,
                                       req.path_info,
                                       req.query_string,
                                       req.body)
        except Exception:
            LOG.exception(_LE("Unexpected error."))
            msg = _('An unknown error has occurred. '
                    'Please try your request again.')
            return webob.exc.HTTPInternalServerError(explanation=unicode(msg))

    def get_network_id(self, domain_id, remote_address):
        filedir = '/var/lib/neutron/opflex_agent'
        filename = 'instance_networks.state'
        fqfn = '%s/%s' % (filedir, filename)

        nets = None
        try:
            with open(fqfn, "r") as f:
                nets = jsonutils.load(f)
        except Exception as e:
            LOG.warn("Exception in reading file: %s" % str(e))

        if nets:
            if domain_id in nets:
                if remote_address in nets[domain_id]:
                    return nets[domain_id][remote_address]
        LOG.warn("IP address not found: domain=%s, addr=%s" % (
                 domain_id, remote_address))
        return None

    def _proxy_request(self, remote_address, method, path_info,
                       query_string, body):
        headers = {
            'X-Forwarded-For': remote_address,
        }

        if self.domain_id:
            network_id = self.get_network_id(self.domain_id, remote_address)
            if network_id:
                headers['X-Neutron-Network-ID'] = network_id
            else:
                return webob.exc.HTTPNotFound()
        elif self.router_id:
            headers['X-Neutron-Router-ID'] = self.router_id
        else:
{'fraction_non_alphanumeric': 0.0760928961748634, 'fraction_numerical': 0.003005464480874317, 'mean_word_length': 2.154243860404998, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3395082', 'n_tokens_mistral': 2028, 'n_tokens_neox': 1944, 'n_words': 632}