Skip to main content

object_store/
config.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[cfg(feature = "hdfs-object-store")]
16use std::collections::HashMap;
17use std::time::Duration;
18
19use common_base::readable_size::ReadableSize;
20use common_base::secrets::{ExposeSecret, SecretString};
21#[cfg(feature = "hdfs-object-store")]
22use opendal::services::HdfsNative;
23#[cfg(feature = "mysql-object-store")]
24use opendal::services::Mysql;
25use opendal::services::{Azblob, Gcs, Oss, S3};
26use serde::{Deserialize, Serialize};
27
28use crate::util;
29
30const DEFAULT_OBJECT_STORE_CACHE_SIZE: ReadableSize = ReadableSize::gb(5);
31
32/// Object storage config
33#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
34#[serde(tag = "type")]
35pub enum ObjectStoreConfig {
36    File(FileConfig),
37    S3(S3Config),
38    Oss(OssConfig),
39    Azblob(AzblobConfig),
40    Gcs(GcsConfig),
41    #[cfg(feature = "hdfs-object-store")]
42    Hdfs(HdfsConfig),
43    #[cfg(feature = "mysql-object-store")]
44    Mysql(MysqlConfig),
45}
46
47impl Default for ObjectStoreConfig {
48    fn default() -> Self {
49        ObjectStoreConfig::File(FileConfig {})
50    }
51}
52
53impl ObjectStoreConfig {
54    /// Returns the object storage type name, such as `S3`, `Oss` etc.
55    pub fn provider_name(&self) -> &'static str {
56        match self {
57            Self::File(_) => "File",
58            Self::S3(_) => "S3",
59            Self::Oss(_) => "Oss",
60            Self::Azblob(_) => "Azblob",
61            Self::Gcs(_) => "Gcs",
62            #[cfg(feature = "hdfs-object-store")]
63            Self::Hdfs(_) => "Hdfs",
64            #[cfg(feature = "mysql-object-store")]
65            Self::Mysql(_) => "Mysql",
66        }
67    }
68
69    /// Returns true when it's a remote object storage such as AWS s3 etc.
70    pub fn is_object_storage(&self) -> bool {
71        !matches!(self, Self::File(_))
72    }
73
74    /// Returns the object storage configuration name, return the provider name if it's empty.
75    pub fn config_name(&self) -> &str {
76        let name = match self {
77            // file storage doesn't support name
78            Self::File(_) => self.provider_name(),
79            Self::S3(s3) => &s3.name,
80            Self::Oss(oss) => &oss.name,
81            Self::Azblob(az) => &az.name,
82            Self::Gcs(gcs) => &gcs.name,
83            #[cfg(feature = "hdfs-object-store")]
84            Self::Hdfs(hdfs) => &hdfs.name,
85            #[cfg(feature = "mysql-object-store")]
86            Self::Mysql(mysql) => &mysql.name,
87        };
88
89        if name.trim().is_empty() {
90            return self.provider_name();
91        }
92
93        name
94    }
95
96    /// Returns the object storage cache configuration.
97    pub fn cache_config(&self) -> Option<&ObjectStorageCacheConfig> {
98        match self {
99            Self::File(_) => None,
100            Self::S3(s3) => Some(&s3.cache),
101            Self::Oss(oss) => Some(&oss.cache),
102            Self::Azblob(az) => Some(&az.cache),
103            Self::Gcs(gcs) => Some(&gcs.cache),
104            #[cfg(feature = "hdfs-object-store")]
105            Self::Hdfs(hdfs) => Some(&hdfs.cache),
106            #[cfg(feature = "mysql-object-store")]
107            Self::Mysql(mysql) => Some(&mysql.cache),
108        }
109    }
110
111    /// Returns the mutable object storage cache configuration.
112    pub fn cache_config_mut(&mut self) -> Option<&mut ObjectStorageCacheConfig> {
113        match self {
114            Self::File(_) => None,
115            Self::S3(s3) => Some(&mut s3.cache),
116            Self::Oss(oss) => Some(&mut oss.cache),
117            Self::Azblob(az) => Some(&mut az.cache),
118            Self::Gcs(gcs) => Some(&mut gcs.cache),
119            #[cfg(feature = "hdfs-object-store")]
120            Self::Hdfs(hdfs) => Some(&mut hdfs.cache),
121            #[cfg(feature = "mysql-object-store")]
122            Self::Mysql(mysql) => Some(&mut mysql.cache),
123        }
124    }
125}
126
127#[derive(Debug, Clone, Serialize, Default, Deserialize, Eq, PartialEq)]
128#[serde(default)]
129pub struct FileConfig {}
130
131#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
132#[serde(default)]
133pub struct S3Connection {
134    pub bucket: String,
135    pub root: String,
136    #[serde(skip_serializing)]
137    pub access_key_id: SecretString,
138    #[serde(skip_serializing)]
139    pub secret_access_key: SecretString,
140    pub endpoint: Option<String>,
141    pub region: Option<String>,
142    /// Enable virtual host style so that opendal will send API requests in virtual host style instead of path style.
143    /// By default, opendal will send API to https://s3.us-east-1.amazonaws.com/bucket_name
144    /// Enabled, opendal will send API to https://bucket_name.s3.us-east-1.amazonaws.com
145    pub enable_virtual_host_style: bool,
146    /// Disable EC2 metadata service.
147    /// By default, opendal will use EC2 metadata service to load credentials from the instance metadata,
148    /// when access key id and secret access key are not provided.
149    /// If enabled, opendal will *NOT* use EC2 metadata service.
150    pub disable_ec2_metadata: bool,
151}
152
153impl From<&S3Connection> for S3 {
154    fn from(connection: &S3Connection) -> Self {
155        let root = util::normalize_dir(&connection.root);
156
157        let mut builder = S3::default()
158            .root(&root)
159            .bucket(&connection.bucket)
160            .access_key_id(connection.access_key_id.expose_secret())
161            .secret_access_key(connection.secret_access_key.expose_secret());
162
163        if connection.disable_ec2_metadata {
164            builder = builder.disable_ec2_metadata();
165        }
166
167        if let Some(endpoint) = &connection.endpoint {
168            builder = builder.endpoint(endpoint);
169        }
170        if let Some(region) = &connection.region {
171            builder = builder.region(region);
172        }
173        if connection.enable_virtual_host_style {
174            builder = builder.enable_virtual_host_style();
175        }
176
177        builder
178    }
179}
180
181#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
182#[serde(default)]
183pub struct S3Config {
184    pub name: String,
185    #[serde(flatten)]
186    pub connection: S3Connection,
187    #[serde(flatten)]
188    pub cache: ObjectStorageCacheConfig,
189    pub http_client: HttpClientConfig,
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
193#[serde(default)]
194pub struct OssConnection {
195    pub bucket: String,
196    pub root: String,
197    #[serde(skip_serializing)]
198    pub access_key_id: SecretString,
199    #[serde(skip_serializing)]
200    pub access_key_secret: SecretString,
201    pub endpoint: String,
202}
203
204impl From<&OssConnection> for Oss {
205    fn from(connection: &OssConnection) -> Self {
206        let root = util::normalize_dir(&connection.root);
207        Oss::default()
208            .root(&root)
209            .bucket(&connection.bucket)
210            .endpoint(&connection.endpoint)
211            .access_key_id(connection.access_key_id.expose_secret())
212            .access_key_secret(connection.access_key_secret.expose_secret())
213    }
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
217#[serde(default)]
218pub struct OssConfig {
219    pub name: String,
220    #[serde(flatten)]
221    pub connection: OssConnection,
222    #[serde(flatten)]
223    pub cache: ObjectStorageCacheConfig,
224    pub http_client: HttpClientConfig,
225}
226
227#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
228#[serde(default)]
229pub struct AzblobConnection {
230    pub container: String,
231    pub root: String,
232    #[serde(skip_serializing)]
233    pub account_name: SecretString,
234    #[serde(skip_serializing)]
235    pub account_key: SecretString,
236    pub endpoint: String,
237    #[serde(skip_serializing)]
238    pub sas_token: Option<SecretString>,
239}
240
241impl From<&AzblobConnection> for Azblob {
242    fn from(connection: &AzblobConnection) -> Self {
243        let root = util::normalize_dir(&connection.root);
244        let mut builder = Azblob::default()
245            .root(&root)
246            .container(&connection.container)
247            .endpoint(&connection.endpoint)
248            .account_name(connection.account_name.expose_secret())
249            .account_key(connection.account_key.expose_secret());
250
251        if let Some(token) = &connection.sas_token {
252            builder = builder.sas_token(token.expose_secret());
253        };
254
255        builder
256    }
257}
258
259#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
260#[serde(default)]
261pub struct AzblobConfig {
262    pub name: String,
263    #[serde(flatten)]
264    pub connection: AzblobConnection,
265    #[serde(flatten)]
266    pub cache: ObjectStorageCacheConfig,
267    pub http_client: HttpClientConfig,
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
271#[serde(default)]
272pub struct GcsConnection {
273    pub root: String,
274    pub bucket: String,
275    pub scope: String,
276    #[serde(skip_serializing)]
277    pub credential_path: SecretString,
278    #[serde(skip_serializing)]
279    pub credential: SecretString,
280    pub endpoint: String,
281}
282
283#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
284#[serde(default)]
285pub struct GcsConfig {
286    pub name: String,
287    #[serde(flatten)]
288    pub connection: GcsConnection,
289    #[serde(flatten)]
290    pub cache: ObjectStorageCacheConfig,
291    pub http_client: HttpClientConfig,
292}
293
294impl From<&GcsConnection> for Gcs {
295    fn from(connection: &GcsConnection) -> Self {
296        let root = util::normalize_dir(&connection.root);
297        Gcs::default()
298            .root(&root)
299            .bucket(&connection.bucket)
300            .scope(&connection.scope)
301            .credential_path(connection.credential_path.expose_secret())
302            .credential(connection.credential.expose_secret())
303            .endpoint(&connection.endpoint)
304    }
305}
306
307/// Connection options for a Hadoop Distributed File System backend.
308#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
309#[serde(default)]
310#[cfg(feature = "hdfs-object-store")]
311pub struct HdfsConnection {
312    /// Working directory for all object-store operations.
313    pub root: String,
314    /// HDFS NameNode URI, for example `hdfs://127.0.0.1:9000`.
315    pub name_node: String,
316    /// Additional options passed to the native HDFS client.
317    pub options: HashMap<String, String>,
318}
319
320#[cfg(feature = "hdfs-object-store")]
321impl From<&HdfsConnection> for HdfsNative {
322    fn from(connection: &HdfsConnection) -> Self {
323        let root = util::normalize_dir(&connection.root);
324        HdfsNative::default()
325            .root(&root)
326            .name_node(&connection.name_node)
327            .options(connection.options.clone())
328    }
329}
330
331/// Hadoop Distributed File System object storage configuration.
332#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
333#[serde(default)]
334#[cfg(feature = "hdfs-object-store")]
335pub struct HdfsConfig {
336    pub name: String,
337    #[serde(flatten)]
338    pub connection: HdfsConnection,
339    #[serde(flatten)]
340    pub cache: ObjectStorageCacheConfig,
341}
342
343#[cfg(feature = "mysql-object-store")]
344#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
345#[serde(default)]
346pub struct MysqlConfig {
347    pub name: String,
348    pub root: String,
349    #[serde(skip_serializing)]
350    pub connection_string: SecretString,
351    pub table: Option<String>,
352    #[serde(flatten)]
353    pub cache: ObjectStorageCacheConfig,
354}
355
356#[cfg(feature = "mysql-object-store")]
357impl From<&MysqlConfig> for Mysql {
358    fn from(config: &MysqlConfig) -> Self {
359        let root = util::normalize_dir(&config.root);
360        let mut builder = Mysql::default()
361            .connection_string(config.connection_string.expose_secret())
362            .root(&root)
363            .key_field("key")
364            .value_field("value");
365
366        if let Some(table) = &config.table {
367            builder = builder.table(table);
368        } else {
369            builder = builder.table("greptime");
370        }
371
372        builder
373    }
374}
375
376/// The http client options to the storage.
377#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
378#[serde(default)]
379pub struct HttpClientConfig {
380    /// The maximum idle connection per host allowed in the pool.
381    pub(crate) pool_max_idle_per_host: u32,
382
383    /// The timeout for only the connect phase of a http client.
384    #[serde(with = "humantime_serde")]
385    pub(crate) connect_timeout: Duration,
386
387    /// The total request timeout, applied from when the request starts connecting until the response body has finished.
388    /// Also considered a total deadline.
389    #[serde(with = "humantime_serde")]
390    pub(crate) timeout: Duration,
391
392    /// The timeout for idle sockets being kept-alive.
393    #[serde(with = "humantime_serde")]
394    pub(crate) pool_idle_timeout: Duration,
395
396    /// Skip SSL certificate validation (insecure)
397    pub skip_ssl_validation: bool,
398}
399
400impl Default for HttpClientConfig {
401    fn default() -> Self {
402        Self {
403            pool_max_idle_per_host: 1024,
404            connect_timeout: Duration::from_secs(30),
405            timeout: Duration::from_secs(30),
406            pool_idle_timeout: Duration::from_secs(90),
407            skip_ssl_validation: false,
408        }
409    }
410}
411
412#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
413#[serde(default)]
414pub struct ObjectStorageCacheConfig {
415    /// Whether to enable read cache. If not set, the read cache will be enabled by default.
416    pub enable_read_cache: bool,
417    /// The local file cache directory
418    pub cache_path: String,
419    /// The cache capacity in bytes
420    pub cache_capacity: ReadableSize,
421}
422
423impl Default for ObjectStorageCacheConfig {
424    fn default() -> Self {
425        Self {
426            enable_read_cache: true,
427            // The cache directory is set to the value of data_home in the build_cache_layer process.
428            cache_path: String::default(),
429            cache_capacity: DEFAULT_OBJECT_STORE_CACHE_SIZE,
430        }
431    }
432}
433
434impl ObjectStorageCacheConfig {
435    /// Sanitize the `ObjectStorageCacheConfig` to ensure the config is valid.
436    pub fn sanitize(&mut self, data_home: &str) {
437        // If `cache_path` is unset, default to use `${data_home}` as the local read cache directory.
438        if self.cache_path.is_empty() {
439            self.cache_path = data_home.to_string();
440        }
441    }
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447    use crate::config::ObjectStoreConfig;
448
449    #[test]
450    fn test_azblob_sas_token_is_not_disclosed() {
451        let config: AzblobConnection =
452            toml::from_str("container = 'test'\nsas_token = 'sas-secret'").unwrap();
453        assert_eq!(
454            config.sas_token.as_ref().unwrap().expose_secret(),
455            "sas-secret"
456        );
457        let serialized = toml::to_string(&config).unwrap();
458        assert!(!serialized.contains("sas_token"));
459        assert!(!format!("{config:#?}").contains("sas-secret"));
460        assert!(serialized.contains("container = \"test\""));
461    }
462
463    #[test]
464    fn test_config_name() {
465        let object_store_config = ObjectStoreConfig::default();
466        assert_eq!("File", object_store_config.config_name());
467
468        let s3_config = ObjectStoreConfig::S3(S3Config::default());
469        assert_eq!("S3", s3_config.config_name());
470        assert_eq!("S3", s3_config.provider_name());
471
472        let s3_config = ObjectStoreConfig::S3(S3Config {
473            name: "test".to_string(),
474            ..Default::default()
475        });
476        assert_eq!("test", s3_config.config_name());
477        assert_eq!("S3", s3_config.provider_name());
478
479        #[cfg(feature = "hdfs-object-store")]
480        {
481            let hdfs_config = ObjectStoreConfig::Hdfs(HdfsConfig::default());
482            assert_eq!("Hdfs", hdfs_config.config_name());
483            assert_eq!("Hdfs", hdfs_config.provider_name());
484
485            let hdfs_config = ObjectStoreConfig::Hdfs(HdfsConfig {
486                name: "test".to_string(),
487                ..Default::default()
488            });
489            assert_eq!("test", hdfs_config.config_name());
490            assert_eq!("Hdfs", hdfs_config.provider_name());
491        }
492
493        #[cfg(feature = "mysql-object-store")]
494        {
495            let mysql_config = ObjectStoreConfig::Mysql(MysqlConfig::default());
496            assert_eq!("Mysql", mysql_config.config_name());
497            assert_eq!("Mysql", mysql_config.provider_name());
498
499            let mysql_config = ObjectStoreConfig::Mysql(MysqlConfig {
500                name: "test".to_string(),
501                ..Default::default()
502            });
503            assert_eq!("test", mysql_config.config_name());
504            assert_eq!("Mysql", mysql_config.provider_name());
505        }
506    }
507
508    #[test]
509    fn test_is_object_storage() {
510        let store = ObjectStoreConfig::default();
511        assert!(!store.is_object_storage());
512        let s3_config = ObjectStoreConfig::S3(S3Config::default());
513        assert!(s3_config.is_object_storage());
514        let oss_config = ObjectStoreConfig::Oss(OssConfig::default());
515        assert!(oss_config.is_object_storage());
516        let gcs_config = ObjectStoreConfig::Gcs(GcsConfig::default());
517        assert!(gcs_config.is_object_storage());
518        let azblob_config = ObjectStoreConfig::Azblob(AzblobConfig::default());
519        assert!(azblob_config.is_object_storage());
520        #[cfg(feature = "hdfs-object-store")]
521        {
522            let hdfs_config = ObjectStoreConfig::Hdfs(HdfsConfig::default());
523            assert!(hdfs_config.is_object_storage());
524        }
525        #[cfg(feature = "mysql-object-store")]
526        {
527            let mysql_config = ObjectStoreConfig::Mysql(MysqlConfig::default());
528            assert!(mysql_config.is_object_storage());
529        }
530    }
531
532    #[cfg(feature = "hdfs-object-store")]
533    #[test]
534    fn test_hdfs_config_serde() {
535        let config: ObjectStoreConfig = toml::from_str(
536            r#"
537type = "Hdfs"
538name = "hdfs-store"
539root = "/greptimedb"
540name_node = "hdfs://127.0.0.1:9000"
541
542[options]
543"dfs.client.block.write.replace-datanode-on-failure.enable" = "true"
544"#,
545        )
546        .unwrap();
547
548        let ObjectStoreConfig::Hdfs(hdfs_config) = config else {
549            unreachable!()
550        };
551
552        assert_eq!("hdfs-store", hdfs_config.name);
553        assert_eq!("/greptimedb", hdfs_config.connection.root);
554        assert_eq!("hdfs://127.0.0.1:9000", hdfs_config.connection.name_node);
555        assert_eq!(
556            Some(&"true".to_string()),
557            hdfs_config
558                .connection
559                .options
560                .get("dfs.client.block.write.replace-datanode-on-failure.enable")
561        );
562
563        let serialized = toml::to_string(&hdfs_config).unwrap();
564        assert!(serialized.contains("name_node = \"hdfs://127.0.0.1:9000\""));
565        assert!(
566            serialized.contains(
567                "\"dfs.client.block.write.replace-datanode-on-failure.enable\" = \"true\""
568            )
569        );
570    }
571
572    #[cfg(feature = "mysql-object-store")]
573    #[test]
574    fn test_mysql_config_connection_string_serde() {
575        let config: ObjectStoreConfig = toml::from_str(
576            r#"
577type = "Mysql"
578name = "mysql-store"
579root = "/greptimedb"
580connection_string = "mysql://user:password@127.0.0.1:3306/greptime"
581table = "object_store"
582"#,
583        )
584        .unwrap();
585
586        let ObjectStoreConfig::Mysql(mysql_config) = config else {
587            unreachable!()
588        };
589
590        assert_eq!("mysql-store", mysql_config.name);
591        assert_eq!("/greptimedb", mysql_config.root);
592        assert_eq!(
593            "mysql://user:password@127.0.0.1:3306/greptime",
594            mysql_config.connection_string.expose_secret()
595        );
596        assert_eq!(Some("object_store"), mysql_config.table.as_deref());
597
598        let serialized = toml::to_string(&mysql_config).unwrap();
599        assert!(!serialized.contains("connection_string"));
600        assert!(!serialized.contains("password"));
601    }
602}