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