diff --git a/ci/scripts/python_wheel_check_cloudfs_split.py b/ci/scripts/python_wheel_check_cloudfs_split.py new file mode 100644 index 00000000000..4647826f7c4 --- /dev/null +++ b/ci/scripts/python_wheel_check_cloudfs_split.py @@ -0,0 +1,125 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Check S3, GCS and Azure against the pyarrow-cloudfs split. +# +# Usage: python_wheel_check_cloudfs_split.py missing|mismatch|installed +# +# missing: run with pyarrow installed but not pyarrow-cloudfs. Each enabled +# filesystem must fail with a message pointing at pyarrow-cloudfs, both +# from pyarrow.fs and from FileSystem.from_uri. +# mismatch: run with pyarrow installed but not pyarrow-cloudfs. Installs an +# empty pyarrow-cloudfs of another version, as 'pip install -U pyarrow' +# leaves behind after upgrading from a placeholder release, checks that each +# enabled filesystem fails with the command to install the matching +# version, then uninstalls it again. +# installed: run with both installed. FileSystem.from_uri must resolve each +# enabled filesystem even if pyarrow.fs was never imported. +# +# A filesystem is checked when its PYARROW_TEST_ variable is ON. + +import os +import subprocess +import sys +import tempfile + +from pyarrow.lib import ArrowInvalid + +from python_wheel_empty_wheel import MISMATCHED_VERSION, write_empty_wheel + +# (PYARROW_TEST_ variable, pyarrow.fs name, URI, FileSystem.type_name) +FILESYSTEMS = [ + ("PYARROW_TEST_S3", "S3FileSystem", + "s3://bucket/key?region=us-east-1", "s3"), + ("PYARROW_TEST_GCS", "GcsFileSystem", + "gs://anonymous@bucket/key", "gcs"), + ("PYARROW_TEST_AZURE", "AzureFileSystem", + "abfs://container@account.dfs.core.windows.net/key" + "?credential_kind=anonymous", "abfs"), +] + +mode = sys.argv[1] +enabled = [fs for fs in FILESYSTEMS if os.environ.get(fs[0]) == "ON"] + +if mode == "mismatch": + pip = [sys.executable, "-m", "pip"] + with tempfile.TemporaryDirectory() as directory: + wheel_path = write_empty_wheel(directory, "pyarrow-cloudfs", + MISMATCHED_VERSION) + subprocess.run(pip + ["install", "--no-deps", wheel_path], check=True) + try: + # A fresh interpreter, so pyarrow.fs runs its check at import time. + subprocess.run([sys.executable, __file__, "mismatch-check"], check=True) + finally: + subprocess.run(pip + ["uninstall", "--yes", "pyarrow-cloudfs"], + check=True) + print(f"Checked mismatch: {[name for _, name, _, _ in enabled]}") + sys.exit(0) + +if mode == "mismatch-check": + import pyarrow + expected = f"pyarrow-cloudfs=={pyarrow.__version__}" + +for _, name, uri, type_name in enabled: + if mode == "mismatch-check": + from pyarrow._fs import FileSystem + try: + FileSystem.from_uri(uri) + except ArrowInvalid as e: + assert expected in str(e), e + else: + raise AssertionError(f"from_uri resolved {uri} with a mismatched " + "pyarrow-cloudfs") + + import pyarrow.fs as fs + try: + getattr(fs, name) + except ImportError as e: + assert expected in str(e), e + else: + raise AssertionError(f"{name} available with a mismatched " + "pyarrow-cloudfs") + elif mode == "missing": + try: + from pyarrow._fs import FileSystem + FileSystem.from_uri(uri) + except ArrowInvalid as e: + assert "pyarrow-cloudfs" in str(e), e + else: + raise AssertionError(f"from_uri resolved {uri} without pyarrow-cloudfs") + + import pyarrow.fs as fs + try: + getattr(fs, name) + except ImportError as e: + assert "pyarrow-cloudfs" in str(e), e + else: + raise AssertionError(f"{name} available without pyarrow-cloudfs") + elif mode == "installed": + from pyarrow._fs import FileSystem + filesystem, _ = FileSystem.from_uri(uri) + assert filesystem.type_name == type_name, filesystem.type_name + else: + raise ValueError(f"unknown mode: {mode}") + +if mode == "mismatch-check": + # The extensions must not have been imported: their RPATH would let the + # loader pick up the mismatched libraries. + for module in ("pyarrow._s3fs", "pyarrow._gcsfs", "pyarrow._azurefs"): + assert module not in sys.modules, module + +print(f"Checked {mode}: {[name for _, name, _, _ in enabled]}") diff --git a/ci/scripts/python_wheel_check_flight_split.py b/ci/scripts/python_wheel_check_flight_split.py new file mode 100644 index 00000000000..041ee228788 --- /dev/null +++ b/ci/scripts/python_wheel_check_flight_split.py @@ -0,0 +1,79 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Check Flight against the pyarrow-flight split. +# +# Usage: python_wheel_check_flight_split.py missing|mismatch|installed +# +# missing: run with pyarrow installed but not pyarrow-flight. Importing +# pyarrow.flight must fail with a message pointing at pyarrow-flight. +# mismatch: run with pyarrow installed but not pyarrow-flight. Installs an +# empty pyarrow-flight of another version, checks that importing +# pyarrow.flight fails with the command to install the matching version +# without importing pyarrow._flight, then uninstalls it again. +# installed: run with both installed. pyarrow.flight must import and a server +# must start, which needs libarrow_flight and the gRPC it bundles. + +import subprocess +import sys +import tempfile + +from python_wheel_empty_wheel import MISMATCHED_VERSION, write_empty_wheel + +mode = sys.argv[1] + +if mode == "mismatch": + pip = [sys.executable, "-m", "pip"] + with tempfile.TemporaryDirectory() as directory: + wheel_path = write_empty_wheel(directory, "pyarrow-flight", + MISMATCHED_VERSION) + subprocess.run(pip + ["install", "--no-deps", wheel_path], check=True) + try: + # A fresh interpreter, so pyarrow.flight runs its check at import. + subprocess.run([sys.executable, __file__, "mismatch-check"], check=True) + finally: + subprocess.run(pip + ["uninstall", "--yes", "pyarrow-flight"], + check=True) +elif mode == "mismatch-check": + import pyarrow + expected = f"pyarrow-flight=={pyarrow.__version__}" + try: + import pyarrow.flight # noqa: F401 + except ImportError as e: + assert expected in str(e), e + else: + raise AssertionError("pyarrow.flight available with a mismatched " + "pyarrow-flight") + # The extension must not have been imported: its RPATH would let the + # loader pick up the mismatched library. + assert "pyarrow._flight" not in sys.modules +elif mode == "missing": + try: + import pyarrow.flight # noqa: F401 + except ImportError as e: + assert "pyarrow-flight" in str(e), e + else: + raise AssertionError("pyarrow.flight available without pyarrow-flight") +elif mode == "installed": + import pyarrow.flight as flight + server = flight.FlightServerBase("grpc://localhost:0") + assert server.port > 0, server.port + server.shutdown() +else: + raise ValueError(f"unknown mode: {mode}") + +print(f"Checked {mode}: Flight") diff --git a/ci/scripts/python_wheel_macos_build.sh b/ci/scripts/python_wheel_macos_build.sh index 4724f8e1524..e0b5cc5099d 100755 --- a/ci/scripts/python_wheel_macos_build.sh +++ b/ci/scripts/python_wheel_macos_build.sh @@ -193,3 +193,23 @@ fi # Move the verified wheels mkdir -p "${source_dir}/python/repaired_wheels" mv "${source_dir}"/python/dist/*.whl "${source_dir}"/python/repaired_wheels/ + +if [ "${ARROW_S3}" == "ON" ] || [ "${ARROW_GCS}" == "ON" ] || [ "${ARROW_AZURE}" == "ON" ]; then + echo "=== (${PYTHON_VERSION}) Building pyarrow-cloudfs wheel ===" + # CMake pulls libarrow_s3, libarrow_gcs and libarrow_azure from the Arrow + # install via CMAKE_PREFIX_PATH. + python -m build --wheel --no-isolation \ + --outdir "${source_dir}/python/repaired_wheels" \ + -C cmake.define.PYARROW_CLOUDFS_S3="${ARROW_S3}" \ + -C cmake.define.PYARROW_CLOUDFS_GCS="${ARROW_GCS}" \ + -C cmake.define.PYARROW_CLOUDFS_AZURE="${ARROW_AZURE}" \ + "${source_dir}/python/pyarrow-cloudfs" +fi + +if [ "${ARROW_FLIGHT}" == "ON" ]; then + echo "=== (${PYTHON_VERSION}) Building pyarrow-flight wheel ===" + # CMake pulls libarrow_flight from the Arrow install via CMAKE_PREFIX_PATH. + python -m build --wheel --no-isolation \ + --outdir "${source_dir}/python/repaired_wheels" \ + "${source_dir}/python/pyarrow-flight" +fi diff --git a/ci/scripts/python_wheel_unix_test.sh b/ci/scripts/python_wheel_unix_test.sh index cb445611e23..a60b30cdb9e 100755 --- a/ci/scripts/python_wheel_unix_test.sh +++ b/ci/scripts/python_wheel_unix_test.sh @@ -58,8 +58,23 @@ export ARROW_TEST_DATA=${source_dir}/testing/data export PARQUET_TEST_DATA=${source_dir}/cpp/submodules/parquet-testing/data if [ "${INSTALL_PYARROW}" == "ON" ]; then - # Install the built wheels - python -m pip install "${source_dir}"/python/repaired_wheels/*.whl + # Install the core wheel alone first: S3, GCS and Azure ship in the + # separate pyarrow-cloudfs wheel, so check that they fail with an + # actionable message without it. + python -m pip install "${source_dir}"/python/repaired_wheels/pyarrow-*.whl + if [ "${PYARROW_TEST_S3}" == "ON" ] || [ "${PYARROW_TEST_GCS}" == "ON" ] || [ "${PYARROW_TEST_AZURE}" == "ON" ]; then + python "${source_dir}/ci/scripts/python_wheel_check_cloudfs_split.py" missing + python "${source_dir}/ci/scripts/python_wheel_check_cloudfs_split.py" mismatch + python -m pip install "${source_dir}"/python/repaired_wheels/pyarrow_cloudfs-*.whl + python "${source_dir}/ci/scripts/python_wheel_check_cloudfs_split.py" installed + fi + # Flight ships in the separate pyarrow-flight wheel. + if [ "${PYARROW_TEST_FLIGHT}" == "ON" ]; then + python "${source_dir}/ci/scripts/python_wheel_check_flight_split.py" missing + python "${source_dir}/ci/scripts/python_wheel_check_flight_split.py" mismatch + python -m pip install "${source_dir}"/python/repaired_wheels/pyarrow_flight-*.whl + python "${source_dir}/ci/scripts/python_wheel_check_flight_split.py" installed + fi fi if [ "${CHECK_IMPORTS}" == "ON" ]; then @@ -74,11 +89,16 @@ import pyarrow.json import pyarrow.orc import pyarrow.parquet " + # S3, GCS and Azure ship in the separate pyarrow-cloudfs wheel, which + # pyarrow.fs loads, so import them through pyarrow.fs. + if [ "${PYARROW_TEST_AZURE}" == "ON" ]; then + python -c "import pyarrow.fs; pyarrow.fs.AzureFileSystem" + fi if [ "${PYARROW_TEST_GCS}" == "ON" ]; then - python -c "import pyarrow._gcsfs" + python -c "import pyarrow.fs; pyarrow.fs.GcsFileSystem" fi if [ "${PYARROW_TEST_S3}" == "ON" ]; then - python -c "import pyarrow._s3fs" + python -c "import pyarrow.fs; pyarrow.fs.S3FileSystem" fi if [ "${PYARROW_TEST_FLIGHT}" == "ON" ]; then python -c "import pyarrow.flight" diff --git a/ci/scripts/python_wheel_validate_contents.py b/ci/scripts/python_wheel_validate_contents.py index f11b24c11e0..95696dc2344 100644 --- a/ci/scripts/python_wheel_validate_contents.py +++ b/ci/scripts/python_wheel_validate_contents.py @@ -40,7 +40,9 @@ def _count_docstrings(source): # TODO(GH-48970): Check stubs ARE present once annotations are complete def validate_wheel(path): p = Path(path) - wheels = list(p.glob('*.whl')) + # Only the core pyarrow wheel; pyarrow_cloudfs-*.whl and + # pyarrow_flight-*.whl sit alongside it. + wheels = list(p.glob('pyarrow-*.whl')) error_msg = f"{len(wheels)} wheels found but only 1 expected ({wheels})" assert len(wheels) == 1, error_msg with zipfile.ZipFile(wheels[0]) as wheel_zip: diff --git a/ci/scripts/python_wheel_windows_build.bat b/ci/scripts/python_wheel_windows_build.bat index 3805f750d45..fa2e3b28270 100644 --- a/ci/scripts/python_wheel_windows_build.bat +++ b/ci/scripts/python_wheel_windows_build.bat @@ -151,8 +151,51 @@ pushd C:\arrow\python for /f %%i in ('dir dist\pyarrow-*.whl /B') do (set WHEEL_NAME=%cd%\dist\%%i) || exit /B 1 echo "Wheel name: %WHEEL_NAME%" +@REM arrow_s3.dll, arrow_gcs.dll and arrow_azure.dll ship in the separate +@REM pyarrow-cloudfs wheel, arrow_flight.dll in the pyarrow-flight wheel. %PYTHON_CMD% -m delvewheel repair -vv ^ --ignore-existing --with-mangle ^ + --exclude "arrow_s3.dll;arrow_gcs.dll;arrow_azure.dll;arrow_flight.dll" ^ -w repaired_wheels %WHEEL_NAME% || exit /B 1 +set BUILD_CLOUDFS=OFF +if "%ARROW_S3%"=="ON" set BUILD_CLOUDFS=ON +if "%ARROW_GCS%"=="ON" set BUILD_CLOUDFS=ON +if "%ARROW_AZURE%"=="ON" set BUILD_CLOUDFS=ON +if not "%BUILD_CLOUDFS%"=="ON" goto :skip_pyarrow_cloudfs + +@REM Build pyarrow-cloudfs: CMake pulls arrow_s3.dll, arrow_gcs.dll and +@REM arrow_azure.dll from C:\arrow-dist via CMAKE_PREFIX_PATH. +%PYTHON_CMD% -m build --wheel --no-isolation --outdir dist-cloudfs ^ + -C cmake.define.PYARROW_CLOUDFS_S3=%ARROW_S3% ^ + -C cmake.define.PYARROW_CLOUDFS_GCS=%ARROW_GCS% ^ + -C cmake.define.PYARROW_CLOUDFS_AZURE=%ARROW_AZURE% ^ + pyarrow-cloudfs || exit /B 1 + +for /f %%i in ('dir dist-cloudfs\pyarrow_cloudfs-*.whl /B') do (set CLOUDFS_WHEEL_NAME=%cd%\dist-cloudfs\%%i) || exit /B 1 +echo "pyarrow-cloudfs wheel name: %CLOUDFS_WHEEL_NAME%" + +@REM arrow.dll ships in the pyarrow wheel. +%PYTHON_CMD% -m delvewheel repair -vv ^ + --ignore-existing --analyze-existing --with-mangle --exclude arrow.dll ^ + -w repaired_wheels %CLOUDFS_WHEEL_NAME% || exit /B 1 + +:skip_pyarrow_cloudfs + +if not "%ARROW_FLIGHT%"=="ON" goto :skip_pyarrow_flight + +@REM Build pyarrow-flight: CMake pulls arrow_flight.dll from C:\arrow-dist via +@REM CMAKE_PREFIX_PATH. +%PYTHON_CMD% -m build --wheel --no-isolation --outdir dist-flight pyarrow-flight || exit /B 1 + +for /f %%i in ('dir dist-flight\pyarrow_flight-*.whl /B') do (set FLIGHT_WHEEL_NAME=%cd%\dist-flight\%%i) || exit /B 1 +echo "pyarrow-flight wheel name: %FLIGHT_WHEEL_NAME%" + +@REM arrow.dll ships in the pyarrow wheel. +%PYTHON_CMD% -m delvewheel repair -vv ^ + --ignore-existing --analyze-existing --with-mangle --exclude arrow.dll ^ + -w repaired_wheels %FLIGHT_WHEEL_NAME% || exit /B 1 + +:skip_pyarrow_flight + popd diff --git a/ci/scripts/python_wheel_windows_test.bat b/ci/scripts/python_wheel_windows_test.bat index 1e9cacac8bf..d305895c494 100755 --- a/ci/scripts/python_wheel_windows_test.bat +++ b/ci/scripts/python_wheel_windows_test.bat @@ -42,12 +42,26 @@ py -0p @REM Install the built wheels %PYTHON_CMD% -m pip install --no-index --find-links=C:\arrow\python\repaired_wheels pyarrow || exit /B 1 +@REM S3, GCS and Azure ship in the separate pyarrow-cloudfs wheel: with only +@REM pyarrow installed, check that they fail with an actionable message, then +@REM install it and check that they work. +%PYTHON_CMD% C:\arrow\ci\scripts\python_wheel_check_cloudfs_split.py missing || exit /B 1 +%PYTHON_CMD% C:\arrow\ci\scripts\python_wheel_check_cloudfs_split.py mismatch || exit /B 1 +%PYTHON_CMD% -m pip install --no-index --find-links=C:\arrow\python\repaired_wheels pyarrow-cloudfs || exit /B 1 +%PYTHON_CMD% C:\arrow\ci\scripts\python_wheel_check_cloudfs_split.py installed || exit /B 1 + +@REM Flight ships in the separate pyarrow-flight wheel. +%PYTHON_CMD% C:\arrow\ci\scripts\python_wheel_check_flight_split.py missing || exit /B 1 +%PYTHON_CMD% C:\arrow\ci\scripts\python_wheel_check_flight_split.py mismatch || exit /B 1 +%PYTHON_CMD% -m pip install --no-index --find-links=C:\arrow\python\repaired_wheels pyarrow-flight || exit /B 1 +%PYTHON_CMD% C:\arrow\ci\scripts\python_wheel_check_flight_split.py installed || exit /B 1 + @REM Test that the modules are importable %PYTHON_CMD% -c "import pyarrow" || exit /B 1 -%PYTHON_CMD% -c "import pyarrow._azurefs" || exit /B 1 -%PYTHON_CMD% -c "import pyarrow._gcsfs" || exit /B 1 +%PYTHON_CMD% -c "import pyarrow.fs; pyarrow.fs.AzureFileSystem" || exit /B 1 +%PYTHON_CMD% -c "import pyarrow.fs; pyarrow.fs.GcsFileSystem" || exit /B 1 %PYTHON_CMD% -c "import pyarrow._hdfs" || exit /B 1 -%PYTHON_CMD% -c "import pyarrow._s3fs" || exit /B 1 +%PYTHON_CMD% -c "import pyarrow.fs; pyarrow.fs.S3FileSystem" || exit /B 1 %PYTHON_CMD% -c "import pyarrow.csv" || exit /B 1 %PYTHON_CMD% -c "import pyarrow.dataset" || exit /B 1 %PYTHON_CMD% -c "import pyarrow.flight" || exit /B 1 diff --git a/ci/scripts/python_wheel_xlinux_build.sh b/ci/scripts/python_wheel_xlinux_build.sh index a64ca50b61e..96b7c3b659d 100755 --- a/ci/scripts/python_wheel_xlinux_build.sh +++ b/ci/scripts/python_wheel_xlinux_build.sh @@ -225,6 +225,42 @@ popd rm -rf dist/temp-fix-wheel +build_cloudfs=OFF +if [ "${ARROW_S3}" == "ON" ] || [ "${ARROW_GCS}" == "ON" ] || [ "${ARROW_AZURE}" == "ON" ]; then + build_cloudfs=ON +fi + +if [ "${build_cloudfs}" == "ON" ]; then + echo "=== (${PYTHON_VERSION}) Building pyarrow-cloudfs wheel ===" + # CMake pulls libarrow_s3, libarrow_gcs and libarrow_azure from + # /tmp/arrow-dist via CMAKE_PREFIX_PATH. + python -m build --wheel --no-isolation --outdir dist \ + -C cmake.define.PYARROW_CLOUDFS_S3="${ARROW_S3}" \ + -C cmake.define.PYARROW_CLOUDFS_GCS="${ARROW_GCS}" \ + -C cmake.define.PYARROW_CLOUDFS_AZURE="${ARROW_AZURE}" \ + pyarrow-cloudfs +fi + +if [ "${ARROW_FLIGHT}" == "ON" ]; then + echo "=== (${PYTHON_VERSION}) Building pyarrow-flight wheel ===" + # CMake pulls libarrow_flight from /tmp/arrow-dist via CMAKE_PREFIX_PATH. + python -m build --wheel --no-isolation --outdir dist pyarrow-flight +fi + echo "=== (${PYTHON_VERSION}) Tag the wheel with ${LINUX_WHEEL_KIND}${LINUX_WHEEL_VERSION} ===" -auditwheel repair dist/pyarrow-*.whl -w repaired_wheels +# libarrow ships in pyarrow, libarrow_s3, libarrow_gcs and libarrow_azure in +# pyarrow-cloudfs, and libarrow_flight in pyarrow-flight: no wheel may graft +# another's libraries. +auditwheel repair \ + --exclude 'libarrow_s3.so.*' \ + --exclude 'libarrow_gcs.so.*' \ + --exclude 'libarrow_azure.so.*' \ + --exclude 'libarrow_flight.so.*' \ + dist/pyarrow-*.whl -w repaired_wheels +if [ "${build_cloudfs}" == "ON" ]; then + auditwheel repair --exclude 'libarrow.so.*' dist/pyarrow_cloudfs-*.whl -w repaired_wheels +fi +if [ "${ARROW_FLIGHT}" == "ON" ]; then + auditwheel repair --exclude 'libarrow.so.*' dist/pyarrow_flight-*.whl -w repaired_wheels +fi popd diff --git a/python/CMakeLists.txt b/python/CMakeLists.txt index f38abce98a4..1cc561065c9 100644 --- a/python/CMakeLists.txt +++ b/python/CMakeLists.txt @@ -121,10 +121,11 @@ if(UNIX AND NOT CMAKE_SYSTEM_NAME STREQUAL "Emscripten") # loaded properly if(APPLE) set(CMAKE_INSTALL_NAME_DIR "@rpath") - set(CMAKE_INSTALL_RPATH "@loader_path/") + set(PYARROW_RPATH_ORIGIN "@loader_path") else() - set(CMAKE_INSTALL_RPATH "\$ORIGIN") + set(PYARROW_RPATH_ORIGIN "\$ORIGIN") endif() + set(CMAKE_INSTALL_RPATH "${PYARROW_RPATH_ORIGIN}/") endif() find_program(CCACHE_FOUND ccache) @@ -731,12 +732,8 @@ if(PYARROW_BUILD_AZURE) endif() find_package(ArrowAzure REQUIRED) if(ARROW_BUILD_SHARED) - if(PYARROW_BUNDLE_ARROW_CPP) - bundle_arrow_lib(${ARROW_AZURE_SHARED_LIB} SO_VERSION ${ARROW_SO_VERSION}) - if(MSVC) - bundle_arrow_import_lib(${ARROW_AZURE_IMPORT_LIB}) - endif() - endif() + # Not bundled in the PyArrow wheel: it ships in the separate + # pyarrow-cloudfs wheel (python/pyarrow-cloudfs). set(AZURE_LINK_LIBS ArrowAzure::arrow_azure_shared) else() set(AZURE_LINK_LIBS ArrowAzure::arrow_azure_static) @@ -751,12 +748,8 @@ if(PYARROW_BUILD_GCS) endif() find_package(ArrowGcs REQUIRED) if(ARROW_BUILD_SHARED) - if(PYARROW_BUNDLE_ARROW_CPP) - bundle_arrow_lib(${ARROW_GCS_SHARED_LIB} SO_VERSION ${ARROW_SO_VERSION}) - if(MSVC) - bundle_arrow_import_lib(${ARROW_GCS_IMPORT_LIB}) - endif() - endif() + # Not bundled in the PyArrow wheel: it ships in the separate + # pyarrow-cloudfs wheel (python/pyarrow-cloudfs). set(GCS_LINK_LIBS ArrowGcs::arrow_gcs_shared) else() set(GCS_LINK_LIBS ArrowGcs::arrow_gcs_static) @@ -771,12 +764,8 @@ if(PYARROW_BUILD_S3) endif() find_package(ArrowS3 REQUIRED) if(ARROW_BUILD_SHARED) - if(PYARROW_BUNDLE_ARROW_CPP) - bundle_arrow_lib(${ARROW_S3_SHARED_LIB} SO_VERSION ${ARROW_SO_VERSION}) - if(MSVC) - bundle_arrow_import_lib(${ARROW_S3_IMPORT_LIB}) - endif() - endif() + # Not bundled in the PyArrow wheel: it ships in the separate + # pyarrow-cloudfs wheel (python/pyarrow-cloudfs). set(S3_LINK_LIBS ArrowS3::arrow_s3_shared) else() set(S3_LINK_LIBS ArrowS3::arrow_s3_static) @@ -894,18 +883,8 @@ endif() # Flight if(PYARROW_BUILD_FLIGHT) - if(PYARROW_BUNDLE_ARROW_CPP) - bundle_arrow_lib(${ARROW_FLIGHT_SHARED_LIB} SO_VERSION ${ARROW_SO_VERSION}) - if(MSVC) - bundle_arrow_import_lib(${ARROW_FLIGHT_IMPORT_LIB}) - # XXX Hardcoded library names because CMake is too stupid to give us - # the shared library paths. - # https://gitlab.kitware.com/cmake/cmake/issues/16210 - # bundle_arrow_dependency(libcrypto-1_1-x64) - # bundle_arrow_dependency(libssl-1_1-x64) - endif() - endif() - + # libarrow_flight is not bundled in the PyArrow wheel: it ships in the + # separate pyarrow-flight wheel (python/pyarrow-flight). set(FLIGHT_LINK_LIBS arrow_python_flight) list(APPEND CYTHON_EXTENSIONS _flight) else() @@ -1089,6 +1068,31 @@ if(PYARROW_BUILD_S3) target_link_libraries(_s3fs PRIVATE ${S3_LINK_LIBS}) endif() +if(PYARROW_BUNDLE_ARROW_CPP AND UNIX) + # libarrow_s3, libarrow_gcs and libarrow_azure ship in the sibling + # pyarrow-cloudfs wheel, so they are not in any directory these extensions + # already search. Preloading them from pyarrow_cloudfs/__init__.py is not + # enough: musl's loader does not match a DT_NEEDED entry against a library + # that was opened by an explicit path. + foreach(cloudfs_extension _azurefs _gcsfs _s3fs) + if(TARGET ${cloudfs_extension}) + set_property(TARGET ${cloudfs_extension} + APPEND + PROPERTY INSTALL_RPATH "${PYARROW_RPATH_ORIGIN}/../pyarrow_cloudfs") + endif() + endforeach() + # Likewise for libarrow_flight, which ships in the sibling pyarrow-flight + # wheel. arrow_python_flight carries the DT_NEEDED entry on it, and _flight + # links it through arrow_python_flight. + foreach(flight_target arrow_python_flight _flight) + if(TARGET ${flight_target}) + set_property(TARGET ${flight_target} + APPEND + PROPERTY INSTALL_RPATH "${PYARROW_RPATH_ORIGIN}/../pyarrow_flight") + endif() + endforeach() +endif() + # # Type stubs with docstring injection # diff --git a/python/pyarrow-cloudfs/CMakeLists.txt b/python/pyarrow-cloudfs/CMakeLists.txt new file mode 100644 index 00000000000..81469503c86 --- /dev/null +++ b/python/pyarrow-cloudfs/CMakeLists.txt @@ -0,0 +1,66 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +cmake_minimum_required(VERSION 3.25) + +# Nothing is compiled, but Arrow's CMake packages expect a language enabled. +project(pyarrow_cloudfs LANGUAGES CXX) + +# Which libraries to ship. The wheel build scripts pass the same ARROW_S3, +# ARROW_GCS and ARROW_AZURE values they build Arrow C++ with, so this wheel +# ships exactly what the pyarrow wheel leaves out. +option(PYARROW_CLOUDFS_S3 "Ship libarrow_s3" ON) +option(PYARROW_CLOUDFS_GCS "Ship libarrow_gcs" ON) +option(PYARROW_CLOUDFS_AZURE "Ship libarrow_azure" ON) + +# Install one Arrow library under the name pyarrow's extensions look it up by: +# its SONAME on Linux, its install name on macOS, the DLL name on Windows. +# The naming matches bundle_arrow_lib in python/CMakeLists.txt. +function(pyarrow_cloudfs_install_lib shared_lib import_lib) + get_filename_component(lib_real "${shared_lib}" REALPATH) + get_filename_component(lib_name "${shared_lib}" NAME_WE) + if(MSVC) + set(installed_name "${lib_name}${CMAKE_SHARED_LIBRARY_SUFFIX}") + elseif(APPLE) + set(installed_name "${lib_name}.${ARROW_SO_VERSION}${CMAKE_SHARED_LIBRARY_SUFFIX}") + else() + set(installed_name "${lib_name}${CMAKE_SHARED_LIBRARY_SUFFIX}.${ARROW_SO_VERSION}") + endif() + install(FILES "${lib_real}" + DESTINATION pyarrow_cloudfs + RENAME "${installed_name}") + if(MSVC) + # The import library, previously bundled in the pyarrow wheel, for C++ + # extensions that link against these libraries. + install(FILES "${import_lib}" + DESTINATION pyarrow_cloudfs + RENAME "${lib_name}.lib") + endif() +endfunction() + +if(PYARROW_CLOUDFS_S3) + find_package(ArrowS3 REQUIRED) + pyarrow_cloudfs_install_lib("${ARROW_S3_SHARED_LIB}" "${ARROW_S3_IMPORT_LIB}") +endif() +if(PYARROW_CLOUDFS_GCS) + find_package(ArrowGcs REQUIRED) + pyarrow_cloudfs_install_lib("${ARROW_GCS_SHARED_LIB}" "${ARROW_GCS_IMPORT_LIB}") +endif() +if(PYARROW_CLOUDFS_AZURE) + find_package(ArrowAzure REQUIRED) + pyarrow_cloudfs_install_lib("${ARROW_AZURE_SHARED_LIB}" "${ARROW_AZURE_IMPORT_LIB}") +endif() diff --git a/python/pyarrow-cloudfs/pyarrow_cloudfs/__init__.py b/python/pyarrow-cloudfs/pyarrow_cloudfs/__init__.py new file mode 100644 index 00000000000..99c86a1d276 --- /dev/null +++ b/python/pyarrow-cloudfs/pyarrow_cloudfs/__init__.py @@ -0,0 +1,70 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +S3, GCS and Azure filesystem support for PyArrow wheels. + +pyarrow imports this package itself, from pyarrow.fs. Importing it directly +is not needed. +""" + +import ctypes +import glob +import os +import sys +from importlib.metadata import version as _dist_version + +# These libraries depend on libarrow, which ships in the pyarrow wheel. +# Importing pyarrow first loads libarrow into the process, so the dynamic +# loader resolves that dependency by SONAME. +import pyarrow + +__version__ = _dist_version("pyarrow-cloudfs") + +# The libraries are built from the same sources as pyarrow's extensions and +# only work with that exact build. A patch release keeps the library file +# names, so a mismatch would still load: compare the full version. +# pyarrow.fs checks this too before importing this package; this check covers +# importing it directly. +if __version__ != pyarrow.__version__: + raise ImportError( + f"pyarrow-cloudfs {__version__} requires pyarrow {__version__}, but " + f"pyarrow {pyarrow.__version__} is installed. Install matching " + f"versions with 'pip install \"pyarrow-cloudfs=={pyarrow.__version__}\"'" + ) + + +def _pattern(name): + if sys.platform == "win32": + return f"{name}.dll" + elif sys.platform == "darwin": + return f"lib{name}.*.dylib" + else: + return f"lib{name}.so.*" + + +_here = os.path.dirname(__file__) + +# Keep references so the libraries stay loaded for the process lifetime. +# A library missing from the wheel is skipped: the build options +# PYARROW_CLOUDFS_S3, PYARROW_CLOUDFS_GCS and PYARROW_CLOUDFS_AZURE decide +# which ones ship. +_libraries = {} +for _name in ("arrow_s3", "arrow_gcs", "arrow_azure"): + _matches = glob.glob(os.path.join(_here, _pattern(_name))) + if _matches: + _libraries[_name] = ctypes.CDLL(_matches[0], mode=ctypes.RTLD_GLOBAL) diff --git a/python/pyarrow-cloudfs/pyproject.toml b/python/pyarrow-cloudfs/pyproject.toml new file mode 100644 index 00000000000..1c42520d014 --- /dev/null +++ b/python/pyarrow-cloudfs/pyproject.toml @@ -0,0 +1,47 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +[build-system] +requires = ["scikit-build-core>=1.0", "setuptools_scm[toml]>=8"] +build-backend = "scikit_build_core.build" + +[project] +name = "pyarrow-cloudfs" +dynamic = ["version", "dependencies"] +requires-python = ">=3.11" +description = "S3, GCS and Azure filesystem support for PyArrow" +license = "Apache-2.0" +# TODO: Add the license files + +[tool.scikit-build] +metadata.version.provider = "scikit_build_core.metadata.setuptools_scm" +wheel.packages = ["pyarrow_cloudfs"] +# The wheel ships a shared library but no CPython extension: one wheel per +# platform (py3-none-) installed to platlib, next to pyarrow. +wheel.py-api = "py3" +wheel.platlib = true + +# Pin pyarrow to exactly this package's version. +[tool.scikit-build.metadata.dependencies] +provider = "scikit_build_core.metadata.template" +result = ["pyarrow=={project[version]}"] + +[tool.setuptools_scm] +root = '../..' +version_scheme = 'guess-next-dev' +git_describe_command = 'git describe --dirty --tags --long --match "apache-arrow-[0-9]*.*"' +fallback_version = '26.0.0a0' diff --git a/python/pyarrow-flight/CMakeLists.txt b/python/pyarrow-flight/CMakeLists.txt new file mode 100644 index 00000000000..36e69d18825 --- /dev/null +++ b/python/pyarrow-flight/CMakeLists.txt @@ -0,0 +1,46 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +cmake_minimum_required(VERSION 3.25) + +# Nothing is compiled, but Arrow's CMake packages expect a language enabled. +project(pyarrow_flight LANGUAGES CXX) + +find_package(ArrowFlight REQUIRED) + +# Install libarrow_flight under the name pyarrow's arrow_python_flight looks +# it up by: its SONAME on Linux, its install name on macOS, the DLL name on +# Windows. The naming matches bundle_arrow_lib in python/CMakeLists.txt. +get_filename_component(lib_real "${ARROW_FLIGHT_SHARED_LIB}" REALPATH) +get_filename_component(lib_name "${ARROW_FLIGHT_SHARED_LIB}" NAME_WE) +if(MSVC) + set(installed_name "${lib_name}${CMAKE_SHARED_LIBRARY_SUFFIX}") +elseif(APPLE) + set(installed_name "${lib_name}.${ARROW_SO_VERSION}${CMAKE_SHARED_LIBRARY_SUFFIX}") +else() + set(installed_name "${lib_name}${CMAKE_SHARED_LIBRARY_SUFFIX}.${ARROW_SO_VERSION}") +endif() +install(FILES "${lib_real}" + DESTINATION pyarrow_flight + RENAME "${installed_name}") +if(MSVC) + # The import library, previously bundled in the pyarrow wheel, for C++ + # extensions that link against Arrow Flight. + install(FILES "${ARROW_FLIGHT_IMPORT_LIB}" + DESTINATION pyarrow_flight + RENAME "${lib_name}.lib") +endif() diff --git a/python/pyarrow-flight/pyarrow_flight/__init__.py b/python/pyarrow-flight/pyarrow_flight/__init__.py new file mode 100644 index 00000000000..419c414429f --- /dev/null +++ b/python/pyarrow-flight/pyarrow_flight/__init__.py @@ -0,0 +1,61 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Arrow Flight RPC support for PyArrow wheels. + +pyarrow imports this package itself, from pyarrow.flight. Importing it +directly is not needed. +""" + +import ctypes +import glob +import os +import sys +from importlib.metadata import version as _dist_version + +# libarrow_flight depends on libarrow, which ships in the pyarrow wheel. +# Importing pyarrow first loads libarrow into the process, so the dynamic +# loader resolves that dependency by SONAME. +import pyarrow + +__version__ = _dist_version("pyarrow-flight") + +# libarrow_flight is built from the same sources as pyarrow's extensions and +# only works with that exact build. A patch release keeps the library file +# names, so a mismatch would still load: compare the full version. +# pyarrow.flight checks this too before importing this package; this check +# covers importing it directly. +if __version__ != pyarrow.__version__: + raise ImportError( + f"pyarrow-flight {__version__} requires pyarrow {__version__}, but " + f"pyarrow {pyarrow.__version__} is installed. Install matching " + f"versions with 'pip install \"pyarrow-flight=={pyarrow.__version__}\"'" + ) + +if sys.platform == "win32": + _pattern = "arrow_flight.dll" +elif sys.platform == "darwin": + _pattern = "libarrow_flight.*.dylib" +else: + _pattern = "libarrow_flight.so.*" + +# Keep a reference so the library stays loaded for the process lifetime. +_libarrow_flight = ctypes.CDLL( + glob.glob(os.path.join(os.path.dirname(__file__), _pattern))[0], + mode=ctypes.RTLD_GLOBAL, +) diff --git a/python/pyarrow-flight/pyproject.toml b/python/pyarrow-flight/pyproject.toml new file mode 100644 index 00000000000..7b4569d25e4 --- /dev/null +++ b/python/pyarrow-flight/pyproject.toml @@ -0,0 +1,47 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +[build-system] +requires = ["scikit-build-core>=1.0", "setuptools_scm[toml]>=8"] +build-backend = "scikit_build_core.build" + +[project] +name = "pyarrow-flight" +dynamic = ["version", "dependencies"] +requires-python = ">=3.11" +description = "Arrow Flight RPC support for PyArrow" +license = "Apache-2.0" +# TODO: Add the license files + +[tool.scikit-build] +metadata.version.provider = "scikit_build_core.metadata.setuptools_scm" +wheel.packages = ["pyarrow_flight"] +# The wheel ships a shared library but no CPython extension: one wheel per +# platform (py3-none-) installed to platlib, next to pyarrow. +wheel.py-api = "py3" +wheel.platlib = true + +# Pin pyarrow to exactly this package's version. +[tool.scikit-build.metadata.dependencies] +provider = "scikit_build_core.metadata.template" +result = ["pyarrow=={project[version]}"] + +[tool.setuptools_scm] +root = '../..' +version_scheme = 'guess-next-dev' +git_describe_command = 'git describe --dirty --tags --long --match "apache-arrow-[0-9]*.*"' +fallback_version = '26.0.0a0' diff --git a/python/pyarrow/_fs.pyx b/python/pyarrow/_fs.pyx index 10b6ac52dd5..cdaa01573fc 100644 --- a/python/pyarrow/_fs.pyx +++ b/python/pyarrow/_fs.pyx @@ -21,7 +21,7 @@ from cpython.datetime cimport datetime, PyDateTime_DateTime from pyarrow.includes.common cimport * from pyarrow.includes.libarrow_python cimport PyDateTime_to_TimePoint -from pyarrow.lib import _detect_compression, frombytes, tobytes +from pyarrow.lib import ArrowInvalid, _detect_compression, frombytes, tobytes from pyarrow.lib cimport * from pyarrow.util import _stringify_path @@ -408,6 +408,17 @@ cdef class FileSelector(_Weakrefable): return f"" +# URI schemes whose filesystems ship in the pyarrow-cloudfs package for PyPI +# wheels, mapped to the pyarrow.fs name that records why they are missing. +_CLOUDFS_SCHEMES = { + "s3": "S3FileSystem", + "gs": "GcsFileSystem", + "gcs": "GcsFileSystem", + "abfs": "AzureFileSystem", + "abfss": "AzureFileSystem", +} + + cdef class FileSystem(_Weakrefable): """ Abstract file system API. @@ -499,8 +510,28 @@ cdef class FileSystem(_Weakrefable): """ if isinstance(uri, str) and uri.startswith(("fsspec+", "hf://")): return FileSystem._fsspec_from_uri(uri) - else: + try: return FileSystem._native_from_uri(uri) + except ArrowInvalid as exc: + if "Unrecognized filesystem type" not in str(exc): + raise + uri_str = frombytes(uri) if isinstance(uri, bytes) else uri + scheme = (uri_str.partition("://")[0].lower() + if isinstance(uri_str, str) else None) + name = _CLOUDFS_SCHEMES.get(scheme) + if name is None: + raise + # S3, GCS and Azure support can ship separately, as the + # pyarrow-cloudfs package. Importing pyarrow.fs loads it if + # installed, which registers the scheme. + import pyarrow.fs + if name not in pyarrow.fs._not_imported: + return FileSystem._native_from_uri(uri) + reason = pyarrow.fs._not_imported_reasons.get(name) + if reason is None: + # pyarrow was built without this filesystem. + raise + raise ArrowInvalid(f"{exc} ({reason})") from None cdef init(self, const shared_ptr[CFileSystem]& wrapped): self.wrapped = wrapped diff --git a/python/pyarrow/flight.py b/python/pyarrow/flight.py index b1836907c67..36db721f80e 100644 --- a/python/pyarrow/flight.py +++ b/python/pyarrow/flight.py @@ -15,6 +15,34 @@ # specific language governing permissions and limitations # under the License. +def _load_pyarrow_flight(): + # Flight support can be installed separately, as the pyarrow-flight + # package. Importing it loads libarrow_flight so that pyarrow._flight can + # be imported. + from importlib.metadata import PackageNotFoundError, version + from pyarrow import __version__ + try: + installed = version("pyarrow-flight") + except PackageNotFoundError: + return + # libarrow_flight only works with the libarrow of the exact same build. + # A patch release keeps the library file names, so check the version + # before importing: pyarrow._flight would load a mismatched library. + if installed != __version__: + raise ImportError( + f"pyarrow-flight {installed} is installed, but pyarrow is " + f"{__version__}. Install the matching version with " + f"'pip install \"pyarrow-flight=={__version__}\"'" + ) + try: + import pyarrow_flight # noqa: F401 + except (ImportError, OSError) as exc: + raise ImportError( + f"pyarrow-flight could not be loaded: {exc}") from None + + +_load_pyarrow_flight() + try: from pyarrow._flight import ( # noqa:F401 connect, @@ -64,6 +92,12 @@ TracingServerMiddlewareFactory, ) except ImportError as exc: - raise ImportError( - f"The pyarrow installation is not built with support for 'flight' ({str(exc)})" - ) from None + msg = f"The pyarrow installation is not built with support for 'flight' ({exc})" + if not isinstance(exc, ModuleNotFoundError): + # pyarrow._flight exists, but libarrow_flight could not be loaded. + msg += ( + ". If pyarrow was installed from PyPI, Flight support is provided " + "by the separate 'pyarrow-flight' package: install it with " + "'pip install \"pyarrow[flight]\"'" + ) + raise ImportError(msg) from None diff --git a/python/pyarrow/fs.py b/python/pyarrow/fs.py index 670ccaaf245..6bf5358fdff 100644 --- a/python/pyarrow/fs.py +++ b/python/pyarrow/fs.py @@ -39,10 +39,79 @@ FileStats = FileInfo _not_imported = [] +_not_imported_reasons: dict[str, str] = {} + + +class _CloudFsUnavailable(ImportError): + pass + + +def _load_cloudfs(): + """ + Load pyarrow-cloudfs if it is installed and matches this pyarrow. + + PyPI wheels ship libarrow_s3, libarrow_gcs and libarrow_azure in the + separate pyarrow-cloudfs package. Other builds (conda, distros, source) + have no such package and link the libraries directly. + + Return a message saying why the installed pyarrow-cloudfs cannot be + used, or None. + """ + from importlib.metadata import PackageNotFoundError, version + from pyarrow import __version__ + try: + installed = version("pyarrow-cloudfs") + except PackageNotFoundError: + return None + if installed != __version__: + # The normal state after 'pip install -U pyarrow': pip upgrades + # pyarrow but not the pyarrow-cloudfs installed next to it. Compare + # the full version: a patch release keeps the library file names, so + # the loader would otherwise load the mismatched libraries. + return ( + f"pyarrow-cloudfs {installed} is installed, but pyarrow is " + f"{__version__}. Install the matching version with " + f"'pip install \"pyarrow-cloudfs=={__version__}\"'" + ) + try: + # Preloads the libraries so that pyarrow._s3fs, _gcsfs and _azurefs + # can resolve them. + import pyarrow_cloudfs # noqa: F401 + except (ImportError, OSError) as exc: + return f"pyarrow-cloudfs could not be loaded: {exc}" + return None + + +_cloudfs_error = _load_cloudfs() + + +def _require_cloudfs(): + # When pyarrow-cloudfs cannot be used, the extensions must not even be + # imported: their RPATH points into the sibling pyarrow_cloudfs + # directory, so the dynamic loader would find its libraries on its own. + if _cloudfs_error is not None: + raise _CloudFsUnavailable(_cloudfs_error) + + +def _cloudfs_not_imported(name, extra, exc): + _not_imported.append(name) + if isinstance(exc, _CloudFsUnavailable): + _not_imported_reasons[name] = str(exc) + elif not isinstance(exc, ModuleNotFoundError): + # The extension exists, but its Arrow library could not be loaded. + _not_imported_reasons[name] = ( + f"{exc}. If pyarrow was installed from PyPI, this support is " + "provided by the separate 'pyarrow-cloudfs' package: install it " + f"with 'pip install \"pyarrow[{extra}]\"'" + ) + # ModuleNotFoundError: pyarrow was built without it, nothing to add. + + try: + _require_cloudfs() from pyarrow._azurefs import AzureFileSystem # noqa -except ImportError: - _not_imported.append("AzureFileSystem") +except ImportError as exc: + _cloudfs_not_imported("AzureFileSystem", "azure", exc) try: from pyarrow._hdfs import HadoopFileSystem # noqa @@ -50,17 +119,19 @@ _not_imported.append("HadoopFileSystem") try: + _require_cloudfs() from pyarrow._gcsfs import GcsFileSystem # noqa -except ImportError: - _not_imported.append("GcsFileSystem") +except ImportError as exc: + _cloudfs_not_imported("GcsFileSystem", "gcs", exc) try: + _require_cloudfs() from pyarrow._s3fs import ( # noqa AwsDefaultS3RetryStrategy, AwsStandardS3RetryStrategy, S3FileSystem, S3LogLevel, S3RetryStrategy, ensure_s3_initialized, finalize_s3, ensure_s3_finalized, initialize_s3, resolve_s3_region) -except ImportError: - _not_imported.append("S3FileSystem") +except ImportError as exc: + _cloudfs_not_imported("S3FileSystem", "s3", exc) else: # GH-38364: we don't initialize S3 eagerly as that could lead # to crashes at shutdown even when S3 isn't used. @@ -72,10 +143,11 @@ def __getattr__(name): if name in _not_imported: + if name in _not_imported_reasons: + raise ImportError( + f"'{name}' is not available: {_not_imported_reasons[name]}") raise ImportError( - "The pyarrow installation is not built with support for " - f"'{name}'" - ) + f"The pyarrow installation is not built with support for '{name}'") raise AttributeError( f"module 'pyarrow.fs' has no attribute '{name}'" diff --git a/python/pyproject.toml b/python/pyproject.toml index 1556354f6bd..89592ff97ae 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -29,7 +29,7 @@ build-backend = "scikit_build_core.build" [project] name = "pyarrow" -dynamic = ["version"] +dynamic = ["version", "optional-dependencies"] requires-python = ">=3.11" description = "Python library for Apache Arrow" readme = {file = "README.md", content-type = "text/markdown"} @@ -104,6 +104,16 @@ PYARROW_GENERATE_COVERAGE = {env = "PYARROW_GENERATE_COVERAGE", default = "OFF"} PYARROW_CXXFLAGS = {env = "PYARROW_CXXFLAGS", default = ""} PYARROW_REQUIRE_STUB_DOCSTRINGS = {env = "PYARROW_REQUIRE_STUB_DOCSTRINGS", default = "OFF"} +# Optional components shipped as separate wheels, pinned to this exact version. +[tool.scikit-build.metadata.optional-dependencies] +provider = "scikit_build_core.metadata.template" + +[tool.scikit-build.metadata.optional-dependencies.result] +s3 = ["pyarrow-cloudfs=={project[version]}"] +gcs = ["pyarrow-cloudfs=={project[version]}"] +azure = ["pyarrow-cloudfs=={project[version]}"] +flight = ["pyarrow-flight=={project[version]}"] + [tool.setuptools_scm] root = '..' version_file = 'pyarrow/_generated_version.py' @@ -128,7 +138,7 @@ follow_imports = "skip" # Optional dependencies without type hints. [[tool.mypy.overrides]] -module = ["fsspec", "sparse"] +module = ["fsspec", "pyarrow_cloudfs", "pyarrow_flight", "sparse"] ignore_missing_imports = true [tool.pyright]