1use 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#[derive(Clone)]
49pub struct MetaSrvEnv {
50 id_gen_manager_impl: SqlIdGeneratorManagerRef,
52
53 system_param_manager_impl: SystemParamsControllerRef,
55
56 session_param_manager_impl: SessionParamsControllerRef,
58
59 meta_store_impl: SqlMetaStore,
61
62 notification_manager: NotificationManagerRef,
64
65 stream_client_pool: StreamClientPoolRef,
67
68 frontend_client_pool: FrontendClientPoolRef,
70
71 idle_manager: IdleManagerRef,
73
74 event_log_manager: EventLogManagerRef,
75
76 cluster_id: ClusterId,
78
79 pub hummock_seq: Arc<SequenceGenerator>,
80
81 await_tree_reg: await_tree::Registry,
83
84 pub opts: Arc<MetaOpts>,
86}
87
88#[derive(Clone, serde::Serialize)]
90pub struct MetaOpts {
91 pub enable_recovery: bool,
94 pub disable_automatic_parallelism_control: bool,
96 pub parallelism_control_batch_size: usize,
98 pub parallelism_control_trigger_period_sec: u64,
100 pub parallelism_control_trigger_first_delay_sec: u64,
102 pub in_flight_barrier_nums: usize,
104 pub max_idle_ms: u64,
107 pub compaction_deterministic_test: bool,
109 pub default_parallelism: DefaultParallelism,
111
112 pub vacuum_interval_sec: u64,
115 pub vacuum_spin_interval_ms: u64,
118 pub time_travel_vacuum_interval_sec: u64,
119 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 pub min_delta_log_num_for_hummock_version_checkpoint: u64,
136 pub min_sst_retention_time_sec: u64,
139 pub full_gc_interval_sec: u64,
141 pub full_gc_object_limit: u64,
143 pub gc_history_retention_time_sec: u64,
145 pub max_inflight_time_travel_query: u64,
147 pub enable_committed_sst_sanity_check: bool,
149 pub periodic_compaction_interval_sec: u64,
151 pub node_num_monitor_interval_sec: u64,
153
154 pub prometheus_endpoint: Option<String>,
160
161 pub prometheus_selector: Option<String>,
163
164 pub vpc_id: Option<String>,
166
167 pub security_group_id: Option<String>,
169
170 pub privatelink_endpoint_default_tags: Option<Vec<(String, String)>>,
174
175 pub periodic_space_reclaim_compaction_interval_sec: u64,
177
178 pub telemetry_enabled: bool,
180 pub periodic_ttl_reclaim_compaction_interval_sec: u64,
182
183 pub periodic_tombstone_reclaim_compaction_interval_sec: u64,
185
186 pub periodic_scheduling_compaction_group_split_interval_sec: u64,
188
189 pub do_not_config_object_storage_lifecycle: bool,
191
192 pub partition_vnode_count: u32,
193
194 pub table_high_write_throughput_threshold: u64,
196 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 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 pub cached_traces_num: u32,
218 pub cached_traces_memory_limit_bytes: usize,
221
222 pub enable_trivial_move: bool,
224
225 pub enable_check_task_level_overlap: bool,
227 pub enable_dropped_column_reclaim: bool,
228
229 pub split_group_size_ratio: f64,
231
232 pub table_stat_high_write_throughput_ratio_for_split: f64,
234
235 pub table_stat_low_write_throughput_ratio_for_merge: f64,
237
238 pub table_stat_throuput_window_seconds_for_split: usize,
240
241 pub table_stat_throuput_window_seconds_for_merge: usize,
243
244 pub object_store_config: ObjectStoreConfig,
246
247 pub max_trivial_move_task_count_per_loop: usize,
249
250 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 pub secret_store_private_key: Option<Vec<u8>>,
262 pub temp_secret_file_dir: String,
264
265 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 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())); 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 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 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_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 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}