Beispiel #1
0
    def testSessionResumption(self):
        # Set up a secure server
        handler = grpc.method_handlers_generic_handler('test', {
            'UnaryUnary':
            grpc.unary_unary_rpc_method_handler(handle_unary_unary)
        })
        server = test_common.test_server()
        server.add_generic_rpc_handlers((handler,))
        server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
        port = server.add_secure_port('[::]:0', server_cred)
        server.start()

        # Create a cache for TLS session tickets
        cache = session_cache.ssl_session_cache_lru(1)
        channel_creds = grpc.ssl_channel_credentials(
            root_certificates=_TEST_ROOT_CERTIFICATES)
        channel_options = _PROPERTY_OPTIONS + (
            ('grpc.ssl_session_cache', cache),)

        # Initial connection has no session to resume
        self._do_one_shot_client_rpc(
            channel_creds,
            channel_options,
            port,
            expect_ssl_session_reused=[b'false'])

        # Subsequent connections resume sessions
        self._do_one_shot_client_rpc(
            channel_creds,
            channel_options,
            port,
            expect_ssl_session_reused=[b'true'])
        server.stop(None)
Beispiel #2
0
    def testSecureNoCert(self):
        handler = grpc.method_handlers_generic_handler('test', {
            'UnaryUnary':
                grpc.unary_unary_rpc_method_handler(handle_unary_unary)
        })
        server = test_common.test_server()
        server.add_generic_rpc_handlers((handler,))
        server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
        port = server.add_secure_port('[::]:0', server_cred)
        server.start()

        channel_creds = grpc.ssl_channel_credentials(
            root_certificates=_TEST_ROOT_CERTIFICATES)
        channel = grpc.secure_channel('localhost:{}'.format(port),
                                      channel_creds,
                                      options=_PROPERTY_OPTIONS)
        response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
        channel.close()
        server.stop(None)

        auth_data = pickle.loads(response)
        self.assertIsNone(auth_data[_ID])
        self.assertIsNone(auth_data[_ID_KEY])
        self.assertDictEqual(
            {
                'security_level': [b'TSI_PRIVACY_AND_INTEGRITY'],
                'transport_security_type': [b'ssl'],
                'ssl_session_reused': [b'false'],
            }, auth_data[_AUTH_CTX])
 def setUp(self):
     self._server = test_common.test_server()
     self._server.add_generic_rpc_handlers((_GenericHandler(
         weakref.proxy(self)),))
     port = self._server.add_insecure_port('[::]:0')
     self._server.start()
     self._channel = grpc.insecure_channel('localhost:%d' % port)
Beispiel #4
0
def _CreateService():
    """Provides a servicer backend and a stub.

  Returns:
    A _Service with which to test RPCs.
  """
    servicer_methods = _ServicerMethods()

    class Servicer(getattr(service_pb2_grpc, SERVICER_IDENTIFIER)):
        def UnaryCall(self, request, context):
            return servicer_methods.UnaryCall(request, context)

        def StreamingOutputCall(self, request, context):
            return servicer_methods.StreamingOutputCall(request, context)

        def StreamingInputCall(self, request_iter, context):
            return servicer_methods.StreamingInputCall(request_iter, context)

        def FullDuplexCall(self, request_iter, context):
            return servicer_methods.FullDuplexCall(request_iter, context)

        def HalfDuplexCall(self, request_iter, context):
            return servicer_methods.HalfDuplexCall(request_iter, context)

    server = test_common.test_server()
    getattr(service_pb2_grpc, ADD_SERVICER_TO_SERVER_IDENTIFIER)(Servicer(),
                                                                 server)
    port = server.add_insecure_port('[::]:0')
    server.start()
    channel = grpc.insecure_channel('localhost:{}'.format(port))
    stub = getattr(service_pb2_grpc, STUB_IDENTIFIER)(channel)
    return _Service(servicer_methods, server, stub)
Beispiel #5
0
def serve():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--port', type=int, required=True, help='the port on which to serve')
    parser.add_argument(
        '--use_tls',
        default=False,
        type=resources.parse_bool,
        help='require a secure connection')
    args = parser.parse_args()

    server = test_common.test_server()
    test_pb2_grpc.add_TestServiceServicer_to_server(methods.TestService(),
                                                    server)
    if args.use_tls:
        private_key = resources.private_key()
        certificate_chain = resources.certificate_chain()
        credentials = grpc.ssl_server_credentials(((private_key,
                                                    certificate_chain),))
        server.add_secure_port('[::]:{}'.format(args.port), credentials)
    else:
        server.add_insecure_port('[::]:{}'.format(args.port))

    server.start()
    _LOGGER.info('Server serving.')
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except BaseException as e:
        _LOGGER.info('Caught exception "%s"; stopping server...', e)
        server.stop(None)
        _LOGGER.info('Server stopped; exiting.')
