blob: 1c42e173c3759a264cd6b8956a57c4030f2dce84 [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 Schuh3bd4c402020-11-06 18:19:06 -0800351std::optional<FlatbufferVector<LogFileHeader>> ReadHeader(
352 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;
363 data.resize(config_data.size() - sizeof(flatbuffers::uoffset_t));
364 memcpy(data.data(), config_data.begin() + sizeof(flatbuffers::uoffset_t),
365 data.size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800366 return FlatbufferVector<LogFileHeader>(std::move(data));
367}
368
Austin Schuh3bd4c402020-11-06 18:19:06 -0800369std::optional<FlatbufferVector<MessageHeader>> ReadNthMessage(
370 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -0700371 SpanReader span_reader(filename);
372 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
373 for (size_t i = 0; i < n + 1; ++i) {
374 data_span = span_reader.ReadMessage();
375
376 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800377 if (data_span == absl::Span<const uint8_t>()) {
378 return std::nullopt;
379 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700380 }
381
Brian Silverman354697a2020-09-22 21:06:32 -0700382 // And copy the config so we have it forever, removing the size prefix.
383 ResizeableBuffer data;
384 data.resize(data_span.size() - sizeof(flatbuffers::uoffset_t));
385 memcpy(data.data(), data_span.begin() + sizeof(flatbuffers::uoffset_t),
386 data.size());
Austin Schuh5212cad2020-09-09 23:12:09 -0700387 return FlatbufferVector<MessageHeader>(std::move(data));
388}
389
Austin Schuh05b70472020-01-01 17:11:17 -0800390MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -0700391 : span_reader_(filename),
392 raw_log_file_header_(FlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuh05b70472020-01-01 17:11:17 -0800393 // Make sure we have enough to read the size.
Austin Schuh97789fc2020-08-01 14:42:45 -0700394 absl::Span<const uint8_t> header_data = span_reader_.ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800395
396 // Make sure something was read.
Austin Schuh97789fc2020-08-01 14:42:45 -0700397 CHECK(header_data != absl::Span<const uint8_t>())
398 << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -0800399
Austin Schuh97789fc2020-08-01 14:42:45 -0700400 // And copy the header data so we have it forever.
Brian Silverman354697a2020-09-22 21:06:32 -0700401 ResizeableBuffer header_data_copy;
402 header_data_copy.resize(header_data.size() - sizeof(flatbuffers::uoffset_t));
403 memcpy(header_data_copy.data(),
404 header_data.begin() + sizeof(flatbuffers::uoffset_t),
405 header_data_copy.size());
Austin Schuh97789fc2020-08-01 14:42:45 -0700406 raw_log_file_header_ =
407 FlatbufferVector<LogFileHeader>(std::move(header_data_copy));
Austin Schuh05b70472020-01-01 17:11:17 -0800408
Austin Schuhcde938c2020-02-02 17:30:07 -0800409 max_out_of_order_duration_ =
Austin Schuh2f8fd752020-09-01 22:38:28 -0700410 chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -0800411
412 VLOG(1) << "Opened " << filename << " as node "
413 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800414}
415
416std::optional<FlatbufferVector<MessageHeader>> MessageReader::ReadMessage() {
417 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
418 if (msg_data == absl::Span<const uint8_t>()) {
419 return std::nullopt;
420 }
421
Brian Silverman354697a2020-09-22 21:06:32 -0700422 ResizeableBuffer result_buffer;
423 result_buffer.resize(msg_data.size() - sizeof(flatbuffers::uoffset_t));
424 memcpy(result_buffer.data(),
425 msg_data.begin() + sizeof(flatbuffers::uoffset_t),
426 result_buffer.size());
427 FlatbufferVector<MessageHeader> result(std::move(result_buffer));
Austin Schuh05b70472020-01-01 17:11:17 -0800428
429 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
430 chrono::nanoseconds(result.message().monotonic_sent_time()));
431
432 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuh8bd96322020-02-13 21:18:22 -0800433 VLOG(2) << "Read from " << filename() << " data " << FlatbufferToJson(result);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800434 return std::move(result);
Austin Schuh05b70472020-01-01 17:11:17 -0800435}
436
Austin Schuhc41603c2020-10-11 16:17:37 -0700437PartsMessageReader::PartsMessageReader(LogParts log_parts)
438 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {}
439
440std::optional<FlatbufferVector<MessageHeader>>
441PartsMessageReader::ReadMessage() {
442 while (!done_) {
443 std::optional<FlatbufferVector<MessageHeader>> message =
444 message_reader_.ReadMessage();
445 if (message) {
446 newest_timestamp_ = message_reader_.newest_timestamp();
447 return message;
448 }
449 NextLog();
450 }
451 return std::nullopt;
452}
453
454void PartsMessageReader::NextLog() {
455 if (next_part_index_ == parts_.parts.size()) {
456 done_ = true;
457 return;
458 }
459 message_reader_ = MessageReader(parts_.parts[next_part_index_]);
460 ++next_part_index_;
461}
462
Austin Schuh6f3babe2020-01-26 20:34:50 -0800463SplitMessageReader::SplitMessageReader(
Austin Schuhfa895892020-01-07 20:07:41 -0800464 const std::vector<std::string> &filenames)
465 : filenames_(filenames),
Austin Schuh97789fc2020-08-01 14:42:45 -0700466 log_file_header_(FlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuhfa895892020-01-07 20:07:41 -0800467 CHECK(NextLogFile()) << ": filenames is empty. Need files to read.";
468
Austin Schuh6f3babe2020-01-26 20:34:50 -0800469 // Grab any log file header. They should all match (and we will check as we
470 // open more of them).
Austin Schuh97789fc2020-08-01 14:42:45 -0700471 log_file_header_ = message_reader_->raw_log_file_header();
Austin Schuhfa895892020-01-07 20:07:41 -0800472
Austin Schuh2f8fd752020-09-01 22:38:28 -0700473 for (size_t i = 1; i < filenames_.size(); ++i) {
474 MessageReader message_reader(filenames_[i]);
475
476 const monotonic_clock::time_point new_monotonic_start_time(
477 chrono::nanoseconds(
478 message_reader.log_file_header()->monotonic_start_time()));
479 const realtime_clock::time_point new_realtime_start_time(
480 chrono::nanoseconds(
481 message_reader.log_file_header()->realtime_start_time()));
482
483 // There are 2 types of part files. Part files from before time estimation
484 // has started, and part files after. We don't declare a log file "started"
485 // until time estimation is up. And once a log file starts, it should never
486 // stop again, and should remain constant.
487 // To compare both types of headers, we mutate our saved copy of the header
488 // to match the next chunk by updating time if we detect a stopped ->
489 // started transition.
490 if (monotonic_start_time() == monotonic_clock::min_time) {
491 CHECK_EQ(realtime_start_time(), realtime_clock::min_time);
492 // We should only be missing the monotonic start time when logging data
Brian Silverman87ac0402020-09-17 14:47:01 -0700493 // for remote nodes. We don't have a good way to determine the remote
Austin Schuh2f8fd752020-09-01 22:38:28 -0700494 // realtime offset, so it shouldn't be filled out.
495 // TODO(austin): If we have a good way, feel free to fill it out. It
496 // probably won't be better than we could do in post though with the same
497 // data.
498 CHECK(!log_file_header_.mutable_message()->has_realtime_start_time());
499 if (new_monotonic_start_time != monotonic_clock::min_time) {
500 // If we finally found our start time, update the header. Do this once
501 // because it should never change again.
502 log_file_header_.mutable_message()->mutate_monotonic_start_time(
503 new_monotonic_start_time.time_since_epoch().count());
504 log_file_header_.mutable_message()->mutate_realtime_start_time(
505 new_realtime_start_time.time_since_epoch().count());
506 }
507 }
508
Austin Schuh64fab802020-09-09 22:47:47 -0700509 // We don't have a good way to set the realtime start time on remote nodes.
510 // Confirm it remains consistent.
511 CHECK_EQ(log_file_header_.mutable_message()->has_realtime_start_time(),
512 message_reader.log_file_header()->has_realtime_start_time());
513
514 // Parts index will *not* match unless we set them to match. We only want
515 // to accept the start time and parts mismatching, so set them.
516 log_file_header_.mutable_message()->mutate_parts_index(
517 message_reader.log_file_header()->parts_index());
518
Austin Schuh2f8fd752020-09-01 22:38:28 -0700519 // Now compare that the headers match.
Austin Schuh64fab802020-09-09 22:47:47 -0700520 if (!CompareFlatBuffer(message_reader.raw_log_file_header(),
521 log_file_header_)) {
Brian Silvermanae7c0332020-09-30 16:58:23 -0700522 if (message_reader.log_file_header()->has_log_event_uuid() &&
523 log_file_header_.message().has_log_event_uuid() &&
524 message_reader.log_file_header()->log_event_uuid()->string_view() !=
525 log_file_header_.message().log_event_uuid()->string_view()) {
Austin Schuh64fab802020-09-09 22:47:47 -0700526 LOG(FATAL) << "Logger UUIDs don't match between log file chunks "
527 << filenames_[0] << " and " << filenames_[i]
528 << ", this is not supported.";
529 }
530 if (message_reader.log_file_header()->has_parts_uuid() &&
531 log_file_header_.message().has_parts_uuid() &&
532 message_reader.log_file_header()->parts_uuid()->string_view() !=
533 log_file_header_.message().parts_uuid()->string_view()) {
534 LOG(FATAL) << "Parts UUIDs don't match between log file chunks "
535 << filenames_[0] << " and " << filenames_[i]
536 << ", this is not supported.";
537 }
538
539 LOG(FATAL) << "Header is different between log file chunks "
540 << filenames_[0] << " and " << filenames_[i]
541 << ", this is not supported.";
542 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700543 }
Austin Schuh64fab802020-09-09 22:47:47 -0700544 // Put the parts index back to the first log file chunk.
545 log_file_header_.mutable_message()->mutate_parts_index(
546 message_reader_->log_file_header()->parts_index());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700547
Austin Schuh6f3babe2020-01-26 20:34:50 -0800548 // Setup per channel state.
Austin Schuh05b70472020-01-01 17:11:17 -0800549 channels_.resize(configuration()->channels()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800550 for (ChannelData &channel_data : channels_) {
551 channel_data.data.split_reader = this;
552 // Build up the timestamp list.
553 if (configuration::MultiNode(configuration())) {
554 channel_data.timestamps.resize(configuration()->nodes()->size());
555 for (MessageHeaderQueue &queue : channel_data.timestamps) {
556 queue.timestamps = true;
557 queue.split_reader = this;
558 }
559 }
560 }
Austin Schuh05b70472020-01-01 17:11:17 -0800561
Austin Schuh6f3babe2020-01-26 20:34:50 -0800562 // Build up channels_to_write_ as an optimization to make it fast to figure
563 // out which datastructure to place any new data from a channel on.
564 for (const Channel *channel : *configuration()->channels()) {
565 // This is the main case. We will only see data on this node.
566 if (configuration::ChannelIsSendableOnNode(channel, node())) {
567 channels_to_write_.emplace_back(
568 &channels_[channels_to_write_.size()].data);
569 } else
570 // If we can't send, but can receive, we should be able to see
571 // timestamps here.
572 if (configuration::ChannelIsReadableOnNode(channel, node())) {
573 channels_to_write_.emplace_back(
574 &(channels_[channels_to_write_.size()]
575 .timestamps[configuration::GetNodeIndex(configuration(),
576 node())]));
577 } else {
578 channels_to_write_.emplace_back(nullptr);
579 }
580 }
Austin Schuh05b70472020-01-01 17:11:17 -0800581}
582
Austin Schuh6f3babe2020-01-26 20:34:50 -0800583bool SplitMessageReader::NextLogFile() {
Austin Schuhfa895892020-01-07 20:07:41 -0800584 if (next_filename_index_ == filenames_.size()) {
585 return false;
586 }
587 message_reader_ =
588 std::make_unique<MessageReader>(filenames_[next_filename_index_]);
589
590 // We can't support the config diverging between two log file headers. See if
591 // they are the same.
592 if (next_filename_index_ != 0) {
Austin Schuh64fab802020-09-09 22:47:47 -0700593 // In order for the headers to identically compare, they need to have the
594 // same parts_index. Rewrite the saved header with the new parts_index,
595 // compare, and then restore.
596 const int32_t original_parts_index =
597 log_file_header_.message().parts_index();
598 log_file_header_.mutable_message()->mutate_parts_index(
599 message_reader_->log_file_header()->parts_index());
600
Austin Schuh97789fc2020-08-01 14:42:45 -0700601 CHECK(CompareFlatBuffer(message_reader_->raw_log_file_header(),
602 log_file_header_))
Austin Schuhfa895892020-01-07 20:07:41 -0800603 << ": Header is different between log file chunks "
604 << filenames_[next_filename_index_] << " and "
605 << filenames_[next_filename_index_ - 1] << ", this is not supported.";
Austin Schuh64fab802020-09-09 22:47:47 -0700606
607 log_file_header_.mutable_message()->mutate_parts_index(
608 original_parts_index);
Austin Schuhfa895892020-01-07 20:07:41 -0800609 }
610
611 ++next_filename_index_;
612 return true;
613}
614
Austin Schuh6f3babe2020-01-26 20:34:50 -0800615bool SplitMessageReader::QueueMessages(
Austin Schuhcde938c2020-02-02 17:30:07 -0800616 monotonic_clock::time_point last_dequeued_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800617 // TODO(austin): Once we are happy that everything works, read a 256kb chunk
618 // to reduce the need to re-heap down below.
Austin Schuhcde938c2020-02-02 17:30:07 -0800619
620 // Special case no more data. Otherwise we blow up on the CHECK statement
621 // confirming that we have enough data queued.
622 if (at_end_) {
623 return false;
624 }
625
626 // If this isn't the first time around, confirm that we had enough data queued
627 // to follow the contract.
628 if (time_to_queue_ != monotonic_clock::min_time) {
629 CHECK_LE(last_dequeued_time,
630 newest_timestamp() - max_out_of_order_duration())
631 << " node " << FlatbufferToJson(node()) << " on " << this;
632
633 // Bail if there is enough data already queued.
634 if (last_dequeued_time < time_to_queue_) {
Austin Schuhee711052020-08-24 16:06:09 -0700635 VLOG(1) << MaybeNodeName(target_node_) << "All up to date on " << this
636 << ", dequeued " << last_dequeued_time << " queue time "
637 << time_to_queue_;
Austin Schuhcde938c2020-02-02 17:30:07 -0800638 return true;
639 }
640 } else {
641 // Startup takes a special dance. We want to queue up until the start time,
642 // but we then want to find the next message to read. The conservative
643 // answer is to immediately trigger a second requeue to get things moving.
644 time_to_queue_ = monotonic_start_time();
Austin Schuheeba0292020-10-11 16:20:05 -0700645 CHECK_NE(time_to_queue_, monotonic_clock::min_time);
Austin Schuhcde938c2020-02-02 17:30:07 -0800646 QueueMessages(time_to_queue_);
647 }
648
649 // If we are asked to queue, queue for at least max_out_of_order_duration past
650 // the last known time in the log file (ie the newest timestep read). As long
651 // as we requeue exactly when time_to_queue_ is dequeued and go no further, we
652 // are safe. And since we pop in order, that works.
653 //
654 // Special case the start of the log file. There should be at most 1 message
655 // from each channel at the start of the log file. So always force the start
656 // of the log file to just be read.
657 time_to_queue_ = std::max(time_to_queue_, newest_timestamp());
Austin Schuhee711052020-08-24 16:06:09 -0700658 VLOG(1) << MaybeNodeName(target_node_) << "Queueing, going until "
659 << time_to_queue_ << " " << filename();
Austin Schuhcde938c2020-02-02 17:30:07 -0800660
661 bool was_emplaced = false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800662 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800663 // Stop if we have enough.
Brian Silverman98360e22020-04-28 16:51:20 -0700664 if (newest_timestamp() > time_to_queue_ + max_out_of_order_duration() &&
Austin Schuhcde938c2020-02-02 17:30:07 -0800665 was_emplaced) {
Austin Schuhee711052020-08-24 16:06:09 -0700666 VLOG(1) << MaybeNodeName(target_node_) << "Done queueing on " << this
667 << ", queued to " << newest_timestamp() << " with requeue time "
668 << time_to_queue_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800669 return true;
670 }
Austin Schuh05b70472020-01-01 17:11:17 -0800671
Austin Schuh6f3babe2020-01-26 20:34:50 -0800672 if (std::optional<FlatbufferVector<MessageHeader>> msg =
673 message_reader_->ReadMessage()) {
674 const MessageHeader &header = msg.value().message();
675
Austin Schuhcde938c2020-02-02 17:30:07 -0800676 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
677 chrono::nanoseconds(header.monotonic_sent_time()));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800678
Austin Schuh0b5fd032020-03-28 17:36:49 -0700679 if (VLOG_IS_ON(2)) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700680 LOG(INFO) << MaybeNodeName(target_node_) << "Queued " << this << " "
681 << filename() << " ttq: " << time_to_queue_ << " now "
Austin Schuhee711052020-08-24 16:06:09 -0700682 << newest_timestamp() << " start time "
683 << monotonic_start_time() << " " << FlatbufferToJson(&header);
Austin Schuh0b5fd032020-03-28 17:36:49 -0700684 } else if (VLOG_IS_ON(1)) {
685 FlatbufferVector<MessageHeader> copy = msg.value();
686 copy.mutable_message()->clear_data();
Austin Schuhee711052020-08-24 16:06:09 -0700687 LOG(INFO) << MaybeNodeName(target_node_) << "Queued " << this << " "
688 << filename() << " ttq: " << time_to_queue_ << " now "
689 << newest_timestamp() << " start time "
690 << monotonic_start_time() << " " << FlatbufferToJson(copy);
Austin Schuh0b5fd032020-03-28 17:36:49 -0700691 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800692
693 const int channel_index = header.channel_index();
694 was_emplaced = channels_to_write_[channel_index]->emplace_back(
695 std::move(msg.value()));
696 if (was_emplaced) {
697 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
698 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800699 } else {
700 if (!NextLogFile()) {
Austin Schuhee711052020-08-24 16:06:09 -0700701 VLOG(1) << MaybeNodeName(target_node_) << "No more files, last was "
702 << filenames_.back();
Austin Schuhcde938c2020-02-02 17:30:07 -0800703 at_end_ = true;
Austin Schuh8bd96322020-02-13 21:18:22 -0800704 for (MessageHeaderQueue *queue : channels_to_write_) {
705 if (queue == nullptr || queue->timestamp_merger == nullptr) {
706 continue;
707 }
708 queue->timestamp_merger->NoticeAtEnd();
709 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800710 return false;
711 }
712 }
Austin Schuh05b70472020-01-01 17:11:17 -0800713 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800714}
715
716void SplitMessageReader::SetTimestampMerger(TimestampMerger *timestamp_merger,
717 int channel_index,
718 const Node *target_node) {
719 const Node *reinterpreted_target_node =
720 configuration::GetNodeOrDie(configuration(), target_node);
Austin Schuhee711052020-08-24 16:06:09 -0700721 target_node_ = reinterpreted_target_node;
722
Austin Schuh6f3babe2020-01-26 20:34:50 -0800723 const Channel *const channel =
724 configuration()->channels()->Get(channel_index);
725
Austin Schuhcde938c2020-02-02 17:30:07 -0800726 VLOG(1) << " Configuring merger " << this << " for channel " << channel_index
727 << " "
728 << configuration::CleanedChannelToString(
729 configuration()->channels()->Get(channel_index));
730
Austin Schuh6f3babe2020-01-26 20:34:50 -0800731 MessageHeaderQueue *message_header_queue = nullptr;
732
733 // Figure out if this log file is from our point of view, or the other node's
734 // point of view.
735 if (node() == reinterpreted_target_node) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800736 VLOG(1) << " Replaying as logged node " << filename();
737
738 if (configuration::ChannelIsSendableOnNode(channel, node())) {
739 VLOG(1) << " Data on node";
740 message_header_queue = &(channels_[channel_index].data);
741 } else if (configuration::ChannelIsReadableOnNode(channel, node())) {
742 VLOG(1) << " Timestamps on node";
743 message_header_queue =
744 &(channels_[channel_index].timestamps[configuration::GetNodeIndex(
745 configuration(), node())]);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800746 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800747 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800748 }
749 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800750 VLOG(1) << " Replaying as other node " << filename();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800751 // We are replaying from another node's point of view. The only interesting
Austin Schuhcde938c2020-02-02 17:30:07 -0800752 // data is data that is sent from our node and received on theirs.
753 if (configuration::ChannelIsReadableOnNode(channel,
754 reinterpreted_target_node) &&
755 configuration::ChannelIsSendableOnNode(channel, node())) {
756 VLOG(1) << " Readable on target node";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800757 // Data from another node.
758 message_header_queue = &(channels_[channel_index].data);
759 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800760 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800761 // This is either not sendable on the other node, or is a timestamp and
762 // therefore not interesting.
763 }
764 }
765
766 // If we found one, write it down. This will be nullptr when there is nothing
767 // relevant on this channel on this node for the target node. In that case,
768 // we want to drop the message instead of queueing it.
769 if (message_header_queue != nullptr) {
770 message_header_queue->timestamp_merger = timestamp_merger;
771 }
772}
773
774std::tuple<monotonic_clock::time_point, uint32_t,
775 FlatbufferVector<MessageHeader>>
776SplitMessageReader::PopOldest(int channel_index) {
777 CHECK_GT(channels_[channel_index].data.size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800778 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
779 timestamp = channels_[channel_index].data.front_timestamp();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800780 FlatbufferVector<MessageHeader> front =
781 std::move(channels_[channel_index].data.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700782 channels_[channel_index].data.PopFront();
Austin Schuhcde938c2020-02-02 17:30:07 -0800783
Austin Schuh2f8fd752020-09-01 22:38:28 -0700784 VLOG(1) << MaybeNodeName(target_node_) << "Popped Data " << this << " "
785 << std::get<0>(timestamp) << " for "
786 << configuration::StrippedChannelToString(
787 configuration()->channels()->Get(channel_index))
788 << " (" << channel_index << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -0800789
790 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800791
792 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
793 std::move(front));
794}
795
796std::tuple<monotonic_clock::time_point, uint32_t,
797 FlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -0700798SplitMessageReader::PopOldestTimestamp(int channel, int node_index) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800799 CHECK_GT(channels_[channel].timestamps[node_index].size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800800 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
801 timestamp = channels_[channel].timestamps[node_index].front_timestamp();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800802 FlatbufferVector<MessageHeader> front =
803 std::move(channels_[channel].timestamps[node_index].front());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700804 channels_[channel].timestamps[node_index].PopFront();
Austin Schuhcde938c2020-02-02 17:30:07 -0800805
Austin Schuh2f8fd752020-09-01 22:38:28 -0700806 VLOG(1) << MaybeNodeName(target_node_) << "Popped timestamp " << this << " "
Austin Schuhee711052020-08-24 16:06:09 -0700807 << std::get<0>(timestamp) << " for "
808 << configuration::StrippedChannelToString(
809 configuration()->channels()->Get(channel))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700810 << " on "
811 << configuration()->nodes()->Get(node_index)->name()->string_view()
812 << " (" << node_index << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -0800813
814 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800815
816 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
817 std::move(front));
818}
819
Austin Schuhcde938c2020-02-02 17:30:07 -0800820bool SplitMessageReader::MessageHeaderQueue::emplace_back(
Austin Schuh6f3babe2020-01-26 20:34:50 -0800821 FlatbufferVector<MessageHeader> &&msg) {
822 CHECK(split_reader != nullptr);
823
824 // If there is no timestamp merger for this queue, nobody is listening. Drop
825 // the message. This happens when a log file from another node is replayed,
826 // and the timestamp mergers down stream just don't care.
827 if (timestamp_merger == nullptr) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800828 return false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800829 }
830
831 CHECK(timestamps != msg.message().has_data())
832 << ": Got timestamps and data mixed up on a node. "
833 << FlatbufferToJson(msg);
834
835 data_.emplace_back(std::move(msg));
836
837 if (data_.size() == 1u) {
838 // Yup, new data. Notify.
839 if (timestamps) {
840 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
841 } else {
842 timestamp_merger->Update(split_reader, front_timestamp());
843 }
844 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800845
846 return true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800847}
848
Austin Schuh2f8fd752020-09-01 22:38:28 -0700849void SplitMessageReader::MessageHeaderQueue::PopFront() {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800850 data_.pop_front();
851 if (data_.size() != 0u) {
852 // Yup, new data.
853 if (timestamps) {
854 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
855 } else {
856 timestamp_merger->Update(split_reader, front_timestamp());
857 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700858 } else {
859 // Poke anyways to update the heap.
860 if (timestamps) {
861 timestamp_merger->UpdateTimestamp(
862 nullptr, std::make_tuple(monotonic_clock::min_time, 0, nullptr));
863 } else {
864 timestamp_merger->Update(
865 nullptr, std::make_tuple(monotonic_clock::min_time, 0, nullptr));
866 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800867 }
Austin Schuh05b70472020-01-01 17:11:17 -0800868}
869
870namespace {
871
Austin Schuh6f3babe2020-01-26 20:34:50 -0800872bool SplitMessageReaderHeapCompare(
873 const std::tuple<monotonic_clock::time_point, uint32_t,
874 SplitMessageReader *>
875 first,
876 const std::tuple<monotonic_clock::time_point, uint32_t,
877 SplitMessageReader *>
878 second) {
879 if (std::get<0>(first) > std::get<0>(second)) {
880 return true;
881 } else if (std::get<0>(first) == std::get<0>(second)) {
882 if (std::get<1>(first) > std::get<1>(second)) {
883 return true;
884 } else if (std::get<1>(first) == std::get<1>(second)) {
885 return std::get<2>(first) > std::get<2>(second);
886 } else {
887 return false;
888 }
889 } else {
890 return false;
891 }
892}
893
Austin Schuh05b70472020-01-01 17:11:17 -0800894bool ChannelHeapCompare(
895 const std::pair<monotonic_clock::time_point, int> first,
896 const std::pair<monotonic_clock::time_point, int> second) {
897 if (first.first > second.first) {
898 return true;
899 } else if (first.first == second.first) {
900 return first.second > second.second;
901 } else {
902 return false;
903 }
904}
905
906} // namespace
907
Austin Schuh6f3babe2020-01-26 20:34:50 -0800908TimestampMerger::TimestampMerger(
909 const Configuration *configuration,
910 std::vector<SplitMessageReader *> split_message_readers, int channel_index,
911 const Node *target_node, ChannelMerger *channel_merger)
912 : configuration_(configuration),
913 split_message_readers_(std::move(split_message_readers)),
914 channel_index_(channel_index),
915 node_index_(configuration::MultiNode(configuration)
916 ? configuration::GetNodeIndex(configuration, target_node)
917 : -1),
918 channel_merger_(channel_merger) {
919 // Tell the readers we care so they know who to notify.
Austin Schuhcde938c2020-02-02 17:30:07 -0800920 VLOG(1) << "Configuring channel " << channel_index << " target node "
921 << FlatbufferToJson(target_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800922 for (SplitMessageReader *reader : split_message_readers_) {
923 reader->SetTimestampMerger(this, channel_index, target_node);
924 }
925
926 // And then determine if we need to track timestamps.
927 const Channel *channel = configuration->channels()->Get(channel_index);
928 if (!configuration::ChannelIsSendableOnNode(channel, target_node) &&
929 configuration::ChannelIsReadableOnNode(channel, target_node)) {
930 has_timestamps_ = true;
931 }
932}
933
934void TimestampMerger::PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800935 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
936 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800937 SplitMessageReader *split_message_reader) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700938 if (split_message_reader != nullptr) {
939 DCHECK(std::find_if(message_heap_.begin(), message_heap_.end(),
940 [split_message_reader](
941 const std::tuple<monotonic_clock::time_point,
942 uint32_t, SplitMessageReader *>
943 x) {
944 return std::get<2>(x) == split_message_reader;
945 }) == message_heap_.end())
946 << ": Pushing message when it is already in the heap.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800947
Austin Schuh2f8fd752020-09-01 22:38:28 -0700948 message_heap_.push_back(std::make_tuple(
949 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800950
Austin Schuh2f8fd752020-09-01 22:38:28 -0700951 std::push_heap(message_heap_.begin(), message_heap_.end(),
952 &SplitMessageReaderHeapCompare);
953 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800954
955 // If we are just a data merger, don't wait for timestamps.
956 if (!has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700957 if (!message_heap_.empty()) {
958 channel_merger_->Update(std::get<0>(message_heap_[0]), channel_index_);
959 pushed_ = true;
960 } else {
961 // Remove ourselves if we are empty.
962 channel_merger_->Update(monotonic_clock::min_time, channel_index_);
963 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800964 }
965}
966
Austin Schuhcde938c2020-02-02 17:30:07 -0800967std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
968TimestampMerger::oldest_message() const {
969 CHECK_GT(message_heap_.size(), 0u);
970 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
971 oldest_message_reader = message_heap_.front();
972 return std::get<2>(oldest_message_reader)->oldest_message(channel_index_);
973}
974
975std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
976TimestampMerger::oldest_timestamp() const {
977 CHECK_GT(timestamp_heap_.size(), 0u);
978 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
979 oldest_message_reader = timestamp_heap_.front();
980 return std::get<2>(oldest_message_reader)
981 ->oldest_message(channel_index_, node_index_);
982}
983
Austin Schuh6f3babe2020-01-26 20:34:50 -0800984void TimestampMerger::PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800985 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
986 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800987 SplitMessageReader *split_message_reader) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700988 if (split_message_reader != nullptr) {
989 DCHECK(std::find_if(timestamp_heap_.begin(), timestamp_heap_.end(),
990 [split_message_reader](
991 const std::tuple<monotonic_clock::time_point,
992 uint32_t, SplitMessageReader *>
993 x) {
994 return std::get<2>(x) == split_message_reader;
995 }) == timestamp_heap_.end())
996 << ": Pushing timestamp when it is already in the heap.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800997
Austin Schuh2f8fd752020-09-01 22:38:28 -0700998 timestamp_heap_.push_back(std::make_tuple(
999 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001000
Austin Schuh2f8fd752020-09-01 22:38:28 -07001001 std::push_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1002 SplitMessageReaderHeapCompare);
1003 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001004
1005 // If we are a timestamp merger, don't wait for data. Missing data will be
1006 // caught at read time.
1007 if (has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001008 if (!timestamp_heap_.empty()) {
1009 channel_merger_->Update(std::get<0>(timestamp_heap_[0]), channel_index_);
1010 pushed_ = true;
1011 } else {
1012 // Remove ourselves if we are empty.
1013 channel_merger_->Update(monotonic_clock::min_time, channel_index_);
1014 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001015 }
1016}
1017
1018std::tuple<monotonic_clock::time_point, uint32_t,
1019 FlatbufferVector<MessageHeader>>
1020TimestampMerger::PopMessageHeap() {
1021 // Pop the oldest message reader pointer off the heap.
1022 CHECK_GT(message_heap_.size(), 0u);
1023 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1024 oldest_message_reader = message_heap_.front();
1025
1026 std::pop_heap(message_heap_.begin(), message_heap_.end(),
1027 &SplitMessageReaderHeapCompare);
1028 message_heap_.pop_back();
1029
1030 // Pop the oldest message. This re-pushes any messages from the reader to the
1031 // message heap.
1032 std::tuple<monotonic_clock::time_point, uint32_t,
1033 FlatbufferVector<MessageHeader>>
1034 oldest_message =
1035 std::get<2>(oldest_message_reader)->PopOldest(channel_index_);
1036
1037 // Confirm that the time and queue_index we have recorded matches.
1038 CHECK_EQ(std::get<0>(oldest_message), std::get<0>(oldest_message_reader));
1039 CHECK_EQ(std::get<1>(oldest_message), std::get<1>(oldest_message_reader));
1040
1041 // Now, keep reading until we have found all duplicates.
Brian Silverman8a32ce62020-08-12 12:02:38 -07001042 while (!message_heap_.empty()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001043 // See if it is a duplicate.
1044 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1045 next_oldest_message_reader = message_heap_.front();
1046
Austin Schuhcde938c2020-02-02 17:30:07 -08001047 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1048 next_oldest_message_time = std::get<2>(next_oldest_message_reader)
1049 ->oldest_message(channel_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001050
1051 if (std::get<0>(next_oldest_message_time) == std::get<0>(oldest_message) &&
1052 std::get<1>(next_oldest_message_time) == std::get<1>(oldest_message)) {
1053 // Pop the message reader pointer.
1054 std::pop_heap(message_heap_.begin(), message_heap_.end(),
1055 &SplitMessageReaderHeapCompare);
1056 message_heap_.pop_back();
1057
1058 // Pop the next oldest message. This re-pushes any messages from the
1059 // reader.
1060 std::tuple<monotonic_clock::time_point, uint32_t,
1061 FlatbufferVector<MessageHeader>>
1062 next_oldest_message = std::get<2>(next_oldest_message_reader)
1063 ->PopOldest(channel_index_);
1064
1065 // And make sure the message matches in it's entirety.
1066 CHECK(std::get<2>(oldest_message).span() ==
1067 std::get<2>(next_oldest_message).span())
1068 << ": Data at the same timestamp doesn't match.";
1069 } else {
1070 break;
1071 }
1072 }
1073
1074 return oldest_message;
1075}
1076
1077std::tuple<monotonic_clock::time_point, uint32_t,
1078 FlatbufferVector<MessageHeader>>
1079TimestampMerger::PopTimestampHeap() {
1080 // Pop the oldest message reader pointer off the heap.
1081 CHECK_GT(timestamp_heap_.size(), 0u);
1082
1083 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1084 oldest_timestamp_reader = timestamp_heap_.front();
1085
1086 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1087 &SplitMessageReaderHeapCompare);
1088 timestamp_heap_.pop_back();
1089
1090 CHECK(node_index_ != -1) << ": Timestamps in a single node environment";
1091
1092 // Pop the oldest message. This re-pushes any timestamps from the reader to
1093 // the timestamp heap.
1094 std::tuple<monotonic_clock::time_point, uint32_t,
1095 FlatbufferVector<MessageHeader>>
1096 oldest_timestamp = std::get<2>(oldest_timestamp_reader)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001097 ->PopOldestTimestamp(channel_index_, node_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001098
1099 // Confirm that the time we have recorded matches.
1100 CHECK_EQ(std::get<0>(oldest_timestamp), std::get<0>(oldest_timestamp_reader));
1101 CHECK_EQ(std::get<1>(oldest_timestamp), std::get<1>(oldest_timestamp_reader));
1102
Austin Schuh2f8fd752020-09-01 22:38:28 -07001103 // Now, keep reading until we have found all duplicates.
1104 while (!timestamp_heap_.empty()) {
1105 // See if it is a duplicate.
1106 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1107 next_oldest_timestamp_reader = timestamp_heap_.front();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001108
Austin Schuh2f8fd752020-09-01 22:38:28 -07001109 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1110 next_oldest_timestamp_time =
1111 std::get<2>(next_oldest_timestamp_reader)
1112 ->oldest_message(channel_index_, node_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001113
Austin Schuh2f8fd752020-09-01 22:38:28 -07001114 if (std::get<0>(next_oldest_timestamp_time) ==
1115 std::get<0>(oldest_timestamp) &&
1116 std::get<1>(next_oldest_timestamp_time) ==
1117 std::get<1>(oldest_timestamp)) {
1118 // Pop the timestamp reader pointer.
1119 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1120 &SplitMessageReaderHeapCompare);
1121 timestamp_heap_.pop_back();
1122
1123 // Pop the next oldest timestamp. This re-pushes any messages from the
1124 // reader.
1125 std::tuple<monotonic_clock::time_point, uint32_t,
1126 FlatbufferVector<MessageHeader>>
1127 next_oldest_timestamp =
1128 std::get<2>(next_oldest_timestamp_reader)
1129 ->PopOldestTimestamp(channel_index_, node_index_);
1130
1131 // And make sure the contents matches in it's entirety.
1132 CHECK(std::get<2>(oldest_timestamp).span() ==
1133 std::get<2>(next_oldest_timestamp).span())
1134 << ": Data at the same timestamp doesn't match, "
1135 << aos::FlatbufferToJson(std::get<2>(oldest_timestamp)) << " vs "
1136 << aos::FlatbufferToJson(std::get<2>(next_oldest_timestamp)) << " "
1137 << absl::BytesToHexString(std::string_view(
1138 reinterpret_cast<const char *>(
1139 std::get<2>(oldest_timestamp).span().data()),
1140 std::get<2>(oldest_timestamp).span().size()))
1141 << " vs "
1142 << absl::BytesToHexString(std::string_view(
1143 reinterpret_cast<const char *>(
1144 std::get<2>(next_oldest_timestamp).span().data()),
1145 std::get<2>(next_oldest_timestamp).span().size()));
1146
1147 } else {
1148 break;
1149 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001150 }
1151
Austin Schuh2f8fd752020-09-01 22:38:28 -07001152 return oldest_timestamp;
Austin Schuh8bd96322020-02-13 21:18:22 -08001153}
1154
Austin Schuh6f3babe2020-01-26 20:34:50 -08001155std::tuple<TimestampMerger::DeliveryTimestamp, FlatbufferVector<MessageHeader>>
1156TimestampMerger::PopOldest() {
1157 if (has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001158 VLOG(1) << "Looking for matching timestamp for "
1159 << configuration::StrippedChannelToString(
1160 configuration_->channels()->Get(channel_index_))
1161 << " (" << channel_index_ << ") "
1162 << " at " << std::get<0>(oldest_timestamp());
1163
Austin Schuh8bd96322020-02-13 21:18:22 -08001164 // Read the timestamps.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001165 std::tuple<monotonic_clock::time_point, uint32_t,
1166 FlatbufferVector<MessageHeader>>
1167 oldest_timestamp = PopTimestampHeap();
1168
1169 TimestampMerger::DeliveryTimestamp timestamp;
1170 timestamp.monotonic_event_time =
1171 monotonic_clock::time_point(chrono::nanoseconds(
1172 std::get<2>(oldest_timestamp).message().monotonic_sent_time()));
1173 timestamp.realtime_event_time =
1174 realtime_clock::time_point(chrono::nanoseconds(
1175 std::get<2>(oldest_timestamp).message().realtime_sent_time()));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001176 timestamp.queue_index =
1177 std::get<2>(oldest_timestamp).message().queue_index();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001178
1179 // Consistency check.
1180 CHECK_EQ(timestamp.monotonic_event_time, std::get<0>(oldest_timestamp));
1181 CHECK_EQ(std::get<2>(oldest_timestamp).message().queue_index(),
1182 std::get<1>(oldest_timestamp));
1183
1184 monotonic_clock::time_point remote_timestamp_monotonic_time(
1185 chrono::nanoseconds(
1186 std::get<2>(oldest_timestamp).message().monotonic_remote_time()));
1187
Austin Schuh8bd96322020-02-13 21:18:22 -08001188 // See if we have any data. If not, pass the problem up the chain.
Brian Silverman8a32ce62020-08-12 12:02:38 -07001189 if (message_heap_.empty()) {
Austin Schuhee711052020-08-24 16:06:09 -07001190 LOG(WARNING) << MaybeNodeName(configuration_->nodes()->Get(node_index_))
1191 << "No data to match timestamp on "
1192 << configuration::CleanedChannelToString(
1193 configuration_->channels()->Get(channel_index_))
1194 << " (" << channel_index_ << ")";
Austin Schuh8bd96322020-02-13 21:18:22 -08001195 return std::make_tuple(timestamp,
1196 std::move(std::get<2>(oldest_timestamp)));
1197 }
1198
Austin Schuh6f3babe2020-01-26 20:34:50 -08001199 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001200 {
1201 // Ok, now try grabbing data until we find one which matches.
1202 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1203 oldest_message_ref = oldest_message();
1204
1205 // Time at which the message was sent (this message is written from the
1206 // sending node's perspective.
1207 monotonic_clock::time_point remote_monotonic_time(chrono::nanoseconds(
1208 std::get<2>(oldest_message_ref)->monotonic_sent_time()));
1209
1210 if (remote_monotonic_time < remote_timestamp_monotonic_time) {
Austin Schuhee711052020-08-24 16:06:09 -07001211 LOG(WARNING) << configuration_->nodes()
1212 ->Get(node_index_)
1213 ->name()
1214 ->string_view()
1215 << " Undelivered message, skipping. Remote time is "
1216 << remote_monotonic_time << " timestamp is "
1217 << remote_timestamp_monotonic_time << " on channel "
1218 << configuration::StrippedChannelToString(
1219 configuration_->channels()->Get(channel_index_))
1220 << " (" << channel_index_ << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -08001221 PopMessageHeap();
1222 continue;
1223 } else if (remote_monotonic_time > remote_timestamp_monotonic_time) {
Austin Schuhee711052020-08-24 16:06:09 -07001224 LOG(WARNING) << configuration_->nodes()
1225 ->Get(node_index_)
1226 ->name()
1227 ->string_view()
1228 << " Data not found. Remote time should be "
1229 << remote_timestamp_monotonic_time
1230 << ", message time is " << remote_monotonic_time
1231 << " on channel "
1232 << configuration::StrippedChannelToString(
1233 configuration_->channels()->Get(channel_index_))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001234 << " (" << channel_index_ << ")"
1235 << (VLOG_IS_ON(1) ? DebugString() : "");
Austin Schuhcde938c2020-02-02 17:30:07 -08001236 return std::make_tuple(timestamp,
1237 std::move(std::get<2>(oldest_timestamp)));
1238 }
1239
1240 timestamp.monotonic_remote_time = remote_monotonic_time;
1241 }
1242
Austin Schuh2f8fd752020-09-01 22:38:28 -07001243 VLOG(1) << "Found matching data "
1244 << configuration::StrippedChannelToString(
1245 configuration_->channels()->Get(channel_index_))
1246 << " (" << channel_index_ << ")";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001247 std::tuple<monotonic_clock::time_point, uint32_t,
1248 FlatbufferVector<MessageHeader>>
1249 oldest_message = PopMessageHeap();
1250
Austin Schuh6f3babe2020-01-26 20:34:50 -08001251 timestamp.realtime_remote_time =
1252 realtime_clock::time_point(chrono::nanoseconds(
1253 std::get<2>(oldest_message).message().realtime_sent_time()));
1254 timestamp.remote_queue_index =
1255 std::get<2>(oldest_message).message().queue_index();
1256
Austin Schuhcde938c2020-02-02 17:30:07 -08001257 CHECK_EQ(timestamp.monotonic_remote_time,
1258 remote_timestamp_monotonic_time);
1259
1260 CHECK_EQ(timestamp.remote_queue_index,
1261 std::get<2>(oldest_timestamp).message().remote_queue_index())
1262 << ": " << FlatbufferToJson(&std::get<2>(oldest_timestamp).message())
1263 << " data "
1264 << FlatbufferToJson(&std::get<2>(oldest_message).message());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001265
Austin Schuh30dd5c52020-08-01 14:43:44 -07001266 return std::make_tuple(timestamp, std::move(std::get<2>(oldest_message)));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001267 }
1268 } else {
1269 std::tuple<monotonic_clock::time_point, uint32_t,
1270 FlatbufferVector<MessageHeader>>
1271 oldest_message = PopMessageHeap();
1272
1273 TimestampMerger::DeliveryTimestamp timestamp;
1274 timestamp.monotonic_event_time =
1275 monotonic_clock::time_point(chrono::nanoseconds(
1276 std::get<2>(oldest_message).message().monotonic_sent_time()));
1277 timestamp.realtime_event_time =
1278 realtime_clock::time_point(chrono::nanoseconds(
1279 std::get<2>(oldest_message).message().realtime_sent_time()));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001280 timestamp.queue_index = std::get<2>(oldest_message).message().queue_index();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001281 timestamp.remote_queue_index = 0xffffffff;
1282
1283 CHECK_EQ(std::get<0>(oldest_message), timestamp.monotonic_event_time);
1284 CHECK_EQ(std::get<1>(oldest_message),
1285 std::get<2>(oldest_message).message().queue_index());
1286
Austin Schuh30dd5c52020-08-01 14:43:44 -07001287 return std::make_tuple(timestamp, std::move(std::get<2>(oldest_message)));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001288 }
1289}
1290
Austin Schuh8bd96322020-02-13 21:18:22 -08001291void TimestampMerger::NoticeAtEnd() { channel_merger_->NoticeAtEnd(); }
1292
Austin Schuh6f3babe2020-01-26 20:34:50 -08001293namespace {
1294std::vector<std::unique_ptr<SplitMessageReader>> MakeSplitMessageReaders(
1295 const std::vector<std::vector<std::string>> &filenames) {
1296 CHECK_GT(filenames.size(), 0u);
1297 // Build up all the SplitMessageReaders.
1298 std::vector<std::unique_ptr<SplitMessageReader>> result;
1299 for (const std::vector<std::string> &filenames : filenames) {
1300 result.emplace_back(std::make_unique<SplitMessageReader>(filenames));
1301 }
1302 return result;
1303}
1304} // namespace
1305
1306ChannelMerger::ChannelMerger(
1307 const std::vector<std::vector<std::string>> &filenames)
1308 : split_message_readers_(MakeSplitMessageReaders(filenames)),
Austin Schuh97789fc2020-08-01 14:42:45 -07001309 log_file_header_(split_message_readers_[0]->raw_log_file_header()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001310 // Now, confirm that the configuration matches for each and pick a start time.
1311 // Also return the list of possible nodes.
1312 for (const std::unique_ptr<SplitMessageReader> &reader :
1313 split_message_readers_) {
1314 CHECK(CompareFlatBuffer(log_file_header_.message().configuration(),
1315 reader->log_file_header()->configuration()))
1316 << ": Replaying log files with different configurations isn't "
1317 "supported";
1318 }
1319
1320 nodes_ = configuration::GetNodes(configuration());
1321}
1322
1323bool ChannelMerger::SetNode(const Node *target_node) {
1324 std::vector<SplitMessageReader *> split_message_readers;
1325 for (const std::unique_ptr<SplitMessageReader> &reader :
1326 split_message_readers_) {
1327 split_message_readers.emplace_back(reader.get());
1328 }
1329
1330 // Go find a log_file_header for this node.
1331 {
1332 bool found_node = false;
1333
1334 for (const std::unique_ptr<SplitMessageReader> &reader :
1335 split_message_readers_) {
James Kuszmaulfc273dc2020-05-09 17:56:19 -07001336 // In order to identify which logfile(s) map to the target node, do a
1337 // logical comparison of the nodes, by confirming that we are either in a
1338 // single-node setup (where the nodes will both be nullptr) or that the
1339 // node names match (but the other node fields--e.g., hostname lists--may
1340 // not).
1341 const bool both_null =
1342 reader->node() == nullptr && target_node == nullptr;
1343 const bool both_have_name =
1344 (reader->node() != nullptr) && (target_node != nullptr) &&
1345 (reader->node()->has_name() && target_node->has_name());
1346 const bool node_names_identical =
Brian Silvermand90905f2020-09-23 14:42:56 -07001347 both_have_name && (reader->node()->name()->string_view() ==
1348 target_node->name()->string_view());
James Kuszmaulfc273dc2020-05-09 17:56:19 -07001349 if (both_null || node_names_identical) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001350 if (!found_node) {
1351 found_node = true;
1352 log_file_header_ = CopyFlatBuffer(reader->log_file_header());
Austin Schuhcde938c2020-02-02 17:30:07 -08001353 VLOG(1) << "Found log file " << reader->filename() << " with node "
1354 << FlatbufferToJson(reader->node()) << " start_time "
1355 << monotonic_start_time();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001356 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001357 // Find the earliest start time. That way, if we get a full log file
1358 // directly from the node, and a partial later, we start with the
1359 // full. Update our header to match that.
1360 const monotonic_clock::time_point new_monotonic_start_time(
1361 chrono::nanoseconds(
1362 reader->log_file_header()->monotonic_start_time()));
1363 const realtime_clock::time_point new_realtime_start_time(
1364 chrono::nanoseconds(
1365 reader->log_file_header()->realtime_start_time()));
1366
1367 if (monotonic_start_time() == monotonic_clock::min_time ||
1368 (new_monotonic_start_time != monotonic_clock::min_time &&
1369 new_monotonic_start_time < monotonic_start_time())) {
1370 log_file_header_.mutable_message()->mutate_monotonic_start_time(
1371 new_monotonic_start_time.time_since_epoch().count());
1372 log_file_header_.mutable_message()->mutate_realtime_start_time(
1373 new_realtime_start_time.time_since_epoch().count());
1374 VLOG(1) << "Updated log file " << reader->filename()
1375 << " with node " << FlatbufferToJson(reader->node())
1376 << " start_time " << new_monotonic_start_time;
1377 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001378 }
1379 }
1380 }
1381
1382 if (!found_node) {
1383 LOG(WARNING) << "Failed to find log file for node "
1384 << FlatbufferToJson(target_node);
1385 return false;
1386 }
1387 }
1388
1389 // Build up all the timestamp mergers. This connects up all the
1390 // SplitMessageReaders.
1391 timestamp_mergers_.reserve(configuration()->channels()->size());
1392 for (size_t channel_index = 0;
1393 channel_index < configuration()->channels()->size(); ++channel_index) {
1394 timestamp_mergers_.emplace_back(
1395 configuration(), split_message_readers, channel_index,
1396 configuration::GetNode(configuration(), target_node), this);
1397 }
1398
1399 // And prime everything.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001400 for (std::unique_ptr<SplitMessageReader> &split_message_reader :
1401 split_message_readers_) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001402 split_message_reader->QueueMessages(
1403 split_message_reader->monotonic_start_time());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001404 }
1405
1406 node_ = configuration::GetNodeOrDie(configuration(), target_node);
1407 return true;
1408}
1409
Austin Schuh858c9f32020-08-31 16:56:12 -07001410monotonic_clock::time_point ChannelMerger::OldestMessageTime() const {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001411 if (channel_heap_.empty()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001412 return monotonic_clock::max_time;
1413 }
1414 return channel_heap_.front().first;
1415}
1416
1417void ChannelMerger::PushChannelHeap(monotonic_clock::time_point timestamp,
1418 int channel_index) {
1419 // Pop and recreate the heap if it has already been pushed. And since we are
1420 // pushing again, we don't need to clear pushed.
1421 if (timestamp_mergers_[channel_index].pushed()) {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001422 const auto channel_iterator = std::find_if(
Austin Schuh6f3babe2020-01-26 20:34:50 -08001423 channel_heap_.begin(), channel_heap_.end(),
1424 [channel_index](const std::pair<monotonic_clock::time_point, int> x) {
1425 return x.second == channel_index;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001426 });
1427 DCHECK(channel_iterator != channel_heap_.end());
1428 if (std::get<0>(*channel_iterator) == timestamp) {
1429 // It's already in the heap, in the correct spot, so nothing
1430 // more for us to do here.
1431 return;
1432 }
1433 channel_heap_.erase(channel_iterator);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001434 std::make_heap(channel_heap_.begin(), channel_heap_.end(),
1435 ChannelHeapCompare);
1436 }
1437
Austin Schuh2f8fd752020-09-01 22:38:28 -07001438 if (timestamp == monotonic_clock::min_time) {
1439 timestamp_mergers_[channel_index].set_pushed(false);
1440 return;
1441 }
1442
Austin Schuh05b70472020-01-01 17:11:17 -08001443 channel_heap_.push_back(std::make_pair(timestamp, channel_index));
1444
1445 // The default sort puts the newest message first. Use a custom comparator to
1446 // put the oldest message first.
1447 std::push_heap(channel_heap_.begin(), channel_heap_.end(),
1448 ChannelHeapCompare);
1449}
1450
Austin Schuh2f8fd752020-09-01 22:38:28 -07001451void ChannelMerger::VerifyHeaps() {
Austin Schuh661a8d82020-09-13 17:25:56 -07001452 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap =
1453 channel_heap_;
1454 std::make_heap(channel_heap.begin(), channel_heap.end(), &ChannelHeapCompare);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001455
Austin Schuh661a8d82020-09-13 17:25:56 -07001456 for (size_t i = 0; i < channel_heap_.size(); ++i) {
1457 CHECK(channel_heap_[i] == channel_heap[i]) << ": Heaps diverged...";
1458 CHECK_EQ(
1459 std::get<0>(channel_heap[i]),
1460 timestamp_mergers_[std::get<1>(channel_heap[i])].channel_merger_time());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001461 }
1462}
1463
Austin Schuh6f3babe2020-01-26 20:34:50 -08001464std::tuple<TimestampMerger::DeliveryTimestamp, int,
1465 FlatbufferVector<MessageHeader>>
1466ChannelMerger::PopOldest() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001467 CHECK_GT(channel_heap_.size(), 0u);
Austin Schuh05b70472020-01-01 17:11:17 -08001468 std::pair<monotonic_clock::time_point, int> oldest_channel_data =
1469 channel_heap_.front();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001470 int channel_index = oldest_channel_data.second;
Austin Schuh05b70472020-01-01 17:11:17 -08001471 std::pop_heap(channel_heap_.begin(), channel_heap_.end(),
1472 &ChannelHeapCompare);
1473 channel_heap_.pop_back();
Austin Schuh8bd96322020-02-13 21:18:22 -08001474
Austin Schuh6f3babe2020-01-26 20:34:50 -08001475 timestamp_mergers_[channel_index].set_pushed(false);
Austin Schuh05b70472020-01-01 17:11:17 -08001476
Austin Schuh6f3babe2020-01-26 20:34:50 -08001477 TimestampMerger *merger = &timestamp_mergers_[channel_index];
Austin Schuh05b70472020-01-01 17:11:17 -08001478
Austin Schuhcde938c2020-02-02 17:30:07 -08001479 // Merger handles any queueing needed from here.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001480 std::tuple<TimestampMerger::DeliveryTimestamp,
1481 FlatbufferVector<MessageHeader>>
1482 message = merger->PopOldest();
Brian Silverman8a32ce62020-08-12 12:02:38 -07001483 DCHECK_EQ(std::get<0>(message).monotonic_event_time,
1484 oldest_channel_data.first)
1485 << ": channel_heap_ was corrupted for " << channel_index << ": "
1486 << DebugString();
Austin Schuh05b70472020-01-01 17:11:17 -08001487
Austin Schuh2f8fd752020-09-01 22:38:28 -07001488 CHECK_GE(std::get<0>(message).monotonic_event_time, last_popped_time_)
1489 << ": " << MaybeNodeName(log_file_header()->node())
1490 << "Messages came off the queue out of order. " << DebugString();
1491 last_popped_time_ = std::get<0>(message).monotonic_event_time;
1492
1493 VLOG(1) << "Popped " << last_popped_time_ << " "
1494 << configuration::StrippedChannelToString(
1495 configuration()->channels()->Get(channel_index))
1496 << " (" << channel_index << ")";
1497
Austin Schuh6f3babe2020-01-26 20:34:50 -08001498 return std::make_tuple(std::get<0>(message), channel_index,
1499 std::move(std::get<1>(message)));
1500}
1501
Austin Schuhcde938c2020-02-02 17:30:07 -08001502std::string SplitMessageReader::MessageHeaderQueue::DebugString() const {
1503 std::stringstream ss;
1504 for (size_t i = 0; i < data_.size(); ++i) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001505 if (i < 5 || i + 5 > data_.size()) {
1506 if (timestamps) {
1507 ss << " msg: ";
1508 } else {
1509 ss << " timestamp: ";
1510 }
1511 ss << monotonic_clock::time_point(
1512 chrono::nanoseconds(data_[i].message().monotonic_sent_time()))
Austin Schuhcde938c2020-02-02 17:30:07 -08001513 << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001514 << realtime_clock::time_point(
1515 chrono::nanoseconds(data_[i].message().realtime_sent_time()))
1516 << ") " << data_[i].message().queue_index();
1517 if (timestamps) {
1518 ss << " <- remote "
1519 << monotonic_clock::time_point(chrono::nanoseconds(
1520 data_[i].message().monotonic_remote_time()))
1521 << " ("
1522 << realtime_clock::time_point(chrono::nanoseconds(
1523 data_[i].message().realtime_remote_time()))
1524 << ")";
1525 }
1526 ss << "\n";
1527 } else if (i == 5) {
1528 ss << " ...\n";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001529 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001530 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001531
Austin Schuhcde938c2020-02-02 17:30:07 -08001532 return ss.str();
1533}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001534
Austin Schuhcde938c2020-02-02 17:30:07 -08001535std::string SplitMessageReader::DebugString(int channel) const {
1536 std::stringstream ss;
1537 ss << "[\n";
1538 ss << channels_[channel].data.DebugString();
1539 ss << " ]";
1540 return ss.str();
1541}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001542
Austin Schuhcde938c2020-02-02 17:30:07 -08001543std::string SplitMessageReader::DebugString(int channel, int node_index) const {
1544 std::stringstream ss;
1545 ss << "[\n";
1546 ss << channels_[channel].timestamps[node_index].DebugString();
1547 ss << " ]";
1548 return ss.str();
1549}
1550
1551std::string TimestampMerger::DebugString() const {
1552 std::stringstream ss;
1553
1554 if (timestamp_heap_.size() > 0) {
1555 ss << " timestamp_heap {\n";
1556 std::vector<
1557 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1558 timestamp_heap = timestamp_heap_;
1559 while (timestamp_heap.size() > 0u) {
1560 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1561 oldest_timestamp_reader = timestamp_heap.front();
1562
1563 ss << " " << std::get<2>(oldest_timestamp_reader) << " "
1564 << std::get<0>(oldest_timestamp_reader) << " queue_index ("
1565 << std::get<1>(oldest_timestamp_reader) << ") ttq "
1566 << std::get<2>(oldest_timestamp_reader)->time_to_queue() << " "
1567 << std::get<2>(oldest_timestamp_reader)->filename() << " -> "
1568 << std::get<2>(oldest_timestamp_reader)
1569 ->DebugString(channel_index_, node_index_)
1570 << "\n";
1571
1572 std::pop_heap(timestamp_heap.begin(), timestamp_heap.end(),
1573 &SplitMessageReaderHeapCompare);
1574 timestamp_heap.pop_back();
1575 }
1576 ss << " }\n";
1577 }
1578
1579 ss << " message_heap {\n";
1580 {
1581 std::vector<
1582 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1583 message_heap = message_heap_;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001584 while (!message_heap.empty()) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001585 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1586 oldest_message_reader = message_heap.front();
1587
1588 ss << " " << std::get<2>(oldest_message_reader) << " "
1589 << std::get<0>(oldest_message_reader) << " queue_index ("
1590 << std::get<1>(oldest_message_reader) << ") ttq "
1591 << std::get<2>(oldest_message_reader)->time_to_queue() << " "
1592 << std::get<2>(oldest_message_reader)->filename() << " -> "
1593 << std::get<2>(oldest_message_reader)->DebugString(channel_index_)
1594 << "\n";
1595
1596 std::pop_heap(message_heap.begin(), message_heap.end(),
1597 &SplitMessageReaderHeapCompare);
1598 message_heap.pop_back();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001599 }
Austin Schuh05b70472020-01-01 17:11:17 -08001600 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001601 ss << " }";
1602
1603 return ss.str();
1604}
1605
1606std::string ChannelMerger::DebugString() const {
1607 std::stringstream ss;
1608 ss << "start_time " << realtime_start_time() << " " << monotonic_start_time()
1609 << "\n";
1610 ss << "channel_heap {\n";
1611 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap =
1612 channel_heap_;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001613 while (!channel_heap.empty()) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001614 std::tuple<monotonic_clock::time_point, int> channel = channel_heap.front();
1615 ss << " " << std::get<0>(channel) << " (" << std::get<1>(channel) << ") "
1616 << configuration::CleanedChannelToString(
1617 configuration()->channels()->Get(std::get<1>(channel)))
1618 << "\n";
1619
1620 ss << timestamp_mergers_[std::get<1>(channel)].DebugString() << "\n";
1621
1622 std::pop_heap(channel_heap.begin(), channel_heap.end(),
1623 &ChannelHeapCompare);
1624 channel_heap.pop_back();
1625 }
1626 ss << "}";
1627
1628 return ss.str();
Austin Schuh05b70472020-01-01 17:11:17 -08001629}
1630
Austin Schuhee711052020-08-24 16:06:09 -07001631std::string MaybeNodeName(const Node *node) {
1632 if (node != nullptr) {
1633 return node->name()->str() + " ";
1634 }
1635 return "";
1636}
1637
Brian Silvermanf51499a2020-09-21 12:49:08 -07001638} // namespace aos::logger