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