def test_hook_client_before_request():
    class ClientBeforeRequestMiddleware(object):
        def __init__(self):
            self.called = False

        def client_before_request(self, event):
            self.called = True
            self.method = event.name

    zero_ctx = zerorpc.Context()
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(context=zero_ctx)
    test_client.connect(endpoint)

    assert test_client.echo("test") == "echo: test"

    test_middleware = ClientBeforeRequestMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    assert test_client.echo("test") == "echo: test"
    assert test_middleware.called == True
    assert test_middleware.method == 'echo'

    test_server.stop()
    test_server_task.join()
Beispiel #2
0
def run_server(ip, port):
    # Run a server if specified
    address = ip + ":" + port
    server = zerorpc.Server(MosaicServer())
    print 'Running server at %s' % address
    server.bind(address)
    server.run()
Beispiel #3
0
def server_up():
    '''
    启动 zerorpc 的服务器,详情见 http://www.zerorpc.io/
    '''
    server = zerorpc.Server(StreamingRPC())
    server.bind("tcp://0.0.0.0:8888")  # listen for local address
    server.run()
def test_hook_client_after_request_timeout():
    class ClientAfterRequestMiddleware(object):
        def __init__(self):
            self.called = False

        def client_after_request(self, req_event, rep_event, exception):
            self.called = True
            assert req_event is not None
            assert req_event.name == "timeout"
            assert rep_event is None

    zero_ctx = zerorpc.Context()
    test_middleware = ClientAfterRequestMiddleware()
    zero_ctx.register_middleware(test_middleware)
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(timeout=TIME_FACTOR * 1, context=zero_ctx)
    test_client.connect(endpoint)

    assert test_middleware.called == False
    try:
        test_client.timeout("test")
    except zerorpc.TimeoutExpired as ex:
        assert test_middleware.called == True
        assert "timeout" in ex.args[0]

    test_server.stop()
    test_server_task.join()
def main():
    tutorial_string = """
    Usage:

        $ primitives-source-simple --source boook --source-name bookendpoint

    """
    parser = argparse.ArgumentParser(
        description=tutorial_string,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--host",
                        help="host ip",
                        default="127.0.0.1",
                        required=False)
    parser.add_argument("-p",
                        "--port",
                        help="port number",
                        default="4242",
                        required=False)
    parser.add_argument("-d", "--directory", help="directory")
    parser.add_argument("-s", "--source", help="source")
    parser.add_argument("--source-name", help="source name")

    source_key_prefix = "source:"
    args = parser.parse_args()
    source_uuid = str(uuid.uuid4())
    source_path = "/tmp/{}".format(source_uuid)

    if args.source_name:
        source_state_exists = r.get(source_key_prefix + args.source_name)
        logger.info("{} found at {}".format(args.source_name,
                                            source_state_exists))
        if source_state_exists:
            logger.info("using existing: {}".format(source_path,
                                                    source_state_exists))
            source_path = source_state_exists

        if not os.path.isdir(source_path) or not source_state_exists:
            logger.warn("{} not found, creating".format(source_path))
            if args.source == 'boook':
                logger.info("creating boook at {}".format(args.source_name))
                #need to pass in params here...
                b = boook.Boook('texxt',
                                [('toc', 1, 'partial'),
                                 ('index', 5, 'partial'), ('bar', 5, 'full'),
                                 ('baz', 5, 'full'), ('zab', 5, 'full'),
                                 ('zoom', 5, 'full')],
                                output_directory=source_path)
                b.generate()
                logger.info("{} set to {}".format(args.source_name,
                                                  source_path))
                r.set(source_key_prefix + args.source_name, source_path)

    s = zerorpc.Server(Source(directory=source_path))
    bind_address = "tcp://{host}:{port}".format(host=args.host, port=args.port)
    logger.info("binding server to: {}".format(bind_address))
    logger.info("sourcing from: {}".format(source_path))
    s.bind(bind_address)
    logger.info("running...")
    s.run()
