async def test_watch_service_status(loop):
    svc = Service()
    s1 = ServiceStatus(loop=loop)
    s2 = ServiceStatus(loop=loop)
    health = Health({svc: [s1, s2]})
    with channel_for([svc, health], loop=loop) as channel:
        stub = HealthStub(channel)
        async with stub.Watch.open() as stream:
            await stream.send_message(
                HealthCheckRequest(service=Service.__name__, ))
            assert await stream.recv_message() == HealthCheckResponse(
                status=HealthCheckResponse.UNKNOWN, )
            s1.set(True)
            assert await stream.recv_message() == HealthCheckResponse(
                status=HealthCheckResponse.NOT_SERVING, )
            s2.set(True)
            assert await stream.recv_message() == HealthCheckResponse(
                status=HealthCheckResponse.SERVING, )
            s1.set(False)
            assert await stream.recv_message() == HealthCheckResponse(
                status=HealthCheckResponse.NOT_SERVING, )
            s1.set(True)
            assert await stream.recv_message() == HealthCheckResponse(
                status=HealthCheckResponse.SERVING, )

            # check that there are no unnecessary messages if status isn't
            # changed
            s1.set(True)
            try:
                with async_timeout.timeout(0.01):
                    assert not await stream.recv_message()
            except asyncio.TimeoutError:
                pass

            await stream.cancel()
async def test_check_zero_checks():
    svc = Service()
    health = Health({svc: []})
    async with ChannelFor([svc, health]) as channel:
        stub = HealthStub(channel)
        response = await stub.Check(HealthCheckRequest(service=SERVICE_NAME))
        assert response == HealthCheckResponse(
            status=HealthCheckResponse.SERVING, )
async def test_check_unknown_service():
    svc = Service()
    health = Health({svc: []})
    async with ChannelFor([svc, health]) as channel:
        stub = HealthStub(channel)
        with pytest.raises(GRPCError) as err:
            await stub.Check(HealthCheckRequest(service='Unknown'))
        assert err.value.status == Status.NOT_FOUND
async def test_check_zero_checks(loop):
    svc = Service()
    health = Health({svc: []})
    with channel_for([svc, health], loop=loop) as channel:
        stub = HealthStub(channel)
        response = await stub.Check(
            HealthCheckRequest(service=Service.__name__, ))
        assert response == HealthCheckResponse(
            status=HealthCheckResponse.SERVING, )
async def test_check_unknown_service(loop):
    svc = Service()
    health = Health({svc: []})
    with channel_for([svc, health], loop=loop) as channel:
        stub = HealthStub(channel)

        with pytest.raises(GRPCError):
            await stub.Check(HealthCheckRequest())

        with pytest.raises(GRPCError):
            await stub.Check(HealthCheckRequest(service='Unknown'))
async def test_check_service_status(v1, v2, status):
    svc = Service()
    s1 = ServiceStatus()
    s2 = ServiceStatus()
    health = Health({svc: [s1, s2]})
    async with ChannelFor([svc, health]) as channel:
        stub = HealthStub(channel)
        s1.set(v1)
        s2.set(v2)
        response = await stub.Check(HealthCheckRequest(service=SERVICE_NAME))
        assert response == HealthCheckResponse(status=status)
Exemple #7
0
async def main(*, host: str = '0.0.0.0', port: int = 50051) -> None:
    server = Server([Health()])
    with graceful_exit([server]):
        await server.start(host,
                           port,
                           ssl=create_secure_context(
                               SERVER_CERT,
                               SERVER_KEY,
                               trusted=CLIENT_CERT,
                           ))
        print(f'Serving on {host}:{port}')
        await server.wait_closed()
Exemple #8
0
    def configure(self, value: grpc_pb2.Server):
        assert isinstance(value, grpc_pb2.Server), type(value)
        self._config = value

        handlers = list(self.handlers)
        if not any(isinstance(h, Health) for h in handlers):
            handlers.append(Health())
        handlers = ServerReflection.extend(handlers)

        self.server = Server(handlers)
        listen(self.server, RecvRequest, _recv_request)
        listen(self.server, SendTrailingMetadata, _send_trailing_metadata)
async def test_check_service_status(loop, v1, v2, status):
    svc = Service()
    s1 = ServiceStatus(loop=loop)
    s2 = ServiceStatus(loop=loop)
    health = Health({svc: [s1, s2]})
    with channel_for([svc, health], loop=loop) as channel:
        stub = HealthStub(channel)
        s1.set(v1)
        s2.set(v2)
        response = await stub.Check(
            HealthCheckRequest(service=Service.__name__, ))
        assert response == HealthCheckResponse(status=status)
Exemple #10
0
 def __init__(
         self,
         golem_app,
         port: int,
         lifecycle: AppLifecycleHandler,
         ssl_context: Optional[ssl.SSLContext] = None,
 ) -> None:
     self._server = server.Server(
         handlers=[golem_app, Health()],
         loop=asyncio.get_event_loop(),
     )
     self._port = port
     self._lifecycle = lifecycle
     self._ssl_context = ssl_context
