_plugin_wrapping.py 4.2 KB

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