Skip to main content

opendal_service_hdfs_native/
config.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
18use std::collections::HashMap;
19use std::fmt::Debug;
20
21use serde::Deserialize;
22use serde::Serialize;
23
24use super::backend::HdfsNativeBuilder;
25
26pub const HDFS_SCHEME_PREFIX: &str = "hdfs://";
27pub const HDFS_DEFAULT_AUTHORITY: &str = "nameservice";
28pub const HA_NAMENODES_PREFIX: &str = "dfs.ha.namenodes";
29pub const HA_NAMENODE_RPC_ADDRESS_PREFIX: &str = "dfs.namenode.rpc-address";
30
31/// Config for HdfsNative services support.
32#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
33#[serde(default)]
34#[non_exhaustive]
35pub struct HdfsNativeConfig {
36    /// work dir of this backend
37    pub root: Option<String>,
38    /// name_node of this backend
39    pub name_node: Option<String>,
40    /// Deprecated: HDFS Native append capability is enabled by default.
41    #[deprecated(
42        since = "0.57.0",
43        note = "HDFS Native append capability is enabled by default and this option is no longer needed."
44    )]
45    pub enable_append: bool,
46    /// other options for hdfs client
47    pub options: Option<HashMap<String, String>>,
48}
49
50impl Debug for HdfsNativeConfig {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("HdfsNativeConfig")
53            .field("root", &self.root)
54            .field("name_node", &self.name_node)
55            .field("options", &self.options)
56            .finish_non_exhaustive()
57    }
58}
59
60impl opendal_core::Configurator for HdfsNativeConfig {
61    type Builder = HdfsNativeBuilder;
62
63    fn from_uri(uri: &opendal_core::OperatorUri) -> opendal_core::Result<Self> {
64        let mut map = uri.options().clone();
65        if let Some(authority) = uri.authority() {
66            map.insert("name_node".to_string(), format!("hdfs://{authority}"));
67        }
68
69        if let Some(root) = uri.root()
70            && !root.is_empty()
71        {
72            map.insert("root".to_string(), root.to_string());
73        }
74
75        Self::from_iter(map)
76    }
77
78    #[allow(deprecated)]
79    fn into_builder(self) -> Self::Builder {
80        HdfsNativeBuilder { config: self }
81    }
82}
83
84pub fn init_hdfs_config(name_node_uri: &str) -> HashMap<String, String> {
85    let namenodes = name_node_uri
86        .split(",")
87        .filter_map(|s| {
88            if !s.is_empty() {
89                Some(s.trim_start_matches("hdfs://").trim_end_matches("/"))
90            } else {
91                None
92            }
93        })
94        .collect::<Vec<&str>>();
95    let mut hdfs_config = HashMap::new();
96    let mut ha_config_namenodes_vec = Vec::new();
97    for (index, namenode) in namenodes.iter().enumerate() {
98        hdfs_config.insert(
99            format!(
100                "{}.{}.nn{}",
101                HA_NAMENODE_RPC_ADDRESS_PREFIX, HDFS_DEFAULT_AUTHORITY, index
102            ),
103            namenode.to_string(),
104        );
105        ha_config_namenodes_vec.push(format!("nn{}", index));
106    }
107    hdfs_config.insert(
108        format!("{}.{}", HA_NAMENODES_PREFIX, HDFS_DEFAULT_AUTHORITY),
109        ha_config_namenodes_vec.join(","),
110    );
111    hdfs_config
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117    use opendal_core::Configurator;
118    use opendal_core::OperatorUri;
119
120    #[test]
121    fn from_uri_sets_name_node_and_root() {
122        let uri = OperatorUri::new(
123            "hdfs-native://namenode:9000/user/project",
124            Vec::<(String, String)>::new(),
125        )
126        .unwrap();
127
128        let cfg = HdfsNativeConfig::from_uri(&uri).unwrap();
129        assert_eq!(cfg.name_node.as_deref(), Some("hdfs://namenode:9000"));
130        assert_eq!(cfg.root.as_deref(), Some("user/project"));
131    }
132
133    #[test]
134    fn from_uri_allows_missing_authority() {
135        let uri = OperatorUri::new("hdfs-native", Vec::<(String, String)>::new()).unwrap();
136
137        let cfg = HdfsNativeConfig::from_uri(&uri).unwrap();
138        assert!(cfg.name_node.is_none());
139    }
140
141    #[test]
142    fn init_hdfs_config_from_single_namenode() {
143        let hdfs_config = init_hdfs_config("hdfs://namenode1:9000/");
144        println!("{:?}", hdfs_config);
145        assert!(!hdfs_config.is_empty() && hdfs_config.len() == 2);
146        assert_eq!(
147            hdfs_config.get("dfs.ha.namenodes.nameservice"),
148            Some(&"nn0".to_string())
149        );
150        assert_eq!(
151            hdfs_config.get("dfs.namenode.rpc-address.nameservice.nn0"),
152            Some(&"namenode1:9000".to_string())
153        );
154    }
155
156    #[test]
157    fn init_hdfs_config_from_multi_namenodes() {
158        let hdfs_config = init_hdfs_config("hdfs://namenode1:9000,namenode2:9000/");
159        println!("{:?}", hdfs_config);
160        assert!(!hdfs_config.is_empty() && hdfs_config.len() == 3);
161        assert_eq!(
162            hdfs_config.get("dfs.ha.namenodes.nameservice"),
163            Some(&"nn0,nn1".to_string())
164        );
165        assert_eq!(
166            hdfs_config.get("dfs.namenode.rpc-address.nameservice.nn0"),
167            Some(&"namenode1:9000".to_string())
168        );
169        assert_eq!(
170            hdfs_config.get("dfs.namenode.rpc-address.nameservice.nn1"),
171            Some(&"namenode2:9000".to_string())
172        );
173    }
174}