blob: 03380571e4cc76e1f4582e17f753ae610c9309b6 [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"
Austin Schuh05b70472020-01-01 17:11:17 -080013#include "aos/configuration.h"
James Kuszmauldd0a5042021-10-28 23:38:04 -070014#include "aos/events/logging/snappy_encoder.h"
Austin Schuhfa895892020-01-07 20:07:41 -080015#include "aos/flatbuffer_merge.h"
Austin Schuh6f3babe2020-01-26 20:34:50 -080016#include "aos/util/file.h"
Austin Schuha36c8902019-12-30 18:07:15 -080017#include "flatbuffers/flatbuffers.h"
Austin Schuh05b70472020-01-01 17:11:17 -080018#include "gflags/gflags.h"
19#include "glog/logging.h"
Austin Schuha36c8902019-12-30 18:07:15 -080020
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070021#if defined(__x86_64__)
Tyler Chatow2015bc62021-08-04 21:15:09 -070022#define ENABLE_LZMA (!__has_feature(memory_sanitizer))
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070023#elif defined(__aarch64__)
Tyler Chatow2015bc62021-08-04 21:15:09 -070024#define ENABLE_LZMA (!__has_feature(memory_sanitizer))
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070025#else
26#define ENABLE_LZMA 0
27#endif
28
29#if ENABLE_LZMA
30#include "aos/events/logging/lzma_encoder.h"
31#endif
Austin Schuh86110712022-09-16 15:40:54 -070032#if ENABLE_S3
33#include "aos/events/logging/s3_fetcher.h"
34#endif
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070035
Austin Schuh48d10d62022-10-16 22:19:23 -070036DEFINE_int32(flush_size, 128 * 1024,
Austin Schuha36c8902019-12-30 18:07:15 -080037 "Number of outstanding bytes to allow before flushing to disk.");
Austin Schuhbd06ae42021-03-31 22:48:21 -070038DEFINE_double(
39 flush_period, 5.0,
40 "Max time to let data sit in the queue before flushing in seconds.");
Austin Schuha36c8902019-12-30 18:07:15 -080041
Austin Schuha040c3f2021-02-13 16:09:07 -080042DEFINE_double(
Austin Schuh6a7358f2021-11-18 22:40:40 -080043 max_network_delay, 1.0,
44 "Max time to assume a message takes to cross the network before we are "
45 "willing to drop it from our buffers and assume it didn't make it. "
46 "Increasing this number can increase memory usage depending on the packet "
47 "loss of your network or if the timestamps aren't logged for a message.");
48
49DEFINE_double(
Austin Schuha040c3f2021-02-13 16:09:07 -080050 max_out_of_order, -1,
51 "If set, this overrides the max out of order duration for a log file.");
52
Austin Schuh0e8db662021-07-06 10:43:47 -070053DEFINE_bool(workaround_double_headers, true,
54 "Some old log files have two headers at the beginning. Use the "
55 "last header as the actual header.");
56
Brian Smarttea913d42021-12-10 15:02:38 -080057DEFINE_bool(crash_on_corrupt_message, true,
58 "When true, MessageReader will crash the first time a message "
59 "with corrupted format is found. When false, the crash will be "
60 "suppressed, and any remaining readable messages will be "
61 "evaluated to present verified vs corrupted stats.");
62
63DEFINE_bool(ignore_corrupt_messages, false,
64 "When true, and crash_on_corrupt_message is false, then any "
65 "corrupt message found by MessageReader be silently ignored, "
66 "providing access to all uncorrupted messages in a logfile.");
67
Brian Silvermanf51499a2020-09-21 12:49:08 -070068namespace aos::logger {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070069namespace {
Austin Schuha36c8902019-12-30 18:07:15 -080070
Austin Schuh05b70472020-01-01 17:11:17 -080071namespace chrono = std::chrono;
72
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070073template <typename T>
74void PrintOptionalOrNull(std::ostream *os, const std::optional<T> &t) {
75 if (t.has_value()) {
76 *os << *t;
77 } else {
78 *os << "null";
79 }
80}
81} // namespace
82
Alexei Strots01395492023-03-20 13:59:56 -070083DetachedBufferWriter::DetachedBufferWriter(
84 std::unique_ptr<FileHandler> file_handler,
85 std::unique_ptr<DataEncoder> encoder)
86 : file_handler_(std::move(file_handler)), encoder_(std::move(encoder)) {
87 CHECK(file_handler_);
88 ran_out_of_space_ = file_handler_->OpenForWrite() == WriteCode::kOutOfSpace;
89 if (ran_out_of_space_) {
90 LOG(WARNING) << "And we are out of space";
Austin Schuh4c3cdb72023-02-11 15:05:26 -080091 }
92}
93
Austin Schuha36c8902019-12-30 18:07:15 -080094DetachedBufferWriter::~DetachedBufferWriter() {
Brian Silverman0465fcf2020-09-24 00:29:18 -070095 Close();
96 if (ran_out_of_space_) {
97 CHECK(acknowledge_ran_out_of_space_)
98 << ": Unacknowledged out of disk space, log file was not completed";
Brian Silvermanf51499a2020-09-21 12:49:08 -070099 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700100}
101
Brian Silvermand90905f2020-09-23 14:42:56 -0700102DetachedBufferWriter::DetachedBufferWriter(DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700103 *this = std::move(other);
104}
105
Brian Silverman87ac0402020-09-17 14:47:01 -0700106// When other is destroyed "soon" (which it should be because we're getting an
107// rvalue reference to it), it will flush etc all the data we have queued up
108// (because that data will then be its data).
Austin Schuh2f8fd752020-09-01 22:38:28 -0700109DetachedBufferWriter &DetachedBufferWriter::operator=(
110 DetachedBufferWriter &&other) {
Alexei Strots01395492023-03-20 13:59:56 -0700111 std::swap(file_handler_, other.file_handler_);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700112 std::swap(encoder_, other.encoder_);
Brian Silverman0465fcf2020-09-24 00:29:18 -0700113 std::swap(ran_out_of_space_, other.ran_out_of_space_);
114 std::swap(acknowledge_ran_out_of_space_, other.acknowledge_ran_out_of_space_);
Austin Schuh4c3cdb72023-02-11 15:05:26 -0800115 std::swap(last_flush_time_, other.last_flush_time_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700116 return *this;
Austin Schuha36c8902019-12-30 18:07:15 -0800117}
118
Austin Schuh8bdfc492023-02-11 12:53:13 -0800119void DetachedBufferWriter::CopyMessage(DataEncoder::Copier *copier,
Austin Schuh7ef11a42023-02-04 17:15:12 -0800120 aos::monotonic_clock::time_point now) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -0700121 if (ran_out_of_space_) {
122 // We don't want any later data to be written after space becomes
123 // available, so refuse to write anything more once we've dropped data
124 // because we ran out of space.
Austin Schuh48d10d62022-10-16 22:19:23 -0700125 return;
Austin Schuha36c8902019-12-30 18:07:15 -0800126 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700127
Austin Schuh8bdfc492023-02-11 12:53:13 -0800128 const size_t message_size = copier->size();
129 size_t overall_bytes_written = 0;
Austin Schuh48d10d62022-10-16 22:19:23 -0700130
Austin Schuh8bdfc492023-02-11 12:53:13 -0800131 // Keep writing chunks until we've written it all. If we end up with a
132 // partial write, this means we need to flush to disk.
133 do {
Alexei Strots01395492023-03-20 13:59:56 -0700134 const size_t bytes_written =
135 encoder_->Encode(copier, overall_bytes_written);
Austin Schuh8bdfc492023-02-11 12:53:13 -0800136 CHECK(bytes_written != 0);
137
138 overall_bytes_written += bytes_written;
139 if (overall_bytes_written < message_size) {
140 VLOG(1) << "Flushing because of a partial write, tried to write "
141 << message_size << " wrote " << overall_bytes_written;
142 Flush(now);
143 }
144 } while (overall_bytes_written < message_size);
145
Austin Schuhbd06ae42021-03-31 22:48:21 -0700146 FlushAtThreshold(now);
Austin Schuha36c8902019-12-30 18:07:15 -0800147}
148
Brian Silverman0465fcf2020-09-24 00:29:18 -0700149void DetachedBufferWriter::Close() {
Alexei Strots01395492023-03-20 13:59:56 -0700150 if (!file_handler_->is_open()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700151 return;
152 }
153 encoder_->Finish();
154 while (encoder_->queue_size() > 0) {
Austin Schuh8bdfc492023-02-11 12:53:13 -0800155 Flush(monotonic_clock::max_time);
Brian Silverman0465fcf2020-09-24 00:29:18 -0700156 }
Alexei Strots01395492023-03-20 13:59:56 -0700157 ran_out_of_space_ = file_handler_->Close() == WriteCode::kOutOfSpace;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700158}
159
Austin Schuh8bdfc492023-02-11 12:53:13 -0800160void DetachedBufferWriter::Flush(aos::monotonic_clock::time_point now) {
161 last_flush_time_ = now;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700162 if (ran_out_of_space_) {
163 // We don't want any later data to be written after space becomes available,
164 // so refuse to write anything more once we've dropped data because we ran
165 // out of space.
Austin Schuha426f1f2021-03-31 22:27:41 -0700166 if (encoder_) {
167 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
168 encoder_->Clear(encoder_->queue().size());
169 } else {
170 VLOG(1) << "No queue to ignore";
171 }
172 return;
173 }
174
175 const auto queue = encoder_->queue();
176 if (queue.empty()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700177 return;
178 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700179
Alexei Strots01395492023-03-20 13:59:56 -0700180 const WriteResult result = file_handler_->Write(queue);
181 encoder_->Clear(result.messages_written);
182 ran_out_of_space_ = result.code == WriteCode::kOutOfSpace;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700183}
184
Austin Schuhbd06ae42021-03-31 22:48:21 -0700185void DetachedBufferWriter::FlushAtThreshold(
186 aos::monotonic_clock::time_point now) {
Austin Schuha426f1f2021-03-31 22:27:41 -0700187 if (ran_out_of_space_) {
188 // We don't want any later data to be written after space becomes available,
189 // so refuse to write anything more once we've dropped data because we ran
190 // out of space.
191 if (encoder_) {
192 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
193 encoder_->Clear(encoder_->queue().size());
194 } else {
195 VLOG(1) << "No queue to ignore";
196 }
197 return;
198 }
199
Austin Schuhbd06ae42021-03-31 22:48:21 -0700200 // We don't want to flush the first time through. Otherwise we will flush as
201 // the log file header might be compressing, defeating any parallelism and
202 // queueing there.
203 if (last_flush_time_ == aos::monotonic_clock::min_time) {
204 last_flush_time_ = now;
205 }
206
Brian Silvermanf51499a2020-09-21 12:49:08 -0700207 // Flush if we are at the max number of iovs per writev, because there's no
208 // point queueing up any more data in memory. Also flush once we have enough
Austin Schuhbd06ae42021-03-31 22:48:21 -0700209 // data queued up or if it has been long enough.
Austin Schuh8bdfc492023-02-11 12:53:13 -0800210 while (encoder_->space() == 0 ||
211 encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
Austin Schuhbd06ae42021-03-31 22:48:21 -0700212 encoder_->queue_size() >= IOV_MAX ||
213 now > last_flush_time_ +
214 chrono::duration_cast<chrono::nanoseconds>(
215 chrono::duration<double>(FLAGS_flush_period))) {
Austin Schuh8bdfc492023-02-11 12:53:13 -0800216 VLOG(1) << "Chose to flush at " << now << ", last " << last_flush_time_;
217 Flush(now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700218 }
Austin Schuha36c8902019-12-30 18:07:15 -0800219}
220
Austin Schuhf2d0e682022-10-16 14:20:58 -0700221// Do the magic dance to convert the endianness of the data and append it to the
222// buffer.
223namespace {
224
225// TODO(austin): Look at the generated code to see if building the header is
226// efficient or not.
227template <typename T>
228uint8_t *Push(uint8_t *buffer, const T data) {
229 const T endian_data = flatbuffers::EndianScalar<T>(data);
230 std::memcpy(buffer, &endian_data, sizeof(T));
231 return buffer + sizeof(T);
232}
233
234uint8_t *PushBytes(uint8_t *buffer, const void *data, size_t size) {
235 std::memcpy(buffer, data, size);
236 return buffer + size;
237}
238
239uint8_t *Pad(uint8_t *buffer, size_t padding) {
240 std::memset(buffer, 0, padding);
241 return buffer + padding;
242}
243} // namespace
244
245flatbuffers::Offset<MessageHeader> PackRemoteMessage(
246 flatbuffers::FlatBufferBuilder *fbb,
247 const message_bridge::RemoteMessage *msg, int channel_index,
248 const aos::monotonic_clock::time_point monotonic_timestamp_time) {
249 logger::MessageHeader::Builder message_header_builder(*fbb);
250 // Note: this must match the same order as MessageBridgeServer and
251 // PackMessage. We want identical headers to have identical
252 // on-the-wire formats to make comparing them easier.
253
254 message_header_builder.add_channel_index(channel_index);
255
256 message_header_builder.add_queue_index(msg->queue_index());
257 message_header_builder.add_monotonic_sent_time(msg->monotonic_sent_time());
258 message_header_builder.add_realtime_sent_time(msg->realtime_sent_time());
259
260 message_header_builder.add_monotonic_remote_time(
261 msg->monotonic_remote_time());
262 message_header_builder.add_realtime_remote_time(msg->realtime_remote_time());
263 message_header_builder.add_remote_queue_index(msg->remote_queue_index());
264
265 message_header_builder.add_monotonic_timestamp_time(
266 monotonic_timestamp_time.time_since_epoch().count());
267
268 return message_header_builder.Finish();
269}
270
271size_t PackRemoteMessageInline(
272 uint8_t *buffer, const message_bridge::RemoteMessage *msg,
273 int channel_index,
Austin Schuh71a40d42023-02-04 21:22:22 -0800274 const aos::monotonic_clock::time_point monotonic_timestamp_time,
275 size_t start_byte, size_t end_byte) {
Austin Schuhf2d0e682022-10-16 14:20:58 -0700276 const flatbuffers::uoffset_t message_size = PackRemoteMessageSize();
Austin Schuh71a40d42023-02-04 21:22:22 -0800277 DCHECK_EQ((start_byte % 8u), 0u);
278 DCHECK_EQ((end_byte % 8u), 0u);
279 DCHECK_LE(start_byte, end_byte);
280 DCHECK_LE(end_byte, message_size);
Austin Schuhf2d0e682022-10-16 14:20:58 -0700281
Austin Schuh71a40d42023-02-04 21:22:22 -0800282 switch (start_byte) {
283 case 0x00u:
284 if ((end_byte) == 0x00u) {
285 break;
286 }
287 // clang-format off
288 // header:
289 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
290 buffer = Push<flatbuffers::uoffset_t>(
291 buffer, message_size - sizeof(flatbuffers::uoffset_t));
292 // +0x04 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: +0x24 | offset to root table `aos.logger.MessageHeader`
293 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x20);
294 [[fallthrough]];
295 case 0x08u:
296 if ((end_byte) == 0x08u) {
297 break;
298 }
299 //
300 // padding:
301 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
302 buffer = Pad(buffer, 6);
303 //
304 // vtable (aos.logger.MessageHeader):
305 // +0x0E | 16 00 | uint16_t | 0x0016 (22) | size of this vtable
306 buffer = Push<flatbuffers::voffset_t>(buffer, 0x16);
307 [[fallthrough]];
308 case 0x10u:
309 if ((end_byte) == 0x10u) {
310 break;
311 }
312 // +0x10 | 3C 00 | uint16_t | 0x003C (60) | size of referring table
313 buffer = Push<flatbuffers::voffset_t>(buffer, 0x3c);
314 // +0x12 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `channel_index` (id: 0)
315 buffer = Push<flatbuffers::voffset_t>(buffer, 0x38);
316 // +0x14 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `monotonic_sent_time` (id: 1)
317 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
318 // +0x16 | 24 00 | VOffset16 | 0x0024 (36) | offset to field `realtime_sent_time` (id: 2)
319 buffer = Push<flatbuffers::voffset_t>(buffer, 0x24);
320 [[fallthrough]];
321 case 0x18u:
322 if ((end_byte) == 0x18u) {
323 break;
324 }
325 // +0x18 | 34 00 | VOffset16 | 0x0034 (52) | offset to field `queue_index` (id: 3)
326 buffer = Push<flatbuffers::voffset_t>(buffer, 0x34);
327 // +0x1A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `data` (id: 4) <null> (Vector)
328 buffer = Push<flatbuffers::voffset_t>(buffer, 0x00);
329 // +0x1C | 1C 00 | VOffset16 | 0x001C (28) | offset to field `monotonic_remote_time` (id: 5)
330 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
331 // +0x1E | 14 00 | VOffset16 | 0x0014 (20) | offset to field `realtime_remote_time` (id: 6)
332 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
333 [[fallthrough]];
334 case 0x20u:
335 if ((end_byte) == 0x20u) {
336 break;
337 }
338 // +0x20 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `remote_queue_index` (id: 7)
339 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
340 // +0x22 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `monotonic_timestamp_time` (id: 8)
341 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
342 //
343 // root_table (aos.logger.MessageHeader):
344 // +0x24 | 16 00 00 00 | SOffset32 | 0x00000016 (22) Loc: +0x0E | offset to vtable
345 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x16);
346 [[fallthrough]];
347 case 0x28u:
348 if ((end_byte) == 0x28u) {
349 break;
350 }
351 // +0x28 | F6 0B D8 11 A4 A8 B1 71 | int64_t | 0x71B1A8A411D80BF6 (8192514619791117302) | table field `monotonic_timestamp_time` (Long)
352 buffer = Push<int64_t>(buffer,
353 monotonic_timestamp_time.time_since_epoch().count());
354 [[fallthrough]];
355 case 0x30u:
356 if ((end_byte) == 0x30u) {
357 break;
358 }
359 // +0x30 | 00 00 00 00 | uint8_t[4] | .... | padding
360 // TODO(austin): Can we re-arrange the order to ditch the padding?
361 // (Answer is yes, but what is the impact elsewhere? It will change the
362 // binary format)
363 buffer = Pad(buffer, 4);
364 // +0x34 | 75 00 00 00 | uint32_t | 0x00000075 (117) | table field `remote_queue_index` (UInt)
365 buffer = Push<uint32_t>(buffer, msg->remote_queue_index());
366 [[fallthrough]];
367 case 0x38u:
368 if ((end_byte) == 0x38u) {
369 break;
370 }
371 // +0x38 | AA B0 43 0A 35 BE FA D2 | int64_t | 0xD2FABE350A43B0AA (-3244071446552268630) | table field `realtime_remote_time` (Long)
372 buffer = Push<int64_t>(buffer, msg->realtime_remote_time());
373 [[fallthrough]];
374 case 0x40u:
375 if ((end_byte) == 0x40u) {
376 break;
377 }
378 // +0x40 | D5 40 30 F3 C1 A7 26 1D | int64_t | 0x1D26A7C1F33040D5 (2100550727665467605) | table field `monotonic_remote_time` (Long)
379 buffer = Push<int64_t>(buffer, msg->monotonic_remote_time());
380 [[fallthrough]];
381 case 0x48u:
382 if ((end_byte) == 0x48u) {
383 break;
384 }
385 // +0x48 | 5B 25 32 A1 4A E8 46 CA | int64_t | 0xCA46E84AA132255B (-3871151422448720549) | table field `realtime_sent_time` (Long)
386 buffer = Push<int64_t>(buffer, msg->realtime_sent_time());
387 [[fallthrough]];
388 case 0x50u:
389 if ((end_byte) == 0x50u) {
390 break;
391 }
392 // +0x50 | 49 7D 45 1F 8C 36 6B A3 | int64_t | 0xA36B368C1F457D49 (-6671178447571288759) | table field `monotonic_sent_time` (Long)
393 buffer = Push<int64_t>(buffer, msg->monotonic_sent_time());
394 [[fallthrough]];
395 case 0x58u:
396 if ((end_byte) == 0x58u) {
397 break;
398 }
399 // +0x58 | 33 00 00 00 | uint32_t | 0x00000033 (51) | table field `queue_index` (UInt)
400 buffer = Push<uint32_t>(buffer, msg->queue_index());
401 // +0x5C | 76 00 00 00 | uint32_t | 0x00000076 (118) | table field `channel_index` (UInt)
402 buffer = Push<uint32_t>(buffer, channel_index);
403 // clang-format on
404 [[fallthrough]];
405 case 0x60u:
406 if ((end_byte) == 0x60u) {
407 break;
408 }
409 }
Austin Schuhf2d0e682022-10-16 14:20:58 -0700410
Austin Schuh71a40d42023-02-04 21:22:22 -0800411 return end_byte - start_byte;
Austin Schuhf2d0e682022-10-16 14:20:58 -0700412}
413
Austin Schuha36c8902019-12-30 18:07:15 -0800414flatbuffers::Offset<MessageHeader> PackMessage(
415 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
416 int channel_index, LogType log_type) {
417 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
418
419 switch (log_type) {
420 case LogType::kLogMessage:
421 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800422 case LogType::kLogRemoteMessage:
Austin Schuhfa30c352022-10-16 11:12:02 -0700423 // Since the timestamps are 8 byte aligned, we are going to end up adding
424 // padding in the middle of the message to pad everything out to 8 byte
425 // alignment. That's rather wasteful. To make things efficient to mmap
426 // while reading uncompressed logs, we'd actually rather the message be
427 // aligned. So, force 8 byte alignment (enough to preserve alignment
428 // inside the nested message so that we can read it without moving it)
429 // here.
430 fbb->ForceVectorAlignment(context.size, sizeof(uint8_t), 8);
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700431 data_offset = fbb->CreateVector(
432 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800433 break;
434
435 case LogType::kLogDeliveryTimeOnly:
436 break;
437 }
438
439 MessageHeader::Builder message_header_builder(*fbb);
440 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800441
Austin Schuhfa30c352022-10-16 11:12:02 -0700442 // These are split out into very explicit serialization calls because the
443 // order here changes the order things are written out on the wire, and we
444 // want to control and understand it here. Changing the order can increase
445 // the amount of padding bytes in the middle.
446 //
James Kuszmaul9776b392023-01-14 14:08:08 -0800447 // It is also easier to follow... And doesn't actually make things much
448 // bigger.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800449 switch (log_type) {
450 case LogType::kLogRemoteMessage:
451 message_header_builder.add_queue_index(context.remote_queue_index);
Austin Schuhfa30c352022-10-16 11:12:02 -0700452 message_header_builder.add_data(data_offset);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800453 message_header_builder.add_monotonic_sent_time(
454 context.monotonic_remote_time.time_since_epoch().count());
455 message_header_builder.add_realtime_sent_time(
456 context.realtime_remote_time.time_since_epoch().count());
457 break;
458
Austin Schuh6f3babe2020-01-26 20:34:50 -0800459 case LogType::kLogDeliveryTimeOnly:
460 message_header_builder.add_queue_index(context.queue_index);
461 message_header_builder.add_monotonic_sent_time(
462 context.monotonic_event_time.time_since_epoch().count());
463 message_header_builder.add_realtime_sent_time(
464 context.realtime_event_time.time_since_epoch().count());
Austin Schuha36c8902019-12-30 18:07:15 -0800465 message_header_builder.add_monotonic_remote_time(
466 context.monotonic_remote_time.time_since_epoch().count());
467 message_header_builder.add_realtime_remote_time(
468 context.realtime_remote_time.time_since_epoch().count());
469 message_header_builder.add_remote_queue_index(context.remote_queue_index);
470 break;
Austin Schuhfa30c352022-10-16 11:12:02 -0700471
472 case LogType::kLogMessage:
473 message_header_builder.add_queue_index(context.queue_index);
474 message_header_builder.add_data(data_offset);
475 message_header_builder.add_monotonic_sent_time(
476 context.monotonic_event_time.time_since_epoch().count());
477 message_header_builder.add_realtime_sent_time(
478 context.realtime_event_time.time_since_epoch().count());
479 break;
480
481 case LogType::kLogMessageAndDeliveryTime:
482 message_header_builder.add_queue_index(context.queue_index);
483 message_header_builder.add_remote_queue_index(context.remote_queue_index);
484 message_header_builder.add_monotonic_sent_time(
485 context.monotonic_event_time.time_since_epoch().count());
486 message_header_builder.add_realtime_sent_time(
487 context.realtime_event_time.time_since_epoch().count());
488 message_header_builder.add_monotonic_remote_time(
489 context.monotonic_remote_time.time_since_epoch().count());
490 message_header_builder.add_realtime_remote_time(
491 context.realtime_remote_time.time_since_epoch().count());
492 message_header_builder.add_data(data_offset);
493 break;
Austin Schuha36c8902019-12-30 18:07:15 -0800494 }
495
496 return message_header_builder.Finish();
497}
498
Austin Schuhfa30c352022-10-16 11:12:02 -0700499flatbuffers::uoffset_t PackMessageHeaderSize(LogType log_type) {
500 switch (log_type) {
501 case LogType::kLogMessage:
502 return
503 // Root table size + offset.
504 sizeof(flatbuffers::uoffset_t) * 2 +
505 // 6 padding bytes to pad the header out properly.
506 6 +
507 // vtable header (size + size of table)
508 sizeof(flatbuffers::voffset_t) * 2 +
509 // offsets to all the fields.
510 sizeof(flatbuffers::voffset_t) * 5 +
511 // pointer to vtable
512 sizeof(flatbuffers::soffset_t) +
513 // pointer to data
514 sizeof(flatbuffers::uoffset_t) +
515 // realtime_sent_time, monotonic_sent_time
516 sizeof(int64_t) * 2 +
517 // queue_index, channel_index
518 sizeof(uint32_t) * 2;
519
520 case LogType::kLogDeliveryTimeOnly:
521 return
522 // Root table size + offset.
523 sizeof(flatbuffers::uoffset_t) * 2 +
524 // 6 padding bytes to pad the header out properly.
525 4 +
526 // vtable header (size + size of table)
527 sizeof(flatbuffers::voffset_t) * 2 +
528 // offsets to all the fields.
529 sizeof(flatbuffers::voffset_t) * 8 +
530 // pointer to vtable
531 sizeof(flatbuffers::soffset_t) +
532 // remote_queue_index
533 sizeof(uint32_t) +
534 // realtime_remote_time, monotonic_remote_time, realtime_sent_time,
535 // monotonic_sent_time
536 sizeof(int64_t) * 4 +
537 // queue_index, channel_index
538 sizeof(uint32_t) * 2;
539
540 case LogType::kLogMessageAndDeliveryTime:
541 return
542 // Root table size + offset.
543 sizeof(flatbuffers::uoffset_t) * 2 +
544 // 4 padding bytes to pad the header out properly.
545 4 +
546 // vtable header (size + size of table)
547 sizeof(flatbuffers::voffset_t) * 2 +
548 // offsets to all the fields.
549 sizeof(flatbuffers::voffset_t) * 8 +
550 // pointer to vtable
551 sizeof(flatbuffers::soffset_t) +
552 // pointer to data
553 sizeof(flatbuffers::uoffset_t) +
554 // realtime_remote_time, monotonic_remote_time, realtime_sent_time,
555 // monotonic_sent_time
556 sizeof(int64_t) * 4 +
557 // remote_queue_index, queue_index, channel_index
558 sizeof(uint32_t) * 3;
559
560 case LogType::kLogRemoteMessage:
561 return
562 // Root table size + offset.
563 sizeof(flatbuffers::uoffset_t) * 2 +
564 // 6 padding bytes to pad the header out properly.
565 6 +
566 // vtable header (size + size of table)
567 sizeof(flatbuffers::voffset_t) * 2 +
568 // offsets to all the fields.
569 sizeof(flatbuffers::voffset_t) * 5 +
570 // pointer to vtable
571 sizeof(flatbuffers::soffset_t) +
572 // realtime_sent_time, monotonic_sent_time
573 sizeof(int64_t) * 2 +
574 // pointer to data
575 sizeof(flatbuffers::uoffset_t) +
576 // queue_index, channel_index
577 sizeof(uint32_t) * 2;
578 }
579 LOG(FATAL);
580}
581
James Kuszmaul9776b392023-01-14 14:08:08 -0800582flatbuffers::uoffset_t PackMessageSize(LogType log_type, size_t data_size) {
Austin Schuhfa30c352022-10-16 11:12:02 -0700583 static_assert(sizeof(flatbuffers::uoffset_t) == 4u,
584 "Update size logic please.");
585 const flatbuffers::uoffset_t aligned_data_length =
Austin Schuh48d10d62022-10-16 22:19:23 -0700586 ((data_size + 7) & 0xfffffff8u);
Austin Schuhfa30c352022-10-16 11:12:02 -0700587 switch (log_type) {
588 case LogType::kLogDeliveryTimeOnly:
589 return PackMessageHeaderSize(log_type);
590
591 case LogType::kLogMessage:
592 case LogType::kLogMessageAndDeliveryTime:
593 case LogType::kLogRemoteMessage:
594 return PackMessageHeaderSize(log_type) +
595 // Vector...
596 sizeof(flatbuffers::uoffset_t) + aligned_data_length;
597 }
598 LOG(FATAL);
599}
600
Austin Schuhfa30c352022-10-16 11:12:02 -0700601size_t PackMessageInline(uint8_t *buffer, const Context &context,
Austin Schuh71a40d42023-02-04 21:22:22 -0800602 int channel_index, LogType log_type, size_t start_byte,
603 size_t end_byte) {
Austin Schuh48d10d62022-10-16 22:19:23 -0700604 // TODO(austin): Figure out how to copy directly from shared memory instead of
605 // first into the fetcher's memory and then into here. That would save a lot
606 // of memory.
Austin Schuhfa30c352022-10-16 11:12:02 -0700607 const flatbuffers::uoffset_t message_size =
Austin Schuh48d10d62022-10-16 22:19:23 -0700608 PackMessageSize(log_type, context.size);
Austin Schuh71a40d42023-02-04 21:22:22 -0800609 DCHECK_EQ((message_size % 8), 0u) << ": Non 8 byte length...";
610 DCHECK_EQ((start_byte % 8u), 0u);
611 DCHECK_EQ((end_byte % 8u), 0u);
612 DCHECK_LE(start_byte, end_byte);
613 DCHECK_LE(end_byte, message_size);
Austin Schuhfa30c352022-10-16 11:12:02 -0700614
615 // Pack all the data in. This is brittle but easy to change. Use the
616 // InlinePackMessage.Equivilent unit test to verify everything matches.
617 switch (log_type) {
618 case LogType::kLogMessage:
Austin Schuh71a40d42023-02-04 21:22:22 -0800619 switch (start_byte) {
620 case 0x00u:
621 if ((end_byte) == 0x00u) {
622 break;
623 }
624 // clang-format off
625 // header:
626 // +0x00 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: +0x4C | size prefix
627 buffer = Push<flatbuffers::uoffset_t>(
628 buffer, message_size - sizeof(flatbuffers::uoffset_t));
629
630 // +0x04 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: +0x1C | offset to root table `aos.logger.MessageHeader`
631 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x18);
632 [[fallthrough]];
633 case 0x08u:
634 if ((end_byte) == 0x08u) {
635 break;
636 }
637 //
638 // padding:
639 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
640 buffer = Pad(buffer, 6);
641 //
642 // vtable (aos.logger.MessageHeader):
643 // +0x0E | 0E 00 | uint16_t | 0x000E (14) | size of this vtable
644 buffer = Push<flatbuffers::voffset_t>(buffer, 0xe);
645 [[fallthrough]];
646 case 0x10u:
647 if ((end_byte) == 0x10u) {
648 break;
649 }
650 // +0x10 | 20 00 | uint16_t | 0x0020 (32) | size of referring table
651 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
652 // +0x12 | 1C 00 | VOffset16 | 0x001C (28) | offset to field `channel_index` (id: 0)
653 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
654 // +0x14 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `monotonic_sent_time` (id: 1)
655 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0c);
656 // +0x16 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `realtime_sent_time` (id: 2)
657 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
658 [[fallthrough]];
659 case 0x18u:
660 if ((end_byte) == 0x18u) {
661 break;
662 }
663 // +0x18 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `queue_index` (id: 3)
664 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
665 // +0x1A | 14 00 | VOffset16 | 0x0014 (20) | offset to field `data` (id: 4)
666 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
667 //
668 // root_table (aos.logger.MessageHeader):
669 // +0x1C | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: +0x0E | offset to vtable
670 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0e);
671 [[fallthrough]];
672 case 0x20u:
673 if ((end_byte) == 0x20u) {
674 break;
675 }
676 // +0x20 | B2 E4 EF 89 19 7D 7F 6F | int64_t | 0x6F7F7D1989EFE4B2 (8034277808894108850) | table field `realtime_sent_time` (Long)
677 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
678 [[fallthrough]];
679 case 0x28u:
680 if ((end_byte) == 0x28u) {
681 break;
682 }
683 // +0x28 | 86 8D 92 65 FC 79 74 2B | int64_t | 0x2B7479FC65928D86 (3131261765872160134) | table field `monotonic_sent_time` (Long)
684 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
685 [[fallthrough]];
686 case 0x30u:
687 if ((end_byte) == 0x30u) {
688 break;
689 }
690 // +0x30 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: +0x3C | offset to field `data` (vector)
691 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0c);
692 // +0x34 | 86 00 00 00 | uint32_t | 0x00000086 (134) | table field `queue_index` (UInt)
693 buffer = Push<uint32_t>(buffer, context.queue_index);
694 [[fallthrough]];
695 case 0x38u:
696 if ((end_byte) == 0x38u) {
697 break;
698 }
699 // +0x38 | 71 00 00 00 | uint32_t | 0x00000071 (113) | table field `channel_index` (UInt)
700 buffer = Push<uint32_t>(buffer, channel_index);
701 //
702 // vector (aos.logger.MessageHeader.data):
703 // +0x3C | 0E 00 00 00 | uint32_t | 0x0000000E (14) | length of vector (# items)
704 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
705 [[fallthrough]];
706 case 0x40u:
707 if ((end_byte) == 0x40u) {
708 break;
709 }
710 [[fallthrough]];
711 default:
712 // +0x40 | FF | uint8_t | 0xFF (255) | value[0]
713 // +0x41 | B8 | uint8_t | 0xB8 (184) | value[1]
714 // +0x42 | EE | uint8_t | 0xEE (238) | value[2]
715 // +0x43 | 00 | uint8_t | 0x00 (0) | value[3]
716 // +0x44 | 20 | uint8_t | 0x20 (32) | value[4]
717 // +0x45 | 4D | uint8_t | 0x4D (77) | value[5]
718 // +0x46 | FF | uint8_t | 0xFF (255) | value[6]
719 // +0x47 | 25 | uint8_t | 0x25 (37) | value[7]
720 // +0x48 | 3C | uint8_t | 0x3C (60) | value[8]
721 // +0x49 | 17 | uint8_t | 0x17 (23) | value[9]
722 // +0x4A | 65 | uint8_t | 0x65 (101) | value[10]
723 // +0x4B | 2F | uint8_t | 0x2F (47) | value[11]
724 // +0x4C | 63 | uint8_t | 0x63 (99) | value[12]
725 // +0x4D | 58 | uint8_t | 0x58 (88) | value[13]
726 //
727 // padding:
728 // +0x4E | 00 00 | uint8_t[2] | .. | padding
729 // clang-format on
730 if (start_byte <= 0x40 && end_byte == message_size) {
731 // The easy one, slap it all down.
732 buffer = PushBytes(buffer, context.data, context.size);
733 buffer =
734 Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
735 } else {
736 const size_t data_start_byte =
737 start_byte < 0x40 ? 0x0u : (start_byte - 0x40);
738 const size_t data_end_byte = end_byte - 0x40;
739 const size_t padded_size = ((context.size + 7) & 0xfffffff8u);
740 if (data_start_byte < padded_size) {
741 buffer = PushBytes(
742 buffer,
743 reinterpret_cast<const uint8_t *>(context.data) +
744 data_start_byte,
745 std::min(context.size, data_end_byte) - data_start_byte);
746 if (data_end_byte == padded_size) {
747 // We can only pad the last 7 bytes, so this only gets written
748 // if we write the last byte.
749 buffer = Pad(buffer,
750 ((context.size + 7) & 0xfffffff8u) - context.size);
751 }
752 }
753 }
754 break;
755 }
Austin Schuhfa30c352022-10-16 11:12:02 -0700756 break;
757
758 case LogType::kLogDeliveryTimeOnly:
Austin Schuh71a40d42023-02-04 21:22:22 -0800759 switch (start_byte) {
760 case 0x00u:
761 if ((end_byte) == 0x00u) {
762 break;
763 }
764 // clang-format off
765 // header:
766 // +0x00 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: +0x4C | size prefix
767 buffer = Push<flatbuffers::uoffset_t>(
768 buffer, message_size - sizeof(flatbuffers::uoffset_t));
769 // +0x04 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: +0x20 | offset to root table `aos.logger.MessageHeader`
770 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x1c);
Austin Schuhfa30c352022-10-16 11:12:02 -0700771
Austin Schuh71a40d42023-02-04 21:22:22 -0800772 [[fallthrough]];
773 case 0x08u:
774 if ((end_byte) == 0x08u) {
775 break;
776 }
777 //
778 // padding:
779 // +0x08 | 00 00 00 00 | uint8_t[4] | .... | padding
780 buffer = Pad(buffer, 4);
781 //
782 // vtable (aos.logger.MessageHeader):
783 // +0x0C | 14 00 | uint16_t | 0x0014 (20) | size of this vtable
784 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
785 // +0x0E | 30 00 | uint16_t | 0x0030 (48) | size of referring table
786 buffer = Push<flatbuffers::voffset_t>(buffer, 0x30);
787 [[fallthrough]];
788 case 0x10u:
789 if ((end_byte) == 0x10u) {
790 break;
791 }
792 // +0x10 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `channel_index` (id: 0)
793 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
794 // +0x12 | 20 00 | VOffset16 | 0x0020 (32) | offset to field `monotonic_sent_time` (id: 1)
795 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
796 // +0x14 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `realtime_sent_time` (id: 2)
797 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
798 // +0x16 | 28 00 | VOffset16 | 0x0028 (40) | offset to field `queue_index` (id: 3)
799 buffer = Push<flatbuffers::voffset_t>(buffer, 0x28);
800 [[fallthrough]];
801 case 0x18u:
802 if ((end_byte) == 0x18u) {
803 break;
804 }
805 // +0x18 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `data` (id: 4) <null> (Vector)
806 buffer = Push<flatbuffers::voffset_t>(buffer, 0x00);
807 // +0x1A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `monotonic_remote_time` (id: 5)
808 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
809 // +0x1C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `realtime_remote_time` (id: 6)
810 buffer = Push<flatbuffers::voffset_t>(buffer, 0x08);
811 // +0x1E | 04 00 | VOffset16 | 0x0004 (4) | offset to field `remote_queue_index` (id: 7)
812 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
813 [[fallthrough]];
814 case 0x20u:
815 if ((end_byte) == 0x20u) {
816 break;
817 }
818 //
819 // root_table (aos.logger.MessageHeader):
820 // +0x20 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: +0x0C | offset to vtable
821 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x14);
822 // +0x24 | 69 00 00 00 | uint32_t | 0x00000069 (105) | table field `remote_queue_index` (UInt)
823 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
824 [[fallthrough]];
825 case 0x28u:
826 if ((end_byte) == 0x28u) {
827 break;
828 }
829 // +0x28 | C6 85 F1 AB 83 B5 CD EB | int64_t | 0xEBCDB583ABF185C6 (-1455307527440726586) | table field `realtime_remote_time` (Long)
830 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
831 [[fallthrough]];
832 case 0x30u:
833 if ((end_byte) == 0x30u) {
834 break;
835 }
836 // +0x30 | 47 24 D3 97 1E 42 2D 99 | int64_t | 0x992D421E97D32447 (-7409193112790948793) | table field `monotonic_remote_time` (Long)
837 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
838 [[fallthrough]];
839 case 0x38u:
840 if ((end_byte) == 0x38u) {
841 break;
842 }
843 // +0x38 | C8 B9 A7 AB 79 F2 CD 60 | int64_t | 0x60CDF279ABA7B9C8 (6975498002251626952) | table field `realtime_sent_time` (Long)
844 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
845 [[fallthrough]];
846 case 0x40u:
847 if ((end_byte) == 0x40u) {
848 break;
849 }
850 // +0x40 | EA 8F 2A 0F AF 01 7A AB | int64_t | 0xAB7A01AF0F2A8FEA (-6090553694679822358) | table field `monotonic_sent_time` (Long)
851 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
852 [[fallthrough]];
853 case 0x48u:
854 if ((end_byte) == 0x48u) {
855 break;
856 }
857 // +0x48 | F5 00 00 00 | uint32_t | 0x000000F5 (245) | table field `queue_index` (UInt)
858 buffer = Push<uint32_t>(buffer, context.queue_index);
859 // +0x4C | 88 00 00 00 | uint32_t | 0x00000088 (136) | table field `channel_index` (UInt)
860 buffer = Push<uint32_t>(buffer, channel_index);
861
862 // clang-format on
863 }
Austin Schuhfa30c352022-10-16 11:12:02 -0700864 break;
865
866 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh71a40d42023-02-04 21:22:22 -0800867 switch (start_byte) {
868 case 0x00u:
869 if ((end_byte) == 0x00u) {
870 break;
871 }
872 // clang-format off
873 // header:
874 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
875 buffer = Push<flatbuffers::uoffset_t>(
876 buffer, message_size - sizeof(flatbuffers::uoffset_t));
877 // +0x04 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: +0x20 | offset to root table `aos.logger.MessageHeader`
878 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x1c);
879 [[fallthrough]];
880 case 0x08u:
881 if ((end_byte) == 0x08u) {
882 break;
883 }
884 //
885 // padding:
886 // +0x08 | 00 00 00 00 | uint8_t[4] | .... | padding
887 buffer = Pad(buffer, 4);
888 //
889 // vtable (aos.logger.MessageHeader):
890 // +0x0C | 14 00 | uint16_t | 0x0014 (20) | size of this vtable
891 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
892 // +0x0E | 34 00 | uint16_t | 0x0034 (52) | size of referring table
893 buffer = Push<flatbuffers::voffset_t>(buffer, 0x34);
894 [[fallthrough]];
895 case 0x10u:
896 if ((end_byte) == 0x10u) {
897 break;
898 }
899 // +0x10 | 30 00 | VOffset16 | 0x0030 (48) | offset to field `channel_index` (id: 0)
900 buffer = Push<flatbuffers::voffset_t>(buffer, 0x30);
901 // +0x12 | 20 00 | VOffset16 | 0x0020 (32) | offset to field `monotonic_sent_time` (id: 1)
902 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
903 // +0x14 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `realtime_sent_time` (id: 2)
904 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
905 // +0x16 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `queue_index` (id: 3)
906 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
907 [[fallthrough]];
908 case 0x18u:
909 if ((end_byte) == 0x18u) {
910 break;
911 }
912 // +0x18 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `data` (id: 4)
913 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
914 // +0x1A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `monotonic_remote_time` (id: 5)
915 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
916 // +0x1C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `realtime_remote_time` (id: 6)
917 buffer = Push<flatbuffers::voffset_t>(buffer, 0x08);
918 // +0x1E | 28 00 | VOffset16 | 0x0028 (40) | offset to field `remote_queue_index` (id: 7)
919 buffer = Push<flatbuffers::voffset_t>(buffer, 0x28);
920 [[fallthrough]];
921 case 0x20u:
922 if ((end_byte) == 0x20u) {
923 break;
924 }
925 //
926 // root_table (aos.logger.MessageHeader):
927 // +0x20 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: +0x0C | offset to vtable
928 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x14);
929 // +0x24 | 30 00 00 00 | UOffset32 | 0x00000030 (48) Loc: +0x54 | offset to field `data` (vector)
930 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x30);
931 [[fallthrough]];
932 case 0x28u:
933 if ((end_byte) == 0x28u) {
934 break;
935 }
936 // +0x28 | C4 C8 87 BF 40 6C 1F 29 | int64_t | 0x291F6C40BF87C8C4 (2963206105180129476) | table field `realtime_remote_time` (Long)
937 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
938 [[fallthrough]];
939 case 0x30u:
940 if ((end_byte) == 0x30u) {
941 break;
942 }
943 // +0x30 | 0F 00 26 FD D2 6D C0 1F | int64_t | 0x1FC06DD2FD26000F (2287949363661897743) | table field `monotonic_remote_time` (Long)
944 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
945 [[fallthrough]];
946 case 0x38u:
947 if ((end_byte) == 0x38u) {
948 break;
949 }
950 // +0x38 | 29 75 09 C0 73 73 BF 88 | int64_t | 0x88BF7373C0097529 (-8593022623019338455) | table field `realtime_sent_time` (Long)
951 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
952 [[fallthrough]];
953 case 0x40u:
954 if ((end_byte) == 0x40u) {
955 break;
956 }
957 // +0x40 | 6D 8A AE 04 50 25 9C E9 | int64_t | 0xE99C255004AE8A6D (-1613373540899321235) | table field `monotonic_sent_time` (Long)
958 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
959 [[fallthrough]];
960 case 0x48u:
961 if ((end_byte) == 0x48u) {
962 break;
963 }
964 // +0x48 | 47 00 00 00 | uint32_t | 0x00000047 (71) | table field `remote_queue_index` (UInt)
965 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
966 // +0x4C | 4C 00 00 00 | uint32_t | 0x0000004C (76) | table field `queue_index` (UInt)
967 buffer = Push<uint32_t>(buffer, context.queue_index);
968 [[fallthrough]];
969 case 0x50u:
970 if ((end_byte) == 0x50u) {
971 break;
972 }
973 // +0x50 | 72 00 00 00 | uint32_t | 0x00000072 (114) | table field `channel_index` (UInt)
974 buffer = Push<uint32_t>(buffer, channel_index);
975 //
976 // vector (aos.logger.MessageHeader.data):
977 // +0x54 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of vector (# items)
978 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
979 [[fallthrough]];
980 case 0x58u:
981 if ((end_byte) == 0x58u) {
982 break;
983 }
984 [[fallthrough]];
985 default:
986 // +0x58 | B1 | uint8_t | 0xB1 (177) | value[0]
987 // +0x59 | 4A | uint8_t | 0x4A (74) | value[1]
988 // +0x5A | 50 | uint8_t | 0x50 (80) | value[2]
989 // +0x5B | 24 | uint8_t | 0x24 (36) | value[3]
990 // +0x5C | AF | uint8_t | 0xAF (175) | value[4]
991 // +0x5D | C8 | uint8_t | 0xC8 (200) | value[5]
992 // +0x5E | D5 | uint8_t | 0xD5 (213) | value[6]
993 //
994 // padding:
995 // +0x5F | 00 | uint8_t[1] | . | padding
996 // clang-format on
997
998 if (start_byte <= 0x58 && end_byte == message_size) {
999 // The easy one, slap it all down.
1000 buffer = PushBytes(buffer, context.data, context.size);
1001 buffer =
1002 Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
1003 } else {
1004 const size_t data_start_byte =
1005 start_byte < 0x58 ? 0x0u : (start_byte - 0x58);
1006 const size_t data_end_byte = end_byte - 0x58;
1007 const size_t padded_size = ((context.size + 7) & 0xfffffff8u);
1008 if (data_start_byte < padded_size) {
1009 buffer = PushBytes(
1010 buffer,
1011 reinterpret_cast<const uint8_t *>(context.data) +
1012 data_start_byte,
1013 std::min(context.size, data_end_byte) - data_start_byte);
1014 if (data_end_byte == padded_size) {
1015 // We can only pad the last 7 bytes, so this only gets written
1016 // if we write the last byte.
1017 buffer = Pad(buffer,
1018 ((context.size + 7) & 0xfffffff8u) - context.size);
1019 }
1020 }
1021 }
1022
1023 break;
1024 }
Austin Schuhfa30c352022-10-16 11:12:02 -07001025
1026 break;
1027
1028 case LogType::kLogRemoteMessage:
Austin Schuh71a40d42023-02-04 21:22:22 -08001029 switch (start_byte) {
1030 case 0x00u:
1031 if ((end_byte) == 0x00u) {
1032 break;
1033 }
1034 // This is the message we need to recreate.
1035 //
1036 // clang-format off
1037 // header:
1038 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
1039 buffer = Push<flatbuffers::uoffset_t>(
1040 buffer, message_size - sizeof(flatbuffers::uoffset_t));
1041 // +0x04 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: +0x1C | offset to root table `aos.logger.MessageHeader`
1042 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x18);
1043 [[fallthrough]];
1044 case 0x08u:
1045 if ((end_byte) == 0x08u) {
1046 break;
1047 }
1048 //
1049 // padding:
1050 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
1051 buffer = Pad(buffer, 6);
1052 //
1053 // vtable (aos.logger.MessageHeader):
1054 // +0x0E | 0E 00 | uint16_t | 0x000E (14) | size of this vtable
1055 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0e);
1056 [[fallthrough]];
1057 case 0x10u:
1058 if ((end_byte) == 0x10u) {
1059 break;
1060 }
1061 // +0x10 | 20 00 | uint16_t | 0x0020 (32) | size of referring table
1062 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
1063 // +0x12 | 1C 00 | VOffset16 | 0x001C (28) | offset to field `channel_index` (id: 0)
1064 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
1065 // +0x14 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `monotonic_sent_time` (id: 1)
1066 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0c);
1067 // +0x16 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `realtime_sent_time` (id: 2)
1068 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
1069 [[fallthrough]];
1070 case 0x18u:
1071 if ((end_byte) == 0x18u) {
1072 break;
1073 }
1074 // +0x18 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `queue_index` (id: 3)
1075 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
1076 // +0x1A | 14 00 | VOffset16 | 0x0014 (20) | offset to field `data` (id: 4)
1077 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
1078 //
1079 // root_table (aos.logger.MessageHeader):
1080 // +0x1C | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: +0x0E | offset to vtable
1081 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0E);
1082 [[fallthrough]];
1083 case 0x20u:
1084 if ((end_byte) == 0x20u) {
1085 break;
1086 }
1087 // +0x20 | D8 96 32 1A A0 D3 23 BB | int64_t | 0xBB23D3A01A3296D8 (-4961889679844403496) | table field `realtime_sent_time` (Long)
1088 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
1089 [[fallthrough]];
1090 case 0x28u:
1091 if ((end_byte) == 0x28u) {
1092 break;
1093 }
1094 // +0x28 | 2E 5D 23 B3 BE 84 CF C2 | int64_t | 0xC2CF84BEB3235D2E (-4409159555588334290) | table field `monotonic_sent_time` (Long)
1095 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
1096 [[fallthrough]];
1097 case 0x30u:
1098 if ((end_byte) == 0x30u) {
1099 break;
1100 }
1101 // +0x30 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: +0x3C | offset to field `data` (vector)
1102 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0C);
1103 // +0x34 | 69 00 00 00 | uint32_t | 0x00000069 (105) | table field `queue_index` (UInt)
1104 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
1105 [[fallthrough]];
1106 case 0x38u:
1107 if ((end_byte) == 0x38u) {
1108 break;
1109 }
1110 // +0x38 | F3 00 00 00 | uint32_t | 0x000000F3 (243) | table field `channel_index` (UInt)
1111 buffer = Push<uint32_t>(buffer, channel_index);
1112 //
1113 // vector (aos.logger.MessageHeader.data):
1114 // +0x3C | 1A 00 00 00 | uint32_t | 0x0000001A (26) | length of vector (# items)
1115 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
1116 [[fallthrough]];
1117 case 0x40u:
1118 if ((end_byte) == 0x40u) {
1119 break;
1120 }
1121 [[fallthrough]];
1122 default:
1123 // +0x40 | 38 | uint8_t | 0x38 (56) | value[0]
1124 // +0x41 | 1A | uint8_t | 0x1A (26) | value[1]
1125 // ...
1126 // +0x58 | 90 | uint8_t | 0x90 (144) | value[24]
1127 // +0x59 | 92 | uint8_t | 0x92 (146) | value[25]
1128 //
1129 // padding:
1130 // +0x5A | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
1131 // clang-format on
1132 if (start_byte <= 0x40 && end_byte == message_size) {
1133 // The easy one, slap it all down.
1134 buffer = PushBytes(buffer, context.data, context.size);
1135 buffer =
1136 Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
1137 } else {
1138 const size_t data_start_byte =
1139 start_byte < 0x40 ? 0x0u : (start_byte - 0x40);
1140 const size_t data_end_byte = end_byte - 0x40;
1141 const size_t padded_size = ((context.size + 7) & 0xfffffff8u);
1142 if (data_start_byte < padded_size) {
1143 buffer = PushBytes(
1144 buffer,
1145 reinterpret_cast<const uint8_t *>(context.data) +
1146 data_start_byte,
1147 std::min(context.size, data_end_byte) - data_start_byte);
1148 if (data_end_byte == padded_size) {
1149 // We can only pad the last 7 bytes, so this only gets written
1150 // if we write the last byte.
1151 buffer = Pad(buffer,
1152 ((context.size + 7) & 0xfffffff8u) - context.size);
1153 }
1154 }
1155 }
1156 break;
1157 }
Austin Schuhfa30c352022-10-16 11:12:02 -07001158 }
1159
Austin Schuh71a40d42023-02-04 21:22:22 -08001160 return end_byte - start_byte;
Austin Schuhfa30c352022-10-16 11:12:02 -07001161}
1162
Austin Schuhcd368422021-11-22 21:23:29 -08001163SpanReader::SpanReader(std::string_view filename, bool quiet)
1164 : filename_(filename) {
Austin Schuh86110712022-09-16 15:40:54 -07001165 static constexpr std::string_view kS3 = "s3:";
1166 if (filename.substr(0, kS3.size()) == kS3) {
1167#if ENABLE_S3
1168 decoder_ = std::make_unique<S3Fetcher>(filename);
1169#else
1170 LOG(FATAL) << "Reading files from S3 not supported on this platform";
1171#endif
1172 } else {
1173 decoder_ = std::make_unique<DummyDecoder>(filename);
1174 }
Tyler Chatow2015bc62021-08-04 21:15:09 -07001175
1176 static constexpr std::string_view kXz = ".xz";
James Kuszmauldd0a5042021-10-28 23:38:04 -07001177 static constexpr std::string_view kSnappy = SnappyDecoder::kExtension;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -07001178 if (filename.substr(filename.size() - kXz.size()) == kXz) {
1179#if ENABLE_LZMA
Austin Schuhcd368422021-11-22 21:23:29 -08001180 decoder_ =
1181 std::make_unique<ThreadedLzmaDecoder>(std::move(decoder_), quiet);
Brian Silvermanf59fe3f2020-09-22 21:04:09 -07001182#else
Austin Schuhcd368422021-11-22 21:23:29 -08001183 (void)quiet;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -07001184 LOG(FATAL) << "Reading xz-compressed files not supported on this platform";
1185#endif
James Kuszmauldd0a5042021-10-28 23:38:04 -07001186 } else if (filename.substr(filename.size() - kSnappy.size()) == kSnappy) {
1187 decoder_ = std::make_unique<SnappyDecoder>(std::move(decoder_));
Brian Silvermanf59fe3f2020-09-22 21:04:09 -07001188 }
Austin Schuh05b70472020-01-01 17:11:17 -08001189}
1190
Austin Schuhcf5f6442021-07-06 10:43:28 -07001191absl::Span<const uint8_t> SpanReader::PeekMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -08001192 // Make sure we have enough for the size.
1193 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
1194 if (!ReadBlock()) {
1195 return absl::Span<const uint8_t>();
1196 }
1197 }
1198
1199 // Now make sure we have enough for the message.
1200 const size_t data_size =
1201 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
1202 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -08001203 if (data_size == sizeof(flatbuffers::uoffset_t)) {
1204 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
1205 LOG(ERROR) << " Rest of log file is "
1206 << absl::BytesToHexString(std::string_view(
1207 reinterpret_cast<const char *>(data_.data() +
1208 consumed_data_),
1209 data_.size() - consumed_data_));
1210 return absl::Span<const uint8_t>();
1211 }
Austin Schuh05b70472020-01-01 17:11:17 -08001212 while (data_.size() < consumed_data_ + data_size) {
1213 if (!ReadBlock()) {
1214 return absl::Span<const uint8_t>();
1215 }
1216 }
1217
1218 // And return it, consuming the data.
1219 const uint8_t *data_ptr = data_.data() + consumed_data_;
1220
Austin Schuh05b70472020-01-01 17:11:17 -08001221 return absl::Span<const uint8_t>(data_ptr, data_size);
1222}
1223
Austin Schuhcf5f6442021-07-06 10:43:28 -07001224void SpanReader::ConsumeMessage() {
Brian Smarttea913d42021-12-10 15:02:38 -08001225 size_t consumed_size =
Austin Schuhcf5f6442021-07-06 10:43:28 -07001226 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
1227 sizeof(flatbuffers::uoffset_t);
Brian Smarttea913d42021-12-10 15:02:38 -08001228 consumed_data_ += consumed_size;
1229 total_consumed_ += consumed_size;
Austin Schuhcf5f6442021-07-06 10:43:28 -07001230}
1231
1232absl::Span<const uint8_t> SpanReader::ReadMessage() {
1233 absl::Span<const uint8_t> result = PeekMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001234 if (!result.empty()) {
Austin Schuhcf5f6442021-07-06 10:43:28 -07001235 ConsumeMessage();
Brian Smarttea913d42021-12-10 15:02:38 -08001236 } else {
1237 is_finished_ = true;
Austin Schuhcf5f6442021-07-06 10:43:28 -07001238 }
1239 return result;
1240}
1241
Austin Schuh05b70472020-01-01 17:11:17 -08001242bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -07001243 // This is the amount of data we grab at a time. Doing larger chunks minimizes
1244 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -08001245 constexpr size_t kReadSize = 256 * 1024;
1246
1247 // Strip off any unused data at the front.
1248 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -07001249 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -08001250 consumed_data_ = 0;
1251 }
1252
1253 const size_t starting_size = data_.size();
1254
1255 // This should automatically grow the backing store. It won't shrink if we
1256 // get a small chunk later. This reduces allocations when we want to append
1257 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -07001258 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -08001259
Brian Silvermanf51499a2020-09-21 12:49:08 -07001260 const size_t count =
1261 decoder_->Read(data_.begin() + starting_size, data_.end());
1262 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -08001263 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -08001264 return false;
1265 }
Austin Schuh05b70472020-01-01 17:11:17 -08001266
Brian Smarttea913d42021-12-10 15:02:38 -08001267 total_read_ += count;
1268
Austin Schuh05b70472020-01-01 17:11:17 -08001269 return true;
1270}
1271
Austin Schuhadd6eb32020-11-09 21:24:26 -08001272std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh0e8db662021-07-06 10:43:47 -07001273 SpanReader *span_reader) {
1274 absl::Span<const uint8_t> config_data = span_reader->ReadMessage();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001275
1276 // Make sure something was read.
James Kuszmaul9776b392023-01-14 14:08:08 -08001277 if (config_data.empty()) {
Austin Schuh3bd4c402020-11-06 18:19:06 -08001278 return std::nullopt;
1279 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001280
Austin Schuh5212cad2020-09-09 23:12:09 -07001281 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -07001282 SizePrefixedFlatbufferVector<LogFileHeader> result(config_data);
Austin Schuhe09beb12020-12-11 20:04:27 -08001283 if (!result.Verify()) {
1284 return std::nullopt;
1285 }
Austin Schuh0e8db662021-07-06 10:43:47 -07001286
Austin Schuhcc2c9a52022-12-12 15:55:13 -08001287 // We only know of busted headers in the versions of the log file header
1288 // *before* the logger_sha1 field was added. At some point before that point,
1289 // the logic to track when a header has been written was rewritten in such a
1290 // way that it can't happen anymore. We've seen some logs where the body
1291 // parses as a header recently, so the simple solution of always looking is
1292 // failing us.
1293 if (FLAGS_workaround_double_headers && !result.message().has_logger_sha1()) {
Austin Schuh0e8db662021-07-06 10:43:47 -07001294 while (true) {
1295 absl::Span<const uint8_t> maybe_header_data = span_reader->PeekMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001296 if (maybe_header_data.empty()) {
Austin Schuh0e8db662021-07-06 10:43:47 -07001297 break;
1298 }
1299
1300 aos::SizePrefixedFlatbufferSpan<aos::logger::LogFileHeader> maybe_header(
1301 maybe_header_data);
1302 if (maybe_header.Verify()) {
1303 LOG(WARNING) << "Found duplicate LogFileHeader in "
1304 << span_reader->filename();
1305 ResizeableBuffer header_data_copy;
1306 header_data_copy.resize(maybe_header_data.size());
1307 memcpy(header_data_copy.data(), maybe_header_data.begin(),
1308 header_data_copy.size());
1309 result = SizePrefixedFlatbufferVector<LogFileHeader>(
1310 std::move(header_data_copy));
1311
1312 span_reader->ConsumeMessage();
1313 } else {
1314 break;
1315 }
1316 }
1317 }
Austin Schuhe09beb12020-12-11 20:04:27 -08001318 return result;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001319}
1320
Austin Schuh0e8db662021-07-06 10:43:47 -07001321std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
1322 std::string_view filename) {
1323 SpanReader span_reader(filename);
1324 return ReadHeader(&span_reader);
1325}
1326
Austin Schuhadd6eb32020-11-09 21:24:26 -08001327std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -08001328 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -07001329 SpanReader span_reader(filename);
1330 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
1331 for (size_t i = 0; i < n + 1; ++i) {
1332 data_span = span_reader.ReadMessage();
1333
1334 // Make sure something was read.
James Kuszmaul9776b392023-01-14 14:08:08 -08001335 if (data_span.empty()) {
Austin Schuh3bd4c402020-11-06 18:19:06 -08001336 return std::nullopt;
1337 }
Austin Schuh5212cad2020-09-09 23:12:09 -07001338 }
1339
Brian Silverman354697a2020-09-22 21:06:32 -07001340 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -07001341 SizePrefixedFlatbufferVector<MessageHeader> result(data_span);
Austin Schuhe09beb12020-12-11 20:04:27 -08001342 if (!result.Verify()) {
1343 return std::nullopt;
1344 }
1345 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -07001346}
1347
Austin Schuh05b70472020-01-01 17:11:17 -08001348MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -07001349 : span_reader_(filename),
Austin Schuhadd6eb32020-11-09 21:24:26 -08001350 raw_log_file_header_(
1351 SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001352 set_crash_on_corrupt_message_flag(FLAGS_crash_on_corrupt_message);
1353 set_ignore_corrupt_messages_flag(FLAGS_ignore_corrupt_messages);
1354
Austin Schuh0e8db662021-07-06 10:43:47 -07001355 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>>
1356 raw_log_file_header = ReadHeader(&span_reader_);
Austin Schuh05b70472020-01-01 17:11:17 -08001357
1358 // Make sure something was read.
Austin Schuh0e8db662021-07-06 10:43:47 -07001359 CHECK(raw_log_file_header) << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -08001360
Austin Schuh0e8db662021-07-06 10:43:47 -07001361 raw_log_file_header_ = std::move(*raw_log_file_header);
Austin Schuh05b70472020-01-01 17:11:17 -08001362
Austin Schuh5b728b72021-06-16 14:57:15 -07001363 CHECK(raw_log_file_header_.Verify()) << "Log file header is corrupted";
1364
Brian Smarttea913d42021-12-10 15:02:38 -08001365 total_verified_before_ = span_reader_.TotalConsumed();
1366
Austin Schuhcde938c2020-02-02 17:30:07 -08001367 max_out_of_order_duration_ =
Austin Schuha040c3f2021-02-13 16:09:07 -08001368 FLAGS_max_out_of_order > 0
1369 ? chrono::duration_cast<chrono::nanoseconds>(
1370 chrono::duration<double>(FLAGS_max_out_of_order))
1371 : chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -08001372
1373 VLOG(1) << "Opened " << filename << " as node "
1374 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -08001375}
1376
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001377std::shared_ptr<UnpackedMessageHeader> MessageReader::ReadMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -08001378 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001379 if (msg_data.empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001380 if (is_corrupted()) {
1381 LOG(ERROR) << "Total corrupted volumes: before = "
1382 << total_verified_before_
1383 << " | corrupted = " << total_corrupted_
1384 << " | during = " << total_verified_during_
1385 << " | after = " << total_verified_after_ << std::endl;
1386 }
1387
1388 if (span_reader_.IsIncomplete()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001389 LOG(ERROR) << "Unable to access some messages in " << filename() << " : "
1390 << span_reader_.TotalRead() << " bytes read, "
Brian Smarttea913d42021-12-10 15:02:38 -08001391 << span_reader_.TotalConsumed() << " bytes usable."
1392 << std::endl;
1393 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001394 return nullptr;
Austin Schuh05b70472020-01-01 17:11:17 -08001395 }
1396
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001397 SizePrefixedFlatbufferSpan<MessageHeader> msg(msg_data);
Brian Smarttea913d42021-12-10 15:02:38 -08001398
1399 if (crash_on_corrupt_message_flag_) {
1400 CHECK(msg.Verify()) << "Corrupted message at offset "
Austin Schuh60e77942022-05-16 17:48:24 -07001401 << total_verified_before_ << " found within "
1402 << filename()
Brian Smarttea913d42021-12-10 15:02:38 -08001403 << "; set --nocrash_on_corrupt_message to see summary;"
1404 << " also set --ignore_corrupt_messages to process"
1405 << " anyway";
1406
1407 } else if (!msg.Verify()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001408 LOG(ERROR) << "Corrupted message at offset " << total_verified_before_
Brian Smarttea913d42021-12-10 15:02:38 -08001409 << " from " << filename() << std::endl;
1410
1411 total_corrupted_ += msg_data.size();
1412
1413 while (true) {
1414 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
1415
James Kuszmaul9776b392023-01-14 14:08:08 -08001416 if (msg_data.empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001417 if (!ignore_corrupt_messages_flag_) {
1418 LOG(ERROR) << "Total corrupted volumes: before = "
1419 << total_verified_before_
1420 << " | corrupted = " << total_corrupted_
1421 << " | during = " << total_verified_during_
1422 << " | after = " << total_verified_after_ << std::endl;
1423
1424 if (span_reader_.IsIncomplete()) {
1425 LOG(ERROR) << "Unable to access some messages in " << filename()
1426 << " : " << span_reader_.TotalRead() << " bytes read, "
1427 << span_reader_.TotalConsumed() << " bytes usable."
1428 << std::endl;
1429 }
1430 return nullptr;
1431 }
1432 break;
1433 }
1434
1435 SizePrefixedFlatbufferSpan<MessageHeader> next_msg(msg_data);
1436
1437 if (!next_msg.Verify()) {
1438 total_corrupted_ += msg_data.size();
1439 total_verified_during_ += total_verified_after_;
1440 total_verified_after_ = 0;
1441
1442 } else {
1443 total_verified_after_ += msg_data.size();
1444 if (ignore_corrupt_messages_flag_) {
1445 msg = next_msg;
1446 break;
1447 }
1448 }
1449 }
1450 }
1451
1452 if (is_corrupted()) {
1453 total_verified_after_ += msg_data.size();
1454 } else {
1455 total_verified_before_ += msg_data.size();
1456 }
Austin Schuh05b70472020-01-01 17:11:17 -08001457
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001458 auto result = UnpackedMessageHeader::MakeMessage(msg.message());
Austin Schuh0e8db662021-07-06 10:43:47 -07001459
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001460 const monotonic_clock::time_point timestamp = result->monotonic_sent_time;
Austin Schuh05b70472020-01-01 17:11:17 -08001461
1462 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuhd1873292021-11-18 15:35:30 -08001463
1464 if (VLOG_IS_ON(3)) {
1465 VLOG(3) << "Read from " << filename() << " data " << FlatbufferToJson(msg);
1466 } else if (VLOG_IS_ON(2)) {
1467 SizePrefixedFlatbufferVector<MessageHeader> msg_copy = msg;
1468 msg_copy.mutable_message()->clear_data();
1469 VLOG(2) << "Read from " << filename() << " data "
1470 << FlatbufferToJson(msg_copy);
1471 }
1472
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001473 return result;
1474}
1475
1476std::shared_ptr<UnpackedMessageHeader> UnpackedMessageHeader::MakeMessage(
1477 const MessageHeader &message) {
1478 const size_t data_size = message.has_data() ? message.data()->size() : 0;
1479
1480 UnpackedMessageHeader *const unpacked_message =
1481 reinterpret_cast<UnpackedMessageHeader *>(
1482 malloc(sizeof(UnpackedMessageHeader) + data_size +
1483 kChannelDataAlignment - 1));
1484
1485 CHECK(message.has_channel_index());
1486 CHECK(message.has_monotonic_sent_time());
1487
1488 absl::Span<uint8_t> span;
1489 if (data_size > 0) {
1490 span =
1491 absl::Span<uint8_t>(reinterpret_cast<uint8_t *>(RoundChannelData(
1492 &unpacked_message->actual_data[0], data_size)),
1493 data_size);
1494 }
1495
Austin Schuh826e6ce2021-11-18 20:33:10 -08001496 std::optional<aos::monotonic_clock::time_point> monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001497 if (message.has_monotonic_remote_time()) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001498 monotonic_remote_time = aos::monotonic_clock::time_point(
1499 std::chrono::nanoseconds(message.monotonic_remote_time()));
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001500 }
1501 std::optional<realtime_clock::time_point> realtime_remote_time;
1502 if (message.has_realtime_remote_time()) {
1503 realtime_remote_time = realtime_clock::time_point(
1504 chrono::nanoseconds(message.realtime_remote_time()));
1505 }
1506
1507 std::optional<uint32_t> remote_queue_index;
1508 if (message.has_remote_queue_index()) {
1509 remote_queue_index = message.remote_queue_index();
1510 }
1511
James Kuszmaul9776b392023-01-14 14:08:08 -08001512 new (unpacked_message) UnpackedMessageHeader(
1513 message.channel_index(),
1514 monotonic_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001515 chrono::nanoseconds(message.monotonic_sent_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001516 realtime_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001517 chrono::nanoseconds(message.realtime_sent_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001518 message.queue_index(), monotonic_remote_time, realtime_remote_time,
1519 remote_queue_index,
1520 monotonic_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001521 std::chrono::nanoseconds(message.monotonic_timestamp_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001522 message.has_monotonic_timestamp_time(), span);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001523
1524 if (data_size > 0) {
1525 memcpy(span.data(), message.data()->data(), data_size);
1526 }
1527
1528 return std::shared_ptr<UnpackedMessageHeader>(unpacked_message,
1529 &DestroyAndFree);
Austin Schuh05b70472020-01-01 17:11:17 -08001530}
1531
Austin Schuhc41603c2020-10-11 16:17:37 -07001532PartsMessageReader::PartsMessageReader(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -07001533 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {
Brian Silvermanfee16972021-09-14 12:06:38 -07001534 if (parts_.parts.size() >= 2) {
1535 next_message_reader_.emplace(parts_.parts[1]);
1536 }
Austin Schuh48507722021-07-17 17:29:24 -07001537 ComputeBootCounts();
1538}
1539
1540void PartsMessageReader::ComputeBootCounts() {
1541 boot_counts_.assign(configuration::NodesCount(parts_.config.get()),
1542 std::nullopt);
1543
1544 // We have 3 vintages of log files with different amounts of information.
1545 if (log_file_header()->has_boot_uuids()) {
1546 // The new hotness with the boots explicitly listed out. We can use the log
1547 // file header to compute the boot count of all relevant nodes.
1548 CHECK_EQ(log_file_header()->boot_uuids()->size(), boot_counts_.size());
1549 size_t node_index = 0;
1550 for (const flatbuffers::String *boot_uuid :
1551 *log_file_header()->boot_uuids()) {
1552 CHECK(parts_.boots);
1553 if (boot_uuid->size() != 0) {
1554 auto it = parts_.boots->boot_count_map.find(boot_uuid->str());
1555 if (it != parts_.boots->boot_count_map.end()) {
1556 boot_counts_[node_index] = it->second;
1557 }
1558 } else if (parts().boots->boots[node_index].size() == 1u) {
1559 boot_counts_[node_index] = 0;
1560 }
1561 ++node_index;
1562 }
1563 } else {
1564 // Older multi-node logs which are guarenteed to have UUIDs logged, or
1565 // single node log files with boot UUIDs in the header. We only know how to
1566 // order certain boots in certain circumstances.
1567 if (configuration::MultiNode(parts_.config.get()) || parts_.boots) {
1568 for (size_t node_index = 0; node_index < boot_counts_.size();
1569 ++node_index) {
1570 CHECK(parts_.boots);
1571 if (parts().boots->boots[node_index].size() == 1u) {
1572 boot_counts_[node_index] = 0;
1573 }
1574 }
1575 } else {
1576 // Really old single node logs without any UUIDs. They can't reboot.
1577 CHECK_EQ(boot_counts_.size(), 1u);
1578 boot_counts_[0] = 0u;
1579 }
1580 }
1581}
Austin Schuhc41603c2020-10-11 16:17:37 -07001582
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001583std::shared_ptr<UnpackedMessageHeader> PartsMessageReader::ReadMessage() {
Austin Schuhc41603c2020-10-11 16:17:37 -07001584 while (!done_) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001585 std::shared_ptr<UnpackedMessageHeader> message =
Austin Schuhc41603c2020-10-11 16:17:37 -07001586 message_reader_.ReadMessage();
1587 if (message) {
1588 newest_timestamp_ = message_reader_.newest_timestamp();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001589 const monotonic_clock::time_point monotonic_sent_time =
1590 message->monotonic_sent_time;
1591
1592 // TODO(austin): Does this work with startup? Might need to use the
1593 // start time.
1594 // TODO(austin): Does this work with startup when we don't know the
1595 // remote start time too? Look at one of those logs to compare.
Austin Schuh315b96b2020-12-11 21:21:12 -08001596 if (monotonic_sent_time >
1597 parts_.monotonic_start_time + max_out_of_order_duration()) {
1598 after_start_ = true;
1599 }
1600 if (after_start_) {
Austin Schuhb000de62020-12-03 22:00:40 -08001601 CHECK_GE(monotonic_sent_time,
1602 newest_timestamp_ - max_out_of_order_duration())
Austin Schuha040c3f2021-02-13 16:09:07 -08001603 << ": Max out of order of " << max_out_of_order_duration().count()
1604 << "ns exceeded. " << parts_ << ", start time is "
Austin Schuh315b96b2020-12-11 21:21:12 -08001605 << parts_.monotonic_start_time << " currently reading "
1606 << filename();
Austin Schuhb000de62020-12-03 22:00:40 -08001607 }
Austin Schuhc41603c2020-10-11 16:17:37 -07001608 return message;
1609 }
1610 NextLog();
1611 }
Austin Schuh32f68492020-11-08 21:45:51 -08001612 newest_timestamp_ = monotonic_clock::max_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001613 return nullptr;
Austin Schuhc41603c2020-10-11 16:17:37 -07001614}
1615
1616void PartsMessageReader::NextLog() {
1617 if (next_part_index_ == parts_.parts.size()) {
Brian Silvermanfee16972021-09-14 12:06:38 -07001618 CHECK(!next_message_reader_);
Austin Schuhc41603c2020-10-11 16:17:37 -07001619 done_ = true;
1620 return;
1621 }
Brian Silvermanfee16972021-09-14 12:06:38 -07001622 CHECK(next_message_reader_);
1623 message_reader_ = std::move(*next_message_reader_);
Austin Schuh48507722021-07-17 17:29:24 -07001624 ComputeBootCounts();
Brian Silvermanfee16972021-09-14 12:06:38 -07001625 if (next_part_index_ + 1 < parts_.parts.size()) {
1626 next_message_reader_.emplace(parts_.parts[next_part_index_ + 1]);
1627 } else {
1628 next_message_reader_.reset();
1629 }
Austin Schuhc41603c2020-10-11 16:17:37 -07001630 ++next_part_index_;
1631}
1632
Austin Schuh1be0ce42020-11-29 22:43:26 -08001633bool Message::operator<(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001634 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001635
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001636 if (this->timestamp.time < m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -08001637 return true;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001638 } else if (this->timestamp.time > m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -08001639 return false;
1640 }
1641
1642 if (this->channel_index < m2.channel_index) {
1643 return true;
1644 } else if (this->channel_index > m2.channel_index) {
1645 return false;
1646 }
1647
1648 return this->queue_index < m2.queue_index;
1649}
1650
1651bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001652bool Message::operator==(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001653 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001654
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001655 return timestamp.time == m2.timestamp.time &&
1656 channel_index == m2.channel_index && queue_index == m2.queue_index;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001657}
Austin Schuh1be0ce42020-11-29 22:43:26 -08001658
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001659std::ostream &operator<<(std::ostream &os, const UnpackedMessageHeader &m) {
1660 os << "{.channel_index=" << m.channel_index
1661 << ", .monotonic_sent_time=" << m.monotonic_sent_time
1662 << ", .realtime_sent_time=" << m.realtime_sent_time
1663 << ", .queue_index=" << m.queue_index;
1664 if (m.monotonic_remote_time) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001665 os << ", .monotonic_remote_time=" << *m.monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001666 }
1667 os << ", .realtime_remote_time=";
1668 PrintOptionalOrNull(&os, m.realtime_remote_time);
1669 os << ", .remote_queue_index=";
1670 PrintOptionalOrNull(&os, m.remote_queue_index);
1671 if (m.has_monotonic_timestamp_time) {
1672 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
1673 }
Austin Schuh22cf7862022-09-19 19:09:42 -07001674 os << "}";
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001675 return os;
1676}
1677
Austin Schuh1be0ce42020-11-29 22:43:26 -08001678std::ostream &operator<<(std::ostream &os, const Message &m) {
1679 os << "{.channel_index=" << m.channel_index
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001680 << ", .queue_index=" << m.queue_index << ", .timestamp=" << m.timestamp;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001681 if (m.data != nullptr) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001682 if (m.data->remote_queue_index.has_value()) {
1683 os << ", .remote_queue_index=" << *m.data->remote_queue_index;
1684 }
1685 if (m.data->monotonic_remote_time.has_value()) {
1686 os << ", .monotonic_remote_time=" << *m.data->monotonic_remote_time;
1687 }
Austin Schuhfb1b3292021-11-16 21:20:15 -08001688 os << ", .data=" << m.data;
Austin Schuhd2f96102020-12-01 20:27:29 -08001689 }
1690 os << "}";
1691 return os;
1692}
1693
1694std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m) {
1695 os << "{.channel_index=" << m.channel_index
1696 << ", .queue_index=" << m.queue_index
1697 << ", .monotonic_event_time=" << m.monotonic_event_time
1698 << ", .realtime_event_time=" << m.realtime_event_time;
Austin Schuh58646e22021-08-23 23:51:46 -07001699 if (m.remote_queue_index != BootQueueIndex::Invalid()) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001700 os << ", .remote_queue_index=" << m.remote_queue_index;
1701 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001702 if (m.monotonic_remote_time != BootTimestamp::min_time()) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001703 os << ", .monotonic_remote_time=" << m.monotonic_remote_time;
1704 }
1705 if (m.realtime_remote_time != realtime_clock::min_time) {
1706 os << ", .realtime_remote_time=" << m.realtime_remote_time;
1707 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001708 if (m.monotonic_timestamp_time != BootTimestamp::min_time()) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001709 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
1710 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001711 if (m.data != nullptr) {
1712 os << ", .data=" << *m.data;
Austin Schuh22cf7862022-09-19 19:09:42 -07001713 } else {
1714 os << ", .data=nullptr";
Austin Schuhd2f96102020-12-01 20:27:29 -08001715 }
1716 os << "}";
Austin Schuh1be0ce42020-11-29 22:43:26 -08001717 return os;
1718}
1719
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001720LogPartsSorter::LogPartsSorter(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -07001721 : parts_message_reader_(log_parts),
1722 source_node_index_(configuration::SourceNodeIndex(parts().config.get())) {
1723}
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001724
1725Message *LogPartsSorter::Front() {
1726 // Queue up data until enough data has been queued that the front message is
1727 // sorted enough to be safe to pop. This may do nothing, so we should make
1728 // sure the nothing path is checked quickly.
1729 if (sorted_until() != monotonic_clock::max_time) {
1730 while (true) {
Austin Schuh48507722021-07-17 17:29:24 -07001731 if (!messages_.empty() &&
1732 messages_.begin()->timestamp.time < sorted_until() &&
Austin Schuhb000de62020-12-03 22:00:40 -08001733 sorted_until() >= monotonic_start_time()) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001734 break;
1735 }
1736
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001737 std::shared_ptr<UnpackedMessageHeader> m =
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001738 parts_message_reader_.ReadMessage();
1739 // No data left, sorted forever, work through what is left.
1740 if (!m) {
1741 sorted_until_ = monotonic_clock::max_time;
1742 break;
1743 }
1744
Austin Schuh48507722021-07-17 17:29:24 -07001745 size_t monotonic_timestamp_boot = 0;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001746 if (m->has_monotonic_timestamp_time) {
Austin Schuh48507722021-07-17 17:29:24 -07001747 monotonic_timestamp_boot = parts().logger_boot_count;
1748 }
1749 size_t monotonic_remote_boot = 0xffffff;
1750
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001751 if (m->monotonic_remote_time.has_value()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001752 const Node *node =
1753 parts().config->nodes()->Get(source_node_index_[m->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -07001754
Austin Schuh48507722021-07-17 17:29:24 -07001755 std::optional<size_t> boot = parts_message_reader_.boot_count(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001756 source_node_index_[m->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -07001757 CHECK(boot) << ": Failed to find boot for node " << MaybeNodeName(node)
Austin Schuh60e77942022-05-16 17:48:24 -07001758 << ", with index " << source_node_index_[m->channel_index];
Austin Schuh48507722021-07-17 17:29:24 -07001759 monotonic_remote_boot = *boot;
1760 }
1761
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001762 messages_.insert(
1763 Message{.channel_index = m->channel_index,
1764 .queue_index = BootQueueIndex{.boot = parts().boot_count,
1765 .index = m->queue_index},
1766 .timestamp = BootTimestamp{.boot = parts().boot_count,
1767 .time = m->monotonic_sent_time},
1768 .monotonic_remote_boot = monotonic_remote_boot,
1769 .monotonic_timestamp_boot = monotonic_timestamp_boot,
1770 .data = std::move(m)});
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001771
1772 // Now, update sorted_until_ to match the new message.
1773 if (parts_message_reader_.newest_timestamp() >
1774 monotonic_clock::min_time +
1775 parts_message_reader_.max_out_of_order_duration()) {
1776 sorted_until_ = parts_message_reader_.newest_timestamp() -
1777 parts_message_reader_.max_out_of_order_duration();
1778 } else {
1779 sorted_until_ = monotonic_clock::min_time;
1780 }
1781 }
1782 }
1783
1784 // Now that we have enough data queued, return a pointer to the oldest piece
1785 // of data if it exists.
1786 if (messages_.empty()) {
Austin Schuhb000de62020-12-03 22:00:40 -08001787 last_message_time_ = monotonic_clock::max_time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001788 return nullptr;
1789 }
1790
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001791 CHECK_GE(messages_.begin()->timestamp.time, last_message_time_)
Austin Schuh315b96b2020-12-11 21:21:12 -08001792 << DebugString() << " reading " << parts_message_reader_.filename();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001793 last_message_time_ = messages_.begin()->timestamp.time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001794 return &(*messages_.begin());
1795}
1796
1797void LogPartsSorter::PopFront() { messages_.erase(messages_.begin()); }
1798
1799std::string LogPartsSorter::DebugString() const {
1800 std::stringstream ss;
1801 ss << "messages: [\n";
Austin Schuh315b96b2020-12-11 21:21:12 -08001802 int count = 0;
1803 bool no_dots = true;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001804 for (const Message &m : messages_) {
Austin Schuh315b96b2020-12-11 21:21:12 -08001805 if (count < 15 || count > static_cast<int>(messages_.size()) - 15) {
1806 ss << m << "\n";
1807 } else if (no_dots) {
1808 ss << "...\n";
1809 no_dots = false;
1810 }
1811 ++count;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001812 }
1813 ss << "] <- " << parts_message_reader_.filename();
1814 return ss.str();
1815}
1816
Austin Schuhd2f96102020-12-01 20:27:29 -08001817NodeMerger::NodeMerger(std::vector<LogParts> parts) {
1818 CHECK_GE(parts.size(), 1u);
Austin Schuh715adc12021-06-29 22:07:39 -07001819 // Enforce that we are sorting things only from a single node from a single
1820 // boot.
1821 const std::string_view part0_node = parts[0].node;
1822 const std::string_view part0_source_boot_uuid = parts[0].source_boot_uuid;
Austin Schuhd2f96102020-12-01 20:27:29 -08001823 for (size_t i = 1; i < parts.size(); ++i) {
1824 CHECK_EQ(part0_node, parts[i].node) << ": Can't merge different nodes.";
Austin Schuh715adc12021-06-29 22:07:39 -07001825 CHECK_EQ(part0_source_boot_uuid, parts[i].source_boot_uuid)
1826 << ": Can't merge different boots.";
Austin Schuhd2f96102020-12-01 20:27:29 -08001827 }
Austin Schuh715adc12021-06-29 22:07:39 -07001828
1829 node_ = configuration::GetNodeIndex(parts[0].config.get(), part0_node);
1830
Austin Schuhd2f96102020-12-01 20:27:29 -08001831 for (LogParts &part : parts) {
1832 parts_sorters_.emplace_back(std::move(part));
1833 }
1834
Austin Schuhd2f96102020-12-01 20:27:29 -08001835 monotonic_start_time_ = monotonic_clock::max_time;
Austin Schuh9dc42612021-09-20 20:41:29 -07001836 realtime_start_time_ = realtime_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001837 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001838 // We want to capture the earliest meaningful start time here. The start
1839 // time defaults to min_time when there's no meaningful value to report, so
1840 // let's ignore those.
Austin Schuh9dc42612021-09-20 20:41:29 -07001841 if (parts_sorter.monotonic_start_time() != monotonic_clock::min_time) {
1842 bool accept = false;
1843 // We want to prioritize start times from the logger node. Really, we
1844 // want to prioritize start times with a valid realtime_clock time. So,
1845 // if we have a start time without a RT clock, prefer a start time with a
1846 // RT clock, even it if is later.
1847 if (parts_sorter.realtime_start_time() != realtime_clock::min_time) {
1848 // We've got a good one. See if the current start time has a good RT
1849 // clock, or if we should use this one instead.
1850 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
1851 accept = true;
1852 } else if (realtime_start_time_ == realtime_clock::min_time) {
1853 // The previous start time doesn't have a good RT time, so it is very
1854 // likely the start time from a remote part file. We just found a
1855 // better start time with a real RT time, so switch to that instead.
1856 accept = true;
1857 }
1858 } else if (realtime_start_time_ == realtime_clock::min_time) {
1859 // We don't have a RT time, so take the oldest.
1860 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
1861 accept = true;
1862 }
1863 }
1864
1865 if (accept) {
1866 monotonic_start_time_ = parts_sorter.monotonic_start_time();
1867 realtime_start_time_ = parts_sorter.realtime_start_time();
1868 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001869 }
1870 }
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001871
1872 // If there was no meaningful start time reported, just use min_time.
1873 if (monotonic_start_time_ == monotonic_clock::max_time) {
1874 monotonic_start_time_ = monotonic_clock::min_time;
1875 realtime_start_time_ = realtime_clock::min_time;
1876 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001877}
Austin Schuh8f52ed52020-11-30 23:12:39 -08001878
Austin Schuh0ca51f32020-12-25 21:51:45 -08001879std::vector<const LogParts *> NodeMerger::Parts() const {
1880 std::vector<const LogParts *> p;
1881 p.reserve(parts_sorters_.size());
1882 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
1883 p.emplace_back(&parts_sorter.parts());
1884 }
1885 return p;
1886}
1887
Austin Schuh8f52ed52020-11-30 23:12:39 -08001888Message *NodeMerger::Front() {
1889 // Return the current Front if we have one, otherwise go compute one.
1890 if (current_ != nullptr) {
Austin Schuhb000de62020-12-03 22:00:40 -08001891 Message *result = current_->Front();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001892 CHECK_GE(result->timestamp.time, last_message_time_);
Austin Schuhb000de62020-12-03 22:00:40 -08001893 return result;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001894 }
1895
1896 // Otherwise, do a simple search for the oldest message, deduplicating any
1897 // duplicates.
1898 Message *oldest = nullptr;
1899 sorted_until_ = monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001900 for (LogPartsSorter &parts_sorter : parts_sorters_) {
1901 Message *m = parts_sorter.Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -08001902 if (!m) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001903 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001904 continue;
1905 }
1906 if (oldest == nullptr || *m < *oldest) {
1907 oldest = m;
Austin Schuhd2f96102020-12-01 20:27:29 -08001908 current_ = &parts_sorter;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001909 } else if (*m == *oldest) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001910 // Found a duplicate. If there is a choice, we want the one which has
1911 // the timestamp time.
1912 if (!m->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001913 parts_sorter.PopFront();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001914 } else if (!oldest->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001915 current_->PopFront();
1916 current_ = &parts_sorter;
1917 oldest = m;
1918 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001919 CHECK_EQ(m->data->monotonic_timestamp_time,
1920 oldest->data->monotonic_timestamp_time);
Austin Schuh8bf1e632021-01-02 22:41:04 -08001921 parts_sorter.PopFront();
1922 }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001923 }
1924
1925 // PopFront may change this, so compute it down here.
Austin Schuhd2f96102020-12-01 20:27:29 -08001926 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001927 }
1928
Austin Schuhb000de62020-12-03 22:00:40 -08001929 if (oldest) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001930 CHECK_GE(oldest->timestamp.time, last_message_time_);
1931 last_message_time_ = oldest->timestamp.time;
Austin Schuh5dd22842021-11-17 16:09:39 -08001932 monotonic_oldest_time_ =
1933 std::min(monotonic_oldest_time_, oldest->timestamp.time);
Austin Schuhb000de62020-12-03 22:00:40 -08001934 } else {
1935 last_message_time_ = monotonic_clock::max_time;
1936 }
1937
Austin Schuh8f52ed52020-11-30 23:12:39 -08001938 // Return the oldest message found. This will be nullptr if nothing was
1939 // found, indicating there is nothing left.
1940 return oldest;
1941}
1942
1943void NodeMerger::PopFront() {
1944 CHECK(current_ != nullptr) << "Popping before calling Front()";
1945 current_->PopFront();
1946 current_ = nullptr;
1947}
1948
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001949BootMerger::BootMerger(std::vector<LogParts> files) {
1950 std::vector<std::vector<LogParts>> boots;
1951
1952 // Now, we need to split things out by boot.
1953 for (size_t i = 0; i < files.size(); ++i) {
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001954 const size_t boot_count = files[i].boot_count;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001955 if (boot_count + 1 > boots.size()) {
1956 boots.resize(boot_count + 1);
1957 }
1958 boots[boot_count].emplace_back(std::move(files[i]));
1959 }
1960
1961 node_mergers_.reserve(boots.size());
1962 for (size_t i = 0; i < boots.size(); ++i) {
Austin Schuh48507722021-07-17 17:29:24 -07001963 VLOG(2) << "Boot " << i;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001964 for (auto &p : boots[i]) {
Austin Schuh48507722021-07-17 17:29:24 -07001965 VLOG(2) << "Part " << p;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001966 }
1967 node_mergers_.emplace_back(
1968 std::make_unique<NodeMerger>(std::move(boots[i])));
1969 }
1970}
1971
1972Message *BootMerger::Front() {
1973 Message *result = node_mergers_[index_]->Front();
1974
1975 if (result != nullptr) {
1976 return result;
1977 }
1978
1979 if (index_ + 1u == node_mergers_.size()) {
1980 // At the end of the last node merger, just return.
1981 return nullptr;
1982 } else {
1983 ++index_;
1984 return Front();
1985 }
1986}
1987
1988void BootMerger::PopFront() { node_mergers_[index_]->PopFront(); }
1989
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001990std::vector<const LogParts *> BootMerger::Parts() const {
1991 std::vector<const LogParts *> results;
1992 for (const std::unique_ptr<NodeMerger> &node_merger : node_mergers_) {
1993 std::vector<const LogParts *> node_parts = node_merger->Parts();
1994
1995 results.insert(results.end(), std::make_move_iterator(node_parts.begin()),
1996 std::make_move_iterator(node_parts.end()));
1997 }
1998
1999 return results;
2000}
2001
Austin Schuhd2f96102020-12-01 20:27:29 -08002002TimestampMapper::TimestampMapper(std::vector<LogParts> parts)
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002003 : boot_merger_(std::move(parts)),
Austin Schuh79b30942021-01-24 22:32:21 -08002004 timestamp_callback_([](TimestampedMessage *) {}) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002005 for (const LogParts *part : boot_merger_.Parts()) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08002006 if (!configuration_) {
2007 configuration_ = part->config;
2008 } else {
2009 CHECK_EQ(configuration_.get(), part->config.get());
2010 }
2011 }
2012 const Configuration *config = configuration_.get();
Austin Schuhd2f96102020-12-01 20:27:29 -08002013 // Only fill out nodes_data_ if there are nodes. Otherwise everything gets
2014 // pretty simple.
2015 if (configuration::MultiNode(config)) {
2016 nodes_data_.resize(config->nodes()->size());
2017 const Node *my_node = config->nodes()->Get(node());
2018 for (size_t node_index = 0; node_index < nodes_data_.size(); ++node_index) {
2019 const Node *node = config->nodes()->Get(node_index);
2020 NodeData *node_data = &nodes_data_[node_index];
2021 node_data->channels.resize(config->channels()->size());
2022 // We should save the channel if it is delivered to the node represented
2023 // by the NodeData, but not sent by that node. That combo means it is
2024 // forwarded.
2025 size_t channel_index = 0;
2026 node_data->any_delivered = false;
2027 for (const Channel *channel : *config->channels()) {
2028 node_data->channels[channel_index].delivered =
2029 configuration::ChannelIsReadableOnNode(channel, node) &&
Austin Schuhb3dbb6d2021-01-02 17:29:35 -08002030 configuration::ChannelIsSendableOnNode(channel, my_node) &&
2031 (my_node != node);
Austin Schuhd2f96102020-12-01 20:27:29 -08002032 node_data->any_delivered = node_data->any_delivered ||
2033 node_data->channels[channel_index].delivered;
Austin Schuh6a7358f2021-11-18 22:40:40 -08002034 if (node_data->channels[channel_index].delivered) {
2035 const Connection *connection =
2036 configuration::ConnectionToNode(channel, node);
2037 node_data->channels[channel_index].time_to_live =
2038 chrono::nanoseconds(connection->time_to_live());
2039 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002040 ++channel_index;
2041 }
2042 }
2043
2044 for (const Channel *channel : *config->channels()) {
2045 source_node_.emplace_back(configuration::GetNodeIndex(
2046 config, channel->source_node()->string_view()));
2047 }
2048 }
2049}
2050
2051void TimestampMapper::AddPeer(TimestampMapper *timestamp_mapper) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08002052 CHECK(configuration::MultiNode(configuration()));
Austin Schuhd2f96102020-12-01 20:27:29 -08002053 CHECK_NE(timestamp_mapper->node(), node());
2054 CHECK_LT(timestamp_mapper->node(), nodes_data_.size());
2055
2056 NodeData *node_data = &nodes_data_[timestamp_mapper->node()];
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002057 // Only set it if this node delivers to the peer timestamp_mapper. Otherwise
Austin Schuhd2f96102020-12-01 20:27:29 -08002058 // we could needlessly save data.
2059 if (node_data->any_delivered) {
Austin Schuh87dd3832021-01-01 23:07:31 -08002060 VLOG(1) << "Registering on node " << node() << " for peer node "
2061 << timestamp_mapper->node();
Austin Schuhd2f96102020-12-01 20:27:29 -08002062 CHECK(timestamp_mapper->nodes_data_[node()].peer == nullptr);
2063
2064 timestamp_mapper->nodes_data_[node()].peer = this;
Austin Schuh36c00932021-07-19 18:13:21 -07002065
2066 node_data->save_for_peer = true;
Austin Schuhd2f96102020-12-01 20:27:29 -08002067 }
2068}
2069
Austin Schuh79b30942021-01-24 22:32:21 -08002070void TimestampMapper::QueueMessage(Message *m) {
Austin Schuh60e77942022-05-16 17:48:24 -07002071 matched_messages_.emplace_back(
2072 TimestampedMessage{.channel_index = m->channel_index,
2073 .queue_index = m->queue_index,
2074 .monotonic_event_time = m->timestamp,
2075 .realtime_event_time = m->data->realtime_sent_time,
2076 .remote_queue_index = BootQueueIndex::Invalid(),
2077 .monotonic_remote_time = BootTimestamp::min_time(),
2078 .realtime_remote_time = realtime_clock::min_time,
2079 .monotonic_timestamp_time = BootTimestamp::min_time(),
2080 .data = std::move(m->data)});
Austin Schuhd2f96102020-12-01 20:27:29 -08002081}
2082
2083TimestampedMessage *TimestampMapper::Front() {
2084 // No need to fetch anything new. A previous message still exists.
2085 switch (first_message_) {
2086 case FirstMessage::kNeedsUpdate:
2087 break;
2088 case FirstMessage::kInMessage:
Austin Schuh79b30942021-01-24 22:32:21 -08002089 return &matched_messages_.front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002090 case FirstMessage::kNullptr:
2091 return nullptr;
2092 }
2093
Austin Schuh79b30942021-01-24 22:32:21 -08002094 if (matched_messages_.empty()) {
2095 if (!QueueMatched()) {
2096 first_message_ = FirstMessage::kNullptr;
2097 return nullptr;
2098 }
2099 }
2100 first_message_ = FirstMessage::kInMessage;
2101 return &matched_messages_.front();
2102}
2103
2104bool TimestampMapper::QueueMatched() {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002105 MatchResult result = MatchResult::kEndOfFile;
2106 do {
2107 result = MaybeQueueMatched();
2108 } while (result == MatchResult::kSkipped);
2109 return result == MatchResult::kQueued;
2110}
2111
2112bool TimestampMapper::CheckReplayChannelsAndMaybePop(
2113 const TimestampedMessage & /*message*/) {
2114 if (replay_channels_callback_ &&
2115 !replay_channels_callback_(matched_messages_.back())) {
2116 matched_messages_.pop_back();
2117 return true;
2118 }
2119 return false;
2120}
2121
2122TimestampMapper::MatchResult TimestampMapper::MaybeQueueMatched() {
Austin Schuhd2f96102020-12-01 20:27:29 -08002123 if (nodes_data_.empty()) {
2124 // Simple path. We are single node, so there are no timestamps to match!
2125 CHECK_EQ(messages_.size(), 0u);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002126 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002127 if (!m) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002128 return MatchResult::kEndOfFile;
Austin Schuhd2f96102020-12-01 20:27:29 -08002129 }
Austin Schuh79b30942021-01-24 22:32:21 -08002130 // Enqueue this message into matched_messages_ so we have a place to
2131 // associate remote timestamps, and return it.
2132 QueueMessage(m);
Austin Schuhd2f96102020-12-01 20:27:29 -08002133
Austin Schuh79b30942021-01-24 22:32:21 -08002134 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
2135 last_message_time_ = matched_messages_.back().monotonic_event_time;
2136
2137 // We are thin wrapper around node_merger. Call it directly.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002138 boot_merger_.PopFront();
Austin Schuh79b30942021-01-24 22:32:21 -08002139 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002140 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2141 return MatchResult::kSkipped;
2142 }
2143 return MatchResult::kQueued;
Austin Schuhd2f96102020-12-01 20:27:29 -08002144 }
2145
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002146 // We need to only add messages to the list so they get processed for
2147 // messages which are delivered. Reuse the flow below which uses messages_
2148 // by just adding the new message to messages_ and continuing.
Austin Schuhd2f96102020-12-01 20:27:29 -08002149 if (messages_.empty()) {
2150 if (!Queue()) {
2151 // Found nothing to add, we are out of data!
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002152 return MatchResult::kEndOfFile;
Austin Schuhd2f96102020-12-01 20:27:29 -08002153 }
2154
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002155 // Now that it has been added (and cannibalized), forget about it
2156 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002157 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08002158 }
2159
2160 Message *m = &(messages_.front());
2161
2162 if (source_node_[m->channel_index] == node()) {
2163 // From us, just forward it on, filling the remote data in as invalid.
Austin Schuh79b30942021-01-24 22:32:21 -08002164 QueueMessage(m);
2165 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
2166 last_message_time_ = matched_messages_.back().monotonic_event_time;
2167 messages_.pop_front();
2168 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002169 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2170 return MatchResult::kSkipped;
2171 }
2172 return MatchResult::kQueued;
Austin Schuhd2f96102020-12-01 20:27:29 -08002173 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002174 // Got a timestamp, find the matching remote data, match it, and return
2175 // it.
Austin Schuhd2f96102020-12-01 20:27:29 -08002176 Message data = MatchingMessageFor(*m);
2177
2178 // Return the data from the remote. The local message only has timestamp
2179 // info which isn't relevant anymore once extracted.
Austin Schuh79b30942021-01-24 22:32:21 -08002180 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -08002181 .channel_index = m->channel_index,
2182 .queue_index = m->queue_index,
2183 .monotonic_event_time = m->timestamp,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002184 .realtime_event_time = m->data->realtime_sent_time,
Austin Schuh58646e22021-08-23 23:51:46 -07002185 .remote_queue_index =
2186 BootQueueIndex{.boot = m->monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002187 .index = m->data->remote_queue_index.value()},
2188 .monotonic_remote_time = {m->monotonic_remote_boot,
Austin Schuh826e6ce2021-11-18 20:33:10 -08002189 m->data->monotonic_remote_time.value()},
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002190 .realtime_remote_time = m->data->realtime_remote_time.value(),
2191 .monotonic_timestamp_time = {m->monotonic_timestamp_boot,
2192 m->data->monotonic_timestamp_time},
Austin Schuh79b30942021-01-24 22:32:21 -08002193 .data = std::move(data.data)});
2194 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
2195 last_message_time_ = matched_messages_.back().monotonic_event_time;
2196 // Since messages_ holds the data, drop it.
2197 messages_.pop_front();
2198 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002199 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2200 return MatchResult::kSkipped;
2201 }
2202 return MatchResult::kQueued;
Austin Schuh79b30942021-01-24 22:32:21 -08002203 }
2204}
2205
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002206void TimestampMapper::QueueUntil(BootTimestamp queue_time) {
Austin Schuh79b30942021-01-24 22:32:21 -08002207 while (last_message_time_ <= queue_time) {
2208 if (!QueueMatched()) {
2209 return;
2210 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002211 }
2212}
2213
Austin Schuhe639ea12021-01-25 13:00:22 -08002214void TimestampMapper::QueueFor(chrono::nanoseconds time_estimation_buffer) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002215 // Note: queueing for time doesn't really work well across boots. So we
2216 // just assume that if you are using this, you only care about the current
2217 // boot.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002218 //
2219 // TODO(austin): Is that the right concept?
2220 //
Austin Schuhe639ea12021-01-25 13:00:22 -08002221 // Make sure we have something queued first. This makes the end time
2222 // calculation simpler, and is typically what folks want regardless.
2223 if (matched_messages_.empty()) {
2224 if (!QueueMatched()) {
2225 return;
2226 }
2227 }
2228
2229 const aos::monotonic_clock::time_point end_queue_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002230 std::max(monotonic_start_time(
2231 matched_messages_.front().monotonic_event_time.boot),
2232 matched_messages_.front().monotonic_event_time.time) +
Austin Schuhe639ea12021-01-25 13:00:22 -08002233 time_estimation_buffer;
2234
2235 // Place sorted messages on the list until we have
2236 // --time_estimation_buffer_seconds seconds queued up (but queue at least
2237 // until the log starts).
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002238 while (end_queue_time >= last_message_time_.time) {
Austin Schuhe639ea12021-01-25 13:00:22 -08002239 if (!QueueMatched()) {
2240 return;
2241 }
2242 }
2243}
2244
Austin Schuhd2f96102020-12-01 20:27:29 -08002245void TimestampMapper::PopFront() {
2246 CHECK(first_message_ != FirstMessage::kNeedsUpdate);
Austin Schuh6a7358f2021-11-18 22:40:40 -08002247 last_popped_message_time_ = Front()->monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08002248 first_message_ = FirstMessage::kNeedsUpdate;
2249
Austin Schuh79b30942021-01-24 22:32:21 -08002250 matched_messages_.pop_front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002251}
2252
2253Message TimestampMapper::MatchingMessageFor(const Message &message) {
Austin Schuhd2f96102020-12-01 20:27:29 -08002254 // Figure out what queue index we are looking for.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002255 CHECK_NOTNULL(message.data);
2256 CHECK(message.data->remote_queue_index.has_value());
Austin Schuh58646e22021-08-23 23:51:46 -07002257 const BootQueueIndex remote_queue_index =
2258 BootQueueIndex{.boot = message.monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002259 .index = *message.data->remote_queue_index};
Austin Schuhd2f96102020-12-01 20:27:29 -08002260
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002261 CHECK(message.data->monotonic_remote_time.has_value());
2262 CHECK(message.data->realtime_remote_time.has_value());
Austin Schuhd2f96102020-12-01 20:27:29 -08002263
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002264 const BootTimestamp monotonic_remote_time{
Austin Schuh48507722021-07-17 17:29:24 -07002265 .boot = message.monotonic_remote_boot,
Austin Schuh826e6ce2021-11-18 20:33:10 -08002266 .time = message.data->monotonic_remote_time.value()};
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002267 const realtime_clock::time_point realtime_remote_time =
2268 *message.data->realtime_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08002269
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002270 TimestampMapper *peer =
2271 nodes_data_[source_node_[message.data->channel_index]].peer;
Austin Schuhfecf1d82020-12-19 16:57:28 -08002272
2273 // We only register the peers which we have data for. So, if we are being
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002274 // asked to pull a timestamp from a peer which doesn't exist, return an
2275 // empty message.
Austin Schuhfecf1d82020-12-19 16:57:28 -08002276 if (peer == nullptr) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002277 // TODO(austin): Make sure the tests hit all these paths with a boot count
2278 // of 1...
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002279 return Message{.channel_index = message.channel_index,
2280 .queue_index = remote_queue_index,
2281 .timestamp = monotonic_remote_time,
2282 .monotonic_remote_boot = 0xffffff,
2283 .monotonic_timestamp_boot = 0xffffff,
2284 .data = nullptr};
Austin Schuhfecf1d82020-12-19 16:57:28 -08002285 }
2286
2287 // The queue which will have the matching data, if available.
2288 std::deque<Message> *data_queue =
2289 &peer->nodes_data_[node()].channels[message.channel_index].messages;
2290
Austin Schuh79b30942021-01-24 22:32:21 -08002291 peer->QueueUnmatchedUntil(monotonic_remote_time);
Austin Schuhd2f96102020-12-01 20:27:29 -08002292
2293 if (data_queue->empty()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002294 return Message{.channel_index = message.channel_index,
2295 .queue_index = remote_queue_index,
2296 .timestamp = monotonic_remote_time,
2297 .monotonic_remote_boot = 0xffffff,
2298 .monotonic_timestamp_boot = 0xffffff,
2299 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08002300 }
2301
Austin Schuhd2f96102020-12-01 20:27:29 -08002302 if (remote_queue_index < data_queue->front().queue_index ||
2303 remote_queue_index > data_queue->back().queue_index) {
Austin Schuh60e77942022-05-16 17:48:24 -07002304 return Message{.channel_index = message.channel_index,
2305 .queue_index = remote_queue_index,
2306 .timestamp = monotonic_remote_time,
2307 .monotonic_remote_boot = 0xffffff,
2308 .monotonic_timestamp_boot = 0xffffff,
2309 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08002310 }
2311
Austin Schuh993ccb52020-12-12 15:59:32 -08002312 // The algorithm below is constant time with some assumptions. We need there
2313 // to be no missing messages in the data stream. This also assumes a queue
2314 // hasn't wrapped. That is conservative, but should let us get started.
Austin Schuh58646e22021-08-23 23:51:46 -07002315 if (data_queue->back().queue_index.boot ==
2316 data_queue->front().queue_index.boot &&
2317 (data_queue->back().queue_index.index -
2318 data_queue->front().queue_index.index + 1u ==
2319 data_queue->size())) {
2320 CHECK_EQ(remote_queue_index.boot, data_queue->front().queue_index.boot);
Austin Schuh993ccb52020-12-12 15:59:32 -08002321 // Pull the data out and confirm that the timestamps match as expected.
Austin Schuh58646e22021-08-23 23:51:46 -07002322 //
2323 // TODO(austin): Move if not reliable.
2324 Message result = (*data_queue)[remote_queue_index.index -
2325 data_queue->front().queue_index.index];
Austin Schuh993ccb52020-12-12 15:59:32 -08002326
2327 CHECK_EQ(result.timestamp, monotonic_remote_time)
2328 << ": Queue index matches, but timestamp doesn't. Please investigate!";
Austin Schuh6a7358f2021-11-18 22:40:40 -08002329 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
Austin Schuh993ccb52020-12-12 15:59:32 -08002330 << ": Queue index matches, but timestamp doesn't. Please investigate!";
2331 // Now drop the data off the front. We have deduplicated timestamps, so we
2332 // are done. And all the data is in order.
Austin Schuh58646e22021-08-23 23:51:46 -07002333 data_queue->erase(
2334 data_queue->begin(),
2335 data_queue->begin() +
2336 (remote_queue_index.index - data_queue->front().queue_index.index));
Austin Schuh993ccb52020-12-12 15:59:32 -08002337 return result;
2338 } else {
Austin Schuh58646e22021-08-23 23:51:46 -07002339 // TODO(austin): Binary search.
2340 auto it = std::find_if(
2341 data_queue->begin(), data_queue->end(),
2342 [remote_queue_index,
2343 remote_boot = monotonic_remote_time.boot](const Message &m) {
2344 return m.queue_index == remote_queue_index &&
2345 m.timestamp.boot == remote_boot;
2346 });
Austin Schuh993ccb52020-12-12 15:59:32 -08002347 if (it == data_queue->end()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002348 return Message{.channel_index = message.channel_index,
2349 .queue_index = remote_queue_index,
2350 .timestamp = monotonic_remote_time,
2351 .monotonic_remote_boot = 0xffffff,
2352 .monotonic_timestamp_boot = 0xffffff,
2353 .data = nullptr};
Austin Schuh993ccb52020-12-12 15:59:32 -08002354 }
2355
2356 Message result = std::move(*it);
2357
2358 CHECK_EQ(result.timestamp, monotonic_remote_time)
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002359 << ": Queue index matches, but timestamp doesn't. Please "
2360 "investigate!";
2361 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
2362 << ": Queue index matches, but timestamp doesn't. Please "
2363 "investigate!";
Austin Schuh993ccb52020-12-12 15:59:32 -08002364
Austin Schuhd6b1f4c2021-11-18 20:29:00 -08002365 // Erase everything up to this message. We want to keep 1 message in the
2366 // queue so we can handle reliable messages forwarded across boots.
2367 data_queue->erase(data_queue->begin(), it);
Austin Schuh993ccb52020-12-12 15:59:32 -08002368
2369 return result;
2370 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002371}
2372
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002373void TimestampMapper::QueueUnmatchedUntil(BootTimestamp t) {
Austin Schuhd2f96102020-12-01 20:27:29 -08002374 if (queued_until_ > t) {
2375 return;
2376 }
2377 while (true) {
2378 if (!messages_.empty() && messages_.back().timestamp > t) {
2379 queued_until_ = std::max(queued_until_, messages_.back().timestamp);
2380 return;
2381 }
2382
2383 if (!Queue()) {
2384 // Found nothing to add, we are out of data!
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002385 queued_until_ = BootTimestamp::max_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08002386 return;
2387 }
2388
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002389 // Now that it has been added (and cannibalized), forget about it
2390 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002391 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08002392 }
2393}
2394
2395bool TimestampMapper::Queue() {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002396 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002397 if (m == nullptr) {
2398 return false;
2399 }
2400 for (NodeData &node_data : nodes_data_) {
2401 if (!node_data.any_delivered) continue;
Austin Schuh36c00932021-07-19 18:13:21 -07002402 if (!node_data.save_for_peer) continue;
Austin Schuhd2f96102020-12-01 20:27:29 -08002403 if (node_data.channels[m->channel_index].delivered) {
Austin Schuh6a7358f2021-11-18 22:40:40 -08002404 // If we have data but no timestamps (logs where the timestamps didn't get
2405 // logged are classic), we can grow this indefinitely. We don't need to
2406 // keep anything that is older than the last message returned.
2407
2408 // We have the time on the source node.
2409 // We care to wait until we have the time on the destination node.
2410 std::deque<Message> &messages =
2411 node_data.channels[m->channel_index].messages;
2412 // Max delay over the network is the TTL, so let's take the queue time and
2413 // add TTL to it. Don't forget any messages which are reliable until
2414 // someone can come up with a good reason to forget those too.
2415 if (node_data.channels[m->channel_index].time_to_live >
2416 chrono::nanoseconds(0)) {
2417 // We need to make *some* assumptions about network delay for this to
2418 // work. We want to only look at the RX side. This means we need to
2419 // track the last time a message was popped from any channel from the
2420 // node sending this message, and compare that to the max time we expect
2421 // that a message will take to be delivered across the network. This
2422 // assumes that messages are popped in time order as a proxy for
2423 // measuring the distributed time at this layer.
2424 //
2425 // Leave at least 1 message in here so we can handle reboots and
2426 // messages getting sent twice.
2427 while (messages.size() > 1u &&
2428 messages.begin()->timestamp +
2429 node_data.channels[m->channel_index].time_to_live +
2430 chrono::duration_cast<chrono::nanoseconds>(
2431 chrono::duration<double>(FLAGS_max_network_delay)) <
2432 last_popped_message_time_) {
2433 messages.pop_front();
2434 }
2435 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002436 node_data.channels[m->channel_index].messages.emplace_back(*m);
2437 }
2438 }
2439
2440 messages_.emplace_back(std::move(*m));
2441 return true;
2442}
2443
2444std::string TimestampMapper::DebugString() const {
2445 std::stringstream ss;
Austin Schuh6e014b82021-09-14 17:46:33 -07002446 ss << "node " << node() << " (" << node_name() << ") [\n";
Austin Schuhd2f96102020-12-01 20:27:29 -08002447 for (const Message &message : messages_) {
2448 ss << " " << message << "\n";
2449 }
2450 ss << "] queued_until " << queued_until_;
2451 for (const NodeData &ns : nodes_data_) {
2452 if (ns.peer == nullptr) continue;
2453 ss << "\nnode " << ns.peer->node() << " remote_data [\n";
2454 size_t channel_index = 0;
2455 for (const NodeData::ChannelData &channel_data :
2456 ns.peer->nodes_data_[node()].channels) {
2457 if (channel_data.messages.empty()) {
2458 continue;
2459 }
Austin Schuhb000de62020-12-03 22:00:40 -08002460
Austin Schuhd2f96102020-12-01 20:27:29 -08002461 ss << " channel " << channel_index << " [\n";
2462 for (const Message &m : channel_data.messages) {
2463 ss << " " << m << "\n";
2464 }
2465 ss << " ]\n";
2466 ++channel_index;
2467 }
2468 ss << "] queued_until " << ns.peer->queued_until_;
2469 }
2470 return ss.str();
2471}
2472
Austin Schuhee711052020-08-24 16:06:09 -07002473std::string MaybeNodeName(const Node *node) {
2474 if (node != nullptr) {
2475 return node->name()->str() + " ";
2476 }
2477 return "";
2478}
2479
Brian Silvermanf51499a2020-09-21 12:49:08 -07002480} // namespace aos::logger