risingwave_meta/manager/
env.rs

1// Copyright 2025 RisingWave Labs
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 std::ops::Deref;
16use std::path::PathBuf;
17use std::sync::Arc;
18
19use anyhow::Context;
20use risingwave_common::config::{
21    CompactionConfig, DefaultParallelism, ObjectStoreConfig, RpcClientConfig,
22};
23use risingwave_common::session_config::SessionConfig;
24use risingwave_common::system_param::reader::SystemParamsReader;
25use risingwave_common::{bail, system_param};
26use risingwave_meta_model::prelude::Cluster;
27use risingwave_pb::meta::SystemParams;
28use risingwave_rpc_client::{
29    FrontendClientPool, FrontendClientPoolRef, StreamClientPool, StreamClientPoolRef,
30};
31use risingwave_sqlparser::ast::RedactSqlOptionKeywordsRef;
32use sea_orm::EntityTrait;
33
34use crate::MetaResult;
35use crate::controller::SqlMetaStore;
36use crate::controller::id::{
37    IdGeneratorManager as SqlIdGeneratorManager, IdGeneratorManagerRef as SqlIdGeneratorManagerRef,
38};
39use crate::controller::session_params::{SessionParamsController, SessionParamsControllerRef};
40use crate::controller::system_param::{SystemParamsController, SystemParamsControllerRef};
41use crate::hummock::sequence::SequenceGenerator;
42use crate::manager::event_log::{EventLogManagerRef, start_event_log_manager};
43use crate::manager::{IdleManager, IdleManagerRef, NotificationManager, NotificationManagerRef};
44use crate::model::ClusterId;
45
46/// [`MetaSrvEnv`] is the global environment in Meta service. The instance will be shared by all
47/// kind of managers inside Meta.
48#[derive(Clone)]
49pub struct MetaSrvEnv {
50    /// id generator manager.
51    id_gen_manager_impl: SqlIdGeneratorManagerRef,
52
53    /// system param manager.
54    system_param_manager_impl: SystemParamsControllerRef,
55
56    /// session param manager.
57    session_param_manager_impl: SessionParamsControllerRef,
58
59    /// meta store.
60    meta_store_impl: SqlMetaStore,
61
62    /// notification manager.
63    notification_manager: NotificationManagerRef,
64
65    /// stream client pool memorization.
66    stream_client_pool: StreamClientPoolRef,
67
68    /// rpc client pool for frontend nodes.
69    frontend_client_pool: FrontendClientPoolRef,
70
71    /// idle status manager.
72    idle_manager: IdleManagerRef,
73
74    event_log_manager: EventLogManagerRef,
75
76    /// Unique identifier of the cluster.
77    cluster_id: ClusterId,
78
79    pub hummock_seq: Arc<SequenceGenerator>,
80
81    /// The await-tree registry of the current meta node.
82    await_tree_reg: await_tree::Registry,
83
84    /// options read by all services
85    pub opts: Arc<MetaOpts>,
86}
87
88/// Options shared by all meta service instances
89#[derive(Clone, serde::Serialize)]
90pub struct MetaOpts {
91    /// Whether to enable the recovery of the cluster. If disabled, the meta service will exit on
92    /// abnormal cases.
93    pub enable_recovery: bool,
94    /// Whether to disable the auto-scaling feature.
95    pub disable_automatic_parallelism_control: bool,
96    /// The number of streaming jobs per scaling operation.
97    pub parallelism_control_batch_size: usize,
98    /// The period of parallelism control trigger.
99    pub parallelism_control_trigger_period_sec: u64,
100    /// The first delay of parallelism control.
101    pub parallelism_control_trigger_first_delay_sec: u64,
102    /// The maximum number of barriers in-flight in the compute nodes.
103    pub in_flight_barrier_nums: usize,
104    /// After specified seconds of idle (no mview or flush), the process will be exited.
105    /// 0 for infinite, process will never be exited due to long idle time.
106    pub max_idle_ms: u64,
107    /// Whether run in compaction detection test mode
108    pub compaction_deterministic_test: bool,
109    /// Default parallelism of units for all streaming jobs.
110    pub default_parallelism: DefaultParallelism,
111
112    /// Interval of invoking a vacuum job, to remove stale metadata from meta store and objects
113    /// from object store.
114    pub vacuum_interval_sec: u64,
115    /// The spin interval inside a vacuum job. It avoids the vacuum job monopolizing resources of
116    /// meta node.
117    pub vacuum_spin_interval_ms: u64,
118    pub time_travel_vacuum_interval_sec: u64,
119    /// Interval of hummock version checkpoint.
120    pub hummock_version_checkpoint_interval_sec: u64,
121    pub enable_hummock_data_archive: bool,
122    pub hummock_time_travel_snapshot_interval: u64,
123    pub hummock_time_travel_sst_info_fetch_batch_size: usize,
124    pub hummock_time_travel_sst_info_insert_batch_size: usize,
125    pub hummock_time_travel_epoch_version_insert_batch_size: usize,
126    pub hummock_gc_history_insert_batch_size: usize,
127    pub hummock_time_travel_filter_out_objects_batch_size: usize,
128    pub hummock_time_travel_filter_out_objects_v1: bool,
129    pub hummock_time_travel_filter_out_objects_list_version_batch_size: usize,
130    pub hummock_time_travel_filter_out_objects_list_delta_batch_size: usize,
131    /// The minimum delta log number a new checkpoint should compact, otherwise the checkpoint
132    /// attempt is rejected. Greater value reduces object store IO, meanwhile it results in
133    /// more loss of in memory `HummockVersionCheckpoint::stale_objects` state when meta node is
134    /// restarted.
135    pub min_delta_log_num_for_hummock_version_checkpoint: u64,
136    /// Objects within `min_sst_retention_time_sec` won't be deleted by hummock full GC, even they
137    /// are dangling.
138    pub min_sst_retention_time_sec: u64,
139    /// Interval of automatic hummock full GC.
140    pub full_gc_interval_sec: u64,
141    /// Max number of object per full GC job can fetch.
142    pub full_gc_object_limit: u64,
143    /// Duration in seconds to retain garbage collection history data.
144    pub gc_history_retention_time_sec: u64,
145    /// Max number of inflight time travel query.
146    pub max_inflight_time_travel_query: u64,
147    /// Enable sanity check when SSTs are committed
148    pub enable_committed_sst_sanity_check: bool,
149    /// Schedule compaction for all compaction groups with this interval.
150    pub periodic_compaction_interval_sec: u64,
151    /// Interval of reporting the number of nodes in the cluster.
152    pub node_num_monitor_interval_sec: u64,
153
154    /// The Prometheus endpoint for Meta Dashboard Service.
155    /// The Dashboard service uses this in the following ways:
156    /// 1. Query Prometheus for relevant metrics to find Stream Graph Bottleneck, and display it.
157    /// 2. Provide cluster diagnostics, at `/api/monitor/diagnose` to troubleshoot cluster.
158    ///    These are just examples which show how the Meta Dashboard Service queries Prometheus.
159    pub prometheus_endpoint: Option<String>,
160
161    /// The additional selector used when querying Prometheus.
162    pub prometheus_selector: Option<String>,
163
164    /// The VPC id of the cluster.
165    pub vpc_id: Option<String>,
166
167    /// A usable security group id to assign to a vpc endpoint
168    pub security_group_id: Option<String>,
169
170    /// Default tag for the endpoint created when creating a privatelink connection.
171    /// Will be appended to the tags specified in the `tags` field in with clause in `create
172    /// connection`.
173    pub privatelink_endpoint_default_tags: Option<Vec<(String, String)>>,
174
175    /// Schedule `space_reclaim_compaction` for all compaction groups with this interval.
176    pub periodic_space_reclaim_compaction_interval_sec: u64,
177
178    /// telemetry enabled in config file or not
179    pub telemetry_enabled: bool,
180    /// Schedule `ttl_reclaim_compaction` for all compaction groups with this interval.
181    pub periodic_ttl_reclaim_compaction_interval_sec: u64,
182
183    /// Schedule `tombstone_reclaim_compaction` for all compaction groups with this interval.
184    pub periodic_tombstone_reclaim_compaction_interval_sec: u64,
185
186    /// Schedule `periodic_scheduling_compaction_group_split_interval_sec` for all compaction groups with this interval.
187    pub periodic_scheduling_compaction_group_split_interval_sec: u64,
188
189    /// Whether config object storage bucket lifecycle to purge stale data.
190    pub do_not_config_object_storage_lifecycle: bool,
191
192    pub partition_vnode_count: u32,
193
194    /// threshold of high write throughput of state-table, unit: B/sec
195    pub table_high_write_throughput_threshold: u64,
196    /// threshold of low write throughput of state-table, unit: B/sec
197    pub table_low_write_throughput_threshold: u64,
198
199    pub compaction_task_max_heartbeat_interval_secs: u64,
200    pub compaction_task_max_progress_interval_secs: u64,
201    pub compaction_config: Option<CompactionConfig>,
202
203    /// hybird compaction group config
204    ///
205    /// `hybrid_partition_vnode_count` determines the granularity of vnodes in the hybrid compaction group for SST alignment.
206    /// When `hybrid_partition_vnode_count` > 0, in hybrid compaction group
207    /// - Tables with high write throughput will be split at vnode granularity
208    /// - Tables with high size tables will be split by table granularity
209    ///   When `hybrid_partition_vnode_count` = 0,no longer be special alignment operations for the hybird compaction group
210    pub hybrid_partition_node_count: u32,
211
212    pub event_log_enabled: bool,
213    pub event_log_channel_max_size: u32,
214    pub advertise_addr: String,
215    /// The number of traces to be cached in-memory by the tracing collector
216    /// embedded in the meta node.
217    pub cached_traces_num: u32,
218    /// The maximum memory usage in bytes for the tracing collector embedded
219    /// in the meta node.
220    pub cached_traces_memory_limit_bytes: usize,
221
222    /// l0 picker whether to select trivial move task
223    pub enable_trivial_move: bool,
224
225    /// l0 multi level picker whether to check the overlap accuracy between sub levels
226    pub enable_check_task_level_overlap: bool,
227    pub enable_dropped_column_reclaim: bool,
228
229    /// Whether to split the compaction group when the size of the group exceeds the threshold.
230    pub split_group_size_ratio: f64,
231
232    /// To split the compaction group when the high throughput statistics of the group exceeds the threshold.
233    pub table_stat_high_write_throughput_ratio_for_split: f64,
234
235    /// To merge the compaction group when the low throughput statistics of the group exceeds the threshold.
236    pub table_stat_low_write_throughput_ratio_for_merge: f64,
237
238    /// The window seconds of table throughput statistic history for split compaction group.
239    pub table_stat_throuput_window_seconds_for_split: usize,
240
241    /// The window seconds of table throughput statistic history for merge compaction group.
242    pub table_stat_throuput_window_seconds_for_merge: usize,
243
244    /// The configuration of the object store
245    pub object_store_config: ObjectStoreConfig,
246
247    /// The maximum number of trivial move tasks to be picked in a single loop
248    pub max_trivial_move_task_count_per_loop: usize,
249
250    /// The maximum number of times to probe for `PullTaskEvent`
251    pub max_get_task_probe_times: usize,
252
253    pub compact_task_table_size_partition_threshold_low: u64,
254    pub compact_task_table_size_partition_threshold_high: u64,
255
256    pub periodic_scheduling_compaction_group_merge_interval_sec: u64,
257
258    pub compaction_group_merge_dimension_threshold: f64,
259
260    // The private key for the secret store, used when the secret is stored in the meta.
261    pub secret_store_private_key: Option<Vec<u8>>,
262    /// The path of the temp secret file directory.
263    pub temp_secret_file_dir: String,
264
265    // Cluster limits
266    pub actor_cnt_per_worker_parallelism_hard_limit: usize,
267    pub actor_cnt_per_worker_parallelism_soft_limit: usize,
268
269    pub license_key_path: Option<PathBuf>,
270
271    pub compute_client_config: RpcClientConfig,
272    pub stream_client_config: RpcClientConfig,
273    pub frontend_client_config: RpcClientConfig,
274    pub redact_sql_option_keywords: RedactSqlOptionKeywordsRef,
275}
276
277impl MetaOpts {
278    /// Default opts for testing. Some tests need `enable_recovery=true`
279    pub fn test(enable_recovery: bool) -> Self {
280        Self {
281            enable_recovery,
282            disable_automatic_parallelism_control: false,
283            parallelism_control_batch_size: 1,
284            parallelism_control_trigger_period_sec: 10,
285            parallelism_control_trigger_first_delay_sec: 30,
286            in_flight_barrier_nums: 40,
287            max_idle_ms: 0,
288            compaction_deterministic_test: false,
289            default_parallelism: DefaultParallelism::Full,
290            vacuum_interval_sec: 30,
291            time_travel_vacuum_interval_sec: 30,
292            vacuum_spin_interval_ms: 0,
293            hummock_version_checkpoint_interval_sec: 30,
294            enable_hummock_data_archive: false,
295            hummock_time_travel_snapshot_interval: 0,
296            hummock_time_travel_sst_info_fetch_batch_size: 10_000,
297            hummock_time_travel_sst_info_insert_batch_size: 10,
298            hummock_time_travel_epoch_version_insert_batch_size: 1000,
299            hummock_gc_history_insert_batch_size: 1000,
300            hummock_time_travel_filter_out_objects_batch_size: 1000,
301            hummock_time_travel_filter_out_objects_v1: false,
302            hummock_time_travel_filter_out_objects_list_version_batch_size: 10,
303            hummock_time_travel_filter_out_objects_list_delta_batch_size: 1000,
304            min_delta_log_num_for_hummock_version_checkpoint: 1,
305            min_sst_retention_time_sec: 3600 * 24 * 7,
306            full_gc_interval_sec: 3600 * 24 * 7,
307            full_gc_object_limit: 100_000,
308            gc_history_retention_time_sec: 3600 * 24 * 7,
309            max_inflight_time_travel_query: 1000,
310            enable_committed_sst_sanity_check: false,
311            periodic_compaction_interval_sec: 60,
312            node_num_monitor_interval_sec: 10,
313            prometheus_endpoint: None,
314            prometheus_selector: None,
315            vpc_id: None,
316            security_group_id: None,
317            privatelink_endpoint_default_tags: None,
318            periodic_space_reclaim_compaction_interval_sec: 60,
319            telemetry_enabled: false,
320            periodic_ttl_reclaim_compaction_interval_sec: 60,
321            periodic_tombstone_reclaim_compaction_interval_sec: 60,
322            periodic_scheduling_compaction_group_split_interval_sec: 60,
323            compact_task_table_size_partition_threshold_low: 128 * 1024 * 1024,
324            compact_task_table_size_partition_threshold_high: 512 * 1024 * 1024,
325            table_high_write_throughput_threshold: 128 * 1024 * 1024,
326            table_low_write_throughput_threshold: 64 * 1024 * 1024,
327            do_not_config_object_storage_lifecycle: true,
328            partition_vnode_count: 32,
329            compaction_task_max_heartbeat_interval_secs: 0,
330            compaction_task_max_progress_interval_secs: 1,
331            compaction_config: None,
332            hybrid_partition_node_count: 4,
333            event_log_enabled: false,
334            event_log_channel_max_size: 1,
335            advertise_addr: "".to_owned(),
336            cached_traces_num: 1,
337            cached_traces_memory_limit_bytes: usize::MAX,
338            enable_trivial_move: true,
339            enable_check_task_level_overlap: true,
340            enable_dropped_column_reclaim: false,
341            object_store_config: ObjectStoreConfig::default(),
342            max_trivial_move_task_count_per_loop: 256,
343            max_get_task_probe_times: 5,
344            secret_store_private_key: Some(
345                hex::decode("0123456789abcdef0123456789abcdef").unwrap(),
346            ),
347            temp_secret_file_dir: "./secrets".to_owned(),
348            actor_cnt_per_worker_parallelism_hard_limit: usize::MAX,
349            actor_cnt_per_worker_parallelism_soft_limit: usize::MAX,
350            split_group_size_ratio: 0.9,
351            table_stat_high_write_throughput_ratio_for_split: 0.5,
352            table_stat_low_write_throughput_ratio_for_merge: 0.7,
353            table_stat_throuput_window_seconds_for_split: 60,
354            table_stat_throuput_window_seconds_for_merge: 240,
355            periodic_scheduling_compaction_group_merge_interval_sec: 60 * 10,
356            compaction_group_merge_dimension_threshold: 1.2,
357            license_key_path: None,
358            compute_client_config: RpcClientConfig::default(),
359            stream_client_config: RpcClientConfig::default(),
360            frontend_client_config: RpcClientConfig::default(),
361            redact_sql_option_keywords: Arc::new(Default::default()),
362        }
363    }
364}
365
366impl MetaSrvEnv {
367    pub async fn new(
368        opts: MetaOpts,
369        mut init_system_params: SystemParams,
370        init_session_config: SessionConfig,
371        meta_store_impl: SqlMetaStore,
372    ) -> MetaResult<Self> {
373        let idle_manager = Arc::new(IdleManager::new(opts.max_idle_ms));
374        let stream_client_pool =
375            Arc::new(StreamClientPool::new(1, opts.stream_client_config.clone())); // typically no need for plural clients
376        let frontend_client_pool = Arc::new(FrontendClientPool::new(
377            1,
378            opts.frontend_client_config.clone(),
379        ));
380        let event_log_manager = Arc::new(start_event_log_manager(
381            opts.event_log_enabled,
382            opts.event_log_channel_max_size,
383        ));
384
385        // When license key path is specified, license key from system parameters can be easily
386        // overwritten. So we simply reject this case.
387        if opts.license_key_path.is_some()
388            && init_system_params.license_key
389                != system_param::default::license_key_opt().map(Into::into)
390        {
391            bail!(
392                "argument `--license-key-path` (or env var `RW_LICENSE_KEY_PATH`) and \
393                 system parameter `license_key` (or env var `RW_LICENSE_KEY`) may not \
394                 be set at the same time"
395            );
396        }
397
398        let cluster_first_launch = meta_store_impl.up().await.context(
399            "Failed to initialize the meta store, \
400            this may happen if there's existing metadata incompatible with the current version of RisingWave, \
401            e.g., downgrading from a newer release or a nightly build to an older one. \
402            For a single-node deployment, you may want to reset all data by deleting the data directory, \
403            typically located at `~/.risingwave`.",
404        )?;
405
406        let notification_manager =
407            Arc::new(NotificationManager::new(meta_store_impl.clone()).await);
408        let cluster_id = Cluster::find()
409            .one(&meta_store_impl.conn)
410            .await?
411            .map(|c| c.cluster_id.to_string().into())
412            .unwrap();
413
414        // For new clusters:
415        // - the name of the object store needs to be prefixed according to the object id.
416        //
417        // For old clusters
418        // - the prefix is ​​not divided for the sake of compatibility.
419        init_system_params.use_new_object_prefix_strategy = Some(cluster_first_launch);
420
421        let system_param_controller = Arc::new(
422            SystemParamsController::new(
423                meta_store_impl.clone(),
424                notification_manager.clone(),
425                init_system_params,
426            )
427            .await?,
428        );
429        let session_param_controller = Arc::new(
430            SessionParamsController::new(
431                meta_store_impl.clone(),
432                notification_manager.clone(),
433                init_session_config,
434            )
435            .await?,
436        );
437        Ok(Self {
438            id_gen_manager_impl: Arc::new(SqlIdGeneratorManager::new(&meta_store_impl.conn).await?),
439            system_param_manager_impl: system_param_controller,
440            session_param_manager_impl: session_param_controller,
441            meta_store_impl: meta_store_impl.clone(),
442            notification_manager,
443            stream_client_pool,
444            frontend_client_pool,
445            idle_manager,
446            event_log_manager,
447            cluster_id,
448            hummock_seq: Arc::new(SequenceGenerator::new(meta_store_impl.conn.clone())),
449            opts: opts.into(),
450            // Await trees on the meta node is lightweight, thus always enabled.
451            await_tree_reg: await_tree::Registry::new(Default::default()),
452        })
453    }
454
455    pub fn meta_store(&self) -> SqlMetaStore {
456        self.meta_store_impl.clone()
457    }
458
459    pub fn meta_store_ref(&self) -> &SqlMetaStore {
460        &self.meta_store_impl
461    }
462
463    pub fn id_gen_manager(&self) -> &SqlIdGeneratorManagerRef {
464        &self.id_gen_manager_impl
465    }
466
467    pub fn notification_manager_ref(&self) -> NotificationManagerRef {
468        self.notification_manager.clone()
469    }
470
471    pub fn notification_manager(&self) -> &NotificationManager {
472        self.notification_manager.deref()
473    }
474
475    pub fn idle_manager_ref(&self) -> IdleManagerRef {
476        self.idle_manager.clone()
477    }
478
479    pub fn idle_manager(&self) -> &IdleManager {
480        self.idle_manager.deref()
481    }
482
483    pub async fn system_params_reader(&self) -> SystemParamsReader {
484        self.system_param_manager_impl.get_params().await
485    }
486
487    pub fn system_params_manager_impl_ref(&self) -> SystemParamsControllerRef {
488        self.system_param_manager_impl.clone()
489    }
490
491    pub fn session_params_manager_impl_ref(&self) -> SessionParamsControllerRef {
492        self.session_param_manager_impl.clone()
493    }
494
495    pub fn stream_client_pool_ref(&self) -> StreamClientPoolRef {
496        self.stream_client_pool.clone()
497    }
498
499    pub fn stream_client_pool(&self) -> &StreamClientPool {
500        self.stream_client_pool.deref()
501    }
502
503    pub fn frontend_client_pool(&self) -> &FrontendClientPool {
504        self.frontend_client_pool.deref()
505    }
506
507    pub fn cluster_id(&self) -> &ClusterId {
508        &self.cluster_id
509    }
510
511    pub fn event_log_manager_ref(&self) -> EventLogManagerRef {
512        self.event_log_manager.clone()
513    }
514
515    pub fn await_tree_reg(&self) -> &await_tree::Registry {
516        &self.await_tree_reg
517    }
518}
519
520#[cfg(any(test, feature = "test"))]
521impl MetaSrvEnv {
522    // Instance for test.
523    pub async fn for_test() -> Self {
524        Self::for_test_opts(MetaOpts::test(false)).await
525    }
526
527    pub async fn for_test_opts(opts: MetaOpts) -> Self {
528        Self::new(
529            opts,
530            risingwave_common::system_param::system_params_for_test(),
531            Default::default(),
532            SqlMetaStore::for_test().await,
533        )
534        .await
535        .unwrap()
536    }
537}