+#include "cpbuffer.h"
+
+extern EventLoop_t eventLoop;
+
+static bool log_current_line[2]; // Whether the current line is being logged (for console, main log)
+LogLevel log_level[2] = { LogLevel::WARN, LogLevel::WARN };
+
+static ServiceSet *service_set = nullptr; // Reference to service set
+
+namespace {
+class BufferedLogStream : public EventLoop_t::FdWatcher
+{
+ private:
+
+ // Outgoing:
+ bool partway = false; // if we are partway throught output of a log message
+ bool discarded = false; // if we have discarded a message
+ bool release = true; // if we should inhibit output and release console
+
+ // A "special message" is not stored in the circular buffer; instead
+ // it is delivered from an external buffer not managed by BufferedLogger.
+ bool special = false; // currently outputting special message?
+ char *special_buf; // buffer containing special message
+ int msg_index; // index into special message
+
+ CPBuffer<4096> log_buffer;
+
+ public:
+
+ // Incoming:
+ int current_index = 0; // current/next incoming message index
+
+ int fd = -1;
+
+ void init(int fd)
+ {
+ this->fd = fd;
+ release = false;
+ }
+
+ Rearm gotEvent(EventLoop_t *loop, int fd, int flags) noexcept override;
+
+ // Check whether the console can be released.
+ void flushForRelease();
+ void release_console();
+ bool is_release_set() { return release; }
+
+ // Commit a log message
+ void commit_msg()
+ {
+ bool was_first = current_index == 0;
+ current_index = log_buffer.get_length();
+ if (was_first && ! release) {
+ setEnabled(&eventLoop, true);
+ }
+ }
+
+ void rollback_msg()
+ {
+ log_buffer.trim_to(current_index);
+ }
+
+ int get_free()
+ {
+ return log_buffer.get_free();
+ }
+
+ void append(const char *s, size_t len)
+ {
+ log_buffer.append(s, len);
+ }
+};
+}
+
+// Two log streams:
+// (One for main log, one for console)
+static BufferedLogStream log_stream[2];
+
+constexpr static int DLOG_MAIN = 0; // main log facility
+constexpr static int DLOG_CONS = 1; // console
+
+void BufferedLogStream::release_console()
+{
+ if (release) {
+ int flags = fcntl(1, F_GETFL, 0);
+ fcntl(1, F_SETFL, flags & ~O_NONBLOCK);
+ service_set->pullConsoleQueue();
+ }
+}
+
+void BufferedLogStream::flushForRelease()
+{
+ release = true;
+
+ // Try to flush any messages that are currently buffered. (Console is non-blocking
+ // so it will fail gracefully).
+ if (gotEvent(&eventLoop, fd, OUT_EVENTS) == Rearm::DISARM) {
+ // Console has already been released at this point.
+ setEnabled(&eventLoop, false);
+ }
+ // gotEvent didn't want to disarm, so must be partway through a message; will
+ // release when it's finished.
+}
+
+Rearm BufferedLogStream::gotEvent(EventLoop_t *loop, int fd, int flags) noexcept
+{
+ auto &log_stream = *this;
+
+ if ((! partway) && log_stream.special) {
+ char * start = log_stream.special_buf + log_stream.msg_index;
+ char * end = std::find(log_stream.special_buf + log_stream.msg_index, (char *)nullptr, '\n');
+ int r = write(fd, start, end - start + 1);
+ if (r >= 0) {
+ if (start + r > end) {
+ // All written: go on to next message in queue
+ log_stream.special = false;
+ log_stream.partway = false;
+ log_stream.msg_index = 0;
+
+ if (release) {
+ release_console();
+ return Rearm::DISARM;
+ }
+ }
+ else {
+ log_stream.msg_index += r;
+ return Rearm::REARM;
+ }
+ }
+ else if (errno != EAGAIN && errno != EINTR && errno != EWOULDBLOCK) {
+ return Rearm::REMOVE;
+ }
+ return Rearm::REARM;
+ }
+ else {
+ // Writing from the regular circular buffer
+
+ // TODO issue special message if we have discarded a log message
+
+ if (current_index == 0) {
+ release_console();
+ return Rearm::DISARM;
+ }
+
+ // We try to find a complete line (terminated by '\n') in the buffer, and write it
+ // out. Since it may span the circular buffer end, it may consist of two distinct spans,
+ // and so we use writev to write them atomically.
+
+ struct iovec logiov[2];
+
+ char *ptr = log_buffer.get_ptr(0);
+ int len = log_buffer.get_contiguous_length(ptr);
+ char *creptr = ptr + len; // contiguous region end
+ char *eptr = std::find(ptr, creptr, '\n');
+
+ bool will_complete = false; // will complete this message?
+ if (eptr != creptr) {
+ eptr++; // include '\n'
+ will_complete = true;
+ }
+
+ len = eptr - ptr;
+
+ logiov[0].iov_base = ptr;
+ logiov[0].iov_len = len;
+ int iovs_to_write = 1;
+
+ // Do we need the second span?
+ if (! will_complete && len != log_buffer.get_length()) {
+ ptr = log_buffer.get_buf_base();
+ creptr = static_cast<char *>(logiov[1].iov_base) + log_buffer.get_length() - len;
+ eptr = std::find(ptr, creptr, '\n');
+ if (eptr != creptr) {
+ eptr++; // include '\n'
+ // It should not ever be the case that we do not now have a complete message
+ will_complete = true;
+ }
+ logiov[1].iov_base = ptr;
+ logiov[1].iov_len = eptr - ptr;
+ len += logiov[1].iov_len;
+ iovs_to_write = 2;
+ }
+
+ ssize_t r = writev(fd, logiov, iovs_to_write);
+
+ if (r >= 0) {
+ bool complete = (r == len) && will_complete;
+ log_stream.log_buffer.consume(len);
+ log_stream.partway = ! complete;
+ if (complete) {
+ log_stream.current_index -= len;
+ if (log_stream.current_index == 0 || release) {
+ // No more messages buffered / stop logging to console:
+ release_console();
+ return Rearm::DISARM;
+ }
+ }
+ }
+ else if (errno != EAGAIN && errno != EINTR && errno != EWOULDBLOCK) {
+ return Rearm::REMOVE;
+ }
+ }
+
+ // We've written something by the time we get here. We could fall through to below, but
+ // let's give other events a chance to be processed by returning now.
+ return Rearm::REARM;
+}
+
+// Initialise the logging subsystem
+// Potentially throws std::bad_alloc or std::system_error
+void init_log(ServiceSet *sset)
+{
+ service_set = sset;
+ log_stream[DLOG_CONS].registerWith(&eventLoop, STDOUT_FILENO, OUT_EVENTS); // TODO register in disabled state
+ enable_console_log(true);
+}
+
+// Set up the main log to output to the given file descriptor.
+// Potentially throws std::bad_alloc or std::system_error
+void setup_main_log(int fd)
+{
+ log_stream[DLOG_MAIN].init(fd);
+ log_stream[DLOG_MAIN].registerWith(&eventLoop, fd, OUT_EVENTS);
+}
+
+bool is_log_flushed() noexcept
+{
+ return log_stream[DLOG_CONS].current_index == 0;
+}