Beispiel #6
0
def serve():
    parser = argparse.ArgumentParser()
    parser.add_argument('--port',
                        type=int,
                        required=True,
                        help='the port on which to serve')
    parser.add_argument('--use_tls',
                        default=False,
                        type=resources.parse_bool,
                        help='require a secure connection')
    args = parser.parse_args()

    server = test_common.test_server()
    test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
                                                    server)
    if args.use_tls:
        private_key = resources.private_key()
        certificate_chain = resources.certificate_chain()
        credentials = grpc.ssl_server_credentials(
            ((private_key, certificate_chain), ))
        server.add_secure_port('[::]:{}'.format(args.port), credentials)
    else:
        server.add_insecure_port('[::]:{}'.format(args.port))

    server.start()
    _LOGGER.info('Server serving.')
    server.wait_for_termination()
    _LOGGER.info('Server stopped; exiting.')
Beispiel #7
0
    def testSessionResumption(self):
        # Set up a secure server
        handler = grpc.method_handlers_generic_handler('test', {
            'UnaryUnary':
                grpc.unary_unary_rpc_method_handler(handle_unary_unary)
        })
        server = test_common.test_server()
        server.add_generic_rpc_handlers((handler,))
        server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
        port = server.add_secure_port('[::]:0', server_cred)
        server.start()

        # Create a cache for TLS session tickets
        cache = session_cache.ssl_session_cache_lru(1)
        channel_creds = grpc.ssl_channel_credentials(
            root_certificates=_TEST_ROOT_CERTIFICATES)
        channel_options = _PROPERTY_OPTIONS + (
            ('grpc.ssl_session_cache', cache),)

        # Initial connection has no session to resume
        self._do_one_shot_client_rpc(channel_creds,
                                     channel_options,
                                     port,
                                     expect_ssl_session_reused=[b'false'])

        # Subsequent connections resume sessions
        self._do_one_shot_client_rpc(channel_creds,
                                     channel_options,
                                     port,
                                     expect_ssl_session_reused=[b'true'])
        server.stop(None)
Beispiel #8
0
    def testSecureNoCert(self):
        handler = grpc.method_handlers_generic_handler('test', {
            'UnaryUnary':
            grpc.unary_unary_rpc_method_handler(handle_unary_unary)
        })
        server = test_common.test_server()
        server.add_generic_rpc_handlers((handler,))
        server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
        port = server.add_secure_port('[::]:0', server_cred)
        server.start()

        channel_creds = grpc.ssl_channel_credentials(
            root_certificates=_TEST_ROOT_CERTIFICATES)
        channel = grpc.secure_channel(
            'localhost:{}'.format(port),
            channel_creds,
            options=_PROPERTY_OPTIONS)
        response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
        channel.close()
        server.stop(None)

        auth_data = pickle.loads(response)
        self.assertIsNone(auth_data[_ID])
        self.assertIsNone(auth_data[_ID_KEY])
        self.assertDictEqual({
            'transport_security_type': [b'ssl'],
            'ssl_session_reused': [b'false'],
        }, auth_data[_AUTH_CTX])
Beispiel #9
0
    def testSecureClientCert(self):
        handler = grpc.method_handlers_generic_handler('test', {
            'UnaryUnary':
            grpc.unary_unary_rpc_method_handler(handle_unary_unary)
        })
        server = test_common.test_server()
        server.add_generic_rpc_handlers((handler,))
        server_cred = grpc.ssl_server_credentials(
            _SERVER_CERTS,
            root_certificates=_TEST_ROOT_CERTIFICATES,
            require_client_auth=True)
        port = server.add_secure_port('[::]:0', server_cred)
        server.start()

        channel_creds = grpc.ssl_channel_credentials(
            root_certificates=_TEST_ROOT_CERTIFICATES,
            private_key=_PRIVATE_KEY,
            certificate_chain=_CERTIFICATE_CHAIN)
        channel = grpc.secure_channel(
            'localhost:{}'.format(port),
            channel_creds,
            options=_PROPERTY_OPTIONS)

        response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
        channel.close()
        server.stop(None)

        auth_data = pickle.loads(response)
        auth_ctx = auth_data[_AUTH_CTX]
        six.assertCountEqual(self, _CLIENT_IDS, auth_data[_ID])
        self.assertEqual('x509_subject_alternative_name', auth_data[_ID_KEY])
        self.assertSequenceEqual([b'ssl'], auth_ctx['transport_security_type'])
        self.assertSequenceEqual([b'*.test.google.com'],
                                 auth_ctx['x509_common_name'])
