├── .gitignore ├── .gitmodules ├── Cargo.toml ├── LICENSE ├── README.md ├── docker └── ubuntu │ ├── Dockerfile │ └── README.md ├── hdfs-examples ├── Cargo.toml └── src │ └── bin │ └── ballista-sql.rs ├── hdfs-testing ├── Cargo.toml └── src │ ├── lib.rs │ └── util.rs └── hdfs ├── Cargo.toml └── src ├── lib.rs └── object_store ├── hdfs.rs └── mod.rs /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | .idea/ 3 | 4 | # Compiled source 5 | *.a 6 | *.dll 7 | *.o 8 | *.py[ocd] 9 | *.so 10 | *.so.* 11 | *.bundle 12 | *.dylib 13 | 14 | # Generated Visual Studio files 15 | *.vcxproj 16 | *.vcxproj.* 17 | *.sln 18 | *.iml 19 | 20 | # macOS 21 | .DS_Store 22 | 23 | # Rust 24 | target 25 | build 26 | Cargo.lock 27 | 28 | # For files generated by build.rs 29 | tmp -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "parquet-testing"] 2 | path = parquet-testing 3 | url = https://github.com/apache/parquet-testing.git 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | [workspace] 19 | members = [ 20 | "hdfs", 21 | "hdfs-examples", 22 | "hdfs-testing", 23 | ] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # datafusion-objectstore-hdfs 2 | 3 | HDFS as a remote ObjectStore for [Datafusion](https://github.com/apache/arrow-datafusion). 4 | 5 | ## Querying files on HDFS with DataFusion 6 | 7 | This crate introduces ``HadoopFileSystem`` as a remote ObjectStore which provides the ability of querying on HDFS files. 8 | 9 | For the HDFS access, We leverage the library [fs-hdfs](https://github.com/datafusion-contrib/fs-hdfs). Basically, the library only provides Rust FFI APIs for the ``libhdfs`` which can be compiled by a set of C files provided by the [official Hadoop Community](https://github.com/apache/hadoop). 10 | 11 | ## Prerequisites 12 | Since the ``libhdfs`` is also just a C interface wrapper and the real implementation for the HDFS access is a set of Java jars, in order to make this crate work, we need to prepare the Hadoop client jars and the JRE environment. 13 | 14 | ### Prepare JAVA 15 | 16 | 1. Install Java. 17 | 18 | 2. Specify and export ``JAVA_HOME``. 19 | 20 | ### Prepare Hadoop client 21 | 22 | 1. To get a Hadoop distribution, download a recent stable release from one of the [Apache Download Mirrors](http://www.apache.org/dyn/closer.cgi/hadoop/common). Currently, we support Hadoop-2 and Hadoop-3. 23 | 24 | 2. Unpack the downloaded Hadoop distribution. For example, the folder is /opt/hadoop. Then prepare some environment variables: 25 | ```shell 26 | export HADOOP_HOME=/opt/hadoop 27 | 28 | export PATH=$PATH:$HADOOP_HOME/bin 29 | ``` 30 | 31 | ### Prepare JRE environment 32 | 33 | 1. Firstly, we need to add library path for the jvm related dependencies. An example for MacOS, 34 | ```shell 35 | export DYLD_LIBRARY_PATH=$JAVA_HOME/jre/lib/server 36 | ``` 37 | 38 | 2. Since our compiled libhdfs is JNI native implementation, it requires the proper CLASSPATH to load the Hadoop related jars. An example, 39 | ```shell 40 | export CLASSPATH=$CLASSPATH:`hadoop classpath --glob` 41 | ``` 42 | 43 | ## Examples 44 | Suppose there's a hdfs directory, 45 | ```rust 46 | let hdfs_file_uri = "hdfs://localhost:8020/testing/tpch_1g/parquet/line_item"; 47 | ``` 48 | in which there're a list of parquet files. Then we can query on these parquet files as follows: 49 | ```rust 50 | let ctx = SessionContext::new(); 51 | let url = Url::parse("hdfs://").unwrap(); 52 | ctx.runtime_env().register_object_store(&url, Arc::new(HadoopFileSystem)); 53 | let table_name = "line_item"; 54 | println!( 55 | "Register table {} with parquet file {}", 56 | table_name, hdfs_file_uri 57 | ); 58 | ctx.register_parquet(table_name, &hdfs_file_uri, ParquetReadOptions::default()).await?; 59 | 60 | let sql = "SELECT count(*) FROM line_item"; 61 | let result = ctx.sql(sql).await?.collect().await?; 62 | ``` 63 | 64 | ## Testing 65 | 1. First clone the test data repository: 66 | ```shell 67 | git submodule update --init --recursive 68 | ``` 69 | 70 | 2. Run testing 71 | ```shell 72 | cargo test 73 | ``` 74 | During the testing, a HDFS cluster will be mocked and started automatically. 75 | 76 | 3. Run testing for with enabling feature hdfs3 77 | ```shell 78 | cargo build --no-default-features --features datafusion-objectstore-hdfs/hdfs3,datafusion-objectstore-hdfs-testing/hdfs3,datafusion-hdfs-examples/hdfs3 79 | 80 | cargo test --no-default-features --features datafusion-objectstore-hdfs/hdfs3,datafusion-objectstore-hdfs-testing/hdfs3,datafusion-hdfs-examples/hdfs3 81 | ``` 82 | 83 | Run the ballista-sql test by 84 | ```shell 85 | cargo run --bin ballista-sql --no-default-features --features hdfs3 86 | ``` -------------------------------------------------------------------------------- /docker/ubuntu/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:20.04 2 | 3 | MAINTAINER Yanghong Zhong 4 | 5 | WORKDIR /tmp 6 | 7 | # install tools 8 | RUN set -x \ 9 | && apt-get update \ 10 | && apt install -y lsb-release wget curl 11 | 12 | # install llvm 13 | RUN set -x \ 14 | && apt install -y software-properties-common apt-transport-https \ 15 | && cd /tmp \ 16 | && wget https://apt.llvm.org/llvm.sh \ 17 | && chmod +x llvm.sh \ 18 | && ./llvm.sh 12 19 | 20 | ARG APACHE_HOME=/apache 21 | 22 | # install jdk 23 | RUN set -x \ 24 | && apt-get install -y openjdk-8-jdk \ 25 | && java -version 26 | 27 | ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64 28 | 29 | RUN set -x \ 30 | && mkdir -p $APACHE_HOME \ 31 | && ln -s $JAVA_HOME /apache/java 32 | 33 | # install hadoop clients 34 | ARG HADOOP_VERSION=2.10.1 35 | ENV HADOOP_HOME=$APACHE_HOME/hadoop 36 | RUN set -x \ 37 | && wget https://dlcdn.apache.org/hadoop/common/stable2/hadoop-${HADOOP_VERSION}.tar.gz \ 38 | && tar -xzvf hadoop-${HADOOP_VERSION}.tar.gz -C $APACHE_HOME \ 39 | && rm -f hadoop-${HADOOP_VERSION}.tar.gz \ 40 | && ln -s $APACHE_HOME/hadoop-${HADOOP_VERSION} $HADOOP_HOME 41 | 42 | # install Rust 43 | RUN curl https://sh.rustup.rs -sSf | bash -s -- -y 44 | 45 | ENV PATH=$PATH:$JAVA_HOME/bin:$HADOOP_HOME/bin:$HADOOP_HOME/sbin:$HOME/.cargo/bin 46 | 47 | RUN echo "export CLASSPATH=`hadoop classpath --glob`:$CLASSPATH" >> $HOME/.bashrc 48 | 49 | ENV LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/amd64/server/:$LD_LIBRARY_PATH 50 | 51 | # install gcc 52 | RUN set -x \ 53 | && apt-get install -y gcc \ 54 | && gcc --version 55 | 56 | # install git 57 | RUN set -x \ 58 | && apt-get install -y git \ 59 | && git version 60 | 61 | # Download source code 62 | RUN set -x \ 63 | && cd ~ \ 64 | && git clone https://github.com/datafusion-contrib/datafusion-objectstore-hdfs.git 65 | 66 | -------------------------------------------------------------------------------- /docker/ubuntu/README.md: -------------------------------------------------------------------------------- 1 | # Guidance 2 | 3 | ## Build Image 4 | 5 | > docker build -t datafusion-objectstore-hdfs-ubuntu:1.0 -f ./Dockerfile . 6 | 7 | ## Run Container 8 | 9 | Run container 10 | > docker run --name datafusion-objectstore-hdfs -it datafusion-objectstore-hdfs-ubuntu:1.0 bash 11 | 12 | > docker start datafusion-objectstore-hdfs 13 | 14 | > docker exec -it datafusion-objectstore-hdfs bash 15 | 16 | ## Test 17 | 18 | > cd ~/datafusion-objectstore-hdfs 19 | 20 | > git submodule update --init --recursive 21 | 22 | > cargo test -------------------------------------------------------------------------------- /hdfs-examples/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "datafusion-hdfs-examples" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | authors = ["Yanghong Zhong "] 7 | license = "Apache-2.0" 8 | readme = "../README.md" 9 | repository = "https://github.com/datafusion-contrib/datafusion-objectstore-hdfs" 10 | 11 | [features] 12 | default = ["hdfs"] 13 | hdfs = ["ballista/hdfs", "datafusion-objectstore-hdfs-testing/hdfs"] 14 | hdfs3 = ["ballista/hdfs3", "datafusion-objectstore-hdfs-testing/hdfs3"] 15 | 16 | [dependencies] 17 | ballista = { git = "https://github.com/apache/arrow-ballista.git", rev = "90b5cc748c5f92762e9ede52d6908d62823f9563", features = ["standalone"] } 18 | datafusion = "34.0.0" 19 | datafusion-objectstore-hdfs-testing = { path = "../hdfs-testing", default-features = false } 20 | futures = "0.3" 21 | num_cpus = "1.13.0" 22 | prost = "0.11" 23 | tokio = { version = "1.18", features = ["macros", "rt", "rt-multi-thread", "sync", "parking_lot"] } 24 | tonic = "0.10" -------------------------------------------------------------------------------- /hdfs-examples/src/bin/ballista-sql.rs: -------------------------------------------------------------------------------- 1 | // Licensed to the Apache Software Foundation (ASF) under one 2 | // or more contributor license agreements. See the NOTICE file 3 | // distributed with this work for additional information 4 | // regarding copyright ownership. The ASF licenses this file 5 | // to you under the Apache License, Version 2.0 (the 6 | // "License"); you may not use this file except in compliance 7 | // with the License. You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, 12 | // software distributed under the License is distributed on an 13 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | // KIND, either express or implied. See the License for the 15 | // specific language governing permissions and limitations 16 | // under the License. 17 | 18 | use std::future::Future; 19 | use std::pin::Pin; 20 | 21 | use ballista::prelude::*; 22 | use datafusion::error::{DataFusionError, Result}; 23 | use datafusion::prelude::ParquetReadOptions; 24 | 25 | use datafusion_objectstore_hdfs_testing::util::run_hdfs_test; 26 | 27 | /// This example demonstrates executing a simple query against an Arrow data source (CSV) and 28 | /// fetching results, using SQL 29 | #[tokio::main] 30 | async fn main() -> Result<()> { 31 | run_with_register_alltypes_parquet(|ctx| { 32 | Box::pin(async move { 33 | { 34 | // NOTE that string_col is actually a binary column and does not have the UTF8 logical type 35 | // so we need an explicit cast 36 | let sql = "SELECT id, CAST(string_col AS varchar) FROM alltypes_plain"; 37 | 38 | // execute the query 39 | let df = ctx.sql(sql).await?; 40 | 41 | // print the results 42 | df.show().await?; 43 | } 44 | 45 | { 46 | let sql = "SELECT count(*) FROM alltypes_plain"; 47 | 48 | // execute the query 49 | let df = ctx.sql(sql).await?; 50 | 51 | // print the results 52 | df.show().await?; 53 | } 54 | 55 | Ok(()) 56 | }) 57 | }) 58 | .await?; 59 | 60 | Ok(()) 61 | } 62 | 63 | /// Run query after table registered with parquet file on hdfs 64 | pub async fn run_with_register_alltypes_parquet(test_query: F) -> Result<()> 65 | where 66 | F: FnOnce(BallistaContext) -> Pin> + 'static>> 67 | + Send 68 | + 'static, 69 | { 70 | run_hdfs_test("alltypes_plain.parquet".to_string(), |filename_hdfs| { 71 | Box::pin(async move { 72 | let config = BallistaConfig::builder() 73 | .set("ballista.shuffle.partitions", "4") 74 | .build() 75 | .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?; 76 | let ctx = BallistaContext::standalone(&config, 4) 77 | .await 78 | .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?; 79 | 80 | let table_name = "alltypes_plain"; 81 | println!( 82 | "Register table {} with parquet file {}", 83 | table_name, filename_hdfs 84 | ); 85 | ctx.register_parquet(table_name, &filename_hdfs, ParquetReadOptions::default()) 86 | .await?; 87 | 88 | test_query(ctx).await 89 | }) 90 | }) 91 | .await 92 | } 93 | -------------------------------------------------------------------------------- /hdfs-testing/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | [package] 19 | name = "datafusion-objectstore-hdfs-testing" 20 | version = "0.1.3" 21 | edition = "2021" 22 | 23 | authors = ["Yanghong Zhong "] 24 | license = "Apache-2.0" 25 | readme = "../README.md" 26 | repository = "https://github.com/datafusion-contrib/datafusion-objectstore-hdfs" 27 | 28 | [features] 29 | default = ["hdfs"] 30 | hdfs = ["fs-hdfs"] 31 | hdfs3 = ["fs-hdfs3"] 32 | 33 | [dependencies] 34 | datafusion = { version = "34.0.0" } 35 | fs-hdfs = { version = "^0.1.12", optional = true } 36 | fs-hdfs3 = { version = "^0.1.12", optional = true } 37 | uuid = { version = "1.0", features = ["v4"] } 38 | 39 | [dev-dependencies] 40 | arrow = { version = "45.0.0", features = ["prettyprint", "dyn_cmp_dict"] } 41 | datafusion-objectstore-hdfs = { path = "../hdfs" } 42 | futures = "0.3" 43 | object_store = "0.8.0" 44 | tokio = { version = "1.18", features = ["macros", "rt", "rt-multi-thread", "sync", "fs"] } 45 | url = "2.2" -------------------------------------------------------------------------------- /hdfs-testing/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Licensed to the Apache Software Foundation (ASF) under one 2 | // or more contributor license agreements. See the NOTICE file 3 | // distributed with this work for additional information 4 | // regarding copyright ownership. The ASF licenses this file 5 | // to you under the Apache License, Version 2.0 (the 6 | // "License"); you may not use this file except in compliance 7 | // with the License. You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, 12 | // software distributed under the License is distributed on an 13 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | // KIND, either express or implied. See the License for the 15 | // specific language governing permissions and limitations 16 | // under the License. 17 | 18 | pub mod util; 19 | 20 | #[cfg(test)] 21 | mod tests { 22 | use crate::util::run_hdfs_test; 23 | 24 | use std::future::Future; 25 | use std::pin::Pin; 26 | use std::sync::Arc; 27 | 28 | use datafusion::assert_batches_eq; 29 | use datafusion::datasource::file_format::parquet::ParquetFormat; 30 | use datafusion::datasource::file_format::FileFormat; 31 | use datafusion::datasource::listing::PartitionedFile; 32 | use datafusion::datasource::object_store::ObjectStoreUrl; 33 | use datafusion::datasource::physical_plan::FileScanConfig; 34 | use datafusion::error::Result; 35 | use datafusion::physical_plan::ExecutionPlan; 36 | use datafusion::prelude::{ParquetReadOptions, SessionConfig, SessionContext}; 37 | 38 | use datafusion_objectstore_hdfs::object_store::hdfs::{get_path, HadoopFileSystem}; 39 | use futures::StreamExt; 40 | use object_store::ObjectStore; 41 | use url::Url; 42 | 43 | #[tokio::test] 44 | async fn test_read() -> Result<()> { 45 | run_hdfs_test("alltypes_plain.parquet".to_string(), |filename_hdfs| { 46 | Box::pin(async move { 47 | let hdfs_object_store = HadoopFileSystem::new(&filename_hdfs).unwrap(); 48 | let location = get_path(&filename_hdfs, &hdfs_object_store.get_path_root()); 49 | let ret = hdfs_object_store.get(&location).await?; 50 | let data = ret.bytes().await?; 51 | assert!(data.len() > 0); 52 | 53 | Ok(()) 54 | }) 55 | }) 56 | .await 57 | } 58 | 59 | #[tokio::test] 60 | async fn read_small_batches_from_hdfs() -> Result<()> { 61 | run_hdfs_test("alltypes_plain.parquet".to_string(), |filename_hdfs| { 62 | Box::pin(async move { 63 | let session_context = 64 | SessionContext::with_config(SessionConfig::new().with_batch_size(2)); 65 | let projection = None; 66 | let exec = 67 | get_hdfs_exec(&session_context, filename_hdfs.as_str(), &projection, None) 68 | .await?; 69 | let stream = exec.execute(0, session_context.task_ctx())?; 70 | 71 | let tt_batches = stream 72 | .map(|batch| { 73 | let batch = batch.unwrap(); 74 | assert_eq!(11, batch.num_columns()); 75 | assert_eq!(2, batch.num_rows()); 76 | }) 77 | .fold(0, |acc, _| async move { acc + 1i32 }) 78 | .await; 79 | 80 | assert_eq!(tt_batches, 4 /* 8/2 */); 81 | 82 | // test metadata 83 | assert_eq!(exec.statistics().num_rows, Some(8)); 84 | assert_eq!(exec.statistics().total_byte_size, Some(671)); 85 | 86 | Ok(()) 87 | }) 88 | }) 89 | .await 90 | } 91 | 92 | #[tokio::test] 93 | async fn parquet_query() { 94 | run_with_register_alltypes_parquet(|ctx| { 95 | Box::pin(async move { 96 | // NOTE that string_col is actually a binary column and does not have the UTF8 logical type 97 | // so we need an explicit cast 98 | let sql = "SELECT id, CAST(string_col AS varchar) FROM alltypes_plain"; 99 | let actual = ctx.sql(sql).await?.collect().await?; 100 | let expected = vec![ 101 | "+----+---------------------------+", 102 | "| id | alltypes_plain.string_col |", 103 | "+----+---------------------------+", 104 | "| 4 | 0 |", 105 | "| 5 | 1 |", 106 | "| 6 | 0 |", 107 | "| 7 | 1 |", 108 | "| 2 | 0 |", 109 | "| 3 | 1 |", 110 | "| 0 | 0 |", 111 | "| 1 | 1 |", 112 | "+----+---------------------------+", 113 | ]; 114 | 115 | assert_batches_eq!(expected, &actual); 116 | 117 | Ok(()) 118 | }) 119 | }) 120 | .await 121 | .unwrap() 122 | } 123 | 124 | async fn get_hdfs_exec( 125 | ctx: &SessionContext, 126 | file_name: &str, 127 | projection: &Option>, 128 | limit: Option, 129 | ) -> Result> { 130 | let state = ctx.state(); 131 | let store = Arc::new(HadoopFileSystem::new(file_name).unwrap()); 132 | register_hdfs_object_store(ctx, store.clone()); 133 | 134 | let path_root = store.get_path_root(); 135 | let file_path = store.get_path(file_name); 136 | let file_meta = store.head(&file_path).await?; 137 | let file_partition = PartitionedFile { 138 | object_meta: file_meta.clone(), 139 | partition_values: vec![], 140 | range: None, 141 | extensions: None, 142 | }; 143 | 144 | let store = store as _; 145 | let format = ParquetFormat::default(); 146 | let file_schema = format 147 | .infer_schema(&state, &store, vec![file_meta.clone()].as_slice()) 148 | .await 149 | .expect("Schema inference"); 150 | let statistics = format 151 | .infer_stats(&state, &store, file_schema.clone(), &file_meta) 152 | .await 153 | .expect("Stats inference"); 154 | let file_groups = vec![vec![file_partition]]; 155 | let exec = format 156 | .create_physical_plan( 157 | &state, 158 | FileScanConfig { 159 | object_store_url: ObjectStoreUrl::parse(path_root).unwrap(), 160 | file_schema, 161 | file_groups, 162 | statistics, 163 | projection: projection.clone(), 164 | limit, 165 | table_partition_cols: vec![], 166 | output_ordering: vec![], 167 | infinite_source: false, 168 | }, 169 | None, 170 | ) 171 | .await?; 172 | Ok(exec) 173 | } 174 | 175 | /// Run query after table registered with parquet file on hdfs 176 | pub async fn run_with_register_alltypes_parquet(test_query: F) -> Result<()> 177 | where 178 | F: FnOnce(SessionContext) -> Pin> + Send + 'static>> 179 | + Send 180 | + 'static, 181 | { 182 | run_hdfs_test("alltypes_plain.parquet".to_string(), |hdfs_file_uri| { 183 | Box::pin(async move { 184 | let ctx = SessionContext::new(); 185 | register_hdfs_object_store( 186 | &ctx, 187 | Arc::new(HadoopFileSystem::new(&hdfs_file_uri).unwrap()), 188 | ); 189 | let table_name = "alltypes_plain"; 190 | println!( 191 | "Register table {} with parquet file {}", 192 | table_name, hdfs_file_uri 193 | ); 194 | ctx.register_parquet(table_name, &hdfs_file_uri, ParquetReadOptions::default()) 195 | .await?; 196 | 197 | test_query(ctx).await 198 | }) 199 | }) 200 | .await 201 | } 202 | 203 | fn register_hdfs_object_store(ctx: &SessionContext, store: Arc) { 204 | let url = Url::parse(&store.get_path_root()).unwrap(); 205 | ctx.runtime_env().register_object_store(&url, store); 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /hdfs-testing/src/util.rs: -------------------------------------------------------------------------------- 1 | // Licensed to the Apache Software Foundation (ASF) under one 2 | // or more contributor license agreements. See the NOTICE file 3 | // distributed with this work for additional information 4 | // regarding copyright ownership. The ASF licenses this file 5 | // to you under the Apache License, Version 2.0 (the 6 | // "License"); you may not use this file except in compliance 7 | // with the License. You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, 12 | // software distributed under the License is distributed on an 13 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | // KIND, either express or implied. See the License for the 15 | // specific language governing permissions and limitations 16 | // under the License. 17 | 18 | //! utility for setup local hdfs testing environment 19 | 20 | use datafusion::common::DataFusionError; 21 | use datafusion::error::Result; 22 | use hdfs::minidfs; 23 | use hdfs::util::HdfsUtil; 24 | use std::env; 25 | use std::future::Future; 26 | use std::path::PathBuf; 27 | use std::pin::Pin; 28 | use uuid::Uuid; 29 | 30 | /// Run test after related data prepared 31 | pub async fn run_hdfs_test(filename: String, test: F) -> Result<()> 32 | where 33 | F: FnOnce(String) -> Pin> + 'static>>, 34 | { 35 | let (tmp_dir, dst_file) = setup_with_hdfs_data(&filename); 36 | 37 | let result = test(dst_file).await; 38 | 39 | teardown(&tmp_dir); 40 | 41 | result 42 | } 43 | 44 | /// Prepare hdfs parquet file by copying local parquet file to hdfs 45 | fn setup_with_hdfs_data(filename: &str) -> (String, String) { 46 | let uuid = Uuid::new_v4().to_string(); 47 | let tmp_dir = format!("/{}", uuid); 48 | 49 | let dfs = minidfs::get_dfs(); 50 | let fs = dfs.get_hdfs().ok().unwrap(); 51 | assert!(fs.mkdir(&tmp_dir).is_ok()); 52 | 53 | // Source 54 | let testdata = parquet_test_data(); 55 | let src_path = format!("{}/{}", testdata, filename); 56 | 57 | // Destination 58 | let dst_path = format!("{}/{}", tmp_dir, filename); 59 | 60 | // Copy to hdfs 61 | assert!(HdfsUtil::copy_file_to_hdfs(dfs.clone(), &src_path, &dst_path).is_ok()); 62 | 63 | (tmp_dir, format!("{}{}", dfs.namenode_addr(), dst_path)) 64 | } 65 | 66 | /// Cleanup testing files in hdfs 67 | fn teardown(tmp_dir: &str) { 68 | let dfs = minidfs::get_dfs(); 69 | let fs = dfs.get_hdfs().ok().unwrap(); 70 | assert!(fs.delete(tmp_dir, true).is_ok()); 71 | } 72 | 73 | /// Returns the parquet test data directory, which is by default 74 | /// stored in a git submodule rooted at 75 | /// `parquet-testing/data`. 76 | /// 77 | /// panics when the directory can not be found. 78 | pub fn parquet_test_data() -> String { 79 | match get_data_dir("../parquet-testing/data") { 80 | Ok(pb) => pb.display().to_string(), 81 | Err(err) => panic!("failed to get parquet data dir: {}", err), 82 | } 83 | } 84 | 85 | /// Returns a directory path for finding test data. 86 | /// 87 | /// submodule_dir: path relative to CARGO_MANIFEST_DIR 88 | /// 89 | /// Returns: 90 | /// The submodule_data directory relative to CARGO_MANIFEST_PATH 91 | fn get_data_dir(submodule_data: &str) -> Result { 92 | // env "CARGO_MANIFEST_DIR" is "the directory containing the manifest of your package", 93 | // set by `cargo run` or `cargo test`, see: 94 | // https://doc.rust-lang.org/cargo/reference/environment-variables.html 95 | let dir = env!("CARGO_MANIFEST_DIR"); 96 | 97 | let pb = PathBuf::from(dir).join(submodule_data); 98 | if pb.is_dir() { 99 | Ok(pb) 100 | } else { 101 | Err(DataFusionError::External( 102 | format!( 103 | "the pre-defined data dir `{}` not found\n\ 104 | HINT: try running `git submodule update --init`", 105 | pb.display(), 106 | ) 107 | .into(), 108 | )) 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /hdfs/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | [package] 19 | name = "datafusion-objectstore-hdfs" 20 | version = "0.1.4" 21 | edition = "2021" 22 | 23 | description = "A hdfs object store implemented the object store" 24 | authors = ["Yanghong Zhong "] 25 | license = "Apache-2.0" 26 | readme = "../README.md" 27 | keywords = [ 28 | "hadoop", 29 | "hdfs", 30 | "hdfs3", 31 | "store", 32 | ] 33 | repository = "https://github.com/datafusion-contrib/datafusion-objectstore-hdfs" 34 | 35 | [features] 36 | default = ["hdfs", "try_spawn_blocking"] 37 | hdfs = ["fs-hdfs"] 38 | hdfs3 = ["fs-hdfs3"] 39 | # Used for trying to spawn a blocking thread for implementing each object store interface when running in a tokio runtime 40 | try_spawn_blocking = [] 41 | 42 | [dependencies] 43 | async-trait = "0.1.53" 44 | bytes = "1.0" 45 | chrono = { version = "0.4" } 46 | fs-hdfs = { version = "^0.1.12", optional = true } 47 | fs-hdfs3 = { version = "^0.1.12", optional = true } 48 | futures = "0.3" 49 | object_store = "0.8.0" 50 | tokio = { version = "1.18", features = ["macros", "rt", "rt-multi-thread", "sync", "parking_lot"] } 51 | -------------------------------------------------------------------------------- /hdfs/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Licensed to the Apache Software Foundation (ASF) under one 2 | // or more contributor license agreements. See the NOTICE file 3 | // distributed with this work for additional information 4 | // regarding copyright ownership. The ASF licenses this file 5 | // to you under the Apache License, Version 2.0 (the 6 | // "License"); you may not use this file except in compliance 7 | // with the License. You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, 12 | // software distributed under the License is distributed on an 13 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | // KIND, either express or implied. See the License for the 15 | // specific language governing permissions and limitations 16 | // under the License. 17 | 18 | //! HDFS as a remote ObjectStore for [Datafusion](https://github.com/apache/arrow-datafusion). 19 | //! 20 | //! This crate introduces ``HadoopFileSystem`` as a remote ObjectStore which provides the ability of querying on HDFS files. 21 | //! 22 | //! For the HDFS access, We leverage the library [fs-hdfs](https://github.com/datafusion-contrib/fs-hdfs). 23 | //! Basically, the library only provides Rust FFI APIs for the ``libhdfs`` which can be compiled by a set of C files provided by the [official Hadoop Community](https://github.com/apache/hadoop). 24 | pub mod object_store; 25 | -------------------------------------------------------------------------------- /hdfs/src/object_store/hdfs.rs: -------------------------------------------------------------------------------- 1 | // Licensed to the Apache Software Foundation (ASF) under one 2 | // or more contributor license agreements. See the NOTICE file 3 | // distributed with this work for additional information 4 | // regarding copyright ownership. The ASF licenses this file 5 | // to you under the Apache License, Version 2.0 (the 6 | // "License"); you may not use this file except in compliance 7 | // with the License. You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, 12 | // software distributed under the License is distributed on an 13 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | // KIND, either express or implied. See the License for the 15 | // specific language governing permissions and limitations 16 | // under the License. 17 | 18 | //! Object store that represents the HDFS File System. 19 | 20 | use std::collections::{BTreeSet, VecDeque}; 21 | use std::fmt::{Display, Formatter}; 22 | use std::ops::Range; 23 | use std::path::PathBuf; 24 | use std::sync::Arc; 25 | 26 | use async_trait::async_trait; 27 | use bytes::Bytes; 28 | use chrono::{DateTime, NaiveDateTime, Utc}; 29 | use futures::{stream::BoxStream, StreamExt, TryStreamExt}; 30 | use hdfs::hdfs::{get_hdfs_by_full_path, FileStatus, HdfsErr, HdfsFile, HdfsFs}; 31 | use hdfs::walkdir::HdfsWalkDir; 32 | use object_store::{ 33 | path::{self, Path}, 34 | Error, GetOptions, GetResult, GetResultPayload, ListResult, MultipartId, ObjectMeta, 35 | ObjectStore, PutOptions, PutResult, Result, 36 | }; 37 | use tokio::io::AsyncWrite; 38 | 39 | /// scheme for HDFS File System 40 | pub static HDFS_SCHEME: &str = "hdfs"; 41 | /// scheme for HDFS Federation File System 42 | pub static VIEWFS_SCHEME: &str = "viewfs"; 43 | 44 | #[derive(Debug)] 45 | /// Hadoop File System as Object Store. 46 | pub struct HadoopFileSystem { 47 | hdfs: Arc, 48 | } 49 | 50 | impl Default for HadoopFileSystem { 51 | fn default() -> Self { 52 | Self { 53 | hdfs: get_hdfs_by_full_path("default").expect("Fail to get default HdfsFs"), 54 | } 55 | } 56 | } 57 | 58 | impl HadoopFileSystem { 59 | /// Get HDFS from the full path, like hdfs://localhost:8020/xxx/xxx 60 | pub fn new(full_path: &str) -> Option { 61 | get_hdfs_by_full_path(full_path) 62 | .map(|hdfs| Some(Self { hdfs })) 63 | .unwrap_or(None) 64 | } 65 | 66 | /// Return filesystem path of the given location 67 | fn path_to_filesystem(location: &Path) -> String { 68 | format!("/{}", location.as_ref()) 69 | } 70 | 71 | pub fn get_path_root(&self) -> String { 72 | self.hdfs.url().to_owned() 73 | } 74 | 75 | pub fn get_path(&self, full_path: &str) -> Path { 76 | get_path(full_path, self.hdfs.url()) 77 | } 78 | 79 | pub fn get_hdfs_host(&self) -> String { 80 | let hdfs_url = self.hdfs.url(); 81 | if hdfs_url.starts_with(HDFS_SCHEME) { 82 | hdfs_url[7..].to_owned() 83 | } else if hdfs_url.starts_with(VIEWFS_SCHEME) { 84 | hdfs_url[9..].to_owned() 85 | } else { 86 | "".to_owned() 87 | } 88 | } 89 | 90 | fn read_range(range: &Range, file: &HdfsFile) -> Result { 91 | let to_read = range.end - range.start; 92 | let mut buf = vec![0; to_read]; 93 | let read = file 94 | .read_with_pos(range.start as i64, buf.as_mut_slice()) 95 | .map_err(to_error)?; 96 | assert_eq!( 97 | to_read as i32, 98 | read, 99 | "Read path {} from {} with expected size {} and actual size {}", 100 | file.path(), 101 | range.start, 102 | to_read, 103 | read 104 | ); 105 | Ok(buf.into()) 106 | } 107 | } 108 | 109 | impl Display for HadoopFileSystem { 110 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 111 | write!(f, "HadoopFileSystem") 112 | } 113 | } 114 | 115 | #[async_trait] 116 | impl ObjectStore for HadoopFileSystem { 117 | // Current implementation is very simple due to missing configs, 118 | // like whether able to overwrite, whether able to create parent directories, etc 119 | async fn put(&self, location: &Path, bytes: Bytes) -> Result { 120 | let hdfs = self.hdfs.clone(); 121 | let location = HadoopFileSystem::path_to_filesystem(location); 122 | 123 | maybe_spawn_blocking(move || { 124 | let file = match hdfs.create_with_overwrite(&location, true) { 125 | Ok(f) => f, 126 | Err(e) => { 127 | return Err(to_error(e)); 128 | } 129 | }; 130 | 131 | file.write(bytes.as_ref()).map_err(to_error)?; 132 | 133 | file.close().map_err(to_error)?; 134 | 135 | Ok(()) 136 | }) 137 | .await?; 138 | return Ok(PutResult { 139 | e_tag: None, 140 | version: None, 141 | }); 142 | } 143 | 144 | async fn put_opts( 145 | &self, 146 | _location: &Path, 147 | _bytes: Bytes, 148 | _opts: PutOptions, 149 | ) -> Result { 150 | todo!() 151 | } 152 | 153 | async fn put_multipart( 154 | &self, 155 | _location: &Path, 156 | ) -> Result<(MultipartId, Box)> { 157 | todo!() 158 | } 159 | 160 | async fn abort_multipart(&self, _location: &Path, _multipart_id: &MultipartId) -> Result<()> { 161 | todo!() 162 | } 163 | 164 | async fn get(&self, location: &Path) -> Result { 165 | let hdfs = self.hdfs.clone(); 166 | let hdfs_root = self.hdfs.url().to_owned(); 167 | let location = HadoopFileSystem::path_to_filesystem(location); 168 | 169 | let (blob, object_metadata, range) = maybe_spawn_blocking(move || { 170 | let file = hdfs.open(&location).map_err(to_error)?; 171 | 172 | let file_status = file.get_file_status().map_err(to_error)?; 173 | 174 | let to_read = file_status.len(); 175 | let mut buf = vec![0; to_read]; 176 | let read = file.read(buf.as_mut_slice()).map_err(to_error)?; 177 | assert_eq!( 178 | to_read as i32, read, 179 | "Read path {} with expected size {} and actual size {}", 180 | &location, to_read, read 181 | ); 182 | 183 | file.close().map_err(to_error)?; 184 | 185 | let object_metadata = convert_metadata(file_status, &hdfs_root); 186 | 187 | let range = Range { 188 | start: 0, 189 | end: file_status.len(), 190 | }; 191 | 192 | Ok((buf.into(), object_metadata, range)) 193 | }) 194 | .await?; 195 | 196 | Ok(GetResult { 197 | payload: GetResultPayload::Stream( 198 | futures::stream::once(async move { Ok(blob) }).boxed(), 199 | ), 200 | meta: object_metadata, 201 | range, 202 | }) 203 | } 204 | 205 | async fn get_opts(&self, location: &Path, options: GetOptions) -> Result { 206 | if options.if_match.is_some() || options.if_none_match.is_some() { 207 | return Err(Error::Generic { 208 | store: "HadoopFileSystem", 209 | source: Box::new(HdfsErr::Generic("ETags not supported".to_string())), 210 | }); 211 | } 212 | 213 | let hdfs = self.hdfs.clone(); 214 | let hdfs_root = self.hdfs.url().to_owned(); 215 | let location = HadoopFileSystem::path_to_filesystem(location); 216 | 217 | let (blob, object_metadata, range) = maybe_spawn_blocking(move || { 218 | let file = hdfs.open(&location).map_err(to_error)?; 219 | 220 | let file_status = file.get_file_status().map_err(to_error)?; 221 | 222 | if options.if_unmodified_since.is_some() || options.if_modified_since.is_some() { 223 | check_modified(&options, &location, last_modified(&file_status))?; 224 | } 225 | 226 | let range = if let Some(range) = options.range { 227 | range 228 | } else { 229 | Range { 230 | start: 0, 231 | end: file_status.len(), 232 | } 233 | }; 234 | 235 | let buf = Self::read_range(&range, &file)?; 236 | 237 | file.close().map_err(to_error)?; 238 | 239 | let object_meta = convert_metadata(file_status, &hdfs_root); 240 | 241 | Ok((buf, object_meta, range)) 242 | }) 243 | .await?; 244 | 245 | Ok(GetResult { 246 | payload: GetResultPayload::Stream( 247 | futures::stream::once(async move { Ok(blob) }).boxed(), 248 | ), 249 | meta: object_metadata, 250 | range, 251 | }) 252 | } 253 | 254 | async fn get_range(&self, location: &Path, range: Range) -> Result { 255 | let hdfs = self.hdfs.clone(); 256 | let location = HadoopFileSystem::path_to_filesystem(location); 257 | 258 | maybe_spawn_blocking(move || { 259 | let file = hdfs.open(&location).map_err(to_error)?; 260 | let buf = Self::read_range(&range, &file)?; 261 | file.close().map_err(to_error)?; 262 | 263 | Ok(buf) 264 | }) 265 | .await 266 | } 267 | 268 | async fn get_ranges(&self, location: &Path, ranges: &[Range]) -> Result> { 269 | coalesce_ranges( 270 | ranges, 271 | |range| self.get_range(location, range), 272 | HDFS_COALESCE_DEFAULT, 273 | ) 274 | .await 275 | } 276 | 277 | async fn head(&self, location: &Path) -> Result { 278 | let hdfs = self.hdfs.clone(); 279 | let hdfs_root = self.hdfs.url().to_owned(); 280 | let location = HadoopFileSystem::path_to_filesystem(location); 281 | 282 | maybe_spawn_blocking(move || { 283 | let file_status = hdfs.get_file_status(&location).map_err(to_error)?; 284 | Ok(convert_metadata(file_status, &hdfs_root)) 285 | }) 286 | .await 287 | } 288 | 289 | async fn delete(&self, location: &Path) -> Result<()> { 290 | let hdfs = self.hdfs.clone(); 291 | let location = HadoopFileSystem::path_to_filesystem(location); 292 | 293 | maybe_spawn_blocking(move || { 294 | hdfs.delete(&location, false).map_err(to_error)?; 295 | 296 | Ok(()) 297 | }) 298 | .await 299 | } 300 | 301 | /// List all of the leaf files under the prefix path. 302 | /// It will recursively search leaf files whose depth is larger than 1 303 | fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result> { 304 | let default_path = Path::from(self.get_path_root()); 305 | let prefix = prefix.unwrap_or(&default_path); 306 | let hdfs = self.hdfs.clone(); 307 | let hdfs_root = self.hdfs.url().to_owned(); 308 | let walkdir = 309 | HdfsWalkDir::new_with_hdfs(HadoopFileSystem::path_to_filesystem(prefix), hdfs) 310 | .min_depth(1); 311 | 312 | let s = 313 | walkdir.into_iter().flat_map(move |result_dir_entry| { 314 | match convert_walkdir_result(result_dir_entry) { 315 | Err(e) => Some(Err(e)), 316 | Ok(None) => None, 317 | Ok(entry @ Some(_)) => entry 318 | .filter(|dir_entry| dir_entry.is_file()) 319 | .map(|entry| Ok(convert_metadata(entry, &hdfs_root))), 320 | } 321 | }); 322 | 323 | // If no tokio context, return iterator directly as no 324 | // need to perform chunked spawn_blocking reads 325 | if tokio::runtime::Handle::try_current().is_err() { 326 | return futures::stream::iter(s).boxed(); 327 | } 328 | 329 | // Otherwise list in batches of CHUNK_SIZE 330 | const CHUNK_SIZE: usize = 1024; 331 | 332 | let buffer = VecDeque::with_capacity(CHUNK_SIZE); 333 | let stream = futures::stream::try_unfold((s, buffer), |(mut s, mut buffer)| async move { 334 | if buffer.is_empty() { 335 | (s, buffer) = tokio::task::spawn_blocking(move || { 336 | for _ in 0..CHUNK_SIZE { 337 | match s.next() { 338 | Some(r) => buffer.push_back(r), 339 | None => break, 340 | } 341 | } 342 | (s, buffer) 343 | }) 344 | .await?; 345 | } 346 | 347 | match buffer.pop_front() { 348 | Some(Err(e)) => Err(e), 349 | Some(Ok(meta)) => Ok(Some((meta, (s, buffer)))), 350 | None => Ok(None), 351 | } 352 | }); 353 | 354 | stream.boxed() 355 | } 356 | 357 | /// List files and directories directly under the prefix path. 358 | /// It will not recursively search leaf files whose depth is larger than 1 359 | async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result { 360 | let default_path = Path::from(self.get_path_root()); 361 | let prefix = prefix.unwrap_or(&default_path); 362 | let hdfs = self.hdfs.clone(); 363 | let hdfs_root = self.hdfs.url().to_owned(); 364 | let walkdir = 365 | HdfsWalkDir::new_with_hdfs(HadoopFileSystem::path_to_filesystem(prefix), hdfs) 366 | .min_depth(1) 367 | .max_depth(1); 368 | 369 | let prefix = prefix.clone(); 370 | maybe_spawn_blocking(move || { 371 | let mut common_prefixes = BTreeSet::new(); 372 | let mut objects = Vec::new(); 373 | 374 | for entry_res in walkdir.into_iter().map(convert_walkdir_result) { 375 | if let Some(entry) = entry_res? { 376 | let is_directory = entry.is_directory(); 377 | let entry_location = get_path(entry.name(), &hdfs_root); 378 | 379 | let mut parts = match entry_location.prefix_match(&prefix) { 380 | Some(parts) => parts, 381 | None => continue, 382 | }; 383 | 384 | let common_prefix = match parts.next() { 385 | Some(p) => p, 386 | None => continue, 387 | }; 388 | 389 | drop(parts); 390 | 391 | if is_directory { 392 | common_prefixes.insert(prefix.child(common_prefix)); 393 | } else { 394 | objects.push(convert_metadata(entry, &hdfs_root)); 395 | } 396 | } 397 | } 398 | 399 | Ok(ListResult { 400 | common_prefixes: common_prefixes.into_iter().collect(), 401 | objects, 402 | }) 403 | }) 404 | .await 405 | } 406 | 407 | /// Copy an object from one path to another. 408 | /// If there exists an object at the destination, it will be overwritten. 409 | async fn copy(&self, from: &Path, to: &Path) -> Result<()> { 410 | let hdfs = self.hdfs.clone(); 411 | let from = HadoopFileSystem::path_to_filesystem(from); 412 | let to = HadoopFileSystem::path_to_filesystem(to); 413 | 414 | maybe_spawn_blocking(move || { 415 | // We need to make sure the source exist 416 | if !hdfs.exist(&from) { 417 | return Err(Error::NotFound { 418 | path: from.clone(), 419 | source: Box::new(HdfsErr::FileNotFound(from)), 420 | }); 421 | } 422 | // Delete destination if exists 423 | if hdfs.exist(&to) { 424 | hdfs.delete(&to, false).map_err(to_error)?; 425 | } 426 | 427 | hdfs::util::HdfsUtil::copy(hdfs.as_ref(), &from, hdfs.as_ref(), &to) 428 | .map_err(to_error)?; 429 | 430 | Ok(()) 431 | }) 432 | .await 433 | } 434 | 435 | /// It's only allowed for the same HDFS 436 | async fn rename(&self, from: &Path, to: &Path) -> Result<()> { 437 | let hdfs = self.hdfs.clone(); 438 | let from = HadoopFileSystem::path_to_filesystem(from); 439 | let to = HadoopFileSystem::path_to_filesystem(to); 440 | 441 | maybe_spawn_blocking(move || { 442 | hdfs.rename(&from, &to).map_err(to_error)?; 443 | 444 | Ok(()) 445 | }) 446 | .await 447 | } 448 | 449 | /// Copy an object from one path to another, only if destination is empty. 450 | /// Will return an error if the destination already has an object. 451 | async fn copy_if_not_exists(&self, from: &Path, to: &Path) -> Result<()> { 452 | let hdfs = self.hdfs.clone(); 453 | let from = HadoopFileSystem::path_to_filesystem(from); 454 | let to = HadoopFileSystem::path_to_filesystem(to); 455 | 456 | maybe_spawn_blocking(move || { 457 | if hdfs.exist(&to) { 458 | return Err(Error::AlreadyExists { 459 | path: from, 460 | source: Box::new(HdfsErr::FileAlreadyExists(to)), 461 | }); 462 | } 463 | 464 | hdfs::util::HdfsUtil::copy(hdfs.as_ref(), &from, hdfs.as_ref(), &to) 465 | .map_err(to_error)?; 466 | 467 | Ok(()) 468 | }) 469 | .await 470 | } 471 | } 472 | 473 | /// Create Path without prefix 474 | pub fn get_path(full_path: &str, prefix: &str) -> Path { 475 | let partial_path = &full_path[prefix.len()..]; 476 | Path::parse(partial_path).unwrap() 477 | } 478 | 479 | /// Convert HDFS file status to ObjectMeta 480 | pub fn convert_metadata(file: FileStatus, prefix: &str) -> ObjectMeta { 481 | ObjectMeta { 482 | location: get_path(file.name(), prefix), 483 | last_modified: last_modified(&file), 484 | size: file.len(), 485 | e_tag: None, 486 | version: None, 487 | } 488 | } 489 | 490 | fn last_modified(file: &FileStatus) -> DateTime { 491 | DateTime::::from_naive_utc_and_offset( 492 | NaiveDateTime::from_timestamp_opt(file.last_modified(), 0).unwrap(), 493 | Utc, 494 | ) 495 | } 496 | 497 | fn check_modified( 498 | get_options: &GetOptions, 499 | location: &str, 500 | last_modified: DateTime, 501 | ) -> Result<()> { 502 | if let Some(date) = get_options.if_modified_since { 503 | if last_modified <= date { 504 | return Err(Error::NotModified { 505 | path: location.to_string(), 506 | source: format!("{} >= {}", date, last_modified).into(), 507 | }); 508 | } 509 | } 510 | 511 | if let Some(date) = get_options.if_unmodified_since { 512 | if last_modified > date { 513 | return Err(Error::Precondition { 514 | path: location.to_string(), 515 | source: format!("{} < {}", date, last_modified).into(), 516 | }); 517 | } 518 | } 519 | Ok(()) 520 | } 521 | 522 | /// Convert walkdir results and converts not-found errors into `None`. 523 | fn convert_walkdir_result( 524 | res: std::result::Result, 525 | ) -> Result> { 526 | match res { 527 | Ok(entry) => Ok(Some(entry)), 528 | Err(walkdir_err) => match walkdir_err { 529 | HdfsErr::FileNotFound(_) => Ok(None), 530 | _ => Err(to_error(HdfsErr::Generic( 531 | "Fail to walk hdfs directory".to_owned(), 532 | ))), 533 | }, 534 | } 535 | } 536 | 537 | /// Range requests with a gap less than or equal to this, 538 | /// will be coalesced into a single request by [`coalesce_ranges`] 539 | pub const HDFS_COALESCE_DEFAULT: usize = 1024 * 1024; 540 | 541 | /// Up to this number of range requests will be performed in parallel by [`coalesce_ranges`] 542 | pub const OBJECT_STORE_COALESCE_PARALLEL: usize = 10; 543 | 544 | /// Takes a function to fetch ranges and coalesces adjacent ranges if they are 545 | /// less than `coalesce` bytes apart. 546 | pub async fn coalesce_ranges( 547 | ranges: &[Range], 548 | fetch: F, 549 | coalesce: usize, 550 | ) -> Result> 551 | where 552 | F: FnMut(Range) -> Fut, 553 | Fut: std::future::Future>, 554 | { 555 | let fetch_ranges = merge_ranges(ranges, coalesce); 556 | 557 | let fetched: Vec<_> = futures::stream::iter(fetch_ranges.iter().cloned()) 558 | .map(fetch) 559 | .buffered(OBJECT_STORE_COALESCE_PARALLEL) 560 | .try_collect() 561 | .await?; 562 | 563 | Ok(ranges 564 | .iter() 565 | .map(|range| { 566 | let idx = fetch_ranges.partition_point(|v| v.start <= range.start) - 1; 567 | let fetch_range = &fetch_ranges[idx]; 568 | let fetch_bytes = &fetched[idx]; 569 | 570 | let start = range.start - fetch_range.start; 571 | let end = range.end - fetch_range.start; 572 | fetch_bytes.slice(start..end) 573 | }) 574 | .collect()) 575 | } 576 | 577 | /// Takes a function and spawns it to a tokio blocking pool if available 578 | pub async fn maybe_spawn_blocking(f: F) -> Result 579 | where 580 | F: FnOnce() -> Result + Send + 'static, 581 | T: Send + 'static, 582 | { 583 | #[cfg(feature = "try_spawn_blocking")] 584 | match tokio::runtime::Handle::try_current() { 585 | Ok(runtime) => runtime.spawn_blocking(f).await?, 586 | Err(_) => f(), 587 | } 588 | 589 | #[cfg(not(feature = "try_spawn_blocking"))] 590 | f() 591 | } 592 | 593 | /// Returns a sorted list of ranges that cover `ranges` 594 | fn merge_ranges(ranges: &[Range], coalesce: usize) -> Vec> { 595 | if ranges.is_empty() { 596 | return vec![]; 597 | } 598 | 599 | let mut ranges = ranges.to_vec(); 600 | ranges.sort_unstable_by_key(|range| range.start); 601 | 602 | let mut ret = Vec::with_capacity(ranges.len()); 603 | let mut start_idx = 0; 604 | let mut end_idx = 1; 605 | 606 | while start_idx != ranges.len() { 607 | let mut range_end = ranges[start_idx].end; 608 | 609 | while end_idx != ranges.len() 610 | && ranges[end_idx] 611 | .start 612 | .checked_sub(range_end) 613 | .map(|delta| delta <= coalesce) 614 | .unwrap_or(true) 615 | { 616 | range_end = range_end.max(ranges[end_idx].end); 617 | end_idx += 1; 618 | } 619 | 620 | let start = ranges[start_idx].start; 621 | let end = range_end; 622 | ret.push(start..end); 623 | 624 | start_idx = end_idx; 625 | end_idx += 1; 626 | } 627 | 628 | ret 629 | } 630 | 631 | fn to_error(err: HdfsErr) -> Error { 632 | match err { 633 | HdfsErr::FileNotFound(path) => Error::NotFound { 634 | path: path.clone(), 635 | source: Box::new(HdfsErr::FileNotFound(path)), 636 | }, 637 | HdfsErr::FileAlreadyExists(path) => Error::AlreadyExists { 638 | path: path.clone(), 639 | source: Box::new(HdfsErr::FileAlreadyExists(path)), 640 | }, 641 | HdfsErr::InvalidUrl(path) => Error::InvalidPath { 642 | source: path::Error::InvalidPath { 643 | path: PathBuf::from(path), 644 | }, 645 | }, 646 | HdfsErr::CannotConnectToNameNode(namenode_uri) => Error::Generic { 647 | store: "HadoopFileSystem", 648 | source: Box::new(HdfsErr::CannotConnectToNameNode(namenode_uri)), 649 | }, 650 | HdfsErr::Generic(err_str) => Error::Generic { 651 | store: "HadoopFileSystem", 652 | source: Box::new(HdfsErr::Generic(err_str)), 653 | }, 654 | } 655 | } 656 | 657 | #[cfg(test)] 658 | mod tests { 659 | use super::*; 660 | use std::ops::Range; 661 | 662 | #[tokio::test] 663 | async fn test_coalesce_ranges() { 664 | let do_fetch = |ranges: Vec>, coalesce: usize| async move { 665 | let max = ranges.iter().map(|x| x.end).max().unwrap_or(0); 666 | let src: Vec<_> = (0..max).map(|x| x as u8).collect(); 667 | 668 | let mut fetches = vec![]; 669 | let coalesced = coalesce_ranges( 670 | &ranges, 671 | |range| { 672 | fetches.push(range.clone()); 673 | futures::future::ready(Ok(Bytes::from(src[range].to_vec()))) 674 | }, 675 | coalesce, 676 | ) 677 | .await 678 | .unwrap(); 679 | 680 | assert_eq!(ranges.len(), coalesced.len()); 681 | for (range, bytes) in ranges.iter().zip(coalesced) { 682 | assert_eq!(bytes.as_ref(), &src[range.clone()]); 683 | } 684 | fetches 685 | }; 686 | 687 | let fetches = do_fetch(vec![], 0).await; 688 | assert_eq!(fetches, vec![]); 689 | 690 | let fetches = do_fetch(vec![0..3], 0).await; 691 | assert_eq!(fetches, vec![0..3]); 692 | 693 | let fetches = do_fetch(vec![0..2, 3..5], 0).await; 694 | assert_eq!(fetches, vec![0..2, 3..5]); 695 | 696 | let fetches = do_fetch(vec![0..1, 1..2], 0).await; 697 | assert_eq!(fetches, vec![0..2]); 698 | 699 | let fetches = do_fetch(vec![0..1, 2..72], 1).await; 700 | assert_eq!(fetches, vec![0..72]); 701 | 702 | let fetches = do_fetch(vec![0..1, 56..72, 73..75], 1).await; 703 | assert_eq!(fetches, vec![0..1, 56..75]); 704 | 705 | let fetches = do_fetch(vec![0..1, 5..6, 7..9, 4..6], 1).await; 706 | assert_eq!(fetches, vec![0..1, 4..9]); 707 | } 708 | } 709 | -------------------------------------------------------------------------------- /hdfs/src/object_store/mod.rs: -------------------------------------------------------------------------------- 1 | // Licensed to the Apache Software Foundation (ASF) under one 2 | // or more contributor license agreements. See the NOTICE file 3 | // distributed with this work for additional information 4 | // regarding copyright ownership. The ASF licenses this file 5 | // to you under the Apache License, Version 2.0 (the 6 | // "License"); you may not use this file except in compliance 7 | // with the License. You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, 12 | // software distributed under the License is distributed on an 13 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | // KIND, either express or implied. See the License for the 15 | // specific language governing permissions and limitations 16 | // under the License. 17 | 18 | pub mod hdfs; 19 | --------------------------------------------------------------------------------