Ejemplo n.º 1
0
def test_agents():
    import zmq
    from openre.agent.helpers import RPCBroker, Transport, RPC, AgentBase
    from openre.helpers import from_json
    from openre.agent.server import Agent as ServerAgent
    transport = Transport()
    class ServerAgentTest(ServerAgent):
        def init(self):
            self.responder = transport.socket(zmq.ROUTER)
            self.responder.bind("inproc://server-responder")
            self.broker_socket = transport.socket(zmq.DEALER)
            self.broker_socket.RCVTIMEO = 10000
            self.broker_socket.connect("inproc://server-broker")
            self.broker = RPCBroker(self.broker_socket)

    class ClientAgent(AgentBase):
        def init(self):
            self.server_socket = transport.socket(zmq.REQ)
            self.server_socket.connect("inproc://server-responder")
            self.server = RPC(self.server_socket)
    # server
    server_agent = ServerAgentTest({})
    # client
    client_agent = ClientAgent({})

    # client -> server -> client
    client_agent.send_server('ping', {'test': 'ok'}, skip_recv=True)
    message = server_agent.responder.recv_multipart()
    assert len(message) == 4
    print message
    assert message[1] == ''
    assert message[2] == ''
    assert 'action' in message[3]
    data = from_json(message[3])
    assert data['action'] == 'ping'
    assert data['data']['test'] == 'ok'
    address = message[0]
    server_agent.reply(address, 'pong')
    reply_message = client_agent.server_socket.recv()
    reply_data = from_json(reply_message)
    assert reply_data == 'pong'
Ejemplo n.º 2
0
 def __call__(self, *args, **kwargs):
     self._response = None
     # original message
     message = {
         'action': self.name,
         'wait': self._wait,
         'no_reply': self._no_reply,
         'bytes': len(self._bytes),
         'priority': int(self._priority),
         'args': {
             'args': args,
             'kwargs': kwargs
         }
     }
     # pack message to envelope
     message = {
         'action': self.proxy._proxy_method,
         'address': self.proxy._proxy_address,
         'data': message,
         'wait': self._wait,
         'no_reply': self._no_reply,
         'bytes': len(self._bytes),
         'priority': int(self._priority),
         'args': {
             'args': self.proxy._proxy_args,
             'kwargs': self.proxy._proxy_kwargs
         }
     }
     message = to_json(message)
     logging.debug('RPC broker proxy >>> %s',
                   pretty_func_str('%s.%s' % (
                       self.proxy._proxy_method, self.name),
                       *args, **kwargs)
                  )
     packet = ['', message]
     if self._bytes:
         packet.extend(self._bytes)
     self.proxy._socket.send_multipart(packet)
     ret = {'success': True, 'data': None}
     if not self._no_reply:
         ret = self.proxy._socket.recv_multipart()
         assert ret[0] == ''
         ret = from_json(ret[1])
     self.proxy._response = ret
     logging.debug('RPC broker proxy %s', ret)
     if not ret['success']:
         if 'traceback' in ret and ret['traceback']:
             raise RPCException(ret, ret['traceback'])
         raise RPCException(ret, ret['error'])
     return ret['data']
Ejemplo n.º 3
0
 def init(self):
     self.init_actions()
     self.net_config = None
     if self.config['config']:
         json_data = None
         if isinstance(self.config['config'], basestring):
             if os.path.isfile(self.config['config']):
                 with open(self.config['config'], 'r') as inf:
                     json_data = inf.read()
             else:
                 json_data = self.config['config']
         elif isinstance(self.config['config'], dict):
             json_data = self.config['config']
         else:
             json_data = self.config['config'].read()
         if isinstance(json_data, dict):
             self.net_config = json_data
         else:
             self.net_config = from_json(json_data)
Ejemplo n.º 4
0
 def api_call(*args, **kwargs):
     self._response = None
     message = {
         'action': name,
         'args': {
             'args': args,
             'kwargs': kwargs
         }
     }
     message = to_json(message)
     logging.debug('RPC >>> server.%s',
                   pretty_func_str(name, *args, **kwargs))
     self._socket.send_multipart(['', message])
     ret = self._socket.recv_multipart()
     assert ret[0] == ''
     ret = from_json(ret[1])
     self._response = ret
     logging.debug('RPC %s', ret)
     if not ret['success']:
         if 'traceback' in ret and ret['traceback']:
             raise RPCException(ret, ret['traceback'])
         raise RPCException(ret, ret['error'])
     return ret['data']
Ejemplo n.º 5
0
 def from_json(self, json):
     try:
         json = from_json(json)
     except ValueError:
         logging.warn('Message is not valid json: %s', json)
     return json
Ejemplo n.º 6
0
 def load(self, file_name):
     with open(file_name, 'r') as inp:
         self.clear()
         data = from_json(inp.read())
         self.update(data)