_common.py 6.1 KB

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