blob: c7f013d883975b42b1c7aaa4c54154542d90f194 [file] [log] [blame]
Austin Schuha36c8902019-12-30 18:07:15 -08001#include "aos/events/logging/logfile_utils.h"
2
3#include <fcntl.h>
Austin Schuha36c8902019-12-30 18:07:15 -08004#include <sys/stat.h>
5#include <sys/types.h>
6#include <sys/uio.h>
7
Brian Silvermanf51499a2020-09-21 12:49:08 -07008#include <algorithm>
9#include <climits>
Austin Schuha36c8902019-12-30 18:07:15 -080010
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 Schuhfa895892020-01-07 20:07:41 -080013#include "aos/flatbuffer_merge.h"
Austin Schuh6f3babe2020-01-26 20:34:50 -080014#include "aos/util/file.h"
Austin Schuha36c8902019-12-30 18:07:15 -080015#include "flatbuffers/flatbuffers.h"
Austin Schuh05b70472020-01-01 17:11:17 -080016#include "gflags/gflags.h"
17#include "glog/logging.h"
Austin Schuha36c8902019-12-30 18:07:15 -080018
Austin Schuh7fbf5a72020-09-21 16:28:13 -070019DEFINE_int32(flush_size, 128000,
Austin Schuha36c8902019-12-30 18:07:15 -080020 "Number of outstanding bytes to allow before flushing to disk.");
21
Brian Silvermanf51499a2020-09-21 12:49:08 -070022namespace aos::logger {
Austin Schuha36c8902019-12-30 18:07:15 -080023
Austin Schuh05b70472020-01-01 17:11:17 -080024namespace chrono = std::chrono;
25
Brian Silvermanf51499a2020-09-21 12:49:08 -070026DetachedBufferWriter::DetachedBufferWriter(
27 std::string_view filename, std::unique_ptr<DetachedBufferEncoder> encoder)
28 : filename_(filename), encoder_(std::move(encoder)) {
Austin Schuh6f3babe2020-01-26 20:34:50 -080029 util::MkdirP(filename, 0777);
30 fd_ = open(std::string(filename).c_str(),
31 O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, 0774);
32 VLOG(1) << "Opened " << filename << " for writing";
33 PCHECK(fd_ != -1) << ": Failed to open " << filename << " for writing";
Austin Schuha36c8902019-12-30 18:07:15 -080034}
35
36DetachedBufferWriter::~DetachedBufferWriter() {
Brian Silvermanf51499a2020-09-21 12:49:08 -070037 encoder_->Finish();
38 while (encoder_->queue_size() > 0) {
39 Flush();
40 }
Austin Schuha36c8902019-12-30 18:07:15 -080041 PLOG_IF(ERROR, close(fd_) == -1) << " Failed to close logfile";
Austin Schuh2f8fd752020-09-01 22:38:28 -070042 VLOG(1) << "Closed " << filename_;
43}
44
Brian Silvermand90905f2020-09-23 14:42:56 -070045DetachedBufferWriter::DetachedBufferWriter(DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070046 *this = std::move(other);
47}
48
Brian Silverman87ac0402020-09-17 14:47:01 -070049// When other is destroyed "soon" (which it should be because we're getting an
50// rvalue reference to it), it will flush etc all the data we have queued up
51// (because that data will then be its data).
Austin Schuh2f8fd752020-09-01 22:38:28 -070052DetachedBufferWriter &DetachedBufferWriter::operator=(
53 DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070054 std::swap(filename_, other.filename_);
Brian Silvermanf51499a2020-09-21 12:49:08 -070055 std::swap(encoder_, other.encoder_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070056 std::swap(fd_, other.fd_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070057 std::swap(iovec_, other.iovec_);
Brian Silvermanf51499a2020-09-21 12:49:08 -070058 std::swap(max_write_time_, other.max_write_time_);
59 std::swap(max_write_time_bytes_, other.max_write_time_bytes_);
60 std::swap(max_write_time_messages_, other.max_write_time_messages_);
61 std::swap(total_write_time_, other.total_write_time_);
62 std::swap(total_write_count_, other.total_write_count_);
63 std::swap(total_write_messages_, other.total_write_messages_);
64 std::swap(total_write_bytes_, other.total_write_bytes_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070065 return *this;
Austin Schuha36c8902019-12-30 18:07:15 -080066}
67
Brian Silvermanf51499a2020-09-21 12:49:08 -070068void DetachedBufferWriter::QueueSpan(absl::Span<const uint8_t> span) {
69 if (encoder_->may_bypass() && span.size() > 4096u) {
70 // Over this threshold, we'll assume it's cheaper to add an extra
71 // syscall to write the data immediately instead of copying it to
72 // enqueue.
Austin Schuha36c8902019-12-30 18:07:15 -080073
Brian Silvermanf51499a2020-09-21 12:49:08 -070074 // First, flush everything.
75 while (encoder_->queue_size() > 0u) {
76 Flush();
77 }
Austin Schuhde031b72020-01-10 19:34:41 -080078
Brian Silvermanf51499a2020-09-21 12:49:08 -070079 // Then, write it directly.
80 const auto start = aos::monotonic_clock::now();
81 const ssize_t written = write(fd_, span.data(), span.size());
82 const auto end = aos::monotonic_clock::now();
83 PCHECK(written >= 0) << ": write failed";
84 CHECK_EQ(written, static_cast<ssize_t>(span.size()))
85 << ": Wrote " << written << " expected " << span.size();
86 UpdateStatsForWrite(end - start, written, 1);
87 } else {
88 encoder_->Encode(CopySpanAsDetachedBuffer(span));
Austin Schuha36c8902019-12-30 18:07:15 -080089 }
Brian Silvermanf51499a2020-09-21 12:49:08 -070090
91 FlushAtThreshold();
Austin Schuha36c8902019-12-30 18:07:15 -080092}
93
94void DetachedBufferWriter::Flush() {
Brian Silvermanf51499a2020-09-21 12:49:08 -070095 const auto queue = encoder_->queue();
96 if (queue.empty()) {
Austin Schuha36c8902019-12-30 18:07:15 -080097 return;
98 }
Brian Silvermanf51499a2020-09-21 12:49:08 -070099
Austin Schuha36c8902019-12-30 18:07:15 -0800100 iovec_.clear();
Brian Silvermanf51499a2020-09-21 12:49:08 -0700101 const size_t iovec_size = std::min<size_t>(queue.size(), IOV_MAX);
102 iovec_.resize(iovec_size);
Austin Schuha36c8902019-12-30 18:07:15 -0800103 size_t counted_size = 0;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700104 for (size_t i = 0; i < iovec_size; ++i) {
105 iovec_[i].iov_base = const_cast<uint8_t *>(queue[i].data());
106 iovec_[i].iov_len = queue[i].size();
107 counted_size += iovec_[i].iov_len;
Austin Schuha36c8902019-12-30 18:07:15 -0800108 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700109
110 const auto start = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800111 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700112 const auto end = aos::monotonic_clock::now();
113 PCHECK(written >= 0) << ": writev failed";
Austin Schuha36c8902019-12-30 18:07:15 -0800114 // TODO(austin): Handle partial writes in some way other than crashing...
Brian Silvermanf51499a2020-09-21 12:49:08 -0700115 CHECK_EQ(written, static_cast<ssize_t>(counted_size))
116 << ": Wrote " << written << " expected " << counted_size;
117
118 encoder_->Clear(iovec_size);
119
120 UpdateStatsForWrite(end - start, written, iovec_size);
121}
122
123void DetachedBufferWriter::UpdateStatsForWrite(
124 aos::monotonic_clock::duration duration, ssize_t written, int iovec_size) {
125 if (duration > max_write_time_) {
126 max_write_time_ = duration;
127 max_write_time_bytes_ = written;
128 max_write_time_messages_ = iovec_size;
129 }
130 total_write_time_ += duration;
131 ++total_write_count_;
132 total_write_messages_ += iovec_size;
133 total_write_bytes_ += written;
134}
135
136void DetachedBufferWriter::FlushAtThreshold() {
137 // Flush if we are at the max number of iovs per writev, because there's no
138 // point queueing up any more data in memory. Also flush once we have enough
139 // data queued up.
140 while (encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
141 encoder_->queue_size() >= IOV_MAX) {
142 Flush();
143 }
Austin Schuha36c8902019-12-30 18:07:15 -0800144}
145
146flatbuffers::Offset<MessageHeader> PackMessage(
147 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
148 int channel_index, LogType log_type) {
149 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
150
151 switch (log_type) {
152 case LogType::kLogMessage:
153 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800154 case LogType::kLogRemoteMessage:
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700155 data_offset = fbb->CreateVector(
156 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800157 break;
158
159 case LogType::kLogDeliveryTimeOnly:
160 break;
161 }
162
163 MessageHeader::Builder message_header_builder(*fbb);
164 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800165
166 switch (log_type) {
167 case LogType::kLogRemoteMessage:
168 message_header_builder.add_queue_index(context.remote_queue_index);
169 message_header_builder.add_monotonic_sent_time(
170 context.monotonic_remote_time.time_since_epoch().count());
171 message_header_builder.add_realtime_sent_time(
172 context.realtime_remote_time.time_since_epoch().count());
173 break;
174
175 case LogType::kLogMessage:
176 case LogType::kLogMessageAndDeliveryTime:
177 case LogType::kLogDeliveryTimeOnly:
178 message_header_builder.add_queue_index(context.queue_index);
179 message_header_builder.add_monotonic_sent_time(
180 context.monotonic_event_time.time_since_epoch().count());
181 message_header_builder.add_realtime_sent_time(
182 context.realtime_event_time.time_since_epoch().count());
183 break;
184 }
Austin Schuha36c8902019-12-30 18:07:15 -0800185
186 switch (log_type) {
187 case LogType::kLogMessage:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800188 case LogType::kLogRemoteMessage:
Austin Schuha36c8902019-12-30 18:07:15 -0800189 message_header_builder.add_data(data_offset);
190 break;
191
192 case LogType::kLogMessageAndDeliveryTime:
193 message_header_builder.add_data(data_offset);
194 [[fallthrough]];
195
196 case LogType::kLogDeliveryTimeOnly:
197 message_header_builder.add_monotonic_remote_time(
198 context.monotonic_remote_time.time_since_epoch().count());
199 message_header_builder.add_realtime_remote_time(
200 context.realtime_remote_time.time_since_epoch().count());
201 message_header_builder.add_remote_queue_index(context.remote_queue_index);
202 break;
203 }
204
205 return message_header_builder.Finish();
206}
207
Brian Silvermanf51499a2020-09-21 12:49:08 -0700208SpanReader::SpanReader(std::string_view filename) : filename_(filename) {
209 // Support for other kinds of decoders based on the filename should be added
210 // here.
211 decoder_ = std::make_unique<DummyDecoder>(filename);
Austin Schuh05b70472020-01-01 17:11:17 -0800212}
213
214absl::Span<const uint8_t> SpanReader::ReadMessage() {
215 // Make sure we have enough for the size.
216 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
217 if (!ReadBlock()) {
218 return absl::Span<const uint8_t>();
219 }
220 }
221
222 // Now make sure we have enough for the message.
223 const size_t data_size =
224 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
225 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -0800226 if (data_size == sizeof(flatbuffers::uoffset_t)) {
227 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
228 LOG(ERROR) << " Rest of log file is "
229 << absl::BytesToHexString(std::string_view(
230 reinterpret_cast<const char *>(data_.data() +
231 consumed_data_),
232 data_.size() - consumed_data_));
233 return absl::Span<const uint8_t>();
234 }
Austin Schuh05b70472020-01-01 17:11:17 -0800235 while (data_.size() < consumed_data_ + data_size) {
236 if (!ReadBlock()) {
237 return absl::Span<const uint8_t>();
238 }
239 }
240
241 // And return it, consuming the data.
242 const uint8_t *data_ptr = data_.data() + consumed_data_;
243
244 consumed_data_ += data_size;
245
246 return absl::Span<const uint8_t>(data_ptr, data_size);
247}
248
249bool SpanReader::MessageAvailable() {
250 // Are we big enough to read the size?
251 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
252 return false;
253 }
254
255 // Then, are we big enough to read the full message?
256 const size_t data_size =
257 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
258 sizeof(flatbuffers::uoffset_t);
259 if (data_.size() < consumed_data_ + data_size) {
260 return false;
261 }
262
263 return true;
264}
265
266bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700267 // This is the amount of data we grab at a time. Doing larger chunks minimizes
268 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -0800269 constexpr size_t kReadSize = 256 * 1024;
270
271 // Strip off any unused data at the front.
272 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700273 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -0800274 consumed_data_ = 0;
275 }
276
277 const size_t starting_size = data_.size();
278
279 // This should automatically grow the backing store. It won't shrink if we
280 // get a small chunk later. This reduces allocations when we want to append
281 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700282 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -0800283
Brian Silvermanf51499a2020-09-21 12:49:08 -0700284 const size_t count =
285 decoder_->Read(data_.begin() + starting_size, data_.end());
286 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -0800287 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -0800288 return false;
289 }
Austin Schuh05b70472020-01-01 17:11:17 -0800290
291 return true;
292}
293
Austin Schuh6f3babe2020-01-26 20:34:50 -0800294FlatbufferVector<LogFileHeader> ReadHeader(std::string_view filename) {
295 SpanReader span_reader(filename);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800296 absl::Span<const uint8_t> config_data = span_reader.ReadMessage();
297
298 // Make sure something was read.
Austin Schuh97789fc2020-08-01 14:42:45 -0700299 CHECK(config_data != absl::Span<const uint8_t>())
300 << ": Failed to read header from: " << filename;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800301
Austin Schuh5212cad2020-09-09 23:12:09 -0700302 // And copy the config so we have it forever, removing the size prefix.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800303 std::vector<uint8_t> data(
304 config_data.begin() + sizeof(flatbuffers::uoffset_t), config_data.end());
305 return FlatbufferVector<LogFileHeader>(std::move(data));
306}
307
Austin Schuh5212cad2020-09-09 23:12:09 -0700308FlatbufferVector<MessageHeader> ReadNthMessage(std::string_view filename,
309 size_t n) {
310 SpanReader span_reader(filename);
311 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
312 for (size_t i = 0; i < n + 1; ++i) {
313 data_span = span_reader.ReadMessage();
314
315 // Make sure something was read.
316 CHECK(data_span != absl::Span<const uint8_t>())
317 << ": Failed to read data from: " << filename;
318 }
319
320 // And copy the data so we have it forever.
321 std::vector<uint8_t> data(data_span.begin() + sizeof(flatbuffers::uoffset_t),
322 data_span.end());
323 return FlatbufferVector<MessageHeader>(std::move(data));
324}
325
Austin Schuh05b70472020-01-01 17:11:17 -0800326MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -0700327 : span_reader_(filename),
328 raw_log_file_header_(FlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuh05b70472020-01-01 17:11:17 -0800329 // Make sure we have enough to read the size.
Austin Schuh97789fc2020-08-01 14:42:45 -0700330 absl::Span<const uint8_t> header_data = span_reader_.ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800331
332 // Make sure something was read.
Austin Schuh97789fc2020-08-01 14:42:45 -0700333 CHECK(header_data != absl::Span<const uint8_t>())
334 << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -0800335
Austin Schuh97789fc2020-08-01 14:42:45 -0700336 // And copy the header data so we have it forever.
337 std::vector<uint8_t> header_data_copy(
338 header_data.begin() + sizeof(flatbuffers::uoffset_t), header_data.end());
339 raw_log_file_header_ =
340 FlatbufferVector<LogFileHeader>(std::move(header_data_copy));
Austin Schuh05b70472020-01-01 17:11:17 -0800341
Austin Schuhcde938c2020-02-02 17:30:07 -0800342 max_out_of_order_duration_ =
Austin Schuh2f8fd752020-09-01 22:38:28 -0700343 chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -0800344
345 VLOG(1) << "Opened " << filename << " as node "
346 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800347}
348
349std::optional<FlatbufferVector<MessageHeader>> MessageReader::ReadMessage() {
350 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
351 if (msg_data == absl::Span<const uint8_t>()) {
352 return std::nullopt;
353 }
354
355 FlatbufferVector<MessageHeader> result{std::vector<uint8_t>(
356 msg_data.begin() + sizeof(flatbuffers::uoffset_t), msg_data.end())};
357
358 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
359 chrono::nanoseconds(result.message().monotonic_sent_time()));
360
361 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuh8bd96322020-02-13 21:18:22 -0800362 VLOG(2) << "Read from " << filename() << " data " << FlatbufferToJson(result);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800363 return std::move(result);
Austin Schuh05b70472020-01-01 17:11:17 -0800364}
365
Austin Schuh6f3babe2020-01-26 20:34:50 -0800366SplitMessageReader::SplitMessageReader(
Austin Schuhfa895892020-01-07 20:07:41 -0800367 const std::vector<std::string> &filenames)
368 : filenames_(filenames),
Austin Schuh97789fc2020-08-01 14:42:45 -0700369 log_file_header_(FlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuhfa895892020-01-07 20:07:41 -0800370 CHECK(NextLogFile()) << ": filenames is empty. Need files to read.";
371
Austin Schuh6f3babe2020-01-26 20:34:50 -0800372 // Grab any log file header. They should all match (and we will check as we
373 // open more of them).
Austin Schuh97789fc2020-08-01 14:42:45 -0700374 log_file_header_ = message_reader_->raw_log_file_header();
Austin Schuhfa895892020-01-07 20:07:41 -0800375
Austin Schuh2f8fd752020-09-01 22:38:28 -0700376 for (size_t i = 1; i < filenames_.size(); ++i) {
377 MessageReader message_reader(filenames_[i]);
378
379 const monotonic_clock::time_point new_monotonic_start_time(
380 chrono::nanoseconds(
381 message_reader.log_file_header()->monotonic_start_time()));
382 const realtime_clock::time_point new_realtime_start_time(
383 chrono::nanoseconds(
384 message_reader.log_file_header()->realtime_start_time()));
385
386 // There are 2 types of part files. Part files from before time estimation
387 // has started, and part files after. We don't declare a log file "started"
388 // until time estimation is up. And once a log file starts, it should never
389 // stop again, and should remain constant.
390 // To compare both types of headers, we mutate our saved copy of the header
391 // to match the next chunk by updating time if we detect a stopped ->
392 // started transition.
393 if (monotonic_start_time() == monotonic_clock::min_time) {
394 CHECK_EQ(realtime_start_time(), realtime_clock::min_time);
395 // We should only be missing the monotonic start time when logging data
Brian Silverman87ac0402020-09-17 14:47:01 -0700396 // for remote nodes. We don't have a good way to determine the remote
Austin Schuh2f8fd752020-09-01 22:38:28 -0700397 // realtime offset, so it shouldn't be filled out.
398 // TODO(austin): If we have a good way, feel free to fill it out. It
399 // probably won't be better than we could do in post though with the same
400 // data.
401 CHECK(!log_file_header_.mutable_message()->has_realtime_start_time());
402 if (new_monotonic_start_time != monotonic_clock::min_time) {
403 // If we finally found our start time, update the header. Do this once
404 // because it should never change again.
405 log_file_header_.mutable_message()->mutate_monotonic_start_time(
406 new_monotonic_start_time.time_since_epoch().count());
407 log_file_header_.mutable_message()->mutate_realtime_start_time(
408 new_realtime_start_time.time_since_epoch().count());
409 }
410 }
411
Austin Schuh64fab802020-09-09 22:47:47 -0700412 // We don't have a good way to set the realtime start time on remote nodes.
413 // Confirm it remains consistent.
414 CHECK_EQ(log_file_header_.mutable_message()->has_realtime_start_time(),
415 message_reader.log_file_header()->has_realtime_start_time());
416
417 // Parts index will *not* match unless we set them to match. We only want
418 // to accept the start time and parts mismatching, so set them.
419 log_file_header_.mutable_message()->mutate_parts_index(
420 message_reader.log_file_header()->parts_index());
421
Austin Schuh2f8fd752020-09-01 22:38:28 -0700422 // Now compare that the headers match.
Austin Schuh64fab802020-09-09 22:47:47 -0700423 if (!CompareFlatBuffer(message_reader.raw_log_file_header(),
424 log_file_header_)) {
425 if (message_reader.log_file_header()->has_logger_uuid() &&
426 log_file_header_.message().has_logger_uuid() &&
427 message_reader.log_file_header()->logger_uuid()->string_view() !=
428 log_file_header_.message().logger_uuid()->string_view()) {
429 LOG(FATAL) << "Logger UUIDs don't match between log file chunks "
430 << filenames_[0] << " and " << filenames_[i]
431 << ", this is not supported.";
432 }
433 if (message_reader.log_file_header()->has_parts_uuid() &&
434 log_file_header_.message().has_parts_uuid() &&
435 message_reader.log_file_header()->parts_uuid()->string_view() !=
436 log_file_header_.message().parts_uuid()->string_view()) {
437 LOG(FATAL) << "Parts UUIDs don't match between log file chunks "
438 << filenames_[0] << " and " << filenames_[i]
439 << ", this is not supported.";
440 }
441
442 LOG(FATAL) << "Header is different between log file chunks "
443 << filenames_[0] << " and " << filenames_[i]
444 << ", this is not supported.";
445 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700446 }
Austin Schuh64fab802020-09-09 22:47:47 -0700447 // Put the parts index back to the first log file chunk.
448 log_file_header_.mutable_message()->mutate_parts_index(
449 message_reader_->log_file_header()->parts_index());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700450
Austin Schuh6f3babe2020-01-26 20:34:50 -0800451 // Setup per channel state.
Austin Schuh05b70472020-01-01 17:11:17 -0800452 channels_.resize(configuration()->channels()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800453 for (ChannelData &channel_data : channels_) {
454 channel_data.data.split_reader = this;
455 // Build up the timestamp list.
456 if (configuration::MultiNode(configuration())) {
457 channel_data.timestamps.resize(configuration()->nodes()->size());
458 for (MessageHeaderQueue &queue : channel_data.timestamps) {
459 queue.timestamps = true;
460 queue.split_reader = this;
461 }
462 }
463 }
Austin Schuh05b70472020-01-01 17:11:17 -0800464
Austin Schuh6f3babe2020-01-26 20:34:50 -0800465 // Build up channels_to_write_ as an optimization to make it fast to figure
466 // out which datastructure to place any new data from a channel on.
467 for (const Channel *channel : *configuration()->channels()) {
468 // This is the main case. We will only see data on this node.
469 if (configuration::ChannelIsSendableOnNode(channel, node())) {
470 channels_to_write_.emplace_back(
471 &channels_[channels_to_write_.size()].data);
472 } else
473 // If we can't send, but can receive, we should be able to see
474 // timestamps here.
475 if (configuration::ChannelIsReadableOnNode(channel, node())) {
476 channels_to_write_.emplace_back(
477 &(channels_[channels_to_write_.size()]
478 .timestamps[configuration::GetNodeIndex(configuration(),
479 node())]));
480 } else {
481 channels_to_write_.emplace_back(nullptr);
482 }
483 }
Austin Schuh05b70472020-01-01 17:11:17 -0800484}
485
Austin Schuh6f3babe2020-01-26 20:34:50 -0800486bool SplitMessageReader::NextLogFile() {
Austin Schuhfa895892020-01-07 20:07:41 -0800487 if (next_filename_index_ == filenames_.size()) {
488 return false;
489 }
490 message_reader_ =
491 std::make_unique<MessageReader>(filenames_[next_filename_index_]);
492
493 // We can't support the config diverging between two log file headers. See if
494 // they are the same.
495 if (next_filename_index_ != 0) {
Austin Schuh64fab802020-09-09 22:47:47 -0700496 // In order for the headers to identically compare, they need to have the
497 // same parts_index. Rewrite the saved header with the new parts_index,
498 // compare, and then restore.
499 const int32_t original_parts_index =
500 log_file_header_.message().parts_index();
501 log_file_header_.mutable_message()->mutate_parts_index(
502 message_reader_->log_file_header()->parts_index());
503
Austin Schuh97789fc2020-08-01 14:42:45 -0700504 CHECK(CompareFlatBuffer(message_reader_->raw_log_file_header(),
505 log_file_header_))
Austin Schuhfa895892020-01-07 20:07:41 -0800506 << ": Header is different between log file chunks "
507 << filenames_[next_filename_index_] << " and "
508 << filenames_[next_filename_index_ - 1] << ", this is not supported.";
Austin Schuh64fab802020-09-09 22:47:47 -0700509
510 log_file_header_.mutable_message()->mutate_parts_index(
511 original_parts_index);
Austin Schuhfa895892020-01-07 20:07:41 -0800512 }
513
514 ++next_filename_index_;
515 return true;
516}
517
Austin Schuh6f3babe2020-01-26 20:34:50 -0800518bool SplitMessageReader::QueueMessages(
Austin Schuhcde938c2020-02-02 17:30:07 -0800519 monotonic_clock::time_point last_dequeued_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800520 // TODO(austin): Once we are happy that everything works, read a 256kb chunk
521 // to reduce the need to re-heap down below.
Austin Schuhcde938c2020-02-02 17:30:07 -0800522
523 // Special case no more data. Otherwise we blow up on the CHECK statement
524 // confirming that we have enough data queued.
525 if (at_end_) {
526 return false;
527 }
528
529 // If this isn't the first time around, confirm that we had enough data queued
530 // to follow the contract.
531 if (time_to_queue_ != monotonic_clock::min_time) {
532 CHECK_LE(last_dequeued_time,
533 newest_timestamp() - max_out_of_order_duration())
534 << " node " << FlatbufferToJson(node()) << " on " << this;
535
536 // Bail if there is enough data already queued.
537 if (last_dequeued_time < time_to_queue_) {
Austin Schuhee711052020-08-24 16:06:09 -0700538 VLOG(1) << MaybeNodeName(target_node_) << "All up to date on " << this
539 << ", dequeued " << last_dequeued_time << " queue time "
540 << time_to_queue_;
Austin Schuhcde938c2020-02-02 17:30:07 -0800541 return true;
542 }
543 } else {
544 // Startup takes a special dance. We want to queue up until the start time,
545 // but we then want to find the next message to read. The conservative
546 // answer is to immediately trigger a second requeue to get things moving.
547 time_to_queue_ = monotonic_start_time();
548 QueueMessages(time_to_queue_);
549 }
550
551 // If we are asked to queue, queue for at least max_out_of_order_duration past
552 // the last known time in the log file (ie the newest timestep read). As long
553 // as we requeue exactly when time_to_queue_ is dequeued and go no further, we
554 // are safe. And since we pop in order, that works.
555 //
556 // Special case the start of the log file. There should be at most 1 message
557 // from each channel at the start of the log file. So always force the start
558 // of the log file to just be read.
559 time_to_queue_ = std::max(time_to_queue_, newest_timestamp());
Austin Schuhee711052020-08-24 16:06:09 -0700560 VLOG(1) << MaybeNodeName(target_node_) << "Queueing, going until "
561 << time_to_queue_ << " " << filename();
Austin Schuhcde938c2020-02-02 17:30:07 -0800562
563 bool was_emplaced = false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800564 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800565 // Stop if we have enough.
Brian Silverman98360e22020-04-28 16:51:20 -0700566 if (newest_timestamp() > time_to_queue_ + max_out_of_order_duration() &&
Austin Schuhcde938c2020-02-02 17:30:07 -0800567 was_emplaced) {
Austin Schuhee711052020-08-24 16:06:09 -0700568 VLOG(1) << MaybeNodeName(target_node_) << "Done queueing on " << this
569 << ", queued to " << newest_timestamp() << " with requeue time "
570 << time_to_queue_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800571 return true;
572 }
Austin Schuh05b70472020-01-01 17:11:17 -0800573
Austin Schuh6f3babe2020-01-26 20:34:50 -0800574 if (std::optional<FlatbufferVector<MessageHeader>> msg =
575 message_reader_->ReadMessage()) {
576 const MessageHeader &header = msg.value().message();
577
Austin Schuhcde938c2020-02-02 17:30:07 -0800578 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
579 chrono::nanoseconds(header.monotonic_sent_time()));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800580
Austin Schuh0b5fd032020-03-28 17:36:49 -0700581 if (VLOG_IS_ON(2)) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700582 LOG(INFO) << MaybeNodeName(target_node_) << "Queued " << this << " "
583 << filename() << " ttq: " << time_to_queue_ << " now "
Austin Schuhee711052020-08-24 16:06:09 -0700584 << newest_timestamp() << " start time "
585 << monotonic_start_time() << " " << FlatbufferToJson(&header);
Austin Schuh0b5fd032020-03-28 17:36:49 -0700586 } else if (VLOG_IS_ON(1)) {
587 FlatbufferVector<MessageHeader> copy = msg.value();
588 copy.mutable_message()->clear_data();
Austin Schuhee711052020-08-24 16:06:09 -0700589 LOG(INFO) << MaybeNodeName(target_node_) << "Queued " << this << " "
590 << filename() << " ttq: " << time_to_queue_ << " now "
591 << newest_timestamp() << " start time "
592 << monotonic_start_time() << " " << FlatbufferToJson(copy);
Austin Schuh0b5fd032020-03-28 17:36:49 -0700593 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800594
595 const int channel_index = header.channel_index();
596 was_emplaced = channels_to_write_[channel_index]->emplace_back(
597 std::move(msg.value()));
598 if (was_emplaced) {
599 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
600 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800601 } else {
602 if (!NextLogFile()) {
Austin Schuhee711052020-08-24 16:06:09 -0700603 VLOG(1) << MaybeNodeName(target_node_) << "No more files, last was "
604 << filenames_.back();
Austin Schuhcde938c2020-02-02 17:30:07 -0800605 at_end_ = true;
Austin Schuh8bd96322020-02-13 21:18:22 -0800606 for (MessageHeaderQueue *queue : channels_to_write_) {
607 if (queue == nullptr || queue->timestamp_merger == nullptr) {
608 continue;
609 }
610 queue->timestamp_merger->NoticeAtEnd();
611 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800612 return false;
613 }
614 }
Austin Schuh05b70472020-01-01 17:11:17 -0800615 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800616}
617
618void SplitMessageReader::SetTimestampMerger(TimestampMerger *timestamp_merger,
619 int channel_index,
620 const Node *target_node) {
621 const Node *reinterpreted_target_node =
622 configuration::GetNodeOrDie(configuration(), target_node);
Austin Schuhee711052020-08-24 16:06:09 -0700623 target_node_ = reinterpreted_target_node;
624
Austin Schuh6f3babe2020-01-26 20:34:50 -0800625 const Channel *const channel =
626 configuration()->channels()->Get(channel_index);
627
Austin Schuhcde938c2020-02-02 17:30:07 -0800628 VLOG(1) << " Configuring merger " << this << " for channel " << channel_index
629 << " "
630 << configuration::CleanedChannelToString(
631 configuration()->channels()->Get(channel_index));
632
Austin Schuh6f3babe2020-01-26 20:34:50 -0800633 MessageHeaderQueue *message_header_queue = nullptr;
634
635 // Figure out if this log file is from our point of view, or the other node's
636 // point of view.
637 if (node() == reinterpreted_target_node) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800638 VLOG(1) << " Replaying as logged node " << filename();
639
640 if (configuration::ChannelIsSendableOnNode(channel, node())) {
641 VLOG(1) << " Data on node";
642 message_header_queue = &(channels_[channel_index].data);
643 } else if (configuration::ChannelIsReadableOnNode(channel, node())) {
644 VLOG(1) << " Timestamps on node";
645 message_header_queue =
646 &(channels_[channel_index].timestamps[configuration::GetNodeIndex(
647 configuration(), node())]);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800648 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800649 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800650 }
651 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800652 VLOG(1) << " Replaying as other node " << filename();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800653 // We are replaying from another node's point of view. The only interesting
Austin Schuhcde938c2020-02-02 17:30:07 -0800654 // data is data that is sent from our node and received on theirs.
655 if (configuration::ChannelIsReadableOnNode(channel,
656 reinterpreted_target_node) &&
657 configuration::ChannelIsSendableOnNode(channel, node())) {
658 VLOG(1) << " Readable on target node";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800659 // Data from another node.
660 message_header_queue = &(channels_[channel_index].data);
661 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800662 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800663 // This is either not sendable on the other node, or is a timestamp and
664 // therefore not interesting.
665 }
666 }
667
668 // If we found one, write it down. This will be nullptr when there is nothing
669 // relevant on this channel on this node for the target node. In that case,
670 // we want to drop the message instead of queueing it.
671 if (message_header_queue != nullptr) {
672 message_header_queue->timestamp_merger = timestamp_merger;
673 }
674}
675
676std::tuple<monotonic_clock::time_point, uint32_t,
677 FlatbufferVector<MessageHeader>>
678SplitMessageReader::PopOldest(int channel_index) {
679 CHECK_GT(channels_[channel_index].data.size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800680 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
681 timestamp = channels_[channel_index].data.front_timestamp();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800682 FlatbufferVector<MessageHeader> front =
683 std::move(channels_[channel_index].data.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700684 channels_[channel_index].data.PopFront();
Austin Schuhcde938c2020-02-02 17:30:07 -0800685
Austin Schuh2f8fd752020-09-01 22:38:28 -0700686 VLOG(1) << MaybeNodeName(target_node_) << "Popped Data " << this << " "
687 << std::get<0>(timestamp) << " for "
688 << configuration::StrippedChannelToString(
689 configuration()->channels()->Get(channel_index))
690 << " (" << channel_index << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -0800691
692 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800693
694 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
695 std::move(front));
696}
697
698std::tuple<monotonic_clock::time_point, uint32_t,
699 FlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -0700700SplitMessageReader::PopOldestTimestamp(int channel, int node_index) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800701 CHECK_GT(channels_[channel].timestamps[node_index].size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800702 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
703 timestamp = channels_[channel].timestamps[node_index].front_timestamp();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800704 FlatbufferVector<MessageHeader> front =
705 std::move(channels_[channel].timestamps[node_index].front());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700706 channels_[channel].timestamps[node_index].PopFront();
Austin Schuhcde938c2020-02-02 17:30:07 -0800707
Austin Schuh2f8fd752020-09-01 22:38:28 -0700708 VLOG(1) << MaybeNodeName(target_node_) << "Popped timestamp " << this << " "
Austin Schuhee711052020-08-24 16:06:09 -0700709 << std::get<0>(timestamp) << " for "
710 << configuration::StrippedChannelToString(
711 configuration()->channels()->Get(channel))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700712 << " on "
713 << configuration()->nodes()->Get(node_index)->name()->string_view()
714 << " (" << node_index << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -0800715
716 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800717
718 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
719 std::move(front));
720}
721
Austin Schuhcde938c2020-02-02 17:30:07 -0800722bool SplitMessageReader::MessageHeaderQueue::emplace_back(
Austin Schuh6f3babe2020-01-26 20:34:50 -0800723 FlatbufferVector<MessageHeader> &&msg) {
724 CHECK(split_reader != nullptr);
725
726 // If there is no timestamp merger for this queue, nobody is listening. Drop
727 // the message. This happens when a log file from another node is replayed,
728 // and the timestamp mergers down stream just don't care.
729 if (timestamp_merger == nullptr) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800730 return false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800731 }
732
733 CHECK(timestamps != msg.message().has_data())
734 << ": Got timestamps and data mixed up on a node. "
735 << FlatbufferToJson(msg);
736
737 data_.emplace_back(std::move(msg));
738
739 if (data_.size() == 1u) {
740 // Yup, new data. Notify.
741 if (timestamps) {
742 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
743 } else {
744 timestamp_merger->Update(split_reader, front_timestamp());
745 }
746 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800747
748 return true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800749}
750
Austin Schuh2f8fd752020-09-01 22:38:28 -0700751void SplitMessageReader::MessageHeaderQueue::PopFront() {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800752 data_.pop_front();
753 if (data_.size() != 0u) {
754 // Yup, new data.
755 if (timestamps) {
756 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
757 } else {
758 timestamp_merger->Update(split_reader, front_timestamp());
759 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700760 } else {
761 // Poke anyways to update the heap.
762 if (timestamps) {
763 timestamp_merger->UpdateTimestamp(
764 nullptr, std::make_tuple(monotonic_clock::min_time, 0, nullptr));
765 } else {
766 timestamp_merger->Update(
767 nullptr, std::make_tuple(monotonic_clock::min_time, 0, nullptr));
768 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800769 }
Austin Schuh05b70472020-01-01 17:11:17 -0800770}
771
772namespace {
773
Austin Schuh6f3babe2020-01-26 20:34:50 -0800774bool SplitMessageReaderHeapCompare(
775 const std::tuple<monotonic_clock::time_point, uint32_t,
776 SplitMessageReader *>
777 first,
778 const std::tuple<monotonic_clock::time_point, uint32_t,
779 SplitMessageReader *>
780 second) {
781 if (std::get<0>(first) > std::get<0>(second)) {
782 return true;
783 } else if (std::get<0>(first) == std::get<0>(second)) {
784 if (std::get<1>(first) > std::get<1>(second)) {
785 return true;
786 } else if (std::get<1>(first) == std::get<1>(second)) {
787 return std::get<2>(first) > std::get<2>(second);
788 } else {
789 return false;
790 }
791 } else {
792 return false;
793 }
794}
795
Austin Schuh05b70472020-01-01 17:11:17 -0800796bool ChannelHeapCompare(
797 const std::pair<monotonic_clock::time_point, int> first,
798 const std::pair<monotonic_clock::time_point, int> second) {
799 if (first.first > second.first) {
800 return true;
801 } else if (first.first == second.first) {
802 return first.second > second.second;
803 } else {
804 return false;
805 }
806}
807
808} // namespace
809
Austin Schuh6f3babe2020-01-26 20:34:50 -0800810TimestampMerger::TimestampMerger(
811 const Configuration *configuration,
812 std::vector<SplitMessageReader *> split_message_readers, int channel_index,
813 const Node *target_node, ChannelMerger *channel_merger)
814 : configuration_(configuration),
815 split_message_readers_(std::move(split_message_readers)),
816 channel_index_(channel_index),
817 node_index_(configuration::MultiNode(configuration)
818 ? configuration::GetNodeIndex(configuration, target_node)
819 : -1),
820 channel_merger_(channel_merger) {
821 // Tell the readers we care so they know who to notify.
Austin Schuhcde938c2020-02-02 17:30:07 -0800822 VLOG(1) << "Configuring channel " << channel_index << " target node "
823 << FlatbufferToJson(target_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800824 for (SplitMessageReader *reader : split_message_readers_) {
825 reader->SetTimestampMerger(this, channel_index, target_node);
826 }
827
828 // And then determine if we need to track timestamps.
829 const Channel *channel = configuration->channels()->Get(channel_index);
830 if (!configuration::ChannelIsSendableOnNode(channel, target_node) &&
831 configuration::ChannelIsReadableOnNode(channel, target_node)) {
832 has_timestamps_ = true;
833 }
834}
835
836void TimestampMerger::PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800837 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
838 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800839 SplitMessageReader *split_message_reader) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700840 if (split_message_reader != nullptr) {
841 DCHECK(std::find_if(message_heap_.begin(), message_heap_.end(),
842 [split_message_reader](
843 const std::tuple<monotonic_clock::time_point,
844 uint32_t, SplitMessageReader *>
845 x) {
846 return std::get<2>(x) == split_message_reader;
847 }) == message_heap_.end())
848 << ": Pushing message when it is already in the heap.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800849
Austin Schuh2f8fd752020-09-01 22:38:28 -0700850 message_heap_.push_back(std::make_tuple(
851 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800852
Austin Schuh2f8fd752020-09-01 22:38:28 -0700853 std::push_heap(message_heap_.begin(), message_heap_.end(),
854 &SplitMessageReaderHeapCompare);
855 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800856
857 // If we are just a data merger, don't wait for timestamps.
858 if (!has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700859 if (!message_heap_.empty()) {
860 channel_merger_->Update(std::get<0>(message_heap_[0]), channel_index_);
861 pushed_ = true;
862 } else {
863 // Remove ourselves if we are empty.
864 channel_merger_->Update(monotonic_clock::min_time, channel_index_);
865 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800866 }
867}
868
Austin Schuhcde938c2020-02-02 17:30:07 -0800869std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
870TimestampMerger::oldest_message() const {
871 CHECK_GT(message_heap_.size(), 0u);
872 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
873 oldest_message_reader = message_heap_.front();
874 return std::get<2>(oldest_message_reader)->oldest_message(channel_index_);
875}
876
877std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
878TimestampMerger::oldest_timestamp() const {
879 CHECK_GT(timestamp_heap_.size(), 0u);
880 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
881 oldest_message_reader = timestamp_heap_.front();
882 return std::get<2>(oldest_message_reader)
883 ->oldest_message(channel_index_, node_index_);
884}
885
Austin Schuh6f3babe2020-01-26 20:34:50 -0800886void TimestampMerger::PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800887 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
888 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800889 SplitMessageReader *split_message_reader) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700890 if (split_message_reader != nullptr) {
891 DCHECK(std::find_if(timestamp_heap_.begin(), timestamp_heap_.end(),
892 [split_message_reader](
893 const std::tuple<monotonic_clock::time_point,
894 uint32_t, SplitMessageReader *>
895 x) {
896 return std::get<2>(x) == split_message_reader;
897 }) == timestamp_heap_.end())
898 << ": Pushing timestamp when it is already in the heap.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800899
Austin Schuh2f8fd752020-09-01 22:38:28 -0700900 timestamp_heap_.push_back(std::make_tuple(
901 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800902
Austin Schuh2f8fd752020-09-01 22:38:28 -0700903 std::push_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
904 SplitMessageReaderHeapCompare);
905 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800906
907 // If we are a timestamp merger, don't wait for data. Missing data will be
908 // caught at read time.
909 if (has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700910 if (!timestamp_heap_.empty()) {
911 channel_merger_->Update(std::get<0>(timestamp_heap_[0]), channel_index_);
912 pushed_ = true;
913 } else {
914 // Remove ourselves if we are empty.
915 channel_merger_->Update(monotonic_clock::min_time, channel_index_);
916 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800917 }
918}
919
920std::tuple<monotonic_clock::time_point, uint32_t,
921 FlatbufferVector<MessageHeader>>
922TimestampMerger::PopMessageHeap() {
923 // Pop the oldest message reader pointer off the heap.
924 CHECK_GT(message_heap_.size(), 0u);
925 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
926 oldest_message_reader = message_heap_.front();
927
928 std::pop_heap(message_heap_.begin(), message_heap_.end(),
929 &SplitMessageReaderHeapCompare);
930 message_heap_.pop_back();
931
932 // Pop the oldest message. This re-pushes any messages from the reader to the
933 // message heap.
934 std::tuple<monotonic_clock::time_point, uint32_t,
935 FlatbufferVector<MessageHeader>>
936 oldest_message =
937 std::get<2>(oldest_message_reader)->PopOldest(channel_index_);
938
939 // Confirm that the time and queue_index we have recorded matches.
940 CHECK_EQ(std::get<0>(oldest_message), std::get<0>(oldest_message_reader));
941 CHECK_EQ(std::get<1>(oldest_message), std::get<1>(oldest_message_reader));
942
943 // Now, keep reading until we have found all duplicates.
Brian Silverman8a32ce62020-08-12 12:02:38 -0700944 while (!message_heap_.empty()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800945 // See if it is a duplicate.
946 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
947 next_oldest_message_reader = message_heap_.front();
948
Austin Schuhcde938c2020-02-02 17:30:07 -0800949 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
950 next_oldest_message_time = std::get<2>(next_oldest_message_reader)
951 ->oldest_message(channel_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800952
953 if (std::get<0>(next_oldest_message_time) == std::get<0>(oldest_message) &&
954 std::get<1>(next_oldest_message_time) == std::get<1>(oldest_message)) {
955 // Pop the message reader pointer.
956 std::pop_heap(message_heap_.begin(), message_heap_.end(),
957 &SplitMessageReaderHeapCompare);
958 message_heap_.pop_back();
959
960 // Pop the next oldest message. This re-pushes any messages from the
961 // reader.
962 std::tuple<monotonic_clock::time_point, uint32_t,
963 FlatbufferVector<MessageHeader>>
964 next_oldest_message = std::get<2>(next_oldest_message_reader)
965 ->PopOldest(channel_index_);
966
967 // And make sure the message matches in it's entirety.
968 CHECK(std::get<2>(oldest_message).span() ==
969 std::get<2>(next_oldest_message).span())
970 << ": Data at the same timestamp doesn't match.";
971 } else {
972 break;
973 }
974 }
975
976 return oldest_message;
977}
978
979std::tuple<monotonic_clock::time_point, uint32_t,
980 FlatbufferVector<MessageHeader>>
981TimestampMerger::PopTimestampHeap() {
982 // Pop the oldest message reader pointer off the heap.
983 CHECK_GT(timestamp_heap_.size(), 0u);
984
985 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
986 oldest_timestamp_reader = timestamp_heap_.front();
987
988 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
989 &SplitMessageReaderHeapCompare);
990 timestamp_heap_.pop_back();
991
992 CHECK(node_index_ != -1) << ": Timestamps in a single node environment";
993
994 // Pop the oldest message. This re-pushes any timestamps from the reader to
995 // the timestamp heap.
996 std::tuple<monotonic_clock::time_point, uint32_t,
997 FlatbufferVector<MessageHeader>>
998 oldest_timestamp = std::get<2>(oldest_timestamp_reader)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700999 ->PopOldestTimestamp(channel_index_, node_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001000
1001 // Confirm that the time we have recorded matches.
1002 CHECK_EQ(std::get<0>(oldest_timestamp), std::get<0>(oldest_timestamp_reader));
1003 CHECK_EQ(std::get<1>(oldest_timestamp), std::get<1>(oldest_timestamp_reader));
1004
Austin Schuh2f8fd752020-09-01 22:38:28 -07001005 // Now, keep reading until we have found all duplicates.
1006 while (!timestamp_heap_.empty()) {
1007 // See if it is a duplicate.
1008 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1009 next_oldest_timestamp_reader = timestamp_heap_.front();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001010
Austin Schuh2f8fd752020-09-01 22:38:28 -07001011 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1012 next_oldest_timestamp_time =
1013 std::get<2>(next_oldest_timestamp_reader)
1014 ->oldest_message(channel_index_, node_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001015
Austin Schuh2f8fd752020-09-01 22:38:28 -07001016 if (std::get<0>(next_oldest_timestamp_time) ==
1017 std::get<0>(oldest_timestamp) &&
1018 std::get<1>(next_oldest_timestamp_time) ==
1019 std::get<1>(oldest_timestamp)) {
1020 // Pop the timestamp reader pointer.
1021 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1022 &SplitMessageReaderHeapCompare);
1023 timestamp_heap_.pop_back();
1024
1025 // Pop the next oldest timestamp. This re-pushes any messages from the
1026 // reader.
1027 std::tuple<monotonic_clock::time_point, uint32_t,
1028 FlatbufferVector<MessageHeader>>
1029 next_oldest_timestamp =
1030 std::get<2>(next_oldest_timestamp_reader)
1031 ->PopOldestTimestamp(channel_index_, node_index_);
1032
1033 // And make sure the contents matches in it's entirety.
1034 CHECK(std::get<2>(oldest_timestamp).span() ==
1035 std::get<2>(next_oldest_timestamp).span())
1036 << ": Data at the same timestamp doesn't match, "
1037 << aos::FlatbufferToJson(std::get<2>(oldest_timestamp)) << " vs "
1038 << aos::FlatbufferToJson(std::get<2>(next_oldest_timestamp)) << " "
1039 << absl::BytesToHexString(std::string_view(
1040 reinterpret_cast<const char *>(
1041 std::get<2>(oldest_timestamp).span().data()),
1042 std::get<2>(oldest_timestamp).span().size()))
1043 << " vs "
1044 << absl::BytesToHexString(std::string_view(
1045 reinterpret_cast<const char *>(
1046 std::get<2>(next_oldest_timestamp).span().data()),
1047 std::get<2>(next_oldest_timestamp).span().size()));
1048
1049 } else {
1050 break;
1051 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001052 }
1053
Austin Schuh2f8fd752020-09-01 22:38:28 -07001054 return oldest_timestamp;
Austin Schuh8bd96322020-02-13 21:18:22 -08001055}
1056
Austin Schuh6f3babe2020-01-26 20:34:50 -08001057std::tuple<TimestampMerger::DeliveryTimestamp, FlatbufferVector<MessageHeader>>
1058TimestampMerger::PopOldest() {
1059 if (has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001060 VLOG(1) << "Looking for matching timestamp for "
1061 << configuration::StrippedChannelToString(
1062 configuration_->channels()->Get(channel_index_))
1063 << " (" << channel_index_ << ") "
1064 << " at " << std::get<0>(oldest_timestamp());
1065
Austin Schuh8bd96322020-02-13 21:18:22 -08001066 // Read the timestamps.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001067 std::tuple<monotonic_clock::time_point, uint32_t,
1068 FlatbufferVector<MessageHeader>>
1069 oldest_timestamp = PopTimestampHeap();
1070
1071 TimestampMerger::DeliveryTimestamp timestamp;
1072 timestamp.monotonic_event_time =
1073 monotonic_clock::time_point(chrono::nanoseconds(
1074 std::get<2>(oldest_timestamp).message().monotonic_sent_time()));
1075 timestamp.realtime_event_time =
1076 realtime_clock::time_point(chrono::nanoseconds(
1077 std::get<2>(oldest_timestamp).message().realtime_sent_time()));
1078
1079 // Consistency check.
1080 CHECK_EQ(timestamp.monotonic_event_time, std::get<0>(oldest_timestamp));
1081 CHECK_EQ(std::get<2>(oldest_timestamp).message().queue_index(),
1082 std::get<1>(oldest_timestamp));
1083
1084 monotonic_clock::time_point remote_timestamp_monotonic_time(
1085 chrono::nanoseconds(
1086 std::get<2>(oldest_timestamp).message().monotonic_remote_time()));
1087
Austin Schuh8bd96322020-02-13 21:18:22 -08001088 // See if we have any data. If not, pass the problem up the chain.
Brian Silverman8a32ce62020-08-12 12:02:38 -07001089 if (message_heap_.empty()) {
Austin Schuhee711052020-08-24 16:06:09 -07001090 LOG(WARNING) << MaybeNodeName(configuration_->nodes()->Get(node_index_))
1091 << "No data to match timestamp on "
1092 << configuration::CleanedChannelToString(
1093 configuration_->channels()->Get(channel_index_))
1094 << " (" << channel_index_ << ")";
Austin Schuh8bd96322020-02-13 21:18:22 -08001095 return std::make_tuple(timestamp,
1096 std::move(std::get<2>(oldest_timestamp)));
1097 }
1098
Austin Schuh6f3babe2020-01-26 20:34:50 -08001099 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001100 {
1101 // Ok, now try grabbing data until we find one which matches.
1102 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1103 oldest_message_ref = oldest_message();
1104
1105 // Time at which the message was sent (this message is written from the
1106 // sending node's perspective.
1107 monotonic_clock::time_point remote_monotonic_time(chrono::nanoseconds(
1108 std::get<2>(oldest_message_ref)->monotonic_sent_time()));
1109
1110 if (remote_monotonic_time < remote_timestamp_monotonic_time) {
Austin Schuhee711052020-08-24 16:06:09 -07001111 LOG(WARNING) << configuration_->nodes()
1112 ->Get(node_index_)
1113 ->name()
1114 ->string_view()
1115 << " Undelivered message, skipping. Remote time is "
1116 << remote_monotonic_time << " timestamp is "
1117 << remote_timestamp_monotonic_time << " on channel "
1118 << configuration::StrippedChannelToString(
1119 configuration_->channels()->Get(channel_index_))
1120 << " (" << channel_index_ << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -08001121 PopMessageHeap();
1122 continue;
1123 } else if (remote_monotonic_time > remote_timestamp_monotonic_time) {
Austin Schuhee711052020-08-24 16:06:09 -07001124 LOG(WARNING) << configuration_->nodes()
1125 ->Get(node_index_)
1126 ->name()
1127 ->string_view()
1128 << " Data not found. Remote time should be "
1129 << remote_timestamp_monotonic_time
1130 << ", message time is " << remote_monotonic_time
1131 << " on channel "
1132 << configuration::StrippedChannelToString(
1133 configuration_->channels()->Get(channel_index_))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001134 << " (" << channel_index_ << ")"
1135 << (VLOG_IS_ON(1) ? DebugString() : "");
Austin Schuhcde938c2020-02-02 17:30:07 -08001136 return std::make_tuple(timestamp,
1137 std::move(std::get<2>(oldest_timestamp)));
1138 }
1139
1140 timestamp.monotonic_remote_time = remote_monotonic_time;
1141 }
1142
Austin Schuh2f8fd752020-09-01 22:38:28 -07001143 VLOG(1) << "Found matching data "
1144 << configuration::StrippedChannelToString(
1145 configuration_->channels()->Get(channel_index_))
1146 << " (" << channel_index_ << ")";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001147 std::tuple<monotonic_clock::time_point, uint32_t,
1148 FlatbufferVector<MessageHeader>>
1149 oldest_message = PopMessageHeap();
1150
Austin Schuh6f3babe2020-01-26 20:34:50 -08001151 timestamp.realtime_remote_time =
1152 realtime_clock::time_point(chrono::nanoseconds(
1153 std::get<2>(oldest_message).message().realtime_sent_time()));
1154 timestamp.remote_queue_index =
1155 std::get<2>(oldest_message).message().queue_index();
1156
Austin Schuhcde938c2020-02-02 17:30:07 -08001157 CHECK_EQ(timestamp.monotonic_remote_time,
1158 remote_timestamp_monotonic_time);
1159
1160 CHECK_EQ(timestamp.remote_queue_index,
1161 std::get<2>(oldest_timestamp).message().remote_queue_index())
1162 << ": " << FlatbufferToJson(&std::get<2>(oldest_timestamp).message())
1163 << " data "
1164 << FlatbufferToJson(&std::get<2>(oldest_message).message());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001165
Austin Schuh30dd5c52020-08-01 14:43:44 -07001166 return std::make_tuple(timestamp, std::move(std::get<2>(oldest_message)));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001167 }
1168 } else {
1169 std::tuple<monotonic_clock::time_point, uint32_t,
1170 FlatbufferVector<MessageHeader>>
1171 oldest_message = PopMessageHeap();
1172
1173 TimestampMerger::DeliveryTimestamp timestamp;
1174 timestamp.monotonic_event_time =
1175 monotonic_clock::time_point(chrono::nanoseconds(
1176 std::get<2>(oldest_message).message().monotonic_sent_time()));
1177 timestamp.realtime_event_time =
1178 realtime_clock::time_point(chrono::nanoseconds(
1179 std::get<2>(oldest_message).message().realtime_sent_time()));
1180 timestamp.remote_queue_index = 0xffffffff;
1181
1182 CHECK_EQ(std::get<0>(oldest_message), timestamp.monotonic_event_time);
1183 CHECK_EQ(std::get<1>(oldest_message),
1184 std::get<2>(oldest_message).message().queue_index());
1185
Austin Schuh30dd5c52020-08-01 14:43:44 -07001186 return std::make_tuple(timestamp, std::move(std::get<2>(oldest_message)));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001187 }
1188}
1189
Austin Schuh8bd96322020-02-13 21:18:22 -08001190void TimestampMerger::NoticeAtEnd() { channel_merger_->NoticeAtEnd(); }
1191
Austin Schuh6f3babe2020-01-26 20:34:50 -08001192namespace {
1193std::vector<std::unique_ptr<SplitMessageReader>> MakeSplitMessageReaders(
1194 const std::vector<std::vector<std::string>> &filenames) {
1195 CHECK_GT(filenames.size(), 0u);
1196 // Build up all the SplitMessageReaders.
1197 std::vector<std::unique_ptr<SplitMessageReader>> result;
1198 for (const std::vector<std::string> &filenames : filenames) {
1199 result.emplace_back(std::make_unique<SplitMessageReader>(filenames));
1200 }
1201 return result;
1202}
1203} // namespace
1204
1205ChannelMerger::ChannelMerger(
1206 const std::vector<std::vector<std::string>> &filenames)
1207 : split_message_readers_(MakeSplitMessageReaders(filenames)),
Austin Schuh97789fc2020-08-01 14:42:45 -07001208 log_file_header_(split_message_readers_[0]->raw_log_file_header()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001209 // Now, confirm that the configuration matches for each and pick a start time.
1210 // Also return the list of possible nodes.
1211 for (const std::unique_ptr<SplitMessageReader> &reader :
1212 split_message_readers_) {
1213 CHECK(CompareFlatBuffer(log_file_header_.message().configuration(),
1214 reader->log_file_header()->configuration()))
1215 << ": Replaying log files with different configurations isn't "
1216 "supported";
1217 }
1218
1219 nodes_ = configuration::GetNodes(configuration());
1220}
1221
1222bool ChannelMerger::SetNode(const Node *target_node) {
1223 std::vector<SplitMessageReader *> split_message_readers;
1224 for (const std::unique_ptr<SplitMessageReader> &reader :
1225 split_message_readers_) {
1226 split_message_readers.emplace_back(reader.get());
1227 }
1228
1229 // Go find a log_file_header for this node.
1230 {
1231 bool found_node = false;
1232
1233 for (const std::unique_ptr<SplitMessageReader> &reader :
1234 split_message_readers_) {
James Kuszmaulfc273dc2020-05-09 17:56:19 -07001235 // In order to identify which logfile(s) map to the target node, do a
1236 // logical comparison of the nodes, by confirming that we are either in a
1237 // single-node setup (where the nodes will both be nullptr) or that the
1238 // node names match (but the other node fields--e.g., hostname lists--may
1239 // not).
1240 const bool both_null =
1241 reader->node() == nullptr && target_node == nullptr;
1242 const bool both_have_name =
1243 (reader->node() != nullptr) && (target_node != nullptr) &&
1244 (reader->node()->has_name() && target_node->has_name());
1245 const bool node_names_identical =
Brian Silvermand90905f2020-09-23 14:42:56 -07001246 both_have_name && (reader->node()->name()->string_view() ==
1247 target_node->name()->string_view());
James Kuszmaulfc273dc2020-05-09 17:56:19 -07001248 if (both_null || node_names_identical) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001249 if (!found_node) {
1250 found_node = true;
1251 log_file_header_ = CopyFlatBuffer(reader->log_file_header());
Austin Schuhcde938c2020-02-02 17:30:07 -08001252 VLOG(1) << "Found log file " << reader->filename() << " with node "
1253 << FlatbufferToJson(reader->node()) << " start_time "
1254 << monotonic_start_time();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001255 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001256 // Find the earliest start time. That way, if we get a full log file
1257 // directly from the node, and a partial later, we start with the
1258 // full. Update our header to match that.
1259 const monotonic_clock::time_point new_monotonic_start_time(
1260 chrono::nanoseconds(
1261 reader->log_file_header()->monotonic_start_time()));
1262 const realtime_clock::time_point new_realtime_start_time(
1263 chrono::nanoseconds(
1264 reader->log_file_header()->realtime_start_time()));
1265
1266 if (monotonic_start_time() == monotonic_clock::min_time ||
1267 (new_monotonic_start_time != monotonic_clock::min_time &&
1268 new_monotonic_start_time < monotonic_start_time())) {
1269 log_file_header_.mutable_message()->mutate_monotonic_start_time(
1270 new_monotonic_start_time.time_since_epoch().count());
1271 log_file_header_.mutable_message()->mutate_realtime_start_time(
1272 new_realtime_start_time.time_since_epoch().count());
1273 VLOG(1) << "Updated log file " << reader->filename()
1274 << " with node " << FlatbufferToJson(reader->node())
1275 << " start_time " << new_monotonic_start_time;
1276 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001277 }
1278 }
1279 }
1280
1281 if (!found_node) {
1282 LOG(WARNING) << "Failed to find log file for node "
1283 << FlatbufferToJson(target_node);
1284 return false;
1285 }
1286 }
1287
1288 // Build up all the timestamp mergers. This connects up all the
1289 // SplitMessageReaders.
1290 timestamp_mergers_.reserve(configuration()->channels()->size());
1291 for (size_t channel_index = 0;
1292 channel_index < configuration()->channels()->size(); ++channel_index) {
1293 timestamp_mergers_.emplace_back(
1294 configuration(), split_message_readers, channel_index,
1295 configuration::GetNode(configuration(), target_node), this);
1296 }
1297
1298 // And prime everything.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001299 for (std::unique_ptr<SplitMessageReader> &split_message_reader :
1300 split_message_readers_) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001301 split_message_reader->QueueMessages(
1302 split_message_reader->monotonic_start_time());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001303 }
1304
1305 node_ = configuration::GetNodeOrDie(configuration(), target_node);
1306 return true;
1307}
1308
Austin Schuh858c9f32020-08-31 16:56:12 -07001309monotonic_clock::time_point ChannelMerger::OldestMessageTime() const {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001310 if (channel_heap_.empty()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001311 return monotonic_clock::max_time;
1312 }
1313 return channel_heap_.front().first;
1314}
1315
1316void ChannelMerger::PushChannelHeap(monotonic_clock::time_point timestamp,
1317 int channel_index) {
1318 // Pop and recreate the heap if it has already been pushed. And since we are
1319 // pushing again, we don't need to clear pushed.
1320 if (timestamp_mergers_[channel_index].pushed()) {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001321 const auto channel_iterator = std::find_if(
Austin Schuh6f3babe2020-01-26 20:34:50 -08001322 channel_heap_.begin(), channel_heap_.end(),
1323 [channel_index](const std::pair<monotonic_clock::time_point, int> x) {
1324 return x.second == channel_index;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001325 });
1326 DCHECK(channel_iterator != channel_heap_.end());
1327 if (std::get<0>(*channel_iterator) == timestamp) {
1328 // It's already in the heap, in the correct spot, so nothing
1329 // more for us to do here.
1330 return;
1331 }
1332 channel_heap_.erase(channel_iterator);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001333 std::make_heap(channel_heap_.begin(), channel_heap_.end(),
1334 ChannelHeapCompare);
1335 }
1336
Austin Schuh2f8fd752020-09-01 22:38:28 -07001337 if (timestamp == monotonic_clock::min_time) {
1338 timestamp_mergers_[channel_index].set_pushed(false);
1339 return;
1340 }
1341
Austin Schuh05b70472020-01-01 17:11:17 -08001342 channel_heap_.push_back(std::make_pair(timestamp, channel_index));
1343
1344 // The default sort puts the newest message first. Use a custom comparator to
1345 // put the oldest message first.
1346 std::push_heap(channel_heap_.begin(), channel_heap_.end(),
1347 ChannelHeapCompare);
1348}
1349
Austin Schuh2f8fd752020-09-01 22:38:28 -07001350void ChannelMerger::VerifyHeaps() {
Austin Schuh661a8d82020-09-13 17:25:56 -07001351 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap =
1352 channel_heap_;
1353 std::make_heap(channel_heap.begin(), channel_heap.end(), &ChannelHeapCompare);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001354
Austin Schuh661a8d82020-09-13 17:25:56 -07001355 for (size_t i = 0; i < channel_heap_.size(); ++i) {
1356 CHECK(channel_heap_[i] == channel_heap[i]) << ": Heaps diverged...";
1357 CHECK_EQ(
1358 std::get<0>(channel_heap[i]),
1359 timestamp_mergers_[std::get<1>(channel_heap[i])].channel_merger_time());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001360 }
1361}
1362
Austin Schuh6f3babe2020-01-26 20:34:50 -08001363std::tuple<TimestampMerger::DeliveryTimestamp, int,
1364 FlatbufferVector<MessageHeader>>
1365ChannelMerger::PopOldest() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001366 CHECK_GT(channel_heap_.size(), 0u);
Austin Schuh05b70472020-01-01 17:11:17 -08001367 std::pair<monotonic_clock::time_point, int> oldest_channel_data =
1368 channel_heap_.front();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001369 int channel_index = oldest_channel_data.second;
Austin Schuh05b70472020-01-01 17:11:17 -08001370 std::pop_heap(channel_heap_.begin(), channel_heap_.end(),
1371 &ChannelHeapCompare);
1372 channel_heap_.pop_back();
Austin Schuh8bd96322020-02-13 21:18:22 -08001373
Austin Schuh6f3babe2020-01-26 20:34:50 -08001374 timestamp_mergers_[channel_index].set_pushed(false);
Austin Schuh05b70472020-01-01 17:11:17 -08001375
Austin Schuh6f3babe2020-01-26 20:34:50 -08001376 TimestampMerger *merger = &timestamp_mergers_[channel_index];
Austin Schuh05b70472020-01-01 17:11:17 -08001377
Austin Schuhcde938c2020-02-02 17:30:07 -08001378 // Merger handles any queueing needed from here.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001379 std::tuple<TimestampMerger::DeliveryTimestamp,
1380 FlatbufferVector<MessageHeader>>
1381 message = merger->PopOldest();
Brian Silverman8a32ce62020-08-12 12:02:38 -07001382 DCHECK_EQ(std::get<0>(message).monotonic_event_time,
1383 oldest_channel_data.first)
1384 << ": channel_heap_ was corrupted for " << channel_index << ": "
1385 << DebugString();
Austin Schuh05b70472020-01-01 17:11:17 -08001386
Austin Schuh2f8fd752020-09-01 22:38:28 -07001387 CHECK_GE(std::get<0>(message).monotonic_event_time, last_popped_time_)
1388 << ": " << MaybeNodeName(log_file_header()->node())
1389 << "Messages came off the queue out of order. " << DebugString();
1390 last_popped_time_ = std::get<0>(message).monotonic_event_time;
1391
1392 VLOG(1) << "Popped " << last_popped_time_ << " "
1393 << configuration::StrippedChannelToString(
1394 configuration()->channels()->Get(channel_index))
1395 << " (" << channel_index << ")";
1396
Austin Schuh6f3babe2020-01-26 20:34:50 -08001397 return std::make_tuple(std::get<0>(message), channel_index,
1398 std::move(std::get<1>(message)));
1399}
1400
Austin Schuhcde938c2020-02-02 17:30:07 -08001401std::string SplitMessageReader::MessageHeaderQueue::DebugString() const {
1402 std::stringstream ss;
1403 for (size_t i = 0; i < data_.size(); ++i) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001404 if (i < 5 || i + 5 > data_.size()) {
1405 if (timestamps) {
1406 ss << " msg: ";
1407 } else {
1408 ss << " timestamp: ";
1409 }
1410 ss << monotonic_clock::time_point(
1411 chrono::nanoseconds(data_[i].message().monotonic_sent_time()))
Austin Schuhcde938c2020-02-02 17:30:07 -08001412 << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001413 << realtime_clock::time_point(
1414 chrono::nanoseconds(data_[i].message().realtime_sent_time()))
1415 << ") " << data_[i].message().queue_index();
1416 if (timestamps) {
1417 ss << " <- remote "
1418 << monotonic_clock::time_point(chrono::nanoseconds(
1419 data_[i].message().monotonic_remote_time()))
1420 << " ("
1421 << realtime_clock::time_point(chrono::nanoseconds(
1422 data_[i].message().realtime_remote_time()))
1423 << ")";
1424 }
1425 ss << "\n";
1426 } else if (i == 5) {
1427 ss << " ...\n";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001428 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001429 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001430
Austin Schuhcde938c2020-02-02 17:30:07 -08001431 return ss.str();
1432}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001433
Austin Schuhcde938c2020-02-02 17:30:07 -08001434std::string SplitMessageReader::DebugString(int channel) const {
1435 std::stringstream ss;
1436 ss << "[\n";
1437 ss << channels_[channel].data.DebugString();
1438 ss << " ]";
1439 return ss.str();
1440}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001441
Austin Schuhcde938c2020-02-02 17:30:07 -08001442std::string SplitMessageReader::DebugString(int channel, int node_index) const {
1443 std::stringstream ss;
1444 ss << "[\n";
1445 ss << channels_[channel].timestamps[node_index].DebugString();
1446 ss << " ]";
1447 return ss.str();
1448}
1449
1450std::string TimestampMerger::DebugString() const {
1451 std::stringstream ss;
1452
1453 if (timestamp_heap_.size() > 0) {
1454 ss << " timestamp_heap {\n";
1455 std::vector<
1456 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1457 timestamp_heap = timestamp_heap_;
1458 while (timestamp_heap.size() > 0u) {
1459 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1460 oldest_timestamp_reader = timestamp_heap.front();
1461
1462 ss << " " << std::get<2>(oldest_timestamp_reader) << " "
1463 << std::get<0>(oldest_timestamp_reader) << " queue_index ("
1464 << std::get<1>(oldest_timestamp_reader) << ") ttq "
1465 << std::get<2>(oldest_timestamp_reader)->time_to_queue() << " "
1466 << std::get<2>(oldest_timestamp_reader)->filename() << " -> "
1467 << std::get<2>(oldest_timestamp_reader)
1468 ->DebugString(channel_index_, node_index_)
1469 << "\n";
1470
1471 std::pop_heap(timestamp_heap.begin(), timestamp_heap.end(),
1472 &SplitMessageReaderHeapCompare);
1473 timestamp_heap.pop_back();
1474 }
1475 ss << " }\n";
1476 }
1477
1478 ss << " message_heap {\n";
1479 {
1480 std::vector<
1481 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1482 message_heap = message_heap_;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001483 while (!message_heap.empty()) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001484 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1485 oldest_message_reader = message_heap.front();
1486
1487 ss << " " << std::get<2>(oldest_message_reader) << " "
1488 << std::get<0>(oldest_message_reader) << " queue_index ("
1489 << std::get<1>(oldest_message_reader) << ") ttq "
1490 << std::get<2>(oldest_message_reader)->time_to_queue() << " "
1491 << std::get<2>(oldest_message_reader)->filename() << " -> "
1492 << std::get<2>(oldest_message_reader)->DebugString(channel_index_)
1493 << "\n";
1494
1495 std::pop_heap(message_heap.begin(), message_heap.end(),
1496 &SplitMessageReaderHeapCompare);
1497 message_heap.pop_back();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001498 }
Austin Schuh05b70472020-01-01 17:11:17 -08001499 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001500 ss << " }";
1501
1502 return ss.str();
1503}
1504
1505std::string ChannelMerger::DebugString() const {
1506 std::stringstream ss;
1507 ss << "start_time " << realtime_start_time() << " " << monotonic_start_time()
1508 << "\n";
1509 ss << "channel_heap {\n";
1510 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap =
1511 channel_heap_;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001512 while (!channel_heap.empty()) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001513 std::tuple<monotonic_clock::time_point, int> channel = channel_heap.front();
1514 ss << " " << std::get<0>(channel) << " (" << std::get<1>(channel) << ") "
1515 << configuration::CleanedChannelToString(
1516 configuration()->channels()->Get(std::get<1>(channel)))
1517 << "\n";
1518
1519 ss << timestamp_mergers_[std::get<1>(channel)].DebugString() << "\n";
1520
1521 std::pop_heap(channel_heap.begin(), channel_heap.end(),
1522 &ChannelHeapCompare);
1523 channel_heap.pop_back();
1524 }
1525 ss << "}";
1526
1527 return ss.str();
Austin Schuh05b70472020-01-01 17:11:17 -08001528}
1529
Austin Schuhee711052020-08-24 16:06:09 -07001530std::string MaybeNodeName(const Node *node) {
1531 if (node != nullptr) {
1532 return node->name()->str() + " ";
1533 }
1534 return "";
1535}
1536
Brian Silvermanf51499a2020-09-21 12:49:08 -07001537} // namespace aos::logger