Beispiel #10
0
def _CreateService():
    """Provides a servicer backend and a stub.

  Returns:
    A _Service with which to test RPCs.
  """
    servicer_methods = _ServicerMethods()

    class Servicer(getattr(service_pb2_grpc, SERVICER_IDENTIFIER)):

        def UnaryCall(self, request, context):
            return servicer_methods.UnaryCall(request, context)

        def StreamingOutputCall(self, request, context):
            return servicer_methods.StreamingOutputCall(request, context)

        def StreamingInputCall(self, request_iter, context):
            return servicer_methods.StreamingInputCall(request_iter, context)

        def FullDuplexCall(self, request_iter, context):
            return servicer_methods.FullDuplexCall(request_iter, context)

        def HalfDuplexCall(self, request_iter, context):
            return servicer_methods.HalfDuplexCall(request_iter, context)

    server = test_common.test_server()
    getattr(service_pb2_grpc, ADD_SERVICER_TO_SERVER_IDENTIFIER)(Servicer(),
                                                                 server)
    port = server.add_insecure_port('[::]:0')
    server.start()
    channel = grpc.insecure_channel('localhost:{}'.format(port))
    stub = getattr(service_pb2_grpc, STUB_IDENTIFIER)(channel)
    return _Service(servicer_methods, server, stub)
Beispiel #11
0
    def testSecureClientCert(self):
        handler = grpc.method_handlers_generic_handler('test', {
            'UnaryUnary':
            grpc.unary_unary_rpc_method_handler(handle_unary_unary)
        })
        server = test_common.test_server()
        server.add_generic_rpc_handlers((handler, ))
        server_cred = grpc.ssl_server_credentials(
            _SERVER_CERTS,
            root_certificates=_TEST_ROOT_CERTIFICATES,
            require_client_auth=True)
        port = server.add_secure_port('[::]:0', server_cred)
        server.start()

        channel_creds = grpc.ssl_channel_credentials(
            root_certificates=_TEST_ROOT_CERTIFICATES,
            private_key=_PRIVATE_KEY,
            certificate_chain=_CERTIFICATE_CHAIN)
        channel = grpc.secure_channel('localhost:{}'.format(port),
                                      channel_creds,
                                      options=_PROPERTY_OPTIONS)

        response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
        server.stop(None)

        auth_data = pickle.loads(response)
        auth_ctx = auth_data[_AUTH_CTX]
        six.assertCountEqual(self, _CLIENT_IDS, auth_data[_ID])
        self.assertEqual('x509_subject_alternative_name', auth_data[_ID_KEY])
        self.assertSequenceEqual([b'ssl'], auth_ctx['transport_security_type'])
        self.assertSequenceEqual([b'*.test.google.com'],
                                 auth_ctx['x509_common_name'])
Beispiel #12
0
    def setUp(self):
        self._server = test_common.test_server()
        port = self._server.add_insecure_port('[::]:0')
        self._server.add_generic_rpc_handlers((_GenericHandler(), ))
        self._server.start()

        self._channel = grpc.insecure_channel('localhost:%d' % port)
 def setUp(self):
     self.server = test_common.test_server()
     test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
                                                     self.server)
     port = self.server.add_insecure_port('[::]:0')
     self.server.start()
     self.stub = test_pb2_grpc.TestServiceStub(
         grpc.insecure_channel('localhost:{}'.format(port)))
    def setUp(self):
        self._server = test_common.test_server()
        reflection.enable_server_reflection(_SERVICE_NAMES, self._server)
        port = self._server.add_insecure_port('[::]:0')
        self._server.start()

        channel = grpc.insecure_channel('localhost:%d' % port)
        self._stub = reflection_pb2_grpc.ServerReflectionStub(channel)
Beispiel #15
0
    def setUp(self):
        self._server = test_common.test_server()
        port = self._server.add_insecure_port('[::]:0')
        self._server.add_generic_rpc_handlers((_GenericHandler(self.case), ))
        self._server.start()

        self._channel = grpc.insecure_channel('localhost:%d' % port)
        self._multi_callable = self._channel.stream_stream(_RPC_METHOD)
Beispiel #16
0
def run_worker_server(port):
    server = test_common.test_server()
    servicer = worker_server.WorkerServer()
    services_pb2_grpc.add_WorkerServiceServicer_to_server(servicer, server)
    server.add_insecure_port('[::]:{}'.format(port))
    server.start()
    servicer.wait_for_quit()
    server.stop(0)
 def setUp(self):
     self.server = test_common.test_server()
     test_pb2_grpc.add_TestServiceServicer_to_server(
         service.TestService(), self.server)
     port = self.server.add_insecure_port('[::]:0')
     self.server.start()
     self.stub = test_pb2_grpc.TestServiceStub(
         grpc.insecure_channel('localhost:{}'.format(port)))
Beispiel #18
0
 def setUp(self):
     self._server = test_common.test_server()
     self._server.add_generic_rpc_handlers(
         (_GenericHandler(weakref.proxy(self)), ))
     port = self._server.add_insecure_port('[::]:0')
     self._server.start()
     self._channel = grpc.insecure_channel('localhost:%d' % port,
                                           options=_CHANNEL_ARGS)
