Пример #1
0
    def issue_commission(self, request):
        """Issue a commission

        Keyword arguments:
        request -- commision request (dict)

        In case of success return commission's id (int).
        Otherwise raise an AstakosClientException.

        """
        req_headers = {'content-type': 'application/json'}
        req_body = parse_request(request, self.logger)
        try:
            response = self._call_astakos(self.api_commissions,
                                          headers=req_headers,
                                          body=req_body,
                                          method="POST")
        except AstakosClientException as err:
            if err.status == 413:
                raise QuotaLimit(err.message, err.details)
            else:
                raise

        if "serial" in response:
            return response['serial']
        else:
            msg = "issue_commission_core request returned %s. " + \
                  "No serial found" % response
            self.logger.error(msg)
            raise AstakosClientException(msg)
Пример #2
0
    def issue_commission(self, token, request):
        """Issue a commission

        Keyword arguments:
        token   -- service's token (string)
        request -- commision request (dict)

        In case of success return commission's id (int).
        Otherwise raise an AstakosClientException.

        """
        req_headers = {'content-type': 'application/json'}
        req_body = parse_request(request, self.logger)
        try:
            response = self._call_astakos(token, copy(API_COMMISSIONS),
                                          req_headers, req_body, "POST")
        except AstakosClientException as err:
            if err.status == 413:
                raise QuotaLimit(err.message, err.details)
            else:
                raise

        if "serial" in response:
            return response['serial']
        else:
            m = "issue_commission_core request returned %s. No serial found" \
                % response
            self.logger.error(m)
            raise AstakosClientException(m)
Пример #3
0
 def _displayname_catalog(self, token, display_names, req_path):
     req_headers = {'content-type': 'application/json'}
     req_body = parse_request({'displaynames': display_names}, self.logger)
     data = self._call_astakos(token, req_path, req_headers, req_body,
                               "POST")
     if "displayname_catalog" in data:
         return data.get("displayname_catalog")
     else:
         m = "_displayname_catalog request returned %s. " \
             "No displayname_catalog found" % data
         self.logger.error(m)
         raise AstakosClientException(m)
Пример #4
0
 def _uuid_catalog(self, token, uuids, req_path):
     req_headers = {'content-type': 'application/json'}
     req_body = parse_request({'uuids': uuids}, self.logger)
     data = self._call_astakos(token, req_path, req_headers, req_body,
                               "POST")
     if "uuid_catalog" in data:
         return data.get("uuid_catalog")
     else:
         m = "_uuid_catalog request returned %s. No uuid_catalog found" \
             % data
         self.logger.error(m)
         raise AstakosClientException(m)
Пример #5
0
 def _displayname_catalog(self, display_names, req_path):
     """Helper function to retrieve display names catalog"""
     req_headers = {'content-type': 'application/json'}
     req_body = parse_request({'displaynames': display_names}, self.logger)
     data = self._call_astakos(req_path, headers=req_headers,
                               body=req_body, method="POST")
     if "displayname_catalog" in data:
         return data.get("displayname_catalog")
     else:
         msg = "_displayname_catalog request returned %r. " \
               "No displayname_catalog found" % data
         self.logger.error(msg)
         raise AstakosClientException(message=msg, response=data)
Пример #6
0
 def _uuid_catalog(self, uuids, req_path):
     """Helper function to retrieve uuid catalog"""
     req_headers = {'content-type': 'application/json'}
     req_body = parse_request({'uuids': uuids}, self.logger)
     data = self._call_astakos(req_path, headers=req_headers,
                               body=req_body, method="POST")
     if "uuid_catalog" in data:
         return data.get("uuid_catalog")
     else:
         msg = "_uuid_catalog request returned %r. No uuid_catalog found" \
               % data
         self.logger.error(msg)
         raise AstakosClientException(message=msg, response=data)
Пример #7
0
    def _issue_commission(self, request):
        """Issue a commission

        Keyword arguments:
        request -- commision request (dict)

        In case of success return commission's id (int).
        Otherwise raise an AstakosClientException.

        """
        req_headers = {'content-type': 'application/json'}
        req_body = parse_request(request, self.logger)
        try:
            response = self._call_astakos(self.api_commissions,
                                          headers=req_headers,
                                          body=req_body,
                                          method="POST")
        except AstakosClientException as err:
            if err.status == 413:
                try:
                    msg, details = render_overlimit_exception(
                        err.response, self.logger)
                except Exception as perr:
                    self.logger.error(
                        "issue_commission request returned '413'"
                        " but response '%r' could not be parsed:"
                        " %s", err.response, str(perr))
                    msg, details = err.message, ""
                raise QuotaLimit(message=msg,
                                 details=details,
                                 response=err.response)
            else:
                raise

        if "serial" in response:
            return response['serial']
        else:
            msg = "issue_commission_core request returned %r. " + \
                  "No serial found" % response
            self.logger.error(msg)
            raise AstakosClientException(message=msg, response=response)
