blob: 78b67246fb5321d96959c49dbb151d8bc2405c60 [file] [log] [blame]
John Park33858a32018-09-28 23:05:48 -07001#include "aos/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
John Park33858a32018-09-28 23:05:48 -07009#include "aos/die.h"
10#include "aos/logging/printf_formats.h"
11#include "aos/queue_types.h"
12#include "aos/time/time.h"
John Park398c74a2018-10-20 21:17:39 -070013#include "aos/ipc_lib/queue.h"
Sabina Davis2ed5ea22017-09-26 22:27:42 -070014#include "aos/once.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)) {
Austin Schuhc804fd12019-03-22 21:15:37 -0700115 LOG(FATAL,
116 "serialized struct %s (size %zd + %zd > %zd) and message %s too big\n",
117 type->name.c_str(), message_string.size(), size,
118 sizeof(message->structure.serialized), message_string.c_str());
Brian Silverman88471dc2014-02-15 22:35:42 -0800119 }
120 message->structure.string_length = message_string.size();
121 memcpy(message->structure.serialized, message_string.data(),
122 message->structure.string_length);
123
124 message->message_length = serialize(
125 &message->structure.serialized[message->structure.string_length]);
126 message->type = LogMessage::Type::kStruct;
127}
128
Brian Silverman664db1a2014-03-20 17:06:29 -0700129void FillInMessageMatrix(log_level level,
130 const ::std::string &message_string, uint32_t type_id,
131 int rows, int cols, const void *data,
132 LogMessage *message) {
133 CHECK(MessageType::IsPrimitive(type_id));
134 message->matrix.type = type_id;
135
136 const auto element_size = MessageType::Sizeof(type_id);
137
138 FillInMessageBase(level, message);
139
140 message->message_length = rows * cols * element_size;
141 if (message_string.size() + message->message_length >
142 sizeof(message->matrix.data)) {
143 LOG(FATAL, "%dx%d matrix of type %" PRIu32
144 " (size %u) and message %s is too big\n",
145 rows, cols, type_id, element_size, message_string.c_str());
146 }
147 message->matrix.string_length = message_string.size();
148 memcpy(message->matrix.data, message_string.data(),
149 message->matrix.string_length);
150
151 message->matrix.rows = rows;
152 message->matrix.cols = cols;
153 SerializeMatrix(type_id, &message->matrix.data[message->matrix.string_length],
154 data, rows, cols);
155 message->type = LogMessage::Type::kMatrix;
156}
157
Brian Silverman88471dc2014-02-15 22:35:42 -0800158void FillInMessage(log_level level, const char *format, va_list ap,
159 LogMessage *message) {
160 FillInMessageBase(level, message);
161
162 message->message_length =
163 ExecuteFormat(message->message, sizeof(message->message), format, ap);
164 message->type = LogMessage::Type::kString;
165}
166
Brian Silvermanf665d692013-02-17 22:11:39 -0800167void PrintMessage(FILE *output, const LogMessage &message) {
Brian Silvermana7234c62014-03-24 20:23:25 -0700168#define BASE_ARGS \
169 AOS_LOGGING_BASE_ARGS( \
170 message.name_length, message.name, static_cast<int32_t>(message.source), \
171 message.sequence, message.level, message.seconds, message.nseconds)
172 switch (message.type) {
Brian Silverman88471dc2014-02-15 22:35:42 -0800173 case LogMessage::Type::kString:
Brian Silvermana7234c62014-03-24 20:23:25 -0700174 fprintf(output, AOS_LOGGING_BASE_FORMAT "%.*s", BASE_ARGS,
Brian Silverman88471dc2014-02-15 22:35:42 -0800175 static_cast<int>(message.message_length), message.message);
176 break;
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700177 case LogMessage::Type::kStruct: {
Austin Schuheee8c962017-04-12 22:32:44 -0700178 char buffer[4096];
Brian Silverman88471dc2014-02-15 22:35:42 -0800179 size_t output_length = sizeof(buffer);
180 size_t input_length = message.message_length;
181 if (!PrintMessage(
182 buffer, &output_length,
183 message.structure.serialized + message.structure.string_length,
184 &input_length, type_cache::Get(message.structure.type_id))) {
185 LOG(FATAL,
186 "printing message (%.*s) of type %s into %zu-byte buffer failed\n",
187 static_cast<int>(message.message_length), message.message,
188 type_cache::Get(message.structure.type_id).name.c_str(),
189 sizeof(buffer));
190 }
191 if (input_length > 0) {
192 LOG(WARNING, "%zu extra bytes on message of type %s\n", input_length,
193 type_cache::Get(message.structure.type_id).name.c_str());
194 }
Brian Silvermana7234c62014-03-24 20:23:25 -0700195 fprintf(output, AOS_LOGGING_BASE_FORMAT "%.*s: %.*s\n", BASE_ARGS,
Brian Silvermanb263d302014-02-16 00:01:43 -0800196 static_cast<int>(message.structure.string_length),
197 message.structure.serialized,
198 static_cast<int>(sizeof(buffer) - output_length), buffer);
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700199 } break;
200 case LogMessage::Type::kMatrix: {
201 char buffer[1024];
202 size_t output_length = sizeof(buffer);
203 if (message.message_length !=
204 static_cast<size_t>(message.matrix.rows * message.matrix.cols *
205 MessageType::Sizeof(message.matrix.type))) {
206 LOG(FATAL, "expected %d bytes of matrix data but have %zu\n",
207 message.matrix.rows * message.matrix.cols *
208 MessageType::Sizeof(message.matrix.type),
209 message.message_length);
210 }
211 if (!PrintMatrix(buffer, &output_length,
212 message.matrix.data + message.matrix.string_length,
213 message.matrix.type, message.matrix.rows,
214 message.matrix.cols)) {
215 LOG(FATAL, "printing %dx%d matrix of type %" PRIu32 " failed\n",
216 message.matrix.rows, message.matrix.cols, message.matrix.type);
217 }
Brian Silvermana7234c62014-03-24 20:23:25 -0700218 fprintf(output, AOS_LOGGING_BASE_FORMAT "%.*s: %.*s\n", BASE_ARGS,
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700219 static_cast<int>(message.matrix.string_length),
Brian Silverman664db1a2014-03-20 17:06:29 -0700220 message.matrix.data,
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700221 static_cast<int>(sizeof(buffer) - output_length), buffer);
222 } break;
Brian Silverman88471dc2014-02-15 22:35:42 -0800223 }
Brian Silvermanc1a244e2014-02-20 14:12:39 -0800224#undef BASE_ARGS
Brian Silvermanf665d692013-02-17 22:11:39 -0800225}
226
227} // namespace internal
228
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500229void SimpleLogImplementation::LogStruct(
Brian Silverman669669f2014-02-14 16:32:56 -0800230 log_level level, const ::std::string &message, size_t size,
231 const MessageType *type, const ::std::function<size_t(char *)> &serialize) {
232 char serialized[1024];
233 if (size > sizeof(serialized)) {
234 LOG(FATAL, "structure of type %s too big to serialize\n",
235 type->name.c_str());
236 }
237 size_t used = serialize(serialized);
Brian Silverman2508c082014-02-17 15:45:02 -0800238 char printed[1024];
Brian Silverman669669f2014-02-14 16:32:56 -0800239 size_t printed_bytes = sizeof(printed);
240 if (!PrintMessage(printed, &printed_bytes, serialized, &used, *type)) {
241 LOG(FATAL, "PrintMessage(%p, %p(=%zd), %p, %p(=%zd), %p(name=%s)) failed\n",
242 printed, &printed_bytes, printed_bytes, serialized, &used, used, type,
243 type->name.c_str());
244 }
245 DoLogVariadic(level, "%.*s: %.*s\n", static_cast<int>(message.size()),
Brian Silverman1c7b8192014-02-16 22:37:36 -0800246 message.data(),
247 static_cast<int>(sizeof(printed) - printed_bytes), printed);
Brian Silverman669669f2014-02-14 16:32:56 -0800248}
249
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500250void SimpleLogImplementation::LogMatrix(
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700251 log_level level, const ::std::string &message, uint32_t type_id,
252 int rows, int cols, const void *data) {
253 char serialized[1024];
254 if (static_cast<size_t>(rows * cols * MessageType::Sizeof(type_id)) >
255 sizeof(serialized)) {
256 LOG(FATAL, "matrix of size %u too big to serialize\n",
257 rows * cols * MessageType::Sizeof(type_id));
258 }
259 SerializeMatrix(type_id, serialized, data, rows, cols);
260 char printed[1024];
261 size_t printed_bytes = sizeof(printed);
262 if (!PrintMatrix(printed, &printed_bytes, serialized, type_id, rows, cols)) {
263 LOG(FATAL, "PrintMatrix(%p, %p(=%zd), %p, %" PRIu32 ", %d, %d) failed\n",
264 printed, &printed_bytes, printed_bytes, serialized, type_id, rows,
265 cols);
266 }
267 DoLogVariadic(level, "%.*s: %.*s\n", static_cast<int>(message.size()),
268 message.data(),
269 static_cast<int>(sizeof(printed) - printed_bytes), printed);
270}
271
Brian Silvermanbe858a12014-04-30 17:37:28 -0700272void HandleMessageLogImplementation::DoLog(log_level level, const char *format,
273 va_list ap) {
274 LogMessage message;
275 internal::FillInMessage(level, format, ap, &message);
276 HandleMessage(message);
277}
278
279void HandleMessageLogImplementation::LogStruct(
280 log_level level, const ::std::string &message_string, size_t size,
281 const MessageType *type, const ::std::function<size_t(char *)> &serialize) {
282 LogMessage message;
283 internal::FillInMessageStructure(level, message_string, size, type, serialize,
284 &message);
285 HandleMessage(message);
286}
287
288void HandleMessageLogImplementation::LogMatrix(
289 log_level level, const ::std::string &message_string, uint32_t type_id,
290 int rows, int cols, const void *data) {
291 LogMessage message;
292 internal::FillInMessageMatrix(level, message_string, type_id, rows, cols,
293 data, &message);
294 HandleMessage(message);
295}
296
Brian Silverman1e8ddfe2013-12-19 16:20:53 -0800297StreamLogImplementation::StreamLogImplementation(FILE *stream)
298 : stream_(stream) {}
299
Brian Silvermanbe858a12014-04-30 17:37:28 -0700300void StreamLogImplementation::HandleMessage(const LogMessage &message) {
Brian Silverman1e8ddfe2013-12-19 16:20:53 -0800301 internal::PrintMessage(stream_, message);
302}
303
Brian Silvermanf665d692013-02-17 22:11:39 -0800304void AddImplementation(LogImplementation *implementation) {
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500305 internal::Context *context = internal::Context::Get();
Brian Silvermanf665d692013-02-17 22:11:39 -0800306
307 if (implementation->next() != NULL) {
308 LOG(FATAL, "%p already has a next implementation, but it's not"
309 " being used yet\n", implementation);
310 }
311
312 LogImplementation *old = context->implementation;
313 if (old != NULL) {
314 implementation->set_next(old);
315 }
316 SetGlobalImplementation(implementation);
Brian Silverman2e799732014-06-05 21:50:19 -0700317 root_implementation->have_other_implementation();
Brian Silvermanf665d692013-02-17 22:11:39 -0800318}
319
320void Init() {
321 static Once<void> once(DoInit);
322 once.Get();
323}
324
325void Load() {
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500326 internal::Context::Get();
Brian Silvermanf665d692013-02-17 22:11:39 -0800327}
328
329void Cleanup() {
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500330 internal::Context::Delete();
331}
332
333namespace {
334
335RawQueue *queue = NULL;
336
337int dropped_messages = 0;
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800338monotonic_clock::time_point dropped_start, backoff_start;
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500339// Wait this long after dropping a message before even trying to write any more.
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800340constexpr chrono::milliseconds kDropBackoff = chrono::milliseconds(100);
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500341
342LogMessage *GetMessageOrDie() {
343 LogMessage *message = static_cast<LogMessage *>(queue->GetMessage());
344 if (message == NULL) {
345 LOG(FATAL, "%p->GetMessage() failed\n", queue);
346 } else {
347 return message;
348 }
349}
350
351void Write(LogMessage *msg) {
352 if (__builtin_expect(dropped_messages > 0, false)) {
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800353 monotonic_clock::time_point message_time(
354 chrono::seconds(msg->seconds) + chrono::nanoseconds(msg->nseconds));
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500355 if (message_time - backoff_start < kDropBackoff) {
356 ++dropped_messages;
357 queue->FreeMessage(msg);
358 return;
359 }
360
361 LogMessage *dropped_message = GetMessageOrDie();
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800362 chrono::seconds dropped_start_sec = chrono::duration_cast<chrono::seconds>(
363 dropped_start.time_since_epoch());
364 chrono::nanoseconds dropped_start_nsec =
365 chrono::duration_cast<chrono::nanoseconds>(
366 dropped_start.time_since_epoch() - dropped_start_sec);
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500367 internal::FillInMessageVarargs(
368 ERROR, dropped_message,
369 "%d logs starting at %" PRId32 ".%" PRId32 " dropped\n",
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800370 dropped_messages, static_cast<int32_t>(dropped_start_sec.count()),
371 static_cast<int32_t>(dropped_start_nsec.count()));
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500372 if (queue->WriteMessage(dropped_message, RawQueue::kNonBlock)) {
373 dropped_messages = 0;
374 } else {
375 // Don't even bother trying to write this message because it's not likely
376 // to work and it would be confusing to have one log in the middle of a
377 // string of failures get through.
378 ++dropped_messages;
379 backoff_start = message_time;
380 queue->FreeMessage(msg);
381 return;
382 }
383 }
384 if (!queue->WriteMessage(msg, RawQueue::kNonBlock)) {
385 if (dropped_messages == 0) {
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800386 monotonic_clock::time_point message_time(
387 chrono::seconds(msg->seconds) + chrono::nanoseconds(msg->nseconds));
388 dropped_start = backoff_start = message_time;
Brian Silvermancb5da1f2015-12-05 22:19:58 -0500389 }
390 ++dropped_messages;
391 }
392}
393
394class LinuxQueueLogImplementation : public LogImplementation {
395 __attribute__((format(GOOD_PRINTF_FORMAT_TYPE, 3, 0)))
396 void DoLog(log_level level, const char *format, va_list ap) override {
397 LogMessage *message = GetMessageOrDie();
398 internal::FillInMessage(level, format, ap, message);
399 Write(message);
400 }
401
402 void LogStruct(log_level level, const ::std::string &message_string,
403 size_t size, const MessageType *type,
404 const ::std::function<size_t(char *)> &serialize) override {
405 LogMessage *message = GetMessageOrDie();
406 internal::FillInMessageStructure(level, message_string, size, type,
407 serialize, message);
408 Write(message);
409 }
410
411 void LogMatrix(log_level level, const ::std::string &message_string,
412 uint32_t type_id, int rows, int cols,
413 const void *data) override {
414 LogMessage *message = GetMessageOrDie();
415 internal::FillInMessageMatrix(level, message_string, type_id, rows, cols,
416 data, message);
417 Write(message);
418 }
419};
420
421} // namespace
422
423RawQueue *GetLoggingQueue() {
424 return RawQueue::Fetch("LoggingQueue", sizeof(LogMessage), 1323, 40000);
425}
426
427void RegisterQueueImplementation() {
428 Init();
429
430 queue = GetLoggingQueue();
431 if (queue == NULL) {
432 Die("logging: couldn't fetch queue\n");
433 }
434
435 AddImplementation(new LinuxQueueLogImplementation());
Brian Silvermanf665d692013-02-17 22:11:39 -0800436}
437
438} // namespace logging
439} // namespace aos