blob: 22cd4f4b1d555b07ad6fc6c330877f929d5b3ba0 [file] [log] [blame]
Brian Silvermancb5da1f2015-12-05 22:19:58 -05001#include "aos/common/logging/implementations.h"
Brian Silvermanf665d692013-02-17 22:11:39 -08002
Brian Silvermanb0893882014-02-10 14:48:30 -08003#include <stdarg.h>
Brian4a424a22014-04-02 11:52:45 -07004#include <inttypes.h>
Austin Schuh044e18b2015-10-21 20:17:09 -07005
Brian Silvermancb5da1f2015-12-05 22:19:58 -05006#include <algorithm>
Austin Schuhf2a50ba2016-12-24 16:16:26 -08007#include <chrono>
Brian Silvermancb5da1f2015-12-05 22:19:58 -05008
9#include "aos/common/die.h"
Brian Silvermanf665d692013-02-17 22:11:39 -080010#include "aos/common/once.h"
Austin Schuh044e18b2015-10-21 20:17:09 -070011#include "aos/common/time.h"
Brian Silverman669669f2014-02-14 16:32:56 -080012#include "aos/common/queue_types.h"
Brian Silvermancb5da1f2015-12-05 22:19:58 -050013#include "aos/common/logging/printf_formats.h"
14#include "aos/linux_code/ipc_lib/queue.h"
Brian Silvermanf665d692013-02-17 22:11:39 -080015
16namespace aos {
17namespace logging {
18namespace {
19
Austin Schuhf2a50ba2016-12-24 16:16:26 -080020namespace chrono = ::std::chrono;
21
Brian Silvermanf665d692013-02-17 22:11:39 -080022// The root LogImplementation. It only logs to stderr/stdout.
23// Some of the things specified in the LogImplementation documentation doesn't
24// apply here (mostly the parts about being able to use LOG) because this is the
25// root one.
Brian Silvermancb5da1f2015-12-05 22:19:58 -050026class RootLogImplementation : public SimpleLogImplementation {
Brian Silverman2e799732014-06-05 21:50:19 -070027 public:
28 void have_other_implementation() { only_implementation_ = false; }
29
30 private:
Brian Silvermancb5da1f2015-12-05 22:19:58 -050031 void set_next(LogImplementation *) override {
Brian Silvermanf665d692013-02-17 22:11:39 -080032 LOG(FATAL, "can't have a next logger from here\n");
33 }
34
Brian Silvermanf7986142014-04-21 17:42:35 -070035 __attribute__((format(GOOD_PRINTF_FORMAT_TYPE, 3, 0)))
Brian Silvermancb5da1f2015-12-05 22:19:58 -050036 void DoLog(log_level level, const char *format, va_list ap) override {
Brian Silvermanf665d692013-02-17 22:11:39 -080037 LogMessage message;
38 internal::FillInMessage(level, format, ap, &message);
39 internal::PrintMessage(stderr, message);
Brian Silverman2e799732014-06-05 21:50:19 -070040 if (!only_implementation_) {
41 fputs("root logger got used, see stderr for message\n", stdout);
42 }
Brian Silvermanf665d692013-02-17 22:11:39 -080043 }
Brian Silverman2e799732014-06-05 21:50:19 -070044
45 bool only_implementation_ = true;
Brian Silvermanf665d692013-02-17 22:11:39 -080046};
47
Brian Silverman2e799732014-06-05 21:50:19 -070048RootLogImplementation *root_implementation = nullptr;
49
Brian Silvermanf665d692013-02-17 22:11:39 -080050void SetGlobalImplementation(LogImplementation *implementation) {
Brian Silverman5c201e22014-06-12 22:40:28 -070051 if (root_implementation == nullptr) {
52 fputs("Somebody didn't call logging::Init()!\n", stderr);
53 abort();
54 }
55
Brian Silvermancb5da1f2015-12-05 22:19:58 -050056 internal::Context *context = internal::Context::Get();
Brian Silvermanf665d692013-02-17 22:11:39 -080057
58 context->implementation = implementation;
Brian Silvermancb5da1f2015-12-05 22:19:58 -050059 internal::global_top_implementation.store(implementation);
Brian Silvermanf665d692013-02-17 22:11:39 -080060}
61
Brian Silvermane5d65692013-02-28 15:15:03 -080062void NewContext() {
Brian Silvermancb5da1f2015-12-05 22:19:58 -050063 internal::Context::Delete();
Brian Silvermane5d65692013-02-28 15:15:03 -080064}
65
Brian Silvermanf665d692013-02-17 22:11:39 -080066void *DoInit() {
Brian Silverman2e799732014-06-05 21:50:19 -070067 SetGlobalImplementation(root_implementation = new RootLogImplementation());
Brian Silvermane5d65692013-02-28 15:15:03 -080068
Brian Silvermane5d65692013-02-28 15:15:03 -080069 if (pthread_atfork(NULL /*prepare*/, NULL /*parent*/,
70 NewContext /*child*/) != 0) {
71 LOG(FATAL, "pthread_atfork(NULL, NULL, %p) failed\n",
72 NewContext);
73 }
Brian Silvermane5d65692013-02-28 15:15:03 -080074
Brian Silvermanf665d692013-02-17 22:11:39 -080075 return NULL;
76}
77
78} // namespace
79namespace internal {
Brian Silverman88471dc2014-02-15 22:35:42 -080080namespace {
Brian Silvermanf665d692013-02-17 22:11:39 -080081
Brian Silverman88471dc2014-02-15 22:35:42 -080082void FillInMessageBase(log_level level, LogMessage *message) {
Brian Silvermanf665d692013-02-17 22:11:39 -080083 Context *context = Context::Get();
84
Brian Silvermanf665d692013-02-17 22:11:39 -080085 message->level = level;
86 message->source = context->source;
Austin Schuhaebbc342015-01-25 02:25:13 -080087 memcpy(message->name, context->name, context->name_size);
88 message->name_length = context->name_size;
Brian Silvermanf665d692013-02-17 22:11:39 -080089
Austin Schuhf2a50ba2016-12-24 16:16:26 -080090 monotonic_clock::time_point monotonic_now = monotonic_clock::now();
91 message->seconds =
92 chrono::duration_cast<chrono::seconds>(monotonic_now.time_since_epoch())
93 .count();
94 message->nseconds =
95 chrono::duration_cast<chrono::nanoseconds>(
96 monotonic_now.time_since_epoch() - chrono::seconds(message->seconds))
97 .count();
Brian Silvermanf665d692013-02-17 22:11:39 -080098
99 message->sequence = context->sequence++;
100}
101
Brian Silverman88471dc2014-02-15 22:35:42 -0800102} // namespace
103
104void FillInMessageStructure(log_level level,
105 const ::std::string &message_string, size_t size,
106 const MessageType *type,
107 const ::std::function<size_t(char *)> &serialize,
108 LogMessage *message) {
109 type_cache::AddShm(type->id);
110 message->structure.type_id = type->id;
111
112 FillInMessageBase(level, message);
113
114 if (message_string.size() + size > sizeof(message->structure.serialized)) {
115 LOG(FATAL, "serialized struct %s (size %zd) and message %s too big\n",
116 type->name.c_str(), size, message_string.c_str());
117 }
118 message->structure.string_length = message_string.size();
119 memcpy(message->structure.serialized, message_string.data(),
120 message->structure.string_length);
121
122 message->message_length = serialize(
123 &message->structure.serialized[message->structure.string_length]);
124 message->type = LogMessage::Type::kStruct;
125}
126
Brian Silverman664db1a2014-03-20 17:06:29 -0700127void FillInMessageMatrix(log_level level,
128 const ::std::string &message_string, uint32_t type_id,
129 int rows, int cols, const void *data,
130 LogMessage *message) {
131 CHECK(MessageType::IsPrimitive(type_id));
132 message->matrix.type = type_id;
133
134 const auto element_size = MessageType::Sizeof(type_id);
135
136 FillInMessageBase(level, message);
137
138 message->message_length = rows * cols * element_size;
139 if (message_string.size() + message->message_length >
140 sizeof(message->matrix.data)) {
141 LOG(FATAL, "%dx%d matrix of type %" PRIu32
142 " (size %u) and message %s is too big\n",
143 rows, cols, type_id, element_size, message_string.c_str());
144 }
145 message->matrix.string_length = message_string.size();
146 memcpy(message->matrix.data, message_string.data(),
147 message->matrix.string_length);
148
149 message->matrix.rows = rows;
150 message->matrix.cols = cols;
151 SerializeMatrix(type_id, &message->matrix.data[message->matrix.string_length],
152 data, rows, cols);
153 message->type = LogMessage::Type::kMatrix;
154}
155
Brian Silverman88471dc2014-02-15 22:35:42 -0800156void FillInMessage(log_level level, const char *format, va_list ap,
157 LogMessage *message) {
158 FillInMessageBase(level, message);
159
160 message->message_length =
161 ExecuteFormat(message->message, sizeof(message->message), format, ap);
162 message->type = LogMessage::Type::kString;
163}
164
Brian Silvermanf665d692013-02-17 22:11:39 -0800165void PrintMessage(FILE *output, const LogMessage &message) {
Brian Silvermana7234c62014-03-24 20:23:25 -0700166#define BASE_ARGS \
167 AOS_LOGGING_BASE_ARGS( \
168 message.name_length, message.name, static_cast<int32_t>(message.source), \
169 message.sequence, message.level, message.seconds, message.nseconds)
170 switch (message.type) {
Brian Silverman88471dc2014-02-15 22:35:42 -0800171 case LogMessage::Type::kString:
Brian Silvermana7234c62014-03-24 20:23:25 -0700172 fprintf(output, AOS_LOGGING_BASE_FORMAT "%.*s", BASE_ARGS,
Brian Silverman88471dc2014-02-15 22:35:42 -0800173 static_cast<int>(message.message_length), message.message);
174 break;
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700175 case LogMessage::Type::kStruct: {
Austin Schuheee8c962017-04-12 22:32:44 -0700176 char buffer[4096];
Brian Silverman88471dc2014-02-15 22:35:42 -0800177 size_t output_length = sizeof(buffer);
178 size_t input_length = message.message_length;
179 if (!PrintMessage(
180 buffer, &output_length,
181 message.structure.serialized + message.structure.string_length,
182 &input_length, type_cache::Get(message.structure.type_id))) {
183 LOG(FATAL,
184 "printing message (%.*s) of type %s into %zu-byte buffer failed\n",
185 static_cast<int>(message.message_length), message.message,
186 type_cache::Get(message.structure.type_id).name.c_str(),
187 sizeof(buffer));
188 }
189 if (input_length > 0) {
190 LOG(WARNING, "%zu extra bytes on message of type %s\n", input_length,
191 type_cache::Get(message.structure.type_id).name.c_str());
192 }
Brian Silvermana7234c62014-03-24 20:23:25 -0700193 fprintf(output, AOS_LOGGING_BASE_FORMAT "%.*s: %.*s\n", BASE_ARGS,
Brian Silvermanb263d302014-02-16 00:01:43 -0800194 static_cast<int>(message.structure.string_length),
195 message.structure.serialized,
196 static_cast<int>(sizeof(buffer) - output_length), buffer);
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700197 } break;
198 case LogMessage::Type::kMatrix: {
199 char buffer[1024];
200 size_t output_length = sizeof(buffer);
201 if (message.message_length !=
202 static_cast<size_t>(message.matrix.rows * message.matrix.cols *
203 MessageType::Sizeof(message.matrix.type))) {
204 LOG(FATAL, "expected %d bytes of matrix data but have %zu\n",
205 message.matrix.rows * message.matrix.cols *
206 MessageType::Sizeof(message.matrix.type),
207 message.message_length);
208 }
209 if (!PrintMatrix(buffer, &output_length,
210 message.matrix.data + message.matrix.string_length,
211 message.matrix.type, message.matrix.rows,
212 message.matrix.cols)) {
213 LOG(FATAL, "printing %dx%d matrix of type %" PRIu32 " failed\n",
214 message.matrix.rows, message.matrix.cols, message.matrix.type);
215 }
Brian Silvermana7234c62014-03-24 20:23:25 -0700216 fprintf(output, AOS_LOGGING_BASE_FORMAT "%.*s: %.*s\n", BASE_ARGS,
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700217 static_cast<int>(message.matrix.string_length),
Brian Silverman664db1a2014-03-20 17:06:29 -0700218 message.matrix.data,
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700219 static_cast<int>(sizeof(buffer) - output_length), buffer);
220 } break;
Brian Silverman88471dc2014-02-15 22:35:42 -0800221 }
Brian Silvermanc1a244e2014-02-20 14:12:39 -0800222#undef BASE_ARGS
Brian Silvermanf665d692013-02-17 22:11:39 -0800223}
224
225} // namespace internal
226
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500227void SimpleLogImplementation::LogStruct(
Brian Silverman669669f2014-02-14 16:32:56 -0800228 log_level level, const ::std::string &message, size_t size,
229 const MessageType *type, const ::std::function<size_t(char *)> &serialize) {
230 char serialized[1024];
231 if (size > sizeof(serialized)) {
232 LOG(FATAL, "structure of type %s too big to serialize\n",
233 type->name.c_str());
234 }
235 size_t used = serialize(serialized);
Brian Silverman2508c082014-02-17 15:45:02 -0800236 char printed[1024];
Brian Silverman669669f2014-02-14 16:32:56 -0800237 size_t printed_bytes = sizeof(printed);
238 if (!PrintMessage(printed, &printed_bytes, serialized, &used, *type)) {
239 LOG(FATAL, "PrintMessage(%p, %p(=%zd), %p, %p(=%zd), %p(name=%s)) failed\n",
240 printed, &printed_bytes, printed_bytes, serialized, &used, used, type,
241 type->name.c_str());
242 }
243 DoLogVariadic(level, "%.*s: %.*s\n", static_cast<int>(message.size()),
Brian Silverman1c7b8192014-02-16 22:37:36 -0800244 message.data(),
245 static_cast<int>(sizeof(printed) - printed_bytes), printed);
Brian Silverman669669f2014-02-14 16:32:56 -0800246}
247
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500248void SimpleLogImplementation::LogMatrix(
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700249 log_level level, const ::std::string &message, uint32_t type_id,
250 int rows, int cols, const void *data) {
251 char serialized[1024];
252 if (static_cast<size_t>(rows * cols * MessageType::Sizeof(type_id)) >
253 sizeof(serialized)) {
254 LOG(FATAL, "matrix of size %u too big to serialize\n",
255 rows * cols * MessageType::Sizeof(type_id));
256 }
257 SerializeMatrix(type_id, serialized, data, rows, cols);
258 char printed[1024];
259 size_t printed_bytes = sizeof(printed);
260 if (!PrintMatrix(printed, &printed_bytes, serialized, type_id, rows, cols)) {
261 LOG(FATAL, "PrintMatrix(%p, %p(=%zd), %p, %" PRIu32 ", %d, %d) failed\n",
262 printed, &printed_bytes, printed_bytes, serialized, type_id, rows,
263 cols);
264 }
265 DoLogVariadic(level, "%.*s: %.*s\n", static_cast<int>(message.size()),
266 message.data(),
267 static_cast<int>(sizeof(printed) - printed_bytes), printed);
268}
269
Brian Silvermanbe858a12014-04-30 17:37:28 -0700270void HandleMessageLogImplementation::DoLog(log_level level, const char *format,
271 va_list ap) {
272 LogMessage message;
273 internal::FillInMessage(level, format, ap, &message);
274 HandleMessage(message);
275}
276
277void HandleMessageLogImplementation::LogStruct(
278 log_level level, const ::std::string &message_string, size_t size,
279 const MessageType *type, const ::std::function<size_t(char *)> &serialize) {
280 LogMessage message;
281 internal::FillInMessageStructure(level, message_string, size, type, serialize,
282 &message);
283 HandleMessage(message);
284}
285
286void HandleMessageLogImplementation::LogMatrix(
287 log_level level, const ::std::string &message_string, uint32_t type_id,
288 int rows, int cols, const void *data) {
289 LogMessage message;
290 internal::FillInMessageMatrix(level, message_string, type_id, rows, cols,
291 data, &message);
292 HandleMessage(message);
293}
294
Brian Silverman1e8ddfe2013-12-19 16:20:53 -0800295StreamLogImplementation::StreamLogImplementation(FILE *stream)
296 : stream_(stream) {}
297
Brian Silvermanbe858a12014-04-30 17:37:28 -0700298void StreamLogImplementation::HandleMessage(const LogMessage &message) {
Brian Silverman1e8ddfe2013-12-19 16:20:53 -0800299 internal::PrintMessage(stream_, message);
300}
301
Brian Silvermanf665d692013-02-17 22:11:39 -0800302void AddImplementation(LogImplementation *implementation) {
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500303 internal::Context *context = internal::Context::Get();
Brian Silvermanf665d692013-02-17 22:11:39 -0800304
305 if (implementation->next() != NULL) {
306 LOG(FATAL, "%p already has a next implementation, but it's not"
307 " being used yet\n", implementation);
308 }
309
310 LogImplementation *old = context->implementation;
311 if (old != NULL) {
312 implementation->set_next(old);
313 }
314 SetGlobalImplementation(implementation);
Brian Silverman2e799732014-06-05 21:50:19 -0700315 root_implementation->have_other_implementation();
Brian Silvermanf665d692013-02-17 22:11:39 -0800316}
317
318void Init() {
319 static Once<void> once(DoInit);
320 once.Get();
321}
322
323void Load() {
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500324 internal::Context::Get();
Brian Silvermanf665d692013-02-17 22:11:39 -0800325}
326
327void Cleanup() {
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500328 internal::Context::Delete();
329}
330
331namespace {
332
333RawQueue *queue = NULL;
334
335int dropped_messages = 0;
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800336monotonic_clock::time_point dropped_start, backoff_start;
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500337// Wait this long after dropping a message before even trying to write any more.
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800338constexpr chrono::milliseconds kDropBackoff = chrono::milliseconds(100);
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500339
340LogMessage *GetMessageOrDie() {
341 LogMessage *message = static_cast<LogMessage *>(queue->GetMessage());
342 if (message == NULL) {
343 LOG(FATAL, "%p->GetMessage() failed\n", queue);
344 } else {
345 return message;
346 }
347}
348
349void Write(LogMessage *msg) {
350 if (__builtin_expect(dropped_messages > 0, false)) {
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800351 monotonic_clock::time_point message_time(
352 chrono::seconds(msg->seconds) + chrono::nanoseconds(msg->nseconds));
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500353 if (message_time - backoff_start < kDropBackoff) {
354 ++dropped_messages;
355 queue->FreeMessage(msg);
356 return;
357 }
358
359 LogMessage *dropped_message = GetMessageOrDie();
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800360 chrono::seconds dropped_start_sec = chrono::duration_cast<chrono::seconds>(
361 dropped_start.time_since_epoch());
362 chrono::nanoseconds dropped_start_nsec =
363 chrono::duration_cast<chrono::nanoseconds>(
364 dropped_start.time_since_epoch() - dropped_start_sec);
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500365 internal::FillInMessageVarargs(
366 ERROR, dropped_message,
367 "%d logs starting at %" PRId32 ".%" PRId32 " dropped\n",
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800368 dropped_messages, static_cast<int32_t>(dropped_start_sec.count()),
369 static_cast<int32_t>(dropped_start_nsec.count()));
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500370 if (queue->WriteMessage(dropped_message, RawQueue::kNonBlock)) {
371 dropped_messages = 0;
372 } else {
373 // Don't even bother trying to write this message because it's not likely
374 // to work and it would be confusing to have one log in the middle of a
375 // string of failures get through.
376 ++dropped_messages;
377 backoff_start = message_time;
378 queue->FreeMessage(msg);
379 return;
380 }
381 }
382 if (!queue->WriteMessage(msg, RawQueue::kNonBlock)) {
383 if (dropped_messages == 0) {
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800384 monotonic_clock::time_point message_time(
385 chrono::seconds(msg->seconds) + chrono::nanoseconds(msg->nseconds));
386 dropped_start = backoff_start = message_time;
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500387 }
388 ++dropped_messages;
389 }
390}
391
392class LinuxQueueLogImplementation : public LogImplementation {
393 __attribute__((format(GOOD_PRINTF_FORMAT_TYPE, 3, 0)))
394 void DoLog(log_level level, const char *format, va_list ap) override {
395 LogMessage *message = GetMessageOrDie();
396 internal::FillInMessage(level, format, ap, message);
397 Write(message);
398 }
399
400 void LogStruct(log_level level, const ::std::string &message_string,
401 size_t size, const MessageType *type,
402 const ::std::function<size_t(char *)> &serialize) override {
403 LogMessage *message = GetMessageOrDie();
404 internal::FillInMessageStructure(level, message_string, size, type,
405 serialize, message);
406 Write(message);
407 }
408
409 void LogMatrix(log_level level, const ::std::string &message_string,
410 uint32_t type_id, int rows, int cols,
411 const void *data) override {
412 LogMessage *message = GetMessageOrDie();
413 internal::FillInMessageMatrix(level, message_string, type_id, rows, cols,
414 data, message);
415 Write(message);
416 }
417};
418
419} // namespace
420
421RawQueue *GetLoggingQueue() {
422 return RawQueue::Fetch("LoggingQueue", sizeof(LogMessage), 1323, 40000);
423}
424
425void RegisterQueueImplementation() {
426 Init();
427
428 queue = GetLoggingQueue();
429 if (queue == NULL) {
430 Die("logging: couldn't fetch queue\n");
431 }
432
433 AddImplementation(new LinuxQueueLogImplementation());
Brian Silvermanf665d692013-02-17 22:11:39 -0800434}
435
436} // namespace logging
437} // namespace aos