_plugin_wrapping.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. # Copyright 2015 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. import collections
  15. import logging
  16. import threading
  17. import grpc
  18. from grpc import _common
  19. from grpc._cython import cygrpc
  20. _LOGGER = logging.getLogger(__name__)
  21. class _AuthMetadataContext(
  22. collections.namedtuple('AuthMetadataContext', (
  23. 'service_url',
  24. 'method_name',
  25. )), grpc.AuthMetadataContext):
  26. pass
  27. class _CallbackState(object):
  28. def __init__(self):
  29. self.lock = threading.Lock()
  30. self.called = False
  31. self.exception = None
  32. class _AuthMetadataPluginCallback(grpc.AuthMetadataPluginCallback):
  33. def __init__(self, state, callback):
  34. self._state = state
  35. self._callback = callback
  36. def __call__(self, metadata, error):
  37. with self._state.lock:
  38. if self._state.exception is None:
  39. if self._state.called:
  40. raise RuntimeError(
  41. 'AuthMetadataPluginCallback invoked more than once!')
  42. else:
  43. self._state.called = True
  44. else:
  45. raise RuntimeError(
  46. 'AuthMetadataPluginCallback raised exception "{}"!'.format(
  47. self._state.exception))
  48. if error is None:
  49. self._callback(metadata, cygrpc.StatusCode.ok, None)
  50. else:
  51. self._callback(None, cygrpc.StatusCode.internal,
  52. _common.encode(str(error)))
  53. class _Plugin(object):
  54. def __init__(self, metadata_plugin):
  55. self._metadata_plugin = metadata_plugin
  56. self._stored_ctx = None
  57. try:
  58. import contextvars # pylint: disable=wrong-import-position
  59. # The plugin may be invoked on a thread created by Core, which will not
  60. # have the context propagated. This context is stored and installed in
  61. # the thread invoking the plugin.
  62. self._stored_ctx = contextvars.copy_context()
  63. except ImportError:
  64. # Support versions predating contextvars.
  65. pass
  66. def __call__(self, service_url, method_name, callback):
  67. context = _AuthMetadataContext(_common.decode(service_url),
  68. _common.decode(method_name))
  69. callback_state = _CallbackState()
  70. try:
  71. self._metadata_plugin(
  72. context, _AuthMetadataPluginCallback(callback_state, callback))
  73. except Exception as exception: # pylint: disable=broad-except
  74. _LOGGER.exception(
  75. 'AuthMetadataPluginCallback "%s" raised exception!',
  76. self._metadata_plugin)
  77. with callback_state.lock:
  78. callback_state.exception = exception
  79. if callback_state.called:
  80. return
  81. callback(None, cygrpc.StatusCode.internal,
  82. _common.encode(str(exception)))
  83. def metadata_plugin_call_credentials(metadata_plugin, name):
  84. if name is None:
  85. try:
  86. effective_name = metadata_plugin.__name__
  87. except AttributeError:
  88. effective_name = metadata_plugin.__class__.__name__
  89. else:
  90. effective_name = name
  91. return grpc.CallCredentials(
  92. cygrpc.MetadataPluginCallCredentials(_Plugin(metadata_plugin),
  93. _common.encode(effective_name)))