Beispiel #19
0
    def setUp(self):
        self._server = test_common.test_server()
        reflection.enable_server_reflection(_SERVICE_NAMES, self._server)
        port = self._server.add_insecure_port('[::]:0')
        self._server.start()

        self._channel = grpc.insecure_channel('localhost:%d' % port)
        self._stub = reflection_pb2_grpc.ServerReflectionStub(self._channel)
Beispiel #20
0
 def setUp(self):
     super(SimpleStubsPluginTest, self).setUp()
     self._server = test_common.test_server()
     service_pb2_grpc.add_TestServiceServicer_to_server(
         self.Servicer(), self._server)
     self._port = self._server.add_insecure_port('[::]:0')
     self._server.start()
     self._target = 'localhost:{}'.format(self._port)
def run_server(port_queue):
    server = test_common.test_server()
    port = server.add_insecure_port('[::]:0')
    port_queue.put(port)
    server.add_generic_rpc_handlers((GenericHandler(),))
    server.start()
    # threading.Event.wait() does not exhibit the bug identified in
    # https://github.com/grpc/grpc/issues/17093, sleep instead
    time.sleep(WAIT_TIME)
def run_server(port_queue):
    server = test_common.test_server()
    port = server.add_insecure_port('[::]:0')
    port_queue.put(port)
    server.add_generic_rpc_handlers((GenericHandler(), ))
    server.start()
    # threading.Event.wait() does not exhibit the bug identified in
    # https://github.com/grpc/grpc/issues/17093, sleep instead
    time.sleep(WAIT_TIME)
    def test_call_wait_for_ready_enabled(self):
        # To test the wait mechanism, Python thread is required to make
        #   client set up first without handling them case by case.
        # Also, Python thread don't pass the unhandled exceptions to
        #   main thread. So, it need another method to store the
        #   exceptions and raise them again in main thread.
        unhandled_exceptions = queue.Queue()

        # We just need an unused TCP port
        host, port, sock = get_socket(sock_options=(socket.SO_REUSEADDR, ))
        sock.close()

        addr = '{}:{}'.format(host, port)
        wg = test_common.WaitGroup(len(_ALL_CALL_CASES))

        def wait_for_transient_failure(channel_connectivity):
            if channel_connectivity == grpc.ChannelConnectivity.TRANSIENT_FAILURE:
                wg.done()

        def test_call(perform_call):
            with grpc.insecure_channel(addr) as channel:
                try:
                    channel.subscribe(wait_for_transient_failure)
                    perform_call(channel, wait_for_ready=True)
                except BaseException as e:  # pylint: disable=broad-except
                    # If the call failed, the thread would be destroyed. The
                    # channel object can be collected before calling the
                    # callback, which will result in a deadlock.
                    wg.done()
                    unhandled_exceptions.put(e, True)

        test_threads = []
        for perform_call in _ALL_CALL_CASES:
            test_thread = threading.Thread(target=test_call,
                                           args=(perform_call, ))
            test_thread.daemon = True
            test_thread.exception = None
            test_thread.start()
            test_threads.append(test_thread)

        # Start the server after the connections are waiting
        wg.wait()
        server = test_common.test_server(reuse_port=True)
        server.add_generic_rpc_handlers(
            (_GenericHandler(weakref.proxy(self)), ))
        server.add_insecure_port(addr)
        server.start()

        for test_thread in test_threads:
            test_thread.join()

        # Stop the server to make test end properly
        server.stop(0)

        if not unhandled_exceptions.empty():
            raise unhandled_exceptions.get(True)
Beispiel #24
0
    def setUp(self):
        self._control = test_control.PauseFailControl()
        self._handler = _Handler(self._control)

        self._server = test_common.test_server()
        port = self._server.add_insecure_port('[::]:0')
        self._server.add_generic_rpc_handlers((_GenericHandler(self._handler),))
        self._server.start()

        self._channel = grpc.insecure_channel('localhost:%d' % port)
def _server():
    try:
        server = test_common.test_server()
        target = 'localhost:0'
        port = server.add_insecure_port(target)
        server.add_generic_rpc_handlers((_GenericHandler(),))
        server.start()
        yield port
    finally:
        server.stop(None)
def start_secure_server():
    handler = grpc.method_handlers_generic_handler(
        'test',
        {'UnaryUnary': grpc.unary_unary_rpc_method_handler(handle_unary_unary)})
    server = test_common.test_server()
    server.add_generic_rpc_handlers((handler,))
    server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
    port = server.add_secure_port('[::]:0', server_cred)
    server.start()

    return server, port
Beispiel #27
0
    def setUp(self):
        self._control = test_control.PauseFailControl()
        self._thread_pool = thread_pool.RecordingThreadPool(max_workers=None)
        self._handler = _Handler(self._control, self._thread_pool)

        self._server = test_common.test_server()
        port = self._server.add_insecure_port('[::]:0')
        self._server.add_generic_rpc_handlers((_GenericHandler(self._handler),))
        self._server.start()

        self._channel = grpc.insecure_channel('localhost:%d' % port)
