vector/
app.rs

1#![allow(missing_docs)]
2#[cfg(unix)]
3use std::os::unix::process::ExitStatusExt;
4#[cfg(windows)]
5use std::os::windows::process::ExitStatusExt;
6use std::{
7    num::{NonZeroU64, NonZeroUsize},
8    path::PathBuf,
9    process::ExitStatus,
10    sync::atomic::{AtomicUsize, Ordering},
11    time::Duration,
12};
13
14use exitcode::ExitCode;
15use futures::StreamExt;
16use tokio::{
17    runtime::{self, Handle, Runtime},
18    sync::{MutexGuard, broadcast::error::RecvError},
19};
20use tokio_stream::wrappers::UnboundedReceiverStream;
21
22#[cfg(feature = "api")]
23use crate::{api, internal_events::ApiStarted};
24use crate::{
25    cli::{LogFormat, Opts, RootOpts, WatchConfigMethod, handle_config_errors},
26    config::{self, ComponentConfig, ComponentType, Config, ConfigPath},
27    extra_context::ExtraContext,
28    heartbeat,
29    internal_events::{VectorConfigLoadError, VectorQuit, VectorStarted, VectorStopped},
30    signal::{SignalHandler, SignalPair, SignalRx, SignalTo},
31    topology::{
32        ReloadOutcome, RunningTopology, SharedTopologyController, ShutdownErrorReceiver,
33        TopologyController,
34    },
35    trace,
36};
37
38static WORKER_THREADS: AtomicUsize = AtomicUsize::new(0);
39
40pub fn worker_threads() -> Option<NonZeroUsize> {
41    NonZeroUsize::new(WORKER_THREADS.load(Ordering::Relaxed))
42}
43
44pub struct ApplicationConfig {
45    pub config_paths: Vec<config::ConfigPath>,
46    pub topology: RunningTopology,
47    pub graceful_crash_receiver: ShutdownErrorReceiver,
48    pub internal_topologies: Vec<RunningTopology>,
49    #[cfg(feature = "api")]
50    pub api: config::api::Options,
51    pub extra_context: ExtraContext,
52}
53
54pub struct Application {
55    pub root_opts: RootOpts,
56    pub config: ApplicationConfig,
57    pub signals: SignalPair,
58}
59
60impl ApplicationConfig {
61    pub async fn from_opts(
62        opts: &RootOpts,
63        signal_handler: &mut SignalHandler,
64        extra_context: ExtraContext,
65    ) -> Result<Self, ExitCode> {
66        let config_paths = opts.config_paths_with_formats();
67
68        let graceful_shutdown_duration = (!opts.no_graceful_shutdown_limit)
69            .then(|| Duration::from_secs(u64::from(opts.graceful_shutdown_limit_secs)));
70
71        let watcher_conf = if opts.watch_config {
72            Some(watcher_config(
73                opts.watch_config_method,
74                opts.watch_config_poll_interval_seconds,
75            ))
76        } else {
77            None
78        };
79
80        let config = load_configs(
81            &config_paths,
82            watcher_conf,
83            opts.require_healthy,
84            opts.allow_empty_config,
85            graceful_shutdown_duration,
86            signal_handler,
87        )
88        .await?;
89
90        Self::from_config(config_paths, config, extra_context).await
91    }
92
93    pub async fn from_config(
94        config_paths: Vec<ConfigPath>,
95        config: Config,
96        extra_context: ExtraContext,
97    ) -> Result<Self, ExitCode> {
98        #[cfg(feature = "api")]
99        let api = config.api;
100
101        let (topology, graceful_crash_receiver) =
102            RunningTopology::start_init_validated(config, extra_context.clone())
103                .await
104                .ok_or(exitcode::CONFIG)?;
105
106        Ok(Self {
107            config_paths,
108            topology,
109            graceful_crash_receiver,
110            internal_topologies: Vec::new(),
111            #[cfg(feature = "api")]
112            api,
113            extra_context,
114        })
115    }
116
117    pub async fn add_internal_config(
118        &mut self,
119        config: Config,
120        extra_context: ExtraContext,
121    ) -> Result<(), ExitCode> {
122        let Some((topology, _)) =
123            RunningTopology::start_init_validated(config, extra_context).await
124        else {
125            return Err(exitcode::CONFIG);
126        };
127        self.internal_topologies.push(topology);
128        Ok(())
129    }
130
131    /// Configure the API server, if applicable
132    #[cfg(feature = "api")]
133    pub fn setup_api(&self, handle: &Handle) -> Option<api::Server> {
134        if self.api.enabled {
135            match api::Server::start(
136                self.topology.config(),
137                self.topology.watch(),
138                std::sync::Arc::clone(&self.topology.running),
139                handle,
140            ) {
141                Ok(api_server) => {
142                    emit!(ApiStarted {
143                        addr: self.api.address.unwrap(),
144                        playground: self.api.playground,
145                        graphql: self.api.graphql
146                    });
147
148                    Some(api_server)
149                }
150                Err(error) => {
151                    let error = error.to_string();
152                    error!("An error occurred that Vector couldn't handle: {}.", error);
153                    _ = self
154                        .topology
155                        .abort_tx
156                        .send(crate::signal::ShutdownError::ApiFailed { error });
157                    None
158                }
159            }
160        } else {
161            info!(
162                message = "API is disabled, enable by setting `api.enabled` to `true` and use commands like `vector top`."
163            );
164            None
165        }
166    }
167}
168
169impl Application {
170    pub fn run(extra_context: ExtraContext) -> ExitStatus {
171        let (runtime, app) =
172            Self::prepare_start(extra_context).unwrap_or_else(|code| std::process::exit(code));
173
174        runtime.block_on(app.run())
175    }
176
177    pub fn prepare_start(
178        extra_context: ExtraContext,
179    ) -> Result<(Runtime, StartedApplication), ExitCode> {
180        Self::prepare(extra_context)
181            .and_then(|(runtime, app)| app.start(runtime.handle()).map(|app| (runtime, app)))
182    }
183
184    pub fn prepare(extra_context: ExtraContext) -> Result<(Runtime, Self), ExitCode> {
185        let opts = Opts::get_matches().map_err(|error| {
186            // Printing to stdout/err can itself fail; ignore it.
187            _ = error.print();
188            exitcode::USAGE
189        })?;
190
191        Self::prepare_from_opts(opts, extra_context)
192    }
193
194    pub fn prepare_from_opts(
195        opts: Opts,
196        extra_context: ExtraContext,
197    ) -> Result<(Runtime, Self), ExitCode> {
198        opts.root.init_global();
199
200        let color = opts.root.color.use_color();
201
202        init_logging(
203            color,
204            opts.root.log_format,
205            opts.log_level(),
206            opts.root.internal_log_rate_limit,
207        );
208
209        // Can only log this after initializing the logging subsystem
210        if opts.root.openssl_no_probe {
211            debug!(
212                message = "Disabled probing and configuration of root certificate locations on the system for OpenSSL."
213            );
214        }
215
216        let runtime = build_runtime(opts.root.threads, "vector-worker")?;
217
218        // Signal handler for OS and provider messages.
219        let mut signals = SignalPair::new(&runtime);
220
221        if let Some(sub_command) = &opts.sub_command {
222            return Err(runtime.block_on(sub_command.execute(signals, color)));
223        }
224
225        let config = runtime.block_on(ApplicationConfig::from_opts(
226            &opts.root,
227            &mut signals.handler,
228            extra_context,
229        ))?;
230
231        Ok((
232            runtime,
233            Self {
234                root_opts: opts.root,
235                config,
236                signals,
237            },
238        ))
239    }
240
241    pub fn start(self, handle: &Handle) -> Result<StartedApplication, ExitCode> {
242        // Any internal_logs sources will have grabbed a copy of the
243        // early buffer by this point and set up a subscriber.
244        crate::trace::stop_early_buffering();
245
246        emit!(VectorStarted);
247        handle.spawn(heartbeat::heartbeat());
248
249        let Self {
250            root_opts,
251            config,
252            signals,
253        } = self;
254
255        let topology_controller = SharedTopologyController::new(TopologyController {
256            #[cfg(feature = "api")]
257            api_server: config.setup_api(handle),
258            topology: config.topology,
259            config_paths: config.config_paths.clone(),
260            require_healthy: root_opts.require_healthy,
261            extra_context: config.extra_context,
262        });
263
264        Ok(StartedApplication {
265            config_paths: config.config_paths,
266            internal_topologies: config.internal_topologies,
267            graceful_crash_receiver: config.graceful_crash_receiver,
268            signals,
269            topology_controller,
270            allow_empty_config: root_opts.allow_empty_config,
271        })
272    }
273}
274
275pub struct StartedApplication {
276    pub config_paths: Vec<ConfigPath>,
277    pub internal_topologies: Vec<RunningTopology>,
278    pub graceful_crash_receiver: ShutdownErrorReceiver,
279    pub signals: SignalPair,
280    pub topology_controller: SharedTopologyController,
281    pub allow_empty_config: bool,
282}
283
284impl StartedApplication {
285    pub async fn run(self) -> ExitStatus {
286        self.main().await.shutdown().await
287    }
288
289    pub async fn main(self) -> FinishedApplication {
290        let Self {
291            config_paths,
292            graceful_crash_receiver,
293            signals,
294            topology_controller,
295            internal_topologies,
296            allow_empty_config,
297        } = self;
298
299        let mut graceful_crash = UnboundedReceiverStream::new(graceful_crash_receiver);
300
301        let mut signal_handler = signals.handler;
302        let mut signal_rx = signals.receiver;
303
304        let signal = loop {
305            let has_sources = !topology_controller.lock().await.topology.config.is_empty();
306            tokio::select! {
307                signal = signal_rx.recv() => if let Some(signal) = handle_signal(
308                    signal,
309                    &topology_controller,
310                    &config_paths,
311                    &mut signal_handler,
312                    allow_empty_config,
313                ).await {
314                    break signal;
315                },
316                // Trigger graceful shutdown if a component crashed, or all sources have ended.
317                error = graceful_crash.next() => break SignalTo::Shutdown(error),
318                _ = TopologyController::sources_finished(topology_controller.clone()), if has_sources => {
319                    info!("All sources have finished.");
320                    break SignalTo::Shutdown(None)
321                } ,
322                else => unreachable!("Signal streams never end"),
323            }
324        };
325
326        FinishedApplication {
327            signal,
328            signal_rx,
329            topology_controller,
330            internal_topologies,
331        }
332    }
333}
334
335async fn handle_signal(
336    signal: Result<SignalTo, RecvError>,
337    topology_controller: &SharedTopologyController,
338    config_paths: &[ConfigPath],
339    signal_handler: &mut SignalHandler,
340    allow_empty_config: bool,
341) -> Option<SignalTo> {
342    match signal {
343        Ok(SignalTo::ReloadComponents(components_to_reload)) => {
344            let mut topology_controller = topology_controller.lock().await;
345            topology_controller
346                .topology
347                .extend_reload_set(components_to_reload);
348
349            // Reload paths
350            if let Some(paths) = config::process_paths(config_paths) {
351                topology_controller.config_paths = paths;
352            }
353
354            // Reload config
355            let new_config = config::load_from_paths_with_provider_and_secrets(
356                &topology_controller.config_paths,
357                signal_handler,
358                allow_empty_config,
359            )
360            .await;
361
362            reload_config_from_result(topology_controller, new_config).await
363        }
364        Ok(SignalTo::ReloadFromConfigBuilder(config_builder)) => {
365            let topology_controller = topology_controller.lock().await;
366            reload_config_from_result(topology_controller, config_builder.build()).await
367        }
368        Ok(SignalTo::ReloadFromDisk) => {
369            let mut topology_controller = topology_controller.lock().await;
370
371            // Reload paths
372            if let Some(paths) = config::process_paths(config_paths) {
373                topology_controller.config_paths = paths;
374            }
375
376            // Reload config
377            let new_config = config::load_from_paths_with_provider_and_secrets(
378                &topology_controller.config_paths,
379                signal_handler,
380                allow_empty_config,
381            )
382            .await;
383
384            reload_config_from_result(topology_controller, new_config).await
385        }
386        Ok(SignalTo::ReloadEnrichmentTables) => {
387            let topology_controller = topology_controller.lock().await;
388
389            topology_controller
390                .topology
391                .reload_enrichment_tables()
392                .await;
393            None
394        }
395        Err(RecvError::Lagged(amt)) => {
396            warn!("Overflow, dropped {} signals.", amt);
397            None
398        }
399        Err(RecvError::Closed) => Some(SignalTo::Shutdown(None)),
400        Ok(signal) => Some(signal),
401    }
402}
403
404async fn reload_config_from_result(
405    mut topology_controller: MutexGuard<'_, TopologyController>,
406    config: Result<Config, Vec<String>>,
407) -> Option<SignalTo> {
408    match config {
409        Ok(new_config) => match topology_controller.reload(new_config).await {
410            ReloadOutcome::FatalError(error) => Some(SignalTo::Shutdown(Some(error))),
411            _ => None,
412        },
413        Err(errors) => {
414            handle_config_errors(errors);
415            emit!(VectorConfigLoadError);
416            None
417        }
418    }
419}
420
421pub struct FinishedApplication {
422    pub signal: SignalTo,
423    pub signal_rx: SignalRx,
424    pub topology_controller: SharedTopologyController,
425    pub internal_topologies: Vec<RunningTopology>,
426}
427
428impl FinishedApplication {
429    pub async fn shutdown(self) -> ExitStatus {
430        let FinishedApplication {
431            signal,
432            signal_rx,
433            topology_controller,
434            internal_topologies,
435        } = self;
436
437        // At this point, we'll have the only reference to the shared topology controller and can
438        // safely remove it from the wrapper to shut down the topology.
439        let topology_controller = topology_controller
440            .try_into_inner()
441            .expect("fail to unwrap topology controller")
442            .into_inner();
443
444        let status = match signal {
445            SignalTo::Shutdown(_) => Self::stop(topology_controller, signal_rx).await,
446            SignalTo::Quit => Self::quit(),
447            _ => unreachable!(),
448        };
449
450        for topology in internal_topologies {
451            topology.stop().await;
452        }
453
454        status
455    }
456
457    async fn stop(topology_controller: TopologyController, mut signal_rx: SignalRx) -> ExitStatus {
458        emit!(VectorStopped);
459        tokio::select! {
460            _ = topology_controller.stop() => ExitStatus::from_raw({
461                #[cfg(windows)]
462                {
463                    exitcode::OK as u32
464                }
465                #[cfg(unix)]
466                exitcode::OK
467            }), // Graceful shutdown finished
468            _ = signal_rx.recv() => Self::quit(),
469        }
470    }
471
472    fn quit() -> ExitStatus {
473        // It is highly unlikely that this event will exit from topology.
474        emit!(VectorQuit);
475        ExitStatus::from_raw({
476            #[cfg(windows)]
477            {
478                exitcode::UNAVAILABLE as u32
479            }
480            #[cfg(unix)]
481            exitcode::OK
482        })
483    }
484}
485
486fn get_log_levels(default: &str) -> String {
487    std::env::var("VECTOR_LOG")
488        .or_else(|_| {
489            std::env::var("LOG").inspect(|_log| {
490                warn!(
491                    message =
492                        "DEPRECATED: Use of $LOG is deprecated. Please use $VECTOR_LOG instead."
493                );
494            })
495        })
496        .unwrap_or_else(|_| default.into())
497}
498
499pub fn build_runtime(threads: Option<usize>, thread_name: &str) -> Result<Runtime, ExitCode> {
500    let mut rt_builder = runtime::Builder::new_multi_thread();
501    rt_builder.max_blocking_threads(20_000);
502    rt_builder.enable_all().thread_name(thread_name);
503
504    let threads = threads.unwrap_or_else(crate::num_threads);
505    if threads == 0 {
506        error!("The `threads` argument must be greater or equal to 1.");
507        return Err(exitcode::CONFIG);
508    }
509    WORKER_THREADS
510        .compare_exchange(0, threads, Ordering::Acquire, Ordering::Relaxed)
511        .unwrap_or_else(|_| panic!("double thread initialization"));
512    rt_builder.worker_threads(threads);
513
514    debug!(messaged = "Building runtime.", worker_threads = threads);
515    Ok(rt_builder.build().expect("Unable to create async runtime"))
516}
517
518pub async fn load_configs(
519    config_paths: &[ConfigPath],
520    watcher_conf: Option<config::watcher::WatcherConfig>,
521    require_healthy: Option<bool>,
522    allow_empty_config: bool,
523    graceful_shutdown_duration: Option<Duration>,
524    signal_handler: &mut SignalHandler,
525) -> Result<Config, ExitCode> {
526    let config_paths = config::process_paths(config_paths).ok_or(exitcode::CONFIG)?;
527
528    let watched_paths = config_paths
529        .iter()
530        .map(<&PathBuf>::from)
531        .collect::<Vec<_>>();
532
533    info!(
534        message = "Loading configs.",
535        paths = ?watched_paths
536    );
537
538    let mut config = config::load_from_paths_with_provider_and_secrets(
539        &config_paths,
540        signal_handler,
541        allow_empty_config,
542    )
543    .await
544    .map_err(handle_config_errors)?;
545
546    let mut watched_component_paths = Vec::new();
547
548    if let Some(watcher_conf) = watcher_conf {
549        for (name, transform) in config.transforms() {
550            let files = transform.inner.files_to_watch();
551            let component_config = ComponentConfig::new(
552                files.into_iter().cloned().collect(),
553                name.clone(),
554                ComponentType::Transform,
555            );
556            watched_component_paths.push(component_config);
557        }
558
559        for (name, sink) in config.sinks() {
560            let files = sink.inner.files_to_watch();
561            let component_config = ComponentConfig::new(
562                files.into_iter().cloned().collect(),
563                name.clone(),
564                ComponentType::Sink,
565            );
566            watched_component_paths.push(component_config);
567        }
568
569        for (name, table) in config.enrichment_tables() {
570            let files = table.inner.files_to_watch();
571            let component_config = ComponentConfig::new(
572                files.into_iter().cloned().collect(),
573                name.clone(),
574                ComponentType::EnrichmentTable,
575            );
576            watched_component_paths.push(component_config);
577        }
578
579        info!(
580            message = "Starting watcher.",
581            paths = ?watched_paths
582        );
583        info!(
584            message = "Components to watch.",
585            paths = ?watched_component_paths
586        );
587
588        // Start listening for config changes.
589        config::watcher::spawn_thread(
590            watcher_conf,
591            signal_handler.clone_tx(),
592            watched_paths,
593            watched_component_paths,
594            None,
595        )
596        .map_err(|error| {
597            error!(message = "Unable to start config watcher.", %error);
598            exitcode::CONFIG
599        })?;
600    }
601
602    config::init_log_schema(config.global.log_schema.clone(), true);
603    config::init_telemetry(config.global.telemetry.clone(), true);
604
605    if !config.healthchecks.enabled {
606        info!("Health checks are disabled.");
607    }
608    config.healthchecks.set_require_healthy(require_healthy);
609    config.graceful_shutdown_duration = graceful_shutdown_duration;
610
611    Ok(config)
612}
613
614pub fn init_logging(color: bool, format: LogFormat, log_level: &str, rate: u64) {
615    let level = get_log_levels(log_level);
616    let json = match format {
617        LogFormat::Text => false,
618        LogFormat::Json => true,
619    };
620
621    trace::init(color, json, &level, rate);
622    debug!(
623        message = "Internal log rate limit configured.",
624        internal_log_rate_secs = rate,
625    );
626    info!(message = "Log level is enabled.", level = ?level);
627}
628
629pub fn watcher_config(
630    method: WatchConfigMethod,
631    interval: NonZeroU64,
632) -> config::watcher::WatcherConfig {
633    match method {
634        WatchConfigMethod::Recommended => config::watcher::WatcherConfig::RecommendedWatcher,
635        WatchConfigMethod::Poll => config::watcher::WatcherConfig::PollWatcher(interval.into()),
636    }
637}