claviron_logging/
system.rs1use 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#[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 pub path: PathBuf,
40 #[serde(default)]
41 pub format: SystemLogFormat,
42 #[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 #[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 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
82pub struct SystemLog {
84 open: Arc<OpenFile>,
85}
86
87struct OpenFile {
90 path: PathBuf,
91 file: RwLock<File>,
92}
93
94static OPEN: OnceLock<Arc<OpenFile>> = OnceLock::new();
97
98pub(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
117fn 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 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 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 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 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 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
250pub(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;