protoc.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. #!/usr/bin/env python3
  2. # Copyright 2016 gRPC authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. import sys
  17. from grpc_tools import _protoc_compiler
  18. import pkg_resources
  19. _PROTO_MODULE_SUFFIX = "_pb2"
  20. _SERVICE_MODULE_SUFFIX = "_pb2_grpc"
  21. _DISABLE_DYNAMIC_STUBS = "GRPC_PYTHON_DISABLE_DYNAMIC_STUBS"
  22. def main(command_arguments):
  23. """Run the protocol buffer compiler with the given command-line arguments.
  24. Args:
  25. command_arguments: a list of strings representing command line arguments to
  26. `protoc`.
  27. """
  28. command_arguments = [argument.encode() for argument in command_arguments]
  29. return _protoc_compiler.run_main(command_arguments)
  30. # NOTE(rbellevi): importlib.abc is not supported on 3.4.
  31. if sys.version_info >= (3, 5, 0):
  32. import contextlib
  33. import importlib
  34. import importlib.abc
  35. import importlib.machinery
  36. import threading
  37. _FINDERS_INSTALLED = False
  38. _FINDERS_INSTALLED_LOCK = threading.Lock()
  39. def _maybe_install_proto_finders():
  40. global _FINDERS_INSTALLED
  41. with _FINDERS_INSTALLED_LOCK:
  42. if not _FINDERS_INSTALLED:
  43. sys.meta_path.extend([
  44. ProtoFinder(_PROTO_MODULE_SUFFIX,
  45. _protoc_compiler.get_protos),
  46. ProtoFinder(_SERVICE_MODULE_SUFFIX,
  47. _protoc_compiler.get_services)
  48. ])
  49. sys.path.append(
  50. pkg_resources.resource_filename('grpc_tools', '_proto'))
  51. _FINDERS_INSTALLED = True
  52. def _module_name_to_proto_file(suffix, module_name):
  53. components = module_name.split(".")
  54. proto_name = components[-1][:-1 * len(suffix)]
  55. # NOTE(rbellevi): The Protobuf library expects this path to use
  56. # forward slashes on every platform.
  57. return "/".join(components[:-1] + [proto_name + ".proto"])
  58. def _proto_file_to_module_name(suffix, proto_file):
  59. components = proto_file.split(os.path.sep)
  60. proto_base_name = os.path.splitext(components[-1])[0]
  61. return ".".join(components[:-1] + [proto_base_name + suffix])
  62. def _protos(protobuf_path):
  63. """Returns a gRPC module generated from the indicated proto file."""
  64. _maybe_install_proto_finders()
  65. module_name = _proto_file_to_module_name(_PROTO_MODULE_SUFFIX,
  66. protobuf_path)
  67. module = importlib.import_module(module_name)
  68. return module
  69. def _services(protobuf_path):
  70. """Returns a module generated from the indicated proto file."""
  71. _maybe_install_proto_finders()
  72. _protos(protobuf_path)
  73. module_name = _proto_file_to_module_name(_SERVICE_MODULE_SUFFIX,
  74. protobuf_path)
  75. module = importlib.import_module(module_name)
  76. return module
  77. def _protos_and_services(protobuf_path):
  78. """Returns two modules, corresponding to _pb2.py and _pb2_grpc.py files."""
  79. return (_protos(protobuf_path), _services(protobuf_path))
  80. _proto_code_cache = {}
  81. _proto_code_cache_lock = threading.RLock()
  82. class ProtoLoader(importlib.abc.Loader):
  83. def __init__(self, suffix, codegen_fn, module_name, protobuf_path,
  84. proto_root):
  85. self._suffix = suffix
  86. self._codegen_fn = codegen_fn
  87. self._module_name = module_name
  88. self._protobuf_path = protobuf_path
  89. self._proto_root = proto_root
  90. def create_module(self, spec):
  91. return None
  92. def _generated_file_to_module_name(self, filepath):
  93. components = filepath.split(os.path.sep)
  94. return ".".join(components[:-1] +
  95. [os.path.splitext(components[-1])[0]])
  96. def exec_module(self, module):
  97. assert module.__name__ == self._module_name
  98. code = None
  99. with _proto_code_cache_lock:
  100. if self._module_name in _proto_code_cache:
  101. code = _proto_code_cache[self._module_name]
  102. exec(code, module.__dict__)
  103. else:
  104. files = self._codegen_fn(
  105. self._protobuf_path.encode('ascii'),
  106. [path.encode('ascii') for path in sys.path])
  107. # NOTE: The files are returned in topological order of dependencies. Each
  108. # entry is guaranteed to depend only on the modules preceding it in the
  109. # list and the last entry is guaranteed to be our requested module. We
  110. # cache the code from the first invocation at module-scope so that we
  111. # don't have to regenerate code that has already been generated by protoc.
  112. for f in files[:-1]:
  113. module_name = self._generated_file_to_module_name(
  114. f[0].decode('ascii'))
  115. if module_name not in sys.modules:
  116. if module_name not in _proto_code_cache:
  117. _proto_code_cache[module_name] = f[1]
  118. importlib.import_module(module_name)
  119. exec(files[-1][1], module.__dict__)
  120. class ProtoFinder(importlib.abc.MetaPathFinder):
  121. def __init__(self, suffix, codegen_fn):
  122. self._suffix = suffix
  123. self._codegen_fn = codegen_fn
  124. def find_spec(self, fullname, path, target=None):
  125. if not fullname.endswith(self._suffix):
  126. return None
  127. filepath = _module_name_to_proto_file(self._suffix, fullname)
  128. for search_path in sys.path:
  129. try:
  130. prospective_path = os.path.join(search_path, filepath)
  131. os.stat(prospective_path)
  132. except (FileNotFoundError, NotADirectoryError, OSError):
  133. continue
  134. else:
  135. return importlib.machinery.ModuleSpec(
  136. fullname,
  137. ProtoLoader(self._suffix, self._codegen_fn, fullname,
  138. filepath, search_path))
  139. # NOTE(rbellevi): We provide an environment variable that enables users to completely
  140. # disable this behavior if it is not desired, e.g. for performance reasons.
  141. if not os.getenv(_DISABLE_DYNAMIC_STUBS):
  142. _maybe_install_proto_finders()
  143. if __name__ == '__main__':
  144. proto_include = pkg_resources.resource_filename('grpc_tools', '_proto')
  145. sys.exit(main(sys.argv + ['-I{}'.format(proto_include)]))