xref: /aosp_15_r20/external/grpc-grpc/src/python/grpcio/support.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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
15import os
16import os.path
17import shutil
18import sys
19import tempfile
20
21try:
22    from setuptools.errors import CompileError
23except ImportError:
24    # CompileError only exist for setuptools>=59.0.1, which becomes standard library
25    # after Python 3.10.6.
26    # TODO(xuanwn): Remove this once Python version floor is higher than 3.10.
27    from distutils.errors import CompileError
28
29import commands
30
31C_PYTHON_DEV = """
32#include <Python.h>
33int main(int argc, char **argv) { return 0; }
34"""
35C_PYTHON_DEV_ERROR_MESSAGE = """
36Could not find <Python.h>. This could mean the following:
37  * You're on Ubuntu and haven't run `apt-get install <PY_REPR>-dev`.
38  * You're on RHEL/Fedora and haven't run `yum install <PY_REPR>-devel` or
39    `dnf install <PY_REPR>-devel` (make sure you also have redhat-rpm-config
40    installed)
41  * You're on Mac OS X and the usual Python framework was somehow corrupted
42    (check your environment variables or try re-installing?)
43  * You're on Windows and your Python installation was somehow corrupted
44    (check your environment variables or try re-installing?)
45"""
46if sys.version_info[0] == 2:
47    PYTHON_REPRESENTATION = "python"
48elif sys.version_info[0] == 3:
49    PYTHON_REPRESENTATION = "python3"
50else:
51    raise NotImplementedError("Unsupported Python version: %s" % sys.version)
52
53C_CHECKS = {
54    C_PYTHON_DEV: C_PYTHON_DEV_ERROR_MESSAGE.replace(
55        "<PY_REPR>", PYTHON_REPRESENTATION
56    ),
57}
58
59
60def _compile(compiler, source_string):
61    tempdir = tempfile.mkdtemp()
62    cpath = os.path.join(tempdir, "a.c")
63    with open(cpath, "w") as cfile:
64        cfile.write(source_string)
65    try:
66        compiler.compile([cpath])
67    except CompileError as error:
68        return error
69    finally:
70        shutil.rmtree(tempdir)
71
72
73def _expect_compile(compiler, source_string, error_message):
74    if _compile(compiler, source_string) is not None:
75        sys.stderr.write(error_message)
76        raise commands.CommandError(
77            "Diagnostics found a compilation environment issue:\n{}".format(
78                error_message
79            )
80        )
81
82
83def diagnose_compile_error(build_ext, error):
84    """Attempt to diagnose an error during compilation."""
85    for c_check, message in C_CHECKS.items():
86        _expect_compile(build_ext.compiler, c_check, message)
87    python_sources = [
88        source
89        for source in build_ext.get_source_files()
90        if source.startswith("./src/python") and source.endswith("c")
91    ]
92    for source in python_sources:
93        if not os.path.isfile(source):
94            raise commands.CommandError(
95                (
96                    "Diagnostics found a missing Python extension source"
97                    " file:\n{}\n\nThis is usually because the Cython sources"
98                    " haven't been transpiled into C yet and you're building"
99                    " from source.\nTry setting the environment variable"
100                    " `GRPC_PYTHON_BUILD_WITH_CYTHON=1` when invoking"
101                    " `setup.py` or when using `pip`, e.g.:\n\npip install"
102                    " -rrequirements.txt\nGRPC_PYTHON_BUILD_WITH_CYTHON=1 pip"
103                    " install ."
104                ).format(source)
105            )
106
107
108def diagnose_attribute_error(build_ext, error):
109    if any("_needs_stub" in arg for arg in error.args):
110        raise commands.CommandError(
111            "We expect a missing `_needs_stub` attribute from older versions of"
112            " setuptools. Consider upgrading setuptools."
113        )
114
115
116_ERROR_DIAGNOSES = {
117    CompileError: diagnose_compile_error,
118    AttributeError: diagnose_attribute_error,
119}
120
121
122def diagnose_build_ext_error(build_ext, error, formatted):
123    diagnostic = _ERROR_DIAGNOSES.get(type(error))
124    if diagnostic is None:
125        raise commands.CommandError(
126            "\n\nWe could not diagnose your build failure with type {}. If you are unable to"
127            " proceed, please file an issue at http://www.github.com/grpc/grpc"
128            " with `[Python install]` in the title; please attach the whole log"
129            " (including everything that may have appeared above the Python"
130            " backtrace).\n\n{}".format(type(error), formatted)
131        )
132    else:
133        diagnostic(build_ext, error)
134