1use std::ops::Deref;
16use std::path::PathBuf;
17use std::sync::Arc;
18use std::sync::atomic::AtomicU32;
19
20use anyhow::Context;
21use risingwave_common::config::{
22 CompactionConfig, DefaultParallelism, ObjectStoreConfig, RpcClientConfig,
23};
24use risingwave_common::session_config::SessionConfig;
25use risingwave_common::system_param::reader::SystemParamsReader;
26use risingwave_common::{bail, system_param};
27use risingwave_meta_model::prelude::Cluster;
28use risingwave_pb::meta::SystemParams;
29use risingwave_rpc_client::{
30 FrontendClientPool, FrontendClientPoolRef, StreamClientPool, StreamClientPoolRef,
31};
32use risingwave_sqlparser::ast::RedactSqlOptionKeywordsRef;
33use sea_orm::EntityTrait;
34
35use crate::MetaResult;
36use crate::barrier::SharedActorInfos;
37use crate::barrier::cdc_progress::{CdcTableBackfillTracker, CdcTableBackfillTrackerRef};
38use crate::controller::SqlMetaStore;
39use crate::controller::id::{
40 IdGeneratorManager as SqlIdGeneratorManager, IdGeneratorManagerRef as SqlIdGeneratorManagerRef,
41};
42use crate::controller::session_params::{SessionParamsController, SessionParamsControllerRef};
43use crate::controller::system_param::{SystemParamsController, SystemParamsControllerRef};
44use crate::hummock::sequence::SequenceGenerator;
45use crate::manager::event_log::{EventLogManagerRef, start_event_log_manager};
46use crate::manager::{IdleManager, IdleManagerRef, NotificationManager, NotificationManagerRef};
47use crate::model::ClusterId;
48
49#[derive(Clone)]
52pub struct MetaSrvEnv {
53 id_gen_manager_impl: SqlIdGeneratorManagerRef,
55
56 system_param_manager_impl: SystemParamsControllerRef,
58
59 session_param_manager_impl: SessionParamsControllerRef,
61
62 meta_store_impl: SqlMetaStore,
64
65 notification_manager: NotificationManagerRef,
67
68 pub shared_actor_info: SharedActorInfos,
69
70 stream_client_pool: StreamClientPoolRef,
72
73 frontend_client_pool: FrontendClientPoolRef,
75
76 idle_manager: IdleManagerRef,
78
79 event_log_manager: EventLogManagerRef,
80
81 cluster_id: ClusterId,
83
84 pub hummock_seq: Arc<SequenceGenerator>,
85
86 await_tree_reg: await_tree::Registry,
88
89 pub opts: Arc<MetaOpts>,
91
92 pub cdc_table_backfill_tracker: CdcTableBackfillTrackerRef,
93
94 actor_id_generator: Arc<AtomicU32>,
95}
96
97#[derive(Clone, serde::Serialize)]
99pub struct MetaOpts {
100 pub enable_recovery: bool,
103 pub disable_automatic_parallelism_control: bool,
105 pub parallelism_control_batch_size: usize,
107 pub parallelism_control_trigger_period_sec: u64,
109 pub parallelism_control_trigger_first_delay_sec: u64,
111 pub in_flight_barrier_nums: usize,
113 pub max_idle_ms: u64,
116 pub compaction_deterministic_test: bool,
118 pub default_parallelism: DefaultParallelism,
120
121 pub vacuum_interval_sec: u64,
124 pub vacuum_spin_interval_ms: u64,
127 pub iceberg_gc_interval_sec: u64,
129 pub time_travel_vacuum_interval_sec: u64,
130 pub hummock_version_checkpoint_interval_sec: u64,
132 pub enable_hummock_data_archive: bool,
133 pub hummock_time_travel_snapshot_interval: u64,
134 pub hummock_time_travel_sst_info_fetch_batch_size: usize,
135 pub hummock_time_travel_sst_info_insert_batch_size: usize,
136 pub hummock_time_travel_epoch_version_insert_batch_size: usize,
137 pub hummock_gc_history_insert_batch_size: usize,
138 pub hummock_time_travel_filter_out_objects_batch_size: usize,
139 pub hummock_time_travel_filter_out_objects_v1: bool,
140 pub hummock_time_travel_filter_out_objects_list_version_batch_size: usize,
141 pub hummock_time_travel_filter_out_objects_list_delta_batch_size: usize,
142 pub min_delta_log_num_for_hummock_version_checkpoint: u64,
147 pub min_sst_retention_time_sec: u64,
150 pub full_gc_interval_sec: u64,
152 pub full_gc_object_limit: u64,
154 pub gc_history_retention_time_sec: u64,
156 pub max_inflight_time_travel_query: u64,
158 pub enable_committed_sst_sanity_check: bool,
160 pub periodic_compaction_interval_sec: u64,
162 pub node_num_monitor_interval_sec: u64,
164 pub protect_drop_table_with_incoming_sink: bool,
166 pub prometheus_endpoint: Option<String>,
172
173 pub prometheus_selector: Option<String>,
175
176 pub vpc_id: Option<String>,
178
179 pub security_group_id: Option<String>,
181
182 pub privatelink_endpoint_default_tags: Option<Vec<(String, String)>>,
186
187 pub periodic_space_reclaim_compaction_interval_sec: u64,
189
190 pub telemetry_enabled: bool,
192 pub periodic_ttl_reclaim_compaction_interval_sec: u64,
194
195 pub periodic_tombstone_reclaim_compaction_interval_sec: u64,
197
198 pub periodic_scheduling_compaction_group_split_interval_sec: u64,
200
201 pub do_not_config_object_storage_lifecycle: bool,
203
204 pub partition_vnode_count: u32,
205
206 pub table_high_write_throughput_threshold: u64,
208 pub table_low_write_throughput_threshold: u64,
210
211 pub compaction_task_max_heartbeat_interval_secs: u64,
212 pub compaction_task_max_progress_interval_secs: u64,
213 pub compaction_config: Option<CompactionConfig>,
214
215 pub hybrid_partition_node_count: u32,
223
224 pub event_log_enabled: bool,
225 pub event_log_channel_max_size: u32,
226 pub advertise_addr: String,
227 pub cached_traces_num: u32,
230 pub cached_traces_memory_limit_bytes: usize,
233
234 pub enable_trivial_move: bool,
236
237 pub enable_check_task_level_overlap: bool,
239 pub enable_dropped_column_reclaim: bool,
240
241 pub split_group_size_ratio: f64,
243
244 pub refresh_scheduler_interval_sec: u64,
246
247 pub table_stat_high_write_throughput_ratio_for_split: f64,
249
250 pub table_stat_low_write_throughput_ratio_for_merge: f64,
252
253 pub table_stat_throuput_window_seconds_for_split: usize,
255
256 pub table_stat_throuput_window_seconds_for_merge: usize,
258
259 pub object_store_config: ObjectStoreConfig,
261
262 pub max_trivial_move_task_count_per_loop: usize,
264
265 pub max_get_task_probe_times: usize,
267
268 pub compact_task_table_size_partition_threshold_low: u64,
269 pub compact_task_table_size_partition_threshold_high: u64,
270
271 pub periodic_scheduling_compaction_group_merge_interval_sec: u64,
272
273 pub compaction_group_merge_dimension_threshold: f64,
274
275 pub secret_store_private_key: Option<Vec<u8>>,
277 pub temp_secret_file_dir: String,
279
280 pub actor_cnt_per_worker_parallelism_hard_limit: usize,
282 pub actor_cnt_per_worker_parallelism_soft_limit: usize,
283
284 pub license_key_path: Option<PathBuf>,
285
286 pub compute_client_config: RpcClientConfig,
287 pub stream_client_config: RpcClientConfig,
288 pub frontend_client_config: RpcClientConfig,
289 pub redact_sql_option_keywords: RedactSqlOptionKeywordsRef,
290
291 pub cdc_table_split_init_sleep_interval_splits: u64,
292 pub cdc_table_split_init_sleep_duration_millis: u64,
293 pub cdc_table_split_init_insert_batch_size: u64,
294
295 pub enable_legacy_table_migration: bool,
296}
297
298impl MetaOpts {
299 pub fn test(enable_recovery: bool) -> Self {
301 Self {
302 enable_recovery,
303 disable_automatic_parallelism_control: false,
304 parallelism_control_batch_size: 1,
305 parallelism_control_trigger_period_sec: 10,
306 parallelism_control_trigger_first_delay_sec: 30,
307 in_flight_barrier_nums: 40,
308 max_idle_ms: 0,
309 compaction_deterministic_test: false,
310 default_parallelism: DefaultParallelism::Full,
311 vacuum_interval_sec: 30,
312 time_travel_vacuum_interval_sec: 30,
313 vacuum_spin_interval_ms: 0,
314 iceberg_gc_interval_sec: 3600,
315 hummock_version_checkpoint_interval_sec: 30,
316 enable_hummock_data_archive: false,
317 hummock_time_travel_snapshot_interval: 0,
318 hummock_time_travel_sst_info_fetch_batch_size: 10_000,
319 hummock_time_travel_sst_info_insert_batch_size: 10,
320 hummock_time_travel_epoch_version_insert_batch_size: 1000,
321 hummock_gc_history_insert_batch_size: 1000,
322 hummock_time_travel_filter_out_objects_batch_size: 1000,
323 hummock_time_travel_filter_out_objects_v1: false,
324 hummock_time_travel_filter_out_objects_list_version_batch_size: 10,
325 hummock_time_travel_filter_out_objects_list_delta_batch_size: 1000,
326 min_delta_log_num_for_hummock_version_checkpoint: 1,
327 min_sst_retention_time_sec: 3600 * 24 * 7,
328 full_gc_interval_sec: 3600 * 24 * 7,
329 full_gc_object_limit: 100_000,
330 gc_history_retention_time_sec: 3600 * 24 * 7,
331 max_inflight_time_travel_query: 1000,
332 enable_committed_sst_sanity_check: false,
333 periodic_compaction_interval_sec: 60,
334 node_num_monitor_interval_sec: 10,
335 protect_drop_table_with_incoming_sink: false,
336 prometheus_endpoint: None,
337 prometheus_selector: None,
338 vpc_id: None,
339 security_group_id: None,
340 privatelink_endpoint_default_tags: None,
341 periodic_space_reclaim_compaction_interval_sec: 60,
342 telemetry_enabled: false,
343 periodic_ttl_reclaim_compaction_interval_sec: 60,
344 periodic_tombstone_reclaim_compaction_interval_sec: 60,
345 periodic_scheduling_compaction_group_split_interval_sec: 60,
346 compact_task_table_size_partition_threshold_low: 128 * 1024 * 1024,
347 compact_task_table_size_partition_threshold_high: 512 * 1024 * 1024,
348 table_high_write_throughput_threshold: 128 * 1024 * 1024,
349 table_low_write_throughput_threshold: 64 * 1024 * 1024,
350 do_not_config_object_storage_lifecycle: true,
351 partition_vnode_count: 32,
352 compaction_task_max_heartbeat_interval_secs: 0,
353 compaction_task_max_progress_interval_secs: 1,
354 compaction_config: None,
355 hybrid_partition_node_count: 4,
356 event_log_enabled: false,
357 event_log_channel_max_size: 1,
358 advertise_addr: "".to_owned(),
359 cached_traces_num: 1,
360 cached_traces_memory_limit_bytes: usize::MAX,
361 enable_trivial_move: true,
362 enable_check_task_level_overlap: true,
363 enable_dropped_column_reclaim: false,
364 object_store_config: ObjectStoreConfig::default(),
365 max_trivial_move_task_count_per_loop: 256,
366 max_get_task_probe_times: 5,
367 secret_store_private_key: Some(
368 hex::decode("0123456789abcdef0123456789abcdef").unwrap(),
369 ),
370 temp_secret_file_dir: "./secrets".to_owned(),
371 actor_cnt_per_worker_parallelism_hard_limit: usize::MAX,
372 actor_cnt_per_worker_parallelism_soft_limit: usize::MAX,
373 split_group_size_ratio: 0.9,
374 table_stat_high_write_throughput_ratio_for_split: 0.5,
375 table_stat_low_write_throughput_ratio_for_merge: 0.7,
376 table_stat_throuput_window_seconds_for_split: 60,
377 table_stat_throuput_window_seconds_for_merge: 240,
378 periodic_scheduling_compaction_group_merge_interval_sec: 60 * 10,
379 compaction_group_merge_dimension_threshold: 1.2,
380 license_key_path: None,
381 compute_client_config: RpcClientConfig::default(),
382 stream_client_config: RpcClientConfig::default(),
383 frontend_client_config: RpcClientConfig::default(),
384 redact_sql_option_keywords: Arc::new(Default::default()),
385 cdc_table_split_init_sleep_interval_splits: 1000,
386 cdc_table_split_init_sleep_duration_millis: 10,
387 cdc_table_split_init_insert_batch_size: 1000,
388 enable_legacy_table_migration: true,
389 refresh_scheduler_interval_sec: 60,
390 }
391 }
392}
393
394impl MetaSrvEnv {
395 pub async fn new(
396 opts: MetaOpts,
397 mut init_system_params: SystemParams,
398 init_session_config: SessionConfig,
399 meta_store_impl: SqlMetaStore,
400 ) -> MetaResult<Self> {
401 let idle_manager = Arc::new(IdleManager::new(opts.max_idle_ms));
402 let stream_client_pool =
403 Arc::new(StreamClientPool::new(1, opts.stream_client_config.clone())); let frontend_client_pool = Arc::new(FrontendClientPool::new(
405 1,
406 opts.frontend_client_config.clone(),
407 ));
408 let event_log_manager = Arc::new(start_event_log_manager(
409 opts.event_log_enabled,
410 opts.event_log_channel_max_size,
411 ));
412
413 if opts.license_key_path.is_some()
416 && init_system_params.license_key
417 != system_param::default::license_key_opt().map(Into::into)
418 {
419 bail!(
420 "argument `--license-key-path` (or env var `RW_LICENSE_KEY_PATH`) and \
421 system parameter `license_key` (or env var `RW_LICENSE_KEY`) may not \
422 be set at the same time"
423 );
424 }
425
426 let cluster_first_launch = meta_store_impl.up().await.context(
427 "Failed to initialize the meta store, \
428 this may happen if there's existing metadata incompatible with the current version of RisingWave, \
429 e.g., downgrading from a newer release or a nightly build to an older one. \
430 For a single-node deployment, you may want to reset all data by deleting the data directory, \
431 typically located at `~/.risingwave`.",
432 )?;
433
434 let notification_manager =
435 Arc::new(NotificationManager::new(meta_store_impl.clone()).await);
436 let cluster_id = Cluster::find()
437 .one(&meta_store_impl.conn)
438 .await?
439 .map(|c| c.cluster_id.to_string().into())
440 .unwrap();
441
442 init_system_params.use_new_object_prefix_strategy = Some(cluster_first_launch);
448
449 let system_param_controller = Arc::new(
450 SystemParamsController::new(
451 meta_store_impl.clone(),
452 notification_manager.clone(),
453 init_system_params,
454 )
455 .await?,
456 );
457 let session_param_controller = Arc::new(
458 SessionParamsController::new(
459 meta_store_impl.clone(),
460 notification_manager.clone(),
461 init_session_config,
462 )
463 .await?,
464 );
465 let cdc_table_backfill_tracker = CdcTableBackfillTracker::new(meta_store_impl.clone())
466 .await?
467 .into();
468 Ok(Self {
469 id_gen_manager_impl: Arc::new(SqlIdGeneratorManager::new(&meta_store_impl.conn).await?),
470 system_param_manager_impl: system_param_controller,
471 session_param_manager_impl: session_param_controller,
472 meta_store_impl: meta_store_impl.clone(),
473 shared_actor_info: SharedActorInfos::new(notification_manager.clone()),
474 notification_manager,
475 stream_client_pool,
476 frontend_client_pool,
477 idle_manager,
478 event_log_manager,
479 cluster_id,
480 hummock_seq: Arc::new(SequenceGenerator::new(meta_store_impl.conn.clone())),
481 opts: opts.into(),
482 await_tree_reg: await_tree::Registry::new(Default::default()),
484 cdc_table_backfill_tracker,
485 actor_id_generator: Arc::new(AtomicU32::new(0)),
486 })
487 }
488
489 pub fn meta_store(&self) -> SqlMetaStore {
490 self.meta_store_impl.clone()
491 }
492
493 pub fn meta_store_ref(&self) -> &SqlMetaStore {
494 &self.meta_store_impl
495 }
496
497 pub fn id_gen_manager(&self) -> &SqlIdGeneratorManagerRef {
498 &self.id_gen_manager_impl
499 }
500
501 pub fn notification_manager_ref(&self) -> NotificationManagerRef {
502 self.notification_manager.clone()
503 }
504
505 pub fn notification_manager(&self) -> &NotificationManager {
506 self.notification_manager.deref()
507 }
508
509 pub fn idle_manager_ref(&self) -> IdleManagerRef {
510 self.idle_manager.clone()
511 }
512
513 pub fn idle_manager(&self) -> &IdleManager {
514 self.idle_manager.deref()
515 }
516
517 pub fn actor_id_generator(&self) -> &AtomicU32 {
518 self.actor_id_generator.deref()
519 }
520
521 pub async fn system_params_reader(&self) -> SystemParamsReader {
522 self.system_param_manager_impl.get_params().await
523 }
524
525 pub fn system_params_manager_impl_ref(&self) -> SystemParamsControllerRef {
526 self.system_param_manager_impl.clone()
527 }
528
529 pub fn session_params_manager_impl_ref(&self) -> SessionParamsControllerRef {
530 self.session_param_manager_impl.clone()
531 }
532
533 pub fn stream_client_pool_ref(&self) -> StreamClientPoolRef {
534 self.stream_client_pool.clone()
535 }
536
537 pub fn stream_client_pool(&self) -> &StreamClientPool {
538 self.stream_client_pool.deref()
539 }
540
541 pub fn frontend_client_pool(&self) -> &FrontendClientPool {
542 self.frontend_client_pool.deref()
543 }
544
545 pub fn cluster_id(&self) -> &ClusterId {
546 &self.cluster_id
547 }
548
549 pub fn event_log_manager_ref(&self) -> EventLogManagerRef {
550 self.event_log_manager.clone()
551 }
552
553 pub fn await_tree_reg(&self) -> &await_tree::Registry {
554 &self.await_tree_reg
555 }
556
557 pub fn shared_actor_infos(&self) -> &SharedActorInfos {
558 &self.shared_actor_info
559 }
560
561 pub fn cdc_table_backfill_tracker(&self) -> CdcTableBackfillTrackerRef {
562 self.cdc_table_backfill_tracker.clone()
563 }
564}
565
566#[cfg(any(test, feature = "test"))]
567impl MetaSrvEnv {
568 pub async fn for_test() -> Self {
570 Self::for_test_opts(MetaOpts::test(false), |_| ()).await
571 }
572
573 pub async fn for_test_opts(
574 opts: MetaOpts,
575 on_test_system_params: impl FnOnce(&mut risingwave_pb::meta::PbSystemParams),
576 ) -> Self {
577 let mut system_params = risingwave_common::system_param::system_params_for_test();
578 on_test_system_params(&mut system_params);
579 Self::new(
580 opts,
581 system_params,
582 Default::default(),
583 SqlMetaStore::for_test().await,
584 )
585 .await
586 .unwrap()
587 }
588}