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 hummock_version_checkpoint_interval_sec: u64,
129 pub enable_hummock_data_archive: bool,
130 pub hummock_time_travel_snapshot_interval: u64,
131 pub hummock_time_travel_sst_info_fetch_batch_size: usize,
132 pub hummock_time_travel_sst_info_insert_batch_size: usize,
133 pub hummock_time_travel_epoch_version_insert_batch_size: usize,
134 pub hummock_gc_history_insert_batch_size: usize,
135 pub hummock_time_travel_filter_out_objects_batch_size: usize,
136 pub hummock_time_travel_filter_out_objects_v1: bool,
137 pub hummock_time_travel_filter_out_objects_list_version_batch_size: usize,
138 pub hummock_time_travel_filter_out_objects_list_delta_batch_size: usize,
139 pub min_delta_log_num_for_hummock_version_checkpoint: u64,
144 pub min_sst_retention_time_sec: u64,
147 pub full_gc_interval_sec: u64,
149 pub full_gc_object_limit: u64,
151 pub gc_history_retention_time_sec: u64,
153 pub max_inflight_time_travel_query: u64,
155 pub enable_committed_sst_sanity_check: bool,
157 pub periodic_compaction_interval_sec: u64,
159 pub node_num_monitor_interval_sec: u64,
161 pub protect_drop_table_with_incoming_sink: bool,
163 pub prometheus_endpoint: Option<String>,
169
170 pub prometheus_selector: Option<String>,
172
173 pub vpc_id: Option<String>,
175
176 pub security_group_id: Option<String>,
178
179 pub privatelink_endpoint_default_tags: Option<Vec<(String, String)>>,
183
184 pub periodic_space_reclaim_compaction_interval_sec: u64,
186
187 pub telemetry_enabled: bool,
189 pub periodic_ttl_reclaim_compaction_interval_sec: u64,
191
192 pub periodic_tombstone_reclaim_compaction_interval_sec: u64,
194
195 pub periodic_scheduling_compaction_group_split_interval_sec: u64,
197
198 pub do_not_config_object_storage_lifecycle: bool,
200
201 pub partition_vnode_count: u32,
202
203 pub table_high_write_throughput_threshold: u64,
205 pub table_low_write_throughput_threshold: u64,
207
208 pub compaction_task_max_heartbeat_interval_secs: u64,
209 pub compaction_task_max_progress_interval_secs: u64,
210 pub compaction_config: Option<CompactionConfig>,
211
212 pub hybrid_partition_node_count: u32,
220
221 pub event_log_enabled: bool,
222 pub event_log_channel_max_size: u32,
223 pub advertise_addr: String,
224 pub cached_traces_num: u32,
227 pub cached_traces_memory_limit_bytes: usize,
230
231 pub enable_trivial_move: bool,
233
234 pub enable_check_task_level_overlap: bool,
236 pub enable_dropped_column_reclaim: bool,
237
238 pub split_group_size_ratio: f64,
240
241 pub refresh_scheduler_interval_sec: u64,
243
244 pub table_stat_high_write_throughput_ratio_for_split: f64,
246
247 pub table_stat_low_write_throughput_ratio_for_merge: f64,
249
250 pub table_stat_throuput_window_seconds_for_split: usize,
252
253 pub table_stat_throuput_window_seconds_for_merge: usize,
255
256 pub object_store_config: ObjectStoreConfig,
258
259 pub max_trivial_move_task_count_per_loop: usize,
261
262 pub max_get_task_probe_times: usize,
264
265 pub compact_task_table_size_partition_threshold_low: u64,
266 pub compact_task_table_size_partition_threshold_high: u64,
267
268 pub periodic_scheduling_compaction_group_merge_interval_sec: u64,
269
270 pub compaction_group_merge_dimension_threshold: f64,
271
272 pub secret_store_private_key: Option<Vec<u8>>,
274 pub temp_secret_file_dir: String,
276
277 pub actor_cnt_per_worker_parallelism_hard_limit: usize,
279 pub actor_cnt_per_worker_parallelism_soft_limit: usize,
280
281 pub license_key_path: Option<PathBuf>,
282
283 pub compute_client_config: RpcClientConfig,
284 pub stream_client_config: RpcClientConfig,
285 pub frontend_client_config: RpcClientConfig,
286 pub redact_sql_option_keywords: RedactSqlOptionKeywordsRef,
287
288 pub cdc_table_split_init_sleep_interval_splits: u64,
289 pub cdc_table_split_init_sleep_duration_millis: u64,
290 pub cdc_table_split_init_insert_batch_size: u64,
291
292 pub enable_legacy_table_migration: bool,
293 pub pause_on_next_bootstrap_offline: bool,
294}
295
296impl MetaOpts {
297 pub fn test(enable_recovery: bool) -> Self {
299 Self {
300 enable_recovery,
301 disable_automatic_parallelism_control: false,
302 parallelism_control_batch_size: 1,
303 parallelism_control_trigger_period_sec: 10,
304 parallelism_control_trigger_first_delay_sec: 30,
305 in_flight_barrier_nums: 40,
306 max_idle_ms: 0,
307 compaction_deterministic_test: false,
308 default_parallelism: DefaultParallelism::Full,
309 vacuum_interval_sec: 30,
310 time_travel_vacuum_interval_sec: 30,
311 vacuum_spin_interval_ms: 0,
312 iceberg_gc_interval_sec: 3600,
313 hummock_version_checkpoint_interval_sec: 30,
314 enable_hummock_data_archive: false,
315 hummock_time_travel_snapshot_interval: 0,
316 hummock_time_travel_sst_info_fetch_batch_size: 10_000,
317 hummock_time_travel_sst_info_insert_batch_size: 10,
318 hummock_time_travel_epoch_version_insert_batch_size: 1000,
319 hummock_gc_history_insert_batch_size: 1000,
320 hummock_time_travel_filter_out_objects_batch_size: 1000,
321 hummock_time_travel_filter_out_objects_v1: false,
322 hummock_time_travel_filter_out_objects_list_version_batch_size: 10,
323 hummock_time_travel_filter_out_objects_list_delta_batch_size: 1000,
324 min_delta_log_num_for_hummock_version_checkpoint: 1,
325 min_sst_retention_time_sec: 3600 * 24 * 7,
326 full_gc_interval_sec: 3600 * 24 * 7,
327 full_gc_object_limit: 100_000,
328 gc_history_retention_time_sec: 3600 * 24 * 7,
329 max_inflight_time_travel_query: 1000,
330 enable_committed_sst_sanity_check: false,
331 periodic_compaction_interval_sec: 60,
332 node_num_monitor_interval_sec: 10,
333 protect_drop_table_with_incoming_sink: false,
334 prometheus_endpoint: None,
335 prometheus_selector: None,
336 vpc_id: None,
337 security_group_id: None,
338 privatelink_endpoint_default_tags: None,
339 periodic_space_reclaim_compaction_interval_sec: 60,
340 telemetry_enabled: false,
341 periodic_ttl_reclaim_compaction_interval_sec: 60,
342 periodic_tombstone_reclaim_compaction_interval_sec: 60,
343 periodic_scheduling_compaction_group_split_interval_sec: 60,
344 compact_task_table_size_partition_threshold_low: 128 * 1024 * 1024,
345 compact_task_table_size_partition_threshold_high: 512 * 1024 * 1024,
346 table_high_write_throughput_threshold: 128 * 1024 * 1024,
347 table_low_write_throughput_threshold: 64 * 1024 * 1024,
348 do_not_config_object_storage_lifecycle: true,
349 partition_vnode_count: 32,
350 compaction_task_max_heartbeat_interval_secs: 0,
351 compaction_task_max_progress_interval_secs: 1,
352 compaction_config: None,
353 hybrid_partition_node_count: 4,
354 event_log_enabled: false,
355 event_log_channel_max_size: 1,
356 advertise_addr: "".to_owned(),
357 cached_traces_num: 1,
358 cached_traces_memory_limit_bytes: usize::MAX,
359 enable_trivial_move: true,
360 enable_check_task_level_overlap: true,
361 enable_dropped_column_reclaim: false,
362 object_store_config: ObjectStoreConfig::default(),
363 max_trivial_move_task_count_per_loop: 256,
364 max_get_task_probe_times: 5,
365 secret_store_private_key: Some(
366 hex::decode("0123456789abcdef0123456789abcdef").unwrap(),
367 ),
368 temp_secret_file_dir: "./secrets".to_owned(),
369 actor_cnt_per_worker_parallelism_hard_limit: usize::MAX,
370 actor_cnt_per_worker_parallelism_soft_limit: usize::MAX,
371 split_group_size_ratio: 0.9,
372 table_stat_high_write_throughput_ratio_for_split: 0.5,
373 table_stat_low_write_throughput_ratio_for_merge: 0.7,
374 table_stat_throuput_window_seconds_for_split: 60,
375 table_stat_throuput_window_seconds_for_merge: 240,
376 periodic_scheduling_compaction_group_merge_interval_sec: 60 * 10,
377 compaction_group_merge_dimension_threshold: 1.2,
378 license_key_path: None,
379 compute_client_config: RpcClientConfig::default(),
380 stream_client_config: RpcClientConfig::default(),
381 frontend_client_config: RpcClientConfig::default(),
382 redact_sql_option_keywords: Arc::new(Default::default()),
383 cdc_table_split_init_sleep_interval_splits: 1000,
384 cdc_table_split_init_sleep_duration_millis: 10,
385 cdc_table_split_init_insert_batch_size: 1000,
386 enable_legacy_table_migration: true,
387 refresh_scheduler_interval_sec: 60,
388 pause_on_next_bootstrap_offline: false,
389 }
390 }
391}
392
393impl MetaSrvEnv {
394 pub async fn new(
395 opts: MetaOpts,
396 mut init_system_params: SystemParams,
397 init_session_config: SessionConfig,
398 meta_store_impl: SqlMetaStore,
399 ) -> MetaResult<Self> {
400 let idle_manager = Arc::new(IdleManager::new(opts.max_idle_ms));
401 let stream_client_pool =
402 Arc::new(StreamClientPool::new(1, opts.stream_client_config.clone())); let frontend_client_pool = Arc::new(FrontendClientPool::new(
404 1,
405 opts.frontend_client_config.clone(),
406 ));
407 let event_log_manager = Arc::new(start_event_log_manager(
408 opts.event_log_enabled,
409 opts.event_log_channel_max_size,
410 ));
411
412 if opts.license_key_path.is_some()
415 && init_system_params.license_key
416 != system_param::default::license_key_opt().map(Into::into)
417 {
418 bail!(
419 "argument `--license-key-path` (or env var `RW_LICENSE_KEY_PATH`) and \
420 system parameter `license_key` (or env var `RW_LICENSE_KEY`) may not \
421 be set at the same time"
422 );
423 }
424
425 let cluster_first_launch = meta_store_impl.up().await.context(
426 "Failed to initialize the meta store, \
427 this may happen if there's existing metadata incompatible with the current version of RisingWave, \
428 e.g., downgrading from a newer release or a nightly build to an older one. \
429 For a single-node deployment, you may want to reset all data by deleting the data directory, \
430 typically located at `~/.risingwave`.",
431 )?;
432
433 let notification_manager =
434 Arc::new(NotificationManager::new(meta_store_impl.clone()).await);
435 let cluster_id = Cluster::find()
436 .one(&meta_store_impl.conn)
437 .await?
438 .map(|c| c.cluster_id.to_string().into())
439 .unwrap();
440
441 init_system_params.use_new_object_prefix_strategy = Some(cluster_first_launch);
447
448 let system_param_controller = Arc::new(
449 SystemParamsController::new(
450 meta_store_impl.clone(),
451 notification_manager.clone(),
452 init_system_params,
453 )
454 .await?,
455 );
456 let session_param_controller = Arc::new(
457 SessionParamsController::new(
458 meta_store_impl.clone(),
459 notification_manager.clone(),
460 init_session_config,
461 )
462 .await?,
463 );
464 Ok(Self {
465 id_gen_manager_impl: Arc::new(SqlIdGeneratorManager::new(&meta_store_impl.conn).await?),
466 system_param_manager_impl: system_param_controller,
467 session_param_manager_impl: session_param_controller,
468 meta_store_impl: meta_store_impl.clone(),
469 shared_actor_info: SharedActorInfos::new(notification_manager.clone()),
470 notification_manager,
471 stream_client_pool,
472 frontend_client_pool,
473 idle_manager,
474 event_log_manager,
475 cluster_id,
476 hummock_seq: Arc::new(SequenceGenerator::new(meta_store_impl.conn.clone())),
477 opts: opts.into(),
478 await_tree_reg: await_tree::Registry::new(Default::default()),
480 actor_id_generator: Arc::new(AtomicU32::new(0)),
481 })
482 }
483
484 pub fn meta_store(&self) -> SqlMetaStore {
485 self.meta_store_impl.clone()
486 }
487
488 pub fn meta_store_ref(&self) -> &SqlMetaStore {
489 &self.meta_store_impl
490 }
491
492 pub fn id_gen_manager(&self) -> &SqlIdGeneratorManagerRef {
493 &self.id_gen_manager_impl
494 }
495
496 pub fn notification_manager_ref(&self) -> NotificationManagerRef {
497 self.notification_manager.clone()
498 }
499
500 pub fn notification_manager(&self) -> &NotificationManager {
501 self.notification_manager.deref()
502 }
503
504 pub fn idle_manager_ref(&self) -> IdleManagerRef {
505 self.idle_manager.clone()
506 }
507
508 pub fn idle_manager(&self) -> &IdleManager {
509 self.idle_manager.deref()
510 }
511
512 pub fn actor_id_generator(&self) -> &AtomicU32 {
513 self.actor_id_generator.deref()
514 }
515
516 pub async fn system_params_reader(&self) -> SystemParamsReader {
517 self.system_param_manager_impl.get_params().await
518 }
519
520 pub fn system_params_manager_impl_ref(&self) -> SystemParamsControllerRef {
521 self.system_param_manager_impl.clone()
522 }
523
524 pub fn session_params_manager_impl_ref(&self) -> SessionParamsControllerRef {
525 self.session_param_manager_impl.clone()
526 }
527
528 pub fn stream_client_pool_ref(&self) -> StreamClientPoolRef {
529 self.stream_client_pool.clone()
530 }
531
532 pub fn stream_client_pool(&self) -> &StreamClientPool {
533 self.stream_client_pool.deref()
534 }
535
536 pub fn frontend_client_pool(&self) -> &FrontendClientPool {
537 self.frontend_client_pool.deref()
538 }
539
540 pub fn cluster_id(&self) -> &ClusterId {
541 &self.cluster_id
542 }
543
544 pub fn event_log_manager_ref(&self) -> EventLogManagerRef {
545 self.event_log_manager.clone()
546 }
547
548 pub fn await_tree_reg(&self) -> &await_tree::Registry {
549 &self.await_tree_reg
550 }
551
552 pub fn shared_actor_infos(&self) -> &SharedActorInfos {
553 &self.shared_actor_info
554 }
555}
556
557#[cfg(any(test, feature = "test"))]
558impl MetaSrvEnv {
559 pub async fn for_test() -> Self {
561 Self::for_test_opts(MetaOpts::test(false), |_| ()).await
562 }
563
564 pub async fn for_test_opts(
565 opts: MetaOpts,
566 on_test_system_params: impl FnOnce(&mut risingwave_pb::meta::PbSystemParams),
567 ) -> Self {
568 let mut system_params = risingwave_common::system_param::system_params_for_test();
569 on_test_system_params(&mut system_params);
570 Self::new(
571 opts,
572 system_params,
573 Default::default(),
574 SqlMetaStore::for_test().await,
575 )
576 .await
577 .unwrap()
578 }
579}