<commit_before># Copyright 2016 NOKIA
#
#    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 base64
try:
    import httplib as httpclient      # python 2
except ImportError:
    import http.client as httpclient  # python 3
import json
import logging
import re
import socket
import ssl
import time

from neutron._i18n import _
from nuage_neutron.plugins.common import config as nuage_config
from nuage_neutron.plugins.common import constants as plugin_constants


LOG = logging.getLogger(__name__)

REST_SUCCESS_CODES = range(200, 207)
REST_UNAUTHORIZED = 401
REST_NOT_FOUND = 404
REST_CONFLICT = 409
REST_CONFLICT_ERR_CODE = REST_CONFLICT
REST_SERV_UNAVAILABLE_CODE = 503

REST_EXISTS_INTERNAL_ERR_CODE = '2510'
REST_NO_ATTR_CHANGES_TO_MODIFY_ERR_CODE = '2039'
REST_VM_UUID_IN_USE_ERR_CODE = '2748'
REST_VLAN_EXISTS_ERR_CODE = '3316'
REST_VLAN_IN_USE_ERR_CODE = '7053'
REST_IFACE_EXISTS_ERR_CODE = '7006'
REST_ENT_PERMS_EXISTS_ERR_CODE = '4504'

# legacy - deprecated
CONFLICT_ERR_CODE = REST_CONFLICT
RES_NOT_FOUND = REST_NOT_FOUND
RES_CONFLICT = REST_CONFLICT
RES_EXISTS_INTERNAL_ERR_CODE = REST_EXISTS_INTERNAL_ERR_CODE
VSD_NO_ATTR_CHANGES_TO_MODIFY_ERR_CODE = \
    REST_NO_ATTR_CHANGES_TO_MODIFY_ERR_CODE

VSD_RESP_OBJ = 3

LIST_L2DOMAINS = re.compile('.*/l2domains(\?.*)?$')
LIST_SUBNETS = re.compile('.*/subnets(\?.*)?$')
GET_L2DOMAIN = re.compile('/l2domains/([0-9a-fA-F\-]+?)(\?.*)?$')
GET_SUBNET = re.compile('/subnets/([0-9a-fA-F\-]+?)(\?.*)?$')


class RESTProxyBaseException(Exception):
    message = _("An unknown exception occurred.")

    def __init__(self, **kwargs):
        try:
            super(RESTProxyBaseException, self).__init__(self.message % kwargs)
            self.msg = self.message % kwargs
        except Exception:
            if self.use_fatal_exceptions():
                raise
            else:
                super(RESTProxyBaseException, self).__init__(self.message)

    def __unicode__(self):
        return str(self.msg)

    def use_fatal_exceptions(self):
        return False


class RESTProxyError(RESTProxyBaseException):
    def __init__(self, message, error_code=None, vsd_code=None):
        self.code = 0
        if error_code:
            self.code = error_code
        self.vsd_code = vsd_code

        if message is None:
            message = "None"

        if self.code == REST_CONFLICT_ERR_CODE:
            self.message = (_('%s') % message)
        else:
            self.message = (_('Error in REST call to VSD: %s') % message)
        super(RESTProxyError, self).__init__()


class ResourceExistsException(RESTProxyError):
    def __init__(self, message):
        super(ResourceExistsException, self).__init__(
            message,
            REST_CONFLICT_ERR_CODE,
            vsd_code=REST_EXISTS_INTERNAL_ERR_CODE)

        super(RESTProxyError, self).__init__()


class ResourceNotFoundException(RESTProxyError):
    def __init__(self, message):
        super(ResourceNotFoundException, self).__init__(
            message,
            REST_NOT_FOUND)


