blob: 4474c7ef8eb2ec73d7b91c2444b64712af9e7411 [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
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070019#if defined(__x86_64__)
20#define ENABLE_LZMA 1
21#elif defined(__aarch64__)
22#define ENABLE_LZMA 1
23#else
24#define ENABLE_LZMA 0
25#endif
26
27#if ENABLE_LZMA
28#include "aos/events/logging/lzma_encoder.h"
29#endif
30
Austin Schuh7fbf5a72020-09-21 16:28:13 -070031DEFINE_int32(flush_size, 128000,
Austin Schuha36c8902019-12-30 18:07:15 -080032 "Number of outstanding bytes to allow before flushing to disk.");
33
Brian Silvermanf51499a2020-09-21 12:49:08 -070034namespace aos::logger {
Austin Schuha36c8902019-12-30 18:07:15 -080035
Austin Schuh05b70472020-01-01 17:11:17 -080036namespace chrono = std::chrono;
37
Brian Silvermanf51499a2020-09-21 12:49:08 -070038DetachedBufferWriter::DetachedBufferWriter(
39 std::string_view filename, std::unique_ptr<DetachedBufferEncoder> encoder)
40 : filename_(filename), encoder_(std::move(encoder)) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070041 if (!util::MkdirPIfSpace(filename, 0777)) {
42 ran_out_of_space_ = true;
43 } else {
44 fd_ = open(std::string(filename).c_str(),
45 O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, 0774);
46 if (fd_ == -1 && errno == ENOSPC) {
47 ran_out_of_space_ = true;
48 } else {
49 PCHECK(fd_ != -1) << ": Failed to open " << filename << " for writing";
50 VLOG(1) << "Opened " << filename << " for writing";
51 }
52 }
Austin Schuha36c8902019-12-30 18:07:15 -080053}
54
55DetachedBufferWriter::~DetachedBufferWriter() {
Brian Silverman0465fcf2020-09-24 00:29:18 -070056 Close();
57 if (ran_out_of_space_) {
58 CHECK(acknowledge_ran_out_of_space_)
59 << ": Unacknowledged out of disk space, log file was not completed";
Brian Silvermanf51499a2020-09-21 12:49:08 -070060 }
Austin Schuh2f8fd752020-09-01 22:38:28 -070061}
62
Brian Silvermand90905f2020-09-23 14:42:56 -070063DetachedBufferWriter::DetachedBufferWriter(DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070064 *this = std::move(other);
65}
66
Brian Silverman87ac0402020-09-17 14:47:01 -070067// When other is destroyed "soon" (which it should be because we're getting an
68// rvalue reference to it), it will flush etc all the data we have queued up
69// (because that data will then be its data).
Austin Schuh2f8fd752020-09-01 22:38:28 -070070DetachedBufferWriter &DetachedBufferWriter::operator=(
71 DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070072 std::swap(filename_, other.filename_);
Brian Silvermanf51499a2020-09-21 12:49:08 -070073 std::swap(encoder_, other.encoder_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070074 std::swap(fd_, other.fd_);
Brian Silverman0465fcf2020-09-24 00:29:18 -070075 std::swap(ran_out_of_space_, other.ran_out_of_space_);
76 std::swap(acknowledge_ran_out_of_space_, other.acknowledge_ran_out_of_space_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070077 std::swap(iovec_, other.iovec_);
Brian Silvermanf51499a2020-09-21 12:49:08 -070078 std::swap(max_write_time_, other.max_write_time_);
79 std::swap(max_write_time_bytes_, other.max_write_time_bytes_);
80 std::swap(max_write_time_messages_, other.max_write_time_messages_);
81 std::swap(total_write_time_, other.total_write_time_);
82 std::swap(total_write_count_, other.total_write_count_);
83 std::swap(total_write_messages_, other.total_write_messages_);
84 std::swap(total_write_bytes_, other.total_write_bytes_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070085 return *this;
Austin Schuha36c8902019-12-30 18:07:15 -080086}
87
Brian Silvermanf51499a2020-09-21 12:49:08 -070088void DetachedBufferWriter::QueueSpan(absl::Span<const uint8_t> span) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070089 if (ran_out_of_space_) {
90 // We don't want any later data to be written after space becomes
91 // available, so refuse to write anything more once we've dropped data
92 // because we ran out of space.
93 VLOG(1) << "Ignoring span: " << span.size();
94 return;
95 }
96
Brian Silvermanf51499a2020-09-21 12:49:08 -070097 if (encoder_->may_bypass() && span.size() > 4096u) {
98 // Over this threshold, we'll assume it's cheaper to add an extra
99 // syscall to write the data immediately instead of copying it to
100 // enqueue.
Austin Schuha36c8902019-12-30 18:07:15 -0800101
Brian Silvermanf51499a2020-09-21 12:49:08 -0700102 // First, flush everything.
103 while (encoder_->queue_size() > 0u) {
104 Flush();
105 }
Austin Schuhde031b72020-01-10 19:34:41 -0800106
Brian Silvermanf51499a2020-09-21 12:49:08 -0700107 // Then, write it directly.
108 const auto start = aos::monotonic_clock::now();
109 const ssize_t written = write(fd_, span.data(), span.size());
110 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700111 HandleWriteReturn(written, span.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700112 UpdateStatsForWrite(end - start, written, 1);
113 } else {
114 encoder_->Encode(CopySpanAsDetachedBuffer(span));
Austin Schuha36c8902019-12-30 18:07:15 -0800115 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700116
117 FlushAtThreshold();
Austin Schuha36c8902019-12-30 18:07:15 -0800118}
119
Brian Silverman0465fcf2020-09-24 00:29:18 -0700120void DetachedBufferWriter::Close() {
121 if (fd_ == -1) {
122 return;
123 }
124 encoder_->Finish();
125 while (encoder_->queue_size() > 0) {
126 Flush();
127 }
128 if (close(fd_) == -1) {
129 if (errno == ENOSPC) {
130 ran_out_of_space_ = true;
131 } else {
132 PLOG(ERROR) << "Closing log file failed";
133 }
134 }
135 fd_ = -1;
136 VLOG(1) << "Closed " << filename_;
137}
138
Austin Schuha36c8902019-12-30 18:07:15 -0800139void DetachedBufferWriter::Flush() {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700140 const auto queue = encoder_->queue();
141 if (queue.empty()) {
Austin Schuha36c8902019-12-30 18:07:15 -0800142 return;
143 }
Brian Silverman0465fcf2020-09-24 00:29:18 -0700144 if (ran_out_of_space_) {
145 // We don't want any later data to be written after space becomes available,
146 // so refuse to write anything more once we've dropped data because we ran
147 // out of space.
148 VLOG(1) << "Ignoring queue: " << queue.size();
149 encoder_->Clear(queue.size());
150 return;
151 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700152
Austin Schuha36c8902019-12-30 18:07:15 -0800153 iovec_.clear();
Brian Silvermanf51499a2020-09-21 12:49:08 -0700154 const size_t iovec_size = std::min<size_t>(queue.size(), IOV_MAX);
155 iovec_.resize(iovec_size);
Austin Schuha36c8902019-12-30 18:07:15 -0800156 size_t counted_size = 0;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700157 for (size_t i = 0; i < iovec_size; ++i) {
158 iovec_[i].iov_base = const_cast<uint8_t *>(queue[i].data());
159 iovec_[i].iov_len = queue[i].size();
160 counted_size += iovec_[i].iov_len;
Austin Schuha36c8902019-12-30 18:07:15 -0800161 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700162
163 const auto start = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800164 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700165 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700166 HandleWriteReturn(written, counted_size);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700167
168 encoder_->Clear(iovec_size);
169
170 UpdateStatsForWrite(end - start, written, iovec_size);
171}
172
Brian Silverman0465fcf2020-09-24 00:29:18 -0700173void DetachedBufferWriter::HandleWriteReturn(ssize_t write_return,
174 size_t write_size) {
175 if (write_return == -1 && errno == ENOSPC) {
176 ran_out_of_space_ = true;
177 return;
178 }
179 PCHECK(write_return >= 0) << ": write failed";
180 if (write_return < static_cast<ssize_t>(write_size)) {
181 // Sometimes this happens instead of ENOSPC. On a real filesystem, this
182 // never seems to happen in any other case. If we ever want to log to a
183 // socket, this will happen more often. However, until we get there, we'll
184 // just assume it means we ran out of space.
185 ran_out_of_space_ = true;
186 return;
187 }
188}
189
Brian Silvermanf51499a2020-09-21 12:49:08 -0700190void DetachedBufferWriter::UpdateStatsForWrite(
191 aos::monotonic_clock::duration duration, ssize_t written, int iovec_size) {
192 if (duration > max_write_time_) {
193 max_write_time_ = duration;
194 max_write_time_bytes_ = written;
195 max_write_time_messages_ = iovec_size;
196 }
197 total_write_time_ += duration;
198 ++total_write_count_;
199 total_write_messages_ += iovec_size;
200 total_write_bytes_ += written;
201}
202
203void DetachedBufferWriter::FlushAtThreshold() {
204 // Flush if we are at the max number of iovs per writev, because there's no
205 // point queueing up any more data in memory. Also flush once we have enough
206 // data queued up.
207 while (encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
208 encoder_->queue_size() >= IOV_MAX) {
209 Flush();
210 }
Austin Schuha36c8902019-12-30 18:07:15 -0800211}
212
213flatbuffers::Offset<MessageHeader> PackMessage(
214 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
215 int channel_index, LogType log_type) {
216 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
217
218 switch (log_type) {
219 case LogType::kLogMessage:
220 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800221 case LogType::kLogRemoteMessage:
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700222 data_offset = fbb->CreateVector(
223 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800224 break;
225
226 case LogType::kLogDeliveryTimeOnly:
227 break;
228 }
229
230 MessageHeader::Builder message_header_builder(*fbb);
231 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800232
233 switch (log_type) {
234 case LogType::kLogRemoteMessage:
235 message_header_builder.add_queue_index(context.remote_queue_index);
236 message_header_builder.add_monotonic_sent_time(
237 context.monotonic_remote_time.time_since_epoch().count());
238 message_header_builder.add_realtime_sent_time(
239 context.realtime_remote_time.time_since_epoch().count());
240 break;
241
242 case LogType::kLogMessage:
243 case LogType::kLogMessageAndDeliveryTime:
244 case LogType::kLogDeliveryTimeOnly:
245 message_header_builder.add_queue_index(context.queue_index);
246 message_header_builder.add_monotonic_sent_time(
247 context.monotonic_event_time.time_since_epoch().count());
248 message_header_builder.add_realtime_sent_time(
249 context.realtime_event_time.time_since_epoch().count());
250 break;
251 }
Austin Schuha36c8902019-12-30 18:07:15 -0800252
253 switch (log_type) {
254 case LogType::kLogMessage:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800255 case LogType::kLogRemoteMessage:
Austin Schuha36c8902019-12-30 18:07:15 -0800256 message_header_builder.add_data(data_offset);
257 break;
258
259 case LogType::kLogMessageAndDeliveryTime:
260 message_header_builder.add_data(data_offset);
261 [[fallthrough]];
262
263 case LogType::kLogDeliveryTimeOnly:
264 message_header_builder.add_monotonic_remote_time(
265 context.monotonic_remote_time.time_since_epoch().count());
266 message_header_builder.add_realtime_remote_time(
267 context.realtime_remote_time.time_since_epoch().count());
268 message_header_builder.add_remote_queue_index(context.remote_queue_index);
269 break;
270 }
271
272 return message_header_builder.Finish();
273}
274
Brian Silvermanf51499a2020-09-21 12:49:08 -0700275SpanReader::SpanReader(std::string_view filename) : filename_(filename) {
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700276 static const std::string_view kXz = ".xz";
277 if (filename.substr(filename.size() - kXz.size()) == kXz) {
278#if ENABLE_LZMA
279 decoder_ = std::make_unique<LzmaDecoder>(filename);
280#else
281 LOG(FATAL) << "Reading xz-compressed files not supported on this platform";
282#endif
283 } else {
284 decoder_ = std::make_unique<DummyDecoder>(filename);
285 }
Austin Schuh05b70472020-01-01 17:11:17 -0800286}
287
288absl::Span<const uint8_t> SpanReader::ReadMessage() {
289 // Make sure we have enough for the size.
290 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
291 if (!ReadBlock()) {
292 return absl::Span<const uint8_t>();
293 }
294 }
295
296 // Now make sure we have enough for the message.
297 const size_t data_size =
298 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
299 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -0800300 if (data_size == sizeof(flatbuffers::uoffset_t)) {
301 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
302 LOG(ERROR) << " Rest of log file is "
303 << absl::BytesToHexString(std::string_view(
304 reinterpret_cast<const char *>(data_.data() +
305 consumed_data_),
306 data_.size() - consumed_data_));
307 return absl::Span<const uint8_t>();
308 }
Austin Schuh05b70472020-01-01 17:11:17 -0800309 while (data_.size() < consumed_data_ + data_size) {
310 if (!ReadBlock()) {
311 return absl::Span<const uint8_t>();
312 }
313 }
314
315 // And return it, consuming the data.
316 const uint8_t *data_ptr = data_.data() + consumed_data_;
317
318 consumed_data_ += data_size;
319
320 return absl::Span<const uint8_t>(data_ptr, data_size);
321}
322
Austin Schuh05b70472020-01-01 17:11:17 -0800323bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700324 // This is the amount of data we grab at a time. Doing larger chunks minimizes
325 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -0800326 constexpr size_t kReadSize = 256 * 1024;
327
328 // Strip off any unused data at the front.
329 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700330 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -0800331 consumed_data_ = 0;
332 }
333
334 const size_t starting_size = data_.size();
335
336 // This should automatically grow the backing store. It won't shrink if we
337 // get a small chunk later. This reduces allocations when we want to append
338 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700339 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -0800340
Brian Silvermanf51499a2020-09-21 12:49:08 -0700341 const size_t count =
342 decoder_->Read(data_.begin() + starting_size, data_.end());
343 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -0800344 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -0800345 return false;
346 }
Austin Schuh05b70472020-01-01 17:11:17 -0800347
348 return true;
349}
350
Austin Schuhadd6eb32020-11-09 21:24:26 -0800351std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800352 std::string_view filename) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800353 SpanReader span_reader(filename);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800354 absl::Span<const uint8_t> config_data = span_reader.ReadMessage();
355
356 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800357 if (config_data == absl::Span<const uint8_t>()) {
358 return std::nullopt;
359 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800360
Austin Schuh5212cad2020-09-09 23:12:09 -0700361 // And copy the config so we have it forever, removing the size prefix.
Brian Silverman354697a2020-09-22 21:06:32 -0700362 ResizeableBuffer data;
Austin Schuhadd6eb32020-11-09 21:24:26 -0800363 data.resize(config_data.size());
364 memcpy(data.data(), config_data.begin(), data.size());
365 return SizePrefixedFlatbufferVector<LogFileHeader>(std::move(data));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800366}
367
Austin Schuhadd6eb32020-11-09 21:24:26 -0800368std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800369 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -0700370 SpanReader span_reader(filename);
371 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
372 for (size_t i = 0; i < n + 1; ++i) {
373 data_span = span_reader.ReadMessage();
374
375 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800376 if (data_span == absl::Span<const uint8_t>()) {
377 return std::nullopt;
378 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700379 }
380
Brian Silverman354697a2020-09-22 21:06:32 -0700381 // And copy the config so we have it forever, removing the size prefix.
382 ResizeableBuffer data;
Austin Schuhadd6eb32020-11-09 21:24:26 -0800383 data.resize(data_span.size());
384 memcpy(data.data(), data_span.begin(), data.size());
385 return SizePrefixedFlatbufferVector<MessageHeader>(std::move(data));
Austin Schuh5212cad2020-09-09 23:12:09 -0700386}
387
Austin Schuh05b70472020-01-01 17:11:17 -0800388MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -0700389 : span_reader_(filename),
Austin Schuhadd6eb32020-11-09 21:24:26 -0800390 raw_log_file_header_(
391 SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuh05b70472020-01-01 17:11:17 -0800392 // Make sure we have enough to read the size.
Austin Schuh97789fc2020-08-01 14:42:45 -0700393 absl::Span<const uint8_t> header_data = span_reader_.ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800394
395 // Make sure something was read.
Austin Schuh97789fc2020-08-01 14:42:45 -0700396 CHECK(header_data != absl::Span<const uint8_t>())
397 << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -0800398
Austin Schuh97789fc2020-08-01 14:42:45 -0700399 // And copy the header data so we have it forever.
Brian Silverman354697a2020-09-22 21:06:32 -0700400 ResizeableBuffer header_data_copy;
Austin Schuhadd6eb32020-11-09 21:24:26 -0800401 header_data_copy.resize(header_data.size());
402 memcpy(header_data_copy.data(), header_data.begin(), header_data_copy.size());
Austin Schuh97789fc2020-08-01 14:42:45 -0700403 raw_log_file_header_ =
Austin Schuhadd6eb32020-11-09 21:24:26 -0800404 SizePrefixedFlatbufferVector<LogFileHeader>(std::move(header_data_copy));
Austin Schuh05b70472020-01-01 17:11:17 -0800405
Austin Schuhcde938c2020-02-02 17:30:07 -0800406 max_out_of_order_duration_ =
Austin Schuh2f8fd752020-09-01 22:38:28 -0700407 chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -0800408
409 VLOG(1) << "Opened " << filename << " as node "
410 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800411}
412
Austin Schuhadd6eb32020-11-09 21:24:26 -0800413std::optional<SizePrefixedFlatbufferVector<MessageHeader>>
414MessageReader::ReadMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -0800415 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
416 if (msg_data == absl::Span<const uint8_t>()) {
417 return std::nullopt;
418 }
419
Brian Silverman354697a2020-09-22 21:06:32 -0700420 ResizeableBuffer result_buffer;
Austin Schuhadd6eb32020-11-09 21:24:26 -0800421 result_buffer.resize(msg_data.size());
422 memcpy(result_buffer.data(), msg_data.begin(), result_buffer.size());
423 SizePrefixedFlatbufferVector<MessageHeader> result(std::move(result_buffer));
Austin Schuh05b70472020-01-01 17:11:17 -0800424
425 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
426 chrono::nanoseconds(result.message().monotonic_sent_time()));
427
428 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuh8bd96322020-02-13 21:18:22 -0800429 VLOG(2) << "Read from " << filename() << " data " << FlatbufferToJson(result);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800430 return std::move(result);
Austin Schuh05b70472020-01-01 17:11:17 -0800431}
432
Austin Schuhc41603c2020-10-11 16:17:37 -0700433PartsMessageReader::PartsMessageReader(LogParts log_parts)
434 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {}
435
Austin Schuhadd6eb32020-11-09 21:24:26 -0800436std::optional<SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuhc41603c2020-10-11 16:17:37 -0700437PartsMessageReader::ReadMessage() {
438 while (!done_) {
Austin Schuhadd6eb32020-11-09 21:24:26 -0800439 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> message =
Austin Schuhc41603c2020-10-11 16:17:37 -0700440 message_reader_.ReadMessage();
441 if (message) {
442 newest_timestamp_ = message_reader_.newest_timestamp();
Austin Schuh32f68492020-11-08 21:45:51 -0800443 const monotonic_clock::time_point monotonic_sent_time(
444 chrono::nanoseconds(message->message().monotonic_sent_time()));
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800445 // TODO(austin): Does this work with startup? Might need to use the start
446 // time.
447 // TODO(austin): Does this work with startup when we don't know the remote
448 // start time too? Look at one of those logs to compare.
Austin Schuh32f68492020-11-08 21:45:51 -0800449 CHECK_GE(monotonic_sent_time,
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800450 newest_timestamp_ - max_out_of_order_duration())
451 << ": Max out of order exceeded.";
Austin Schuhc41603c2020-10-11 16:17:37 -0700452 return message;
453 }
454 NextLog();
455 }
Austin Schuh32f68492020-11-08 21:45:51 -0800456 newest_timestamp_ = monotonic_clock::max_time;
Austin Schuhc41603c2020-10-11 16:17:37 -0700457 return std::nullopt;
458}
459
460void PartsMessageReader::NextLog() {
461 if (next_part_index_ == parts_.parts.size()) {
462 done_ = true;
463 return;
464 }
465 message_reader_ = MessageReader(parts_.parts[next_part_index_]);
466 ++next_part_index_;
467}
468
Austin Schuh1be0ce42020-11-29 22:43:26 -0800469bool Message::operator<(const Message &m2) const {
470 if (this->timestamp < m2.timestamp) {
471 return true;
472 } else if (this->timestamp > m2.timestamp) {
473 return false;
474 }
475
476 if (this->channel_index < m2.channel_index) {
477 return true;
478 } else if (this->channel_index > m2.channel_index) {
479 return false;
480 }
481
482 return this->queue_index < m2.queue_index;
483}
484
485bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800486bool Message::operator==(const Message &m2) const {
487 return timestamp == m2.timestamp && channel_index == m2.channel_index &&
488 queue_index == m2.queue_index;
489}
Austin Schuh1be0ce42020-11-29 22:43:26 -0800490
491std::ostream &operator<<(std::ostream &os, const Message &m) {
492 os << "{.channel_index=" << m.channel_index
493 << ", .queue_index=" << m.queue_index << ", .timestamp=" << m.timestamp
494 << ", .data="
495 << aos::FlatbufferToJson(m.data,
496 {.multi_line = false, .max_vector_size = 1})
497 << "}";
498 return os;
499}
500
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800501LogPartsSorter::LogPartsSorter(LogParts log_parts)
502 : parts_message_reader_(log_parts) {}
503
504Message *LogPartsSorter::Front() {
505 // Queue up data until enough data has been queued that the front message is
506 // sorted enough to be safe to pop. This may do nothing, so we should make
507 // sure the nothing path is checked quickly.
508 if (sorted_until() != monotonic_clock::max_time) {
509 while (true) {
510 if (!messages_.empty() && messages_.begin()->timestamp < sorted_until()) {
511 break;
512 }
513
514 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> m =
515 parts_message_reader_.ReadMessage();
516 // No data left, sorted forever, work through what is left.
517 if (!m) {
518 sorted_until_ = monotonic_clock::max_time;
519 break;
520 }
521
522 messages_.insert(
523 {.channel_index = m.value().message().channel_index(),
524 .queue_index = m.value().message().queue_index(),
525 .timestamp = monotonic_clock::time_point(std::chrono::nanoseconds(
526 m.value().message().monotonic_sent_time())),
527 .data = std::move(m.value())});
528
529 // Now, update sorted_until_ to match the new message.
530 if (parts_message_reader_.newest_timestamp() >
531 monotonic_clock::min_time +
532 parts_message_reader_.max_out_of_order_duration()) {
533 sorted_until_ = parts_message_reader_.newest_timestamp() -
534 parts_message_reader_.max_out_of_order_duration();
535 } else {
536 sorted_until_ = monotonic_clock::min_time;
537 }
538 }
539 }
540
541 // Now that we have enough data queued, return a pointer to the oldest piece
542 // of data if it exists.
543 if (messages_.empty()) {
544 return nullptr;
545 }
546
547 return &(*messages_.begin());
548}
549
550void LogPartsSorter::PopFront() { messages_.erase(messages_.begin()); }
551
552std::string LogPartsSorter::DebugString() const {
553 std::stringstream ss;
554 ss << "messages: [\n";
555 for (const Message &m : messages_) {
556 ss << m << "\n";
557 }
558 ss << "] <- " << parts_message_reader_.filename();
559 return ss.str();
560}
561
Austin Schuh8f52ed52020-11-30 23:12:39 -0800562NodeMerger::NodeMerger(std::vector<std::unique_ptr<LogPartsSorter>> parts)
563 : parts_sorters_(std::move(parts)) {}
564
565Message *NodeMerger::Front() {
566 // Return the current Front if we have one, otherwise go compute one.
567 if (current_ != nullptr) {
568 return current_->Front();
569 }
570
571 // Otherwise, do a simple search for the oldest message, deduplicating any
572 // duplicates.
573 Message *oldest = nullptr;
574 sorted_until_ = monotonic_clock::max_time;
575 for (std::unique_ptr<LogPartsSorter> &parts_sorter : parts_sorters_) {
576 Message *m = parts_sorter->Front();
577 if (!m) {
578 sorted_until_ = std::min(sorted_until_, parts_sorter->sorted_until());
579 continue;
580 }
581 if (oldest == nullptr || *m < *oldest) {
582 oldest = m;
583 current_ = parts_sorter.get();
584 } else if (*m == *oldest) {
585 // Found a duplicate. It doesn't matter which one we return. It is
586 // easiest to just drop the new one.
587 parts_sorter->PopFront();
588 }
589
590 // PopFront may change this, so compute it down here.
591 sorted_until_ = std::min(sorted_until_, parts_sorter->sorted_until());
592 }
593
594 // Return the oldest message found. This will be nullptr if nothing was
595 // found, indicating there is nothing left.
596 return oldest;
597}
598
599void NodeMerger::PopFront() {
600 CHECK(current_ != nullptr) << "Popping before calling Front()";
601 current_->PopFront();
602 current_ = nullptr;
603}
604
Austin Schuh6f3babe2020-01-26 20:34:50 -0800605SplitMessageReader::SplitMessageReader(
Austin Schuhfa895892020-01-07 20:07:41 -0800606 const std::vector<std::string> &filenames)
607 : filenames_(filenames),
Austin Schuhadd6eb32020-11-09 21:24:26 -0800608 log_file_header_(SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuhfa895892020-01-07 20:07:41 -0800609 CHECK(NextLogFile()) << ": filenames is empty. Need files to read.";
610
Austin Schuh6f3babe2020-01-26 20:34:50 -0800611 // Grab any log file header. They should all match (and we will check as we
612 // open more of them).
Austin Schuh97789fc2020-08-01 14:42:45 -0700613 log_file_header_ = message_reader_->raw_log_file_header();
Austin Schuhfa895892020-01-07 20:07:41 -0800614
Austin Schuh2f8fd752020-09-01 22:38:28 -0700615 for (size_t i = 1; i < filenames_.size(); ++i) {
616 MessageReader message_reader(filenames_[i]);
617
618 const monotonic_clock::time_point new_monotonic_start_time(
619 chrono::nanoseconds(
620 message_reader.log_file_header()->monotonic_start_time()));
621 const realtime_clock::time_point new_realtime_start_time(
622 chrono::nanoseconds(
623 message_reader.log_file_header()->realtime_start_time()));
624
625 // There are 2 types of part files. Part files from before time estimation
626 // has started, and part files after. We don't declare a log file "started"
627 // until time estimation is up. And once a log file starts, it should never
628 // stop again, and should remain constant.
629 // To compare both types of headers, we mutate our saved copy of the header
630 // to match the next chunk by updating time if we detect a stopped ->
631 // started transition.
632 if (monotonic_start_time() == monotonic_clock::min_time) {
633 CHECK_EQ(realtime_start_time(), realtime_clock::min_time);
634 // We should only be missing the monotonic start time when logging data
Brian Silverman87ac0402020-09-17 14:47:01 -0700635 // for remote nodes. We don't have a good way to determine the remote
Austin Schuh2f8fd752020-09-01 22:38:28 -0700636 // realtime offset, so it shouldn't be filled out.
637 // TODO(austin): If we have a good way, feel free to fill it out. It
638 // probably won't be better than we could do in post though with the same
639 // data.
640 CHECK(!log_file_header_.mutable_message()->has_realtime_start_time());
641 if (new_monotonic_start_time != monotonic_clock::min_time) {
642 // If we finally found our start time, update the header. Do this once
643 // because it should never change again.
644 log_file_header_.mutable_message()->mutate_monotonic_start_time(
645 new_monotonic_start_time.time_since_epoch().count());
646 log_file_header_.mutable_message()->mutate_realtime_start_time(
647 new_realtime_start_time.time_since_epoch().count());
648 }
649 }
650
Austin Schuh64fab802020-09-09 22:47:47 -0700651 // We don't have a good way to set the realtime start time on remote nodes.
652 // Confirm it remains consistent.
653 CHECK_EQ(log_file_header_.mutable_message()->has_realtime_start_time(),
654 message_reader.log_file_header()->has_realtime_start_time());
655
656 // Parts index will *not* match unless we set them to match. We only want
657 // to accept the start time and parts mismatching, so set them.
658 log_file_header_.mutable_message()->mutate_parts_index(
659 message_reader.log_file_header()->parts_index());
660
Austin Schuh2f8fd752020-09-01 22:38:28 -0700661 // Now compare that the headers match.
Austin Schuh64fab802020-09-09 22:47:47 -0700662 if (!CompareFlatBuffer(message_reader.raw_log_file_header(),
663 log_file_header_)) {
Brian Silvermanae7c0332020-09-30 16:58:23 -0700664 if (message_reader.log_file_header()->has_log_event_uuid() &&
665 log_file_header_.message().has_log_event_uuid() &&
666 message_reader.log_file_header()->log_event_uuid()->string_view() !=
667 log_file_header_.message().log_event_uuid()->string_view()) {
Austin Schuh64fab802020-09-09 22:47:47 -0700668 LOG(FATAL) << "Logger UUIDs don't match between log file chunks "
669 << filenames_[0] << " and " << filenames_[i]
670 << ", this is not supported.";
671 }
672 if (message_reader.log_file_header()->has_parts_uuid() &&
673 log_file_header_.message().has_parts_uuid() &&
674 message_reader.log_file_header()->parts_uuid()->string_view() !=
675 log_file_header_.message().parts_uuid()->string_view()) {
676 LOG(FATAL) << "Parts UUIDs don't match between log file chunks "
677 << filenames_[0] << " and " << filenames_[i]
678 << ", this is not supported.";
679 }
680
681 LOG(FATAL) << "Header is different between log file chunks "
682 << filenames_[0] << " and " << filenames_[i]
683 << ", this is not supported.";
684 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700685 }
Austin Schuh64fab802020-09-09 22:47:47 -0700686 // Put the parts index back to the first log file chunk.
687 log_file_header_.mutable_message()->mutate_parts_index(
688 message_reader_->log_file_header()->parts_index());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700689
Austin Schuh6f3babe2020-01-26 20:34:50 -0800690 // Setup per channel state.
Austin Schuh05b70472020-01-01 17:11:17 -0800691 channels_.resize(configuration()->channels()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800692 for (ChannelData &channel_data : channels_) {
693 channel_data.data.split_reader = this;
694 // Build up the timestamp list.
695 if (configuration::MultiNode(configuration())) {
696 channel_data.timestamps.resize(configuration()->nodes()->size());
697 for (MessageHeaderQueue &queue : channel_data.timestamps) {
698 queue.timestamps = true;
699 queue.split_reader = this;
700 }
701 }
702 }
Austin Schuh05b70472020-01-01 17:11:17 -0800703
Austin Schuh6f3babe2020-01-26 20:34:50 -0800704 // Build up channels_to_write_ as an optimization to make it fast to figure
705 // out which datastructure to place any new data from a channel on.
706 for (const Channel *channel : *configuration()->channels()) {
707 // This is the main case. We will only see data on this node.
708 if (configuration::ChannelIsSendableOnNode(channel, node())) {
709 channels_to_write_.emplace_back(
710 &channels_[channels_to_write_.size()].data);
711 } else
712 // If we can't send, but can receive, we should be able to see
713 // timestamps here.
714 if (configuration::ChannelIsReadableOnNode(channel, node())) {
715 channels_to_write_.emplace_back(
716 &(channels_[channels_to_write_.size()]
717 .timestamps[configuration::GetNodeIndex(configuration(),
718 node())]));
719 } else {
720 channels_to_write_.emplace_back(nullptr);
721 }
722 }
Austin Schuh05b70472020-01-01 17:11:17 -0800723}
724
Austin Schuh6f3babe2020-01-26 20:34:50 -0800725bool SplitMessageReader::NextLogFile() {
Austin Schuhfa895892020-01-07 20:07:41 -0800726 if (next_filename_index_ == filenames_.size()) {
727 return false;
728 }
729 message_reader_ =
730 std::make_unique<MessageReader>(filenames_[next_filename_index_]);
731
732 // We can't support the config diverging between two log file headers. See if
733 // they are the same.
734 if (next_filename_index_ != 0) {
Austin Schuh64fab802020-09-09 22:47:47 -0700735 // In order for the headers to identically compare, they need to have the
736 // same parts_index. Rewrite the saved header with the new parts_index,
737 // compare, and then restore.
738 const int32_t original_parts_index =
739 log_file_header_.message().parts_index();
740 log_file_header_.mutable_message()->mutate_parts_index(
741 message_reader_->log_file_header()->parts_index());
742
Austin Schuh97789fc2020-08-01 14:42:45 -0700743 CHECK(CompareFlatBuffer(message_reader_->raw_log_file_header(),
744 log_file_header_))
Austin Schuhfa895892020-01-07 20:07:41 -0800745 << ": Header is different between log file chunks "
746 << filenames_[next_filename_index_] << " and "
747 << filenames_[next_filename_index_ - 1] << ", this is not supported.";
Austin Schuh64fab802020-09-09 22:47:47 -0700748
749 log_file_header_.mutable_message()->mutate_parts_index(
750 original_parts_index);
Austin Schuhfa895892020-01-07 20:07:41 -0800751 }
752
753 ++next_filename_index_;
754 return true;
755}
756
Austin Schuh6f3babe2020-01-26 20:34:50 -0800757bool SplitMessageReader::QueueMessages(
Austin Schuhcde938c2020-02-02 17:30:07 -0800758 monotonic_clock::time_point last_dequeued_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800759 // TODO(austin): Once we are happy that everything works, read a 256kb chunk
760 // to reduce the need to re-heap down below.
Austin Schuhcde938c2020-02-02 17:30:07 -0800761
762 // Special case no more data. Otherwise we blow up on the CHECK statement
763 // confirming that we have enough data queued.
764 if (at_end_) {
765 return false;
766 }
767
768 // If this isn't the first time around, confirm that we had enough data queued
769 // to follow the contract.
770 if (time_to_queue_ != monotonic_clock::min_time) {
771 CHECK_LE(last_dequeued_time,
772 newest_timestamp() - max_out_of_order_duration())
773 << " node " << FlatbufferToJson(node()) << " on " << this;
774
775 // Bail if there is enough data already queued.
776 if (last_dequeued_time < time_to_queue_) {
Austin Schuhee711052020-08-24 16:06:09 -0700777 VLOG(1) << MaybeNodeName(target_node_) << "All up to date on " << this
778 << ", dequeued " << last_dequeued_time << " queue time "
779 << time_to_queue_;
Austin Schuhcde938c2020-02-02 17:30:07 -0800780 return true;
781 }
782 } else {
783 // Startup takes a special dance. We want to queue up until the start time,
784 // but we then want to find the next message to read. The conservative
785 // answer is to immediately trigger a second requeue to get things moving.
786 time_to_queue_ = monotonic_start_time();
Austin Schuheeba0292020-10-11 16:20:05 -0700787 CHECK_NE(time_to_queue_, monotonic_clock::min_time);
Austin Schuhcde938c2020-02-02 17:30:07 -0800788 QueueMessages(time_to_queue_);
789 }
790
791 // If we are asked to queue, queue for at least max_out_of_order_duration past
792 // the last known time in the log file (ie the newest timestep read). As long
793 // as we requeue exactly when time_to_queue_ is dequeued and go no further, we
794 // are safe. And since we pop in order, that works.
795 //
796 // Special case the start of the log file. There should be at most 1 message
797 // from each channel at the start of the log file. So always force the start
798 // of the log file to just be read.
799 time_to_queue_ = std::max(time_to_queue_, newest_timestamp());
Austin Schuhee711052020-08-24 16:06:09 -0700800 VLOG(1) << MaybeNodeName(target_node_) << "Queueing, going until "
801 << time_to_queue_ << " " << filename();
Austin Schuhcde938c2020-02-02 17:30:07 -0800802
803 bool was_emplaced = false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800804 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800805 // Stop if we have enough.
Brian Silverman98360e22020-04-28 16:51:20 -0700806 if (newest_timestamp() > time_to_queue_ + max_out_of_order_duration() &&
Austin Schuhcde938c2020-02-02 17:30:07 -0800807 was_emplaced) {
Austin Schuhee711052020-08-24 16:06:09 -0700808 VLOG(1) << MaybeNodeName(target_node_) << "Done queueing on " << this
809 << ", queued to " << newest_timestamp() << " with requeue time "
810 << time_to_queue_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800811 return true;
812 }
Austin Schuh05b70472020-01-01 17:11:17 -0800813
Austin Schuhadd6eb32020-11-09 21:24:26 -0800814 if (std::optional<SizePrefixedFlatbufferVector<MessageHeader>> msg =
Austin Schuh6f3babe2020-01-26 20:34:50 -0800815 message_reader_->ReadMessage()) {
816 const MessageHeader &header = msg.value().message();
817
Austin Schuhcde938c2020-02-02 17:30:07 -0800818 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
819 chrono::nanoseconds(header.monotonic_sent_time()));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800820
Austin Schuh0b5fd032020-03-28 17:36:49 -0700821 if (VLOG_IS_ON(2)) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700822 LOG(INFO) << MaybeNodeName(target_node_) << "Queued " << this << " "
823 << filename() << " ttq: " << time_to_queue_ << " now "
Austin Schuhee711052020-08-24 16:06:09 -0700824 << newest_timestamp() << " start time "
825 << monotonic_start_time() << " " << FlatbufferToJson(&header);
Austin Schuh0b5fd032020-03-28 17:36:49 -0700826 } else if (VLOG_IS_ON(1)) {
Austin Schuhadd6eb32020-11-09 21:24:26 -0800827 SizePrefixedFlatbufferVector<MessageHeader> copy = msg.value();
Austin Schuh0b5fd032020-03-28 17:36:49 -0700828 copy.mutable_message()->clear_data();
Austin Schuhee711052020-08-24 16:06:09 -0700829 LOG(INFO) << MaybeNodeName(target_node_) << "Queued " << this << " "
830 << filename() << " ttq: " << time_to_queue_ << " now "
831 << newest_timestamp() << " start time "
832 << monotonic_start_time() << " " << FlatbufferToJson(copy);
Austin Schuh0b5fd032020-03-28 17:36:49 -0700833 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800834
835 const int channel_index = header.channel_index();
836 was_emplaced = channels_to_write_[channel_index]->emplace_back(
837 std::move(msg.value()));
838 if (was_emplaced) {
839 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
840 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800841 } else {
842 if (!NextLogFile()) {
Austin Schuhee711052020-08-24 16:06:09 -0700843 VLOG(1) << MaybeNodeName(target_node_) << "No more files, last was "
844 << filenames_.back();
Austin Schuhcde938c2020-02-02 17:30:07 -0800845 at_end_ = true;
Austin Schuh8bd96322020-02-13 21:18:22 -0800846 for (MessageHeaderQueue *queue : channels_to_write_) {
847 if (queue == nullptr || queue->timestamp_merger == nullptr) {
848 continue;
849 }
850 queue->timestamp_merger->NoticeAtEnd();
851 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800852 return false;
853 }
854 }
Austin Schuh05b70472020-01-01 17:11:17 -0800855 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800856}
857
858void SplitMessageReader::SetTimestampMerger(TimestampMerger *timestamp_merger,
859 int channel_index,
860 const Node *target_node) {
861 const Node *reinterpreted_target_node =
862 configuration::GetNodeOrDie(configuration(), target_node);
Austin Schuhee711052020-08-24 16:06:09 -0700863 target_node_ = reinterpreted_target_node;
864
Austin Schuh6f3babe2020-01-26 20:34:50 -0800865 const Channel *const channel =
866 configuration()->channels()->Get(channel_index);
867
Austin Schuhcde938c2020-02-02 17:30:07 -0800868 VLOG(1) << " Configuring merger " << this << " for channel " << channel_index
869 << " "
870 << configuration::CleanedChannelToString(
871 configuration()->channels()->Get(channel_index));
872
Austin Schuh6f3babe2020-01-26 20:34:50 -0800873 MessageHeaderQueue *message_header_queue = nullptr;
874
875 // Figure out if this log file is from our point of view, or the other node's
876 // point of view.
877 if (node() == reinterpreted_target_node) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800878 VLOG(1) << " Replaying as logged node " << filename();
879
880 if (configuration::ChannelIsSendableOnNode(channel, node())) {
881 VLOG(1) << " Data on node";
882 message_header_queue = &(channels_[channel_index].data);
883 } else if (configuration::ChannelIsReadableOnNode(channel, node())) {
884 VLOG(1) << " Timestamps on node";
885 message_header_queue =
886 &(channels_[channel_index].timestamps[configuration::GetNodeIndex(
887 configuration(), node())]);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800888 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800889 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800890 }
891 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800892 VLOG(1) << " Replaying as other node " << filename();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800893 // We are replaying from another node's point of view. The only interesting
Austin Schuhcde938c2020-02-02 17:30:07 -0800894 // data is data that is sent from our node and received on theirs.
895 if (configuration::ChannelIsReadableOnNode(channel,
896 reinterpreted_target_node) &&
897 configuration::ChannelIsSendableOnNode(channel, node())) {
898 VLOG(1) << " Readable on target node";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800899 // Data from another node.
900 message_header_queue = &(channels_[channel_index].data);
901 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800902 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800903 // This is either not sendable on the other node, or is a timestamp and
904 // therefore not interesting.
905 }
906 }
907
908 // If we found one, write it down. This will be nullptr when there is nothing
909 // relevant on this channel on this node for the target node. In that case,
910 // we want to drop the message instead of queueing it.
911 if (message_header_queue != nullptr) {
912 message_header_queue->timestamp_merger = timestamp_merger;
913 }
914}
915
916std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800917 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -0800918SplitMessageReader::PopOldest(int channel_index) {
919 CHECK_GT(channels_[channel_index].data.size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800920 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
921 timestamp = channels_[channel_index].data.front_timestamp();
Austin Schuhadd6eb32020-11-09 21:24:26 -0800922 SizePrefixedFlatbufferVector<MessageHeader> front =
Austin Schuh6f3babe2020-01-26 20:34:50 -0800923 std::move(channels_[channel_index].data.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700924 channels_[channel_index].data.PopFront();
Austin Schuhcde938c2020-02-02 17:30:07 -0800925
Austin Schuh2f8fd752020-09-01 22:38:28 -0700926 VLOG(1) << MaybeNodeName(target_node_) << "Popped Data " << this << " "
927 << std::get<0>(timestamp) << " for "
928 << configuration::StrippedChannelToString(
929 configuration()->channels()->Get(channel_index))
930 << " (" << channel_index << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -0800931
932 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800933
934 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
935 std::move(front));
936}
937
938std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800939 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -0700940SplitMessageReader::PopOldestTimestamp(int channel, int node_index) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800941 CHECK_GT(channels_[channel].timestamps[node_index].size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800942 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
943 timestamp = channels_[channel].timestamps[node_index].front_timestamp();
Austin Schuhadd6eb32020-11-09 21:24:26 -0800944 SizePrefixedFlatbufferVector<MessageHeader> front =
Austin Schuh6f3babe2020-01-26 20:34:50 -0800945 std::move(channels_[channel].timestamps[node_index].front());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700946 channels_[channel].timestamps[node_index].PopFront();
Austin Schuhcde938c2020-02-02 17:30:07 -0800947
Austin Schuh2f8fd752020-09-01 22:38:28 -0700948 VLOG(1) << MaybeNodeName(target_node_) << "Popped timestamp " << this << " "
Austin Schuhee711052020-08-24 16:06:09 -0700949 << std::get<0>(timestamp) << " for "
950 << configuration::StrippedChannelToString(
951 configuration()->channels()->Get(channel))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700952 << " on "
953 << configuration()->nodes()->Get(node_index)->name()->string_view()
954 << " (" << node_index << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -0800955
956 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800957
958 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
959 std::move(front));
960}
961
Austin Schuhcde938c2020-02-02 17:30:07 -0800962bool SplitMessageReader::MessageHeaderQueue::emplace_back(
Austin Schuhadd6eb32020-11-09 21:24:26 -0800963 SizePrefixedFlatbufferVector<MessageHeader> &&msg) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800964 CHECK(split_reader != nullptr);
965
966 // If there is no timestamp merger for this queue, nobody is listening. Drop
967 // the message. This happens when a log file from another node is replayed,
968 // and the timestamp mergers down stream just don't care.
969 if (timestamp_merger == nullptr) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800970 return false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800971 }
972
973 CHECK(timestamps != msg.message().has_data())
974 << ": Got timestamps and data mixed up on a node. "
975 << FlatbufferToJson(msg);
976
977 data_.emplace_back(std::move(msg));
978
979 if (data_.size() == 1u) {
980 // Yup, new data. Notify.
981 if (timestamps) {
982 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
983 } else {
984 timestamp_merger->Update(split_reader, front_timestamp());
985 }
986 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800987
988 return true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800989}
990
Austin Schuh2f8fd752020-09-01 22:38:28 -0700991void SplitMessageReader::MessageHeaderQueue::PopFront() {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800992 data_.pop_front();
993 if (data_.size() != 0u) {
994 // Yup, new data.
995 if (timestamps) {
996 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
997 } else {
998 timestamp_merger->Update(split_reader, front_timestamp());
999 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001000 } else {
1001 // Poke anyways to update the heap.
1002 if (timestamps) {
1003 timestamp_merger->UpdateTimestamp(
1004 nullptr, std::make_tuple(monotonic_clock::min_time, 0, nullptr));
1005 } else {
1006 timestamp_merger->Update(
1007 nullptr, std::make_tuple(monotonic_clock::min_time, 0, nullptr));
1008 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001009 }
Austin Schuh05b70472020-01-01 17:11:17 -08001010}
1011
1012namespace {
1013
Austin Schuh6f3babe2020-01-26 20:34:50 -08001014bool SplitMessageReaderHeapCompare(
1015 const std::tuple<monotonic_clock::time_point, uint32_t,
1016 SplitMessageReader *>
1017 first,
1018 const std::tuple<monotonic_clock::time_point, uint32_t,
1019 SplitMessageReader *>
1020 second) {
1021 if (std::get<0>(first) > std::get<0>(second)) {
1022 return true;
1023 } else if (std::get<0>(first) == std::get<0>(second)) {
1024 if (std::get<1>(first) > std::get<1>(second)) {
1025 return true;
1026 } else if (std::get<1>(first) == std::get<1>(second)) {
1027 return std::get<2>(first) > std::get<2>(second);
1028 } else {
1029 return false;
1030 }
1031 } else {
1032 return false;
1033 }
1034}
1035
Austin Schuh05b70472020-01-01 17:11:17 -08001036bool ChannelHeapCompare(
1037 const std::pair<monotonic_clock::time_point, int> first,
1038 const std::pair<monotonic_clock::time_point, int> second) {
1039 if (first.first > second.first) {
1040 return true;
1041 } else if (first.first == second.first) {
1042 return first.second > second.second;
1043 } else {
1044 return false;
1045 }
1046}
1047
1048} // namespace
1049
Austin Schuh6f3babe2020-01-26 20:34:50 -08001050TimestampMerger::TimestampMerger(
1051 const Configuration *configuration,
1052 std::vector<SplitMessageReader *> split_message_readers, int channel_index,
1053 const Node *target_node, ChannelMerger *channel_merger)
1054 : configuration_(configuration),
1055 split_message_readers_(std::move(split_message_readers)),
1056 channel_index_(channel_index),
1057 node_index_(configuration::MultiNode(configuration)
1058 ? configuration::GetNodeIndex(configuration, target_node)
1059 : -1),
1060 channel_merger_(channel_merger) {
1061 // Tell the readers we care so they know who to notify.
Austin Schuhcde938c2020-02-02 17:30:07 -08001062 VLOG(1) << "Configuring channel " << channel_index << " target node "
1063 << FlatbufferToJson(target_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001064 for (SplitMessageReader *reader : split_message_readers_) {
1065 reader->SetTimestampMerger(this, channel_index, target_node);
1066 }
1067
1068 // And then determine if we need to track timestamps.
1069 const Channel *channel = configuration->channels()->Get(channel_index);
1070 if (!configuration::ChannelIsSendableOnNode(channel, target_node) &&
1071 configuration::ChannelIsReadableOnNode(channel, target_node)) {
1072 has_timestamps_ = true;
1073 }
1074}
1075
1076void TimestampMerger::PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -08001077 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1078 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001079 SplitMessageReader *split_message_reader) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001080 if (split_message_reader != nullptr) {
1081 DCHECK(std::find_if(message_heap_.begin(), message_heap_.end(),
1082 [split_message_reader](
1083 const std::tuple<monotonic_clock::time_point,
1084 uint32_t, SplitMessageReader *>
1085 x) {
1086 return std::get<2>(x) == split_message_reader;
1087 }) == message_heap_.end())
1088 << ": Pushing message when it is already in the heap.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001089
Austin Schuh2f8fd752020-09-01 22:38:28 -07001090 message_heap_.push_back(std::make_tuple(
1091 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001092
Austin Schuh2f8fd752020-09-01 22:38:28 -07001093 std::push_heap(message_heap_.begin(), message_heap_.end(),
1094 &SplitMessageReaderHeapCompare);
1095 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001096
1097 // If we are just a data merger, don't wait for timestamps.
1098 if (!has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001099 if (!message_heap_.empty()) {
1100 channel_merger_->Update(std::get<0>(message_heap_[0]), channel_index_);
1101 pushed_ = true;
1102 } else {
1103 // Remove ourselves if we are empty.
1104 channel_merger_->Update(monotonic_clock::min_time, channel_index_);
1105 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001106 }
1107}
1108
Austin Schuhcde938c2020-02-02 17:30:07 -08001109std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1110TimestampMerger::oldest_message() const {
1111 CHECK_GT(message_heap_.size(), 0u);
1112 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1113 oldest_message_reader = message_heap_.front();
1114 return std::get<2>(oldest_message_reader)->oldest_message(channel_index_);
1115}
1116
1117std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1118TimestampMerger::oldest_timestamp() const {
1119 CHECK_GT(timestamp_heap_.size(), 0u);
1120 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1121 oldest_message_reader = timestamp_heap_.front();
1122 return std::get<2>(oldest_message_reader)
1123 ->oldest_message(channel_index_, node_index_);
1124}
1125
Austin Schuh6f3babe2020-01-26 20:34:50 -08001126void TimestampMerger::PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -08001127 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1128 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001129 SplitMessageReader *split_message_reader) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001130 if (split_message_reader != nullptr) {
1131 DCHECK(std::find_if(timestamp_heap_.begin(), timestamp_heap_.end(),
1132 [split_message_reader](
1133 const std::tuple<monotonic_clock::time_point,
1134 uint32_t, SplitMessageReader *>
1135 x) {
1136 return std::get<2>(x) == split_message_reader;
1137 }) == timestamp_heap_.end())
1138 << ": Pushing timestamp when it is already in the heap.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001139
Austin Schuh2f8fd752020-09-01 22:38:28 -07001140 timestamp_heap_.push_back(std::make_tuple(
1141 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001142
Austin Schuh2f8fd752020-09-01 22:38:28 -07001143 std::push_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1144 SplitMessageReaderHeapCompare);
1145 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001146
1147 // If we are a timestamp merger, don't wait for data. Missing data will be
1148 // caught at read time.
1149 if (has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001150 if (!timestamp_heap_.empty()) {
1151 channel_merger_->Update(std::get<0>(timestamp_heap_[0]), channel_index_);
1152 pushed_ = true;
1153 } else {
1154 // Remove ourselves if we are empty.
1155 channel_merger_->Update(monotonic_clock::min_time, channel_index_);
1156 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001157 }
1158}
1159
1160std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -08001161 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -08001162TimestampMerger::PopMessageHeap() {
1163 // Pop the oldest message reader pointer off the heap.
1164 CHECK_GT(message_heap_.size(), 0u);
1165 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1166 oldest_message_reader = message_heap_.front();
1167
1168 std::pop_heap(message_heap_.begin(), message_heap_.end(),
1169 &SplitMessageReaderHeapCompare);
1170 message_heap_.pop_back();
1171
1172 // Pop the oldest message. This re-pushes any messages from the reader to the
1173 // message heap.
1174 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -08001175 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -08001176 oldest_message =
1177 std::get<2>(oldest_message_reader)->PopOldest(channel_index_);
1178
1179 // Confirm that the time and queue_index we have recorded matches.
1180 CHECK_EQ(std::get<0>(oldest_message), std::get<0>(oldest_message_reader));
1181 CHECK_EQ(std::get<1>(oldest_message), std::get<1>(oldest_message_reader));
1182
1183 // Now, keep reading until we have found all duplicates.
Brian Silverman8a32ce62020-08-12 12:02:38 -07001184 while (!message_heap_.empty()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001185 // See if it is a duplicate.
1186 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1187 next_oldest_message_reader = message_heap_.front();
1188
Austin Schuhcde938c2020-02-02 17:30:07 -08001189 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1190 next_oldest_message_time = std::get<2>(next_oldest_message_reader)
1191 ->oldest_message(channel_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001192
1193 if (std::get<0>(next_oldest_message_time) == std::get<0>(oldest_message) &&
1194 std::get<1>(next_oldest_message_time) == std::get<1>(oldest_message)) {
1195 // Pop the message reader pointer.
1196 std::pop_heap(message_heap_.begin(), message_heap_.end(),
1197 &SplitMessageReaderHeapCompare);
1198 message_heap_.pop_back();
1199
1200 // Pop the next oldest message. This re-pushes any messages from the
1201 // reader.
1202 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -08001203 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -08001204 next_oldest_message = std::get<2>(next_oldest_message_reader)
1205 ->PopOldest(channel_index_);
1206
1207 // And make sure the message matches in it's entirety.
1208 CHECK(std::get<2>(oldest_message).span() ==
1209 std::get<2>(next_oldest_message).span())
1210 << ": Data at the same timestamp doesn't match.";
1211 } else {
1212 break;
1213 }
1214 }
1215
1216 return oldest_message;
1217}
1218
1219std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -08001220 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -08001221TimestampMerger::PopTimestampHeap() {
1222 // Pop the oldest message reader pointer off the heap.
1223 CHECK_GT(timestamp_heap_.size(), 0u);
1224
1225 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1226 oldest_timestamp_reader = timestamp_heap_.front();
1227
1228 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1229 &SplitMessageReaderHeapCompare);
1230 timestamp_heap_.pop_back();
1231
1232 CHECK(node_index_ != -1) << ": Timestamps in a single node environment";
1233
1234 // Pop the oldest message. This re-pushes any timestamps from the reader to
1235 // the timestamp heap.
1236 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -08001237 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -08001238 oldest_timestamp = std::get<2>(oldest_timestamp_reader)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001239 ->PopOldestTimestamp(channel_index_, node_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001240
1241 // Confirm that the time we have recorded matches.
1242 CHECK_EQ(std::get<0>(oldest_timestamp), std::get<0>(oldest_timestamp_reader));
1243 CHECK_EQ(std::get<1>(oldest_timestamp), std::get<1>(oldest_timestamp_reader));
1244
Austin Schuh2f8fd752020-09-01 22:38:28 -07001245 // Now, keep reading until we have found all duplicates.
1246 while (!timestamp_heap_.empty()) {
1247 // See if it is a duplicate.
1248 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1249 next_oldest_timestamp_reader = timestamp_heap_.front();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001250
Austin Schuh2f8fd752020-09-01 22:38:28 -07001251 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1252 next_oldest_timestamp_time =
1253 std::get<2>(next_oldest_timestamp_reader)
1254 ->oldest_message(channel_index_, node_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001255
Austin Schuh2f8fd752020-09-01 22:38:28 -07001256 if (std::get<0>(next_oldest_timestamp_time) ==
1257 std::get<0>(oldest_timestamp) &&
1258 std::get<1>(next_oldest_timestamp_time) ==
1259 std::get<1>(oldest_timestamp)) {
1260 // Pop the timestamp reader pointer.
1261 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1262 &SplitMessageReaderHeapCompare);
1263 timestamp_heap_.pop_back();
1264
1265 // Pop the next oldest timestamp. This re-pushes any messages from the
1266 // reader.
1267 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -08001268 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -07001269 next_oldest_timestamp =
1270 std::get<2>(next_oldest_timestamp_reader)
1271 ->PopOldestTimestamp(channel_index_, node_index_);
1272
1273 // And make sure the contents matches in it's entirety.
1274 CHECK(std::get<2>(oldest_timestamp).span() ==
1275 std::get<2>(next_oldest_timestamp).span())
1276 << ": Data at the same timestamp doesn't match, "
1277 << aos::FlatbufferToJson(std::get<2>(oldest_timestamp)) << " vs "
1278 << aos::FlatbufferToJson(std::get<2>(next_oldest_timestamp)) << " "
1279 << absl::BytesToHexString(std::string_view(
1280 reinterpret_cast<const char *>(
1281 std::get<2>(oldest_timestamp).span().data()),
1282 std::get<2>(oldest_timestamp).span().size()))
1283 << " vs "
1284 << absl::BytesToHexString(std::string_view(
1285 reinterpret_cast<const char *>(
1286 std::get<2>(next_oldest_timestamp).span().data()),
1287 std::get<2>(next_oldest_timestamp).span().size()));
1288
1289 } else {
1290 break;
1291 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001292 }
1293
Austin Schuh2f8fd752020-09-01 22:38:28 -07001294 return oldest_timestamp;
Austin Schuh8bd96322020-02-13 21:18:22 -08001295}
1296
Austin Schuhadd6eb32020-11-09 21:24:26 -08001297std::tuple<TimestampMerger::DeliveryTimestamp,
1298 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -08001299TimestampMerger::PopOldest() {
1300 if (has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001301 VLOG(1) << "Looking for matching timestamp for "
1302 << configuration::StrippedChannelToString(
1303 configuration_->channels()->Get(channel_index_))
1304 << " (" << channel_index_ << ") "
1305 << " at " << std::get<0>(oldest_timestamp());
1306
Austin Schuh8bd96322020-02-13 21:18:22 -08001307 // Read the timestamps.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001308 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -08001309 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -08001310 oldest_timestamp = PopTimestampHeap();
1311
1312 TimestampMerger::DeliveryTimestamp timestamp;
1313 timestamp.monotonic_event_time =
1314 monotonic_clock::time_point(chrono::nanoseconds(
1315 std::get<2>(oldest_timestamp).message().monotonic_sent_time()));
1316 timestamp.realtime_event_time =
1317 realtime_clock::time_point(chrono::nanoseconds(
1318 std::get<2>(oldest_timestamp).message().realtime_sent_time()));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001319 timestamp.queue_index =
1320 std::get<2>(oldest_timestamp).message().queue_index();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001321
1322 // Consistency check.
1323 CHECK_EQ(timestamp.monotonic_event_time, std::get<0>(oldest_timestamp));
1324 CHECK_EQ(std::get<2>(oldest_timestamp).message().queue_index(),
1325 std::get<1>(oldest_timestamp));
1326
1327 monotonic_clock::time_point remote_timestamp_monotonic_time(
1328 chrono::nanoseconds(
1329 std::get<2>(oldest_timestamp).message().monotonic_remote_time()));
1330
Austin Schuh8bd96322020-02-13 21:18:22 -08001331 // See if we have any data. If not, pass the problem up the chain.
Brian Silverman8a32ce62020-08-12 12:02:38 -07001332 if (message_heap_.empty()) {
Austin Schuhee711052020-08-24 16:06:09 -07001333 LOG(WARNING) << MaybeNodeName(configuration_->nodes()->Get(node_index_))
1334 << "No data to match timestamp on "
1335 << configuration::CleanedChannelToString(
1336 configuration_->channels()->Get(channel_index_))
1337 << " (" << channel_index_ << ")";
Austin Schuh8bd96322020-02-13 21:18:22 -08001338 return std::make_tuple(timestamp,
1339 std::move(std::get<2>(oldest_timestamp)));
1340 }
1341
Austin Schuh6f3babe2020-01-26 20:34:50 -08001342 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001343 {
1344 // Ok, now try grabbing data until we find one which matches.
1345 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1346 oldest_message_ref = oldest_message();
1347
1348 // Time at which the message was sent (this message is written from the
1349 // sending node's perspective.
1350 monotonic_clock::time_point remote_monotonic_time(chrono::nanoseconds(
1351 std::get<2>(oldest_message_ref)->monotonic_sent_time()));
1352
1353 if (remote_monotonic_time < remote_timestamp_monotonic_time) {
Austin Schuhee711052020-08-24 16:06:09 -07001354 LOG(WARNING) << configuration_->nodes()
1355 ->Get(node_index_)
1356 ->name()
1357 ->string_view()
1358 << " Undelivered message, skipping. Remote time is "
1359 << remote_monotonic_time << " timestamp is "
1360 << remote_timestamp_monotonic_time << " on channel "
1361 << configuration::StrippedChannelToString(
1362 configuration_->channels()->Get(channel_index_))
1363 << " (" << channel_index_ << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -08001364 PopMessageHeap();
1365 continue;
1366 } else if (remote_monotonic_time > remote_timestamp_monotonic_time) {
Austin Schuhee711052020-08-24 16:06:09 -07001367 LOG(WARNING) << configuration_->nodes()
1368 ->Get(node_index_)
1369 ->name()
1370 ->string_view()
1371 << " Data not found. Remote time should be "
1372 << remote_timestamp_monotonic_time
1373 << ", message time is " << remote_monotonic_time
1374 << " on channel "
1375 << configuration::StrippedChannelToString(
1376 configuration_->channels()->Get(channel_index_))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001377 << " (" << channel_index_ << ")"
1378 << (VLOG_IS_ON(1) ? DebugString() : "");
Austin Schuhcde938c2020-02-02 17:30:07 -08001379 return std::make_tuple(timestamp,
1380 std::move(std::get<2>(oldest_timestamp)));
1381 }
1382
1383 timestamp.monotonic_remote_time = remote_monotonic_time;
1384 }
1385
Austin Schuh2f8fd752020-09-01 22:38:28 -07001386 VLOG(1) << "Found matching data "
1387 << configuration::StrippedChannelToString(
1388 configuration_->channels()->Get(channel_index_))
1389 << " (" << channel_index_ << ")";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001390 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -08001391 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -08001392 oldest_message = PopMessageHeap();
1393
Austin Schuh6f3babe2020-01-26 20:34:50 -08001394 timestamp.realtime_remote_time =
1395 realtime_clock::time_point(chrono::nanoseconds(
1396 std::get<2>(oldest_message).message().realtime_sent_time()));
1397 timestamp.remote_queue_index =
1398 std::get<2>(oldest_message).message().queue_index();
1399
Austin Schuhcde938c2020-02-02 17:30:07 -08001400 CHECK_EQ(timestamp.monotonic_remote_time,
1401 remote_timestamp_monotonic_time);
1402
1403 CHECK_EQ(timestamp.remote_queue_index,
1404 std::get<2>(oldest_timestamp).message().remote_queue_index())
1405 << ": " << FlatbufferToJson(&std::get<2>(oldest_timestamp).message())
1406 << " data "
1407 << FlatbufferToJson(&std::get<2>(oldest_message).message());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001408
Austin Schuh30dd5c52020-08-01 14:43:44 -07001409 return std::make_tuple(timestamp, std::move(std::get<2>(oldest_message)));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001410 }
1411 } else {
1412 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -08001413 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -08001414 oldest_message = PopMessageHeap();
1415
1416 TimestampMerger::DeliveryTimestamp timestamp;
1417 timestamp.monotonic_event_time =
1418 monotonic_clock::time_point(chrono::nanoseconds(
1419 std::get<2>(oldest_message).message().monotonic_sent_time()));
1420 timestamp.realtime_event_time =
1421 realtime_clock::time_point(chrono::nanoseconds(
1422 std::get<2>(oldest_message).message().realtime_sent_time()));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001423 timestamp.queue_index = std::get<2>(oldest_message).message().queue_index();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001424 timestamp.remote_queue_index = 0xffffffff;
1425
1426 CHECK_EQ(std::get<0>(oldest_message), timestamp.monotonic_event_time);
1427 CHECK_EQ(std::get<1>(oldest_message),
1428 std::get<2>(oldest_message).message().queue_index());
1429
Austin Schuh30dd5c52020-08-01 14:43:44 -07001430 return std::make_tuple(timestamp, std::move(std::get<2>(oldest_message)));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001431 }
1432}
1433
Austin Schuh8bd96322020-02-13 21:18:22 -08001434void TimestampMerger::NoticeAtEnd() { channel_merger_->NoticeAtEnd(); }
1435
Austin Schuh6f3babe2020-01-26 20:34:50 -08001436namespace {
1437std::vector<std::unique_ptr<SplitMessageReader>> MakeSplitMessageReaders(
1438 const std::vector<std::vector<std::string>> &filenames) {
1439 CHECK_GT(filenames.size(), 0u);
1440 // Build up all the SplitMessageReaders.
1441 std::vector<std::unique_ptr<SplitMessageReader>> result;
1442 for (const std::vector<std::string> &filenames : filenames) {
1443 result.emplace_back(std::make_unique<SplitMessageReader>(filenames));
1444 }
1445 return result;
1446}
1447} // namespace
1448
1449ChannelMerger::ChannelMerger(
1450 const std::vector<std::vector<std::string>> &filenames)
1451 : split_message_readers_(MakeSplitMessageReaders(filenames)),
Austin Schuh97789fc2020-08-01 14:42:45 -07001452 log_file_header_(split_message_readers_[0]->raw_log_file_header()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001453 // Now, confirm that the configuration matches for each and pick a start time.
1454 // Also return the list of possible nodes.
1455 for (const std::unique_ptr<SplitMessageReader> &reader :
1456 split_message_readers_) {
1457 CHECK(CompareFlatBuffer(log_file_header_.message().configuration(),
1458 reader->log_file_header()->configuration()))
1459 << ": Replaying log files with different configurations isn't "
1460 "supported";
1461 }
1462
1463 nodes_ = configuration::GetNodes(configuration());
1464}
1465
1466bool ChannelMerger::SetNode(const Node *target_node) {
1467 std::vector<SplitMessageReader *> split_message_readers;
1468 for (const std::unique_ptr<SplitMessageReader> &reader :
1469 split_message_readers_) {
1470 split_message_readers.emplace_back(reader.get());
1471 }
1472
1473 // Go find a log_file_header for this node.
1474 {
1475 bool found_node = false;
1476
1477 for (const std::unique_ptr<SplitMessageReader> &reader :
1478 split_message_readers_) {
James Kuszmaulfc273dc2020-05-09 17:56:19 -07001479 // In order to identify which logfile(s) map to the target node, do a
1480 // logical comparison of the nodes, by confirming that we are either in a
1481 // single-node setup (where the nodes will both be nullptr) or that the
1482 // node names match (but the other node fields--e.g., hostname lists--may
1483 // not).
1484 const bool both_null =
1485 reader->node() == nullptr && target_node == nullptr;
1486 const bool both_have_name =
1487 (reader->node() != nullptr) && (target_node != nullptr) &&
1488 (reader->node()->has_name() && target_node->has_name());
1489 const bool node_names_identical =
Brian Silvermand90905f2020-09-23 14:42:56 -07001490 both_have_name && (reader->node()->name()->string_view() ==
1491 target_node->name()->string_view());
James Kuszmaulfc273dc2020-05-09 17:56:19 -07001492 if (both_null || node_names_identical) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001493 if (!found_node) {
1494 found_node = true;
Austin Schuhadd6eb32020-11-09 21:24:26 -08001495 log_file_header_ = reader->raw_log_file_header();
Austin Schuhcde938c2020-02-02 17:30:07 -08001496 VLOG(1) << "Found log file " << reader->filename() << " with node "
1497 << FlatbufferToJson(reader->node()) << " start_time "
1498 << monotonic_start_time();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001499 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001500 // Find the earliest start time. That way, if we get a full log file
1501 // directly from the node, and a partial later, we start with the
1502 // full. Update our header to match that.
1503 const monotonic_clock::time_point new_monotonic_start_time(
1504 chrono::nanoseconds(
1505 reader->log_file_header()->monotonic_start_time()));
1506 const realtime_clock::time_point new_realtime_start_time(
1507 chrono::nanoseconds(
1508 reader->log_file_header()->realtime_start_time()));
1509
1510 if (monotonic_start_time() == monotonic_clock::min_time ||
1511 (new_monotonic_start_time != monotonic_clock::min_time &&
1512 new_monotonic_start_time < monotonic_start_time())) {
1513 log_file_header_.mutable_message()->mutate_monotonic_start_time(
1514 new_monotonic_start_time.time_since_epoch().count());
1515 log_file_header_.mutable_message()->mutate_realtime_start_time(
1516 new_realtime_start_time.time_since_epoch().count());
1517 VLOG(1) << "Updated log file " << reader->filename()
1518 << " with node " << FlatbufferToJson(reader->node())
1519 << " start_time " << new_monotonic_start_time;
1520 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001521 }
1522 }
1523 }
1524
1525 if (!found_node) {
1526 LOG(WARNING) << "Failed to find log file for node "
1527 << FlatbufferToJson(target_node);
1528 return false;
1529 }
1530 }
1531
1532 // Build up all the timestamp mergers. This connects up all the
1533 // SplitMessageReaders.
1534 timestamp_mergers_.reserve(configuration()->channels()->size());
1535 for (size_t channel_index = 0;
1536 channel_index < configuration()->channels()->size(); ++channel_index) {
1537 timestamp_mergers_.emplace_back(
1538 configuration(), split_message_readers, channel_index,
1539 configuration::GetNode(configuration(), target_node), this);
1540 }
1541
1542 // And prime everything.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001543 for (std::unique_ptr<SplitMessageReader> &split_message_reader :
1544 split_message_readers_) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001545 split_message_reader->QueueMessages(
1546 split_message_reader->monotonic_start_time());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001547 }
1548
1549 node_ = configuration::GetNodeOrDie(configuration(), target_node);
1550 return true;
1551}
1552
Austin Schuh858c9f32020-08-31 16:56:12 -07001553monotonic_clock::time_point ChannelMerger::OldestMessageTime() const {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001554 if (channel_heap_.empty()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001555 return monotonic_clock::max_time;
1556 }
1557 return channel_heap_.front().first;
1558}
1559
1560void ChannelMerger::PushChannelHeap(monotonic_clock::time_point timestamp,
1561 int channel_index) {
1562 // Pop and recreate the heap if it has already been pushed. And since we are
1563 // pushing again, we don't need to clear pushed.
1564 if (timestamp_mergers_[channel_index].pushed()) {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001565 const auto channel_iterator = std::find_if(
Austin Schuh6f3babe2020-01-26 20:34:50 -08001566 channel_heap_.begin(), channel_heap_.end(),
1567 [channel_index](const std::pair<monotonic_clock::time_point, int> x) {
1568 return x.second == channel_index;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001569 });
1570 DCHECK(channel_iterator != channel_heap_.end());
1571 if (std::get<0>(*channel_iterator) == timestamp) {
1572 // It's already in the heap, in the correct spot, so nothing
1573 // more for us to do here.
1574 return;
1575 }
1576 channel_heap_.erase(channel_iterator);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001577 std::make_heap(channel_heap_.begin(), channel_heap_.end(),
1578 ChannelHeapCompare);
1579 }
1580
Austin Schuh2f8fd752020-09-01 22:38:28 -07001581 if (timestamp == monotonic_clock::min_time) {
1582 timestamp_mergers_[channel_index].set_pushed(false);
1583 return;
1584 }
1585
Austin Schuh05b70472020-01-01 17:11:17 -08001586 channel_heap_.push_back(std::make_pair(timestamp, channel_index));
1587
1588 // The default sort puts the newest message first. Use a custom comparator to
1589 // put the oldest message first.
1590 std::push_heap(channel_heap_.begin(), channel_heap_.end(),
1591 ChannelHeapCompare);
1592}
1593
Austin Schuh2f8fd752020-09-01 22:38:28 -07001594void ChannelMerger::VerifyHeaps() {
Austin Schuh661a8d82020-09-13 17:25:56 -07001595 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap =
1596 channel_heap_;
1597 std::make_heap(channel_heap.begin(), channel_heap.end(), &ChannelHeapCompare);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001598
Austin Schuh661a8d82020-09-13 17:25:56 -07001599 for (size_t i = 0; i < channel_heap_.size(); ++i) {
1600 CHECK(channel_heap_[i] == channel_heap[i]) << ": Heaps diverged...";
1601 CHECK_EQ(
1602 std::get<0>(channel_heap[i]),
1603 timestamp_mergers_[std::get<1>(channel_heap[i])].channel_merger_time());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001604 }
1605}
1606
Austin Schuh6f3babe2020-01-26 20:34:50 -08001607std::tuple<TimestampMerger::DeliveryTimestamp, int,
Austin Schuhadd6eb32020-11-09 21:24:26 -08001608 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -08001609ChannelMerger::PopOldest() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001610 CHECK_GT(channel_heap_.size(), 0u);
Austin Schuh05b70472020-01-01 17:11:17 -08001611 std::pair<monotonic_clock::time_point, int> oldest_channel_data =
1612 channel_heap_.front();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001613 int channel_index = oldest_channel_data.second;
Austin Schuh05b70472020-01-01 17:11:17 -08001614 std::pop_heap(channel_heap_.begin(), channel_heap_.end(),
1615 &ChannelHeapCompare);
1616 channel_heap_.pop_back();
Austin Schuh8bd96322020-02-13 21:18:22 -08001617
Austin Schuh6f3babe2020-01-26 20:34:50 -08001618 timestamp_mergers_[channel_index].set_pushed(false);
Austin Schuh05b70472020-01-01 17:11:17 -08001619
Austin Schuh6f3babe2020-01-26 20:34:50 -08001620 TimestampMerger *merger = &timestamp_mergers_[channel_index];
Austin Schuh05b70472020-01-01 17:11:17 -08001621
Austin Schuhcde938c2020-02-02 17:30:07 -08001622 // Merger handles any queueing needed from here.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001623 std::tuple<TimestampMerger::DeliveryTimestamp,
Austin Schuhadd6eb32020-11-09 21:24:26 -08001624 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -08001625 message = merger->PopOldest();
Brian Silverman8a32ce62020-08-12 12:02:38 -07001626 DCHECK_EQ(std::get<0>(message).monotonic_event_time,
1627 oldest_channel_data.first)
1628 << ": channel_heap_ was corrupted for " << channel_index << ": "
1629 << DebugString();
Austin Schuh05b70472020-01-01 17:11:17 -08001630
Austin Schuh2f8fd752020-09-01 22:38:28 -07001631 CHECK_GE(std::get<0>(message).monotonic_event_time, last_popped_time_)
1632 << ": " << MaybeNodeName(log_file_header()->node())
1633 << "Messages came off the queue out of order. " << DebugString();
1634 last_popped_time_ = std::get<0>(message).monotonic_event_time;
1635
1636 VLOG(1) << "Popped " << last_popped_time_ << " "
1637 << configuration::StrippedChannelToString(
1638 configuration()->channels()->Get(channel_index))
1639 << " (" << channel_index << ")";
1640
Austin Schuh6f3babe2020-01-26 20:34:50 -08001641 return std::make_tuple(std::get<0>(message), channel_index,
1642 std::move(std::get<1>(message)));
1643}
1644
Austin Schuhcde938c2020-02-02 17:30:07 -08001645std::string SplitMessageReader::MessageHeaderQueue::DebugString() const {
1646 std::stringstream ss;
1647 for (size_t i = 0; i < data_.size(); ++i) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001648 if (i < 5 || i + 5 > data_.size()) {
1649 if (timestamps) {
1650 ss << " msg: ";
1651 } else {
1652 ss << " timestamp: ";
1653 }
1654 ss << monotonic_clock::time_point(
1655 chrono::nanoseconds(data_[i].message().monotonic_sent_time()))
Austin Schuhcde938c2020-02-02 17:30:07 -08001656 << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001657 << realtime_clock::time_point(
1658 chrono::nanoseconds(data_[i].message().realtime_sent_time()))
1659 << ") " << data_[i].message().queue_index();
1660 if (timestamps) {
1661 ss << " <- remote "
1662 << monotonic_clock::time_point(chrono::nanoseconds(
1663 data_[i].message().monotonic_remote_time()))
1664 << " ("
1665 << realtime_clock::time_point(chrono::nanoseconds(
1666 data_[i].message().realtime_remote_time()))
1667 << ")";
1668 }
1669 ss << "\n";
1670 } else if (i == 5) {
1671 ss << " ...\n";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001672 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001673 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001674
Austin Schuhcde938c2020-02-02 17:30:07 -08001675 return ss.str();
1676}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001677
Austin Schuhcde938c2020-02-02 17:30:07 -08001678std::string SplitMessageReader::DebugString(int channel) const {
1679 std::stringstream ss;
1680 ss << "[\n";
1681 ss << channels_[channel].data.DebugString();
1682 ss << " ]";
1683 return ss.str();
1684}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001685
Austin Schuhcde938c2020-02-02 17:30:07 -08001686std::string SplitMessageReader::DebugString(int channel, int node_index) const {
1687 std::stringstream ss;
1688 ss << "[\n";
1689 ss << channels_[channel].timestamps[node_index].DebugString();
1690 ss << " ]";
1691 return ss.str();
1692}
1693
1694std::string TimestampMerger::DebugString() const {
1695 std::stringstream ss;
1696
1697 if (timestamp_heap_.size() > 0) {
1698 ss << " timestamp_heap {\n";
1699 std::vector<
1700 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1701 timestamp_heap = timestamp_heap_;
1702 while (timestamp_heap.size() > 0u) {
1703 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1704 oldest_timestamp_reader = timestamp_heap.front();
1705
1706 ss << " " << std::get<2>(oldest_timestamp_reader) << " "
1707 << std::get<0>(oldest_timestamp_reader) << " queue_index ("
1708 << std::get<1>(oldest_timestamp_reader) << ") ttq "
1709 << std::get<2>(oldest_timestamp_reader)->time_to_queue() << " "
1710 << std::get<2>(oldest_timestamp_reader)->filename() << " -> "
1711 << std::get<2>(oldest_timestamp_reader)
1712 ->DebugString(channel_index_, node_index_)
1713 << "\n";
1714
1715 std::pop_heap(timestamp_heap.begin(), timestamp_heap.end(),
1716 &SplitMessageReaderHeapCompare);
1717 timestamp_heap.pop_back();
1718 }
1719 ss << " }\n";
1720 }
1721
1722 ss << " message_heap {\n";
1723 {
1724 std::vector<
1725 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1726 message_heap = message_heap_;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001727 while (!message_heap.empty()) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001728 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1729 oldest_message_reader = message_heap.front();
1730
1731 ss << " " << std::get<2>(oldest_message_reader) << " "
1732 << std::get<0>(oldest_message_reader) << " queue_index ("
1733 << std::get<1>(oldest_message_reader) << ") ttq "
1734 << std::get<2>(oldest_message_reader)->time_to_queue() << " "
1735 << std::get<2>(oldest_message_reader)->filename() << " -> "
1736 << std::get<2>(oldest_message_reader)->DebugString(channel_index_)
1737 << "\n";
1738
1739 std::pop_heap(message_heap.begin(), message_heap.end(),
1740 &SplitMessageReaderHeapCompare);
1741 message_heap.pop_back();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001742 }
Austin Schuh05b70472020-01-01 17:11:17 -08001743 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001744 ss << " }";
1745
1746 return ss.str();
1747}
1748
1749std::string ChannelMerger::DebugString() const {
1750 std::stringstream ss;
1751 ss << "start_time " << realtime_start_time() << " " << monotonic_start_time()
1752 << "\n";
1753 ss << "channel_heap {\n";
1754 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap =
1755 channel_heap_;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001756 while (!channel_heap.empty()) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001757 std::tuple<monotonic_clock::time_point, int> channel = channel_heap.front();
1758 ss << " " << std::get<0>(channel) << " (" << std::get<1>(channel) << ") "
1759 << configuration::CleanedChannelToString(
1760 configuration()->channels()->Get(std::get<1>(channel)))
1761 << "\n";
1762
1763 ss << timestamp_mergers_[std::get<1>(channel)].DebugString() << "\n";
1764
1765 std::pop_heap(channel_heap.begin(), channel_heap.end(),
1766 &ChannelHeapCompare);
1767 channel_heap.pop_back();
1768 }
1769 ss << "}";
1770
1771 return ss.str();
Austin Schuh05b70472020-01-01 17:11:17 -08001772}
1773
Austin Schuhee711052020-08-24 16:06:09 -07001774std::string MaybeNodeName(const Node *node) {
1775 if (node != nullptr) {
1776 return node->name()->str() + " ";
1777 }
1778 return "";
1779}
1780
Brian Silvermanf51499a2020-09-21 12:49:08 -07001781} // namespace aos::logger