Skip to main content

standalone/
options.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
15use common_base::readable_size::ReadableSize;
16use common_config::{Configurable, KvBackendConfig};
17use common_event_recorder::EventRecorderOptions;
18use common_memory_manager::OnExhaustedPolicy;
19use common_options::memory::MemoryOptions;
20use common_telemetry::logging::{LoggingOptions, SlowQueryOptions, TracingOptions};
21use common_wal::config::DatanodeWalConfig;
22use datanode::config::{DatanodeOptions, ProcedureConfig, RegionEngineConfig, StorageConfig};
23use file_engine::config::EngineConfig as FileEngineConfig;
24use flow::FlowConfig;
25use frontend::frontend::FrontendOptions;
26use frontend::service_config::{
27    InfluxdbOptions, JaegerOptions, MysqlOptions, OpentsdbOptions, OtlpOptions,
28    PendingRowsBatcherOptions, PostgresOptions, PromStoreOptions, WriteRetryOptions,
29};
30use mito2::config::MitoConfig;
31use pipeline::PipelineOptions;
32use query::options::QueryOptions;
33use serde::{Deserialize, Serialize};
34use servers::grpc::GrpcOptions;
35use servers::http::HttpOptions;
36
37#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
38#[serde(default)]
39pub struct StandaloneOptions {
40    pub enable_telemetry: bool,
41    pub default_timezone: Option<String>,
42    pub default_column_prefix: Option<String>,
43    /// Server-side global switch for auto table creation on write.
44    /// Upper bound: when `false`, missing tables are never auto-created even if a
45    /// request sets the `auto_create_table` hint to `true`. Default: `true`.
46    pub auto_create_table: bool,
47    /// Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
48    /// Set to 0 to disable the limit. Default: "0" (unlimited)
49    pub max_in_flight_write_bytes: ReadableSize,
50    /// Policy when write bytes quota is exhausted.
51    /// Options: "wait" (default, 10s), "wait(<duration>)", "fail"
52    pub write_bytes_exhausted_policy: OnExhaustedPolicy,
53    pub http: HttpOptions,
54    pub grpc: GrpcOptions,
55    pub mysql: MysqlOptions,
56    pub postgres: PostgresOptions,
57    pub opentsdb: OpentsdbOptions,
58    pub influxdb: InfluxdbOptions,
59    /// Ordinary-table batching with independent logical-table controls.
60    pub pending_rows_batcher: PendingRowsBatcherOptions,
61    pub jaeger: JaegerOptions,
62    pub otlp: OtlpOptions,
63    pub prom_store: PromStoreOptions,
64    pub wal: DatanodeWalConfig,
65    pub storage: StorageConfig,
66    pub metadata_store: KvBackendConfig,
67    pub procedure: ProcedureConfig,
68    pub flow: FlowConfig,
69    pub logging: LoggingOptions,
70    pub user_provider: Option<String>,
71    /// Options for different store engines.
72    pub region_engine: Vec<RegionEngineConfig>,
73    pub tracing: TracingOptions,
74    pub init_regions_in_background: bool,
75    pub init_regions_parallelism: usize,
76    pub slow_query: SlowQueryOptions,
77    pub query: QueryOptions,
78    pub memory: MemoryOptions,
79    /// The pipeline options.
80    pub pipeline: PipelineOptions,
81    /// The event recorder options.
82    pub event_recorder: EventRecorderOptions,
83    /// Environment variable keys to read and report in heartbeat messages.
84    pub heartbeat_env_vars: Vec<String>,
85}
86
87impl Default for StandaloneOptions {
88    fn default() -> Self {
89        Self {
90            enable_telemetry: true,
91            default_timezone: None,
92            default_column_prefix: None,
93            auto_create_table: true,
94            max_in_flight_write_bytes: ReadableSize(0),
95            write_bytes_exhausted_policy: OnExhaustedPolicy::default(),
96            http: HttpOptions::default(),
97            grpc: GrpcOptions::default(),
98            mysql: MysqlOptions::default(),
99            postgres: PostgresOptions::default(),
100            opentsdb: OpentsdbOptions::default(),
101            influxdb: InfluxdbOptions::default(),
102            pending_rows_batcher: PendingRowsBatcherOptions::default(),
103            jaeger: JaegerOptions::default(),
104            otlp: OtlpOptions::default(),
105            prom_store: PromStoreOptions::default(),
106            wal: DatanodeWalConfig::default(),
107            storage: StorageConfig::default(),
108            metadata_store: KvBackendConfig::default(),
109            procedure: ProcedureConfig::default(),
110            flow: FlowConfig::default(),
111            logging: LoggingOptions::default(),
112            user_provider: None,
113            region_engine: vec![
114                RegionEngineConfig::Mito(MitoConfig::default()),
115                RegionEngineConfig::File(FileEngineConfig::default()),
116            ],
117            tracing: TracingOptions::default(),
118            init_regions_in_background: false,
119            init_regions_parallelism: 16,
120            slow_query: SlowQueryOptions::default(),
121            query: QueryOptions::default(),
122            memory: MemoryOptions::default(),
123            pipeline: PipelineOptions::default(),
124            event_recorder: EventRecorderOptions::default(),
125            heartbeat_env_vars: vec![],
126        }
127    }
128}
129
130impl Configurable for StandaloneOptions {
131    fn env_list_keys() -> Option<&'static [&'static str]> {
132        Some(&[
133            "heartbeat_env_vars",
134            "wal.broker_endpoints",
135            "event_recorder.event_types",
136            "pending_rows_batcher.protocols",
137            "pending_rows_batcher.logical_table.protocols",
138        ])
139    }
140}
141
142/// The [`StandaloneOptions`] is only defined in `standalone` crate,
143/// we don't want to make `frontend` depends on it, so impl [`Into`]
144/// rather than [`From`].
145#[allow(clippy::from_over_into)]
146impl Into<FrontendOptions> for StandaloneOptions {
147    fn into(self) -> FrontendOptions {
148        self.frontend_options()
149    }
150}
151
152impl StandaloneOptions {
153    pub fn frontend_options(&self) -> FrontendOptions {
154        let cloned_opts = self.clone();
155        FrontendOptions {
156            default_timezone: cloned_opts.default_timezone,
157            auto_create_table: cloned_opts.auto_create_table,
158            max_in_flight_write_bytes: cloned_opts.max_in_flight_write_bytes,
159            write_bytes_exhausted_policy: cloned_opts.write_bytes_exhausted_policy,
160            http: cloned_opts.http,
161            grpc: cloned_opts.grpc,
162            mysql: cloned_opts.mysql,
163            postgres: cloned_opts.postgres,
164            opentsdb: cloned_opts.opentsdb,
165            influxdb: cloned_opts.influxdb,
166            pending_rows_batcher: cloned_opts.pending_rows_batcher,
167            jaeger: cloned_opts.jaeger,
168            otlp: cloned_opts.otlp,
169            prom_store: cloned_opts.prom_store,
170            meta_client: None,
171            // Local region calls consume requests directly and do not use remote write retries.
172            write_retry: WriteRetryOptions {
173                max_retries: 0,
174                ..Default::default()
175            },
176            logging: cloned_opts.logging,
177            user_provider: cloned_opts.user_provider,
178            query: cloned_opts.query,
179            slow_query: cloned_opts.slow_query,
180            pipeline: cloned_opts.pipeline,
181            event_recorder: cloned_opts.event_recorder,
182            heartbeat_env_vars: cloned_opts.heartbeat_env_vars.clone(),
183            ..Default::default()
184        }
185    }
186
187    pub fn datanode_options(&self) -> DatanodeOptions {
188        let cloned_opts = self.clone();
189        DatanodeOptions {
190            node_id: Some(0),
191            enable_telemetry: cloned_opts.enable_telemetry,
192            wal: cloned_opts.wal,
193            storage: cloned_opts.storage,
194            region_engine: cloned_opts.region_engine,
195            grpc: cloned_opts.grpc,
196            init_regions_in_background: cloned_opts.init_regions_in_background,
197            init_regions_parallelism: cloned_opts.init_regions_parallelism,
198            query: cloned_opts.query,
199            heartbeat_env_vars: cloned_opts.heartbeat_env_vars,
200            ..Default::default()
201        }
202    }
203
204    /// Sanitize the `StandaloneOptions` to ensure the config is valid.
205    pub fn sanitize(&mut self) {
206        if self.storage.is_object_storage() {
207            self.storage
208                .store
209                .cache_config_mut()
210                .unwrap()
211                .sanitize(&self.storage.data_home);
212        }
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use std::sync::Arc;
219
220    use common_event_recorder::EventTypeFilter;
221    use servers::batcher::BatchingProtocol;
222
223    use crate::options::*;
224
225    #[test]
226    fn test_frontend_write_retries_disabled() {
227        assert!(FrontendOptions::default().write_retry.max_retries > 0);
228        assert_eq!(
229            StandaloneOptions::default()
230                .frontend_options()
231                .write_retry
232                .max_retries,
233            0
234        );
235    }
236
237    #[test]
238    fn test_logical_batcher_config_forwarding() {
239        let opts: StandaloneOptions = toml::from_str("[pending_rows_batcher]\nprotocols = ['influxdb']\n[pending_rows_batcher.logical_table]\nprotocols = ['otlp', 'prom']\npending_rows_flush_interval = '10ms'").unwrap();
240        let frontend = opts.frontend_options();
241        assert_eq!(frontend.pending_rows_batcher, opts.pending_rows_batcher);
242        assert_eq!(
243            frontend.pending_rows_batcher.logical_table,
244            opts.pending_rows_batcher.logical_table
245        );
246        let restored: StandaloneOptions = toml::from_str(&toml::to_string(&opts).unwrap()).unwrap();
247        assert_eq!(
248            restored.pending_rows_batcher.logical_table,
249            opts.pending_rows_batcher.logical_table
250        );
251        assert!(
252            toml::from_str::<StandaloneOptions>(
253                "[pending_rows_batcher.logical_table]\nprotocols = ['logs']"
254            )
255            .is_err()
256        );
257    }
258
259    #[test]
260    fn test_logical_batcher_protocols_from_env() {
261        temp_env::with_vars(
262            [
263                (
264                    "STANDALONE_LOGICAL_TEST__PENDING_ROWS_BATCHER__PROTOCOLS",
265                    Some("otlp,influxdb"),
266                ),
267                (
268                    "STANDALONE_LOGICAL_TEST__PENDING_ROWS_BATCHER__LOGICAL_TABLE__PROTOCOLS",
269                    Some("prom,otlp"),
270                ),
271            ],
272            || {
273                let options =
274                    StandaloneOptions::load_layered_options(None, "STANDALONE_LOGICAL_TEST")
275                        .unwrap();
276                assert_eq!(options.pending_rows_batcher.table.protocols.len(), 2);
277                assert_eq!(
278                    options
279                        .pending_rows_batcher
280                        .logical_table
281                        .unwrap()
282                        .protocols,
283                    vec![BatchingProtocol::Prom, BatchingProtocol::Otlp]
284                );
285            },
286        );
287    }
288
289    #[test]
290    fn test_batcher_protocols_from_env() {
291        temp_env::with_vars(
292            [(
293                "STANDALONE_BATCHER_TEST__PENDING_ROWS_BATCHER__PROTOCOLS",
294                Some("influxdb,http_sql"),
295            )],
296            || {
297                let options =
298                    StandaloneOptions::load_layered_options(None, "STANDALONE_BATCHER_TEST")
299                        .unwrap();
300                assert_eq!(
301                    options.pending_rows_batcher.table.protocols,
302                    vec![BatchingProtocol::Influxdb, BatchingProtocol::HttpSql]
303                );
304            },
305        );
306    }
307
308    #[test]
309    fn test_protocol_pending_rows_batcher_config() {
310        let defaults: StandaloneOptions = toml::from_str("").unwrap();
311        assert!(
312            !defaults
313                .pending_rows_batcher
314                .table
315                .pending_rows_batching_enabled()
316        );
317        let options: StandaloneOptions = toml::from_str(
318            r#"
319[pending_rows_batcher]
320protocols = ["influxdb", "http_sql"]
321pending_rows_flush_interval = "5ms"
322max_batch_rows = 25
323flow_notification_queue_capacity = 17
324"#,
325        )
326        .unwrap();
327        assert_eq!(options.pending_rows_batcher.table.max_batch_rows, 25);
328        assert_eq!(options.pending_rows_batcher.table.protocols.len(), 2);
329        assert_eq!(
330            options
331                .pending_rows_batcher
332                .table
333                .flow_notification_queue_capacity
334                .get(),
335            17
336        );
337        assert!(
338            options
339                .pending_rows_batcher
340                .table
341                .pending_rows_batching_enabled()
342        );
343        let serialized = toml::to_string(&options).unwrap();
344        let parsed: StandaloneOptions = toml::from_str(&serialized).unwrap();
345        assert_eq!(options.influxdb, parsed.influxdb);
346        assert_eq!(options.opentsdb, parsed.opentsdb);
347        assert_eq!(options.pending_rows_batcher, parsed.pending_rows_batcher);
348        let frontend = options.frontend_options();
349        assert_eq!(options.influxdb, frontend.influxdb);
350        assert_eq!(options.opentsdb, frontend.opentsdb);
351        assert_eq!(options.pending_rows_batcher, frontend.pending_rows_batcher);
352    }
353
354    #[test]
355    fn test_event_recorder_event_types_preserve_filter_semantics() {
356        let all: StandaloneOptions = toml::from_str("").unwrap();
357        let none: StandaloneOptions = toml::from_str("[event_recorder]\nevent_types = []").unwrap();
358        let selected: StandaloneOptions =
359            toml::from_str("[event_recorder]\nevent_types = ['create_database']").unwrap();
360
361        assert!(all.event_recorder.event_types.allows("future_event"));
362        assert_eq!(
363            none.event_recorder.event_types.as_ref(),
364            &EventTypeFilter::Only(Default::default())
365        );
366        assert!(
367            selected
368                .event_recorder
369                .event_types
370                .allows("create_database")
371        );
372        assert!(!selected.event_recorder.event_types.allows("drop_database"));
373
374        let frontend_options = selected.frontend_options();
375        assert!(Arc::ptr_eq(
376            &selected.event_recorder.event_types,
377            &frontend_options.event_recorder.event_types,
378        ));
379    }
380
381    #[test]
382    fn test_query_options_propagated_to_components() {
383        let mut options = StandaloneOptions::default();
384        options.query.parallelism = 4;
385
386        assert_eq!(options.frontend_options().query.parallelism, 4);
387        assert_eq!(options.datanode_options().query.parallelism, 4);
388    }
389}