def commandReceived(self, ssn, message): """ Process incoming commands, coming in with session and message information. ================= ========================== Parameter Description ================= ========================== ssn AMQP session object message Received AMQP message ================= ========================== Incoming messages are coming from an :class:`gosa.common.components.amqp_proxy.AMQPServiceProxy` which is providing a *reply to* queue as a return channel. The command result is written to that queue. """ # Check for id if not message.user_id: raise ValueError("incoming message without user_id") err = None res = None id_ = '' try: req = loads(message.content) except ServiceRequestNotTranslatable, e: err = str(e) req = {'id': id_}
def __call__(self, *args, **kwargs): if len(kwargs) > 0 and len(args) > 0: raise JSONRPCException("JSON-RPC does not support positional and keyword arguments at the same time") if len(kwargs): postdata = dumps({"method": self.__serviceName, 'params': kwargs, 'id': 'jsonrpc'}) else: postdata = dumps({"method": self.__serviceName, 'params': args, 'id': 'jsonrpc'}) respdata = self.__opener.open(self.__serviceURL, postdata).read() resp = loads(respdata) if resp['error'] != None: raise JSONRPCException(resp['error']) else: # Look for json class hint if "result" in resp and \ isinstance(resp["result"], DictType) and \ "__jsonclass__" in resp["result"] and \ resp["result"]["__jsonclass__"][0] == "json.ObjectFactory": resp = resp["result"] jc = resp["__jsonclass__"][1] del resp["__jsonclass__"] # Extract property presets data = {} for prop in resp: data[prop] = resp[prop] jc.insert(0, JSONServiceProxy(self.__serviceURL, None, self.__opener)) jc.append(data) return ObjectFactory.get_instance(*jc) return resp['result']
def process(self, req, environ): """ Process an incoming JSONRPC request and dispatch it thru the *CommandRegistry*. ================= ========================== Parameter Description ================= ========================== req Incoming Request environ WSGI environment ================= ========================== ``Return``: varries """ if not req.method == "POST": raise exc.HTTPMethodNotAllowed("Only POST allowed", allow="POST").exception try: json = loads(req.body) except ValueError, e: raise ValueError("Bad JSON: %s" % e)
def __call__(self, *args, **kwargs): if len(kwargs) > 0 and len(args) > 0: raise JSONRPCException("JSON-RPC does not support positional and keyword arguments at the same time") # Default to 'core' queue, pylint: disable=W0612 queue = "core" if AMQPServiceProxy.methods[self.__serviceAddress]: if not self.__serviceName in AMQPServiceProxy.methods[self.__serviceAddress]: raise NameError("name '%s' not defined" % self.__serviceName) if AMQPServiceProxy.domain: queue = AMQPServiceProxy.methods[self.__serviceAddress][self.__serviceName]['target'] else: queue = self.__serviceAddress # Find free session for requested queue for sess, dsc in AMQPServiceProxy.worker[self.__serviceAddress].iteritems(): if not dsc['locked']: self.__ssn = dsc['ssn'] self.__sender = dsc['sender'] self.__receiver = dsc['receiver'] self.__worker = sess dsc['locked'] = True break # No free session? if not self.__ssn: raise AMQPException('no free session - increase workers') # Send if len(kwargs): postdata = dumps({"method": self.__serviceName, 'params': kwargs, 'id': 'jsonrpc'}) else: postdata = dumps({"method": self.__serviceName, 'params': args, 'id': 'jsonrpc'}) message = Message(postdata) message.user_id = self.__URL['user'] message.reply_to = 'reply-%s' % self.__ssn.name self.__sender.send(message) # Get response respdata = self.__receiver.fetch() resp = loads(respdata.content) self.__ssn.acknowledge(respdata) if resp['error'] != None: AMQPServiceProxy.worker[self.__serviceAddress][self.__worker]['locked'] = False raise JSONRPCException(resp['error']) else: # Look for json class hint if "result" in resp and \ isinstance(resp["result"], DictType) and \ "__jsonclass__" in resp["result"] and \ resp["result"]["__jsonclass__"][0] == "json.ObjectFactory": resp = resp["result"] jc = resp["__jsonclass__"][1] del resp["__jsonclass__"] # Extract property presets data = {} for prop in resp: data[prop] = resp[prop] jc.insert(0, AMQPServiceProxy(self.__serviceURL, self.__serviceAddress, None, self.__conn, workers=self.__workers)) jc.append(data) AMQPServiceProxy.worker[self.__serviceAddress][self.__worker]['locked'] = False return ObjectFactory.get_instance(*jc) AMQPServiceProxy.worker[self.__serviceAddress][self.__worker]['locked'] = False return resp['result']
self.log.error(e.error) return Response( status=500, content_type="application/json", charset="utf8", body=dumps(dict(result=None, error=error_value, id=jid)), ) except Exception as e: text = traceback.format_exc() exc_value = sys.exc_info()[1] err = str(e) # If message starts with [, it's a translateable message in # repr format if err.startswith("[") and not err.startswith("[Err"): err = loads(repr2json(err)) if err.startswith("("): err = "[" + err[1:-1] + "]" err = loads(repr2json(err)) error_value = dict(name="JSONRPCError", code=100, message=str(exc_value), error=err) self.log.error("returning call [%s]: %s / %s" % (jid, None, f_print(err))) self.log.error(text) return Response( content_type="application/json", charset="utf8", body=dumps(dict(result=None, error=error_value, id=jid)), )