10 #include "dinit-log.h"
13 extern EventLoop_t eventLoop;
15 LogLevel log_level = LogLevel::WARN;
16 LogLevel cons_log_level = LogLevel::WARN;
18 static bool log_to_console = false; // whether we should output log messages to
19 // console immediately
20 static bool log_current_line; // Whether the current line is being logged
22 static ServiceSet *service_set = nullptr; // Reference to service set
25 class BufferedLogStream : public PosixFdWatcher<NullMutex>
30 bool partway = false; // if we are partway throught output of a log message
31 bool discarded = false; // if we have discarded a message
33 // A "special message" is not stored in the circular buffer; instead
34 // it is delivered from an external buffer not managed by BufferedLogger.
35 bool special = false; // currently outputting special message?
36 char *special_buf; // buffer containing special message
37 int msg_index; // index into special message
39 CPBuffer<4096> log_buffer;
44 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();
58 // Commit a log message
61 bool was_first = current_index == 0;
62 current_index = log_buffer.get_length();
63 if (was_first && log_to_console) {
64 setEnabled(&eventLoop, true);
70 log_buffer.trim_to(current_index);
75 return log_buffer.get_free();
78 void append(const char *s, size_t len)
80 log_buffer.append(s, len);
86 // (One for main log, one for console)
87 static BufferedLogStream log_stream[2];
89 constexpr static int DLOG_MAIN = 0; // main log facility
90 constexpr static int DLOG_CONS = 1; // console
93 static void release_console()
95 if (! log_to_console) {
96 int flags = fcntl(1, F_GETFL, 0);
97 fcntl(1, F_SETFL, flags & ~O_NONBLOCK);
98 service_set->pullConsoleQueue();
102 void BufferedLogStream::flushForRelease()
104 // Try to flush any messages that are currently buffered. (Console is non-blocking
105 // so it will fail gracefully).
106 if (gotEvent(&eventLoop, fd, out_events) == Rearm::DISARM) {
107 // Console has already been released at this point.
108 setEnabled(&eventLoop, false);
110 // gotEvent didn't want to disarm, so must be partway through a message; will
111 // release when it's finished.
114 Rearm BufferedLogStream::gotEvent(EventLoop_t *loop, int fd, int flags) noexcept
116 // TODO correct for the case that this is *not* the console log stream.
118 auto &log_stream = *this;
120 if ((! partway) && log_stream.special) {
121 char * start = log_stream.special_buf + log_stream.msg_index;
122 char * end = std::find(log_stream.special_buf + log_stream.msg_index, (char *)nullptr, '\n');
123 int r = write(fd, start, end - start + 1);
125 if (start + r > end) {
126 // All written: go on to next message in queue
127 log_stream.special = false;
128 log_stream.partway = false;
129 log_stream.msg_index = 0;
131 if (!log_to_console) {
133 return Rearm::DISARM;
137 log_stream.msg_index += r;
142 // spurious readiness - EAGAIN or EWOULDBLOCK?
149 // Writing from the regular circular buffer
151 // TODO issue special message if we have discarded a log message
153 if (log_stream.current_index == 0) {
155 return Rearm::DISARM;
158 char *ptr = log_stream.log_buffer.get_ptr(0);
159 int len = log_stream.log_buffer.get_contiguous_length(ptr);
160 char *creptr = ptr + len; // contiguous region end
161 char *eptr = std::find(ptr, creptr, '\n');
163 bool will_complete = false; // will complete this message?
164 if (eptr != creptr) {
165 eptr++; // include '\n'
166 will_complete = true;
171 int r = write(fd, ptr, len);
174 bool complete = (r == len) && will_complete;
175 log_stream.log_buffer.consume(len);
176 log_stream.partway = ! complete;
178 log_stream.current_index -= len;
179 if (log_stream.current_index == 0 || !log_to_console) {
180 // No more messages buffered / stop logging to console:
182 return Rearm::DISARM;
188 // EAGAIN / EWOULDBLOCK?
194 // We've written something by the time we get here. We could fall through to below, but
195 // let's give other events a chance to be processed by returning now.
199 void init_log(ServiceSet *sset) noexcept
202 log_stream[DLOG_CONS].registerWith(&eventLoop, STDOUT_FILENO, out_events); // TODO register in disabled state
203 enable_console_log(true);
206 bool is_log_flushed() noexcept
208 return log_stream[DLOG_CONS].current_index == 0;
211 // Enable or disable console logging. If disabled, console logging will be disabled on the
212 // completion of output of the current message (if any), at which point the first service record
213 // queued in the service set will acquire the console.
214 void enable_console_log(bool enable) noexcept
216 if (enable && ! log_to_console) {
217 // Console is fd 1 - stdout
218 // Set non-blocking IO:
219 int flags = fcntl(1, F_GETFL, 0);
220 fcntl(1, F_SETFL, flags | O_NONBLOCK);
222 log_stream[DLOG_CONS].init(STDOUT_FILENO);
223 log_stream[DLOG_CONS].setEnabled(&eventLoop, true);
224 log_to_console = true;
226 else if (! enable && log_to_console) {
227 log_to_console = false;
228 log_stream[DLOG_CONS].flushForRelease();
233 // Variadic method to calculate the sum of string lengths:
234 static int sum_length(const char *arg) noexcept
236 return std::strlen(arg);
239 template <typename U, typename ... T> static int sum_length(U first, T ... args) noexcept
241 return sum_length(first) + sum_length(args...);
244 // Variadic method to append strings to a buffer:
245 static void append(BufferedLogStream &buf, const char *s)
247 buf.append(s, std::strlen(s));
250 template <typename U, typename ... T> static void append(BufferedLogStream &buf, U u, T ... t)
256 // Variadic method to log a sequence of strings as a single message:
257 template <typename ... T> static void do_log(T ... args) noexcept
259 int amount = sum_length(args...);
260 if (log_stream[DLOG_CONS].get_free() >= amount) {
261 append(log_stream[DLOG_CONS], args...);
263 bool was_first = (log_stream[DLOG_CONS].current_index == 0);
264 log_stream[DLOG_CONS].current_index += amount;
265 if (was_first && log_to_console) {
266 log_stream[DLOG_CONS].setEnabled(&eventLoop, true);
270 // TODO mark a discarded message
274 // Variadic method to potentially log a sequence of strings as a single message with the given log level:
275 template <typename ... T> static void do_log(LogLevel lvl, T ... args) noexcept
277 if (lvl >= cons_log_level) {
282 // Log a message. A newline will be appended.
283 void log(LogLevel lvl, const char *msg) noexcept
285 do_log(lvl, "dinit: ", msg, "\n");
288 // Log part of a message. A series of calls to do_log_part must be followed by a call to do_log_commit.
289 template <typename T> static void do_log_part(T arg) noexcept
291 int amount = sum_length(arg);
292 if (log_stream[DLOG_CONS].get_free() >= amount) {
293 append(log_stream[DLOG_CONS], arg);
296 log_stream[DLOG_CONS].rollback_msg();
297 log_current_line = false;
298 // TODO mark discarded message
302 // Commit a message that was issued as a series of parts (via do_log_part).
303 static void do_log_commit() noexcept
305 if (log_current_line) {
306 log_stream[DLOG_CONS].commit_msg();
310 // Log a multi-part message beginning
311 void logMsgBegin(LogLevel lvl, const char *msg) noexcept
314 log_current_line = lvl >= log_level;
315 if (log_current_line) {
316 if (log_to_console) {
317 do_log_part("dinit: ");
323 // Continue a multi-part log message
324 void logMsgPart(const char *msg) noexcept
327 if (log_current_line) {
328 if (log_to_console) {
334 // Complete a multi-part log message
335 void logMsgEnd(const char *msg) noexcept
338 if (log_current_line) {
339 if (log_to_console) {
347 void logServiceStarted(const char *service_name) noexcept
349 do_log("[ OK ] ", service_name, "\n");
352 void logServiceFailed(const char *service_name) noexcept
354 do_log("[FAILED] ", service_name, "\n");
357 void logServiceStopped(const char *service_name) noexcept
359 do_log("[STOPPD] ", service_name, "\n");