def handle(self): logger = self.server.logger while True: try: req_raw = self.request.recv(MAX_MSG_SIZE) except socket.error as err: logger.warning("Failed to receive request: %s" % err) break if not req_raw: break req = rpc_proto.Request() try: req.ParseFromString(req_raw) except: logger.warning("Invalid request") break logger.debug("Received request:\n" + "-" * 8 + "\n%s" % req + "-" * 8) handler = self.__handlers.get(req.type) try: if not handler: raise Error(errno.EINVAL, "Invalid request type") resp = handler(self, req) if not resp: resp = rpc_proto.Response() resp.type = rpc_proto.RESP_EMPTY except Error as err: resp = rpc_proto.Response() resp.type = rpc_proto.RESP_ERROR resp.errcode = err.errcode resp.errmsg = err.errmsg resp_list = resp if isinstance(resp, list) else [resp] try: for resp in resp_list: logger.debug("Sending response:\n" + "-" * 8 + "\n%s" % resp + "-" * 8) self.request.send(resp.SerializeToString()) except socket.error as err: logger.warning("Failed to send response: %s" % err) break
def _sendRPC(self, service, method, request, response): try: request_wrapper = rpc_pb2.Request() request_wrapper.rpc_id = self._next_rpc_id self._next_rpc_id += 1 request_wrapper.service = service request_wrapper.method = method request_wrapper.body = request.Encode() self._writePB(request_wrapper) response_wrapper = rpc_pb2.Response() self._readPB(response_wrapper) except: # Any exception here should cause us to close the socket to make sure we # don't leave it in an unknown state. self.closeSession() raise assert response_wrapper.rpc_id == request_wrapper.rpc_id if response_wrapper.status == APPLICATION_ERROR: raise apiproxy_errors.ApplicationError( response_wrapper.application_error, response_wrapper.error_detail) elif response_wrapper.status in _ExceptionsMap: ex, message = _ExceptionsMap[response_wrapper.status] raise ex(message % (service, method)) else: response.ParseFromString(response_wrapper.body)
def handleError(self, e): '''Produce an RPC response to convey a server error to the client.''' msg = "%d : %s" % (e.rpc_error_code, e.message) logging.error(msg) # Create error reply response = rpc_pb.Response() response.error_reason = e.rpc_error_code response.error = e.message return response
def test_handle(self): input = rpc_pb2.Request() input.service_name = self.service.GetDescriptor().full_name input.method_name = 'HelloWorld' data = hello_world_pb2.HelloRequest() data.my_name = 'Zach' input.request_proto = data.SerializeToString() ret = self.handler.handle(input.SerializeToString()) response = rpc_pb2.Response() response.ParseFromString(ret) service_res = hello_world_pb2.HelloResponse() service_res.ParseFromString(response.response_proto) self.assertEqual(service_res.hello_world, 'Hello Zach')
def __recv_response(self, expected_type): assert self.socket, "Not connected" resp_raw = self.socket.recv(MAX_MSG_SIZE) resp = rpc_proto.Response() try: resp.ParseFromString(resp_raw) except: raise RPCError("Failed to parse response") if resp.type == rpc_proto.RESP_ERROR: raise Error(resp.errcode, resp.errmsg) if resp.type != expected_type: raise RPCError("Unexpected response type " "(received %s, expected %s)" % (resp.type, expected_type)) return resp
def _make_response(type, errcode=0, errmsg="", id="", config=LoadConfig(), list_len=0): resp = rpc_proto.Response() resp.type = type resp.errcode = errcode resp.errmsg = errmsg resp.id = id resp.config.guarantee = config.guarantee resp.config.limit = config.limit resp.config.swap_limit = config.swap_limit resp.list_len = list_len return resp
def run(): request = get_request() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 8080)) sock.send(request) recv = sock.recv(6) protocol = RPCProtocol() len = protocol.request_len(recv) print len ret = sock.recv(len) response = rpc_pb2.Response() response.ParseFromString(ret) service_res = user_pb2.UserLoginResponse() service_res.ParseFromString(response.response_proto) print service_res.login sock.close()
def callMethod(self, service, method, proto_request): '''Execute a service method request.''' logging.debug('Calling service %s' % service) logging.debug('Calling method %s' % method) # Create the controller (initialised to success) and callback controller = SocketRpcController() callback = Callback() try: service.CallMethod(method, controller, proto_request, callback) except Exception, e: raise error.RpcError(unicode(e)) # Return an RPC response, with payload defined in the callback response = rpc_pb.Response() if callback.response: response.callback = True response.response_proto = callback.response.SerializeToString() else: response.callback = callback.invoked # Check to see if controller has been set to not success by user. if controller.failed(): response.error = controller.error() response.error_reason = rpc_pb.RPC_FAILED return response def handleError(self, e): '''Produce an RPC response to convey a server error to the client.'''