blob: b76bcadac856865dc5aa440870b152a7bb5e87ac [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}
114} // namespace
115
Alexei Strotsbc082d82023-05-03 08:43:42 -0700116DetachedBufferWriter::DetachedBufferWriter(std::unique_ptr<LogSink> log_sink,
117 std::unique_ptr<DataEncoder> encoder)
118 : log_sink_(std::move(log_sink)), encoder_(std::move(encoder)) {
119 CHECK(log_sink_);
120 ran_out_of_space_ = log_sink_->OpenForWrite() == WriteCode::kOutOfSpace;
Alexei Strots01395492023-03-20 13:59:56 -0700121 if (ran_out_of_space_) {
122 LOG(WARNING) << "And we are out of space";
Austin Schuh4c3cdb72023-02-11 15:05:26 -0800123 }
124}
125
Austin Schuha36c8902019-12-30 18:07:15 -0800126DetachedBufferWriter::~DetachedBufferWriter() {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700127 Close();
128 if (ran_out_of_space_) {
129 CHECK(acknowledge_ran_out_of_space_)
130 << ": Unacknowledged out of disk space, log file was not completed";
Brian Silvermanf51499a2020-09-21 12:49:08 -0700131 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700132}
133
Brian Silvermand90905f2020-09-23 14:42:56 -0700134DetachedBufferWriter::DetachedBufferWriter(DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700135 *this = std::move(other);
136}
137
Brian Silverman87ac0402020-09-17 14:47:01 -0700138// When other is destroyed "soon" (which it should be because we're getting an
139// rvalue reference to it), it will flush etc all the data we have queued up
140// (because that data will then be its data).
Austin Schuh2f8fd752020-09-01 22:38:28 -0700141DetachedBufferWriter &DetachedBufferWriter::operator=(
142 DetachedBufferWriter &&other) {
Alexei Strotsbc082d82023-05-03 08:43:42 -0700143 std::swap(log_sink_, other.log_sink_);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700144 std::swap(encoder_, other.encoder_);
Brian Silverman0465fcf2020-09-24 00:29:18 -0700145 std::swap(ran_out_of_space_, other.ran_out_of_space_);
146 std::swap(acknowledge_ran_out_of_space_, other.acknowledge_ran_out_of_space_);
Austin Schuh4c3cdb72023-02-11 15:05:26 -0800147 std::swap(last_flush_time_, other.last_flush_time_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700148 return *this;
Austin Schuha36c8902019-12-30 18:07:15 -0800149}
150
Austin Schuh8bdfc492023-02-11 12:53:13 -0800151void DetachedBufferWriter::CopyMessage(DataEncoder::Copier *copier,
Austin Schuh7ef11a42023-02-04 17:15:12 -0800152 aos::monotonic_clock::time_point now) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -0700153 if (ran_out_of_space_) {
154 // We don't want any later data to be written after space becomes
155 // available, so refuse to write anything more once we've dropped data
156 // because we ran out of space.
Austin Schuh48d10d62022-10-16 22:19:23 -0700157 return;
Austin Schuha36c8902019-12-30 18:07:15 -0800158 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700159
Austin Schuh8bdfc492023-02-11 12:53:13 -0800160 const size_t message_size = copier->size();
161 size_t overall_bytes_written = 0;
Austin Schuh48d10d62022-10-16 22:19:23 -0700162
Austin Schuh8bdfc492023-02-11 12:53:13 -0800163 // Keep writing chunks until we've written it all. If we end up with a
164 // partial write, this means we need to flush to disk.
165 do {
Alexei Strots01395492023-03-20 13:59:56 -0700166 const size_t bytes_written =
167 encoder_->Encode(copier, overall_bytes_written);
Austin Schuh8bdfc492023-02-11 12:53:13 -0800168 CHECK(bytes_written != 0);
169
170 overall_bytes_written += bytes_written;
171 if (overall_bytes_written < message_size) {
172 VLOG(1) << "Flushing because of a partial write, tried to write "
173 << message_size << " wrote " << overall_bytes_written;
174 Flush(now);
175 }
176 } while (overall_bytes_written < message_size);
177
Austin Schuhbd06ae42021-03-31 22:48:21 -0700178 FlushAtThreshold(now);
Austin Schuha36c8902019-12-30 18:07:15 -0800179}
180
Brian Silverman0465fcf2020-09-24 00:29:18 -0700181void DetachedBufferWriter::Close() {
Alexei Strotsbc082d82023-05-03 08:43:42 -0700182 if (!log_sink_->is_open()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700183 return;
184 }
185 encoder_->Finish();
186 while (encoder_->queue_size() > 0) {
Austin Schuh8bdfc492023-02-11 12:53:13 -0800187 Flush(monotonic_clock::max_time);
Brian Silverman0465fcf2020-09-24 00:29:18 -0700188 }
Austin Schuhb2461652023-05-01 08:30:56 -0700189 encoder_.reset();
Alexei Strotsbc082d82023-05-03 08:43:42 -0700190 ran_out_of_space_ = log_sink_->Close() == WriteCode::kOutOfSpace;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700191}
192
Austin Schuh8bdfc492023-02-11 12:53:13 -0800193void DetachedBufferWriter::Flush(aos::monotonic_clock::time_point now) {
194 last_flush_time_ = now;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700195 if (ran_out_of_space_) {
196 // We don't want any later data to be written after space becomes available,
197 // so refuse to write anything more once we've dropped data because we ran
198 // out of space.
Austin Schuha426f1f2021-03-31 22:27:41 -0700199 if (encoder_) {
200 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
201 encoder_->Clear(encoder_->queue().size());
202 } else {
203 VLOG(1) << "No queue to ignore";
204 }
205 return;
206 }
207
208 const auto queue = encoder_->queue();
209 if (queue.empty()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700210 return;
211 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700212
Alexei Strotsbc082d82023-05-03 08:43:42 -0700213 const WriteResult result = log_sink_->Write(queue);
Alexei Strots01395492023-03-20 13:59:56 -0700214 encoder_->Clear(result.messages_written);
215 ran_out_of_space_ = result.code == WriteCode::kOutOfSpace;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700216}
217
Austin Schuhbd06ae42021-03-31 22:48:21 -0700218void DetachedBufferWriter::FlushAtThreshold(
219 aos::monotonic_clock::time_point now) {
Austin Schuha426f1f2021-03-31 22:27:41 -0700220 if (ran_out_of_space_) {
221 // We don't want any later data to be written after space becomes available,
222 // so refuse to write anything more once we've dropped data because we ran
223 // out of space.
224 if (encoder_) {
225 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
226 encoder_->Clear(encoder_->queue().size());
227 } else {
228 VLOG(1) << "No queue to ignore";
229 }
230 return;
231 }
232
Austin Schuhbd06ae42021-03-31 22:48:21 -0700233 // We don't want to flush the first time through. Otherwise we will flush as
234 // the log file header might be compressing, defeating any parallelism and
235 // queueing there.
236 if (last_flush_time_ == aos::monotonic_clock::min_time) {
237 last_flush_time_ = now;
238 }
239
Brian Silvermanf51499a2020-09-21 12:49:08 -0700240 // Flush if we are at the max number of iovs per writev, because there's no
241 // point queueing up any more data in memory. Also flush once we have enough
Austin Schuhbd06ae42021-03-31 22:48:21 -0700242 // data queued up or if it has been long enough.
Austin Schuh8bdfc492023-02-11 12:53:13 -0800243 while (encoder_->space() == 0 ||
244 encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
Austin Schuhbd06ae42021-03-31 22:48:21 -0700245 encoder_->queue_size() >= IOV_MAX ||
Austin Schuh3ebaf782023-04-07 16:03:28 -0700246 (now > last_flush_time_ +
247 chrono::duration_cast<chrono::nanoseconds>(
248 chrono::duration<double>(FLAGS_flush_period)) &&
249 encoder_->queued_bytes() != 0)) {
250 VLOG(1) << "Chose to flush at " << now << ", last " << last_flush_time_
251 << " queued bytes " << encoder_->queued_bytes();
Austin Schuh8bdfc492023-02-11 12:53:13 -0800252 Flush(now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700253 }
Austin Schuha36c8902019-12-30 18:07:15 -0800254}
255
Austin Schuhf2d0e682022-10-16 14:20:58 -0700256// Do the magic dance to convert the endianness of the data and append it to the
257// buffer.
258namespace {
259
260// TODO(austin): Look at the generated code to see if building the header is
261// efficient or not.
262template <typename T>
263uint8_t *Push(uint8_t *buffer, const T data) {
264 const T endian_data = flatbuffers::EndianScalar<T>(data);
265 std::memcpy(buffer, &endian_data, sizeof(T));
266 return buffer + sizeof(T);
267}
268
269uint8_t *PushBytes(uint8_t *buffer, const void *data, size_t size) {
270 std::memcpy(buffer, data, size);
271 return buffer + size;
272}
273
274uint8_t *Pad(uint8_t *buffer, size_t padding) {
275 std::memset(buffer, 0, padding);
276 return buffer + padding;
277}
278} // namespace
279
280flatbuffers::Offset<MessageHeader> PackRemoteMessage(
281 flatbuffers::FlatBufferBuilder *fbb,
282 const message_bridge::RemoteMessage *msg, int channel_index,
283 const aos::monotonic_clock::time_point monotonic_timestamp_time) {
284 logger::MessageHeader::Builder message_header_builder(*fbb);
285 // Note: this must match the same order as MessageBridgeServer and
286 // PackMessage. We want identical headers to have identical
287 // on-the-wire formats to make comparing them easier.
288
289 message_header_builder.add_channel_index(channel_index);
290
291 message_header_builder.add_queue_index(msg->queue_index());
292 message_header_builder.add_monotonic_sent_time(msg->monotonic_sent_time());
293 message_header_builder.add_realtime_sent_time(msg->realtime_sent_time());
294
295 message_header_builder.add_monotonic_remote_time(
296 msg->monotonic_remote_time());
297 message_header_builder.add_realtime_remote_time(msg->realtime_remote_time());
298 message_header_builder.add_remote_queue_index(msg->remote_queue_index());
299
300 message_header_builder.add_monotonic_timestamp_time(
301 monotonic_timestamp_time.time_since_epoch().count());
302
303 return message_header_builder.Finish();
304}
305
306size_t PackRemoteMessageInline(
307 uint8_t *buffer, const message_bridge::RemoteMessage *msg,
308 int channel_index,
Austin Schuh71a40d42023-02-04 21:22:22 -0800309 const aos::monotonic_clock::time_point monotonic_timestamp_time,
310 size_t start_byte, size_t end_byte) {
Austin Schuhf2d0e682022-10-16 14:20:58 -0700311 const flatbuffers::uoffset_t message_size = PackRemoteMessageSize();
Austin Schuh71a40d42023-02-04 21:22:22 -0800312 DCHECK_EQ((start_byte % 8u), 0u);
313 DCHECK_EQ((end_byte % 8u), 0u);
314 DCHECK_LE(start_byte, end_byte);
315 DCHECK_LE(end_byte, message_size);
Austin Schuhf2d0e682022-10-16 14:20:58 -0700316
Austin Schuh71a40d42023-02-04 21:22:22 -0800317 switch (start_byte) {
318 case 0x00u:
319 if ((end_byte) == 0x00u) {
320 break;
321 }
322 // clang-format off
323 // header:
324 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
325 buffer = Push<flatbuffers::uoffset_t>(
326 buffer, message_size - sizeof(flatbuffers::uoffset_t));
327 // +0x04 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: +0x24 | offset to root table `aos.logger.MessageHeader`
328 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x20);
329 [[fallthrough]];
330 case 0x08u:
331 if ((end_byte) == 0x08u) {
332 break;
333 }
334 //
335 // padding:
336 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
337 buffer = Pad(buffer, 6);
338 //
339 // vtable (aos.logger.MessageHeader):
340 // +0x0E | 16 00 | uint16_t | 0x0016 (22) | size of this vtable
341 buffer = Push<flatbuffers::voffset_t>(buffer, 0x16);
342 [[fallthrough]];
343 case 0x10u:
344 if ((end_byte) == 0x10u) {
345 break;
346 }
347 // +0x10 | 3C 00 | uint16_t | 0x003C (60) | size of referring table
348 buffer = Push<flatbuffers::voffset_t>(buffer, 0x3c);
349 // +0x12 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `channel_index` (id: 0)
350 buffer = Push<flatbuffers::voffset_t>(buffer, 0x38);
351 // +0x14 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `monotonic_sent_time` (id: 1)
352 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
353 // +0x16 | 24 00 | VOffset16 | 0x0024 (36) | offset to field `realtime_sent_time` (id: 2)
354 buffer = Push<flatbuffers::voffset_t>(buffer, 0x24);
355 [[fallthrough]];
356 case 0x18u:
357 if ((end_byte) == 0x18u) {
358 break;
359 }
360 // +0x18 | 34 00 | VOffset16 | 0x0034 (52) | offset to field `queue_index` (id: 3)
361 buffer = Push<flatbuffers::voffset_t>(buffer, 0x34);
362 // +0x1A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `data` (id: 4) <null> (Vector)
363 buffer = Push<flatbuffers::voffset_t>(buffer, 0x00);
364 // +0x1C | 1C 00 | VOffset16 | 0x001C (28) | offset to field `monotonic_remote_time` (id: 5)
365 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
366 // +0x1E | 14 00 | VOffset16 | 0x0014 (20) | offset to field `realtime_remote_time` (id: 6)
367 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
368 [[fallthrough]];
369 case 0x20u:
370 if ((end_byte) == 0x20u) {
371 break;
372 }
373 // +0x20 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `remote_queue_index` (id: 7)
374 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
375 // +0x22 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `monotonic_timestamp_time` (id: 8)
376 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
377 //
378 // root_table (aos.logger.MessageHeader):
379 // +0x24 | 16 00 00 00 | SOffset32 | 0x00000016 (22) Loc: +0x0E | offset to vtable
380 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x16);
381 [[fallthrough]];
382 case 0x28u:
383 if ((end_byte) == 0x28u) {
384 break;
385 }
386 // +0x28 | F6 0B D8 11 A4 A8 B1 71 | int64_t | 0x71B1A8A411D80BF6 (8192514619791117302) | table field `monotonic_timestamp_time` (Long)
387 buffer = Push<int64_t>(buffer,
388 monotonic_timestamp_time.time_since_epoch().count());
389 [[fallthrough]];
390 case 0x30u:
391 if ((end_byte) == 0x30u) {
392 break;
393 }
394 // +0x30 | 00 00 00 00 | uint8_t[4] | .... | padding
395 // TODO(austin): Can we re-arrange the order to ditch the padding?
396 // (Answer is yes, but what is the impact elsewhere? It will change the
397 // binary format)
398 buffer = Pad(buffer, 4);
399 // +0x34 | 75 00 00 00 | uint32_t | 0x00000075 (117) | table field `remote_queue_index` (UInt)
400 buffer = Push<uint32_t>(buffer, msg->remote_queue_index());
401 [[fallthrough]];
402 case 0x38u:
403 if ((end_byte) == 0x38u) {
404 break;
405 }
406 // +0x38 | AA B0 43 0A 35 BE FA D2 | int64_t | 0xD2FABE350A43B0AA (-3244071446552268630) | table field `realtime_remote_time` (Long)
407 buffer = Push<int64_t>(buffer, msg->realtime_remote_time());
408 [[fallthrough]];
409 case 0x40u:
410 if ((end_byte) == 0x40u) {
411 break;
412 }
413 // +0x40 | D5 40 30 F3 C1 A7 26 1D | int64_t | 0x1D26A7C1F33040D5 (2100550727665467605) | table field `monotonic_remote_time` (Long)
414 buffer = Push<int64_t>(buffer, msg->monotonic_remote_time());
415 [[fallthrough]];
416 case 0x48u:
417 if ((end_byte) == 0x48u) {
418 break;
419 }
420 // +0x48 | 5B 25 32 A1 4A E8 46 CA | int64_t | 0xCA46E84AA132255B (-3871151422448720549) | table field `realtime_sent_time` (Long)
421 buffer = Push<int64_t>(buffer, msg->realtime_sent_time());
422 [[fallthrough]];
423 case 0x50u:
424 if ((end_byte) == 0x50u) {
425 break;
426 }
427 // +0x50 | 49 7D 45 1F 8C 36 6B A3 | int64_t | 0xA36B368C1F457D49 (-6671178447571288759) | table field `monotonic_sent_time` (Long)
428 buffer = Push<int64_t>(buffer, msg->monotonic_sent_time());
429 [[fallthrough]];
430 case 0x58u:
431 if ((end_byte) == 0x58u) {
432 break;
433 }
434 // +0x58 | 33 00 00 00 | uint32_t | 0x00000033 (51) | table field `queue_index` (UInt)
435 buffer = Push<uint32_t>(buffer, msg->queue_index());
436 // +0x5C | 76 00 00 00 | uint32_t | 0x00000076 (118) | table field `channel_index` (UInt)
437 buffer = Push<uint32_t>(buffer, channel_index);
438 // clang-format on
439 [[fallthrough]];
440 case 0x60u:
441 if ((end_byte) == 0x60u) {
442 break;
443 }
444 }
Austin Schuhf2d0e682022-10-16 14:20:58 -0700445
Austin Schuh71a40d42023-02-04 21:22:22 -0800446 return end_byte - start_byte;
Austin Schuhf2d0e682022-10-16 14:20:58 -0700447}
448
Austin Schuha36c8902019-12-30 18:07:15 -0800449flatbuffers::Offset<MessageHeader> PackMessage(
450 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
451 int channel_index, LogType log_type) {
452 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
453
454 switch (log_type) {
455 case LogType::kLogMessage:
456 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800457 case LogType::kLogRemoteMessage:
Austin Schuhfa30c352022-10-16 11:12:02 -0700458 // Since the timestamps are 8 byte aligned, we are going to end up adding
459 // padding in the middle of the message to pad everything out to 8 byte
460 // alignment. That's rather wasteful. To make things efficient to mmap
461 // while reading uncompressed logs, we'd actually rather the message be
462 // aligned. So, force 8 byte alignment (enough to preserve alignment
463 // inside the nested message so that we can read it without moving it)
464 // here.
465 fbb->ForceVectorAlignment(context.size, sizeof(uint8_t), 8);
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700466 data_offset = fbb->CreateVector(
467 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800468 break;
469
470 case LogType::kLogDeliveryTimeOnly:
471 break;
472 }
473
474 MessageHeader::Builder message_header_builder(*fbb);
475 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800476
Austin Schuhfa30c352022-10-16 11:12:02 -0700477 // These are split out into very explicit serialization calls because the
478 // order here changes the order things are written out on the wire, and we
479 // want to control and understand it here. Changing the order can increase
480 // the amount of padding bytes in the middle.
481 //
James Kuszmaul9776b392023-01-14 14:08:08 -0800482 // It is also easier to follow... And doesn't actually make things much
483 // bigger.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800484 switch (log_type) {
485 case LogType::kLogRemoteMessage:
486 message_header_builder.add_queue_index(context.remote_queue_index);
Austin Schuhfa30c352022-10-16 11:12:02 -0700487 message_header_builder.add_data(data_offset);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800488 message_header_builder.add_monotonic_sent_time(
489 context.monotonic_remote_time.time_since_epoch().count());
490 message_header_builder.add_realtime_sent_time(
491 context.realtime_remote_time.time_since_epoch().count());
492 break;
493
Austin Schuh6f3babe2020-01-26 20:34:50 -0800494 case LogType::kLogDeliveryTimeOnly:
495 message_header_builder.add_queue_index(context.queue_index);
496 message_header_builder.add_monotonic_sent_time(
497 context.monotonic_event_time.time_since_epoch().count());
498 message_header_builder.add_realtime_sent_time(
499 context.realtime_event_time.time_since_epoch().count());
Austin Schuha36c8902019-12-30 18:07:15 -0800500 message_header_builder.add_monotonic_remote_time(
501 context.monotonic_remote_time.time_since_epoch().count());
502 message_header_builder.add_realtime_remote_time(
503 context.realtime_remote_time.time_since_epoch().count());
504 message_header_builder.add_remote_queue_index(context.remote_queue_index);
505 break;
Austin Schuhfa30c352022-10-16 11:12:02 -0700506
507 case LogType::kLogMessage:
508 message_header_builder.add_queue_index(context.queue_index);
509 message_header_builder.add_data(data_offset);
510 message_header_builder.add_monotonic_sent_time(
511 context.monotonic_event_time.time_since_epoch().count());
512 message_header_builder.add_realtime_sent_time(
513 context.realtime_event_time.time_since_epoch().count());
514 break;
515
516 case LogType::kLogMessageAndDeliveryTime:
517 message_header_builder.add_queue_index(context.queue_index);
518 message_header_builder.add_remote_queue_index(context.remote_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());
523 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_data(data_offset);
528 break;
Austin Schuha36c8902019-12-30 18:07:15 -0800529 }
530
531 return message_header_builder.Finish();
532}
533
Austin Schuhfa30c352022-10-16 11:12:02 -0700534flatbuffers::uoffset_t PackMessageHeaderSize(LogType log_type) {
535 switch (log_type) {
536 case LogType::kLogMessage:
537 return
538 // Root table size + offset.
539 sizeof(flatbuffers::uoffset_t) * 2 +
540 // 6 padding bytes to pad the header out properly.
541 6 +
542 // vtable header (size + size of table)
543 sizeof(flatbuffers::voffset_t) * 2 +
544 // offsets to all the fields.
545 sizeof(flatbuffers::voffset_t) * 5 +
546 // pointer to vtable
547 sizeof(flatbuffers::soffset_t) +
548 // pointer to data
549 sizeof(flatbuffers::uoffset_t) +
550 // realtime_sent_time, monotonic_sent_time
551 sizeof(int64_t) * 2 +
552 // queue_index, channel_index
553 sizeof(uint32_t) * 2;
554
555 case LogType::kLogDeliveryTimeOnly:
556 return
557 // Root table size + offset.
558 sizeof(flatbuffers::uoffset_t) * 2 +
559 // 6 padding bytes to pad the header out properly.
560 4 +
561 // vtable header (size + size of table)
562 sizeof(flatbuffers::voffset_t) * 2 +
563 // offsets to all the fields.
564 sizeof(flatbuffers::voffset_t) * 8 +
565 // pointer to vtable
566 sizeof(flatbuffers::soffset_t) +
567 // remote_queue_index
568 sizeof(uint32_t) +
569 // realtime_remote_time, monotonic_remote_time, realtime_sent_time,
570 // monotonic_sent_time
571 sizeof(int64_t) * 4 +
572 // queue_index, channel_index
573 sizeof(uint32_t) * 2;
574
575 case LogType::kLogMessageAndDeliveryTime:
576 return
577 // Root table size + offset.
578 sizeof(flatbuffers::uoffset_t) * 2 +
579 // 4 padding bytes to pad the header out properly.
580 4 +
581 // vtable header (size + size of table)
582 sizeof(flatbuffers::voffset_t) * 2 +
583 // offsets to all the fields.
584 sizeof(flatbuffers::voffset_t) * 8 +
585 // pointer to vtable
586 sizeof(flatbuffers::soffset_t) +
587 // pointer to data
588 sizeof(flatbuffers::uoffset_t) +
589 // realtime_remote_time, monotonic_remote_time, realtime_sent_time,
590 // monotonic_sent_time
591 sizeof(int64_t) * 4 +
592 // remote_queue_index, queue_index, channel_index
593 sizeof(uint32_t) * 3;
594
595 case LogType::kLogRemoteMessage:
596 return
597 // Root table size + offset.
598 sizeof(flatbuffers::uoffset_t) * 2 +
599 // 6 padding bytes to pad the header out properly.
600 6 +
601 // vtable header (size + size of table)
602 sizeof(flatbuffers::voffset_t) * 2 +
603 // offsets to all the fields.
604 sizeof(flatbuffers::voffset_t) * 5 +
605 // pointer to vtable
606 sizeof(flatbuffers::soffset_t) +
607 // realtime_sent_time, monotonic_sent_time
608 sizeof(int64_t) * 2 +
609 // pointer to data
610 sizeof(flatbuffers::uoffset_t) +
611 // queue_index, channel_index
612 sizeof(uint32_t) * 2;
613 }
614 LOG(FATAL);
615}
616
James Kuszmaul9776b392023-01-14 14:08:08 -0800617flatbuffers::uoffset_t PackMessageSize(LogType log_type, size_t data_size) {
Austin Schuhfa30c352022-10-16 11:12:02 -0700618 static_assert(sizeof(flatbuffers::uoffset_t) == 4u,
619 "Update size logic please.");
620 const flatbuffers::uoffset_t aligned_data_length =
Austin Schuh48d10d62022-10-16 22:19:23 -0700621 ((data_size + 7) & 0xfffffff8u);
Austin Schuhfa30c352022-10-16 11:12:02 -0700622 switch (log_type) {
623 case LogType::kLogDeliveryTimeOnly:
624 return PackMessageHeaderSize(log_type);
625
626 case LogType::kLogMessage:
627 case LogType::kLogMessageAndDeliveryTime:
628 case LogType::kLogRemoteMessage:
629 return PackMessageHeaderSize(log_type) +
630 // Vector...
631 sizeof(flatbuffers::uoffset_t) + aligned_data_length;
632 }
633 LOG(FATAL);
634}
635
Austin Schuhfa30c352022-10-16 11:12:02 -0700636size_t PackMessageInline(uint8_t *buffer, const Context &context,
Austin Schuh71a40d42023-02-04 21:22:22 -0800637 int channel_index, LogType log_type, size_t start_byte,
638 size_t end_byte) {
Austin Schuh48d10d62022-10-16 22:19:23 -0700639 // TODO(austin): Figure out how to copy directly from shared memory instead of
640 // first into the fetcher's memory and then into here. That would save a lot
641 // of memory.
Austin Schuhfa30c352022-10-16 11:12:02 -0700642 const flatbuffers::uoffset_t message_size =
Austin Schuh48d10d62022-10-16 22:19:23 -0700643 PackMessageSize(log_type, context.size);
Austin Schuh71a40d42023-02-04 21:22:22 -0800644 DCHECK_EQ((message_size % 8), 0u) << ": Non 8 byte length...";
645 DCHECK_EQ((start_byte % 8u), 0u);
646 DCHECK_EQ((end_byte % 8u), 0u);
647 DCHECK_LE(start_byte, end_byte);
648 DCHECK_LE(end_byte, message_size);
Austin Schuhfa30c352022-10-16 11:12:02 -0700649
650 // Pack all the data in. This is brittle but easy to change. Use the
651 // InlinePackMessage.Equivilent unit test to verify everything matches.
652 switch (log_type) {
653 case LogType::kLogMessage:
Austin Schuh71a40d42023-02-04 21:22:22 -0800654 switch (start_byte) {
655 case 0x00u:
656 if ((end_byte) == 0x00u) {
657 break;
658 }
659 // clang-format off
660 // header:
661 // +0x00 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: +0x4C | size prefix
662 buffer = Push<flatbuffers::uoffset_t>(
663 buffer, message_size - sizeof(flatbuffers::uoffset_t));
664
665 // +0x04 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: +0x1C | offset to root table `aos.logger.MessageHeader`
666 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x18);
667 [[fallthrough]];
668 case 0x08u:
669 if ((end_byte) == 0x08u) {
670 break;
671 }
672 //
673 // padding:
674 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
675 buffer = Pad(buffer, 6);
676 //
677 // vtable (aos.logger.MessageHeader):
678 // +0x0E | 0E 00 | uint16_t | 0x000E (14) | size of this vtable
679 buffer = Push<flatbuffers::voffset_t>(buffer, 0xe);
680 [[fallthrough]];
681 case 0x10u:
682 if ((end_byte) == 0x10u) {
683 break;
684 }
685 // +0x10 | 20 00 | uint16_t | 0x0020 (32) | size of referring table
686 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
687 // +0x12 | 1C 00 | VOffset16 | 0x001C (28) | offset to field `channel_index` (id: 0)
688 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
689 // +0x14 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `monotonic_sent_time` (id: 1)
690 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0c);
691 // +0x16 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `realtime_sent_time` (id: 2)
692 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
693 [[fallthrough]];
694 case 0x18u:
695 if ((end_byte) == 0x18u) {
696 break;
697 }
698 // +0x18 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `queue_index` (id: 3)
699 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
700 // +0x1A | 14 00 | VOffset16 | 0x0014 (20) | offset to field `data` (id: 4)
701 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
702 //
703 // root_table (aos.logger.MessageHeader):
704 // +0x1C | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: +0x0E | offset to vtable
705 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0e);
706 [[fallthrough]];
707 case 0x20u:
708 if ((end_byte) == 0x20u) {
709 break;
710 }
711 // +0x20 | B2 E4 EF 89 19 7D 7F 6F | int64_t | 0x6F7F7D1989EFE4B2 (8034277808894108850) | table field `realtime_sent_time` (Long)
712 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
713 [[fallthrough]];
714 case 0x28u:
715 if ((end_byte) == 0x28u) {
716 break;
717 }
718 // +0x28 | 86 8D 92 65 FC 79 74 2B | int64_t | 0x2B7479FC65928D86 (3131261765872160134) | table field `monotonic_sent_time` (Long)
719 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
720 [[fallthrough]];
721 case 0x30u:
722 if ((end_byte) == 0x30u) {
723 break;
724 }
725 // +0x30 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: +0x3C | offset to field `data` (vector)
726 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0c);
727 // +0x34 | 86 00 00 00 | uint32_t | 0x00000086 (134) | table field `queue_index` (UInt)
728 buffer = Push<uint32_t>(buffer, context.queue_index);
729 [[fallthrough]];
730 case 0x38u:
731 if ((end_byte) == 0x38u) {
732 break;
733 }
734 // +0x38 | 71 00 00 00 | uint32_t | 0x00000071 (113) | table field `channel_index` (UInt)
735 buffer = Push<uint32_t>(buffer, channel_index);
736 //
737 // vector (aos.logger.MessageHeader.data):
738 // +0x3C | 0E 00 00 00 | uint32_t | 0x0000000E (14) | length of vector (# items)
739 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
740 [[fallthrough]];
741 case 0x40u:
742 if ((end_byte) == 0x40u) {
743 break;
744 }
745 [[fallthrough]];
746 default:
747 // +0x40 | FF | uint8_t | 0xFF (255) | value[0]
748 // +0x41 | B8 | uint8_t | 0xB8 (184) | value[1]
749 // +0x42 | EE | uint8_t | 0xEE (238) | value[2]
750 // +0x43 | 00 | uint8_t | 0x00 (0) | value[3]
751 // +0x44 | 20 | uint8_t | 0x20 (32) | value[4]
752 // +0x45 | 4D | uint8_t | 0x4D (77) | value[5]
753 // +0x46 | FF | uint8_t | 0xFF (255) | value[6]
754 // +0x47 | 25 | uint8_t | 0x25 (37) | value[7]
755 // +0x48 | 3C | uint8_t | 0x3C (60) | value[8]
756 // +0x49 | 17 | uint8_t | 0x17 (23) | value[9]
757 // +0x4A | 65 | uint8_t | 0x65 (101) | value[10]
758 // +0x4B | 2F | uint8_t | 0x2F (47) | value[11]
759 // +0x4C | 63 | uint8_t | 0x63 (99) | value[12]
760 // +0x4D | 58 | uint8_t | 0x58 (88) | value[13]
761 //
762 // padding:
763 // +0x4E | 00 00 | uint8_t[2] | .. | padding
764 // clang-format on
765 if (start_byte <= 0x40 && end_byte == message_size) {
766 // The easy one, slap it all down.
767 buffer = PushBytes(buffer, context.data, context.size);
768 buffer =
769 Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
770 } else {
771 const size_t data_start_byte =
772 start_byte < 0x40 ? 0x0u : (start_byte - 0x40);
773 const size_t data_end_byte = end_byte - 0x40;
774 const size_t padded_size = ((context.size + 7) & 0xfffffff8u);
775 if (data_start_byte < padded_size) {
776 buffer = PushBytes(
777 buffer,
778 reinterpret_cast<const uint8_t *>(context.data) +
779 data_start_byte,
780 std::min(context.size, data_end_byte) - data_start_byte);
781 if (data_end_byte == padded_size) {
782 // We can only pad the last 7 bytes, so this only gets written
783 // if we write the last byte.
784 buffer = Pad(buffer,
785 ((context.size + 7) & 0xfffffff8u) - context.size);
786 }
787 }
788 }
789 break;
790 }
Austin Schuhfa30c352022-10-16 11:12:02 -0700791 break;
792
793 case LogType::kLogDeliveryTimeOnly:
Austin Schuh71a40d42023-02-04 21:22:22 -0800794 switch (start_byte) {
795 case 0x00u:
796 if ((end_byte) == 0x00u) {
797 break;
798 }
799 // clang-format off
800 // header:
801 // +0x00 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: +0x4C | size prefix
802 buffer = Push<flatbuffers::uoffset_t>(
803 buffer, message_size - sizeof(flatbuffers::uoffset_t));
804 // +0x04 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: +0x20 | offset to root table `aos.logger.MessageHeader`
805 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x1c);
Austin Schuhfa30c352022-10-16 11:12:02 -0700806
Austin Schuh71a40d42023-02-04 21:22:22 -0800807 [[fallthrough]];
808 case 0x08u:
809 if ((end_byte) == 0x08u) {
810 break;
811 }
812 //
813 // padding:
814 // +0x08 | 00 00 00 00 | uint8_t[4] | .... | padding
815 buffer = Pad(buffer, 4);
816 //
817 // vtable (aos.logger.MessageHeader):
818 // +0x0C | 14 00 | uint16_t | 0x0014 (20) | size of this vtable
819 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
820 // +0x0E | 30 00 | uint16_t | 0x0030 (48) | size of referring table
821 buffer = Push<flatbuffers::voffset_t>(buffer, 0x30);
822 [[fallthrough]];
823 case 0x10u:
824 if ((end_byte) == 0x10u) {
825 break;
826 }
827 // +0x10 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `channel_index` (id: 0)
828 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
829 // +0x12 | 20 00 | VOffset16 | 0x0020 (32) | offset to field `monotonic_sent_time` (id: 1)
830 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
831 // +0x14 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `realtime_sent_time` (id: 2)
832 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
833 // +0x16 | 28 00 | VOffset16 | 0x0028 (40) | offset to field `queue_index` (id: 3)
834 buffer = Push<flatbuffers::voffset_t>(buffer, 0x28);
835 [[fallthrough]];
836 case 0x18u:
837 if ((end_byte) == 0x18u) {
838 break;
839 }
840 // +0x18 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `data` (id: 4) <null> (Vector)
841 buffer = Push<flatbuffers::voffset_t>(buffer, 0x00);
842 // +0x1A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `monotonic_remote_time` (id: 5)
843 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
844 // +0x1C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `realtime_remote_time` (id: 6)
845 buffer = Push<flatbuffers::voffset_t>(buffer, 0x08);
846 // +0x1E | 04 00 | VOffset16 | 0x0004 (4) | offset to field `remote_queue_index` (id: 7)
847 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
848 [[fallthrough]];
849 case 0x20u:
850 if ((end_byte) == 0x20u) {
851 break;
852 }
853 //
854 // root_table (aos.logger.MessageHeader):
855 // +0x20 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: +0x0C | offset to vtable
856 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x14);
857 // +0x24 | 69 00 00 00 | uint32_t | 0x00000069 (105) | table field `remote_queue_index` (UInt)
858 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
859 [[fallthrough]];
860 case 0x28u:
861 if ((end_byte) == 0x28u) {
862 break;
863 }
864 // +0x28 | C6 85 F1 AB 83 B5 CD EB | int64_t | 0xEBCDB583ABF185C6 (-1455307527440726586) | table field `realtime_remote_time` (Long)
865 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
866 [[fallthrough]];
867 case 0x30u:
868 if ((end_byte) == 0x30u) {
869 break;
870 }
871 // +0x30 | 47 24 D3 97 1E 42 2D 99 | int64_t | 0x992D421E97D32447 (-7409193112790948793) | table field `monotonic_remote_time` (Long)
872 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
873 [[fallthrough]];
874 case 0x38u:
875 if ((end_byte) == 0x38u) {
876 break;
877 }
878 // +0x38 | C8 B9 A7 AB 79 F2 CD 60 | int64_t | 0x60CDF279ABA7B9C8 (6975498002251626952) | table field `realtime_sent_time` (Long)
879 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
880 [[fallthrough]];
881 case 0x40u:
882 if ((end_byte) == 0x40u) {
883 break;
884 }
885 // +0x40 | EA 8F 2A 0F AF 01 7A AB | int64_t | 0xAB7A01AF0F2A8FEA (-6090553694679822358) | table field `monotonic_sent_time` (Long)
886 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
887 [[fallthrough]];
888 case 0x48u:
889 if ((end_byte) == 0x48u) {
890 break;
891 }
892 // +0x48 | F5 00 00 00 | uint32_t | 0x000000F5 (245) | table field `queue_index` (UInt)
893 buffer = Push<uint32_t>(buffer, context.queue_index);
894 // +0x4C | 88 00 00 00 | uint32_t | 0x00000088 (136) | table field `channel_index` (UInt)
895 buffer = Push<uint32_t>(buffer, channel_index);
896
897 // clang-format on
898 }
Austin Schuhfa30c352022-10-16 11:12:02 -0700899 break;
900
901 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh71a40d42023-02-04 21:22:22 -0800902 switch (start_byte) {
903 case 0x00u:
904 if ((end_byte) == 0x00u) {
905 break;
906 }
907 // clang-format off
908 // header:
909 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
910 buffer = Push<flatbuffers::uoffset_t>(
911 buffer, message_size - sizeof(flatbuffers::uoffset_t));
912 // +0x04 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: +0x20 | offset to root table `aos.logger.MessageHeader`
913 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x1c);
914 [[fallthrough]];
915 case 0x08u:
916 if ((end_byte) == 0x08u) {
917 break;
918 }
919 //
920 // padding:
921 // +0x08 | 00 00 00 00 | uint8_t[4] | .... | padding
922 buffer = Pad(buffer, 4);
923 //
924 // vtable (aos.logger.MessageHeader):
925 // +0x0C | 14 00 | uint16_t | 0x0014 (20) | size of this vtable
926 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
927 // +0x0E | 34 00 | uint16_t | 0x0034 (52) | size of referring table
928 buffer = Push<flatbuffers::voffset_t>(buffer, 0x34);
929 [[fallthrough]];
930 case 0x10u:
931 if ((end_byte) == 0x10u) {
932 break;
933 }
934 // +0x10 | 30 00 | VOffset16 | 0x0030 (48) | offset to field `channel_index` (id: 0)
935 buffer = Push<flatbuffers::voffset_t>(buffer, 0x30);
936 // +0x12 | 20 00 | VOffset16 | 0x0020 (32) | offset to field `monotonic_sent_time` (id: 1)
937 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
938 // +0x14 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `realtime_sent_time` (id: 2)
939 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
940 // +0x16 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `queue_index` (id: 3)
941 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
942 [[fallthrough]];
943 case 0x18u:
944 if ((end_byte) == 0x18u) {
945 break;
946 }
947 // +0x18 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `data` (id: 4)
948 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
949 // +0x1A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `monotonic_remote_time` (id: 5)
950 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
951 // +0x1C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `realtime_remote_time` (id: 6)
952 buffer = Push<flatbuffers::voffset_t>(buffer, 0x08);
953 // +0x1E | 28 00 | VOffset16 | 0x0028 (40) | offset to field `remote_queue_index` (id: 7)
954 buffer = Push<flatbuffers::voffset_t>(buffer, 0x28);
955 [[fallthrough]];
956 case 0x20u:
957 if ((end_byte) == 0x20u) {
958 break;
959 }
960 //
961 // root_table (aos.logger.MessageHeader):
962 // +0x20 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: +0x0C | offset to vtable
963 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x14);
964 // +0x24 | 30 00 00 00 | UOffset32 | 0x00000030 (48) Loc: +0x54 | offset to field `data` (vector)
965 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x30);
966 [[fallthrough]];
967 case 0x28u:
968 if ((end_byte) == 0x28u) {
969 break;
970 }
971 // +0x28 | C4 C8 87 BF 40 6C 1F 29 | int64_t | 0x291F6C40BF87C8C4 (2963206105180129476) | table field `realtime_remote_time` (Long)
972 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
973 [[fallthrough]];
974 case 0x30u:
975 if ((end_byte) == 0x30u) {
976 break;
977 }
978 // +0x30 | 0F 00 26 FD D2 6D C0 1F | int64_t | 0x1FC06DD2FD26000F (2287949363661897743) | table field `monotonic_remote_time` (Long)
979 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
980 [[fallthrough]];
981 case 0x38u:
982 if ((end_byte) == 0x38u) {
983 break;
984 }
985 // +0x38 | 29 75 09 C0 73 73 BF 88 | int64_t | 0x88BF7373C0097529 (-8593022623019338455) | table field `realtime_sent_time` (Long)
986 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
987 [[fallthrough]];
988 case 0x40u:
989 if ((end_byte) == 0x40u) {
990 break;
991 }
992 // +0x40 | 6D 8A AE 04 50 25 9C E9 | int64_t | 0xE99C255004AE8A6D (-1613373540899321235) | table field `monotonic_sent_time` (Long)
993 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
994 [[fallthrough]];
995 case 0x48u:
996 if ((end_byte) == 0x48u) {
997 break;
998 }
999 // +0x48 | 47 00 00 00 | uint32_t | 0x00000047 (71) | table field `remote_queue_index` (UInt)
1000 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
1001 // +0x4C | 4C 00 00 00 | uint32_t | 0x0000004C (76) | table field `queue_index` (UInt)
1002 buffer = Push<uint32_t>(buffer, context.queue_index);
1003 [[fallthrough]];
1004 case 0x50u:
1005 if ((end_byte) == 0x50u) {
1006 break;
1007 }
1008 // +0x50 | 72 00 00 00 | uint32_t | 0x00000072 (114) | table field `channel_index` (UInt)
1009 buffer = Push<uint32_t>(buffer, channel_index);
1010 //
1011 // vector (aos.logger.MessageHeader.data):
1012 // +0x54 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of vector (# items)
1013 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
1014 [[fallthrough]];
1015 case 0x58u:
1016 if ((end_byte) == 0x58u) {
1017 break;
1018 }
1019 [[fallthrough]];
1020 default:
1021 // +0x58 | B1 | uint8_t | 0xB1 (177) | value[0]
1022 // +0x59 | 4A | uint8_t | 0x4A (74) | value[1]
1023 // +0x5A | 50 | uint8_t | 0x50 (80) | value[2]
1024 // +0x5B | 24 | uint8_t | 0x24 (36) | value[3]
1025 // +0x5C | AF | uint8_t | 0xAF (175) | value[4]
1026 // +0x5D | C8 | uint8_t | 0xC8 (200) | value[5]
1027 // +0x5E | D5 | uint8_t | 0xD5 (213) | value[6]
1028 //
1029 // padding:
1030 // +0x5F | 00 | uint8_t[1] | . | padding
1031 // clang-format on
1032
1033 if (start_byte <= 0x58 && end_byte == message_size) {
1034 // The easy one, slap it all down.
1035 buffer = PushBytes(buffer, context.data, context.size);
1036 buffer =
1037 Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
1038 } else {
1039 const size_t data_start_byte =
1040 start_byte < 0x58 ? 0x0u : (start_byte - 0x58);
1041 const size_t data_end_byte = end_byte - 0x58;
1042 const size_t padded_size = ((context.size + 7) & 0xfffffff8u);
1043 if (data_start_byte < padded_size) {
1044 buffer = PushBytes(
1045 buffer,
1046 reinterpret_cast<const uint8_t *>(context.data) +
1047 data_start_byte,
1048 std::min(context.size, data_end_byte) - data_start_byte);
1049 if (data_end_byte == padded_size) {
1050 // We can only pad the last 7 bytes, so this only gets written
1051 // if we write the last byte.
1052 buffer = Pad(buffer,
1053 ((context.size + 7) & 0xfffffff8u) - context.size);
1054 }
1055 }
1056 }
1057
1058 break;
1059 }
Austin Schuhfa30c352022-10-16 11:12:02 -07001060
1061 break;
1062
1063 case LogType::kLogRemoteMessage:
Austin Schuh71a40d42023-02-04 21:22:22 -08001064 switch (start_byte) {
1065 case 0x00u:
1066 if ((end_byte) == 0x00u) {
1067 break;
1068 }
1069 // This is the message we need to recreate.
1070 //
1071 // clang-format off
1072 // header:
1073 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
1074 buffer = Push<flatbuffers::uoffset_t>(
1075 buffer, message_size - sizeof(flatbuffers::uoffset_t));
1076 // +0x04 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: +0x1C | offset to root table `aos.logger.MessageHeader`
1077 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x18);
1078 [[fallthrough]];
1079 case 0x08u:
1080 if ((end_byte) == 0x08u) {
1081 break;
1082 }
1083 //
1084 // padding:
1085 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
1086 buffer = Pad(buffer, 6);
1087 //
1088 // vtable (aos.logger.MessageHeader):
1089 // +0x0E | 0E 00 | uint16_t | 0x000E (14) | size of this vtable
1090 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0e);
1091 [[fallthrough]];
1092 case 0x10u:
1093 if ((end_byte) == 0x10u) {
1094 break;
1095 }
1096 // +0x10 | 20 00 | uint16_t | 0x0020 (32) | size of referring table
1097 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
1098 // +0x12 | 1C 00 | VOffset16 | 0x001C (28) | offset to field `channel_index` (id: 0)
1099 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
1100 // +0x14 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `monotonic_sent_time` (id: 1)
1101 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0c);
1102 // +0x16 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `realtime_sent_time` (id: 2)
1103 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
1104 [[fallthrough]];
1105 case 0x18u:
1106 if ((end_byte) == 0x18u) {
1107 break;
1108 }
1109 // +0x18 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `queue_index` (id: 3)
1110 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
1111 // +0x1A | 14 00 | VOffset16 | 0x0014 (20) | offset to field `data` (id: 4)
1112 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
1113 //
1114 // root_table (aos.logger.MessageHeader):
1115 // +0x1C | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: +0x0E | offset to vtable
1116 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0E);
1117 [[fallthrough]];
1118 case 0x20u:
1119 if ((end_byte) == 0x20u) {
1120 break;
1121 }
1122 // +0x20 | D8 96 32 1A A0 D3 23 BB | int64_t | 0xBB23D3A01A3296D8 (-4961889679844403496) | table field `realtime_sent_time` (Long)
1123 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
1124 [[fallthrough]];
1125 case 0x28u:
1126 if ((end_byte) == 0x28u) {
1127 break;
1128 }
1129 // +0x28 | 2E 5D 23 B3 BE 84 CF C2 | int64_t | 0xC2CF84BEB3235D2E (-4409159555588334290) | table field `monotonic_sent_time` (Long)
1130 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
1131 [[fallthrough]];
1132 case 0x30u:
1133 if ((end_byte) == 0x30u) {
1134 break;
1135 }
1136 // +0x30 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: +0x3C | offset to field `data` (vector)
1137 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0C);
1138 // +0x34 | 69 00 00 00 | uint32_t | 0x00000069 (105) | table field `queue_index` (UInt)
1139 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
1140 [[fallthrough]];
1141 case 0x38u:
1142 if ((end_byte) == 0x38u) {
1143 break;
1144 }
1145 // +0x38 | F3 00 00 00 | uint32_t | 0x000000F3 (243) | table field `channel_index` (UInt)
1146 buffer = Push<uint32_t>(buffer, channel_index);
1147 //
1148 // vector (aos.logger.MessageHeader.data):
1149 // +0x3C | 1A 00 00 00 | uint32_t | 0x0000001A (26) | length of vector (# items)
1150 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
1151 [[fallthrough]];
1152 case 0x40u:
1153 if ((end_byte) == 0x40u) {
1154 break;
1155 }
1156 [[fallthrough]];
1157 default:
1158 // +0x40 | 38 | uint8_t | 0x38 (56) | value[0]
1159 // +0x41 | 1A | uint8_t | 0x1A (26) | value[1]
1160 // ...
1161 // +0x58 | 90 | uint8_t | 0x90 (144) | value[24]
1162 // +0x59 | 92 | uint8_t | 0x92 (146) | value[25]
1163 //
1164 // padding:
1165 // +0x5A | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
1166 // clang-format on
1167 if (start_byte <= 0x40 && end_byte == message_size) {
1168 // The easy one, slap it all down.
1169 buffer = PushBytes(buffer, context.data, context.size);
1170 buffer =
1171 Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
1172 } else {
1173 const size_t data_start_byte =
1174 start_byte < 0x40 ? 0x0u : (start_byte - 0x40);
1175 const size_t data_end_byte = end_byte - 0x40;
1176 const size_t padded_size = ((context.size + 7) & 0xfffffff8u);
1177 if (data_start_byte < padded_size) {
1178 buffer = PushBytes(
1179 buffer,
1180 reinterpret_cast<const uint8_t *>(context.data) +
1181 data_start_byte,
1182 std::min(context.size, data_end_byte) - data_start_byte);
1183 if (data_end_byte == padded_size) {
1184 // We can only pad the last 7 bytes, so this only gets written
1185 // if we write the last byte.
1186 buffer = Pad(buffer,
1187 ((context.size + 7) & 0xfffffff8u) - context.size);
1188 }
1189 }
1190 }
1191 break;
1192 }
Austin Schuhfa30c352022-10-16 11:12:02 -07001193 }
1194
Austin Schuh71a40d42023-02-04 21:22:22 -08001195 return end_byte - start_byte;
Austin Schuhfa30c352022-10-16 11:12:02 -07001196}
1197
Austin Schuhcd368422021-11-22 21:23:29 -08001198SpanReader::SpanReader(std::string_view filename, bool quiet)
Alexei Strotscee7b372023-04-21 11:57:54 -07001199 : SpanReader(filename, ResolveDecoder(filename, quiet)) {}
Tyler Chatow2015bc62021-08-04 21:15:09 -07001200
Alexei Strotscee7b372023-04-21 11:57:54 -07001201SpanReader::SpanReader(std::string_view filename,
1202 std::unique_ptr<DataDecoder> decoder)
1203 : filename_(filename), decoder_(std::move(decoder)) {}
Austin Schuh05b70472020-01-01 17:11:17 -08001204
Austin Schuhcf5f6442021-07-06 10:43:28 -07001205absl::Span<const uint8_t> SpanReader::PeekMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -08001206 // Make sure we have enough for the size.
1207 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
1208 if (!ReadBlock()) {
1209 return absl::Span<const uint8_t>();
1210 }
1211 }
1212
1213 // Now make sure we have enough for the message.
1214 const size_t data_size =
1215 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
1216 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -08001217 if (data_size == sizeof(flatbuffers::uoffset_t)) {
1218 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
1219 LOG(ERROR) << " Rest of log file is "
1220 << absl::BytesToHexString(std::string_view(
1221 reinterpret_cast<const char *>(data_.data() +
1222 consumed_data_),
1223 data_.size() - consumed_data_));
1224 return absl::Span<const uint8_t>();
1225 }
Austin Schuh05b70472020-01-01 17:11:17 -08001226 while (data_.size() < consumed_data_ + data_size) {
1227 if (!ReadBlock()) {
1228 return absl::Span<const uint8_t>();
1229 }
1230 }
1231
1232 // And return it, consuming the data.
1233 const uint8_t *data_ptr = data_.data() + consumed_data_;
1234
Austin Schuh05b70472020-01-01 17:11:17 -08001235 return absl::Span<const uint8_t>(data_ptr, data_size);
1236}
1237
Austin Schuhcf5f6442021-07-06 10:43:28 -07001238void SpanReader::ConsumeMessage() {
Brian Smarttea913d42021-12-10 15:02:38 -08001239 size_t consumed_size =
Austin Schuhcf5f6442021-07-06 10:43:28 -07001240 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
1241 sizeof(flatbuffers::uoffset_t);
Brian Smarttea913d42021-12-10 15:02:38 -08001242 consumed_data_ += consumed_size;
1243 total_consumed_ += consumed_size;
Austin Schuhcf5f6442021-07-06 10:43:28 -07001244}
1245
1246absl::Span<const uint8_t> SpanReader::ReadMessage() {
1247 absl::Span<const uint8_t> result = PeekMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001248 if (!result.empty()) {
Austin Schuhcf5f6442021-07-06 10:43:28 -07001249 ConsumeMessage();
Brian Smarttea913d42021-12-10 15:02:38 -08001250 } else {
1251 is_finished_ = true;
Austin Schuhcf5f6442021-07-06 10:43:28 -07001252 }
1253 return result;
1254}
1255
Austin Schuh05b70472020-01-01 17:11:17 -08001256bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -07001257 // This is the amount of data we grab at a time. Doing larger chunks minimizes
1258 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -08001259 constexpr size_t kReadSize = 256 * 1024;
1260
1261 // Strip off any unused data at the front.
1262 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -07001263 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -08001264 consumed_data_ = 0;
1265 }
1266
1267 const size_t starting_size = data_.size();
1268
1269 // This should automatically grow the backing store. It won't shrink if we
1270 // get a small chunk later. This reduces allocations when we want to append
1271 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -07001272 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -08001273
Brian Silvermanf51499a2020-09-21 12:49:08 -07001274 const size_t count =
1275 decoder_->Read(data_.begin() + starting_size, data_.end());
1276 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -08001277 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -08001278 return false;
1279 }
Austin Schuh05b70472020-01-01 17:11:17 -08001280
Brian Smarttea913d42021-12-10 15:02:38 -08001281 total_read_ += count;
1282
Austin Schuh05b70472020-01-01 17:11:17 -08001283 return true;
1284}
1285
Alexei Strotsa3194712023-04-21 23:30:50 -07001286LogReadersPool::LogReadersPool(const LogSource *log_source, size_t pool_size)
1287 : log_source_(log_source), pool_size_(pool_size) {}
1288
1289SpanReader *LogReadersPool::BorrowReader(std::string_view id) {
1290 if (part_readers_.size() > pool_size_) {
1291 // Don't leave arbitrary numbers of readers open, because they each take
1292 // resources, so close a big batch at once periodically.
1293 part_readers_.clear();
1294 }
1295 if (log_source_ == nullptr) {
1296 part_readers_.emplace_back(id, FLAGS_quiet_sorting);
1297 } else {
1298 part_readers_.emplace_back(id, log_source_->GetDecoder(id));
1299 }
1300 return &part_readers_.back();
1301}
1302
Austin Schuhadd6eb32020-11-09 21:24:26 -08001303std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh0e8db662021-07-06 10:43:47 -07001304 SpanReader *span_reader) {
1305 absl::Span<const uint8_t> config_data = span_reader->ReadMessage();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001306
1307 // Make sure something was read.
James Kuszmaul9776b392023-01-14 14:08:08 -08001308 if (config_data.empty()) {
Austin Schuh3bd4c402020-11-06 18:19:06 -08001309 return std::nullopt;
1310 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001311
Austin Schuh5212cad2020-09-09 23:12:09 -07001312 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -07001313 SizePrefixedFlatbufferVector<LogFileHeader> result(config_data);
Austin Schuhe09beb12020-12-11 20:04:27 -08001314 if (!result.Verify()) {
1315 return std::nullopt;
1316 }
Austin Schuh0e8db662021-07-06 10:43:47 -07001317
Austin Schuhcc2c9a52022-12-12 15:55:13 -08001318 // We only know of busted headers in the versions of the log file header
1319 // *before* the logger_sha1 field was added. At some point before that point,
1320 // the logic to track when a header has been written was rewritten in such a
1321 // way that it can't happen anymore. We've seen some logs where the body
1322 // parses as a header recently, so the simple solution of always looking is
1323 // failing us.
1324 if (FLAGS_workaround_double_headers && !result.message().has_logger_sha1()) {
Austin Schuh0e8db662021-07-06 10:43:47 -07001325 while (true) {
1326 absl::Span<const uint8_t> maybe_header_data = span_reader->PeekMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001327 if (maybe_header_data.empty()) {
Austin Schuh0e8db662021-07-06 10:43:47 -07001328 break;
1329 }
1330
1331 aos::SizePrefixedFlatbufferSpan<aos::logger::LogFileHeader> maybe_header(
1332 maybe_header_data);
1333 if (maybe_header.Verify()) {
1334 LOG(WARNING) << "Found duplicate LogFileHeader in "
1335 << span_reader->filename();
1336 ResizeableBuffer header_data_copy;
1337 header_data_copy.resize(maybe_header_data.size());
1338 memcpy(header_data_copy.data(), maybe_header_data.begin(),
1339 header_data_copy.size());
1340 result = SizePrefixedFlatbufferVector<LogFileHeader>(
1341 std::move(header_data_copy));
1342
1343 span_reader->ConsumeMessage();
1344 } else {
1345 break;
1346 }
1347 }
1348 }
Austin Schuhe09beb12020-12-11 20:04:27 -08001349 return result;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001350}
1351
Austin Schuh0e8db662021-07-06 10:43:47 -07001352std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
1353 std::string_view filename) {
1354 SpanReader span_reader(filename);
1355 return ReadHeader(&span_reader);
1356}
1357
Austin Schuhadd6eb32020-11-09 21:24:26 -08001358std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -08001359 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -07001360 SpanReader span_reader(filename);
1361 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
1362 for (size_t i = 0; i < n + 1; ++i) {
1363 data_span = span_reader.ReadMessage();
1364
1365 // Make sure something was read.
James Kuszmaul9776b392023-01-14 14:08:08 -08001366 if (data_span.empty()) {
Austin Schuh3bd4c402020-11-06 18:19:06 -08001367 return std::nullopt;
1368 }
Austin Schuh5212cad2020-09-09 23:12:09 -07001369 }
1370
Brian Silverman354697a2020-09-22 21:06:32 -07001371 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -07001372 SizePrefixedFlatbufferVector<MessageHeader> result(data_span);
Austin Schuhe09beb12020-12-11 20:04:27 -08001373 if (!result.Verify()) {
1374 return std::nullopt;
1375 }
1376 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -07001377}
1378
Austin Schuh05b70472020-01-01 17:11:17 -08001379MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -07001380 : span_reader_(filename),
Austin Schuhadd6eb32020-11-09 21:24:26 -08001381 raw_log_file_header_(
1382 SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001383 set_crash_on_corrupt_message_flag(FLAGS_crash_on_corrupt_message);
1384 set_ignore_corrupt_messages_flag(FLAGS_ignore_corrupt_messages);
1385
Austin Schuh0e8db662021-07-06 10:43:47 -07001386 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>>
1387 raw_log_file_header = ReadHeader(&span_reader_);
Austin Schuh05b70472020-01-01 17:11:17 -08001388
1389 // Make sure something was read.
Austin Schuh0e8db662021-07-06 10:43:47 -07001390 CHECK(raw_log_file_header) << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -08001391
Austin Schuh0e8db662021-07-06 10:43:47 -07001392 raw_log_file_header_ = std::move(*raw_log_file_header);
Austin Schuh05b70472020-01-01 17:11:17 -08001393
Austin Schuh5b728b72021-06-16 14:57:15 -07001394 CHECK(raw_log_file_header_.Verify()) << "Log file header is corrupted";
1395
Brian Smarttea913d42021-12-10 15:02:38 -08001396 total_verified_before_ = span_reader_.TotalConsumed();
1397
Austin Schuhcde938c2020-02-02 17:30:07 -08001398 max_out_of_order_duration_ =
Austin Schuha040c3f2021-02-13 16:09:07 -08001399 FLAGS_max_out_of_order > 0
1400 ? chrono::duration_cast<chrono::nanoseconds>(
1401 chrono::duration<double>(FLAGS_max_out_of_order))
1402 : chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -08001403
1404 VLOG(1) << "Opened " << filename << " as node "
1405 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -08001406}
1407
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001408std::shared_ptr<UnpackedMessageHeader> MessageReader::ReadMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -08001409 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001410 if (msg_data.empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001411 if (is_corrupted()) {
1412 LOG(ERROR) << "Total corrupted volumes: before = "
1413 << total_verified_before_
1414 << " | corrupted = " << total_corrupted_
1415 << " | during = " << total_verified_during_
1416 << " | after = " << total_verified_after_ << std::endl;
1417 }
1418
1419 if (span_reader_.IsIncomplete()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001420 LOG(ERROR) << "Unable to access some messages in " << filename() << " : "
1421 << span_reader_.TotalRead() << " bytes read, "
Brian Smarttea913d42021-12-10 15:02:38 -08001422 << span_reader_.TotalConsumed() << " bytes usable."
1423 << std::endl;
1424 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001425 return nullptr;
Austin Schuh05b70472020-01-01 17:11:17 -08001426 }
1427
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001428 SizePrefixedFlatbufferSpan<MessageHeader> msg(msg_data);
Brian Smarttea913d42021-12-10 15:02:38 -08001429
1430 if (crash_on_corrupt_message_flag_) {
1431 CHECK(msg.Verify()) << "Corrupted message at offset "
Austin Schuh60e77942022-05-16 17:48:24 -07001432 << total_verified_before_ << " found within "
1433 << filename()
Brian Smarttea913d42021-12-10 15:02:38 -08001434 << "; set --nocrash_on_corrupt_message to see summary;"
1435 << " also set --ignore_corrupt_messages to process"
1436 << " anyway";
1437
1438 } else if (!msg.Verify()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001439 LOG(ERROR) << "Corrupted message at offset " << total_verified_before_
Brian Smarttea913d42021-12-10 15:02:38 -08001440 << " from " << filename() << std::endl;
1441
1442 total_corrupted_ += msg_data.size();
1443
1444 while (true) {
1445 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
1446
James Kuszmaul9776b392023-01-14 14:08:08 -08001447 if (msg_data.empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001448 if (!ignore_corrupt_messages_flag_) {
1449 LOG(ERROR) << "Total corrupted volumes: before = "
1450 << total_verified_before_
1451 << " | corrupted = " << total_corrupted_
1452 << " | during = " << total_verified_during_
1453 << " | after = " << total_verified_after_ << std::endl;
1454
1455 if (span_reader_.IsIncomplete()) {
1456 LOG(ERROR) << "Unable to access some messages in " << filename()
1457 << " : " << span_reader_.TotalRead() << " bytes read, "
1458 << span_reader_.TotalConsumed() << " bytes usable."
1459 << std::endl;
1460 }
1461 return nullptr;
1462 }
1463 break;
1464 }
1465
1466 SizePrefixedFlatbufferSpan<MessageHeader> next_msg(msg_data);
1467
1468 if (!next_msg.Verify()) {
1469 total_corrupted_ += msg_data.size();
1470 total_verified_during_ += total_verified_after_;
1471 total_verified_after_ = 0;
1472
1473 } else {
1474 total_verified_after_ += msg_data.size();
1475 if (ignore_corrupt_messages_flag_) {
1476 msg = next_msg;
1477 break;
1478 }
1479 }
1480 }
1481 }
1482
1483 if (is_corrupted()) {
1484 total_verified_after_ += msg_data.size();
1485 } else {
1486 total_verified_before_ += msg_data.size();
1487 }
Austin Schuh05b70472020-01-01 17:11:17 -08001488
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001489 auto result = UnpackedMessageHeader::MakeMessage(msg.message());
Austin Schuh0e8db662021-07-06 10:43:47 -07001490
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001491 const monotonic_clock::time_point timestamp = result->monotonic_sent_time;
Austin Schuh05b70472020-01-01 17:11:17 -08001492
1493 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuhd1873292021-11-18 15:35:30 -08001494
1495 if (VLOG_IS_ON(3)) {
1496 VLOG(3) << "Read from " << filename() << " data " << FlatbufferToJson(msg);
1497 } else if (VLOG_IS_ON(2)) {
1498 SizePrefixedFlatbufferVector<MessageHeader> msg_copy = msg;
1499 msg_copy.mutable_message()->clear_data();
1500 VLOG(2) << "Read from " << filename() << " data "
1501 << FlatbufferToJson(msg_copy);
1502 }
1503
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001504 return result;
1505}
1506
1507std::shared_ptr<UnpackedMessageHeader> UnpackedMessageHeader::MakeMessage(
1508 const MessageHeader &message) {
1509 const size_t data_size = message.has_data() ? message.data()->size() : 0;
1510
1511 UnpackedMessageHeader *const unpacked_message =
1512 reinterpret_cast<UnpackedMessageHeader *>(
1513 malloc(sizeof(UnpackedMessageHeader) + data_size +
1514 kChannelDataAlignment - 1));
1515
1516 CHECK(message.has_channel_index());
1517 CHECK(message.has_monotonic_sent_time());
1518
1519 absl::Span<uint8_t> span;
1520 if (data_size > 0) {
1521 span =
1522 absl::Span<uint8_t>(reinterpret_cast<uint8_t *>(RoundChannelData(
1523 &unpacked_message->actual_data[0], data_size)),
1524 data_size);
1525 }
1526
Austin Schuh826e6ce2021-11-18 20:33:10 -08001527 std::optional<aos::monotonic_clock::time_point> monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001528 if (message.has_monotonic_remote_time()) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001529 monotonic_remote_time = aos::monotonic_clock::time_point(
1530 std::chrono::nanoseconds(message.monotonic_remote_time()));
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001531 }
1532 std::optional<realtime_clock::time_point> realtime_remote_time;
1533 if (message.has_realtime_remote_time()) {
1534 realtime_remote_time = realtime_clock::time_point(
1535 chrono::nanoseconds(message.realtime_remote_time()));
1536 }
1537
1538 std::optional<uint32_t> remote_queue_index;
1539 if (message.has_remote_queue_index()) {
1540 remote_queue_index = message.remote_queue_index();
1541 }
1542
James Kuszmaul9776b392023-01-14 14:08:08 -08001543 new (unpacked_message) UnpackedMessageHeader(
1544 message.channel_index(),
1545 monotonic_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001546 chrono::nanoseconds(message.monotonic_sent_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001547 realtime_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001548 chrono::nanoseconds(message.realtime_sent_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001549 message.queue_index(), monotonic_remote_time, realtime_remote_time,
1550 remote_queue_index,
1551 monotonic_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001552 std::chrono::nanoseconds(message.monotonic_timestamp_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001553 message.has_monotonic_timestamp_time(), span);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001554
1555 if (data_size > 0) {
1556 memcpy(span.data(), message.data()->data(), data_size);
1557 }
1558
1559 return std::shared_ptr<UnpackedMessageHeader>(unpacked_message,
1560 &DestroyAndFree);
Austin Schuh05b70472020-01-01 17:11:17 -08001561}
1562
Austin Schuhc41603c2020-10-11 16:17:37 -07001563PartsMessageReader::PartsMessageReader(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -07001564 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {
Brian Silvermanfee16972021-09-14 12:06:38 -07001565 if (parts_.parts.size() >= 2) {
1566 next_message_reader_.emplace(parts_.parts[1]);
1567 }
Austin Schuh48507722021-07-17 17:29:24 -07001568 ComputeBootCounts();
1569}
1570
1571void PartsMessageReader::ComputeBootCounts() {
1572 boot_counts_.assign(configuration::NodesCount(parts_.config.get()),
1573 std::nullopt);
1574
1575 // We have 3 vintages of log files with different amounts of information.
1576 if (log_file_header()->has_boot_uuids()) {
1577 // The new hotness with the boots explicitly listed out. We can use the log
1578 // file header to compute the boot count of all relevant nodes.
1579 CHECK_EQ(log_file_header()->boot_uuids()->size(), boot_counts_.size());
1580 size_t node_index = 0;
1581 for (const flatbuffers::String *boot_uuid :
1582 *log_file_header()->boot_uuids()) {
1583 CHECK(parts_.boots);
1584 if (boot_uuid->size() != 0) {
1585 auto it = parts_.boots->boot_count_map.find(boot_uuid->str());
1586 if (it != parts_.boots->boot_count_map.end()) {
1587 boot_counts_[node_index] = it->second;
1588 }
1589 } else if (parts().boots->boots[node_index].size() == 1u) {
1590 boot_counts_[node_index] = 0;
1591 }
1592 ++node_index;
1593 }
1594 } else {
1595 // Older multi-node logs which are guarenteed to have UUIDs logged, or
1596 // single node log files with boot UUIDs in the header. We only know how to
1597 // order certain boots in certain circumstances.
1598 if (configuration::MultiNode(parts_.config.get()) || parts_.boots) {
1599 for (size_t node_index = 0; node_index < boot_counts_.size();
1600 ++node_index) {
1601 CHECK(parts_.boots);
1602 if (parts().boots->boots[node_index].size() == 1u) {
1603 boot_counts_[node_index] = 0;
1604 }
1605 }
1606 } else {
1607 // Really old single node logs without any UUIDs. They can't reboot.
1608 CHECK_EQ(boot_counts_.size(), 1u);
1609 boot_counts_[0] = 0u;
1610 }
1611 }
1612}
Austin Schuhc41603c2020-10-11 16:17:37 -07001613
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001614std::shared_ptr<UnpackedMessageHeader> PartsMessageReader::ReadMessage() {
Austin Schuhc41603c2020-10-11 16:17:37 -07001615 while (!done_) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001616 std::shared_ptr<UnpackedMessageHeader> message =
Austin Schuhc41603c2020-10-11 16:17:37 -07001617 message_reader_.ReadMessage();
1618 if (message) {
1619 newest_timestamp_ = message_reader_.newest_timestamp();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001620 const monotonic_clock::time_point monotonic_sent_time =
1621 message->monotonic_sent_time;
1622
1623 // TODO(austin): Does this work with startup? Might need to use the
1624 // start time.
1625 // TODO(austin): Does this work with startup when we don't know the
1626 // remote start time too? Look at one of those logs to compare.
Austin Schuh315b96b2020-12-11 21:21:12 -08001627 if (monotonic_sent_time >
1628 parts_.monotonic_start_time + max_out_of_order_duration()) {
1629 after_start_ = true;
1630 }
1631 if (after_start_) {
Austin Schuhb000de62020-12-03 22:00:40 -08001632 CHECK_GE(monotonic_sent_time,
1633 newest_timestamp_ - max_out_of_order_duration())
Austin Schuha040c3f2021-02-13 16:09:07 -08001634 << ": Max out of order of " << max_out_of_order_duration().count()
1635 << "ns exceeded. " << parts_ << ", start time is "
Austin Schuh315b96b2020-12-11 21:21:12 -08001636 << parts_.monotonic_start_time << " currently reading "
1637 << filename();
Austin Schuhb000de62020-12-03 22:00:40 -08001638 }
Austin Schuhc41603c2020-10-11 16:17:37 -07001639 return message;
1640 }
1641 NextLog();
1642 }
Austin Schuh32f68492020-11-08 21:45:51 -08001643 newest_timestamp_ = monotonic_clock::max_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001644 return nullptr;
Austin Schuhc41603c2020-10-11 16:17:37 -07001645}
1646
1647void PartsMessageReader::NextLog() {
1648 if (next_part_index_ == parts_.parts.size()) {
Brian Silvermanfee16972021-09-14 12:06:38 -07001649 CHECK(!next_message_reader_);
Austin Schuhc41603c2020-10-11 16:17:37 -07001650 done_ = true;
1651 return;
1652 }
Brian Silvermanfee16972021-09-14 12:06:38 -07001653 CHECK(next_message_reader_);
1654 message_reader_ = std::move(*next_message_reader_);
Austin Schuh48507722021-07-17 17:29:24 -07001655 ComputeBootCounts();
Brian Silvermanfee16972021-09-14 12:06:38 -07001656 if (next_part_index_ + 1 < parts_.parts.size()) {
1657 next_message_reader_.emplace(parts_.parts[next_part_index_ + 1]);
1658 } else {
1659 next_message_reader_.reset();
1660 }
Austin Schuhc41603c2020-10-11 16:17:37 -07001661 ++next_part_index_;
1662}
1663
Austin Schuh1be0ce42020-11-29 22:43:26 -08001664bool Message::operator<(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001665 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001666
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001667 if (this->timestamp.time < m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -08001668 return true;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001669 } else if (this->timestamp.time > m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -08001670 return false;
1671 }
1672
1673 if (this->channel_index < m2.channel_index) {
1674 return true;
1675 } else if (this->channel_index > m2.channel_index) {
1676 return false;
1677 }
1678
1679 return this->queue_index < m2.queue_index;
1680}
1681
1682bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001683bool Message::operator==(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001684 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001685
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001686 return timestamp.time == m2.timestamp.time &&
1687 channel_index == m2.channel_index && queue_index == m2.queue_index;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001688}
Austin Schuh1be0ce42020-11-29 22:43:26 -08001689
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001690std::ostream &operator<<(std::ostream &os, const UnpackedMessageHeader &m) {
1691 os << "{.channel_index=" << m.channel_index
1692 << ", .monotonic_sent_time=" << m.monotonic_sent_time
1693 << ", .realtime_sent_time=" << m.realtime_sent_time
1694 << ", .queue_index=" << m.queue_index;
1695 if (m.monotonic_remote_time) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001696 os << ", .monotonic_remote_time=" << *m.monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001697 }
1698 os << ", .realtime_remote_time=";
1699 PrintOptionalOrNull(&os, m.realtime_remote_time);
1700 os << ", .remote_queue_index=";
1701 PrintOptionalOrNull(&os, m.remote_queue_index);
1702 if (m.has_monotonic_timestamp_time) {
1703 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
1704 }
Austin Schuh22cf7862022-09-19 19:09:42 -07001705 os << "}";
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001706 return os;
1707}
1708
Austin Schuh1be0ce42020-11-29 22:43:26 -08001709std::ostream &operator<<(std::ostream &os, const Message &m) {
1710 os << "{.channel_index=" << m.channel_index
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001711 << ", .queue_index=" << m.queue_index << ", .timestamp=" << m.timestamp;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001712 if (m.data != nullptr) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001713 if (m.data->remote_queue_index.has_value()) {
1714 os << ", .remote_queue_index=" << *m.data->remote_queue_index;
1715 }
1716 if (m.data->monotonic_remote_time.has_value()) {
1717 os << ", .monotonic_remote_time=" << *m.data->monotonic_remote_time;
1718 }
Austin Schuhfb1b3292021-11-16 21:20:15 -08001719 os << ", .data=" << m.data;
Austin Schuhd2f96102020-12-01 20:27:29 -08001720 }
1721 os << "}";
1722 return os;
1723}
1724
1725std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m) {
1726 os << "{.channel_index=" << m.channel_index
1727 << ", .queue_index=" << m.queue_index
1728 << ", .monotonic_event_time=" << m.monotonic_event_time
1729 << ", .realtime_event_time=" << m.realtime_event_time;
Austin Schuh58646e22021-08-23 23:51:46 -07001730 if (m.remote_queue_index != BootQueueIndex::Invalid()) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001731 os << ", .remote_queue_index=" << m.remote_queue_index;
1732 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001733 if (m.monotonic_remote_time != BootTimestamp::min_time()) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001734 os << ", .monotonic_remote_time=" << m.monotonic_remote_time;
1735 }
1736 if (m.realtime_remote_time != realtime_clock::min_time) {
1737 os << ", .realtime_remote_time=" << m.realtime_remote_time;
1738 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001739 if (m.monotonic_timestamp_time != BootTimestamp::min_time()) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001740 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
1741 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001742 if (m.data != nullptr) {
1743 os << ", .data=" << *m.data;
Austin Schuh22cf7862022-09-19 19:09:42 -07001744 } else {
1745 os << ", .data=nullptr";
Austin Schuhd2f96102020-12-01 20:27:29 -08001746 }
1747 os << "}";
Austin Schuh1be0ce42020-11-29 22:43:26 -08001748 return os;
1749}
1750
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001751MessageSorter::MessageSorter(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -07001752 : parts_message_reader_(log_parts),
1753 source_node_index_(configuration::SourceNodeIndex(parts().config.get())) {
1754}
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001755
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001756Message *MessageSorter::Front() {
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001757 // Queue up data until enough data has been queued that the front message is
1758 // sorted enough to be safe to pop. This may do nothing, so we should make
1759 // sure the nothing path is checked quickly.
1760 if (sorted_until() != monotonic_clock::max_time) {
1761 while (true) {
Austin Schuh48507722021-07-17 17:29:24 -07001762 if (!messages_.empty() &&
1763 messages_.begin()->timestamp.time < sorted_until() &&
Austin Schuhb000de62020-12-03 22:00:40 -08001764 sorted_until() >= monotonic_start_time()) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001765 break;
1766 }
1767
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001768 std::shared_ptr<UnpackedMessageHeader> m =
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001769 parts_message_reader_.ReadMessage();
1770 // No data left, sorted forever, work through what is left.
1771 if (!m) {
1772 sorted_until_ = monotonic_clock::max_time;
1773 break;
1774 }
1775
Austin Schuh48507722021-07-17 17:29:24 -07001776 size_t monotonic_timestamp_boot = 0;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001777 if (m->has_monotonic_timestamp_time) {
Austin Schuh48507722021-07-17 17:29:24 -07001778 monotonic_timestamp_boot = parts().logger_boot_count;
1779 }
1780 size_t monotonic_remote_boot = 0xffffff;
1781
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001782 if (m->monotonic_remote_time.has_value()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001783 const Node *node =
1784 parts().config->nodes()->Get(source_node_index_[m->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -07001785
Austin Schuh48507722021-07-17 17:29:24 -07001786 std::optional<size_t> boot = parts_message_reader_.boot_count(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001787 source_node_index_[m->channel_index]);
Alexei Strots036d84e2023-05-03 16:05:12 -07001788 CHECK(boot) << ": Failed to find boot for node '" << MaybeNodeName(node)
1789 << "', with index " << source_node_index_[m->channel_index];
Austin Schuh48507722021-07-17 17:29:24 -07001790 monotonic_remote_boot = *boot;
1791 }
1792
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001793 messages_.insert(
1794 Message{.channel_index = m->channel_index,
1795 .queue_index = BootQueueIndex{.boot = parts().boot_count,
1796 .index = m->queue_index},
1797 .timestamp = BootTimestamp{.boot = parts().boot_count,
1798 .time = m->monotonic_sent_time},
1799 .monotonic_remote_boot = monotonic_remote_boot,
1800 .monotonic_timestamp_boot = monotonic_timestamp_boot,
1801 .data = std::move(m)});
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001802
1803 // Now, update sorted_until_ to match the new message.
1804 if (parts_message_reader_.newest_timestamp() >
1805 monotonic_clock::min_time +
1806 parts_message_reader_.max_out_of_order_duration()) {
1807 sorted_until_ = parts_message_reader_.newest_timestamp() -
1808 parts_message_reader_.max_out_of_order_duration();
1809 } else {
1810 sorted_until_ = monotonic_clock::min_time;
1811 }
1812 }
1813 }
1814
1815 // Now that we have enough data queued, return a pointer to the oldest piece
1816 // of data if it exists.
1817 if (messages_.empty()) {
Austin Schuhb000de62020-12-03 22:00:40 -08001818 last_message_time_ = monotonic_clock::max_time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001819 return nullptr;
1820 }
1821
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001822 CHECK_GE(messages_.begin()->timestamp.time, last_message_time_)
Austin Schuh315b96b2020-12-11 21:21:12 -08001823 << DebugString() << " reading " << parts_message_reader_.filename();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001824 last_message_time_ = messages_.begin()->timestamp.time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001825 return &(*messages_.begin());
1826}
1827
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001828void MessageSorter::PopFront() { messages_.erase(messages_.begin()); }
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001829
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001830std::string MessageSorter::DebugString() const {
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001831 std::stringstream ss;
1832 ss << "messages: [\n";
Austin Schuh315b96b2020-12-11 21:21:12 -08001833 int count = 0;
1834 bool no_dots = true;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001835 for (const Message &m : messages_) {
Austin Schuh315b96b2020-12-11 21:21:12 -08001836 if (count < 15 || count > static_cast<int>(messages_.size()) - 15) {
1837 ss << m << "\n";
1838 } else if (no_dots) {
1839 ss << "...\n";
1840 no_dots = false;
1841 }
1842 ++count;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001843 }
1844 ss << "] <- " << parts_message_reader_.filename();
1845 return ss.str();
1846}
1847
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001848PartsMerger::PartsMerger(std::vector<LogParts> parts) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001849 CHECK_GE(parts.size(), 1u);
Austin Schuh715adc12021-06-29 22:07:39 -07001850 // Enforce that we are sorting things only from a single node from a single
1851 // boot.
1852 const std::string_view part0_node = parts[0].node;
1853 const std::string_view part0_source_boot_uuid = parts[0].source_boot_uuid;
Austin Schuhd2f96102020-12-01 20:27:29 -08001854 for (size_t i = 1; i < parts.size(); ++i) {
1855 CHECK_EQ(part0_node, parts[i].node) << ": Can't merge different nodes.";
Austin Schuh715adc12021-06-29 22:07:39 -07001856 CHECK_EQ(part0_source_boot_uuid, parts[i].source_boot_uuid)
1857 << ": Can't merge different boots.";
Austin Schuhd2f96102020-12-01 20:27:29 -08001858 }
Austin Schuh715adc12021-06-29 22:07:39 -07001859
1860 node_ = configuration::GetNodeIndex(parts[0].config.get(), part0_node);
1861
Austin Schuhd2f96102020-12-01 20:27:29 -08001862 for (LogParts &part : parts) {
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001863 message_sorters_.emplace_back(std::move(part));
Austin Schuhd2f96102020-12-01 20:27:29 -08001864 }
1865
Austin Schuhd2f96102020-12-01 20:27:29 -08001866 monotonic_start_time_ = monotonic_clock::max_time;
Austin Schuh9dc42612021-09-20 20:41:29 -07001867 realtime_start_time_ = realtime_clock::min_time;
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001868 for (const MessageSorter &message_sorter : message_sorters_) {
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001869 // We want to capture the earliest meaningful start time here. The start
1870 // time defaults to min_time when there's no meaningful value to report, so
1871 // let's ignore those.
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001872 if (message_sorter.monotonic_start_time() != monotonic_clock::min_time) {
Austin Schuh9dc42612021-09-20 20:41:29 -07001873 bool accept = false;
1874 // We want to prioritize start times from the logger node. Really, we
1875 // want to prioritize start times with a valid realtime_clock time. So,
1876 // if we have a start time without a RT clock, prefer a start time with a
1877 // RT clock, even it if is later.
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001878 if (message_sorter.realtime_start_time() != realtime_clock::min_time) {
Austin Schuh9dc42612021-09-20 20:41:29 -07001879 // We've got a good one. See if the current start time has a good RT
1880 // clock, or if we should use this one instead.
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001881 if (message_sorter.monotonic_start_time() < monotonic_start_time_) {
Austin Schuh9dc42612021-09-20 20:41:29 -07001882 accept = true;
1883 } else if (realtime_start_time_ == realtime_clock::min_time) {
1884 // The previous start time doesn't have a good RT time, so it is very
1885 // likely the start time from a remote part file. We just found a
1886 // better start time with a real RT time, so switch to that instead.
1887 accept = true;
1888 }
1889 } else if (realtime_start_time_ == realtime_clock::min_time) {
1890 // We don't have a RT time, so take the oldest.
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001891 if (message_sorter.monotonic_start_time() < monotonic_start_time_) {
Austin Schuh9dc42612021-09-20 20:41:29 -07001892 accept = true;
1893 }
1894 }
1895
1896 if (accept) {
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001897 monotonic_start_time_ = message_sorter.monotonic_start_time();
1898 realtime_start_time_ = message_sorter.realtime_start_time();
Austin Schuh9dc42612021-09-20 20:41:29 -07001899 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001900 }
1901 }
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001902
1903 // If there was no meaningful start time reported, just use min_time.
1904 if (monotonic_start_time_ == monotonic_clock::max_time) {
1905 monotonic_start_time_ = monotonic_clock::min_time;
1906 realtime_start_time_ = realtime_clock::min_time;
1907 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001908}
Austin Schuh8f52ed52020-11-30 23:12:39 -08001909
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001910std::vector<const LogParts *> PartsMerger::Parts() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001911 std::vector<const LogParts *> p;
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001912 p.reserve(message_sorters_.size());
1913 for (const MessageSorter &message_sorter : message_sorters_) {
1914 p.emplace_back(&message_sorter.parts());
Austin Schuh0ca51f32020-12-25 21:51:45 -08001915 }
1916 return p;
1917}
1918
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001919Message *PartsMerger::Front() {
Austin Schuh8f52ed52020-11-30 23:12:39 -08001920 // Return the current Front if we have one, otherwise go compute one.
1921 if (current_ != nullptr) {
Austin Schuhb000de62020-12-03 22:00:40 -08001922 Message *result = current_->Front();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001923 CHECK_GE(result->timestamp.time, last_message_time_);
Austin Schuhb000de62020-12-03 22:00:40 -08001924 return result;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001925 }
1926
1927 // Otherwise, do a simple search for the oldest message, deduplicating any
1928 // duplicates.
1929 Message *oldest = nullptr;
1930 sorted_until_ = monotonic_clock::max_time;
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001931 for (MessageSorter &message_sorter : message_sorters_) {
1932 Message *m = message_sorter.Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -08001933 if (!m) {
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001934 sorted_until_ = std::min(sorted_until_, message_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001935 continue;
1936 }
1937 if (oldest == nullptr || *m < *oldest) {
1938 oldest = m;
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001939 current_ = &message_sorter;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001940 } else if (*m == *oldest) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001941 // Found a duplicate. If there is a choice, we want the one which has
1942 // the timestamp time.
1943 if (!m->data->has_monotonic_timestamp_time) {
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001944 message_sorter.PopFront();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001945 } else if (!oldest->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001946 current_->PopFront();
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001947 current_ = &message_sorter;
Austin Schuh8bf1e632021-01-02 22:41:04 -08001948 oldest = m;
1949 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001950 CHECK_EQ(m->data->monotonic_timestamp_time,
1951 oldest->data->monotonic_timestamp_time);
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001952 message_sorter.PopFront();
Austin Schuh8bf1e632021-01-02 22:41:04 -08001953 }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001954 }
1955
1956 // PopFront may change this, so compute it down here.
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001957 sorted_until_ = std::min(sorted_until_, message_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001958 }
1959
Austin Schuhb000de62020-12-03 22:00:40 -08001960 if (oldest) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001961 CHECK_GE(oldest->timestamp.time, last_message_time_);
1962 last_message_time_ = oldest->timestamp.time;
Austin Schuh5dd22842021-11-17 16:09:39 -08001963 monotonic_oldest_time_ =
1964 std::min(monotonic_oldest_time_, oldest->timestamp.time);
Austin Schuhb000de62020-12-03 22:00:40 -08001965 } else {
1966 last_message_time_ = monotonic_clock::max_time;
1967 }
1968
Austin Schuh8f52ed52020-11-30 23:12:39 -08001969 // Return the oldest message found. This will be nullptr if nothing was
1970 // found, indicating there is nothing left.
1971 return oldest;
1972}
1973
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001974void PartsMerger::PopFront() {
Austin Schuh8f52ed52020-11-30 23:12:39 -08001975 CHECK(current_ != nullptr) << "Popping before calling Front()";
1976 current_->PopFront();
1977 current_ = nullptr;
1978}
1979
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001980BootMerger::BootMerger(std::vector<LogParts> files) {
1981 std::vector<std::vector<LogParts>> boots;
1982
1983 // Now, we need to split things out by boot.
1984 for (size_t i = 0; i < files.size(); ++i) {
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001985 const size_t boot_count = files[i].boot_count;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001986 if (boot_count + 1 > boots.size()) {
1987 boots.resize(boot_count + 1);
1988 }
1989 boots[boot_count].emplace_back(std::move(files[i]));
1990 }
1991
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001992 parts_mergers_.reserve(boots.size());
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001993 for (size_t i = 0; i < boots.size(); ++i) {
Austin Schuh48507722021-07-17 17:29:24 -07001994 VLOG(2) << "Boot " << i;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001995 for (auto &p : boots[i]) {
Austin Schuh48507722021-07-17 17:29:24 -07001996 VLOG(2) << "Part " << p;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001997 }
Alexei Strotsa8dadd12023-04-28 15:19:23 -07001998 parts_mergers_.emplace_back(
1999 std::make_unique<PartsMerger>(std::move(boots[i])));
Austin Schuhf16ef6a2021-06-30 21:48:17 -07002000 }
2001}
2002
2003Message *BootMerger::Front() {
Alexei Strotsa8dadd12023-04-28 15:19:23 -07002004 Message *result = parts_mergers_[index_]->Front();
Austin Schuhf16ef6a2021-06-30 21:48:17 -07002005
2006 if (result != nullptr) {
2007 return result;
2008 }
2009
Alexei Strotsa8dadd12023-04-28 15:19:23 -07002010 if (index_ + 1u == parts_mergers_.size()) {
Austin Schuhf16ef6a2021-06-30 21:48:17 -07002011 // At the end of the last node merger, just return.
2012 return nullptr;
2013 } else {
2014 ++index_;
2015 return Front();
2016 }
2017}
2018
Alexei Strotsa8dadd12023-04-28 15:19:23 -07002019void BootMerger::PopFront() { parts_mergers_[index_]->PopFront(); }
Austin Schuhf16ef6a2021-06-30 21:48:17 -07002020
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002021std::vector<const LogParts *> BootMerger::Parts() const {
2022 std::vector<const LogParts *> results;
Alexei Strotsa8dadd12023-04-28 15:19:23 -07002023 for (const std::unique_ptr<PartsMerger> &parts_merger : parts_mergers_) {
2024 std::vector<const LogParts *> node_parts = parts_merger->Parts();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002025
2026 results.insert(results.end(), std::make_move_iterator(node_parts.begin()),
2027 std::make_move_iterator(node_parts.end()));
2028 }
2029
2030 return results;
2031}
2032
Austin Schuhd2f96102020-12-01 20:27:29 -08002033TimestampMapper::TimestampMapper(std::vector<LogParts> parts)
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002034 : boot_merger_(std::move(parts)),
Austin Schuh79b30942021-01-24 22:32:21 -08002035 timestamp_callback_([](TimestampedMessage *) {}) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002036 for (const LogParts *part : boot_merger_.Parts()) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08002037 if (!configuration_) {
2038 configuration_ = part->config;
2039 } else {
2040 CHECK_EQ(configuration_.get(), part->config.get());
2041 }
2042 }
2043 const Configuration *config = configuration_.get();
Austin Schuhd2f96102020-12-01 20:27:29 -08002044 // Only fill out nodes_data_ if there are nodes. Otherwise everything gets
2045 // pretty simple.
2046 if (configuration::MultiNode(config)) {
2047 nodes_data_.resize(config->nodes()->size());
2048 const Node *my_node = config->nodes()->Get(node());
2049 for (size_t node_index = 0; node_index < nodes_data_.size(); ++node_index) {
2050 const Node *node = config->nodes()->Get(node_index);
2051 NodeData *node_data = &nodes_data_[node_index];
2052 node_data->channels.resize(config->channels()->size());
2053 // We should save the channel if it is delivered to the node represented
2054 // by the NodeData, but not sent by that node. That combo means it is
2055 // forwarded.
2056 size_t channel_index = 0;
2057 node_data->any_delivered = false;
2058 for (const Channel *channel : *config->channels()) {
2059 node_data->channels[channel_index].delivered =
2060 configuration::ChannelIsReadableOnNode(channel, node) &&
Austin Schuhb3dbb6d2021-01-02 17:29:35 -08002061 configuration::ChannelIsSendableOnNode(channel, my_node) &&
2062 (my_node != node);
Austin Schuhd2f96102020-12-01 20:27:29 -08002063 node_data->any_delivered = node_data->any_delivered ||
2064 node_data->channels[channel_index].delivered;
Austin Schuh6a7358f2021-11-18 22:40:40 -08002065 if (node_data->channels[channel_index].delivered) {
2066 const Connection *connection =
2067 configuration::ConnectionToNode(channel, node);
2068 node_data->channels[channel_index].time_to_live =
2069 chrono::nanoseconds(connection->time_to_live());
2070 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002071 ++channel_index;
2072 }
2073 }
2074
2075 for (const Channel *channel : *config->channels()) {
2076 source_node_.emplace_back(configuration::GetNodeIndex(
2077 config, channel->source_node()->string_view()));
2078 }
2079 }
2080}
2081
2082void TimestampMapper::AddPeer(TimestampMapper *timestamp_mapper) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08002083 CHECK(configuration::MultiNode(configuration()));
Austin Schuhd2f96102020-12-01 20:27:29 -08002084 CHECK_NE(timestamp_mapper->node(), node());
2085 CHECK_LT(timestamp_mapper->node(), nodes_data_.size());
2086
2087 NodeData *node_data = &nodes_data_[timestamp_mapper->node()];
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002088 // Only set it if this node delivers to the peer timestamp_mapper. Otherwise
Austin Schuhd2f96102020-12-01 20:27:29 -08002089 // we could needlessly save data.
2090 if (node_data->any_delivered) {
Austin Schuh87dd3832021-01-01 23:07:31 -08002091 VLOG(1) << "Registering on node " << node() << " for peer node "
2092 << timestamp_mapper->node();
Austin Schuhd2f96102020-12-01 20:27:29 -08002093 CHECK(timestamp_mapper->nodes_data_[node()].peer == nullptr);
2094
2095 timestamp_mapper->nodes_data_[node()].peer = this;
Austin Schuh36c00932021-07-19 18:13:21 -07002096
2097 node_data->save_for_peer = true;
Austin Schuhd2f96102020-12-01 20:27:29 -08002098 }
2099}
2100
Austin Schuh79b30942021-01-24 22:32:21 -08002101void TimestampMapper::QueueMessage(Message *m) {
Austin Schuh60e77942022-05-16 17:48:24 -07002102 matched_messages_.emplace_back(
2103 TimestampedMessage{.channel_index = m->channel_index,
2104 .queue_index = m->queue_index,
2105 .monotonic_event_time = m->timestamp,
2106 .realtime_event_time = m->data->realtime_sent_time,
2107 .remote_queue_index = BootQueueIndex::Invalid(),
2108 .monotonic_remote_time = BootTimestamp::min_time(),
2109 .realtime_remote_time = realtime_clock::min_time,
2110 .monotonic_timestamp_time = BootTimestamp::min_time(),
2111 .data = std::move(m->data)});
Austin Schuhd2f96102020-12-01 20:27:29 -08002112}
2113
2114TimestampedMessage *TimestampMapper::Front() {
2115 // No need to fetch anything new. A previous message still exists.
2116 switch (first_message_) {
2117 case FirstMessage::kNeedsUpdate:
2118 break;
2119 case FirstMessage::kInMessage:
Austin Schuh79b30942021-01-24 22:32:21 -08002120 return &matched_messages_.front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002121 case FirstMessage::kNullptr:
2122 return nullptr;
2123 }
2124
Austin Schuh79b30942021-01-24 22:32:21 -08002125 if (matched_messages_.empty()) {
2126 if (!QueueMatched()) {
2127 first_message_ = FirstMessage::kNullptr;
2128 return nullptr;
2129 }
2130 }
2131 first_message_ = FirstMessage::kInMessage;
2132 return &matched_messages_.front();
2133}
2134
2135bool TimestampMapper::QueueMatched() {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002136 MatchResult result = MatchResult::kEndOfFile;
2137 do {
2138 result = MaybeQueueMatched();
2139 } while (result == MatchResult::kSkipped);
2140 return result == MatchResult::kQueued;
2141}
2142
2143bool TimestampMapper::CheckReplayChannelsAndMaybePop(
2144 const TimestampedMessage & /*message*/) {
2145 if (replay_channels_callback_ &&
2146 !replay_channels_callback_(matched_messages_.back())) {
2147 matched_messages_.pop_back();
2148 return true;
2149 }
2150 return false;
2151}
2152
2153TimestampMapper::MatchResult TimestampMapper::MaybeQueueMatched() {
Austin Schuhd2f96102020-12-01 20:27:29 -08002154 if (nodes_data_.empty()) {
2155 // Simple path. We are single node, so there are no timestamps to match!
2156 CHECK_EQ(messages_.size(), 0u);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002157 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002158 if (!m) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002159 return MatchResult::kEndOfFile;
Austin Schuhd2f96102020-12-01 20:27:29 -08002160 }
Austin Schuh79b30942021-01-24 22:32:21 -08002161 // Enqueue this message into matched_messages_ so we have a place to
2162 // associate remote timestamps, and return it.
2163 QueueMessage(m);
Austin Schuhd2f96102020-12-01 20:27:29 -08002164
Austin Schuh79b30942021-01-24 22:32:21 -08002165 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
2166 last_message_time_ = matched_messages_.back().monotonic_event_time;
2167
Alexei Strotsa8dadd12023-04-28 15:19:23 -07002168 // We are thin wrapper around parts_merger. Call it directly.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002169 boot_merger_.PopFront();
Austin Schuh79b30942021-01-24 22:32:21 -08002170 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002171 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2172 return MatchResult::kSkipped;
2173 }
2174 return MatchResult::kQueued;
Austin Schuhd2f96102020-12-01 20:27:29 -08002175 }
2176
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002177 // We need to only add messages to the list so they get processed for
2178 // messages which are delivered. Reuse the flow below which uses messages_
2179 // by just adding the new message to messages_ and continuing.
Austin Schuhd2f96102020-12-01 20:27:29 -08002180 if (messages_.empty()) {
2181 if (!Queue()) {
2182 // Found nothing to add, we are out of data!
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002183 return MatchResult::kEndOfFile;
Austin Schuhd2f96102020-12-01 20:27:29 -08002184 }
2185
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002186 // Now that it has been added (and cannibalized), forget about it
2187 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002188 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08002189 }
2190
2191 Message *m = &(messages_.front());
2192
2193 if (source_node_[m->channel_index] == node()) {
2194 // From us, just forward it on, filling the remote data in as invalid.
Austin Schuh79b30942021-01-24 22:32:21 -08002195 QueueMessage(m);
2196 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
2197 last_message_time_ = matched_messages_.back().monotonic_event_time;
2198 messages_.pop_front();
2199 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002200 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2201 return MatchResult::kSkipped;
2202 }
2203 return MatchResult::kQueued;
Austin Schuhd2f96102020-12-01 20:27:29 -08002204 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002205 // Got a timestamp, find the matching remote data, match it, and return
2206 // it.
Austin Schuhd2f96102020-12-01 20:27:29 -08002207 Message data = MatchingMessageFor(*m);
2208
2209 // Return the data from the remote. The local message only has timestamp
2210 // info which isn't relevant anymore once extracted.
Austin Schuh79b30942021-01-24 22:32:21 -08002211 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -08002212 .channel_index = m->channel_index,
2213 .queue_index = m->queue_index,
2214 .monotonic_event_time = m->timestamp,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002215 .realtime_event_time = m->data->realtime_sent_time,
Austin Schuh58646e22021-08-23 23:51:46 -07002216 .remote_queue_index =
2217 BootQueueIndex{.boot = m->monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002218 .index = m->data->remote_queue_index.value()},
2219 .monotonic_remote_time = {m->monotonic_remote_boot,
Austin Schuh826e6ce2021-11-18 20:33:10 -08002220 m->data->monotonic_remote_time.value()},
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002221 .realtime_remote_time = m->data->realtime_remote_time.value(),
2222 .monotonic_timestamp_time = {m->monotonic_timestamp_boot,
2223 m->data->monotonic_timestamp_time},
Austin Schuh79b30942021-01-24 22:32:21 -08002224 .data = std::move(data.data)});
2225 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
2226 last_message_time_ = matched_messages_.back().monotonic_event_time;
2227 // Since messages_ holds the data, drop it.
2228 messages_.pop_front();
2229 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002230 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2231 return MatchResult::kSkipped;
2232 }
2233 return MatchResult::kQueued;
Austin Schuh79b30942021-01-24 22:32:21 -08002234 }
2235}
2236
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002237void TimestampMapper::QueueUntil(BootTimestamp queue_time) {
Austin Schuh79b30942021-01-24 22:32:21 -08002238 while (last_message_time_ <= queue_time) {
2239 if (!QueueMatched()) {
2240 return;
2241 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002242 }
2243}
2244
Austin Schuhe639ea12021-01-25 13:00:22 -08002245void TimestampMapper::QueueFor(chrono::nanoseconds time_estimation_buffer) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002246 // Note: queueing for time doesn't really work well across boots. So we
2247 // just assume that if you are using this, you only care about the current
2248 // boot.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002249 //
2250 // TODO(austin): Is that the right concept?
2251 //
Austin Schuhe639ea12021-01-25 13:00:22 -08002252 // Make sure we have something queued first. This makes the end time
2253 // calculation simpler, and is typically what folks want regardless.
2254 if (matched_messages_.empty()) {
2255 if (!QueueMatched()) {
2256 return;
2257 }
2258 }
2259
2260 const aos::monotonic_clock::time_point end_queue_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002261 std::max(monotonic_start_time(
2262 matched_messages_.front().monotonic_event_time.boot),
2263 matched_messages_.front().monotonic_event_time.time) +
Austin Schuhe639ea12021-01-25 13:00:22 -08002264 time_estimation_buffer;
2265
2266 // Place sorted messages on the list until we have
2267 // --time_estimation_buffer_seconds seconds queued up (but queue at least
2268 // until the log starts).
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002269 while (end_queue_time >= last_message_time_.time) {
Austin Schuhe639ea12021-01-25 13:00:22 -08002270 if (!QueueMatched()) {
2271 return;
2272 }
2273 }
2274}
2275
Austin Schuhd2f96102020-12-01 20:27:29 -08002276void TimestampMapper::PopFront() {
2277 CHECK(first_message_ != FirstMessage::kNeedsUpdate);
Austin Schuh6a7358f2021-11-18 22:40:40 -08002278 last_popped_message_time_ = Front()->monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08002279 first_message_ = FirstMessage::kNeedsUpdate;
2280
Austin Schuh79b30942021-01-24 22:32:21 -08002281 matched_messages_.pop_front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002282}
2283
2284Message TimestampMapper::MatchingMessageFor(const Message &message) {
Austin Schuhd2f96102020-12-01 20:27:29 -08002285 // Figure out what queue index we are looking for.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002286 CHECK_NOTNULL(message.data);
2287 CHECK(message.data->remote_queue_index.has_value());
Austin Schuh58646e22021-08-23 23:51:46 -07002288 const BootQueueIndex remote_queue_index =
2289 BootQueueIndex{.boot = message.monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002290 .index = *message.data->remote_queue_index};
Austin Schuhd2f96102020-12-01 20:27:29 -08002291
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002292 CHECK(message.data->monotonic_remote_time.has_value());
2293 CHECK(message.data->realtime_remote_time.has_value());
Austin Schuhd2f96102020-12-01 20:27:29 -08002294
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002295 const BootTimestamp monotonic_remote_time{
Austin Schuh48507722021-07-17 17:29:24 -07002296 .boot = message.monotonic_remote_boot,
Austin Schuh826e6ce2021-11-18 20:33:10 -08002297 .time = message.data->monotonic_remote_time.value()};
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002298 const realtime_clock::time_point realtime_remote_time =
2299 *message.data->realtime_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08002300
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002301 TimestampMapper *peer =
2302 nodes_data_[source_node_[message.data->channel_index]].peer;
Austin Schuhfecf1d82020-12-19 16:57:28 -08002303
2304 // We only register the peers which we have data for. So, if we are being
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002305 // asked to pull a timestamp from a peer which doesn't exist, return an
2306 // empty message.
Austin Schuhfecf1d82020-12-19 16:57:28 -08002307 if (peer == nullptr) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002308 // TODO(austin): Make sure the tests hit all these paths with a boot count
2309 // of 1...
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002310 return Message{.channel_index = message.channel_index,
2311 .queue_index = remote_queue_index,
2312 .timestamp = monotonic_remote_time,
2313 .monotonic_remote_boot = 0xffffff,
2314 .monotonic_timestamp_boot = 0xffffff,
2315 .data = nullptr};
Austin Schuhfecf1d82020-12-19 16:57:28 -08002316 }
2317
2318 // The queue which will have the matching data, if available.
2319 std::deque<Message> *data_queue =
2320 &peer->nodes_data_[node()].channels[message.channel_index].messages;
2321
Austin Schuh79b30942021-01-24 22:32:21 -08002322 peer->QueueUnmatchedUntil(monotonic_remote_time);
Austin Schuhd2f96102020-12-01 20:27:29 -08002323
2324 if (data_queue->empty()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002325 return Message{.channel_index = message.channel_index,
2326 .queue_index = remote_queue_index,
2327 .timestamp = monotonic_remote_time,
2328 .monotonic_remote_boot = 0xffffff,
2329 .monotonic_timestamp_boot = 0xffffff,
2330 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08002331 }
2332
Austin Schuhd2f96102020-12-01 20:27:29 -08002333 if (remote_queue_index < data_queue->front().queue_index ||
2334 remote_queue_index > data_queue->back().queue_index) {
Austin Schuh60e77942022-05-16 17:48:24 -07002335 return Message{.channel_index = message.channel_index,
2336 .queue_index = remote_queue_index,
2337 .timestamp = monotonic_remote_time,
2338 .monotonic_remote_boot = 0xffffff,
2339 .monotonic_timestamp_boot = 0xffffff,
2340 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08002341 }
2342
Austin Schuh993ccb52020-12-12 15:59:32 -08002343 // The algorithm below is constant time with some assumptions. We need there
2344 // to be no missing messages in the data stream. This also assumes a queue
2345 // hasn't wrapped. That is conservative, but should let us get started.
Austin Schuh58646e22021-08-23 23:51:46 -07002346 if (data_queue->back().queue_index.boot ==
2347 data_queue->front().queue_index.boot &&
2348 (data_queue->back().queue_index.index -
2349 data_queue->front().queue_index.index + 1u ==
2350 data_queue->size())) {
2351 CHECK_EQ(remote_queue_index.boot, data_queue->front().queue_index.boot);
Austin Schuh993ccb52020-12-12 15:59:32 -08002352 // Pull the data out and confirm that the timestamps match as expected.
Austin Schuh58646e22021-08-23 23:51:46 -07002353 //
2354 // TODO(austin): Move if not reliable.
2355 Message result = (*data_queue)[remote_queue_index.index -
2356 data_queue->front().queue_index.index];
Austin Schuh993ccb52020-12-12 15:59:32 -08002357
2358 CHECK_EQ(result.timestamp, monotonic_remote_time)
2359 << ": Queue index matches, but timestamp doesn't. Please investigate!";
Austin Schuh6a7358f2021-11-18 22:40:40 -08002360 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
Austin Schuh993ccb52020-12-12 15:59:32 -08002361 << ": Queue index matches, but timestamp doesn't. Please investigate!";
2362 // Now drop the data off the front. We have deduplicated timestamps, so we
2363 // are done. And all the data is in order.
Austin Schuh58646e22021-08-23 23:51:46 -07002364 data_queue->erase(
2365 data_queue->begin(),
2366 data_queue->begin() +
2367 (remote_queue_index.index - data_queue->front().queue_index.index));
Austin Schuh993ccb52020-12-12 15:59:32 -08002368 return result;
2369 } else {
Austin Schuh58646e22021-08-23 23:51:46 -07002370 // TODO(austin): Binary search.
2371 auto it = std::find_if(
2372 data_queue->begin(), data_queue->end(),
2373 [remote_queue_index,
2374 remote_boot = monotonic_remote_time.boot](const Message &m) {
2375 return m.queue_index == remote_queue_index &&
2376 m.timestamp.boot == remote_boot;
2377 });
Austin Schuh993ccb52020-12-12 15:59:32 -08002378 if (it == data_queue->end()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002379 return Message{.channel_index = message.channel_index,
2380 .queue_index = remote_queue_index,
2381 .timestamp = monotonic_remote_time,
2382 .monotonic_remote_boot = 0xffffff,
2383 .monotonic_timestamp_boot = 0xffffff,
2384 .data = nullptr};
Austin Schuh993ccb52020-12-12 15:59:32 -08002385 }
2386
2387 Message result = std::move(*it);
2388
2389 CHECK_EQ(result.timestamp, monotonic_remote_time)
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002390 << ": Queue index matches, but timestamp doesn't. Please "
2391 "investigate!";
2392 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
2393 << ": Queue index matches, but timestamp doesn't. Please "
2394 "investigate!";
Austin Schuh993ccb52020-12-12 15:59:32 -08002395
Austin Schuhd6b1f4c2021-11-18 20:29:00 -08002396 // Erase everything up to this message. We want to keep 1 message in the
2397 // queue so we can handle reliable messages forwarded across boots.
2398 data_queue->erase(data_queue->begin(), it);
Austin Schuh993ccb52020-12-12 15:59:32 -08002399
2400 return result;
2401 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002402}
2403
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002404void TimestampMapper::QueueUnmatchedUntil(BootTimestamp t) {
Austin Schuhd2f96102020-12-01 20:27:29 -08002405 if (queued_until_ > t) {
2406 return;
2407 }
2408 while (true) {
2409 if (!messages_.empty() && messages_.back().timestamp > t) {
2410 queued_until_ = std::max(queued_until_, messages_.back().timestamp);
2411 return;
2412 }
2413
2414 if (!Queue()) {
2415 // Found nothing to add, we are out of data!
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002416 queued_until_ = BootTimestamp::max_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08002417 return;
2418 }
2419
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002420 // Now that it has been added (and cannibalized), forget about it
2421 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002422 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08002423 }
2424}
2425
2426bool TimestampMapper::Queue() {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002427 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002428 if (m == nullptr) {
2429 return false;
2430 }
2431 for (NodeData &node_data : nodes_data_) {
2432 if (!node_data.any_delivered) continue;
Austin Schuh36c00932021-07-19 18:13:21 -07002433 if (!node_data.save_for_peer) continue;
Austin Schuhd2f96102020-12-01 20:27:29 -08002434 if (node_data.channels[m->channel_index].delivered) {
Austin Schuh6a7358f2021-11-18 22:40:40 -08002435 // If we have data but no timestamps (logs where the timestamps didn't get
2436 // logged are classic), we can grow this indefinitely. We don't need to
2437 // keep anything that is older than the last message returned.
2438
2439 // We have the time on the source node.
2440 // We care to wait until we have the time on the destination node.
2441 std::deque<Message> &messages =
2442 node_data.channels[m->channel_index].messages;
2443 // Max delay over the network is the TTL, so let's take the queue time and
2444 // add TTL to it. Don't forget any messages which are reliable until
2445 // someone can come up with a good reason to forget those too.
2446 if (node_data.channels[m->channel_index].time_to_live >
2447 chrono::nanoseconds(0)) {
2448 // We need to make *some* assumptions about network delay for this to
2449 // work. We want to only look at the RX side. This means we need to
2450 // track the last time a message was popped from any channel from the
2451 // node sending this message, and compare that to the max time we expect
2452 // that a message will take to be delivered across the network. This
2453 // assumes that messages are popped in time order as a proxy for
2454 // measuring the distributed time at this layer.
2455 //
2456 // Leave at least 1 message in here so we can handle reboots and
2457 // messages getting sent twice.
2458 while (messages.size() > 1u &&
2459 messages.begin()->timestamp +
2460 node_data.channels[m->channel_index].time_to_live +
2461 chrono::duration_cast<chrono::nanoseconds>(
2462 chrono::duration<double>(FLAGS_max_network_delay)) <
2463 last_popped_message_time_) {
2464 messages.pop_front();
2465 }
2466 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002467 node_data.channels[m->channel_index].messages.emplace_back(*m);
2468 }
2469 }
2470
2471 messages_.emplace_back(std::move(*m));
2472 return true;
2473}
2474
2475std::string TimestampMapper::DebugString() const {
2476 std::stringstream ss;
Austin Schuh6e014b82021-09-14 17:46:33 -07002477 ss << "node " << node() << " (" << node_name() << ") [\n";
Austin Schuhd2f96102020-12-01 20:27:29 -08002478 for (const Message &message : messages_) {
2479 ss << " " << message << "\n";
2480 }
2481 ss << "] queued_until " << queued_until_;
2482 for (const NodeData &ns : nodes_data_) {
2483 if (ns.peer == nullptr) continue;
2484 ss << "\nnode " << ns.peer->node() << " remote_data [\n";
2485 size_t channel_index = 0;
2486 for (const NodeData::ChannelData &channel_data :
2487 ns.peer->nodes_data_[node()].channels) {
2488 if (channel_data.messages.empty()) {
2489 continue;
2490 }
Austin Schuhb000de62020-12-03 22:00:40 -08002491
Austin Schuhd2f96102020-12-01 20:27:29 -08002492 ss << " channel " << channel_index << " [\n";
2493 for (const Message &m : channel_data.messages) {
2494 ss << " " << m << "\n";
2495 }
2496 ss << " ]\n";
2497 ++channel_index;
2498 }
2499 ss << "] queued_until " << ns.peer->queued_until_;
2500 }
2501 return ss.str();
2502}
2503
Brian Silvermanf51499a2020-09-21 12:49:08 -07002504} // namespace aos::logger