def _marshaled_dispatch(self, data, dispatch_method=None):
     response = None
     try:
         request = jsonrpclib.loads(data)
     except Exception as e:
         fault = Fault(-32700, 'Request %s invalid. (%s)' % (data, e))
         response = fault.response()
         return response
     if not request:
         fault = Fault(-32600, 'Request invalid -- no request data.')
         return fault.response()
     if isinstance(request, list):
         # This SHOULD be a batch, by spec
         responses = []
         for req_entry in request:
             result = validate_request(req_entry)
             if type(result) is Fault:
                 responses.append(result.response())
                 continue
             resp_entry = self._marshaled_single_dispatch(req_entry)
             if resp_entry is not None:
                 responses.append(resp_entry)
         if len(responses) > 0:
             response = '[%s]' % ','.join(responses)
         else:
             response = ''
     else:
         result = validate_request(request)
         if type(result) is Fault:
             return result.response()
         response = self._marshaled_single_dispatch(request)
     return response
Exemple #2
0
 def _marshaled_single_dispatch(self, request):
     # TODO - Use the multiprocessing and skip the response if
     # it is a notification
     # Put in support for custom dispatcher here
     # (See SimpleXMLRPCServer._marshaled_dispatch)
     method = request.get('method')
     params = request.get('params')
     try:
         response = self._dispatch(method, params)
     except:
         exc_type, exc_value, exc_tb = sys.exc_info()
         fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
         return fault.response()
     if 'id' not in request.keys() or request['id'] == None:
         # It's a notification
         return None
     try:
         response = jsonrpclib.dumps(response,
                                     methodresponse=True,
                                     rpcid=request['id'])
         return response
     except:
         exc_type, exc_value, exc_tb = sys.exc_info()
         fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
         return fault.response()
Exemple #3
0
 def _marshaled_dispatch(self, data, dispatch_method=None):
     """Convert the data to a JSON RPC method request and dispatch it."""
     try:
         request = jsonrpclib.loads(data)
     except Exception as e:
         fault = Fault(-32700, "Request %s invalid. (%s)" % (data, e))
         response = fault.response()
         return response
     if not request:
         fault = Fault(-32600, "Request invalid -- no request data.")
         return fault.response()
     if isinstance(request, types.ListType):
         # batch of requests
         responses = []
         for req_entry in request:
             result = validate_request(req_entry)
             if type(result) is Fault:
                 responses.append(result.response())
                 continue
             resp_entry = self._marshaled_single_dispatch(req_entry)
             if resp_entry is not None:
                 responses.append(resp_entry)
         if len(responses) > 0:
             response = "[%s]" % ",".join(responses)
         else:
             response = ""
     else:
         # single request
         result = validate_request(request)
         if type(result) is Fault:
             return result.response()
         response = self._marshaled_single_dispatch(request)
     return response
 def _marshaled_single_dispatch(self, request):
     # TODO - Use the multiprocessing and skip the response if
     # it is a notification
     # Put in support for custom dispatcher here
     # (See SimpleXMLRPCServer._marshaled_dispatch)
     method = request.get('method')
     params = request.get('params')
     try:
         response = self._dispatch(method, params)
     except:
         exc_type, exc_value, exc_tb = sys.exc_info()
         fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
         return fault.response()
     if 'id' not in request.keys() or request['id'] == None:
         # It's a notification
         return None
     try:
         response = jsonrpclib.dumps(response,
                                     methodresponse=True,
                                     rpcid=request['id']
                                     )
         return response
     except:
         exc_type, exc_value, exc_tb = sys.exc_info()
         fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
         return fault.response()
Exemple #5
0
    def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
        """
        Parses the request data (marshaled), calls method(s) and returns a
        JSON string (marshaled)

        :param data: A JSON request string
        :param dispatch_method: Custom dispatch method (for method resolution)
        :param path: Unused parameter, to keep compatibility with xmlrpclib
        :return: A JSON-RPC response string (marshaled)
        """
        # Parse the request
        try:
            request = jsonrpclib.loads(data, self.json_config)
        except Exception as ex:
            # Parsing/loading error
            fault = Fault(-32700, 'Request {0} invalid. ({1}:{2})'
                          .format(data, type(ex).__name__, ex),
                          config=self.json_config)
            _logger.warning("Error parsing request: %s", fault)
            return fault.response()

        # Get the response dictionary
        try:
            response = self._unmarshaled_dispatch(request, dispatch_method)
            if response is not None:
                # Compute the string representation of the dictionary/list
                return jsonrpclib.jdumps(response, self.encoding)
            else:
                # No result (notification)
                return ''
        except NoMulticallResult:
            # Return an empty string (jsonrpclib internal behaviour)
            return ''
    def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
        """
        Parses the request data (marshaled), calls method(s) and returns a
        JSON string (marshaled)

        :param data: A JSON request string
        :param dispatch_method: Custom dispatch method (for method resolution)
        :param path: Unused parameter, to keep compatibility with xmlrpclib
        :return: A JSON-RPC response string (marshaled)
        """
        # Parse the request
        try:
            request = jsonrpclib.loads(data, self.json_config)
        except Exception as ex:
            # Parsing/loading error
            fault = Fault(-32700, 'Request {0} invalid. ({1}:{2})'
                          .format(data, type(ex).__name__, ex),
                          config=self.json_config)
            _logger.warning("Error parsing request: %s", fault)
            return fault.response()

        # Get the response dictionary
        try:
            response = self._unmarshaled_dispatch(request, dispatch_method)
            if response is not None:
                # Compute the string representation of the dictionary/list
                return jsonrpclib.jdumps(response, self.encoding)
            else:
                # No result (notification)
                return ''
        except NoMulticallResult:
            # Return an empty string (jsonrpclib internal behaviour)
            return ''
 def _marshaled_dispatch(self, session_id, data, dispatch_method=None):
     response = None
     try:
         request = jsonrpclib.loads(data)
     except Exception, e:
         fault = Fault(-32700, 'Request %s invalid. (%s)' % (data, e))
         response = fault.response()
         return response
 def _marshaled_dispatch(self, session_id, data, dispatch_method=None):
     response = None
     try:
         request = jsonrpclib.loads(data)
     except Exception, e:
         fault = Fault(-32700, 'Request %s invalid. (%s)' % (data, e))
         response = fault.response()
         return response
