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