def test_hook_client_handle_remote_error_inspect():
    class ClientHandleRemoteErrorMiddleware(object):
        def __init__(self):
            self.called = False

        def client_handle_remote_error(self, event):
            self.called = True

    test_middleware = ClientHandleRemoteErrorMiddleware()
    zero_ctx = zerorpc.Context()
    zero_ctx.register_middleware(test_middleware)
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(context=zero_ctx)
    test_client.connect(endpoint)

    assert test_middleware.called == False
    try:
        test_client.crash("test")
    except zerorpc.RemoteError as ex:
        assert test_middleware.called == True
        assert ex.name == "RuntimeError"

    test_server.stop()
    test_server_task.join()
def test_hook_client_after_request_stream():
    zero_ctx = zerorpc.Context()
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(context=zero_ctx)
    test_client.connect(endpoint)

    it = test_client.echoes("test")
    assert next(it) == "echo: test"
    for echo in it:
        assert echo == "echo: test"

    test_middleware = ClientAfterRequestMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    it = test_client.echoes("test")
    assert next(it) == "echo: test"
    assert test_middleware.called == False
    for echo in it:
        assert echo == "echo: test"
    assert test_middleware.called == True
    assert test_middleware.retcode == 'STREAM_DONE'

    test_server.stop()
    test_server_task.join()
Beispiel #8
0
def test_server_inspect_exception_middleware_stream():
    endpoint = random_ipc_endpoint()

    middleware = InspectExceptionMiddleware()
    ctx = zerorpc.Context()
    ctx.register_middleware(middleware)

    module = Srv()
    server = zerorpc.Server(module, context=ctx)
    server.bind(endpoint)
    gevent.spawn(server.run)

    client = zerorpc.Client()
    client.connect(endpoint)

    try:
        client.echo(
            'This is a test which should call the InspectExceptionMiddleware')
    except zerorpc.exceptions.RemoteError as ex:
        assert ex.name == 'RuntimeError'

    client.close()
    server.close()

    assert middleware.called is True
Beispiel #9
0
def main():
    _log("api.main()\n")
    addr = 'tcp://127.0.0.1:' + str(parse_port())
    s = zerorpc.Server(CalcApi())
    s.bind(addr)
    _log('start running on {}'.format(addr))
    s.run()
def main(port):
    addr = 'tcp://127.0.0.1:' + port
    server = Server()
    server.register(HelloWorld())
    s = zerorpc.Server(server)
    s.bind(addr)
    print("start running on {}".format(addr))
    s.run()
Beispiel #11
0
 def __init__(self, ip='127.0.0.1', port=4242, methods=None):
     server = zerorpc.Server(methods)
     try:
         server.bind("tcp://%s:%s" % (ip, port))
         # logger.info('rpc start %(ip)s:%(port)s', {'ip': ip, 'port': port})
         server.run()
     except Exception, ex:
         pass
Beispiel #12
0
 def __init__(self, name, reloader, service_file, port, notifier):
     self.name = name
     self.reloader = reloader
     self.service_file = service_file
     self.notifier = notifier
     server = zerorpc.Server(self)
     server.bind('tcp://127.0.0.1:{}'.format(port))
     server.run()
def start_rpc_server():
    s = zerorpc.Server(RPCInterface(), heartbeat=None)
    logging.info("[-] Starting RPC server")
    try:
        s.bind("tcp://0.0.0.0:" + str(RPC_PORT))
        return s
    except Exception as err:
        raise (err)
Beispiel #14
0
    def __init__(self):
        super(ShallowCarbonCache, self).__init__()
        self.complete = gevent.event.Event()
        self.latest = {}

        self.rpc = zerorpc.Server({'get_latest': self.get_latest})

        self.rpc_thread = None
Beispiel #15
0
 def rpcServer(self):
     # print "enter rpc"
     rpc_server = zerorpc.Server(self)
     addr = "tcp://0.0.0.0:" + self.port
     # print "address: %s", addr
     rpc_server.bind(addr)
     # print "rpc run 1"
     rpc_server.run()
Beispiel #16
0
def server_main(namespace):
    url = "tcp://{}:{}".format(namespace.interface, namespace.port)

    print "Listening to {}".format(url)

    server = zerorpc.Server(TestService())
    server.bind(url)
    server.run()
Beispiel #17
0
def main():

    addr = "tcp://127.0.0.1:4242"
    s = zerorpc.Server(Api())
    s.bind(addr)
    print("server started running on {}".format(addr))
    sys.stdout.flush()
    s.run()
