_server.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # Copyright 2019 The gRPC Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Server-side implementation of gRPC Asyncio Python."""
  15. from concurrent.futures import Executor
  16. from typing import Any, Optional, Sequence
  17. import grpc
  18. from grpc import _common
  19. from grpc import _compression
  20. from grpc._cython import cygrpc
  21. from . import _base_server
  22. from ._interceptor import ServerInterceptor
  23. from ._typing import ChannelArgumentType
  24. def _augment_channel_arguments(base_options: ChannelArgumentType,
  25. compression: Optional[grpc.Compression]):
  26. compression_option = _compression.create_channel_option(compression)
  27. return tuple(base_options) + compression_option
  28. class Server(_base_server.Server):
  29. """Serves RPCs."""
  30. def __init__(self, thread_pool: Optional[Executor],
  31. generic_handlers: Optional[Sequence[grpc.GenericRpcHandler]],
  32. interceptors: Optional[Sequence[Any]],
  33. options: ChannelArgumentType,
  34. maximum_concurrent_rpcs: Optional[int],
  35. compression: Optional[grpc.Compression]):
  36. self._loop = cygrpc.get_working_loop()
  37. if interceptors:
  38. invalid_interceptors = [
  39. interceptor for interceptor in interceptors
  40. if not isinstance(interceptor, ServerInterceptor)
  41. ]
  42. if invalid_interceptors:
  43. raise ValueError(
  44. 'Interceptor must be ServerInterceptor, the '
  45. f'following are invalid: {invalid_interceptors}')
  46. self._server = cygrpc.AioServer(
  47. self._loop, thread_pool, generic_handlers, interceptors,
  48. _augment_channel_arguments(options, compression),
  49. maximum_concurrent_rpcs)
  50. def add_generic_rpc_handlers(
  51. self,
  52. generic_rpc_handlers: Sequence[grpc.GenericRpcHandler]) -> None:
  53. """Registers GenericRpcHandlers with this Server.
  54. This method is only safe to call before the server is started.
  55. Args:
  56. generic_rpc_handlers: A sequence of GenericRpcHandlers that will be
  57. used to service RPCs.
  58. """
  59. self._server.add_generic_rpc_handlers(generic_rpc_handlers)
  60. def add_insecure_port(self, address: str) -> int:
  61. """Opens an insecure port for accepting RPCs.
  62. This method may only be called before starting the server.
  63. Args:
  64. address: The address for which to open a port. If the port is 0,
  65. or not specified in the address, then the gRPC runtime will choose a port.
  66. Returns:
  67. An integer port on which the server will accept RPC requests.
  68. """
  69. return _common.validate_port_binding_result(
  70. address, self._server.add_insecure_port(_common.encode(address)))
  71. def add_secure_port(self, address: str,
  72. server_credentials: grpc.ServerCredentials) -> int:
  73. """Opens a secure port for accepting RPCs.
  74. This method may only be called before starting the server.
  75. Args:
  76. address: The address for which to open a port.
  77. if the port is 0, or not specified in the address, then the gRPC
  78. runtime will choose a port.
  79. server_credentials: A ServerCredentials object.
  80. Returns:
  81. An integer port on which the server will accept RPC requests.
  82. """
  83. return _common.validate_port_binding_result(
  84. address,
  85. self._server.add_secure_port(_common.encode(address),
  86. server_credentials))
  87. async def start(self) -> None:
  88. """Starts this Server.
  89. This method may only be called once. (i.e. it is not idempotent).
  90. """
  91. await self._server.start()
  92. async def stop(self, grace: Optional[float]) -> None:
  93. """Stops this Server.
  94. This method immediately stops the server from servicing new RPCs in
  95. all cases.
  96. If a grace period is specified, this method returns immediately and all
  97. RPCs active at the end of the grace period are aborted. If a grace
  98. period is not specified (by passing None for grace), all existing RPCs
  99. are aborted immediately and this method blocks until the last RPC
  100. handler terminates.
  101. This method is idempotent and may be called at any time. Passing a
  102. smaller grace value in a subsequent call will have the effect of
  103. stopping the Server sooner (passing None will have the effect of
  104. stopping the server immediately). Passing a larger grace value in a
  105. subsequent call will not have the effect of stopping the server later
  106. (i.e. the most restrictive grace value is used).
  107. Args:
  108. grace: A duration of time in seconds or None.
  109. """
  110. await self._server.shutdown(grace)
  111. async def wait_for_termination(self,
  112. timeout: Optional[float] = None) -> bool:
  113. """Block current coroutine until the server stops.
  114. This is an EXPERIMENTAL API.
  115. The wait will not consume computational resources during blocking, and
  116. it will block until one of the two following conditions are met:
  117. 1) The server is stopped or terminated;
  118. 2) A timeout occurs if timeout is not `None`.
  119. The timeout argument works in the same way as `threading.Event.wait()`.
  120. https://docs.python.org/3/library/threading.html#threading.Event.wait
  121. Args:
  122. timeout: A floating point number specifying a timeout for the
  123. operation in seconds.
  124. Returns:
  125. A bool indicates if the operation times out.
  126. """
  127. return await self._server.wait_for_termination(timeout)
  128. def __del__(self):
  129. """Schedules a graceful shutdown in current event loop.
  130. The Cython AioServer doesn't hold a ref-count to this class. It should
  131. be safe to slightly extend the underlying Cython object's life span.
  132. """
  133. if hasattr(self, '_server'):
  134. if self._server.is_running():
  135. cygrpc.schedule_coro_threadsafe(
  136. self._server.shutdown(None),
  137. self._loop,
  138. )
  139. def server(migration_thread_pool: Optional[Executor] = None,
  140. handlers: Optional[Sequence[grpc.GenericRpcHandler]] = None,
  141. interceptors: Optional[Sequence[Any]] = None,
  142. options: Optional[ChannelArgumentType] = None,
  143. maximum_concurrent_rpcs: Optional[int] = None,
  144. compression: Optional[grpc.Compression] = None):
  145. """Creates a Server with which RPCs can be serviced.
  146. Args:
  147. migration_thread_pool: A futures.ThreadPoolExecutor to be used by the
  148. Server to execute non-AsyncIO RPC handlers for migration purpose.
  149. handlers: An optional list of GenericRpcHandlers used for executing RPCs.
  150. More handlers may be added by calling add_generic_rpc_handlers any time
  151. before the server is started.
  152. interceptors: An optional list of ServerInterceptor objects that observe
  153. and optionally manipulate the incoming RPCs before handing them over to
  154. handlers. The interceptors are given control in the order they are
  155. specified. This is an EXPERIMENTAL API.
  156. options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
  157. to configure the channel.
  158. maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
  159. will service before returning RESOURCE_EXHAUSTED status, or None to
  160. indicate no limit.
  161. compression: An element of grpc.compression, e.g.
  162. grpc.compression.Gzip. This compression algorithm will be used for the
  163. lifetime of the server unless overridden by set_compression.
  164. Returns:
  165. A Server object.
  166. """
  167. return Server(migration_thread_pool, () if handlers is None else handlers,
  168. () if interceptors is None else interceptors,
  169. () if options is None else options, maximum_concurrent_rpcs,
  170. compression)