blob: 9059eb31e7da4f96ee312fd980dfec139978d96b [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 Silvermanf51499a2020-09-21 12:49:08 -070053namespace aos::logger {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070054namespace {
Austin Schuha36c8902019-12-30 18:07:15 -080055
Austin Schuh05b70472020-01-01 17:11:17 -080056namespace chrono = std::chrono;
57
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070058template <typename T>
59void PrintOptionalOrNull(std::ostream *os, const std::optional<T> &t) {
60 if (t.has_value()) {
61 *os << *t;
62 } else {
63 *os << "null";
64 }
65}
66} // namespace
67
Brian Silvermanf51499a2020-09-21 12:49:08 -070068DetachedBufferWriter::DetachedBufferWriter(
69 std::string_view filename, std::unique_ptr<DetachedBufferEncoder> encoder)
70 : filename_(filename), encoder_(std::move(encoder)) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070071 if (!util::MkdirPIfSpace(filename, 0777)) {
72 ran_out_of_space_ = true;
73 } else {
74 fd_ = open(std::string(filename).c_str(),
75 O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, 0774);
76 if (fd_ == -1 && errno == ENOSPC) {
77 ran_out_of_space_ = true;
78 } else {
Austin Schuh58646e22021-08-23 23:51:46 -070079 PCHECK(fd_ != -1) << ": Failed to open " << this->filename()
80 << " for writing";
81 VLOG(1) << "Opened " << this->filename() << " for writing";
Brian Silvermana9f2ec92020-10-06 18:00:53 -070082 }
83 }
Austin Schuha36c8902019-12-30 18:07:15 -080084}
85
86DetachedBufferWriter::~DetachedBufferWriter() {
Brian Silverman0465fcf2020-09-24 00:29:18 -070087 Close();
88 if (ran_out_of_space_) {
89 CHECK(acknowledge_ran_out_of_space_)
90 << ": Unacknowledged out of disk space, log file was not completed";
Brian Silvermanf51499a2020-09-21 12:49:08 -070091 }
Austin Schuh2f8fd752020-09-01 22:38:28 -070092}
93
Brian Silvermand90905f2020-09-23 14:42:56 -070094DetachedBufferWriter::DetachedBufferWriter(DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070095 *this = std::move(other);
96}
97
Brian Silverman87ac0402020-09-17 14:47:01 -070098// When other is destroyed "soon" (which it should be because we're getting an
99// rvalue reference to it), it will flush etc all the data we have queued up
100// (because that data will then be its data).
Austin Schuh2f8fd752020-09-01 22:38:28 -0700101DetachedBufferWriter &DetachedBufferWriter::operator=(
102 DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700103 std::swap(filename_, other.filename_);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700104 std::swap(encoder_, other.encoder_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700105 std::swap(fd_, other.fd_);
Brian Silverman0465fcf2020-09-24 00:29:18 -0700106 std::swap(ran_out_of_space_, other.ran_out_of_space_);
107 std::swap(acknowledge_ran_out_of_space_, other.acknowledge_ran_out_of_space_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700108 std::swap(iovec_, other.iovec_);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700109 std::swap(max_write_time_, other.max_write_time_);
110 std::swap(max_write_time_bytes_, other.max_write_time_bytes_);
111 std::swap(max_write_time_messages_, other.max_write_time_messages_);
112 std::swap(total_write_time_, other.total_write_time_);
113 std::swap(total_write_count_, other.total_write_count_);
114 std::swap(total_write_messages_, other.total_write_messages_);
115 std::swap(total_write_bytes_, other.total_write_bytes_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700116 return *this;
Austin Schuha36c8902019-12-30 18:07:15 -0800117}
118
Brian Silvermanf51499a2020-09-21 12:49:08 -0700119void DetachedBufferWriter::QueueSpan(absl::Span<const uint8_t> span) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -0700120 if (ran_out_of_space_) {
121 // We don't want any later data to be written after space becomes
122 // available, so refuse to write anything more once we've dropped data
123 // because we ran out of space.
124 VLOG(1) << "Ignoring span: " << span.size();
125 return;
126 }
127
Austin Schuhbd06ae42021-03-31 22:48:21 -0700128 aos::monotonic_clock::time_point now;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700129 if (encoder_->may_bypass() && span.size() > 4096u) {
130 // Over this threshold, we'll assume it's cheaper to add an extra
131 // syscall to write the data immediately instead of copying it to
132 // enqueue.
Austin Schuha36c8902019-12-30 18:07:15 -0800133
Brian Silvermanf51499a2020-09-21 12:49:08 -0700134 // First, flush everything.
135 while (encoder_->queue_size() > 0u) {
136 Flush();
137 }
Austin Schuhde031b72020-01-10 19:34:41 -0800138
Brian Silvermanf51499a2020-09-21 12:49:08 -0700139 // Then, write it directly.
140 const auto start = aos::monotonic_clock::now();
141 const ssize_t written = write(fd_, span.data(), span.size());
142 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700143 HandleWriteReturn(written, span.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700144 UpdateStatsForWrite(end - start, written, 1);
Austin Schuhbd06ae42021-03-31 22:48:21 -0700145 now = end;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700146 } else {
147 encoder_->Encode(CopySpanAsDetachedBuffer(span));
Austin Schuhbd06ae42021-03-31 22:48:21 -0700148 now = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800149 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700150
Austin Schuhbd06ae42021-03-31 22:48:21 -0700151 FlushAtThreshold(now);
Austin Schuha36c8902019-12-30 18:07:15 -0800152}
153
Brian Silverman0465fcf2020-09-24 00:29:18 -0700154void DetachedBufferWriter::Close() {
155 if (fd_ == -1) {
156 return;
157 }
158 encoder_->Finish();
159 while (encoder_->queue_size() > 0) {
160 Flush();
161 }
162 if (close(fd_) == -1) {
163 if (errno == ENOSPC) {
164 ran_out_of_space_ = true;
165 } else {
166 PLOG(ERROR) << "Closing log file failed";
167 }
168 }
169 fd_ = -1;
Austin Schuh58646e22021-08-23 23:51:46 -0700170 VLOG(1) << "Closed " << filename();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700171}
172
Austin Schuha36c8902019-12-30 18:07:15 -0800173void DetachedBufferWriter::Flush() {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700174 if (ran_out_of_space_) {
175 // We don't want any later data to be written after space becomes available,
176 // so refuse to write anything more once we've dropped data because we ran
177 // out of space.
Austin Schuha426f1f2021-03-31 22:27:41 -0700178 if (encoder_) {
179 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
180 encoder_->Clear(encoder_->queue().size());
181 } else {
182 VLOG(1) << "No queue to ignore";
183 }
184 return;
185 }
186
187 const auto queue = encoder_->queue();
188 if (queue.empty()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700189 return;
190 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700191
Austin Schuha36c8902019-12-30 18:07:15 -0800192 iovec_.clear();
Brian Silvermanf51499a2020-09-21 12:49:08 -0700193 const size_t iovec_size = std::min<size_t>(queue.size(), IOV_MAX);
194 iovec_.resize(iovec_size);
Austin Schuha36c8902019-12-30 18:07:15 -0800195 size_t counted_size = 0;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700196 for (size_t i = 0; i < iovec_size; ++i) {
197 iovec_[i].iov_base = const_cast<uint8_t *>(queue[i].data());
198 iovec_[i].iov_len = queue[i].size();
199 counted_size += iovec_[i].iov_len;
Austin Schuha36c8902019-12-30 18:07:15 -0800200 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700201
202 const auto start = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800203 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700204 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700205 HandleWriteReturn(written, counted_size);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700206
207 encoder_->Clear(iovec_size);
208
209 UpdateStatsForWrite(end - start, written, iovec_size);
210}
211
Brian Silverman0465fcf2020-09-24 00:29:18 -0700212void DetachedBufferWriter::HandleWriteReturn(ssize_t write_return,
213 size_t write_size) {
214 if (write_return == -1 && errno == ENOSPC) {
215 ran_out_of_space_ = true;
216 return;
217 }
218 PCHECK(write_return >= 0) << ": write failed";
219 if (write_return < static_cast<ssize_t>(write_size)) {
220 // Sometimes this happens instead of ENOSPC. On a real filesystem, this
221 // never seems to happen in any other case. If we ever want to log to a
222 // socket, this will happen more often. However, until we get there, we'll
223 // just assume it means we ran out of space.
224 ran_out_of_space_ = true;
225 return;
226 }
227}
228
Brian Silvermanf51499a2020-09-21 12:49:08 -0700229void DetachedBufferWriter::UpdateStatsForWrite(
230 aos::monotonic_clock::duration duration, ssize_t written, int iovec_size) {
231 if (duration > max_write_time_) {
232 max_write_time_ = duration;
233 max_write_time_bytes_ = written;
234 max_write_time_messages_ = iovec_size;
235 }
236 total_write_time_ += duration;
237 ++total_write_count_;
238 total_write_messages_ += iovec_size;
239 total_write_bytes_ += written;
240}
241
Austin Schuhbd06ae42021-03-31 22:48:21 -0700242void DetachedBufferWriter::FlushAtThreshold(
243 aos::monotonic_clock::time_point now) {
Austin Schuha426f1f2021-03-31 22:27:41 -0700244 if (ran_out_of_space_) {
245 // We don't want any later data to be written after space becomes available,
246 // so refuse to write anything more once we've dropped data because we ran
247 // out of space.
248 if (encoder_) {
249 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
250 encoder_->Clear(encoder_->queue().size());
251 } else {
252 VLOG(1) << "No queue to ignore";
253 }
254 return;
255 }
256
Austin Schuhbd06ae42021-03-31 22:48:21 -0700257 // We don't want to flush the first time through. Otherwise we will flush as
258 // the log file header might be compressing, defeating any parallelism and
259 // queueing there.
260 if (last_flush_time_ == aos::monotonic_clock::min_time) {
261 last_flush_time_ = now;
262 }
263
Brian Silvermanf51499a2020-09-21 12:49:08 -0700264 // Flush if we are at the max number of iovs per writev, because there's no
265 // point queueing up any more data in memory. Also flush once we have enough
Austin Schuhbd06ae42021-03-31 22:48:21 -0700266 // data queued up or if it has been long enough.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700267 while (encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
Austin Schuhbd06ae42021-03-31 22:48:21 -0700268 encoder_->queue_size() >= IOV_MAX ||
269 now > last_flush_time_ +
270 chrono::duration_cast<chrono::nanoseconds>(
271 chrono::duration<double>(FLAGS_flush_period))) {
272 last_flush_time_ = now;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700273 Flush();
274 }
Austin Schuha36c8902019-12-30 18:07:15 -0800275}
276
277flatbuffers::Offset<MessageHeader> PackMessage(
278 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
279 int channel_index, LogType log_type) {
280 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
281
282 switch (log_type) {
283 case LogType::kLogMessage:
284 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800285 case LogType::kLogRemoteMessage:
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700286 data_offset = fbb->CreateVector(
287 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800288 break;
289
290 case LogType::kLogDeliveryTimeOnly:
291 break;
292 }
293
294 MessageHeader::Builder message_header_builder(*fbb);
295 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800296
297 switch (log_type) {
298 case LogType::kLogRemoteMessage:
299 message_header_builder.add_queue_index(context.remote_queue_index);
300 message_header_builder.add_monotonic_sent_time(
301 context.monotonic_remote_time.time_since_epoch().count());
302 message_header_builder.add_realtime_sent_time(
303 context.realtime_remote_time.time_since_epoch().count());
304 break;
305
306 case LogType::kLogMessage:
307 case LogType::kLogMessageAndDeliveryTime:
308 case LogType::kLogDeliveryTimeOnly:
309 message_header_builder.add_queue_index(context.queue_index);
310 message_header_builder.add_monotonic_sent_time(
311 context.monotonic_event_time.time_since_epoch().count());
312 message_header_builder.add_realtime_sent_time(
313 context.realtime_event_time.time_since_epoch().count());
314 break;
315 }
Austin Schuha36c8902019-12-30 18:07:15 -0800316
317 switch (log_type) {
318 case LogType::kLogMessage:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800319 case LogType::kLogRemoteMessage:
Austin Schuha36c8902019-12-30 18:07:15 -0800320 message_header_builder.add_data(data_offset);
321 break;
322
323 case LogType::kLogMessageAndDeliveryTime:
324 message_header_builder.add_data(data_offset);
325 [[fallthrough]];
326
327 case LogType::kLogDeliveryTimeOnly:
328 message_header_builder.add_monotonic_remote_time(
329 context.monotonic_remote_time.time_since_epoch().count());
330 message_header_builder.add_realtime_remote_time(
331 context.realtime_remote_time.time_since_epoch().count());
332 message_header_builder.add_remote_queue_index(context.remote_queue_index);
333 break;
334 }
335
336 return message_header_builder.Finish();
337}
338
Brian Silvermanf51499a2020-09-21 12:49:08 -0700339SpanReader::SpanReader(std::string_view filename) : filename_(filename) {
Tyler Chatow2015bc62021-08-04 21:15:09 -0700340 decoder_ = std::make_unique<DummyDecoder>(filename);
341
342 static constexpr std::string_view kXz = ".xz";
James Kuszmauldd0a5042021-10-28 23:38:04 -0700343 static constexpr std::string_view kSnappy = SnappyDecoder::kExtension;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700344 if (filename.substr(filename.size() - kXz.size()) == kXz) {
345#if ENABLE_LZMA
Tyler Chatow2015bc62021-08-04 21:15:09 -0700346 decoder_ = std::make_unique<ThreadedLzmaDecoder>(std::move(decoder_));
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700347#else
348 LOG(FATAL) << "Reading xz-compressed files not supported on this platform";
349#endif
James Kuszmauldd0a5042021-10-28 23:38:04 -0700350 } else if (filename.substr(filename.size() - kSnappy.size()) == kSnappy) {
351 decoder_ = std::make_unique<SnappyDecoder>(std::move(decoder_));
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700352 }
Austin Schuh05b70472020-01-01 17:11:17 -0800353}
354
Austin Schuhcf5f6442021-07-06 10:43:28 -0700355absl::Span<const uint8_t> SpanReader::PeekMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -0800356 // Make sure we have enough for the size.
357 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
358 if (!ReadBlock()) {
359 return absl::Span<const uint8_t>();
360 }
361 }
362
363 // Now make sure we have enough for the message.
364 const size_t data_size =
365 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
366 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -0800367 if (data_size == sizeof(flatbuffers::uoffset_t)) {
368 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
369 LOG(ERROR) << " Rest of log file is "
370 << absl::BytesToHexString(std::string_view(
371 reinterpret_cast<const char *>(data_.data() +
372 consumed_data_),
373 data_.size() - consumed_data_));
374 return absl::Span<const uint8_t>();
375 }
Austin Schuh05b70472020-01-01 17:11:17 -0800376 while (data_.size() < consumed_data_ + data_size) {
377 if (!ReadBlock()) {
378 return absl::Span<const uint8_t>();
379 }
380 }
381
382 // And return it, consuming the data.
383 const uint8_t *data_ptr = data_.data() + consumed_data_;
384
Austin Schuh05b70472020-01-01 17:11:17 -0800385 return absl::Span<const uint8_t>(data_ptr, data_size);
386}
387
Austin Schuhcf5f6442021-07-06 10:43:28 -0700388void SpanReader::ConsumeMessage() {
389 consumed_data_ +=
390 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
391 sizeof(flatbuffers::uoffset_t);
392}
393
394absl::Span<const uint8_t> SpanReader::ReadMessage() {
395 absl::Span<const uint8_t> result = PeekMessage();
396 if (result != absl::Span<const uint8_t>()) {
397 ConsumeMessage();
398 }
399 return result;
400}
401
Austin Schuh05b70472020-01-01 17:11:17 -0800402bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700403 // This is the amount of data we grab at a time. Doing larger chunks minimizes
404 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -0800405 constexpr size_t kReadSize = 256 * 1024;
406
407 // Strip off any unused data at the front.
408 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700409 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -0800410 consumed_data_ = 0;
411 }
412
413 const size_t starting_size = data_.size();
414
415 // This should automatically grow the backing store. It won't shrink if we
416 // get a small chunk later. This reduces allocations when we want to append
417 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700418 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -0800419
Brian Silvermanf51499a2020-09-21 12:49:08 -0700420 const size_t count =
421 decoder_->Read(data_.begin() + starting_size, data_.end());
422 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -0800423 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -0800424 return false;
425 }
Austin Schuh05b70472020-01-01 17:11:17 -0800426
427 return true;
428}
429
Austin Schuhadd6eb32020-11-09 21:24:26 -0800430std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh0e8db662021-07-06 10:43:47 -0700431 SpanReader *span_reader) {
432 absl::Span<const uint8_t> config_data = span_reader->ReadMessage();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800433
434 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800435 if (config_data == absl::Span<const uint8_t>()) {
436 return std::nullopt;
437 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800438
Austin Schuh5212cad2020-09-09 23:12:09 -0700439 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -0700440 SizePrefixedFlatbufferVector<LogFileHeader> result(config_data);
Austin Schuhe09beb12020-12-11 20:04:27 -0800441 if (!result.Verify()) {
442 return std::nullopt;
443 }
Austin Schuh0e8db662021-07-06 10:43:47 -0700444
445 if (FLAGS_workaround_double_headers) {
446 while (true) {
447 absl::Span<const uint8_t> maybe_header_data = span_reader->PeekMessage();
448 if (maybe_header_data == absl::Span<const uint8_t>()) {
449 break;
450 }
451
452 aos::SizePrefixedFlatbufferSpan<aos::logger::LogFileHeader> maybe_header(
453 maybe_header_data);
454 if (maybe_header.Verify()) {
455 LOG(WARNING) << "Found duplicate LogFileHeader in "
456 << span_reader->filename();
457 ResizeableBuffer header_data_copy;
458 header_data_copy.resize(maybe_header_data.size());
459 memcpy(header_data_copy.data(), maybe_header_data.begin(),
460 header_data_copy.size());
461 result = SizePrefixedFlatbufferVector<LogFileHeader>(
462 std::move(header_data_copy));
463
464 span_reader->ConsumeMessage();
465 } else {
466 break;
467 }
468 }
469 }
Austin Schuhe09beb12020-12-11 20:04:27 -0800470 return result;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800471}
472
Austin Schuh0e8db662021-07-06 10:43:47 -0700473std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
474 std::string_view filename) {
475 SpanReader span_reader(filename);
476 return ReadHeader(&span_reader);
477}
478
Austin Schuhadd6eb32020-11-09 21:24:26 -0800479std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800480 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -0700481 SpanReader span_reader(filename);
482 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
483 for (size_t i = 0; i < n + 1; ++i) {
484 data_span = span_reader.ReadMessage();
485
486 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800487 if (data_span == absl::Span<const uint8_t>()) {
488 return std::nullopt;
489 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700490 }
491
Brian Silverman354697a2020-09-22 21:06:32 -0700492 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -0700493 SizePrefixedFlatbufferVector<MessageHeader> result(data_span);
Austin Schuhe09beb12020-12-11 20:04:27 -0800494 if (!result.Verify()) {
495 return std::nullopt;
496 }
497 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -0700498}
499
Austin Schuh05b70472020-01-01 17:11:17 -0800500MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -0700501 : span_reader_(filename),
Austin Schuhadd6eb32020-11-09 21:24:26 -0800502 raw_log_file_header_(
503 SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuh0e8db662021-07-06 10:43:47 -0700504 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>>
505 raw_log_file_header = ReadHeader(&span_reader_);
Austin Schuh05b70472020-01-01 17:11:17 -0800506
507 // Make sure something was read.
Austin Schuh0e8db662021-07-06 10:43:47 -0700508 CHECK(raw_log_file_header) << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -0800509
Austin Schuh0e8db662021-07-06 10:43:47 -0700510 raw_log_file_header_ = std::move(*raw_log_file_header);
Austin Schuh05b70472020-01-01 17:11:17 -0800511
Austin Schuh5b728b72021-06-16 14:57:15 -0700512 CHECK(raw_log_file_header_.Verify()) << "Log file header is corrupted";
513
Austin Schuhcde938c2020-02-02 17:30:07 -0800514 max_out_of_order_duration_ =
Austin Schuha040c3f2021-02-13 16:09:07 -0800515 FLAGS_max_out_of_order > 0
516 ? chrono::duration_cast<chrono::nanoseconds>(
517 chrono::duration<double>(FLAGS_max_out_of_order))
518 : chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -0800519
520 VLOG(1) << "Opened " << filename << " as node "
521 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800522}
523
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700524std::shared_ptr<UnpackedMessageHeader> MessageReader::ReadMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -0800525 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
526 if (msg_data == absl::Span<const uint8_t>()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700527 return nullptr;
Austin Schuh05b70472020-01-01 17:11:17 -0800528 }
529
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700530 SizePrefixedFlatbufferSpan<MessageHeader> msg(msg_data);
531 CHECK(msg.Verify()) << ": Corrupted message from " << filename();
Austin Schuh05b70472020-01-01 17:11:17 -0800532
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700533 auto result = UnpackedMessageHeader::MakeMessage(msg.message());
Austin Schuh0e8db662021-07-06 10:43:47 -0700534
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700535 const monotonic_clock::time_point timestamp = result->monotonic_sent_time;
Austin Schuh05b70472020-01-01 17:11:17 -0800536
537 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700538 VLOG(2) << "Read from " << filename() << " data " << FlatbufferToJson(msg);
539 return result;
540}
541
542std::shared_ptr<UnpackedMessageHeader> UnpackedMessageHeader::MakeMessage(
543 const MessageHeader &message) {
544 const size_t data_size = message.has_data() ? message.data()->size() : 0;
545
546 UnpackedMessageHeader *const unpacked_message =
547 reinterpret_cast<UnpackedMessageHeader *>(
548 malloc(sizeof(UnpackedMessageHeader) + data_size +
549 kChannelDataAlignment - 1));
550
551 CHECK(message.has_channel_index());
552 CHECK(message.has_monotonic_sent_time());
553
554 absl::Span<uint8_t> span;
555 if (data_size > 0) {
556 span =
557 absl::Span<uint8_t>(reinterpret_cast<uint8_t *>(RoundChannelData(
558 &unpacked_message->actual_data[0], data_size)),
559 data_size);
560 }
561
562 std::optional<std::chrono::nanoseconds> monotonic_remote_time;
563 if (message.has_monotonic_remote_time()) {
564 monotonic_remote_time =
565 std::chrono::nanoseconds(message.monotonic_remote_time());
566 }
567 std::optional<realtime_clock::time_point> realtime_remote_time;
568 if (message.has_realtime_remote_time()) {
569 realtime_remote_time = realtime_clock::time_point(
570 chrono::nanoseconds(message.realtime_remote_time()));
571 }
572
573 std::optional<uint32_t> remote_queue_index;
574 if (message.has_remote_queue_index()) {
575 remote_queue_index = message.remote_queue_index();
576 }
577
578 new (unpacked_message) UnpackedMessageHeader{
579 .channel_index = message.channel_index(),
580 .monotonic_sent_time = monotonic_clock::time_point(
581 chrono::nanoseconds(message.monotonic_sent_time())),
582 .realtime_sent_time = realtime_clock::time_point(
583 chrono::nanoseconds(message.realtime_sent_time())),
584 .queue_index = message.queue_index(),
585 .monotonic_remote_time = monotonic_remote_time,
586 .realtime_remote_time = realtime_remote_time,
587 .remote_queue_index = remote_queue_index,
588 .monotonic_timestamp_time = monotonic_clock::time_point(
589 std::chrono::nanoseconds(message.monotonic_timestamp_time())),
590 .has_monotonic_timestamp_time = message.has_monotonic_timestamp_time(),
591 .span = span};
592
593 if (data_size > 0) {
594 memcpy(span.data(), message.data()->data(), data_size);
595 }
596
597 return std::shared_ptr<UnpackedMessageHeader>(unpacked_message,
598 &DestroyAndFree);
Austin Schuh05b70472020-01-01 17:11:17 -0800599}
600
Austin Schuhc41603c2020-10-11 16:17:37 -0700601PartsMessageReader::PartsMessageReader(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -0700602 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {
Brian Silvermanfee16972021-09-14 12:06:38 -0700603 if (parts_.parts.size() >= 2) {
604 next_message_reader_.emplace(parts_.parts[1]);
605 }
Austin Schuh48507722021-07-17 17:29:24 -0700606 ComputeBootCounts();
607}
608
609void PartsMessageReader::ComputeBootCounts() {
610 boot_counts_.assign(configuration::NodesCount(parts_.config.get()),
611 std::nullopt);
612
613 // We have 3 vintages of log files with different amounts of information.
614 if (log_file_header()->has_boot_uuids()) {
615 // The new hotness with the boots explicitly listed out. We can use the log
616 // file header to compute the boot count of all relevant nodes.
617 CHECK_EQ(log_file_header()->boot_uuids()->size(), boot_counts_.size());
618 size_t node_index = 0;
619 for (const flatbuffers::String *boot_uuid :
620 *log_file_header()->boot_uuids()) {
621 CHECK(parts_.boots);
622 if (boot_uuid->size() != 0) {
623 auto it = parts_.boots->boot_count_map.find(boot_uuid->str());
624 if (it != parts_.boots->boot_count_map.end()) {
625 boot_counts_[node_index] = it->second;
626 }
627 } else if (parts().boots->boots[node_index].size() == 1u) {
628 boot_counts_[node_index] = 0;
629 }
630 ++node_index;
631 }
632 } else {
633 // Older multi-node logs which are guarenteed to have UUIDs logged, or
634 // single node log files with boot UUIDs in the header. We only know how to
635 // order certain boots in certain circumstances.
636 if (configuration::MultiNode(parts_.config.get()) || parts_.boots) {
637 for (size_t node_index = 0; node_index < boot_counts_.size();
638 ++node_index) {
639 CHECK(parts_.boots);
640 if (parts().boots->boots[node_index].size() == 1u) {
641 boot_counts_[node_index] = 0;
642 }
643 }
644 } else {
645 // Really old single node logs without any UUIDs. They can't reboot.
646 CHECK_EQ(boot_counts_.size(), 1u);
647 boot_counts_[0] = 0u;
648 }
649 }
650}
Austin Schuhc41603c2020-10-11 16:17:37 -0700651
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700652std::shared_ptr<UnpackedMessageHeader> PartsMessageReader::ReadMessage() {
Austin Schuhc41603c2020-10-11 16:17:37 -0700653 while (!done_) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700654 std::shared_ptr<UnpackedMessageHeader> message =
Austin Schuhc41603c2020-10-11 16:17:37 -0700655 message_reader_.ReadMessage();
656 if (message) {
657 newest_timestamp_ = message_reader_.newest_timestamp();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700658 const monotonic_clock::time_point monotonic_sent_time =
659 message->monotonic_sent_time;
660
661 // TODO(austin): Does this work with startup? Might need to use the
662 // start time.
663 // TODO(austin): Does this work with startup when we don't know the
664 // remote start time too? Look at one of those logs to compare.
Austin Schuh315b96b2020-12-11 21:21:12 -0800665 if (monotonic_sent_time >
666 parts_.monotonic_start_time + max_out_of_order_duration()) {
667 after_start_ = true;
668 }
669 if (after_start_) {
Austin Schuhb000de62020-12-03 22:00:40 -0800670 CHECK_GE(monotonic_sent_time,
671 newest_timestamp_ - max_out_of_order_duration())
Austin Schuha040c3f2021-02-13 16:09:07 -0800672 << ": Max out of order of " << max_out_of_order_duration().count()
673 << "ns exceeded. " << parts_ << ", start time is "
Austin Schuh315b96b2020-12-11 21:21:12 -0800674 << parts_.monotonic_start_time << " currently reading "
675 << filename();
Austin Schuhb000de62020-12-03 22:00:40 -0800676 }
Austin Schuhc41603c2020-10-11 16:17:37 -0700677 return message;
678 }
679 NextLog();
680 }
Austin Schuh32f68492020-11-08 21:45:51 -0800681 newest_timestamp_ = monotonic_clock::max_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700682 return nullptr;
Austin Schuhc41603c2020-10-11 16:17:37 -0700683}
684
685void PartsMessageReader::NextLog() {
686 if (next_part_index_ == parts_.parts.size()) {
Brian Silvermanfee16972021-09-14 12:06:38 -0700687 CHECK(!next_message_reader_);
Austin Schuhc41603c2020-10-11 16:17:37 -0700688 done_ = true;
689 return;
690 }
Brian Silvermanfee16972021-09-14 12:06:38 -0700691 CHECK(next_message_reader_);
692 message_reader_ = std::move(*next_message_reader_);
Austin Schuh48507722021-07-17 17:29:24 -0700693 ComputeBootCounts();
Brian Silvermanfee16972021-09-14 12:06:38 -0700694 if (next_part_index_ + 1 < parts_.parts.size()) {
695 next_message_reader_.emplace(parts_.parts[next_part_index_ + 1]);
696 } else {
697 next_message_reader_.reset();
698 }
Austin Schuhc41603c2020-10-11 16:17:37 -0700699 ++next_part_index_;
700}
701
Austin Schuh1be0ce42020-11-29 22:43:26 -0800702bool Message::operator<(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700703 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700704
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700705 if (this->timestamp.time < m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -0800706 return true;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700707 } else if (this->timestamp.time > m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -0800708 return false;
709 }
710
711 if (this->channel_index < m2.channel_index) {
712 return true;
713 } else if (this->channel_index > m2.channel_index) {
714 return false;
715 }
716
717 return this->queue_index < m2.queue_index;
718}
719
720bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800721bool Message::operator==(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700722 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700723
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700724 return timestamp.time == m2.timestamp.time &&
725 channel_index == m2.channel_index && queue_index == m2.queue_index;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800726}
Austin Schuh1be0ce42020-11-29 22:43:26 -0800727
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700728std::ostream &operator<<(std::ostream &os, const UnpackedMessageHeader &m) {
729 os << "{.channel_index=" << m.channel_index
730 << ", .monotonic_sent_time=" << m.monotonic_sent_time
731 << ", .realtime_sent_time=" << m.realtime_sent_time
732 << ", .queue_index=" << m.queue_index;
733 if (m.monotonic_remote_time) {
734 os << ", .monotonic_remote_time=" << m.monotonic_remote_time->count();
735 }
736 os << ", .realtime_remote_time=";
737 PrintOptionalOrNull(&os, m.realtime_remote_time);
738 os << ", .remote_queue_index=";
739 PrintOptionalOrNull(&os, m.remote_queue_index);
740 if (m.has_monotonic_timestamp_time) {
741 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
742 }
743 return os;
744}
745
Austin Schuh1be0ce42020-11-29 22:43:26 -0800746std::ostream &operator<<(std::ostream &os, const Message &m) {
747 os << "{.channel_index=" << m.channel_index
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700748 << ", .queue_index=" << m.queue_index << ", .timestamp=" << m.timestamp;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700749 if (m.data != nullptr) {
Austin Schuhfb1b3292021-11-16 21:20:15 -0800750 os << ", .data=" << m.data;
Austin Schuhd2f96102020-12-01 20:27:29 -0800751 }
752 os << "}";
753 return os;
754}
755
756std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m) {
757 os << "{.channel_index=" << m.channel_index
758 << ", .queue_index=" << m.queue_index
759 << ", .monotonic_event_time=" << m.monotonic_event_time
760 << ", .realtime_event_time=" << m.realtime_event_time;
Austin Schuh58646e22021-08-23 23:51:46 -0700761 if (m.remote_queue_index != BootQueueIndex::Invalid()) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800762 os << ", .remote_queue_index=" << m.remote_queue_index;
763 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700764 if (m.monotonic_remote_time != BootTimestamp::min_time()) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800765 os << ", .monotonic_remote_time=" << m.monotonic_remote_time;
766 }
767 if (m.realtime_remote_time != realtime_clock::min_time) {
768 os << ", .realtime_remote_time=" << m.realtime_remote_time;
769 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700770 if (m.monotonic_timestamp_time != BootTimestamp::min_time()) {
Austin Schuh8bf1e632021-01-02 22:41:04 -0800771 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
772 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700773 if (m.data != nullptr) {
774 os << ", .data=" << *m.data;
Austin Schuhd2f96102020-12-01 20:27:29 -0800775 }
776 os << "}";
Austin Schuh1be0ce42020-11-29 22:43:26 -0800777 return os;
778}
779
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800780LogPartsSorter::LogPartsSorter(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -0700781 : parts_message_reader_(log_parts),
782 source_node_index_(configuration::SourceNodeIndex(parts().config.get())) {
783}
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800784
785Message *LogPartsSorter::Front() {
786 // Queue up data until enough data has been queued that the front message is
787 // sorted enough to be safe to pop. This may do nothing, so we should make
788 // sure the nothing path is checked quickly.
789 if (sorted_until() != monotonic_clock::max_time) {
790 while (true) {
Austin Schuh48507722021-07-17 17:29:24 -0700791 if (!messages_.empty() &&
792 messages_.begin()->timestamp.time < sorted_until() &&
Austin Schuhb000de62020-12-03 22:00:40 -0800793 sorted_until() >= monotonic_start_time()) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800794 break;
795 }
796
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700797 std::shared_ptr<UnpackedMessageHeader> m =
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800798 parts_message_reader_.ReadMessage();
799 // No data left, sorted forever, work through what is left.
800 if (!m) {
801 sorted_until_ = monotonic_clock::max_time;
802 break;
803 }
804
Austin Schuh48507722021-07-17 17:29:24 -0700805 size_t monotonic_timestamp_boot = 0;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700806 if (m->has_monotonic_timestamp_time) {
Austin Schuh48507722021-07-17 17:29:24 -0700807 monotonic_timestamp_boot = parts().logger_boot_count;
808 }
809 size_t monotonic_remote_boot = 0xffffff;
810
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700811 if (m->monotonic_remote_time.has_value()) {
milind-ua50344f2021-08-25 18:22:20 -0700812 const Node *node = parts().config->nodes()->Get(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700813 source_node_index_[m->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -0700814
Austin Schuh48507722021-07-17 17:29:24 -0700815 std::optional<size_t> boot = parts_message_reader_.boot_count(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700816 source_node_index_[m->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -0700817 CHECK(boot) << ": Failed to find boot for node " << MaybeNodeName(node)
818 << ", with index "
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700819 << source_node_index_[m->channel_index];
Austin Schuh48507722021-07-17 17:29:24 -0700820 monotonic_remote_boot = *boot;
821 }
822
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700823 messages_.insert(
824 Message{.channel_index = m->channel_index,
825 .queue_index = BootQueueIndex{.boot = parts().boot_count,
826 .index = m->queue_index},
827 .timestamp = BootTimestamp{.boot = parts().boot_count,
828 .time = m->monotonic_sent_time},
829 .monotonic_remote_boot = monotonic_remote_boot,
830 .monotonic_timestamp_boot = monotonic_timestamp_boot,
831 .data = std::move(m)});
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800832
833 // Now, update sorted_until_ to match the new message.
834 if (parts_message_reader_.newest_timestamp() >
835 monotonic_clock::min_time +
836 parts_message_reader_.max_out_of_order_duration()) {
837 sorted_until_ = parts_message_reader_.newest_timestamp() -
838 parts_message_reader_.max_out_of_order_duration();
839 } else {
840 sorted_until_ = monotonic_clock::min_time;
841 }
842 }
843 }
844
845 // Now that we have enough data queued, return a pointer to the oldest piece
846 // of data if it exists.
847 if (messages_.empty()) {
Austin Schuhb000de62020-12-03 22:00:40 -0800848 last_message_time_ = monotonic_clock::max_time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800849 return nullptr;
850 }
851
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700852 CHECK_GE(messages_.begin()->timestamp.time, last_message_time_)
Austin Schuh315b96b2020-12-11 21:21:12 -0800853 << DebugString() << " reading " << parts_message_reader_.filename();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700854 last_message_time_ = messages_.begin()->timestamp.time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800855 return &(*messages_.begin());
856}
857
858void LogPartsSorter::PopFront() { messages_.erase(messages_.begin()); }
859
860std::string LogPartsSorter::DebugString() const {
861 std::stringstream ss;
862 ss << "messages: [\n";
Austin Schuh315b96b2020-12-11 21:21:12 -0800863 int count = 0;
864 bool no_dots = true;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800865 for (const Message &m : messages_) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800866 if (count < 15 || count > static_cast<int>(messages_.size()) - 15) {
867 ss << m << "\n";
868 } else if (no_dots) {
869 ss << "...\n";
870 no_dots = false;
871 }
872 ++count;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800873 }
874 ss << "] <- " << parts_message_reader_.filename();
875 return ss.str();
876}
877
Austin Schuhd2f96102020-12-01 20:27:29 -0800878NodeMerger::NodeMerger(std::vector<LogParts> parts) {
879 CHECK_GE(parts.size(), 1u);
Austin Schuh715adc12021-06-29 22:07:39 -0700880 // Enforce that we are sorting things only from a single node from a single
881 // boot.
882 const std::string_view part0_node = parts[0].node;
883 const std::string_view part0_source_boot_uuid = parts[0].source_boot_uuid;
Austin Schuhd2f96102020-12-01 20:27:29 -0800884 for (size_t i = 1; i < parts.size(); ++i) {
885 CHECK_EQ(part0_node, parts[i].node) << ": Can't merge different nodes.";
Austin Schuh715adc12021-06-29 22:07:39 -0700886 CHECK_EQ(part0_source_boot_uuid, parts[i].source_boot_uuid)
887 << ": Can't merge different boots.";
Austin Schuhd2f96102020-12-01 20:27:29 -0800888 }
Austin Schuh715adc12021-06-29 22:07:39 -0700889
890 node_ = configuration::GetNodeIndex(parts[0].config.get(), part0_node);
891
Austin Schuhd2f96102020-12-01 20:27:29 -0800892 for (LogParts &part : parts) {
893 parts_sorters_.emplace_back(std::move(part));
894 }
895
Austin Schuhd2f96102020-12-01 20:27:29 -0800896 monotonic_start_time_ = monotonic_clock::max_time;
Austin Schuh9dc42612021-09-20 20:41:29 -0700897 realtime_start_time_ = realtime_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800898 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
Sanjay Narayanan9896c752021-09-01 16:16:48 -0700899 // We want to capture the earliest meaningful start time here. The start
900 // time defaults to min_time when there's no meaningful value to report, so
901 // let's ignore those.
Austin Schuh9dc42612021-09-20 20:41:29 -0700902 if (parts_sorter.monotonic_start_time() != monotonic_clock::min_time) {
903 bool accept = false;
904 // We want to prioritize start times from the logger node. Really, we
905 // want to prioritize start times with a valid realtime_clock time. So,
906 // if we have a start time without a RT clock, prefer a start time with a
907 // RT clock, even it if is later.
908 if (parts_sorter.realtime_start_time() != realtime_clock::min_time) {
909 // We've got a good one. See if the current start time has a good RT
910 // clock, or if we should use this one instead.
911 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
912 accept = true;
913 } else if (realtime_start_time_ == realtime_clock::min_time) {
914 // The previous start time doesn't have a good RT time, so it is very
915 // likely the start time from a remote part file. We just found a
916 // better start time with a real RT time, so switch to that instead.
917 accept = true;
918 }
919 } else if (realtime_start_time_ == realtime_clock::min_time) {
920 // We don't have a RT time, so take the oldest.
921 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
922 accept = true;
923 }
924 }
925
926 if (accept) {
927 monotonic_start_time_ = parts_sorter.monotonic_start_time();
928 realtime_start_time_ = parts_sorter.realtime_start_time();
929 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800930 }
931 }
Sanjay Narayanan9896c752021-09-01 16:16:48 -0700932
933 // If there was no meaningful start time reported, just use min_time.
934 if (monotonic_start_time_ == monotonic_clock::max_time) {
935 monotonic_start_time_ = monotonic_clock::min_time;
936 realtime_start_time_ = realtime_clock::min_time;
937 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800938}
Austin Schuh8f52ed52020-11-30 23:12:39 -0800939
Austin Schuh0ca51f32020-12-25 21:51:45 -0800940std::vector<const LogParts *> NodeMerger::Parts() const {
941 std::vector<const LogParts *> p;
942 p.reserve(parts_sorters_.size());
943 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
944 p.emplace_back(&parts_sorter.parts());
945 }
946 return p;
947}
948
Austin Schuh8f52ed52020-11-30 23:12:39 -0800949Message *NodeMerger::Front() {
950 // Return the current Front if we have one, otherwise go compute one.
951 if (current_ != nullptr) {
Austin Schuhb000de62020-12-03 22:00:40 -0800952 Message *result = current_->Front();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700953 CHECK_GE(result->timestamp.time, last_message_time_);
Austin Schuhb000de62020-12-03 22:00:40 -0800954 return result;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800955 }
956
957 // Otherwise, do a simple search for the oldest message, deduplicating any
958 // duplicates.
959 Message *oldest = nullptr;
960 sorted_until_ = monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800961 for (LogPartsSorter &parts_sorter : parts_sorters_) {
962 Message *m = parts_sorter.Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -0800963 if (!m) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800964 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -0800965 continue;
966 }
967 if (oldest == nullptr || *m < *oldest) {
968 oldest = m;
Austin Schuhd2f96102020-12-01 20:27:29 -0800969 current_ = &parts_sorter;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800970 } else if (*m == *oldest) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700971 // Found a duplicate. If there is a choice, we want the one which has
972 // the timestamp time.
973 if (!m->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -0800974 parts_sorter.PopFront();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700975 } else if (!oldest->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -0800976 current_->PopFront();
977 current_ = &parts_sorter;
978 oldest = m;
979 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700980 CHECK_EQ(m->data->monotonic_timestamp_time,
981 oldest->data->monotonic_timestamp_time);
Austin Schuh8bf1e632021-01-02 22:41:04 -0800982 parts_sorter.PopFront();
983 }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800984 }
985
986 // PopFront may change this, so compute it down here.
Austin Schuhd2f96102020-12-01 20:27:29 -0800987 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -0800988 }
989
Austin Schuhb000de62020-12-03 22:00:40 -0800990 if (oldest) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700991 CHECK_GE(oldest->timestamp.time, last_message_time_);
992 last_message_time_ = oldest->timestamp.time;
Austin Schuhb000de62020-12-03 22:00:40 -0800993 } else {
994 last_message_time_ = monotonic_clock::max_time;
995 }
996
Austin Schuh8f52ed52020-11-30 23:12:39 -0800997 // Return the oldest message found. This will be nullptr if nothing was
998 // found, indicating there is nothing left.
999 return oldest;
1000}
1001
1002void NodeMerger::PopFront() {
1003 CHECK(current_ != nullptr) << "Popping before calling Front()";
1004 current_->PopFront();
1005 current_ = nullptr;
1006}
1007
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001008BootMerger::BootMerger(std::vector<LogParts> files) {
1009 std::vector<std::vector<LogParts>> boots;
1010
1011 // Now, we need to split things out by boot.
1012 for (size_t i = 0; i < files.size(); ++i) {
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001013 const size_t boot_count = files[i].boot_count;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001014 if (boot_count + 1 > boots.size()) {
1015 boots.resize(boot_count + 1);
1016 }
1017 boots[boot_count].emplace_back(std::move(files[i]));
1018 }
1019
1020 node_mergers_.reserve(boots.size());
1021 for (size_t i = 0; i < boots.size(); ++i) {
Austin Schuh48507722021-07-17 17:29:24 -07001022 VLOG(2) << "Boot " << i;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001023 for (auto &p : boots[i]) {
Austin Schuh48507722021-07-17 17:29:24 -07001024 VLOG(2) << "Part " << p;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001025 }
1026 node_mergers_.emplace_back(
1027 std::make_unique<NodeMerger>(std::move(boots[i])));
1028 }
1029}
1030
1031Message *BootMerger::Front() {
1032 Message *result = node_mergers_[index_]->Front();
1033
1034 if (result != nullptr) {
1035 return result;
1036 }
1037
1038 if (index_ + 1u == node_mergers_.size()) {
1039 // At the end of the last node merger, just return.
1040 return nullptr;
1041 } else {
1042 ++index_;
1043 return Front();
1044 }
1045}
1046
1047void BootMerger::PopFront() { node_mergers_[index_]->PopFront(); }
1048
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001049std::vector<const LogParts *> BootMerger::Parts() const {
1050 std::vector<const LogParts *> results;
1051 for (const std::unique_ptr<NodeMerger> &node_merger : node_mergers_) {
1052 std::vector<const LogParts *> node_parts = node_merger->Parts();
1053
1054 results.insert(results.end(), std::make_move_iterator(node_parts.begin()),
1055 std::make_move_iterator(node_parts.end()));
1056 }
1057
1058 return results;
1059}
1060
Austin Schuhd2f96102020-12-01 20:27:29 -08001061TimestampMapper::TimestampMapper(std::vector<LogParts> parts)
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001062 : boot_merger_(std::move(parts)),
Austin Schuh79b30942021-01-24 22:32:21 -08001063 timestamp_callback_([](TimestampedMessage *) {}) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001064 for (const LogParts *part : boot_merger_.Parts()) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001065 if (!configuration_) {
1066 configuration_ = part->config;
1067 } else {
1068 CHECK_EQ(configuration_.get(), part->config.get());
1069 }
1070 }
1071 const Configuration *config = configuration_.get();
Austin Schuhd2f96102020-12-01 20:27:29 -08001072 // Only fill out nodes_data_ if there are nodes. Otherwise everything gets
1073 // pretty simple.
1074 if (configuration::MultiNode(config)) {
1075 nodes_data_.resize(config->nodes()->size());
1076 const Node *my_node = config->nodes()->Get(node());
1077 for (size_t node_index = 0; node_index < nodes_data_.size(); ++node_index) {
1078 const Node *node = config->nodes()->Get(node_index);
1079 NodeData *node_data = &nodes_data_[node_index];
1080 node_data->channels.resize(config->channels()->size());
1081 // We should save the channel if it is delivered to the node represented
1082 // by the NodeData, but not sent by that node. That combo means it is
1083 // forwarded.
1084 size_t channel_index = 0;
1085 node_data->any_delivered = false;
1086 for (const Channel *channel : *config->channels()) {
1087 node_data->channels[channel_index].delivered =
1088 configuration::ChannelIsReadableOnNode(channel, node) &&
Austin Schuhb3dbb6d2021-01-02 17:29:35 -08001089 configuration::ChannelIsSendableOnNode(channel, my_node) &&
1090 (my_node != node);
Austin Schuhd2f96102020-12-01 20:27:29 -08001091 node_data->any_delivered = node_data->any_delivered ||
1092 node_data->channels[channel_index].delivered;
Austin Schuh6a7358f2021-11-18 22:40:40 -08001093 if (node_data->channels[channel_index].delivered) {
1094 const Connection *connection =
1095 configuration::ConnectionToNode(channel, node);
1096 node_data->channels[channel_index].time_to_live =
1097 chrono::nanoseconds(connection->time_to_live());
1098 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001099 ++channel_index;
1100 }
1101 }
1102
1103 for (const Channel *channel : *config->channels()) {
1104 source_node_.emplace_back(configuration::GetNodeIndex(
1105 config, channel->source_node()->string_view()));
1106 }
1107 }
1108}
1109
1110void TimestampMapper::AddPeer(TimestampMapper *timestamp_mapper) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001111 CHECK(configuration::MultiNode(configuration()));
Austin Schuhd2f96102020-12-01 20:27:29 -08001112 CHECK_NE(timestamp_mapper->node(), node());
1113 CHECK_LT(timestamp_mapper->node(), nodes_data_.size());
1114
1115 NodeData *node_data = &nodes_data_[timestamp_mapper->node()];
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001116 // Only set it if this node delivers to the peer timestamp_mapper. Otherwise
Austin Schuhd2f96102020-12-01 20:27:29 -08001117 // we could needlessly save data.
1118 if (node_data->any_delivered) {
Austin Schuh87dd3832021-01-01 23:07:31 -08001119 VLOG(1) << "Registering on node " << node() << " for peer node "
1120 << timestamp_mapper->node();
Austin Schuhd2f96102020-12-01 20:27:29 -08001121 CHECK(timestamp_mapper->nodes_data_[node()].peer == nullptr);
1122
1123 timestamp_mapper->nodes_data_[node()].peer = this;
Austin Schuh36c00932021-07-19 18:13:21 -07001124
1125 node_data->save_for_peer = true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001126 }
1127}
1128
Austin Schuh79b30942021-01-24 22:32:21 -08001129void TimestampMapper::QueueMessage(Message *m) {
1130 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -08001131 .channel_index = m->channel_index,
1132 .queue_index = m->queue_index,
1133 .monotonic_event_time = m->timestamp,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001134 .realtime_event_time = m->data->realtime_sent_time,
Austin Schuh58646e22021-08-23 23:51:46 -07001135 .remote_queue_index = BootQueueIndex::Invalid(),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001136 .monotonic_remote_time = BootTimestamp::min_time(),
Austin Schuhd2f96102020-12-01 20:27:29 -08001137 .realtime_remote_time = realtime_clock::min_time,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001138 .monotonic_timestamp_time = BootTimestamp::min_time(),
Austin Schuh79b30942021-01-24 22:32:21 -08001139 .data = std::move(m->data)});
Austin Schuhd2f96102020-12-01 20:27:29 -08001140}
1141
1142TimestampedMessage *TimestampMapper::Front() {
1143 // No need to fetch anything new. A previous message still exists.
1144 switch (first_message_) {
1145 case FirstMessage::kNeedsUpdate:
1146 break;
1147 case FirstMessage::kInMessage:
Austin Schuh79b30942021-01-24 22:32:21 -08001148 return &matched_messages_.front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001149 case FirstMessage::kNullptr:
1150 return nullptr;
1151 }
1152
Austin Schuh79b30942021-01-24 22:32:21 -08001153 if (matched_messages_.empty()) {
1154 if (!QueueMatched()) {
1155 first_message_ = FirstMessage::kNullptr;
1156 return nullptr;
1157 }
1158 }
1159 first_message_ = FirstMessage::kInMessage;
1160 return &matched_messages_.front();
1161}
1162
1163bool TimestampMapper::QueueMatched() {
Austin Schuhd2f96102020-12-01 20:27:29 -08001164 if (nodes_data_.empty()) {
1165 // Simple path. We are single node, so there are no timestamps to match!
1166 CHECK_EQ(messages_.size(), 0u);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001167 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001168 if (!m) {
Austin Schuh79b30942021-01-24 22:32:21 -08001169 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -08001170 }
Austin Schuh79b30942021-01-24 22:32:21 -08001171 // Enqueue this message into matched_messages_ so we have a place to
1172 // associate remote timestamps, and return it.
1173 QueueMessage(m);
Austin Schuhd2f96102020-12-01 20:27:29 -08001174
Austin Schuh79b30942021-01-24 22:32:21 -08001175 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1176 last_message_time_ = matched_messages_.back().monotonic_event_time;
1177
1178 // We are thin wrapper around node_merger. Call it directly.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001179 boot_merger_.PopFront();
Austin Schuh79b30942021-01-24 22:32:21 -08001180 timestamp_callback_(&matched_messages_.back());
1181 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001182 }
1183
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001184 // We need to only add messages to the list so they get processed for
1185 // messages which are delivered. Reuse the flow below which uses messages_
1186 // by just adding the new message to messages_ and continuing.
Austin Schuhd2f96102020-12-01 20:27:29 -08001187 if (messages_.empty()) {
1188 if (!Queue()) {
1189 // Found nothing to add, we are out of data!
Austin Schuh79b30942021-01-24 22:32:21 -08001190 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -08001191 }
1192
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001193 // Now that it has been added (and cannibalized), forget about it
1194 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001195 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08001196 }
1197
1198 Message *m = &(messages_.front());
1199
1200 if (source_node_[m->channel_index] == node()) {
1201 // From us, just forward it on, filling the remote data in as invalid.
Austin Schuh79b30942021-01-24 22:32:21 -08001202 QueueMessage(m);
1203 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1204 last_message_time_ = matched_messages_.back().monotonic_event_time;
1205 messages_.pop_front();
1206 timestamp_callback_(&matched_messages_.back());
1207 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001208 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001209 // Got a timestamp, find the matching remote data, match it, and return
1210 // it.
Austin Schuhd2f96102020-12-01 20:27:29 -08001211 Message data = MatchingMessageFor(*m);
1212
1213 // Return the data from the remote. The local message only has timestamp
1214 // info which isn't relevant anymore once extracted.
Austin Schuh79b30942021-01-24 22:32:21 -08001215 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -08001216 .channel_index = m->channel_index,
1217 .queue_index = m->queue_index,
1218 .monotonic_event_time = m->timestamp,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001219 .realtime_event_time = m->data->realtime_sent_time,
Austin Schuh58646e22021-08-23 23:51:46 -07001220 .remote_queue_index =
1221 BootQueueIndex{.boot = m->monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001222 .index = m->data->remote_queue_index.value()},
1223 .monotonic_remote_time = {m->monotonic_remote_boot,
1224 monotonic_clock::time_point(
1225 m->data->monotonic_remote_time.value())},
1226 .realtime_remote_time = m->data->realtime_remote_time.value(),
1227 .monotonic_timestamp_time = {m->monotonic_timestamp_boot,
1228 m->data->monotonic_timestamp_time},
Austin Schuh79b30942021-01-24 22:32:21 -08001229 .data = std::move(data.data)});
1230 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1231 last_message_time_ = matched_messages_.back().monotonic_event_time;
1232 // Since messages_ holds the data, drop it.
1233 messages_.pop_front();
1234 timestamp_callback_(&matched_messages_.back());
1235 return true;
1236 }
1237}
1238
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001239void TimestampMapper::QueueUntil(BootTimestamp queue_time) {
Austin Schuh79b30942021-01-24 22:32:21 -08001240 while (last_message_time_ <= queue_time) {
1241 if (!QueueMatched()) {
1242 return;
1243 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001244 }
1245}
1246
Austin Schuhe639ea12021-01-25 13:00:22 -08001247void TimestampMapper::QueueFor(chrono::nanoseconds time_estimation_buffer) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001248 // Note: queueing for time doesn't really work well across boots. So we
1249 // just assume that if you are using this, you only care about the current
1250 // boot.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001251 //
1252 // TODO(austin): Is that the right concept?
1253 //
Austin Schuhe639ea12021-01-25 13:00:22 -08001254 // Make sure we have something queued first. This makes the end time
1255 // calculation simpler, and is typically what folks want regardless.
1256 if (matched_messages_.empty()) {
1257 if (!QueueMatched()) {
1258 return;
1259 }
1260 }
1261
1262 const aos::monotonic_clock::time_point end_queue_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001263 std::max(monotonic_start_time(
1264 matched_messages_.front().monotonic_event_time.boot),
1265 matched_messages_.front().monotonic_event_time.time) +
Austin Schuhe639ea12021-01-25 13:00:22 -08001266 time_estimation_buffer;
1267
1268 // Place sorted messages on the list until we have
1269 // --time_estimation_buffer_seconds seconds queued up (but queue at least
1270 // until the log starts).
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001271 while (end_queue_time >= last_message_time_.time) {
Austin Schuhe639ea12021-01-25 13:00:22 -08001272 if (!QueueMatched()) {
1273 return;
1274 }
1275 }
1276}
1277
Austin Schuhd2f96102020-12-01 20:27:29 -08001278void TimestampMapper::PopFront() {
1279 CHECK(first_message_ != FirstMessage::kNeedsUpdate);
Austin Schuh6a7358f2021-11-18 22:40:40 -08001280 last_popped_message_time_ = Front()->monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001281 first_message_ = FirstMessage::kNeedsUpdate;
1282
Austin Schuh79b30942021-01-24 22:32:21 -08001283 matched_messages_.pop_front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001284}
1285
1286Message TimestampMapper::MatchingMessageFor(const Message &message) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001287 // Figure out what queue index we are looking for.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001288 CHECK_NOTNULL(message.data);
1289 CHECK(message.data->remote_queue_index.has_value());
Austin Schuh58646e22021-08-23 23:51:46 -07001290 const BootQueueIndex remote_queue_index =
1291 BootQueueIndex{.boot = message.monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001292 .index = *message.data->remote_queue_index};
Austin Schuhd2f96102020-12-01 20:27:29 -08001293
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001294 CHECK(message.data->monotonic_remote_time.has_value());
1295 CHECK(message.data->realtime_remote_time.has_value());
Austin Schuhd2f96102020-12-01 20:27:29 -08001296
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001297 const BootTimestamp monotonic_remote_time{
Austin Schuh48507722021-07-17 17:29:24 -07001298 .boot = message.monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001299 .time = monotonic_clock::time_point(
1300 message.data->monotonic_remote_time.value())};
1301 const realtime_clock::time_point realtime_remote_time =
1302 *message.data->realtime_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001303
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001304 TimestampMapper *peer =
1305 nodes_data_[source_node_[message.data->channel_index]].peer;
Austin Schuhfecf1d82020-12-19 16:57:28 -08001306
1307 // We only register the peers which we have data for. So, if we are being
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001308 // asked to pull a timestamp from a peer which doesn't exist, return an
1309 // empty message.
Austin Schuhfecf1d82020-12-19 16:57:28 -08001310 if (peer == nullptr) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001311 // TODO(austin): Make sure the tests hit all these paths with a boot count
1312 // of 1...
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001313 return Message{.channel_index = message.channel_index,
1314 .queue_index = remote_queue_index,
1315 .timestamp = monotonic_remote_time,
1316 .monotonic_remote_boot = 0xffffff,
1317 .monotonic_timestamp_boot = 0xffffff,
1318 .data = nullptr};
Austin Schuhfecf1d82020-12-19 16:57:28 -08001319 }
1320
1321 // The queue which will have the matching data, if available.
1322 std::deque<Message> *data_queue =
1323 &peer->nodes_data_[node()].channels[message.channel_index].messages;
1324
Austin Schuh79b30942021-01-24 22:32:21 -08001325 peer->QueueUnmatchedUntil(monotonic_remote_time);
Austin Schuhd2f96102020-12-01 20:27:29 -08001326
1327 if (data_queue->empty()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001328 return Message{.channel_index = message.channel_index,
1329 .queue_index = remote_queue_index,
1330 .timestamp = monotonic_remote_time,
1331 .monotonic_remote_boot = 0xffffff,
1332 .monotonic_timestamp_boot = 0xffffff,
1333 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08001334 }
1335
Austin Schuhd2f96102020-12-01 20:27:29 -08001336 if (remote_queue_index < data_queue->front().queue_index ||
1337 remote_queue_index > data_queue->back().queue_index) {
1338 return Message{
1339 .channel_index = message.channel_index,
1340 .queue_index = remote_queue_index,
1341 .timestamp = monotonic_remote_time,
Austin Schuh48507722021-07-17 17:29:24 -07001342 .monotonic_remote_boot = 0xffffff,
1343 .monotonic_timestamp_boot = 0xffffff,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001344 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08001345 }
1346
Austin Schuh993ccb52020-12-12 15:59:32 -08001347 // The algorithm below is constant time with some assumptions. We need there
1348 // to be no missing messages in the data stream. This also assumes a queue
1349 // hasn't wrapped. That is conservative, but should let us get started.
Austin Schuh58646e22021-08-23 23:51:46 -07001350 if (data_queue->back().queue_index.boot ==
1351 data_queue->front().queue_index.boot &&
1352 (data_queue->back().queue_index.index -
1353 data_queue->front().queue_index.index + 1u ==
1354 data_queue->size())) {
1355 CHECK_EQ(remote_queue_index.boot, data_queue->front().queue_index.boot);
Austin Schuh993ccb52020-12-12 15:59:32 -08001356 // Pull the data out and confirm that the timestamps match as expected.
Austin Schuh58646e22021-08-23 23:51:46 -07001357 //
1358 // TODO(austin): Move if not reliable.
1359 Message result = (*data_queue)[remote_queue_index.index -
1360 data_queue->front().queue_index.index];
Austin Schuh993ccb52020-12-12 15:59:32 -08001361
1362 CHECK_EQ(result.timestamp, monotonic_remote_time)
1363 << ": Queue index matches, but timestamp doesn't. Please investigate!";
Austin Schuh6a7358f2021-11-18 22:40:40 -08001364 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
Austin Schuh993ccb52020-12-12 15:59:32 -08001365 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1366 // Now drop the data off the front. We have deduplicated timestamps, so we
1367 // are done. And all the data is in order.
Austin Schuh58646e22021-08-23 23:51:46 -07001368 data_queue->erase(
1369 data_queue->begin(),
1370 data_queue->begin() +
1371 (remote_queue_index.index - data_queue->front().queue_index.index));
Austin Schuh993ccb52020-12-12 15:59:32 -08001372 return result;
1373 } else {
Austin Schuh58646e22021-08-23 23:51:46 -07001374 // TODO(austin): Binary search.
1375 auto it = std::find_if(
1376 data_queue->begin(), data_queue->end(),
1377 [remote_queue_index,
1378 remote_boot = monotonic_remote_time.boot](const Message &m) {
1379 return m.queue_index == remote_queue_index &&
1380 m.timestamp.boot == remote_boot;
1381 });
Austin Schuh993ccb52020-12-12 15:59:32 -08001382 if (it == data_queue->end()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001383 return Message{.channel_index = message.channel_index,
1384 .queue_index = remote_queue_index,
1385 .timestamp = monotonic_remote_time,
1386 .monotonic_remote_boot = 0xffffff,
1387 .monotonic_timestamp_boot = 0xffffff,
1388 .data = nullptr};
Austin Schuh993ccb52020-12-12 15:59:32 -08001389 }
1390
1391 Message result = std::move(*it);
1392
1393 CHECK_EQ(result.timestamp, monotonic_remote_time)
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001394 << ": Queue index matches, but timestamp doesn't. Please "
1395 "investigate!";
1396 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
1397 << ": Queue index matches, but timestamp doesn't. Please "
1398 "investigate!";
Austin Schuh993ccb52020-12-12 15:59:32 -08001399
Austin Schuh58646e22021-08-23 23:51:46 -07001400 // TODO(austin): We still go in order, so we can erase from the beginning to
1401 // our iterator minus 1. That'll keep 1 in the queue.
Austin Schuh993ccb52020-12-12 15:59:32 -08001402 data_queue->erase(it);
1403
1404 return result;
1405 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001406}
1407
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001408void TimestampMapper::QueueUnmatchedUntil(BootTimestamp t) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001409 if (queued_until_ > t) {
1410 return;
1411 }
1412 while (true) {
1413 if (!messages_.empty() && messages_.back().timestamp > t) {
1414 queued_until_ = std::max(queued_until_, messages_.back().timestamp);
1415 return;
1416 }
1417
1418 if (!Queue()) {
1419 // Found nothing to add, we are out of data!
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001420 queued_until_ = BootTimestamp::max_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08001421 return;
1422 }
1423
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001424 // Now that it has been added (and cannibalized), forget about it
1425 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001426 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08001427 }
1428}
1429
1430bool TimestampMapper::Queue() {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001431 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001432 if (m == nullptr) {
1433 return false;
1434 }
1435 for (NodeData &node_data : nodes_data_) {
1436 if (!node_data.any_delivered) continue;
Austin Schuh36c00932021-07-19 18:13:21 -07001437 if (!node_data.save_for_peer) continue;
Austin Schuhd2f96102020-12-01 20:27:29 -08001438 if (node_data.channels[m->channel_index].delivered) {
Austin Schuh6a7358f2021-11-18 22:40:40 -08001439 // If we have data but no timestamps (logs where the timestamps didn't get
1440 // logged are classic), we can grow this indefinitely. We don't need to
1441 // keep anything that is older than the last message returned.
1442
1443 // We have the time on the source node.
1444 // We care to wait until we have the time on the destination node.
1445 std::deque<Message> &messages =
1446 node_data.channels[m->channel_index].messages;
1447 // Max delay over the network is the TTL, so let's take the queue time and
1448 // add TTL to it. Don't forget any messages which are reliable until
1449 // someone can come up with a good reason to forget those too.
1450 if (node_data.channels[m->channel_index].time_to_live >
1451 chrono::nanoseconds(0)) {
1452 // We need to make *some* assumptions about network delay for this to
1453 // work. We want to only look at the RX side. This means we need to
1454 // track the last time a message was popped from any channel from the
1455 // node sending this message, and compare that to the max time we expect
1456 // that a message will take to be delivered across the network. This
1457 // assumes that messages are popped in time order as a proxy for
1458 // measuring the distributed time at this layer.
1459 //
1460 // Leave at least 1 message in here so we can handle reboots and
1461 // messages getting sent twice.
1462 while (messages.size() > 1u &&
1463 messages.begin()->timestamp +
1464 node_data.channels[m->channel_index].time_to_live +
1465 chrono::duration_cast<chrono::nanoseconds>(
1466 chrono::duration<double>(FLAGS_max_network_delay)) <
1467 last_popped_message_time_) {
1468 messages.pop_front();
1469 }
1470 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001471 node_data.channels[m->channel_index].messages.emplace_back(*m);
1472 }
1473 }
1474
1475 messages_.emplace_back(std::move(*m));
1476 return true;
1477}
1478
1479std::string TimestampMapper::DebugString() const {
1480 std::stringstream ss;
Austin Schuh6e014b82021-09-14 17:46:33 -07001481 ss << "node " << node() << " (" << node_name() << ") [\n";
Austin Schuhd2f96102020-12-01 20:27:29 -08001482 for (const Message &message : messages_) {
1483 ss << " " << message << "\n";
1484 }
1485 ss << "] queued_until " << queued_until_;
1486 for (const NodeData &ns : nodes_data_) {
1487 if (ns.peer == nullptr) continue;
1488 ss << "\nnode " << ns.peer->node() << " remote_data [\n";
1489 size_t channel_index = 0;
1490 for (const NodeData::ChannelData &channel_data :
1491 ns.peer->nodes_data_[node()].channels) {
1492 if (channel_data.messages.empty()) {
1493 continue;
1494 }
Austin Schuhb000de62020-12-03 22:00:40 -08001495
Austin Schuhd2f96102020-12-01 20:27:29 -08001496 ss << " channel " << channel_index << " [\n";
1497 for (const Message &m : channel_data.messages) {
1498 ss << " " << m << "\n";
1499 }
1500 ss << " ]\n";
1501 ++channel_index;
1502 }
1503 ss << "] queued_until " << ns.peer->queued_until_;
1504 }
1505 return ss.str();
1506}
1507
Austin Schuhee711052020-08-24 16:06:09 -07001508std::string MaybeNodeName(const Node *node) {
1509 if (node != nullptr) {
1510 return node->name()->str() + " ";
1511 }
1512 return "";
1513}
1514
Brian Silvermanf51499a2020-09-21 12:49:08 -07001515} // namespace aos::logger