diff --git a/config/config.md b/config/config.md index 8f8bddf3c0e..cda48c547d8 100644 --- a/config/config.md +++ b/config/config.md @@ -512,6 +512,7 @@ | `datanode.client.max_send_message_size` | String | `512MB` | The maximum send message size for the gRPC client. | | `wal` | -- | -- | -- | | `wal.provider` | String | `raft_engine` | -- | +| `wal.prefix` | String | `wal` | Public root prefix for `experimental_object_store` WAL (enterprise builds only).
The distributed WAL enablement plugin is also required. Metasrv only reads
this prefix; it can use the same WAL configuration as the datanodes.
All datanodes must configure the same prefix and shared object storage. | | `wal.broker_endpoints` | Array | -- | The broker endpoints of the Kafka cluster.

**It's only used when the provider is `kafka`**. | | `wal.connect_timeout` | String | `3s` | The connect timeout for kafka client.
**It's only used when the provider is `kafka`**. | | `wal.timeout` | String | `5s` | The total request timeout for kafka client.
**It's only used when the provider is `kafka`**. | @@ -622,7 +623,7 @@ | `wal.consumer_wait_timeout` | String | `100ms` | The consumer wait timeout.
**It's only used when the provider is `kafka`**. | | `wal.overwrite_entry_start_id` | Bool | `false` | Ignore missing entries during read WAL.
**It's only used when the provider is `kafka`**.