Beispiel #28
0
def start_secure_server():
    handler = grpc.method_handlers_generic_handler('test', {
        'UnaryUnary':
        grpc.unary_unary_rpc_method_handler(handle_unary_unary)
    })
    server = test_common.test_server()
    server.add_generic_rpc_handlers((handler,))
    server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
    port = server.add_secure_port('[::]:0', server_cred)
    server.start()

    return server, port
Beispiel #29
0
    def test_call(self):
        self._protoc()

        for services_module in self._services_modules():
            server = test_common.test_server()
            services_module.add_TestServiceServicer_to_server(
                _Servicer(self._messages_pb2.Response), server)
            port = server.add_insecure_port('[::]:0')
            server.start()
            channel = grpc.insecure_channel('localhost:{}'.format(port))
            stub = services_module.TestServiceStub(channel)
            response = stub.Call(self._messages_pb2.Request())
            self.assertEqual(self._messages_pb2.Response(), response)
Beispiel #30
0
    def test_call(self):
        self._protoc()

        for services_module in self._services_modules():
            server = test_common.test_server()
            services_module.add_TestServiceServicer_to_server(
                _Servicer(self._messages_pb2.Response), server)
            port = server.add_insecure_port('[::]:0')
            server.start()
            channel = grpc.insecure_channel('localhost:{}'.format(port))
            stub = services_module.TestServiceStub(channel)
            response = stub.Call(self._messages_pb2.Request())
            self.assertEqual(self._messages_pb2.Response(), response)
Beispiel #31
0
def _server(credentials: Optional[grpc.ServerCredentials]):
    try:
        server = test_common.test_server()
        target = '[::]:0'
        if credentials is None:
            port = server.add_insecure_port(target)
        else:
            port = server.add_secure_port(target, credentials)
        server.add_generic_rpc_handlers((_GenericHandler(), ))
        server.start()
        yield port
    finally:
        server.stop(None)
Beispiel #32
0
    def test_call_wait_for_ready_enabled(self):
        # To test the wait mechanism, Python thread is required to make
        #   client set up first without handling them case by case.
        # Also, Python thread don't pass the unhandled exceptions to
        #   main thread. So, it need another method to store the
        #   exceptions and raise them again in main thread.
        unhandled_exceptions = queue.Queue()
        tcp, addr = get_free_loopback_tcp_port()
        wg = test_common.WaitGroup(len(_ALL_CALL_CASES))

        def wait_for_transient_failure(channel_connectivity):
            if channel_connectivity == grpc.ChannelConnectivity.TRANSIENT_FAILURE:
                wg.done()

        def test_call(perform_call):
            with grpc.insecure_channel(addr) as channel:
                try:
                    channel.subscribe(wait_for_transient_failure)
                    perform_call(channel, wait_for_ready=True)
                except BaseException as e:  # pylint: disable=broad-except
                    # If the call failed, the thread would be destroyed. The
                    # channel object can be collected before calling the
                    # callback, which will result in a deadlock.
                    wg.done()
                    unhandled_exceptions.put(e, True)

        test_threads = []
        for perform_call in _ALL_CALL_CASES:
            test_thread = threading.Thread(
                target=test_call, args=(perform_call,))
            test_thread.exception = None
            test_thread.start()
            test_threads.append(test_thread)

        # Start the server after the connections are waiting
        wg.wait()
        tcp.close()
        server = test_common.test_server()
        server.add_generic_rpc_handlers((_GenericHandler(weakref.proxy(self)),))
        server.add_insecure_port(addr)
        server.start()

        for test_thread in test_threads:
            test_thread.join()

        # Stop the server to make test end properly
        server.stop(0)

        if not unhandled_exceptions.empty():
            raise unhandled_exceptions.get(True)
Beispiel #33
0
    def setUp(self):
        self._server = test_common.test_server()
        self._SERVICE_NAMES = (
            test_pb2.DESCRIPTOR.services_by_name["TestService"].full_name,
            reflection.SERVICE_NAME,
        )
        reflection.enable_server_reflection(self._SERVICE_NAMES, self._server)
        port = self._server.add_insecure_port("[::]:0")
        self._server.start()

        self._channel = grpc.insecure_channel("localhost:%d" % port)

        self._reflection_db = ProtoReflectionDescriptorDatabase(self._channel)
        self.desc_pool = DescriptorPool(self._reflection_db)
