1# Protocol Buffers - Google's data interchange format 2# Copyright 2008 Google Inc. All rights reserved. 3# https://developers.google.com/protocol-buffers/ 4# 5# Redistribution and use in source and binary forms, with or without 6# modification, are permitted provided that the following conditions are 7# met: 8# 9# * Redistributions of source code must retain the above copyright 10# notice, this list of conditions and the following disclaimer. 11# * Redistributions in binary form must reproduce the above 12# copyright notice, this list of conditions and the following disclaimer 13# in the documentation and/or other materials provided with the 14# distribution. 15# * Neither the name of Google Inc. nor the names of its 16# contributors may be used to endorse or promote products derived from 17# this software without specific prior written permission. 18# 19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 31"""Determine which implementation of the protobuf API is used in this process. 32""" 33 34import importlib 35import os 36import sys 37import warnings 38 39 40def _ApiVersionToImplementationType(api_version): 41 if api_version == 2: 42 return 'cpp' 43 if api_version == 1: 44 raise ValueError('api_version=1 is no longer supported.') 45 if api_version == 0: 46 return 'python' 47 return None 48 49 50_implementation_type = None 51try: 52 # pylint: disable=g-import-not-at-top 53 from google.protobuf.internal import _api_implementation 54 # The compile-time constants in the _api_implementation module can be used to 55 # switch to a certain implementation of the Python API at build time. 56 _implementation_type = _ApiVersionToImplementationType( 57 _api_implementation.api_version) 58except ImportError: 59 pass # Unspecified by compiler flags. 60 61 62def _CanImport(mod_name): 63 try: 64 mod = importlib.import_module(mod_name) 65 # Work around a known issue in the classic bootstrap .par import hook. 66 if not mod: 67 raise ImportError(mod_name + ' import succeeded but was None') 68 return True 69 except ImportError: 70 return False 71 72 73if _implementation_type is None: 74 if _CanImport('google._upb._message'): 75 _implementation_type = 'upb' 76 elif _CanImport('google.protobuf.pyext._message'): 77 _implementation_type = 'cpp' 78 else: 79 _implementation_type = 'python' 80 81 82# This environment variable can be used to switch to a certain implementation 83# of the Python API, overriding the compile-time constants in the 84# _api_implementation module. Right now only 'python', 'cpp' and 'upb' are 85# valid values. Any other value will raise error. 86_implementation_type = os.getenv('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION', 87 _implementation_type) 88 89if _implementation_type not in ('python', 'cpp', 'upb'): 90 raise ValueError('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION {0} is not ' 91 'supported. Please set to \'python\', \'cpp\' or ' 92 '\'upb\'.'.format(_implementation_type)) 93 94if 'PyPy' in sys.version and _implementation_type == 'cpp': 95 warnings.warn('PyPy does not work yet with cpp protocol buffers. ' 96 'Falling back to the python implementation.') 97 _implementation_type = 'python' 98 99_c_module = None 100 101if _implementation_type == 'cpp': 102 try: 103 # pylint: disable=g-import-not-at-top 104 from google.protobuf.pyext import _message 105 _c_module = _message 106 del _message 107 except ImportError: 108 # TODO(jieluo): fail back to python 109 warnings.warn( 110 'Selected implementation cpp is not available.') 111 pass 112 113if _implementation_type == 'upb': 114 try: 115 # pylint: disable=g-import-not-at-top 116 from google._upb import _message 117 _c_module = _message 118 del _message 119 except ImportError: 120 warnings.warn('Selected implementation upb is not available. ' 121 'Falling back to the python implementation.') 122 _implementation_type = 'python' 123 pass 124 125# Detect if serialization should be deterministic by default 126try: 127 # The presence of this module in a build allows the proto implementation to 128 # be upgraded merely via build deps. 129 # 130 # NOTE: Merely importing this automatically enables deterministic proto 131 # serialization for C++ code, but we still need to export it as a boolean so 132 # that we can do the same for `_implementation_type == 'python'`. 133 # 134 # NOTE2: It is possible for C++ code to enable deterministic serialization by 135 # default _without_ affecting Python code, if the C++ implementation is not in 136 # use by this module. That is intended behavior, so we don't actually expose 137 # this boolean outside of this module. 138 # 139 # pylint: disable=g-import-not-at-top,unused-import 140 from google.protobuf import enable_deterministic_proto_serialization 141 _python_deterministic_proto_serialization = True 142except ImportError: 143 _python_deterministic_proto_serialization = False 144 145 146# Usage of this function is discouraged. Clients shouldn't care which 147# implementation of the API is in use. Note that there is no guarantee 148# that differences between APIs will be maintained. 149# Please don't use this function if possible. 150def Type(): 151 return _implementation_type 152 153 154def _SetType(implementation_type): 155 """Never use! Only for protobuf benchmark.""" 156 global _implementation_type 157 _implementation_type = implementation_type 158 159 160# See comment on 'Type' above. 161# TODO(jieluo): Remove the API, it returns a constant. b/228102101 162def Version(): 163 return 2 164 165 166# For internal use only 167def IsPythonDefaultSerializationDeterministic(): 168 return _python_deterministic_proto_serialization 169