This option ensures that when Kafka messages are deleted, the system
can still successfully replay memtable data without throwing an
out-of-range error.
However, enabling this option might lead to unexpected data loss,
as the system will skip over missing entries instead of treating
them as critical errors. | | `wal.storage_provider` | String | `""` | The name of the storage provider that holds the WAL objects, an empty name selects the default object store.
**It's only used when the provider is `experimental_object_store`**. | -| `wal.prefix` | String | `wal` | The path prefix of the WAL objects inside the storage provider.
The objects are written under `/datanodes//epochs/`, which is derived from this prefix.
**It's only used when the provider is `experimental_object_store`**. | +| `wal.prefix` | String | `wal` | The path prefix of the WAL objects inside the storage provider.
In distributed mode, metasrv and all datanodes must use the same public root prefix and shared object storage.
A mismatched prefix prevents regions from opening; do not configure per-node root prefixes.
The objects are written under `/datanodes//epochs/`, which is derived from this prefix.
**It's only used when the provider is `experimental_object_store`**. | | `wal.flush_interval` | String | `100ms` | The interval of flushing buffered entries to the object store, at least `10ms`, defaults to `100ms`.
Each non-empty timer-triggered flush creates one object, and a batch that reaches `max_batch_bytes` is flushed immediately, so the batch seals on size only when the admitted bytes reach `max_batch_bytes` before the next timer tick; otherwise it seals on the timer, whatever the load.
When writes are sparse, a shorter interval lowers the acknowledgement latency of `durable` appends and raises the number of object requests: timer-triggered sealing creates at most one object per interval per node, and in `enqueued` mode the backlog thresholds can seal earlier. An `enqueued` append does not wait for its batch to seal once it is admitted, but the backlog thresholds can delay admission.
**It's only used when the provider is `experimental_object_store`**. | | `wal.ack_mode` | String | `durable` | When an append to the object store WAL returns.
- `durable`: an append returns after the object holding its entries is durable (the default).
- `enqueued`: an append returns once its entries are admitted and their ids are assigned, and the object is created in the background. A crash loses the unpersisted backlog.
**It's only used when the provider is `experimental_object_store`**. | | `wal.max_unpersisted_bytes` | String | `64MB` | The size of the unpersisted backlog at which new appends stall until an upload completes, in `enqueued` mode.
Nothing is dropped and nothing is rejected; the threshold does not bound what a crash during an outage can lose.
**It's only used when the provider is `experimental_object_store` and `ack_mode` is `enqueued`**. | diff --git a/config/datanode.example.toml b/config/datanode.example.toml index 8ac0308cd1c..28275c40f4a 100644 --- a/config/datanode.example.toml +++ b/config/datanode.example.toml @@ -227,6 +227,8 @@ overwrite_entry_start_id = false #+ storage_provider = "" ## The path prefix of the WAL objects inside the storage provider. +## In distributed mode, metasrv and all datanodes must use the same public root prefix and shared object storage. +## A mismatched prefix prevents regions from opening; do not configure per-node root prefixes. ## The objects are written under `/datanodes//epochs/`, which is derived from this prefix. ## **It's only used when the provider is `experimental_object_store`**. #+ prefix = "wal" diff --git a/config/metasrv.example.toml b/config/metasrv.example.toml index 35ba3ae0a98..0d3076640fe 100644 --- a/config/metasrv.example.toml +++ b/config/metasrv.example.toml @@ -231,8 +231,15 @@ max_send_message_size = "512MB" # Available wal providers: # - `raft_engine` (default): there're none raft-engine wal config since metasrv only involves in remote wal currently. # - `kafka`: metasrv **have to be** configured with kafka wal config when using kafka wal provider in datanode. +# - `experimental_object_store`: enterprise-only; requires the distributed WAL enablement plugin. provider = "raft_engine" +## Public root prefix for `experimental_object_store` WAL (enterprise builds only). +## The distributed WAL enablement plugin is also required. Metasrv only reads +## this prefix; it can use the same WAL configuration as the datanodes. +## All datanodes must configure the same prefix and shared object storage. +#+ prefix = "wal" + ## The broker endpoints of the Kafka cluster. ## ## **It's only used when the provider is `kafka`**. diff --git a/src/cmd/tests/load_config_test.rs b/src/cmd/tests/load_config_test.rs index 4f2a68ba988..639a6af0d73 100644 --- a/src/cmd/tests/load_config_test.rs +++ b/src/cmd/tests/load_config_test.rs @@ -591,7 +591,12 @@ where /// /// `variants` lists tagged sections, e.g. `("wal", "provider", ["kafka"])`, /// whose options only deserialize under a specific tag value. -fn check_example_defaults(name: &str, variants: &[(&str, &str, &[&str])]) -> Vec +/// `enterprise_options` lists fields unavailable in OSS builds of this component. +fn check_example_defaults( + name: &str, + variants: &[(&str, &str, &[&str])], + enterprise_options: &[&str], +) -> Vec where T: Configurable + serde::Serialize, { @@ -635,7 +640,8 @@ where let mut full_leaves = Vec::new(); leaf_values(&full, "", &mut full_leaves); for (path, _) in full_leaves { - if SKIP_SERIALIZING.contains(&path.as_str()) + if (!cfg!(feature = "enterprise") && enterprise_options.contains(&path.as_str())) + || SKIP_SERIALIZING.contains(&path.as_str()) || (path == "tracing.tokio_console_addr" && !cfg!(feature = "tokio-console")) { continue; @@ -668,7 +674,9 @@ where let mut documented_leaves = Vec::new(); leaf_values(&documented, "", &mut documented_leaves); for (path, documented_value) in documented_leaves { - if SKIP_SERIALIZING.contains(&path.as_str()) { + if (!cfg!(feature = "enterprise") && enterprise_options.contains(&path.as_str())) + || SKIP_SERIALIZING.contains(&path.as_str()) + { continue; } if let Some((_, resolved)) = resolved_at_runtime.iter().find(|(p, _)| *p == path) { @@ -717,23 +725,38 @@ fn test_example_configs_document_actual_defaults() { const STORAGE: (&str, &str, &[&str]) = ("storage", "type", &["S3", "Oss", "Azblob", "Gcs", "Hdfs"]); - let mut errors = - check_example_defaults::("standalone.example.toml", &[WAL, STORAGE]); + let mut errors = check_example_defaults::( + "standalone.example.toml", + &[WAL, STORAGE], + &[], + ); errors.extend(check_example_defaults::( "frontend.example.toml", &[], + &[], )); errors.extend(check_example_defaults::( "datanode.example.toml", &[WAL, STORAGE], + &[], )); errors.extend(check_example_defaults::( "metasrv.example.toml", - &[("wal", "provider", &["kafka"])], + &[( + "wal", + "provider", + &[ + "kafka", + #[cfg(feature = "enterprise")] + "experimental_object_store", + ], + )], + &["wal.prefix"], )); errors.extend(check_example_defaults::( "flownode.example.toml", &[], + &[], )); assert!(errors.is_empty(), "{}", errors.join("\n")); } diff --git a/src/common/meta/Cargo.toml b/src/common/meta/Cargo.toml index d235f6e9ad1..0c99d8d2c00 100644 --- a/src/common/meta/Cargo.toml +++ b/src/common/meta/Cargo.toml @@ -16,7 +16,7 @@ pg_kvbackend = [ "dep:rustls", ] mysql_kvbackend = ["dep:sqlx", "dep:rustls"] -enterprise = ["prost-types"] +enterprise = ["common-wal/enterprise", "prost-types"] [lints] workspace = true diff --git a/src/common/meta/src/error.rs b/src/common/meta/src/error.rs index 7dd7b9b0a62..f5ef827f311 100644 --- a/src/common/meta/src/error.rs +++ b/src/common/meta/src/error.rs @@ -979,6 +979,14 @@ pub enum Error { location: Location, }, + #[snafu(display("Invalid object store WAL prefix {:?}: {}", prefix, reason))] + InvalidObjectStoreWalPrefix { + prefix: String, + reason: &'static str, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("Invalid topic name prefix: {}", prefix))] InvalidTopicNamePrefix { prefix: String, @@ -1303,6 +1311,7 @@ impl ErrorExt for Error { | InvalidSetDatabaseOption { .. } | InvalidUnsetDatabaseOption { .. } | InvalidTopicNamePrefix { .. } + | InvalidObjectStoreWalPrefix { .. } | InvalidFileExtension { .. } | InvalidFileName { .. } | InvalidFlowRequestBody { .. } diff --git a/src/common/meta/src/wal_provider.rs b/src/common/meta/src/wal_provider.rs index 99fc3efd627..f51751923ac 100644 --- a/src/common/meta/src/wal_provider.rs +++ b/src/common/meta/src/wal_provider.rs @@ -30,6 +30,8 @@ use snafu::ensure; use store_api::storage::{RegionId, RegionNumber}; use crate::ddl::allocator::wal_options::WalOptionsAllocator; +#[cfg(feature = "enterprise")] +use crate::error::InvalidObjectStoreWalPrefixSnafu; use crate::error::{InvalidTopicNamePrefixSnafu, Result}; use crate::key::topic_name::TopicNameKey; use crate::key::{TOPIC_NAME_PATTERN_REGEX, TableMetadataManagerRef}; @@ -286,7 +288,10 @@ impl WalProvider { /// Returns true if it's the remote WAL. pub fn is_remote_wal(&self) -> bool { - matches!(&self, WalProvider::Kafka(_)) + matches!( + &self, + WalProvider::Kafka(_) | WalProvider::ObjectStore { .. } + ) } } @@ -312,6 +317,19 @@ pub async fn build_wal_provider( ) -> Result { match config { MetasrvWalConfig::RaftEngine => Ok(WalProvider::RaftEngine), + #[cfg(feature = "enterprise")] + MetasrvWalConfig::ObjectStore(config) => { + config.validate_prefix().map_err(|reason| { + InvalidObjectStoreWalPrefixSnafu { + prefix: &config.prefix, + reason, + } + .build() + })?; + Ok(WalProvider::ObjectStore { + prefix: config.prefix.clone(), + }) + } MetasrvWalConfig::Kafka(kafka_config) => { let prefix = &kafka_config.kafka_topic.topic_name_prefix; ensure!( @@ -543,6 +561,61 @@ mod tests { ); } + #[cfg(feature = "enterprise")] + #[tokio::test] + async fn test_build_object_store_provider() { + let config = + MetasrvWalConfig::ObjectStore(common_wal::config::object_store::ObjectStoreWalConfig { + prefix: "cluster/wal".to_string(), + // Metasrv only validates the prefix, not writer settings. + flush_interval: std::time::Duration::ZERO, + ..Default::default() + }); + let provider = build_wal_provider(&config, Arc::new(MemoryKvBackend::new())) + .await + .unwrap(); + assert!(provider.is_remote_wal()); + let options = provider.allocate(&[1, 2], false).await.unwrap(); + assert_eq!( + options, + HashMap::from([ + ( + 1, + WalOptions::ObjectStore(ObjectStoreWalOptions::new("cluster/wal".into())) + ), + ( + 2, + WalOptions::ObjectStore(ObjectStoreWalOptions::new("cluster/wal".into())) + ), + ]) + ); + assert!(remote_wal_topics(&options).is_empty()); + } + + #[cfg(feature = "enterprise")] + #[tokio::test] + async fn test_build_object_store_provider_rejects_invalid_prefix() { + use common_error::ext::ErrorExt; + use common_error::status_code::StatusCode; + use common_wal::config::object_store::ObjectStoreWalConfig; + + for prefix in [ + "", " ", "/wal", "wal/", "wal//a", "wal/../a", ".", "wal/./a", + ] { + let config = MetasrvWalConfig::ObjectStore(ObjectStoreWalConfig { + prefix: prefix.to_string(), + ..Default::default() + }); + let error = build_wal_provider(&config, Arc::new(MemoryKvBackend::new())) + .await + .unwrap_err(); + assert_eq!(StatusCode::InvalidArguments, error.status_code()); + assert!( + matches!(error, crate::error::Error::InvalidObjectStoreWalPrefix { prefix: actual, .. } if actual == prefix) + ); + } + } + #[tokio::test] async fn test_provider_with_object_store() { let provider = WalProvider::ObjectStore { diff --git a/src/common/wal/Cargo.toml b/src/common/wal/Cargo.toml index 62fdee79ae5..373ef80e185 100644 --- a/src/common/wal/Cargo.toml +++ b/src/common/wal/Cargo.toml @@ -5,6 +5,7 @@ edition.workspace = true license.workspace = true [features] +enterprise = [] testing = [] [lints] diff --git a/src/common/wal/src/config.rs b/src/common/wal/src/config.rs index 0d26085452c..e56cb21d9b4 100644 --- a/src/common/wal/src/config.rs +++ b/src/common/wal/src/config.rs @@ -38,6 +38,10 @@ pub enum MetasrvWalConfig { #[default] RaftEngine, Kafka(MetasrvKafkaConfig), + /// Distributed object store WAL; metasrv only uses the public prefix. + #[cfg(feature = "enterprise")] + #[serde(rename = "experimental_object_store")] + ObjectStore(ObjectStoreWalConfig), } #[allow(clippy::large_enum_variant)] @@ -87,6 +91,9 @@ impl TryFrom for MetasrvWalConfig { provider: "noop".to_string(), } .fail(), + #[cfg(feature = "enterprise")] + DatanodeWalConfig::ObjectStore(config) => Ok(Self::ObjectStore(config)), + #[cfg(not(feature = "enterprise"))] DatanodeWalConfig::ObjectStore(_) => UnsupportedWalProviderSnafu { provider: "experimental_object_store".to_string(), } @@ -100,6 +107,8 @@ impl MetasrvWalConfig { pub fn enable_active_wal_pruning(&self) -> bool { match self { MetasrvWalConfig::RaftEngine => false, + #[cfg(feature = "enterprise")] + MetasrvWalConfig::ObjectStore(_) => false, MetasrvWalConfig::Kafka(config) => config.auto_prune_interval > Duration::ZERO, } } @@ -108,6 +117,8 @@ impl MetasrvWalConfig { pub fn remote_wal_options(&self) -> Option<&MetasrvKafkaConfig> { match self { MetasrvWalConfig::RaftEngine => None, + #[cfg(feature = "enterprise")] + MetasrvWalConfig::ObjectStore(_) => None, MetasrvWalConfig::Kafka(config) => Some(config), } } @@ -117,6 +128,8 @@ impl From for DatanodeWalConfig { fn from(config: MetasrvWalConfig) -> Self { match config { MetasrvWalConfig::RaftEngine => Self::RaftEngine(RaftEngineConfig::default()), + #[cfg(feature = "enterprise")] + MetasrvWalConfig::ObjectStore(config) => Self::ObjectStore(config), MetasrvWalConfig::Kafka(config) => Self::Kafka(DatanodeKafkaConfig { connection: config.connection, kafka_topic: config.kafka_topic, @@ -141,6 +154,33 @@ mod tests { use crate::config::object_store::{AckMode, CorruptedSegmentAction}; use crate::config::{DatanodeKafkaConfig, MetasrvKafkaConfig}; + #[test] + fn test_metasrv_object_store_feature_gate() { + let input = r#"provider = "experimental_object_store" +prefix = "cluster/wal" +storage_provider = "s3" +max_batch_bytes = "4MB" +"#; + #[cfg(not(feature = "enterprise"))] + assert!(toml::from_str::(input).is_err()); + #[cfg(feature = "enterprise")] + { + let config: MetasrvWalConfig = toml::from_str(input).unwrap(); + let datanode: DatanodeWalConfig = toml::from_str(input).unwrap(); + assert_eq!( + MetasrvWalConfig::try_from(datanode.clone()).unwrap(), + config + ); + assert_eq!(DatanodeWalConfig::from(config.clone()), datanode); + assert!(!config.enable_active_wal_pruning()); + assert!(config.remote_wal_options().is_none()); + assert_eq!( + toml::from_str::(&toml::to_string(&config).unwrap()).unwrap(), + config + ); + } + } + #[test] fn test_toml_raft_engine() { // With none configs. @@ -299,6 +339,7 @@ mod tests { assert_eq!(config.max_unpersisted_age, Duration::from_secs(8)); assert_eq!(config.on_corrupted_segment, CorruptedSegmentAction::Skip); assert!(!config.accept_missing_history); + #[cfg(not(feature = "enterprise"))] assert!(matches!( MetasrvWalConfig::try_from(datanode_wal_config).unwrap_err(), Error::UnsupportedWalProvider { .. } diff --git a/src/common/wal/src/config/object_store.rs b/src/common/wal/src/config/object_store.rs index c41adadcb69..ea32d22e051 100644 --- a/src/common/wal/src/config/object_store.rs +++ b/src/common/wal/src/config/object_store.rs @@ -23,11 +23,11 @@ use serde::{Deserialize, Serialize}; /// both the heartbeat node epoch and the store epoch carried in object headers. pub const FIXED_DIRECTORY_GENERATION: u64 = 0; -/// Plugin marker allowing a metasrv-controlled datanode to use object-store WAL. +/// Plugin marker allowing metasrv and its datanodes to use object-store WAL. /// /// OSS does not register this marker. Cluster integration registers it only after -/// the distributed WAL prerequisites are available; it does not itself configure -/// metasrv or enable region failover. +/// the distributed WAL prerequisites, including handoff and takeover, are available. +/// It does not itself configure storage or implement region failover. #[derive(Debug, Clone, Copy)] pub struct EnableObjectStoreWal; @@ -65,6 +65,9 @@ pub struct ObjectStoreWalConfig { /// An empty name selects the default object store. pub storage_provider: String, /// Path prefix of the WAL objects inside the storage provider. + /// In distributed mode, metasrv and all datanodes must use the same public + /// root prefix and shared object storage. A mismatched prefix prevents regions + /// from opening. /// /// The store runs under a node prefix derived from it, see /// [`node_prefix`](Self::node_prefix). @@ -112,12 +115,40 @@ impl Default for ObjectStoreWalConfig { } impl ObjectStoreWalConfig { + /// Validates the public root prefix without changing its stored identity. + /// Other WAL settings are irrelevant to metasrv and validated by the datanode. + pub fn validate_prefix(&self) -> Result<(), &'static str> { + let prefix = self.prefix.trim(); + if prefix.is_empty() { + return Err("must not be empty"); + } + if prefix.starts_with('/') { + return Err("must be a relative path"); + } + if prefix + .split('/') + .any(|component| component.is_empty() || component == "..") + { + return Err("must not contain empty or `..` components"); + } + // The node suffix preserves trailing whitespace in the root's last component. + if self + .prefix + .trim_start() + .split('/') + .any(|component| component == ".") + { + return Err("must not contain `.` components"); + } + Ok(()) + } + /// Returns the prefix the store of `node_id` runs under in `generation`: /// `/datanodes//epochs/`. /// - /// Every place that names the store's prefix, whether to open the store or - /// to allocate the WAL options of a region, must derive it here so the - /// prefix a region persists matches the one its store runs under. + /// Writers and remote readers derive concrete node directories here. + /// Distributed region metadata retains the public root instead; standalone + /// WAL options retain this concrete prefix for compatibility. pub fn node_prefix(&self, node_id: u64, generation: u64) -> String { format!("{}/datanodes/{node_id}/epochs/{generation}", self.prefix) } @@ -127,6 +158,27 @@ impl ObjectStoreWalConfig { mod tests { use super::*; + #[test] + fn test_validate_prefix() { + for prefix in [ + "", " ", "/wal", "wal/", "wal//a", "wal/../a", ".", "wal/./a", + ] { + let config = ObjectStoreWalConfig { + prefix: prefix.to_string(), + ..Default::default() + }; + assert!(config.validate_prefix().is_err(), "{prefix:?}"); + } + for prefix in ["wal", "tenant/wal", " wal ", "wal/. ", ". "] { + let config = ObjectStoreWalConfig { + prefix: prefix.to_string(), + ..Default::default() + }; + assert_eq!(Ok(()), config.validate_prefix()); + assert_eq!(prefix, config.prefix); + } + } + #[test] fn test_node_prefix() { let config = ObjectStoreWalConfig::default(); diff --git a/src/common/wal/src/options/object_store.rs b/src/common/wal/src/options/object_store.rs index d41e18dd38a..5dd9a2f0620 100644 --- a/src/common/wal/src/options/object_store.rs +++ b/src/common/wal/src/options/object_store.rs @@ -17,10 +17,10 @@ use serde::{Deserialize, Serialize}; /// Object store wal options allocated to a region. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct ObjectStoreWalOptions { - /// Path prefix of the WAL objects the region belongs to. - /// - /// Persisted so that reopening the region can detect a prefix that differs - /// from the process configuration. + /// Public WAL root in distributed mode, unchanged when the region moves. + /// The local log store resolves it to its own node directory and rejects + /// roots that differ from its configuration. Standalone metadata may hold + /// the concrete node prefix, which remains accepted by that same store. pub prefix: String, } diff --git a/src/datanode/src/datanode.rs b/src/datanode/src/datanode.rs index f33188a8208..ca14f6cd823 100644 --- a/src/datanode/src/datanode.rs +++ b/src/datanode/src/datanode.rs @@ -1031,33 +1031,14 @@ fn validate_region_engine_config(configs: &[RegionEngineConfig]) -> Result<()> { /// Rejects an object store WAL config the log store cannot run on. fn validate_object_store_wal_config(config: &ObjectStoreWalConfig) -> Result<()> { - let prefix = config.prefix.trim(); - ensure!( - !prefix.is_empty(), + config.validate_prefix().map_err(|reason| { InvalidObjectStoreWalConfigSnafu { field: "prefix", value: &config.prefix, - reason: "must not be empty", + reason, } - ); - ensure!( - !prefix.starts_with('/'), - InvalidObjectStoreWalConfigSnafu { - field: "prefix", - value: &config.prefix, - reason: "must be a relative path", - } - ); - ensure!( - !prefix - .split('/') - .any(|component| component.is_empty() || component == ".."), - InvalidObjectStoreWalConfigSnafu { - field: "prefix", - value: &config.prefix, - reason: "must not contain empty or `..` components", - } - ); + .build() + })?; ensure!( config.flush_interval >= Duration::from_millis(10), InvalidObjectStoreWalConfigSnafu { @@ -1498,6 +1479,13 @@ mod tests { }, "prefix", ), + ( + ObjectStoreWalConfig { + prefix: "wal/./objects".to_string(), + ..Default::default() + }, + "prefix", + ), ( ObjectStoreWalConfig { flush_interval: Duration::from_millis(9), diff --git a/src/log-store/src/object_store_wal/store.rs b/src/log-store/src/object_store_wal/store.rs index 7d58a8e2ba9..64836d4df6d 100644 --- a/src/log-store/src/object_store_wal/store.rs +++ b/src/log-store/src/object_store_wal/store.rs @@ -915,6 +915,31 @@ impl ObjectStoreLogStore { impl LogStore for ObjectStoreLogStore { type Error = Error; + fn resolve_provider(&self, provider: Provider) -> Result { + // Noop is a per-region opt-out, including on object store WAL nodes. + if matches!(provider, Provider::Noop) { + return Ok(provider); + } + let options = + provider + .as_object_store_provider() + .with_context(|| InvalidProviderSnafu { + expected: ObjectStoreProvider::type_name(), + actual: provider.type_name(), + })?; + ensure!( + options.prefix == self.config.prefix || options.prefix == self.prefix, + MismatchedWalPrefixSnafu { + expected: format!("{} or {}", self.config.prefix, self.prefix), + actual: options.prefix.clone(), + } + ); + Ok(Provider::object_store_provider( + options.region_id, + self.prefix.clone(), + )) + } + fn flush_candidates(&self) -> Vec { // A soft threshold: closed regions and recovery retention can still // pin objects. The engine decides which candidates it can flush. @@ -4346,6 +4371,42 @@ mod tests { } } + #[tokio::test] + async fn test_resolve_object_store_provider() { + let _guard = SERIALIZED.lock().await; + let storage = memory_store(); + let config = eager(); + let region_id = RegionId::new(1, 1); + for node_id in [1, 2] { + let store = ObjectStoreLogStore::try_new(storage.clone(), &config, node_id, 0) + .await + .unwrap(); + let expected = + Provider::object_store_provider(region_id, config.node_prefix(node_id, 0)); + let metadata_provider = + Provider::object_store_provider(region_id, config.prefix.clone()); + assert!(matches!( + store.latest_entry_id(&metadata_provider), + Err(Error::MismatchedWalPrefix { .. }) + )); + let resolved = store.resolve_provider(metadata_provider).unwrap(); + assert_eq!(resolved, expected); + assert_eq!(store.latest_entry_id(&resolved).unwrap(), 0); + assert_eq!(store.resolve_provider(expected.clone()).unwrap(), expected); + for prefix in ["other/wal".to_string(), config.node_prefix(3, 0)] { + assert!(matches!( + store.resolve_provider(Provider::object_store_provider(region_id, prefix)), + Err(Error::MismatchedWalPrefix { .. }) + )); + } + assert_eq!( + store.resolve_provider(Provider::noop_provider()).unwrap(), + Provider::noop_provider() + ); + store.stop().await.unwrap(); + } + } + #[tokio::test] async fn test_store_recovers_only_its_node_and_generation() { let _serialized = SERIALIZED.lock().await; diff --git a/src/meta-srv/src/metasrv/builder.rs b/src/meta-srv/src/metasrv/builder.rs index 44de98e7502..a27fd2cd353 100644 --- a/src/meta-srv/src/metasrv/builder.rs +++ b/src/meta-srv/src/metasrv/builder.rs @@ -46,11 +46,12 @@ use common_meta::region_registry::LeaderRegionRegistry; use common_meta::sequence::SequenceBuilder; use common_meta::state_store::KvStateStore; use common_meta::stats::topic::TopicStatsRegistry; -use common_meta::wal_provider::{build_kafka_client, build_wal_provider}; +use common_meta::wal_provider::{WalProvider, build_kafka_client, build_wal_provider}; use common_procedure::ProcedureManagerRef; use common_procedure::local::{LocalManager, ManagerConfig}; use common_stat::ResourceStatImpl; use common_telemetry::{info, warn}; +use common_wal::config::object_store::EnableObjectStoreWal; use snafu::{ResultExt, ensure}; use store_api::storage::MAX_REGION_SEQ; @@ -306,6 +307,18 @@ impl MetasrvBuilder { let wal_provider = build_wal_provider(&options.wal, kv_backend.clone()) .await .context(BuildWalProviderSnafu)?; + if matches!(wal_provider, WalProvider::ObjectStore { .. }) { + ensure!( + plugins + .as_ref() + .and_then(|plugins| plugins.get::()) + .is_some(), + error::InvalidArgumentsSnafu { + err_msg: "WAL provider `experimental_object_store` requires the `EnableObjectStoreWal` plugin", + } + ); + } + let wal_provider = Arc::new(wal_provider); let is_remote_wal = wal_provider.is_remote_wal(); let table_metadata_allocator = table_metadata_allocator.unwrap_or_else(|| { @@ -528,8 +541,8 @@ impl MetasrvBuilder { let ddl_manager = Arc::new(ddl_manager); - let region_flush_ticker = if is_remote_wal { - let remote_wal_options = options.wal.remote_wal_options().unwrap(); + let region_flush_ticker = if let Some(remote_wal_options) = options.wal.remote_wal_options() + { let (region_flush_trigger, region_flush_ticker) = RegionFlushTrigger::new( table_metadata_manager.clone(), leader_region_registry.clone(), @@ -548,11 +561,11 @@ impl MetasrvBuilder { None }; - // remote WAL prune ticker and manager - let wal_prune_ticker = if is_remote_wal && options.wal.enable_active_wal_pruning() { + // Kafka WAL prune ticker and manager. + let wal_prune_ticker = if let Some(remote_wal_options) = options.wal.remote_wal_options() + && options.wal.enable_active_wal_pruning() + { let (tx, rx) = WalPruneManager::channel(); - // Safety: Must be remote WAL. - let remote_wal_options = options.wal.remote_wal_options().unwrap(); let kafka_client = build_kafka_client(&remote_wal_options.connection) .await .context(error::BuildKafkaClientSnafu)?; @@ -783,6 +796,37 @@ pub struct DdlManagerConfigureContext { mod tests { use super::*; + #[cfg(feature = "enterprise")] + #[tokio::test] + async fn test_object_store_wal_requires_enablement() { + use common_wal::config::MetasrvWalConfig; + + let options = MetasrvOptions { + wal: MetasrvWalConfig::ObjectStore(Default::default()), + enable_region_failover: true, + enable_telemetry: false, + ..Default::default() + }; + let result = MetasrvBuilder::new().options(options.clone()).build().await; + assert!(matches!( + result, + Err(error::Error::InvalidArguments { err_msg, .. }) + if err_msg == "WAL provider `experimental_object_store` requires the `EnableObjectStoreWal` plugin" + )); + let plugins = Plugins::new(); + plugins.insert(EnableObjectStoreWal); + let metasrv = MetasrvBuilder::new() + .options(options) + .plugins(plugins) + .build() + .await + .unwrap(); + assert!(metasrv.wal_provider.is_remote_wal()); + assert!(metasrv.region_supervisor_ticker.is_some()); + assert!(metasrv.region_flush_ticker.is_none()); + assert!(metasrv.wal_prune_ticker.is_none()); + } + #[cfg(feature = "enterprise")] #[test] fn test_ddl_soft_drop_gate_preserves_retention_for_recovery() { diff --git a/src/mito2/src/engine/object_store_wal_test.rs b/src/mito2/src/engine/object_store_wal_test.rs index 4f6fe9090c1..2b64acaa389 100644 --- a/src/mito2/src/engine/object_store_wal_test.rs +++ b/src/mito2/src/engine/object_store_wal_test.rs @@ -217,6 +217,74 @@ async fn test_create_and_reopen_region_with_object_store_wal() { assert_eq!(3, count_rows(&engine, region_id).await); } +#[tokio::test] +async fn test_root_prefix_create_reopen_and_offline_cleanup() { + let mut env = TestEnv::with_prefix("object-store-wal-root-prefix").await; + let (engine, log_store) = new_engine(&mut env).await; + let region_id = RegionId::new(1, 1); + let provider = object_store_provider(region_id); + let options = HashMap::from([( + WAL_OPTIONS_KEY.to_string(), + serde_json::to_string(&WalOptions::ObjectStore(ObjectStoreWalOptions::new( + wal_config().prefix, + ))) + .unwrap(), + )]); + let request = CreateRequestBuilder::new() + .insert_option(WAL_OPTIONS_KEY, &options[WAL_OPTIONS_KEY]) + .build(); + let table_dir = request.table_dir.clone(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + assert_eq!(provider, engine.get_region(region_id).unwrap().provider); + put_rows( + &engine, + region_id, + Rows { + schema, + rows: build_rows(0, 3), + }, + ) + .await; + let last_entry_id = log_store.latest_entry_id(&provider).unwrap(); + + reopen_region(&engine, region_id, table_dir.clone(), true, options.clone()).await; + let region = engine.get_region(region_id).unwrap(); + assert_eq!(provider, region.provider); + assert_eq!( + last_entry_id, + region.version_control.current().last_entry_id + ); + assert_eq!(3, count_rows(&engine, region_id).await); + let object_store = region.access_layer.object_store().clone(); + let region_dir = region_dir_from_table_dir(&table_dir, region_id, PathType::Bare); + assert!(!object_store.list(®ion_dir).await.unwrap().is_empty()); + drop(region); + + close_region(&engine, region_id).await; + assert_eq!( + vec![last_entry_id], + stored_entry_ids(&log_store, region_id).await + ); + engine + .handle_request( + region_id, + RegionRequest::CleanUp(RegionCleanUpRequest { + engine: String::new(), + table_dir, + path_type: PathType::Bare, + options, + }), + ) + .await + .unwrap(); + assert!(stored_entry_ids(&log_store, region_id).await.is_empty()); + assert!(object_store.list(®ion_dir).await.unwrap().is_empty()); +} + #[tokio::test] async fn test_topic_latest_entry_id_follows_replay() { let mut env = TestEnv::with_prefix("object-store-wal-latest-entry-id").await; diff --git a/src/mito2/src/error.rs b/src/mito2/src/error.rs index 43853bb565c..79db4ad2a4e 100644 --- a/src/mito2/src/error.rs +++ b/src/mito2/src/error.rs @@ -558,6 +558,14 @@ pub enum Error { source: BoxedError, }, + #[snafu(display("Failed to resolve the WAL provider, region_id: {}", region_id))] + ResolveWalProvider { + region_id: RegionId, + #[snafu(implicit)] + location: Location, + source: BoxedError, + }, + // Shared error for each writer in the write group. #[snafu(display("Failed to write region"))] WriteGroup { source: Arc }, @@ -1671,6 +1679,7 @@ impl ErrorExt for Error { | ReadNodeWal { source, .. } | DeleteWal { source, .. } | WaitWalDurable { source, .. } + | ResolveWalProvider { source, .. } | CheckWalHistory { source, .. } => source.status_code(), CompressObject { .. } | DecompressObject { .. } @@ -1911,6 +1920,7 @@ impl ErrorExt for Error { | ReadNodeWal { source, .. } | DeleteWal { source, .. } | WaitWalDurable { source, .. } + | ResolveWalProvider { source, .. } | CheckWalHistory { source, .. } | FetchManifests { source, .. } | External { source, .. } => source.retry_hint(), diff --git a/src/mito2/src/region/opener.rs b/src/mito2/src/region/opener.rs index f7bfedabedb..000af1317b9 100644 --- a/src/mito2/src/region/opener.rs +++ b/src/mito2/src/region/opener.rs @@ -380,7 +380,7 @@ impl RegionOpener { // Safety: must be set before calling this method. let mut options = self.options.take().unwrap(); let object_store = get_object_store(&options.storage, &self.object_store_manager)?; - let provider = self.provider::(&options.wal_options)?; + let provider = self.provider(wal, &options.wal_options)?; let metadata = Arc::new(metadata); // Sets the sst_format based on options or flat_format flag let sst_format = if let Some(format) = options.sst_format { @@ -544,8 +544,9 @@ impl RegionOpener { Ok(region) } - fn provider(&self, wal_options: &WalOptions) -> Result { - provider_from_wal_options::(self.region_id, wal_options) + fn provider(&self, wal: &Wal, wal_options: &WalOptions) -> Result { + let provider = provider_from_wal_options::(self.region_id, wal_options)?; + wal.resolve_provider(self.region_id, provider) } /// Tries to open the region and returns `None` if the region directory is empty. @@ -599,7 +600,7 @@ impl RegionOpener { region_options.validate_column_compression(&metadata)?; let region_id = self.region_id; - let provider = self.provider::(®ion_options.wal_options)?; + let provider = self.provider(wal, ®ion_options.wal_options)?; let wal_entry_reader = self .wal_entry_reader .take() diff --git a/src/mito2/src/wal.rs b/src/mito2/src/wal.rs index c87cb7724e8..7a55014449f 100644 --- a/src/mito2/src/wal.rs +++ b/src/mito2/src/wal.rs @@ -41,7 +41,7 @@ use tokio::sync::watch; use crate::error::{ BuildEntrySnafu, CheckWalHistorySnafu, DeleteWalSnafu, ReadNodeWalSnafu, - RemoteWalUnsupportedSnafu, Result, WaitWalDurableSnafu, WriteWalSnafu, + RemoteWalUnsupportedSnafu, ResolveWalProviderSnafu, Result, WaitWalDurableSnafu, WriteWalSnafu, }; use crate::wal::entry_reader::{LogStoreEntryReader, WalEntryReader, decode_raw_entry}; use crate::wal::raw_entry_reader::{LogStoreRawEntryReader, RegionRawEntryReader}; @@ -116,6 +116,18 @@ impl Clone for Wal { } impl Wal { + /// Resolves persisted WAL options to this node's runtime namespace. + pub(crate) fn resolve_provider( + &self, + region_id: RegionId, + provider: Provider, + ) -> Result { + self.store + .resolve_provider(provider) + .map_err(BoxedError::new) + .context(ResolveWalProviderSnafu { region_id }) + } + /// Subscribes to shared WAL pressure snapshots. Notifications only advise /// workers to check their current region state, and never wait for flush. pub(crate) fn subscribe_flush_candidates(&self) -> watch::Receiver> { diff --git a/src/mito2/src/worker/handle_open.rs b/src/mito2/src/worker/handle_open.rs index 28a612fad8d..39d5c70de4d 100644 --- a/src/mito2/src/worker/handle_open.rs +++ b/src/mito2/src/worker/handle_open.rs @@ -63,6 +63,7 @@ impl RegionWorkerLoop { let options = RegionOptions::try_from_options(region_id, &request.options)?; let object_store = get_object_store(&options.storage, &self.object_store_manager)?; let provider = provider_from_wal_options::(region_id, &options.wal_options)?; + let provider = self.wal.resolve_provider(region_id, provider)?; self.wal.obsolete_all(region_id, &provider).await?; let table_dir = normalize_dir(&request.table_dir); diff --git a/src/store-api/src/logstore.rs b/src/store-api/src/logstore.rs index 00f3f1a929f..4634a400d69 100644 --- a/src/store-api/src/logstore.rs +++ b/src/store-api/src/logstore.rs @@ -55,6 +55,13 @@ pub trait LogStore: Send + Sync + 'static + std::fmt::Debug { Vec::new() } + /// Resolves a metadata provider into the namespace used by this store. + /// Backends with node-local namespaces validate the configured root here. + /// Providers already naming a concrete namespace remain compatible. + fn resolve_provider(&self, provider: Provider) -> Result { + Ok(provider) + } + /// Stops components of the logstore. async fn stop(&self) -> Result<(), Self::Error>; diff --git a/tests-integration/src/cluster.rs b/tests-integration/src/cluster.rs index 6d668ba9451..99913b9a3ee 100644 --- a/tests-integration/src/cluster.rs +++ b/tests-integration/src/cluster.rs @@ -159,6 +159,8 @@ pub struct GreptimeDbCluster { pub kv_backend: KvBackendRef, pub metasrv: Arc, pub frontend: Arc, + metasrv_connection: MockInfo, + datanode_clients: Arc, } impl GreptimeDbCluster { @@ -266,6 +268,7 @@ pub struct GreptimeDbClusterBuilder { shared_home_dir: Option>, meta_selector: Option, plugins: Plugins, + datanode_plugins: Arc Plugins + Send + Sync>, local_file_access: LocalFileAccess, event_recorder_options: EventRecorderOptions, real_datanode_grpc_addr: bool, @@ -307,6 +310,7 @@ impl GreptimeDbClusterBuilder { shared_home_dir: None, meta_selector: None, plugins: Plugins::default(), + datanode_plugins: Arc::new(|_| Plugins::default()), local_file_access: LocalFileAccess::default(), event_recorder_options: EventRecorderOptions::default(), real_datanode_grpc_addr: false, @@ -530,11 +534,49 @@ impl GreptimeDbClusterBuilder { datanode_rpc_stats, network_do_get, kv_backend: self.kv_backend.clone(), - metasrv: metasrv.metasrv, + metasrv: metasrv.metasrv.clone(), + metasrv_connection: metasrv, + datanode_clients, frontend: Arc::new(frontend), } } + /// Creates a fresh plugin registry for each datanode start, including restarts. + /// Datanode construction adds internal plugins, so registries cannot be shared. + #[must_use] + pub fn with_datanode_plugins( + mut self, + plugins: impl Fn(DatanodeId) -> Plugins + Send + Sync + 'static, + ) -> Self { + self.datanode_plugins = Arc::new(plugins); + self + } + + /// Restarts one in-process datanode and reconnects the shared client pool. + /// Real TCP listeners are not restartable by this harness. + pub async fn restart_datanode(&self, cluster: &mut GreptimeDbCluster, node_id: DatanodeId) { + assert!(!self.real_datanode_grpc_addr); + let mut old = cluster.datanode_instances.remove(&node_id).unwrap(); + old.shutdown().await.unwrap(); + drop(old); + let options = cluster + .datanode_options + .iter() + .find(|options| options.node_id == Some(node_id)) + .unwrap() + .clone(); + let instance = self + .create_datanode(options.clone(), cluster.metasrv_connection.clone()) + .await; + let (addr, client) = + create_datanode_client(&instance, &options.grpc.server_addr, None).await; + cluster + .datanode_clients + .insert_client(Peer::new(node_id, addr), client) + .await; + cluster.datanode_instances.insert(node_id, instance); + } + pub async fn build(&self, start_frontend_servers: bool) -> GreptimeDbCluster { let datanodes = self.datanodes.unwrap_or(4); let (datanode_options, guards) = self.build_datanode_options_and_guards(datanodes).await; @@ -671,7 +713,8 @@ impl GreptimeDbClusterBuilder { let layered_cache_registry = Arc::new(build_datanode_layered_cache_registry(meta_backend.clone())); - let mut builder = DatanodeBuilder::new(opts.clone(), Plugins::default(), meta_backend); + let plugins = (self.datanode_plugins)(opts.node_id.unwrap()); + let mut builder = DatanodeBuilder::new(opts.clone(), plugins, meta_backend); builder .with_cache_registry(layered_cache_registry.clone()) .with_meta_client(meta_client); @@ -1141,6 +1184,132 @@ mod tests { ); } + #[cfg(feature = "enterprise")] + #[tokio::test(flavor = "multi_thread")] + async fn test_object_store_cluster_entry_and_restart() { + use crate::test_util::{execute_sql, execute_sql_and_expect, get_test_store_config}; + use client::OutputData; + use common_wal::config::object_store::{ + EnableObjectStoreWal, FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig, + }; + + let home = Arc::new(create_temp_dir("object-store-cluster-entry")); + let (storage, _guard) = get_test_store_config(&StorageType::File); + let config = ObjectStoreWalConfig { + prefix: "cluster/wal".into(), + ..Default::default() + }; + let plugins = Plugins::new(); + plugins.insert(EnableObjectStoreWal); + let builder = GreptimeDbClusterBuilder::new("object-store-cluster-entry") + .await + .with_datanodes(2) + .with_store_config(storage) + .with_shared_home_dir(home.clone()) + .with_metasrv_wal_config(MetasrvWalConfig::ObjectStore(config.clone())) + .with_datanode_wal_config(DatanodeWalConfig::ObjectStore(config.clone())) + .with_plugins(plugins) + .with_datanode_plugins(|_| { + let plugins = Plugins::new(); + plugins.insert(EnableObjectStoreWal); + plugins + }); + let mut cluster = builder.build(false).await; + execute_sql(cluster.fe_instance(), "CREATE TABLE oswal_entry (i INT PRIMARY KEY, ts TIMESTAMP TIME INDEX) PARTITION ON COLUMNS (i) (i < 10, i >= 10)").await; + assert!(matches!( + execute_sql( + cluster.fe_instance(), + "INSERT INTO oswal_entry VALUES (1, 0), (11, 0)" + ) + .await + .data, + OutputData::AffectedRows(2) + )); + let expected = r#"+----+---------------------+ +| i | ts | ++----+---------------------+ +| 1 | 1970-01-01T00:00:00 | +| 11 | 1970-01-01T00:00:00 | ++----+---------------------+"#; + execute_sql_and_expect( + cluster.fe_instance(), + "SELECT * FROM oswal_entry ORDER BY i", + expected, + ) + .await; + let table = cluster + .fe_instance() + .catalog_manager() + .table("greptime", "public", "oswal_entry", None) + .await + .unwrap() + .unwrap(); + let table_id = table.table_info().table_id(); + let stores = + DatanodeBuilder::build_object_store_manager(&cluster.datanode_options[0].storage, 1) + .await + .unwrap(); + for node_id in [1, 2] { + let key = common_meta::key::datanode_table::DatanodeTableKey::new(node_id, table_id); + let metadata = cluster + .metasrv + .table_metadata_manager() + .datanode_table_manager() + .get(&key) + .await + .unwrap() + .unwrap(); + assert!(!metadata.regions.is_empty()); + assert!(metadata.region_info.region_wal_options.values().all(|options| { + matches!(options, common_wal::options::WalOptions::ObjectStore(options) if options.prefix == config.prefix) + })); + let prefix = format!( + "{}/objects/", + config.node_prefix(node_id, FIXED_DIRECTORY_GENERATION) + ); + assert!( + !stores + .default_object_store() + .list(&prefix) + .await + .unwrap() + .is_empty() + ); + builder.restart_datanode(&mut cluster, node_id).await; + execute_sql_and_expect( + cluster.fe_instance(), + "SELECT * FROM oswal_entry ORDER BY i", + expected, + ) + .await; + } + assert!(matches!( + execute_sql( + cluster.fe_instance(), + "INSERT INTO oswal_entry VALUES (2, 0), (12, 0)" + ) + .await + .data, + OutputData::AffectedRows(2) + )); + execute_sql_and_expect( + cluster.fe_instance(), + "SELECT * FROM oswal_entry ORDER BY i", + r#"+----+---------------------+ +| i | ts | ++----+---------------------+ +| 1 | 1970-01-01T00:00:00 | +| 2 | 1970-01-01T00:00:00 | +| 11 | 1970-01-01T00:00:00 | +| 12 | 1970-01-01T00:00:00 | ++----+---------------------+"#, + ) + .await; + for node in cluster.datanode_instances.values_mut() { + node.shutdown().await.unwrap(); + } + } + const HEALTH_REFRESH_INTERVAL: Duration = Duration::from_millis(10); const HEALTH_REFRESH_TIMEOUT: Duration = Duration::from_secs(5);