def run_test(args):
    if args.scenario == SERVER_RAISES_EXCEPTION:
        server = test_common.test_server()
        server.start()
        raise Exception()
    elif args.scenario == SERVER_DEALLOCATED:
        server = test_common.test_server()
        server.start()
        server.__del__()
        while server._state.stage != grpc._server._ServerStage.STOPPED:
            pass
    elif args.scenario == SERVER_FORK_CAN_EXIT:
        port_queue = queue.Queue()
        thread = threading.Thread(target=run_server, args=(port_queue,))
        thread.daemon = True
        thread.start()
        port = port_queue.get()
        channel = grpc.insecure_channel('localhost:%d' % port)
        multi_callable = channel.unary_unary(FORK_EXIT)
        result, call = multi_callable.with_call(REQUEST, wait_for_ready=True)
        os.wait()
    else:
        raise ValueError('unknown test scenario')
def run_test(args):
    if args.scenario == SERVER_RAISES_EXCEPTION:
        server = test_common.test_server()
        server.start()
        raise Exception()
    elif args.scenario == SERVER_DEALLOCATED:
        server = test_common.test_server()
        server.start()
        server.__del__()
        while server._state.stage != grpc._server._ServerStage.STOPPED:
            pass
    elif args.scenario == SERVER_FORK_CAN_EXIT:
        port_queue = queue.Queue()
        thread = threading.Thread(target=run_server, args=(port_queue, ))
        thread.daemon = True
        thread.start()
        port = port_queue.get()
        channel = grpc.insecure_channel('localhost:%d' % port)
        multi_callable = channel.unary_unary(FORK_EXIT)
        result, call = multi_callable.with_call(REQUEST, wait_for_ready=True)
        os.wait()
    else:
        raise ValueError('unknown test scenario')
 def setUp(self):
     self.server = test_common.test_server()
     services_pb2_grpc.add_FirstServiceServicer_to_server(
         _server_application.FirstServiceServicer(), self.server)
     switch_cert_on_client_num = 10
     initial_cert_config = grpc.ssl_server_certificate_configuration(
         [(SERVER_KEY_1_PEM, SERVER_CERT_CHAIN_1_PEM)],
         root_certificates=CA_2_PEM)
     self.cert_config_fetcher = CertConfigFetcher()
     server_credentials = grpc.dynamic_ssl_server_credentials(
         initial_cert_config,
         self.cert_config_fetcher,
         require_client_authentication=self.require_client_auth())
     self.port = self.server.add_secure_port('[::]:0', server_credentials)
     self.server.start()
Beispiel #37
0
 def _on_connectivity_changed(connectivity):
     nonlocal server
     if connectivity is grpc.ChannelConnectivity.TRANSIENT_FAILURE:
         self.assertFalse(rpc_finished_event.is_set())
         self.assertFalse(rpc_failed_event.is_set())
         server = test_common.test_server()
         server.add_insecure_port(target)
         server.add_generic_rpc_handlers((_GenericHandler(), ))
         server.start()
         channel.unsubscribe(_on_connectivity_changed)
     elif connectivity in (grpc.ChannelConnectivity.IDLE,
                           grpc.ChannelConnectivity.CONNECTING):
         pass
     else:
         self.fail("Encountered unknown state.")
Beispiel #38
0
 def setUp(self):
     self.server = test_common.test_server()
     services_pb2_grpc.add_FirstServiceServicer_to_server(
         _server_application.FirstServiceServicer(), self.server)
     switch_cert_on_client_num = 10
     initial_cert_config = grpc.ssl_server_certificate_configuration(
         [(SERVER_KEY_1_PEM, SERVER_CERT_CHAIN_1_PEM)],
         root_certificates=CA_2_PEM)
     self.cert_config_fetcher = CertConfigFetcher()
     server_credentials = grpc.dynamic_ssl_server_credentials(
         initial_cert_config,
         self.cert_config_fetcher,
         require_client_authentication=self.require_client_auth())
     self.port = self.server.add_secure_port('[::]:0', server_credentials)
     self.server.start()
Beispiel #39
0
 def setUp(self):
     self.server = test_common.test_server()
     test_pb2_grpc.add_TestServiceServicer_to_server(methods.TestService(),
                                                     self.server)
     port = self.server.add_secure_port(
         '[::]:0',
         grpc.ssl_server_credentials([(resources.private_key(),
                                       resources.certificate_chain())]))
     self.server.start()
     self.stub = test_pb2_grpc.TestServiceStub(
         grpc.secure_channel('localhost:{}'.format(port),
                             grpc.ssl_channel_credentials(
                                 resources.test_root_certificates()), ((
                                     'grpc.ssl_target_name_override',
                                     _SERVER_HOST_OVERRIDE,
                                 ),)))
Beispiel #40
0
def serve():
    args = parse_interop_server_arguments()

    server = test_common.test_server()
    test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
                                                    server)
    if args.use_tls:
        credentials = get_server_credentials()
        server.add_secure_port('[::]:{}'.format(args.port), credentials)
    else:
        server.add_insecure_port('[::]:{}'.format(args.port))

    server.start()
    _LOGGER.info('Server serving.')
    server.wait_for_termination()
    _LOGGER.info('Server stopped; exiting.')
