blob: a7238ba5cd776dcb2ced0efbe132768c26d42233 [file] [log] [blame]
Austin Schuha36c8902019-12-30 18:07:15 -08001#include "aos/events/logging/logfile_utils.h"
2
3#include <fcntl.h>
4#include <limits.h>
5#include <sys/stat.h>
6#include <sys/types.h>
7#include <sys/uio.h>
8
9#include <vector>
10
Austin Schuhe4fca832020-03-07 16:58:53 -080011#include "absl/strings/escaping.h"
Austin Schuh05b70472020-01-01 17:11:17 -080012#include "aos/configuration.h"
Austin Schuha36c8902019-12-30 18:07:15 -080013#include "aos/events/logging/logger_generated.h"
Austin Schuhfa895892020-01-07 20:07:41 -080014#include "aos/flatbuffer_merge.h"
Austin Schuh6f3babe2020-01-26 20:34:50 -080015#include "aos/util/file.h"
Austin Schuha36c8902019-12-30 18:07:15 -080016#include "flatbuffers/flatbuffers.h"
Austin Schuh05b70472020-01-01 17:11:17 -080017#include "gflags/gflags.h"
18#include "glog/logging.h"
Austin Schuha36c8902019-12-30 18:07:15 -080019
20DEFINE_int32(flush_size, 1000000,
21 "Number of outstanding bytes to allow before flushing to disk.");
22
23namespace aos {
24namespace logger {
25
Austin Schuh05b70472020-01-01 17:11:17 -080026namespace chrono = std::chrono;
27
Austin Schuha36c8902019-12-30 18:07:15 -080028DetachedBufferWriter::DetachedBufferWriter(std::string_view filename)
Austin Schuh6f3babe2020-01-26 20:34:50 -080029 : filename_(filename) {
30 util::MkdirP(filename, 0777);
31 fd_ = open(std::string(filename).c_str(),
32 O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, 0774);
33 VLOG(1) << "Opened " << filename << " for writing";
34 PCHECK(fd_ != -1) << ": Failed to open " << filename << " for writing";
Austin Schuha36c8902019-12-30 18:07:15 -080035}
36
37DetachedBufferWriter::~DetachedBufferWriter() {
38 Flush();
39 PLOG_IF(ERROR, close(fd_) == -1) << " Failed to close logfile";
40}
41
42void DetachedBufferWriter::QueueSizedFlatbuffer(
43 flatbuffers::FlatBufferBuilder *fbb) {
44 QueueSizedFlatbuffer(fbb->Release());
45}
46
Austin Schuhde031b72020-01-10 19:34:41 -080047void DetachedBufferWriter::WriteSizedFlatbuffer(
48 absl::Span<const uint8_t> span) {
49 // Cheat aggressively... Write out the queued up data, and then write this
50 // data once without buffering. It is hard to make a DetachedBuffer out of
51 // this data, and we don't want to worry about lifetimes.
52 Flush();
53 iovec_.clear();
54 iovec_.reserve(1);
55
56 struct iovec n;
57 n.iov_base = const_cast<uint8_t *>(span.data());
58 n.iov_len = span.size();
59 iovec_.emplace_back(n);
60
61 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
62
63 PCHECK(written == static_cast<ssize_t>(n.iov_len))
64 << ": Wrote " << written << " expected " << n.iov_len;
65}
66
Austin Schuha36c8902019-12-30 18:07:15 -080067void DetachedBufferWriter::QueueSizedFlatbuffer(
68 flatbuffers::DetachedBuffer &&buffer) {
69 queued_size_ += buffer.size();
70 queue_.emplace_back(std::move(buffer));
71
72 // Flush if we are at the max number of iovs per writev, or have written
73 // enough data. Otherwise writev will fail with an invalid argument.
74 if (queued_size_ > static_cast<size_t>(FLAGS_flush_size) ||
75 queue_.size() == IOV_MAX) {
76 Flush();
77 }
78}
79
80void DetachedBufferWriter::Flush() {
81 if (queue_.size() == 0u) {
82 return;
83 }
84 iovec_.clear();
85 iovec_.reserve(queue_.size());
86 size_t counted_size = 0;
87 for (size_t i = 0; i < queue_.size(); ++i) {
88 struct iovec n;
89 n.iov_base = queue_[i].data();
90 n.iov_len = queue_[i].size();
91 counted_size += n.iov_len;
92 iovec_.emplace_back(std::move(n));
93 }
94 CHECK_EQ(counted_size, queued_size_);
95 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
96
97 PCHECK(written == static_cast<ssize_t>(queued_size_))
98 << ": Wrote " << written << " expected " << queued_size_;
99
100 queued_size_ = 0;
101 queue_.clear();
102 // TODO(austin): Handle partial writes in some way other than crashing...
103}
104
105flatbuffers::Offset<MessageHeader> PackMessage(
106 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
107 int channel_index, LogType log_type) {
108 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
109
110 switch (log_type) {
111 case LogType::kLogMessage:
112 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800113 case LogType::kLogRemoteMessage:
Austin Schuha36c8902019-12-30 18:07:15 -0800114 data_offset =
115 fbb->CreateVector(static_cast<uint8_t *>(context.data), context.size);
116 break;
117
118 case LogType::kLogDeliveryTimeOnly:
119 break;
120 }
121
122 MessageHeader::Builder message_header_builder(*fbb);
123 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800124
125 switch (log_type) {
126 case LogType::kLogRemoteMessage:
127 message_header_builder.add_queue_index(context.remote_queue_index);
128 message_header_builder.add_monotonic_sent_time(
129 context.monotonic_remote_time.time_since_epoch().count());
130 message_header_builder.add_realtime_sent_time(
131 context.realtime_remote_time.time_since_epoch().count());
132 break;
133
134 case LogType::kLogMessage:
135 case LogType::kLogMessageAndDeliveryTime:
136 case LogType::kLogDeliveryTimeOnly:
137 message_header_builder.add_queue_index(context.queue_index);
138 message_header_builder.add_monotonic_sent_time(
139 context.monotonic_event_time.time_since_epoch().count());
140 message_header_builder.add_realtime_sent_time(
141 context.realtime_event_time.time_since_epoch().count());
142 break;
143 }
Austin Schuha36c8902019-12-30 18:07:15 -0800144
145 switch (log_type) {
146 case LogType::kLogMessage:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800147 case LogType::kLogRemoteMessage:
Austin Schuha36c8902019-12-30 18:07:15 -0800148 message_header_builder.add_data(data_offset);
149 break;
150
151 case LogType::kLogMessageAndDeliveryTime:
152 message_header_builder.add_data(data_offset);
153 [[fallthrough]];
154
155 case LogType::kLogDeliveryTimeOnly:
156 message_header_builder.add_monotonic_remote_time(
157 context.monotonic_remote_time.time_since_epoch().count());
158 message_header_builder.add_realtime_remote_time(
159 context.realtime_remote_time.time_since_epoch().count());
160 message_header_builder.add_remote_queue_index(context.remote_queue_index);
161 break;
162 }
163
164 return message_header_builder.Finish();
165}
166
Austin Schuh05b70472020-01-01 17:11:17 -0800167SpanReader::SpanReader(std::string_view filename)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800168 : filename_(filename),
169 fd_(open(std::string(filename).c_str(), O_RDONLY | O_CLOEXEC)) {
Austin Schuh05b70472020-01-01 17:11:17 -0800170 PCHECK(fd_ != -1) << ": Failed to open " << filename;
171}
172
173absl::Span<const uint8_t> SpanReader::ReadMessage() {
174 // Make sure we have enough for the size.
175 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
176 if (!ReadBlock()) {
177 return absl::Span<const uint8_t>();
178 }
179 }
180
181 // Now make sure we have enough for the message.
182 const size_t data_size =
183 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
184 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -0800185 if (data_size == sizeof(flatbuffers::uoffset_t)) {
186 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
187 LOG(ERROR) << " Rest of log file is "
188 << absl::BytesToHexString(std::string_view(
189 reinterpret_cast<const char *>(data_.data() +
190 consumed_data_),
191 data_.size() - consumed_data_));
192 return absl::Span<const uint8_t>();
193 }
Austin Schuh05b70472020-01-01 17:11:17 -0800194 while (data_.size() < consumed_data_ + data_size) {
195 if (!ReadBlock()) {
196 return absl::Span<const uint8_t>();
197 }
198 }
199
200 // And return it, consuming the data.
201 const uint8_t *data_ptr = data_.data() + consumed_data_;
202
203 consumed_data_ += data_size;
204
205 return absl::Span<const uint8_t>(data_ptr, data_size);
206}
207
208bool SpanReader::MessageAvailable() {
209 // Are we big enough to read the size?
210 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
211 return false;
212 }
213
214 // Then, are we big enough to read the full message?
215 const size_t data_size =
216 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
217 sizeof(flatbuffers::uoffset_t);
218 if (data_.size() < consumed_data_ + data_size) {
219 return false;
220 }
221
222 return true;
223}
224
225bool SpanReader::ReadBlock() {
226 if (end_of_file_) {
227 return false;
228 }
229
230 // Appends 256k. This is enough that the read call is efficient. We don't
231 // want to spend too much time reading small chunks because the syscalls for
232 // that will be expensive.
233 constexpr size_t kReadSize = 256 * 1024;
234
235 // Strip off any unused data at the front.
236 if (consumed_data_ != 0) {
237 data_.erase(data_.begin(), data_.begin() + consumed_data_);
238 consumed_data_ = 0;
239 }
240
241 const size_t starting_size = data_.size();
242
243 // This should automatically grow the backing store. It won't shrink if we
244 // get a small chunk later. This reduces allocations when we want to append
245 // more data.
246 data_.resize(data_.size() + kReadSize);
247
248 ssize_t count = read(fd_, &data_[starting_size], kReadSize);
249 data_.resize(starting_size + std::max(count, static_cast<ssize_t>(0)));
250 if (count == 0) {
251 end_of_file_ = true;
252 return false;
253 }
254 PCHECK(count > 0);
255
256 return true;
257}
258
Austin Schuh6f3babe2020-01-26 20:34:50 -0800259FlatbufferVector<LogFileHeader> ReadHeader(std::string_view filename) {
260 SpanReader span_reader(filename);
261 // Make sure we have enough to read the size.
262 absl::Span<const uint8_t> config_data = span_reader.ReadMessage();
263
264 // Make sure something was read.
265 CHECK(config_data != absl::Span<const uint8_t>());
266
267 // And copy the config so we have it forever.
268 std::vector<uint8_t> data(
269 config_data.begin() + sizeof(flatbuffers::uoffset_t), config_data.end());
270 return FlatbufferVector<LogFileHeader>(std::move(data));
271}
272
Austin Schuh05b70472020-01-01 17:11:17 -0800273MessageReader::MessageReader(std::string_view filename)
274 : span_reader_(filename) {
275 // Make sure we have enough to read the size.
276 absl::Span<const uint8_t> config_data = span_reader_.ReadMessage();
277
278 // Make sure something was read.
279 CHECK(config_data != absl::Span<const uint8_t>());
280
281 // And copy the config so we have it forever.
282 configuration_ = std::vector<uint8_t>(config_data.begin(), config_data.end());
283
Austin Schuhcde938c2020-02-02 17:30:07 -0800284 max_out_of_order_duration_ =
285 std::chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
286
287 VLOG(1) << "Opened " << filename << " as node "
288 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800289}
290
291std::optional<FlatbufferVector<MessageHeader>> MessageReader::ReadMessage() {
292 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
293 if (msg_data == absl::Span<const uint8_t>()) {
294 return std::nullopt;
295 }
296
297 FlatbufferVector<MessageHeader> result{std::vector<uint8_t>(
298 msg_data.begin() + sizeof(flatbuffers::uoffset_t), msg_data.end())};
299
300 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
301 chrono::nanoseconds(result.message().monotonic_sent_time()));
302
303 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuh8bd96322020-02-13 21:18:22 -0800304 VLOG(2) << "Read from " << filename() << " data " << FlatbufferToJson(result);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800305 return std::move(result);
Austin Schuh05b70472020-01-01 17:11:17 -0800306}
307
Austin Schuh6f3babe2020-01-26 20:34:50 -0800308SplitMessageReader::SplitMessageReader(
Austin Schuhfa895892020-01-07 20:07:41 -0800309 const std::vector<std::string> &filenames)
310 : filenames_(filenames),
311 log_file_header_(FlatbufferDetachedBuffer<LogFileHeader>::Empty()) {
312 CHECK(NextLogFile()) << ": filenames is empty. Need files to read.";
313
Austin Schuh6f3babe2020-01-26 20:34:50 -0800314 // Grab any log file header. They should all match (and we will check as we
315 // open more of them).
Austin Schuhfa895892020-01-07 20:07:41 -0800316 log_file_header_ = CopyFlatBuffer(message_reader_->log_file_header());
317
Austin Schuh6f3babe2020-01-26 20:34:50 -0800318 // Setup per channel state.
Austin Schuh05b70472020-01-01 17:11:17 -0800319 channels_.resize(configuration()->channels()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800320 for (ChannelData &channel_data : channels_) {
321 channel_data.data.split_reader = this;
322 // Build up the timestamp list.
323 if (configuration::MultiNode(configuration())) {
324 channel_data.timestamps.resize(configuration()->nodes()->size());
325 for (MessageHeaderQueue &queue : channel_data.timestamps) {
326 queue.timestamps = true;
327 queue.split_reader = this;
328 }
329 }
330 }
Austin Schuh05b70472020-01-01 17:11:17 -0800331
Austin Schuh6f3babe2020-01-26 20:34:50 -0800332 // Build up channels_to_write_ as an optimization to make it fast to figure
333 // out which datastructure to place any new data from a channel on.
334 for (const Channel *channel : *configuration()->channels()) {
335 // This is the main case. We will only see data on this node.
336 if (configuration::ChannelIsSendableOnNode(channel, node())) {
337 channels_to_write_.emplace_back(
338 &channels_[channels_to_write_.size()].data);
339 } else
340 // If we can't send, but can receive, we should be able to see
341 // timestamps here.
342 if (configuration::ChannelIsReadableOnNode(channel, node())) {
343 channels_to_write_.emplace_back(
344 &(channels_[channels_to_write_.size()]
345 .timestamps[configuration::GetNodeIndex(configuration(),
346 node())]));
347 } else {
348 channels_to_write_.emplace_back(nullptr);
349 }
350 }
Austin Schuh05b70472020-01-01 17:11:17 -0800351}
352
Austin Schuh6f3babe2020-01-26 20:34:50 -0800353bool SplitMessageReader::NextLogFile() {
Austin Schuhfa895892020-01-07 20:07:41 -0800354 if (next_filename_index_ == filenames_.size()) {
355 return false;
356 }
357 message_reader_ =
358 std::make_unique<MessageReader>(filenames_[next_filename_index_]);
359
360 // We can't support the config diverging between two log file headers. See if
361 // they are the same.
362 if (next_filename_index_ != 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800363 CHECK(CompareFlatBuffer(&log_file_header_.message(),
364 message_reader_->log_file_header()))
Austin Schuhfa895892020-01-07 20:07:41 -0800365 << ": Header is different between log file chunks "
366 << filenames_[next_filename_index_] << " and "
367 << filenames_[next_filename_index_ - 1] << ", this is not supported.";
368 }
369
370 ++next_filename_index_;
371 return true;
372}
373
Austin Schuh6f3babe2020-01-26 20:34:50 -0800374bool SplitMessageReader::QueueMessages(
Austin Schuhcde938c2020-02-02 17:30:07 -0800375 monotonic_clock::time_point last_dequeued_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800376 // TODO(austin): Once we are happy that everything works, read a 256kb chunk
377 // to reduce the need to re-heap down below.
Austin Schuhcde938c2020-02-02 17:30:07 -0800378
379 // Special case no more data. Otherwise we blow up on the CHECK statement
380 // confirming that we have enough data queued.
381 if (at_end_) {
382 return false;
383 }
384
385 // If this isn't the first time around, confirm that we had enough data queued
386 // to follow the contract.
387 if (time_to_queue_ != monotonic_clock::min_time) {
388 CHECK_LE(last_dequeued_time,
389 newest_timestamp() - max_out_of_order_duration())
390 << " node " << FlatbufferToJson(node()) << " on " << this;
391
392 // Bail if there is enough data already queued.
393 if (last_dequeued_time < time_to_queue_) {
394 VLOG(1) << "All up to date on " << this << ", dequeued "
395 << last_dequeued_time << " queue time " << time_to_queue_;
396 return true;
397 }
398 } else {
399 // Startup takes a special dance. We want to queue up until the start time,
400 // but we then want to find the next message to read. The conservative
401 // answer is to immediately trigger a second requeue to get things moving.
402 time_to_queue_ = monotonic_start_time();
403 QueueMessages(time_to_queue_);
404 }
405
406 // If we are asked to queue, queue for at least max_out_of_order_duration past
407 // the last known time in the log file (ie the newest timestep read). As long
408 // as we requeue exactly when time_to_queue_ is dequeued and go no further, we
409 // are safe. And since we pop in order, that works.
410 //
411 // Special case the start of the log file. There should be at most 1 message
412 // from each channel at the start of the log file. So always force the start
413 // of the log file to just be read.
414 time_to_queue_ = std::max(time_to_queue_, newest_timestamp());
415 VLOG(1) << "Queueing, going until " << time_to_queue_ << " " << filename();
416
417 bool was_emplaced = false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800418 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800419 // Stop if we have enough.
420 if (newest_timestamp() >
421 time_to_queue_ + max_out_of_order_duration() &&
422 was_emplaced) {
423 VLOG(1) << "Done queueing on " << this << ", queued to "
424 << newest_timestamp() << " with requeue time " << time_to_queue_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800425 return true;
426 }
Austin Schuh05b70472020-01-01 17:11:17 -0800427
Austin Schuh6f3babe2020-01-26 20:34:50 -0800428 if (std::optional<FlatbufferVector<MessageHeader>> msg =
429 message_reader_->ReadMessage()) {
430 const MessageHeader &header = msg.value().message();
431
Austin Schuhcde938c2020-02-02 17:30:07 -0800432 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
433 chrono::nanoseconds(header.monotonic_sent_time()));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800434
Austin Schuhcde938c2020-02-02 17:30:07 -0800435 VLOG(1) << "Queued " << this << " " << filename()
436 << " ttq: " << time_to_queue_ << " now "
437 << newest_timestamp() << " start time "
438 << monotonic_start_time() << " " << FlatbufferToJson(&header);
439
440 const int channel_index = header.channel_index();
441 was_emplaced = channels_to_write_[channel_index]->emplace_back(
442 std::move(msg.value()));
443 if (was_emplaced) {
444 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
445 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800446 } else {
447 if (!NextLogFile()) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800448 VLOG(1) << "End of log file " << filenames_.back();
Austin Schuhcde938c2020-02-02 17:30:07 -0800449 at_end_ = true;
Austin Schuh8bd96322020-02-13 21:18:22 -0800450 for (MessageHeaderQueue *queue : channels_to_write_) {
451 if (queue == nullptr || queue->timestamp_merger == nullptr) {
452 continue;
453 }
454 queue->timestamp_merger->NoticeAtEnd();
455 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800456 return false;
457 }
458 }
Austin Schuh05b70472020-01-01 17:11:17 -0800459 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800460}
461
462void SplitMessageReader::SetTimestampMerger(TimestampMerger *timestamp_merger,
463 int channel_index,
464 const Node *target_node) {
465 const Node *reinterpreted_target_node =
466 configuration::GetNodeOrDie(configuration(), target_node);
467 const Channel *const channel =
468 configuration()->channels()->Get(channel_index);
469
Austin Schuhcde938c2020-02-02 17:30:07 -0800470 VLOG(1) << " Configuring merger " << this << " for channel " << channel_index
471 << " "
472 << configuration::CleanedChannelToString(
473 configuration()->channels()->Get(channel_index));
474
Austin Schuh6f3babe2020-01-26 20:34:50 -0800475 MessageHeaderQueue *message_header_queue = nullptr;
476
477 // Figure out if this log file is from our point of view, or the other node's
478 // point of view.
479 if (node() == reinterpreted_target_node) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800480 VLOG(1) << " Replaying as logged node " << filename();
481
482 if (configuration::ChannelIsSendableOnNode(channel, node())) {
483 VLOG(1) << " Data on node";
484 message_header_queue = &(channels_[channel_index].data);
485 } else if (configuration::ChannelIsReadableOnNode(channel, node())) {
486 VLOG(1) << " Timestamps on node";
487 message_header_queue =
488 &(channels_[channel_index].timestamps[configuration::GetNodeIndex(
489 configuration(), node())]);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800490 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800491 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800492 }
493 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800494 VLOG(1) << " Replaying as other node " << filename();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800495 // We are replaying from another node's point of view. The only interesting
Austin Schuhcde938c2020-02-02 17:30:07 -0800496 // data is data that is sent from our node and received on theirs.
497 if (configuration::ChannelIsReadableOnNode(channel,
498 reinterpreted_target_node) &&
499 configuration::ChannelIsSendableOnNode(channel, node())) {
500 VLOG(1) << " Readable on target node";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800501 // Data from another node.
502 message_header_queue = &(channels_[channel_index].data);
503 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800504 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800505 // This is either not sendable on the other node, or is a timestamp and
506 // therefore not interesting.
507 }
508 }
509
510 // If we found one, write it down. This will be nullptr when there is nothing
511 // relevant on this channel on this node for the target node. In that case,
512 // we want to drop the message instead of queueing it.
513 if (message_header_queue != nullptr) {
514 message_header_queue->timestamp_merger = timestamp_merger;
515 }
516}
517
518std::tuple<monotonic_clock::time_point, uint32_t,
519 FlatbufferVector<MessageHeader>>
520SplitMessageReader::PopOldest(int channel_index) {
521 CHECK_GT(channels_[channel_index].data.size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800522 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
523 timestamp = channels_[channel_index].data.front_timestamp();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800524 FlatbufferVector<MessageHeader> front =
525 std::move(channels_[channel_index].data.front());
526 channels_[channel_index].data.pop_front();
Austin Schuhcde938c2020-02-02 17:30:07 -0800527
528 VLOG(1) << "Popped " << this << " " << std::get<0>(timestamp);
529
530 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800531
532 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
533 std::move(front));
534}
535
536std::tuple<monotonic_clock::time_point, uint32_t,
537 FlatbufferVector<MessageHeader>>
538SplitMessageReader::PopOldest(int channel, int node_index) {
539 CHECK_GT(channels_[channel].timestamps[node_index].size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800540 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
541 timestamp = channels_[channel].timestamps[node_index].front_timestamp();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800542 FlatbufferVector<MessageHeader> front =
543 std::move(channels_[channel].timestamps[node_index].front());
544 channels_[channel].timestamps[node_index].pop_front();
Austin Schuhcde938c2020-02-02 17:30:07 -0800545
546 VLOG(1) << "Popped " << this << " " << std::get<0>(timestamp);
547
548 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800549
550 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
551 std::move(front));
552}
553
Austin Schuhcde938c2020-02-02 17:30:07 -0800554bool SplitMessageReader::MessageHeaderQueue::emplace_back(
Austin Schuh6f3babe2020-01-26 20:34:50 -0800555 FlatbufferVector<MessageHeader> &&msg) {
556 CHECK(split_reader != nullptr);
557
558 // If there is no timestamp merger for this queue, nobody is listening. Drop
559 // the message. This happens when a log file from another node is replayed,
560 // and the timestamp mergers down stream just don't care.
561 if (timestamp_merger == nullptr) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800562 return false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800563 }
564
565 CHECK(timestamps != msg.message().has_data())
566 << ": Got timestamps and data mixed up on a node. "
567 << FlatbufferToJson(msg);
568
569 data_.emplace_back(std::move(msg));
570
571 if (data_.size() == 1u) {
572 // Yup, new data. Notify.
573 if (timestamps) {
574 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
575 } else {
576 timestamp_merger->Update(split_reader, front_timestamp());
577 }
578 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800579
580 return true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800581}
582
583void SplitMessageReader::MessageHeaderQueue::pop_front() {
584 data_.pop_front();
585 if (data_.size() != 0u) {
586 // Yup, new data.
587 if (timestamps) {
588 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
589 } else {
590 timestamp_merger->Update(split_reader, front_timestamp());
591 }
592 }
Austin Schuh05b70472020-01-01 17:11:17 -0800593}
594
595namespace {
596
Austin Schuh6f3babe2020-01-26 20:34:50 -0800597bool SplitMessageReaderHeapCompare(
598 const std::tuple<monotonic_clock::time_point, uint32_t,
599 SplitMessageReader *>
600 first,
601 const std::tuple<monotonic_clock::time_point, uint32_t,
602 SplitMessageReader *>
603 second) {
604 if (std::get<0>(first) > std::get<0>(second)) {
605 return true;
606 } else if (std::get<0>(first) == std::get<0>(second)) {
607 if (std::get<1>(first) > std::get<1>(second)) {
608 return true;
609 } else if (std::get<1>(first) == std::get<1>(second)) {
610 return std::get<2>(first) > std::get<2>(second);
611 } else {
612 return false;
613 }
614 } else {
615 return false;
616 }
617}
618
Austin Schuh05b70472020-01-01 17:11:17 -0800619bool ChannelHeapCompare(
620 const std::pair<monotonic_clock::time_point, int> first,
621 const std::pair<monotonic_clock::time_point, int> second) {
622 if (first.first > second.first) {
623 return true;
624 } else if (first.first == second.first) {
625 return first.second > second.second;
626 } else {
627 return false;
628 }
629}
630
631} // namespace
632
Austin Schuh6f3babe2020-01-26 20:34:50 -0800633TimestampMerger::TimestampMerger(
634 const Configuration *configuration,
635 std::vector<SplitMessageReader *> split_message_readers, int channel_index,
636 const Node *target_node, ChannelMerger *channel_merger)
637 : configuration_(configuration),
638 split_message_readers_(std::move(split_message_readers)),
639 channel_index_(channel_index),
640 node_index_(configuration::MultiNode(configuration)
641 ? configuration::GetNodeIndex(configuration, target_node)
642 : -1),
643 channel_merger_(channel_merger) {
644 // Tell the readers we care so they know who to notify.
Austin Schuhcde938c2020-02-02 17:30:07 -0800645 VLOG(1) << "Configuring channel " << channel_index << " target node "
646 << FlatbufferToJson(target_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800647 for (SplitMessageReader *reader : split_message_readers_) {
648 reader->SetTimestampMerger(this, channel_index, target_node);
649 }
650
651 // And then determine if we need to track timestamps.
652 const Channel *channel = configuration->channels()->Get(channel_index);
653 if (!configuration::ChannelIsSendableOnNode(channel, target_node) &&
654 configuration::ChannelIsReadableOnNode(channel, target_node)) {
655 has_timestamps_ = true;
656 }
657}
658
659void TimestampMerger::PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800660 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
661 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800662 SplitMessageReader *split_message_reader) {
663 DCHECK(std::find_if(message_heap_.begin(), message_heap_.end(),
664 [split_message_reader](
665 const std::tuple<monotonic_clock::time_point,
666 uint32_t, SplitMessageReader *>
667 x) {
668 return std::get<2>(x) == split_message_reader;
669 }) == message_heap_.end())
670 << ": Pushing message when it is already in the heap.";
671
672 message_heap_.push_back(std::make_tuple(
673 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
674
675 std::push_heap(message_heap_.begin(), message_heap_.end(),
676 &SplitMessageReaderHeapCompare);
677
678 // If we are just a data merger, don't wait for timestamps.
679 if (!has_timestamps_) {
680 channel_merger_->Update(std::get<0>(timestamp), channel_index_);
681 pushed_ = true;
682 }
683}
684
Austin Schuhcde938c2020-02-02 17:30:07 -0800685std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
686TimestampMerger::oldest_message() const {
687 CHECK_GT(message_heap_.size(), 0u);
688 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
689 oldest_message_reader = message_heap_.front();
690 return std::get<2>(oldest_message_reader)->oldest_message(channel_index_);
691}
692
693std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
694TimestampMerger::oldest_timestamp() const {
695 CHECK_GT(timestamp_heap_.size(), 0u);
696 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
697 oldest_message_reader = timestamp_heap_.front();
698 return std::get<2>(oldest_message_reader)
699 ->oldest_message(channel_index_, node_index_);
700}
701
Austin Schuh6f3babe2020-01-26 20:34:50 -0800702void TimestampMerger::PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800703 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
704 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800705 SplitMessageReader *split_message_reader) {
706 DCHECK(std::find_if(timestamp_heap_.begin(), timestamp_heap_.end(),
707 [split_message_reader](
708 const std::tuple<monotonic_clock::time_point,
709 uint32_t, SplitMessageReader *>
710 x) {
711 return std::get<2>(x) == split_message_reader;
712 }) == timestamp_heap_.end())
713 << ": Pushing timestamp when it is already in the heap.";
714
715 timestamp_heap_.push_back(std::make_tuple(
716 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
717
718 std::push_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
719 SplitMessageReaderHeapCompare);
720
721 // If we are a timestamp merger, don't wait for data. Missing data will be
722 // caught at read time.
723 if (has_timestamps_) {
724 channel_merger_->Update(std::get<0>(timestamp), channel_index_);
725 pushed_ = true;
726 }
727}
728
729std::tuple<monotonic_clock::time_point, uint32_t,
730 FlatbufferVector<MessageHeader>>
731TimestampMerger::PopMessageHeap() {
732 // Pop the oldest message reader pointer off the heap.
733 CHECK_GT(message_heap_.size(), 0u);
734 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
735 oldest_message_reader = message_heap_.front();
736
737 std::pop_heap(message_heap_.begin(), message_heap_.end(),
738 &SplitMessageReaderHeapCompare);
739 message_heap_.pop_back();
740
741 // Pop the oldest message. This re-pushes any messages from the reader to the
742 // message heap.
743 std::tuple<monotonic_clock::time_point, uint32_t,
744 FlatbufferVector<MessageHeader>>
745 oldest_message =
746 std::get<2>(oldest_message_reader)->PopOldest(channel_index_);
747
748 // Confirm that the time and queue_index we have recorded matches.
749 CHECK_EQ(std::get<0>(oldest_message), std::get<0>(oldest_message_reader));
750 CHECK_EQ(std::get<1>(oldest_message), std::get<1>(oldest_message_reader));
751
752 // Now, keep reading until we have found all duplicates.
753 while (message_heap_.size() > 0u) {
754 // See if it is a duplicate.
755 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
756 next_oldest_message_reader = message_heap_.front();
757
Austin Schuhcde938c2020-02-02 17:30:07 -0800758 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
759 next_oldest_message_time = std::get<2>(next_oldest_message_reader)
760 ->oldest_message(channel_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800761
762 if (std::get<0>(next_oldest_message_time) == std::get<0>(oldest_message) &&
763 std::get<1>(next_oldest_message_time) == std::get<1>(oldest_message)) {
764 // Pop the message reader pointer.
765 std::pop_heap(message_heap_.begin(), message_heap_.end(),
766 &SplitMessageReaderHeapCompare);
767 message_heap_.pop_back();
768
769 // Pop the next oldest message. This re-pushes any messages from the
770 // reader.
771 std::tuple<monotonic_clock::time_point, uint32_t,
772 FlatbufferVector<MessageHeader>>
773 next_oldest_message = std::get<2>(next_oldest_message_reader)
774 ->PopOldest(channel_index_);
775
776 // And make sure the message matches in it's entirety.
777 CHECK(std::get<2>(oldest_message).span() ==
778 std::get<2>(next_oldest_message).span())
779 << ": Data at the same timestamp doesn't match.";
780 } else {
781 break;
782 }
783 }
784
785 return oldest_message;
786}
787
788std::tuple<monotonic_clock::time_point, uint32_t,
789 FlatbufferVector<MessageHeader>>
790TimestampMerger::PopTimestampHeap() {
791 // Pop the oldest message reader pointer off the heap.
792 CHECK_GT(timestamp_heap_.size(), 0u);
793
794 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
795 oldest_timestamp_reader = timestamp_heap_.front();
796
797 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
798 &SplitMessageReaderHeapCompare);
799 timestamp_heap_.pop_back();
800
801 CHECK(node_index_ != -1) << ": Timestamps in a single node environment";
802
803 // Pop the oldest message. This re-pushes any timestamps from the reader to
804 // the timestamp heap.
805 std::tuple<monotonic_clock::time_point, uint32_t,
806 FlatbufferVector<MessageHeader>>
807 oldest_timestamp = std::get<2>(oldest_timestamp_reader)
808 ->PopOldest(channel_index_, node_index_);
809
810 // Confirm that the time we have recorded matches.
811 CHECK_EQ(std::get<0>(oldest_timestamp), std::get<0>(oldest_timestamp_reader));
812 CHECK_EQ(std::get<1>(oldest_timestamp), std::get<1>(oldest_timestamp_reader));
813
814 // TODO(austin): What if we get duplicate timestamps?
815
816 return oldest_timestamp;
817}
818
Austin Schuh8bd96322020-02-13 21:18:22 -0800819TimestampMerger::DeliveryTimestamp TimestampMerger::OldestTimestamp() const {
820 if (!has_timestamps_ || timestamp_heap_.size() == 0u) {
821 return TimestampMerger::DeliveryTimestamp{};
822 }
823
824 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
825 oldest_timestamp_reader = timestamp_heap_.front();
826
827 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
828 oldest_timestamp = std::get<2>(oldest_timestamp_reader)
829 ->oldest_message(channel_index_, node_index_);
830
831 TimestampMerger::DeliveryTimestamp timestamp;
832 timestamp.monotonic_event_time =
833 monotonic_clock::time_point(chrono::nanoseconds(
834 std::get<2>(oldest_timestamp)->monotonic_sent_time()));
835 timestamp.realtime_event_time = realtime_clock::time_point(
836 chrono::nanoseconds(std::get<2>(oldest_timestamp)->realtime_sent_time()));
837
838 timestamp.monotonic_remote_time =
839 monotonic_clock::time_point(chrono::nanoseconds(
840 std::get<2>(oldest_timestamp)->monotonic_remote_time()));
841 timestamp.realtime_remote_time =
842 realtime_clock::time_point(chrono::nanoseconds(
843 std::get<2>(oldest_timestamp)->realtime_remote_time()));
844
845 timestamp.remote_queue_index = std::get<2>(oldest_timestamp)->queue_index();
846 return timestamp;
847}
848
Austin Schuh6f3babe2020-01-26 20:34:50 -0800849std::tuple<TimestampMerger::DeliveryTimestamp, FlatbufferVector<MessageHeader>>
850TimestampMerger::PopOldest() {
851 if (has_timestamps_) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800852 // Read the timestamps.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800853 std::tuple<monotonic_clock::time_point, uint32_t,
854 FlatbufferVector<MessageHeader>>
855 oldest_timestamp = PopTimestampHeap();
856
857 TimestampMerger::DeliveryTimestamp timestamp;
858 timestamp.monotonic_event_time =
859 monotonic_clock::time_point(chrono::nanoseconds(
860 std::get<2>(oldest_timestamp).message().monotonic_sent_time()));
861 timestamp.realtime_event_time =
862 realtime_clock::time_point(chrono::nanoseconds(
863 std::get<2>(oldest_timestamp).message().realtime_sent_time()));
864
865 // Consistency check.
866 CHECK_EQ(timestamp.monotonic_event_time, std::get<0>(oldest_timestamp));
867 CHECK_EQ(std::get<2>(oldest_timestamp).message().queue_index(),
868 std::get<1>(oldest_timestamp));
869
870 monotonic_clock::time_point remote_timestamp_monotonic_time(
871 chrono::nanoseconds(
872 std::get<2>(oldest_timestamp).message().monotonic_remote_time()));
873
Austin Schuh8bd96322020-02-13 21:18:22 -0800874 // See if we have any data. If not, pass the problem up the chain.
875 if (message_heap_.size() == 0u) {
876 VLOG(1) << "No data to match timestamp on "
877 << configuration::CleanedChannelToString(
878 configuration_->channels()->Get(channel_index_));
879 return std::make_tuple(timestamp,
880 std::move(std::get<2>(oldest_timestamp)));
881 }
882
Austin Schuh6f3babe2020-01-26 20:34:50 -0800883 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800884 {
885 // Ok, now try grabbing data until we find one which matches.
886 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
887 oldest_message_ref = oldest_message();
888
889 // Time at which the message was sent (this message is written from the
890 // sending node's perspective.
891 monotonic_clock::time_point remote_monotonic_time(chrono::nanoseconds(
892 std::get<2>(oldest_message_ref)->monotonic_sent_time()));
893
894 if (remote_monotonic_time < remote_timestamp_monotonic_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800895 VLOG(1) << "Undelivered message, skipping. Remote time is "
896 << remote_monotonic_time << " timestamp is "
897 << remote_timestamp_monotonic_time << " on channel "
898 << channel_index_;
Austin Schuhcde938c2020-02-02 17:30:07 -0800899 PopMessageHeap();
900 continue;
901 } else if (remote_monotonic_time > remote_timestamp_monotonic_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800902 VLOG(1) << "Data not found. Remote time should be "
903 << remote_timestamp_monotonic_time << " on channel "
904 << channel_index_;
Austin Schuhcde938c2020-02-02 17:30:07 -0800905 return std::make_tuple(timestamp,
906 std::move(std::get<2>(oldest_timestamp)));
907 }
908
909 timestamp.monotonic_remote_time = remote_monotonic_time;
910 }
911
Austin Schuh6f3babe2020-01-26 20:34:50 -0800912 std::tuple<monotonic_clock::time_point, uint32_t,
913 FlatbufferVector<MessageHeader>>
914 oldest_message = PopMessageHeap();
915
Austin Schuh6f3babe2020-01-26 20:34:50 -0800916 timestamp.realtime_remote_time =
917 realtime_clock::time_point(chrono::nanoseconds(
918 std::get<2>(oldest_message).message().realtime_sent_time()));
919 timestamp.remote_queue_index =
920 std::get<2>(oldest_message).message().queue_index();
921
Austin Schuhcde938c2020-02-02 17:30:07 -0800922 CHECK_EQ(timestamp.monotonic_remote_time,
923 remote_timestamp_monotonic_time);
924
925 CHECK_EQ(timestamp.remote_queue_index,
926 std::get<2>(oldest_timestamp).message().remote_queue_index())
927 << ": " << FlatbufferToJson(&std::get<2>(oldest_timestamp).message())
928 << " data "
929 << FlatbufferToJson(&std::get<2>(oldest_message).message());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800930
931 return std::make_tuple(timestamp, std::get<2>(oldest_message));
932 }
933 } else {
934 std::tuple<monotonic_clock::time_point, uint32_t,
935 FlatbufferVector<MessageHeader>>
936 oldest_message = PopMessageHeap();
937
938 TimestampMerger::DeliveryTimestamp timestamp;
939 timestamp.monotonic_event_time =
940 monotonic_clock::time_point(chrono::nanoseconds(
941 std::get<2>(oldest_message).message().monotonic_sent_time()));
942 timestamp.realtime_event_time =
943 realtime_clock::time_point(chrono::nanoseconds(
944 std::get<2>(oldest_message).message().realtime_sent_time()));
945 timestamp.remote_queue_index = 0xffffffff;
946
947 CHECK_EQ(std::get<0>(oldest_message), timestamp.monotonic_event_time);
948 CHECK_EQ(std::get<1>(oldest_message),
949 std::get<2>(oldest_message).message().queue_index());
950
951 return std::make_tuple(timestamp, std::get<2>(oldest_message));
952 }
953}
954
Austin Schuh8bd96322020-02-13 21:18:22 -0800955void TimestampMerger::NoticeAtEnd() { channel_merger_->NoticeAtEnd(); }
956
Austin Schuh6f3babe2020-01-26 20:34:50 -0800957namespace {
958std::vector<std::unique_ptr<SplitMessageReader>> MakeSplitMessageReaders(
959 const std::vector<std::vector<std::string>> &filenames) {
960 CHECK_GT(filenames.size(), 0u);
961 // Build up all the SplitMessageReaders.
962 std::vector<std::unique_ptr<SplitMessageReader>> result;
963 for (const std::vector<std::string> &filenames : filenames) {
964 result.emplace_back(std::make_unique<SplitMessageReader>(filenames));
965 }
966 return result;
967}
968} // namespace
969
970ChannelMerger::ChannelMerger(
971 const std::vector<std::vector<std::string>> &filenames)
972 : split_message_readers_(MakeSplitMessageReaders(filenames)),
973 log_file_header_(
974 CopyFlatBuffer(split_message_readers_[0]->log_file_header())) {
975 // Now, confirm that the configuration matches for each and pick a start time.
976 // Also return the list of possible nodes.
977 for (const std::unique_ptr<SplitMessageReader> &reader :
978 split_message_readers_) {
979 CHECK(CompareFlatBuffer(log_file_header_.message().configuration(),
980 reader->log_file_header()->configuration()))
981 << ": Replaying log files with different configurations isn't "
982 "supported";
983 }
984
985 nodes_ = configuration::GetNodes(configuration());
986}
987
988bool ChannelMerger::SetNode(const Node *target_node) {
989 std::vector<SplitMessageReader *> split_message_readers;
990 for (const std::unique_ptr<SplitMessageReader> &reader :
991 split_message_readers_) {
992 split_message_readers.emplace_back(reader.get());
993 }
994
995 // Go find a log_file_header for this node.
996 {
997 bool found_node = false;
998
999 for (const std::unique_ptr<SplitMessageReader> &reader :
1000 split_message_readers_) {
1001 if (CompareFlatBuffer(reader->node(), target_node)) {
1002 if (!found_node) {
1003 found_node = true;
1004 log_file_header_ = CopyFlatBuffer(reader->log_file_header());
Austin Schuhcde938c2020-02-02 17:30:07 -08001005 VLOG(1) << "Found log file " << reader->filename() << " with node "
1006 << FlatbufferToJson(reader->node()) << " start_time "
1007 << monotonic_start_time();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001008 } else {
1009 // And then make sure all the other files have matching headers.
Austin Schuhcde938c2020-02-02 17:30:07 -08001010 CHECK(CompareFlatBuffer(log_file_header(), reader->log_file_header()))
1011 << ": " << FlatbufferToJson(log_file_header()) << " reader "
1012 << FlatbufferToJson(reader->log_file_header());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001013 }
1014 }
1015 }
1016
1017 if (!found_node) {
1018 LOG(WARNING) << "Failed to find log file for node "
1019 << FlatbufferToJson(target_node);
1020 return false;
1021 }
1022 }
1023
1024 // Build up all the timestamp mergers. This connects up all the
1025 // SplitMessageReaders.
1026 timestamp_mergers_.reserve(configuration()->channels()->size());
1027 for (size_t channel_index = 0;
1028 channel_index < configuration()->channels()->size(); ++channel_index) {
1029 timestamp_mergers_.emplace_back(
1030 configuration(), split_message_readers, channel_index,
1031 configuration::GetNode(configuration(), target_node), this);
1032 }
1033
1034 // And prime everything.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001035 for (std::unique_ptr<SplitMessageReader> &split_message_reader :
1036 split_message_readers_) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001037 split_message_reader->QueueMessages(
1038 split_message_reader->monotonic_start_time());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001039 }
1040
1041 node_ = configuration::GetNodeOrDie(configuration(), target_node);
1042 return true;
1043}
1044
1045monotonic_clock::time_point ChannelMerger::OldestMessage() const {
1046 if (channel_heap_.size() == 0u) {
1047 return monotonic_clock::max_time;
1048 }
1049 return channel_heap_.front().first;
1050}
1051
Austin Schuh8bd96322020-02-13 21:18:22 -08001052TimestampMerger::DeliveryTimestamp ChannelMerger::OldestTimestamp() const {
1053 if (timestamp_heap_.size() == 0u) {
1054 return TimestampMerger::DeliveryTimestamp{};
1055 }
1056 return timestamp_mergers_[timestamp_heap_.front().second].OldestTimestamp();
1057}
1058
1059TimestampMerger::DeliveryTimestamp ChannelMerger::OldestTimestampForChannel(
1060 int channel) const {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001061 // If we didn't find any data for this node, we won't have any mergers. Return
1062 // an invalid timestamp in that case.
1063 if (timestamp_mergers_.size() <= static_cast<size_t>(channel)) {
1064 TimestampMerger::DeliveryTimestamp result;
1065 return result;
1066 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001067 return timestamp_mergers_[channel].OldestTimestamp();
1068}
1069
Austin Schuh6f3babe2020-01-26 20:34:50 -08001070void ChannelMerger::PushChannelHeap(monotonic_clock::time_point timestamp,
1071 int channel_index) {
1072 // Pop and recreate the heap if it has already been pushed. And since we are
1073 // pushing again, we don't need to clear pushed.
1074 if (timestamp_mergers_[channel_index].pushed()) {
1075 channel_heap_.erase(std::find_if(
1076 channel_heap_.begin(), channel_heap_.end(),
1077 [channel_index](const std::pair<monotonic_clock::time_point, int> x) {
1078 return x.second == channel_index;
1079 }));
1080 std::make_heap(channel_heap_.begin(), channel_heap_.end(),
1081 ChannelHeapCompare);
Austin Schuh8bd96322020-02-13 21:18:22 -08001082
1083 if (timestamp_mergers_[channel_index].has_timestamps()) {
1084 timestamp_heap_.erase(std::find_if(
1085 timestamp_heap_.begin(), timestamp_heap_.end(),
1086 [channel_index](const std::pair<monotonic_clock::time_point, int> x) {
1087 return x.second == channel_index;
1088 }));
1089 std::make_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1090 ChannelHeapCompare);
1091 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001092 }
1093
Austin Schuh05b70472020-01-01 17:11:17 -08001094 channel_heap_.push_back(std::make_pair(timestamp, channel_index));
1095
1096 // The default sort puts the newest message first. Use a custom comparator to
1097 // put the oldest message first.
1098 std::push_heap(channel_heap_.begin(), channel_heap_.end(),
1099 ChannelHeapCompare);
Austin Schuh8bd96322020-02-13 21:18:22 -08001100
1101 if (timestamp_mergers_[channel_index].has_timestamps()) {
1102 timestamp_heap_.push_back(std::make_pair(timestamp, channel_index));
1103 std::push_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1104 ChannelHeapCompare);
1105 }
Austin Schuh05b70472020-01-01 17:11:17 -08001106}
1107
Austin Schuh6f3babe2020-01-26 20:34:50 -08001108std::tuple<TimestampMerger::DeliveryTimestamp, int,
1109 FlatbufferVector<MessageHeader>>
1110ChannelMerger::PopOldest() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001111 CHECK_GT(channel_heap_.size(), 0u);
Austin Schuh05b70472020-01-01 17:11:17 -08001112 std::pair<monotonic_clock::time_point, int> oldest_channel_data =
1113 channel_heap_.front();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001114 int channel_index = oldest_channel_data.second;
Austin Schuh05b70472020-01-01 17:11:17 -08001115 std::pop_heap(channel_heap_.begin(), channel_heap_.end(),
1116 &ChannelHeapCompare);
1117 channel_heap_.pop_back();
Austin Schuh8bd96322020-02-13 21:18:22 -08001118
Austin Schuh6f3babe2020-01-26 20:34:50 -08001119 timestamp_mergers_[channel_index].set_pushed(false);
Austin Schuh05b70472020-01-01 17:11:17 -08001120
Austin Schuh6f3babe2020-01-26 20:34:50 -08001121 TimestampMerger *merger = &timestamp_mergers_[channel_index];
Austin Schuh05b70472020-01-01 17:11:17 -08001122
Austin Schuh8bd96322020-02-13 21:18:22 -08001123 if (merger->has_timestamps()) {
1124 CHECK_GT(timestamp_heap_.size(), 0u);
1125 std::pair<monotonic_clock::time_point, int> oldest_timestamp_data =
1126 timestamp_heap_.front();
1127 CHECK(oldest_timestamp_data == oldest_channel_data)
1128 << ": Timestamp heap out of sync.";
1129 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1130 &ChannelHeapCompare);
1131 timestamp_heap_.pop_back();
1132 }
1133
Austin Schuhcde938c2020-02-02 17:30:07 -08001134 // Merger handles any queueing needed from here.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001135 std::tuple<TimestampMerger::DeliveryTimestamp,
1136 FlatbufferVector<MessageHeader>>
1137 message = merger->PopOldest();
Austin Schuh05b70472020-01-01 17:11:17 -08001138
Austin Schuh6f3babe2020-01-26 20:34:50 -08001139 return std::make_tuple(std::get<0>(message), channel_index,
1140 std::move(std::get<1>(message)));
1141}
1142
Austin Schuhcde938c2020-02-02 17:30:07 -08001143std::string SplitMessageReader::MessageHeaderQueue::DebugString() const {
1144 std::stringstream ss;
1145 for (size_t i = 0; i < data_.size(); ++i) {
1146 if (timestamps) {
1147 ss << " msg: ";
1148 } else {
1149 ss << " timestamp: ";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001150 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001151 ss << monotonic_clock::time_point(std::chrono::nanoseconds(
1152 data_[i].message().monotonic_sent_time()))
1153 << " ("
1154 << realtime_clock::time_point(
1155 std::chrono::nanoseconds(data_[i].message().realtime_sent_time()))
1156 << ") " << data_[i].message().queue_index();
1157 if (timestamps) {
1158 ss << " <- remote "
1159 << monotonic_clock::time_point(std::chrono::nanoseconds(
1160 data_[i].message().monotonic_remote_time()))
1161 << " ("
1162 << realtime_clock::time_point(std::chrono::nanoseconds(
1163 data_[i].message().realtime_remote_time()))
1164 << ")";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001165 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001166 ss << "\n";
1167 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001168
Austin Schuhcde938c2020-02-02 17:30:07 -08001169 return ss.str();
1170}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001171
Austin Schuhcde938c2020-02-02 17:30:07 -08001172std::string SplitMessageReader::DebugString(int channel) const {
1173 std::stringstream ss;
1174 ss << "[\n";
1175 ss << channels_[channel].data.DebugString();
1176 ss << " ]";
1177 return ss.str();
1178}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001179
Austin Schuhcde938c2020-02-02 17:30:07 -08001180std::string SplitMessageReader::DebugString(int channel, int node_index) const {
1181 std::stringstream ss;
1182 ss << "[\n";
1183 ss << channels_[channel].timestamps[node_index].DebugString();
1184 ss << " ]";
1185 return ss.str();
1186}
1187
1188std::string TimestampMerger::DebugString() const {
1189 std::stringstream ss;
1190
1191 if (timestamp_heap_.size() > 0) {
1192 ss << " timestamp_heap {\n";
1193 std::vector<
1194 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1195 timestamp_heap = timestamp_heap_;
1196 while (timestamp_heap.size() > 0u) {
1197 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1198 oldest_timestamp_reader = timestamp_heap.front();
1199
1200 ss << " " << std::get<2>(oldest_timestamp_reader) << " "
1201 << std::get<0>(oldest_timestamp_reader) << " queue_index ("
1202 << std::get<1>(oldest_timestamp_reader) << ") ttq "
1203 << std::get<2>(oldest_timestamp_reader)->time_to_queue() << " "
1204 << std::get<2>(oldest_timestamp_reader)->filename() << " -> "
1205 << std::get<2>(oldest_timestamp_reader)
1206 ->DebugString(channel_index_, node_index_)
1207 << "\n";
1208
1209 std::pop_heap(timestamp_heap.begin(), timestamp_heap.end(),
1210 &SplitMessageReaderHeapCompare);
1211 timestamp_heap.pop_back();
1212 }
1213 ss << " }\n";
1214 }
1215
1216 ss << " message_heap {\n";
1217 {
1218 std::vector<
1219 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1220 message_heap = message_heap_;
1221 while (message_heap.size() > 0u) {
1222 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1223 oldest_message_reader = message_heap.front();
1224
1225 ss << " " << std::get<2>(oldest_message_reader) << " "
1226 << std::get<0>(oldest_message_reader) << " queue_index ("
1227 << std::get<1>(oldest_message_reader) << ") ttq "
1228 << std::get<2>(oldest_message_reader)->time_to_queue() << " "
1229 << std::get<2>(oldest_message_reader)->filename() << " -> "
1230 << std::get<2>(oldest_message_reader)->DebugString(channel_index_)
1231 << "\n";
1232
1233 std::pop_heap(message_heap.begin(), message_heap.end(),
1234 &SplitMessageReaderHeapCompare);
1235 message_heap.pop_back();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001236 }
Austin Schuh05b70472020-01-01 17:11:17 -08001237 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001238 ss << " }";
1239
1240 return ss.str();
1241}
1242
1243std::string ChannelMerger::DebugString() const {
1244 std::stringstream ss;
1245 ss << "start_time " << realtime_start_time() << " " << monotonic_start_time()
1246 << "\n";
1247 ss << "channel_heap {\n";
1248 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap =
1249 channel_heap_;
1250 while (channel_heap.size() > 0u) {
1251 std::tuple<monotonic_clock::time_point, int> channel = channel_heap.front();
1252 ss << " " << std::get<0>(channel) << " (" << std::get<1>(channel) << ") "
1253 << configuration::CleanedChannelToString(
1254 configuration()->channels()->Get(std::get<1>(channel)))
1255 << "\n";
1256
1257 ss << timestamp_mergers_[std::get<1>(channel)].DebugString() << "\n";
1258
1259 std::pop_heap(channel_heap.begin(), channel_heap.end(),
1260 &ChannelHeapCompare);
1261 channel_heap.pop_back();
1262 }
1263 ss << "}";
1264
1265 return ss.str();
Austin Schuh05b70472020-01-01 17:11:17 -08001266}
1267
Austin Schuha36c8902019-12-30 18:07:15 -08001268} // namespace logger
1269} // namespace aos