def server_gan():
    image_gen = ImageGenerator()
    s = zerorpc.Server(image_gen)
    print('build server...')
    s.bind("tcp://0.0.0.0:8688")
    print('bind port...')
    s.run()
    print('server runing....')
Beispiel #19
0
def main():
    addr = sys.argv[1]
    print(addr)
    bully = Bully(addr)
    s = zerorpc.Server(bully)
    s.bind("tcp://" + addr)
    bully.start()
    s.run()
Beispiel #20
0
def main():
    t1 = threading.Thread(target=start_detector)
    t1.start()
    addr = 'tcp://127.0.0.1:' + parse_port()
    s = zerorpc.Server(Detector())
    s.bind(addr)
    print('start running on {}'.format(addr))
    s.run()
Beispiel #21
0
 def __init__(self, ip, port, methods):
     s = zerorpc.Server(methods)
     try:
         s.bind("tcp://%s:%s" % (ip, port))
         print 'rpc start %s:%s' % (ip, port)
         s.run()
     except Exception, ex:
         print("%s:%s" % (Exception, ex))
Beispiel #22
0
def main(port):
    addr = 'tcp://127.0.0.1:' + str(port)
    server = Server()
    server.register(RadiusFinder())
    s = zerorpc.Server(server)
    s.bind(addr)
    print("start running on {}. Python: {}".format(addr, sys.version))
    s.run()
Beispiel #23
0
 def run(self):
     try:
         print("SERVER_THREAD IS RUNNING")
         s = zerorpc.Server(my_chord_instance)
         s.bind("tcp://{0}:{1}".format(my_IP, default_port))
         s.run()
     except KeyboardInterrupt:
         print("Exit using KeyboardInterrupt")
Beispiel #24
0
 def main(self):
     gevent.hub.signal(signal.SIGINT, self.shutdown)
     gevent.hub.signal(signal.SIGTERM, self.shutdown)
     # self.zerorpc = zerorpc.Server(self, heartbeat=15)
     self.zerorpc = zerorpc.Server(self)
     addr = 'tcp://127.0.0.1:' + str(self.port())
     self.zerorpc.bind(addr)
     print('start running on {}'.format(addr))
     self.zerorpc.run()
Beispiel #25
0
def main():
    addr = sys.argv[1]
    bully = Bully(addr)
    s = zerorpc.Server(bully)
    s.bind('tcp://' + addr)
    bully.start()
    # Start server
    print '[%s] Starting ZeroRPC Server' % addr
    s.run()
Beispiel #26
0
def main():
    ownAddress = sys.argv[1]
    bully = BullyAlgorithm(ownAddress)
    s = zerorpc.Server(bully)
    s.bind('tcp://' + ownAddress)
    bully.start()
    # Start server
    print('[%s] Starting ZeroRPC Server' % ownAddress)
    s.run()
 def run(self):
     s = zerorpc.Server(Browser())
     s.bind("tcp://0.0.0.0:4242")
     try:
         s.run()
     except:
         print "Restarting zerorpc"
         sys.stdout.flush()
         self.run()
Beispiel #28
0
 def __init__(self, service):
     """This method initializes the service available"""
     self.port = 8888
     #self.server = zerorpc.Server(Foo(self))    # Initializing the server with the service
     self.server = zerorpc.Server(Bar(self))
     try:
         self.server.bind('tcp://0.0.0.0:{}'.format(self.port))
     except Exception as exc:
         print(exc)
Beispiel #29
0
 def __init__(self, manager):
     super(RpcThread, self).__init__()
     self._manager = manager
     self._complete = gevent.event.Event()
     if zerorpc is None:
         log.error("zerorpc package is missing")
         raise RuntimeError("Cannot run without zerorpc installed!")
     self._server = zerorpc.Server(RpcInterface(manager))
     self._bound = False
Beispiel #30
0
def Executor(name):
    print 'hello', name
    #    if sys.platform == 'linux2':
    #        import ctypes
    #        libc = ctypes.cdll.LoadLibrary('libc.so.6')
    #        libc.prctl(15, 'My Simple App', 0, 0, 0)
    s = zerorpc.Server(HelloRPC())
    s.bind("tcp://0.0.0.0:%d" % conf.exec_port)
    s.run()