Repository navigation
Expand file tree
/
Copy pathcli.rs
More file actions
530 lines (475 loc) Β· 18.5 KB
/
Copy pathcli.rs
File metadata and controls
530 lines (475 loc) Β· 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
// Copyright 2023 The RocketMQ Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Command Line Interface Module for RocketMQ Controller
//!
//! This module provides CLI argument parsing and configuration loading for the RocketMQ Controller.
//! Uses the `config` crate (via `parse_config_file`) to support multiple configuration formats
//! including TOML, JSON, YAML, etc.
//!
//! # Examples
//!
//! ```bash
//! # Start with config file
//! rocketmq-controller --config-file ./conf/controller.toml
//!
//! # Print configuration and exit
//! rocketmq-controller --print-config-item
//!
//! # Show help
//! rocketmq-controller --help
//! ```
use std::path::Path;
use std::path::PathBuf;
use crate::ControllerResult;
use clap::Parser;
use tracing::info;
use crate::config::ControllerConfig;
const REMOVED_CONTROLLER_TELEMETRY_KEYS: [&str; 10] = [
"metricsExporterType",
"metricsGrpcExporterTarget",
"metricsGrpcExporterHeader",
"metricGrpcExporterTimeOutInMills",
"metricGrpcExporterIntervalInMills",
"metricLoggingExporterIntervalInMills",
"metricsPromExporterHost",
"metricsPromExporterPort",
"metricsLabel",
"metricsInDelta",
];
fn parse_controller_config_file(config_path: &Path) -> ControllerResult<ControllerConfig> {
let config = config::Config::builder()
.add_source(config::File::from(config_path))
.build()
.map_err(|error| crate::error::configuration_invalid_by("controller.config", error))?;
if config.get::<config::Value>("storageBackend").is_ok() {
return Err(crate::error::configuration_invalid(
"storageBackend (removed; use storageEngineType)",
));
}
for key in REMOVED_CONTROLLER_TELEMETRY_KEYS {
if config.get::<config::Value>(key).is_ok() {
return Err(crate::error::configuration_invalid(key));
}
}
config
.try_deserialize()
.map_err(|error| crate::error::configuration_invalid_by("controller.config", error))
}
/// RocketMQ Controller Command Line Arguments
///
/// Parses command-line arguments for the RocketMQ Controller using clap.
/// Supports loading configuration from files (TOML/JSON/YAML) and printing config items.
#[derive(Parser, Debug, Clone)]
#[command(
name = "rocketmq-controller-rust",
author,
version,
about = "RocketMQ-Rust Controller",
long_about = "Controller for RocketMQ-Rust, a Rust implementation of Apache RocketMQ.\n\n\
Provides broker master election, heartbeat tracking, replica metadata \
management, and replicated controller state.\n\n\
Project: https://github.com/mxsm/rocketmq-rust"
)]
pub struct ControllerCli {
/// Controller configuration file path (TOML, JSON, YAML, etc.)
///
/// # Examples
///
/// ```bash
/// --config-file /opt/rocketmq/conf/controller.toml
/// -c ./controller.toml
/// ```
#[arg(
short = 'c',
long = "config-file",
value_name = "FILE",
help = "Controller config file (TOML/JSON/YAML)"
)]
pub config_file: Option<PathBuf>,
/// Print all configuration items and exit
///
/// When enabled, prints all controller configuration properties
/// to the console and exits without starting the controller.
#[arg(short = 'p', long = "print-config-item", help = "Print all config items")]
pub print_config_item: bool,
/// Enable test/development mode with fake identifiers
///
/// When enabled, uses test-mode configurations for development purposes.
#[arg(short = 'm', long = "print-important-config", help = "Print important config items")]
pub print_important_config: bool,
/// Override the process log filter for this startup.
#[arg(long = "log-filter", value_name = "DIRECTIVE")]
pub log_filter: Option<String>,
}
impl ControllerCli {
/// Parse command line arguments
///
/// Wrapper around clap's parse() for easier testing and mocking.
pub fn parse_args() -> Self {
Self::parse()
}
/// Validate parsed arguments
///
/// Checks for:
/// - Config file exists if specified
/// - Config file is readable
///
/// # Errors
///
/// Returns error if validation fails
pub fn validate(&self) -> ControllerResult<()> {
// Validate config file if specified
if let Some(ref path) = self.config_file {
if !path.exists() {
return Err(crate::error::io_failed(
"validate Controller config file",
std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("Config file not found: {}", path.display()),
),
));
}
if !path.is_file() {
return Err(crate::error::io_failed(
"validate Controller config file",
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("Config path is not a file: {}", path.display()),
),
));
}
}
Ok(())
}
/// Load configuration from file
///
/// Uses the `config` crate, which supports multiple formats:
/// - TOML (.toml)
/// - JSON (.json)
/// - YAML (.yaml, .yml)
/// - And other formats supported by the `config` crate
///
/// If no config file is specified, returns the default configuration.
///
/// # Arguments
///
/// * `config` - Default configuration to use if no file is specified
///
/// # Returns
///
/// Loaded configuration
///
/// # Errors
///
/// Returns error if:
/// - Config file cannot be read
/// - Config file format is invalid
pub fn load_config(&self, config: ControllerConfig) -> ControllerResult<ControllerConfig> {
// Load from config file if specified
if let Some(ref config_path) = self.config_file {
info!("Loading configuration from file: {}", config_path.display());
let loaded_config = parse_controller_config_file(config_path)?;
println!("Loaded configuration from file: {}", config_path.display());
Ok(loaded_config)
} else {
Ok(config)
}
}
/// Print configuration to console
///
/// Prints configuration in human-readable format with sections:
/// - Controller Configuration
/// - Node Configuration
/// - Raft Configuration
/// - Storage Configuration
pub fn print_config(config: &ControllerConfig) {
println!("\n========== Controller Configuration ==========");
println!("RocketMQ Home: {}", config.rocketmq_home);
println!("Config Store Path: {:?}", config.config_store_path);
println!("Controller Type: {}", config.controller_type);
println!("Scan Interval: {} ms", config.scan_not_active_broker_interval);
println!("Thread Pool Nums: {}", config.controller_thread_pool_nums);
println!(
"Request Queue Capacity: {}",
config.controller_request_thread_pool_queue_capacity
);
println!("\n========== Node Configuration ==========");
println!("Node ID: {}", config.node_id);
println!("Listen Address: {}", config.listen_addr);
println!("\n========== Raft Configuration ==========");
println!("Election Timeout: {} ms", config.election_timeout_ms);
println!("Heartbeat Interval: {} ms", config.heartbeat_interval_ms);
let peers = config.raft_member_endpoints();
println!("Raft Peers: {} peers", peers.len());
for peer in &peers {
println!(" - Node {}: {}", peer.id, peer.addr);
}
println!("\n========== Storage Configuration ==========");
println!("Storage Path: {}", config.storage_path);
println!("Storage Engine Type: {:?}", config.storage_engine_type);
println!("Mapped File Size: {} bytes", config.mapped_file_size);
println!();
}
}
/// Parse command line arguments and load configuration
///
/// High-level helper function that combines parsing, validation, and config loading.
/// This is the recommended entry point for applications.
///
/// # Returns
///
/// Tuple of (CLI arguments, loaded configuration)
///
/// # Errors
///
/// Returns error if:
/// - Argument parsing fails (handled by clap, exits process)
/// - Validation fails
/// - Configuration loading fails
///
/// # Examples
///
/// ```rust,no_run
/// use rocketmq_controller::parse_command_line;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let (cli, config) = parse_command_line()?;
///
/// if cli.print_config_item {
/// rocketmq_controller::ControllerCli::print_config(&config);
/// std::process::exit(0);
/// }
///
/// // Start controller with config...
/// Ok(())
/// }
/// ```
pub fn parse_command_line() -> ControllerResult<(ControllerCli, ControllerConfig)> {
// Parse arguments (exits on --help or --version)
let cli = ControllerCli::parse_args();
// Validate arguments
cli.validate()?;
// Load default configuration
let default_config = ControllerConfig::default();
// Apply config file if specified
let config = cli.load_config(default_config)?;
Ok((cli, config))
}
#[cfg(test)]
mod tests {
use super::*;
fn cli_with_config_file(config_file: PathBuf) -> ControllerCli {
ControllerCli {
config_file: Some(config_file),
print_config_item: false,
print_important_config: false,
log_filter: None,
}
}
#[test]
fn controller_config_file_preserves_logging_observability_and_defaults() {
let directory = tempfile::tempdir().expect("temporary Controller config directory");
let path = directory.path().join("controller.toml");
std::fs::write(
&path,
r#"
logFilter = "info"
controllerThreadPoolNums = 24
[logging]
filter = "info"
reload.enabled = true
[observability.metrics]
exporter = "prometheus"
[observability.prometheus]
host = "127.0.0.1"
port = 9464
path = "/rocketmq"
"#,
)
.expect("write Controller configuration");
let config = cli_with_config_file(path.clone())
.load_config(ControllerConfig::default())
.expect("Controller-owned and logging configuration should share one file");
let logging: rocketmq_observability::LoggingOverrides =
rocketmq_runtime::common::parse_config_file::parse_config_file(path)
.expect("logging overrides should load from the same file");
assert_eq!(config.controller_thread_pool_nums, 24);
assert_eq!(config.node_id, 1);
assert_eq!(config.controller_type, "Raft");
assert_eq!(
config.observability.metrics.exporter,
Some(rocketmq_observability::MetricsExporter::Prometheus)
);
assert_eq!(config.observability.prometheus.host.as_deref(), Some("127.0.0.1"));
assert_eq!(config.observability.prometheus.port, Some(9464));
assert_eq!(config.observability.prometheus.path.as_deref(), Some("/rocketmq"));
assert_eq!(logging.log_filter.as_deref(), Some("info"));
assert_eq!(logging.logging.filter.as_deref(), Some("info"));
assert!(logging.logging.reload.enabled);
}
#[test]
fn controller_config_file_storage_selector_uses_only_canonical_key() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("controller.toml");
for source in [
"storageBackend = 'Memory'",
"storageEngineType = 'RocksDB'\nstorageBackend = 'Memory'",
"storageBackend = 'private-value'",
"storageEngineType = 'Memory'\nstorageBackend = 'private-value'",
] {
std::fs::write(&path, source).unwrap();
let error = cli_with_config_file(path.clone())
.load_config(ControllerConfig::default())
.unwrap_err();
assert_eq!(error.descriptor(), &rocketmq_error::CONTROLLER_CONFIGURATION_INVALID);
let diagnostic = error.diagnostic_view().unwrap();
let key = diagnostic.fields().find(|field| field.name() == "key").unwrap();
assert_eq!(
key.value(),
rocketmq_error::ViewValueRef::Text("storageBackend (removed; use storageEngineType)")
);
assert!(!format!("{error:?}").contains("private-value"));
}
std::fs::write(&path, "storageEngineType = 'Memory'\nunrelatedField = true").unwrap();
let config = cli_with_config_file(path)
.load_config(ControllerConfig::default())
.unwrap();
assert_eq!(config.storage_engine_type, crate::StorageEngineType::Memory);
}
#[test]
fn controller_config_file_rejects_every_removed_telemetry_key() {
let directory = tempfile::tempdir().expect("temporary Controller config directory");
let path = directory.path().join("controller.toml");
for (key, value) in [
("metricsExporterType", "\"disable\""),
("metricsGrpcExporterTarget", "\"http://collector:4317\""),
("metricsGrpcExporterHeader", "\"key:value\""),
("metricGrpcExporterTimeOutInMills", "3000"),
("metricGrpcExporterIntervalInMills", "60000"),
("metricLoggingExporterIntervalInMills", "10000"),
("metricsPromExporterHost", "\"127.0.0.1\""),
("metricsPromExporterPort", "9464"),
("metricsLabel", "\"cluster:test\""),
("metricsInDelta", "false"),
] {
std::fs::write(
&path,
format!("{key} = {value}\n\n[observability.metrics]\nexporter = \"disable\"\n"),
)
.expect("write legacy Controller configuration");
let error = cli_with_config_file(path.clone())
.load_config(ControllerConfig::default())
.expect_err("every removed telemetry key must be rejected");
let diagnostic = error.diagnostic_view().expect("schema-valid diagnostic view");
let rejected = diagnostic
.fields()
.find(|field| field.name() == "key")
.expect("the rejected key must be retained as diagnostic context");
assert_eq!(
rejected.value(),
rocketmq_error::ViewValueRef::Text(key),
"error must identify {key}"
);
}
}
#[test]
fn controller_config_file_errors_redact_observability_values() {
let directory = tempfile::tempdir().expect("temporary Controller config directory");
let path = directory.path().join("controller.toml");
for (source, canary) in [
(
"[observability.otlp]\nheaders = \"CONTROLLER_HEADER_CANARY\"\n",
"CONTROLLER_HEADER_CANARY",
),
(
"[observability]\nresourceAttributes = \"CONTROLLER_RESOURCE_CANARY\"\n",
"CONTROLLER_RESOURCE_CANARY",
),
(
"[observability.otlp]\nendpoint = \"https://collector.invalid?token=CONTROLLER_ENDPOINT_CANARY\" trailing\n",
"CONTROLLER_ENDPOINT_CANARY",
),
] {
std::fs::write(&path, source).expect("write invalid Controller configuration");
let error = cli_with_config_file(path.clone())
.load_config(ControllerConfig::default())
.expect_err("invalid observability configuration must fail");
for output in [error.to_string(), format!("{error:?}")] {
assert!(
!output.contains(canary),
"Controller configuration error exposed sensitive input: {output}"
);
}
}
}
#[test]
fn test_cli_parse_log_filter_override() {
let cli = ControllerCli::try_parse_from(["mqcontroller", "--log-filter", "info,rocketmq_controller=debug"])
.expect("log filter should parse");
assert_eq!(cli.log_filter.as_deref(), Some("info,rocketmq_controller=debug"));
}
#[test]
fn test_cli_parse_no_args() {
let cli = ControllerCli::parse_from(vec!["mqcontroller"]);
assert!(cli.config_file.is_none());
assert!(!cli.print_config_item);
assert!(!cli.print_important_config);
}
#[test]
fn test_cli_parse_with_config() {
let cli = ControllerCli::parse_from(vec!["mqcontroller", "-c", "config.toml"]);
assert!(cli.config_file.is_some());
assert_eq!(cli.config_file.unwrap().to_str().unwrap(), "config.toml");
}
#[test]
fn test_cli_parse_print_config() {
let cli = ControllerCli::parse_from(vec!["mqcontroller", "--print-config-item"]);
assert!(cli.print_config_item);
}
#[test]
fn test_validate_nonexistent_file() {
let cli = ControllerCli {
config_file: Some(PathBuf::from("/nonexistent/file.toml")),
print_config_item: false,
print_important_config: false,
log_filter: None,
};
assert!(cli.validate().is_err());
}
#[test]
fn test_validate_no_config_file() {
let cli = ControllerCli {
config_file: None,
print_config_item: false,
print_important_config: false,
log_filter: None,
};
assert!(cli.validate().is_ok());
}
#[test]
fn test_load_config_no_file() {
let cli = ControllerCli {
config_file: None,
print_config_item: false,
print_important_config: false,
log_filter: None,
};
let default_config = ControllerConfig::default();
let result = cli.load_config(default_config.clone());
assert!(result.is_ok());
// Should return default config
assert_eq!(result.unwrap().node_id, default_config.node_id);
}
}