blob: 7125bda3234f87963f9bd8d83c80c7ffd59a56b8 [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()) {
Brian Silverman8a32ce62020-08-12 12:02:38 -0700464 VLOG(1) << "No more files, last was " << 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
Brian Silverman8a32ce62020-08-12 12:02:38 -0700544 VLOG(1) << "Popped " << this << " " << std::get<0>(timestamp) << " for "
545 << channel_index;
Austin Schuhcde938c2020-02-02 17:30:07 -0800546
547 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800548
549 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
550 std::move(front));
551}
552
553std::tuple<monotonic_clock::time_point, uint32_t,
554 FlatbufferVector<MessageHeader>>
555SplitMessageReader::PopOldest(int channel, int node_index) {
556 CHECK_GT(channels_[channel].timestamps[node_index].size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800557 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
558 timestamp = channels_[channel].timestamps[node_index].front_timestamp();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800559 FlatbufferVector<MessageHeader> front =
560 std::move(channels_[channel].timestamps[node_index].front());
561 channels_[channel].timestamps[node_index].pop_front();
Austin Schuhcde938c2020-02-02 17:30:07 -0800562
Brian Silverman8a32ce62020-08-12 12:02:38 -0700563 VLOG(1) << "Popped " << this << " " << std::get<0>(timestamp) << " for "
564 << channel << " on " << node_index;
Austin Schuhcde938c2020-02-02 17:30:07 -0800565
566 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800567
568 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
569 std::move(front));
570}
571
Austin Schuhcde938c2020-02-02 17:30:07 -0800572bool SplitMessageReader::MessageHeaderQueue::emplace_back(
Austin Schuh6f3babe2020-01-26 20:34:50 -0800573 FlatbufferVector<MessageHeader> &&msg) {
574 CHECK(split_reader != nullptr);
575
576 // If there is no timestamp merger for this queue, nobody is listening. Drop
577 // the message. This happens when a log file from another node is replayed,
578 // and the timestamp mergers down stream just don't care.
579 if (timestamp_merger == nullptr) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800580 return false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800581 }
582
583 CHECK(timestamps != msg.message().has_data())
584 << ": Got timestamps and data mixed up on a node. "
585 << FlatbufferToJson(msg);
586
587 data_.emplace_back(std::move(msg));
588
589 if (data_.size() == 1u) {
590 // Yup, new data. Notify.
591 if (timestamps) {
592 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
593 } else {
594 timestamp_merger->Update(split_reader, front_timestamp());
595 }
596 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800597
598 return true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800599}
600
601void SplitMessageReader::MessageHeaderQueue::pop_front() {
602 data_.pop_front();
603 if (data_.size() != 0u) {
604 // Yup, new data.
605 if (timestamps) {
606 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
607 } else {
608 timestamp_merger->Update(split_reader, front_timestamp());
609 }
610 }
Austin Schuh05b70472020-01-01 17:11:17 -0800611}
612
613namespace {
614
Austin Schuh6f3babe2020-01-26 20:34:50 -0800615bool SplitMessageReaderHeapCompare(
616 const std::tuple<monotonic_clock::time_point, uint32_t,
617 SplitMessageReader *>
618 first,
619 const std::tuple<monotonic_clock::time_point, uint32_t,
620 SplitMessageReader *>
621 second) {
622 if (std::get<0>(first) > std::get<0>(second)) {
623 return true;
624 } else if (std::get<0>(first) == std::get<0>(second)) {
625 if (std::get<1>(first) > std::get<1>(second)) {
626 return true;
627 } else if (std::get<1>(first) == std::get<1>(second)) {
628 return std::get<2>(first) > std::get<2>(second);
629 } else {
630 return false;
631 }
632 } else {
633 return false;
634 }
635}
636
Austin Schuh05b70472020-01-01 17:11:17 -0800637bool ChannelHeapCompare(
638 const std::pair<monotonic_clock::time_point, int> first,
639 const std::pair<monotonic_clock::time_point, int> second) {
640 if (first.first > second.first) {
641 return true;
642 } else if (first.first == second.first) {
643 return first.second > second.second;
644 } else {
645 return false;
646 }
647}
648
649} // namespace
650
Austin Schuh6f3babe2020-01-26 20:34:50 -0800651TimestampMerger::TimestampMerger(
652 const Configuration *configuration,
653 std::vector<SplitMessageReader *> split_message_readers, int channel_index,
654 const Node *target_node, ChannelMerger *channel_merger)
655 : configuration_(configuration),
656 split_message_readers_(std::move(split_message_readers)),
657 channel_index_(channel_index),
658 node_index_(configuration::MultiNode(configuration)
659 ? configuration::GetNodeIndex(configuration, target_node)
660 : -1),
661 channel_merger_(channel_merger) {
662 // Tell the readers we care so they know who to notify.
Austin Schuhcde938c2020-02-02 17:30:07 -0800663 VLOG(1) << "Configuring channel " << channel_index << " target node "
664 << FlatbufferToJson(target_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800665 for (SplitMessageReader *reader : split_message_readers_) {
666 reader->SetTimestampMerger(this, channel_index, target_node);
667 }
668
669 // And then determine if we need to track timestamps.
670 const Channel *channel = configuration->channels()->Get(channel_index);
671 if (!configuration::ChannelIsSendableOnNode(channel, target_node) &&
672 configuration::ChannelIsReadableOnNode(channel, target_node)) {
673 has_timestamps_ = true;
674 }
675}
676
677void TimestampMerger::PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800678 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
679 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800680 SplitMessageReader *split_message_reader) {
681 DCHECK(std::find_if(message_heap_.begin(), message_heap_.end(),
682 [split_message_reader](
683 const std::tuple<monotonic_clock::time_point,
684 uint32_t, SplitMessageReader *>
685 x) {
686 return std::get<2>(x) == split_message_reader;
687 }) == message_heap_.end())
688 << ": Pushing message when it is already in the heap.";
689
690 message_heap_.push_back(std::make_tuple(
691 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
692
693 std::push_heap(message_heap_.begin(), message_heap_.end(),
694 &SplitMessageReaderHeapCompare);
695
696 // If we are just a data merger, don't wait for timestamps.
697 if (!has_timestamps_) {
Brian Silverman8a32ce62020-08-12 12:02:38 -0700698 channel_merger_->Update(std::get<0>(message_heap_[0]), channel_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800699 pushed_ = true;
700 }
701}
702
Austin Schuhcde938c2020-02-02 17:30:07 -0800703std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
704TimestampMerger::oldest_message() const {
705 CHECK_GT(message_heap_.size(), 0u);
706 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
707 oldest_message_reader = message_heap_.front();
708 return std::get<2>(oldest_message_reader)->oldest_message(channel_index_);
709}
710
711std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
712TimestampMerger::oldest_timestamp() const {
713 CHECK_GT(timestamp_heap_.size(), 0u);
714 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
715 oldest_message_reader = timestamp_heap_.front();
716 return std::get<2>(oldest_message_reader)
717 ->oldest_message(channel_index_, node_index_);
718}
719
Austin Schuh6f3babe2020-01-26 20:34:50 -0800720void TimestampMerger::PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800721 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
722 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800723 SplitMessageReader *split_message_reader) {
724 DCHECK(std::find_if(timestamp_heap_.begin(), timestamp_heap_.end(),
725 [split_message_reader](
726 const std::tuple<monotonic_clock::time_point,
727 uint32_t, SplitMessageReader *>
728 x) {
729 return std::get<2>(x) == split_message_reader;
730 }) == timestamp_heap_.end())
731 << ": Pushing timestamp when it is already in the heap.";
732
733 timestamp_heap_.push_back(std::make_tuple(
734 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
735
736 std::push_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
737 SplitMessageReaderHeapCompare);
738
739 // If we are a timestamp merger, don't wait for data. Missing data will be
740 // caught at read time.
741 if (has_timestamps_) {
Brian Silverman8a32ce62020-08-12 12:02:38 -0700742 channel_merger_->Update(std::get<0>(timestamp_heap_[0]), channel_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800743 pushed_ = true;
744 }
745}
746
747std::tuple<monotonic_clock::time_point, uint32_t,
748 FlatbufferVector<MessageHeader>>
749TimestampMerger::PopMessageHeap() {
750 // Pop the oldest message reader pointer off the heap.
751 CHECK_GT(message_heap_.size(), 0u);
752 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
753 oldest_message_reader = message_heap_.front();
754
755 std::pop_heap(message_heap_.begin(), message_heap_.end(),
756 &SplitMessageReaderHeapCompare);
757 message_heap_.pop_back();
758
759 // Pop the oldest message. This re-pushes any messages from the reader to the
760 // message heap.
761 std::tuple<monotonic_clock::time_point, uint32_t,
762 FlatbufferVector<MessageHeader>>
763 oldest_message =
764 std::get<2>(oldest_message_reader)->PopOldest(channel_index_);
765
766 // Confirm that the time and queue_index we have recorded matches.
767 CHECK_EQ(std::get<0>(oldest_message), std::get<0>(oldest_message_reader));
768 CHECK_EQ(std::get<1>(oldest_message), std::get<1>(oldest_message_reader));
769
770 // Now, keep reading until we have found all duplicates.
Brian Silverman8a32ce62020-08-12 12:02:38 -0700771 while (!message_heap_.empty()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800772 // See if it is a duplicate.
773 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
774 next_oldest_message_reader = message_heap_.front();
775
Austin Schuhcde938c2020-02-02 17:30:07 -0800776 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
777 next_oldest_message_time = std::get<2>(next_oldest_message_reader)
778 ->oldest_message(channel_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800779
780 if (std::get<0>(next_oldest_message_time) == std::get<0>(oldest_message) &&
781 std::get<1>(next_oldest_message_time) == std::get<1>(oldest_message)) {
782 // Pop the message reader pointer.
783 std::pop_heap(message_heap_.begin(), message_heap_.end(),
784 &SplitMessageReaderHeapCompare);
785 message_heap_.pop_back();
786
787 // Pop the next oldest message. This re-pushes any messages from the
788 // reader.
789 std::tuple<monotonic_clock::time_point, uint32_t,
790 FlatbufferVector<MessageHeader>>
791 next_oldest_message = std::get<2>(next_oldest_message_reader)
792 ->PopOldest(channel_index_);
793
794 // And make sure the message matches in it's entirety.
795 CHECK(std::get<2>(oldest_message).span() ==
796 std::get<2>(next_oldest_message).span())
797 << ": Data at the same timestamp doesn't match.";
798 } else {
799 break;
800 }
801 }
802
803 return oldest_message;
804}
805
806std::tuple<monotonic_clock::time_point, uint32_t,
807 FlatbufferVector<MessageHeader>>
808TimestampMerger::PopTimestampHeap() {
809 // Pop the oldest message reader pointer off the heap.
810 CHECK_GT(timestamp_heap_.size(), 0u);
811
812 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
813 oldest_timestamp_reader = timestamp_heap_.front();
814
815 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
816 &SplitMessageReaderHeapCompare);
817 timestamp_heap_.pop_back();
818
819 CHECK(node_index_ != -1) << ": Timestamps in a single node environment";
820
821 // Pop the oldest message. This re-pushes any timestamps from the reader to
822 // the timestamp heap.
823 std::tuple<monotonic_clock::time_point, uint32_t,
824 FlatbufferVector<MessageHeader>>
825 oldest_timestamp = std::get<2>(oldest_timestamp_reader)
826 ->PopOldest(channel_index_, node_index_);
827
828 // Confirm that the time we have recorded matches.
829 CHECK_EQ(std::get<0>(oldest_timestamp), std::get<0>(oldest_timestamp_reader));
830 CHECK_EQ(std::get<1>(oldest_timestamp), std::get<1>(oldest_timestamp_reader));
831
832 // TODO(austin): What if we get duplicate timestamps?
833
834 return oldest_timestamp;
835}
836
Austin Schuh8bd96322020-02-13 21:18:22 -0800837TimestampMerger::DeliveryTimestamp TimestampMerger::OldestTimestamp() const {
838 if (!has_timestamps_ || timestamp_heap_.size() == 0u) {
839 return TimestampMerger::DeliveryTimestamp{};
840 }
841
842 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
843 oldest_timestamp_reader = timestamp_heap_.front();
844
845 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
846 oldest_timestamp = std::get<2>(oldest_timestamp_reader)
847 ->oldest_message(channel_index_, node_index_);
848
849 TimestampMerger::DeliveryTimestamp timestamp;
850 timestamp.monotonic_event_time =
851 monotonic_clock::time_point(chrono::nanoseconds(
852 std::get<2>(oldest_timestamp)->monotonic_sent_time()));
853 timestamp.realtime_event_time = realtime_clock::time_point(
854 chrono::nanoseconds(std::get<2>(oldest_timestamp)->realtime_sent_time()));
855
856 timestamp.monotonic_remote_time =
857 monotonic_clock::time_point(chrono::nanoseconds(
858 std::get<2>(oldest_timestamp)->monotonic_remote_time()));
859 timestamp.realtime_remote_time =
860 realtime_clock::time_point(chrono::nanoseconds(
861 std::get<2>(oldest_timestamp)->realtime_remote_time()));
862
863 timestamp.remote_queue_index = std::get<2>(oldest_timestamp)->queue_index();
864 return timestamp;
865}
866
Austin Schuh6f3babe2020-01-26 20:34:50 -0800867std::tuple<TimestampMerger::DeliveryTimestamp, FlatbufferVector<MessageHeader>>
868TimestampMerger::PopOldest() {
869 if (has_timestamps_) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800870 // Read the timestamps.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800871 std::tuple<monotonic_clock::time_point, uint32_t,
872 FlatbufferVector<MessageHeader>>
873 oldest_timestamp = PopTimestampHeap();
874
875 TimestampMerger::DeliveryTimestamp timestamp;
876 timestamp.monotonic_event_time =
877 monotonic_clock::time_point(chrono::nanoseconds(
878 std::get<2>(oldest_timestamp).message().monotonic_sent_time()));
879 timestamp.realtime_event_time =
880 realtime_clock::time_point(chrono::nanoseconds(
881 std::get<2>(oldest_timestamp).message().realtime_sent_time()));
882
883 // Consistency check.
884 CHECK_EQ(timestamp.monotonic_event_time, std::get<0>(oldest_timestamp));
885 CHECK_EQ(std::get<2>(oldest_timestamp).message().queue_index(),
886 std::get<1>(oldest_timestamp));
887
888 monotonic_clock::time_point remote_timestamp_monotonic_time(
889 chrono::nanoseconds(
890 std::get<2>(oldest_timestamp).message().monotonic_remote_time()));
891
Austin Schuh8bd96322020-02-13 21:18:22 -0800892 // See if we have any data. If not, pass the problem up the chain.
Brian Silverman8a32ce62020-08-12 12:02:38 -0700893 if (message_heap_.empty()) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800894 VLOG(1) << "No data to match timestamp on "
895 << configuration::CleanedChannelToString(
896 configuration_->channels()->Get(channel_index_));
897 return std::make_tuple(timestamp,
898 std::move(std::get<2>(oldest_timestamp)));
899 }
900
Austin Schuh6f3babe2020-01-26 20:34:50 -0800901 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800902 {
903 // Ok, now try grabbing data until we find one which matches.
904 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
905 oldest_message_ref = oldest_message();
906
907 // Time at which the message was sent (this message is written from the
908 // sending node's perspective.
909 monotonic_clock::time_point remote_monotonic_time(chrono::nanoseconds(
910 std::get<2>(oldest_message_ref)->monotonic_sent_time()));
911
912 if (remote_monotonic_time < remote_timestamp_monotonic_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800913 VLOG(1) << "Undelivered message, skipping. Remote time is "
914 << remote_monotonic_time << " timestamp is "
915 << remote_timestamp_monotonic_time << " on channel "
916 << channel_index_;
Austin Schuhcde938c2020-02-02 17:30:07 -0800917 PopMessageHeap();
918 continue;
919 } else if (remote_monotonic_time > remote_timestamp_monotonic_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800920 VLOG(1) << "Data not found. Remote time should be "
921 << remote_timestamp_monotonic_time << " on channel "
922 << channel_index_;
Austin Schuhcde938c2020-02-02 17:30:07 -0800923 return std::make_tuple(timestamp,
924 std::move(std::get<2>(oldest_timestamp)));
925 }
926
927 timestamp.monotonic_remote_time = remote_monotonic_time;
928 }
929
Austin Schuh6f3babe2020-01-26 20:34:50 -0800930 std::tuple<monotonic_clock::time_point, uint32_t,
931 FlatbufferVector<MessageHeader>>
932 oldest_message = PopMessageHeap();
933
Austin Schuh6f3babe2020-01-26 20:34:50 -0800934 timestamp.realtime_remote_time =
935 realtime_clock::time_point(chrono::nanoseconds(
936 std::get<2>(oldest_message).message().realtime_sent_time()));
937 timestamp.remote_queue_index =
938 std::get<2>(oldest_message).message().queue_index();
939
Austin Schuhcde938c2020-02-02 17:30:07 -0800940 CHECK_EQ(timestamp.monotonic_remote_time,
941 remote_timestamp_monotonic_time);
942
943 CHECK_EQ(timestamp.remote_queue_index,
944 std::get<2>(oldest_timestamp).message().remote_queue_index())
945 << ": " << FlatbufferToJson(&std::get<2>(oldest_timestamp).message())
946 << " data "
947 << FlatbufferToJson(&std::get<2>(oldest_message).message());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800948
Austin Schuh30dd5c52020-08-01 14:43:44 -0700949 return std::make_tuple(timestamp, std::move(std::get<2>(oldest_message)));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800950 }
951 } else {
952 std::tuple<monotonic_clock::time_point, uint32_t,
953 FlatbufferVector<MessageHeader>>
954 oldest_message = PopMessageHeap();
955
956 TimestampMerger::DeliveryTimestamp timestamp;
957 timestamp.monotonic_event_time =
958 monotonic_clock::time_point(chrono::nanoseconds(
959 std::get<2>(oldest_message).message().monotonic_sent_time()));
960 timestamp.realtime_event_time =
961 realtime_clock::time_point(chrono::nanoseconds(
962 std::get<2>(oldest_message).message().realtime_sent_time()));
963 timestamp.remote_queue_index = 0xffffffff;
964
965 CHECK_EQ(std::get<0>(oldest_message), timestamp.monotonic_event_time);
966 CHECK_EQ(std::get<1>(oldest_message),
967 std::get<2>(oldest_message).message().queue_index());
968
Austin Schuh30dd5c52020-08-01 14:43:44 -0700969 return std::make_tuple(timestamp, std::move(std::get<2>(oldest_message)));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800970 }
971}
972
Austin Schuh8bd96322020-02-13 21:18:22 -0800973void TimestampMerger::NoticeAtEnd() { channel_merger_->NoticeAtEnd(); }
974
Austin Schuh6f3babe2020-01-26 20:34:50 -0800975namespace {
976std::vector<std::unique_ptr<SplitMessageReader>> MakeSplitMessageReaders(
977 const std::vector<std::vector<std::string>> &filenames) {
978 CHECK_GT(filenames.size(), 0u);
979 // Build up all the SplitMessageReaders.
980 std::vector<std::unique_ptr<SplitMessageReader>> result;
981 for (const std::vector<std::string> &filenames : filenames) {
982 result.emplace_back(std::make_unique<SplitMessageReader>(filenames));
983 }
984 return result;
985}
986} // namespace
987
988ChannelMerger::ChannelMerger(
989 const std::vector<std::vector<std::string>> &filenames)
990 : split_message_readers_(MakeSplitMessageReaders(filenames)),
Austin Schuh97789fc2020-08-01 14:42:45 -0700991 log_file_header_(split_message_readers_[0]->raw_log_file_header()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800992 // Now, confirm that the configuration matches for each and pick a start time.
993 // Also return the list of possible nodes.
994 for (const std::unique_ptr<SplitMessageReader> &reader :
995 split_message_readers_) {
996 CHECK(CompareFlatBuffer(log_file_header_.message().configuration(),
997 reader->log_file_header()->configuration()))
998 << ": Replaying log files with different configurations isn't "
999 "supported";
1000 }
1001
1002 nodes_ = configuration::GetNodes(configuration());
1003}
1004
1005bool ChannelMerger::SetNode(const Node *target_node) {
1006 std::vector<SplitMessageReader *> split_message_readers;
1007 for (const std::unique_ptr<SplitMessageReader> &reader :
1008 split_message_readers_) {
1009 split_message_readers.emplace_back(reader.get());
1010 }
1011
1012 // Go find a log_file_header for this node.
1013 {
1014 bool found_node = false;
1015
1016 for (const std::unique_ptr<SplitMessageReader> &reader :
1017 split_message_readers_) {
James Kuszmaulfc273dc2020-05-09 17:56:19 -07001018 // In order to identify which logfile(s) map to the target node, do a
1019 // logical comparison of the nodes, by confirming that we are either in a
1020 // single-node setup (where the nodes will both be nullptr) or that the
1021 // node names match (but the other node fields--e.g., hostname lists--may
1022 // not).
1023 const bool both_null =
1024 reader->node() == nullptr && target_node == nullptr;
1025 const bool both_have_name =
1026 (reader->node() != nullptr) && (target_node != nullptr) &&
1027 (reader->node()->has_name() && target_node->has_name());
1028 const bool node_names_identical =
1029 both_have_name &&
1030 (reader->node()->name()->string_view() ==
1031 target_node->name()->string_view());
1032 if (both_null || node_names_identical) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001033 if (!found_node) {
1034 found_node = true;
1035 log_file_header_ = CopyFlatBuffer(reader->log_file_header());
Austin Schuhcde938c2020-02-02 17:30:07 -08001036 VLOG(1) << "Found log file " << reader->filename() << " with node "
1037 << FlatbufferToJson(reader->node()) << " start_time "
1038 << monotonic_start_time();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001039 } else {
1040 // And then make sure all the other files have matching headers.
Austin Schuhcde938c2020-02-02 17:30:07 -08001041 CHECK(CompareFlatBuffer(log_file_header(), reader->log_file_header()))
1042 << ": " << FlatbufferToJson(log_file_header()) << " reader "
1043 << FlatbufferToJson(reader->log_file_header());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001044 }
1045 }
1046 }
1047
1048 if (!found_node) {
1049 LOG(WARNING) << "Failed to find log file for node "
1050 << FlatbufferToJson(target_node);
1051 return false;
1052 }
1053 }
1054
1055 // Build up all the timestamp mergers. This connects up all the
1056 // SplitMessageReaders.
1057 timestamp_mergers_.reserve(configuration()->channels()->size());
1058 for (size_t channel_index = 0;
1059 channel_index < configuration()->channels()->size(); ++channel_index) {
1060 timestamp_mergers_.emplace_back(
1061 configuration(), split_message_readers, channel_index,
1062 configuration::GetNode(configuration(), target_node), this);
1063 }
1064
1065 // And prime everything.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001066 for (std::unique_ptr<SplitMessageReader> &split_message_reader :
1067 split_message_readers_) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001068 split_message_reader->QueueMessages(
1069 split_message_reader->monotonic_start_time());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001070 }
1071
1072 node_ = configuration::GetNodeOrDie(configuration(), target_node);
1073 return true;
1074}
1075
1076monotonic_clock::time_point ChannelMerger::OldestMessage() const {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001077 if (channel_heap_.empty()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001078 return monotonic_clock::max_time;
1079 }
1080 return channel_heap_.front().first;
1081}
1082
Austin Schuh8bd96322020-02-13 21:18:22 -08001083TimestampMerger::DeliveryTimestamp ChannelMerger::OldestTimestamp() const {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001084 if (timestamp_heap_.empty()) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001085 return TimestampMerger::DeliveryTimestamp{};
1086 }
1087 return timestamp_mergers_[timestamp_heap_.front().second].OldestTimestamp();
1088}
1089
1090TimestampMerger::DeliveryTimestamp ChannelMerger::OldestTimestampForChannel(
1091 int channel) const {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001092 // If we didn't find any data for this node, we won't have any mergers. Return
1093 // an invalid timestamp in that case.
1094 if (timestamp_mergers_.size() <= static_cast<size_t>(channel)) {
1095 TimestampMerger::DeliveryTimestamp result;
1096 return result;
1097 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001098 return timestamp_mergers_[channel].OldestTimestamp();
1099}
1100
Austin Schuh6f3babe2020-01-26 20:34:50 -08001101void ChannelMerger::PushChannelHeap(monotonic_clock::time_point timestamp,
1102 int channel_index) {
1103 // Pop and recreate the heap if it has already been pushed. And since we are
1104 // pushing again, we don't need to clear pushed.
1105 if (timestamp_mergers_[channel_index].pushed()) {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001106 const auto channel_iterator = std::find_if(
Austin Schuh6f3babe2020-01-26 20:34:50 -08001107 channel_heap_.begin(), channel_heap_.end(),
1108 [channel_index](const std::pair<monotonic_clock::time_point, int> x) {
1109 return x.second == channel_index;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001110 });
1111 DCHECK(channel_iterator != channel_heap_.end());
1112 if (std::get<0>(*channel_iterator) == timestamp) {
1113 // It's already in the heap, in the correct spot, so nothing
1114 // more for us to do here.
1115 return;
1116 }
1117 channel_heap_.erase(channel_iterator);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001118 std::make_heap(channel_heap_.begin(), channel_heap_.end(),
1119 ChannelHeapCompare);
Austin Schuh8bd96322020-02-13 21:18:22 -08001120
1121 if (timestamp_mergers_[channel_index].has_timestamps()) {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001122 const auto timestamp_iterator = std::find_if(
Austin Schuh8bd96322020-02-13 21:18:22 -08001123 timestamp_heap_.begin(), timestamp_heap_.end(),
1124 [channel_index](const std::pair<monotonic_clock::time_point, int> x) {
1125 return x.second == channel_index;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001126 });
1127 DCHECK(timestamp_iterator != timestamp_heap_.end());
1128 if (std::get<0>(*timestamp_iterator) == timestamp) {
1129 // It's already in the heap, in the correct spot, so nothing
1130 // more for us to do here.
1131 return;
1132 }
1133 timestamp_heap_.erase(timestamp_iterator);
Austin Schuh8bd96322020-02-13 21:18:22 -08001134 std::make_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1135 ChannelHeapCompare);
1136 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001137 }
1138
Austin Schuh05b70472020-01-01 17:11:17 -08001139 channel_heap_.push_back(std::make_pair(timestamp, channel_index));
1140
1141 // The default sort puts the newest message first. Use a custom comparator to
1142 // put the oldest message first.
1143 std::push_heap(channel_heap_.begin(), channel_heap_.end(),
1144 ChannelHeapCompare);
Austin Schuh8bd96322020-02-13 21:18:22 -08001145
1146 if (timestamp_mergers_[channel_index].has_timestamps()) {
1147 timestamp_heap_.push_back(std::make_pair(timestamp, channel_index));
1148 std::push_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1149 ChannelHeapCompare);
1150 }
Austin Schuh05b70472020-01-01 17:11:17 -08001151}
1152
Austin Schuh6f3babe2020-01-26 20:34:50 -08001153std::tuple<TimestampMerger::DeliveryTimestamp, int,
1154 FlatbufferVector<MessageHeader>>
1155ChannelMerger::PopOldest() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001156 CHECK_GT(channel_heap_.size(), 0u);
Austin Schuh05b70472020-01-01 17:11:17 -08001157 std::pair<monotonic_clock::time_point, int> oldest_channel_data =
1158 channel_heap_.front();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001159 int channel_index = oldest_channel_data.second;
Austin Schuh05b70472020-01-01 17:11:17 -08001160 std::pop_heap(channel_heap_.begin(), channel_heap_.end(),
1161 &ChannelHeapCompare);
1162 channel_heap_.pop_back();
Austin Schuh8bd96322020-02-13 21:18:22 -08001163
Austin Schuh6f3babe2020-01-26 20:34:50 -08001164 timestamp_mergers_[channel_index].set_pushed(false);
Austin Schuh05b70472020-01-01 17:11:17 -08001165
Austin Schuh6f3babe2020-01-26 20:34:50 -08001166 TimestampMerger *merger = &timestamp_mergers_[channel_index];
Austin Schuh05b70472020-01-01 17:11:17 -08001167
Austin Schuh8bd96322020-02-13 21:18:22 -08001168 if (merger->has_timestamps()) {
1169 CHECK_GT(timestamp_heap_.size(), 0u);
1170 std::pair<monotonic_clock::time_point, int> oldest_timestamp_data =
1171 timestamp_heap_.front();
1172 CHECK(oldest_timestamp_data == oldest_channel_data)
1173 << ": Timestamp heap out of sync.";
1174 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1175 &ChannelHeapCompare);
1176 timestamp_heap_.pop_back();
1177 }
1178
Austin Schuhcde938c2020-02-02 17:30:07 -08001179 // Merger handles any queueing needed from here.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001180 std::tuple<TimestampMerger::DeliveryTimestamp,
1181 FlatbufferVector<MessageHeader>>
1182 message = merger->PopOldest();
Brian Silverman8a32ce62020-08-12 12:02:38 -07001183 DCHECK_EQ(std::get<0>(message).monotonic_event_time,
1184 oldest_channel_data.first)
1185 << ": channel_heap_ was corrupted for " << channel_index << ": "
1186 << DebugString();
Austin Schuh05b70472020-01-01 17:11:17 -08001187
Austin Schuh6f3babe2020-01-26 20:34:50 -08001188 return std::make_tuple(std::get<0>(message), channel_index,
1189 std::move(std::get<1>(message)));
1190}
1191
Austin Schuhcde938c2020-02-02 17:30:07 -08001192std::string SplitMessageReader::MessageHeaderQueue::DebugString() const {
1193 std::stringstream ss;
1194 for (size_t i = 0; i < data_.size(); ++i) {
1195 if (timestamps) {
1196 ss << " msg: ";
1197 } else {
1198 ss << " timestamp: ";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001199 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001200 ss << monotonic_clock::time_point(std::chrono::nanoseconds(
1201 data_[i].message().monotonic_sent_time()))
1202 << " ("
1203 << realtime_clock::time_point(
1204 std::chrono::nanoseconds(data_[i].message().realtime_sent_time()))
1205 << ") " << data_[i].message().queue_index();
1206 if (timestamps) {
1207 ss << " <- remote "
1208 << monotonic_clock::time_point(std::chrono::nanoseconds(
1209 data_[i].message().monotonic_remote_time()))
1210 << " ("
1211 << realtime_clock::time_point(std::chrono::nanoseconds(
1212 data_[i].message().realtime_remote_time()))
1213 << ")";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001214 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001215 ss << "\n";
1216 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001217
Austin Schuhcde938c2020-02-02 17:30:07 -08001218 return ss.str();
1219}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001220
Austin Schuhcde938c2020-02-02 17:30:07 -08001221std::string SplitMessageReader::DebugString(int channel) const {
1222 std::stringstream ss;
1223 ss << "[\n";
1224 ss << channels_[channel].data.DebugString();
1225 ss << " ]";
1226 return ss.str();
1227}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001228
Austin Schuhcde938c2020-02-02 17:30:07 -08001229std::string SplitMessageReader::DebugString(int channel, int node_index) const {
1230 std::stringstream ss;
1231 ss << "[\n";
1232 ss << channels_[channel].timestamps[node_index].DebugString();
1233 ss << " ]";
1234 return ss.str();
1235}
1236
1237std::string TimestampMerger::DebugString() const {
1238 std::stringstream ss;
1239
1240 if (timestamp_heap_.size() > 0) {
1241 ss << " timestamp_heap {\n";
1242 std::vector<
1243 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1244 timestamp_heap = timestamp_heap_;
1245 while (timestamp_heap.size() > 0u) {
1246 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1247 oldest_timestamp_reader = timestamp_heap.front();
1248
1249 ss << " " << std::get<2>(oldest_timestamp_reader) << " "
1250 << std::get<0>(oldest_timestamp_reader) << " queue_index ("
1251 << std::get<1>(oldest_timestamp_reader) << ") ttq "
1252 << std::get<2>(oldest_timestamp_reader)->time_to_queue() << " "
1253 << std::get<2>(oldest_timestamp_reader)->filename() << " -> "
1254 << std::get<2>(oldest_timestamp_reader)
1255 ->DebugString(channel_index_, node_index_)
1256 << "\n";
1257
1258 std::pop_heap(timestamp_heap.begin(), timestamp_heap.end(),
1259 &SplitMessageReaderHeapCompare);
1260 timestamp_heap.pop_back();
1261 }
1262 ss << " }\n";
1263 }
1264
1265 ss << " message_heap {\n";
1266 {
1267 std::vector<
1268 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1269 message_heap = message_heap_;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001270 while (!message_heap.empty()) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001271 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1272 oldest_message_reader = message_heap.front();
1273
1274 ss << " " << std::get<2>(oldest_message_reader) << " "
1275 << std::get<0>(oldest_message_reader) << " queue_index ("
1276 << std::get<1>(oldest_message_reader) << ") ttq "
1277 << std::get<2>(oldest_message_reader)->time_to_queue() << " "
1278 << std::get<2>(oldest_message_reader)->filename() << " -> "
1279 << std::get<2>(oldest_message_reader)->DebugString(channel_index_)
1280 << "\n";
1281
1282 std::pop_heap(message_heap.begin(), message_heap.end(),
1283 &SplitMessageReaderHeapCompare);
1284 message_heap.pop_back();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001285 }
Austin Schuh05b70472020-01-01 17:11:17 -08001286 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001287 ss << " }";
1288
1289 return ss.str();
1290}
1291
1292std::string ChannelMerger::DebugString() const {
1293 std::stringstream ss;
1294 ss << "start_time " << realtime_start_time() << " " << monotonic_start_time()
1295 << "\n";
1296 ss << "channel_heap {\n";
1297 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap =
1298 channel_heap_;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001299 while (!channel_heap.empty()) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001300 std::tuple<monotonic_clock::time_point, int> channel = channel_heap.front();
1301 ss << " " << std::get<0>(channel) << " (" << std::get<1>(channel) << ") "
1302 << configuration::CleanedChannelToString(
1303 configuration()->channels()->Get(std::get<1>(channel)))
1304 << "\n";
1305
1306 ss << timestamp_mergers_[std::get<1>(channel)].DebugString() << "\n";
1307
1308 std::pop_heap(channel_heap.begin(), channel_heap.end(),
1309 &ChannelHeapCompare);
1310 channel_heap.pop_back();
1311 }
1312 ss << "}";
1313
1314 return ss.str();
Austin Schuh05b70472020-01-01 17:11:17 -08001315}
1316
Austin Schuha36c8902019-12-30 18:07:15 -08001317} // namespace logger
1318} // namespace aos