Skip to main content

claviron_logging/
system.rs

1//! The system log: a server process's own diagnostics, written to a file by
2//! the process itself.
3//!
4//! Every process of a family — master and each worker — opens the file on
5//! its own with `O_APPEND` and writes each event with one `write`, so their
6//! lines land whole at the end of one file without an fd handed from one to
7//! another and without depending on who started the master or where its
8//! stdout goes. Nothing here touches Orbit: the lines that matter most are
9//! the ones written while something below the server has failed.
10//!
11//! Declared in `logging.yaml`, beside the pipeline's channels:
12//!
13//! ```yaml
14//! system_log:
15//!   path: ${SYSTEM_LOG_PATH}
16//!   format: line
17//!   truncate_on_startup: false # `truncate` is an alias.
18//! ```
19
20use std::fs::{File, OpenOptions};
21use std::io::{self, Write};
22use std::path::{Path, PathBuf};
23use std::sync::{Arc, OnceLock, RwLock};
24
25use claviron_runtime::RunMode;
26use serde::{Deserialize, Serialize};
27
28/// What `logging.yaml` says about the system log. The rest of the file is
29/// the pipeline's and is not read here.
30#[derive(Deserialize)]
31struct LoggingFile {
32    system_log: Option<SystemLogConfig>,
33}
34
35#[derive(Clone, Debug, Deserialize, Serialize)]
36#[serde(deny_unknown_fields)]
37pub struct SystemLogConfig {
38    /// A relative path is the working directory's.
39    pub path: PathBuf,
40    #[serde(default)]
41    pub format: SystemLogFormat,
42    /// Reset only on a new master or standalone launch, never in workers.
43    #[serde(default, alias = "truncate")]
44    pub truncate_on_startup: bool,
45}
46
47#[derive(
48    Clone, Copy, Debug, Default, Deserialize, Serialize, Eq, PartialEq,
49)]
50#[serde(rename_all = "snake_case")]
51pub enum SystemLogFormat {
52    /// The console's line — time, level, target, role, message — without
53    /// colour.
54    #[default]
55    Line,
56}
57
58impl SystemLogConfig {
59    pub fn validate(&self) -> Result<(), crate::Error> {
60        if self.path.as_os_str().is_empty() {
61            return Err(crate::Error::Config(
62                "system_log.path is empty".into(),
63            ));
64        }
65        Ok(())
66    }
67
68    /// Resolve boot-time variables using the same rules as `logging.yaml`.
69    pub fn resolve(
70        &self,
71        lookup: impl Fn(&str) -> Option<String>,
72    ) -> Result<Self, crate::Error> {
73        let raw = serde_yaml::to_string(self)
74            .map_err(|error| crate::Error::Config(error.to_string()))?;
75        let raw = claviron_helpers::yaml::expand_env_with(&raw, lookup)
76            .map_err(|error| crate::Error::Config(error.to_string()))?;
77        serde_yaml::from_str(&raw)
78            .map_err(|error| crate::Error::Config(error.to_string()))
79    }
80}
81
82/// An opened system log.
83pub struct SystemLog {
84    open: Arc<OpenFile>,
85}
86
87/// The file every event is written to, and where it lives, so it can be
88/// opened again after a rotation moved it.
89struct OpenFile {
90    path: PathBuf,
91    file: RwLock<File>,
92}
93
94/// This process's system log, once the logger holds it: what a log reopen
95/// reaches.
96static OPEN: OnceLock<Arc<OpenFile>> = OnceLock::new();
97
98/// Open the system log file again, at its configured path. Writers take the
99/// new file from their next line on; a line is never split between the two.
100pub(crate) fn reopen() {
101    let Some(open) = OPEN.get() else { return };
102    match append(&open.path) {
103        Ok(file) => {
104            *open.file.write().unwrap_or_else(|poison| poison.into_inner()) =
105                file
106        }
107        Err(error) => {
108            tracing::error!(path = %open.path.display(), %error, "system log could not be reopened")
109        }
110    }
111}
112
113fn append(path: &Path) -> io::Result<File> {
114    OpenOptions::new().create(true).append(true).open(path)
115}
116
117/// What `logging.yaml` in `config_dir` says about the system log; `None`
118/// when there is no file or it declares none.
119///
120/// Read directly rather than through Congif: this runs before the runtime
121/// and its reader exist, with the environment the process booted with as
122/// `lookup`, because the system log must be open before anything that could
123/// fail to report through it.
124fn read(
125    config_dir: &Path,
126    lookup: impl Fn(&str) -> Option<String>,
127) -> Result<Option<SystemLogConfig>, crate::Error> {
128    let path = config_dir.join("logging.yaml");
129    let raw = match std::fs::read_to_string(&path) {
130        Ok(raw) => raw,
131        Err(error) if error.kind() == io::ErrorKind::NotFound => {
132            return Ok(None);
133        }
134        Err(error) => {
135            return Err(crate::Error::Config(format!(
136                "read {}: {error}",
137                path.display()
138            )));
139        }
140    };
141    let text = claviron_helpers::yaml::expand_env_with(&raw, lookup).map_err(
142        |error| crate::Error::Config(format!("{}: {error}", path.display())),
143    )?;
144    let file: LoggingFile = serde_yaml::from_str(&text).map_err(|error| {
145        crate::Error::Config(format!("parse {}: {error}", path.display()))
146    })?;
147    let Some(config) = file.system_log else { return Ok(None) };
148    config.validate()?;
149    Ok(Some(config))
150}
151
152impl SystemLog {
153    /// The system log `logging.yaml` in `config_dir` declares, opened for
154    /// appending; `None` when there is no file or it declares none.
155    pub fn from_config_dir(
156        config_dir: &Path,
157        lookup: impl Fn(&str) -> Option<String>,
158    ) -> Result<Option<Self>, crate::Error> {
159        Self::open(config_dir, lookup, false)
160    }
161
162    /// Open at process startup. An opted-in reset belongs only to the master
163    /// or standalone process; workers always append, including replacements.
164    pub fn from_config_dir_for_startup(
165        config_dir: &Path,
166        lookup: impl Fn(&str) -> Option<String>,
167        run_mode: RunMode,
168    ) -> Result<Option<Self>, crate::Error> {
169        Self::open(config_dir, lookup, !matches!(run_mode, RunMode::Worker(_)))
170    }
171
172    fn open(
173        config_dir: &Path,
174        lookup: impl Fn(&str) -> Option<String>,
175        startup_reset_allowed: bool,
176    ) -> Result<Option<Self>, crate::Error> {
177        let Some(config) = read(config_dir, lookup)? else { return Ok(None) };
178        Self::open_configuration(config, startup_reset_allowed).map(Some)
179    }
180
181    /// Open an explicitly configured system log without reading another file.
182    pub fn from_configuration(
183        config: SystemLogConfig,
184        run_mode: RunMode,
185    ) -> Result<Self, crate::Error> {
186        Self::open_configuration(
187            config,
188            !matches!(run_mode, RunMode::Worker(_)),
189        )
190    }
191
192    fn open_configuration(
193        config: SystemLogConfig,
194        startup_reset_allowed: bool,
195    ) -> Result<Self, crate::Error> {
196        config.validate()?;
197        let SystemLogFormat::Line = config.format;
198        if let Some(parent) =
199            config.path.parent().filter(|parent| !parent.as_os_str().is_empty())
200        {
201            std::fs::create_dir_all(parent).map_err(|error| {
202                crate::Error::Config(format!(
203                    "system log {}: {error}",
204                    parent.display()
205                ))
206            })?;
207        }
208        let file = append(&config.path)
209            .and_then(|file| {
210                if startup_reset_allowed && config.truncate_on_startup {
211                    // Keep O_APPEND for every subsequent write from this process.
212                    file.set_len(0)?;
213                }
214                Ok(file)
215            })
216            .map_err(|error| {
217                crate::Error::Config(format!(
218                    "system log {}: {error}",
219                    config.path.display()
220                ))
221            })?;
222        Ok(Self {
223            open: Arc::new(OpenFile {
224                path: config.path,
225                file: RwLock::new(file),
226            }),
227        })
228    }
229
230    /// What [`Self::from_config_dir`] reads, checked and nothing opened: for
231    /// a configuration check, which may run as another user than the
232    /// service and must not create, or depend on writing, the service's
233    /// files.
234    pub fn check_config_dir(
235        config_dir: &Path,
236        lookup: impl Fn(&str) -> Option<String>,
237    ) -> Result<(), crate::Error> {
238        read(config_dir, lookup).map(|_| ())
239    }
240
241    pub(crate) fn writer(
242        self
243    ) -> impl Fn() -> AppendWriter + Send + Sync + 'static {
244        let _ = OPEN.set(Arc::clone(&self.open));
245        let open = self.open;
246        move || AppendWriter(Arc::clone(&open))
247    }
248}
249
250/// One event's writer. The formatter hands it the whole line at once.
251pub(crate) struct AppendWriter(Arc<OpenFile>);
252
253impl Write for AppendWriter {
254    fn write(
255        &mut self,
256        buf: &[u8],
257    ) -> io::Result<usize> {
258        let file =
259            self.0.file.read().unwrap_or_else(|poison| poison.into_inner());
260        (&*file).write(buf)
261    }
262
263    fn flush(&mut self) -> io::Result<()> {
264        let file =
265            self.0.file.read().unwrap_or_else(|poison| poison.into_inner());
266        (&*file).flush()
267    }
268}
269
270#[cfg(test)]
271#[path = "../tests/system.rs"]
272mod tests;