Flush main log (as well) before exit
[oweals/dinit.git] / src / dinit-log.cc
1 #include <algorithm>
2
3 #include <unistd.h>
4 #include <fcntl.h>
5 #include <sys/syslog.h>
6 #include <sys/uio.h>
7
8 #include "dasynq.h"
9
10 #include "service.h"
11 #include "dinit-log.h"
12 #include "cpbuffer.h"
13
14 // Dinit logging subsystem.
15 //
16 // Note that most actual functions for logging messages are found in the header, dinit-log.h.
17 //
18 // We have two separate log "streams": one for the console/stdout, one for the syslog facility (or log
19 // file). Both have a circular buffer. Log messages are appended to the circular buffer (for a syslog
20 // stream, the messages are prepended with a syslog priority indicator). Both streams start out inactive
21 // (release = true in buffered_log_stream), which means they will buffer messages but not write them.
22 //
23 // The console log stream needs to be able to release the console, if a service is waiting to acquire it.
24 // This is accomplished by calling flush_for_release() which then completes the output of the current
25 // message (if any) and then assigns the console to a waiting service.
26
27 extern eventloop_t event_loop;
28
29 static bool log_current_line[2];  // Whether the current line is being logged (for console, main log)
30 static bool log_format_syslog[2] = { false, true };
31
32 static service_set *services = nullptr;  // Reference to service set
33
34 loglevel_t log_level[2] = { loglevel_t::INFO, loglevel_t::WARN };
35 bool console_service_status = true;  // show service status messages to console?
36
37 dasynq::time_val release_time; // time the log was released
38
39 using rearm = dasynq::rearm;
40
41 namespace {
42 class buffered_log_stream : public eventloop_t::fd_watcher_impl<buffered_log_stream>
43 {
44     private:
45
46     // Outgoing:
47     bool partway = false;     // if we are partway throught output of a log message
48     bool discarded = false;   // if we have discarded a message
49     bool release = true;      // if we should inhibit output and release console
50
51     // A "special message" is not stored in the circular buffer; instead
52     // it is delivered from an external buffer not managed by BufferedLogger.
53     bool special = false;      // currently outputting special message?
54     const char *special_buf; // buffer containing special message
55     int msg_index;     // index into special message
56
57     cpbuffer<4096> log_buffer;
58     
59     public:
60     
61     // Incoming:
62     int current_index = 0;    // current/next incoming message index
63
64     int fd = -1;
65
66     void init(int fd)
67     {
68         this->fd = fd;
69         release = false;
70     }
71     
72     rearm fd_event(eventloop_t &loop, int fd, int flags) noexcept;
73
74     // Check whether the console can be released.
75     void flush_for_release();
76     bool is_release_set() { return release; }
77     
78     // Commit a log message
79     void commit_msg()
80     {
81         bool was_first = current_index == 0;
82         current_index = log_buffer.get_length();
83         if (was_first && ! release) {
84             set_enabled(event_loop, true);
85         }
86     }
87     
88     void rollback_msg()
89     {
90         log_buffer.trim_to(current_index);
91     }
92     
93     int get_free()
94     {
95         return log_buffer.get_free();
96     }
97     
98     void append(const char *s, size_t len)
99     {
100         log_buffer.append(s, len);
101     }
102     
103     // Discard buffer; call only when the stream isn't active.
104     void discard()
105     {
106         current_index = 0;
107         log_buffer.trim_to(0);
108     }
109
110     // Mark that a message was discarded due to full buffer
111     void mark_discarded()
112     {
113         discarded = true;
114     }
115
116     private:
117     void release_console();
118 };
119 }
120
121 // Two log streams:
122 // (One for main log, one for console)
123 static buffered_log_stream log_stream[2];
124
125 void buffered_log_stream::release_console()
126 {
127     if (release) {
128         int flags = fcntl(1, F_GETFL, 0);
129         fcntl(1, F_SETFL, flags & ~O_NONBLOCK);
130         services->pull_console_queue();
131         if (release) {
132             // release still set, we didn't immediately get the console back; record the
133             // time at which we released:
134             event_loop.get_time(release_time, clock_type::MONOTONIC);
135         }
136     }
137 }
138
139 void buffered_log_stream::flush_for_release()
140 {
141     release = true;
142     
143     // Try to flush any messages that are currently buffered. (Console is non-blocking
144     // so it will fail gracefully).
145     if (fd_event(event_loop, fd, dasynq::OUT_EVENTS) == rearm::DISARM) {
146         // Console has already been released at this point.
147         set_enabled(event_loop, false);
148     }
149     // fd_event didn't want to disarm, so must be partway through a message; will
150     // release when it's finished.
151 }
152
153 rearm buffered_log_stream::fd_event(eventloop_t &loop, int fd, int flags) noexcept
154 {
155     if ((! partway) && (! special) && discarded) {
156         special_buf = "dinit: *** log message discarded due to full buffer ***\n";
157         special = true;
158         discarded = false;
159         msg_index = 0;
160     }
161
162     if ((! partway) && special) {
163         const char * start = special_buf + msg_index;
164         const char * end = start;
165         while (*end != '\n') end++;
166         int r = write(fd, start, end - start + 1);
167         if (r >= 0) {
168             if (start + r > end) {
169                 // All written: go on to next message in queue
170                 special = false;
171                 discarded = false;
172                 msg_index = 0;
173                 
174                 if (release) {
175                     release_console();
176                     return rearm::DISARM;
177                 }
178             }
179             else {
180                 msg_index += r;
181                 return rearm::REARM;
182             }
183         }
184         else if (errno != EAGAIN && errno != EINTR && errno != EWOULDBLOCK) {
185             return rearm::REMOVE;
186         }
187         return rearm::REARM;
188     }
189     else {
190         // Writing from the regular circular buffer
191         
192         if (current_index == 0) {
193             release_console();
194             return rearm::DISARM;
195         }
196         
197         // We try to find a complete line (terminated by '\n') in the buffer, and write it
198         // out. Since it may span the circular buffer end, it may consist of two distinct spans,
199         // and so we use writev to write them atomically.
200         
201         struct iovec logiov[2];
202         
203         char *ptr = log_buffer.get_ptr(0);
204         int len = log_buffer.get_contiguous_length(ptr);
205         char *creptr = ptr + len;  // contiguous region end
206         char *eptr = std::find(ptr, creptr, '\n');
207         
208         bool will_complete = false;  // will complete this message?
209         if (eptr != creptr) {
210             eptr++;  // include '\n'
211             will_complete = true;
212         }
213
214         len = eptr - ptr;
215         
216         logiov[0].iov_base = ptr;
217         logiov[0].iov_len = len;
218         int iovs_to_write = 1;
219         
220         // Do we need the second span?
221         if (! will_complete && len != log_buffer.get_length()) {
222             ptr = log_buffer.get_buf_base();
223             creptr = ptr + log_buffer.get_length() - len;
224             eptr = std::find(ptr, creptr, '\n');
225             if (eptr != creptr) {
226                 eptr++; // include '\n'
227                 // It should not ever be the case that we do not now have a complete message
228                 will_complete = true;
229             }
230             logiov[1].iov_base = ptr;
231             logiov[1].iov_len = eptr - ptr;
232             len += logiov[1].iov_len;
233             iovs_to_write = 2;
234         }
235         
236         ssize_t r = writev(fd, logiov, iovs_to_write);
237
238         if (r >= 0) {
239             bool complete = (r == len) && will_complete;
240             log_buffer.consume(len);
241             partway = ! complete;
242             if (complete) {
243                 current_index -= len;
244                 if (current_index == 0 || release) {
245                     // No more messages buffered / stop logging to console:
246                     release_console();
247                     return rearm::DISARM;
248                 }
249             }
250         }
251         else if (errno != EAGAIN && errno != EINTR && errno != EWOULDBLOCK) {
252             return rearm::REMOVE;
253         }
254     }
255     
256     // We've written something by the time we get here. We could fall through to below, but
257     // let's give other events a chance to be processed by returning now.
258     return rearm::REARM;
259 }
260
261 // Initialise the logging subsystem
262 // Potentially throws std::bad_alloc or std::system_error
263 void init_log(service_set *sset, bool syslog_format)
264 {
265     services = sset;
266     log_stream[DLOG_CONS].add_watch(event_loop, STDOUT_FILENO, dasynq::OUT_EVENTS, false);
267     enable_console_log(true);
268
269     // The main (non-console) log won't be active yet, but we set the format here so that we
270     // buffer messages in the correct format:
271     log_format_syslog[DLOG_MAIN] = syslog_format;
272 }
273
274 // Set up the main log to output to the given file descriptor.
275 // Potentially throws std::bad_alloc or std::system_error
276 void setup_main_log(int fd)
277 {
278     log_stream[DLOG_MAIN].init(fd);
279     log_stream[DLOG_MAIN].add_watch(event_loop, fd, dasynq::OUT_EVENTS);
280 }
281
282 bool is_log_flushed() noexcept
283 {
284     return log_stream[DLOG_CONS].current_index == 0 &&
285             (log_stream[DLOG_MAIN].fd == -1 || log_stream[DLOG_MAIN].current_index == 0);
286 }
287
288 // Enable or disable console logging. If disabled, console logging will be disabled on the
289 // completion of output of the current message (if any), at which point the first service record
290 // queued in the service set will acquire the console.
291 void enable_console_log(bool enable) noexcept
292 {
293     bool log_to_console = ! log_stream[DLOG_CONS].is_release_set();
294     if (enable && ! log_to_console) {
295         // Set non-blocking IO:
296         int flags = fcntl(STDOUT_FILENO, F_GETFL, 0);
297         fcntl(STDOUT_FILENO, F_SETFL, flags | O_NONBLOCK);
298         // Activate watcher:
299         log_stream[DLOG_CONS].init(STDOUT_FILENO);
300         log_stream[DLOG_CONS].set_enabled(event_loop, true);
301     }
302     else if (! enable && log_to_console) {
303         log_stream[DLOG_CONS].flush_for_release();
304     }
305 }
306
307 void discard_console_log_buffer() noexcept
308 {
309     // Only discard if more than a second has passed since we released the console.
310     dasynq::time_val current_time;
311     event_loop.get_time(current_time, clock_type::MONOTONIC);
312     if (current_time - release_time >= dasynq::time_val(1, 0)) {
313         log_stream[DLOG_CONS].discard();
314     }
315 }
316
317 // Variadic method to calculate the sum of string lengths:
318 static int sum_length(const char *arg) noexcept
319 {
320     return std::strlen(arg);
321 }
322
323 template <typename ... T> static int sum_length(const char * first, T ... args) noexcept
324 {
325     return sum_length(first) + sum_length(args...);
326 }
327
328 // Variadic method to append strings to a buffer:
329 static void append(buffered_log_stream &buf, const char *s)
330 {
331     buf.append(s, std::strlen(s));
332 }
333
334 template <typename ... T> static void append(buffered_log_stream &buf, const char *u, T ... t)
335 {
336     append(buf, u);
337     append(buf, t...);
338 }
339
340 static int log_level_to_syslog_level(loglevel_t l)
341 {
342     switch (l) {
343     case loglevel_t::DEBUG:
344         return LOG_DEBUG;
345     case loglevel_t::INFO:
346         return LOG_INFO;
347     case loglevel_t::WARN:
348         return LOG_WARNING;
349     case loglevel_t::ERROR:
350         return LOG_ERR;
351     default: ;
352     }
353     
354     return LOG_CRIT;
355 }
356
357 // Variadic method to log a sequence of strings as a single message to a particular facility:
358 template <typename ... T> static void push_to_log(int idx, T ... args) noexcept
359 {
360     if (! log_current_line[idx]) return;
361     int amount = sum_length(args...);
362     if (log_stream[idx].get_free() >= amount) {
363         append(log_stream[idx], args...);
364         log_stream[idx].commit_msg();
365     }
366     else {
367         log_stream[idx].mark_discarded();
368     }
369 }
370
371 // Variadic method to potentially log a sequence of strings as a single message with the given log level:
372 template <typename ... T> static void do_log(loglevel_t lvl, bool to_cons, T ... args) noexcept
373 {
374     log_current_line[DLOG_CONS] = (lvl >= log_level[DLOG_CONS]) && to_cons;
375     log_current_line[DLOG_MAIN] = (lvl >= log_level[DLOG_MAIN]);
376     push_to_log(DLOG_CONS, args...);
377     
378     if (log_current_line[DLOG_MAIN]) {
379         if (log_format_syslog[DLOG_MAIN]) {
380             char svcbuf[10];
381             snprintf(svcbuf, 10, "<%d>", LOG_DAEMON | log_level_to_syslog_level(lvl));
382             push_to_log(DLOG_MAIN, svcbuf, args...);
383         }
384         else {
385             push_to_log(DLOG_MAIN, args...);
386         }
387     }
388 }
389
390 template <typename ... T> static void do_log_cons(T ... args) noexcept
391 {
392     if (console_service_status) {
393         log_current_line[DLOG_CONS] = true;
394         log_current_line[DLOG_MAIN] = false;
395         push_to_log(DLOG_CONS, args...);
396     }
397 }
398
399 // Log to the main facility at NOTICE level
400 template <typename ... T> static void do_log_main(T ... args) noexcept
401 {
402     log_current_line[DLOG_CONS] = false;
403     log_current_line[DLOG_MAIN] = true;
404     
405     if (log_format_syslog[DLOG_MAIN]) {
406         char svcbuf[10];
407         snprintf(svcbuf, 10, "<%d>", LOG_DAEMON | LOG_NOTICE);
408         push_to_log(DLOG_MAIN, svcbuf, args...);
409     }
410     else {
411         push_to_log(DLOG_MAIN, args...);
412     }
413 }
414
415 // Log a message. A newline will be appended.
416 void log(loglevel_t lvl, const char *msg) noexcept
417 {
418     do_log(lvl, true, "dinit: ", msg, "\n");
419 }
420
421 void log(loglevel_t lvl, bool to_cons, const char *msg) noexcept
422 {
423     do_log(lvl, to_cons, "dinit: ", msg, "\n");
424 }
425
426 // Log part of a message. A series of calls to do_log_part must be followed by a call to do_log_commit.
427 static void do_log_part(int idx, const char *arg) noexcept
428 {
429     if (log_current_line[idx]) {
430         int amount = sum_length(arg);
431         if (log_stream[idx].get_free() >= amount) {
432             append(log_stream[idx], arg);
433         }
434         else {
435             log_stream[idx].rollback_msg();
436             log_current_line[idx] = false;
437             log_stream[idx].mark_discarded();
438         }
439     }
440 }
441
442 // Commit a message that was issued as a series of parts (via do_log_part).
443 static void do_log_commit(int idx) noexcept
444 {
445     if (log_current_line[idx]) {
446         log_stream[idx].commit_msg();
447     }
448 }
449
450 // Log a multi-part message beginning
451 void log_msg_begin(loglevel_t lvl, const char *msg) noexcept
452 {
453     log_current_line[DLOG_CONS] = lvl >= log_level[DLOG_CONS];
454     log_current_line[DLOG_MAIN] = lvl >= log_level[DLOG_MAIN];
455
456     // Prepend the syslog priority level string ("<N>") for the main log:
457     if (log_current_line[DLOG_MAIN]) {
458         if (log_format_syslog[DLOG_MAIN]) {
459             char svcbuf[10];
460             snprintf(svcbuf, 10, "<%d>", LOG_DAEMON | log_level_to_syslog_level(lvl));
461             do_log_part(DLOG_MAIN, svcbuf);
462         }
463     }
464
465     for (int i = 0; i < 2; i++) {
466         do_log_part(i, "dinit: ");
467         do_log_part(i, msg);
468     }
469 }
470
471 // Continue a multi-part log message
472 void log_msg_part(const char *msg) noexcept
473 {
474     do_log_part(DLOG_CONS, msg);
475     do_log_part(DLOG_MAIN, msg);
476 }
477
478 // Complete a multi-part log message
479 void log_msg_end(const char *msg) noexcept
480 {
481     for (int i = 0; i < 2; i++) {
482         do_log_part(i, msg);
483         do_log_part(i, "\n");
484         do_log_commit(i);
485     }
486 }
487
488 void log_service_started(const char *service_name) noexcept
489 {
490     do_log_cons("[  OK  ] ", service_name, "\n");
491     do_log_main("dinit: service ", service_name, " started.\n");
492 }
493
494 void log_service_failed(const char *service_name) noexcept
495 {
496     do_log_cons("[FAILED] ", service_name, "\n");
497     do_log_main("dinit: service ", service_name, " failed to start.\n");
498 }
499
500 void log_service_stopped(const char *service_name) noexcept
501 {
502     do_log_cons("[STOPPD] ", service_name, "\n");
503     do_log_main("dinit: service ", service_name, " stopped.\n");
504 }