Exemple #9
0
    def _marshaled_dispatch(self, data, client_ip=None):
        response = None
        try:
            request = jsonrpclib.loads(data)
            if not request.has_key("params"):
                request["params"] = {}
            request["params"]["client_ip"] = client_ip

        except Exception, e:
            fault = Fault(-32700, "Request %s invalid. (%s)" % (data, e))
            response = fault.response()
            return response
Exemple #10
0
 def _marshaled_dispatch(self, data, client_ip=None):
     response = None
     try:
         request = jsonrpclib.loads(data)
         if not request.has_key('params'):
             request['params'] = {}
         request['params']['client_ip'] = client_ip
         
     except Exception, e:
         fault = Fault(-32700, 'Request %s invalid. (%s)' % (data, e))
         response = fault.response()
         return response
Exemple #11
0
 def _marshaled_dispatch(self, data, dispatch_method = None):
     response = None
     try:
         request = jsonrpclib.loads(data)
     except:
         fault = Fault(-32600, 'Request %s invalid.' % data)
         response = fault.response()
         return response
     version = get_version(request)
     if not version:
         fault = Fault(-32600, 'Request %s invalid.' % data)
         response = fault.response()
         return response
     if type(request) is types.ListType:
         # This SHOULD be a batch, by spec
         responses = []
         for req_entry in request:
             resp_entry = self._marshaled_single_dispatch(req_entry)
             if resp_entry is not None:
                 responses.append(resp_entry)
         response = '[%s]' % ','.join(responses)
     else:
         response = self._marshaled_single_dispatch(request)
     return response
Exemple #12
0
    def do_POST(self):
        """
        HTTP POST method processor.
        """

        if not self.is_rpc_path_valid():
            logger.warning("[Response] HTTP 404 - The path requested is not " "a  valid address.")
            self.report_404()
            return

        try:
            size_remaining = int(self.headers["content-length"])
            L = []
            while size_remaining:
                chunk_size = min(size_remaining, self.MAX_CHUNK_SIZE)
                L.append(self.rfile.read(chunk_size))
                size_remaining -= len(L[-1])
            data = "".join(L)
            c_ip, c_port = self.client_address
            logger.info("[Request] Client %s:%s method POST: %s" % (c_ip, c_port, data))
            response = self.server._marshaled_dispatch(data)
            status = 200
            message = "Request accepted."
        except Exception:
            logger.exception("Exception processing request:")
            status = 500
            message = "Internal Server Error."
            err_lines = traceback.format_exc().splitlines()
            trace_string = "%s | %s" % (err_lines[-3], err_lines[-1])
            fault = Fault(-32603, "Server error: %s" % trace_string)
            response = fault.response()
        finally:
            logger.info("[Response] HTTP %d - %s" % (status, message))
            self.send_response(status)

        logger.info("[Response] Content: %s" % repr(response))
        self.send_header("Content-type", "application/json-rpc")
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        self.wfile.write(response)
        self.wfile.flush()
        self.connection.shutdown(1)
Exemple #13
0
    def _marshaled_dispatch(self, session_id, data, dispatch_method=None):
        response = None
        try:
            request = jsonrpclib.loads(data)
        except Exception as e:
            fault = Fault(-32700, 'Request %s invalid. (%s)' % (data, e))
            response = fault.response()
            return response

        session = self.dispatcher.get_session_by_address(session_id)
        if not session:
            return 'Error: session not found'
        session.time = time.time()

        responses = []
        if not isinstance(request, types.ListType):
            request = [request]

        for req_entry in request:
            result = validate_request(req_entry)
            if type(result) is Fault:
                responses.append(result.response())
                continue

            self.dispatcher.do_dispatch(session, req_entry)

            if req_entry['method'] == 'server.stop':
                return json.dumps({'result': 'ok'})

        r = self.poll_session(session)
        for item in r:
            responses.append(json.dumps(item))

        if len(responses) > 1:
            response = '[%s]' % ','.join(responses)
        elif len(responses) == 1:
            response = responses[0]
        else:
            response = ''

        return response
    def _marshaled_single_dispatch(self, request):
        # TODO - Use the multiprocessing and skip the response if
        # it is a notification
        # Put in support for custom dispatcher here
        # (See SimpleXMLRPCServer._marshaled_dispatch)
        method = request.get('method')
        params = request.get('params')
        try:
            response = self._dispatch(method, params)
        except Fault, fault:
            return fault.response()
        except:
            exc_type, exc_value, exc_tb = sys.exc_info()
            fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
            return fault.response()
        if 'id' not in request.keys() or request['id'] == None:
            # It's a notification
            return None
        try:
            response = jsonrpclib.dumps(response,
                                        methodresponse=True,
                                        rpcid=request['id']
                                        )
            return response
        except:
            exc_type, exc_value, exc_tb = sys.exc_info()
            fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
            return fault.response()

    def _dispatch(self, method, params):