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, SessionInitConfig,
23};
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::barrier::SharedActorInfos;
36use crate::controller::SqlMetaStore;
37use crate::controller::id::{
38 IdGeneratorManager as SqlIdGeneratorManager, IdGeneratorManagerRef as SqlIdGeneratorManagerRef,
39};
40use crate::controller::session_params::{SessionParamsController, SessionParamsControllerRef};
41use crate::controller::system_param::{SystemParamsController, SystemParamsControllerRef};
42use crate::hummock::sequence::SequenceGenerator;
43use crate::manager::event_log::{EventLogManagerRef, start_event_log_manager};
44use crate::manager::{IdleManager, IdleManagerRef, NotificationManager, NotificationManagerRef};
45use crate::model::ClusterId;
46
47#[derive(Clone)]
50pub struct MetaSrvEnv {
51 id_gen_manager_impl: SqlIdGeneratorManagerRef,
53
54 system_param_manager_impl: SystemParamsControllerRef,
56
57 session_param_manager_impl: SessionParamsControllerRef,
59
60 meta_store_impl: SqlMetaStore,
62
63 notification_manager: NotificationManagerRef,
65
66 pub shared_actor_info: SharedActorInfos,
67
68 stream_client_pool: StreamClientPoolRef,
70
71 frontend_client_pool: FrontendClientPoolRef,
73
74 idle_manager: IdleManagerRef,
76
77 event_log_manager: EventLogManagerRef,
78
79 cluster_id: ClusterId,
81
82 pub hummock_seq: Arc<SequenceGenerator>,
83
84 await_tree_reg: await_tree::Registry,
86
87 pub opts: Arc<MetaOpts>,
89
90 actor_id_generator: Arc<AtomicU32>,
91}
92
93#[derive(Clone, serde::Serialize)]
95pub struct MetaOpts {
96 pub enable_recovery: bool,
99 pub clean_all_foreground_jobs_on_recovery: bool,
101 pub disable_automatic_parallelism_control: bool,
103 pub parallelism_control_batch_size: usize,
105 pub parallelism_control_trigger_period_sec: u64,
107 pub parallelism_control_trigger_first_delay_sec: u64,
109 pub in_flight_barrier_nums: usize,
111 pub snapshot_backfill_finish_max_lagged_barriers: usize,
113 pub snapshot_backfill_barrier_amplification_factor: usize,
115 pub max_idle_ms: u64,
118 pub compaction_deterministic_test: bool,
120 pub default_parallelism: DefaultParallelism,
122
123 pub vacuum_interval_sec: u64,
126 pub vacuum_spin_interval_ms: u64,
129 pub iceberg_gc_interval_sec: u64,
131 pub iceberg_compaction_report_timeout_sec: u64,
133 pub iceberg_compaction_config_refresh_interval_sec: u64,
135 pub time_travel_vacuum_interval_sec: u64,
136 pub time_travel_vacuum_max_version_count: Option<u32>,
137 pub hummock_version_checkpoint_interval_sec: u64,
139 pub enable_hummock_data_archive: bool,
140 pub checkpoint_compression_algorithm: risingwave_common::config::CheckpointCompression,
142 pub checkpoint_read_chunk_size: usize,
144 pub checkpoint_read_max_in_flight_chunks: usize,
146 pub hummock_time_travel_snapshot_interval: u64,
147 pub hummock_time_travel_sst_info_fetch_batch_size: usize,
148 pub hummock_time_travel_sst_info_insert_batch_size: usize,
149 pub hummock_time_travel_epoch_version_insert_batch_size: usize,
150 pub hummock_time_travel_delta_fetch_batch_size: usize,
151 pub hummock_gc_history_insert_batch_size: usize,
152 pub hummock_time_travel_filter_out_objects_batch_size: usize,
153 pub hummock_time_travel_filter_out_objects_v1: bool,
154 pub hummock_time_travel_filter_out_objects_list_version_batch_size: usize,
155 pub hummock_time_travel_filter_out_objects_list_delta_batch_size: usize,
156 pub min_delta_log_num_for_hummock_version_checkpoint: u64,
161 pub min_sst_retention_time_sec: u64,
164 pub full_gc_interval_sec: u64,
166 pub full_gc_object_limit: u64,
168 pub gc_history_retention_time_sec: u64,
170 pub max_inflight_time_travel_query: u64,
172 pub enable_committed_sst_sanity_check: bool,
174 pub periodic_compaction_interval_sec: u64,
176 pub node_num_monitor_interval_sec: u64,
178 pub prometheus_endpoint: Option<String>,
184
185 pub prometheus_selector: Option<String>,
187
188 pub vpc_id: Option<String>,
190
191 pub security_group_id: Option<String>,
193
194 pub privatelink_endpoint_default_tags: Option<Vec<(String, String)>>,
198
199 pub periodic_space_reclaim_compaction_interval_sec: u64,
201
202 pub telemetry_enabled: bool,
204 pub periodic_ttl_reclaim_compaction_interval_sec: u64,
206
207 pub periodic_tombstone_reclaim_compaction_interval_sec: u64,
209
210 pub periodic_scheduling_compaction_group_split_interval_sec: u64,
212 pub enable_compaction_group_normalize: bool,
214 pub max_normalize_splits_per_round: u64,
216
217 pub do_not_config_object_storage_lifecycle: bool,
219
220 pub partition_vnode_count: u32,
221
222 pub table_high_write_throughput_threshold: u64,
224 pub table_low_write_throughput_threshold: u64,
226
227 pub compaction_task_max_heartbeat_interval_secs: u64,
228 pub compaction_task_max_progress_interval_secs: u64,
229 pub compaction_task_id_refill_capacity: u32,
230 pub compaction_config: Option<CompactionConfig>,
231
232 pub hybrid_partition_node_count: u32,
240
241 pub event_log_enabled: bool,
242 pub event_log_channel_max_size: u32,
243 pub advertise_addr: String,
244 pub cached_traces_num: u32,
247 pub cached_traces_memory_limit_bytes: usize,
250
251 pub enable_trivial_move: bool,
253
254 pub enable_check_task_level_overlap: bool,
256 pub enable_dropped_column_reclaim: bool,
257
258 pub split_group_size_ratio: f64,
260
261 pub refresh_scheduler_interval_sec: u64,
263
264 pub table_stat_high_write_throughput_ratio_for_split: f64,
266
267 pub table_stat_low_write_throughput_ratio_for_merge: f64,
269
270 pub table_stat_throuput_window_seconds_for_split: usize,
272
273 pub table_stat_throuput_window_seconds_for_merge: usize,
275
276 pub object_store_config: ObjectStoreConfig,
278
279 pub max_trivial_move_task_count_per_loop: usize,
281
282 pub max_get_task_probe_times: usize,
284
285 pub compact_task_table_size_partition_threshold_low: u64,
286 pub compact_task_table_size_partition_threshold_high: u64,
287
288 pub periodic_scheduling_compaction_group_merge_interval_sec: u64,
289
290 pub compaction_group_merge_dimension_threshold: f64,
291
292 pub secret_store_private_key: Option<Vec<u8>>,
294 pub temp_secret_file_dir: String,
296
297 pub actor_cnt_per_worker_parallelism_hard_limit: usize,
299 pub actor_cnt_per_worker_parallelism_soft_limit: usize,
300
301 pub table_change_log_insert_batch_size: u64,
302 pub table_change_log_delete_batch_size: u64,
303 pub table_change_log_truncate_interval_sec: u64,
304
305 pub license_key_path: Option<PathBuf>,
306
307 pub compute_client_config: RpcClientConfig,
308 pub stream_client_config: RpcClientConfig,
309 pub frontend_client_config: RpcClientConfig,
310 pub redact_sql_option_keywords: RedactSqlOptionKeywordsRef,
311
312 pub cdc_table_split_init_sleep_interval_splits: u64,
313 pub cdc_table_split_init_sleep_duration_millis: u64,
314 pub cdc_table_split_init_insert_batch_size: u64,
315
316 pub enable_legacy_table_migration: bool,
317 pub pause_on_next_bootstrap_offline: bool,
318 pub serverless_backfill_controller_addr: String,
319}
320
321impl MetaOpts {
322 pub fn test(enable_recovery: bool) -> Self {
324 Self {
325 enable_recovery,
326 clean_all_foreground_jobs_on_recovery: false,
327 disable_automatic_parallelism_control: false,
328 parallelism_control_batch_size: 1,
329 parallelism_control_trigger_period_sec: 10,
330 parallelism_control_trigger_first_delay_sec: 30,
331 in_flight_barrier_nums: 40,
332 snapshot_backfill_finish_max_lagged_barriers: 100,
333 snapshot_backfill_barrier_amplification_factor: 1,
334 max_idle_ms: 0,
335 compaction_deterministic_test: false,
336 default_parallelism: DefaultParallelism::Full,
337 vacuum_interval_sec: 30,
338 time_travel_vacuum_interval_sec: 30,
339 time_travel_vacuum_max_version_count: None,
340 vacuum_spin_interval_ms: 0,
341 iceberg_gc_interval_sec: 3600,
342 iceberg_compaction_report_timeout_sec: 30 * 60,
343 iceberg_compaction_config_refresh_interval_sec: 60,
344 hummock_version_checkpoint_interval_sec: 30,
345 enable_hummock_data_archive: false,
346 checkpoint_compression_algorithm:
347 risingwave_common::config::CheckpointCompression::Zstd,
348 checkpoint_read_chunk_size: 128 * 1024 * 1024,
349 checkpoint_read_max_in_flight_chunks: 4,
350 hummock_time_travel_snapshot_interval: 0,
351 hummock_time_travel_sst_info_fetch_batch_size: 10_000,
352 hummock_time_travel_sst_info_insert_batch_size: 10,
353 hummock_time_travel_epoch_version_insert_batch_size: 1000,
354 hummock_time_travel_delta_fetch_batch_size: 1000,
355 hummock_gc_history_insert_batch_size: 1000,
356 hummock_time_travel_filter_out_objects_batch_size: 1000,
357 hummock_time_travel_filter_out_objects_v1: false,
358 hummock_time_travel_filter_out_objects_list_version_batch_size: 10,
359 hummock_time_travel_filter_out_objects_list_delta_batch_size: 1000,
360 min_delta_log_num_for_hummock_version_checkpoint: 1,
361 min_sst_retention_time_sec: 3600 * 24 * 7,
362 full_gc_interval_sec: 3600 * 24 * 7,
363 full_gc_object_limit: 100_000,
364 gc_history_retention_time_sec: 3600 * 24 * 7,
365 max_inflight_time_travel_query: 1000,
366 enable_committed_sst_sanity_check: false,
367 periodic_compaction_interval_sec: 300,
368 node_num_monitor_interval_sec: 10,
369 prometheus_endpoint: None,
370 prometheus_selector: None,
371 vpc_id: None,
372 security_group_id: None,
373 privatelink_endpoint_default_tags: None,
374 periodic_space_reclaim_compaction_interval_sec: 60,
375 telemetry_enabled: false,
376 periodic_ttl_reclaim_compaction_interval_sec: 60,
377 periodic_tombstone_reclaim_compaction_interval_sec: 60,
378 periodic_scheduling_compaction_group_split_interval_sec: 60,
379 enable_compaction_group_normalize: false,
380 max_normalize_splits_per_round: 4,
381 compact_task_table_size_partition_threshold_low: 128 * 1024 * 1024,
382 compact_task_table_size_partition_threshold_high: 512 * 1024 * 1024,
383 table_high_write_throughput_threshold: 128 * 1024 * 1024,
384 table_low_write_throughput_threshold: 64 * 1024 * 1024,
385 do_not_config_object_storage_lifecycle: true,
386 partition_vnode_count: 32,
387 compaction_task_max_heartbeat_interval_secs: 0,
388 compaction_task_max_progress_interval_secs: 1,
389 compaction_task_id_refill_capacity: 64,
390 compaction_config: None,
391 hybrid_partition_node_count: 4,
392 event_log_enabled: false,
393 event_log_channel_max_size: 1,
394 advertise_addr: "".to_owned(),
395 cached_traces_num: 1,
396 cached_traces_memory_limit_bytes: usize::MAX,
397 enable_trivial_move: true,
398 enable_check_task_level_overlap: true,
399 enable_dropped_column_reclaim: false,
400 object_store_config: ObjectStoreConfig::default(),
401 max_trivial_move_task_count_per_loop: 256,
402 max_get_task_probe_times: 5,
403 secret_store_private_key: Some(
404 hex::decode("0123456789abcdef0123456789abcdef").unwrap(),
405 ),
406 temp_secret_file_dir: "./secrets".to_owned(),
407 actor_cnt_per_worker_parallelism_hard_limit: usize::MAX,
408 actor_cnt_per_worker_parallelism_soft_limit: usize::MAX,
409 split_group_size_ratio: 0.9,
410 table_stat_high_write_throughput_ratio_for_split: 0.5,
411 table_stat_low_write_throughput_ratio_for_merge: 0.7,
412 table_stat_throuput_window_seconds_for_split: 60,
413 table_stat_throuput_window_seconds_for_merge: 240,
414 periodic_scheduling_compaction_group_merge_interval_sec: 60 * 10,
415 compaction_group_merge_dimension_threshold: 1.2,
416 license_key_path: None,
417 compute_client_config: RpcClientConfig::default(),
418 stream_client_config: RpcClientConfig::default(),
419 frontend_client_config: RpcClientConfig::default(),
420 redact_sql_option_keywords: Arc::new(Default::default()),
421 cdc_table_split_init_sleep_interval_splits: 1000,
422 cdc_table_split_init_sleep_duration_millis: 10,
423 cdc_table_split_init_insert_batch_size: 1000,
424 enable_legacy_table_migration: true,
425 refresh_scheduler_interval_sec: 60,
426 pause_on_next_bootstrap_offline: false,
427 serverless_backfill_controller_addr: String::new(),
428 table_change_log_insert_batch_size: 1000,
429 table_change_log_delete_batch_size: 1000,
430 table_change_log_truncate_interval_sec: 600,
431 }
432 }
433}
434
435impl MetaSrvEnv {
436 pub async fn new(
437 opts: MetaOpts,
438 mut init_system_params: SystemParams,
439 session_init: SessionInitConfig,
440 meta_store_impl: SqlMetaStore,
441 ) -> MetaResult<Self> {
442 let idle_manager = Arc::new(IdleManager::new(opts.max_idle_ms));
443 let stream_client_pool =
444 Arc::new(StreamClientPool::new(1, opts.stream_client_config.clone())); let frontend_client_pool = Arc::new(FrontendClientPool::new(
446 1,
447 opts.frontend_client_config.clone(),
448 ));
449 let event_log_manager = Arc::new(start_event_log_manager(
450 opts.event_log_enabled,
451 opts.event_log_channel_max_size,
452 ));
453
454 if opts.license_key_path.is_some()
457 && init_system_params.license_key
458 != system_param::default::license_key_opt().map(Into::into)
459 {
460 bail!(
461 "argument `--license-key-path` (or env var `RW_LICENSE_KEY_PATH`) and \
462 system parameter `license_key` (or env var `RW_LICENSE_KEY`) may not \
463 be set at the same time"
464 );
465 }
466
467 let cluster_first_launch = meta_store_impl.up().await.context(
468 "Failed to initialize the meta store, \
469 this may happen if there's existing metadata incompatible with the current version of RisingWave, \
470 e.g., downgrading from a newer release or a nightly build to an older one. \
471 For a single-node deployment, you may want to reset all data by deleting the data directory, \
472 typically located at `~/.risingwave`.",
473 )?;
474
475 let notification_manager =
476 Arc::new(NotificationManager::new(meta_store_impl.clone()).await);
477 let cluster_id = Cluster::find()
478 .one(&meta_store_impl.conn)
479 .await?
480 .map(|c| c.cluster_id.to_string().into())
481 .unwrap();
482
483 init_system_params.use_new_object_prefix_strategy = Some(cluster_first_launch);
489
490 let system_param_controller = Arc::new(
491 SystemParamsController::new(
492 meta_store_impl.clone(),
493 notification_manager.clone(),
494 init_system_params,
495 )
496 .await?,
497 );
498 let session_param_controller = Arc::new(
499 SessionParamsController::new(
500 meta_store_impl.clone(),
501 notification_manager.clone(),
502 session_init,
503 )
504 .await?,
505 );
506 Ok(Self {
507 id_gen_manager_impl: Arc::new(SqlIdGeneratorManager::new(&meta_store_impl.conn).await?),
508 system_param_manager_impl: system_param_controller,
509 session_param_manager_impl: session_param_controller,
510 meta_store_impl: meta_store_impl.clone(),
511 shared_actor_info: SharedActorInfos::new(notification_manager.clone()),
512 notification_manager,
513 stream_client_pool,
514 frontend_client_pool,
515 idle_manager,
516 event_log_manager,
517 cluster_id,
518 hummock_seq: Arc::new(SequenceGenerator::new(meta_store_impl.conn.clone())),
519 opts: opts.into(),
520 await_tree_reg: await_tree::Registry::new(Default::default()),
522 actor_id_generator: Arc::new(AtomicU32::new(0)),
523 })
524 }
525
526 pub fn meta_store(&self) -> SqlMetaStore {
527 self.meta_store_impl.clone()
528 }
529
530 pub fn meta_store_ref(&self) -> &SqlMetaStore {
531 &self.meta_store_impl
532 }
533
534 pub fn id_gen_manager(&self) -> &SqlIdGeneratorManagerRef {
535 &self.id_gen_manager_impl
536 }
537
538 pub fn notification_manager_ref(&self) -> NotificationManagerRef {
539 self.notification_manager.clone()
540 }
541
542 pub fn notification_manager(&self) -> &NotificationManager {
543 self.notification_manager.deref()
544 }
545
546 pub fn idle_manager_ref(&self) -> IdleManagerRef {
547 self.idle_manager.clone()
548 }
549
550 pub fn idle_manager(&self) -> &IdleManager {
551 self.idle_manager.deref()
552 }
553
554 pub fn actor_id_generator(&self) -> &AtomicU32 {
555 self.actor_id_generator.deref()
556 }
557
558 pub async fn system_params_reader(&self) -> SystemParamsReader {
559 self.system_param_manager_impl.get_params().await
560 }
561
562 pub fn system_params_manager_impl_ref(&self) -> SystemParamsControllerRef {
563 self.system_param_manager_impl.clone()
564 }
565
566 pub fn session_params_manager_impl_ref(&self) -> SessionParamsControllerRef {
567 self.session_param_manager_impl.clone()
568 }
569
570 pub fn stream_client_pool_ref(&self) -> StreamClientPoolRef {
571 self.stream_client_pool.clone()
572 }
573
574 pub fn stream_client_pool(&self) -> &StreamClientPool {
575 self.stream_client_pool.deref()
576 }
577
578 pub fn frontend_client_pool(&self) -> &FrontendClientPool {
579 self.frontend_client_pool.deref()
580 }
581
582 pub fn cluster_id(&self) -> &ClusterId {
583 &self.cluster_id
584 }
585
586 pub fn event_log_manager_ref(&self) -> EventLogManagerRef {
587 self.event_log_manager.clone()
588 }
589
590 pub fn await_tree_reg(&self) -> &await_tree::Registry {
591 &self.await_tree_reg
592 }
593
594 pub fn shared_actor_infos(&self) -> &SharedActorInfos {
595 &self.shared_actor_info
596 }
597}
598
599#[cfg(any(test, feature = "test"))]
600impl MetaSrvEnv {
601 pub async fn for_test() -> Self {
603 Self::for_test_opts(MetaOpts::test(false), |_| ()).await
604 }
605
606 pub async fn for_test_opts(
607 opts: MetaOpts,
608 on_test_system_params: impl FnOnce(&mut risingwave_pb::meta::PbSystemParams),
609 ) -> Self {
610 let mut system_params = risingwave_common::system_param::system_params_for_test();
611 on_test_system_params(&mut system_params);
612 Self::new(
613 opts,
614 system_params,
615 Default::default(),
616 SqlMetaStore::for_test().await,
617 )
618 .await
619 .unwrap()
620 }
621}