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 = "wasm")]
424 {
425 let base_dir = std::path::Path::new(&config_path)
426 .parent()
427 .unwrap_or(std::path::Path::new("."))
428 .to_path_buf();
429 let wasm_bundle = camel_component_wasm::WasmBundle::new(
430 Arc::new(camel_core::RegistryComponentContext::new(
431 ctx.registry_arc(),
432 )),
433 base_dir,
434 );
435 <camel_component_wasm::WasmBundle as camel_component_api::ComponentBundle>::register_all(
436 wasm_bundle,
437 &mut ctx,
438 );
439 }
440
441 match camel_dsl::discover_routes_with_threshold_and_security(
449 &patterns,
450 camel_config.stream_caching.threshold,
451 security_compile_context.clone(),
452 ) {
453 Ok(defs) => {
454 #[cfg(feature = "exec")]
457 {
458 let exec_used = camel_core::startup_validation::route_definitions_reference_scheme(
459 &defs, "exec",
460 );
461 let exec_configured = camel_config.components.raw.contains_key("exec");
462 if exec_used || exec_configured {
463 register_bundle!(ctx, camel_config, camel_component_exec::ExecBundle);
464 }
465 }
466
467 for check in
472 camel_core::startup_validation::scan_route_definitions_for_sql_checks(&defs)
473 {
474 ctx.add_startup_check(check);
475 }
476 let defs = crate::commands::bench_instrument::maybe_instrument_routes(defs);
479 for def in defs {
480 let id = def.route_id().to_string();
481 if let Err(e) = ctx.add_route_definition(def).await {
482 tracing::error!("Failed to add route '{}': {}", id, e);
484 }
485 }
486 }
487 Err(e) => {
488 tracing::error!("Failed to discover routes: {}", e);
490 std::process::exit(1);
491 }
492 }
493
494 if let Err(e) = ctx.start().await {
496 tracing::error!("Failed to start CamelContext: {}", e);
498 std::process::exit(1);
499 }
500
501 tracing::info!("camel-cli: context started");
502
503 let watch_enabled = cli_watch.unwrap_or(camel_config.watch);
506
507 let watcher_shutdown = CancellationToken::new();
509 if watch_enabled {
510 let ctrl = ctx.runtime_execution_handle();
511 let watch_patterns = patterns.clone();
512 let watch_security_compile_context = security_compile_context.clone();
513 let drain_timeout = std::time::Duration::from_millis(camel_config.drain_timeout_ms);
514 let debounce = std::time::Duration::from_millis(camel_config.watch_debounce_ms);
515 let watcher_token = watcher_shutdown.clone();
516 tokio::spawn(async move {
517 let watch_dirs = camel_core::reload_watcher::resolve_watch_dirs(&watch_patterns);
518 let result = camel_core::reload_watcher::watch_and_reload(
519 watch_dirs,
520 ctrl,
521 move || {
522 camel_dsl::discover_routes_with_threshold_and_security(
523 &watch_patterns,
524 camel_config.stream_caching.threshold,
525 watch_security_compile_context.clone(),
526 )
527 .map_err(|e| camel_api::CamelError::RouteError(e.to_string()))
528 },
529 Some(watcher_token),
530 drain_timeout,
531 debounce,
532 )
533 .await;
534 if let Err(e) = result {
535 tracing::error!("File watcher failed: {}", e);
537 }
538 });
539 tracing::info!(
540 "camel-cli: hot-reload watching {:?}. Press Ctrl+C to stop.",
541 patterns
542 );
543 } else {
544 tracing::info!("camel-cli: running (hot-reload disabled). Press Ctrl+C to stop.");
545 }
546
547 tokio::select! {
548 _ = tokio::signal::ctrl_c() => tracing::info!("Received Ctrl+C"),
549 _ = async {
550 #[cfg(unix)]
551 {
552 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
553 .expect("Failed to install SIGTERM handler") .recv()
555 .await
556 }
557 #[cfg(not(unix))]
558 {
559 std::future::pending::<()>().await
560 }
561 } => tracing::info!("Received SIGTERM"),
562 }
563
564 let force_exit = tokio::spawn(async {
566 tokio::signal::ctrl_c().await.ok();
567 tracing::warn!("Second Ctrl+C — forcing exit");
568 std::process::exit(1);
569 });
570
571 tracing::info!("camel-cli: shutting down...");
572 watcher_shutdown.cancel();
573
574 jms_pool.begin_shutdown();
576 cxf_pool.begin_shutdown();
577
578 ctx.stop().await.unwrap_or_else(|e| {
580 tracing::error!("Error during shutdown: {}", e);
582 });
583
584 const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
586
587 match tokio::time::timeout(SHUTDOWN_TIMEOUT, jms_pool.shutdown()).await {
588 Ok(Ok(())) => {}
589 Ok(Err(e)) => {
590 tracing::error!("JMS pool shutdown failed: {}", e);
592 }
593 Err(_) => tracing::warn!("JMS pool shutdown timed out after 30s"),
594 }
595
596 match tokio::time::timeout(SHUTDOWN_TIMEOUT, cxf_pool.shutdown()).await {
597 Ok(Ok(())) => {}
598 Ok(Err(e)) => {
599 tracing::error!("CXF pool shutdown failed: {}", e);
601 }
602 Err(_) => tracing::warn!("CXF pool shutdown timed out after 30s"),
603 }
604
605 force_exit.abort();
606
607 tracing::info!("camel-cli: stopped");
608 Ok(())
609}
610
611#[cfg(test)]
616mod tests {
617 #[test]
619 fn startup_warning_emitted() {
620 let source = include_str!("run.rs");
621 let a = "camel run trusts the current working directory";
624 let b = " and will execute route";
625 let msg = format!("{a}{b}");
626 let count = source.matches(&msg).count();
627 assert_eq!(
628 count, 1,
629 "expected exactly one tracing::warn! with the trust-model message in run.rs; found {count}"
630 );
631 }
632
633 #[test]
635 fn clap_help_documents_trust_model() {
636 let source = include_str!("../main.rs");
637 let has_trust_doc = source
638 .contains("Trust model: `camel run` executes route scripts, WASM modules, and beans")
639 || source
640 .contains("Trust model: camel run executes route scripts, WASM modules, and beans");
641 assert!(
642 has_trust_doc,
643 "expected trust model documentation in the Run subcommand help in main.rs"
644 );
645 }
646}