1use std::collections::HashMap;
16use std::env;
17use std::fmt;
18use std::net::SocketAddr;
19use std::path::PathBuf;
20
21use rocketmq_error::RocketMQError;
22use rocketmq_error::RocketMQResult;
23use serde::Deserialize;
24use serde::Serialize;
25use tokio::sync::RwLock;
26
27use crate::common::metrics::MetricsExporterType;
28use crate::common::mix_all::ROCKETMQ_HOME_ENV;
29use crate::utils::env_utils::EnvUtils;
30
31pub const RAFT_CONTROLLER: &str = "Raft";
33
34#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct RaftPeer {
41 pub id: u64,
43
44 pub addr: SocketAddr,
46}
47
48#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50pub enum StorageBackendType {
51 RocksDB,
53
54 File,
56
57 Memory,
59}
60
61impl fmt::Display for StorageBackendType {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 match self {
64 Self::RocksDB => write!(f, "rocks_db"),
65 Self::File => write!(f, "file"),
66 Self::Memory => write!(f, "memory"),
67 }
68 }
69}
70
71#[derive(Debug, Serialize, Deserialize)]
72#[serde(rename_all = "camelCase")]
73pub struct ControllerConfig {
74 pub rocketmq_home: String,
79
80 pub config_store_path: PathBuf,
84
85 pub controller_type: String,
90
91 pub scan_not_active_broker_interval: u64,
95
96 pub controller_thread_pool_nums: usize,
100
101 pub controller_request_thread_pool_queue_capacity: usize,
105
106 pub mapped_file_size: usize,
110
111 pub controller_store_path: String,
115
116 pub elect_master_max_retry_count: u32,
120
121 pub enable_elect_unclean_master: bool,
125
126 pub is_process_read_event: bool,
130
131 pub notify_broker_role_changed: bool,
135
136 pub scan_inactive_master_interval: u64,
140
141 pub raft_scan_wait_timeout_ms: u64,
145
146 pub metrics_exporter_type: MetricsExporterType,
150
151 pub metrics_grpc_exporter_target: String,
153
154 pub metrics_grpc_exporter_header: String,
156
157 pub metric_grpc_exporter_time_out_in_mills: u64,
161
162 pub metric_grpc_exporter_interval_in_mills: u64,
166
167 pub metric_logging_exporter_interval_in_mills: u64,
171
172 pub metrics_prom_exporter_port: u16,
176
177 pub metrics_prom_exporter_host: String,
179
180 pub metrics_label: String,
184
185 pub metrics_in_delta: bool,
189
190 pub config_black_list: String,
195
196 pub node_id: u64,
199
200 pub listen_addr: SocketAddr,
202
203 pub raft_peers: Vec<RaftPeer>,
205
206 pub controller_peers: Vec<RaftPeer>,
208
209 pub election_timeout_ms: u64,
211
212 pub heartbeat_interval_ms: u64,
214
215 pub storage_path: String,
217
218 pub storage_backend: StorageBackendType,
220
221 pub enable_elect_unclean_master_local: bool,
223 #[serde(skip)]
224 rw_lock: RwLock<()>,
225}
226impl Clone for ControllerConfig {
227 fn clone(&self) -> Self {
228 Self {
229 rocketmq_home: self.rocketmq_home.clone(),
230 config_store_path: self.config_store_path.clone(),
231 controller_type: self.controller_type.clone(),
232 scan_not_active_broker_interval: self.scan_not_active_broker_interval,
233 controller_thread_pool_nums: self.controller_thread_pool_nums,
234 controller_request_thread_pool_queue_capacity: self.controller_request_thread_pool_queue_capacity,
235 mapped_file_size: self.mapped_file_size,
236 controller_store_path: self.controller_store_path.clone(),
237 elect_master_max_retry_count: self.elect_master_max_retry_count,
238 enable_elect_unclean_master: self.enable_elect_unclean_master,
239 is_process_read_event: self.is_process_read_event,
240 notify_broker_role_changed: self.notify_broker_role_changed,
241 scan_inactive_master_interval: self.scan_inactive_master_interval,
242 raft_scan_wait_timeout_ms: self.raft_scan_wait_timeout_ms,
243 metrics_exporter_type: self.metrics_exporter_type,
244 metrics_grpc_exporter_target: self.metrics_grpc_exporter_target.clone(),
245 metrics_grpc_exporter_header: self.metrics_grpc_exporter_header.clone(),
246 metric_grpc_exporter_time_out_in_mills: self.metric_grpc_exporter_time_out_in_mills,
247 metric_grpc_exporter_interval_in_mills: self.metric_grpc_exporter_interval_in_mills,
248 metric_logging_exporter_interval_in_mills: self.metric_logging_exporter_interval_in_mills,
249 metrics_prom_exporter_port: self.metrics_prom_exporter_port,
250 metrics_prom_exporter_host: self.metrics_prom_exporter_host.clone(),
251 metrics_label: self.metrics_label.clone(),
252 metrics_in_delta: self.metrics_in_delta,
253 config_black_list: self.config_black_list.clone(),
254 node_id: self.node_id,
255 listen_addr: self.listen_addr,
256 raft_peers: self.raft_peers.clone(),
257 controller_peers: self.controller_peers.clone(),
258 election_timeout_ms: self.election_timeout_ms,
259 heartbeat_interval_ms: self.heartbeat_interval_ms,
260 storage_path: self.storage_path.clone(),
261 storage_backend: self.storage_backend.clone(),
262 enable_elect_unclean_master_local: self.enable_elect_unclean_master_local,
263 rw_lock: RwLock::new(()),
264 }
265 }
266}
267
268impl Default for ControllerConfig {
269 fn default() -> Self {
270 let rocketmq_home = env::var(ROCKETMQ_HOME_ENV)
272 .ok()
273 .or_else(|| env::var("rocketmq.home.dir").ok())
274 .unwrap_or_else(EnvUtils::get_rocketmq_home);
275
276 let user_home = dirs::home_dir()
278 .unwrap_or_else(|| PathBuf::from("."))
279 .to_string_lossy()
280 .to_string();
281
282 Self {
283 rocketmq_home,
284 config_store_path: PathBuf::from(&user_home)
285 .join("controller")
286 .join("controller.properties"),
287 controller_type: RAFT_CONTROLLER.to_string(),
288 scan_not_active_broker_interval: 5 * 1000,
289 controller_thread_pool_nums: 16,
290 controller_request_thread_pool_queue_capacity: 50000,
291 mapped_file_size: 1024 * 1024 * 1024,
292 controller_store_path: String::new(),
293 elect_master_max_retry_count: 3,
294 enable_elect_unclean_master: false,
295 is_process_read_event: false,
296 notify_broker_role_changed: true,
297 scan_inactive_master_interval: 5 * 1000,
298 raft_scan_wait_timeout_ms: 1000,
299 metrics_exporter_type: MetricsExporterType::Disable,
300 metrics_grpc_exporter_target: String::new(),
301 metrics_grpc_exporter_header: String::new(),
302 metric_grpc_exporter_time_out_in_mills: 3 * 1000,
303 metric_grpc_exporter_interval_in_mills: 60 * 1000,
304 metric_logging_exporter_interval_in_mills: 10 * 1000,
305 metrics_prom_exporter_port: 5557,
306 metrics_prom_exporter_host: String::new(),
307 metrics_label: String::new(),
308 metrics_in_delta: false,
309 config_black_list: "configBlackList;configStorePath".to_string(),
310 node_id: 1,
311 listen_addr: SocketAddr::from(([127, 0, 0, 1], 60109)),
312 raft_peers: Vec::new(),
313 controller_peers: Vec::new(),
314 election_timeout_ms: 1000,
315 heartbeat_interval_ms: 300,
316 storage_path: String::new(),
317 storage_backend: StorageBackendType::Memory,
318 enable_elect_unclean_master_local: false,
319 rw_lock: RwLock::new(()),
320 }
321 }
322}
323
324impl ControllerConfig {
325 pub fn new() -> Self {
327 Self::default()
328 }
329
330 pub fn with_rocketmq_home(mut self, path: impl Into<String>) -> Self {
332 self.rocketmq_home = path.into();
333 self
334 }
335
336 pub fn with_config_store_path(mut self, path: PathBuf) -> Self {
338 self.config_store_path = path;
339 self
340 }
341
342 pub fn with_controller_type(mut self, controller_type: impl Into<String>) -> Self {
344 self.controller_type = controller_type.into();
345 self
346 }
347
348 pub fn with_scan_not_active_broker_interval(mut self, interval_ms: u64) -> Self {
350 self.scan_not_active_broker_interval = interval_ms;
351 self
352 }
353
354 pub fn with_controller_thread_pool_nums(mut self, nums: usize) -> Self {
356 self.controller_thread_pool_nums = nums;
357 self
358 }
359
360 pub fn with_controller_request_queue_capacity(mut self, capacity: usize) -> Self {
362 self.controller_request_thread_pool_queue_capacity = capacity;
363 self
364 }
365
366 pub fn with_controller_store_path(mut self, path: impl Into<String>) -> Self {
368 self.controller_store_path = path.into();
369 self
370 }
371
372 pub fn with_mapped_file_size(mut self, size: usize) -> Self {
374 self.mapped_file_size = size;
375 self
376 }
377
378 pub fn with_elect_master_max_retry_count(mut self, count: u32) -> Self {
380 self.elect_master_max_retry_count = count;
381 self
382 }
383
384 pub fn with_enable_elect_unclean_master(mut self, enable: bool) -> Self {
386 self.enable_elect_unclean_master = enable;
387 self
388 }
389
390 pub fn with_process_read_event(mut self, enable: bool) -> Self {
392 self.is_process_read_event = enable;
393 self
394 }
395
396 pub fn with_notify_broker_role_changed(mut self, enable: bool) -> Self {
398 self.notify_broker_role_changed = enable;
399 self
400 }
401
402 pub fn with_scan_inactive_master_interval(mut self, interval_ms: u64) -> Self {
404 self.scan_inactive_master_interval = interval_ms;
405 self
406 }
407
408 pub fn with_raft_scan_wait_timeout_ms(mut self, timeout_ms: u64) -> Self {
410 self.raft_scan_wait_timeout_ms = timeout_ms;
411 self
412 }
413
414 pub fn with_metrics_exporter_type(mut self, exporter_type: MetricsExporterType) -> Self {
416 self.metrics_exporter_type = exporter_type;
417 self
418 }
419
420 pub fn with_metrics_grpc_exporter(mut self, target: impl Into<String>, header: impl Into<String>) -> Self {
422 self.metrics_grpc_exporter_target = target.into();
423 self.metrics_grpc_exporter_header = header.into();
424 self
425 }
426
427 pub fn with_metrics_prom_exporter(mut self, host: impl Into<String>, port: u16) -> Self {
429 self.metrics_prom_exporter_host = host.into();
430 self.metrics_prom_exporter_port = port;
431 self
432 }
433
434 pub fn with_metrics_label(mut self, label: impl Into<String>) -> Self {
436 self.metrics_label = label.into();
437 self
438 }
439
440 pub fn with_node_info(mut self, node_id: u64, listen_addr: SocketAddr) -> Self {
442 self.node_id = node_id;
443 self.listen_addr = listen_addr;
444 self
445 }
446
447 pub fn with_raft_peers(mut self, peers: Vec<RaftPeer>) -> Self {
449 self.raft_peers = peers;
450 self
451 }
452
453 pub fn with_controller_peers(mut self, peers: Vec<RaftPeer>) -> Self {
455 self.controller_peers = peers;
456 self
457 }
458
459 pub fn with_election_timeout_ms(mut self, ms: u64) -> Self {
461 self.election_timeout_ms = ms;
462 self
463 }
464
465 pub fn with_heartbeat_interval_ms(mut self, ms: u64) -> Self {
467 self.heartbeat_interval_ms = ms;
468 self
469 }
470
471 pub fn with_storage_path(mut self, path: impl Into<String>) -> Self {
473 self.storage_path = path.into();
474 self
475 }
476
477 pub fn with_enable_elect_unclean_master_local(mut self, enable: bool) -> Self {
479 self.enable_elect_unclean_master_local = enable;
480 self
481 }
482
483 pub fn with_storage_backend(mut self, backend: StorageBackendType) -> Self {
485 self.storage_backend = backend;
486 self
487 }
488
489 pub fn with_config_black_list(mut self, blacklist: impl Into<String>) -> Self {
491 self.config_black_list = blacklist.into();
492 self
493 }
494
495 pub fn new_node(node_id: u64, listen_addr: SocketAddr) -> Self {
497 Self::default().with_node_info(node_id, listen_addr)
498 }
499
500 pub fn test_config() -> Self {
502 Self::default().with_node_info(1, SocketAddr::from(([127, 0, 0, 1], 60109)))
503 }
504
505 pub fn raft_addr_for(&self, node_id: u64) -> Option<SocketAddr> {
507 self.raft_peers
508 .iter()
509 .find(|peer| peer.id == node_id)
510 .map(|peer| peer.addr)
511 }
512
513 pub fn local_raft_addr(&self) -> SocketAddr {
515 self.raft_addr_for(self.node_id).unwrap_or(self.listen_addr)
516 }
517
518 pub fn controller_addr_for(&self, node_id: u64) -> Option<SocketAddr> {
520 if node_id == self.node_id {
521 return Some(self.listen_addr);
522 }
523
524 self.controller_peers
525 .iter()
526 .find(|peer| peer.id == node_id)
527 .map(|peer| peer.addr)
528 }
529
530 pub fn controller_peer_addrs(&self) -> Vec<SocketAddr> {
532 if self.controller_peers.is_empty() {
533 return vec![self.listen_addr];
534 }
535
536 let mut addrs = Vec::with_capacity(self.controller_peers.len() + 1);
537 addrs.push(self.listen_addr);
538 for peer in &self.controller_peers {
539 if !addrs.contains(&peer.addr) {
540 addrs.push(peer.addr);
541 }
542 }
543 addrs
544 }
545
546 pub fn is_config_in_blacklist(&self, key: &str) -> bool {
548 self.config_black_list.split(';').any(|item| item.trim() == key)
549 }
550
551 pub fn validate(&self) -> Result<(), String> {
553 if self.controller_type != RAFT_CONTROLLER {
554 return Err(format!(
555 "Invalid controller type: {}. Must be '{}'",
556 self.controller_type, RAFT_CONTROLLER
557 ));
558 }
559
560 if self.controller_thread_pool_nums == 0 {
561 return Err("controller_thread_pool_nums must be greater than 0".to_string());
562 }
563
564 if self.controller_request_thread_pool_queue_capacity == 0 {
565 return Err("controller_request_thread_pool_queue_capacity must be greater than 0".to_string());
566 }
567
568 if self.mapped_file_size == 0 {
569 return Err("mapped_file_size must be greater than 0".to_string());
570 }
571
572 if self.elect_master_max_retry_count == 0 {
573 return Err("elect_master_max_retry_count must be greater than 0".to_string());
574 }
575
576 Ok(())
577 }
578
579 pub fn to_properties_string(&self) -> String {
583 use std::fmt::Write;
584
585 let mut result = String::with_capacity(2048);
586 macro_rules! write_property {
587 ($($arg:tt)*) => {
588 let _ = writeln!(result, $($arg)*);
589 };
590 }
591
592 write_property!("rocketmqHome={}", self.rocketmq_home);
593 write_property!("configStorePath={}", self.config_store_path.display());
594 write_property!("controllerType={}", self.controller_type);
595 write_property!("scanNotActiveBrokerInterval={}", self.scan_not_active_broker_interval);
596 write_property!("controllerThreadPoolNums={}", self.controller_thread_pool_nums);
597 write_property!(
598 "controllerRequestThreadPoolQueueCapacity={}",
599 self.controller_request_thread_pool_queue_capacity
600 );
601 write_property!("mappedFileSize={}", self.mapped_file_size);
602 write_property!("controllerStorePath={}", self.controller_store_path);
603 write_property!("electMasterMaxRetryCount={}", self.elect_master_max_retry_count);
604 write_property!("enableElectUncleanMaster={}", self.enable_elect_unclean_master);
605 write_property!("isProcessReadEvent={}", self.is_process_read_event);
606 write_property!("notifyBrokerRoleChanged={}", self.notify_broker_role_changed);
607 write_property!("scanInactiveMasterInterval={}", self.scan_inactive_master_interval);
608 write_property!("raftScanWaitTimeoutMs={}", self.raft_scan_wait_timeout_ms);
609 write_property!("metricsExporterType={}", self.metrics_exporter_type);
610 write_property!("metricsGrpcExporterTarget={}", self.metrics_grpc_exporter_target);
611 write_property!("metricsGrpcExporterHeader={}", self.metrics_grpc_exporter_header);
612 write_property!(
613 "metricGrpcExporterTimeOutInMills={}",
614 self.metric_grpc_exporter_time_out_in_mills
615 );
616 write_property!(
617 "metricGrpcExporterIntervalInMills={}",
618 self.metric_grpc_exporter_interval_in_mills
619 );
620 write_property!(
621 "metricLoggingExporterIntervalInMills={}",
622 self.metric_logging_exporter_interval_in_mills
623 );
624 write_property!("metricsPromExporterPort={}", self.metrics_prom_exporter_port);
625 write_property!("metricsPromExporterHost={}", self.metrics_prom_exporter_host);
626 write_property!("metricsLabel={}", self.metrics_label);
627 write_property!("metricsInDelta={}", self.metrics_in_delta);
628 write_property!("configBlackList={}", self.config_black_list);
629 write_property!("nodeId={}", self.node_id);
630 write_property!("listenAddr={}", self.listen_addr);
631
632 let peers: Vec<String> = self
633 .raft_peers
634 .iter()
635 .map(|peer| format!("{}-{}", peer.id, peer.addr))
636 .collect();
637 write_property!("raftPeers={}", peers.join(";"));
638
639 let controller_peers: Vec<String> = self
640 .controller_peers
641 .iter()
642 .map(|peer| format!("{}-{}", peer.id, peer.addr))
643 .collect();
644 write_property!("controllerPeers={}", controller_peers.join(";"));
645
646 write_property!("electionTimeoutMs={}", self.election_timeout_ms);
647 write_property!("heartbeatIntervalMs={}", self.heartbeat_interval_ms);
648 write_property!("storagePath={}", self.storage_path);
649 write_property!("storageBackend={}", self.storage_backend);
650 write_property!(
651 "enableElectUncleanMasterLocal={}",
652 self.enable_elect_unclean_master_local
653 );
654
655 result
656 }
657 pub async fn update(&mut self, properties: HashMap<String, String>) -> RocketMQResult<()> {
658 let lock = self.rw_lock.write().await;
659 for (key, value) in &properties {
660 match key.as_str() {
661 "rocketmqHome" => {
662 self.rocketmq_home = value.clone();
663 }
664
665 "configStorePath" => {
666 self.config_store_path =
667 serde_json::from_str::<PathBuf>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
668 }
669
670 "controllerType" => {
671 self.controller_type = value.clone();
672 }
673
674 "scanNotActiveBrokerInterval" => {
675 self.scan_not_active_broker_interval =
676 serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
677 }
678
679 "controllerThreadPoolNums" => {
680 self.controller_thread_pool_nums =
681 serde_json::from_str::<usize>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
682 }
683
684 "controllerRequestThreadPoolQueueCapacity" => {
685 self.controller_request_thread_pool_queue_capacity =
686 serde_json::from_str::<usize>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
687 }
688
689 "mappedFileSize" => {
690 self.mapped_file_size =
691 serde_json::from_str::<usize>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
692 }
693
694 "controllerStorePath" => {
695 self.controller_store_path = value.clone();
696 }
697
698 "electMasterMaxRetryCount" => {
699 self.elect_master_max_retry_count =
700 serde_json::from_str::<u32>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
701 }
702
703 "enableElectUncleanMaster" => {
704 self.enable_elect_unclean_master =
705 serde_json::from_str::<bool>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
706 }
707
708 "isProcessReadEvent" => {
709 self.is_process_read_event =
710 serde_json::from_str::<bool>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
711 }
712
713 "notifyBrokerRoleChanged" => {
714 self.notify_broker_role_changed =
715 serde_json::from_str::<bool>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
716 }
717
718 "scanInactiveMasterInterval" => {
719 self.scan_inactive_master_interval =
720 serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
721 }
722
723 "raftScanWaitTimeoutMs" | "jRaftScanWaitTimeoutMs" => {
724 self.raft_scan_wait_timeout_ms =
725 serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
726 }
727
728 "metricsExporterType" => {
729 self.metrics_exporter_type = serde_json::from_str::<MetricsExporterType>(value)
730 .map_err(|e| RocketMQError::Internal(e.to_string()))?;
731 }
732
733 "metricsGrpcExporterTarget" => {
734 self.metrics_grpc_exporter_target = value.clone();
735 }
736
737 "metricsGrpcExporterHeader" => {
738 self.metrics_grpc_exporter_header = value.clone();
739 }
740
741 "metricGrpcExporterTimeOutInMills" => {
742 self.metric_grpc_exporter_time_out_in_mills =
743 serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
744 }
745
746 "metricGrpcExporterIntervalInMills" => {
747 self.metric_grpc_exporter_interval_in_mills =
748 serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
749 }
750
751 "metricLoggingExporterIntervalInMills" => {
752 self.metric_logging_exporter_interval_in_mills =
753 serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
754 }
755
756 "metricsPromExporterPort" => {
757 self.metrics_prom_exporter_port =
758 serde_json::from_str::<u16>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
759 }
760
761 "metricsPromExporterHost" => {
762 self.metrics_prom_exporter_host = value.clone();
763 }
764
765 "metricsLabel" => {
766 self.metrics_label = value.clone();
767 }
768
769 "metricsInDelta" => {
770 self.metrics_in_delta =
771 serde_json::from_str::<bool>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
772 }
773
774 "configBlackList" => {
775 self.config_black_list = value.clone();
776 }
777
778 "nodeId" => {
779 self.node_id =
780 serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
781 }
782
783 "listenAddr" => {
784 self.listen_addr = serde_json::from_str::<SocketAddr>(value)
785 .map_err(|e| RocketMQError::Internal(e.to_string()))?;
786 }
787
788 "raftPeers" => {
789 self.raft_peers = serde_json::from_str::<Vec<RaftPeer>>(value)
790 .map_err(|e| RocketMQError::Internal(e.to_string()))?;
791 }
792
793 "controllerPeers" => {
794 self.controller_peers = serde_json::from_str::<Vec<RaftPeer>>(value)
795 .map_err(|e| RocketMQError::Internal(e.to_string()))?;
796 }
797
798 "electionTimeoutMs" => {
799 self.election_timeout_ms =
800 serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
801 }
802
803 "heartbeatIntervalMs" => {
804 self.heartbeat_interval_ms =
805 serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
806 }
807
808 "storagePath" => {
809 self.storage_path = value.clone();
810 }
811
812 "storageBackend" => {
813 self.storage_backend = serde_json::from_str::<StorageBackendType>(value)
814 .map_err(|e| RocketMQError::Internal(e.to_string()))?;
815 }
816
817 "enableElectUncleanMasterLocal" => {
818 self.enable_elect_unclean_master_local =
819 serde_json::from_str::<bool>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
820 }
821 _ => {
822 return Err(RocketMQError::Internal(format!("found unknown property: {}", key)));
823 }
824 }
825 }
826 Ok(())
827 }
828}
829
830#[cfg(test)]
831mod tests {
832 use super::*;
833
834 #[test]
835 fn test_controller_config_default() {
836 let config = ControllerConfig::default();
837
838 assert_eq!(config.controller_type, RAFT_CONTROLLER);
839 assert_eq!(config.scan_not_active_broker_interval, 5000);
840 assert_eq!(config.controller_thread_pool_nums, 16);
841 assert_eq!(config.controller_request_thread_pool_queue_capacity, 50000);
842 assert_eq!(config.mapped_file_size, 1024 * 1024 * 1024);
843 assert_eq!(config.elect_master_max_retry_count, 3);
844 assert!(!config.enable_elect_unclean_master);
845 assert!(!config.is_process_read_event);
846 assert!(config.notify_broker_role_changed);
847 assert_eq!(config.metrics_prom_exporter_port, 5557);
848 }
849
850 #[test]
851 fn test_controller_config_builder() {
852 let config = ControllerConfig::new()
853 .with_controller_type(RAFT_CONTROLLER)
854 .with_scan_not_active_broker_interval(10000)
855 .with_controller_thread_pool_nums(32)
856 .with_enable_elect_unclean_master(true);
857
858 assert_eq!(config.controller_type, RAFT_CONTROLLER);
859 assert_eq!(config.scan_not_active_broker_interval, 10000);
860 assert_eq!(config.controller_thread_pool_nums, 32);
861 assert!(config.enable_elect_unclean_master);
862 }
863
864 #[test]
865 fn test_config_validation_invalid_type() {
866 let config = ControllerConfig {
867 controller_type: "InvalidType".to_string(),
868 ..Default::default()
869 };
870
871 assert!(config.validate().is_err());
872 }
873
874 #[test]
875 fn test_config_validation_success() {
876 let config = ControllerConfig::new();
877
878 assert!(config.validate().is_ok());
879 }
880
881 #[test]
882 fn test_config_blacklist() {
883 let config = ControllerConfig::default();
884
885 assert!(config.is_config_in_blacklist("configBlackList"));
886 assert!(config.is_config_in_blacklist("configStorePath"));
887 assert!(!config.is_config_in_blacklist("controllerType"));
888 }
889
890 #[test]
891 fn test_metrics_config() {
892 let config = ControllerConfig::new()
893 .with_metrics_exporter_type(MetricsExporterType::Prom)
894 .with_metrics_prom_exporter("localhost", 9090)
895 .with_metrics_label("instance_id:test,uid:123");
896
897 assert_eq!(config.metrics_exporter_type, MetricsExporterType::Prom);
898 assert_eq!(config.metrics_prom_exporter_host, "localhost");
899 assert_eq!(config.metrics_prom_exporter_port, 9090);
900 assert_eq!(config.metrics_label, "instance_id:test,uid:123");
901 }
902
903 #[test]
904 fn test_to_properties_string_basic() {
905 let config = ControllerConfig::default();
906 let result = config.to_properties_string();
907
908 assert!(result.contains("rocketmqHome="));
909 assert!(result.contains("controllerType=Raft"));
910 assert!(result.contains("scanNotActiveBrokerInterval=5000"));
911 assert!(result.contains("controllerThreadPoolNums=16"));
912 assert!(result.contains("notifyBrokerRoleChanged=true"));
913 assert!(result.contains("enableElectUncleanMaster=false"));
914 }
915
916 #[test]
917 fn test_to_properties_string_format() {
918 let config = ControllerConfig::default();
919 let result = config.to_properties_string();
920
921 let lines: Vec<&str> = result.lines().collect();
922 assert!(!lines.is_empty());
923
924 for line in lines {
925 assert!(line.contains('='), "Each line should contain '=': {}", line);
926 let parts: Vec<&str> = line.split('=').collect();
927 assert_eq!(parts.len(), 2, "Each line should have exactly one '=': {}", line);
928 }
929 }
930
931 #[test]
932 fn test_to_properties_string_with_custom_config() {
933 let config = ControllerConfig::new()
934 .with_controller_type(RAFT_CONTROLLER)
935 .with_scan_not_active_broker_interval(10000)
936 .with_controller_thread_pool_nums(32)
937 .with_enable_elect_unclean_master(true)
938 .with_storage_backend(StorageBackendType::RocksDB);
939
940 let result = config.to_properties_string();
941
942 assert!(result.contains("controllerType=Raft"));
943 assert!(result.contains("scanNotActiveBrokerInterval=10000"));
944 assert!(result.contains("controllerThreadPoolNums=32"));
945 assert!(result.contains("enableElectUncleanMaster=true"));
946 assert!(result.contains("storageBackend=rocks_db"));
947 }
948
949 #[test]
950 fn test_to_properties_string_with_raft_peers() {
951 let config = ControllerConfig::new().with_raft_peers(vec![
952 RaftPeer {
953 id: 1,
954 addr: "127.0.0.1:9877".parse().unwrap(),
955 },
956 RaftPeer {
957 id: 2,
958 addr: "127.0.0.1:9878".parse().unwrap(),
959 },
960 ]);
961
962 let result = config.to_properties_string();
963
964 assert!(result.contains("raftPeers=1-127.0.0.1:9877;2-127.0.0.1:9878"));
965 }
966}