Skip to main content

schedr_tls/
reload.rs

1//! The configurations in use, read again when the files change (rotation without a restart).
2//!
3//! Kubernetes updates a mounted Secret by swapping a symbolic link, so the files are polled
4//! (`[tls] reload_interval`, 30 s by default) rather than watched. A change is used once all
5//! three files read and go together; until then the previous material stays in use, and the
6//! error is logged once per change. New connections use the new material; open ones go on.
7
8use std::sync::{Arc, PoisonError, RwLock};
9use std::time::Duration;
10
11use rustls::{ClientConfig, ServerConfig};
12
13use crate::material::{Configs, Contents, TlsError, TlsFiles, build};
14
15#[cfg(test)]
16mod tests;
17
18/// A role's TLS material, shared by its servers and clients (cheap to clone).
19#[derive(Debug, Clone)]
20pub struct Tls {
21    inner: Arc<Inner>,
22    handshake_timeout: Duration,
23    handshakes_at_once: usize,
24}
25
26#[derive(Debug)]
27struct Inner {
28    files: TlsFiles,
29    worker_name: String,
30    ui_name: String,
31    state: RwLock<State>,
32}
33
34#[derive(Debug)]
35struct State {
36    contents: Contents,
37    configs: Configs,
38    generation: u64,
39    /// The last error, so a broken change is reported once.
40    failed: Option<String>,
41}
42
43/// What [`Tls::reload`] found.
44#[derive(Debug)]
45pub enum Reload {
46    /// The files are as they were (or as they were when they last failed).
47    Unchanged,
48    /// The files changed and are in use now.
49    Reloaded,
50    /// The files changed but can't be used; the previous material stays in use.
51    Failed(TlsError),
52}
53
54impl Tls {
55    /// Reads `files`; workers' certificates must name `worker_name`, `schedr ui`'s
56    /// `ui_name` (on a webserver's UI port).
57    ///
58    /// # Errors
59    ///
60    /// [`TlsError`] if the files can't be read or used.
61    pub fn load(files: TlsFiles, worker_name: &str, ui_name: &str) -> Result<Self, TlsError> {
62        let contents = files.read()?;
63        let configs = build(&contents, &files, (worker_name, ui_name))?;
64        Ok(Self {
65            inner: Arc::new(Inner {
66                files,
67                worker_name: worker_name.to_owned(),
68                ui_name: ui_name.to_owned(),
69                state: RwLock::new(State {
70                    contents,
71                    configs,
72                    generation: 0,
73                    failed: None,
74                }),
75            }),
76            handshake_timeout: crate::incoming::HANDSHAKE_TIMEOUT,
77            handshakes_at_once: crate::incoming::MAX_HANDSHAKES,
78        })
79    }
80
81    /// This, giving peers `timeout` to complete a handshake (`handshake_timeout`).
82    #[must_use]
83    pub fn with_handshake_timeout(self, timeout: Duration) -> Self {
84        Self {
85            handshake_timeout: timeout,
86            ..self
87        }
88    }
89
90    /// How long a peer has to complete a handshake.
91    #[must_use]
92    pub const fn handshake_timeout(&self) -> Duration {
93        self.handshake_timeout
94    }
95
96    /// This, running at most `most` handshakes at once (`SCHEDR_HIDDEN__TLS__HANDSHAKES_AT_ONCE`).
97    #[must_use]
98    pub fn with_handshakes_at_once(self, most: usize) -> Self {
99        Self {
100            handshakes_at_once: most.max(1),
101            ..self
102        }
103    }
104
105    /// How many handshakes a listener runs at once.
106    #[must_use]
107    pub const fn handshakes_at_once(&self) -> usize {
108        self.handshakes_at_once
109    }
110
111    fn configs(&self) -> Configs {
112        self.inner
113            .state
114            .read()
115            .unwrap_or_else(PoisonError::into_inner)
116            .configs
117            .clone()
118    }
119
120    /// The master's gRPC server configuration.
121    #[must_use]
122    pub fn grpc_server(&self) -> Arc<ServerConfig> {
123        self.configs().grpc_server
124    }
125
126    /// A worker's log endpoint configuration.
127    #[must_use]
128    pub fn http_server(&self) -> Arc<ServerConfig> {
129        self.configs().http_server
130    }
131
132    /// A worker's client configuration towards the master.
133    #[must_use]
134    pub fn grpc_client(&self) -> Arc<ClientConfig> {
135        self.configs().grpc_client
136    }
137
138    /// The webserver's client configuration towards workers.
139    #[must_use]
140    pub fn worker_client(&self) -> Arc<ClientConfig> {
141        self.configs().worker_client
142    }
143
144    /// A webserver's UI port configuration (only `schedr ui`'s certificate passes).
145    #[must_use]
146    pub fn ui_server(&self) -> Arc<ServerConfig> {
147        self.configs().ui_server
148    }
149
150    /// `schedr ui`'s client configuration towards webservers' UI ports.
151    #[must_use]
152    pub fn api_client(&self) -> Arc<ClientConfig> {
153        self.configs().api_client
154    }
155
156    /// How many times the material changed (clients built from it are rebuilt when it does).
157    #[must_use]
158    pub fn generation(&self) -> u64 {
159        self.inner
160            .state
161            .read()
162            .unwrap_or_else(PoisonError::into_inner)
163            .generation
164    }
165
166    /// Reads the files again and uses them if they changed and can be used.
167    pub fn reload(&self) -> Reload {
168        let read = self.inner.files.read();
169        let mut state = self
170            .inner
171            .state
172            .write()
173            .unwrap_or_else(PoisonError::into_inner);
174        let built = read.and_then(|contents| {
175            if contents == state.contents {
176                return Ok(None);
177            }
178            let names = (self.inner.worker_name.as_str(), self.inner.ui_name.as_str());
179            let configs = build(&contents, &self.inner.files, names)?;
180            Ok(Some((contents, configs)))
181        });
182        match built {
183            Ok(None) => {
184                state.failed = None;
185                Reload::Unchanged
186            }
187            Ok(Some((contents, configs))) => {
188                state.contents = contents;
189                state.configs = configs;
190                state.generation += 1;
191                state.failed = None;
192                Reload::Reloaded
193            }
194            Err(error) => {
195                let text = error.to_string();
196                if state.failed.as_ref() == Some(&text) {
197                    return Reload::Unchanged;
198                }
199                state.failed = Some(text);
200                Reload::Failed(error)
201            }
202        }
203    }
204
205    /// Reloads every `interval` until `stop` completes, logging what changed.
206    pub async fn watch(self, interval: Duration, stop: impl Future<Output = ()>) {
207        tokio::pin!(stop);
208        let mut tick = tokio::time::interval(interval);
209        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
210        tick.tick().await;
211        loop {
212            tokio::select! {
213                () = &mut stop => return,
214                _ = tick.tick() => match self.reload() {
215                    Reload::Unchanged => {}
216                    Reload::Reloaded => tracing::info!(
217                        cert = %self.inner.files.cert.display(),
218                        "TLS certificates changed: new connections use them"
219                    ),
220                    Reload::Failed(error) => tracing::error!(
221                        %error,
222                        "TLS certificates changed but can't be used; keeping the previous ones"
223                    ),
224                },
225            }
226        }
227    }
228}