Beispiel #41
0
    def setUp(self):
        servicer = health.HealthServicer()
        servicer.set('', health_pb2.HealthCheckResponse.SERVING)
        servicer.set('grpc.test.TestServiceServing',
                     health_pb2.HealthCheckResponse.SERVING)
        servicer.set('grpc.test.TestServiceUnknown',
                     health_pb2.HealthCheckResponse.UNKNOWN)
        servicer.set('grpc.test.TestServiceNotServing',
                     health_pb2.HealthCheckResponse.NOT_SERVING)
        self._server = test_common.test_server()
        port = self._server.add_insecure_port('[::]:0')
        health_pb2_grpc.add_HealthServicer_to_server(servicer, self._server)
        self._server.start()

        channel = grpc.insecure_channel('localhost:%d' % port)
        self._stub = health_pb2_grpc.HealthStub(channel)
    def setUp(self):
        servicer = health.HealthServicer()
        servicer.set('', health_pb2.HealthCheckResponse.SERVING)
        servicer.set('grpc.test.TestServiceServing',
                     health_pb2.HealthCheckResponse.SERVING)
        servicer.set('grpc.test.TestServiceUnknown',
                     health_pb2.HealthCheckResponse.UNKNOWN)
        servicer.set('grpc.test.TestServiceNotServing',
                     health_pb2.HealthCheckResponse.NOT_SERVING)
        self._server = test_common.test_server()
        port = self._server.add_insecure_port('[::]:0')
        health_pb2_grpc.add_HealthServicer_to_server(servicer, self._server)
        self._server.start()

        channel = grpc.insecure_channel('localhost:%d' % port)
        self._stub = health_pb2_grpc.HealthStub(channel)
Beispiel #43
0
    def testInsecure(self):
        handler = grpc.method_handlers_generic_handler('test', {
            'UnaryUnary':
            grpc.unary_unary_rpc_method_handler(handle_unary_unary)
        })
        server = test_common.test_server()
        server.add_generic_rpc_handlers((handler, ))
        port = server.add_insecure_port('[::]:0')
        server.start()

        channel = grpc.insecure_channel('localhost:%d' % port)
        response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
        server.stop(None)

        auth_data = pickle.loads(response)
        self.assertIsNone(auth_data[_ID])
        self.assertIsNone(auth_data[_ID_KEY])
        self.assertDictEqual({}, auth_data[_AUTH_CTX])
Beispiel #44
0
def _CreateIncompleteService():
    """Provides a servicer backend that fails to implement methods and its stub.

  Returns:
    A _Service with which to test RPCs. The returned _Service's
      servicer_methods implements none of the methods required of it.
  """
    class Servicer(getattr(service_pb2_grpc, SERVICER_IDENTIFIER)):
        pass

    server = test_common.test_server()
    getattr(service_pb2_grpc, ADD_SERVICER_TO_SERVER_IDENTIFIER)(Servicer(),
                                                                 server)
    port = server.add_insecure_port('[::]:0')
    server.start()
    channel = grpc.insecure_channel('localhost:{}'.format(port))
    stub = getattr(service_pb2_grpc, STUB_IDENTIFIER)(channel)
    return _Service(None, server, stub)
    def setUp(self):
        self._servicer = _InspectServicer()
        self._server = test_common.test_server()
        self._server.add_generic_rpc_handlers(
            (_generic_handler(self._servicer), ))
        port = self._server.add_insecure_port('[::]:0')
        self._server.start()

        self._channel = grpc.insecure_channel('localhost:{}'.format(port))
        self._unary_unary = self._channel.unary_unary(
            '/'.join((
                '',
                _SERVICE,
                _UNARY_UNARY,
            )),
            request_serializer=_REQUEST_SERIALIZER,
            response_deserializer=_RESPONSE_DESERIALIZER,
        )
Beispiel #46
0
    def testInsecure(self):
        handler = grpc.method_handlers_generic_handler('test', {
            'UnaryUnary':
            grpc.unary_unary_rpc_method_handler(handle_unary_unary)
        })
        server = test_common.test_server()
        server.add_generic_rpc_handlers((handler,))
        port = server.add_insecure_port('[::]:0')
        server.start()

        with grpc.insecure_channel('localhost:%d' % port) as channel:
            response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
        server.stop(None)

        auth_data = pickle.loads(response)
        self.assertIsNone(auth_data[_ID])
        self.assertIsNone(auth_data[_ID_KEY])
        self.assertDictEqual({}, auth_data[_AUTH_CTX])
