blob: c78b160361a71fbdb441862b8ea24f7cfdacfd15 [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;
Brian Silverman98360e22020-04-28 16:51:20 -070065 written_size_ += written;
Austin Schuhde031b72020-01-10 19:34:41 -080066}
67
Austin Schuha36c8902019-12-30 18:07:15 -080068void DetachedBufferWriter::QueueSizedFlatbuffer(
69 flatbuffers::DetachedBuffer &&buffer) {
70 queued_size_ += buffer.size();
71 queue_.emplace_back(std::move(buffer));
72
73 // Flush if we are at the max number of iovs per writev, or have written
74 // enough data. Otherwise writev will fail with an invalid argument.
75 if (queued_size_ > static_cast<size_t>(FLAGS_flush_size) ||
76 queue_.size() == IOV_MAX) {
77 Flush();
78 }
79}
80
81void DetachedBufferWriter::Flush() {
82 if (queue_.size() == 0u) {
83 return;
84 }
85 iovec_.clear();
86 iovec_.reserve(queue_.size());
87 size_t counted_size = 0;
88 for (size_t i = 0; i < queue_.size(); ++i) {
89 struct iovec n;
90 n.iov_base = queue_[i].data();
91 n.iov_len = queue_[i].size();
92 counted_size += n.iov_len;
93 iovec_.emplace_back(std::move(n));
94 }
95 CHECK_EQ(counted_size, queued_size_);
96 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
97
98 PCHECK(written == static_cast<ssize_t>(queued_size_))
99 << ": Wrote " << written << " expected " << queued_size_;
Brian Silverman98360e22020-04-28 16:51:20 -0700100 written_size_ += written;
Austin Schuha36c8902019-12-30 18:07:15 -0800101
102 queued_size_ = 0;
103 queue_.clear();
104 // TODO(austin): Handle partial writes in some way other than crashing...
105}
106
107flatbuffers::Offset<MessageHeader> PackMessage(
108 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
109 int channel_index, LogType log_type) {
110 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
111
112 switch (log_type) {
113 case LogType::kLogMessage:
114 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800115 case LogType::kLogRemoteMessage:
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700116 data_offset = fbb->CreateVector(
117 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800118 break;
119
120 case LogType::kLogDeliveryTimeOnly:
121 break;
122 }
123
124 MessageHeader::Builder message_header_builder(*fbb);
125 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800126
127 switch (log_type) {
128 case LogType::kLogRemoteMessage:
129 message_header_builder.add_queue_index(context.remote_queue_index);
130 message_header_builder.add_monotonic_sent_time(
131 context.monotonic_remote_time.time_since_epoch().count());
132 message_header_builder.add_realtime_sent_time(
133 context.realtime_remote_time.time_since_epoch().count());
134 break;
135
136 case LogType::kLogMessage:
137 case LogType::kLogMessageAndDeliveryTime:
138 case LogType::kLogDeliveryTimeOnly:
139 message_header_builder.add_queue_index(context.queue_index);
140 message_header_builder.add_monotonic_sent_time(
141 context.monotonic_event_time.time_since_epoch().count());
142 message_header_builder.add_realtime_sent_time(
143 context.realtime_event_time.time_since_epoch().count());
144 break;
145 }
Austin Schuha36c8902019-12-30 18:07:15 -0800146
147 switch (log_type) {
148 case LogType::kLogMessage:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800149 case LogType::kLogRemoteMessage:
Austin Schuha36c8902019-12-30 18:07:15 -0800150 message_header_builder.add_data(data_offset);
151 break;
152
153 case LogType::kLogMessageAndDeliveryTime:
154 message_header_builder.add_data(data_offset);
155 [[fallthrough]];
156
157 case LogType::kLogDeliveryTimeOnly:
158 message_header_builder.add_monotonic_remote_time(
159 context.monotonic_remote_time.time_since_epoch().count());
160 message_header_builder.add_realtime_remote_time(
161 context.realtime_remote_time.time_since_epoch().count());
162 message_header_builder.add_remote_queue_index(context.remote_queue_index);
163 break;
164 }
165
166 return message_header_builder.Finish();
167}
168
Austin Schuh05b70472020-01-01 17:11:17 -0800169SpanReader::SpanReader(std::string_view filename)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800170 : filename_(filename),
171 fd_(open(std::string(filename).c_str(), O_RDONLY | O_CLOEXEC)) {
Austin Schuh05b70472020-01-01 17:11:17 -0800172 PCHECK(fd_ != -1) << ": Failed to open " << filename;
173}
174
175absl::Span<const uint8_t> SpanReader::ReadMessage() {
176 // Make sure we have enough for the size.
177 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
178 if (!ReadBlock()) {
179 return absl::Span<const uint8_t>();
180 }
181 }
182
183 // Now make sure we have enough for the message.
184 const size_t data_size =
185 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
186 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -0800187 if (data_size == sizeof(flatbuffers::uoffset_t)) {
188 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
189 LOG(ERROR) << " Rest of log file is "
190 << absl::BytesToHexString(std::string_view(
191 reinterpret_cast<const char *>(data_.data() +
192 consumed_data_),
193 data_.size() - consumed_data_));
194 return absl::Span<const uint8_t>();
195 }
Austin Schuh05b70472020-01-01 17:11:17 -0800196 while (data_.size() < consumed_data_ + data_size) {
197 if (!ReadBlock()) {
198 return absl::Span<const uint8_t>();
199 }
200 }
201
202 // And return it, consuming the data.
203 const uint8_t *data_ptr = data_.data() + consumed_data_;
204
205 consumed_data_ += data_size;
206
207 return absl::Span<const uint8_t>(data_ptr, data_size);
208}
209
210bool SpanReader::MessageAvailable() {
211 // Are we big enough to read the size?
212 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
213 return false;
214 }
215
216 // Then, are we big enough to read the full message?
217 const size_t data_size =
218 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
219 sizeof(flatbuffers::uoffset_t);
220 if (data_.size() < consumed_data_ + data_size) {
221 return false;
222 }
223
224 return true;
225}
226
227bool SpanReader::ReadBlock() {
228 if (end_of_file_) {
229 return false;
230 }
231
232 // Appends 256k. This is enough that the read call is efficient. We don't
233 // want to spend too much time reading small chunks because the syscalls for
234 // that will be expensive.
235 constexpr size_t kReadSize = 256 * 1024;
236
237 // Strip off any unused data at the front.
238 if (consumed_data_ != 0) {
239 data_.erase(data_.begin(), data_.begin() + consumed_data_);
240 consumed_data_ = 0;
241 }
242
243 const size_t starting_size = data_.size();
244
245 // This should automatically grow the backing store. It won't shrink if we
246 // get a small chunk later. This reduces allocations when we want to append
247 // more data.
248 data_.resize(data_.size() + kReadSize);
249
250 ssize_t count = read(fd_, &data_[starting_size], kReadSize);
251 data_.resize(starting_size + std::max(count, static_cast<ssize_t>(0)));
252 if (count == 0) {
253 end_of_file_ = true;
254 return false;
255 }
256 PCHECK(count > 0);
257
258 return true;
259}
260
Austin Schuh6f3babe2020-01-26 20:34:50 -0800261FlatbufferVector<LogFileHeader> ReadHeader(std::string_view filename) {
262 SpanReader span_reader(filename);
263 // Make sure we have enough to read the size.
264 absl::Span<const uint8_t> config_data = span_reader.ReadMessage();
265
266 // Make sure something was read.
Austin Schuh97789fc2020-08-01 14:42:45 -0700267 CHECK(config_data != absl::Span<const uint8_t>())
268 << ": Failed to read header from: " << filename;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800269
270 // And copy the config so we have it forever.
271 std::vector<uint8_t> data(
272 config_data.begin() + sizeof(flatbuffers::uoffset_t), config_data.end());
273 return FlatbufferVector<LogFileHeader>(std::move(data));
274}
275
Austin Schuh05b70472020-01-01 17:11:17 -0800276MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -0700277 : span_reader_(filename),
278 raw_log_file_header_(FlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuh05b70472020-01-01 17:11:17 -0800279 // Make sure we have enough to read the size.
Austin Schuh97789fc2020-08-01 14:42:45 -0700280 absl::Span<const uint8_t> header_data = span_reader_.ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800281
282 // Make sure something was read.
Austin Schuh97789fc2020-08-01 14:42:45 -0700283 CHECK(header_data != absl::Span<const uint8_t>())
284 << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -0800285
Austin Schuh97789fc2020-08-01 14:42:45 -0700286 // And copy the header data so we have it forever.
287 std::vector<uint8_t> header_data_copy(
288 header_data.begin() + sizeof(flatbuffers::uoffset_t), header_data.end());
289 raw_log_file_header_ =
290 FlatbufferVector<LogFileHeader>(std::move(header_data_copy));
Austin Schuh05b70472020-01-01 17:11:17 -0800291
Austin Schuhcde938c2020-02-02 17:30:07 -0800292 max_out_of_order_duration_ =
293 std::chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
294
295 VLOG(1) << "Opened " << filename << " as node "
296 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800297}
298
299std::optional<FlatbufferVector<MessageHeader>> MessageReader::ReadMessage() {
300 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
301 if (msg_data == absl::Span<const uint8_t>()) {
302 return std::nullopt;
303 }
304
305 FlatbufferVector<MessageHeader> result{std::vector<uint8_t>(
306 msg_data.begin() + sizeof(flatbuffers::uoffset_t), msg_data.end())};
307
308 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
309 chrono::nanoseconds(result.message().monotonic_sent_time()));
310
311 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuh8bd96322020-02-13 21:18:22 -0800312 VLOG(2) << "Read from " << filename() << " data " << FlatbufferToJson(result);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800313 return std::move(result);
Austin Schuh05b70472020-01-01 17:11:17 -0800314}
315
Austin Schuh6f3babe2020-01-26 20:34:50 -0800316SplitMessageReader::SplitMessageReader(
Austin Schuhfa895892020-01-07 20:07:41 -0800317 const std::vector<std::string> &filenames)
318 : filenames_(filenames),
Austin Schuh97789fc2020-08-01 14:42:45 -0700319 log_file_header_(FlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuhfa895892020-01-07 20:07:41 -0800320 CHECK(NextLogFile()) << ": filenames is empty. Need files to read.";
321
Austin Schuh6f3babe2020-01-26 20:34:50 -0800322 // Grab any log file header. They should all match (and we will check as we
323 // open more of them).
Austin Schuh97789fc2020-08-01 14:42:45 -0700324 log_file_header_ = message_reader_->raw_log_file_header();
Austin Schuhfa895892020-01-07 20:07:41 -0800325
Austin Schuh6f3babe2020-01-26 20:34:50 -0800326 // Setup per channel state.
Austin Schuh05b70472020-01-01 17:11:17 -0800327 channels_.resize(configuration()->channels()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800328 for (ChannelData &channel_data : channels_) {
329 channel_data.data.split_reader = this;
330 // Build up the timestamp list.
331 if (configuration::MultiNode(configuration())) {
332 channel_data.timestamps.resize(configuration()->nodes()->size());
333 for (MessageHeaderQueue &queue : channel_data.timestamps) {
334 queue.timestamps = true;
335 queue.split_reader = this;
336 }
337 }
338 }
Austin Schuh05b70472020-01-01 17:11:17 -0800339
Austin Schuh6f3babe2020-01-26 20:34:50 -0800340 // Build up channels_to_write_ as an optimization to make it fast to figure
341 // out which datastructure to place any new data from a channel on.
342 for (const Channel *channel : *configuration()->channels()) {
343 // This is the main case. We will only see data on this node.
344 if (configuration::ChannelIsSendableOnNode(channel, node())) {
345 channels_to_write_.emplace_back(
346 &channels_[channels_to_write_.size()].data);
347 } else
348 // If we can't send, but can receive, we should be able to see
349 // timestamps here.
350 if (configuration::ChannelIsReadableOnNode(channel, node())) {
351 channels_to_write_.emplace_back(
352 &(channels_[channels_to_write_.size()]
353 .timestamps[configuration::GetNodeIndex(configuration(),
354 node())]));
355 } else {
356 channels_to_write_.emplace_back(nullptr);
357 }
358 }
Austin Schuh05b70472020-01-01 17:11:17 -0800359}
360
Austin Schuh6f3babe2020-01-26 20:34:50 -0800361bool SplitMessageReader::NextLogFile() {
Austin Schuhfa895892020-01-07 20:07:41 -0800362 if (next_filename_index_ == filenames_.size()) {
363 return false;
364 }
365 message_reader_ =
366 std::make_unique<MessageReader>(filenames_[next_filename_index_]);
367
368 // We can't support the config diverging between two log file headers. See if
369 // they are the same.
370 if (next_filename_index_ != 0) {
Austin Schuh97789fc2020-08-01 14:42:45 -0700371 CHECK(CompareFlatBuffer(message_reader_->raw_log_file_header(),
372 log_file_header_))
Austin Schuhfa895892020-01-07 20:07:41 -0800373 << ": Header is different between log file chunks "
374 << filenames_[next_filename_index_] << " and "
375 << filenames_[next_filename_index_ - 1] << ", this is not supported.";
376 }
377
378 ++next_filename_index_;
379 return true;
380}
381
Austin Schuh6f3babe2020-01-26 20:34:50 -0800382bool SplitMessageReader::QueueMessages(
Austin Schuhcde938c2020-02-02 17:30:07 -0800383 monotonic_clock::time_point last_dequeued_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800384 // TODO(austin): Once we are happy that everything works, read a 256kb chunk
385 // to reduce the need to re-heap down below.
Austin Schuhcde938c2020-02-02 17:30:07 -0800386
387 // Special case no more data. Otherwise we blow up on the CHECK statement
388 // confirming that we have enough data queued.
389 if (at_end_) {
390 return false;
391 }
392
393 // If this isn't the first time around, confirm that we had enough data queued
394 // to follow the contract.
395 if (time_to_queue_ != monotonic_clock::min_time) {
396 CHECK_LE(last_dequeued_time,
397 newest_timestamp() - max_out_of_order_duration())
398 << " node " << FlatbufferToJson(node()) << " on " << this;
399
400 // Bail if there is enough data already queued.
401 if (last_dequeued_time < time_to_queue_) {
402 VLOG(1) << "All up to date on " << this << ", dequeued "
403 << last_dequeued_time << " queue time " << time_to_queue_;
404 return true;
405 }
406 } else {
407 // Startup takes a special dance. We want to queue up until the start time,
408 // but we then want to find the next message to read. The conservative
409 // answer is to immediately trigger a second requeue to get things moving.
410 time_to_queue_ = monotonic_start_time();
411 QueueMessages(time_to_queue_);
412 }
413
414 // If we are asked to queue, queue for at least max_out_of_order_duration past
415 // the last known time in the log file (ie the newest timestep read). As long
416 // as we requeue exactly when time_to_queue_ is dequeued and go no further, we
417 // are safe. And since we pop in order, that works.
418 //
419 // Special case the start of the log file. There should be at most 1 message
420 // from each channel at the start of the log file. So always force the start
421 // of the log file to just be read.
422 time_to_queue_ = std::max(time_to_queue_, newest_timestamp());
423 VLOG(1) << "Queueing, going until " << time_to_queue_ << " " << filename();
424
425 bool was_emplaced = false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800426 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800427 // Stop if we have enough.
Brian Silverman98360e22020-04-28 16:51:20 -0700428 if (newest_timestamp() > time_to_queue_ + max_out_of_order_duration() &&
Austin Schuhcde938c2020-02-02 17:30:07 -0800429 was_emplaced) {
430 VLOG(1) << "Done queueing on " << this << ", queued to "
431 << newest_timestamp() << " with requeue time " << time_to_queue_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800432 return true;
433 }
Austin Schuh05b70472020-01-01 17:11:17 -0800434
Austin Schuh6f3babe2020-01-26 20:34:50 -0800435 if (std::optional<FlatbufferVector<MessageHeader>> msg =
436 message_reader_->ReadMessage()) {
437 const MessageHeader &header = msg.value().message();
438
Austin Schuhcde938c2020-02-02 17:30:07 -0800439 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
440 chrono::nanoseconds(header.monotonic_sent_time()));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800441
Austin Schuh0b5fd032020-03-28 17:36:49 -0700442 if (VLOG_IS_ON(2)) {
443 LOG(INFO) << "Queued " << this << " " << filename()
444 << " ttq: " << time_to_queue_ << " now " << newest_timestamp()
445 << " start time " << monotonic_start_time() << " "
446 << FlatbufferToJson(&header);
447 } else if (VLOG_IS_ON(1)) {
448 FlatbufferVector<MessageHeader> copy = msg.value();
449 copy.mutable_message()->clear_data();
450 LOG(INFO) << "Queued " << this << " " << filename()
451 << " ttq: " << time_to_queue_ << " now " << newest_timestamp()
452 << " start time " << monotonic_start_time() << " "
453 << FlatbufferToJson(copy);
454 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800455
456 const int channel_index = header.channel_index();
457 was_emplaced = channels_to_write_[channel_index]->emplace_back(
458 std::move(msg.value()));
459 if (was_emplaced) {
460 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
461 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800462 } else {
463 if (!NextLogFile()) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800464 VLOG(1) << "End of log file " << filenames_.back();
Austin Schuhcde938c2020-02-02 17:30:07 -0800465 at_end_ = true;
Austin Schuh8bd96322020-02-13 21:18:22 -0800466 for (MessageHeaderQueue *queue : channels_to_write_) {
467 if (queue == nullptr || queue->timestamp_merger == nullptr) {
468 continue;
469 }
470 queue->timestamp_merger->NoticeAtEnd();
471 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800472 return false;
473 }
474 }
Austin Schuh05b70472020-01-01 17:11:17 -0800475 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800476}
477
478void SplitMessageReader::SetTimestampMerger(TimestampMerger *timestamp_merger,
479 int channel_index,
480 const Node *target_node) {
481 const Node *reinterpreted_target_node =
482 configuration::GetNodeOrDie(configuration(), target_node);
483 const Channel *const channel =
484 configuration()->channels()->Get(channel_index);
485
Austin Schuhcde938c2020-02-02 17:30:07 -0800486 VLOG(1) << " Configuring merger " << this << " for channel " << channel_index
487 << " "
488 << configuration::CleanedChannelToString(
489 configuration()->channels()->Get(channel_index));
490
Austin Schuh6f3babe2020-01-26 20:34:50 -0800491 MessageHeaderQueue *message_header_queue = nullptr;
492
493 // Figure out if this log file is from our point of view, or the other node's
494 // point of view.
495 if (node() == reinterpreted_target_node) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800496 VLOG(1) << " Replaying as logged node " << filename();
497
498 if (configuration::ChannelIsSendableOnNode(channel, node())) {
499 VLOG(1) << " Data on node";
500 message_header_queue = &(channels_[channel_index].data);
501 } else if (configuration::ChannelIsReadableOnNode(channel, node())) {
502 VLOG(1) << " Timestamps on node";
503 message_header_queue =
504 &(channels_[channel_index].timestamps[configuration::GetNodeIndex(
505 configuration(), node())]);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800506 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800507 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800508 }
509 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800510 VLOG(1) << " Replaying as other node " << filename();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800511 // We are replaying from another node's point of view. The only interesting
Austin Schuhcde938c2020-02-02 17:30:07 -0800512 // data is data that is sent from our node and received on theirs.
513 if (configuration::ChannelIsReadableOnNode(channel,
514 reinterpreted_target_node) &&
515 configuration::ChannelIsSendableOnNode(channel, node())) {
516 VLOG(1) << " Readable on target node";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800517 // Data from another node.
518 message_header_queue = &(channels_[channel_index].data);
519 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800520 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800521 // This is either not sendable on the other node, or is a timestamp and
522 // therefore not interesting.
523 }
524 }
525
526 // If we found one, write it down. This will be nullptr when there is nothing
527 // relevant on this channel on this node for the target node. In that case,
528 // we want to drop the message instead of queueing it.
529 if (message_header_queue != nullptr) {
530 message_header_queue->timestamp_merger = timestamp_merger;
531 }
532}
533
534std::tuple<monotonic_clock::time_point, uint32_t,
535 FlatbufferVector<MessageHeader>>
536SplitMessageReader::PopOldest(int channel_index) {
537 CHECK_GT(channels_[channel_index].data.size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800538 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
539 timestamp = channels_[channel_index].data.front_timestamp();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800540 FlatbufferVector<MessageHeader> front =
541 std::move(channels_[channel_index].data.front());
542 channels_[channel_index].data.pop_front();
Austin Schuhcde938c2020-02-02 17:30:07 -0800543
544 VLOG(1) << "Popped " << this << " " << std::get<0>(timestamp);
545
546 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800547
548 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
549 std::move(front));
550}
551
552std::tuple<monotonic_clock::time_point, uint32_t,
553 FlatbufferVector<MessageHeader>>
554SplitMessageReader::PopOldest(int channel, int node_index) {
555 CHECK_GT(channels_[channel].timestamps[node_index].size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800556 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
557 timestamp = channels_[channel].timestamps[node_index].front_timestamp();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800558 FlatbufferVector<MessageHeader> front =
559 std::move(channels_[channel].timestamps[node_index].front());
560 channels_[channel].timestamps[node_index].pop_front();
Austin Schuhcde938c2020-02-02 17:30:07 -0800561
562 VLOG(1) << "Popped " << this << " " << std::get<0>(timestamp);
563
564 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800565
566 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
567 std::move(front));
568}
569
Austin Schuhcde938c2020-02-02 17:30:07 -0800570bool SplitMessageReader::MessageHeaderQueue::emplace_back(
Austin Schuh6f3babe2020-01-26 20:34:50 -0800571 FlatbufferVector<MessageHeader> &&msg) {
572 CHECK(split_reader != nullptr);
573
574 // If there is no timestamp merger for this queue, nobody is listening. Drop
575 // the message. This happens when a log file from another node is replayed,
576 // and the timestamp mergers down stream just don't care.
577 if (timestamp_merger == nullptr) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800578 return false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800579 }
580
581 CHECK(timestamps != msg.message().has_data())
582 << ": Got timestamps and data mixed up on a node. "
583 << FlatbufferToJson(msg);
584
585 data_.emplace_back(std::move(msg));
586
587 if (data_.size() == 1u) {
588 // Yup, new data. Notify.
589 if (timestamps) {
590 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
591 } else {
592 timestamp_merger->Update(split_reader, front_timestamp());
593 }
594 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800595
596 return true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800597}
598
599void SplitMessageReader::MessageHeaderQueue::pop_front() {
600 data_.pop_front();
601 if (data_.size() != 0u) {
602 // Yup, new data.
603 if (timestamps) {
604 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
605 } else {
606 timestamp_merger->Update(split_reader, front_timestamp());
607 }
608 }
Austin Schuh05b70472020-01-01 17:11:17 -0800609}
610
611namespace {
612
Austin Schuh6f3babe2020-01-26 20:34:50 -0800613bool SplitMessageReaderHeapCompare(
614 const std::tuple<monotonic_clock::time_point, uint32_t,
615 SplitMessageReader *>
616 first,
617 const std::tuple<monotonic_clock::time_point, uint32_t,
618 SplitMessageReader *>
619 second) {
620 if (std::get<0>(first) > std::get<0>(second)) {
621 return true;
622 } else if (std::get<0>(first) == std::get<0>(second)) {
623 if (std::get<1>(first) > std::get<1>(second)) {
624 return true;
625 } else if (std::get<1>(first) == std::get<1>(second)) {
626 return std::get<2>(first) > std::get<2>(second);
627 } else {
628 return false;
629 }
630 } else {
631 return false;
632 }
633}
634
Austin Schuh05b70472020-01-01 17:11:17 -0800635bool ChannelHeapCompare(
636 const std::pair<monotonic_clock::time_point, int> first,
637 const std::pair<monotonic_clock::time_point, int> second) {
638 if (first.first > second.first) {
639 return true;
640 } else if (first.first == second.first) {
641 return first.second > second.second;
642 } else {
643 return false;
644 }
645}
646
647} // namespace
648
Austin Schuh6f3babe2020-01-26 20:34:50 -0800649TimestampMerger::TimestampMerger(
650 const Configuration *configuration,
651 std::vector<SplitMessageReader *> split_message_readers, int channel_index,
652 const Node *target_node, ChannelMerger *channel_merger)
653 : configuration_(configuration),
654 split_message_readers_(std::move(split_message_readers)),
655 channel_index_(channel_index),
656 node_index_(configuration::MultiNode(configuration)
657 ? configuration::GetNodeIndex(configuration, target_node)
658 : -1),
659 channel_merger_(channel_merger) {
660 // Tell the readers we care so they know who to notify.
Austin Schuhcde938c2020-02-02 17:30:07 -0800661 VLOG(1) << "Configuring channel " << channel_index << " target node "
662 << FlatbufferToJson(target_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800663 for (SplitMessageReader *reader : split_message_readers_) {
664 reader->SetTimestampMerger(this, channel_index, target_node);
665 }
666
667 // And then determine if we need to track timestamps.
668 const Channel *channel = configuration->channels()->Get(channel_index);
669 if (!configuration::ChannelIsSendableOnNode(channel, target_node) &&
670 configuration::ChannelIsReadableOnNode(channel, target_node)) {
671 has_timestamps_ = true;
672 }
673}
674
675void TimestampMerger::PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800676 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
677 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800678 SplitMessageReader *split_message_reader) {
679 DCHECK(std::find_if(message_heap_.begin(), message_heap_.end(),
680 [split_message_reader](
681 const std::tuple<monotonic_clock::time_point,
682 uint32_t, SplitMessageReader *>
683 x) {
684 return std::get<2>(x) == split_message_reader;
685 }) == message_heap_.end())
686 << ": Pushing message when it is already in the heap.";
687
688 message_heap_.push_back(std::make_tuple(
689 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
690
691 std::push_heap(message_heap_.begin(), message_heap_.end(),
692 &SplitMessageReaderHeapCompare);
693
694 // If we are just a data merger, don't wait for timestamps.
695 if (!has_timestamps_) {
696 channel_merger_->Update(std::get<0>(timestamp), channel_index_);
697 pushed_ = true;
698 }
699}
700
Austin Schuhcde938c2020-02-02 17:30:07 -0800701std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
702TimestampMerger::oldest_message() const {
703 CHECK_GT(message_heap_.size(), 0u);
704 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
705 oldest_message_reader = message_heap_.front();
706 return std::get<2>(oldest_message_reader)->oldest_message(channel_index_);
707}
708
709std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
710TimestampMerger::oldest_timestamp() const {
711 CHECK_GT(timestamp_heap_.size(), 0u);
712 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
713 oldest_message_reader = timestamp_heap_.front();
714 return std::get<2>(oldest_message_reader)
715 ->oldest_message(channel_index_, node_index_);
716}
717
Austin Schuh6f3babe2020-01-26 20:34:50 -0800718void TimestampMerger::PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800719 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
720 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800721 SplitMessageReader *split_message_reader) {
722 DCHECK(std::find_if(timestamp_heap_.begin(), timestamp_heap_.end(),
723 [split_message_reader](
724 const std::tuple<monotonic_clock::time_point,
725 uint32_t, SplitMessageReader *>
726 x) {
727 return std::get<2>(x) == split_message_reader;
728 }) == timestamp_heap_.end())
729 << ": Pushing timestamp when it is already in the heap.";
730
731 timestamp_heap_.push_back(std::make_tuple(
732 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
733
734 std::push_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
735 SplitMessageReaderHeapCompare);
736
737 // If we are a timestamp merger, don't wait for data. Missing data will be
738 // caught at read time.
739 if (has_timestamps_) {
740 channel_merger_->Update(std::get<0>(timestamp), channel_index_);
741 pushed_ = true;
742 }
743}
744
745std::tuple<monotonic_clock::time_point, uint32_t,
746 FlatbufferVector<MessageHeader>>
747TimestampMerger::PopMessageHeap() {
748 // Pop the oldest message reader pointer off the heap.
749 CHECK_GT(message_heap_.size(), 0u);
750 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
751 oldest_message_reader = message_heap_.front();
752
753 std::pop_heap(message_heap_.begin(), message_heap_.end(),
754 &SplitMessageReaderHeapCompare);
755 message_heap_.pop_back();
756
757 // Pop the oldest message. This re-pushes any messages from the reader to the
758 // message heap.
759 std::tuple<monotonic_clock::time_point, uint32_t,
760 FlatbufferVector<MessageHeader>>
761 oldest_message =
762 std::get<2>(oldest_message_reader)->PopOldest(channel_index_);
763
764 // Confirm that the time and queue_index we have recorded matches.
765 CHECK_EQ(std::get<0>(oldest_message), std::get<0>(oldest_message_reader));
766 CHECK_EQ(std::get<1>(oldest_message), std::get<1>(oldest_message_reader));
767
768 // Now, keep reading until we have found all duplicates.
769 while (message_heap_.size() > 0u) {
770 // See if it is a duplicate.
771 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
772 next_oldest_message_reader = message_heap_.front();
773
Austin Schuhcde938c2020-02-02 17:30:07 -0800774 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
775 next_oldest_message_time = std::get<2>(next_oldest_message_reader)
776 ->oldest_message(channel_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800777
778 if (std::get<0>(next_oldest_message_time) == std::get<0>(oldest_message) &&
779 std::get<1>(next_oldest_message_time) == std::get<1>(oldest_message)) {
780 // Pop the message reader pointer.
781 std::pop_heap(message_heap_.begin(), message_heap_.end(),
782 &SplitMessageReaderHeapCompare);
783 message_heap_.pop_back();
784
785 // Pop the next oldest message. This re-pushes any messages from the
786 // reader.
787 std::tuple<monotonic_clock::time_point, uint32_t,
788 FlatbufferVector<MessageHeader>>
789 next_oldest_message = std::get<2>(next_oldest_message_reader)
790 ->PopOldest(channel_index_);
791
792 // And make sure the message matches in it's entirety.
793 CHECK(std::get<2>(oldest_message).span() ==
794 std::get<2>(next_oldest_message).span())
795 << ": Data at the same timestamp doesn't match.";
796 } else {
797 break;
798 }
799 }
800
801 return oldest_message;
802}
803
804std::tuple<monotonic_clock::time_point, uint32_t,
805 FlatbufferVector<MessageHeader>>
806TimestampMerger::PopTimestampHeap() {
807 // Pop the oldest message reader pointer off the heap.
808 CHECK_GT(timestamp_heap_.size(), 0u);
809
810 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
811 oldest_timestamp_reader = timestamp_heap_.front();
812
813 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
814 &SplitMessageReaderHeapCompare);
815 timestamp_heap_.pop_back();
816
817 CHECK(node_index_ != -1) << ": Timestamps in a single node environment";
818
819 // Pop the oldest message. This re-pushes any timestamps from the reader to
820 // the timestamp heap.
821 std::tuple<monotonic_clock::time_point, uint32_t,
822 FlatbufferVector<MessageHeader>>
823 oldest_timestamp = std::get<2>(oldest_timestamp_reader)
824 ->PopOldest(channel_index_, node_index_);
825
826 // Confirm that the time we have recorded matches.
827 CHECK_EQ(std::get<0>(oldest_timestamp), std::get<0>(oldest_timestamp_reader));
828 CHECK_EQ(std::get<1>(oldest_timestamp), std::get<1>(oldest_timestamp_reader));
829
830 // TODO(austin): What if we get duplicate timestamps?
831
832 return oldest_timestamp;
833}
834
Austin Schuh8bd96322020-02-13 21:18:22 -0800835TimestampMerger::DeliveryTimestamp TimestampMerger::OldestTimestamp() const {
836 if (!has_timestamps_ || timestamp_heap_.size() == 0u) {
837 return TimestampMerger::DeliveryTimestamp{};
838 }
839
840 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
841 oldest_timestamp_reader = timestamp_heap_.front();
842
843 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
844 oldest_timestamp = std::get<2>(oldest_timestamp_reader)
845 ->oldest_message(channel_index_, node_index_);
846
847 TimestampMerger::DeliveryTimestamp timestamp;
848 timestamp.monotonic_event_time =
849 monotonic_clock::time_point(chrono::nanoseconds(
850 std::get<2>(oldest_timestamp)->monotonic_sent_time()));
851 timestamp.realtime_event_time = realtime_clock::time_point(
852 chrono::nanoseconds(std::get<2>(oldest_timestamp)->realtime_sent_time()));
853
854 timestamp.monotonic_remote_time =
855 monotonic_clock::time_point(chrono::nanoseconds(
856 std::get<2>(oldest_timestamp)->monotonic_remote_time()));
857 timestamp.realtime_remote_time =
858 realtime_clock::time_point(chrono::nanoseconds(
859 std::get<2>(oldest_timestamp)->realtime_remote_time()));
860
861 timestamp.remote_queue_index = std::get<2>(oldest_timestamp)->queue_index();
862 return timestamp;
863}
864
Austin Schuh6f3babe2020-01-26 20:34:50 -0800865std::tuple<TimestampMerger::DeliveryTimestamp, FlatbufferVector<MessageHeader>>
866TimestampMerger::PopOldest() {
867 if (has_timestamps_) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800868 // Read the timestamps.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800869 std::tuple<monotonic_clock::time_point, uint32_t,
870 FlatbufferVector<MessageHeader>>
871 oldest_timestamp = PopTimestampHeap();
872
873 TimestampMerger::DeliveryTimestamp timestamp;
874 timestamp.monotonic_event_time =
875 monotonic_clock::time_point(chrono::nanoseconds(
876 std::get<2>(oldest_timestamp).message().monotonic_sent_time()));
877 timestamp.realtime_event_time =
878 realtime_clock::time_point(chrono::nanoseconds(
879 std::get<2>(oldest_timestamp).message().realtime_sent_time()));
880
881 // Consistency check.
882 CHECK_EQ(timestamp.monotonic_event_time, std::get<0>(oldest_timestamp));
883 CHECK_EQ(std::get<2>(oldest_timestamp).message().queue_index(),
884 std::get<1>(oldest_timestamp));
885
886 monotonic_clock::time_point remote_timestamp_monotonic_time(
887 chrono::nanoseconds(
888 std::get<2>(oldest_timestamp).message().monotonic_remote_time()));
889
Austin Schuh8bd96322020-02-13 21:18:22 -0800890 // See if we have any data. If not, pass the problem up the chain.
891 if (message_heap_.size() == 0u) {
892 VLOG(1) << "No data to match timestamp on "
893 << configuration::CleanedChannelToString(
894 configuration_->channels()->Get(channel_index_));
895 return std::make_tuple(timestamp,
896 std::move(std::get<2>(oldest_timestamp)));
897 }
898
Austin Schuh6f3babe2020-01-26 20:34:50 -0800899 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800900 {
901 // Ok, now try grabbing data until we find one which matches.
902 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
903 oldest_message_ref = oldest_message();
904
905 // Time at which the message was sent (this message is written from the
906 // sending node's perspective.
907 monotonic_clock::time_point remote_monotonic_time(chrono::nanoseconds(
908 std::get<2>(oldest_message_ref)->monotonic_sent_time()));
909
910 if (remote_monotonic_time < remote_timestamp_monotonic_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800911 VLOG(1) << "Undelivered message, skipping. Remote time is "
912 << remote_monotonic_time << " timestamp is "
913 << remote_timestamp_monotonic_time << " on channel "
914 << channel_index_;
Austin Schuhcde938c2020-02-02 17:30:07 -0800915 PopMessageHeap();
916 continue;
917 } else if (remote_monotonic_time > remote_timestamp_monotonic_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800918 VLOG(1) << "Data not found. Remote time should be "
919 << remote_timestamp_monotonic_time << " on channel "
920 << channel_index_;
Austin Schuhcde938c2020-02-02 17:30:07 -0800921 return std::make_tuple(timestamp,
922 std::move(std::get<2>(oldest_timestamp)));
923 }
924
925 timestamp.monotonic_remote_time = remote_monotonic_time;
926 }
927
Austin Schuh6f3babe2020-01-26 20:34:50 -0800928 std::tuple<monotonic_clock::time_point, uint32_t,
929 FlatbufferVector<MessageHeader>>
930 oldest_message = PopMessageHeap();
931
Austin Schuh6f3babe2020-01-26 20:34:50 -0800932 timestamp.realtime_remote_time =
933 realtime_clock::time_point(chrono::nanoseconds(
934 std::get<2>(oldest_message).message().realtime_sent_time()));
935 timestamp.remote_queue_index =
936 std::get<2>(oldest_message).message().queue_index();
937
Austin Schuhcde938c2020-02-02 17:30:07 -0800938 CHECK_EQ(timestamp.monotonic_remote_time,
939 remote_timestamp_monotonic_time);
940
941 CHECK_EQ(timestamp.remote_queue_index,
942 std::get<2>(oldest_timestamp).message().remote_queue_index())
943 << ": " << FlatbufferToJson(&std::get<2>(oldest_timestamp).message())
944 << " data "
945 << FlatbufferToJson(&std::get<2>(oldest_message).message());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800946
947 return std::make_tuple(timestamp, std::get<2>(oldest_message));
948 }
949 } else {
950 std::tuple<monotonic_clock::time_point, uint32_t,
951 FlatbufferVector<MessageHeader>>
952 oldest_message = PopMessageHeap();
953
954 TimestampMerger::DeliveryTimestamp timestamp;
955 timestamp.monotonic_event_time =
956 monotonic_clock::time_point(chrono::nanoseconds(
957 std::get<2>(oldest_message).message().monotonic_sent_time()));
958 timestamp.realtime_event_time =
959 realtime_clock::time_point(chrono::nanoseconds(
960 std::get<2>(oldest_message).message().realtime_sent_time()));
961 timestamp.remote_queue_index = 0xffffffff;
962
963 CHECK_EQ(std::get<0>(oldest_message), timestamp.monotonic_event_time);
964 CHECK_EQ(std::get<1>(oldest_message),
965 std::get<2>(oldest_message).message().queue_index());
966
967 return std::make_tuple(timestamp, std::get<2>(oldest_message));
968 }
969}
970
Austin Schuh8bd96322020-02-13 21:18:22 -0800971void TimestampMerger::NoticeAtEnd() { channel_merger_->NoticeAtEnd(); }
972
Austin Schuh6f3babe2020-01-26 20:34:50 -0800973namespace {
974std::vector<std::unique_ptr<SplitMessageReader>> MakeSplitMessageReaders(
975 const std::vector<std::vector<std::string>> &filenames) {
976 CHECK_GT(filenames.size(), 0u);
977 // Build up all the SplitMessageReaders.
978 std::vector<std::unique_ptr<SplitMessageReader>> result;
979 for (const std::vector<std::string> &filenames : filenames) {
980 result.emplace_back(std::make_unique<SplitMessageReader>(filenames));
981 }
982 return result;
983}
984} // namespace
985
986ChannelMerger::ChannelMerger(
987 const std::vector<std::vector<std::string>> &filenames)
988 : split_message_readers_(MakeSplitMessageReaders(filenames)),
Austin Schuh97789fc2020-08-01 14:42:45 -0700989 log_file_header_(split_message_readers_[0]->raw_log_file_header()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800990 // Now, confirm that the configuration matches for each and pick a start time.
991 // Also return the list of possible nodes.
992 for (const std::unique_ptr<SplitMessageReader> &reader :
993 split_message_readers_) {
994 CHECK(CompareFlatBuffer(log_file_header_.message().configuration(),
995 reader->log_file_header()->configuration()))
996 << ": Replaying log files with different configurations isn't "
997 "supported";
998 }
999
1000 nodes_ = configuration::GetNodes(configuration());
1001}
1002
1003bool ChannelMerger::SetNode(const Node *target_node) {
1004 std::vector<SplitMessageReader *> split_message_readers;
1005 for (const std::unique_ptr<SplitMessageReader> &reader :
1006 split_message_readers_) {
1007 split_message_readers.emplace_back(reader.get());
1008 }
1009
1010 // Go find a log_file_header for this node.
1011 {
1012 bool found_node = false;
1013
1014 for (const std::unique_ptr<SplitMessageReader> &reader :
1015 split_message_readers_) {
James Kuszmaulfc273dc2020-05-09 17:56:19 -07001016 // In order to identify which logfile(s) map to the target node, do a
1017 // logical comparison of the nodes, by confirming that we are either in a
1018 // single-node setup (where the nodes will both be nullptr) or that the
1019 // node names match (but the other node fields--e.g., hostname lists--may
1020 // not).
1021 const bool both_null =
1022 reader->node() == nullptr && target_node == nullptr;
1023 const bool both_have_name =
1024 (reader->node() != nullptr) && (target_node != nullptr) &&
1025 (reader->node()->has_name() && target_node->has_name());
1026 const bool node_names_identical =
1027 both_have_name &&
1028 (reader->node()->name()->string_view() ==
1029 target_node->name()->string_view());
1030 if (both_null || node_names_identical) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001031 if (!found_node) {
1032 found_node = true;
1033 log_file_header_ = CopyFlatBuffer(reader->log_file_header());
Austin Schuhcde938c2020-02-02 17:30:07 -08001034 VLOG(1) << "Found log file " << reader->filename() << " with node "
1035 << FlatbufferToJson(reader->node()) << " start_time "
1036 << monotonic_start_time();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001037 } else {
1038 // And then make sure all the other files have matching headers.
Austin Schuhcde938c2020-02-02 17:30:07 -08001039 CHECK(CompareFlatBuffer(log_file_header(), reader->log_file_header()))
1040 << ": " << FlatbufferToJson(log_file_header()) << " reader "
1041 << FlatbufferToJson(reader->log_file_header());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001042 }
1043 }
1044 }
1045
1046 if (!found_node) {
1047 LOG(WARNING) << "Failed to find log file for node "
1048 << FlatbufferToJson(target_node);
1049 return false;
1050 }
1051 }
1052
1053 // Build up all the timestamp mergers. This connects up all the
1054 // SplitMessageReaders.
1055 timestamp_mergers_.reserve(configuration()->channels()->size());
1056 for (size_t channel_index = 0;
1057 channel_index < configuration()->channels()->size(); ++channel_index) {
1058 timestamp_mergers_.emplace_back(
1059 configuration(), split_message_readers, channel_index,
1060 configuration::GetNode(configuration(), target_node), this);
1061 }
1062
1063 // And prime everything.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001064 for (std::unique_ptr<SplitMessageReader> &split_message_reader :
1065 split_message_readers_) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001066 split_message_reader->QueueMessages(
1067 split_message_reader->monotonic_start_time());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001068 }
1069
1070 node_ = configuration::GetNodeOrDie(configuration(), target_node);
1071 return true;
1072}
1073
1074monotonic_clock::time_point ChannelMerger::OldestMessage() const {
1075 if (channel_heap_.size() == 0u) {
1076 return monotonic_clock::max_time;
1077 }
1078 return channel_heap_.front().first;
1079}
1080
Austin Schuh8bd96322020-02-13 21:18:22 -08001081TimestampMerger::DeliveryTimestamp ChannelMerger::OldestTimestamp() const {
1082 if (timestamp_heap_.size() == 0u) {
1083 return TimestampMerger::DeliveryTimestamp{};
1084 }
1085 return timestamp_mergers_[timestamp_heap_.front().second].OldestTimestamp();
1086}
1087
1088TimestampMerger::DeliveryTimestamp ChannelMerger::OldestTimestampForChannel(
1089 int channel) const {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001090 // If we didn't find any data for this node, we won't have any mergers. Return
1091 // an invalid timestamp in that case.
1092 if (timestamp_mergers_.size() <= static_cast<size_t>(channel)) {
1093 TimestampMerger::DeliveryTimestamp result;
1094 return result;
1095 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001096 return timestamp_mergers_[channel].OldestTimestamp();
1097}
1098
Austin Schuh6f3babe2020-01-26 20:34:50 -08001099void ChannelMerger::PushChannelHeap(monotonic_clock::time_point timestamp,
1100 int channel_index) {
1101 // Pop and recreate the heap if it has already been pushed. And since we are
1102 // pushing again, we don't need to clear pushed.
1103 if (timestamp_mergers_[channel_index].pushed()) {
1104 channel_heap_.erase(std::find_if(
1105 channel_heap_.begin(), channel_heap_.end(),
1106 [channel_index](const std::pair<monotonic_clock::time_point, int> x) {
1107 return x.second == channel_index;
1108 }));
1109 std::make_heap(channel_heap_.begin(), channel_heap_.end(),
1110 ChannelHeapCompare);
Austin Schuh8bd96322020-02-13 21:18:22 -08001111
1112 if (timestamp_mergers_[channel_index].has_timestamps()) {
1113 timestamp_heap_.erase(std::find_if(
1114 timestamp_heap_.begin(), timestamp_heap_.end(),
1115 [channel_index](const std::pair<monotonic_clock::time_point, int> x) {
1116 return x.second == channel_index;
1117 }));
1118 std::make_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1119 ChannelHeapCompare);
1120 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001121 }
1122
Austin Schuh05b70472020-01-01 17:11:17 -08001123 channel_heap_.push_back(std::make_pair(timestamp, channel_index));
1124
1125 // The default sort puts the newest message first. Use a custom comparator to
1126 // put the oldest message first.
1127 std::push_heap(channel_heap_.begin(), channel_heap_.end(),
1128 ChannelHeapCompare);
Austin Schuh8bd96322020-02-13 21:18:22 -08001129
1130 if (timestamp_mergers_[channel_index].has_timestamps()) {
1131 timestamp_heap_.push_back(std::make_pair(timestamp, channel_index));
1132 std::push_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1133 ChannelHeapCompare);
1134 }
Austin Schuh05b70472020-01-01 17:11:17 -08001135}
1136
Austin Schuh6f3babe2020-01-26 20:34:50 -08001137std::tuple<TimestampMerger::DeliveryTimestamp, int,
1138 FlatbufferVector<MessageHeader>>
1139ChannelMerger::PopOldest() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001140 CHECK_GT(channel_heap_.size(), 0u);
Austin Schuh05b70472020-01-01 17:11:17 -08001141 std::pair<monotonic_clock::time_point, int> oldest_channel_data =
1142 channel_heap_.front();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001143 int channel_index = oldest_channel_data.second;
Austin Schuh05b70472020-01-01 17:11:17 -08001144 std::pop_heap(channel_heap_.begin(), channel_heap_.end(),
1145 &ChannelHeapCompare);
1146 channel_heap_.pop_back();
Austin Schuh8bd96322020-02-13 21:18:22 -08001147
Austin Schuh6f3babe2020-01-26 20:34:50 -08001148 timestamp_mergers_[channel_index].set_pushed(false);
Austin Schuh05b70472020-01-01 17:11:17 -08001149
Austin Schuh6f3babe2020-01-26 20:34:50 -08001150 TimestampMerger *merger = &timestamp_mergers_[channel_index];
Austin Schuh05b70472020-01-01 17:11:17 -08001151
Austin Schuh8bd96322020-02-13 21:18:22 -08001152 if (merger->has_timestamps()) {
1153 CHECK_GT(timestamp_heap_.size(), 0u);
1154 std::pair<monotonic_clock::time_point, int> oldest_timestamp_data =
1155 timestamp_heap_.front();
1156 CHECK(oldest_timestamp_data == oldest_channel_data)
1157 << ": Timestamp heap out of sync.";
1158 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1159 &ChannelHeapCompare);
1160 timestamp_heap_.pop_back();
1161 }
1162
Austin Schuhcde938c2020-02-02 17:30:07 -08001163 // Merger handles any queueing needed from here.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001164 std::tuple<TimestampMerger::DeliveryTimestamp,
1165 FlatbufferVector<MessageHeader>>
1166 message = merger->PopOldest();
Austin Schuh05b70472020-01-01 17:11:17 -08001167
Austin Schuh6f3babe2020-01-26 20:34:50 -08001168 return std::make_tuple(std::get<0>(message), channel_index,
1169 std::move(std::get<1>(message)));
1170}
1171
Austin Schuhcde938c2020-02-02 17:30:07 -08001172std::string SplitMessageReader::MessageHeaderQueue::DebugString() const {
1173 std::stringstream ss;
1174 for (size_t i = 0; i < data_.size(); ++i) {
1175 if (timestamps) {
1176 ss << " msg: ";
1177 } else {
1178 ss << " timestamp: ";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001179 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001180 ss << monotonic_clock::time_point(std::chrono::nanoseconds(
1181 data_[i].message().monotonic_sent_time()))
1182 << " ("
1183 << realtime_clock::time_point(
1184 std::chrono::nanoseconds(data_[i].message().realtime_sent_time()))
1185 << ") " << data_[i].message().queue_index();
1186 if (timestamps) {
1187 ss << " <- remote "
1188 << monotonic_clock::time_point(std::chrono::nanoseconds(
1189 data_[i].message().monotonic_remote_time()))
1190 << " ("
1191 << realtime_clock::time_point(std::chrono::nanoseconds(
1192 data_[i].message().realtime_remote_time()))
1193 << ")";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001194 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001195 ss << "\n";
1196 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001197
Austin Schuhcde938c2020-02-02 17:30:07 -08001198 return ss.str();
1199}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001200
Austin Schuhcde938c2020-02-02 17:30:07 -08001201std::string SplitMessageReader::DebugString(int channel) const {
1202 std::stringstream ss;
1203 ss << "[\n";
1204 ss << channels_[channel].data.DebugString();
1205 ss << " ]";
1206 return ss.str();
1207}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001208
Austin Schuhcde938c2020-02-02 17:30:07 -08001209std::string SplitMessageReader::DebugString(int channel, int node_index) const {
1210 std::stringstream ss;
1211 ss << "[\n";
1212 ss << channels_[channel].timestamps[node_index].DebugString();
1213 ss << " ]";
1214 return ss.str();
1215}
1216
1217std::string TimestampMerger::DebugString() const {
1218 std::stringstream ss;
1219
1220 if (timestamp_heap_.size() > 0) {
1221 ss << " timestamp_heap {\n";
1222 std::vector<
1223 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1224 timestamp_heap = timestamp_heap_;
1225 while (timestamp_heap.size() > 0u) {
1226 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1227 oldest_timestamp_reader = timestamp_heap.front();
1228
1229 ss << " " << std::get<2>(oldest_timestamp_reader) << " "
1230 << std::get<0>(oldest_timestamp_reader) << " queue_index ("
1231 << std::get<1>(oldest_timestamp_reader) << ") ttq "
1232 << std::get<2>(oldest_timestamp_reader)->time_to_queue() << " "
1233 << std::get<2>(oldest_timestamp_reader)->filename() << " -> "
1234 << std::get<2>(oldest_timestamp_reader)
1235 ->DebugString(channel_index_, node_index_)
1236 << "\n";
1237
1238 std::pop_heap(timestamp_heap.begin(), timestamp_heap.end(),
1239 &SplitMessageReaderHeapCompare);
1240 timestamp_heap.pop_back();
1241 }
1242 ss << " }\n";
1243 }
1244
1245 ss << " message_heap {\n";
1246 {
1247 std::vector<
1248 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1249 message_heap = message_heap_;
1250 while (message_heap.size() > 0u) {
1251 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1252 oldest_message_reader = message_heap.front();
1253
1254 ss << " " << std::get<2>(oldest_message_reader) << " "
1255 << std::get<0>(oldest_message_reader) << " queue_index ("
1256 << std::get<1>(oldest_message_reader) << ") ttq "
1257 << std::get<2>(oldest_message_reader)->time_to_queue() << " "
1258 << std::get<2>(oldest_message_reader)->filename() << " -> "
1259 << std::get<2>(oldest_message_reader)->DebugString(channel_index_)
1260 << "\n";
1261
1262 std::pop_heap(message_heap.begin(), message_heap.end(),
1263 &SplitMessageReaderHeapCompare);
1264 message_heap.pop_back();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001265 }
Austin Schuh05b70472020-01-01 17:11:17 -08001266 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001267 ss << " }";
1268
1269 return ss.str();
1270}
1271
1272std::string ChannelMerger::DebugString() const {
1273 std::stringstream ss;
1274 ss << "start_time " << realtime_start_time() << " " << monotonic_start_time()
1275 << "\n";
1276 ss << "channel_heap {\n";
1277 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap =
1278 channel_heap_;
1279 while (channel_heap.size() > 0u) {
1280 std::tuple<monotonic_clock::time_point, int> channel = channel_heap.front();
1281 ss << " " << std::get<0>(channel) << " (" << std::get<1>(channel) << ") "
1282 << configuration::CleanedChannelToString(
1283 configuration()->channels()->Get(std::get<1>(channel)))
1284 << "\n";
1285
1286 ss << timestamp_mergers_[std::get<1>(channel)].DebugString() << "\n";
1287
1288 std::pop_heap(channel_heap.begin(), channel_heap.end(),
1289 &ChannelHeapCompare);
1290 channel_heap.pop_back();
1291 }
1292 ss << "}";
1293
1294 return ss.str();
Austin Schuh05b70472020-01-01 17:11:17 -08001295}
1296
Austin Schuha36c8902019-12-30 18:07:15 -08001297} // namespace logger
1298} // namespace aos