blob: 551e69d27e4f0b21cff143f01c56577962e2f9fa [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>
Alexei Strots01395492023-03-20 13:59:56 -070010#include <filesystem>
Austin Schuha36c8902019-12-30 18:07:15 -080011
Austin Schuhe4fca832020-03-07 16:58:53 -080012#include "absl/strings/escaping.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070013#include "flatbuffers/flatbuffers.h"
14#include "gflags/gflags.h"
15#include "glog/logging.h"
16
Austin Schuh05b70472020-01-01 17:11:17 -080017#include "aos/configuration.h"
James Kuszmauldd0a5042021-10-28 23:38:04 -070018#include "aos/events/logging/snappy_encoder.h"
Austin Schuhfa895892020-01-07 20:07:41 -080019#include "aos/flatbuffer_merge.h"
Austin Schuh6f3babe2020-01-26 20:34:50 -080020#include "aos/util/file.h"
Austin Schuha36c8902019-12-30 18:07:15 -080021
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070022#if defined(__x86_64__)
Tyler Chatow2015bc62021-08-04 21:15:09 -070023#define ENABLE_LZMA (!__has_feature(memory_sanitizer))
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070024#elif defined(__aarch64__)
Tyler Chatow2015bc62021-08-04 21:15:09 -070025#define ENABLE_LZMA (!__has_feature(memory_sanitizer))
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070026#else
27#define ENABLE_LZMA 0
28#endif
29
30#if ENABLE_LZMA
31#include "aos/events/logging/lzma_encoder.h"
32#endif
Austin Schuh86110712022-09-16 15:40:54 -070033#if ENABLE_S3
34#include "aos/events/logging/s3_fetcher.h"
35#endif
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070036
Austin Schuh48d10d62022-10-16 22:19:23 -070037DEFINE_int32(flush_size, 128 * 1024,
Austin Schuha36c8902019-12-30 18:07:15 -080038 "Number of outstanding bytes to allow before flushing to disk.");
Austin Schuhbd06ae42021-03-31 22:48:21 -070039DEFINE_double(
40 flush_period, 5.0,
41 "Max time to let data sit in the queue before flushing in seconds.");
Austin Schuha36c8902019-12-30 18:07:15 -080042
Austin Schuha040c3f2021-02-13 16:09:07 -080043DEFINE_double(
Austin Schuh6a7358f2021-11-18 22:40:40 -080044 max_network_delay, 1.0,
45 "Max time to assume a message takes to cross the network before we are "
46 "willing to drop it from our buffers and assume it didn't make it. "
47 "Increasing this number can increase memory usage depending on the packet "
48 "loss of your network or if the timestamps aren't logged for a message.");
49
50DEFINE_double(
Austin Schuha040c3f2021-02-13 16:09:07 -080051 max_out_of_order, -1,
52 "If set, this overrides the max out of order duration for a log file.");
53
Austin Schuh0e8db662021-07-06 10:43:47 -070054DEFINE_bool(workaround_double_headers, true,
55 "Some old log files have two headers at the beginning. Use the "
56 "last header as the actual header.");
57
Brian Smarttea913d42021-12-10 15:02:38 -080058DEFINE_bool(crash_on_corrupt_message, true,
59 "When true, MessageReader will crash the first time a message "
60 "with corrupted format is found. When false, the crash will be "
61 "suppressed, and any remaining readable messages will be "
62 "evaluated to present verified vs corrupted stats.");
63
64DEFINE_bool(ignore_corrupt_messages, false,
65 "When true, and crash_on_corrupt_message is false, then any "
66 "corrupt message found by MessageReader be silently ignored, "
67 "providing access to all uncorrupted messages in a logfile.");
68
Alexei Strotsa3194712023-04-21 23:30:50 -070069DECLARE_bool(quiet_sorting);
70
Brian Silvermanf51499a2020-09-21 12:49:08 -070071namespace aos::logger {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070072namespace {
Austin Schuh05b70472020-01-01 17:11:17 -080073namespace chrono = std::chrono;
74
Alexei Strotscee7b372023-04-21 11:57:54 -070075std::unique_ptr<DataDecoder> ResolveDecoder(std::string_view filename,
76 bool quiet) {
77 static constexpr std::string_view kS3 = "s3:";
78
79 std::unique_ptr<DataDecoder> decoder;
80
81 if (filename.substr(0, kS3.size()) == kS3) {
82#if ENABLE_S3
83 decoder = std::make_unique<S3Fetcher>(filename);
84#else
85 LOG(FATAL) << "Reading files from S3 not supported on this platform";
86#endif
87 } else {
88 decoder = std::make_unique<DummyDecoder>(filename);
89 }
90
91 static constexpr std::string_view kXz = ".xz";
92 static constexpr std::string_view kSnappy = SnappyDecoder::kExtension;
93 if (filename.substr(filename.size() - kXz.size()) == kXz) {
94#if ENABLE_LZMA
95 decoder = std::make_unique<ThreadedLzmaDecoder>(std::move(decoder), quiet);
96#else
97 (void)quiet;
98 LOG(FATAL) << "Reading xz-compressed files not supported on this platform";
99#endif
100 } else if (filename.substr(filename.size() - kSnappy.size()) == kSnappy) {
101 decoder = std::make_unique<SnappyDecoder>(std::move(decoder));
102 }
103 return decoder;
104}
105
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700106template <typename T>
107void PrintOptionalOrNull(std::ostream *os, const std::optional<T> &t) {
108 if (t.has_value()) {
109 *os << *t;
110 } else {
111 *os << "null";
112 }
113}
Philipp Schrader10397952023-06-15 11:43:07 -0700114
115// A dummy LogSink implementation that handles the special case when we create
116// a DetachedBufferWriter when there's no space left on the system. The
117// DetachedBufferWriter frequently dereferences log_sink_, so we want a class
118// here that effectively refuses to do anything meaningful.
119class OutOfDiskSpaceLogSink : public LogSink {
120 public:
121 WriteCode OpenForWrite() override { return WriteCode::kOutOfSpace; }
122 WriteCode Close() override { return WriteCode::kOk; }
123 bool is_open() const override { return false; }
124 WriteResult Write(
125 const absl::Span<const absl::Span<const uint8_t>> &) override {
126 return WriteResult{
127 .code = WriteCode::kOutOfSpace,
128 .messages_written = 0,
129 };
130 }
131 std::string_view name() const override { return "<out_of_disk_space>"; }
132};
133
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700134} // namespace
135
Alexei Strotsbc082d82023-05-03 08:43:42 -0700136DetachedBufferWriter::DetachedBufferWriter(std::unique_ptr<LogSink> log_sink,
137 std::unique_ptr<DataEncoder> encoder)
138 : log_sink_(std::move(log_sink)), encoder_(std::move(encoder)) {
139 CHECK(log_sink_);
140 ran_out_of_space_ = log_sink_->OpenForWrite() == WriteCode::kOutOfSpace;
Alexei Strots01395492023-03-20 13:59:56 -0700141 if (ran_out_of_space_) {
142 LOG(WARNING) << "And we are out of space";
Austin Schuh4c3cdb72023-02-11 15:05:26 -0800143 }
144}
145
Philipp Schrader10397952023-06-15 11:43:07 -0700146DetachedBufferWriter::DetachedBufferWriter(already_out_of_space_t)
147 : DetachedBufferWriter(std::make_unique<OutOfDiskSpaceLogSink>(), nullptr) {
148}
149
Austin Schuha36c8902019-12-30 18:07:15 -0800150DetachedBufferWriter::~DetachedBufferWriter() {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700151 Close();
152 if (ran_out_of_space_) {
153 CHECK(acknowledge_ran_out_of_space_)
154 << ": Unacknowledged out of disk space, log file was not completed";
Brian Silvermanf51499a2020-09-21 12:49:08 -0700155 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700156}
157
Brian Silvermand90905f2020-09-23 14:42:56 -0700158DetachedBufferWriter::DetachedBufferWriter(DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700159 *this = std::move(other);
160}
161
Brian Silverman87ac0402020-09-17 14:47:01 -0700162// When other is destroyed "soon" (which it should be because we're getting an
163// rvalue reference to it), it will flush etc all the data we have queued up
164// (because that data will then be its data).
Austin Schuh2f8fd752020-09-01 22:38:28 -0700165DetachedBufferWriter &DetachedBufferWriter::operator=(
166 DetachedBufferWriter &&other) {
Alexei Strotsbc082d82023-05-03 08:43:42 -0700167 std::swap(log_sink_, other.log_sink_);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700168 std::swap(encoder_, other.encoder_);
Brian Silverman0465fcf2020-09-24 00:29:18 -0700169 std::swap(ran_out_of_space_, other.ran_out_of_space_);
170 std::swap(acknowledge_ran_out_of_space_, other.acknowledge_ran_out_of_space_);
Austin Schuh4c3cdb72023-02-11 15:05:26 -0800171 std::swap(last_flush_time_, other.last_flush_time_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700172 return *this;
Austin Schuha36c8902019-12-30 18:07:15 -0800173}
174
Austin Schuh8bdfc492023-02-11 12:53:13 -0800175void DetachedBufferWriter::CopyMessage(DataEncoder::Copier *copier,
Austin Schuh7ef11a42023-02-04 17:15:12 -0800176 aos::monotonic_clock::time_point now) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -0700177 if (ran_out_of_space_) {
178 // We don't want any later data to be written after space becomes
179 // available, so refuse to write anything more once we've dropped data
180 // because we ran out of space.
Austin Schuh48d10d62022-10-16 22:19:23 -0700181 return;
Austin Schuha36c8902019-12-30 18:07:15 -0800182 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700183
Austin Schuh8bdfc492023-02-11 12:53:13 -0800184 const size_t message_size = copier->size();
185 size_t overall_bytes_written = 0;
Austin Schuh48d10d62022-10-16 22:19:23 -0700186
Austin Schuh8bdfc492023-02-11 12:53:13 -0800187 // Keep writing chunks until we've written it all. If we end up with a
188 // partial write, this means we need to flush to disk.
189 do {
Alexei Strots01395492023-03-20 13:59:56 -0700190 const size_t bytes_written =
191 encoder_->Encode(copier, overall_bytes_written);
Austin Schuh8bdfc492023-02-11 12:53:13 -0800192 CHECK(bytes_written != 0);
193
194 overall_bytes_written += bytes_written;
195 if (overall_bytes_written < message_size) {
196 VLOG(1) << "Flushing because of a partial write, tried to write "
197 << message_size << " wrote " << overall_bytes_written;
198 Flush(now);
199 }
200 } while (overall_bytes_written < message_size);
201
Austin Schuhbd06ae42021-03-31 22:48:21 -0700202 FlushAtThreshold(now);
Austin Schuha36c8902019-12-30 18:07:15 -0800203}
204
Brian Silverman0465fcf2020-09-24 00:29:18 -0700205void DetachedBufferWriter::Close() {
Alexei Strotsbc082d82023-05-03 08:43:42 -0700206 if (!log_sink_->is_open()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700207 return;
208 }
209 encoder_->Finish();
210 while (encoder_->queue_size() > 0) {
Austin Schuh8bdfc492023-02-11 12:53:13 -0800211 Flush(monotonic_clock::max_time);
Brian Silverman0465fcf2020-09-24 00:29:18 -0700212 }
Austin Schuhb2461652023-05-01 08:30:56 -0700213 encoder_.reset();
Alexei Strotsbc082d82023-05-03 08:43:42 -0700214 ran_out_of_space_ = log_sink_->Close() == WriteCode::kOutOfSpace;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700215}
216
Austin Schuh8bdfc492023-02-11 12:53:13 -0800217void DetachedBufferWriter::Flush(aos::monotonic_clock::time_point now) {
218 last_flush_time_ = now;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700219 if (ran_out_of_space_) {
220 // We don't want any later data to be written after space becomes available,
221 // so refuse to write anything more once we've dropped data because we ran
222 // out of space.
Austin Schuha426f1f2021-03-31 22:27:41 -0700223 if (encoder_) {
224 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
225 encoder_->Clear(encoder_->queue().size());
226 } else {
227 VLOG(1) << "No queue to ignore";
228 }
229 return;
230 }
231
232 const auto queue = encoder_->queue();
233 if (queue.empty()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700234 return;
235 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700236
Alexei Strotsbc082d82023-05-03 08:43:42 -0700237 const WriteResult result = log_sink_->Write(queue);
Alexei Strots01395492023-03-20 13:59:56 -0700238 encoder_->Clear(result.messages_written);
239 ran_out_of_space_ = result.code == WriteCode::kOutOfSpace;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700240}
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.
Austin Schuh8bdfc492023-02-11 12:53:13 -0800267 while (encoder_->space() == 0 ||
268 encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
Austin Schuhbd06ae42021-03-31 22:48:21 -0700269 encoder_->queue_size() >= IOV_MAX ||
Austin Schuh3ebaf782023-04-07 16:03:28 -0700270 (now > last_flush_time_ +
271 chrono::duration_cast<chrono::nanoseconds>(
272 chrono::duration<double>(FLAGS_flush_period)) &&
273 encoder_->queued_bytes() != 0)) {
274 VLOG(1) << "Chose to flush at " << now << ", last " << last_flush_time_
275 << " queued bytes " << encoder_->queued_bytes();
Austin Schuh8bdfc492023-02-11 12:53:13 -0800276 Flush(now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700277 }
Austin Schuha36c8902019-12-30 18:07:15 -0800278}
279
Austin Schuhf2d0e682022-10-16 14:20:58 -0700280// Do the magic dance to convert the endianness of the data and append it to the
281// buffer.
282namespace {
283
284// TODO(austin): Look at the generated code to see if building the header is
285// efficient or not.
286template <typename T>
287uint8_t *Push(uint8_t *buffer, const T data) {
288 const T endian_data = flatbuffers::EndianScalar<T>(data);
289 std::memcpy(buffer, &endian_data, sizeof(T));
290 return buffer + sizeof(T);
291}
292
293uint8_t *PushBytes(uint8_t *buffer, const void *data, size_t size) {
294 std::memcpy(buffer, data, size);
295 return buffer + size;
296}
297
298uint8_t *Pad(uint8_t *buffer, size_t padding) {
299 std::memset(buffer, 0, padding);
300 return buffer + padding;
301}
302} // namespace
303
304flatbuffers::Offset<MessageHeader> PackRemoteMessage(
305 flatbuffers::FlatBufferBuilder *fbb,
306 const message_bridge::RemoteMessage *msg, int channel_index,
307 const aos::monotonic_clock::time_point monotonic_timestamp_time) {
308 logger::MessageHeader::Builder message_header_builder(*fbb);
309 // Note: this must match the same order as MessageBridgeServer and
310 // PackMessage. We want identical headers to have identical
311 // on-the-wire formats to make comparing them easier.
312
313 message_header_builder.add_channel_index(channel_index);
314
315 message_header_builder.add_queue_index(msg->queue_index());
316 message_header_builder.add_monotonic_sent_time(msg->monotonic_sent_time());
317 message_header_builder.add_realtime_sent_time(msg->realtime_sent_time());
318
319 message_header_builder.add_monotonic_remote_time(
320 msg->monotonic_remote_time());
321 message_header_builder.add_realtime_remote_time(msg->realtime_remote_time());
322 message_header_builder.add_remote_queue_index(msg->remote_queue_index());
323
324 message_header_builder.add_monotonic_timestamp_time(
325 monotonic_timestamp_time.time_since_epoch().count());
326
327 return message_header_builder.Finish();
328}
329
330size_t PackRemoteMessageInline(
331 uint8_t *buffer, const message_bridge::RemoteMessage *msg,
332 int channel_index,
Austin Schuh71a40d42023-02-04 21:22:22 -0800333 const aos::monotonic_clock::time_point monotonic_timestamp_time,
334 size_t start_byte, size_t end_byte) {
Austin Schuhf2d0e682022-10-16 14:20:58 -0700335 const flatbuffers::uoffset_t message_size = PackRemoteMessageSize();
Austin Schuh71a40d42023-02-04 21:22:22 -0800336 DCHECK_EQ((start_byte % 8u), 0u);
337 DCHECK_EQ((end_byte % 8u), 0u);
338 DCHECK_LE(start_byte, end_byte);
339 DCHECK_LE(end_byte, message_size);
Austin Schuhf2d0e682022-10-16 14:20:58 -0700340
Austin Schuh71a40d42023-02-04 21:22:22 -0800341 switch (start_byte) {
342 case 0x00u:
343 if ((end_byte) == 0x00u) {
344 break;
345 }
346 // clang-format off
347 // header:
348 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
349 buffer = Push<flatbuffers::uoffset_t>(
350 buffer, message_size - sizeof(flatbuffers::uoffset_t));
351 // +0x04 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: +0x24 | offset to root table `aos.logger.MessageHeader`
352 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x20);
353 [[fallthrough]];
354 case 0x08u:
355 if ((end_byte) == 0x08u) {
356 break;
357 }
358 //
359 // padding:
360 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
361 buffer = Pad(buffer, 6);
362 //
363 // vtable (aos.logger.MessageHeader):
364 // +0x0E | 16 00 | uint16_t | 0x0016 (22) | size of this vtable
365 buffer = Push<flatbuffers::voffset_t>(buffer, 0x16);
366 [[fallthrough]];
367 case 0x10u:
368 if ((end_byte) == 0x10u) {
369 break;
370 }
371 // +0x10 | 3C 00 | uint16_t | 0x003C (60) | size of referring table
372 buffer = Push<flatbuffers::voffset_t>(buffer, 0x3c);
373 // +0x12 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `channel_index` (id: 0)
374 buffer = Push<flatbuffers::voffset_t>(buffer, 0x38);
375 // +0x14 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `monotonic_sent_time` (id: 1)
376 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
377 // +0x16 | 24 00 | VOffset16 | 0x0024 (36) | offset to field `realtime_sent_time` (id: 2)
378 buffer = Push<flatbuffers::voffset_t>(buffer, 0x24);
379 [[fallthrough]];
380 case 0x18u:
381 if ((end_byte) == 0x18u) {
382 break;
383 }
384 // +0x18 | 34 00 | VOffset16 | 0x0034 (52) | offset to field `queue_index` (id: 3)
385 buffer = Push<flatbuffers::voffset_t>(buffer, 0x34);
386 // +0x1A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `data` (id: 4) <null> (Vector)
387 buffer = Push<flatbuffers::voffset_t>(buffer, 0x00);
388 // +0x1C | 1C 00 | VOffset16 | 0x001C (28) | offset to field `monotonic_remote_time` (id: 5)
389 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
390 // +0x1E | 14 00 | VOffset16 | 0x0014 (20) | offset to field `realtime_remote_time` (id: 6)
391 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
392 [[fallthrough]];
393 case 0x20u:
394 if ((end_byte) == 0x20u) {
395 break;
396 }
397 // +0x20 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `remote_queue_index` (id: 7)
398 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
399 // +0x22 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `monotonic_timestamp_time` (id: 8)
400 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
401 //
402 // root_table (aos.logger.MessageHeader):
403 // +0x24 | 16 00 00 00 | SOffset32 | 0x00000016 (22) Loc: +0x0E | offset to vtable
404 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x16);
405 [[fallthrough]];
406 case 0x28u:
407 if ((end_byte) == 0x28u) {
408 break;
409 }
410 // +0x28 | F6 0B D8 11 A4 A8 B1 71 | int64_t | 0x71B1A8A411D80BF6 (8192514619791117302) | table field `monotonic_timestamp_time` (Long)
411 buffer = Push<int64_t>(buffer,
412 monotonic_timestamp_time.time_since_epoch().count());
413 [[fallthrough]];
414 case 0x30u:
415 if ((end_byte) == 0x30u) {
416 break;
417 }
418 // +0x30 | 00 00 00 00 | uint8_t[4] | .... | padding
419 // TODO(austin): Can we re-arrange the order to ditch the padding?
420 // (Answer is yes, but what is the impact elsewhere? It will change the
421 // binary format)
422 buffer = Pad(buffer, 4);
423 // +0x34 | 75 00 00 00 | uint32_t | 0x00000075 (117) | table field `remote_queue_index` (UInt)
424 buffer = Push<uint32_t>(buffer, msg->remote_queue_index());
425 [[fallthrough]];
426 case 0x38u:
427 if ((end_byte) == 0x38u) {
428 break;
429 }
430 // +0x38 | AA B0 43 0A 35 BE FA D2 | int64_t | 0xD2FABE350A43B0AA (-3244071446552268630) | table field `realtime_remote_time` (Long)
431 buffer = Push<int64_t>(buffer, msg->realtime_remote_time());
432 [[fallthrough]];
433 case 0x40u:
434 if ((end_byte) == 0x40u) {
435 break;
436 }
437 // +0x40 | D5 40 30 F3 C1 A7 26 1D | int64_t | 0x1D26A7C1F33040D5 (2100550727665467605) | table field `monotonic_remote_time` (Long)
438 buffer = Push<int64_t>(buffer, msg->monotonic_remote_time());
439 [[fallthrough]];
440 case 0x48u:
441 if ((end_byte) == 0x48u) {
442 break;
443 }
444 // +0x48 | 5B 25 32 A1 4A E8 46 CA | int64_t | 0xCA46E84AA132255B (-3871151422448720549) | table field `realtime_sent_time` (Long)
445 buffer = Push<int64_t>(buffer, msg->realtime_sent_time());
446 [[fallthrough]];
447 case 0x50u:
448 if ((end_byte) == 0x50u) {
449 break;
450 }
451 // +0x50 | 49 7D 45 1F 8C 36 6B A3 | int64_t | 0xA36B368C1F457D49 (-6671178447571288759) | table field `monotonic_sent_time` (Long)
452 buffer = Push<int64_t>(buffer, msg->monotonic_sent_time());
453 [[fallthrough]];
454 case 0x58u:
455 if ((end_byte) == 0x58u) {
456 break;
457 }
458 // +0x58 | 33 00 00 00 | uint32_t | 0x00000033 (51) | table field `queue_index` (UInt)
459 buffer = Push<uint32_t>(buffer, msg->queue_index());
460 // +0x5C | 76 00 00 00 | uint32_t | 0x00000076 (118) | table field `channel_index` (UInt)
461 buffer = Push<uint32_t>(buffer, channel_index);
462 // clang-format on
463 [[fallthrough]];
464 case 0x60u:
465 if ((end_byte) == 0x60u) {
466 break;
467 }
468 }
Austin Schuhf2d0e682022-10-16 14:20:58 -0700469
Austin Schuh71a40d42023-02-04 21:22:22 -0800470 return end_byte - start_byte;
Austin Schuhf2d0e682022-10-16 14:20:58 -0700471}
472
Austin Schuha36c8902019-12-30 18:07:15 -0800473flatbuffers::Offset<MessageHeader> PackMessage(
474 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
475 int channel_index, LogType log_type) {
476 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
477
478 switch (log_type) {
479 case LogType::kLogMessage:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800480 case LogType::kLogRemoteMessage:
Austin Schuhfa30c352022-10-16 11:12:02 -0700481 // Since the timestamps are 8 byte aligned, we are going to end up adding
482 // padding in the middle of the message to pad everything out to 8 byte
483 // alignment. That's rather wasteful. To make things efficient to mmap
484 // while reading uncompressed logs, we'd actually rather the message be
485 // aligned. So, force 8 byte alignment (enough to preserve alignment
486 // inside the nested message so that we can read it without moving it)
487 // here.
488 fbb->ForceVectorAlignment(context.size, sizeof(uint8_t), 8);
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700489 data_offset = fbb->CreateVector(
490 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800491 break;
492
493 case LogType::kLogDeliveryTimeOnly:
494 break;
495 }
496
497 MessageHeader::Builder message_header_builder(*fbb);
498 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800499
Austin Schuhfa30c352022-10-16 11:12:02 -0700500 // These are split out into very explicit serialization calls because the
501 // order here changes the order things are written out on the wire, and we
502 // want to control and understand it here. Changing the order can increase
503 // the amount of padding bytes in the middle.
504 //
James Kuszmaul9776b392023-01-14 14:08:08 -0800505 // It is also easier to follow... And doesn't actually make things much
506 // bigger.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800507 switch (log_type) {
508 case LogType::kLogRemoteMessage:
509 message_header_builder.add_queue_index(context.remote_queue_index);
Austin Schuhfa30c352022-10-16 11:12:02 -0700510 message_header_builder.add_data(data_offset);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800511 message_header_builder.add_monotonic_sent_time(
512 context.monotonic_remote_time.time_since_epoch().count());
513 message_header_builder.add_realtime_sent_time(
514 context.realtime_remote_time.time_since_epoch().count());
515 break;
516
Austin Schuh6f3babe2020-01-26 20:34:50 -0800517 case LogType::kLogDeliveryTimeOnly:
518 message_header_builder.add_queue_index(context.queue_index);
519 message_header_builder.add_monotonic_sent_time(
520 context.monotonic_event_time.time_since_epoch().count());
521 message_header_builder.add_realtime_sent_time(
522 context.realtime_event_time.time_since_epoch().count());
Austin Schuha36c8902019-12-30 18:07:15 -0800523 message_header_builder.add_monotonic_remote_time(
524 context.monotonic_remote_time.time_since_epoch().count());
525 message_header_builder.add_realtime_remote_time(
526 context.realtime_remote_time.time_since_epoch().count());
527 message_header_builder.add_remote_queue_index(context.remote_queue_index);
528 break;
Austin Schuhfa30c352022-10-16 11:12:02 -0700529
530 case LogType::kLogMessage:
531 message_header_builder.add_queue_index(context.queue_index);
532 message_header_builder.add_data(data_offset);
533 message_header_builder.add_monotonic_sent_time(
534 context.monotonic_event_time.time_since_epoch().count());
535 message_header_builder.add_realtime_sent_time(
536 context.realtime_event_time.time_since_epoch().count());
537 break;
Austin Schuha36c8902019-12-30 18:07:15 -0800538 }
539
540 return message_header_builder.Finish();
541}
542
Austin Schuhfa30c352022-10-16 11:12:02 -0700543flatbuffers::uoffset_t PackMessageHeaderSize(LogType log_type) {
544 switch (log_type) {
545 case LogType::kLogMessage:
546 return
547 // Root table size + offset.
548 sizeof(flatbuffers::uoffset_t) * 2 +
549 // 6 padding bytes to pad the header out properly.
550 6 +
551 // vtable header (size + size of table)
552 sizeof(flatbuffers::voffset_t) * 2 +
553 // offsets to all the fields.
554 sizeof(flatbuffers::voffset_t) * 5 +
555 // pointer to vtable
556 sizeof(flatbuffers::soffset_t) +
557 // pointer to data
558 sizeof(flatbuffers::uoffset_t) +
559 // realtime_sent_time, monotonic_sent_time
560 sizeof(int64_t) * 2 +
561 // queue_index, channel_index
562 sizeof(uint32_t) * 2;
563
564 case LogType::kLogDeliveryTimeOnly:
565 return
566 // Root table size + offset.
567 sizeof(flatbuffers::uoffset_t) * 2 +
568 // 6 padding bytes to pad the header out properly.
569 4 +
570 // vtable header (size + size of table)
571 sizeof(flatbuffers::voffset_t) * 2 +
572 // offsets to all the fields.
573 sizeof(flatbuffers::voffset_t) * 8 +
574 // pointer to vtable
575 sizeof(flatbuffers::soffset_t) +
576 // remote_queue_index
577 sizeof(uint32_t) +
578 // realtime_remote_time, monotonic_remote_time, realtime_sent_time,
579 // monotonic_sent_time
580 sizeof(int64_t) * 4 +
581 // queue_index, channel_index
582 sizeof(uint32_t) * 2;
583
Austin Schuhfa30c352022-10-16 11:12:02 -0700584 case LogType::kLogRemoteMessage:
585 return
586 // Root table size + offset.
587 sizeof(flatbuffers::uoffset_t) * 2 +
588 // 6 padding bytes to pad the header out properly.
589 6 +
590 // vtable header (size + size of table)
591 sizeof(flatbuffers::voffset_t) * 2 +
592 // offsets to all the fields.
593 sizeof(flatbuffers::voffset_t) * 5 +
594 // pointer to vtable
595 sizeof(flatbuffers::soffset_t) +
596 // realtime_sent_time, monotonic_sent_time
597 sizeof(int64_t) * 2 +
598 // pointer to data
599 sizeof(flatbuffers::uoffset_t) +
600 // queue_index, channel_index
601 sizeof(uint32_t) * 2;
602 }
603 LOG(FATAL);
604}
605
James Kuszmaul9776b392023-01-14 14:08:08 -0800606flatbuffers::uoffset_t PackMessageSize(LogType log_type, size_t data_size) {
Austin Schuhfa30c352022-10-16 11:12:02 -0700607 static_assert(sizeof(flatbuffers::uoffset_t) == 4u,
608 "Update size logic please.");
609 const flatbuffers::uoffset_t aligned_data_length =
Austin Schuh48d10d62022-10-16 22:19:23 -0700610 ((data_size + 7) & 0xfffffff8u);
Austin Schuhfa30c352022-10-16 11:12:02 -0700611 switch (log_type) {
612 case LogType::kLogDeliveryTimeOnly:
613 return PackMessageHeaderSize(log_type);
614
615 case LogType::kLogMessage:
Austin Schuhfa30c352022-10-16 11:12:02 -0700616 case LogType::kLogRemoteMessage:
617 return PackMessageHeaderSize(log_type) +
618 // Vector...
619 sizeof(flatbuffers::uoffset_t) + aligned_data_length;
620 }
621 LOG(FATAL);
622}
623
Austin Schuhfa30c352022-10-16 11:12:02 -0700624size_t PackMessageInline(uint8_t *buffer, const Context &context,
Austin Schuh71a40d42023-02-04 21:22:22 -0800625 int channel_index, LogType log_type, size_t start_byte,
626 size_t end_byte) {
Austin Schuh48d10d62022-10-16 22:19:23 -0700627 // TODO(austin): Figure out how to copy directly from shared memory instead of
628 // first into the fetcher's memory and then into here. That would save a lot
629 // of memory.
Austin Schuhfa30c352022-10-16 11:12:02 -0700630 const flatbuffers::uoffset_t message_size =
Austin Schuh48d10d62022-10-16 22:19:23 -0700631 PackMessageSize(log_type, context.size);
Austin Schuh71a40d42023-02-04 21:22:22 -0800632 DCHECK_EQ((message_size % 8), 0u) << ": Non 8 byte length...";
633 DCHECK_EQ((start_byte % 8u), 0u);
634 DCHECK_EQ((end_byte % 8u), 0u);
635 DCHECK_LE(start_byte, end_byte);
636 DCHECK_LE(end_byte, message_size);
Austin Schuhfa30c352022-10-16 11:12:02 -0700637
638 // Pack all the data in. This is brittle but easy to change. Use the
639 // InlinePackMessage.Equivilent unit test to verify everything matches.
640 switch (log_type) {
641 case LogType::kLogMessage:
Austin Schuh71a40d42023-02-04 21:22:22 -0800642 switch (start_byte) {
643 case 0x00u:
644 if ((end_byte) == 0x00u) {
645 break;
646 }
647 // clang-format off
648 // header:
649 // +0x00 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: +0x4C | size prefix
650 buffer = Push<flatbuffers::uoffset_t>(
651 buffer, message_size - sizeof(flatbuffers::uoffset_t));
652
653 // +0x04 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: +0x1C | offset to root table `aos.logger.MessageHeader`
654 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x18);
655 [[fallthrough]];
656 case 0x08u:
657 if ((end_byte) == 0x08u) {
658 break;
659 }
660 //
661 // padding:
662 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
663 buffer = Pad(buffer, 6);
664 //
665 // vtable (aos.logger.MessageHeader):
666 // +0x0E | 0E 00 | uint16_t | 0x000E (14) | size of this vtable
667 buffer = Push<flatbuffers::voffset_t>(buffer, 0xe);
668 [[fallthrough]];
669 case 0x10u:
670 if ((end_byte) == 0x10u) {
671 break;
672 }
673 // +0x10 | 20 00 | uint16_t | 0x0020 (32) | size of referring table
674 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
675 // +0x12 | 1C 00 | VOffset16 | 0x001C (28) | offset to field `channel_index` (id: 0)
676 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
677 // +0x14 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `monotonic_sent_time` (id: 1)
678 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0c);
679 // +0x16 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `realtime_sent_time` (id: 2)
680 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
681 [[fallthrough]];
682 case 0x18u:
683 if ((end_byte) == 0x18u) {
684 break;
685 }
686 // +0x18 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `queue_index` (id: 3)
687 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
688 // +0x1A | 14 00 | VOffset16 | 0x0014 (20) | offset to field `data` (id: 4)
689 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
690 //
691 // root_table (aos.logger.MessageHeader):
692 // +0x1C | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: +0x0E | offset to vtable
693 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0e);
694 [[fallthrough]];
695 case 0x20u:
696 if ((end_byte) == 0x20u) {
697 break;
698 }
699 // +0x20 | B2 E4 EF 89 19 7D 7F 6F | int64_t | 0x6F7F7D1989EFE4B2 (8034277808894108850) | table field `realtime_sent_time` (Long)
700 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
701 [[fallthrough]];
702 case 0x28u:
703 if ((end_byte) == 0x28u) {
704 break;
705 }
706 // +0x28 | 86 8D 92 65 FC 79 74 2B | int64_t | 0x2B7479FC65928D86 (3131261765872160134) | table field `monotonic_sent_time` (Long)
707 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
708 [[fallthrough]];
709 case 0x30u:
710 if ((end_byte) == 0x30u) {
711 break;
712 }
713 // +0x30 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: +0x3C | offset to field `data` (vector)
714 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0c);
715 // +0x34 | 86 00 00 00 | uint32_t | 0x00000086 (134) | table field `queue_index` (UInt)
716 buffer = Push<uint32_t>(buffer, context.queue_index);
717 [[fallthrough]];
718 case 0x38u:
719 if ((end_byte) == 0x38u) {
720 break;
721 }
722 // +0x38 | 71 00 00 00 | uint32_t | 0x00000071 (113) | table field `channel_index` (UInt)
723 buffer = Push<uint32_t>(buffer, channel_index);
724 //
725 // vector (aos.logger.MessageHeader.data):
726 // +0x3C | 0E 00 00 00 | uint32_t | 0x0000000E (14) | length of vector (# items)
727 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
728 [[fallthrough]];
729 case 0x40u:
730 if ((end_byte) == 0x40u) {
731 break;
732 }
733 [[fallthrough]];
734 default:
735 // +0x40 | FF | uint8_t | 0xFF (255) | value[0]
736 // +0x41 | B8 | uint8_t | 0xB8 (184) | value[1]
737 // +0x42 | EE | uint8_t | 0xEE (238) | value[2]
738 // +0x43 | 00 | uint8_t | 0x00 (0) | value[3]
739 // +0x44 | 20 | uint8_t | 0x20 (32) | value[4]
740 // +0x45 | 4D | uint8_t | 0x4D (77) | value[5]
741 // +0x46 | FF | uint8_t | 0xFF (255) | value[6]
742 // +0x47 | 25 | uint8_t | 0x25 (37) | value[7]
743 // +0x48 | 3C | uint8_t | 0x3C (60) | value[8]
744 // +0x49 | 17 | uint8_t | 0x17 (23) | value[9]
745 // +0x4A | 65 | uint8_t | 0x65 (101) | value[10]
746 // +0x4B | 2F | uint8_t | 0x2F (47) | value[11]
747 // +0x4C | 63 | uint8_t | 0x63 (99) | value[12]
748 // +0x4D | 58 | uint8_t | 0x58 (88) | value[13]
749 //
750 // padding:
751 // +0x4E | 00 00 | uint8_t[2] | .. | padding
752 // clang-format on
753 if (start_byte <= 0x40 && end_byte == message_size) {
754 // The easy one, slap it all down.
755 buffer = PushBytes(buffer, context.data, context.size);
756 buffer =
757 Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
758 } else {
759 const size_t data_start_byte =
760 start_byte < 0x40 ? 0x0u : (start_byte - 0x40);
761 const size_t data_end_byte = end_byte - 0x40;
762 const size_t padded_size = ((context.size + 7) & 0xfffffff8u);
763 if (data_start_byte < padded_size) {
764 buffer = PushBytes(
765 buffer,
766 reinterpret_cast<const uint8_t *>(context.data) +
767 data_start_byte,
768 std::min(context.size, data_end_byte) - data_start_byte);
769 if (data_end_byte == padded_size) {
770 // We can only pad the last 7 bytes, so this only gets written
771 // if we write the last byte.
772 buffer = Pad(buffer,
773 ((context.size + 7) & 0xfffffff8u) - context.size);
774 }
775 }
776 }
777 break;
778 }
Austin Schuhfa30c352022-10-16 11:12:02 -0700779 break;
780
781 case LogType::kLogDeliveryTimeOnly:
Austin Schuh71a40d42023-02-04 21:22:22 -0800782 switch (start_byte) {
783 case 0x00u:
784 if ((end_byte) == 0x00u) {
785 break;
786 }
787 // clang-format off
788 // header:
789 // +0x00 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: +0x4C | size prefix
790 buffer = Push<flatbuffers::uoffset_t>(
791 buffer, message_size - sizeof(flatbuffers::uoffset_t));
792 // +0x04 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: +0x20 | offset to root table `aos.logger.MessageHeader`
793 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x1c);
Austin Schuhfa30c352022-10-16 11:12:02 -0700794
Austin Schuh71a40d42023-02-04 21:22:22 -0800795 [[fallthrough]];
796 case 0x08u:
797 if ((end_byte) == 0x08u) {
798 break;
799 }
800 //
801 // padding:
802 // +0x08 | 00 00 00 00 | uint8_t[4] | .... | padding
803 buffer = Pad(buffer, 4);
804 //
805 // vtable (aos.logger.MessageHeader):
806 // +0x0C | 14 00 | uint16_t | 0x0014 (20) | size of this vtable
807 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
808 // +0x0E | 30 00 | uint16_t | 0x0030 (48) | size of referring table
809 buffer = Push<flatbuffers::voffset_t>(buffer, 0x30);
810 [[fallthrough]];
811 case 0x10u:
812 if ((end_byte) == 0x10u) {
813 break;
814 }
815 // +0x10 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `channel_index` (id: 0)
816 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
817 // +0x12 | 20 00 | VOffset16 | 0x0020 (32) | offset to field `monotonic_sent_time` (id: 1)
818 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
819 // +0x14 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `realtime_sent_time` (id: 2)
820 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
821 // +0x16 | 28 00 | VOffset16 | 0x0028 (40) | offset to field `queue_index` (id: 3)
822 buffer = Push<flatbuffers::voffset_t>(buffer, 0x28);
823 [[fallthrough]];
824 case 0x18u:
825 if ((end_byte) == 0x18u) {
826 break;
827 }
828 // +0x18 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `data` (id: 4) <null> (Vector)
829 buffer = Push<flatbuffers::voffset_t>(buffer, 0x00);
830 // +0x1A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `monotonic_remote_time` (id: 5)
831 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
832 // +0x1C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `realtime_remote_time` (id: 6)
833 buffer = Push<flatbuffers::voffset_t>(buffer, 0x08);
834 // +0x1E | 04 00 | VOffset16 | 0x0004 (4) | offset to field `remote_queue_index` (id: 7)
835 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
836 [[fallthrough]];
837 case 0x20u:
838 if ((end_byte) == 0x20u) {
839 break;
840 }
841 //
842 // root_table (aos.logger.MessageHeader):
843 // +0x20 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: +0x0C | offset to vtable
844 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x14);
845 // +0x24 | 69 00 00 00 | uint32_t | 0x00000069 (105) | table field `remote_queue_index` (UInt)
846 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
847 [[fallthrough]];
848 case 0x28u:
849 if ((end_byte) == 0x28u) {
850 break;
851 }
852 // +0x28 | C6 85 F1 AB 83 B5 CD EB | int64_t | 0xEBCDB583ABF185C6 (-1455307527440726586) | table field `realtime_remote_time` (Long)
853 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
854 [[fallthrough]];
855 case 0x30u:
856 if ((end_byte) == 0x30u) {
857 break;
858 }
859 // +0x30 | 47 24 D3 97 1E 42 2D 99 | int64_t | 0x992D421E97D32447 (-7409193112790948793) | table field `monotonic_remote_time` (Long)
860 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
861 [[fallthrough]];
862 case 0x38u:
863 if ((end_byte) == 0x38u) {
864 break;
865 }
866 // +0x38 | C8 B9 A7 AB 79 F2 CD 60 | int64_t | 0x60CDF279ABA7B9C8 (6975498002251626952) | table field `realtime_sent_time` (Long)
867 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
868 [[fallthrough]];
869 case 0x40u:
870 if ((end_byte) == 0x40u) {
871 break;
872 }
873 // +0x40 | EA 8F 2A 0F AF 01 7A AB | int64_t | 0xAB7A01AF0F2A8FEA (-6090553694679822358) | table field `monotonic_sent_time` (Long)
874 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
875 [[fallthrough]];
876 case 0x48u:
877 if ((end_byte) == 0x48u) {
878 break;
879 }
880 // +0x48 | F5 00 00 00 | uint32_t | 0x000000F5 (245) | table field `queue_index` (UInt)
881 buffer = Push<uint32_t>(buffer, context.queue_index);
882 // +0x4C | 88 00 00 00 | uint32_t | 0x00000088 (136) | table field `channel_index` (UInt)
883 buffer = Push<uint32_t>(buffer, channel_index);
884
885 // clang-format on
886 }
Austin Schuhfa30c352022-10-16 11:12:02 -0700887 break;
888
Austin Schuhfa30c352022-10-16 11:12:02 -0700889 case LogType::kLogRemoteMessage:
Austin Schuh71a40d42023-02-04 21:22:22 -0800890 switch (start_byte) {
891 case 0x00u:
892 if ((end_byte) == 0x00u) {
893 break;
894 }
895 // This is the message we need to recreate.
896 //
897 // clang-format off
898 // header:
899 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
900 buffer = Push<flatbuffers::uoffset_t>(
901 buffer, message_size - sizeof(flatbuffers::uoffset_t));
902 // +0x04 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: +0x1C | offset to root table `aos.logger.MessageHeader`
903 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x18);
904 [[fallthrough]];
905 case 0x08u:
906 if ((end_byte) == 0x08u) {
907 break;
908 }
909 //
910 // padding:
911 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
912 buffer = Pad(buffer, 6);
913 //
914 // vtable (aos.logger.MessageHeader):
915 // +0x0E | 0E 00 | uint16_t | 0x000E (14) | size of this vtable
916 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0e);
917 [[fallthrough]];
918 case 0x10u:
919 if ((end_byte) == 0x10u) {
920 break;
921 }
922 // +0x10 | 20 00 | uint16_t | 0x0020 (32) | size of referring table
923 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
924 // +0x12 | 1C 00 | VOffset16 | 0x001C (28) | offset to field `channel_index` (id: 0)
925 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
926 // +0x14 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `monotonic_sent_time` (id: 1)
927 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0c);
928 // +0x16 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `realtime_sent_time` (id: 2)
929 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
930 [[fallthrough]];
931 case 0x18u:
932 if ((end_byte) == 0x18u) {
933 break;
934 }
935 // +0x18 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `queue_index` (id: 3)
936 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
937 // +0x1A | 14 00 | VOffset16 | 0x0014 (20) | offset to field `data` (id: 4)
938 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
939 //
940 // root_table (aos.logger.MessageHeader):
941 // +0x1C | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: +0x0E | offset to vtable
942 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0E);
943 [[fallthrough]];
944 case 0x20u:
945 if ((end_byte) == 0x20u) {
946 break;
947 }
948 // +0x20 | D8 96 32 1A A0 D3 23 BB | int64_t | 0xBB23D3A01A3296D8 (-4961889679844403496) | table field `realtime_sent_time` (Long)
949 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
950 [[fallthrough]];
951 case 0x28u:
952 if ((end_byte) == 0x28u) {
953 break;
954 }
955 // +0x28 | 2E 5D 23 B3 BE 84 CF C2 | int64_t | 0xC2CF84BEB3235D2E (-4409159555588334290) | table field `monotonic_sent_time` (Long)
956 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
957 [[fallthrough]];
958 case 0x30u:
959 if ((end_byte) == 0x30u) {
960 break;
961 }
962 // +0x30 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: +0x3C | offset to field `data` (vector)
963 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0C);
964 // +0x34 | 69 00 00 00 | uint32_t | 0x00000069 (105) | table field `queue_index` (UInt)
965 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
966 [[fallthrough]];
967 case 0x38u:
968 if ((end_byte) == 0x38u) {
969 break;
970 }
971 // +0x38 | F3 00 00 00 | uint32_t | 0x000000F3 (243) | table field `channel_index` (UInt)
972 buffer = Push<uint32_t>(buffer, channel_index);
973 //
974 // vector (aos.logger.MessageHeader.data):
975 // +0x3C | 1A 00 00 00 | uint32_t | 0x0000001A (26) | length of vector (# items)
976 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
977 [[fallthrough]];
978 case 0x40u:
979 if ((end_byte) == 0x40u) {
980 break;
981 }
982 [[fallthrough]];
983 default:
984 // +0x40 | 38 | uint8_t | 0x38 (56) | value[0]
985 // +0x41 | 1A | uint8_t | 0x1A (26) | value[1]
986 // ...
987 // +0x58 | 90 | uint8_t | 0x90 (144) | value[24]
988 // +0x59 | 92 | uint8_t | 0x92 (146) | value[25]
989 //
990 // padding:
991 // +0x5A | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
992 // clang-format on
993 if (start_byte <= 0x40 && end_byte == message_size) {
994 // The easy one, slap it all down.
995 buffer = PushBytes(buffer, context.data, context.size);
996 buffer =
997 Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
998 } else {
999 const size_t data_start_byte =
1000 start_byte < 0x40 ? 0x0u : (start_byte - 0x40);
1001 const size_t data_end_byte = end_byte - 0x40;
1002 const size_t padded_size = ((context.size + 7) & 0xfffffff8u);
1003 if (data_start_byte < padded_size) {
1004 buffer = PushBytes(
1005 buffer,
1006 reinterpret_cast<const uint8_t *>(context.data) +
1007 data_start_byte,
1008 std::min(context.size, data_end_byte) - data_start_byte);
1009 if (data_end_byte == padded_size) {
1010 // We can only pad the last 7 bytes, so this only gets written
1011 // if we write the last byte.
1012 buffer = Pad(buffer,
1013 ((context.size + 7) & 0xfffffff8u) - context.size);
1014 }
1015 }
1016 }
1017 break;
1018 }
Austin Schuhfa30c352022-10-16 11:12:02 -07001019 }
1020
Austin Schuh71a40d42023-02-04 21:22:22 -08001021 return end_byte - start_byte;
Austin Schuhfa30c352022-10-16 11:12:02 -07001022}
1023
Austin Schuhcd368422021-11-22 21:23:29 -08001024SpanReader::SpanReader(std::string_view filename, bool quiet)
Alexei Strotscee7b372023-04-21 11:57:54 -07001025 : SpanReader(filename, ResolveDecoder(filename, quiet)) {}
Tyler Chatow2015bc62021-08-04 21:15:09 -07001026
Alexei Strotscee7b372023-04-21 11:57:54 -07001027SpanReader::SpanReader(std::string_view filename,
1028 std::unique_ptr<DataDecoder> decoder)
1029 : filename_(filename), decoder_(std::move(decoder)) {}
Austin Schuh05b70472020-01-01 17:11:17 -08001030
Austin Schuhcf5f6442021-07-06 10:43:28 -07001031absl::Span<const uint8_t> SpanReader::PeekMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -08001032 // Make sure we have enough for the size.
1033 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
1034 if (!ReadBlock()) {
1035 return absl::Span<const uint8_t>();
1036 }
1037 }
1038
1039 // Now make sure we have enough for the message.
1040 const size_t data_size =
1041 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
1042 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -08001043 if (data_size == sizeof(flatbuffers::uoffset_t)) {
1044 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
1045 LOG(ERROR) << " Rest of log file is "
1046 << absl::BytesToHexString(std::string_view(
1047 reinterpret_cast<const char *>(data_.data() +
1048 consumed_data_),
1049 data_.size() - consumed_data_));
1050 return absl::Span<const uint8_t>();
1051 }
Austin Schuh05b70472020-01-01 17:11:17 -08001052 while (data_.size() < consumed_data_ + data_size) {
1053 if (!ReadBlock()) {
1054 return absl::Span<const uint8_t>();
1055 }
1056 }
1057
1058 // And return it, consuming the data.
1059 const uint8_t *data_ptr = data_.data() + consumed_data_;
1060
Austin Schuh05b70472020-01-01 17:11:17 -08001061 return absl::Span<const uint8_t>(data_ptr, data_size);
1062}
1063
Austin Schuhcf5f6442021-07-06 10:43:28 -07001064void SpanReader::ConsumeMessage() {
Brian Smarttea913d42021-12-10 15:02:38 -08001065 size_t consumed_size =
Austin Schuhcf5f6442021-07-06 10:43:28 -07001066 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
1067 sizeof(flatbuffers::uoffset_t);
Brian Smarttea913d42021-12-10 15:02:38 -08001068 consumed_data_ += consumed_size;
1069 total_consumed_ += consumed_size;
Austin Schuhcf5f6442021-07-06 10:43:28 -07001070}
1071
1072absl::Span<const uint8_t> SpanReader::ReadMessage() {
1073 absl::Span<const uint8_t> result = PeekMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001074 if (!result.empty()) {
Austin Schuhcf5f6442021-07-06 10:43:28 -07001075 ConsumeMessage();
Brian Smarttea913d42021-12-10 15:02:38 -08001076 } else {
1077 is_finished_ = true;
Austin Schuhcf5f6442021-07-06 10:43:28 -07001078 }
1079 return result;
1080}
1081
Austin Schuh05b70472020-01-01 17:11:17 -08001082bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -07001083 // This is the amount of data we grab at a time. Doing larger chunks minimizes
1084 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -08001085 constexpr size_t kReadSize = 256 * 1024;
1086
1087 // Strip off any unused data at the front.
1088 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -07001089 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -08001090 consumed_data_ = 0;
1091 }
1092
1093 const size_t starting_size = data_.size();
1094
1095 // This should automatically grow the backing store. It won't shrink if we
1096 // get a small chunk later. This reduces allocations when we want to append
1097 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -07001098 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -08001099
Brian Silvermanf51499a2020-09-21 12:49:08 -07001100 const size_t count =
1101 decoder_->Read(data_.begin() + starting_size, data_.end());
1102 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -08001103 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -08001104 return false;
1105 }
Austin Schuh05b70472020-01-01 17:11:17 -08001106
Brian Smarttea913d42021-12-10 15:02:38 -08001107 total_read_ += count;
1108
Austin Schuh05b70472020-01-01 17:11:17 -08001109 return true;
1110}
1111
Alexei Strotsa3194712023-04-21 23:30:50 -07001112LogReadersPool::LogReadersPool(const LogSource *log_source, size_t pool_size)
1113 : log_source_(log_source), pool_size_(pool_size) {}
1114
1115SpanReader *LogReadersPool::BorrowReader(std::string_view id) {
1116 if (part_readers_.size() > pool_size_) {
1117 // Don't leave arbitrary numbers of readers open, because they each take
1118 // resources, so close a big batch at once periodically.
1119 part_readers_.clear();
1120 }
1121 if (log_source_ == nullptr) {
1122 part_readers_.emplace_back(id, FLAGS_quiet_sorting);
1123 } else {
1124 part_readers_.emplace_back(id, log_source_->GetDecoder(id));
1125 }
1126 return &part_readers_.back();
1127}
1128
Austin Schuhadd6eb32020-11-09 21:24:26 -08001129std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh0e8db662021-07-06 10:43:47 -07001130 SpanReader *span_reader) {
1131 absl::Span<const uint8_t> config_data = span_reader->ReadMessage();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001132
1133 // Make sure something was read.
James Kuszmaul9776b392023-01-14 14:08:08 -08001134 if (config_data.empty()) {
Austin Schuh3bd4c402020-11-06 18:19:06 -08001135 return std::nullopt;
1136 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001137
Austin Schuh5212cad2020-09-09 23:12:09 -07001138 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -07001139 SizePrefixedFlatbufferVector<LogFileHeader> result(config_data);
Austin Schuhe09beb12020-12-11 20:04:27 -08001140 if (!result.Verify()) {
1141 return std::nullopt;
1142 }
Austin Schuh0e8db662021-07-06 10:43:47 -07001143
Austin Schuhcc2c9a52022-12-12 15:55:13 -08001144 // We only know of busted headers in the versions of the log file header
1145 // *before* the logger_sha1 field was added. At some point before that point,
1146 // the logic to track when a header has been written was rewritten in such a
1147 // way that it can't happen anymore. We've seen some logs where the body
1148 // parses as a header recently, so the simple solution of always looking is
1149 // failing us.
1150 if (FLAGS_workaround_double_headers && !result.message().has_logger_sha1()) {
Austin Schuh0e8db662021-07-06 10:43:47 -07001151 while (true) {
1152 absl::Span<const uint8_t> maybe_header_data = span_reader->PeekMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001153 if (maybe_header_data.empty()) {
Austin Schuh0e8db662021-07-06 10:43:47 -07001154 break;
1155 }
1156
1157 aos::SizePrefixedFlatbufferSpan<aos::logger::LogFileHeader> maybe_header(
1158 maybe_header_data);
1159 if (maybe_header.Verify()) {
1160 LOG(WARNING) << "Found duplicate LogFileHeader in "
1161 << span_reader->filename();
1162 ResizeableBuffer header_data_copy;
1163 header_data_copy.resize(maybe_header_data.size());
1164 memcpy(header_data_copy.data(), maybe_header_data.begin(),
1165 header_data_copy.size());
1166 result = SizePrefixedFlatbufferVector<LogFileHeader>(
1167 std::move(header_data_copy));
1168
1169 span_reader->ConsumeMessage();
1170 } else {
1171 break;
1172 }
1173 }
1174 }
Austin Schuhe09beb12020-12-11 20:04:27 -08001175 return result;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001176}
1177
Austin Schuh0e8db662021-07-06 10:43:47 -07001178std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
1179 std::string_view filename) {
1180 SpanReader span_reader(filename);
1181 return ReadHeader(&span_reader);
1182}
1183
Austin Schuhadd6eb32020-11-09 21:24:26 -08001184std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -08001185 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -07001186 SpanReader span_reader(filename);
1187 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
1188 for (size_t i = 0; i < n + 1; ++i) {
1189 data_span = span_reader.ReadMessage();
1190
1191 // Make sure something was read.
James Kuszmaul9776b392023-01-14 14:08:08 -08001192 if (data_span.empty()) {
Austin Schuh3bd4c402020-11-06 18:19:06 -08001193 return std::nullopt;
1194 }
Austin Schuh5212cad2020-09-09 23:12:09 -07001195 }
1196
Brian Silverman354697a2020-09-22 21:06:32 -07001197 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -07001198 SizePrefixedFlatbufferVector<MessageHeader> result(data_span);
Austin Schuhe09beb12020-12-11 20:04:27 -08001199 if (!result.Verify()) {
1200 return std::nullopt;
1201 }
1202 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -07001203}
1204
Alexei Strots58017402023-05-03 22:05:06 -07001205MessageReader::MessageReader(SpanReader span_reader)
1206 : span_reader_(std::move(span_reader)),
Austin Schuhadd6eb32020-11-09 21:24:26 -08001207 raw_log_file_header_(
1208 SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001209 set_crash_on_corrupt_message_flag(FLAGS_crash_on_corrupt_message);
1210 set_ignore_corrupt_messages_flag(FLAGS_ignore_corrupt_messages);
1211
Austin Schuh0e8db662021-07-06 10:43:47 -07001212 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>>
1213 raw_log_file_header = ReadHeader(&span_reader_);
Austin Schuh05b70472020-01-01 17:11:17 -08001214
1215 // Make sure something was read.
Alexei Strots58017402023-05-03 22:05:06 -07001216 CHECK(raw_log_file_header)
1217 << ": Failed to read header from: " << span_reader_.filename();
Austin Schuh05b70472020-01-01 17:11:17 -08001218
Austin Schuh0e8db662021-07-06 10:43:47 -07001219 raw_log_file_header_ = std::move(*raw_log_file_header);
Austin Schuh05b70472020-01-01 17:11:17 -08001220
Austin Schuh5b728b72021-06-16 14:57:15 -07001221 CHECK(raw_log_file_header_.Verify()) << "Log file header is corrupted";
1222
Brian Smarttea913d42021-12-10 15:02:38 -08001223 total_verified_before_ = span_reader_.TotalConsumed();
1224
Austin Schuhcde938c2020-02-02 17:30:07 -08001225 max_out_of_order_duration_ =
Austin Schuha040c3f2021-02-13 16:09:07 -08001226 FLAGS_max_out_of_order > 0
1227 ? chrono::duration_cast<chrono::nanoseconds>(
1228 chrono::duration<double>(FLAGS_max_out_of_order))
1229 : chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -08001230
Alexei Strots58017402023-05-03 22:05:06 -07001231 VLOG(1) << "Opened " << span_reader_.filename() << " as node "
Austin Schuhcde938c2020-02-02 17:30:07 -08001232 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -08001233}
1234
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001235std::shared_ptr<UnpackedMessageHeader> MessageReader::ReadMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -08001236 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001237 if (msg_data.empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001238 if (is_corrupted()) {
1239 LOG(ERROR) << "Total corrupted volumes: before = "
1240 << total_verified_before_
1241 << " | corrupted = " << total_corrupted_
1242 << " | during = " << total_verified_during_
1243 << " | after = " << total_verified_after_ << std::endl;
1244 }
1245
1246 if (span_reader_.IsIncomplete()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001247 LOG(ERROR) << "Unable to access some messages in " << filename() << " : "
1248 << span_reader_.TotalRead() << " bytes read, "
Brian Smarttea913d42021-12-10 15:02:38 -08001249 << span_reader_.TotalConsumed() << " bytes usable."
1250 << std::endl;
1251 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001252 return nullptr;
Austin Schuh05b70472020-01-01 17:11:17 -08001253 }
1254
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001255 SizePrefixedFlatbufferSpan<MessageHeader> msg(msg_data);
Brian Smarttea913d42021-12-10 15:02:38 -08001256
1257 if (crash_on_corrupt_message_flag_) {
1258 CHECK(msg.Verify()) << "Corrupted message at offset "
Austin Schuh60e77942022-05-16 17:48:24 -07001259 << total_verified_before_ << " found within "
1260 << filename()
Brian Smarttea913d42021-12-10 15:02:38 -08001261 << "; set --nocrash_on_corrupt_message to see summary;"
1262 << " also set --ignore_corrupt_messages to process"
1263 << " anyway";
1264
1265 } else if (!msg.Verify()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001266 LOG(ERROR) << "Corrupted message at offset " << total_verified_before_
Brian Smarttea913d42021-12-10 15:02:38 -08001267 << " from " << filename() << std::endl;
1268
1269 total_corrupted_ += msg_data.size();
1270
1271 while (true) {
1272 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
1273
James Kuszmaul9776b392023-01-14 14:08:08 -08001274 if (msg_data.empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001275 if (!ignore_corrupt_messages_flag_) {
1276 LOG(ERROR) << "Total corrupted volumes: before = "
1277 << total_verified_before_
1278 << " | corrupted = " << total_corrupted_
1279 << " | during = " << total_verified_during_
1280 << " | after = " << total_verified_after_ << std::endl;
1281
1282 if (span_reader_.IsIncomplete()) {
1283 LOG(ERROR) << "Unable to access some messages in " << filename()
1284 << " : " << span_reader_.TotalRead() << " bytes read, "
1285 << span_reader_.TotalConsumed() << " bytes usable."
1286 << std::endl;
1287 }
1288 return nullptr;
1289 }
1290 break;
1291 }
1292
1293 SizePrefixedFlatbufferSpan<MessageHeader> next_msg(msg_data);
1294
1295 if (!next_msg.Verify()) {
1296 total_corrupted_ += msg_data.size();
1297 total_verified_during_ += total_verified_after_;
1298 total_verified_after_ = 0;
1299
1300 } else {
1301 total_verified_after_ += msg_data.size();
1302 if (ignore_corrupt_messages_flag_) {
1303 msg = next_msg;
1304 break;
1305 }
1306 }
1307 }
1308 }
1309
1310 if (is_corrupted()) {
1311 total_verified_after_ += msg_data.size();
1312 } else {
1313 total_verified_before_ += msg_data.size();
1314 }
Austin Schuh05b70472020-01-01 17:11:17 -08001315
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001316 auto result = UnpackedMessageHeader::MakeMessage(msg.message());
Austin Schuh0e8db662021-07-06 10:43:47 -07001317
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001318 const monotonic_clock::time_point timestamp = result->monotonic_sent_time;
Austin Schuh05b70472020-01-01 17:11:17 -08001319
1320 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuhd1873292021-11-18 15:35:30 -08001321
1322 if (VLOG_IS_ON(3)) {
1323 VLOG(3) << "Read from " << filename() << " data " << FlatbufferToJson(msg);
1324 } else if (VLOG_IS_ON(2)) {
1325 SizePrefixedFlatbufferVector<MessageHeader> msg_copy = msg;
1326 msg_copy.mutable_message()->clear_data();
1327 VLOG(2) << "Read from " << filename() << " data "
1328 << FlatbufferToJson(msg_copy);
1329 }
1330
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001331 return result;
1332}
1333
1334std::shared_ptr<UnpackedMessageHeader> UnpackedMessageHeader::MakeMessage(
1335 const MessageHeader &message) {
1336 const size_t data_size = message.has_data() ? message.data()->size() : 0;
1337
1338 UnpackedMessageHeader *const unpacked_message =
1339 reinterpret_cast<UnpackedMessageHeader *>(
1340 malloc(sizeof(UnpackedMessageHeader) + data_size +
1341 kChannelDataAlignment - 1));
1342
1343 CHECK(message.has_channel_index());
1344 CHECK(message.has_monotonic_sent_time());
1345
1346 absl::Span<uint8_t> span;
1347 if (data_size > 0) {
1348 span =
1349 absl::Span<uint8_t>(reinterpret_cast<uint8_t *>(RoundChannelData(
1350 &unpacked_message->actual_data[0], data_size)),
1351 data_size);
1352 }
1353
Austin Schuh826e6ce2021-11-18 20:33:10 -08001354 std::optional<aos::monotonic_clock::time_point> monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001355 if (message.has_monotonic_remote_time()) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001356 monotonic_remote_time = aos::monotonic_clock::time_point(
1357 std::chrono::nanoseconds(message.monotonic_remote_time()));
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001358 }
1359 std::optional<realtime_clock::time_point> realtime_remote_time;
1360 if (message.has_realtime_remote_time()) {
1361 realtime_remote_time = realtime_clock::time_point(
1362 chrono::nanoseconds(message.realtime_remote_time()));
1363 }
1364
1365 std::optional<uint32_t> remote_queue_index;
1366 if (message.has_remote_queue_index()) {
1367 remote_queue_index = message.remote_queue_index();
1368 }
1369
James Kuszmaul9776b392023-01-14 14:08:08 -08001370 new (unpacked_message) UnpackedMessageHeader(
1371 message.channel_index(),
1372 monotonic_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001373 chrono::nanoseconds(message.monotonic_sent_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001374 realtime_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001375 chrono::nanoseconds(message.realtime_sent_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001376 message.queue_index(), monotonic_remote_time, realtime_remote_time,
1377 remote_queue_index,
1378 monotonic_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001379 std::chrono::nanoseconds(message.monotonic_timestamp_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001380 message.has_monotonic_timestamp_time(), span);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001381
1382 if (data_size > 0) {
1383 memcpy(span.data(), message.data()->data(), data_size);
1384 }
1385
1386 return std::shared_ptr<UnpackedMessageHeader>(unpacked_message,
1387 &DestroyAndFree);
Austin Schuh05b70472020-01-01 17:11:17 -08001388}
1389
Alexei Strots58017402023-05-03 22:05:06 -07001390SpanReader PartsMessageReader::MakeSpanReader(
1391 const LogPartsAccess &log_parts_access, size_t part_number) {
1392 const auto part = log_parts_access.GetPartAt(part_number);
1393 if (log_parts_access.log_source().has_value()) {
1394 return SpanReader(part,
1395 log_parts_access.log_source().value()->GetDecoder(part));
1396 } else {
1397 return SpanReader(part);
1398 }
1399}
1400
1401PartsMessageReader::PartsMessageReader(LogPartsAccess log_parts_access)
1402 : log_parts_access_(std::move(log_parts_access)),
Mithun Bharadwaja5cb8e02023-08-02 16:10:40 -07001403 message_reader_(MakeSpanReader(log_parts_access_, 0)),
1404 max_out_of_order_duration_(
1405 log_parts_access_.max_out_of_order_duration()) {
Alexei Strots58017402023-05-03 22:05:06 -07001406 if (log_parts_access_.size() >= 2) {
1407 next_message_reader_.emplace(MakeSpanReader(log_parts_access_, 1));
Brian Silvermanfee16972021-09-14 12:06:38 -07001408 }
Austin Schuh48507722021-07-17 17:29:24 -07001409 ComputeBootCounts();
1410}
1411
1412void PartsMessageReader::ComputeBootCounts() {
Austin Schuh63097262023-08-16 17:04:29 -07001413 boot_counts_.assign(
1414 configuration::NodesCount(log_parts_access_.config().get()),
1415 std::nullopt);
Austin Schuh48507722021-07-17 17:29:24 -07001416
Alexei Strots58017402023-05-03 22:05:06 -07001417 const auto boots = log_parts_access_.parts().boots;
1418
Austin Schuh48507722021-07-17 17:29:24 -07001419 // We have 3 vintages of log files with different amounts of information.
1420 if (log_file_header()->has_boot_uuids()) {
1421 // The new hotness with the boots explicitly listed out. We can use the log
1422 // file header to compute the boot count of all relevant nodes.
1423 CHECK_EQ(log_file_header()->boot_uuids()->size(), boot_counts_.size());
1424 size_t node_index = 0;
1425 for (const flatbuffers::String *boot_uuid :
1426 *log_file_header()->boot_uuids()) {
Alexei Strots58017402023-05-03 22:05:06 -07001427 CHECK(boots);
Austin Schuh48507722021-07-17 17:29:24 -07001428 if (boot_uuid->size() != 0) {
Alexei Strots58017402023-05-03 22:05:06 -07001429 auto it = boots->boot_count_map.find(boot_uuid->str());
1430 if (it != boots->boot_count_map.end()) {
Austin Schuh48507722021-07-17 17:29:24 -07001431 boot_counts_[node_index] = it->second;
1432 }
1433 } else if (parts().boots->boots[node_index].size() == 1u) {
1434 boot_counts_[node_index] = 0;
1435 }
1436 ++node_index;
1437 }
1438 } else {
1439 // Older multi-node logs which are guarenteed to have UUIDs logged, or
1440 // single node log files with boot UUIDs in the header. We only know how to
1441 // order certain boots in certain circumstances.
Austin Schuh63097262023-08-16 17:04:29 -07001442 if (configuration::MultiNode(log_parts_access_.config().get()) || boots) {
Austin Schuh48507722021-07-17 17:29:24 -07001443 for (size_t node_index = 0; node_index < boot_counts_.size();
1444 ++node_index) {
Alexei Strots58017402023-05-03 22:05:06 -07001445 if (boots->boots[node_index].size() == 1u) {
Austin Schuh48507722021-07-17 17:29:24 -07001446 boot_counts_[node_index] = 0;
1447 }
1448 }
1449 } else {
1450 // Really old single node logs without any UUIDs. They can't reboot.
1451 CHECK_EQ(boot_counts_.size(), 1u);
1452 boot_counts_[0] = 0u;
1453 }
1454 }
1455}
Austin Schuhc41603c2020-10-11 16:17:37 -07001456
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001457std::shared_ptr<UnpackedMessageHeader> PartsMessageReader::ReadMessage() {
Austin Schuhc41603c2020-10-11 16:17:37 -07001458 while (!done_) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001459 std::shared_ptr<UnpackedMessageHeader> message =
Austin Schuhc41603c2020-10-11 16:17:37 -07001460 message_reader_.ReadMessage();
1461 if (message) {
1462 newest_timestamp_ = message_reader_.newest_timestamp();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001463 const monotonic_clock::time_point monotonic_sent_time =
1464 message->monotonic_sent_time;
1465
1466 // TODO(austin): Does this work with startup? Might need to use the
1467 // start time.
1468 // TODO(austin): Does this work with startup when we don't know the
1469 // remote start time too? Look at one of those logs to compare.
Alexei Strots58017402023-05-03 22:05:06 -07001470 if (monotonic_sent_time > log_parts_access_.parts().monotonic_start_time +
1471 max_out_of_order_duration()) {
Austin Schuh315b96b2020-12-11 21:21:12 -08001472 after_start_ = true;
1473 }
1474 if (after_start_) {
Austin Schuhb000de62020-12-03 22:00:40 -08001475 CHECK_GE(monotonic_sent_time,
1476 newest_timestamp_ - max_out_of_order_duration())
Austin Schuha040c3f2021-02-13 16:09:07 -08001477 << ": Max out of order of " << max_out_of_order_duration().count()
Alexei Strots58017402023-05-03 22:05:06 -07001478 << "ns exceeded. " << log_parts_access_.parts()
1479 << ", start time is "
1480 << log_parts_access_.parts().monotonic_start_time
1481 << " currently reading " << filename();
Austin Schuhb000de62020-12-03 22:00:40 -08001482 }
Austin Schuhc41603c2020-10-11 16:17:37 -07001483 return message;
1484 }
1485 NextLog();
1486 }
Austin Schuh32f68492020-11-08 21:45:51 -08001487 newest_timestamp_ = monotonic_clock::max_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001488 return nullptr;
Austin Schuhc41603c2020-10-11 16:17:37 -07001489}
1490
1491void PartsMessageReader::NextLog() {
Alexei Strots58017402023-05-03 22:05:06 -07001492 if (next_part_index_ == log_parts_access_.size()) {
Brian Silvermanfee16972021-09-14 12:06:38 -07001493 CHECK(!next_message_reader_);
Austin Schuhc41603c2020-10-11 16:17:37 -07001494 done_ = true;
1495 return;
1496 }
Brian Silvermanfee16972021-09-14 12:06:38 -07001497 CHECK(next_message_reader_);
1498 message_reader_ = std::move(*next_message_reader_);
Austin Schuh48507722021-07-17 17:29:24 -07001499 ComputeBootCounts();
Alexei Strots58017402023-05-03 22:05:06 -07001500 if (next_part_index_ + 1 < log_parts_access_.size()) {
1501 next_message_reader_.emplace(
1502 MakeSpanReader(log_parts_access_, next_part_index_ + 1));
Brian Silvermanfee16972021-09-14 12:06:38 -07001503 } else {
1504 next_message_reader_.reset();
1505 }
Austin Schuhc41603c2020-10-11 16:17:37 -07001506 ++next_part_index_;
1507}
1508
Austin Schuh1be0ce42020-11-29 22:43:26 -08001509bool Message::operator<(const Message &m2) const {
Austin Schuh63097262023-08-16 17:04:29 -07001510 if (this->timestamp < m2.timestamp) {
Austin Schuh1be0ce42020-11-29 22:43:26 -08001511 return true;
Austin Schuh63097262023-08-16 17:04:29 -07001512 } else if (this->timestamp > m2.timestamp) {
Austin Schuh1be0ce42020-11-29 22:43:26 -08001513 return false;
1514 }
1515
1516 if (this->channel_index < m2.channel_index) {
1517 return true;
1518 } else if (this->channel_index > m2.channel_index) {
1519 return false;
1520 }
1521
1522 return this->queue_index < m2.queue_index;
1523}
1524
1525bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001526bool Message::operator==(const Message &m2) const {
Austin Schuh63097262023-08-16 17:04:29 -07001527 return timestamp == m2.timestamp && channel_index == m2.channel_index &&
1528 queue_index == m2.queue_index;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001529}
Austin Schuh1be0ce42020-11-29 22:43:26 -08001530
Austin Schuh63097262023-08-16 17:04:29 -07001531bool Message::operator<=(const Message &m2) const {
1532 return *this == m2 || *this < m2;
1533}
1534
1535std::ostream &operator<<(std::ostream &os, const UnpackedMessageHeader &msg) {
1536 os << "{.channel_index=" << msg.channel_index
1537 << ", .monotonic_sent_time=" << msg.monotonic_sent_time
1538 << ", .realtime_sent_time=" << msg.realtime_sent_time
1539 << ", .queue_index=" << msg.queue_index;
1540 if (msg.monotonic_remote_time) {
1541 os << ", .monotonic_remote_time=" << *msg.monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001542 }
1543 os << ", .realtime_remote_time=";
Austin Schuh63097262023-08-16 17:04:29 -07001544 PrintOptionalOrNull(&os, msg.realtime_remote_time);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001545 os << ", .remote_queue_index=";
Austin Schuh63097262023-08-16 17:04:29 -07001546 PrintOptionalOrNull(&os, msg.remote_queue_index);
1547 if (msg.has_monotonic_timestamp_time) {
1548 os << ", .monotonic_timestamp_time=" << msg.monotonic_timestamp_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001549 }
Austin Schuh22cf7862022-09-19 19:09:42 -07001550 os << "}";
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001551 return os;
1552}
1553
Austin Schuh63097262023-08-16 17:04:29 -07001554std::ostream &operator<<(std::ostream &os, const Message &msg) {
1555 os << "{.channel_index=" << msg.channel_index
1556 << ", .queue_index=" << msg.queue_index
1557 << ", .timestamp=" << msg.timestamp;
1558 if (msg.data != nullptr) {
1559 if (msg.data->remote_queue_index.has_value()) {
1560 os << ", .remote_queue_index=" << *msg.data->remote_queue_index;
Austin Schuh826e6ce2021-11-18 20:33:10 -08001561 }
Austin Schuh63097262023-08-16 17:04:29 -07001562 if (msg.data->monotonic_remote_time.has_value()) {
1563 os << ", .monotonic_remote_time=" << *msg.data->monotonic_remote_time;
Austin Schuh826e6ce2021-11-18 20:33:10 -08001564 }
Austin Schuh63097262023-08-16 17:04:29 -07001565 os << ", .data=" << msg.data;
Austin Schuhd2f96102020-12-01 20:27:29 -08001566 }
1567 os << "}";
1568 return os;
1569}
1570
Austin Schuh63097262023-08-16 17:04:29 -07001571std::ostream &operator<<(std::ostream &os, const TimestampedMessage &msg) {
1572 os << "{.channel_index=" << msg.channel_index
1573 << ", .queue_index=" << msg.queue_index
1574 << ", .monotonic_event_time=" << msg.monotonic_event_time
1575 << ", .realtime_event_time=" << msg.realtime_event_time;
1576 if (msg.remote_queue_index != BootQueueIndex::Invalid()) {
1577 os << ", .remote_queue_index=" << msg.remote_queue_index;
Austin Schuhd2f96102020-12-01 20:27:29 -08001578 }
Austin Schuh63097262023-08-16 17:04:29 -07001579 if (msg.monotonic_remote_time != BootTimestamp::min_time()) {
1580 os << ", .monotonic_remote_time=" << msg.monotonic_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001581 }
Austin Schuh63097262023-08-16 17:04:29 -07001582 if (msg.realtime_remote_time != realtime_clock::min_time) {
1583 os << ", .realtime_remote_time=" << msg.realtime_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001584 }
Austin Schuh63097262023-08-16 17:04:29 -07001585 if (msg.monotonic_timestamp_time != BootTimestamp::min_time()) {
1586 os << ", .monotonic_timestamp_time=" << msg.monotonic_timestamp_time;
Austin Schuh8bf1e632021-01-02 22:41:04 -08001587 }
Austin Schuh63097262023-08-16 17:04:29 -07001588 if (msg.data != nullptr) {
1589 os << ", .data=" << *msg.data;
Austin Schuh22cf7862022-09-19 19:09:42 -07001590 } else {
1591 os << ", .data=nullptr";
Austin Schuhd2f96102020-12-01 20:27:29 -08001592 }
1593 os << "}";
Austin Schuh1be0ce42020-11-29 22:43:26 -08001594 return os;
1595}
1596
Alexei Strots58017402023-05-03 22:05:06 -07001597MessageSorter::MessageSorter(const LogPartsAccess log_parts_access)
1598 : parts_message_reader_(log_parts_access),
Austin Schuh48507722021-07-17 17:29:24 -07001599 source_node_index_(configuration::SourceNodeIndex(parts().config.get())) {
1600}
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001601
Adam Snaider13d48d92023-08-03 12:20:15 -07001602const Message *MessageSorter::Front() {
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001603 // Queue up data until enough data has been queued that the front message is
1604 // sorted enough to be safe to pop. This may do nothing, so we should make
1605 // sure the nothing path is checked quickly.
1606 if (sorted_until() != monotonic_clock::max_time) {
1607 while (true) {
Austin Schuh48507722021-07-17 17:29:24 -07001608 if (!messages_.empty() &&
1609 messages_.begin()->timestamp.time < sorted_until() &&
Austin Schuhb000de62020-12-03 22:00:40 -08001610 sorted_until() >= monotonic_start_time()) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001611 break;
1612 }
1613
Austin Schuh63097262023-08-16 17:04:29 -07001614 std::shared_ptr<UnpackedMessageHeader> msg =
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001615 parts_message_reader_.ReadMessage();
1616 // No data left, sorted forever, work through what is left.
Austin Schuh63097262023-08-16 17:04:29 -07001617 if (!msg) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001618 sorted_until_ = monotonic_clock::max_time;
1619 break;
1620 }
1621
Austin Schuh48507722021-07-17 17:29:24 -07001622 size_t monotonic_timestamp_boot = 0;
Austin Schuh63097262023-08-16 17:04:29 -07001623 if (msg->has_monotonic_timestamp_time) {
Austin Schuh48507722021-07-17 17:29:24 -07001624 monotonic_timestamp_boot = parts().logger_boot_count;
1625 }
1626 size_t monotonic_remote_boot = 0xffffff;
1627
Austin Schuh63097262023-08-16 17:04:29 -07001628 if (msg->monotonic_remote_time.has_value()) {
Maxwell Gumley8c1b87f2024-02-13 17:54:52 -07001629 CHECK_LT(msg->channel_index, source_node_index_.size());
Austin Schuh63097262023-08-16 17:04:29 -07001630 const Node *node = parts().config->nodes()->Get(
1631 source_node_index_[msg->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -07001632
Austin Schuh48507722021-07-17 17:29:24 -07001633 std::optional<size_t> boot = parts_message_reader_.boot_count(
Austin Schuh63097262023-08-16 17:04:29 -07001634 source_node_index_[msg->channel_index]);
Alexei Strots036d84e2023-05-03 16:05:12 -07001635 CHECK(boot) << ": Failed to find boot for node '" << MaybeNodeName(node)
Austin Schuh63097262023-08-16 17:04:29 -07001636 << "', with index "
1637 << source_node_index_[msg->channel_index];
Austin Schuh48507722021-07-17 17:29:24 -07001638 monotonic_remote_boot = *boot;
1639 }
1640
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001641 messages_.insert(
Austin Schuh63097262023-08-16 17:04:29 -07001642 Message{.channel_index = msg->channel_index,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001643 .queue_index = BootQueueIndex{.boot = parts().boot_count,
Austin Schuh63097262023-08-16 17:04:29 -07001644 .index = msg->queue_index},
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001645 .timestamp = BootTimestamp{.boot = parts().boot_count,
Austin Schuh63097262023-08-16 17:04:29 -07001646 .time = msg->monotonic_sent_time},
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001647 .monotonic_remote_boot = monotonic_remote_boot,
1648 .monotonic_timestamp_boot = monotonic_timestamp_boot,
Austin Schuh63097262023-08-16 17:04:29 -07001649 .data = std::move(msg)});
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001650
1651 // Now, update sorted_until_ to match the new message.
1652 if (parts_message_reader_.newest_timestamp() >
1653 monotonic_clock::min_time +
1654 parts_message_reader_.max_out_of_order_duration()) {
1655 sorted_until_ = parts_message_reader_.newest_timestamp() -
1656 parts_message_reader_.max_out_of_order_duration();
1657 } else {
1658 sorted_until_ = monotonic_clock::min_time;
1659 }
1660 }
1661 }
1662
1663 // Now that we have enough data queued, return a pointer to the oldest piece
1664 // of data if it exists.
1665 if (messages_.empty()) {
Austin Schuhb000de62020-12-03 22:00:40 -08001666 last_message_time_ = monotonic_clock::max_time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001667 return nullptr;
1668 }
1669
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001670 CHECK_GE(messages_.begin()->timestamp.time, last_message_time_)
Austin Schuh315b96b2020-12-11 21:21:12 -08001671 << DebugString() << " reading " << parts_message_reader_.filename();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001672 last_message_time_ = messages_.begin()->timestamp.time;
Austin Schuh63097262023-08-16 17:04:29 -07001673 VLOG(1) << this << " Front, sorted until " << sorted_until_ << " for "
1674 << (*messages_.begin()) << " on " << parts_message_reader_.filename();
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001675 return &(*messages_.begin());
1676}
1677
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001678void MessageSorter::PopFront() { messages_.erase(messages_.begin()); }
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001679
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001680std::string MessageSorter::DebugString() const {
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001681 std::stringstream ss;
1682 ss << "messages: [\n";
Austin Schuh315b96b2020-12-11 21:21:12 -08001683 int count = 0;
1684 bool no_dots = true;
Austin Schuh63097262023-08-16 17:04:29 -07001685 for (const Message &msg : messages_) {
Austin Schuh315b96b2020-12-11 21:21:12 -08001686 if (count < 15 || count > static_cast<int>(messages_.size()) - 15) {
Austin Schuh63097262023-08-16 17:04:29 -07001687 ss << msg << "\n";
Austin Schuh315b96b2020-12-11 21:21:12 -08001688 } else if (no_dots) {
1689 ss << "...\n";
1690 no_dots = false;
1691 }
1692 ++count;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001693 }
1694 ss << "] <- " << parts_message_reader_.filename();
1695 return ss.str();
1696}
1697
Austin Schuh63097262023-08-16 17:04:29 -07001698// Class to merge start times cleanly, reusably, and incrementally.
1699class StartTimes {
1700 public:
1701 void Update(monotonic_clock::time_point new_monotonic_start_time,
1702 realtime_clock::time_point new_realtime_start_time) {
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001703 // We want to capture the earliest meaningful start time here. The start
1704 // time defaults to min_time when there's no meaningful value to report, so
1705 // let's ignore those.
Austin Schuh63097262023-08-16 17:04:29 -07001706 if (new_monotonic_start_time != monotonic_clock::min_time) {
Austin Schuh9dc42612021-09-20 20:41:29 -07001707 bool accept = false;
1708 // We want to prioritize start times from the logger node. Really, we
1709 // want to prioritize start times with a valid realtime_clock time. So,
1710 // if we have a start time without a RT clock, prefer a start time with a
1711 // RT clock, even it if is later.
Austin Schuh63097262023-08-16 17:04:29 -07001712 if (new_realtime_start_time != realtime_clock::min_time) {
Austin Schuh9dc42612021-09-20 20:41:29 -07001713 // We've got a good one. See if the current start time has a good RT
1714 // clock, or if we should use this one instead.
Austin Schuh63097262023-08-16 17:04:29 -07001715 if (new_monotonic_start_time < monotonic_start_time_ ||
1716 monotonic_start_time_ == monotonic_clock::min_time) {
Austin Schuh9dc42612021-09-20 20:41:29 -07001717 accept = true;
1718 } else if (realtime_start_time_ == realtime_clock::min_time) {
1719 // The previous start time doesn't have a good RT time, so it is very
1720 // likely the start time from a remote part file. We just found a
1721 // better start time with a real RT time, so switch to that instead.
1722 accept = true;
1723 }
1724 } else if (realtime_start_time_ == realtime_clock::min_time) {
1725 // We don't have a RT time, so take the oldest.
Austin Schuh63097262023-08-16 17:04:29 -07001726 if (new_monotonic_start_time < monotonic_start_time_ ||
1727 monotonic_start_time_ == monotonic_clock::min_time) {
Austin Schuh9dc42612021-09-20 20:41:29 -07001728 accept = true;
1729 }
1730 }
1731
1732 if (accept) {
Austin Schuh63097262023-08-16 17:04:29 -07001733 monotonic_start_time_ = new_monotonic_start_time;
1734 realtime_start_time_ = new_realtime_start_time;
Austin Schuh9dc42612021-09-20 20:41:29 -07001735 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001736 }
1737 }
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001738
Austin Schuh63097262023-08-16 17:04:29 -07001739 monotonic_clock::time_point monotonic_start_time() const {
1740 return monotonic_start_time_;
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001741 }
Austin Schuh63097262023-08-16 17:04:29 -07001742 realtime_clock::time_point realtime_start_time() const {
1743 return realtime_start_time_;
1744 }
1745
1746 private:
1747 monotonic_clock::time_point monotonic_start_time_ = monotonic_clock::min_time;
1748 realtime_clock::time_point realtime_start_time_ = realtime_clock::min_time;
1749};
1750
1751PartsMerger::PartsMerger(SelectedLogParts &&parts) {
1752 node_ = configuration::GetNodeIndex(parts.config().get(), parts.node_name());
1753
1754 for (LogPartsAccess part : parts) {
1755 message_sorters_.emplace_back(std::move(part));
1756 }
1757
1758 StartTimes start_times;
1759 for (const MessageSorter &message_sorter : message_sorters_) {
1760 start_times.Update(message_sorter.monotonic_start_time(),
1761 message_sorter.realtime_start_time());
1762 }
1763 monotonic_start_time_ = start_times.monotonic_start_time();
1764 realtime_start_time_ = start_times.realtime_start_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08001765}
Austin Schuh8f52ed52020-11-30 23:12:39 -08001766
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001767std::vector<const LogParts *> PartsMerger::Parts() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001768 std::vector<const LogParts *> p;
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001769 p.reserve(message_sorters_.size());
1770 for (const MessageSorter &message_sorter : message_sorters_) {
1771 p.emplace_back(&message_sorter.parts());
Austin Schuh0ca51f32020-12-25 21:51:45 -08001772 }
1773 return p;
1774}
1775
Adam Snaider13d48d92023-08-03 12:20:15 -07001776const Message *PartsMerger::Front() {
Austin Schuh8f52ed52020-11-30 23:12:39 -08001777 // Return the current Front if we have one, otherwise go compute one.
1778 if (current_ != nullptr) {
Adam Snaider13d48d92023-08-03 12:20:15 -07001779 const Message *result = current_->Front();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001780 CHECK_GE(result->timestamp.time, last_message_time_);
Austin Schuh63097262023-08-16 17:04:29 -07001781 VLOG(1) << this << " PartsMerger::Front for node " << node_name() << " "
1782 << *result;
Austin Schuhb000de62020-12-03 22:00:40 -08001783 return result;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001784 }
1785
1786 // Otherwise, do a simple search for the oldest message, deduplicating any
1787 // duplicates.
Adam Snaider13d48d92023-08-03 12:20:15 -07001788 const Message *oldest = nullptr;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001789 sorted_until_ = monotonic_clock::max_time;
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001790 for (MessageSorter &message_sorter : message_sorters_) {
Adam Snaider13d48d92023-08-03 12:20:15 -07001791 const Message *msg = message_sorter.Front();
Austin Schuh63097262023-08-16 17:04:29 -07001792 if (!msg) {
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001793 sorted_until_ = std::min(sorted_until_, message_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001794 continue;
1795 }
Austin Schuh63097262023-08-16 17:04:29 -07001796 if (oldest == nullptr || *msg < *oldest) {
1797 oldest = msg;
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001798 current_ = &message_sorter;
Austin Schuh63097262023-08-16 17:04:29 -07001799 } else if (*msg == *oldest) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001800 // Found a duplicate. If there is a choice, we want the one which has
1801 // the timestamp time.
Austin Schuh63097262023-08-16 17:04:29 -07001802 if (!msg->data->has_monotonic_timestamp_time) {
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001803 message_sorter.PopFront();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001804 } else if (!oldest->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001805 current_->PopFront();
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001806 current_ = &message_sorter;
Austin Schuh63097262023-08-16 17:04:29 -07001807 oldest = msg;
Austin Schuh8bf1e632021-01-02 22:41:04 -08001808 } else {
Austin Schuh63097262023-08-16 17:04:29 -07001809 CHECK_EQ(msg->data->monotonic_timestamp_time,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001810 oldest->data->monotonic_timestamp_time);
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001811 message_sorter.PopFront();
Austin Schuh8bf1e632021-01-02 22:41:04 -08001812 }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001813 }
1814
1815 // PopFront may change this, so compute it down here.
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001816 sorted_until_ = std::min(sorted_until_, message_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001817 }
1818
Austin Schuhb000de62020-12-03 22:00:40 -08001819 if (oldest) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001820 CHECK_GE(oldest->timestamp.time, last_message_time_);
1821 last_message_time_ = oldest->timestamp.time;
Austin Schuh63097262023-08-16 17:04:29 -07001822 if (monotonic_oldest_time_ > oldest->timestamp.time) {
1823 VLOG(1) << this << " Updating oldest to " << oldest->timestamp.time
1824 << " for node " << node_name() << " with a start time of "
1825 << monotonic_start_time_ << " " << *oldest;
1826 }
Austin Schuh5dd22842021-11-17 16:09:39 -08001827 monotonic_oldest_time_ =
1828 std::min(monotonic_oldest_time_, oldest->timestamp.time);
Austin Schuhb000de62020-12-03 22:00:40 -08001829 } else {
1830 last_message_time_ = monotonic_clock::max_time;
1831 }
1832
Austin Schuh8f52ed52020-11-30 23:12:39 -08001833 // Return the oldest message found. This will be nullptr if nothing was
1834 // found, indicating there is nothing left.
Austin Schuh63097262023-08-16 17:04:29 -07001835 if (oldest) {
1836 VLOG(1) << this << " PartsMerger::Front for node " << node_name() << " "
1837 << *oldest;
1838 } else {
1839 VLOG(1) << this << " PartsMerger::Front for node " << node_name();
1840 }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001841 return oldest;
1842}
1843
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001844void PartsMerger::PopFront() {
Austin Schuh8f52ed52020-11-30 23:12:39 -08001845 CHECK(current_ != nullptr) << "Popping before calling Front()";
1846 current_->PopFront();
1847 current_ = nullptr;
1848}
1849
Alexei Strots1f51ac72023-05-15 10:14:54 -07001850BootMerger::BootMerger(std::string_view node_name,
Austin Schuh63097262023-08-16 17:04:29 -07001851 const LogFilesContainer &log_files,
1852 const std::vector<StoredDataType> &types)
1853 : configuration_(log_files.config()),
1854 node_(configuration::GetNodeIndex(configuration_.get(), node_name)) {
Alexei Strots1f51ac72023-05-15 10:14:54 -07001855 size_t number_of_boots = log_files.BootsForNode(node_name);
1856 parts_mergers_.reserve(number_of_boots);
1857 for (size_t i = 0; i < number_of_boots; ++i) {
Austin Schuh48507722021-07-17 17:29:24 -07001858 VLOG(2) << "Boot " << i;
Austin Schuh63097262023-08-16 17:04:29 -07001859 SelectedLogParts selected_parts =
1860 log_files.SelectParts(node_name, i, types);
1861 // We are guarenteed to have something each boot, but not guarenteed to have
1862 // both timestamps and data for each boot. If we don't have anything, don't
1863 // create a parts merger. The rest of this class will detect that and
1864 // ignore it as required.
1865 if (selected_parts.empty()) {
1866 parts_mergers_.emplace_back(nullptr);
1867 } else {
1868 parts_mergers_.emplace_back(
1869 std::make_unique<PartsMerger>(std::move(selected_parts)));
1870 }
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001871 }
1872}
1873
Austin Schuh63097262023-08-16 17:04:29 -07001874std::string_view BootMerger::node_name() const {
1875 return configuration::NodeName(configuration().get(), node());
1876}
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001877
Adam Snaider13d48d92023-08-03 12:20:15 -07001878const Message *BootMerger::Front() {
Austin Schuh63097262023-08-16 17:04:29 -07001879 if (parts_mergers_[index_].get() != nullptr) {
Adam Snaider13d48d92023-08-03 12:20:15 -07001880 const Message *result = parts_mergers_[index_]->Front();
Austin Schuh63097262023-08-16 17:04:29 -07001881
1882 if (result != nullptr) {
1883 VLOG(1) << this << " BootMerger::Front " << node_name() << " " << *result;
1884 return result;
1885 }
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001886 }
1887
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001888 if (index_ + 1u == parts_mergers_.size()) {
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001889 // At the end of the last node merger, just return.
Austin Schuh63097262023-08-16 17:04:29 -07001890 VLOG(1) << this << " BootMerger::Front " << node_name() << " nullptr";
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001891 return nullptr;
1892 } else {
1893 ++index_;
Adam Snaider13d48d92023-08-03 12:20:15 -07001894 const Message *result = Front();
Austin Schuh63097262023-08-16 17:04:29 -07001895 VLOG(1) << this << " BootMerger::Front " << node_name() << " " << *result;
1896 return result;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001897 }
1898}
1899
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001900void BootMerger::PopFront() { parts_mergers_[index_]->PopFront(); }
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001901
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001902std::vector<const LogParts *> BootMerger::Parts() const {
1903 std::vector<const LogParts *> results;
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001904 for (const std::unique_ptr<PartsMerger> &parts_merger : parts_mergers_) {
Austin Schuh63097262023-08-16 17:04:29 -07001905 if (!parts_merger) continue;
1906
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001907 std::vector<const LogParts *> node_parts = parts_merger->Parts();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001908
1909 results.insert(results.end(), std::make_move_iterator(node_parts.begin()),
1910 std::make_move_iterator(node_parts.end()));
1911 }
1912
1913 return results;
1914}
1915
Austin Schuh63097262023-08-16 17:04:29 -07001916monotonic_clock::time_point BootMerger::monotonic_start_time(
1917 size_t boot) const {
1918 CHECK_LT(boot, parts_mergers_.size());
1919 if (parts_mergers_[boot]) {
1920 return parts_mergers_[boot]->monotonic_start_time();
Austin Schuh0ca51f32020-12-25 21:51:45 -08001921 }
Austin Schuh63097262023-08-16 17:04:29 -07001922 return monotonic_clock::min_time;
1923}
1924
1925realtime_clock::time_point BootMerger::realtime_start_time(size_t boot) const {
1926 CHECK_LT(boot, parts_mergers_.size());
1927 if (parts_mergers_[boot]) {
1928 return parts_mergers_[boot]->realtime_start_time();
1929 }
1930 return realtime_clock::min_time;
1931}
1932
1933monotonic_clock::time_point BootMerger::monotonic_oldest_time(
1934 size_t boot) const {
1935 CHECK_LT(boot, parts_mergers_.size());
1936 if (parts_mergers_[boot]) {
1937 return parts_mergers_[boot]->monotonic_oldest_time();
1938 }
1939 return monotonic_clock::max_time;
1940}
1941
1942bool BootMerger::started() const {
1943 if (index_ == 0) {
1944 if (!parts_mergers_[0]) {
1945 return false;
1946 }
1947 return parts_mergers_[index_]->sorted_until() != monotonic_clock::min_time;
1948 }
1949 return true;
1950}
1951
1952SplitTimestampBootMerger::SplitTimestampBootMerger(
1953 std::string_view node_name, const LogFilesContainer &log_files,
1954 TimestampQueueStrategy timestamp_queue_strategy)
1955 : boot_merger_(node_name, log_files,
1956 (timestamp_queue_strategy ==
1957 TimestampQueueStrategy::kQueueTimestampsAtStartup)
1958 ? std::vector<StoredDataType>{StoredDataType::DATA}
1959 : std::vector<StoredDataType>{
1960 StoredDataType::DATA, StoredDataType::TIMESTAMPS,
1961 StoredDataType::REMOTE_TIMESTAMPS}) {
1962 // Make the timestamp_boot_merger_ only if we are asked to, and if there are
1963 // files to put in it. We don't need it for a data only log.
1964 if (timestamp_queue_strategy ==
1965 TimestampQueueStrategy::kQueueTimestampsAtStartup &&
1966 log_files.HasTimestamps(node_name)) {
1967 timestamp_boot_merger_ = std::make_unique<BootMerger>(
1968 node_name, log_files,
1969 std::vector<StoredDataType>{StoredDataType::TIMESTAMPS,
1970 StoredDataType::REMOTE_TIMESTAMPS});
1971 }
1972
1973 size_t number_of_boots = log_files.BootsForNode(node_name);
1974 monotonic_start_time_.reserve(number_of_boots);
1975 realtime_start_time_.reserve(number_of_boots);
1976
1977 // Start times are split across the timestamp boot merger, and data boot
1978 // merger. Pull from both and combine them to get the same answer as before.
1979 for (size_t i = 0u; i < number_of_boots; ++i) {
1980 StartTimes start_times;
1981
1982 if (timestamp_boot_merger_) {
1983 start_times.Update(timestamp_boot_merger_->monotonic_start_time(i),
1984 timestamp_boot_merger_->realtime_start_time(i));
1985 }
1986
1987 start_times.Update(boot_merger_.monotonic_start_time(i),
1988 boot_merger_.realtime_start_time(i));
1989
1990 monotonic_start_time_.push_back(start_times.monotonic_start_time());
1991 realtime_start_time_.push_back(start_times.realtime_start_time());
1992 }
1993}
1994
1995void SplitTimestampBootMerger::QueueTimestamps(
1996 std::function<void(TimestampedMessage *)> fn,
1997 const std::vector<size_t> &source_node) {
1998 if (!timestamp_boot_merger_) {
1999 return;
2000 }
2001
2002 while (true) {
2003 // Load all the timestamps. If we find data, ignore it and drop it on the
2004 // floor. It will be read when boot_merger_ is used.
Adam Snaider13d48d92023-08-03 12:20:15 -07002005 const Message *msg = timestamp_boot_merger_->Front();
Austin Schuh63097262023-08-16 17:04:29 -07002006 if (!msg) {
2007 queue_timestamps_ran_ = true;
2008 return;
2009 }
2010 if (source_node[msg->channel_index] != static_cast<size_t>(node())) {
2011 timestamp_messages_.emplace_back(TimestampedMessage{
2012 .channel_index = msg->channel_index,
2013 .queue_index = msg->queue_index,
2014 .monotonic_event_time = msg->timestamp,
2015 .realtime_event_time = msg->data->realtime_sent_time,
2016 .remote_queue_index =
2017 BootQueueIndex{.boot = msg->monotonic_remote_boot,
2018 .index = msg->data->remote_queue_index.value()},
2019 .monotonic_remote_time = {msg->monotonic_remote_boot,
2020 msg->data->monotonic_remote_time.value()},
2021 .realtime_remote_time = msg->data->realtime_remote_time.value(),
2022 .monotonic_timestamp_time = {msg->monotonic_timestamp_boot,
2023 msg->data->monotonic_timestamp_time},
2024 .data = std::move(msg->data)});
2025
2026 VLOG(2) << this << " Queued timestamp of " << timestamp_messages_.back();
2027 fn(&timestamp_messages_.back());
2028 } else {
2029 VLOG(2) << this << " Dropped data";
2030 }
2031 timestamp_boot_merger_->PopFront();
2032 }
2033
2034 // TODO(austin): Push the queue into TimestampMapper instead. Have it pull
2035 // all the timestamps. That will also make it so we don't have to clear the
2036 // function.
2037}
2038
2039std::string_view SplitTimestampBootMerger::node_name() const {
2040 return configuration::NodeName(configuration().get(), node());
2041}
2042
2043monotonic_clock::time_point SplitTimestampBootMerger::monotonic_start_time(
2044 size_t boot) const {
2045 CHECK_LT(boot, monotonic_start_time_.size());
2046 return monotonic_start_time_[boot];
2047}
2048
2049realtime_clock::time_point SplitTimestampBootMerger::realtime_start_time(
2050 size_t boot) const {
2051 CHECK_LT(boot, realtime_start_time_.size());
2052 return realtime_start_time_[boot];
2053}
2054
2055monotonic_clock::time_point SplitTimestampBootMerger::monotonic_oldest_time(
2056 size_t boot) const {
2057 if (!timestamp_boot_merger_) {
2058 return boot_merger_.monotonic_oldest_time(boot);
2059 }
2060 return std::min(boot_merger_.monotonic_oldest_time(boot),
2061 timestamp_boot_merger_->monotonic_oldest_time(boot));
2062}
2063
Adam Snaider13d48d92023-08-03 12:20:15 -07002064const Message *SplitTimestampBootMerger::Front() {
2065 const Message *boot_merger_front = boot_merger_.Front();
Austin Schuh63097262023-08-16 17:04:29 -07002066
2067 if (timestamp_boot_merger_) {
2068 CHECK(queue_timestamps_ran_);
2069 }
2070
2071 // timestamp_messages_ is a queue of TimestampedMessage, but we are supposed
2072 // to return a Message. We need to convert the first message in the list
2073 // before returning it (and comparing, honestly). Fill next_timestamp_ in if
2074 // it is empty so the rest of the logic here can just look at next_timestamp_
2075 // and use that instead.
2076 if (!next_timestamp_ && !timestamp_messages_.empty()) {
2077 auto &front = timestamp_messages_.front();
2078 next_timestamp_ = Message{
2079 .channel_index = front.channel_index,
2080 .queue_index = front.queue_index,
2081 .timestamp = front.monotonic_event_time,
2082 .monotonic_remote_boot = front.remote_queue_index.boot,
2083 .monotonic_timestamp_boot = front.monotonic_timestamp_time.boot,
2084 .data = std::move(front.data),
2085 };
2086 timestamp_messages_.pop_front();
2087 }
2088
2089 if (!next_timestamp_) {
2090 message_source_ = MessageSource::kBootMerger;
2091 if (boot_merger_front != nullptr) {
2092 VLOG(1) << this << " SplitTimestampBootMerger::Front " << node_name()
2093 << " " << *boot_merger_front;
2094 } else {
2095 VLOG(1) << this << " SplitTimestampBootMerger::Front " << node_name()
2096 << " nullptr";
2097 }
2098 return boot_merger_front;
2099 }
2100
2101 if (boot_merger_front == nullptr) {
2102 message_source_ = MessageSource::kTimestampMessage;
2103
2104 VLOG(1) << this << " SplitTimestampBootMerger::Front " << node_name() << " "
2105 << next_timestamp_.value();
2106 return &next_timestamp_.value();
2107 }
2108
2109 if (*boot_merger_front <= next_timestamp_.value()) {
2110 if (*boot_merger_front == next_timestamp_.value()) {
2111 VLOG(1) << this << " SplitTimestampBootMerger::Front " << node_name()
2112 << " Dropping duplicate timestamp.";
2113 next_timestamp_.reset();
2114 }
2115 message_source_ = MessageSource::kBootMerger;
2116 if (boot_merger_front != nullptr) {
2117 VLOG(1) << this << " SplitTimestampBootMerger::Front " << node_name()
2118 << " " << *boot_merger_front;
2119 } else {
2120 VLOG(1) << this << " SplitTimestampBootMerger::Front " << node_name()
2121 << " nullptr";
2122 }
2123 return boot_merger_front;
2124 } else {
2125 message_source_ = MessageSource::kTimestampMessage;
2126 VLOG(1) << this << " SplitTimestampBootMerger::Front " << node_name() << " "
2127 << next_timestamp_.value();
2128 return &next_timestamp_.value();
2129 }
2130}
2131
2132void SplitTimestampBootMerger::PopFront() {
2133 switch (message_source_) {
2134 case MessageSource::kTimestampMessage:
2135 CHECK(next_timestamp_.has_value());
2136 next_timestamp_.reset();
2137 break;
2138 case MessageSource::kBootMerger:
2139 boot_merger_.PopFront();
2140 break;
2141 }
2142}
2143
2144TimestampMapper::TimestampMapper(
2145 std::string_view node_name, const LogFilesContainer &log_files,
2146 TimestampQueueStrategy timestamp_queue_strategy)
2147 : boot_merger_(node_name, log_files, timestamp_queue_strategy),
2148 timestamp_callback_([](TimestampedMessage *) {}) {
2149 configuration_ = boot_merger_.configuration();
2150
Austin Schuh0ca51f32020-12-25 21:51:45 -08002151 const Configuration *config = configuration_.get();
Alexei Strots1f51ac72023-05-15 10:14:54 -07002152 // Only fill out nodes_data_ if there are nodes. Otherwise, everything is
Austin Schuhd2f96102020-12-01 20:27:29 -08002153 // pretty simple.
2154 if (configuration::MultiNode(config)) {
2155 nodes_data_.resize(config->nodes()->size());
2156 const Node *my_node = config->nodes()->Get(node());
2157 for (size_t node_index = 0; node_index < nodes_data_.size(); ++node_index) {
2158 const Node *node = config->nodes()->Get(node_index);
2159 NodeData *node_data = &nodes_data_[node_index];
2160 node_data->channels.resize(config->channels()->size());
2161 // We should save the channel if it is delivered to the node represented
2162 // by the NodeData, but not sent by that node. That combo means it is
2163 // forwarded.
2164 size_t channel_index = 0;
2165 node_data->any_delivered = false;
2166 for (const Channel *channel : *config->channels()) {
2167 node_data->channels[channel_index].delivered =
2168 configuration::ChannelIsReadableOnNode(channel, node) &&
Austin Schuhb3dbb6d2021-01-02 17:29:35 -08002169 configuration::ChannelIsSendableOnNode(channel, my_node) &&
2170 (my_node != node);
Austin Schuhd2f96102020-12-01 20:27:29 -08002171 node_data->any_delivered = node_data->any_delivered ||
2172 node_data->channels[channel_index].delivered;
Austin Schuh6a7358f2021-11-18 22:40:40 -08002173 if (node_data->channels[channel_index].delivered) {
2174 const Connection *connection =
2175 configuration::ConnectionToNode(channel, node);
2176 node_data->channels[channel_index].time_to_live =
2177 chrono::nanoseconds(connection->time_to_live());
2178 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002179 ++channel_index;
2180 }
2181 }
2182
2183 for (const Channel *channel : *config->channels()) {
2184 source_node_.emplace_back(configuration::GetNodeIndex(
2185 config, channel->source_node()->string_view()));
2186 }
2187 }
2188}
2189
2190void TimestampMapper::AddPeer(TimestampMapper *timestamp_mapper) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08002191 CHECK(configuration::MultiNode(configuration()));
Austin Schuhd2f96102020-12-01 20:27:29 -08002192 CHECK_NE(timestamp_mapper->node(), node());
2193 CHECK_LT(timestamp_mapper->node(), nodes_data_.size());
2194
2195 NodeData *node_data = &nodes_data_[timestamp_mapper->node()];
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002196 // Only set it if this node delivers to the peer timestamp_mapper. Otherwise
Austin Schuhd2f96102020-12-01 20:27:29 -08002197 // we could needlessly save data.
2198 if (node_data->any_delivered) {
Austin Schuh87dd3832021-01-01 23:07:31 -08002199 VLOG(1) << "Registering on node " << node() << " for peer node "
2200 << timestamp_mapper->node();
Austin Schuhd2f96102020-12-01 20:27:29 -08002201 CHECK(timestamp_mapper->nodes_data_[node()].peer == nullptr);
2202
2203 timestamp_mapper->nodes_data_[node()].peer = this;
Austin Schuh36c00932021-07-19 18:13:21 -07002204
2205 node_data->save_for_peer = true;
Austin Schuhd2f96102020-12-01 20:27:29 -08002206 }
2207}
2208
Adam Snaider13d48d92023-08-03 12:20:15 -07002209void TimestampMapper::QueueMessage(const Message *msg) {
Austin Schuh60e77942022-05-16 17:48:24 -07002210 matched_messages_.emplace_back(
Austin Schuh63097262023-08-16 17:04:29 -07002211 TimestampedMessage{.channel_index = msg->channel_index,
2212 .queue_index = msg->queue_index,
2213 .monotonic_event_time = msg->timestamp,
2214 .realtime_event_time = msg->data->realtime_sent_time,
Austin Schuh60e77942022-05-16 17:48:24 -07002215 .remote_queue_index = BootQueueIndex::Invalid(),
2216 .monotonic_remote_time = BootTimestamp::min_time(),
2217 .realtime_remote_time = realtime_clock::min_time,
2218 .monotonic_timestamp_time = BootTimestamp::min_time(),
Austin Schuh63097262023-08-16 17:04:29 -07002219 .data = std::move(msg->data)});
2220 VLOG(1) << node_name() << " Inserted " << matched_messages_.back();
Austin Schuhd2f96102020-12-01 20:27:29 -08002221}
2222
2223TimestampedMessage *TimestampMapper::Front() {
2224 // No need to fetch anything new. A previous message still exists.
2225 switch (first_message_) {
2226 case FirstMessage::kNeedsUpdate:
2227 break;
2228 case FirstMessage::kInMessage:
Austin Schuh63097262023-08-16 17:04:29 -07002229 VLOG(1) << this << " TimestampMapper::Front " << node_name() << " "
2230 << matched_messages_.front();
Austin Schuh79b30942021-01-24 22:32:21 -08002231 return &matched_messages_.front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002232 case FirstMessage::kNullptr:
Austin Schuh63097262023-08-16 17:04:29 -07002233 VLOG(1) << this << " TimestampMapper::Front " << node_name()
2234 << " nullptr";
Austin Schuhd2f96102020-12-01 20:27:29 -08002235 return nullptr;
2236 }
2237
Austin Schuh79b30942021-01-24 22:32:21 -08002238 if (matched_messages_.empty()) {
2239 if (!QueueMatched()) {
2240 first_message_ = FirstMessage::kNullptr;
Austin Schuh63097262023-08-16 17:04:29 -07002241 VLOG(1) << this << " TimestampMapper::Front " << node_name()
2242 << " nullptr";
Austin Schuh79b30942021-01-24 22:32:21 -08002243 return nullptr;
2244 }
2245 }
2246 first_message_ = FirstMessage::kInMessage;
Austin Schuh63097262023-08-16 17:04:29 -07002247 VLOG(1) << this << " TimestampMapper::Front " << node_name() << " "
2248 << matched_messages_.front();
Austin Schuh79b30942021-01-24 22:32:21 -08002249 return &matched_messages_.front();
2250}
2251
2252bool TimestampMapper::QueueMatched() {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002253 MatchResult result = MatchResult::kEndOfFile;
2254 do {
2255 result = MaybeQueueMatched();
2256 } while (result == MatchResult::kSkipped);
2257 return result == MatchResult::kQueued;
2258}
2259
2260bool TimestampMapper::CheckReplayChannelsAndMaybePop(
2261 const TimestampedMessage & /*message*/) {
2262 if (replay_channels_callback_ &&
2263 !replay_channels_callback_(matched_messages_.back())) {
Austin Schuh63097262023-08-16 17:04:29 -07002264 VLOG(1) << node_name() << " Popped " << matched_messages_.back();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002265 matched_messages_.pop_back();
2266 return true;
2267 }
2268 return false;
2269}
2270
2271TimestampMapper::MatchResult TimestampMapper::MaybeQueueMatched() {
Austin Schuhd2f96102020-12-01 20:27:29 -08002272 if (nodes_data_.empty()) {
2273 // Simple path. We are single node, so there are no timestamps to match!
2274 CHECK_EQ(messages_.size(), 0u);
Adam Snaider13d48d92023-08-03 12:20:15 -07002275 const Message *msg = boot_merger_.Front();
Austin Schuh63097262023-08-16 17:04:29 -07002276 if (!msg) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002277 return MatchResult::kEndOfFile;
Austin Schuhd2f96102020-12-01 20:27:29 -08002278 }
Austin Schuh79b30942021-01-24 22:32:21 -08002279 // Enqueue this message into matched_messages_ so we have a place to
2280 // associate remote timestamps, and return it.
Austin Schuh63097262023-08-16 17:04:29 -07002281 QueueMessage(msg);
Austin Schuhd2f96102020-12-01 20:27:29 -08002282
Austin Schuh63097262023-08-16 17:04:29 -07002283 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_)
2284 << " on " << node_name();
Austin Schuh79b30942021-01-24 22:32:21 -08002285 last_message_time_ = matched_messages_.back().monotonic_event_time;
2286
Alexei Strotsa8dadd12023-04-28 15:19:23 -07002287 // We are thin wrapper around parts_merger. Call it directly.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002288 boot_merger_.PopFront();
Austin Schuh79b30942021-01-24 22:32:21 -08002289 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002290 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2291 return MatchResult::kSkipped;
2292 }
2293 return MatchResult::kQueued;
Austin Schuhd2f96102020-12-01 20:27:29 -08002294 }
2295
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002296 // We need to only add messages to the list so they get processed for
2297 // messages which are delivered. Reuse the flow below which uses messages_
2298 // by just adding the new message to messages_ and continuing.
Austin Schuhd2f96102020-12-01 20:27:29 -08002299 if (messages_.empty()) {
2300 if (!Queue()) {
2301 // Found nothing to add, we are out of data!
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002302 return MatchResult::kEndOfFile;
Austin Schuhd2f96102020-12-01 20:27:29 -08002303 }
2304
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002305 // Now that it has been added (and cannibalized), forget about it
2306 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002307 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08002308 }
2309
Austin Schuh63097262023-08-16 17:04:29 -07002310 Message *msg = &(messages_.front());
Austin Schuhd2f96102020-12-01 20:27:29 -08002311
Austin Schuh63097262023-08-16 17:04:29 -07002312 if (source_node_[msg->channel_index] == node()) {
Austin Schuhd2f96102020-12-01 20:27:29 -08002313 // From us, just forward it on, filling the remote data in as invalid.
Austin Schuh63097262023-08-16 17:04:29 -07002314 QueueMessage(msg);
2315 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_)
2316 << " on " << node_name();
Austin Schuh79b30942021-01-24 22:32:21 -08002317 last_message_time_ = matched_messages_.back().monotonic_event_time;
2318 messages_.pop_front();
2319 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002320 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2321 return MatchResult::kSkipped;
2322 }
2323 return MatchResult::kQueued;
Austin Schuhd2f96102020-12-01 20:27:29 -08002324 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002325 // Got a timestamp, find the matching remote data, match it, and return
2326 // it.
Austin Schuh63097262023-08-16 17:04:29 -07002327 Message data = MatchingMessageFor(*msg);
Austin Schuhd2f96102020-12-01 20:27:29 -08002328
2329 // Return the data from the remote. The local message only has timestamp
2330 // info which isn't relevant anymore once extracted.
Austin Schuh79b30942021-01-24 22:32:21 -08002331 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuh63097262023-08-16 17:04:29 -07002332 .channel_index = msg->channel_index,
2333 .queue_index = msg->queue_index,
2334 .monotonic_event_time = msg->timestamp,
2335 .realtime_event_time = msg->data->realtime_sent_time,
Austin Schuh58646e22021-08-23 23:51:46 -07002336 .remote_queue_index =
Austin Schuh63097262023-08-16 17:04:29 -07002337 BootQueueIndex{.boot = msg->monotonic_remote_boot,
2338 .index = msg->data->remote_queue_index.value()},
2339 .monotonic_remote_time = {msg->monotonic_remote_boot,
2340 msg->data->monotonic_remote_time.value()},
2341 .realtime_remote_time = msg->data->realtime_remote_time.value(),
2342 .monotonic_timestamp_time = {msg->monotonic_timestamp_boot,
2343 msg->data->monotonic_timestamp_time},
Austin Schuh79b30942021-01-24 22:32:21 -08002344 .data = std::move(data.data)});
Austin Schuh63097262023-08-16 17:04:29 -07002345 VLOG(1) << node_name() << " Inserted timestamp "
2346 << matched_messages_.back();
2347 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_)
2348 << " on " << node_name() << " " << matched_messages_.back();
Austin Schuh79b30942021-01-24 22:32:21 -08002349 last_message_time_ = matched_messages_.back().monotonic_event_time;
2350 // Since messages_ holds the data, drop it.
2351 messages_.pop_front();
2352 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002353 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2354 return MatchResult::kSkipped;
2355 }
2356 return MatchResult::kQueued;
Austin Schuh79b30942021-01-24 22:32:21 -08002357 }
2358}
2359
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002360void TimestampMapper::QueueUntil(BootTimestamp queue_time) {
Austin Schuh79b30942021-01-24 22:32:21 -08002361 while (last_message_time_ <= queue_time) {
2362 if (!QueueMatched()) {
2363 return;
2364 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002365 }
2366}
2367
Austin Schuhe639ea12021-01-25 13:00:22 -08002368void TimestampMapper::QueueFor(chrono::nanoseconds time_estimation_buffer) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002369 // Note: queueing for time doesn't really work well across boots. So we
2370 // just assume that if you are using this, you only care about the current
2371 // boot.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002372 //
2373 // TODO(austin): Is that the right concept?
2374 //
Austin Schuhe639ea12021-01-25 13:00:22 -08002375 // Make sure we have something queued first. This makes the end time
2376 // calculation simpler, and is typically what folks want regardless.
2377 if (matched_messages_.empty()) {
2378 if (!QueueMatched()) {
2379 return;
2380 }
2381 }
2382
2383 const aos::monotonic_clock::time_point end_queue_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002384 std::max(monotonic_start_time(
2385 matched_messages_.front().monotonic_event_time.boot),
2386 matched_messages_.front().monotonic_event_time.time) +
Austin Schuhe639ea12021-01-25 13:00:22 -08002387 time_estimation_buffer;
2388
2389 // Place sorted messages on the list until we have
2390 // --time_estimation_buffer_seconds seconds queued up (but queue at least
2391 // until the log starts).
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002392 while (end_queue_time >= last_message_time_.time) {
Austin Schuhe639ea12021-01-25 13:00:22 -08002393 if (!QueueMatched()) {
2394 return;
2395 }
2396 }
2397}
2398
Austin Schuhd2f96102020-12-01 20:27:29 -08002399void TimestampMapper::PopFront() {
2400 CHECK(first_message_ != FirstMessage::kNeedsUpdate);
Austin Schuh6a7358f2021-11-18 22:40:40 -08002401 last_popped_message_time_ = Front()->monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08002402 first_message_ = FirstMessage::kNeedsUpdate;
2403
Austin Schuh63097262023-08-16 17:04:29 -07002404 VLOG(1) << node_name() << " Popped " << matched_messages_.back();
Austin Schuh79b30942021-01-24 22:32:21 -08002405 matched_messages_.pop_front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002406}
2407
2408Message TimestampMapper::MatchingMessageFor(const Message &message) {
Austin Schuhd2f96102020-12-01 20:27:29 -08002409 // Figure out what queue index we are looking for.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002410 CHECK_NOTNULL(message.data);
2411 CHECK(message.data->remote_queue_index.has_value());
Austin Schuh58646e22021-08-23 23:51:46 -07002412 const BootQueueIndex remote_queue_index =
2413 BootQueueIndex{.boot = message.monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002414 .index = *message.data->remote_queue_index};
Austin Schuhd2f96102020-12-01 20:27:29 -08002415
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002416 CHECK(message.data->monotonic_remote_time.has_value());
2417 CHECK(message.data->realtime_remote_time.has_value());
Austin Schuhd2f96102020-12-01 20:27:29 -08002418
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002419 const BootTimestamp monotonic_remote_time{
Austin Schuh48507722021-07-17 17:29:24 -07002420 .boot = message.monotonic_remote_boot,
Austin Schuh826e6ce2021-11-18 20:33:10 -08002421 .time = message.data->monotonic_remote_time.value()};
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002422 const realtime_clock::time_point realtime_remote_time =
2423 *message.data->realtime_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08002424
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002425 TimestampMapper *peer =
2426 nodes_data_[source_node_[message.data->channel_index]].peer;
Austin Schuhfecf1d82020-12-19 16:57:28 -08002427
2428 // We only register the peers which we have data for. So, if we are being
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002429 // asked to pull a timestamp from a peer which doesn't exist, return an
2430 // empty message.
Austin Schuhfecf1d82020-12-19 16:57:28 -08002431 if (peer == nullptr) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002432 // TODO(austin): Make sure the tests hit all these paths with a boot count
2433 // of 1...
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002434 return Message{.channel_index = message.channel_index,
2435 .queue_index = remote_queue_index,
2436 .timestamp = monotonic_remote_time,
2437 .monotonic_remote_boot = 0xffffff,
2438 .monotonic_timestamp_boot = 0xffffff,
2439 .data = nullptr};
Austin Schuhfecf1d82020-12-19 16:57:28 -08002440 }
2441
2442 // The queue which will have the matching data, if available.
2443 std::deque<Message> *data_queue =
2444 &peer->nodes_data_[node()].channels[message.channel_index].messages;
2445
Austin Schuh79b30942021-01-24 22:32:21 -08002446 peer->QueueUnmatchedUntil(monotonic_remote_time);
Austin Schuhd2f96102020-12-01 20:27:29 -08002447
2448 if (data_queue->empty()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002449 return Message{.channel_index = message.channel_index,
2450 .queue_index = remote_queue_index,
2451 .timestamp = monotonic_remote_time,
2452 .monotonic_remote_boot = 0xffffff,
2453 .monotonic_timestamp_boot = 0xffffff,
2454 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08002455 }
2456
Austin Schuhd2f96102020-12-01 20:27:29 -08002457 if (remote_queue_index < data_queue->front().queue_index ||
2458 remote_queue_index > data_queue->back().queue_index) {
Austin Schuh60e77942022-05-16 17:48:24 -07002459 return Message{.channel_index = message.channel_index,
2460 .queue_index = remote_queue_index,
2461 .timestamp = monotonic_remote_time,
2462 .monotonic_remote_boot = 0xffffff,
2463 .monotonic_timestamp_boot = 0xffffff,
2464 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08002465 }
2466
Austin Schuh993ccb52020-12-12 15:59:32 -08002467 // The algorithm below is constant time with some assumptions. We need there
2468 // to be no missing messages in the data stream. This also assumes a queue
2469 // hasn't wrapped. That is conservative, but should let us get started.
Austin Schuh58646e22021-08-23 23:51:46 -07002470 if (data_queue->back().queue_index.boot ==
2471 data_queue->front().queue_index.boot &&
2472 (data_queue->back().queue_index.index -
2473 data_queue->front().queue_index.index + 1u ==
2474 data_queue->size())) {
2475 CHECK_EQ(remote_queue_index.boot, data_queue->front().queue_index.boot);
Austin Schuh993ccb52020-12-12 15:59:32 -08002476 // Pull the data out and confirm that the timestamps match as expected.
Austin Schuh58646e22021-08-23 23:51:46 -07002477 //
2478 // TODO(austin): Move if not reliable.
2479 Message result = (*data_queue)[remote_queue_index.index -
2480 data_queue->front().queue_index.index];
Austin Schuh993ccb52020-12-12 15:59:32 -08002481
2482 CHECK_EQ(result.timestamp, monotonic_remote_time)
2483 << ": Queue index matches, but timestamp doesn't. Please investigate!";
Austin Schuh6a7358f2021-11-18 22:40:40 -08002484 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
Austin Schuh993ccb52020-12-12 15:59:32 -08002485 << ": Queue index matches, but timestamp doesn't. Please investigate!";
2486 // Now drop the data off the front. We have deduplicated timestamps, so we
2487 // are done. And all the data is in order.
Austin Schuh58646e22021-08-23 23:51:46 -07002488 data_queue->erase(
2489 data_queue->begin(),
2490 data_queue->begin() +
2491 (remote_queue_index.index - data_queue->front().queue_index.index));
Austin Schuh993ccb52020-12-12 15:59:32 -08002492 return result;
2493 } else {
Austin Schuh58646e22021-08-23 23:51:46 -07002494 // TODO(austin): Binary search.
2495 auto it = std::find_if(
2496 data_queue->begin(), data_queue->end(),
2497 [remote_queue_index,
Austin Schuh63097262023-08-16 17:04:29 -07002498 remote_boot = monotonic_remote_time.boot](const Message &msg) {
2499 return msg.queue_index == remote_queue_index &&
2500 msg.timestamp.boot == remote_boot;
Austin Schuh58646e22021-08-23 23:51:46 -07002501 });
Austin Schuh993ccb52020-12-12 15:59:32 -08002502 if (it == data_queue->end()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002503 return Message{.channel_index = message.channel_index,
2504 .queue_index = remote_queue_index,
2505 .timestamp = monotonic_remote_time,
2506 .monotonic_remote_boot = 0xffffff,
2507 .monotonic_timestamp_boot = 0xffffff,
2508 .data = nullptr};
Austin Schuh993ccb52020-12-12 15:59:32 -08002509 }
2510
2511 Message result = std::move(*it);
2512
2513 CHECK_EQ(result.timestamp, monotonic_remote_time)
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002514 << ": Queue index matches, but timestamp doesn't. Please "
2515 "investigate!";
2516 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
2517 << ": Queue index matches, but timestamp doesn't. Please "
2518 "investigate!";
Austin Schuh993ccb52020-12-12 15:59:32 -08002519
Austin Schuhd6b1f4c2021-11-18 20:29:00 -08002520 // Erase everything up to this message. We want to keep 1 message in the
2521 // queue so we can handle reliable messages forwarded across boots.
2522 data_queue->erase(data_queue->begin(), it);
Austin Schuh993ccb52020-12-12 15:59:32 -08002523
2524 return result;
2525 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002526}
2527
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002528void TimestampMapper::QueueUnmatchedUntil(BootTimestamp t) {
Austin Schuhd2f96102020-12-01 20:27:29 -08002529 if (queued_until_ > t) {
2530 return;
2531 }
2532 while (true) {
2533 if (!messages_.empty() && messages_.back().timestamp > t) {
2534 queued_until_ = std::max(queued_until_, messages_.back().timestamp);
2535 return;
2536 }
2537
2538 if (!Queue()) {
2539 // Found nothing to add, we are out of data!
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002540 queued_until_ = BootTimestamp::max_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08002541 return;
2542 }
2543
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002544 // Now that it has been added (and cannibalized), forget about it
2545 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002546 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08002547 }
2548}
2549
2550bool TimestampMapper::Queue() {
Adam Snaider13d48d92023-08-03 12:20:15 -07002551 const Message *msg = boot_merger_.Front();
Austin Schuh63097262023-08-16 17:04:29 -07002552 if (msg == nullptr) {
Austin Schuhd2f96102020-12-01 20:27:29 -08002553 return false;
2554 }
2555 for (NodeData &node_data : nodes_data_) {
2556 if (!node_data.any_delivered) continue;
Austin Schuh36c00932021-07-19 18:13:21 -07002557 if (!node_data.save_for_peer) continue;
Austin Schuh63097262023-08-16 17:04:29 -07002558 if (node_data.channels[msg->channel_index].delivered) {
Austin Schuh6a7358f2021-11-18 22:40:40 -08002559 // If we have data but no timestamps (logs where the timestamps didn't get
2560 // logged are classic), we can grow this indefinitely. We don't need to
2561 // keep anything that is older than the last message returned.
2562
2563 // We have the time on the source node.
2564 // We care to wait until we have the time on the destination node.
2565 std::deque<Message> &messages =
Austin Schuh63097262023-08-16 17:04:29 -07002566 node_data.channels[msg->channel_index].messages;
Austin Schuh6a7358f2021-11-18 22:40:40 -08002567 // Max delay over the network is the TTL, so let's take the queue time and
2568 // add TTL to it. Don't forget any messages which are reliable until
2569 // someone can come up with a good reason to forget those too.
Austin Schuh63097262023-08-16 17:04:29 -07002570 if (node_data.channels[msg->channel_index].time_to_live >
Austin Schuh6a7358f2021-11-18 22:40:40 -08002571 chrono::nanoseconds(0)) {
2572 // We need to make *some* assumptions about network delay for this to
2573 // work. We want to only look at the RX side. This means we need to
2574 // track the last time a message was popped from any channel from the
2575 // node sending this message, and compare that to the max time we expect
2576 // that a message will take to be delivered across the network. This
2577 // assumes that messages are popped in time order as a proxy for
2578 // measuring the distributed time at this layer.
2579 //
2580 // Leave at least 1 message in here so we can handle reboots and
2581 // messages getting sent twice.
2582 while (messages.size() > 1u &&
2583 messages.begin()->timestamp +
Austin Schuh63097262023-08-16 17:04:29 -07002584 node_data.channels[msg->channel_index].time_to_live +
Austin Schuh6a7358f2021-11-18 22:40:40 -08002585 chrono::duration_cast<chrono::nanoseconds>(
2586 chrono::duration<double>(FLAGS_max_network_delay)) <
2587 last_popped_message_time_) {
2588 messages.pop_front();
2589 }
2590 }
Austin Schuh63097262023-08-16 17:04:29 -07002591 node_data.channels[msg->channel_index].messages.emplace_back(*msg);
Austin Schuhd2f96102020-12-01 20:27:29 -08002592 }
2593 }
2594
Austin Schuh63097262023-08-16 17:04:29 -07002595 messages_.emplace_back(std::move(*msg));
Austin Schuhd2f96102020-12-01 20:27:29 -08002596 return true;
2597}
2598
Austin Schuh63097262023-08-16 17:04:29 -07002599void TimestampMapper::QueueTimestamps() {
2600 boot_merger_.QueueTimestamps(std::ref(timestamp_callback_), source_node_);
2601}
2602
Austin Schuhd2f96102020-12-01 20:27:29 -08002603std::string TimestampMapper::DebugString() const {
2604 std::stringstream ss;
Austin Schuh6e014b82021-09-14 17:46:33 -07002605 ss << "node " << node() << " (" << node_name() << ") [\n";
Austin Schuhd2f96102020-12-01 20:27:29 -08002606 for (const Message &message : messages_) {
2607 ss << " " << message << "\n";
2608 }
2609 ss << "] queued_until " << queued_until_;
2610 for (const NodeData &ns : nodes_data_) {
2611 if (ns.peer == nullptr) continue;
2612 ss << "\nnode " << ns.peer->node() << " remote_data [\n";
2613 size_t channel_index = 0;
2614 for (const NodeData::ChannelData &channel_data :
2615 ns.peer->nodes_data_[node()].channels) {
2616 if (channel_data.messages.empty()) {
2617 continue;
2618 }
Austin Schuhb000de62020-12-03 22:00:40 -08002619
Austin Schuhd2f96102020-12-01 20:27:29 -08002620 ss << " channel " << channel_index << " [\n";
Austin Schuh63097262023-08-16 17:04:29 -07002621 for (const Message &msg : channel_data.messages) {
2622 ss << " " << msg << "\n";
Austin Schuhd2f96102020-12-01 20:27:29 -08002623 }
2624 ss << " ]\n";
2625 ++channel_index;
2626 }
2627 ss << "] queued_until " << ns.peer->queued_until_;
2628 }
2629 return ss.str();
2630}
2631
Brian Silvermanf51499a2020-09-21 12:49:08 -07002632} // namespace aos::logger