async def test_check_service_check(loop, v1, v2, status):
    svc = Service()
    c1 = Check()
    c2 = Check()
    health = Health({svc: [
        ServiceCheck(c1, check_ttl=0),
        ServiceCheck(c2, check_ttl=0),
    ]})
    async with ChannelFor([svc, health]) as channel:
        stub = HealthStub(channel)
        c1.__current_status__ = v1
        c2.__current_status__ = v2
        response = await stub.Check(HealthCheckRequest(service=SERVICE_NAME))
        assert response == HealthCheckResponse(status=status)
Exemple #12
0
async def main():
    svc = Service()
    loop = asyncio.get_event_loop()
    test_check = ServiceCheck(test, loop=loop, check_ttl=5)
    health = Health({svc: [test_check]})
    print(svc)
    print(health)
    async with ChannelFor([svc, health]) as channel:
        print(channel)
        stub = HealthStub(channel)
        print(stub)
        async with stub.Watch.open() as stream:
            await stream.send_message(
                HealthCheckRequest(service=Service.__name__, ))
            await stream.recv_message()
async def test_watch_unknown_service(loop, request):
    svc = Service()
    health = Health({svc: []})
    with channel_for([svc, health], loop=loop) as channel:
        stub = HealthStub(channel)
        async with stub.Watch.open() as stream:
            await stream.send_message(request, end=True)
            assert await stream.recv_message() == HealthCheckResponse(
                status=HealthCheckResponse.SERVICE_UNKNOWN, )
            try:
                with async_timeout.timeout(0.01):
                    assert not await stream.recv_message()
            except asyncio.TimeoutError:
                pass
            await stream.cancel()
async def test_check_service_check(loop, v1, v2, status):
    svc = Service()
    c1 = Check()
    c2 = Check()
    health = Health({
        svc: [
            ServiceCheck(c1, loop=loop, check_ttl=0),
            ServiceCheck(c2, loop=loop, check_ttl=0),
        ]
    })
    with channel_for([svc, health], loop=loop) as channel:
        stub = HealthStub(channel)
        c1.__current_status__ = v1
        c2.__current_status__ = v2
        response = await stub.Check(
            HealthCheckRequest(service=Service.__name__, ))
        assert response == HealthCheckResponse(status=status)
async def test_watch_zero_checks(loop):
    svc = Service()
    health = Health({svc: []})
    with channel_for([svc, health], loop=loop) as channel:
        stub = HealthStub(channel)
        async with stub.Watch.open() as stream:
            await stream.send_message(
                HealthCheckRequest(service=Service.__name__, ))
            response = await stream.recv_message()
            assert response == HealthCheckResponse(
                status=HealthCheckResponse.SERVING, )
            try:
                with async_timeout.timeout(0.01):
                    assert not await stream.recv_message()
            except asyncio.TimeoutError:
                pass
            await stream.cancel()
async def test_watch_service_check():
    svc = Service()
    c1 = Check()
    c2 = Check()
    health = Health({svc: [
        ServiceCheck(c1, check_ttl=0.001),
        ServiceCheck(c2, check_ttl=0.001),
    ]})
    async with ChannelFor([svc, health]) as channel:
        stub = HealthStub(channel)
        async with stub.Watch.open() as stream:
            await stream.send_message(HealthCheckRequest(service=SERVICE_NAME),
                                      end=True)
            assert await stream.recv_message() == HealthCheckResponse(
                status=HealthCheckResponse.UNKNOWN,
            )

            # check that there are no unnecessary messages
            try:
                with async_timeout.timeout(0.01):
                    assert not await stream.recv_message()
            except asyncio.TimeoutError:
                pass

            c1.__current_status__ = True
            assert await stream.recv_message() == HealthCheckResponse(
                status=HealthCheckResponse.NOT_SERVING,
            )
            c2.__current_status__ = True
            assert await stream.recv_message() == HealthCheckResponse(
                status=HealthCheckResponse.SERVING,
            )
            c1.__current_status__ = False
            assert await stream.recv_message() == HealthCheckResponse(
                status=HealthCheckResponse.NOT_SERVING,
            )
            c1.__current_status__ = True
            assert await stream.recv_message() == HealthCheckResponse(
                status=HealthCheckResponse.SERVING,
            )
            await stream.cancel()
    def __init__(
        self,
        handlers: List['IServable'],

        # grpclib.server.Server kwargs
        server_kwargs: Optional[Dict[str, Any]] = None,

        # Token auth middleware
        api_token: str = "",
        api_token_header: str = API_TOKEN_HEADER,

        # Peer whitelist middleware
        peer_whitelist: List[Union[IPv4Network, IPv6Network]] = [],
    ):
        if server_kwargs is None:
            server_kwargs = dict()

        handlers.append(Health())
        self.server: GRPCLibServer = GRPCLibServer(handlers=handlers, **server_kwargs)
        attach_middlewares(
            server=self.server,
            api_token=api_token, api_token_header=api_token_header,
            peer_whitelist=peer_whitelist
        )