Skip to main content

tuwunel_service/config/
mod.rs

1//! Reloadable homeserver configuration.
2//!
3//! The service exposes the active configuration and replaces it after validation.
4//! Reloads replay the startup sources so command-line paths and overrides remain in force.
5
6#[cfg(test)]
7mod tests;
8
9#[cfg(all(feature = "systemd", target_os = "linux"))]
10use std::borrow::Cow;
11use std::{iter::empty, ops::Deref, path::Path, sync::Arc};
12
13use async_trait::async_trait;
14#[cfg(all(feature = "systemd", target_os = "linux"))]
15use sd_notify::{NotifyState, notify};
16#[cfg(all(feature = "systemd", target_os = "linux"))]
17use tuwunel_core::itertools::Itertools;
18use tuwunel_core::{
19	Result, Server,
20	config::{Config, check::reload as check_reload},
21	error, implement,
22};
23
24/// Provides access to the active configuration and its reload path.
25///
26/// Values are read through the shared server configuration handle. Reloads publish a
27/// replacement only after the new configuration passes the reload checks.
28pub struct Service {
29	server: Arc<Server>,
30}
31
32const SIGNAL: &str = "SIGUSR1";
33
34/// Cap on the status reported to the service manager, which displays one line.
35#[cfg(all(feature = "systemd", target_os = "linux"))]
36const STATUS_MAX: usize = 192;
37
38#[async_trait]
39impl crate::Service for Service {
40	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
41		Ok(Arc::new(Self { server: args.server.clone() }))
42	}
43
44	async fn worker(self: Arc<Self>) -> Result {
45		let mut signaled = self.server.signal.subscribe();
46		while self.server.is_running() {
47			tokio::select! {
48				() = self.server.until_shutdown() => break,
49				signal = signaled.recv() => if signal !=  Ok(SIGNAL) { continue; },
50			}
51
52			if let Err(e) = self.handle_reload() {
53				error!("Failed to reload config: {e}");
54			}
55		}
56
57		Ok(())
58	}
59
60	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
61}
62
63impl Deref for Service {
64	type Target = Arc<Config>;
65
66	#[inline]
67	fn deref(&self) -> &Self::Target { &self.server.config }
68}
69
70#[implement(Service)]
71fn handle_reload(&self) -> Result {
72	// The handshake completes even when reloading is switched off, since the
73	// service manager is already waiting on it by the time the signal arrives.
74	#[cfg(all(feature = "systemd", target_os = "linux"))]
75	NotifyState::monotonic_usec_now()
76		.and_then(|monotonic| notify(&[NotifyState::Reloading, monotonic]))
77		.inspect_err(|e| error!(%e, "failed to notify systemd of reloading state"))
78		.ok();
79
80	let reloaded = self
81		.server
82		.config
83		.configuration
84		.reload_signal
85		.then(|| self.reload(empty()))
86		.transpose();
87
88	// Ready even on failure, since the old config stays in service; the outcome
89	// travels in the status string instead.
90	#[cfg(all(feature = "systemd", target_os = "linux"))]
91	{
92		let status: Cow<'_, str> = match &reloaded {
93			| Ok(Some(_)) => "Configuration reloaded".into(),
94			| Ok(None) => "Configuration reloading is disabled".into(),
95			| Err(e) => format!("Configuration rejected: {e}").into(),
96		};
97
98		notify(&[NotifyState::Ready, NotifyState::Status(&one_line(&status))])
99			.inspect_err(|e| error!(%e, "failed to notify systemd of ready state"))
100			.ok();
101	};
102
103	reloaded?;
104
105	Ok(())
106}
107
108/// The notify protocol delimits assignments by newline and does no escaping, so
109/// a status carrying one would be read as further assignments.
110#[cfg(all(feature = "systemd", target_os = "linux"))]
111fn one_line(status: &str) -> String {
112	status
113		.split_whitespace()
114		.join(" ")
115		.chars()
116		.take(STATUS_MAX)
117		.collect()
118}
119
120/// Loads, validates, and publishes a replacement configuration.
121///
122/// The stored startup sources are replayed together with `paths`. The active configuration
123/// remains unchanged when loading or reload validation fails.
124#[implement(Service)]
125pub fn reload<'a, I>(&'a self, paths: I) -> Result<Arc<Config>>
126where
127	I: Iterator<Item = &'a Path>,
128{
129	// Replay the startup command line so -c paths and -O overrides survive.
130	self.server
131		.config_sources
132		.load(paths)
133		.and_then(|raw| Config::new(&raw))
134		.and_then(|new| self.replace(new))
135}
136
137/// Validates and publishes a replacement configuration.
138///
139/// The active configuration remains unchanged when reload validation fails.
140#[implement(Service)]
141pub fn replace(&self, new: Config) -> Result<Arc<Config>> {
142	let old = self.server.config.clone();
143
144	check_reload(&old, &new)?;
145	self.server.config.update(new)
146}