Beispiel #47
0
def _CreateIncompleteService():
    """Provides a servicer backend that fails to implement methods and its stub.

  Returns:
    A _Service with which to test RPCs. The returned _Service's
      servicer_methods implements none of the methods required of it.
  """

    class Servicer(getattr(service_pb2_grpc, SERVICER_IDENTIFIER)):
        pass

    server = test_common.test_server()
    getattr(service_pb2_grpc, ADD_SERVICER_TO_SERVER_IDENTIFIER)(Servicer(),
                                                                 server)
    port = server.add_insecure_port('[::]:0')
    server.start()
    channel = grpc.insecure_channel('localhost:{}'.format(port))
    stub = getattr(service_pb2_grpc, STUB_IDENTIFIER)(channel)
    return _Service(None, server, stub)
        def start_server(self, non_blocking=False, thread_pool=None):
            self._thread_pool = thread_pool
            self._servicer = health.HealthServicer(
                experimental_non_blocking=non_blocking,
                experimental_thread_pool=thread_pool)
            self._servicer.set('', health_pb2.HealthCheckResponse.SERVING)
            self._servicer.set(_SERVING_SERVICE,
                               health_pb2.HealthCheckResponse.SERVING)
            self._servicer.set(_UNKNOWN_SERVICE,
                               health_pb2.HealthCheckResponse.UNKNOWN)
            self._servicer.set(_NOT_SERVING_SERVICE,
                               health_pb2.HealthCheckResponse.NOT_SERVING)
            self._server = test_common.test_server()
            port = self._server.add_insecure_port('[::]:0')
            health_pb2_grpc.add_HealthServicer_to_server(
                self._servicer, self._server)
            self._server.start()

            self._channel = grpc.insecure_channel('localhost:%d' % port)
            self._stub = health_pb2_grpc.HealthStub(self._channel)
    def setUp(self):
        self._servicer = _Servicer()
        self._server = test_common.test_server()
        self._server.add_generic_rpc_handlers(
            (_generic_handler(self._servicer),))
        port = self._server.add_insecure_port('[::]:0')
        self._server.start()

        channel = grpc.insecure_channel('localhost:{}'.format(port))
        self._unary_unary = channel.unary_unary(
            '/'.join((
                '',
                _SERVICE,
                _UNARY_UNARY,
            )),
            request_serializer=_REQUEST_SERIALIZER,
            response_deserializer=_RESPONSE_DESERIALIZER,
        )
        self._unary_stream = channel.unary_stream('/'.join((
            '',
            _SERVICE,
            _UNARY_STREAM,
        )),)
        self._stream_unary = channel.stream_unary('/'.join((
            '',
            _SERVICE,
            _STREAM_UNARY,
        )),)
        self._stream_stream = channel.stream_stream(
            '/'.join((
                '',
                _SERVICE,
                _STREAM_STREAM,
            )),
            request_serializer=_REQUEST_SERIALIZER,
            response_deserializer=_RESPONSE_DESERIALIZER,
        )
Beispiel #50
0
    def _create_server(self, config):
        if config.async_server_threads == 0:
            # This is the default concurrent.futures thread pool size, but
            # None doesn't seem to work
            server_threads = multiprocessing.cpu_count() * 5
        else:
            server_threads = config.async_server_threads
        server = test_common.test_server(max_workers=server_threads)
        if config.server_type == control_pb2.ASYNC_SERVER:
            servicer = benchmark_server.BenchmarkServer()
            worker_service_pb2_grpc.add_BenchmarkServiceServicer_to_server(
                servicer, server)
        elif config.server_type == control_pb2.ASYNC_GENERIC_SERVER:
            resp_size = config.payload_config.bytebuf_params.resp_size
            servicer = benchmark_server.GenericBenchmarkServer(resp_size)
            method_implementations = {
                'StreamingCall':
                grpc.stream_stream_rpc_method_handler(servicer.StreamingCall),
                'UnaryCall':
                grpc.unary_unary_rpc_method_handler(servicer.UnaryCall),
            }
            handler = grpc.method_handlers_generic_handler(
                'grpc.testing.BenchmarkService', method_implementations)
            server.add_generic_rpc_handlers((handler,))
        else:
            raise Exception('Unsupported server type {}'.format(
                config.server_type))

        if config.HasField('security_params'):  # Use SSL
            server_creds = grpc.ssl_server_credentials(
                ((resources.private_key(), resources.certificate_chain()),))
            port = server.add_secure_port('[::]:{}'.format(config.port),
                                          server_creds)
        else:
            port = server.add_insecure_port('[::]:{}'.format(config.port))

        return (server, port)
Beispiel #51
0
 def setUp(self):
     self._server = test_common.test_server()
     self._server.add_generic_rpc_handlers((GenericHandler(),))
     self._port = self._server.add_insecure_port('[::]:0')
     self._server.start()
 def setUp(self):
     self._server = test_common.test_server(
         max_workers=test_constants.THREAD_CONCURRENCY)
     self._server.add_generic_rpc_handlers((_GENERIC_HANDLER,))
     self._port = self._server.add_insecure_port('[::]:0')
     self._server.start()