_common.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. # Copyright 2016 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. """Shared implementation."""
  15. import logging
  16. import time
  17. from typing import Any, AnyStr, Callable, Optional, Union
  18. import grpc
  19. from grpc._cython import cygrpc
  20. from grpc._typing import DeserializingFunction
  21. from grpc._typing import SerializingFunction
  22. _LOGGER = logging.getLogger(__name__)
  23. CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY = {
  24. cygrpc.ConnectivityState.idle:
  25. grpc.ChannelConnectivity.IDLE,
  26. cygrpc.ConnectivityState.connecting:
  27. grpc.ChannelConnectivity.CONNECTING,
  28. cygrpc.ConnectivityState.ready:
  29. grpc.ChannelConnectivity.READY,
  30. cygrpc.ConnectivityState.transient_failure:
  31. grpc.ChannelConnectivity.TRANSIENT_FAILURE,
  32. cygrpc.ConnectivityState.shutdown:
  33. grpc.ChannelConnectivity.SHUTDOWN,
  34. }
  35. CYGRPC_STATUS_CODE_TO_STATUS_CODE = {
  36. cygrpc.StatusCode.ok: grpc.StatusCode.OK,
  37. cygrpc.StatusCode.cancelled: grpc.StatusCode.CANCELLED,
  38. cygrpc.StatusCode.unknown: grpc.StatusCode.UNKNOWN,
  39. cygrpc.StatusCode.invalid_argument: grpc.StatusCode.INVALID_ARGUMENT,
  40. cygrpc.StatusCode.deadline_exceeded: grpc.StatusCode.DEADLINE_EXCEEDED,
  41. cygrpc.StatusCode.not_found: grpc.StatusCode.NOT_FOUND,
  42. cygrpc.StatusCode.already_exists: grpc.StatusCode.ALREADY_EXISTS,
  43. cygrpc.StatusCode.permission_denied: grpc.StatusCode.PERMISSION_DENIED,
  44. cygrpc.StatusCode.unauthenticated: grpc.StatusCode.UNAUTHENTICATED,
  45. cygrpc.StatusCode.resource_exhausted: grpc.StatusCode.RESOURCE_EXHAUSTED,
  46. cygrpc.StatusCode.failed_precondition: grpc.StatusCode.FAILED_PRECONDITION,
  47. cygrpc.StatusCode.aborted: grpc.StatusCode.ABORTED,
  48. cygrpc.StatusCode.out_of_range: grpc.StatusCode.OUT_OF_RANGE,
  49. cygrpc.StatusCode.unimplemented: grpc.StatusCode.UNIMPLEMENTED,
  50. cygrpc.StatusCode.internal: grpc.StatusCode.INTERNAL,
  51. cygrpc.StatusCode.unavailable: grpc.StatusCode.UNAVAILABLE,
  52. cygrpc.StatusCode.data_loss: grpc.StatusCode.DATA_LOSS,
  53. }
  54. STATUS_CODE_TO_CYGRPC_STATUS_CODE = {
  55. grpc_code: cygrpc_code
  56. for cygrpc_code, grpc_code in CYGRPC_STATUS_CODE_TO_STATUS_CODE.items()
  57. }
  58. MAXIMUM_WAIT_TIMEOUT = 0.1
  59. _ERROR_MESSAGE_PORT_BINDING_FAILED = 'Failed to bind to address %s; set ' \
  60. 'GRPC_VERBOSITY=debug environment variable to see detailed error message.'
  61. def encode(s: AnyStr) -> bytes:
  62. if isinstance(s, bytes):
  63. return s
  64. else:
  65. return s.encode('utf8')
  66. def decode(b: AnyStr) -> str:
  67. if isinstance(b, bytes):
  68. return b.decode('utf-8', 'replace')
  69. return b
  70. def _transform(message: Any, transformer: Union[SerializingFunction,
  71. DeserializingFunction, None],
  72. exception_message: str) -> Any:
  73. if transformer is None:
  74. return message
  75. else:
  76. try:
  77. return transformer(message)
  78. except Exception: # pylint: disable=broad-except
  79. _LOGGER.exception(exception_message)
  80. return None
  81. def serialize(message: Any, serializer: Optional[SerializingFunction]) -> bytes:
  82. return _transform(message, serializer, 'Exception serializing message!')
  83. def deserialize(serialized_message: bytes,
  84. deserializer: Optional[DeserializingFunction]) -> Any:
  85. return _transform(serialized_message, deserializer,
  86. 'Exception deserializing message!')
  87. def fully_qualified_method(group: str, method: str) -> str:
  88. return '/{}/{}'.format(group, method)
  89. def _wait_once(wait_fn: Callable[..., bool], timeout: float,
  90. spin_cb: Optional[Callable[[], None]]):
  91. wait_fn(timeout=timeout)
  92. if spin_cb is not None:
  93. spin_cb()
  94. def wait(wait_fn: Callable[..., bool],
  95. wait_complete_fn: Callable[[], bool],
  96. timeout: Optional[float] = None,
  97. spin_cb: Optional[Callable[[], None]] = None) -> bool:
  98. """Blocks waiting for an event without blocking the thread indefinitely.
  99. See https://github.com/grpc/grpc/issues/19464 for full context. CPython's
  100. `threading.Event.wait` and `threading.Condition.wait` methods, if invoked
  101. without a timeout kwarg, may block the calling thread indefinitely. If the
  102. call is made from the main thread, this means that signal handlers may not
  103. run for an arbitrarily long period of time.
  104. This wrapper calls the supplied wait function with an arbitrary short
  105. timeout to ensure that no signal handler has to wait longer than
  106. MAXIMUM_WAIT_TIMEOUT before executing.
  107. Args:
  108. wait_fn: A callable acceptable a single float-valued kwarg named
  109. `timeout`. This function is expected to be one of `threading.Event.wait`
  110. or `threading.Condition.wait`.
  111. wait_complete_fn: A callable taking no arguments and returning a bool.
  112. When this function returns true, it indicates that waiting should cease.
  113. timeout: An optional float-valued number of seconds after which the wait
  114. should cease.
  115. spin_cb: An optional Callable taking no arguments and returning nothing.
  116. This callback will be called on each iteration of the spin. This may be
  117. used for, e.g. work related to forking.
  118. Returns:
  119. True if a timeout was supplied and it was reached. False otherwise.
  120. """
  121. if timeout is None:
  122. while not wait_complete_fn():
  123. _wait_once(wait_fn, MAXIMUM_WAIT_TIMEOUT, spin_cb)
  124. else:
  125. end = time.time() + timeout
  126. while not wait_complete_fn():
  127. remaining = min(end - time.time(), MAXIMUM_WAIT_TIMEOUT)
  128. if remaining < 0:
  129. return True
  130. _wait_once(wait_fn, remaining, spin_cb)
  131. return False
  132. def validate_port_binding_result(address: str, port: int) -> int:
  133. """Validates if the port binding succeed.
  134. If the port returned by Core is 0, the binding is failed. However, in that
  135. case, the Core API doesn't return a detailed failing reason. The best we
  136. can do is raising an exception to prevent further confusion.
  137. Args:
  138. address: The address string to be bound.
  139. port: An int returned by core
  140. """
  141. if port == 0:
  142. # The Core API doesn't return a failure message. The best we can do
  143. # is raising an exception to prevent further confusion.
  144. raise RuntimeError(_ERROR_MESSAGE_PORT_BINDING_FAILED % address)
  145. else:
  146. return port