1use camel_api::datasource::DatasourceCatalog;
12#[cfg(feature = "wasm")]
13use camel_bean::BeanProcessor;
14use camel_core::datasource::RuntimeDatasourceCatalog;
15use std::sync::Arc;
16use std::time::Duration;
17use tokio_util::sync::CancellationToken;
18
19struct BridgeCleanup {
20 xslt: Arc<camel_xslt::XsltBridgeRuntime>,
21 xj: Arc<camel_xj::XjBridgeRuntime>,
22 validator: Option<Arc<camel_component_validator::xsd_bridge::XsdBridgeBackend>>,
23}
24
25#[async_trait::async_trait]
26impl camel_api::lifecycle::Lifecycle for BridgeCleanup {
27 fn name(&self) -> &str {
28 "bridge-cleanup"
29 }
30
31 async fn start(&mut self) -> Result<(), camel_api::CamelError> {
32 Ok(())
33 }
34
35 async fn stop(&mut self) -> Result<(), camel_api::CamelError> {
36 self.xslt.shutdown().await;
37 self.xj.shutdown().await;
38 if let Some(validator) = &self.validator {
39 validator.shutdown().await;
40 }
41 Ok(())
42 }
43}
44
45pub async fn run(
46 routes_override: Option<String>,
47 config_path: String,
48 cli_watch: Option<bool>,
49 otel: bool,
50 otel_endpoint: Option<String>,
51 service_name: Option<String>,
52 health_port: Option<u16>,
53) -> Result<(), camel_api::CamelError> {
54 let mut camel_config: camel_config::config::CamelConfig =
56 camel_config::config::CamelConfig::from_file(&config_path).unwrap_or_else(|_| {
57 config::Config::builder()
59 .build()
60 .and_then(|c| c.try_deserialize())
61 .unwrap_or_else(|e| {
62 eprintln!("Failed to build default config: {e}");
63 std::process::exit(1);
64 })
65 });
66
67 let otel_enabled = otel || otel_endpoint.is_some() || service_name.is_some();
69 if otel_enabled {
70 let otel_cfg =
71 camel_config
72 .observability
73 .otel
74 .get_or_insert(camel_config::OtelCamelConfig {
75 enabled: true,
76 endpoint: "http://localhost:4317".to_string(),
77 service_name: "rust-camel".to_string(),
78 ..Default::default()
79 });
80 otel_cfg.enabled = true;
81 if let Some(ep) = otel_endpoint {
82 otel_cfg.endpoint = ep;
83 }
84 if let Some(name) = service_name {
85 otel_cfg.service_name = name;
86 }
87 }
88
89 if let Some(port) = health_port {
90 let health_cfg = camel_config
91 .observability
92 .health
93 .get_or_insert(camel_config::config::HealthCamelConfig::default());
94 health_cfg.enabled = true;
95 health_cfg.port = port;
96 }
97
98 let beans_registry = {
100 let bean_reg = std::sync::Arc::new(std::sync::Mutex::new(camel_bean::BeanRegistry::new()));
101 if camel_config.beans.is_empty() {
102 None
103 } else {
104 Some(bean_reg)
105 }
106 };
107
108 let mut ctx = camel_config::config::CamelConfig::configure_context_with_beans(
109 &camel_config,
110 beans_registry.clone(),
111 )
112 .await
113 .unwrap_or_else(|e| {
114 eprintln!("Failed to configure CamelContext: {e}");
115 std::process::exit(1);
116 });
117
118 tracing::warn!(
121 "camel run trusts the current working directory and will execute route \
122 scripts, WASM modules, and beans resolved from it; only run from a \
123 trusted directory"
124 );
125
126 match camel_function::FunctionRuntimeService::with_default_container_provider(
127 camel_function::FunctionConfig::default(),
128 ) {
129 Ok(svc) => ctx = ctx.with_lifecycle(svc),
130 Err(e) => tracing::warn!("Function runtime disabled: {e}"),
131 }
132
133 let datasource_catalog: Arc<dyn DatasourceCatalog> = {
135 let catalog = RuntimeDatasourceCatalog::new(camel_config.datasources.clone())
136 .with_health_registry(ctx.health_registry());
137 Arc::new(catalog)
138 };
139
140 #[cfg(feature = "wasm")]
142 if let Some(ref bean_reg) = beans_registry {
143 let component_registry = ctx.registry_arc();
144 let plugins_dir_raw = camel_config
145 .components
146 .raw
147 .get("wasm")
148 .and_then(|v| v.get("plugins_dir"))
149 .and_then(|v| v.as_str())
150 .unwrap_or("plugins");
151 let config_dir = std::path::Path::new(&config_path)
152 .parent()
153 .map(|p| {
154 if p.as_os_str().is_empty() {
155 std::path::Path::new(".")
156 } else {
157 p
158 }
159 })
160 .unwrap_or(std::path::Path::new("."));
161 let camel_root = config_dir.canonicalize().unwrap_or_else(|e| {
162 eprintln!("Error: cannot resolve project root: {e}");
163 std::process::exit(1);
164 });
165 crate::commands::plugin::validate_plugins_dir(&camel_root, plugins_dir_raw).unwrap_or_else(
166 |e| {
167 eprintln!("Error: invalid plugins_dir: {e}");
168 std::process::exit(1);
169 },
170 );
171 let plugins_dir = camel_root.join(plugins_dir_raw);
172 for (bean_name, bean_cfg) in &camel_config.beans {
173 tracing::info!(bean = %bean_name, plugin = %bean_cfg.plugin, "registering WASM bean");
174
175 if !bean_cfg
176 .plugin
177 .chars()
178 .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
179 {
180 eprintln!(
181 "Invalid bean plugin name '{}': must be alphanumeric with - or _",
182 bean_cfg.plugin
183 );
184 std::process::exit(1);
185 }
186
187 let wasm_path = plugins_dir.join(format!("{}.wasm", bean_cfg.plugin));
188 let canonical_plugins = plugins_dir.canonicalize().unwrap_or_else(|_| {
189 eprintln!("Plugins directory not found: {}", plugins_dir.display());
190 std::process::exit(1);
191 });
192 let canonical_path = wasm_path.canonicalize().unwrap_or_else(|_| {
193 eprintln!("WASM bean plugin not found: {}", wasm_path.display());
194 std::process::exit(1);
195 });
196 if !canonical_path.starts_with(&canonical_plugins) {
197 eprintln!(
198 "Bean plugin path escapes plugins directory: {}",
199 bean_cfg.plugin
200 );
201 std::process::exit(1);
202 }
203 let wasm_config =
204 camel_component_wasm::config::WasmConfig::from_limits(&bean_cfg.limits);
205 let wasm_bean = camel_component_wasm::bean::WasmBean::new(
206 &wasm_path,
207 wasm_config,
208 Arc::new(camel_core::RegistryComponentContext::new(
209 component_registry.clone(),
210 )),
211 bean_cfg.config.clone(),
212 )
213 .await
214 .unwrap_or_else(|e| {
215 eprintln!("Failed to load WASM bean '{}': {}", bean_name, e);
216 std::process::exit(1);
217 });
218 tracing::info!(
219 bean = %bean_name,
220 plugin = %bean_cfg.plugin,
221 methods = ?wasm_bean.methods(),
222 "WASM bean loaded"
223 );
224 bean_reg
225 .lock()
226 .expect("beans registry lock") .register(bean_name, wasm_bean)
228 .unwrap_or_else(|e| {
229 eprintln!("Bean registration failed for '{}': {}", bean_name, e);
230 std::process::exit(1);
231 });
232 }
233 }
234
235 let patterns: Vec<String> = if let Some(p) = routes_override {
237 vec![p]
238 } else if !camel_config.routes.is_empty() {
239 camel_config.routes.clone()
240 } else {
241 vec!["routes/*.yaml".to_string()]
242 };
243
244 tracing::info!("camel-cli: loading routes from patterns: {:?}", patterns);
245
246 let security_compile_context =
247 crate::build_security_compile_context_from_config(&camel_config, ctx.registry_arc())
248 .await?;
249
250 macro_rules! register_bundle {
254 ($ctx:expr, $cfg:expr, $Bundle:ty) => {
255 let raw = $cfg
256 .components
257 .raw
258 .get(<$Bundle as camel_component_api::ComponentBundle>::config_key())
259 .cloned()
260 .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
261 match <$Bundle as camel_component_api::ComponentBundle>::from_toml(raw) {
262 Ok(bundle) => <$Bundle as camel_component_api::ComponentBundle>::register_all(
263 bundle, &mut $ctx,
264 ),
265 Err(e) => {
266 return Err(camel_api::CamelError::Config(format!(
267 "Failed to load {} config: {}",
268 <$Bundle as camel_component_api::ComponentBundle>::config_key(),
269 e
270 )));
271 }
272 }
273 };
274 }
275
276 ctx.register_component(camel_component_timer::TimerComponent::new());
278 ctx.register_component(camel_component_cron::CronComponent::new());
279 ctx.register_component(camel_component_log::LogComponent::new());
280 ctx.register_component(camel_component_direct::DirectComponent::new());
281 ctx.register_component(camel_component_seda::SedaComponent::new());
282 ctx.register_component(camel_component_mock::MockComponent::new());
283 ctx.register_component(camel_component_controlbus::ControlBusComponent::new());
284 let validator_component = camel_component_validator::ValidatorComponent::new();
285 let validator_backend = validator_component.xsd_bridge_backend();
286 ctx.register_component(validator_component);
287
288 let xslt_component = camel_xslt::XsltComponent::default();
289 let xslt_runtime = xslt_component.bridge_runtime();
290 ctx.register_component(xslt_component);
291
292 let xj_component = camel_xj::XjComponent::default();
293 let xj_runtime = xj_component.bridge_runtime();
294 ctx.register_component(xj_component);
295
296 ctx = ctx.with_lifecycle(BridgeCleanup {
297 xslt: xslt_runtime,
298 xj: xj_runtime,
299 validator: validator_backend,
300 });
301
302 register_bundle!(ctx, camel_config, camel_component_http::HttpBundle);
304 #[cfg(feature = "http-static")]
305 register_bundle!(ctx, camel_config, camel_component_http::HttpStaticBundle);
306 register_bundle!(ctx, camel_config, camel_component_ws::WsBundle);
307 register_bundle!(ctx, camel_config, camel_component_file::FileBundle);
308 register_bundle!(
309 ctx,
310 camel_config,
311 camel_component_container::ContainerBundle
312 );
313 register_bundle!(ctx, camel_config, camel_template::TemplateBundle);
315
316 let jms_pool = {
318 let raw = camel_config
319 .components
320 .raw
321 .get("jms")
322 .cloned()
323 .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
324 match <camel_component_jms::JmsBundle as camel_component_api::ComponentBundle>::from_toml(
325 raw,
326 ) {
327 Ok(bundle) => {
328 let pool = bundle.pool();
329 <camel_component_jms::JmsBundle as camel_component_api::ComponentBundle>::register_all(bundle, &mut ctx);
330 pool
331 }
332 Err(e) => {
333 return Err(camel_api::CamelError::Config(format!(
334 "Failed to load jms config: {e}"
335 )));
336 }
337 }
338 };
339
340 let cxf_pool = {
341 let raw = camel_config
342 .components
343 .raw
344 .get("cxf")
345 .cloned()
346 .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
347 match <camel_component_cxf::CxfBundle as camel_component_api::ComponentBundle>::from_toml(
348 raw,
349 ) {
350 Ok(bundle) => {
351 let pool = bundle.pool();
352 <camel_component_cxf::CxfBundle as camel_component_api::ComponentBundle>::register_all(bundle, &mut ctx);
353 pool
354 }
355 Err(e) => {
356 return Err(camel_api::CamelError::Config(format!(
357 "Failed to load cxf config: {e}"
358 )));
359 }
360 }
361 };
362
363 #[cfg(feature = "kafka")]
364 register_bundle!(ctx, camel_config, camel_component_kafka::KafkaBundle);
365 #[cfg(feature = "mqtt")]
366 register_bundle!(ctx, camel_config, camel_component_mqtt::MqttBundle);
367 register_bundle!(ctx, camel_config, camel_master::MasterBundle);
368 register_bundle!(
369 ctx,
370 camel_config,
371 camel_component_opensearch::OpenSearchBundle
372 );
373 register_bundle!(ctx, camel_config, camel_component_redis::RedisBundle);
374 {
375 let sql_raw = camel_config
376 .components
377 .raw
378 .get(<camel_component_sql::SqlBundle as camel_component_api::ComponentBundle>::config_key())
379 .cloned()
380 .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
381 match <camel_component_sql::SqlBundle as camel_component_api::ComponentBundle>::from_toml(
382 sql_raw,
383 ) {
384 Ok(bundle) => {
385 let bundle = bundle.with_catalog(Arc::clone(&datasource_catalog));
386 <camel_component_sql::SqlBundle as camel_component_api::ComponentBundle>::register_all(bundle, &mut ctx);
387 }
388 Err(e) => {
389 tracing::error!("failed to initialize SQL bundle: {}", e);
391 }
392 }
393 }
394 #[cfg(feature = "surrealdb")]
395 {
396 let surrealdb_raw = camel_config
397 .components
398 .raw
399 .get(<camel_component_surrealdb::SurrealDbBundle as camel_component_api::ComponentBundle>::config_key())
400 .cloned()
401 .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
402 match <camel_component_surrealdb::SurrealDbBundle as camel_component_api::ComponentBundle>::from_toml(
403 surrealdb_raw,
404 ) {
405 Ok(bundle) => {
406 let bundle = bundle.with_catalog(Arc::clone(&datasource_catalog));
407 <camel_component_surrealdb::SurrealDbBundle as camel_component_api::ComponentBundle>::register_all(
408 bundle, &mut ctx,
409 );
410 }
411 Err(e) => {
412 tracing::error!("failed to initialize SurrealDB bundle: {}", e);
414 }
415 }
416 }
417 #[cfg(feature = "grpc")]
418 register_bundle!(ctx, camel_config, camel_component_grpc::GrpcBundle);
419
420 #[cfg(feature = "llm")]
421 register_bundle!(ctx, camel_config, camel_component_llm::LlmBundle);
422
423 #[cfg(feature = "mcp")]
424 register_bundle!(ctx, camel_config, camel_component_mcp::McpBundle);
425
426 #[cfg(feature = "wasm")]
427 {
428 let base_dir = std::path::Path::new(&config_path)
429 .parent()
430 .unwrap_or(std::path::Path::new("."))
431 .to_path_buf();
432 let wasm_bundle = camel_component_wasm::WasmBundle::new(
433 Arc::new(camel_core::RegistryComponentContext::new(
434 ctx.registry_arc(),
435 )),
436 base_dir,
437 );
438 <camel_component_wasm::WasmBundle as camel_component_api::ComponentBundle>::register_all(
439 wasm_bundle,
440 &mut ctx,
441 );
442 }
443
444 match camel_dsl::discover_routes_with_threshold_and_security(
452 &patterns,
453 camel_config.stream_caching.threshold,
454 security_compile_context.clone(),
455 ) {
456 Ok(defs) => {
457 #[cfg(feature = "exec")]
460 {
461 let exec_used = camel_core::startup_validation::route_definitions_reference_scheme(
462 &defs, "exec",
463 );
464 let exec_configured = camel_config.components.raw.contains_key("exec");
465 if exec_used || exec_configured {
466 register_bundle!(ctx, camel_config, camel_component_exec::ExecBundle);
467 }
468 }
469
470 for check in
475 camel_core::startup_validation::scan_route_definitions_for_sql_checks(&defs)
476 {
477 ctx.add_startup_check(check);
478 }
479 let defs = crate::commands::bench_instrument::maybe_instrument_routes(defs);
482 for def in defs {
483 let id = def.route_id().to_string();
484 if let Err(e) = ctx.add_route_definition(def).await {
485 tracing::error!("Failed to add route '{}': {}", id, e);
487 }
488 }
489 }
490 Err(e) => {
491 tracing::error!("Failed to discover routes: {}", e);
493 std::process::exit(1);
494 }
495 }
496
497 if let Err(e) = ctx.start().await {
499 tracing::error!("Failed to start CamelContext: {}", e);
501 std::process::exit(1);
502 }
503
504 tracing::info!("camel-cli: context started");
505
506 let watch_enabled = cli_watch.unwrap_or(camel_config.watch);
509
510 let watcher_shutdown = CancellationToken::new();
512 if watch_enabled {
513 let ctrl = ctx.runtime_execution_handle();
514 let watch_patterns = patterns.clone();
515 let watch_security_compile_context = security_compile_context.clone();
516 let drain_timeout = std::time::Duration::from_millis(camel_config.drain_timeout_ms);
517 let debounce = std::time::Duration::from_millis(camel_config.watch_debounce_ms);
518 let watcher_token = watcher_shutdown.clone();
519 tokio::spawn(async move {
520 let watch_dirs = camel_core::reload_watcher::resolve_watch_dirs(&watch_patterns);
521 let result = camel_core::reload_watcher::watch_and_reload(
522 watch_dirs,
523 ctrl,
524 move || {
525 camel_dsl::discover_routes_with_threshold_and_security(
526 &watch_patterns,
527 camel_config.stream_caching.threshold,
528 watch_security_compile_context.clone(),
529 )
530 .map_err(|e| camel_api::CamelError::RouteError(e.to_string()))
531 },
532 Some(watcher_token),
533 drain_timeout,
534 debounce,
535 )
536 .await;
537 if let Err(e) = result {
538 tracing::error!("File watcher failed: {}", e);
540 }
541 });
542 tracing::info!(
543 "camel-cli: hot-reload watching {:?}. Press Ctrl+C to stop.",
544 patterns
545 );
546 } else {
547 tracing::info!("camel-cli: running (hot-reload disabled). Press Ctrl+C to stop.");
548 }
549
550 tokio::select! {
551 _ = tokio::signal::ctrl_c() => tracing::info!("Received Ctrl+C"),
552 _ = async {
553 #[cfg(unix)]
554 {
555 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
556 .expect("Failed to install SIGTERM handler") .recv()
558 .await
559 }
560 #[cfg(not(unix))]
561 {
562 std::future::pending::<()>().await
563 }
564 } => tracing::info!("Received SIGTERM"),
565 }
566
567 let force_exit = tokio::spawn(async {
569 tokio::signal::ctrl_c().await.ok();
570 tracing::warn!("Second Ctrl+C — forcing exit");
571 std::process::exit(1);
572 });
573
574 tracing::info!("camel-cli: shutting down...");
575 watcher_shutdown.cancel();
576
577 jms_pool.begin_shutdown();
579 cxf_pool.begin_shutdown();
580
581 ctx.stop().await.unwrap_or_else(|e| {
583 tracing::error!("Error during shutdown: {}", e);
585 });
586
587 const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
589
590 match tokio::time::timeout(SHUTDOWN_TIMEOUT, jms_pool.shutdown()).await {
591 Ok(Ok(())) => {}
592 Ok(Err(e)) => {
593 tracing::error!("JMS pool shutdown failed: {}", e);
595 }
596 Err(_) => tracing::warn!("JMS pool shutdown timed out after 30s"),
597 }
598
599 match tokio::time::timeout(SHUTDOWN_TIMEOUT, cxf_pool.shutdown()).await {
600 Ok(Ok(())) => {}
601 Ok(Err(e)) => {
602 tracing::error!("CXF pool shutdown failed: {}", e);
604 }
605 Err(_) => tracing::warn!("CXF pool shutdown timed out after 30s"),
606 }
607
608 force_exit.abort();
609
610 tracing::info!("camel-cli: stopped");
611 Ok(())
612}
613
614#[cfg(test)]
619mod tests {
620 #[test]
622 fn startup_warning_emitted() {
623 let source = include_str!("run.rs");
624 let a = "camel run trusts the current working directory";
627 let b = " and will execute route";
628 let msg = format!("{a}{b}");
629 let count = source.matches(&msg).count();
630 assert_eq!(
631 count, 1,
632 "expected exactly one tracing::warn! with the trust-model message in run.rs; found {count}"
633 );
634 }
635
636 #[test]
638 fn clap_help_documents_trust_model() {
639 let source = include_str!("../main.rs");
640 let has_trust_doc = source
641 .contains("Trust model: `camel run` executes route scripts, WASM modules, and beans")
642 || source
643 .contains("Trust model: camel run executes route scripts, WASM modules, and beans");
644 assert!(
645 has_trust_doc,
646 "expected trust model documentation in the Run subcommand help in main.rs"
647 );
648 }
649}