Skip to main content

arks_server/daemon/
log.rs

1//! `git daemon` logging: `--log-destination=(stderr|syslog|none)`, `--syslog`,
2//! `--verbose`.
3//!
4//! Primary: <https://git-scm.com/docs/git-daemon> (`--log-destination`). Errors are
5//! always logged; informational lines only with `--verbose`. stderr lines carry
6//! a `[pid] ` prefix like stock `git daemon`. Syslog writes RFC 3164-style
7//! datagrams (`<PRI>ident[pid]: message`, facility daemon) to the local
8//! `/dev/log` socket; no syslog crate and no libc call are needed.
9
10use std::fmt;
11use std::io::Write;
12use std::path::PathBuf;
13use std::sync::{Arc, Mutex};
14
15/// Syslog identifier used by `arks daemon`.
16pub const SYSLOG_IDENT: &str = "arks-daemon";
17/// Default local syslog socket.
18pub const SYSLOG_SOCKET: &str = "/dev/log";
19
20/// Facility `daemon` (3) as in RFC 5424 ยง6.2.1.
21const FACILITY_DAEMON: u8 = 3;
22const SEVERITY_ERR: u8 = 3;
23const SEVERITY_INFO: u8 = 6;
24
25/// Where log lines go.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum LogDestination {
28    Stderr,
29    Syslog,
30    None,
31}
32
33impl LogDestination {
34    /// Parse a `--log-destination=` value.
35    pub fn parse(value: &str) -> Option<Self> {
36        match value {
37            "stderr" => Some(Self::Stderr),
38            "syslog" => Some(Self::Syslog),
39            "none" => Some(Self::None),
40            _ => None,
41        }
42    }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46enum Level {
47    Info,
48    Error,
49}
50
51enum Sink {
52    Stderr,
53    None,
54    Syslog(SyslogSink),
55    #[cfg(test)]
56    Memory(Vec<String>),
57}
58
59/// Shared daemon logger (cheap to clone; one sink per process).
60#[derive(Clone)]
61pub struct DaemonLog {
62    destination: LogDestination,
63    verbose: bool,
64    sink: Arc<Mutex<Sink>>,
65}
66
67impl Default for DaemonLog {
68    fn default() -> Self {
69        Self::new(LogDestination::Stderr, false)
70    }
71}
72
73impl fmt::Debug for DaemonLog {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.debug_struct("DaemonLog")
76            .field("destination", &self.destination)
77            .field("verbose", &self.verbose)
78            .finish()
79    }
80}
81
82impl DaemonLog {
83    pub fn new(destination: LogDestination, verbose: bool) -> Self {
84        let sink = match destination {
85            LogDestination::Stderr => Sink::Stderr,
86            LogDestination::None => Sink::None,
87            LogDestination::Syslog => Sink::Syslog(SyslogSink::new(PathBuf::from(SYSLOG_SOCKET))),
88        };
89        Self {
90            destination,
91            verbose,
92            sink: Arc::new(Mutex::new(sink)),
93        }
94    }
95
96    /// Syslog logger bound to a custom socket path (tests and non-standard hosts).
97    pub fn syslog_at(socket: PathBuf, verbose: bool) -> Self {
98        Self {
99            destination: LogDestination::Syslog,
100            verbose,
101            sink: Arc::new(Mutex::new(Sink::Syslog(SyslogSink::new(socket)))),
102        }
103    }
104
105    #[cfg(test)]
106    pub(crate) fn memory(verbose: bool) -> Self {
107        Self {
108            destination: LogDestination::Stderr,
109            verbose,
110            sink: Arc::new(Mutex::new(Sink::Memory(Vec::new()))),
111        }
112    }
113
114    #[cfg(test)]
115    pub(crate) fn lines(&self) -> Vec<String> {
116        match &*self.sink.lock().expect("log lock") {
117            Sink::Memory(v) => v.clone(),
118            _ => Vec::new(),
119        }
120    }
121
122    pub fn destination(&self) -> LogDestination {
123        self.destination
124    }
125
126    pub fn verbose(&self) -> bool {
127        self.verbose
128    }
129
130    /// Informational line (only with `--verbose`).
131    pub fn info(&self, msg: &str) {
132        if self.verbose {
133            self.write(Level::Info, msg);
134        }
135    }
136
137    /// Error line (always).
138    pub fn error(&self, msg: &str) {
139        self.write(Level::Error, msg);
140    }
141
142    /// Fatal error of one connection, as git's die routine reports it: `fatal: <msg>`
143    /// on stderr without the `[pid]` prefix, an err datagram under syslog, nothing
144    /// under `none`.
145    pub fn fatal(&self, msg: &str) {
146        let Ok(mut sink) = self.sink.lock() else {
147            return;
148        };
149        match &mut *sink {
150            Sink::None => {}
151            Sink::Stderr => {
152                let _ = std::io::stderr().write_all(format!("fatal: {msg}\n").as_bytes());
153            }
154            Sink::Syslog(s) => s.send(Level::Error, msg),
155            #[cfg(test)]
156            Sink::Memory(v) => v.push(format!("fatal: {msg}")),
157        }
158    }
159
160    fn write(&self, level: Level, msg: &str) {
161        let Ok(mut sink) = self.sink.lock() else {
162            return;
163        };
164        match &mut *sink {
165            Sink::None => {}
166            Sink::Stderr => {
167                let line = format!("[{}] {msg}\n", std::process::id());
168                let _ = std::io::stderr().write_all(line.as_bytes());
169            }
170            Sink::Syslog(s) => s.send(level, msg),
171            #[cfg(test)]
172            Sink::Memory(v) => v.push(msg.to_string()),
173        }
174    }
175}
176
177/// Format one syslog datagram: `<PRI>arks-daemon[pid]: message`.
178fn syslog_datagram(level: Level, msg: &str) -> Vec<u8> {
179    let severity = match level {
180        Level::Info => SEVERITY_INFO,
181        Level::Error => SEVERITY_ERR,
182    };
183    let pri = u16::from(FACILITY_DAEMON) * 8 + u16::from(severity);
184    format!("<{pri}>{SYSLOG_IDENT}[{}]: {msg}", std::process::id()).into_bytes()
185}
186
187struct SyslogSink {
188    path: PathBuf,
189    #[cfg(unix)]
190    socket: Option<std::os::unix::net::UnixDatagram>,
191}
192
193impl SyslogSink {
194    fn new(path: PathBuf) -> Self {
195        Self {
196            path,
197            #[cfg(unix)]
198            socket: None,
199        }
200    }
201
202    #[cfg(unix)]
203    fn send(&mut self, level: Level, msg: &str) {
204        use std::os::unix::net::UnixDatagram;
205        let data = syslog_datagram(level, msg);
206        // Connect lazily and retry once so a restarted syslogd is picked up.
207        for _ in 0..2 {
208            if self.socket.is_none() {
209                let Ok(sock) = UnixDatagram::unbound() else {
210                    return;
211                };
212                if sock.connect(&self.path).is_err() {
213                    return;
214                }
215                self.socket = Some(sock);
216            }
217            if let Some(sock) = &self.socket {
218                if sock.send(&data).is_ok() {
219                    return;
220                }
221            }
222            self.socket = None;
223        }
224    }
225
226    #[cfg(not(unix))]
227    fn send(&mut self, level: Level, msg: &str) {
228        // No local syslog socket on this platform: drop the line.
229        let _ = (&self.path, syslog_datagram(level, msg));
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    #[test]
238    fn destination_values_follow_git_daemon() {
239        assert_eq!(
240            LogDestination::parse("stderr"),
241            Some(LogDestination::Stderr)
242        );
243        assert_eq!(
244            LogDestination::parse("syslog"),
245            Some(LogDestination::Syslog)
246        );
247        assert_eq!(LogDestination::parse("none"), Some(LogDestination::None));
248        assert_eq!(LogDestination::parse("foo"), None);
249    }
250
251    #[test]
252    fn info_lines_need_verbose() {
253        let quiet = DaemonLog::memory(false);
254        quiet.info("hello");
255        quiet.error("boom");
256        assert_eq!(quiet.lines(), vec!["boom".to_string()]);
257        let loud = DaemonLog::memory(true);
258        loud.info("hello");
259        assert_eq!(loud.lines(), vec!["hello".to_string()]);
260    }
261
262    #[test]
263    fn syslog_datagram_uses_daemon_facility() {
264        let info = String::from_utf8(syslog_datagram(Level::Info, "Ready to rumble")).unwrap();
265        assert!(info.starts_with("<30>arks-daemon["), "{info}");
266        assert!(info.ends_with("]: Ready to rumble"), "{info}");
267        let err = String::from_utf8(syslog_datagram(Level::Error, "x")).unwrap();
268        assert!(err.starts_with("<27>"), "{err}");
269    }
270
271    #[cfg(unix)]
272    #[test]
273    fn syslog_sink_writes_to_local_socket() {
274        use std::os::unix::net::UnixDatagram;
275        let dir = tempfile::TempDir::new().unwrap();
276        let path = dir.path().join("log.sock");
277        let collector = UnixDatagram::bind(&path).unwrap();
278        collector
279            .set_read_timeout(Some(std::time::Duration::from_secs(2)))
280            .unwrap();
281        let log = DaemonLog::syslog_at(path, true);
282        log.info("Ready to rumble");
283        log.error("'x': aliased");
284        let mut buf = [0u8; 512];
285        let n = collector.recv(&mut buf).unwrap();
286        let first = String::from_utf8_lossy(&buf[..n]).to_string();
287        assert!(first.starts_with("<30>arks-daemon["), "{first}");
288        assert!(first.ends_with("Ready to rumble"), "{first}");
289        let n = collector.recv(&mut buf).unwrap();
290        let second = String::from_utf8_lossy(&buf[..n]).to_string();
291        assert!(second.starts_with("<27>"), "{second}");
292    }
293
294    #[test]
295    fn none_destination_is_silent() {
296        let log = DaemonLog::new(LogDestination::None, true);
297        log.info("x");
298        log.error("y");
299        assert_eq!(log.destination(), LogDestination::None);
300    }
301}