Exemplo n.º 1
0
    def do_call(self, url, data, method,
                calltimeout=consts.SOCKET_TIMEOUT, log_filter_flag=False):
        """Send requests to Huawei storage server.

        Send HTTPS call, get response in JSON.
        Convert response into Python Object and return it.
        """
        if self.url:
            url = self.url + url

        kwargs = {'timeout': calltimeout}
        if data:
            kwargs['data'] = json.dumps(data)

        if method in ('POST', 'PUT', 'GET', 'DELETE'):
            func = getattr(self.session, method.lower())
        else:
            msg = _("Request method %s is invalid.") % method
            LOG.error(msg)
            raise exception.StorageBackendException(msg)

        try:
            res = func(url, **kwargs)
        except requests.exceptions.SSLError as e:
            LOG.error('SSLError exception from server: %(url)s.'
                      ' Error: %(err)s', {'url': url, 'err': e})
            err_str = six.text_type(e)
            if 'certificate verify failed' in err_str:
                raise exception.SSLCertificateFailed()
            else:
                raise exception.SSLHandshakeFailed()
        except Exception as err:
            LOG.exception('Bad response from server: %(url)s.'
                          ' Error: %(err)s', {'url': url, 'err': err})
            return {"error": {"code": consts.ERROR_CONNECT_TO_SERVER,
                              "description": "Connect to server error."}}

        try:
            res.raise_for_status()
        except requests.HTTPError as exc:
            return {"error": {"code": exc.response.status_code,
                              "description": six.text_type(exc)}}

        res_json = res.json()
        if not log_filter_flag:
            LOG.info('\n\n\n\nRequest URL: %(url)s\n\n'
                     'Call Method: %(method)s\n\n'
                     'Request Data: %(data)s\n\n'
                     'Response Data:%(res)s\n\n',
                     {'url': url,
                      'method': method,
                      'data': data,
                      'res': res_json})

        return res_json
Exemplo n.º 2
0
    def do_call(self, url, data, method, calltimeout=SOCKET_TIMEOUT):
        if 'http' not in url:
            if self.san_address:
                url = '%s%s' % (self.san_address, url)

        kwargs = {'timeout': calltimeout}
        if data:
            kwargs['data'] = json.dumps(data)

        if method in ('POST', 'PUT', 'GET', 'DELETE'):
            func = getattr(self.session, method.lower())
        else:
            msg = _("Request method %s is invalid.") % method
            LOG.error(msg)
            raise exception.StorageBackendException(msg)
        res = None
        try:
            res = func(url, **kwargs)
        except requests.exceptions.ConnectTimeout as ct:
            LOG.error('Connect Timeout err: {}'.format(ct))
            raise exception.InvalidIpOrPort()
        except requests.exceptions.ReadTimeout as rt:
            LOG.error('Read timed out err: {}'.format(rt))
            raise exception.StorageBackendException(six.text_type(rt))
        except requests.exceptions.SSLError as e:
            LOG.error('SSLError for %s %s' % (method, url))
            err_str = six.text_type(e)
            if 'certificate verify failed' in err_str:
                raise exception.SSLCertificateFailed()
            else:
                raise exception.SSLHandshakeFailed()
        except Exception as err:
            LOG.exception(
                'Bad response from server: %(url)s.'
                ' Error: %(err)s', {
                    'url': url,
                    'err': err
                })
            if 'WSAETIMEDOUT' in str(err):
                raise exception.ConnectTimeout()
            elif 'Failed to establish a new connection' in str(err):
                LOG.error('Failed to establish: {}'.format(err))
                raise exception.InvalidIpOrPort()
            elif 'Read timed out' in str(err):
                raise exception.StorageBackendException(six.text_type(err))
            else:
                raise exception.BadResponse()

        return res
Exemplo n.º 3
0
    def request(self,
                target_uri,
                method,
                params=None,
                request_object=None,
                timeout=None):
        """Sends a request (GET, POST, PUT, DELETE) to the target api.
        :param target_uri: target uri (string)
        :param method: The method (GET, POST, PUT, or DELETE)
        :param params: Additional URL parameters
        :param request_object: request payload (dict)
        :param timeout: expiration timeout(in sec)
        :returns: server response object (dict)
        :raises: StorageBackendException, Timeout, ConnectionError,
                 HTTPError, SSLError
        """

        url, message, status_code, response = None, None, None, None
        if not self.session:
            self.establish_rest_session()

        try:
            url = ("%(self.base_uri)s%(target_uri)s" % {
                'self.base_uri': self.base_uri,
                'target_uri': target_uri
            })

            if request_object:
                response = self.session.request(method=method,
                                                url=url,
                                                data=json.dumps(request_object,
                                                                sort_keys=True,
                                                                indent=4),
                                                timeout=timeout)
            elif params:
                response = self.session.request(method=method,
                                                url=url,
                                                params=params,
                                                timeout=timeout)
            else:
                response = self.session.request(method=method,
                                                url=url,
                                                timeout=timeout)

            status_code = response.status_code

            try:
                message = response.json()
            except ValueError:
                LOG.debug(
                    "No response received from API. Status code "
                    "received is: %(status_code)s",
                    {'status_code': status_code})
                message = None

            LOG.debug(
                "%(method)s request to %(url)s has returned with "
                "a status code of: %(status_code)s.", {
                    'method': method,
                    'url': url,
                    'status_code': status_code
                })

        except r_exc.SSLError as e:
            msg = _("The connection to %(base_uri)s has encountered an "
                    "SSL error. Please check your SSL config or supplied "
                    "SSL cert in Delfin configuration. SSL Exception "
                    "message: %(e)s") % {
                        'base_uri': self.base_uri,
                        'e': e
                    }
            LOG.error(msg)
            err_str = six.text_type(e)
            if 'certificate verify failed' in err_str:
                raise exception.SSLCertificateFailed()
            else:
                raise exception.SSLHandshakeFailed()

        except (r_exc.Timeout, r_exc.ConnectionError, r_exc.HTTPError) as e:
            exc_class, __, __ = sys.exc_info()
            msg = _("The %(method)s to Unisphere server %(base)s has "
                    "experienced a %(error)s error. Please check your "
                    "Unisphere server connection/availability. "
                    "Exception message: %(exc_msg)s")
            raise exc_class(
                msg % {
                    'method': method,
                    'base': self.base_uri,
                    'error': e.__class__.__name__,
                    'exc_msg': e
                })

        except Exception as e:
            msg = _("The %(method)s request to URL %(url)s failed with "
                    "exception %(e)s")
            LOG.error(msg, {
                'method': method,
                'url': url,
                'e': six.text_type(e)
            })
            raise exception.StorageBackendException(
                message=(msg, {
                    'method': method,
                    'url': url,
                    'e': six.text_type(e)
                }))

        return status_code, message