From ae09272bcc4fce879e8b57cb9b86bc1f54ef502b Mon Sep 17 00:00:00 2001 From: Joachim Wiberg Date: Wed, 23 Mar 2022 06:29:40 +0100 Subject: [PATCH] logit(): detect running in container to use stderr for logging When running in a container we still want to use any syslog daemon available for our logging needs. However, the time between the first logit() in Finit and any such daemon having started can be long. In a normal (non-containerized) setup we log to the kernel ring buffer, but that's not available in a container scenario. At least not for unprivileged containers. So we need to detect all these cases and be prepared to fall back to log to the console, either using these LOG_CONS flag to openlog(), or by simply calling vfprintf() to stderr. Signed-off-by: Joachim Wiberg --- src/log.c | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/log.c b/src/log.c index d2ec5245..ccd792ff 100644 --- a/src/log.c +++ b/src/log.c @@ -59,18 +59,24 @@ void log_exit(void) enable_progress(1); } -static void log_open(void) +static int log_open(void) { - int opts = LOG_PID; + int opts; + + if (up) + return 1; + if (access("/dev/log", W_OK)) + return 0; + + opts = LOG_CONS | LOG_PID; + if (debug) + opts |= LOG_PERROR; closelog(); - - if (debug) - opts |= LOG_PERROR; /* LOG_CONS | */ openlog("finit", opts, LOG_DAEMON); setlogmask(LOG_UPTO(loglevel)); - up = 1; + return up = 1; } /* Toggle debug mode */ @@ -95,15 +101,12 @@ void log_debug(void) */ void logit(int prio, const char *fmt, ...) { - FILE *fp; va_list ap; + FILE *fp; va_start(ap, fmt); - if (up || fexist("/dev/log")) { - if (!up) - log_open(); - + if (up || log_open()) { vsyslog(prio, fmt, ap); goto done; } @@ -111,8 +114,7 @@ void logit(int prio, const char *fmt, ...) if (LOG_PRI(prio) > loglevel) goto done; - fp = fopen("/dev/kmsg", "w"); - if (!fp) { + if (in_container() || !(fp = fopen("/dev/kmsg", "w"))) { vfprintf(stderr, fmt, ap); goto done; }