blob: 2942ab7438f0c2b1994b341255e6c59b6bfa91b8 [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.");
Austin Schuh15649d62019-12-28 16:36:38 -080021DEFINE_bool(skip_missing_forwarding_entries, false,
22 "If true, drop any forwarding entries with missing data. If "
23 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080024
25namespace aos {
26namespace logger {
27
28namespace chrono = std::chrono;
29
30DetachedBufferWriter::DetachedBufferWriter(absl::string_view filename)
31 : fd_(open(std::string(filename).c_str(),
32 O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, 0774)) {
33 PCHECK(fd_ != -1) << ": Failed to open " << filename;
34}
35
36DetachedBufferWriter::~DetachedBufferWriter() {
37 Flush();
38 PLOG_IF(ERROR, close(fd_) == -1) << " Failed to close logfile";
39}
40
41void DetachedBufferWriter::QueueSizedFlatbuffer(
42 flatbuffers::FlatBufferBuilder *fbb) {
43 QueueSizedFlatbuffer(fbb->Release());
44}
45
46void DetachedBufferWriter::QueueSizedFlatbuffer(
47 flatbuffers::DetachedBuffer &&buffer) {
48 queued_size_ += buffer.size();
49 queue_.emplace_back(std::move(buffer));
50
Austin Schuh4c4e0092019-12-22 16:18:03 -080051 // Flush if we are at the max number of iovs per writev, or have written
52 // enough data. Otherwise writev will fail with an invalid argument.
53 if (queued_size_ > static_cast<size_t>(FLAGS_flush_size) ||
54 queue_.size() == IOV_MAX) {
Austin Schuhe309d2a2019-11-29 13:25:21 -080055 Flush();
56 }
57}
58
59void DetachedBufferWriter::Flush() {
60 if (queue_.size() == 0u) {
61 return;
62 }
63 iovec_.clear();
64 iovec_.reserve(queue_.size());
65 size_t counted_size = 0;
66 for (size_t i = 0; i < queue_.size(); ++i) {
67 struct iovec n;
68 n.iov_base = queue_[i].data();
69 n.iov_len = queue_[i].size();
70 counted_size += n.iov_len;
71 iovec_.emplace_back(std::move(n));
72 }
73 CHECK_EQ(counted_size, queued_size_);
74 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
75
76 PCHECK(written == static_cast<ssize_t>(queued_size_))
77 << ": Wrote " << written << " expected " << queued_size_;
78
79 queued_size_ = 0;
80 queue_.clear();
81 // TODO(austin): Handle partial writes in some way other than crashing...
82}
83
84Logger::Logger(DetachedBufferWriter *writer, EventLoop *event_loop,
85 std::chrono::milliseconds polling_period)
86 : event_loop_(event_loop),
87 writer_(writer),
88 timer_handler_(event_loop_->AddTimer([this]() { DoLogData(); })),
89 polling_period_(polling_period) {
90 for (const Channel *channel : *event_loop_->configuration()->channels()) {
91 FetcherStruct fs;
Austin Schuh15649d62019-12-28 16:36:38 -080092 const bool is_readable =
93 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
94 const bool log_message = configuration::ChannelMessageIsLoggedOnNode(
95 channel, event_loop_->node()) &&
96 is_readable;
97
98 const bool log_delivery_times =
99 (event_loop_->node() == nullptr)
100 ? false
101 : configuration::ConnectionDeliveryTimeIsLoggedOnNode(
102 channel, event_loop_->node(), event_loop_->node());
103
104 if (log_message || log_delivery_times) {
105 fs.fetcher = event_loop->MakeRawFetcher(channel);
106 VLOG(1) << "Logging channel "
107 << configuration::CleanedChannelToString(channel);
108
109 if (log_delivery_times) {
110 if (log_message) {
111 VLOG(1) << " Logging message and delivery times";
112 fs.log_type = LogType::kLogMessageAndDeliveryTime;
113 } else {
114 VLOG(1) << " Logging delivery times only";
115 fs.log_type = LogType::kLogDeliveryTimeOnly;
116 }
117 } else {
118 // We don't have a particularly great use case right now for logging a
119 // forwarded message, but either not logging the delivery times, or
120 // logging them on another node. Fail rather than produce bad results.
121 CHECK(configuration::ChannelIsSendableOnNode(channel,
122 event_loop_->node()))
123 << ": Logger only knows how to log remote messages with "
124 "forwarding timestamps.";
125 VLOG(1) << " Logging message only";
126 fs.log_type = LogType::kLogMessage;
127 }
128 }
129
Austin Schuhe309d2a2019-11-29 13:25:21 -0800130 fs.written = false;
131 fetchers_.emplace_back(std::move(fs));
132 }
133
134 // When things start, we want to log the header, then the most recent messages
135 // available on each fetcher to capture the previous state, then start
136 // polling.
137 event_loop_->OnRun([this, polling_period]() {
138 // Grab data from each channel right before we declare the log file started
139 // so we can capture the latest message on each channel. This lets us have
140 // non periodic messages with configuration that now get logged.
141 for (FetcherStruct &f : fetchers_) {
Austin Schuh15649d62019-12-28 16:36:38 -0800142 if (f.fetcher.get() != nullptr) {
143 f.written = !f.fetcher->Fetch();
144 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800145 }
146
147 // We need to pick a point in time to declare the log file "started". This
148 // starts here. It needs to be after everything is fetched so that the
149 // fetchers are all pointed at the most recent message before the start
150 // time.
151 const monotonic_clock::time_point monotonic_now =
152 event_loop_->monotonic_now();
153 const realtime_clock::time_point realtime_now = event_loop_->realtime_now();
154 last_synchronized_time_ = monotonic_now;
155
156 {
157 // Now write the header with this timestamp in it.
158 flatbuffers::FlatBufferBuilder fbb;
159 fbb.ForceDefaults(1);
160
161 flatbuffers::Offset<aos::Configuration> configuration_offset =
162 CopyFlatBuffer(event_loop_->configuration(), &fbb);
163
Austin Schuh288479d2019-12-18 19:47:52 -0800164 flatbuffers::Offset<flatbuffers::String> string_offset =
165 fbb.CreateString(network::GetHostname());
166
Austin Schuhfd960622020-01-01 13:22:55 -0800167 flatbuffers::Offset<Node> node_offset;
168 if (event_loop_->node() != nullptr) {
169 node_offset = CopyFlatBuffer(event_loop_->node(), &fbb);
170 }
Austin Schuh15649d62019-12-28 16:36:38 -0800171 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node());
172
Austin Schuhe309d2a2019-11-29 13:25:21 -0800173 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
174
Austin Schuh288479d2019-12-18 19:47:52 -0800175 log_file_header_builder.add_name(string_offset);
176
Austin Schuhfd960622020-01-01 13:22:55 -0800177 // Only add the node if we are running in a multinode configuration.
178 if (event_loop_->node() != nullptr) {
179 log_file_header_builder.add_node(node_offset);
180 }
Austin Schuh15649d62019-12-28 16:36:38 -0800181
Austin Schuhe309d2a2019-11-29 13:25:21 -0800182 log_file_header_builder.add_configuration(configuration_offset);
183 // The worst case theoretical out of order is the polling period times 2.
184 // One message could get logged right after the boundary, but be for right
185 // before the next boundary. And the reverse could happen for another
186 // message. Report back 3x to be extra safe, and because the cost isn't
187 // huge on the read side.
188 log_file_header_builder.add_max_out_of_order_duration(
189 std::chrono::duration_cast<std::chrono::nanoseconds>(3 *
190 polling_period)
191 .count());
192
Austin Schuh629c9172019-12-23 20:34:43 -0800193 log_file_header_builder.add_monotonic_start_time(
Austin Schuhe309d2a2019-11-29 13:25:21 -0800194 std::chrono::duration_cast<std::chrono::nanoseconds>(
195 monotonic_now.time_since_epoch())
196 .count());
Austin Schuh629c9172019-12-23 20:34:43 -0800197 log_file_header_builder.add_realtime_start_time(
Austin Schuhe309d2a2019-11-29 13:25:21 -0800198 std::chrono::duration_cast<std::chrono::nanoseconds>(
199 realtime_now.time_since_epoch())
200 .count());
201
202 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
203 writer_->QueueSizedFlatbuffer(&fbb);
204 }
205
206 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period,
207 polling_period);
208 });
209}
210
Austin Schuh646b7b82019-12-22 21:38:55 -0800211flatbuffers::Offset<MessageHeader> PackMessage(
212 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
Austin Schuh15649d62019-12-28 16:36:38 -0800213 int channel_index, LogType log_type) {
214 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
215
216 switch(log_type) {
217 case LogType::kLogMessage:
218 case LogType::kLogMessageAndDeliveryTime:
219 data_offset =
220 fbb->CreateVector(static_cast<uint8_t *>(context.data), context.size);
221 break;
222
223 case LogType::kLogDeliveryTimeOnly:
224 break;
225 }
Austin Schuh646b7b82019-12-22 21:38:55 -0800226
227 MessageHeader::Builder message_header_builder(*fbb);
228 message_header_builder.add_channel_index(channel_index);
Austin Schuh15649d62019-12-28 16:36:38 -0800229 message_header_builder.add_queue_index(context.queue_index);
Austin Schuh646b7b82019-12-22 21:38:55 -0800230 message_header_builder.add_monotonic_sent_time(
Austin Schuhad154822019-12-27 15:45:13 -0800231 context.monotonic_event_time.time_since_epoch().count());
Austin Schuh646b7b82019-12-22 21:38:55 -0800232 message_header_builder.add_realtime_sent_time(
Austin Schuhad154822019-12-27 15:45:13 -0800233 context.realtime_event_time.time_since_epoch().count());
Austin Schuh646b7b82019-12-22 21:38:55 -0800234
Austin Schuh15649d62019-12-28 16:36:38 -0800235 switch (log_type) {
236 case LogType::kLogMessage:
237 message_header_builder.add_data(data_offset);
238 break;
Austin Schuh646b7b82019-12-22 21:38:55 -0800239
Austin Schuh15649d62019-12-28 16:36:38 -0800240 case LogType::kLogMessageAndDeliveryTime:
241 message_header_builder.add_data(data_offset);
242 [[fallthrough]];
243
244 case LogType::kLogDeliveryTimeOnly:
245 message_header_builder.add_monotonic_remote_time(
246 context.monotonic_remote_time.time_since_epoch().count());
247 message_header_builder.add_realtime_remote_time(
248 context.realtime_remote_time.time_since_epoch().count());
249 message_header_builder.add_remote_queue_index(context.remote_queue_index);
250 break;
251 }
252
Austin Schuh646b7b82019-12-22 21:38:55 -0800253 return message_header_builder.Finish();
254}
255
Austin Schuhe309d2a2019-11-29 13:25:21 -0800256void Logger::DoLogData() {
257 // We want to guarentee that messages aren't out of order by more than
258 // max_out_of_order_duration. To do this, we need sync points. Every write
259 // cycle should be a sync point.
260 const monotonic_clock::time_point monotonic_now = monotonic_clock::now();
261
262 do {
263 // Move the sync point up by at most polling_period. This forces one sync
264 // per iteration, even if it is small.
265 last_synchronized_time_ =
266 std::min(last_synchronized_time_ + polling_period_, monotonic_now);
267 size_t channel_index = 0;
268 // Write each channel to disk, one at a time.
269 for (FetcherStruct &f : fetchers_) {
Austin Schuh15649d62019-12-28 16:36:38 -0800270 // Skip any channels which we aren't supposed to log.
271 if (f.fetcher.get() != nullptr) {
272 while (true) {
273 if (f.written) {
274 if (!f.fetcher->FetchNext()) {
275 VLOG(2) << "No new data on "
276 << configuration::CleanedChannelToString(
277 f.fetcher->channel());
278 break;
279 } else {
280 f.written = false;
281 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800282 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800283
Austin Schuh15649d62019-12-28 16:36:38 -0800284 CHECK(!f.written);
285
286 // TODO(james): Write tests to exercise this logic.
287 if (f.fetcher->context().monotonic_event_time <
288 last_synchronized_time_) {
289 // Write!
290 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
291 max_header_size_);
292 fbb.ForceDefaults(1);
293
294 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
295 channel_index, f.log_type));
296
297 VLOG(2) << "Writing data for channel "
298 << configuration::CleanedChannelToString(
299 f.fetcher->channel());
300
301 max_header_size_ = std::max(
302 max_header_size_, fbb.GetSize() - f.fetcher->context().size);
303 writer_->QueueSizedFlatbuffer(&fbb);
304
305 f.written = true;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800306 } else {
Austin Schuh15649d62019-12-28 16:36:38 -0800307 break;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800308 }
309 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800310 }
311
312 ++channel_index;
313 }
314
315 CHECK_EQ(channel_index, fetchers_.size());
316
317 // If we missed cycles, we could be pretty far behind. Spin until we are
318 // caught up.
319 } while (last_synchronized_time_ + polling_period_ < monotonic_now);
320
321 writer_->Flush();
322}
323
324LogReader::LogReader(absl::string_view filename)
325 : fd_(open(std::string(filename).c_str(), O_RDONLY | O_CLOEXEC)) {
326 PCHECK(fd_ != -1) << ": Failed to open " << filename;
327
328 // Make sure we have enough to read the size.
329 absl::Span<const uint8_t> config_data = ReadMessage();
330
331 // Make sure something was read.
332 CHECK(config_data != absl::Span<const uint8_t>());
333
334 // And copy the config so we have it forever.
335 configuration_ = std::vector<uint8_t>(config_data.begin(), config_data.end());
336
337 max_out_of_order_duration_ = std::chrono::nanoseconds(
338 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
339 ->max_out_of_order_duration());
340
341 channels_.resize(configuration()->channels()->size());
342
343 QueueMessages();
344}
345
346bool LogReader::ReadBlock() {
347 if (end_of_file_) {
348 return false;
349 }
350
351 // Appends 256k. This is enough that the read call is efficient. We don't
352 // want to spend too much time reading small chunks because the syscalls for
353 // that will be expensive.
354 constexpr size_t kReadSize = 256 * 1024;
355
356 // Strip off any unused data at the front.
357 if (consumed_data_ != 0) {
358 data_.erase(data_.begin(), data_.begin() + consumed_data_);
359 consumed_data_ = 0;
360 }
361
362 const size_t starting_size = data_.size();
363
364 // This should automatically grow the backing store. It won't shrink if we
365 // get a small chunk later. This reduces allocations when we want to append
366 // more data.
367 data_.resize(data_.size() + kReadSize);
368
369 ssize_t count = read(fd_, &data_[starting_size], kReadSize);
370 data_.resize(starting_size + std::max(count, static_cast<ssize_t>(0)));
371 if (count == 0) {
372 end_of_file_ = true;
373 return false;
374 }
375 PCHECK(count > 0);
376
377 return true;
378}
379
380bool LogReader::MessageAvailable() {
381 // Are we big enough to read the size?
382 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
383 return false;
384 }
385
386 // Then, are we big enough to read the full message?
387 const size_t data_size =
388 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
389 sizeof(flatbuffers::uoffset_t);
390 if (data_.size() < consumed_data_ + data_size) {
391 return false;
392 }
393
394 return true;
395}
396
397absl::Span<const uint8_t> LogReader::ReadMessage() {
398 // Make sure we have enough for the size.
399 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
400 if (!ReadBlock()) {
401 return absl::Span<const uint8_t>();
402 }
403 }
404
405 // Now make sure we have enough for the message.
406 const size_t data_size =
407 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
408 sizeof(flatbuffers::uoffset_t);
409 while (data_.size() < consumed_data_ + data_size) {
410 if (!ReadBlock()) {
411 return absl::Span<const uint8_t>();
412 }
413 }
414
415 // And return it, consuming the data.
416 const uint8_t *data_ptr = data_.data() + consumed_data_;
417
418 consumed_data_ += data_size;
419
420 return absl::Span<const uint8_t>(data_ptr, data_size);
421}
422
423void LogReader::QueueMessages() {
424 while (true) {
425 // Don't queue if we have enough data already.
426 // When a log file starts, there should be a message from each channel.
427 // Those messages might be very old. Make sure to read a chunk past the
428 // starting time.
429 if (channel_heap_.size() > 0 &&
430 newest_timestamp_ >
431 std::max(oldest_message().first, monotonic_start_time()) +
432 max_out_of_order_duration_) {
433 break;
434 }
435
436 absl::Span<const uint8_t> msg_data = ReadMessage();
437 if (msg_data == absl::Span<const uint8_t>()) {
438 break;
439 }
440
441 FlatbufferVector<MessageHeader> msg(std::vector<uint8_t>(
442 msg_data.begin() + sizeof(flatbuffers::uoffset_t), msg_data.end()));
443
444 EmplaceDataBack(std::move(msg));
445 }
446
447 queue_data_time_ = newest_timestamp_ - max_out_of_order_duration_;
448}
449
Austin Schuh15649d62019-12-28 16:36:38 -0800450const Configuration *LogReader::configuration() const {
Austin Schuhe309d2a2019-11-29 13:25:21 -0800451 return flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
452 ->configuration();
453}
454
Austin Schuh15649d62019-12-28 16:36:38 -0800455const Node *LogReader::node() const {
Austin Schuhfd960622020-01-01 13:22:55 -0800456 if (configuration()->has_nodes()) {
457 CHECK(flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
458 ->has_node());
459 CHECK(flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
460 ->node()
461 ->has_name());
462 return configuration::GetNode(
463 configuration(),
464 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
465 ->node()
466 ->name()
467 ->string_view());
468 } else {
469 CHECK(
470 !flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
471 ->has_node());
472 return nullptr;
473 }
Austin Schuh15649d62019-12-28 16:36:38 -0800474}
475
Austin Schuhe309d2a2019-11-29 13:25:21 -0800476monotonic_clock::time_point LogReader::monotonic_start_time() {
477 return monotonic_clock::time_point(std::chrono::nanoseconds(
478 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
Austin Schuh629c9172019-12-23 20:34:43 -0800479 ->monotonic_start_time()));
Austin Schuhe309d2a2019-11-29 13:25:21 -0800480}
481
482realtime_clock::time_point LogReader::realtime_start_time() {
483 return realtime_clock::time_point(std::chrono::nanoseconds(
484 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
Austin Schuh629c9172019-12-23 20:34:43 -0800485 ->realtime_start_time()));
Austin Schuhe309d2a2019-11-29 13:25:21 -0800486}
487
Austin Schuh92547522019-12-28 14:33:43 -0800488void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
489 event_loop_unique_ptr_ = event_loop_factory->MakeEventLoop("log_reader");
490 event_loop_factory_ = event_loop_factory;
491 // We don't run timing reports when trying to print out logged data, because
492 // otherwise we would end up printing out the timing reports themselves...
493 // This is only really relevant when we are replaying into a simulation.
494 event_loop_unique_ptr_->SkipTimingReport();
495
496 Register(event_loop_unique_ptr_.get());
497 event_loop_factory_->RunFor(monotonic_start_time() -
498 event_loop_factory_->monotonic_now());
499}
500
Austin Schuhe309d2a2019-11-29 13:25:21 -0800501void LogReader::Register(EventLoop *event_loop) {
502 event_loop_ = event_loop;
503
Austin Schuh39788ff2019-12-01 18:22:57 -0800504 // Otherwise we replay the timing report and try to resend it...
505 event_loop_->SkipTimingReport();
506
Austin Schuhe309d2a2019-11-29 13:25:21 -0800507 for (size_t i = 0; i < channels_.size(); ++i) {
508 CHECK_EQ(configuration()->channels()->Get(i)->name(),
509 event_loop_->configuration()->channels()->Get(i)->name());
510 CHECK_EQ(configuration()->channels()->Get(i)->type(),
511 event_loop_->configuration()->channels()->Get(i)->type());
512
513 channels_[i].raw_sender = event_loop_->MakeRawSender(
514 event_loop_->configuration()->channels()->Get(i));
515 }
516
517 timer_handler_ = event_loop_->AddTimer([this]() {
518 std::pair<monotonic_clock::time_point, int> oldest_channel_index =
519 PopOldestChannel();
520 const monotonic_clock::time_point monotonic_now =
Austin Schuhad154822019-12-27 15:45:13 -0800521 event_loop_->context().monotonic_event_time;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800522 CHECK(monotonic_now == oldest_channel_index.first)
523 << ": Now " << monotonic_now.time_since_epoch().count()
524 << " trying to send "
525 << oldest_channel_index.first.time_since_epoch().count();
526
527 struct LogReader::ChannelData &channel =
528 channels_[oldest_channel_index.second];
529
530 FlatbufferVector<MessageHeader> front = std::move(channel.front());
531
Austin Schuh15649d62019-12-28 16:36:38 -0800532 if (oldest_channel_index.first > monotonic_start_time() ||
533 event_loop_factory_ != nullptr) {
534 if (!FLAGS_skip_missing_forwarding_entries ||
535 front.message().data() != nullptr) {
536 CHECK(front.message().data() != nullptr)
537 << ": Got a message without data. Forwarding entry which was not "
538 "matched? Use --skip_missing_forwarding_entries to ignore "
539 "this.";
Austin Schuh92547522019-12-28 14:33:43 -0800540
Austin Schuh15649d62019-12-28 16:36:38 -0800541 // If we have access to the factory, use it to fix the realtime time.
542 if (event_loop_factory_ != nullptr) {
543 event_loop_factory_->SetRealtimeOffset(
544 monotonic_clock::time_point(
545 chrono::nanoseconds(front.message().monotonic_sent_time())),
546 realtime_clock::time_point(
547 chrono::nanoseconds(front.message().realtime_sent_time())));
548 }
549
550 channel.raw_sender->Send(
551 front.message().data()->Data(), front.message().data()->size(),
Austin Schuh92547522019-12-28 14:33:43 -0800552 monotonic_clock::time_point(
Austin Schuh15649d62019-12-28 16:36:38 -0800553 chrono::nanoseconds(front.message().monotonic_remote_time())),
Austin Schuh92547522019-12-28 14:33:43 -0800554 realtime_clock::time_point(
Austin Schuh15649d62019-12-28 16:36:38 -0800555 chrono::nanoseconds(front.message().realtime_remote_time())),
556 front.message().remote_queue_index());
Austin Schuh92547522019-12-28 14:33:43 -0800557 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800558 } else {
559 LOG(WARNING) << "Not sending data from before the start of the log file. "
560 << oldest_channel_index.first.time_since_epoch().count()
561 << " start "
562 << monotonic_start_time().time_since_epoch().count() << " "
563 << FlatbufferToJson(front);
564 }
565 channel.data.pop_front();
566
567 // Re-push it and update the oldest timestamp.
568 if (channel.data.size() != 0) {
569 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
570 chrono::nanoseconds(channel.front().message().monotonic_sent_time()));
571 PushChannelHeap(timestamp, oldest_channel_index.second);
572 channel.oldest_timestamp = timestamp;
573 } else {
574 channel.oldest_timestamp = monotonic_clock::min_time;
575 }
576
577 if (monotonic_now > queue_data_time_) {
578 QueueMessages();
579 }
580
581 if (channel_heap_.size() != 0) {
582 timer_handler_->Setup(oldest_message().first);
583 }
584 });
585
586 if (channel_heap_.size() > 0u) {
587 event_loop_->OnRun(
588 [this]() { timer_handler_->Setup(oldest_message().first); });
589 }
590}
591
592void LogReader::Deregister() {
593 for (size_t i = 0; i < channels_.size(); ++i) {
594 channels_[i].raw_sender.reset();
595 }
Austin Schuh92547522019-12-28 14:33:43 -0800596
597 event_loop_factory_ = nullptr;
598 event_loop_unique_ptr_.reset();
599 event_loop_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800600}
601
602void LogReader::EmplaceDataBack(FlatbufferVector<MessageHeader> &&new_data) {
603 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
604 chrono::nanoseconds(new_data.message().monotonic_sent_time()));
605 const size_t channel_index = new_data.message().channel_index();
606 CHECK_LT(channel_index, channels_.size());
607 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
608 if (channels_[channel_index].data.size() == 0) {
609 channels_[channel_index].oldest_timestamp = timestamp;
610 PushChannelHeap(timestamp, channel_index);
611 }
612 channels_[channel_index].data.emplace_back(std::move(new_data));
613}
614
615namespace {
616
617bool ChannelHeapCompare(
618 const std::pair<monotonic_clock::time_point, int> first,
619 const std::pair<monotonic_clock::time_point, int> second) {
620 if (first.first > second.first) {
621 return true;
622 } else if (first.first == second.first) {
623 return first.second > second.second;
624 } else {
625 return false;
626 }
627}
628
629} // namespace
630
631void LogReader::PushChannelHeap(monotonic_clock::time_point timestamp,
632 int channel_index) {
633 channel_heap_.push_back(std::make_pair(timestamp, channel_index));
634
635 // The default sort puts the newest message first. Use a custom comparator to
636 // put the oldest message first.
637 std::push_heap(channel_heap_.begin(), channel_heap_.end(),
638 ChannelHeapCompare);
639}
640
641std::pair<monotonic_clock::time_point, int> LogReader::PopOldestChannel() {
642 std::pair<monotonic_clock::time_point, int> result = channel_heap_.front();
643 std::pop_heap(channel_heap_.begin(), channel_heap_.end(),
644 &ChannelHeapCompare);
645 channel_heap_.pop_back();
646 return result;
647}
648
649} // namespace logger
650} // namespace aos