blob: 01f3002452a03ab528675ae8df16d1fcd39bf188 [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"
James Kuszmauldd0a5042021-10-28 23:38:04 -070013#include "aos/events/logging/snappy_encoder.h"
Austin Schuhfa895892020-01-07 20:07:41 -080014#include "aos/flatbuffer_merge.h"
Austin Schuh6f3babe2020-01-26 20:34:50 -080015#include "aos/util/file.h"
Austin Schuha36c8902019-12-30 18:07:15 -080016#include "flatbuffers/flatbuffers.h"
Austin Schuh05b70472020-01-01 17:11:17 -080017#include "gflags/gflags.h"
18#include "glog/logging.h"
Austin Schuha36c8902019-12-30 18:07:15 -080019
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070020#if defined(__x86_64__)
Tyler Chatow2015bc62021-08-04 21:15:09 -070021#define ENABLE_LZMA (!__has_feature(memory_sanitizer))
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070022#elif defined(__aarch64__)
Tyler Chatow2015bc62021-08-04 21:15:09 -070023#define ENABLE_LZMA (!__has_feature(memory_sanitizer))
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070024#else
25#define ENABLE_LZMA 0
26#endif
27
28#if ENABLE_LZMA
29#include "aos/events/logging/lzma_encoder.h"
30#endif
31
Austin Schuh7fbf5a72020-09-21 16:28:13 -070032DEFINE_int32(flush_size, 128000,
Austin Schuha36c8902019-12-30 18:07:15 -080033 "Number of outstanding bytes to allow before flushing to disk.");
Austin Schuhbd06ae42021-03-31 22:48:21 -070034DEFINE_double(
35 flush_period, 5.0,
36 "Max time to let data sit in the queue before flushing in seconds.");
Austin Schuha36c8902019-12-30 18:07:15 -080037
Austin Schuha040c3f2021-02-13 16:09:07 -080038DEFINE_double(
Austin Schuh6a7358f2021-11-18 22:40:40 -080039 max_network_delay, 1.0,
40 "Max time to assume a message takes to cross the network before we are "
41 "willing to drop it from our buffers and assume it didn't make it. "
42 "Increasing this number can increase memory usage depending on the packet "
43 "loss of your network or if the timestamps aren't logged for a message.");
44
45DEFINE_double(
Austin Schuha040c3f2021-02-13 16:09:07 -080046 max_out_of_order, -1,
47 "If set, this overrides the max out of order duration for a log file.");
48
Austin Schuh0e8db662021-07-06 10:43:47 -070049DEFINE_bool(workaround_double_headers, true,
50 "Some old log files have two headers at the beginning. Use the "
51 "last header as the actual header.");
52
Brian Smarttea913d42021-12-10 15:02:38 -080053DEFINE_bool(crash_on_corrupt_message, true,
54 "When true, MessageReader will crash the first time a message "
55 "with corrupted format is found. When false, the crash will be "
56 "suppressed, and any remaining readable messages will be "
57 "evaluated to present verified vs corrupted stats.");
58
59DEFINE_bool(ignore_corrupt_messages, false,
60 "When true, and crash_on_corrupt_message is false, then any "
61 "corrupt message found by MessageReader be silently ignored, "
62 "providing access to all uncorrupted messages in a logfile.");
63
Brian Silvermanf51499a2020-09-21 12:49:08 -070064namespace aos::logger {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070065namespace {
Austin Schuha36c8902019-12-30 18:07:15 -080066
Austin Schuh05b70472020-01-01 17:11:17 -080067namespace chrono = std::chrono;
68
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070069template <typename T>
70void PrintOptionalOrNull(std::ostream *os, const std::optional<T> &t) {
71 if (t.has_value()) {
72 *os << *t;
73 } else {
74 *os << "null";
75 }
76}
77} // namespace
78
Brian Silvermanf51499a2020-09-21 12:49:08 -070079DetachedBufferWriter::DetachedBufferWriter(
80 std::string_view filename, std::unique_ptr<DetachedBufferEncoder> encoder)
81 : filename_(filename), encoder_(std::move(encoder)) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070082 if (!util::MkdirPIfSpace(filename, 0777)) {
83 ran_out_of_space_ = true;
84 } else {
85 fd_ = open(std::string(filename).c_str(),
86 O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, 0774);
87 if (fd_ == -1 && errno == ENOSPC) {
88 ran_out_of_space_ = true;
89 } else {
Austin Schuh58646e22021-08-23 23:51:46 -070090 PCHECK(fd_ != -1) << ": Failed to open " << this->filename()
91 << " for writing";
92 VLOG(1) << "Opened " << this->filename() << " for writing";
Brian Silvermana9f2ec92020-10-06 18:00:53 -070093 }
94 }
Austin Schuha36c8902019-12-30 18:07:15 -080095}
96
97DetachedBufferWriter::~DetachedBufferWriter() {
Brian Silverman0465fcf2020-09-24 00:29:18 -070098 Close();
99 if (ran_out_of_space_) {
100 CHECK(acknowledge_ran_out_of_space_)
101 << ": Unacknowledged out of disk space, log file was not completed";
Brian Silvermanf51499a2020-09-21 12:49:08 -0700102 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700103}
104
Brian Silvermand90905f2020-09-23 14:42:56 -0700105DetachedBufferWriter::DetachedBufferWriter(DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700106 *this = std::move(other);
107}
108
Brian Silverman87ac0402020-09-17 14:47:01 -0700109// When other is destroyed "soon" (which it should be because we're getting an
110// rvalue reference to it), it will flush etc all the data we have queued up
111// (because that data will then be its data).
Austin Schuh2f8fd752020-09-01 22:38:28 -0700112DetachedBufferWriter &DetachedBufferWriter::operator=(
113 DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700114 std::swap(filename_, other.filename_);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700115 std::swap(encoder_, other.encoder_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700116 std::swap(fd_, other.fd_);
Brian Silverman0465fcf2020-09-24 00:29:18 -0700117 std::swap(ran_out_of_space_, other.ran_out_of_space_);
118 std::swap(acknowledge_ran_out_of_space_, other.acknowledge_ran_out_of_space_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700119 std::swap(iovec_, other.iovec_);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700120 std::swap(max_write_time_, other.max_write_time_);
121 std::swap(max_write_time_bytes_, other.max_write_time_bytes_);
122 std::swap(max_write_time_messages_, other.max_write_time_messages_);
123 std::swap(total_write_time_, other.total_write_time_);
124 std::swap(total_write_count_, other.total_write_count_);
125 std::swap(total_write_messages_, other.total_write_messages_);
126 std::swap(total_write_bytes_, other.total_write_bytes_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700127 return *this;
Austin Schuha36c8902019-12-30 18:07:15 -0800128}
129
Brian Silvermanf51499a2020-09-21 12:49:08 -0700130void DetachedBufferWriter::QueueSpan(absl::Span<const uint8_t> span) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -0700131 if (ran_out_of_space_) {
132 // We don't want any later data to be written after space becomes
133 // available, so refuse to write anything more once we've dropped data
134 // because we ran out of space.
135 VLOG(1) << "Ignoring span: " << span.size();
136 return;
137 }
138
Austin Schuhbd06ae42021-03-31 22:48:21 -0700139 aos::monotonic_clock::time_point now;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700140 if (encoder_->may_bypass() && span.size() > 4096u) {
141 // Over this threshold, we'll assume it's cheaper to add an extra
142 // syscall to write the data immediately instead of copying it to
143 // enqueue.
Austin Schuha36c8902019-12-30 18:07:15 -0800144
Brian Silvermanf51499a2020-09-21 12:49:08 -0700145 // First, flush everything.
146 while (encoder_->queue_size() > 0u) {
147 Flush();
148 }
Austin Schuhde031b72020-01-10 19:34:41 -0800149
Brian Silvermanf51499a2020-09-21 12:49:08 -0700150 // Then, write it directly.
151 const auto start = aos::monotonic_clock::now();
152 const ssize_t written = write(fd_, span.data(), span.size());
153 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700154 HandleWriteReturn(written, span.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700155 UpdateStatsForWrite(end - start, written, 1);
Austin Schuhbd06ae42021-03-31 22:48:21 -0700156 now = end;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700157 } else {
158 encoder_->Encode(CopySpanAsDetachedBuffer(span));
Austin Schuhbd06ae42021-03-31 22:48:21 -0700159 now = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800160 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700161
Austin Schuhbd06ae42021-03-31 22:48:21 -0700162 FlushAtThreshold(now);
Austin Schuha36c8902019-12-30 18:07:15 -0800163}
164
Brian Silverman0465fcf2020-09-24 00:29:18 -0700165void DetachedBufferWriter::Close() {
166 if (fd_ == -1) {
167 return;
168 }
169 encoder_->Finish();
170 while (encoder_->queue_size() > 0) {
171 Flush();
172 }
173 if (close(fd_) == -1) {
174 if (errno == ENOSPC) {
175 ran_out_of_space_ = true;
176 } else {
177 PLOG(ERROR) << "Closing log file failed";
178 }
179 }
180 fd_ = -1;
Austin Schuh58646e22021-08-23 23:51:46 -0700181 VLOG(1) << "Closed " << filename();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700182}
183
Austin Schuha36c8902019-12-30 18:07:15 -0800184void DetachedBufferWriter::Flush() {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700185 if (ran_out_of_space_) {
186 // We don't want any later data to be written after space becomes available,
187 // so refuse to write anything more once we've dropped data because we ran
188 // out of space.
Austin Schuha426f1f2021-03-31 22:27:41 -0700189 if (encoder_) {
190 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
191 encoder_->Clear(encoder_->queue().size());
192 } else {
193 VLOG(1) << "No queue to ignore";
194 }
195 return;
196 }
197
198 const auto queue = encoder_->queue();
199 if (queue.empty()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700200 return;
201 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700202
Austin Schuha36c8902019-12-30 18:07:15 -0800203 iovec_.clear();
Brian Silvermanf51499a2020-09-21 12:49:08 -0700204 const size_t iovec_size = std::min<size_t>(queue.size(), IOV_MAX);
205 iovec_.resize(iovec_size);
Austin Schuha36c8902019-12-30 18:07:15 -0800206 size_t counted_size = 0;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700207 for (size_t i = 0; i < iovec_size; ++i) {
208 iovec_[i].iov_base = const_cast<uint8_t *>(queue[i].data());
209 iovec_[i].iov_len = queue[i].size();
210 counted_size += iovec_[i].iov_len;
Austin Schuha36c8902019-12-30 18:07:15 -0800211 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700212
213 const auto start = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800214 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700215 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700216 HandleWriteReturn(written, counted_size);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700217
218 encoder_->Clear(iovec_size);
219
220 UpdateStatsForWrite(end - start, written, iovec_size);
221}
222
Brian Silverman0465fcf2020-09-24 00:29:18 -0700223void DetachedBufferWriter::HandleWriteReturn(ssize_t write_return,
224 size_t write_size) {
225 if (write_return == -1 && errno == ENOSPC) {
226 ran_out_of_space_ = true;
227 return;
228 }
229 PCHECK(write_return >= 0) << ": write failed";
230 if (write_return < static_cast<ssize_t>(write_size)) {
231 // Sometimes this happens instead of ENOSPC. On a real filesystem, this
232 // never seems to happen in any other case. If we ever want to log to a
233 // socket, this will happen more often. However, until we get there, we'll
234 // just assume it means we ran out of space.
235 ran_out_of_space_ = true;
236 return;
237 }
238}
239
Brian Silvermanf51499a2020-09-21 12:49:08 -0700240void DetachedBufferWriter::UpdateStatsForWrite(
241 aos::monotonic_clock::duration duration, ssize_t written, int iovec_size) {
242 if (duration > max_write_time_) {
243 max_write_time_ = duration;
244 max_write_time_bytes_ = written;
245 max_write_time_messages_ = iovec_size;
246 }
247 total_write_time_ += duration;
248 ++total_write_count_;
249 total_write_messages_ += iovec_size;
250 total_write_bytes_ += written;
251}
252
Austin Schuhbd06ae42021-03-31 22:48:21 -0700253void DetachedBufferWriter::FlushAtThreshold(
254 aos::monotonic_clock::time_point now) {
Austin Schuha426f1f2021-03-31 22:27:41 -0700255 if (ran_out_of_space_) {
256 // We don't want any later data to be written after space becomes available,
257 // so refuse to write anything more once we've dropped data because we ran
258 // out of space.
259 if (encoder_) {
260 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
261 encoder_->Clear(encoder_->queue().size());
262 } else {
263 VLOG(1) << "No queue to ignore";
264 }
265 return;
266 }
267
Austin Schuhbd06ae42021-03-31 22:48:21 -0700268 // We don't want to flush the first time through. Otherwise we will flush as
269 // the log file header might be compressing, defeating any parallelism and
270 // queueing there.
271 if (last_flush_time_ == aos::monotonic_clock::min_time) {
272 last_flush_time_ = now;
273 }
274
Brian Silvermanf51499a2020-09-21 12:49:08 -0700275 // Flush if we are at the max number of iovs per writev, because there's no
276 // point queueing up any more data in memory. Also flush once we have enough
Austin Schuhbd06ae42021-03-31 22:48:21 -0700277 // data queued up or if it has been long enough.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700278 while (encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
Austin Schuhbd06ae42021-03-31 22:48:21 -0700279 encoder_->queue_size() >= IOV_MAX ||
280 now > last_flush_time_ +
281 chrono::duration_cast<chrono::nanoseconds>(
282 chrono::duration<double>(FLAGS_flush_period))) {
283 last_flush_time_ = now;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700284 Flush();
285 }
Austin Schuha36c8902019-12-30 18:07:15 -0800286}
287
288flatbuffers::Offset<MessageHeader> PackMessage(
289 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
290 int channel_index, LogType log_type) {
291 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
292
293 switch (log_type) {
294 case LogType::kLogMessage:
295 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800296 case LogType::kLogRemoteMessage:
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700297 data_offset = fbb->CreateVector(
298 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800299 break;
300
301 case LogType::kLogDeliveryTimeOnly:
302 break;
303 }
304
305 MessageHeader::Builder message_header_builder(*fbb);
306 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800307
308 switch (log_type) {
309 case LogType::kLogRemoteMessage:
310 message_header_builder.add_queue_index(context.remote_queue_index);
311 message_header_builder.add_monotonic_sent_time(
312 context.monotonic_remote_time.time_since_epoch().count());
313 message_header_builder.add_realtime_sent_time(
314 context.realtime_remote_time.time_since_epoch().count());
315 break;
316
317 case LogType::kLogMessage:
318 case LogType::kLogMessageAndDeliveryTime:
319 case LogType::kLogDeliveryTimeOnly:
320 message_header_builder.add_queue_index(context.queue_index);
321 message_header_builder.add_monotonic_sent_time(
322 context.monotonic_event_time.time_since_epoch().count());
323 message_header_builder.add_realtime_sent_time(
324 context.realtime_event_time.time_since_epoch().count());
325 break;
326 }
Austin Schuha36c8902019-12-30 18:07:15 -0800327
328 switch (log_type) {
329 case LogType::kLogMessage:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800330 case LogType::kLogRemoteMessage:
Austin Schuha36c8902019-12-30 18:07:15 -0800331 message_header_builder.add_data(data_offset);
332 break;
333
334 case LogType::kLogMessageAndDeliveryTime:
335 message_header_builder.add_data(data_offset);
336 [[fallthrough]];
337
338 case LogType::kLogDeliveryTimeOnly:
339 message_header_builder.add_monotonic_remote_time(
340 context.monotonic_remote_time.time_since_epoch().count());
341 message_header_builder.add_realtime_remote_time(
342 context.realtime_remote_time.time_since_epoch().count());
343 message_header_builder.add_remote_queue_index(context.remote_queue_index);
344 break;
345 }
346
347 return message_header_builder.Finish();
348}
349
Austin Schuhcd368422021-11-22 21:23:29 -0800350SpanReader::SpanReader(std::string_view filename, bool quiet)
351 : filename_(filename) {
Tyler Chatow2015bc62021-08-04 21:15:09 -0700352 decoder_ = std::make_unique<DummyDecoder>(filename);
353
354 static constexpr std::string_view kXz = ".xz";
James Kuszmauldd0a5042021-10-28 23:38:04 -0700355 static constexpr std::string_view kSnappy = SnappyDecoder::kExtension;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700356 if (filename.substr(filename.size() - kXz.size()) == kXz) {
357#if ENABLE_LZMA
Austin Schuhcd368422021-11-22 21:23:29 -0800358 decoder_ =
359 std::make_unique<ThreadedLzmaDecoder>(std::move(decoder_), quiet);
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700360#else
Austin Schuhcd368422021-11-22 21:23:29 -0800361 (void)quiet;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700362 LOG(FATAL) << "Reading xz-compressed files not supported on this platform";
363#endif
James Kuszmauldd0a5042021-10-28 23:38:04 -0700364 } else if (filename.substr(filename.size() - kSnappy.size()) == kSnappy) {
365 decoder_ = std::make_unique<SnappyDecoder>(std::move(decoder_));
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700366 }
Austin Schuh05b70472020-01-01 17:11:17 -0800367}
368
Austin Schuhcf5f6442021-07-06 10:43:28 -0700369absl::Span<const uint8_t> SpanReader::PeekMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -0800370 // Make sure we have enough for the size.
371 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
372 if (!ReadBlock()) {
373 return absl::Span<const uint8_t>();
374 }
375 }
376
377 // Now make sure we have enough for the message.
378 const size_t data_size =
379 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
380 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -0800381 if (data_size == sizeof(flatbuffers::uoffset_t)) {
382 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
383 LOG(ERROR) << " Rest of log file is "
384 << absl::BytesToHexString(std::string_view(
385 reinterpret_cast<const char *>(data_.data() +
386 consumed_data_),
387 data_.size() - consumed_data_));
388 return absl::Span<const uint8_t>();
389 }
Austin Schuh05b70472020-01-01 17:11:17 -0800390 while (data_.size() < consumed_data_ + data_size) {
391 if (!ReadBlock()) {
392 return absl::Span<const uint8_t>();
393 }
394 }
395
396 // And return it, consuming the data.
397 const uint8_t *data_ptr = data_.data() + consumed_data_;
398
Austin Schuh05b70472020-01-01 17:11:17 -0800399 return absl::Span<const uint8_t>(data_ptr, data_size);
400}
401
Austin Schuhcf5f6442021-07-06 10:43:28 -0700402void SpanReader::ConsumeMessage() {
Brian Smarttea913d42021-12-10 15:02:38 -0800403 size_t consumed_size =
Austin Schuhcf5f6442021-07-06 10:43:28 -0700404 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
405 sizeof(flatbuffers::uoffset_t);
Brian Smarttea913d42021-12-10 15:02:38 -0800406 consumed_data_ += consumed_size;
407 total_consumed_ += consumed_size;
Austin Schuhcf5f6442021-07-06 10:43:28 -0700408}
409
410absl::Span<const uint8_t> SpanReader::ReadMessage() {
411 absl::Span<const uint8_t> result = PeekMessage();
412 if (result != absl::Span<const uint8_t>()) {
413 ConsumeMessage();
Brian Smarttea913d42021-12-10 15:02:38 -0800414 } else {
415 is_finished_ = true;
Austin Schuhcf5f6442021-07-06 10:43:28 -0700416 }
417 return result;
418}
419
Austin Schuh05b70472020-01-01 17:11:17 -0800420bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700421 // This is the amount of data we grab at a time. Doing larger chunks minimizes
422 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -0800423 constexpr size_t kReadSize = 256 * 1024;
424
425 // Strip off any unused data at the front.
426 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700427 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -0800428 consumed_data_ = 0;
429 }
430
431 const size_t starting_size = data_.size();
432
433 // This should automatically grow the backing store. It won't shrink if we
434 // get a small chunk later. This reduces allocations when we want to append
435 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700436 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -0800437
Brian Silvermanf51499a2020-09-21 12:49:08 -0700438 const size_t count =
439 decoder_->Read(data_.begin() + starting_size, data_.end());
440 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -0800441 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -0800442 return false;
443 }
Austin Schuh05b70472020-01-01 17:11:17 -0800444
Brian Smarttea913d42021-12-10 15:02:38 -0800445 total_read_ += count;
446
Austin Schuh05b70472020-01-01 17:11:17 -0800447 return true;
448}
449
Austin Schuhadd6eb32020-11-09 21:24:26 -0800450std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh0e8db662021-07-06 10:43:47 -0700451 SpanReader *span_reader) {
452 absl::Span<const uint8_t> config_data = span_reader->ReadMessage();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800453
454 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800455 if (config_data == absl::Span<const uint8_t>()) {
456 return std::nullopt;
457 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800458
Austin Schuh5212cad2020-09-09 23:12:09 -0700459 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -0700460 SizePrefixedFlatbufferVector<LogFileHeader> result(config_data);
Austin Schuhe09beb12020-12-11 20:04:27 -0800461 if (!result.Verify()) {
462 return std::nullopt;
463 }
Austin Schuh0e8db662021-07-06 10:43:47 -0700464
465 if (FLAGS_workaround_double_headers) {
466 while (true) {
467 absl::Span<const uint8_t> maybe_header_data = span_reader->PeekMessage();
468 if (maybe_header_data == absl::Span<const uint8_t>()) {
469 break;
470 }
471
472 aos::SizePrefixedFlatbufferSpan<aos::logger::LogFileHeader> maybe_header(
473 maybe_header_data);
474 if (maybe_header.Verify()) {
475 LOG(WARNING) << "Found duplicate LogFileHeader in "
476 << span_reader->filename();
477 ResizeableBuffer header_data_copy;
478 header_data_copy.resize(maybe_header_data.size());
479 memcpy(header_data_copy.data(), maybe_header_data.begin(),
480 header_data_copy.size());
481 result = SizePrefixedFlatbufferVector<LogFileHeader>(
482 std::move(header_data_copy));
483
484 span_reader->ConsumeMessage();
485 } else {
486 break;
487 }
488 }
489 }
Austin Schuhe09beb12020-12-11 20:04:27 -0800490 return result;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800491}
492
Austin Schuh0e8db662021-07-06 10:43:47 -0700493std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
494 std::string_view filename) {
495 SpanReader span_reader(filename);
496 return ReadHeader(&span_reader);
497}
498
Austin Schuhadd6eb32020-11-09 21:24:26 -0800499std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800500 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -0700501 SpanReader span_reader(filename);
502 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
503 for (size_t i = 0; i < n + 1; ++i) {
504 data_span = span_reader.ReadMessage();
505
506 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800507 if (data_span == absl::Span<const uint8_t>()) {
508 return std::nullopt;
509 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700510 }
511
Brian Silverman354697a2020-09-22 21:06:32 -0700512 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -0700513 SizePrefixedFlatbufferVector<MessageHeader> result(data_span);
Austin Schuhe09beb12020-12-11 20:04:27 -0800514 if (!result.Verify()) {
515 return std::nullopt;
516 }
517 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -0700518}
519
Austin Schuh05b70472020-01-01 17:11:17 -0800520MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -0700521 : span_reader_(filename),
Austin Schuhadd6eb32020-11-09 21:24:26 -0800522 raw_log_file_header_(
523 SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -0800524 set_crash_on_corrupt_message_flag(FLAGS_crash_on_corrupt_message);
525 set_ignore_corrupt_messages_flag(FLAGS_ignore_corrupt_messages);
526
Austin Schuh0e8db662021-07-06 10:43:47 -0700527 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>>
528 raw_log_file_header = ReadHeader(&span_reader_);
Austin Schuh05b70472020-01-01 17:11:17 -0800529
530 // Make sure something was read.
Austin Schuh0e8db662021-07-06 10:43:47 -0700531 CHECK(raw_log_file_header) << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -0800532
Austin Schuh0e8db662021-07-06 10:43:47 -0700533 raw_log_file_header_ = std::move(*raw_log_file_header);
Austin Schuh05b70472020-01-01 17:11:17 -0800534
Austin Schuh5b728b72021-06-16 14:57:15 -0700535 CHECK(raw_log_file_header_.Verify()) << "Log file header is corrupted";
536
Brian Smarttea913d42021-12-10 15:02:38 -0800537 total_verified_before_ = span_reader_.TotalConsumed();
538
Austin Schuhcde938c2020-02-02 17:30:07 -0800539 max_out_of_order_duration_ =
Austin Schuha040c3f2021-02-13 16:09:07 -0800540 FLAGS_max_out_of_order > 0
541 ? chrono::duration_cast<chrono::nanoseconds>(
542 chrono::duration<double>(FLAGS_max_out_of_order))
543 : chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -0800544
545 VLOG(1) << "Opened " << filename << " as node "
546 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800547}
548
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700549std::shared_ptr<UnpackedMessageHeader> MessageReader::ReadMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -0800550 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
551 if (msg_data == absl::Span<const uint8_t>()) {
Brian Smarttea913d42021-12-10 15:02:38 -0800552 if (is_corrupted()) {
553 LOG(ERROR) << "Total corrupted volumes: before = "
554 << total_verified_before_
555 << " | corrupted = " << total_corrupted_
556 << " | during = " << total_verified_during_
557 << " | after = " << total_verified_after_ << std::endl;
558 }
559
560 if (span_reader_.IsIncomplete()) {
Austin Schuh60e77942022-05-16 17:48:24 -0700561 LOG(ERROR) << "Unable to access some messages in " << filename() << " : "
562 << span_reader_.TotalRead() << " bytes read, "
Brian Smarttea913d42021-12-10 15:02:38 -0800563 << span_reader_.TotalConsumed() << " bytes usable."
564 << std::endl;
565 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700566 return nullptr;
Austin Schuh05b70472020-01-01 17:11:17 -0800567 }
568
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700569 SizePrefixedFlatbufferSpan<MessageHeader> msg(msg_data);
Brian Smarttea913d42021-12-10 15:02:38 -0800570
571 if (crash_on_corrupt_message_flag_) {
572 CHECK(msg.Verify()) << "Corrupted message at offset "
Austin Schuh60e77942022-05-16 17:48:24 -0700573 << total_verified_before_ << " found within "
574 << filename()
Brian Smarttea913d42021-12-10 15:02:38 -0800575 << "; set --nocrash_on_corrupt_message to see summary;"
576 << " also set --ignore_corrupt_messages to process"
577 << " anyway";
578
579 } else if (!msg.Verify()) {
Austin Schuh60e77942022-05-16 17:48:24 -0700580 LOG(ERROR) << "Corrupted message at offset " << total_verified_before_
Brian Smarttea913d42021-12-10 15:02:38 -0800581 << " from " << filename() << std::endl;
582
583 total_corrupted_ += msg_data.size();
584
585 while (true) {
586 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
587
588 if (msg_data == absl::Span<const uint8_t>()) {
589 if (!ignore_corrupt_messages_flag_) {
590 LOG(ERROR) << "Total corrupted volumes: before = "
591 << total_verified_before_
592 << " | corrupted = " << total_corrupted_
593 << " | during = " << total_verified_during_
594 << " | after = " << total_verified_after_ << std::endl;
595
596 if (span_reader_.IsIncomplete()) {
597 LOG(ERROR) << "Unable to access some messages in " << filename()
598 << " : " << span_reader_.TotalRead() << " bytes read, "
599 << span_reader_.TotalConsumed() << " bytes usable."
600 << std::endl;
601 }
602 return nullptr;
603 }
604 break;
605 }
606
607 SizePrefixedFlatbufferSpan<MessageHeader> next_msg(msg_data);
608
609 if (!next_msg.Verify()) {
610 total_corrupted_ += msg_data.size();
611 total_verified_during_ += total_verified_after_;
612 total_verified_after_ = 0;
613
614 } else {
615 total_verified_after_ += msg_data.size();
616 if (ignore_corrupt_messages_flag_) {
617 msg = next_msg;
618 break;
619 }
620 }
621 }
622 }
623
624 if (is_corrupted()) {
625 total_verified_after_ += msg_data.size();
626 } else {
627 total_verified_before_ += msg_data.size();
628 }
Austin Schuh05b70472020-01-01 17:11:17 -0800629
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700630 auto result = UnpackedMessageHeader::MakeMessage(msg.message());
Austin Schuh0e8db662021-07-06 10:43:47 -0700631
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700632 const monotonic_clock::time_point timestamp = result->monotonic_sent_time;
Austin Schuh05b70472020-01-01 17:11:17 -0800633
634 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuhd1873292021-11-18 15:35:30 -0800635
636 if (VLOG_IS_ON(3)) {
637 VLOG(3) << "Read from " << filename() << " data " << FlatbufferToJson(msg);
638 } else if (VLOG_IS_ON(2)) {
639 SizePrefixedFlatbufferVector<MessageHeader> msg_copy = msg;
640 msg_copy.mutable_message()->clear_data();
641 VLOG(2) << "Read from " << filename() << " data "
642 << FlatbufferToJson(msg_copy);
643 }
644
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700645 return result;
646}
647
648std::shared_ptr<UnpackedMessageHeader> UnpackedMessageHeader::MakeMessage(
649 const MessageHeader &message) {
650 const size_t data_size = message.has_data() ? message.data()->size() : 0;
651
652 UnpackedMessageHeader *const unpacked_message =
653 reinterpret_cast<UnpackedMessageHeader *>(
654 malloc(sizeof(UnpackedMessageHeader) + data_size +
655 kChannelDataAlignment - 1));
656
657 CHECK(message.has_channel_index());
658 CHECK(message.has_monotonic_sent_time());
659
660 absl::Span<uint8_t> span;
661 if (data_size > 0) {
662 span =
663 absl::Span<uint8_t>(reinterpret_cast<uint8_t *>(RoundChannelData(
664 &unpacked_message->actual_data[0], data_size)),
665 data_size);
666 }
667
Austin Schuh826e6ce2021-11-18 20:33:10 -0800668 std::optional<aos::monotonic_clock::time_point> monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700669 if (message.has_monotonic_remote_time()) {
Austin Schuh826e6ce2021-11-18 20:33:10 -0800670 monotonic_remote_time = aos::monotonic_clock::time_point(
671 std::chrono::nanoseconds(message.monotonic_remote_time()));
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700672 }
673 std::optional<realtime_clock::time_point> realtime_remote_time;
674 if (message.has_realtime_remote_time()) {
675 realtime_remote_time = realtime_clock::time_point(
676 chrono::nanoseconds(message.realtime_remote_time()));
677 }
678
679 std::optional<uint32_t> remote_queue_index;
680 if (message.has_remote_queue_index()) {
681 remote_queue_index = message.remote_queue_index();
682 }
683
684 new (unpacked_message) UnpackedMessageHeader{
685 .channel_index = message.channel_index(),
686 .monotonic_sent_time = monotonic_clock::time_point(
687 chrono::nanoseconds(message.monotonic_sent_time())),
688 .realtime_sent_time = realtime_clock::time_point(
689 chrono::nanoseconds(message.realtime_sent_time())),
690 .queue_index = message.queue_index(),
691 .monotonic_remote_time = monotonic_remote_time,
692 .realtime_remote_time = realtime_remote_time,
693 .remote_queue_index = remote_queue_index,
694 .monotonic_timestamp_time = monotonic_clock::time_point(
695 std::chrono::nanoseconds(message.monotonic_timestamp_time())),
696 .has_monotonic_timestamp_time = message.has_monotonic_timestamp_time(),
697 .span = span};
698
699 if (data_size > 0) {
700 memcpy(span.data(), message.data()->data(), data_size);
701 }
702
703 return std::shared_ptr<UnpackedMessageHeader>(unpacked_message,
704 &DestroyAndFree);
Austin Schuh05b70472020-01-01 17:11:17 -0800705}
706
Austin Schuhc41603c2020-10-11 16:17:37 -0700707PartsMessageReader::PartsMessageReader(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -0700708 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {
Brian Silvermanfee16972021-09-14 12:06:38 -0700709 if (parts_.parts.size() >= 2) {
710 next_message_reader_.emplace(parts_.parts[1]);
711 }
Austin Schuh48507722021-07-17 17:29:24 -0700712 ComputeBootCounts();
713}
714
715void PartsMessageReader::ComputeBootCounts() {
716 boot_counts_.assign(configuration::NodesCount(parts_.config.get()),
717 std::nullopt);
718
719 // We have 3 vintages of log files with different amounts of information.
720 if (log_file_header()->has_boot_uuids()) {
721 // The new hotness with the boots explicitly listed out. We can use the log
722 // file header to compute the boot count of all relevant nodes.
723 CHECK_EQ(log_file_header()->boot_uuids()->size(), boot_counts_.size());
724 size_t node_index = 0;
725 for (const flatbuffers::String *boot_uuid :
726 *log_file_header()->boot_uuids()) {
727 CHECK(parts_.boots);
728 if (boot_uuid->size() != 0) {
729 auto it = parts_.boots->boot_count_map.find(boot_uuid->str());
730 if (it != parts_.boots->boot_count_map.end()) {
731 boot_counts_[node_index] = it->second;
732 }
733 } else if (parts().boots->boots[node_index].size() == 1u) {
734 boot_counts_[node_index] = 0;
735 }
736 ++node_index;
737 }
738 } else {
739 // Older multi-node logs which are guarenteed to have UUIDs logged, or
740 // single node log files with boot UUIDs in the header. We only know how to
741 // order certain boots in certain circumstances.
742 if (configuration::MultiNode(parts_.config.get()) || parts_.boots) {
743 for (size_t node_index = 0; node_index < boot_counts_.size();
744 ++node_index) {
745 CHECK(parts_.boots);
746 if (parts().boots->boots[node_index].size() == 1u) {
747 boot_counts_[node_index] = 0;
748 }
749 }
750 } else {
751 // Really old single node logs without any UUIDs. They can't reboot.
752 CHECK_EQ(boot_counts_.size(), 1u);
753 boot_counts_[0] = 0u;
754 }
755 }
756}
Austin Schuhc41603c2020-10-11 16:17:37 -0700757
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700758std::shared_ptr<UnpackedMessageHeader> PartsMessageReader::ReadMessage() {
Austin Schuhc41603c2020-10-11 16:17:37 -0700759 while (!done_) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700760 std::shared_ptr<UnpackedMessageHeader> message =
Austin Schuhc41603c2020-10-11 16:17:37 -0700761 message_reader_.ReadMessage();
762 if (message) {
763 newest_timestamp_ = message_reader_.newest_timestamp();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700764 const monotonic_clock::time_point monotonic_sent_time =
765 message->monotonic_sent_time;
766
767 // TODO(austin): Does this work with startup? Might need to use the
768 // start time.
769 // TODO(austin): Does this work with startup when we don't know the
770 // remote start time too? Look at one of those logs to compare.
Austin Schuh315b96b2020-12-11 21:21:12 -0800771 if (monotonic_sent_time >
772 parts_.monotonic_start_time + max_out_of_order_duration()) {
773 after_start_ = true;
774 }
775 if (after_start_) {
Austin Schuhb000de62020-12-03 22:00:40 -0800776 CHECK_GE(monotonic_sent_time,
777 newest_timestamp_ - max_out_of_order_duration())
Austin Schuha040c3f2021-02-13 16:09:07 -0800778 << ": Max out of order of " << max_out_of_order_duration().count()
779 << "ns exceeded. " << parts_ << ", start time is "
Austin Schuh315b96b2020-12-11 21:21:12 -0800780 << parts_.monotonic_start_time << " currently reading "
781 << filename();
Austin Schuhb000de62020-12-03 22:00:40 -0800782 }
Austin Schuhc41603c2020-10-11 16:17:37 -0700783 return message;
784 }
785 NextLog();
786 }
Austin Schuh32f68492020-11-08 21:45:51 -0800787 newest_timestamp_ = monotonic_clock::max_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700788 return nullptr;
Austin Schuhc41603c2020-10-11 16:17:37 -0700789}
790
791void PartsMessageReader::NextLog() {
792 if (next_part_index_ == parts_.parts.size()) {
Brian Silvermanfee16972021-09-14 12:06:38 -0700793 CHECK(!next_message_reader_);
Austin Schuhc41603c2020-10-11 16:17:37 -0700794 done_ = true;
795 return;
796 }
Brian Silvermanfee16972021-09-14 12:06:38 -0700797 CHECK(next_message_reader_);
798 message_reader_ = std::move(*next_message_reader_);
Austin Schuh48507722021-07-17 17:29:24 -0700799 ComputeBootCounts();
Brian Silvermanfee16972021-09-14 12:06:38 -0700800 if (next_part_index_ + 1 < parts_.parts.size()) {
801 next_message_reader_.emplace(parts_.parts[next_part_index_ + 1]);
802 } else {
803 next_message_reader_.reset();
804 }
Austin Schuhc41603c2020-10-11 16:17:37 -0700805 ++next_part_index_;
806}
807
Austin Schuh1be0ce42020-11-29 22:43:26 -0800808bool Message::operator<(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700809 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700810
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700811 if (this->timestamp.time < m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -0800812 return true;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700813 } else if (this->timestamp.time > m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -0800814 return false;
815 }
816
817 if (this->channel_index < m2.channel_index) {
818 return true;
819 } else if (this->channel_index > m2.channel_index) {
820 return false;
821 }
822
823 return this->queue_index < m2.queue_index;
824}
825
826bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800827bool Message::operator==(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700828 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700829
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700830 return timestamp.time == m2.timestamp.time &&
831 channel_index == m2.channel_index && queue_index == m2.queue_index;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800832}
Austin Schuh1be0ce42020-11-29 22:43:26 -0800833
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700834std::ostream &operator<<(std::ostream &os, const UnpackedMessageHeader &m) {
835 os << "{.channel_index=" << m.channel_index
836 << ", .monotonic_sent_time=" << m.monotonic_sent_time
837 << ", .realtime_sent_time=" << m.realtime_sent_time
838 << ", .queue_index=" << m.queue_index;
839 if (m.monotonic_remote_time) {
Austin Schuh826e6ce2021-11-18 20:33:10 -0800840 os << ", .monotonic_remote_time=" << *m.monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700841 }
842 os << ", .realtime_remote_time=";
843 PrintOptionalOrNull(&os, m.realtime_remote_time);
844 os << ", .remote_queue_index=";
845 PrintOptionalOrNull(&os, m.remote_queue_index);
846 if (m.has_monotonic_timestamp_time) {
847 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
848 }
849 return os;
850}
851
Austin Schuh1be0ce42020-11-29 22:43:26 -0800852std::ostream &operator<<(std::ostream &os, const Message &m) {
853 os << "{.channel_index=" << m.channel_index
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700854 << ", .queue_index=" << m.queue_index << ", .timestamp=" << m.timestamp;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700855 if (m.data != nullptr) {
Austin Schuh826e6ce2021-11-18 20:33:10 -0800856 if (m.data->remote_queue_index.has_value()) {
857 os << ", .remote_queue_index=" << *m.data->remote_queue_index;
858 }
859 if (m.data->monotonic_remote_time.has_value()) {
860 os << ", .monotonic_remote_time=" << *m.data->monotonic_remote_time;
861 }
Austin Schuhfb1b3292021-11-16 21:20:15 -0800862 os << ", .data=" << m.data;
Austin Schuhd2f96102020-12-01 20:27:29 -0800863 }
864 os << "}";
865 return os;
866}
867
868std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m) {
869 os << "{.channel_index=" << m.channel_index
870 << ", .queue_index=" << m.queue_index
871 << ", .monotonic_event_time=" << m.monotonic_event_time
872 << ", .realtime_event_time=" << m.realtime_event_time;
Austin Schuh58646e22021-08-23 23:51:46 -0700873 if (m.remote_queue_index != BootQueueIndex::Invalid()) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800874 os << ", .remote_queue_index=" << m.remote_queue_index;
875 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700876 if (m.monotonic_remote_time != BootTimestamp::min_time()) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800877 os << ", .monotonic_remote_time=" << m.monotonic_remote_time;
878 }
879 if (m.realtime_remote_time != realtime_clock::min_time) {
880 os << ", .realtime_remote_time=" << m.realtime_remote_time;
881 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700882 if (m.monotonic_timestamp_time != BootTimestamp::min_time()) {
Austin Schuh8bf1e632021-01-02 22:41:04 -0800883 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
884 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700885 if (m.data != nullptr) {
886 os << ", .data=" << *m.data;
Austin Schuhd2f96102020-12-01 20:27:29 -0800887 }
888 os << "}";
Austin Schuh1be0ce42020-11-29 22:43:26 -0800889 return os;
890}
891
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800892LogPartsSorter::LogPartsSorter(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -0700893 : parts_message_reader_(log_parts),
894 source_node_index_(configuration::SourceNodeIndex(parts().config.get())) {
895}
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800896
897Message *LogPartsSorter::Front() {
898 // Queue up data until enough data has been queued that the front message is
899 // sorted enough to be safe to pop. This may do nothing, so we should make
900 // sure the nothing path is checked quickly.
901 if (sorted_until() != monotonic_clock::max_time) {
902 while (true) {
Austin Schuh48507722021-07-17 17:29:24 -0700903 if (!messages_.empty() &&
904 messages_.begin()->timestamp.time < sorted_until() &&
Austin Schuhb000de62020-12-03 22:00:40 -0800905 sorted_until() >= monotonic_start_time()) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800906 break;
907 }
908
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700909 std::shared_ptr<UnpackedMessageHeader> m =
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800910 parts_message_reader_.ReadMessage();
911 // No data left, sorted forever, work through what is left.
912 if (!m) {
913 sorted_until_ = monotonic_clock::max_time;
914 break;
915 }
916
Austin Schuh48507722021-07-17 17:29:24 -0700917 size_t monotonic_timestamp_boot = 0;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700918 if (m->has_monotonic_timestamp_time) {
Austin Schuh48507722021-07-17 17:29:24 -0700919 monotonic_timestamp_boot = parts().logger_boot_count;
920 }
921 size_t monotonic_remote_boot = 0xffffff;
922
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700923 if (m->monotonic_remote_time.has_value()) {
Austin Schuh60e77942022-05-16 17:48:24 -0700924 const Node *node =
925 parts().config->nodes()->Get(source_node_index_[m->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -0700926
Austin Schuh48507722021-07-17 17:29:24 -0700927 std::optional<size_t> boot = parts_message_reader_.boot_count(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700928 source_node_index_[m->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -0700929 CHECK(boot) << ": Failed to find boot for node " << MaybeNodeName(node)
Austin Schuh60e77942022-05-16 17:48:24 -0700930 << ", with index " << source_node_index_[m->channel_index];
Austin Schuh48507722021-07-17 17:29:24 -0700931 monotonic_remote_boot = *boot;
932 }
933
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700934 messages_.insert(
935 Message{.channel_index = m->channel_index,
936 .queue_index = BootQueueIndex{.boot = parts().boot_count,
937 .index = m->queue_index},
938 .timestamp = BootTimestamp{.boot = parts().boot_count,
939 .time = m->monotonic_sent_time},
940 .monotonic_remote_boot = monotonic_remote_boot,
941 .monotonic_timestamp_boot = monotonic_timestamp_boot,
942 .data = std::move(m)});
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800943
944 // Now, update sorted_until_ to match the new message.
945 if (parts_message_reader_.newest_timestamp() >
946 monotonic_clock::min_time +
947 parts_message_reader_.max_out_of_order_duration()) {
948 sorted_until_ = parts_message_reader_.newest_timestamp() -
949 parts_message_reader_.max_out_of_order_duration();
950 } else {
951 sorted_until_ = monotonic_clock::min_time;
952 }
953 }
954 }
955
956 // Now that we have enough data queued, return a pointer to the oldest piece
957 // of data if it exists.
958 if (messages_.empty()) {
Austin Schuhb000de62020-12-03 22:00:40 -0800959 last_message_time_ = monotonic_clock::max_time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800960 return nullptr;
961 }
962
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700963 CHECK_GE(messages_.begin()->timestamp.time, last_message_time_)
Austin Schuh315b96b2020-12-11 21:21:12 -0800964 << DebugString() << " reading " << parts_message_reader_.filename();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700965 last_message_time_ = messages_.begin()->timestamp.time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800966 return &(*messages_.begin());
967}
968
969void LogPartsSorter::PopFront() { messages_.erase(messages_.begin()); }
970
971std::string LogPartsSorter::DebugString() const {
972 std::stringstream ss;
973 ss << "messages: [\n";
Austin Schuh315b96b2020-12-11 21:21:12 -0800974 int count = 0;
975 bool no_dots = true;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800976 for (const Message &m : messages_) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800977 if (count < 15 || count > static_cast<int>(messages_.size()) - 15) {
978 ss << m << "\n";
979 } else if (no_dots) {
980 ss << "...\n";
981 no_dots = false;
982 }
983 ++count;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800984 }
985 ss << "] <- " << parts_message_reader_.filename();
986 return ss.str();
987}
988
Austin Schuhd2f96102020-12-01 20:27:29 -0800989NodeMerger::NodeMerger(std::vector<LogParts> parts) {
990 CHECK_GE(parts.size(), 1u);
Austin Schuh715adc12021-06-29 22:07:39 -0700991 // Enforce that we are sorting things only from a single node from a single
992 // boot.
993 const std::string_view part0_node = parts[0].node;
994 const std::string_view part0_source_boot_uuid = parts[0].source_boot_uuid;
Austin Schuhd2f96102020-12-01 20:27:29 -0800995 for (size_t i = 1; i < parts.size(); ++i) {
996 CHECK_EQ(part0_node, parts[i].node) << ": Can't merge different nodes.";
Austin Schuh715adc12021-06-29 22:07:39 -0700997 CHECK_EQ(part0_source_boot_uuid, parts[i].source_boot_uuid)
998 << ": Can't merge different boots.";
Austin Schuhd2f96102020-12-01 20:27:29 -0800999 }
Austin Schuh715adc12021-06-29 22:07:39 -07001000
1001 node_ = configuration::GetNodeIndex(parts[0].config.get(), part0_node);
1002
Austin Schuhd2f96102020-12-01 20:27:29 -08001003 for (LogParts &part : parts) {
1004 parts_sorters_.emplace_back(std::move(part));
1005 }
1006
Austin Schuhd2f96102020-12-01 20:27:29 -08001007 monotonic_start_time_ = monotonic_clock::max_time;
Austin Schuh9dc42612021-09-20 20:41:29 -07001008 realtime_start_time_ = realtime_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001009 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001010 // We want to capture the earliest meaningful start time here. The start
1011 // time defaults to min_time when there's no meaningful value to report, so
1012 // let's ignore those.
Austin Schuh9dc42612021-09-20 20:41:29 -07001013 if (parts_sorter.monotonic_start_time() != monotonic_clock::min_time) {
1014 bool accept = false;
1015 // We want to prioritize start times from the logger node. Really, we
1016 // want to prioritize start times with a valid realtime_clock time. So,
1017 // if we have a start time without a RT clock, prefer a start time with a
1018 // RT clock, even it if is later.
1019 if (parts_sorter.realtime_start_time() != realtime_clock::min_time) {
1020 // We've got a good one. See if the current start time has a good RT
1021 // clock, or if we should use this one instead.
1022 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
1023 accept = true;
1024 } else if (realtime_start_time_ == realtime_clock::min_time) {
1025 // The previous start time doesn't have a good RT time, so it is very
1026 // likely the start time from a remote part file. We just found a
1027 // better start time with a real RT time, so switch to that instead.
1028 accept = true;
1029 }
1030 } else if (realtime_start_time_ == realtime_clock::min_time) {
1031 // We don't have a RT time, so take the oldest.
1032 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
1033 accept = true;
1034 }
1035 }
1036
1037 if (accept) {
1038 monotonic_start_time_ = parts_sorter.monotonic_start_time();
1039 realtime_start_time_ = parts_sorter.realtime_start_time();
1040 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001041 }
1042 }
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001043
1044 // If there was no meaningful start time reported, just use min_time.
1045 if (monotonic_start_time_ == monotonic_clock::max_time) {
1046 monotonic_start_time_ = monotonic_clock::min_time;
1047 realtime_start_time_ = realtime_clock::min_time;
1048 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001049}
Austin Schuh8f52ed52020-11-30 23:12:39 -08001050
Austin Schuh0ca51f32020-12-25 21:51:45 -08001051std::vector<const LogParts *> NodeMerger::Parts() const {
1052 std::vector<const LogParts *> p;
1053 p.reserve(parts_sorters_.size());
1054 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
1055 p.emplace_back(&parts_sorter.parts());
1056 }
1057 return p;
1058}
1059
Austin Schuh8f52ed52020-11-30 23:12:39 -08001060Message *NodeMerger::Front() {
1061 // Return the current Front if we have one, otherwise go compute one.
1062 if (current_ != nullptr) {
Austin Schuhb000de62020-12-03 22:00:40 -08001063 Message *result = current_->Front();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001064 CHECK_GE(result->timestamp.time, last_message_time_);
Austin Schuhb000de62020-12-03 22:00:40 -08001065 return result;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001066 }
1067
1068 // Otherwise, do a simple search for the oldest message, deduplicating any
1069 // duplicates.
1070 Message *oldest = nullptr;
1071 sorted_until_ = monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001072 for (LogPartsSorter &parts_sorter : parts_sorters_) {
1073 Message *m = parts_sorter.Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -08001074 if (!m) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001075 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001076 continue;
1077 }
1078 if (oldest == nullptr || *m < *oldest) {
1079 oldest = m;
Austin Schuhd2f96102020-12-01 20:27:29 -08001080 current_ = &parts_sorter;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001081 } else if (*m == *oldest) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001082 // Found a duplicate. If there is a choice, we want the one which has
1083 // the timestamp time.
1084 if (!m->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001085 parts_sorter.PopFront();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001086 } else if (!oldest->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001087 current_->PopFront();
1088 current_ = &parts_sorter;
1089 oldest = m;
1090 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001091 CHECK_EQ(m->data->monotonic_timestamp_time,
1092 oldest->data->monotonic_timestamp_time);
Austin Schuh8bf1e632021-01-02 22:41:04 -08001093 parts_sorter.PopFront();
1094 }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001095 }
1096
1097 // PopFront may change this, so compute it down here.
Austin Schuhd2f96102020-12-01 20:27:29 -08001098 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001099 }
1100
Austin Schuhb000de62020-12-03 22:00:40 -08001101 if (oldest) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001102 CHECK_GE(oldest->timestamp.time, last_message_time_);
1103 last_message_time_ = oldest->timestamp.time;
Austin Schuh5dd22842021-11-17 16:09:39 -08001104 monotonic_oldest_time_ =
1105 std::min(monotonic_oldest_time_, oldest->timestamp.time);
Austin Schuhb000de62020-12-03 22:00:40 -08001106 } else {
1107 last_message_time_ = monotonic_clock::max_time;
1108 }
1109
Austin Schuh8f52ed52020-11-30 23:12:39 -08001110 // Return the oldest message found. This will be nullptr if nothing was
1111 // found, indicating there is nothing left.
1112 return oldest;
1113}
1114
1115void NodeMerger::PopFront() {
1116 CHECK(current_ != nullptr) << "Popping before calling Front()";
1117 current_->PopFront();
1118 current_ = nullptr;
1119}
1120
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001121BootMerger::BootMerger(std::vector<LogParts> files) {
1122 std::vector<std::vector<LogParts>> boots;
1123
1124 // Now, we need to split things out by boot.
1125 for (size_t i = 0; i < files.size(); ++i) {
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001126 const size_t boot_count = files[i].boot_count;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001127 if (boot_count + 1 > boots.size()) {
1128 boots.resize(boot_count + 1);
1129 }
1130 boots[boot_count].emplace_back(std::move(files[i]));
1131 }
1132
1133 node_mergers_.reserve(boots.size());
1134 for (size_t i = 0; i < boots.size(); ++i) {
Austin Schuh48507722021-07-17 17:29:24 -07001135 VLOG(2) << "Boot " << i;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001136 for (auto &p : boots[i]) {
Austin Schuh48507722021-07-17 17:29:24 -07001137 VLOG(2) << "Part " << p;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001138 }
1139 node_mergers_.emplace_back(
1140 std::make_unique<NodeMerger>(std::move(boots[i])));
1141 }
1142}
1143
1144Message *BootMerger::Front() {
1145 Message *result = node_mergers_[index_]->Front();
1146
1147 if (result != nullptr) {
1148 return result;
1149 }
1150
1151 if (index_ + 1u == node_mergers_.size()) {
1152 // At the end of the last node merger, just return.
1153 return nullptr;
1154 } else {
1155 ++index_;
1156 return Front();
1157 }
1158}
1159
1160void BootMerger::PopFront() { node_mergers_[index_]->PopFront(); }
1161
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001162std::vector<const LogParts *> BootMerger::Parts() const {
1163 std::vector<const LogParts *> results;
1164 for (const std::unique_ptr<NodeMerger> &node_merger : node_mergers_) {
1165 std::vector<const LogParts *> node_parts = node_merger->Parts();
1166
1167 results.insert(results.end(), std::make_move_iterator(node_parts.begin()),
1168 std::make_move_iterator(node_parts.end()));
1169 }
1170
1171 return results;
1172}
1173
Austin Schuhd2f96102020-12-01 20:27:29 -08001174TimestampMapper::TimestampMapper(std::vector<LogParts> parts)
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001175 : boot_merger_(std::move(parts)),
Austin Schuh79b30942021-01-24 22:32:21 -08001176 timestamp_callback_([](TimestampedMessage *) {}) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001177 for (const LogParts *part : boot_merger_.Parts()) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001178 if (!configuration_) {
1179 configuration_ = part->config;
1180 } else {
1181 CHECK_EQ(configuration_.get(), part->config.get());
1182 }
1183 }
1184 const Configuration *config = configuration_.get();
Austin Schuhd2f96102020-12-01 20:27:29 -08001185 // Only fill out nodes_data_ if there are nodes. Otherwise everything gets
1186 // pretty simple.
1187 if (configuration::MultiNode(config)) {
1188 nodes_data_.resize(config->nodes()->size());
1189 const Node *my_node = config->nodes()->Get(node());
1190 for (size_t node_index = 0; node_index < nodes_data_.size(); ++node_index) {
1191 const Node *node = config->nodes()->Get(node_index);
1192 NodeData *node_data = &nodes_data_[node_index];
1193 node_data->channels.resize(config->channels()->size());
1194 // We should save the channel if it is delivered to the node represented
1195 // by the NodeData, but not sent by that node. That combo means it is
1196 // forwarded.
1197 size_t channel_index = 0;
1198 node_data->any_delivered = false;
1199 for (const Channel *channel : *config->channels()) {
1200 node_data->channels[channel_index].delivered =
1201 configuration::ChannelIsReadableOnNode(channel, node) &&
Austin Schuhb3dbb6d2021-01-02 17:29:35 -08001202 configuration::ChannelIsSendableOnNode(channel, my_node) &&
1203 (my_node != node);
Austin Schuhd2f96102020-12-01 20:27:29 -08001204 node_data->any_delivered = node_data->any_delivered ||
1205 node_data->channels[channel_index].delivered;
Austin Schuh6a7358f2021-11-18 22:40:40 -08001206 if (node_data->channels[channel_index].delivered) {
1207 const Connection *connection =
1208 configuration::ConnectionToNode(channel, node);
1209 node_data->channels[channel_index].time_to_live =
1210 chrono::nanoseconds(connection->time_to_live());
1211 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001212 ++channel_index;
1213 }
1214 }
1215
1216 for (const Channel *channel : *config->channels()) {
1217 source_node_.emplace_back(configuration::GetNodeIndex(
1218 config, channel->source_node()->string_view()));
1219 }
1220 }
1221}
1222
1223void TimestampMapper::AddPeer(TimestampMapper *timestamp_mapper) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001224 CHECK(configuration::MultiNode(configuration()));
Austin Schuhd2f96102020-12-01 20:27:29 -08001225 CHECK_NE(timestamp_mapper->node(), node());
1226 CHECK_LT(timestamp_mapper->node(), nodes_data_.size());
1227
1228 NodeData *node_data = &nodes_data_[timestamp_mapper->node()];
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001229 // Only set it if this node delivers to the peer timestamp_mapper. Otherwise
Austin Schuhd2f96102020-12-01 20:27:29 -08001230 // we could needlessly save data.
1231 if (node_data->any_delivered) {
Austin Schuh87dd3832021-01-01 23:07:31 -08001232 VLOG(1) << "Registering on node " << node() << " for peer node "
1233 << timestamp_mapper->node();
Austin Schuhd2f96102020-12-01 20:27:29 -08001234 CHECK(timestamp_mapper->nodes_data_[node()].peer == nullptr);
1235
1236 timestamp_mapper->nodes_data_[node()].peer = this;
Austin Schuh36c00932021-07-19 18:13:21 -07001237
1238 node_data->save_for_peer = true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001239 }
1240}
1241
Austin Schuh79b30942021-01-24 22:32:21 -08001242void TimestampMapper::QueueMessage(Message *m) {
Austin Schuh60e77942022-05-16 17:48:24 -07001243 matched_messages_.emplace_back(
1244 TimestampedMessage{.channel_index = m->channel_index,
1245 .queue_index = m->queue_index,
1246 .monotonic_event_time = m->timestamp,
1247 .realtime_event_time = m->data->realtime_sent_time,
1248 .remote_queue_index = BootQueueIndex::Invalid(),
1249 .monotonic_remote_time = BootTimestamp::min_time(),
1250 .realtime_remote_time = realtime_clock::min_time,
1251 .monotonic_timestamp_time = BootTimestamp::min_time(),
1252 .data = std::move(m->data)});
Austin Schuhd2f96102020-12-01 20:27:29 -08001253}
1254
1255TimestampedMessage *TimestampMapper::Front() {
1256 // No need to fetch anything new. A previous message still exists.
1257 switch (first_message_) {
1258 case FirstMessage::kNeedsUpdate:
1259 break;
1260 case FirstMessage::kInMessage:
Austin Schuh79b30942021-01-24 22:32:21 -08001261 return &matched_messages_.front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001262 case FirstMessage::kNullptr:
1263 return nullptr;
1264 }
1265
Austin Schuh79b30942021-01-24 22:32:21 -08001266 if (matched_messages_.empty()) {
1267 if (!QueueMatched()) {
1268 first_message_ = FirstMessage::kNullptr;
1269 return nullptr;
1270 }
1271 }
1272 first_message_ = FirstMessage::kInMessage;
1273 return &matched_messages_.front();
1274}
1275
1276bool TimestampMapper::QueueMatched() {
Austin Schuhd2f96102020-12-01 20:27:29 -08001277 if (nodes_data_.empty()) {
1278 // Simple path. We are single node, so there are no timestamps to match!
1279 CHECK_EQ(messages_.size(), 0u);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001280 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001281 if (!m) {
Austin Schuh79b30942021-01-24 22:32:21 -08001282 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -08001283 }
Austin Schuh79b30942021-01-24 22:32:21 -08001284 // Enqueue this message into matched_messages_ so we have a place to
1285 // associate remote timestamps, and return it.
1286 QueueMessage(m);
Austin Schuhd2f96102020-12-01 20:27:29 -08001287
Austin Schuh79b30942021-01-24 22:32:21 -08001288 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1289 last_message_time_ = matched_messages_.back().monotonic_event_time;
1290
1291 // We are thin wrapper around node_merger. Call it directly.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001292 boot_merger_.PopFront();
Austin Schuh79b30942021-01-24 22:32:21 -08001293 timestamp_callback_(&matched_messages_.back());
1294 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001295 }
1296
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001297 // We need to only add messages to the list so they get processed for
1298 // messages which are delivered. Reuse the flow below which uses messages_
1299 // by just adding the new message to messages_ and continuing.
Austin Schuhd2f96102020-12-01 20:27:29 -08001300 if (messages_.empty()) {
1301 if (!Queue()) {
1302 // Found nothing to add, we are out of data!
Austin Schuh79b30942021-01-24 22:32:21 -08001303 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -08001304 }
1305
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001306 // Now that it has been added (and cannibalized), forget about it
1307 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001308 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08001309 }
1310
1311 Message *m = &(messages_.front());
1312
1313 if (source_node_[m->channel_index] == node()) {
1314 // From us, just forward it on, filling the remote data in as invalid.
Austin Schuh79b30942021-01-24 22:32:21 -08001315 QueueMessage(m);
1316 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1317 last_message_time_ = matched_messages_.back().monotonic_event_time;
1318 messages_.pop_front();
1319 timestamp_callback_(&matched_messages_.back());
1320 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001321 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001322 // Got a timestamp, find the matching remote data, match it, and return
1323 // it.
Austin Schuhd2f96102020-12-01 20:27:29 -08001324 Message data = MatchingMessageFor(*m);
1325
1326 // Return the data from the remote. The local message only has timestamp
1327 // info which isn't relevant anymore once extracted.
Austin Schuh79b30942021-01-24 22:32:21 -08001328 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -08001329 .channel_index = m->channel_index,
1330 .queue_index = m->queue_index,
1331 .monotonic_event_time = m->timestamp,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001332 .realtime_event_time = m->data->realtime_sent_time,
Austin Schuh58646e22021-08-23 23:51:46 -07001333 .remote_queue_index =
1334 BootQueueIndex{.boot = m->monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001335 .index = m->data->remote_queue_index.value()},
1336 .monotonic_remote_time = {m->monotonic_remote_boot,
Austin Schuh826e6ce2021-11-18 20:33:10 -08001337 m->data->monotonic_remote_time.value()},
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001338 .realtime_remote_time = m->data->realtime_remote_time.value(),
1339 .monotonic_timestamp_time = {m->monotonic_timestamp_boot,
1340 m->data->monotonic_timestamp_time},
Austin Schuh79b30942021-01-24 22:32:21 -08001341 .data = std::move(data.data)});
1342 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1343 last_message_time_ = matched_messages_.back().monotonic_event_time;
1344 // Since messages_ holds the data, drop it.
1345 messages_.pop_front();
1346 timestamp_callback_(&matched_messages_.back());
1347 return true;
1348 }
1349}
1350
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001351void TimestampMapper::QueueUntil(BootTimestamp queue_time) {
Austin Schuh79b30942021-01-24 22:32:21 -08001352 while (last_message_time_ <= queue_time) {
1353 if (!QueueMatched()) {
1354 return;
1355 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001356 }
1357}
1358
Austin Schuhe639ea12021-01-25 13:00:22 -08001359void TimestampMapper::QueueFor(chrono::nanoseconds time_estimation_buffer) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001360 // Note: queueing for time doesn't really work well across boots. So we
1361 // just assume that if you are using this, you only care about the current
1362 // boot.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001363 //
1364 // TODO(austin): Is that the right concept?
1365 //
Austin Schuhe639ea12021-01-25 13:00:22 -08001366 // Make sure we have something queued first. This makes the end time
1367 // calculation simpler, and is typically what folks want regardless.
1368 if (matched_messages_.empty()) {
1369 if (!QueueMatched()) {
1370 return;
1371 }
1372 }
1373
1374 const aos::monotonic_clock::time_point end_queue_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001375 std::max(monotonic_start_time(
1376 matched_messages_.front().monotonic_event_time.boot),
1377 matched_messages_.front().monotonic_event_time.time) +
Austin Schuhe639ea12021-01-25 13:00:22 -08001378 time_estimation_buffer;
1379
1380 // Place sorted messages on the list until we have
1381 // --time_estimation_buffer_seconds seconds queued up (but queue at least
1382 // until the log starts).
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001383 while (end_queue_time >= last_message_time_.time) {
Austin Schuhe639ea12021-01-25 13:00:22 -08001384 if (!QueueMatched()) {
1385 return;
1386 }
1387 }
1388}
1389
Austin Schuhd2f96102020-12-01 20:27:29 -08001390void TimestampMapper::PopFront() {
1391 CHECK(first_message_ != FirstMessage::kNeedsUpdate);
Austin Schuh6a7358f2021-11-18 22:40:40 -08001392 last_popped_message_time_ = Front()->monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001393 first_message_ = FirstMessage::kNeedsUpdate;
1394
Austin Schuh79b30942021-01-24 22:32:21 -08001395 matched_messages_.pop_front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001396}
1397
1398Message TimestampMapper::MatchingMessageFor(const Message &message) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001399 // Figure out what queue index we are looking for.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001400 CHECK_NOTNULL(message.data);
1401 CHECK(message.data->remote_queue_index.has_value());
Austin Schuh58646e22021-08-23 23:51:46 -07001402 const BootQueueIndex remote_queue_index =
1403 BootQueueIndex{.boot = message.monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001404 .index = *message.data->remote_queue_index};
Austin Schuhd2f96102020-12-01 20:27:29 -08001405
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001406 CHECK(message.data->monotonic_remote_time.has_value());
1407 CHECK(message.data->realtime_remote_time.has_value());
Austin Schuhd2f96102020-12-01 20:27:29 -08001408
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001409 const BootTimestamp monotonic_remote_time{
Austin Schuh48507722021-07-17 17:29:24 -07001410 .boot = message.monotonic_remote_boot,
Austin Schuh826e6ce2021-11-18 20:33:10 -08001411 .time = message.data->monotonic_remote_time.value()};
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001412 const realtime_clock::time_point realtime_remote_time =
1413 *message.data->realtime_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001414
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001415 TimestampMapper *peer =
1416 nodes_data_[source_node_[message.data->channel_index]].peer;
Austin Schuhfecf1d82020-12-19 16:57:28 -08001417
1418 // We only register the peers which we have data for. So, if we are being
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001419 // asked to pull a timestamp from a peer which doesn't exist, return an
1420 // empty message.
Austin Schuhfecf1d82020-12-19 16:57:28 -08001421 if (peer == nullptr) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001422 // TODO(austin): Make sure the tests hit all these paths with a boot count
1423 // of 1...
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001424 return Message{.channel_index = message.channel_index,
1425 .queue_index = remote_queue_index,
1426 .timestamp = monotonic_remote_time,
1427 .monotonic_remote_boot = 0xffffff,
1428 .monotonic_timestamp_boot = 0xffffff,
1429 .data = nullptr};
Austin Schuhfecf1d82020-12-19 16:57:28 -08001430 }
1431
1432 // The queue which will have the matching data, if available.
1433 std::deque<Message> *data_queue =
1434 &peer->nodes_data_[node()].channels[message.channel_index].messages;
1435
Austin Schuh79b30942021-01-24 22:32:21 -08001436 peer->QueueUnmatchedUntil(monotonic_remote_time);
Austin Schuhd2f96102020-12-01 20:27:29 -08001437
1438 if (data_queue->empty()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001439 return Message{.channel_index = message.channel_index,
1440 .queue_index = remote_queue_index,
1441 .timestamp = monotonic_remote_time,
1442 .monotonic_remote_boot = 0xffffff,
1443 .monotonic_timestamp_boot = 0xffffff,
1444 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08001445 }
1446
Austin Schuhd2f96102020-12-01 20:27:29 -08001447 if (remote_queue_index < data_queue->front().queue_index ||
1448 remote_queue_index > data_queue->back().queue_index) {
Austin Schuh60e77942022-05-16 17:48:24 -07001449 return Message{.channel_index = message.channel_index,
1450 .queue_index = remote_queue_index,
1451 .timestamp = monotonic_remote_time,
1452 .monotonic_remote_boot = 0xffffff,
1453 .monotonic_timestamp_boot = 0xffffff,
1454 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08001455 }
1456
Austin Schuh993ccb52020-12-12 15:59:32 -08001457 // The algorithm below is constant time with some assumptions. We need there
1458 // to be no missing messages in the data stream. This also assumes a queue
1459 // hasn't wrapped. That is conservative, but should let us get started.
Austin Schuh58646e22021-08-23 23:51:46 -07001460 if (data_queue->back().queue_index.boot ==
1461 data_queue->front().queue_index.boot &&
1462 (data_queue->back().queue_index.index -
1463 data_queue->front().queue_index.index + 1u ==
1464 data_queue->size())) {
1465 CHECK_EQ(remote_queue_index.boot, data_queue->front().queue_index.boot);
Austin Schuh993ccb52020-12-12 15:59:32 -08001466 // Pull the data out and confirm that the timestamps match as expected.
Austin Schuh58646e22021-08-23 23:51:46 -07001467 //
1468 // TODO(austin): Move if not reliable.
1469 Message result = (*data_queue)[remote_queue_index.index -
1470 data_queue->front().queue_index.index];
Austin Schuh993ccb52020-12-12 15:59:32 -08001471
1472 CHECK_EQ(result.timestamp, monotonic_remote_time)
1473 << ": Queue index matches, but timestamp doesn't. Please investigate!";
Austin Schuh6a7358f2021-11-18 22:40:40 -08001474 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
Austin Schuh993ccb52020-12-12 15:59:32 -08001475 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1476 // Now drop the data off the front. We have deduplicated timestamps, so we
1477 // are done. And all the data is in order.
Austin Schuh58646e22021-08-23 23:51:46 -07001478 data_queue->erase(
1479 data_queue->begin(),
1480 data_queue->begin() +
1481 (remote_queue_index.index - data_queue->front().queue_index.index));
Austin Schuh993ccb52020-12-12 15:59:32 -08001482 return result;
1483 } else {
Austin Schuh58646e22021-08-23 23:51:46 -07001484 // TODO(austin): Binary search.
1485 auto it = std::find_if(
1486 data_queue->begin(), data_queue->end(),
1487 [remote_queue_index,
1488 remote_boot = monotonic_remote_time.boot](const Message &m) {
1489 return m.queue_index == remote_queue_index &&
1490 m.timestamp.boot == remote_boot;
1491 });
Austin Schuh993ccb52020-12-12 15:59:32 -08001492 if (it == data_queue->end()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001493 return Message{.channel_index = message.channel_index,
1494 .queue_index = remote_queue_index,
1495 .timestamp = monotonic_remote_time,
1496 .monotonic_remote_boot = 0xffffff,
1497 .monotonic_timestamp_boot = 0xffffff,
1498 .data = nullptr};
Austin Schuh993ccb52020-12-12 15:59:32 -08001499 }
1500
1501 Message result = std::move(*it);
1502
1503 CHECK_EQ(result.timestamp, monotonic_remote_time)
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001504 << ": Queue index matches, but timestamp doesn't. Please "
1505 "investigate!";
1506 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
1507 << ": Queue index matches, but timestamp doesn't. Please "
1508 "investigate!";
Austin Schuh993ccb52020-12-12 15:59:32 -08001509
Austin Schuhd6b1f4c2021-11-18 20:29:00 -08001510 // Erase everything up to this message. We want to keep 1 message in the
1511 // queue so we can handle reliable messages forwarded across boots.
1512 data_queue->erase(data_queue->begin(), it);
Austin Schuh993ccb52020-12-12 15:59:32 -08001513
1514 return result;
1515 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001516}
1517
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001518void TimestampMapper::QueueUnmatchedUntil(BootTimestamp t) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001519 if (queued_until_ > t) {
1520 return;
1521 }
1522 while (true) {
1523 if (!messages_.empty() && messages_.back().timestamp > t) {
1524 queued_until_ = std::max(queued_until_, messages_.back().timestamp);
1525 return;
1526 }
1527
1528 if (!Queue()) {
1529 // Found nothing to add, we are out of data!
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001530 queued_until_ = BootTimestamp::max_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08001531 return;
1532 }
1533
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001534 // Now that it has been added (and cannibalized), forget about it
1535 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001536 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08001537 }
1538}
1539
1540bool TimestampMapper::Queue() {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001541 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001542 if (m == nullptr) {
1543 return false;
1544 }
1545 for (NodeData &node_data : nodes_data_) {
1546 if (!node_data.any_delivered) continue;
Austin Schuh36c00932021-07-19 18:13:21 -07001547 if (!node_data.save_for_peer) continue;
Austin Schuhd2f96102020-12-01 20:27:29 -08001548 if (node_data.channels[m->channel_index].delivered) {
Austin Schuh6a7358f2021-11-18 22:40:40 -08001549 // If we have data but no timestamps (logs where the timestamps didn't get
1550 // logged are classic), we can grow this indefinitely. We don't need to
1551 // keep anything that is older than the last message returned.
1552
1553 // We have the time on the source node.
1554 // We care to wait until we have the time on the destination node.
1555 std::deque<Message> &messages =
1556 node_data.channels[m->channel_index].messages;
1557 // Max delay over the network is the TTL, so let's take the queue time and
1558 // add TTL to it. Don't forget any messages which are reliable until
1559 // someone can come up with a good reason to forget those too.
1560 if (node_data.channels[m->channel_index].time_to_live >
1561 chrono::nanoseconds(0)) {
1562 // We need to make *some* assumptions about network delay for this to
1563 // work. We want to only look at the RX side. This means we need to
1564 // track the last time a message was popped from any channel from the
1565 // node sending this message, and compare that to the max time we expect
1566 // that a message will take to be delivered across the network. This
1567 // assumes that messages are popped in time order as a proxy for
1568 // measuring the distributed time at this layer.
1569 //
1570 // Leave at least 1 message in here so we can handle reboots and
1571 // messages getting sent twice.
1572 while (messages.size() > 1u &&
1573 messages.begin()->timestamp +
1574 node_data.channels[m->channel_index].time_to_live +
1575 chrono::duration_cast<chrono::nanoseconds>(
1576 chrono::duration<double>(FLAGS_max_network_delay)) <
1577 last_popped_message_time_) {
1578 messages.pop_front();
1579 }
1580 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001581 node_data.channels[m->channel_index].messages.emplace_back(*m);
1582 }
1583 }
1584
1585 messages_.emplace_back(std::move(*m));
1586 return true;
1587}
1588
1589std::string TimestampMapper::DebugString() const {
1590 std::stringstream ss;
Austin Schuh6e014b82021-09-14 17:46:33 -07001591 ss << "node " << node() << " (" << node_name() << ") [\n";
Austin Schuhd2f96102020-12-01 20:27:29 -08001592 for (const Message &message : messages_) {
1593 ss << " " << message << "\n";
1594 }
1595 ss << "] queued_until " << queued_until_;
1596 for (const NodeData &ns : nodes_data_) {
1597 if (ns.peer == nullptr) continue;
1598 ss << "\nnode " << ns.peer->node() << " remote_data [\n";
1599 size_t channel_index = 0;
1600 for (const NodeData::ChannelData &channel_data :
1601 ns.peer->nodes_data_[node()].channels) {
1602 if (channel_data.messages.empty()) {
1603 continue;
1604 }
Austin Schuhb000de62020-12-03 22:00:40 -08001605
Austin Schuhd2f96102020-12-01 20:27:29 -08001606 ss << " channel " << channel_index << " [\n";
1607 for (const Message &m : channel_data.messages) {
1608 ss << " " << m << "\n";
1609 }
1610 ss << " ]\n";
1611 ++channel_index;
1612 }
1613 ss << "] queued_until " << ns.peer->queued_until_;
1614 }
1615 return ss.str();
1616}
1617
Austin Schuhee711052020-08-24 16:06:09 -07001618std::string MaybeNodeName(const Node *node) {
1619 if (node != nullptr) {
1620 return node->name()->str() + " ";
1621 }
1622 return "";
1623}
1624
Brian Silvermanf51499a2020-09-21 12:49:08 -07001625} // namespace aos::logger