class RESTProxyServer(object):

    def __init__(self, server, base_uri, serverssl,
                 serverauth, auth_resource,
                 organization, servertimeout=30,
                 max_retries=5):
        try:
            server_ip, port = server.split(":")
        except ValueError:
            server_ip = server
            port = None
        self.server = server_ip
        self.port = int(port) if port else None
        self.base_uri = base_uri
        self.serverssl = serverssl
        self.serverauth = serverauth
        self.auth_resource = auth_resource
        self.organization = organization
        self.timeout = servertimeout
        self.max_retries = max_retries
        self.auth = None
        self.success_codes = range(200, 207)
        self.api_count = 0

    @staticmethod
    def raise_rest_error(msg, exc=None, log_as_error=True):
        if log_as_error:
            LOG.error(_('RESTProxy: %s'), msg)
        else:
            LOG.debug(_('RESTProxy: %s'), msg)
        if exc:
            raise exc
        else:
            raise Exception(msg)

    @staticmethod
    def raise_error_response(response):
        errors = json.loads(response[3])
        log_as_error = False
        if response[0] == REST_SERV_UNAVAILABLE_CODE:
            log_as_error = True
            msg = 'VSD temporarily unavailable, ' + str(errors['errors'])
        else:
            msg = str(errors['errors'][0]['descriptions'][0]['description'])

        if response[0] == REST_NOT_FOUND:
            e = ResourceNotFoundException(msg)
        else:
            vsd_code = str(errors.get('internalErrorCode'))
            e = RESTProxyError(msg, error_code=response[0], vsd_code=vsd_code)

        RESTProxyServer.raise_rest_error(msg, e, log_as_error)

    def _rest_call(self, action, resource, data, extra_headers=None,<commit_msg>Fix restproxy when there is unformatted/no response from VSD.<commit_after># Copyright 2016 NOKIA
#
#    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 base64
try:
    import httplib as httpclient      # python 2
except ImportError:
    import http.client as httpclient  # python 3
import json
import logging
import re
import socket
import ssl
import time

from neutron._i18n import _
from nuage_neutron.plugins.common import config as nuage_config
from nuage_neutron.plugins.common import constants as plugin_constants


LOG = logging.getLogger(__name__)

REST_SUCCESS_CODES = range(200, 207)
REST_UNAUTHORIZED = 401
REST_NOT_FOUND = 404
REST_CONFLICT = 409
REST_CONFLICT_ERR_CODE = REST_CONFLICT
REST_SERV_UNAVAILABLE_CODE = 503

REST_EXISTS_INTERNAL_ERR_CODE = '2510'
REST_NO_ATTR_CHANGES_TO_MODIFY_ERR_CODE = '2039'
REST_VM_UUID_IN_USE_ERR_CODE = '2748'
REST_VLAN_EXISTS_ERR_CODE = '3316'
REST_VLAN_IN_USE_ERR_CODE = '7053'
REST_IFACE_EXISTS_ERR_CODE = '7006'
REST_ENT_PERMS_EXISTS_ERR_CODE = '4504'

# legacy - deprecated
CONFLICT_ERR_CODE = REST_CONFLICT
RES_NOT_FOUND = REST_NOT_FOUND
RES_CONFLICT = REST_CONFLICT
RES_EXISTS_INTERNAL_ERR_CODE = REST_EXISTS_INTERNAL_ERR_CODE
VSD_NO_ATTR_CHANGES_TO_MODIFY_ERR_CODE = \
    REST_NO_ATTR_CHANGES_TO_MODIFY_ERR_CODE

VSD_RESP_OBJ = 3

LIST_L2DOMAINS = re.compile('.*/l2domains(\?.*)?$')
LIST_SUBNETS = re.compile('.*/subnets(\?.*)?$')
GET_L2DOMAIN = re.compile('/l2domains/([0-9a-fA-F\-]+?)(\?.*)?$')
GET_SUBNET = re.compile('/subnets/([0-9a-fA-F\-]+?)(\?.*)?$')


class RESTProxyBaseException(Exception):
    message = _("An unknown exception occurred.")

    def __init__(self, **kwargs):
        try:
            super(RESTProxyBaseException, self).__init__(self.message % kwargs)
            self.msg = self.message % kwargs
        except Exception:
            if self.use_fatal_exceptions():
                raise
            else:
                super(RESTProxyBaseException, self).__init__(self.message)

    def __unicode__(self):
        return str(self.msg)

    def use_fatal_exceptions(self):
        return False


class RESTProxyError(RESTProxyBaseException):
    def __init__(self, message, error_code=None, vsd_code=None):
        self.code = 0
        if error_code:
            self.code = error_code
        self.vsd_code = vsd_code

        if message is None:
            message = "None"

        if self.code == REST_CONFLICT_ERR_CODE:
            self.message = (_('%s') % message)
        else:
            self.message = (_('Error in REST call to VSD: %s') % message)
        super(RESTProxyError, self).__init__()


class ResourceExistsException(RESTProxyError):
    def __init__(self, message):
        super(ResourceExistsException, self).__init__(
            message,
            REST_CONFLICT_ERR_CODE,
            vsd_code=REST_EXISTS_INTERNAL_ERR_CODE)

        super(RESTProxyError, self).__init__()


class ResourceNotFoundException(RESTProxyError):
    def __init__(self, message):
        super(ResourceNotFoundException, self).__init__(
            message,
            REST_NOT_FOUND)


class RESTProxyServer(object):

    def __init__(self, server, base_uri, serverssl,
                 serverauth, auth_resource,
                 organization, servertimeout=30,
                 max_retries=5):
        try:
            server_ip, port = server.split(":")
        except ValueError:
            server_ip = server
            port = None
        self.server = server_ip
        self.port = int(port) if port else None
        self.base_uri = base_uri
        self.serverssl = serverssl
        self.serverauth = serverauth
        self.auth_resource = auth_resource
        self.organization = organization
        self.timeout = servertimeout
        self.max_retries = max_retries
        self.auth = None
        self.success_codes = range(200, 207)
        self.api_count = 0

    @staticmethod
    def raise_rest_error(msg, exc=None, log_as_error=True):
        if log_as_error:
            LOG.error(_('RESTProxy: %s'), msg)
        else:
            LOG.debug(_('RESTProxy: %s'), msg)
        if exc:
            raise exc
        else:
            raise Exception(msg)

    @staticmethod
    def raise_error_response(response):
        try:
            errors = json.loads(response[3])
            log_as_error = False
            if response[0] == REST_SERV_UNAVAILABLE_CODE:
                log_as_error = True
                msg = 'VSD temporarily unavailable, ' + str(errors['errors'])
            else:
                msg = str(
                    errors['errors'][0]['descriptions'][0]['description'])

            if response[0] == REST_NOT_FOUND:
                e = ResourceNotFoundException(msg)
            else:
                vsd_code = str(errors.get('internalErrorCode'))
                e = RESTProxyError(msg, error_code=response[0],
                                   vsd_code=vsd_code)
            RESTProxyServer.raise_rest_error(msg, e, log_as_error)
        except (TypeError, ValueError):
            if response[3]:
                LOG.error('REST response from VSD: %s' % response[3])
            msg = ("Cannot communicate with SDN controller. Please do not"
                   " perform any further operations and contact the"
                   " administrator.")
            RESTProxyServer.raise_rest_error(msg)

    def _rest_call(self, action, resource, data, extra_headers=None,
{'fraction_non_alphanumeric': 0.09066901408450705, 'fraction_numerical': 0.015316901408450705, 'mean_word_length': 2.7298095863427445, 'pattern_counts': {'":': 2, '<': 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': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4722330', 'n_tokens_mistral': 3693, 'n_tokens_neox': 3462, 'n_words': 805}