blob: e35fe5bb098448aa4fcc36258407e3263b22fd85 [file] [log] [blame]
James Kuszmaul38735e82019-12-07 16:42:06 -08001#include "aos/events/logging/logger.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -08002
3#include <fcntl.h>
Austin Schuh4c4e0092019-12-22 16:18:03 -08004#include <limits.h>
Austin Schuhe309d2a2019-11-29 13:25:21 -08005#include <sys/stat.h>
6#include <sys/types.h>
7#include <sys/uio.h>
8#include <vector>
9
10#include "absl/strings/string_view.h"
11#include "absl/types/span.h"
12#include "aos/events/event_loop.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080013#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080014#include "aos/flatbuffer_merge.h"
Austin Schuh288479d2019-12-18 19:47:52 -080015#include "aos/network/team_number.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080016#include "aos/time/time.h"
17#include "flatbuffers/flatbuffers.h"
18
19DEFINE_int32(flush_size, 1000000,
20 "Number of outstanding bytes to allow before flushing to disk.");
21
22namespace aos {
23namespace logger {
24
25namespace chrono = std::chrono;
26
27DetachedBufferWriter::DetachedBufferWriter(absl::string_view filename)
28 : fd_(open(std::string(filename).c_str(),
29 O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, 0774)) {
30 PCHECK(fd_ != -1) << ": Failed to open " << filename;
31}
32
33DetachedBufferWriter::~DetachedBufferWriter() {
34 Flush();
35 PLOG_IF(ERROR, close(fd_) == -1) << " Failed to close logfile";
36}
37
38void DetachedBufferWriter::QueueSizedFlatbuffer(
39 flatbuffers::FlatBufferBuilder *fbb) {
40 QueueSizedFlatbuffer(fbb->Release());
41}
42
43void DetachedBufferWriter::QueueSizedFlatbuffer(
44 flatbuffers::DetachedBuffer &&buffer) {
45 queued_size_ += buffer.size();
46 queue_.emplace_back(std::move(buffer));
47
Austin Schuh4c4e0092019-12-22 16:18:03 -080048 // Flush if we are at the max number of iovs per writev, or have written
49 // enough data. Otherwise writev will fail with an invalid argument.
50 if (queued_size_ > static_cast<size_t>(FLAGS_flush_size) ||
51 queue_.size() == IOV_MAX) {
Austin Schuhe309d2a2019-11-29 13:25:21 -080052 Flush();
53 }
54}
55
56void DetachedBufferWriter::Flush() {
57 if (queue_.size() == 0u) {
58 return;
59 }
60 iovec_.clear();
61 iovec_.reserve(queue_.size());
62 size_t counted_size = 0;
63 for (size_t i = 0; i < queue_.size(); ++i) {
64 struct iovec n;
65 n.iov_base = queue_[i].data();
66 n.iov_len = queue_[i].size();
67 counted_size += n.iov_len;
68 iovec_.emplace_back(std::move(n));
69 }
70 CHECK_EQ(counted_size, queued_size_);
71 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
72
73 PCHECK(written == static_cast<ssize_t>(queued_size_))
74 << ": Wrote " << written << " expected " << queued_size_;
75
76 queued_size_ = 0;
77 queue_.clear();
78 // TODO(austin): Handle partial writes in some way other than crashing...
79}
80
81Logger::Logger(DetachedBufferWriter *writer, EventLoop *event_loop,
82 std::chrono::milliseconds polling_period)
83 : event_loop_(event_loop),
84 writer_(writer),
85 timer_handler_(event_loop_->AddTimer([this]() { DoLogData(); })),
86 polling_period_(polling_period) {
87 for (const Channel *channel : *event_loop_->configuration()->channels()) {
88 FetcherStruct fs;
89 fs.fetcher = event_loop->MakeRawFetcher(channel);
90 fs.written = false;
91 fetchers_.emplace_back(std::move(fs));
92 }
93
94 // When things start, we want to log the header, then the most recent messages
95 // available on each fetcher to capture the previous state, then start
96 // polling.
97 event_loop_->OnRun([this, polling_period]() {
98 // Grab data from each channel right before we declare the log file started
99 // so we can capture the latest message on each channel. This lets us have
100 // non periodic messages with configuration that now get logged.
101 for (FetcherStruct &f : fetchers_) {
102 f.written = !f.fetcher->Fetch();
103 }
104
105 // We need to pick a point in time to declare the log file "started". This
106 // starts here. It needs to be after everything is fetched so that the
107 // fetchers are all pointed at the most recent message before the start
108 // time.
109 const monotonic_clock::time_point monotonic_now =
110 event_loop_->monotonic_now();
111 const realtime_clock::time_point realtime_now = event_loop_->realtime_now();
112 last_synchronized_time_ = monotonic_now;
113
114 {
115 // Now write the header with this timestamp in it.
116 flatbuffers::FlatBufferBuilder fbb;
117 fbb.ForceDefaults(1);
118
119 flatbuffers::Offset<aos::Configuration> configuration_offset =
120 CopyFlatBuffer(event_loop_->configuration(), &fbb);
121
Austin Schuh288479d2019-12-18 19:47:52 -0800122 flatbuffers::Offset<flatbuffers::String> string_offset =
123 fbb.CreateString(network::GetHostname());
124
Austin Schuhe309d2a2019-11-29 13:25:21 -0800125 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
126
Austin Schuh288479d2019-12-18 19:47:52 -0800127 log_file_header_builder.add_name(string_offset);
128
Austin Schuhe309d2a2019-11-29 13:25:21 -0800129 log_file_header_builder.add_configuration(configuration_offset);
130 // The worst case theoretical out of order is the polling period times 2.
131 // One message could get logged right after the boundary, but be for right
132 // before the next boundary. And the reverse could happen for another
133 // message. Report back 3x to be extra safe, and because the cost isn't
134 // huge on the read side.
135 log_file_header_builder.add_max_out_of_order_duration(
136 std::chrono::duration_cast<std::chrono::nanoseconds>(3 *
137 polling_period)
138 .count());
139
Austin Schuh629c9172019-12-23 20:34:43 -0800140 log_file_header_builder.add_monotonic_start_time(
Austin Schuhe309d2a2019-11-29 13:25:21 -0800141 std::chrono::duration_cast<std::chrono::nanoseconds>(
142 monotonic_now.time_since_epoch())
143 .count());
Austin Schuh629c9172019-12-23 20:34:43 -0800144 log_file_header_builder.add_realtime_start_time(
Austin Schuhe309d2a2019-11-29 13:25:21 -0800145 std::chrono::duration_cast<std::chrono::nanoseconds>(
146 realtime_now.time_since_epoch())
147 .count());
148
149 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
150 writer_->QueueSizedFlatbuffer(&fbb);
151 }
152
153 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period,
154 polling_period);
155 });
156}
157
Austin Schuh646b7b82019-12-22 21:38:55 -0800158flatbuffers::Offset<MessageHeader> PackMessage(
159 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
160 int channel_index) {
161 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset =
162 fbb->CreateVector(static_cast<uint8_t *>(context.data), context.size);
163
164 MessageHeader::Builder message_header_builder(*fbb);
165 message_header_builder.add_channel_index(channel_index);
166 message_header_builder.add_monotonic_sent_time(
Austin Schuhad154822019-12-27 15:45:13 -0800167 context.monotonic_event_time.time_since_epoch().count());
Austin Schuh646b7b82019-12-22 21:38:55 -0800168 message_header_builder.add_realtime_sent_time(
Austin Schuhad154822019-12-27 15:45:13 -0800169 context.realtime_event_time.time_since_epoch().count());
Austin Schuh646b7b82019-12-22 21:38:55 -0800170
171 message_header_builder.add_queue_index(context.queue_index);
172
173 message_header_builder.add_data(data_offset);
174 return message_header_builder.Finish();
175}
176
Austin Schuhe309d2a2019-11-29 13:25:21 -0800177void Logger::DoLogData() {
178 // We want to guarentee that messages aren't out of order by more than
179 // max_out_of_order_duration. To do this, we need sync points. Every write
180 // cycle should be a sync point.
181 const monotonic_clock::time_point monotonic_now = monotonic_clock::now();
182
183 do {
184 // Move the sync point up by at most polling_period. This forces one sync
185 // per iteration, even if it is small.
186 last_synchronized_time_ =
187 std::min(last_synchronized_time_ + polling_period_, monotonic_now);
188 size_t channel_index = 0;
189 // Write each channel to disk, one at a time.
190 for (FetcherStruct &f : fetchers_) {
191 while (true) {
192 if (f.fetcher.get() == nullptr) {
193 if (!f.fetcher->FetchNext()) {
194 VLOG(1) << "No new data on "
195 << FlatbufferToJson(f.fetcher->channel());
196 break;
197 } else {
198 f.written = false;
199 }
200 }
201
202 if (f.written) {
203 if (!f.fetcher->FetchNext()) {
204 VLOG(1) << "No new data on "
205 << FlatbufferToJson(f.fetcher->channel());
206 break;
207 } else {
208 f.written = false;
209 }
210 }
211
James Kuszmaul91deec92019-12-15 12:18:44 -0800212 CHECK(!f.written);
213
214 // TODO(james): Write tests to exercise this logic.
Austin Schuhad154822019-12-27 15:45:13 -0800215 if (f.fetcher->context().monotonic_event_time <
James Kuszmaul91deec92019-12-15 12:18:44 -0800216 last_synchronized_time_) {
Austin Schuhe309d2a2019-11-29 13:25:21 -0800217 // Write!
218 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
219 max_header_size_);
220 fbb.ForceDefaults(1);
221
Austin Schuh646b7b82019-12-22 21:38:55 -0800222 fbb.FinishSizePrefixed(
223 PackMessage(&fbb, f.fetcher->context(), channel_index));
Austin Schuhe309d2a2019-11-29 13:25:21 -0800224
225 VLOG(1) << "Writing data for channel "
226 << FlatbufferToJson(f.fetcher->channel());
227
Austin Schuhe309d2a2019-11-29 13:25:21 -0800228 max_header_size_ = std::max(
229 max_header_size_, fbb.GetSize() - f.fetcher->context().size);
230 writer_->QueueSizedFlatbuffer(&fbb);
231
232 f.written = true;
James Kuszmaul91deec92019-12-15 12:18:44 -0800233 } else {
234 break;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800235 }
236 }
237
238 ++channel_index;
239 }
240
241 CHECK_EQ(channel_index, fetchers_.size());
242
243 // If we missed cycles, we could be pretty far behind. Spin until we are
244 // caught up.
245 } while (last_synchronized_time_ + polling_period_ < monotonic_now);
246
247 writer_->Flush();
248}
249
250LogReader::LogReader(absl::string_view filename)
251 : fd_(open(std::string(filename).c_str(), O_RDONLY | O_CLOEXEC)) {
252 PCHECK(fd_ != -1) << ": Failed to open " << filename;
253
254 // Make sure we have enough to read the size.
255 absl::Span<const uint8_t> config_data = ReadMessage();
256
257 // Make sure something was read.
258 CHECK(config_data != absl::Span<const uint8_t>());
259
260 // And copy the config so we have it forever.
261 configuration_ = std::vector<uint8_t>(config_data.begin(), config_data.end());
262
263 max_out_of_order_duration_ = std::chrono::nanoseconds(
264 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
265 ->max_out_of_order_duration());
266
267 channels_.resize(configuration()->channels()->size());
268
269 QueueMessages();
270}
271
272bool LogReader::ReadBlock() {
273 if (end_of_file_) {
274 return false;
275 }
276
277 // Appends 256k. This is enough that the read call is efficient. We don't
278 // want to spend too much time reading small chunks because the syscalls for
279 // that will be expensive.
280 constexpr size_t kReadSize = 256 * 1024;
281
282 // Strip off any unused data at the front.
283 if (consumed_data_ != 0) {
284 data_.erase(data_.begin(), data_.begin() + consumed_data_);
285 consumed_data_ = 0;
286 }
287
288 const size_t starting_size = data_.size();
289
290 // This should automatically grow the backing store. It won't shrink if we
291 // get a small chunk later. This reduces allocations when we want to append
292 // more data.
293 data_.resize(data_.size() + kReadSize);
294
295 ssize_t count = read(fd_, &data_[starting_size], kReadSize);
296 data_.resize(starting_size + std::max(count, static_cast<ssize_t>(0)));
297 if (count == 0) {
298 end_of_file_ = true;
299 return false;
300 }
301 PCHECK(count > 0);
302
303 return true;
304}
305
306bool LogReader::MessageAvailable() {
307 // Are we big enough to read the size?
308 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
309 return false;
310 }
311
312 // Then, are we big enough to read the full message?
313 const size_t data_size =
314 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
315 sizeof(flatbuffers::uoffset_t);
316 if (data_.size() < consumed_data_ + data_size) {
317 return false;
318 }
319
320 return true;
321}
322
323absl::Span<const uint8_t> LogReader::ReadMessage() {
324 // Make sure we have enough for the size.
325 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
326 if (!ReadBlock()) {
327 return absl::Span<const uint8_t>();
328 }
329 }
330
331 // Now make sure we have enough for the message.
332 const size_t data_size =
333 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
334 sizeof(flatbuffers::uoffset_t);
335 while (data_.size() < consumed_data_ + data_size) {
336 if (!ReadBlock()) {
337 return absl::Span<const uint8_t>();
338 }
339 }
340
341 // And return it, consuming the data.
342 const uint8_t *data_ptr = data_.data() + consumed_data_;
343
344 consumed_data_ += data_size;
345
346 return absl::Span<const uint8_t>(data_ptr, data_size);
347}
348
349void LogReader::QueueMessages() {
350 while (true) {
351 // Don't queue if we have enough data already.
352 // When a log file starts, there should be a message from each channel.
353 // Those messages might be very old. Make sure to read a chunk past the
354 // starting time.
355 if (channel_heap_.size() > 0 &&
356 newest_timestamp_ >
357 std::max(oldest_message().first, monotonic_start_time()) +
358 max_out_of_order_duration_) {
359 break;
360 }
361
362 absl::Span<const uint8_t> msg_data = ReadMessage();
363 if (msg_data == absl::Span<const uint8_t>()) {
364 break;
365 }
366
367 FlatbufferVector<MessageHeader> msg(std::vector<uint8_t>(
368 msg_data.begin() + sizeof(flatbuffers::uoffset_t), msg_data.end()));
369
370 EmplaceDataBack(std::move(msg));
371 }
372
373 queue_data_time_ = newest_timestamp_ - max_out_of_order_duration_;
374}
375
376const Configuration *LogReader::configuration() {
377 return flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
378 ->configuration();
379}
380
381monotonic_clock::time_point LogReader::monotonic_start_time() {
382 return monotonic_clock::time_point(std::chrono::nanoseconds(
383 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
Austin Schuh629c9172019-12-23 20:34:43 -0800384 ->monotonic_start_time()));
Austin Schuhe309d2a2019-11-29 13:25:21 -0800385}
386
387realtime_clock::time_point LogReader::realtime_start_time() {
388 return realtime_clock::time_point(std::chrono::nanoseconds(
389 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
Austin Schuh629c9172019-12-23 20:34:43 -0800390 ->realtime_start_time()));
Austin Schuhe309d2a2019-11-29 13:25:21 -0800391}
392
Austin Schuh92547522019-12-28 14:33:43 -0800393void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
394 event_loop_unique_ptr_ = event_loop_factory->MakeEventLoop("log_reader");
395 event_loop_factory_ = event_loop_factory;
396 // We don't run timing reports when trying to print out logged data, because
397 // otherwise we would end up printing out the timing reports themselves...
398 // This is only really relevant when we are replaying into a simulation.
399 event_loop_unique_ptr_->SkipTimingReport();
400
401 Register(event_loop_unique_ptr_.get());
402 event_loop_factory_->RunFor(monotonic_start_time() -
403 event_loop_factory_->monotonic_now());
404}
405
Austin Schuhe309d2a2019-11-29 13:25:21 -0800406void LogReader::Register(EventLoop *event_loop) {
407 event_loop_ = event_loop;
408
Austin Schuh39788ff2019-12-01 18:22:57 -0800409 // Otherwise we replay the timing report and try to resend it...
410 event_loop_->SkipTimingReport();
411
Austin Schuhe309d2a2019-11-29 13:25:21 -0800412 for (size_t i = 0; i < channels_.size(); ++i) {
413 CHECK_EQ(configuration()->channels()->Get(i)->name(),
414 event_loop_->configuration()->channels()->Get(i)->name());
415 CHECK_EQ(configuration()->channels()->Get(i)->type(),
416 event_loop_->configuration()->channels()->Get(i)->type());
417
418 channels_[i].raw_sender = event_loop_->MakeRawSender(
419 event_loop_->configuration()->channels()->Get(i));
420 }
421
422 timer_handler_ = event_loop_->AddTimer([this]() {
423 std::pair<monotonic_clock::time_point, int> oldest_channel_index =
424 PopOldestChannel();
425 const monotonic_clock::time_point monotonic_now =
Austin Schuhad154822019-12-27 15:45:13 -0800426 event_loop_->context().monotonic_event_time;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800427 CHECK(monotonic_now == oldest_channel_index.first)
428 << ": Now " << monotonic_now.time_since_epoch().count()
429 << " trying to send "
430 << oldest_channel_index.first.time_since_epoch().count();
431
432 struct LogReader::ChannelData &channel =
433 channels_[oldest_channel_index.second];
434
435 FlatbufferVector<MessageHeader> front = std::move(channel.front());
436
437 CHECK(front.message().data() != nullptr);
Austin Schuh92547522019-12-28 14:33:43 -0800438
Austin Schuhe309d2a2019-11-29 13:25:21 -0800439 if (oldest_channel_index.first > monotonic_start_time()) {
Austin Schuh92547522019-12-28 14:33:43 -0800440 // If we have access to the factory, use it to fix the realtime time.
441 if (event_loop_factory_ != nullptr) {
442 event_loop_factory_->SetRealtimeOffset(
443 monotonic_clock::time_point(
444 chrono::nanoseconds(front.message().monotonic_sent_time())),
445 realtime_clock::time_point(
446 chrono::nanoseconds(front.message().realtime_sent_time())));
447 }
448
Austin Schuhe309d2a2019-11-29 13:25:21 -0800449 channel.raw_sender->Send(front.message().data()->Data(),
450 front.message().data()->size());
451 } else {
452 LOG(WARNING) << "Not sending data from before the start of the log file. "
453 << oldest_channel_index.first.time_since_epoch().count()
454 << " start "
455 << monotonic_start_time().time_since_epoch().count() << " "
456 << FlatbufferToJson(front);
457 }
458 channel.data.pop_front();
459
460 // Re-push it and update the oldest timestamp.
461 if (channel.data.size() != 0) {
462 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
463 chrono::nanoseconds(channel.front().message().monotonic_sent_time()));
464 PushChannelHeap(timestamp, oldest_channel_index.second);
465 channel.oldest_timestamp = timestamp;
466 } else {
467 channel.oldest_timestamp = monotonic_clock::min_time;
468 }
469
470 if (monotonic_now > queue_data_time_) {
471 QueueMessages();
472 }
473
474 if (channel_heap_.size() != 0) {
475 timer_handler_->Setup(oldest_message().first);
476 }
477 });
478
479 if (channel_heap_.size() > 0u) {
480 event_loop_->OnRun(
481 [this]() { timer_handler_->Setup(oldest_message().first); });
482 }
483}
484
485void LogReader::Deregister() {
486 for (size_t i = 0; i < channels_.size(); ++i) {
487 channels_[i].raw_sender.reset();
488 }
Austin Schuh92547522019-12-28 14:33:43 -0800489
490 event_loop_factory_ = nullptr;
491 event_loop_unique_ptr_.reset();
492 event_loop_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800493}
494
495void LogReader::EmplaceDataBack(FlatbufferVector<MessageHeader> &&new_data) {
496 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
497 chrono::nanoseconds(new_data.message().monotonic_sent_time()));
498 const size_t channel_index = new_data.message().channel_index();
499 CHECK_LT(channel_index, channels_.size());
500 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
501 if (channels_[channel_index].data.size() == 0) {
502 channels_[channel_index].oldest_timestamp = timestamp;
503 PushChannelHeap(timestamp, channel_index);
504 }
505 channels_[channel_index].data.emplace_back(std::move(new_data));
506}
507
508namespace {
509
510bool ChannelHeapCompare(
511 const std::pair<monotonic_clock::time_point, int> first,
512 const std::pair<monotonic_clock::time_point, int> second) {
513 if (first.first > second.first) {
514 return true;
515 } else if (first.first == second.first) {
516 return first.second > second.second;
517 } else {
518 return false;
519 }
520}
521
522} // namespace
523
524void LogReader::PushChannelHeap(monotonic_clock::time_point timestamp,
525 int channel_index) {
526 channel_heap_.push_back(std::make_pair(timestamp, channel_index));
527
528 // The default sort puts the newest message first. Use a custom comparator to
529 // put the oldest message first.
530 std::push_heap(channel_heap_.begin(), channel_heap_.end(),
531 ChannelHeapCompare);
532}
533
534std::pair<monotonic_clock::time_point, int> LogReader::PopOldestChannel() {
535 std::pair<monotonic_clock::time_point, int> result = channel_heap_.front();
536 std::pop_heap(channel_heap_.begin(), channel_heap_.end(),
537 &ChannelHeapCompare);
538 channel_heap_.pop_back();
539 return result;
540}
541
542} // namespace logger
543} // namespace aos