Пример #8
0
    def _call_astakos(self,
                      request_path,
                      headers=None,
                      body=None,
                      method="GET",
                      log_body=True):
        """Make the actual call to Astakos Service"""
        hashed_token = hashlib.sha1()
        hashed_token.update(self.token)
        self.logger.debug(
            "Make a %s request to %s, using token with hash %s, "
            "with headers %r and body %r", method, request_path,
            hashed_token.hexdigest(), headers,
            body if log_body else "(not logged)")

        if self.headers:
            request_headers = copy(self.headers)
        else:
            request_headers = {}

        if headers is not None:
            request_headers.update(headers)

        # Check Input
        if body is None:
            body = {}
        # Initialize log_request and log_response attributes
        self.log_request = None
        self.log_response = None

        # Build request's header and body
        kwargs = {}
        kwargs['headers'] = request_headers
        kwargs['headers']['X-Auth-Token'] = self.token
        if body:
            kwargs['body'] = copy(body)
            kwargs['headers'].setdefault('content-type',
                                         'application/octet-stream')
        kwargs['headers'].setdefault('content-length',
                                     len(body) if body else 0)

        try:
            # Get the connection object
            with self.conn_class(self.astakos_base_url) as conn:
                # Log the request so other clients (like kamaki)
                # can use them to produce their own log messages.
                self.log_request = dict(method=method, path=request_path)
                self.log_request.update(kwargs)

                # Send request
                # Used * or ** magic. pylint: disable-msg=W0142
                (message, data, status) = \
                    _do_request(conn, method, request_path, **kwargs)

                # Log the response so other clients (like kamaki)
                # can use them to produce their own log messages.
                self.log_response = dict(status=status,
                                         message=message,
                                         data=data)
        except Exception as err:
            self.logger.error("Failed to send request: %r", err)
            raise ConnectionError(err)

        # Return
        self.logger.debug("Request returned with status %s", status)
        if status == 400:
            raise BadRequest(message, data)
        elif status == 401:
            raise Unauthorized(message, data)
        elif status == 403:
            raise Forbidden(message, data)
        elif status == 404:
            raise NotFound(message, data)
        elif status < 200 or status >= 300:
            raise AstakosClientException(message=message,
                                         status=status,
                                         response=data)

        try:
            if data:
                return json.loads(unicode(data))
            else:
                return None
        except Exception as err:
            msg = "Cannot parse response \"%r\" with json: %s"
            self.logger.error(msg % (data, str(err)))
            raise InvalidResponse(message=str(err), response=data)
Пример #9
0
    def _call_astakos(self,
                      token,
                      request_path,
                      headers=None,
                      body=None,
                      method="GET",
                      log_body=True):
        """Make the actual call to Astakos Service"""
        if token is not None:
            hashed_token = hashlib.sha1()
            hashed_token.update(token)
            using_token = "using token %s" % (hashed_token.hexdigest())
        else:
            using_token = "without using token"
        self.logger.debug(
            "Make a %s request to %s %s with headers %s and body %s" %
            (method, request_path, using_token, headers,
             body if log_body else "(not logged)"))

        # Check Input
        if headers is None:
            headers = {}
        if body is None:
            body = {}
        path = self.path + "/" + request_path.strip('/')

        # Build request's header and body
        kwargs = {}
        kwargs['headers'] = copy(headers)
        if token is not None:
            kwargs['headers']['X-Auth-Token'] = token
        if body:
            kwargs['body'] = copy(body)
            kwargs['headers'].setdefault('content-type',
                                         'application/octet-stream')
        kwargs['headers'].setdefault('content-length',
                                     len(body) if body else 0)

        try:
            # Get the connection object
            with self.conn_class(self.netloc) as conn:
                # Send request
                (message, data, status) = \
                    _do_request(conn, method, path, **kwargs)
        except Exception as err:
            self.logger.error("Failed to send request: %s" % repr(err))
            raise AstakosClientException(str(err))

        # Return
        self.logger.debug("Request returned with status %s" % status)
        if status == 400:
            raise BadRequest(message, data)
        elif status == 401:
            raise Unauthorized(message, data)
        elif status == 403:
            raise Forbidden(message, data)
        elif status == 404:
            raise NotFound(message, data)
        elif status < 200 or status >= 300:
            raise AstakosClientException(message, data, status)

        try:
            if data:
                return simplejson.loads(unicode(data))
            else:
                return None
        except Exception as err:
            self.logger.error(
                "Cannot parse response \"%s\" with simplejson: %s" %
                (data, str(err)))
            raise InvalidResponse(str(err), data)