blob: d906997ee1d0ab4b66ec2873cb984584ccc0205a [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();
Austin Schuh32f68492020-11-08 21:45:51 -0800447 const monotonic_clock::time_point monotonic_sent_time(
448 chrono::nanoseconds(message->message().monotonic_sent_time()));
449 CHECK_GE(monotonic_sent_time,
450 newest_timestamp_ - max_out_of_order_duration());
Austin Schuhc41603c2020-10-11 16:17:37 -0700451 return message;
452 }
453 NextLog();
454 }
Austin Schuh32f68492020-11-08 21:45:51 -0800455 newest_timestamp_ = monotonic_clock::max_time;
Austin Schuhc41603c2020-10-11 16:17:37 -0700456 return std::nullopt;
457}
458
459void PartsMessageReader::NextLog() {
460 if (next_part_index_ == parts_.parts.size()) {
461 done_ = true;
462 return;
463 }
464 message_reader_ = MessageReader(parts_.parts[next_part_index_]);
465 ++next_part_index_;
466}
467
Austin Schuh6f3babe2020-01-26 20:34:50 -0800468SplitMessageReader::SplitMessageReader(
Austin Schuhfa895892020-01-07 20:07:41 -0800469 const std::vector<std::string> &filenames)
470 : filenames_(filenames),
Austin Schuh97789fc2020-08-01 14:42:45 -0700471 log_file_header_(FlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuhfa895892020-01-07 20:07:41 -0800472 CHECK(NextLogFile()) << ": filenames is empty. Need files to read.";
473
Austin Schuh6f3babe2020-01-26 20:34:50 -0800474 // Grab any log file header. They should all match (and we will check as we
475 // open more of them).
Austin Schuh97789fc2020-08-01 14:42:45 -0700476 log_file_header_ = message_reader_->raw_log_file_header();
Austin Schuhfa895892020-01-07 20:07:41 -0800477
Austin Schuh2f8fd752020-09-01 22:38:28 -0700478 for (size_t i = 1; i < filenames_.size(); ++i) {
479 MessageReader message_reader(filenames_[i]);
480
481 const monotonic_clock::time_point new_monotonic_start_time(
482 chrono::nanoseconds(
483 message_reader.log_file_header()->monotonic_start_time()));
484 const realtime_clock::time_point new_realtime_start_time(
485 chrono::nanoseconds(
486 message_reader.log_file_header()->realtime_start_time()));
487
488 // There are 2 types of part files. Part files from before time estimation
489 // has started, and part files after. We don't declare a log file "started"
490 // until time estimation is up. And once a log file starts, it should never
491 // stop again, and should remain constant.
492 // To compare both types of headers, we mutate our saved copy of the header
493 // to match the next chunk by updating time if we detect a stopped ->
494 // started transition.
495 if (monotonic_start_time() == monotonic_clock::min_time) {
496 CHECK_EQ(realtime_start_time(), realtime_clock::min_time);
497 // We should only be missing the monotonic start time when logging data
Brian Silverman87ac0402020-09-17 14:47:01 -0700498 // for remote nodes. We don't have a good way to determine the remote
Austin Schuh2f8fd752020-09-01 22:38:28 -0700499 // realtime offset, so it shouldn't be filled out.
500 // TODO(austin): If we have a good way, feel free to fill it out. It
501 // probably won't be better than we could do in post though with the same
502 // data.
503 CHECK(!log_file_header_.mutable_message()->has_realtime_start_time());
504 if (new_monotonic_start_time != monotonic_clock::min_time) {
505 // If we finally found our start time, update the header. Do this once
506 // because it should never change again.
507 log_file_header_.mutable_message()->mutate_monotonic_start_time(
508 new_monotonic_start_time.time_since_epoch().count());
509 log_file_header_.mutable_message()->mutate_realtime_start_time(
510 new_realtime_start_time.time_since_epoch().count());
511 }
512 }
513
Austin Schuh64fab802020-09-09 22:47:47 -0700514 // We don't have a good way to set the realtime start time on remote nodes.
515 // Confirm it remains consistent.
516 CHECK_EQ(log_file_header_.mutable_message()->has_realtime_start_time(),
517 message_reader.log_file_header()->has_realtime_start_time());
518
519 // Parts index will *not* match unless we set them to match. We only want
520 // to accept the start time and parts mismatching, so set them.
521 log_file_header_.mutable_message()->mutate_parts_index(
522 message_reader.log_file_header()->parts_index());
523
Austin Schuh2f8fd752020-09-01 22:38:28 -0700524 // Now compare that the headers match.
Austin Schuh64fab802020-09-09 22:47:47 -0700525 if (!CompareFlatBuffer(message_reader.raw_log_file_header(),
526 log_file_header_)) {
Brian Silvermanae7c0332020-09-30 16:58:23 -0700527 if (message_reader.log_file_header()->has_log_event_uuid() &&
528 log_file_header_.message().has_log_event_uuid() &&
529 message_reader.log_file_header()->log_event_uuid()->string_view() !=
530 log_file_header_.message().log_event_uuid()->string_view()) {
Austin Schuh64fab802020-09-09 22:47:47 -0700531 LOG(FATAL) << "Logger UUIDs don't match between log file chunks "
532 << filenames_[0] << " and " << filenames_[i]
533 << ", this is not supported.";
534 }
535 if (message_reader.log_file_header()->has_parts_uuid() &&
536 log_file_header_.message().has_parts_uuid() &&
537 message_reader.log_file_header()->parts_uuid()->string_view() !=
538 log_file_header_.message().parts_uuid()->string_view()) {
539 LOG(FATAL) << "Parts UUIDs don't match between log file chunks "
540 << filenames_[0] << " and " << filenames_[i]
541 << ", this is not supported.";
542 }
543
544 LOG(FATAL) << "Header is different between log file chunks "
545 << filenames_[0] << " and " << filenames_[i]
546 << ", this is not supported.";
547 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700548 }
Austin Schuh64fab802020-09-09 22:47:47 -0700549 // Put the parts index back to the first log file chunk.
550 log_file_header_.mutable_message()->mutate_parts_index(
551 message_reader_->log_file_header()->parts_index());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700552
Austin Schuh6f3babe2020-01-26 20:34:50 -0800553 // Setup per channel state.
Austin Schuh05b70472020-01-01 17:11:17 -0800554 channels_.resize(configuration()->channels()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800555 for (ChannelData &channel_data : channels_) {
556 channel_data.data.split_reader = this;
557 // Build up the timestamp list.
558 if (configuration::MultiNode(configuration())) {
559 channel_data.timestamps.resize(configuration()->nodes()->size());
560 for (MessageHeaderQueue &queue : channel_data.timestamps) {
561 queue.timestamps = true;
562 queue.split_reader = this;
563 }
564 }
565 }
Austin Schuh05b70472020-01-01 17:11:17 -0800566
Austin Schuh6f3babe2020-01-26 20:34:50 -0800567 // Build up channels_to_write_ as an optimization to make it fast to figure
568 // out which datastructure to place any new data from a channel on.
569 for (const Channel *channel : *configuration()->channels()) {
570 // This is the main case. We will only see data on this node.
571 if (configuration::ChannelIsSendableOnNode(channel, node())) {
572 channels_to_write_.emplace_back(
573 &channels_[channels_to_write_.size()].data);
574 } else
575 // If we can't send, but can receive, we should be able to see
576 // timestamps here.
577 if (configuration::ChannelIsReadableOnNode(channel, node())) {
578 channels_to_write_.emplace_back(
579 &(channels_[channels_to_write_.size()]
580 .timestamps[configuration::GetNodeIndex(configuration(),
581 node())]));
582 } else {
583 channels_to_write_.emplace_back(nullptr);
584 }
585 }
Austin Schuh05b70472020-01-01 17:11:17 -0800586}
587
Austin Schuh6f3babe2020-01-26 20:34:50 -0800588bool SplitMessageReader::NextLogFile() {
Austin Schuhfa895892020-01-07 20:07:41 -0800589 if (next_filename_index_ == filenames_.size()) {
590 return false;
591 }
592 message_reader_ =
593 std::make_unique<MessageReader>(filenames_[next_filename_index_]);
594
595 // We can't support the config diverging between two log file headers. See if
596 // they are the same.
597 if (next_filename_index_ != 0) {
Austin Schuh64fab802020-09-09 22:47:47 -0700598 // In order for the headers to identically compare, they need to have the
599 // same parts_index. Rewrite the saved header with the new parts_index,
600 // compare, and then restore.
601 const int32_t original_parts_index =
602 log_file_header_.message().parts_index();
603 log_file_header_.mutable_message()->mutate_parts_index(
604 message_reader_->log_file_header()->parts_index());
605
Austin Schuh97789fc2020-08-01 14:42:45 -0700606 CHECK(CompareFlatBuffer(message_reader_->raw_log_file_header(),
607 log_file_header_))
Austin Schuhfa895892020-01-07 20:07:41 -0800608 << ": Header is different between log file chunks "
609 << filenames_[next_filename_index_] << " and "
610 << filenames_[next_filename_index_ - 1] << ", this is not supported.";
Austin Schuh64fab802020-09-09 22:47:47 -0700611
612 log_file_header_.mutable_message()->mutate_parts_index(
613 original_parts_index);
Austin Schuhfa895892020-01-07 20:07:41 -0800614 }
615
616 ++next_filename_index_;
617 return true;
618}
619
Austin Schuh6f3babe2020-01-26 20:34:50 -0800620bool SplitMessageReader::QueueMessages(
Austin Schuhcde938c2020-02-02 17:30:07 -0800621 monotonic_clock::time_point last_dequeued_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800622 // TODO(austin): Once we are happy that everything works, read a 256kb chunk
623 // to reduce the need to re-heap down below.
Austin Schuhcde938c2020-02-02 17:30:07 -0800624
625 // Special case no more data. Otherwise we blow up on the CHECK statement
626 // confirming that we have enough data queued.
627 if (at_end_) {
628 return false;
629 }
630
631 // If this isn't the first time around, confirm that we had enough data queued
632 // to follow the contract.
633 if (time_to_queue_ != monotonic_clock::min_time) {
634 CHECK_LE(last_dequeued_time,
635 newest_timestamp() - max_out_of_order_duration())
636 << " node " << FlatbufferToJson(node()) << " on " << this;
637
638 // Bail if there is enough data already queued.
639 if (last_dequeued_time < time_to_queue_) {
Austin Schuhee711052020-08-24 16:06:09 -0700640 VLOG(1) << MaybeNodeName(target_node_) << "All up to date on " << this
641 << ", dequeued " << last_dequeued_time << " queue time "
642 << time_to_queue_;
Austin Schuhcde938c2020-02-02 17:30:07 -0800643 return true;
644 }
645 } else {
646 // Startup takes a special dance. We want to queue up until the start time,
647 // but we then want to find the next message to read. The conservative
648 // answer is to immediately trigger a second requeue to get things moving.
649 time_to_queue_ = monotonic_start_time();
Austin Schuheeba0292020-10-11 16:20:05 -0700650 CHECK_NE(time_to_queue_, monotonic_clock::min_time);
Austin Schuhcde938c2020-02-02 17:30:07 -0800651 QueueMessages(time_to_queue_);
652 }
653
654 // If we are asked to queue, queue for at least max_out_of_order_duration past
655 // the last known time in the log file (ie the newest timestep read). As long
656 // as we requeue exactly when time_to_queue_ is dequeued and go no further, we
657 // are safe. And since we pop in order, that works.
658 //
659 // Special case the start of the log file. There should be at most 1 message
660 // from each channel at the start of the log file. So always force the start
661 // of the log file to just be read.
662 time_to_queue_ = std::max(time_to_queue_, newest_timestamp());
Austin Schuhee711052020-08-24 16:06:09 -0700663 VLOG(1) << MaybeNodeName(target_node_) << "Queueing, going until "
664 << time_to_queue_ << " " << filename();
Austin Schuhcde938c2020-02-02 17:30:07 -0800665
666 bool was_emplaced = false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800667 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800668 // Stop if we have enough.
Brian Silverman98360e22020-04-28 16:51:20 -0700669 if (newest_timestamp() > time_to_queue_ + max_out_of_order_duration() &&
Austin Schuhcde938c2020-02-02 17:30:07 -0800670 was_emplaced) {
Austin Schuhee711052020-08-24 16:06:09 -0700671 VLOG(1) << MaybeNodeName(target_node_) << "Done queueing on " << this
672 << ", queued to " << newest_timestamp() << " with requeue time "
673 << time_to_queue_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800674 return true;
675 }
Austin Schuh05b70472020-01-01 17:11:17 -0800676
Austin Schuh6f3babe2020-01-26 20:34:50 -0800677 if (std::optional<FlatbufferVector<MessageHeader>> msg =
678 message_reader_->ReadMessage()) {
679 const MessageHeader &header = msg.value().message();
680
Austin Schuhcde938c2020-02-02 17:30:07 -0800681 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
682 chrono::nanoseconds(header.monotonic_sent_time()));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800683
Austin Schuh0b5fd032020-03-28 17:36:49 -0700684 if (VLOG_IS_ON(2)) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700685 LOG(INFO) << MaybeNodeName(target_node_) << "Queued " << this << " "
686 << filename() << " ttq: " << time_to_queue_ << " now "
Austin Schuhee711052020-08-24 16:06:09 -0700687 << newest_timestamp() << " start time "
688 << monotonic_start_time() << " " << FlatbufferToJson(&header);
Austin Schuh0b5fd032020-03-28 17:36:49 -0700689 } else if (VLOG_IS_ON(1)) {
690 FlatbufferVector<MessageHeader> copy = msg.value();
691 copy.mutable_message()->clear_data();
Austin Schuhee711052020-08-24 16:06:09 -0700692 LOG(INFO) << MaybeNodeName(target_node_) << "Queued " << this << " "
693 << filename() << " ttq: " << time_to_queue_ << " now "
694 << newest_timestamp() << " start time "
695 << monotonic_start_time() << " " << FlatbufferToJson(copy);
Austin Schuh0b5fd032020-03-28 17:36:49 -0700696 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800697
698 const int channel_index = header.channel_index();
699 was_emplaced = channels_to_write_[channel_index]->emplace_back(
700 std::move(msg.value()));
701 if (was_emplaced) {
702 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
703 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800704 } else {
705 if (!NextLogFile()) {
Austin Schuhee711052020-08-24 16:06:09 -0700706 VLOG(1) << MaybeNodeName(target_node_) << "No more files, last was "
707 << filenames_.back();
Austin Schuhcde938c2020-02-02 17:30:07 -0800708 at_end_ = true;
Austin Schuh8bd96322020-02-13 21:18:22 -0800709 for (MessageHeaderQueue *queue : channels_to_write_) {
710 if (queue == nullptr || queue->timestamp_merger == nullptr) {
711 continue;
712 }
713 queue->timestamp_merger->NoticeAtEnd();
714 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800715 return false;
716 }
717 }
Austin Schuh05b70472020-01-01 17:11:17 -0800718 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800719}
720
721void SplitMessageReader::SetTimestampMerger(TimestampMerger *timestamp_merger,
722 int channel_index,
723 const Node *target_node) {
724 const Node *reinterpreted_target_node =
725 configuration::GetNodeOrDie(configuration(), target_node);
Austin Schuhee711052020-08-24 16:06:09 -0700726 target_node_ = reinterpreted_target_node;
727
Austin Schuh6f3babe2020-01-26 20:34:50 -0800728 const Channel *const channel =
729 configuration()->channels()->Get(channel_index);
730
Austin Schuhcde938c2020-02-02 17:30:07 -0800731 VLOG(1) << " Configuring merger " << this << " for channel " << channel_index
732 << " "
733 << configuration::CleanedChannelToString(
734 configuration()->channels()->Get(channel_index));
735
Austin Schuh6f3babe2020-01-26 20:34:50 -0800736 MessageHeaderQueue *message_header_queue = nullptr;
737
738 // Figure out if this log file is from our point of view, or the other node's
739 // point of view.
740 if (node() == reinterpreted_target_node) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800741 VLOG(1) << " Replaying as logged node " << filename();
742
743 if (configuration::ChannelIsSendableOnNode(channel, node())) {
744 VLOG(1) << " Data on node";
745 message_header_queue = &(channels_[channel_index].data);
746 } else if (configuration::ChannelIsReadableOnNode(channel, node())) {
747 VLOG(1) << " Timestamps on node";
748 message_header_queue =
749 &(channels_[channel_index].timestamps[configuration::GetNodeIndex(
750 configuration(), node())]);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800751 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800752 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800753 }
754 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800755 VLOG(1) << " Replaying as other node " << filename();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800756 // We are replaying from another node's point of view. The only interesting
Austin Schuhcde938c2020-02-02 17:30:07 -0800757 // data is data that is sent from our node and received on theirs.
758 if (configuration::ChannelIsReadableOnNode(channel,
759 reinterpreted_target_node) &&
760 configuration::ChannelIsSendableOnNode(channel, node())) {
761 VLOG(1) << " Readable on target node";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800762 // Data from another node.
763 message_header_queue = &(channels_[channel_index].data);
764 } else {
Austin Schuhcde938c2020-02-02 17:30:07 -0800765 VLOG(1) << " Dropping";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800766 // This is either not sendable on the other node, or is a timestamp and
767 // therefore not interesting.
768 }
769 }
770
771 // If we found one, write it down. This will be nullptr when there is nothing
772 // relevant on this channel on this node for the target node. In that case,
773 // we want to drop the message instead of queueing it.
774 if (message_header_queue != nullptr) {
775 message_header_queue->timestamp_merger = timestamp_merger;
776 }
777}
778
779std::tuple<monotonic_clock::time_point, uint32_t,
780 FlatbufferVector<MessageHeader>>
781SplitMessageReader::PopOldest(int channel_index) {
782 CHECK_GT(channels_[channel_index].data.size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800783 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
784 timestamp = channels_[channel_index].data.front_timestamp();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800785 FlatbufferVector<MessageHeader> front =
786 std::move(channels_[channel_index].data.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700787 channels_[channel_index].data.PopFront();
Austin Schuhcde938c2020-02-02 17:30:07 -0800788
Austin Schuh2f8fd752020-09-01 22:38:28 -0700789 VLOG(1) << MaybeNodeName(target_node_) << "Popped Data " << this << " "
790 << std::get<0>(timestamp) << " for "
791 << configuration::StrippedChannelToString(
792 configuration()->channels()->Get(channel_index))
793 << " (" << channel_index << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -0800794
795 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800796
797 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
798 std::move(front));
799}
800
801std::tuple<monotonic_clock::time_point, uint32_t,
802 FlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -0700803SplitMessageReader::PopOldestTimestamp(int channel, int node_index) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800804 CHECK_GT(channels_[channel].timestamps[node_index].size(), 0u);
Austin Schuhcde938c2020-02-02 17:30:07 -0800805 const std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
806 timestamp = channels_[channel].timestamps[node_index].front_timestamp();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800807 FlatbufferVector<MessageHeader> front =
808 std::move(channels_[channel].timestamps[node_index].front());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700809 channels_[channel].timestamps[node_index].PopFront();
Austin Schuhcde938c2020-02-02 17:30:07 -0800810
Austin Schuh2f8fd752020-09-01 22:38:28 -0700811 VLOG(1) << MaybeNodeName(target_node_) << "Popped timestamp " << this << " "
Austin Schuhee711052020-08-24 16:06:09 -0700812 << std::get<0>(timestamp) << " for "
813 << configuration::StrippedChannelToString(
814 configuration()->channels()->Get(channel))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700815 << " on "
816 << configuration()->nodes()->Get(node_index)->name()->string_view()
817 << " (" << node_index << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -0800818
819 QueueMessages(std::get<0>(timestamp));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800820
821 return std::make_tuple(std::get<0>(timestamp), std::get<1>(timestamp),
822 std::move(front));
823}
824
Austin Schuhcde938c2020-02-02 17:30:07 -0800825bool SplitMessageReader::MessageHeaderQueue::emplace_back(
Austin Schuh6f3babe2020-01-26 20:34:50 -0800826 FlatbufferVector<MessageHeader> &&msg) {
827 CHECK(split_reader != nullptr);
828
829 // If there is no timestamp merger for this queue, nobody is listening. Drop
830 // the message. This happens when a log file from another node is replayed,
831 // and the timestamp mergers down stream just don't care.
832 if (timestamp_merger == nullptr) {
Austin Schuhcde938c2020-02-02 17:30:07 -0800833 return false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800834 }
835
836 CHECK(timestamps != msg.message().has_data())
837 << ": Got timestamps and data mixed up on a node. "
838 << FlatbufferToJson(msg);
839
840 data_.emplace_back(std::move(msg));
841
842 if (data_.size() == 1u) {
843 // Yup, new data. Notify.
844 if (timestamps) {
845 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
846 } else {
847 timestamp_merger->Update(split_reader, front_timestamp());
848 }
849 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800850
851 return true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800852}
853
Austin Schuh2f8fd752020-09-01 22:38:28 -0700854void SplitMessageReader::MessageHeaderQueue::PopFront() {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800855 data_.pop_front();
856 if (data_.size() != 0u) {
857 // Yup, new data.
858 if (timestamps) {
859 timestamp_merger->UpdateTimestamp(split_reader, front_timestamp());
860 } else {
861 timestamp_merger->Update(split_reader, front_timestamp());
862 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700863 } else {
864 // Poke anyways to update the heap.
865 if (timestamps) {
866 timestamp_merger->UpdateTimestamp(
867 nullptr, std::make_tuple(monotonic_clock::min_time, 0, nullptr));
868 } else {
869 timestamp_merger->Update(
870 nullptr, std::make_tuple(monotonic_clock::min_time, 0, nullptr));
871 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800872 }
Austin Schuh05b70472020-01-01 17:11:17 -0800873}
874
875namespace {
876
Austin Schuh6f3babe2020-01-26 20:34:50 -0800877bool SplitMessageReaderHeapCompare(
878 const std::tuple<monotonic_clock::time_point, uint32_t,
879 SplitMessageReader *>
880 first,
881 const std::tuple<monotonic_clock::time_point, uint32_t,
882 SplitMessageReader *>
883 second) {
884 if (std::get<0>(first) > std::get<0>(second)) {
885 return true;
886 } else if (std::get<0>(first) == std::get<0>(second)) {
887 if (std::get<1>(first) > std::get<1>(second)) {
888 return true;
889 } else if (std::get<1>(first) == std::get<1>(second)) {
890 return std::get<2>(first) > std::get<2>(second);
891 } else {
892 return false;
893 }
894 } else {
895 return false;
896 }
897}
898
Austin Schuh05b70472020-01-01 17:11:17 -0800899bool ChannelHeapCompare(
900 const std::pair<monotonic_clock::time_point, int> first,
901 const std::pair<monotonic_clock::time_point, int> second) {
902 if (first.first > second.first) {
903 return true;
904 } else if (first.first == second.first) {
905 return first.second > second.second;
906 } else {
907 return false;
908 }
909}
910
911} // namespace
912
Austin Schuh6f3babe2020-01-26 20:34:50 -0800913TimestampMerger::TimestampMerger(
914 const Configuration *configuration,
915 std::vector<SplitMessageReader *> split_message_readers, int channel_index,
916 const Node *target_node, ChannelMerger *channel_merger)
917 : configuration_(configuration),
918 split_message_readers_(std::move(split_message_readers)),
919 channel_index_(channel_index),
920 node_index_(configuration::MultiNode(configuration)
921 ? configuration::GetNodeIndex(configuration, target_node)
922 : -1),
923 channel_merger_(channel_merger) {
924 // Tell the readers we care so they know who to notify.
Austin Schuhcde938c2020-02-02 17:30:07 -0800925 VLOG(1) << "Configuring channel " << channel_index << " target node "
926 << FlatbufferToJson(target_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800927 for (SplitMessageReader *reader : split_message_readers_) {
928 reader->SetTimestampMerger(this, channel_index, target_node);
929 }
930
931 // And then determine if we need to track timestamps.
932 const Channel *channel = configuration->channels()->Get(channel_index);
933 if (!configuration::ChannelIsSendableOnNode(channel, target_node) &&
934 configuration::ChannelIsReadableOnNode(channel, target_node)) {
935 has_timestamps_ = true;
936 }
937}
938
939void TimestampMerger::PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800940 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
941 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800942 SplitMessageReader *split_message_reader) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700943 if (split_message_reader != nullptr) {
944 DCHECK(std::find_if(message_heap_.begin(), message_heap_.end(),
945 [split_message_reader](
946 const std::tuple<monotonic_clock::time_point,
947 uint32_t, SplitMessageReader *>
948 x) {
949 return std::get<2>(x) == split_message_reader;
950 }) == message_heap_.end())
951 << ": Pushing message when it is already in the heap.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800952
Austin Schuh2f8fd752020-09-01 22:38:28 -0700953 message_heap_.push_back(std::make_tuple(
954 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
Austin Schuh6f3babe2020-01-26 20:34:50 -0800955
Austin Schuh2f8fd752020-09-01 22:38:28 -0700956 std::push_heap(message_heap_.begin(), message_heap_.end(),
957 &SplitMessageReaderHeapCompare);
958 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800959
960 // If we are just a data merger, don't wait for timestamps.
961 if (!has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700962 if (!message_heap_.empty()) {
963 channel_merger_->Update(std::get<0>(message_heap_[0]), channel_index_);
964 pushed_ = true;
965 } else {
966 // Remove ourselves if we are empty.
967 channel_merger_->Update(monotonic_clock::min_time, channel_index_);
968 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800969 }
970}
971
Austin Schuhcde938c2020-02-02 17:30:07 -0800972std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
973TimestampMerger::oldest_message() const {
974 CHECK_GT(message_heap_.size(), 0u);
975 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
976 oldest_message_reader = message_heap_.front();
977 return std::get<2>(oldest_message_reader)->oldest_message(channel_index_);
978}
979
980std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
981TimestampMerger::oldest_timestamp() const {
982 CHECK_GT(timestamp_heap_.size(), 0u);
983 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
984 oldest_message_reader = timestamp_heap_.front();
985 return std::get<2>(oldest_message_reader)
986 ->oldest_message(channel_index_, node_index_);
987}
988
Austin Schuh6f3babe2020-01-26 20:34:50 -0800989void TimestampMerger::PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800990 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
991 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800992 SplitMessageReader *split_message_reader) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700993 if (split_message_reader != nullptr) {
994 DCHECK(std::find_if(timestamp_heap_.begin(), timestamp_heap_.end(),
995 [split_message_reader](
996 const std::tuple<monotonic_clock::time_point,
997 uint32_t, SplitMessageReader *>
998 x) {
999 return std::get<2>(x) == split_message_reader;
1000 }) == timestamp_heap_.end())
1001 << ": Pushing timestamp when it is already in the heap.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001002
Austin Schuh2f8fd752020-09-01 22:38:28 -07001003 timestamp_heap_.push_back(std::make_tuple(
1004 std::get<0>(timestamp), std::get<1>(timestamp), split_message_reader));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001005
Austin Schuh2f8fd752020-09-01 22:38:28 -07001006 std::push_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1007 SplitMessageReaderHeapCompare);
1008 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001009
1010 // If we are a timestamp merger, don't wait for data. Missing data will be
1011 // caught at read time.
1012 if (has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001013 if (!timestamp_heap_.empty()) {
1014 channel_merger_->Update(std::get<0>(timestamp_heap_[0]), channel_index_);
1015 pushed_ = true;
1016 } else {
1017 // Remove ourselves if we are empty.
1018 channel_merger_->Update(monotonic_clock::min_time, channel_index_);
1019 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001020 }
1021}
1022
1023std::tuple<monotonic_clock::time_point, uint32_t,
1024 FlatbufferVector<MessageHeader>>
1025TimestampMerger::PopMessageHeap() {
1026 // Pop the oldest message reader pointer off the heap.
1027 CHECK_GT(message_heap_.size(), 0u);
1028 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1029 oldest_message_reader = message_heap_.front();
1030
1031 std::pop_heap(message_heap_.begin(), message_heap_.end(),
1032 &SplitMessageReaderHeapCompare);
1033 message_heap_.pop_back();
1034
1035 // Pop the oldest message. This re-pushes any messages from the reader to the
1036 // message heap.
1037 std::tuple<monotonic_clock::time_point, uint32_t,
1038 FlatbufferVector<MessageHeader>>
1039 oldest_message =
1040 std::get<2>(oldest_message_reader)->PopOldest(channel_index_);
1041
1042 // Confirm that the time and queue_index we have recorded matches.
1043 CHECK_EQ(std::get<0>(oldest_message), std::get<0>(oldest_message_reader));
1044 CHECK_EQ(std::get<1>(oldest_message), std::get<1>(oldest_message_reader));
1045
1046 // Now, keep reading until we have found all duplicates.
Brian Silverman8a32ce62020-08-12 12:02:38 -07001047 while (!message_heap_.empty()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001048 // See if it is a duplicate.
1049 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1050 next_oldest_message_reader = message_heap_.front();
1051
Austin Schuhcde938c2020-02-02 17:30:07 -08001052 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1053 next_oldest_message_time = std::get<2>(next_oldest_message_reader)
1054 ->oldest_message(channel_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001055
1056 if (std::get<0>(next_oldest_message_time) == std::get<0>(oldest_message) &&
1057 std::get<1>(next_oldest_message_time) == std::get<1>(oldest_message)) {
1058 // Pop the message reader pointer.
1059 std::pop_heap(message_heap_.begin(), message_heap_.end(),
1060 &SplitMessageReaderHeapCompare);
1061 message_heap_.pop_back();
1062
1063 // Pop the next oldest message. This re-pushes any messages from the
1064 // reader.
1065 std::tuple<monotonic_clock::time_point, uint32_t,
1066 FlatbufferVector<MessageHeader>>
1067 next_oldest_message = std::get<2>(next_oldest_message_reader)
1068 ->PopOldest(channel_index_);
1069
1070 // And make sure the message matches in it's entirety.
1071 CHECK(std::get<2>(oldest_message).span() ==
1072 std::get<2>(next_oldest_message).span())
1073 << ": Data at the same timestamp doesn't match.";
1074 } else {
1075 break;
1076 }
1077 }
1078
1079 return oldest_message;
1080}
1081
1082std::tuple<monotonic_clock::time_point, uint32_t,
1083 FlatbufferVector<MessageHeader>>
1084TimestampMerger::PopTimestampHeap() {
1085 // Pop the oldest message reader pointer off the heap.
1086 CHECK_GT(timestamp_heap_.size(), 0u);
1087
1088 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1089 oldest_timestamp_reader = timestamp_heap_.front();
1090
1091 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1092 &SplitMessageReaderHeapCompare);
1093 timestamp_heap_.pop_back();
1094
1095 CHECK(node_index_ != -1) << ": Timestamps in a single node environment";
1096
1097 // Pop the oldest message. This re-pushes any timestamps from the reader to
1098 // the timestamp heap.
1099 std::tuple<monotonic_clock::time_point, uint32_t,
1100 FlatbufferVector<MessageHeader>>
1101 oldest_timestamp = std::get<2>(oldest_timestamp_reader)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001102 ->PopOldestTimestamp(channel_index_, node_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001103
1104 // Confirm that the time we have recorded matches.
1105 CHECK_EQ(std::get<0>(oldest_timestamp), std::get<0>(oldest_timestamp_reader));
1106 CHECK_EQ(std::get<1>(oldest_timestamp), std::get<1>(oldest_timestamp_reader));
1107
Austin Schuh2f8fd752020-09-01 22:38:28 -07001108 // Now, keep reading until we have found all duplicates.
1109 while (!timestamp_heap_.empty()) {
1110 // See if it is a duplicate.
1111 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1112 next_oldest_timestamp_reader = timestamp_heap_.front();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001113
Austin Schuh2f8fd752020-09-01 22:38:28 -07001114 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1115 next_oldest_timestamp_time =
1116 std::get<2>(next_oldest_timestamp_reader)
1117 ->oldest_message(channel_index_, node_index_);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001118
Austin Schuh2f8fd752020-09-01 22:38:28 -07001119 if (std::get<0>(next_oldest_timestamp_time) ==
1120 std::get<0>(oldest_timestamp) &&
1121 std::get<1>(next_oldest_timestamp_time) ==
1122 std::get<1>(oldest_timestamp)) {
1123 // Pop the timestamp reader pointer.
1124 std::pop_heap(timestamp_heap_.begin(), timestamp_heap_.end(),
1125 &SplitMessageReaderHeapCompare);
1126 timestamp_heap_.pop_back();
1127
1128 // Pop the next oldest timestamp. This re-pushes any messages from the
1129 // reader.
1130 std::tuple<monotonic_clock::time_point, uint32_t,
1131 FlatbufferVector<MessageHeader>>
1132 next_oldest_timestamp =
1133 std::get<2>(next_oldest_timestamp_reader)
1134 ->PopOldestTimestamp(channel_index_, node_index_);
1135
1136 // And make sure the contents matches in it's entirety.
1137 CHECK(std::get<2>(oldest_timestamp).span() ==
1138 std::get<2>(next_oldest_timestamp).span())
1139 << ": Data at the same timestamp doesn't match, "
1140 << aos::FlatbufferToJson(std::get<2>(oldest_timestamp)) << " vs "
1141 << aos::FlatbufferToJson(std::get<2>(next_oldest_timestamp)) << " "
1142 << absl::BytesToHexString(std::string_view(
1143 reinterpret_cast<const char *>(
1144 std::get<2>(oldest_timestamp).span().data()),
1145 std::get<2>(oldest_timestamp).span().size()))
1146 << " vs "
1147 << absl::BytesToHexString(std::string_view(
1148 reinterpret_cast<const char *>(
1149 std::get<2>(next_oldest_timestamp).span().data()),
1150 std::get<2>(next_oldest_timestamp).span().size()));
1151
1152 } else {
1153 break;
1154 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001155 }
1156
Austin Schuh2f8fd752020-09-01 22:38:28 -07001157 return oldest_timestamp;
Austin Schuh8bd96322020-02-13 21:18:22 -08001158}
1159
Austin Schuh6f3babe2020-01-26 20:34:50 -08001160std::tuple<TimestampMerger::DeliveryTimestamp, FlatbufferVector<MessageHeader>>
1161TimestampMerger::PopOldest() {
1162 if (has_timestamps_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001163 VLOG(1) << "Looking for matching timestamp for "
1164 << configuration::StrippedChannelToString(
1165 configuration_->channels()->Get(channel_index_))
1166 << " (" << channel_index_ << ") "
1167 << " at " << std::get<0>(oldest_timestamp());
1168
Austin Schuh8bd96322020-02-13 21:18:22 -08001169 // Read the timestamps.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001170 std::tuple<monotonic_clock::time_point, uint32_t,
1171 FlatbufferVector<MessageHeader>>
1172 oldest_timestamp = PopTimestampHeap();
1173
1174 TimestampMerger::DeliveryTimestamp timestamp;
1175 timestamp.monotonic_event_time =
1176 monotonic_clock::time_point(chrono::nanoseconds(
1177 std::get<2>(oldest_timestamp).message().monotonic_sent_time()));
1178 timestamp.realtime_event_time =
1179 realtime_clock::time_point(chrono::nanoseconds(
1180 std::get<2>(oldest_timestamp).message().realtime_sent_time()));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001181 timestamp.queue_index =
1182 std::get<2>(oldest_timestamp).message().queue_index();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001183
1184 // Consistency check.
1185 CHECK_EQ(timestamp.monotonic_event_time, std::get<0>(oldest_timestamp));
1186 CHECK_EQ(std::get<2>(oldest_timestamp).message().queue_index(),
1187 std::get<1>(oldest_timestamp));
1188
1189 monotonic_clock::time_point remote_timestamp_monotonic_time(
1190 chrono::nanoseconds(
1191 std::get<2>(oldest_timestamp).message().monotonic_remote_time()));
1192
Austin Schuh8bd96322020-02-13 21:18:22 -08001193 // See if we have any data. If not, pass the problem up the chain.
Brian Silverman8a32ce62020-08-12 12:02:38 -07001194 if (message_heap_.empty()) {
Austin Schuhee711052020-08-24 16:06:09 -07001195 LOG(WARNING) << MaybeNodeName(configuration_->nodes()->Get(node_index_))
1196 << "No data to match timestamp on "
1197 << configuration::CleanedChannelToString(
1198 configuration_->channels()->Get(channel_index_))
1199 << " (" << channel_index_ << ")";
Austin Schuh8bd96322020-02-13 21:18:22 -08001200 return std::make_tuple(timestamp,
1201 std::move(std::get<2>(oldest_timestamp)));
1202 }
1203
Austin Schuh6f3babe2020-01-26 20:34:50 -08001204 while (true) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001205 {
1206 // Ok, now try grabbing data until we find one which matches.
1207 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
1208 oldest_message_ref = oldest_message();
1209
1210 // Time at which the message was sent (this message is written from the
1211 // sending node's perspective.
1212 monotonic_clock::time_point remote_monotonic_time(chrono::nanoseconds(
1213 std::get<2>(oldest_message_ref)->monotonic_sent_time()));
1214
1215 if (remote_monotonic_time < remote_timestamp_monotonic_time) {
Austin Schuhee711052020-08-24 16:06:09 -07001216 LOG(WARNING) << configuration_->nodes()
1217 ->Get(node_index_)
1218 ->name()
1219 ->string_view()
1220 << " Undelivered message, skipping. Remote time is "
1221 << remote_monotonic_time << " timestamp is "
1222 << remote_timestamp_monotonic_time << " on channel "
1223 << configuration::StrippedChannelToString(
1224 configuration_->channels()->Get(channel_index_))
1225 << " (" << channel_index_ << ")";
Austin Schuhcde938c2020-02-02 17:30:07 -08001226 PopMessageHeap();
1227 continue;
1228 } else if (remote_monotonic_time > remote_timestamp_monotonic_time) {
Austin Schuhee711052020-08-24 16:06:09 -07001229 LOG(WARNING) << configuration_->nodes()
1230 ->Get(node_index_)
1231 ->name()
1232 ->string_view()
1233 << " Data not found. Remote time should be "
1234 << remote_timestamp_monotonic_time
1235 << ", message time is " << remote_monotonic_time
1236 << " on channel "
1237 << configuration::StrippedChannelToString(
1238 configuration_->channels()->Get(channel_index_))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001239 << " (" << channel_index_ << ")"
1240 << (VLOG_IS_ON(1) ? DebugString() : "");
Austin Schuhcde938c2020-02-02 17:30:07 -08001241 return std::make_tuple(timestamp,
1242 std::move(std::get<2>(oldest_timestamp)));
1243 }
1244
1245 timestamp.monotonic_remote_time = remote_monotonic_time;
1246 }
1247
Austin Schuh2f8fd752020-09-01 22:38:28 -07001248 VLOG(1) << "Found matching data "
1249 << configuration::StrippedChannelToString(
1250 configuration_->channels()->Get(channel_index_))
1251 << " (" << channel_index_ << ")";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001252 std::tuple<monotonic_clock::time_point, uint32_t,
1253 FlatbufferVector<MessageHeader>>
1254 oldest_message = PopMessageHeap();
1255
Austin Schuh6f3babe2020-01-26 20:34:50 -08001256 timestamp.realtime_remote_time =
1257 realtime_clock::time_point(chrono::nanoseconds(
1258 std::get<2>(oldest_message).message().realtime_sent_time()));
1259 timestamp.remote_queue_index =
1260 std::get<2>(oldest_message).message().queue_index();
1261
Austin Schuhcde938c2020-02-02 17:30:07 -08001262 CHECK_EQ(timestamp.monotonic_remote_time,
1263 remote_timestamp_monotonic_time);
1264
1265 CHECK_EQ(timestamp.remote_queue_index,
1266 std::get<2>(oldest_timestamp).message().remote_queue_index())
1267 << ": " << FlatbufferToJson(&std::get<2>(oldest_timestamp).message())
1268 << " data "
1269 << FlatbufferToJson(&std::get<2>(oldest_message).message());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001270
Austin Schuh30dd5c52020-08-01 14:43:44 -07001271 return std::make_tuple(timestamp, std::move(std::get<2>(oldest_message)));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001272 }
1273 } else {
1274 std::tuple<monotonic_clock::time_point, uint32_t,
1275 FlatbufferVector<MessageHeader>>
1276 oldest_message = PopMessageHeap();
1277
1278 TimestampMerger::DeliveryTimestamp timestamp;
1279 timestamp.monotonic_event_time =
1280 monotonic_clock::time_point(chrono::nanoseconds(
1281 std::get<2>(oldest_message).message().monotonic_sent_time()));
1282 timestamp.realtime_event_time =
1283 realtime_clock::time_point(chrono::nanoseconds(
1284 std::get<2>(oldest_message).message().realtime_sent_time()));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001285 timestamp.queue_index = std::get<2>(oldest_message).message().queue_index();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001286 timestamp.remote_queue_index = 0xffffffff;
1287
1288 CHECK_EQ(std::get<0>(oldest_message), timestamp.monotonic_event_time);
1289 CHECK_EQ(std::get<1>(oldest_message),
1290 std::get<2>(oldest_message).message().queue_index());
1291
Austin Schuh30dd5c52020-08-01 14:43:44 -07001292 return std::make_tuple(timestamp, std::move(std::get<2>(oldest_message)));
Austin Schuh6f3babe2020-01-26 20:34:50 -08001293 }
1294}
1295
Austin Schuh8bd96322020-02-13 21:18:22 -08001296void TimestampMerger::NoticeAtEnd() { channel_merger_->NoticeAtEnd(); }
1297
Austin Schuh6f3babe2020-01-26 20:34:50 -08001298namespace {
1299std::vector<std::unique_ptr<SplitMessageReader>> MakeSplitMessageReaders(
1300 const std::vector<std::vector<std::string>> &filenames) {
1301 CHECK_GT(filenames.size(), 0u);
1302 // Build up all the SplitMessageReaders.
1303 std::vector<std::unique_ptr<SplitMessageReader>> result;
1304 for (const std::vector<std::string> &filenames : filenames) {
1305 result.emplace_back(std::make_unique<SplitMessageReader>(filenames));
1306 }
1307 return result;
1308}
1309} // namespace
1310
1311ChannelMerger::ChannelMerger(
1312 const std::vector<std::vector<std::string>> &filenames)
1313 : split_message_readers_(MakeSplitMessageReaders(filenames)),
Austin Schuh97789fc2020-08-01 14:42:45 -07001314 log_file_header_(split_message_readers_[0]->raw_log_file_header()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001315 // Now, confirm that the configuration matches for each and pick a start time.
1316 // Also return the list of possible nodes.
1317 for (const std::unique_ptr<SplitMessageReader> &reader :
1318 split_message_readers_) {
1319 CHECK(CompareFlatBuffer(log_file_header_.message().configuration(),
1320 reader->log_file_header()->configuration()))
1321 << ": Replaying log files with different configurations isn't "
1322 "supported";
1323 }
1324
1325 nodes_ = configuration::GetNodes(configuration());
1326}
1327
1328bool ChannelMerger::SetNode(const Node *target_node) {
1329 std::vector<SplitMessageReader *> split_message_readers;
1330 for (const std::unique_ptr<SplitMessageReader> &reader :
1331 split_message_readers_) {
1332 split_message_readers.emplace_back(reader.get());
1333 }
1334
1335 // Go find a log_file_header for this node.
1336 {
1337 bool found_node = false;
1338
1339 for (const std::unique_ptr<SplitMessageReader> &reader :
1340 split_message_readers_) {
James Kuszmaulfc273dc2020-05-09 17:56:19 -07001341 // In order to identify which logfile(s) map to the target node, do a
1342 // logical comparison of the nodes, by confirming that we are either in a
1343 // single-node setup (where the nodes will both be nullptr) or that the
1344 // node names match (but the other node fields--e.g., hostname lists--may
1345 // not).
1346 const bool both_null =
1347 reader->node() == nullptr && target_node == nullptr;
1348 const bool both_have_name =
1349 (reader->node() != nullptr) && (target_node != nullptr) &&
1350 (reader->node()->has_name() && target_node->has_name());
1351 const bool node_names_identical =
Brian Silvermand90905f2020-09-23 14:42:56 -07001352 both_have_name && (reader->node()->name()->string_view() ==
1353 target_node->name()->string_view());
James Kuszmaulfc273dc2020-05-09 17:56:19 -07001354 if (both_null || node_names_identical) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001355 if (!found_node) {
1356 found_node = true;
1357 log_file_header_ = CopyFlatBuffer(reader->log_file_header());
Austin Schuhcde938c2020-02-02 17:30:07 -08001358 VLOG(1) << "Found log file " << reader->filename() << " with node "
1359 << FlatbufferToJson(reader->node()) << " start_time "
1360 << monotonic_start_time();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001361 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001362 // Find the earliest start time. That way, if we get a full log file
1363 // directly from the node, and a partial later, we start with the
1364 // full. Update our header to match that.
1365 const monotonic_clock::time_point new_monotonic_start_time(
1366 chrono::nanoseconds(
1367 reader->log_file_header()->monotonic_start_time()));
1368 const realtime_clock::time_point new_realtime_start_time(
1369 chrono::nanoseconds(
1370 reader->log_file_header()->realtime_start_time()));
1371
1372 if (monotonic_start_time() == monotonic_clock::min_time ||
1373 (new_monotonic_start_time != monotonic_clock::min_time &&
1374 new_monotonic_start_time < monotonic_start_time())) {
1375 log_file_header_.mutable_message()->mutate_monotonic_start_time(
1376 new_monotonic_start_time.time_since_epoch().count());
1377 log_file_header_.mutable_message()->mutate_realtime_start_time(
1378 new_realtime_start_time.time_since_epoch().count());
1379 VLOG(1) << "Updated log file " << reader->filename()
1380 << " with node " << FlatbufferToJson(reader->node())
1381 << " start_time " << new_monotonic_start_time;
1382 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001383 }
1384 }
1385 }
1386
1387 if (!found_node) {
1388 LOG(WARNING) << "Failed to find log file for node "
1389 << FlatbufferToJson(target_node);
1390 return false;
1391 }
1392 }
1393
1394 // Build up all the timestamp mergers. This connects up all the
1395 // SplitMessageReaders.
1396 timestamp_mergers_.reserve(configuration()->channels()->size());
1397 for (size_t channel_index = 0;
1398 channel_index < configuration()->channels()->size(); ++channel_index) {
1399 timestamp_mergers_.emplace_back(
1400 configuration(), split_message_readers, channel_index,
1401 configuration::GetNode(configuration(), target_node), this);
1402 }
1403
1404 // And prime everything.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001405 for (std::unique_ptr<SplitMessageReader> &split_message_reader :
1406 split_message_readers_) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001407 split_message_reader->QueueMessages(
1408 split_message_reader->monotonic_start_time());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001409 }
1410
1411 node_ = configuration::GetNodeOrDie(configuration(), target_node);
1412 return true;
1413}
1414
Austin Schuh858c9f32020-08-31 16:56:12 -07001415monotonic_clock::time_point ChannelMerger::OldestMessageTime() const {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001416 if (channel_heap_.empty()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001417 return monotonic_clock::max_time;
1418 }
1419 return channel_heap_.front().first;
1420}
1421
1422void ChannelMerger::PushChannelHeap(monotonic_clock::time_point timestamp,
1423 int channel_index) {
1424 // Pop and recreate the heap if it has already been pushed. And since we are
1425 // pushing again, we don't need to clear pushed.
1426 if (timestamp_mergers_[channel_index].pushed()) {
Brian Silverman8a32ce62020-08-12 12:02:38 -07001427 const auto channel_iterator = std::find_if(
Austin Schuh6f3babe2020-01-26 20:34:50 -08001428 channel_heap_.begin(), channel_heap_.end(),
1429 [channel_index](const std::pair<monotonic_clock::time_point, int> x) {
1430 return x.second == channel_index;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001431 });
1432 DCHECK(channel_iterator != channel_heap_.end());
1433 if (std::get<0>(*channel_iterator) == timestamp) {
1434 // It's already in the heap, in the correct spot, so nothing
1435 // more for us to do here.
1436 return;
1437 }
1438 channel_heap_.erase(channel_iterator);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001439 std::make_heap(channel_heap_.begin(), channel_heap_.end(),
1440 ChannelHeapCompare);
1441 }
1442
Austin Schuh2f8fd752020-09-01 22:38:28 -07001443 if (timestamp == monotonic_clock::min_time) {
1444 timestamp_mergers_[channel_index].set_pushed(false);
1445 return;
1446 }
1447
Austin Schuh05b70472020-01-01 17:11:17 -08001448 channel_heap_.push_back(std::make_pair(timestamp, channel_index));
1449
1450 // The default sort puts the newest message first. Use a custom comparator to
1451 // put the oldest message first.
1452 std::push_heap(channel_heap_.begin(), channel_heap_.end(),
1453 ChannelHeapCompare);
1454}
1455
Austin Schuh2f8fd752020-09-01 22:38:28 -07001456void ChannelMerger::VerifyHeaps() {
Austin Schuh661a8d82020-09-13 17:25:56 -07001457 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap =
1458 channel_heap_;
1459 std::make_heap(channel_heap.begin(), channel_heap.end(), &ChannelHeapCompare);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001460
Austin Schuh661a8d82020-09-13 17:25:56 -07001461 for (size_t i = 0; i < channel_heap_.size(); ++i) {
1462 CHECK(channel_heap_[i] == channel_heap[i]) << ": Heaps diverged...";
1463 CHECK_EQ(
1464 std::get<0>(channel_heap[i]),
1465 timestamp_mergers_[std::get<1>(channel_heap[i])].channel_merger_time());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001466 }
1467}
1468
Austin Schuh6f3babe2020-01-26 20:34:50 -08001469std::tuple<TimestampMerger::DeliveryTimestamp, int,
1470 FlatbufferVector<MessageHeader>>
1471ChannelMerger::PopOldest() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001472 CHECK_GT(channel_heap_.size(), 0u);
Austin Schuh05b70472020-01-01 17:11:17 -08001473 std::pair<monotonic_clock::time_point, int> oldest_channel_data =
1474 channel_heap_.front();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001475 int channel_index = oldest_channel_data.second;
Austin Schuh05b70472020-01-01 17:11:17 -08001476 std::pop_heap(channel_heap_.begin(), channel_heap_.end(),
1477 &ChannelHeapCompare);
1478 channel_heap_.pop_back();
Austin Schuh8bd96322020-02-13 21:18:22 -08001479
Austin Schuh6f3babe2020-01-26 20:34:50 -08001480 timestamp_mergers_[channel_index].set_pushed(false);
Austin Schuh05b70472020-01-01 17:11:17 -08001481
Austin Schuh6f3babe2020-01-26 20:34:50 -08001482 TimestampMerger *merger = &timestamp_mergers_[channel_index];
Austin Schuh05b70472020-01-01 17:11:17 -08001483
Austin Schuhcde938c2020-02-02 17:30:07 -08001484 // Merger handles any queueing needed from here.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001485 std::tuple<TimestampMerger::DeliveryTimestamp,
1486 FlatbufferVector<MessageHeader>>
1487 message = merger->PopOldest();
Brian Silverman8a32ce62020-08-12 12:02:38 -07001488 DCHECK_EQ(std::get<0>(message).monotonic_event_time,
1489 oldest_channel_data.first)
1490 << ": channel_heap_ was corrupted for " << channel_index << ": "
1491 << DebugString();
Austin Schuh05b70472020-01-01 17:11:17 -08001492
Austin Schuh2f8fd752020-09-01 22:38:28 -07001493 CHECK_GE(std::get<0>(message).monotonic_event_time, last_popped_time_)
1494 << ": " << MaybeNodeName(log_file_header()->node())
1495 << "Messages came off the queue out of order. " << DebugString();
1496 last_popped_time_ = std::get<0>(message).monotonic_event_time;
1497
1498 VLOG(1) << "Popped " << last_popped_time_ << " "
1499 << configuration::StrippedChannelToString(
1500 configuration()->channels()->Get(channel_index))
1501 << " (" << channel_index << ")";
1502
Austin Schuh6f3babe2020-01-26 20:34:50 -08001503 return std::make_tuple(std::get<0>(message), channel_index,
1504 std::move(std::get<1>(message)));
1505}
1506
Austin Schuhcde938c2020-02-02 17:30:07 -08001507std::string SplitMessageReader::MessageHeaderQueue::DebugString() const {
1508 std::stringstream ss;
1509 for (size_t i = 0; i < data_.size(); ++i) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001510 if (i < 5 || i + 5 > data_.size()) {
1511 if (timestamps) {
1512 ss << " msg: ";
1513 } else {
1514 ss << " timestamp: ";
1515 }
1516 ss << monotonic_clock::time_point(
1517 chrono::nanoseconds(data_[i].message().monotonic_sent_time()))
Austin Schuhcde938c2020-02-02 17:30:07 -08001518 << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001519 << realtime_clock::time_point(
1520 chrono::nanoseconds(data_[i].message().realtime_sent_time()))
1521 << ") " << data_[i].message().queue_index();
1522 if (timestamps) {
1523 ss << " <- remote "
1524 << monotonic_clock::time_point(chrono::nanoseconds(
1525 data_[i].message().monotonic_remote_time()))
1526 << " ("
1527 << realtime_clock::time_point(chrono::nanoseconds(
1528 data_[i].message().realtime_remote_time()))
1529 << ")";
1530 }
1531 ss << "\n";
1532 } else if (i == 5) {
1533 ss << " ...\n";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001534 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001535 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001536
Austin Schuhcde938c2020-02-02 17:30:07 -08001537 return ss.str();
1538}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001539
Austin Schuhcde938c2020-02-02 17:30:07 -08001540std::string SplitMessageReader::DebugString(int channel) const {
1541 std::stringstream ss;
1542 ss << "[\n";
1543 ss << channels_[channel].data.DebugString();
1544 ss << " ]";
1545 return ss.str();
1546}
Austin Schuh6f3babe2020-01-26 20:34:50 -08001547
Austin Schuhcde938c2020-02-02 17:30:07 -08001548std::string SplitMessageReader::DebugString(int channel, int node_index) const {
1549 std::stringstream ss;
1550 ss << "[\n";
1551 ss << channels_[channel].timestamps[node_index].DebugString();
1552 ss << " ]";
1553 return ss.str();
1554}
1555
1556std::string TimestampMerger::DebugString() const {
1557 std::stringstream ss;
1558
1559 if (timestamp_heap_.size() > 0) {
1560 ss << " timestamp_heap {\n";
1561 std::vector<
1562 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1563 timestamp_heap = timestamp_heap_;
1564 while (timestamp_heap.size() > 0u) {
1565 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1566 oldest_timestamp_reader = timestamp_heap.front();
1567
1568 ss << " " << std::get<2>(oldest_timestamp_reader) << " "
1569 << std::get<0>(oldest_timestamp_reader) << " queue_index ("
1570 << std::get<1>(oldest_timestamp_reader) << ") ttq "
1571 << std::get<2>(oldest_timestamp_reader)->time_to_queue() << " "
1572 << std::get<2>(oldest_timestamp_reader)->filename() << " -> "
1573 << std::get<2>(oldest_timestamp_reader)
1574 ->DebugString(channel_index_, node_index_)
1575 << "\n";
1576
1577 std::pop_heap(timestamp_heap.begin(), timestamp_heap.end(),
1578 &SplitMessageReaderHeapCompare);
1579 timestamp_heap.pop_back();
1580 }
1581 ss << " }\n";
1582 }
1583
1584 ss << " message_heap {\n";
1585 {
1586 std::vector<
1587 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
1588 message_heap = message_heap_;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001589 while (!message_heap.empty()) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001590 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>
1591 oldest_message_reader = message_heap.front();
1592
1593 ss << " " << std::get<2>(oldest_message_reader) << " "
1594 << std::get<0>(oldest_message_reader) << " queue_index ("
1595 << std::get<1>(oldest_message_reader) << ") ttq "
1596 << std::get<2>(oldest_message_reader)->time_to_queue() << " "
1597 << std::get<2>(oldest_message_reader)->filename() << " -> "
1598 << std::get<2>(oldest_message_reader)->DebugString(channel_index_)
1599 << "\n";
1600
1601 std::pop_heap(message_heap.begin(), message_heap.end(),
1602 &SplitMessageReaderHeapCompare);
1603 message_heap.pop_back();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001604 }
Austin Schuh05b70472020-01-01 17:11:17 -08001605 }
Austin Schuhcde938c2020-02-02 17:30:07 -08001606 ss << " }";
1607
1608 return ss.str();
1609}
1610
1611std::string ChannelMerger::DebugString() const {
1612 std::stringstream ss;
1613 ss << "start_time " << realtime_start_time() << " " << monotonic_start_time()
1614 << "\n";
1615 ss << "channel_heap {\n";
1616 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap =
1617 channel_heap_;
Brian Silverman8a32ce62020-08-12 12:02:38 -07001618 while (!channel_heap.empty()) {
Austin Schuhcde938c2020-02-02 17:30:07 -08001619 std::tuple<monotonic_clock::time_point, int> channel = channel_heap.front();
1620 ss << " " << std::get<0>(channel) << " (" << std::get<1>(channel) << ") "
1621 << configuration::CleanedChannelToString(
1622 configuration()->channels()->Get(std::get<1>(channel)))
1623 << "\n";
1624
1625 ss << timestamp_mergers_[std::get<1>(channel)].DebugString() << "\n";
1626
1627 std::pop_heap(channel_heap.begin(), channel_heap.end(),
1628 &ChannelHeapCompare);
1629 channel_heap.pop_back();
1630 }
1631 ss << "}";
1632
1633 return ss.str();
Austin Schuh05b70472020-01-01 17:11:17 -08001634}
1635
Austin Schuhee711052020-08-24 16:06:09 -07001636std::string MaybeNodeName(const Node *node) {
1637 if (node != nullptr) {
1638 return node->name()->str() + " ";
1639 }
1640 return "";
1641}
1642
Brian Silvermanf51499a2020-09-21 12:49:08 -07001643} // namespace aos::logger