6 #include <sys/syslog.h>
12 #include "dinit-log.h"
15 extern EventLoop_t eventLoop;
17 static bool log_current_line[2]; // Whether the current line is being logged (for console, main log)
18 LogLevel log_level[2] = { LogLevel::WARN, LogLevel::WARN };
20 static ServiceSet *service_set = nullptr; // Reference to service set
23 class BufferedLogStream : public PosixFdWatcher<NullMutex>
28 bool partway = false; // if we are partway throught output of a log message
29 bool discarded = false; // if we have discarded a message
30 bool release = true; // if we should inhibit output and release console
32 // A "special message" is not stored in the circular buffer; instead
33 // it is delivered from an external buffer not managed by BufferedLogger.
34 bool special = false; // currently outputting special message?
35 char *special_buf; // buffer containing special message
36 int msg_index; // index into special message
38 CPBuffer<4096> log_buffer;
43 int current_index = 0; // current/next incoming message index
53 Rearm gotEvent(EventLoop_t *loop, int fd, int flags) noexcept override;
55 // Check whether the console can be released.
56 void flushForRelease();
57 void release_console();
58 bool is_release_set() { return release; }
60 // Commit a log message
63 bool was_first = current_index == 0;
64 current_index = log_buffer.get_length();
65 if (was_first && ! release) {
66 setEnabled(&eventLoop, true);
72 log_buffer.trim_to(current_index);
77 return log_buffer.get_free();
80 void append(const char *s, size_t len)
82 log_buffer.append(s, len);
88 // (One for main log, one for console)
89 static BufferedLogStream log_stream[2];
91 constexpr static int DLOG_MAIN = 0; // main log facility
92 constexpr static int DLOG_CONS = 1; // console
94 void BufferedLogStream::release_console()
97 int flags = fcntl(1, F_GETFL, 0);
98 fcntl(1, F_SETFL, flags & ~O_NONBLOCK);
99 service_set->pullConsoleQueue();
103 void BufferedLogStream::flushForRelease()
107 // Try to flush any messages that are currently buffered. (Console is non-blocking
108 // so it will fail gracefully).
109 if (gotEvent(&eventLoop, fd, out_events) == Rearm::DISARM) {
110 // Console has already been released at this point.
111 setEnabled(&eventLoop, false);
113 // gotEvent didn't want to disarm, so must be partway through a message; will
114 // release when it's finished.
117 Rearm BufferedLogStream::gotEvent(EventLoop_t *loop, int fd, int flags) noexcept
119 auto &log_stream = *this;
121 if ((! partway) && log_stream.special) {
122 char * start = log_stream.special_buf + log_stream.msg_index;
123 char * end = std::find(log_stream.special_buf + log_stream.msg_index, (char *)nullptr, '\n');
124 int r = write(fd, start, end - start + 1);
126 if (start + r > end) {
127 // All written: go on to next message in queue
128 log_stream.special = false;
129 log_stream.partway = false;
130 log_stream.msg_index = 0;
134 return Rearm::DISARM;
138 log_stream.msg_index += r;
142 else if (errno != EAGAIN && errno != EINTR && errno != EWOULDBLOCK) {
143 return Rearm::REMOVE;
148 // Writing from the regular circular buffer
150 // TODO issue special message if we have discarded a log message
152 if (current_index == 0) {
154 return Rearm::DISARM;
157 // We try to find a complete line (terminated by '\n') in the buffer, and write it
158 // out. Since it may span the circular buffer end, it may consist of two distinct spans,
159 // and so we use writev to write them atomically.
161 struct iovec logiov[2];
163 char *ptr = log_buffer.get_ptr(0);
164 int len = log_buffer.get_contiguous_length(ptr);
165 char *creptr = ptr + len; // contiguous region end
166 char *eptr = std::find(ptr, creptr, '\n');
168 bool will_complete = false; // will complete this message?
169 if (eptr != creptr) {
170 eptr++; // include '\n'
171 will_complete = true;
176 logiov[0].iov_base = ptr;
177 logiov[0].iov_len = len;
178 int iovs_to_write = 1;
180 // Do we need the second span?
181 if (! will_complete && len != log_buffer.get_length()) {
182 ptr = log_buffer.get_buf_base();
183 creptr = static_cast<char *>(logiov[1].iov_base) + log_buffer.get_length() - len;
184 eptr = std::find(ptr, creptr, '\n');
185 if (eptr != creptr) {
186 eptr++; // include '\n'
187 // It should not ever be the case that we do not now have a complete message
188 will_complete = true;
190 logiov[1].iov_base = ptr;
191 logiov[1].iov_len = eptr - ptr;
192 len += logiov[1].iov_len;
196 ssize_t r = writev(fd, logiov, iovs_to_write);
199 bool complete = (r == len) && will_complete;
200 log_stream.log_buffer.consume(len);
201 log_stream.partway = ! complete;
203 log_stream.current_index -= len;
204 if (log_stream.current_index == 0 || release) {
205 // No more messages buffered / stop logging to console:
207 return Rearm::DISARM;
211 else if (errno != EAGAIN && errno != EINTR && errno != EWOULDBLOCK) {
212 return Rearm::REMOVE;
216 // We've written something by the time we get here. We could fall through to below, but
217 // let's give other events a chance to be processed by returning now.
221 // Initialise the logging subsystem
222 // Potentially throws std::bad_alloc or std::system_error
223 void init_log(ServiceSet *sset)
226 log_stream[DLOG_CONS].registerWith(&eventLoop, STDOUT_FILENO, out_events); // TODO register in disabled state
227 enable_console_log(true);
230 // Set up the main log to output to the given file descriptor.
231 // Potentially throws std::bad_alloc or std::system_error
232 void setup_main_log(int fd)
234 log_stream[DLOG_MAIN].init(fd);
235 log_stream[DLOG_MAIN].registerWith(&eventLoop, fd, out_events);
238 bool is_log_flushed() noexcept
240 return log_stream[DLOG_CONS].current_index == 0;
243 // Enable or disable console logging. If disabled, console logging will be disabled on the
244 // completion of output of the current message (if any), at which point the first service record
245 // queued in the service set will acquire the console.
246 void enable_console_log(bool enable) noexcept
248 bool log_to_console = ! log_stream[DLOG_CONS].is_release_set();
249 if (enable && ! log_to_console) {
250 // Console is fd 1 - stdout
251 // Set non-blocking IO:
252 int flags = fcntl(1, F_GETFL, 0);
253 fcntl(1, F_SETFL, flags | O_NONBLOCK);
255 log_stream[DLOG_CONS].init(STDOUT_FILENO);
256 log_stream[DLOG_CONS].setEnabled(&eventLoop, true);
258 else if (! enable && log_to_console) {
259 log_stream[DLOG_CONS].flushForRelease();
264 // Variadic method to calculate the sum of string lengths:
265 static int sum_length(const char *arg) noexcept
267 return std::strlen(arg);
270 template <typename ... T> static int sum_length(const char * first, T ... args) noexcept
272 return sum_length(first) + sum_length(args...);
275 // Variadic method to append strings to a buffer:
276 static void append(BufferedLogStream &buf, const char *s)
278 buf.append(s, std::strlen(s));
281 template <typename ... T> static void append(BufferedLogStream &buf, const char *u, T ... t)
287 static int log_level_to_syslog_level(LogLevel l)
290 case LogLevel::DEBUG:
296 case LogLevel::ERROR:
304 // Variadic method to log a sequence of strings as a single message to a particular facility:
305 template <typename ... T> static void push_to_log(int idx, T ... args) noexcept
307 if (! log_current_line[idx]) return;
308 int amount = sum_length(args...);
309 if (log_stream[idx].get_free() >= amount) {
310 append(log_stream[idx], args...);
311 log_stream[idx].commit_msg();
314 // TODO mark a discarded message
318 // Variadic method to potentially log a sequence of strings as a single message with the given log level:
319 template <typename ... T> static void do_log(LogLevel lvl, T ... args) noexcept
321 log_current_line[DLOG_CONS] = lvl >= log_level[DLOG_CONS];
322 log_current_line[DLOG_MAIN] = lvl >= log_level[DLOG_MAIN];
323 push_to_log(DLOG_CONS, args...);
325 if (log_current_line[DLOG_MAIN]) {
327 snprintf(svcbuf, 10, "<%d>", LOG_DAEMON | log_level_to_syslog_level(lvl));
329 push_to_log(DLOG_MAIN, svcbuf, args...);
333 template <typename ... T> static void do_log_cons(T ... args) noexcept
335 log_current_line[DLOG_CONS] = true;
336 log_current_line[DLOG_MAIN] = false;
337 push_to_log(DLOG_CONS, args...);
340 // Log to the main facility at NOTICE level
341 template <typename ... T> static void do_log_main(T ... args) noexcept
343 log_current_line[DLOG_CONS] = false;
344 log_current_line[DLOG_MAIN] = true;
347 snprintf(svcbuf, 10, "<%d>", LOG_DAEMON | LOG_NOTICE);
349 push_to_log(DLOG_MAIN, svcbuf, args...);
352 // Log a message. A newline will be appended.
353 void log(LogLevel lvl, const char *msg) noexcept
355 do_log(lvl, "dinit: ", msg, "\n");
358 // Log part of a message. A series of calls to do_log_part must be followed by a call to do_log_commit.
359 template <typename T> static void do_log_part(int idx, T arg) noexcept
361 if (log_current_line[idx]) {
362 int amount = sum_length(arg);
363 if (log_stream[idx].get_free() >= amount) {
364 append(log_stream[idx], arg);
367 log_stream[idx].rollback_msg();
368 log_current_line[idx] = false;
369 // TODO mark discarded message
374 // Commit a message that was issued as a series of parts (via do_log_part).
375 static void do_log_commit(int idx) noexcept
377 if (log_current_line[idx]) {
378 log_stream[idx].commit_msg();
382 // Log a multi-part message beginning
383 void logMsgBegin(LogLevel lvl, const char *msg) noexcept
385 log_current_line[DLOG_CONS] = lvl >= log_level[DLOG_CONS];
386 log_current_line[DLOG_MAIN] = lvl >= log_level[DLOG_MAIN];
388 if (log_current_line[DLOG_MAIN]) {
390 snprintf(svcbuf, 10, "<%d>", LOG_DAEMON | log_level_to_syslog_level(lvl));
391 do_log_part(DLOG_MAIN, svcbuf);
394 for (int i = 0; i < 2; i++) {
395 do_log_part(i, "dinit: ");
400 // Continue a multi-part log message
401 void logMsgPart(const char *msg) noexcept
403 do_log_part(DLOG_CONS, msg);
404 do_log_part(DLOG_MAIN, msg);
407 // Complete a multi-part log message
408 void logMsgEnd(const char *msg) noexcept
410 for (int i = 0; i < 2; i++) {
412 do_log_part(i, "\n");
417 void logServiceStarted(const char *service_name) noexcept
419 do_log_cons("[ OK ] ", service_name, "\n");
420 do_log_main("dinit: service ", service_name, " started.\n");
423 void logServiceFailed(const char *service_name) noexcept
425 do_log_cons("[FAILED] ", service_name, "\n");
426 do_log_main("dinit: service ", service_name, " failed to start.\n");
429 void logServiceStopped(const char *service_name) noexcept
431 do_log_cons("[STOPPD] ", service_name, "\n");
432 do_log_main("dinit: service ", service_name, " stopped.\n");