blob: 94337d34986fe20ebdc90352c625171896b3fcfe [file] [log] [blame]
Austin Schuha36c8902019-12-30 18:07:15 -08001#include "aos/events/logging/logfile_utils.h"
2
3#include <fcntl.h>
Austin Schuha36c8902019-12-30 18:07:15 -08004#include <sys/stat.h>
5#include <sys/types.h>
6#include <sys/uio.h>
7
Brian Silvermanf51499a2020-09-21 12:49:08 -07008#include <algorithm>
9#include <climits>
Austin Schuha36c8902019-12-30 18:07:15 -080010
Austin Schuhe4fca832020-03-07 16:58:53 -080011#include "absl/strings/escaping.h"
Austin Schuh05b70472020-01-01 17:11:17 -080012#include "aos/configuration.h"
James Kuszmauldd0a5042021-10-28 23:38:04 -070013#include "aos/events/logging/snappy_encoder.h"
Austin Schuhfa895892020-01-07 20:07:41 -080014#include "aos/flatbuffer_merge.h"
Austin Schuh6f3babe2020-01-26 20:34:50 -080015#include "aos/util/file.h"
Austin Schuha36c8902019-12-30 18:07:15 -080016#include "flatbuffers/flatbuffers.h"
Austin Schuh05b70472020-01-01 17:11:17 -080017#include "gflags/gflags.h"
18#include "glog/logging.h"
Austin Schuha36c8902019-12-30 18:07:15 -080019
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070020#if defined(__x86_64__)
Tyler Chatow2015bc62021-08-04 21:15:09 -070021#define ENABLE_LZMA (!__has_feature(memory_sanitizer))
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070022#elif defined(__aarch64__)
Tyler Chatow2015bc62021-08-04 21:15:09 -070023#define ENABLE_LZMA (!__has_feature(memory_sanitizer))
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070024#else
25#define ENABLE_LZMA 0
26#endif
27
28#if ENABLE_LZMA
29#include "aos/events/logging/lzma_encoder.h"
30#endif
Austin Schuh86110712022-09-16 15:40:54 -070031#if ENABLE_S3
32#include "aos/events/logging/s3_fetcher.h"
33#endif
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070034
Austin Schuh48d10d62022-10-16 22:19:23 -070035DEFINE_int32(flush_size, 128 * 1024,
Austin Schuha36c8902019-12-30 18:07:15 -080036 "Number of outstanding bytes to allow before flushing to disk.");
Austin Schuhbd06ae42021-03-31 22:48:21 -070037DEFINE_double(
38 flush_period, 5.0,
39 "Max time to let data sit in the queue before flushing in seconds.");
Austin Schuha36c8902019-12-30 18:07:15 -080040
Austin Schuha040c3f2021-02-13 16:09:07 -080041DEFINE_double(
Austin Schuh6a7358f2021-11-18 22:40:40 -080042 max_network_delay, 1.0,
43 "Max time to assume a message takes to cross the network before we are "
44 "willing to drop it from our buffers and assume it didn't make it. "
45 "Increasing this number can increase memory usage depending on the packet "
46 "loss of your network or if the timestamps aren't logged for a message.");
47
48DEFINE_double(
Austin Schuha040c3f2021-02-13 16:09:07 -080049 max_out_of_order, -1,
50 "If set, this overrides the max out of order duration for a log file.");
51
Austin Schuh0e8db662021-07-06 10:43:47 -070052DEFINE_bool(workaround_double_headers, true,
53 "Some old log files have two headers at the beginning. Use the "
54 "last header as the actual header.");
55
Brian Smarttea913d42021-12-10 15:02:38 -080056DEFINE_bool(crash_on_corrupt_message, true,
57 "When true, MessageReader will crash the first time a message "
58 "with corrupted format is found. When false, the crash will be "
59 "suppressed, and any remaining readable messages will be "
60 "evaluated to present verified vs corrupted stats.");
61
62DEFINE_bool(ignore_corrupt_messages, false,
63 "When true, and crash_on_corrupt_message is false, then any "
64 "corrupt message found by MessageReader be silently ignored, "
65 "providing access to all uncorrupted messages in a logfile.");
66
Brian Silvermanf51499a2020-09-21 12:49:08 -070067namespace aos::logger {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070068namespace {
Austin Schuha36c8902019-12-30 18:07:15 -080069
Austin Schuh05b70472020-01-01 17:11:17 -080070namespace chrono = std::chrono;
71
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070072template <typename T>
73void PrintOptionalOrNull(std::ostream *os, const std::optional<T> &t) {
74 if (t.has_value()) {
75 *os << *t;
76 } else {
77 *os << "null";
78 }
79}
80} // namespace
81
Austin Schuh48d10d62022-10-16 22:19:23 -070082DetachedBufferWriter::DetachedBufferWriter(std::string_view filename,
83 std::unique_ptr<DataEncoder> encoder)
Brian Silvermanf51499a2020-09-21 12:49:08 -070084 : filename_(filename), encoder_(std::move(encoder)) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070085 if (!util::MkdirPIfSpace(filename, 0777)) {
86 ran_out_of_space_ = true;
87 } else {
James Kuszmaul9776b392023-01-14 14:08:08 -080088 fd_ = open(filename_.c_str(), O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, 0774);
Brian Silvermana9f2ec92020-10-06 18:00:53 -070089 if (fd_ == -1 && errno == ENOSPC) {
90 ran_out_of_space_ = true;
91 } else {
Austin Schuh58646e22021-08-23 23:51:46 -070092 PCHECK(fd_ != -1) << ": Failed to open " << this->filename()
93 << " for writing";
94 VLOG(1) << "Opened " << this->filename() << " for writing";
Brian Silvermana9f2ec92020-10-06 18:00:53 -070095 }
96 }
Austin Schuha36c8902019-12-30 18:07:15 -080097}
98
99DetachedBufferWriter::~DetachedBufferWriter() {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700100 Close();
101 if (ran_out_of_space_) {
102 CHECK(acknowledge_ran_out_of_space_)
103 << ": Unacknowledged out of disk space, log file was not completed";
Brian Silvermanf51499a2020-09-21 12:49:08 -0700104 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700105}
106
Brian Silvermand90905f2020-09-23 14:42:56 -0700107DetachedBufferWriter::DetachedBufferWriter(DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700108 *this = std::move(other);
109}
110
Brian Silverman87ac0402020-09-17 14:47:01 -0700111// When other is destroyed "soon" (which it should be because we're getting an
112// rvalue reference to it), it will flush etc all the data we have queued up
113// (because that data will then be its data).
Austin Schuh2f8fd752020-09-01 22:38:28 -0700114DetachedBufferWriter &DetachedBufferWriter::operator=(
115 DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700116 std::swap(filename_, other.filename_);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700117 std::swap(encoder_, other.encoder_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700118 std::swap(fd_, other.fd_);
Brian Silverman0465fcf2020-09-24 00:29:18 -0700119 std::swap(ran_out_of_space_, other.ran_out_of_space_);
120 std::swap(acknowledge_ran_out_of_space_, other.acknowledge_ran_out_of_space_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700121 std::swap(iovec_, other.iovec_);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700122 std::swap(max_write_time_, other.max_write_time_);
123 std::swap(max_write_time_bytes_, other.max_write_time_bytes_);
124 std::swap(max_write_time_messages_, other.max_write_time_messages_);
125 std::swap(total_write_time_, other.total_write_time_);
126 std::swap(total_write_count_, other.total_write_count_);
127 std::swap(total_write_messages_, other.total_write_messages_);
128 std::swap(total_write_bytes_, other.total_write_bytes_);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700129 return *this;
Austin Schuha36c8902019-12-30 18:07:15 -0800130}
131
Brian Silvermanf51499a2020-09-21 12:49:08 -0700132void DetachedBufferWriter::QueueSpan(absl::Span<const uint8_t> span) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -0700133 if (ran_out_of_space_) {
134 // We don't want any later data to be written after space becomes
135 // available, so refuse to write anything more once we've dropped data
136 // because we ran out of space.
137 VLOG(1) << "Ignoring span: " << span.size();
138 return;
139 }
140
Austin Schuh48d10d62022-10-16 22:19:23 -0700141 if (!encoder_->HasSpace(span.size())) {
142 Flush();
143 CHECK(encoder_->HasSpace(span.size()));
144 }
145 DataEncoder::SpanCopier coppier(span);
146 encoder_->Encode(&coppier);
147 FlushAtThreshold(aos::monotonic_clock::now());
148}
Austin Schuha36c8902019-12-30 18:07:15 -0800149
Austin Schuh48d10d62022-10-16 22:19:23 -0700150void DetachedBufferWriter::CopyMessage(DataEncoder::Copier *coppier,
151 aos::monotonic_clock::time_point now) {
152 if (ran_out_of_space_) {
153 return;
Austin Schuha36c8902019-12-30 18:07:15 -0800154 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700155
Austin Schuh48d10d62022-10-16 22:19:23 -0700156 if (!encoder_->HasSpace(coppier->size())) {
157 Flush();
158 CHECK(encoder_->HasSpace(coppier->size()));
159 }
160
161 encoder_->Encode(coppier);
Austin Schuhbd06ae42021-03-31 22:48:21 -0700162 FlushAtThreshold(now);
Austin Schuha36c8902019-12-30 18:07:15 -0800163}
164
Brian Silverman0465fcf2020-09-24 00:29:18 -0700165void DetachedBufferWriter::Close() {
166 if (fd_ == -1) {
167 return;
168 }
169 encoder_->Finish();
170 while (encoder_->queue_size() > 0) {
171 Flush();
172 }
173 if (close(fd_) == -1) {
174 if (errno == ENOSPC) {
175 ran_out_of_space_ = true;
176 } else {
177 PLOG(ERROR) << "Closing log file failed";
178 }
179 }
180 fd_ = -1;
Austin Schuh58646e22021-08-23 23:51:46 -0700181 VLOG(1) << "Closed " << filename();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700182}
183
Austin Schuha36c8902019-12-30 18:07:15 -0800184void DetachedBufferWriter::Flush() {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700185 if (ran_out_of_space_) {
186 // We don't want any later data to be written after space becomes available,
187 // so refuse to write anything more once we've dropped data because we ran
188 // out of space.
Austin Schuha426f1f2021-03-31 22:27:41 -0700189 if (encoder_) {
190 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
191 encoder_->Clear(encoder_->queue().size());
192 } else {
193 VLOG(1) << "No queue to ignore";
194 }
195 return;
196 }
197
198 const auto queue = encoder_->queue();
199 if (queue.empty()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700200 return;
201 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700202
Austin Schuha36c8902019-12-30 18:07:15 -0800203 iovec_.clear();
Brian Silvermanf51499a2020-09-21 12:49:08 -0700204 const size_t iovec_size = std::min<size_t>(queue.size(), IOV_MAX);
205 iovec_.resize(iovec_size);
Austin Schuha36c8902019-12-30 18:07:15 -0800206 size_t counted_size = 0;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700207 for (size_t i = 0; i < iovec_size; ++i) {
208 iovec_[i].iov_base = const_cast<uint8_t *>(queue[i].data());
209 iovec_[i].iov_len = queue[i].size();
210 counted_size += iovec_[i].iov_len;
Austin Schuha36c8902019-12-30 18:07:15 -0800211 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700212
213 const auto start = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800214 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700215 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700216 HandleWriteReturn(written, counted_size);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700217
218 encoder_->Clear(iovec_size);
219
220 UpdateStatsForWrite(end - start, written, iovec_size);
221}
222
Brian Silverman0465fcf2020-09-24 00:29:18 -0700223void DetachedBufferWriter::HandleWriteReturn(ssize_t write_return,
224 size_t write_size) {
225 if (write_return == -1 && errno == ENOSPC) {
226 ran_out_of_space_ = true;
227 return;
228 }
229 PCHECK(write_return >= 0) << ": write failed";
230 if (write_return < static_cast<ssize_t>(write_size)) {
231 // Sometimes this happens instead of ENOSPC. On a real filesystem, this
232 // never seems to happen in any other case. If we ever want to log to a
233 // socket, this will happen more often. However, until we get there, we'll
234 // just assume it means we ran out of space.
235 ran_out_of_space_ = true;
236 return;
237 }
238}
239
Brian Silvermanf51499a2020-09-21 12:49:08 -0700240void DetachedBufferWriter::UpdateStatsForWrite(
241 aos::monotonic_clock::duration duration, ssize_t written, int iovec_size) {
242 if (duration > max_write_time_) {
243 max_write_time_ = duration;
244 max_write_time_bytes_ = written;
245 max_write_time_messages_ = iovec_size;
246 }
247 total_write_time_ += duration;
248 ++total_write_count_;
249 total_write_messages_ += iovec_size;
250 total_write_bytes_ += written;
251}
252
Austin Schuhbd06ae42021-03-31 22:48:21 -0700253void DetachedBufferWriter::FlushAtThreshold(
254 aos::monotonic_clock::time_point now) {
Austin Schuha426f1f2021-03-31 22:27:41 -0700255 if (ran_out_of_space_) {
256 // We don't want any later data to be written after space becomes available,
257 // so refuse to write anything more once we've dropped data because we ran
258 // out of space.
259 if (encoder_) {
260 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
261 encoder_->Clear(encoder_->queue().size());
262 } else {
263 VLOG(1) << "No queue to ignore";
264 }
265 return;
266 }
267
Austin Schuhbd06ae42021-03-31 22:48:21 -0700268 // We don't want to flush the first time through. Otherwise we will flush as
269 // the log file header might be compressing, defeating any parallelism and
270 // queueing there.
271 if (last_flush_time_ == aos::monotonic_clock::min_time) {
272 last_flush_time_ = now;
273 }
274
Brian Silvermanf51499a2020-09-21 12:49:08 -0700275 // Flush if we are at the max number of iovs per writev, because there's no
276 // point queueing up any more data in memory. Also flush once we have enough
Austin Schuhbd06ae42021-03-31 22:48:21 -0700277 // data queued up or if it has been long enough.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700278 while (encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
Austin Schuhbd06ae42021-03-31 22:48:21 -0700279 encoder_->queue_size() >= IOV_MAX ||
280 now > last_flush_time_ +
281 chrono::duration_cast<chrono::nanoseconds>(
282 chrono::duration<double>(FLAGS_flush_period))) {
283 last_flush_time_ = now;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700284 Flush();
285 }
Austin Schuha36c8902019-12-30 18:07:15 -0800286}
287
Austin Schuhf2d0e682022-10-16 14:20:58 -0700288// Do the magic dance to convert the endianness of the data and append it to the
289// buffer.
290namespace {
291
292// TODO(austin): Look at the generated code to see if building the header is
293// efficient or not.
294template <typename T>
295uint8_t *Push(uint8_t *buffer, const T data) {
296 const T endian_data = flatbuffers::EndianScalar<T>(data);
297 std::memcpy(buffer, &endian_data, sizeof(T));
298 return buffer + sizeof(T);
299}
300
301uint8_t *PushBytes(uint8_t *buffer, const void *data, size_t size) {
302 std::memcpy(buffer, data, size);
303 return buffer + size;
304}
305
306uint8_t *Pad(uint8_t *buffer, size_t padding) {
307 std::memset(buffer, 0, padding);
308 return buffer + padding;
309}
310} // namespace
311
312flatbuffers::Offset<MessageHeader> PackRemoteMessage(
313 flatbuffers::FlatBufferBuilder *fbb,
314 const message_bridge::RemoteMessage *msg, int channel_index,
315 const aos::monotonic_clock::time_point monotonic_timestamp_time) {
316 logger::MessageHeader::Builder message_header_builder(*fbb);
317 // Note: this must match the same order as MessageBridgeServer and
318 // PackMessage. We want identical headers to have identical
319 // on-the-wire formats to make comparing them easier.
320
321 message_header_builder.add_channel_index(channel_index);
322
323 message_header_builder.add_queue_index(msg->queue_index());
324 message_header_builder.add_monotonic_sent_time(msg->monotonic_sent_time());
325 message_header_builder.add_realtime_sent_time(msg->realtime_sent_time());
326
327 message_header_builder.add_monotonic_remote_time(
328 msg->monotonic_remote_time());
329 message_header_builder.add_realtime_remote_time(msg->realtime_remote_time());
330 message_header_builder.add_remote_queue_index(msg->remote_queue_index());
331
332 message_header_builder.add_monotonic_timestamp_time(
333 monotonic_timestamp_time.time_since_epoch().count());
334
335 return message_header_builder.Finish();
336}
337
338size_t PackRemoteMessageInline(
339 uint8_t *buffer, const message_bridge::RemoteMessage *msg,
340 int channel_index,
341 const aos::monotonic_clock::time_point monotonic_timestamp_time) {
342 const flatbuffers::uoffset_t message_size = PackRemoteMessageSize();
343
344 // clang-format off
345 // header:
346 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
347 buffer = Push<flatbuffers::uoffset_t>(
348 buffer, message_size - sizeof(flatbuffers::uoffset_t));
349 // +0x04 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: +0x24 | offset to root table `aos.logger.MessageHeader`
350 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x20);
351 //
352 // padding:
353 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
354 buffer = Pad(buffer, 6);
355 //
356 // vtable (aos.logger.MessageHeader):
357 // +0x0E | 16 00 | uint16_t | 0x0016 (22) | size of this vtable
358 buffer = Push<flatbuffers::voffset_t>(buffer, 0x16);
359 // +0x10 | 3C 00 | uint16_t | 0x003C (60) | size of referring table
360 buffer = Push<flatbuffers::voffset_t>(buffer, 0x3c);
361 // +0x12 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `channel_index` (id: 0)
362 buffer = Push<flatbuffers::voffset_t>(buffer, 0x38);
363 // +0x14 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `monotonic_sent_time` (id: 1)
364 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
365 // +0x16 | 24 00 | VOffset16 | 0x0024 (36) | offset to field `realtime_sent_time` (id: 2)
366 buffer = Push<flatbuffers::voffset_t>(buffer, 0x24);
367 // +0x18 | 34 00 | VOffset16 | 0x0034 (52) | offset to field `queue_index` (id: 3)
368 buffer = Push<flatbuffers::voffset_t>(buffer, 0x34);
369 // +0x1A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `data` (id: 4) <null> (Vector)
370 buffer = Push<flatbuffers::voffset_t>(buffer, 0x00);
371 // +0x1C | 1C 00 | VOffset16 | 0x001C (28) | offset to field `monotonic_remote_time` (id: 5)
372 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
373 // +0x1E | 14 00 | VOffset16 | 0x0014 (20) | offset to field `realtime_remote_time` (id: 6)
374 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
375 // +0x20 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `remote_queue_index` (id: 7)
376 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
377 // +0x22 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `monotonic_timestamp_time` (id: 8)
378 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
379 //
380 // root_table (aos.logger.MessageHeader):
381 // +0x24 | 16 00 00 00 | SOffset32 | 0x00000016 (22) Loc: +0x0E | offset to vtable
382 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x16);
383 // +0x28 | F6 0B D8 11 A4 A8 B1 71 | int64_t | 0x71B1A8A411D80BF6 (8192514619791117302) | table field `monotonic_timestamp_time` (Long)
384 buffer = Push<int64_t>(buffer,
385 monotonic_timestamp_time.time_since_epoch().count());
386 // +0x30 | 00 00 00 00 | uint8_t[4] | .... | padding
387 // TODO(austin): Can we re-arrange the order to ditch the padding?
388 // (Answer is yes, but what is the impact elsewhere? It will change the
389 // binary format)
390 buffer = Pad(buffer, 4);
391 // +0x34 | 75 00 00 00 | uint32_t | 0x00000075 (117) | table field `remote_queue_index` (UInt)
392 buffer = Push<uint32_t>(buffer, msg->remote_queue_index());
393 // +0x38 | AA B0 43 0A 35 BE FA D2 | int64_t | 0xD2FABE350A43B0AA (-3244071446552268630) | table field `realtime_remote_time` (Long)
394 buffer = Push<int64_t>(buffer, msg->realtime_remote_time());
395 // +0x40 | D5 40 30 F3 C1 A7 26 1D | int64_t | 0x1D26A7C1F33040D5 (2100550727665467605) | table field `monotonic_remote_time` (Long)
396 buffer = Push<int64_t>(buffer, msg->monotonic_remote_time());
397 // +0x48 | 5B 25 32 A1 4A E8 46 CA | int64_t | 0xCA46E84AA132255B (-3871151422448720549) | table field `realtime_sent_time` (Long)
398 buffer = Push<int64_t>(buffer, msg->realtime_sent_time());
399 // +0x50 | 49 7D 45 1F 8C 36 6B A3 | int64_t | 0xA36B368C1F457D49 (-6671178447571288759) | table field `monotonic_sent_time` (Long)
400 buffer = Push<int64_t>(buffer, msg->monotonic_sent_time());
401 // +0x58 | 33 00 00 00 | uint32_t | 0x00000033 (51) | table field `queue_index` (UInt)
402 buffer = Push<uint32_t>(buffer, msg->queue_index());
403 // +0x5C | 76 00 00 00 | uint32_t | 0x00000076 (118) | table field `channel_index` (UInt)
404 buffer = Push<uint32_t>(buffer, channel_index);
405 // clang-format on
406
407 return message_size;
408}
409
Austin Schuha36c8902019-12-30 18:07:15 -0800410flatbuffers::Offset<MessageHeader> PackMessage(
411 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
412 int channel_index, LogType log_type) {
413 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
414
415 switch (log_type) {
416 case LogType::kLogMessage:
417 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800418 case LogType::kLogRemoteMessage:
Austin Schuhfa30c352022-10-16 11:12:02 -0700419 // Since the timestamps are 8 byte aligned, we are going to end up adding
420 // padding in the middle of the message to pad everything out to 8 byte
421 // alignment. That's rather wasteful. To make things efficient to mmap
422 // while reading uncompressed logs, we'd actually rather the message be
423 // aligned. So, force 8 byte alignment (enough to preserve alignment
424 // inside the nested message so that we can read it without moving it)
425 // here.
426 fbb->ForceVectorAlignment(context.size, sizeof(uint8_t), 8);
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700427 data_offset = fbb->CreateVector(
428 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800429 break;
430
431 case LogType::kLogDeliveryTimeOnly:
432 break;
433 }
434
435 MessageHeader::Builder message_header_builder(*fbb);
436 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800437
Austin Schuhfa30c352022-10-16 11:12:02 -0700438 // These are split out into very explicit serialization calls because the
439 // order here changes the order things are written out on the wire, and we
440 // want to control and understand it here. Changing the order can increase
441 // the amount of padding bytes in the middle.
442 //
James Kuszmaul9776b392023-01-14 14:08:08 -0800443 // It is also easier to follow... And doesn't actually make things much
444 // bigger.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800445 switch (log_type) {
446 case LogType::kLogRemoteMessage:
447 message_header_builder.add_queue_index(context.remote_queue_index);
Austin Schuhfa30c352022-10-16 11:12:02 -0700448 message_header_builder.add_data(data_offset);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800449 message_header_builder.add_monotonic_sent_time(
450 context.monotonic_remote_time.time_since_epoch().count());
451 message_header_builder.add_realtime_sent_time(
452 context.realtime_remote_time.time_since_epoch().count());
453 break;
454
Austin Schuh6f3babe2020-01-26 20:34:50 -0800455 case LogType::kLogDeliveryTimeOnly:
456 message_header_builder.add_queue_index(context.queue_index);
457 message_header_builder.add_monotonic_sent_time(
458 context.monotonic_event_time.time_since_epoch().count());
459 message_header_builder.add_realtime_sent_time(
460 context.realtime_event_time.time_since_epoch().count());
Austin Schuha36c8902019-12-30 18:07:15 -0800461 message_header_builder.add_monotonic_remote_time(
462 context.monotonic_remote_time.time_since_epoch().count());
463 message_header_builder.add_realtime_remote_time(
464 context.realtime_remote_time.time_since_epoch().count());
465 message_header_builder.add_remote_queue_index(context.remote_queue_index);
466 break;
Austin Schuhfa30c352022-10-16 11:12:02 -0700467
468 case LogType::kLogMessage:
469 message_header_builder.add_queue_index(context.queue_index);
470 message_header_builder.add_data(data_offset);
471 message_header_builder.add_monotonic_sent_time(
472 context.monotonic_event_time.time_since_epoch().count());
473 message_header_builder.add_realtime_sent_time(
474 context.realtime_event_time.time_since_epoch().count());
475 break;
476
477 case LogType::kLogMessageAndDeliveryTime:
478 message_header_builder.add_queue_index(context.queue_index);
479 message_header_builder.add_remote_queue_index(context.remote_queue_index);
480 message_header_builder.add_monotonic_sent_time(
481 context.monotonic_event_time.time_since_epoch().count());
482 message_header_builder.add_realtime_sent_time(
483 context.realtime_event_time.time_since_epoch().count());
484 message_header_builder.add_monotonic_remote_time(
485 context.monotonic_remote_time.time_since_epoch().count());
486 message_header_builder.add_realtime_remote_time(
487 context.realtime_remote_time.time_since_epoch().count());
488 message_header_builder.add_data(data_offset);
489 break;
Austin Schuha36c8902019-12-30 18:07:15 -0800490 }
491
492 return message_header_builder.Finish();
493}
494
Austin Schuhfa30c352022-10-16 11:12:02 -0700495flatbuffers::uoffset_t PackMessageHeaderSize(LogType log_type) {
496 switch (log_type) {
497 case LogType::kLogMessage:
498 return
499 // Root table size + offset.
500 sizeof(flatbuffers::uoffset_t) * 2 +
501 // 6 padding bytes to pad the header out properly.
502 6 +
503 // vtable header (size + size of table)
504 sizeof(flatbuffers::voffset_t) * 2 +
505 // offsets to all the fields.
506 sizeof(flatbuffers::voffset_t) * 5 +
507 // pointer to vtable
508 sizeof(flatbuffers::soffset_t) +
509 // pointer to data
510 sizeof(flatbuffers::uoffset_t) +
511 // realtime_sent_time, monotonic_sent_time
512 sizeof(int64_t) * 2 +
513 // queue_index, channel_index
514 sizeof(uint32_t) * 2;
515
516 case LogType::kLogDeliveryTimeOnly:
517 return
518 // Root table size + offset.
519 sizeof(flatbuffers::uoffset_t) * 2 +
520 // 6 padding bytes to pad the header out properly.
521 4 +
522 // vtable header (size + size of table)
523 sizeof(flatbuffers::voffset_t) * 2 +
524 // offsets to all the fields.
525 sizeof(flatbuffers::voffset_t) * 8 +
526 // pointer to vtable
527 sizeof(flatbuffers::soffset_t) +
528 // remote_queue_index
529 sizeof(uint32_t) +
530 // realtime_remote_time, monotonic_remote_time, realtime_sent_time,
531 // monotonic_sent_time
532 sizeof(int64_t) * 4 +
533 // queue_index, channel_index
534 sizeof(uint32_t) * 2;
535
536 case LogType::kLogMessageAndDeliveryTime:
537 return
538 // Root table size + offset.
539 sizeof(flatbuffers::uoffset_t) * 2 +
540 // 4 padding bytes to pad the header out properly.
541 4 +
542 // vtable header (size + size of table)
543 sizeof(flatbuffers::voffset_t) * 2 +
544 // offsets to all the fields.
545 sizeof(flatbuffers::voffset_t) * 8 +
546 // pointer to vtable
547 sizeof(flatbuffers::soffset_t) +
548 // pointer to data
549 sizeof(flatbuffers::uoffset_t) +
550 // realtime_remote_time, monotonic_remote_time, realtime_sent_time,
551 // monotonic_sent_time
552 sizeof(int64_t) * 4 +
553 // remote_queue_index, queue_index, channel_index
554 sizeof(uint32_t) * 3;
555
556 case LogType::kLogRemoteMessage:
557 return
558 // Root table size + offset.
559 sizeof(flatbuffers::uoffset_t) * 2 +
560 // 6 padding bytes to pad the header out properly.
561 6 +
562 // vtable header (size + size of table)
563 sizeof(flatbuffers::voffset_t) * 2 +
564 // offsets to all the fields.
565 sizeof(flatbuffers::voffset_t) * 5 +
566 // pointer to vtable
567 sizeof(flatbuffers::soffset_t) +
568 // realtime_sent_time, monotonic_sent_time
569 sizeof(int64_t) * 2 +
570 // pointer to data
571 sizeof(flatbuffers::uoffset_t) +
572 // queue_index, channel_index
573 sizeof(uint32_t) * 2;
574 }
575 LOG(FATAL);
576}
577
James Kuszmaul9776b392023-01-14 14:08:08 -0800578flatbuffers::uoffset_t PackMessageSize(LogType log_type, size_t data_size) {
Austin Schuhfa30c352022-10-16 11:12:02 -0700579 static_assert(sizeof(flatbuffers::uoffset_t) == 4u,
580 "Update size logic please.");
581 const flatbuffers::uoffset_t aligned_data_length =
Austin Schuh48d10d62022-10-16 22:19:23 -0700582 ((data_size + 7) & 0xfffffff8u);
Austin Schuhfa30c352022-10-16 11:12:02 -0700583 switch (log_type) {
584 case LogType::kLogDeliveryTimeOnly:
585 return PackMessageHeaderSize(log_type);
586
587 case LogType::kLogMessage:
588 case LogType::kLogMessageAndDeliveryTime:
589 case LogType::kLogRemoteMessage:
590 return PackMessageHeaderSize(log_type) +
591 // Vector...
592 sizeof(flatbuffers::uoffset_t) + aligned_data_length;
593 }
594 LOG(FATAL);
595}
596
Austin Schuhfa30c352022-10-16 11:12:02 -0700597size_t PackMessageInline(uint8_t *buffer, const Context &context,
598 int channel_index, LogType log_type) {
Austin Schuh48d10d62022-10-16 22:19:23 -0700599 // TODO(austin): Figure out how to copy directly from shared memory instead of
600 // first into the fetcher's memory and then into here. That would save a lot
601 // of memory.
Austin Schuhfa30c352022-10-16 11:12:02 -0700602 const flatbuffers::uoffset_t message_size =
Austin Schuh48d10d62022-10-16 22:19:23 -0700603 PackMessageSize(log_type, context.size);
Austin Schuhfa30c352022-10-16 11:12:02 -0700604
605 buffer = Push<flatbuffers::uoffset_t>(
606 buffer, message_size - sizeof(flatbuffers::uoffset_t));
607
608 // Pack all the data in. This is brittle but easy to change. Use the
609 // InlinePackMessage.Equivilent unit test to verify everything matches.
610 switch (log_type) {
611 case LogType::kLogMessage:
612 // clang-format off
613 // header:
614 // +0x00 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: +0x4C | size prefix
615 // +0x04 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: +0x1C | offset to root table `aos.logger.MessageHeader`
616 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x18);
617 //
618 // padding:
619 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
620 buffer = Pad(buffer, 6);
621 //
622 // vtable (aos.logger.MessageHeader):
623 // +0x0E | 0E 00 | uint16_t | 0x000E (14) | size of this vtable
624 buffer = Push<flatbuffers::voffset_t>(buffer, 0xe);
625 // +0x10 | 20 00 | uint16_t | 0x0020 (32) | size of referring table
626 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
627 // +0x12 | 1C 00 | VOffset16 | 0x001C (28) | offset to field `channel_index` (id: 0)
628 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
629 // +0x14 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `monotonic_sent_time` (id: 1)
630 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0c);
631 // +0x16 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `realtime_sent_time` (id: 2)
632 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
633 // +0x18 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `queue_index` (id: 3)
634 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
635 // +0x1A | 14 00 | VOffset16 | 0x0014 (20) | offset to field `data` (id: 4)
636 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
637 //
638 // root_table (aos.logger.MessageHeader):
639 // +0x1C | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: +0x0E | offset to vtable
640 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0e);
641 // +0x20 | B2 E4 EF 89 19 7D 7F 6F | int64_t | 0x6F7F7D1989EFE4B2 (8034277808894108850) | table field `realtime_sent_time` (Long)
642 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
643 // +0x28 | 86 8D 92 65 FC 79 74 2B | int64_t | 0x2B7479FC65928D86 (3131261765872160134) | table field `monotonic_sent_time` (Long)
644 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
645 // +0x30 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: +0x3C | offset to field `data` (vector)
646 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0c);
647 // +0x34 | 86 00 00 00 | uint32_t | 0x00000086 (134) | table field `queue_index` (UInt)
648 buffer = Push<uint32_t>(buffer, context.queue_index);
649 // +0x38 | 71 00 00 00 | uint32_t | 0x00000071 (113) | table field `channel_index` (UInt)
650 buffer = Push<uint32_t>(buffer, channel_index);
651 //
652 // vector (aos.logger.MessageHeader.data):
653 // +0x3C | 0E 00 00 00 | uint32_t | 0x0000000E (14) | length of vector (# items)
654 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
655 // +0x40 | FF | uint8_t | 0xFF (255) | value[0]
656 // +0x41 | B8 | uint8_t | 0xB8 (184) | value[1]
657 // +0x42 | EE | uint8_t | 0xEE (238) | value[2]
658 // +0x43 | 00 | uint8_t | 0x00 (0) | value[3]
659 // +0x44 | 20 | uint8_t | 0x20 (32) | value[4]
660 // +0x45 | 4D | uint8_t | 0x4D (77) | value[5]
661 // +0x46 | FF | uint8_t | 0xFF (255) | value[6]
662 // +0x47 | 25 | uint8_t | 0x25 (37) | value[7]
663 // +0x48 | 3C | uint8_t | 0x3C (60) | value[8]
664 // +0x49 | 17 | uint8_t | 0x17 (23) | value[9]
665 // +0x4A | 65 | uint8_t | 0x65 (101) | value[10]
666 // +0x4B | 2F | uint8_t | 0x2F (47) | value[11]
667 // +0x4C | 63 | uint8_t | 0x63 (99) | value[12]
668 // +0x4D | 58 | uint8_t | 0x58 (88) | value[13]
669 buffer = PushBytes(buffer, context.data, context.size);
670 //
671 // padding:
672 // +0x4E | 00 00 | uint8_t[2] | .. | padding
673 buffer = Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
674 // clang-format on
675 break;
676
677 case LogType::kLogDeliveryTimeOnly:
678 // clang-format off
679 // header:
680 // +0x00 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: +0x4C | size prefix
681 // +0x04 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: +0x20 | offset to root table `aos.logger.MessageHeader`
682 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x1c);
683 //
684 // padding:
685 // +0x08 | 00 00 00 00 | uint8_t[4] | .... | padding
686 buffer = Pad(buffer, 4);
687 //
688 // vtable (aos.logger.MessageHeader):
689 // +0x0C | 14 00 | uint16_t | 0x0014 (20) | size of this vtable
690 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
691 // +0x0E | 30 00 | uint16_t | 0x0030 (48) | size of referring table
692 buffer = Push<flatbuffers::voffset_t>(buffer, 0x30);
693 // +0x10 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `channel_index` (id: 0)
694 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
695 // +0x12 | 20 00 | VOffset16 | 0x0020 (32) | offset to field `monotonic_sent_time` (id: 1)
696 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
697 // +0x14 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `realtime_sent_time` (id: 2)
698 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
699 // +0x16 | 28 00 | VOffset16 | 0x0028 (40) | offset to field `queue_index` (id: 3)
700 buffer = Push<flatbuffers::voffset_t>(buffer, 0x28);
701 // +0x18 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `data` (id: 4) <null> (Vector)
702 buffer = Push<flatbuffers::voffset_t>(buffer, 0x00);
703 // +0x1A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `monotonic_remote_time` (id: 5)
704 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
705 // +0x1C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `realtime_remote_time` (id: 6)
706 buffer = Push<flatbuffers::voffset_t>(buffer, 0x08);
707 // +0x1E | 04 00 | VOffset16 | 0x0004 (4) | offset to field `remote_queue_index` (id: 7)
708 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
709 //
710 // root_table (aos.logger.MessageHeader):
711 // +0x20 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: +0x0C | offset to vtable
712 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x14);
713 // +0x24 | 69 00 00 00 | uint32_t | 0x00000069 (105) | table field `remote_queue_index` (UInt)
714 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
715 // +0x28 | C6 85 F1 AB 83 B5 CD EB | int64_t | 0xEBCDB583ABF185C6 (-1455307527440726586) | table field `realtime_remote_time` (Long)
716 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
717 // +0x30 | 47 24 D3 97 1E 42 2D 99 | int64_t | 0x992D421E97D32447 (-7409193112790948793) | table field `monotonic_remote_time` (Long)
718 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
719 // +0x38 | C8 B9 A7 AB 79 F2 CD 60 | int64_t | 0x60CDF279ABA7B9C8 (6975498002251626952) | table field `realtime_sent_time` (Long)
720 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
721 // +0x40 | EA 8F 2A 0F AF 01 7A AB | int64_t | 0xAB7A01AF0F2A8FEA (-6090553694679822358) | table field `monotonic_sent_time` (Long)
722 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
723 // +0x48 | F5 00 00 00 | uint32_t | 0x000000F5 (245) | table field `queue_index` (UInt)
724 buffer = Push<uint32_t>(buffer, context.queue_index);
725 // +0x4C | 88 00 00 00 | uint32_t | 0x00000088 (136) | table field `channel_index` (UInt)
726 buffer = Push<uint32_t>(buffer, channel_index);
727
728 // clang-format on
729 break;
730
731 case LogType::kLogMessageAndDeliveryTime:
732 // clang-format off
733 // header:
734 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
735 // +0x04 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: +0x20 | offset to root table `aos.logger.MessageHeader`
736 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x1c);
737 //
738 // padding:
739 // +0x08 | 00 00 00 00 | uint8_t[4] | .... | padding
740 buffer = Pad(buffer, 4);
741 //
742 // vtable (aos.logger.MessageHeader):
743 // +0x0C | 14 00 | uint16_t | 0x0014 (20) | size of this vtable
744 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
745 // +0x0E | 34 00 | uint16_t | 0x0034 (52) | size of referring table
746 buffer = Push<flatbuffers::voffset_t>(buffer, 0x34);
747 // +0x10 | 30 00 | VOffset16 | 0x0030 (48) | offset to field `channel_index` (id: 0)
748 buffer = Push<flatbuffers::voffset_t>(buffer, 0x30);
749 // +0x12 | 20 00 | VOffset16 | 0x0020 (32) | offset to field `monotonic_sent_time` (id: 1)
750 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
751 // +0x14 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `realtime_sent_time` (id: 2)
752 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
753 // +0x16 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `queue_index` (id: 3)
754 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
755 // +0x18 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `data` (id: 4)
756 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
757 // +0x1A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `monotonic_remote_time` (id: 5)
758 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
759 // +0x1C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `realtime_remote_time` (id: 6)
760 buffer = Push<flatbuffers::voffset_t>(buffer, 0x08);
761 // +0x1E | 28 00 | VOffset16 | 0x0028 (40) | offset to field `remote_queue_index` (id: 7)
762 buffer = Push<flatbuffers::voffset_t>(buffer, 0x28);
763 //
764 // root_table (aos.logger.MessageHeader):
765 // +0x20 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: +0x0C | offset to vtable
766 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x14);
767 // +0x24 | 30 00 00 00 | UOffset32 | 0x00000030 (48) Loc: +0x54 | offset to field `data` (vector)
768 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x30);
769 // +0x28 | C4 C8 87 BF 40 6C 1F 29 | int64_t | 0x291F6C40BF87C8C4 (2963206105180129476) | table field `realtime_remote_time` (Long)
770 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
771 // +0x30 | 0F 00 26 FD D2 6D C0 1F | int64_t | 0x1FC06DD2FD26000F (2287949363661897743) | table field `monotonic_remote_time` (Long)
772 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
773 // +0x38 | 29 75 09 C0 73 73 BF 88 | int64_t | 0x88BF7373C0097529 (-8593022623019338455) | table field `realtime_sent_time` (Long)
774 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
775 // +0x40 | 6D 8A AE 04 50 25 9C E9 | int64_t | 0xE99C255004AE8A6D (-1613373540899321235) | table field `monotonic_sent_time` (Long)
776 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
777 // +0x48 | 47 00 00 00 | uint32_t | 0x00000047 (71) | table field `remote_queue_index` (UInt)
778 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
779 // +0x4C | 4C 00 00 00 | uint32_t | 0x0000004C (76) | table field `queue_index` (UInt)
780 buffer = Push<uint32_t>(buffer, context.queue_index);
781 // +0x50 | 72 00 00 00 | uint32_t | 0x00000072 (114) | table field `channel_index` (UInt)
782 buffer = Push<uint32_t>(buffer, channel_index);
783 //
784 // vector (aos.logger.MessageHeader.data):
785 // +0x54 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of vector (# items)
786 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
787 // +0x58 | B1 | uint8_t | 0xB1 (177) | value[0]
788 // +0x59 | 4A | uint8_t | 0x4A (74) | value[1]
789 // +0x5A | 50 | uint8_t | 0x50 (80) | value[2]
790 // +0x5B | 24 | uint8_t | 0x24 (36) | value[3]
791 // +0x5C | AF | uint8_t | 0xAF (175) | value[4]
792 // +0x5D | C8 | uint8_t | 0xC8 (200) | value[5]
793 // +0x5E | D5 | uint8_t | 0xD5 (213) | value[6]
794 buffer = PushBytes(buffer, context.data, context.size);
795 //
796 // padding:
797 // +0x5F | 00 | uint8_t[1] | . | padding
798 buffer = Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
799 // clang-format on
800
801 break;
802
803 case LogType::kLogRemoteMessage:
804 // This is the message we need to recreate.
805 //
806 // clang-format off
807 // header:
808 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
809 // +0x04 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: +0x1C | offset to root table `aos.logger.MessageHeader`
810 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x18);
811 //
812 // padding:
813 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
814 buffer = Pad(buffer, 6);
815 //
816 // vtable (aos.logger.MessageHeader):
817 // +0x0E | 0E 00 | uint16_t | 0x000E (14) | size of this vtable
818 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0e);
819 // +0x10 | 20 00 | uint16_t | 0x0020 (32) | size of referring table
820 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
821 // +0x12 | 1C 00 | VOffset16 | 0x001C (28) | offset to field `channel_index` (id: 0)
822 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
823 // +0x14 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `monotonic_sent_time` (id: 1)
824 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0c);
825 // +0x16 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `realtime_sent_time` (id: 2)
826 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
827 // +0x18 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `queue_index` (id: 3)
828 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
829 // +0x1A | 14 00 | VOffset16 | 0x0014 (20) | offset to field `data` (id: 4)
830 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
831 //
832 // root_table (aos.logger.MessageHeader):
833 // +0x1C | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: +0x0E | offset to vtable
834 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0E);
835 // +0x20 | D8 96 32 1A A0 D3 23 BB | int64_t | 0xBB23D3A01A3296D8 (-4961889679844403496) | table field `realtime_sent_time` (Long)
836 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
837 // +0x28 | 2E 5D 23 B3 BE 84 CF C2 | int64_t | 0xC2CF84BEB3235D2E (-4409159555588334290) | table field `monotonic_sent_time` (Long)
838 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
839 // +0x30 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: +0x3C | offset to field `data` (vector)
840 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0C);
841 // +0x34 | 69 00 00 00 | uint32_t | 0x00000069 (105) | table field `queue_index` (UInt)
842 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
843 // +0x38 | F3 00 00 00 | uint32_t | 0x000000F3 (243) | table field `channel_index` (UInt)
844 buffer = Push<uint32_t>(buffer, channel_index);
845 //
846 // vector (aos.logger.MessageHeader.data):
847 // +0x3C | 1A 00 00 00 | uint32_t | 0x0000001A (26) | length of vector (# items)
848 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
849 // +0x40 | 38 | uint8_t | 0x38 (56) | value[0]
850 // +0x41 | 1A | uint8_t | 0x1A (26) | value[1]
851 // ...
852 // +0x58 | 90 | uint8_t | 0x90 (144) | value[24]
853 // +0x59 | 92 | uint8_t | 0x92 (146) | value[25]
854 buffer = PushBytes(buffer, context.data, context.size);
855 //
856 // padding:
857 // +0x5A | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
858 buffer = Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
859 // clang-format on
860 }
861
862 return message_size;
863}
864
Austin Schuhcd368422021-11-22 21:23:29 -0800865SpanReader::SpanReader(std::string_view filename, bool quiet)
866 : filename_(filename) {
Austin Schuh86110712022-09-16 15:40:54 -0700867 static constexpr std::string_view kS3 = "s3:";
868 if (filename.substr(0, kS3.size()) == kS3) {
869#if ENABLE_S3
870 decoder_ = std::make_unique<S3Fetcher>(filename);
871#else
872 LOG(FATAL) << "Reading files from S3 not supported on this platform";
873#endif
874 } else {
875 decoder_ = std::make_unique<DummyDecoder>(filename);
876 }
Tyler Chatow2015bc62021-08-04 21:15:09 -0700877
878 static constexpr std::string_view kXz = ".xz";
James Kuszmauldd0a5042021-10-28 23:38:04 -0700879 static constexpr std::string_view kSnappy = SnappyDecoder::kExtension;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700880 if (filename.substr(filename.size() - kXz.size()) == kXz) {
881#if ENABLE_LZMA
Austin Schuhcd368422021-11-22 21:23:29 -0800882 decoder_ =
883 std::make_unique<ThreadedLzmaDecoder>(std::move(decoder_), quiet);
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700884#else
Austin Schuhcd368422021-11-22 21:23:29 -0800885 (void)quiet;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700886 LOG(FATAL) << "Reading xz-compressed files not supported on this platform";
887#endif
James Kuszmauldd0a5042021-10-28 23:38:04 -0700888 } else if (filename.substr(filename.size() - kSnappy.size()) == kSnappy) {
889 decoder_ = std::make_unique<SnappyDecoder>(std::move(decoder_));
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700890 }
Austin Schuh05b70472020-01-01 17:11:17 -0800891}
892
Austin Schuhcf5f6442021-07-06 10:43:28 -0700893absl::Span<const uint8_t> SpanReader::PeekMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -0800894 // Make sure we have enough for the size.
895 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
896 if (!ReadBlock()) {
897 return absl::Span<const uint8_t>();
898 }
899 }
900
901 // Now make sure we have enough for the message.
902 const size_t data_size =
903 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
904 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -0800905 if (data_size == sizeof(flatbuffers::uoffset_t)) {
906 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
907 LOG(ERROR) << " Rest of log file is "
908 << absl::BytesToHexString(std::string_view(
909 reinterpret_cast<const char *>(data_.data() +
910 consumed_data_),
911 data_.size() - consumed_data_));
912 return absl::Span<const uint8_t>();
913 }
Austin Schuh05b70472020-01-01 17:11:17 -0800914 while (data_.size() < consumed_data_ + data_size) {
915 if (!ReadBlock()) {
916 return absl::Span<const uint8_t>();
917 }
918 }
919
920 // And return it, consuming the data.
921 const uint8_t *data_ptr = data_.data() + consumed_data_;
922
Austin Schuh05b70472020-01-01 17:11:17 -0800923 return absl::Span<const uint8_t>(data_ptr, data_size);
924}
925
Austin Schuhcf5f6442021-07-06 10:43:28 -0700926void SpanReader::ConsumeMessage() {
Brian Smarttea913d42021-12-10 15:02:38 -0800927 size_t consumed_size =
Austin Schuhcf5f6442021-07-06 10:43:28 -0700928 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
929 sizeof(flatbuffers::uoffset_t);
Brian Smarttea913d42021-12-10 15:02:38 -0800930 consumed_data_ += consumed_size;
931 total_consumed_ += consumed_size;
Austin Schuhcf5f6442021-07-06 10:43:28 -0700932}
933
934absl::Span<const uint8_t> SpanReader::ReadMessage() {
935 absl::Span<const uint8_t> result = PeekMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -0800936 if (!result.empty()) {
Austin Schuhcf5f6442021-07-06 10:43:28 -0700937 ConsumeMessage();
Brian Smarttea913d42021-12-10 15:02:38 -0800938 } else {
939 is_finished_ = true;
Austin Schuhcf5f6442021-07-06 10:43:28 -0700940 }
941 return result;
942}
943
Austin Schuh05b70472020-01-01 17:11:17 -0800944bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700945 // This is the amount of data we grab at a time. Doing larger chunks minimizes
946 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -0800947 constexpr size_t kReadSize = 256 * 1024;
948
949 // Strip off any unused data at the front.
950 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700951 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -0800952 consumed_data_ = 0;
953 }
954
955 const size_t starting_size = data_.size();
956
957 // This should automatically grow the backing store. It won't shrink if we
958 // get a small chunk later. This reduces allocations when we want to append
959 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700960 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -0800961
Brian Silvermanf51499a2020-09-21 12:49:08 -0700962 const size_t count =
963 decoder_->Read(data_.begin() + starting_size, data_.end());
964 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -0800965 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -0800966 return false;
967 }
Austin Schuh05b70472020-01-01 17:11:17 -0800968
Brian Smarttea913d42021-12-10 15:02:38 -0800969 total_read_ += count;
970
Austin Schuh05b70472020-01-01 17:11:17 -0800971 return true;
972}
973
Austin Schuhadd6eb32020-11-09 21:24:26 -0800974std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh0e8db662021-07-06 10:43:47 -0700975 SpanReader *span_reader) {
976 absl::Span<const uint8_t> config_data = span_reader->ReadMessage();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800977
978 // Make sure something was read.
James Kuszmaul9776b392023-01-14 14:08:08 -0800979 if (config_data.empty()) {
Austin Schuh3bd4c402020-11-06 18:19:06 -0800980 return std::nullopt;
981 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800982
Austin Schuh5212cad2020-09-09 23:12:09 -0700983 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -0700984 SizePrefixedFlatbufferVector<LogFileHeader> result(config_data);
Austin Schuhe09beb12020-12-11 20:04:27 -0800985 if (!result.Verify()) {
986 return std::nullopt;
987 }
Austin Schuh0e8db662021-07-06 10:43:47 -0700988
Austin Schuhcc2c9a52022-12-12 15:55:13 -0800989 // We only know of busted headers in the versions of the log file header
990 // *before* the logger_sha1 field was added. At some point before that point,
991 // the logic to track when a header has been written was rewritten in such a
992 // way that it can't happen anymore. We've seen some logs where the body
993 // parses as a header recently, so the simple solution of always looking is
994 // failing us.
995 if (FLAGS_workaround_double_headers && !result.message().has_logger_sha1()) {
Austin Schuh0e8db662021-07-06 10:43:47 -0700996 while (true) {
997 absl::Span<const uint8_t> maybe_header_data = span_reader->PeekMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -0800998 if (maybe_header_data.empty()) {
Austin Schuh0e8db662021-07-06 10:43:47 -0700999 break;
1000 }
1001
1002 aos::SizePrefixedFlatbufferSpan<aos::logger::LogFileHeader> maybe_header(
1003 maybe_header_data);
1004 if (maybe_header.Verify()) {
1005 LOG(WARNING) << "Found duplicate LogFileHeader in "
1006 << span_reader->filename();
1007 ResizeableBuffer header_data_copy;
1008 header_data_copy.resize(maybe_header_data.size());
1009 memcpy(header_data_copy.data(), maybe_header_data.begin(),
1010 header_data_copy.size());
1011 result = SizePrefixedFlatbufferVector<LogFileHeader>(
1012 std::move(header_data_copy));
1013
1014 span_reader->ConsumeMessage();
1015 } else {
1016 break;
1017 }
1018 }
1019 }
Austin Schuhe09beb12020-12-11 20:04:27 -08001020 return result;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001021}
1022
Austin Schuh0e8db662021-07-06 10:43:47 -07001023std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
1024 std::string_view filename) {
1025 SpanReader span_reader(filename);
1026 return ReadHeader(&span_reader);
1027}
1028
Austin Schuhadd6eb32020-11-09 21:24:26 -08001029std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -08001030 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -07001031 SpanReader span_reader(filename);
1032 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
1033 for (size_t i = 0; i < n + 1; ++i) {
1034 data_span = span_reader.ReadMessage();
1035
1036 // Make sure something was read.
James Kuszmaul9776b392023-01-14 14:08:08 -08001037 if (data_span.empty()) {
Austin Schuh3bd4c402020-11-06 18:19:06 -08001038 return std::nullopt;
1039 }
Austin Schuh5212cad2020-09-09 23:12:09 -07001040 }
1041
Brian Silverman354697a2020-09-22 21:06:32 -07001042 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -07001043 SizePrefixedFlatbufferVector<MessageHeader> result(data_span);
Austin Schuhe09beb12020-12-11 20:04:27 -08001044 if (!result.Verify()) {
1045 return std::nullopt;
1046 }
1047 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -07001048}
1049
Austin Schuh05b70472020-01-01 17:11:17 -08001050MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -07001051 : span_reader_(filename),
Austin Schuhadd6eb32020-11-09 21:24:26 -08001052 raw_log_file_header_(
1053 SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001054 set_crash_on_corrupt_message_flag(FLAGS_crash_on_corrupt_message);
1055 set_ignore_corrupt_messages_flag(FLAGS_ignore_corrupt_messages);
1056
Austin Schuh0e8db662021-07-06 10:43:47 -07001057 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>>
1058 raw_log_file_header = ReadHeader(&span_reader_);
Austin Schuh05b70472020-01-01 17:11:17 -08001059
1060 // Make sure something was read.
Austin Schuh0e8db662021-07-06 10:43:47 -07001061 CHECK(raw_log_file_header) << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -08001062
Austin Schuh0e8db662021-07-06 10:43:47 -07001063 raw_log_file_header_ = std::move(*raw_log_file_header);
Austin Schuh05b70472020-01-01 17:11:17 -08001064
Austin Schuh5b728b72021-06-16 14:57:15 -07001065 CHECK(raw_log_file_header_.Verify()) << "Log file header is corrupted";
1066
Brian Smarttea913d42021-12-10 15:02:38 -08001067 total_verified_before_ = span_reader_.TotalConsumed();
1068
Austin Schuhcde938c2020-02-02 17:30:07 -08001069 max_out_of_order_duration_ =
Austin Schuha040c3f2021-02-13 16:09:07 -08001070 FLAGS_max_out_of_order > 0
1071 ? chrono::duration_cast<chrono::nanoseconds>(
1072 chrono::duration<double>(FLAGS_max_out_of_order))
1073 : chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -08001074
1075 VLOG(1) << "Opened " << filename << " as node "
1076 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -08001077}
1078
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001079std::shared_ptr<UnpackedMessageHeader> MessageReader::ReadMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -08001080 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001081 if (msg_data.empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001082 if (is_corrupted()) {
1083 LOG(ERROR) << "Total corrupted volumes: before = "
1084 << total_verified_before_
1085 << " | corrupted = " << total_corrupted_
1086 << " | during = " << total_verified_during_
1087 << " | after = " << total_verified_after_ << std::endl;
1088 }
1089
1090 if (span_reader_.IsIncomplete()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001091 LOG(ERROR) << "Unable to access some messages in " << filename() << " : "
1092 << span_reader_.TotalRead() << " bytes read, "
Brian Smarttea913d42021-12-10 15:02:38 -08001093 << span_reader_.TotalConsumed() << " bytes usable."
1094 << std::endl;
1095 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001096 return nullptr;
Austin Schuh05b70472020-01-01 17:11:17 -08001097 }
1098
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001099 SizePrefixedFlatbufferSpan<MessageHeader> msg(msg_data);
Brian Smarttea913d42021-12-10 15:02:38 -08001100
1101 if (crash_on_corrupt_message_flag_) {
1102 CHECK(msg.Verify()) << "Corrupted message at offset "
Austin Schuh60e77942022-05-16 17:48:24 -07001103 << total_verified_before_ << " found within "
1104 << filename()
Brian Smarttea913d42021-12-10 15:02:38 -08001105 << "; set --nocrash_on_corrupt_message to see summary;"
1106 << " also set --ignore_corrupt_messages to process"
1107 << " anyway";
1108
1109 } else if (!msg.Verify()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001110 LOG(ERROR) << "Corrupted message at offset " << total_verified_before_
Brian Smarttea913d42021-12-10 15:02:38 -08001111 << " from " << filename() << std::endl;
1112
1113 total_corrupted_ += msg_data.size();
1114
1115 while (true) {
1116 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
1117
James Kuszmaul9776b392023-01-14 14:08:08 -08001118 if (msg_data.empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001119 if (!ignore_corrupt_messages_flag_) {
1120 LOG(ERROR) << "Total corrupted volumes: before = "
1121 << total_verified_before_
1122 << " | corrupted = " << total_corrupted_
1123 << " | during = " << total_verified_during_
1124 << " | after = " << total_verified_after_ << std::endl;
1125
1126 if (span_reader_.IsIncomplete()) {
1127 LOG(ERROR) << "Unable to access some messages in " << filename()
1128 << " : " << span_reader_.TotalRead() << " bytes read, "
1129 << span_reader_.TotalConsumed() << " bytes usable."
1130 << std::endl;
1131 }
1132 return nullptr;
1133 }
1134 break;
1135 }
1136
1137 SizePrefixedFlatbufferSpan<MessageHeader> next_msg(msg_data);
1138
1139 if (!next_msg.Verify()) {
1140 total_corrupted_ += msg_data.size();
1141 total_verified_during_ += total_verified_after_;
1142 total_verified_after_ = 0;
1143
1144 } else {
1145 total_verified_after_ += msg_data.size();
1146 if (ignore_corrupt_messages_flag_) {
1147 msg = next_msg;
1148 break;
1149 }
1150 }
1151 }
1152 }
1153
1154 if (is_corrupted()) {
1155 total_verified_after_ += msg_data.size();
1156 } else {
1157 total_verified_before_ += msg_data.size();
1158 }
Austin Schuh05b70472020-01-01 17:11:17 -08001159
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001160 auto result = UnpackedMessageHeader::MakeMessage(msg.message());
Austin Schuh0e8db662021-07-06 10:43:47 -07001161
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001162 const monotonic_clock::time_point timestamp = result->monotonic_sent_time;
Austin Schuh05b70472020-01-01 17:11:17 -08001163
1164 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuhd1873292021-11-18 15:35:30 -08001165
1166 if (VLOG_IS_ON(3)) {
1167 VLOG(3) << "Read from " << filename() << " data " << FlatbufferToJson(msg);
1168 } else if (VLOG_IS_ON(2)) {
1169 SizePrefixedFlatbufferVector<MessageHeader> msg_copy = msg;
1170 msg_copy.mutable_message()->clear_data();
1171 VLOG(2) << "Read from " << filename() << " data "
1172 << FlatbufferToJson(msg_copy);
1173 }
1174
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001175 return result;
1176}
1177
1178std::shared_ptr<UnpackedMessageHeader> UnpackedMessageHeader::MakeMessage(
1179 const MessageHeader &message) {
1180 const size_t data_size = message.has_data() ? message.data()->size() : 0;
1181
1182 UnpackedMessageHeader *const unpacked_message =
1183 reinterpret_cast<UnpackedMessageHeader *>(
1184 malloc(sizeof(UnpackedMessageHeader) + data_size +
1185 kChannelDataAlignment - 1));
1186
1187 CHECK(message.has_channel_index());
1188 CHECK(message.has_monotonic_sent_time());
1189
1190 absl::Span<uint8_t> span;
1191 if (data_size > 0) {
1192 span =
1193 absl::Span<uint8_t>(reinterpret_cast<uint8_t *>(RoundChannelData(
1194 &unpacked_message->actual_data[0], data_size)),
1195 data_size);
1196 }
1197
Austin Schuh826e6ce2021-11-18 20:33:10 -08001198 std::optional<aos::monotonic_clock::time_point> monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001199 if (message.has_monotonic_remote_time()) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001200 monotonic_remote_time = aos::monotonic_clock::time_point(
1201 std::chrono::nanoseconds(message.monotonic_remote_time()));
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001202 }
1203 std::optional<realtime_clock::time_point> realtime_remote_time;
1204 if (message.has_realtime_remote_time()) {
1205 realtime_remote_time = realtime_clock::time_point(
1206 chrono::nanoseconds(message.realtime_remote_time()));
1207 }
1208
1209 std::optional<uint32_t> remote_queue_index;
1210 if (message.has_remote_queue_index()) {
1211 remote_queue_index = message.remote_queue_index();
1212 }
1213
James Kuszmaul9776b392023-01-14 14:08:08 -08001214 new (unpacked_message) UnpackedMessageHeader(
1215 message.channel_index(),
1216 monotonic_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001217 chrono::nanoseconds(message.monotonic_sent_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001218 realtime_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001219 chrono::nanoseconds(message.realtime_sent_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001220 message.queue_index(), monotonic_remote_time, realtime_remote_time,
1221 remote_queue_index,
1222 monotonic_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001223 std::chrono::nanoseconds(message.monotonic_timestamp_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001224 message.has_monotonic_timestamp_time(), span);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001225
1226 if (data_size > 0) {
1227 memcpy(span.data(), message.data()->data(), data_size);
1228 }
1229
1230 return std::shared_ptr<UnpackedMessageHeader>(unpacked_message,
1231 &DestroyAndFree);
Austin Schuh05b70472020-01-01 17:11:17 -08001232}
1233
Austin Schuhc41603c2020-10-11 16:17:37 -07001234PartsMessageReader::PartsMessageReader(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -07001235 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {
Brian Silvermanfee16972021-09-14 12:06:38 -07001236 if (parts_.parts.size() >= 2) {
1237 next_message_reader_.emplace(parts_.parts[1]);
1238 }
Austin Schuh48507722021-07-17 17:29:24 -07001239 ComputeBootCounts();
1240}
1241
1242void PartsMessageReader::ComputeBootCounts() {
1243 boot_counts_.assign(configuration::NodesCount(parts_.config.get()),
1244 std::nullopt);
1245
1246 // We have 3 vintages of log files with different amounts of information.
1247 if (log_file_header()->has_boot_uuids()) {
1248 // The new hotness with the boots explicitly listed out. We can use the log
1249 // file header to compute the boot count of all relevant nodes.
1250 CHECK_EQ(log_file_header()->boot_uuids()->size(), boot_counts_.size());
1251 size_t node_index = 0;
1252 for (const flatbuffers::String *boot_uuid :
1253 *log_file_header()->boot_uuids()) {
1254 CHECK(parts_.boots);
1255 if (boot_uuid->size() != 0) {
1256 auto it = parts_.boots->boot_count_map.find(boot_uuid->str());
1257 if (it != parts_.boots->boot_count_map.end()) {
1258 boot_counts_[node_index] = it->second;
1259 }
1260 } else if (parts().boots->boots[node_index].size() == 1u) {
1261 boot_counts_[node_index] = 0;
1262 }
1263 ++node_index;
1264 }
1265 } else {
1266 // Older multi-node logs which are guarenteed to have UUIDs logged, or
1267 // single node log files with boot UUIDs in the header. We only know how to
1268 // order certain boots in certain circumstances.
1269 if (configuration::MultiNode(parts_.config.get()) || parts_.boots) {
1270 for (size_t node_index = 0; node_index < boot_counts_.size();
1271 ++node_index) {
1272 CHECK(parts_.boots);
1273 if (parts().boots->boots[node_index].size() == 1u) {
1274 boot_counts_[node_index] = 0;
1275 }
1276 }
1277 } else {
1278 // Really old single node logs without any UUIDs. They can't reboot.
1279 CHECK_EQ(boot_counts_.size(), 1u);
1280 boot_counts_[0] = 0u;
1281 }
1282 }
1283}
Austin Schuhc41603c2020-10-11 16:17:37 -07001284
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001285std::shared_ptr<UnpackedMessageHeader> PartsMessageReader::ReadMessage() {
Austin Schuhc41603c2020-10-11 16:17:37 -07001286 while (!done_) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001287 std::shared_ptr<UnpackedMessageHeader> message =
Austin Schuhc41603c2020-10-11 16:17:37 -07001288 message_reader_.ReadMessage();
1289 if (message) {
1290 newest_timestamp_ = message_reader_.newest_timestamp();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001291 const monotonic_clock::time_point monotonic_sent_time =
1292 message->monotonic_sent_time;
1293
1294 // TODO(austin): Does this work with startup? Might need to use the
1295 // start time.
1296 // TODO(austin): Does this work with startup when we don't know the
1297 // remote start time too? Look at one of those logs to compare.
Austin Schuh315b96b2020-12-11 21:21:12 -08001298 if (monotonic_sent_time >
1299 parts_.monotonic_start_time + max_out_of_order_duration()) {
1300 after_start_ = true;
1301 }
1302 if (after_start_) {
Austin Schuhb000de62020-12-03 22:00:40 -08001303 CHECK_GE(monotonic_sent_time,
1304 newest_timestamp_ - max_out_of_order_duration())
Austin Schuha040c3f2021-02-13 16:09:07 -08001305 << ": Max out of order of " << max_out_of_order_duration().count()
1306 << "ns exceeded. " << parts_ << ", start time is "
Austin Schuh315b96b2020-12-11 21:21:12 -08001307 << parts_.monotonic_start_time << " currently reading "
1308 << filename();
Austin Schuhb000de62020-12-03 22:00:40 -08001309 }
Austin Schuhc41603c2020-10-11 16:17:37 -07001310 return message;
1311 }
1312 NextLog();
1313 }
Austin Schuh32f68492020-11-08 21:45:51 -08001314 newest_timestamp_ = monotonic_clock::max_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001315 return nullptr;
Austin Schuhc41603c2020-10-11 16:17:37 -07001316}
1317
1318void PartsMessageReader::NextLog() {
1319 if (next_part_index_ == parts_.parts.size()) {
Brian Silvermanfee16972021-09-14 12:06:38 -07001320 CHECK(!next_message_reader_);
Austin Schuhc41603c2020-10-11 16:17:37 -07001321 done_ = true;
1322 return;
1323 }
Brian Silvermanfee16972021-09-14 12:06:38 -07001324 CHECK(next_message_reader_);
1325 message_reader_ = std::move(*next_message_reader_);
Austin Schuh48507722021-07-17 17:29:24 -07001326 ComputeBootCounts();
Brian Silvermanfee16972021-09-14 12:06:38 -07001327 if (next_part_index_ + 1 < parts_.parts.size()) {
1328 next_message_reader_.emplace(parts_.parts[next_part_index_ + 1]);
1329 } else {
1330 next_message_reader_.reset();
1331 }
Austin Schuhc41603c2020-10-11 16:17:37 -07001332 ++next_part_index_;
1333}
1334
Austin Schuh1be0ce42020-11-29 22:43:26 -08001335bool Message::operator<(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001336 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001337
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001338 if (this->timestamp.time < m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -08001339 return true;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001340 } else if (this->timestamp.time > m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -08001341 return false;
1342 }
1343
1344 if (this->channel_index < m2.channel_index) {
1345 return true;
1346 } else if (this->channel_index > m2.channel_index) {
1347 return false;
1348 }
1349
1350 return this->queue_index < m2.queue_index;
1351}
1352
1353bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001354bool Message::operator==(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001355 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001356
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001357 return timestamp.time == m2.timestamp.time &&
1358 channel_index == m2.channel_index && queue_index == m2.queue_index;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001359}
Austin Schuh1be0ce42020-11-29 22:43:26 -08001360
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001361std::ostream &operator<<(std::ostream &os, const UnpackedMessageHeader &m) {
1362 os << "{.channel_index=" << m.channel_index
1363 << ", .monotonic_sent_time=" << m.monotonic_sent_time
1364 << ", .realtime_sent_time=" << m.realtime_sent_time
1365 << ", .queue_index=" << m.queue_index;
1366 if (m.monotonic_remote_time) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001367 os << ", .monotonic_remote_time=" << *m.monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001368 }
1369 os << ", .realtime_remote_time=";
1370 PrintOptionalOrNull(&os, m.realtime_remote_time);
1371 os << ", .remote_queue_index=";
1372 PrintOptionalOrNull(&os, m.remote_queue_index);
1373 if (m.has_monotonic_timestamp_time) {
1374 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
1375 }
Austin Schuh22cf7862022-09-19 19:09:42 -07001376 os << "}";
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001377 return os;
1378}
1379
Austin Schuh1be0ce42020-11-29 22:43:26 -08001380std::ostream &operator<<(std::ostream &os, const Message &m) {
1381 os << "{.channel_index=" << m.channel_index
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001382 << ", .queue_index=" << m.queue_index << ", .timestamp=" << m.timestamp;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001383 if (m.data != nullptr) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001384 if (m.data->remote_queue_index.has_value()) {
1385 os << ", .remote_queue_index=" << *m.data->remote_queue_index;
1386 }
1387 if (m.data->monotonic_remote_time.has_value()) {
1388 os << ", .monotonic_remote_time=" << *m.data->monotonic_remote_time;
1389 }
Austin Schuhfb1b3292021-11-16 21:20:15 -08001390 os << ", .data=" << m.data;
Austin Schuhd2f96102020-12-01 20:27:29 -08001391 }
1392 os << "}";
1393 return os;
1394}
1395
1396std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m) {
1397 os << "{.channel_index=" << m.channel_index
1398 << ", .queue_index=" << m.queue_index
1399 << ", .monotonic_event_time=" << m.monotonic_event_time
1400 << ", .realtime_event_time=" << m.realtime_event_time;
Austin Schuh58646e22021-08-23 23:51:46 -07001401 if (m.remote_queue_index != BootQueueIndex::Invalid()) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001402 os << ", .remote_queue_index=" << m.remote_queue_index;
1403 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001404 if (m.monotonic_remote_time != BootTimestamp::min_time()) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001405 os << ", .monotonic_remote_time=" << m.monotonic_remote_time;
1406 }
1407 if (m.realtime_remote_time != realtime_clock::min_time) {
1408 os << ", .realtime_remote_time=" << m.realtime_remote_time;
1409 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001410 if (m.monotonic_timestamp_time != BootTimestamp::min_time()) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001411 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
1412 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001413 if (m.data != nullptr) {
1414 os << ", .data=" << *m.data;
Austin Schuh22cf7862022-09-19 19:09:42 -07001415 } else {
1416 os << ", .data=nullptr";
Austin Schuhd2f96102020-12-01 20:27:29 -08001417 }
1418 os << "}";
Austin Schuh1be0ce42020-11-29 22:43:26 -08001419 return os;
1420}
1421
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001422LogPartsSorter::LogPartsSorter(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -07001423 : parts_message_reader_(log_parts),
1424 source_node_index_(configuration::SourceNodeIndex(parts().config.get())) {
1425}
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001426
1427Message *LogPartsSorter::Front() {
1428 // Queue up data until enough data has been queued that the front message is
1429 // sorted enough to be safe to pop. This may do nothing, so we should make
1430 // sure the nothing path is checked quickly.
1431 if (sorted_until() != monotonic_clock::max_time) {
1432 while (true) {
Austin Schuh48507722021-07-17 17:29:24 -07001433 if (!messages_.empty() &&
1434 messages_.begin()->timestamp.time < sorted_until() &&
Austin Schuhb000de62020-12-03 22:00:40 -08001435 sorted_until() >= monotonic_start_time()) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001436 break;
1437 }
1438
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001439 std::shared_ptr<UnpackedMessageHeader> m =
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001440 parts_message_reader_.ReadMessage();
1441 // No data left, sorted forever, work through what is left.
1442 if (!m) {
1443 sorted_until_ = monotonic_clock::max_time;
1444 break;
1445 }
1446
Austin Schuh48507722021-07-17 17:29:24 -07001447 size_t monotonic_timestamp_boot = 0;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001448 if (m->has_monotonic_timestamp_time) {
Austin Schuh48507722021-07-17 17:29:24 -07001449 monotonic_timestamp_boot = parts().logger_boot_count;
1450 }
1451 size_t monotonic_remote_boot = 0xffffff;
1452
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001453 if (m->monotonic_remote_time.has_value()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001454 const Node *node =
1455 parts().config->nodes()->Get(source_node_index_[m->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -07001456
Austin Schuh48507722021-07-17 17:29:24 -07001457 std::optional<size_t> boot = parts_message_reader_.boot_count(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001458 source_node_index_[m->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -07001459 CHECK(boot) << ": Failed to find boot for node " << MaybeNodeName(node)
Austin Schuh60e77942022-05-16 17:48:24 -07001460 << ", with index " << source_node_index_[m->channel_index];
Austin Schuh48507722021-07-17 17:29:24 -07001461 monotonic_remote_boot = *boot;
1462 }
1463
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001464 messages_.insert(
1465 Message{.channel_index = m->channel_index,
1466 .queue_index = BootQueueIndex{.boot = parts().boot_count,
1467 .index = m->queue_index},
1468 .timestamp = BootTimestamp{.boot = parts().boot_count,
1469 .time = m->monotonic_sent_time},
1470 .monotonic_remote_boot = monotonic_remote_boot,
1471 .monotonic_timestamp_boot = monotonic_timestamp_boot,
1472 .data = std::move(m)});
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001473
1474 // Now, update sorted_until_ to match the new message.
1475 if (parts_message_reader_.newest_timestamp() >
1476 monotonic_clock::min_time +
1477 parts_message_reader_.max_out_of_order_duration()) {
1478 sorted_until_ = parts_message_reader_.newest_timestamp() -
1479 parts_message_reader_.max_out_of_order_duration();
1480 } else {
1481 sorted_until_ = monotonic_clock::min_time;
1482 }
1483 }
1484 }
1485
1486 // Now that we have enough data queued, return a pointer to the oldest piece
1487 // of data if it exists.
1488 if (messages_.empty()) {
Austin Schuhb000de62020-12-03 22:00:40 -08001489 last_message_time_ = monotonic_clock::max_time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001490 return nullptr;
1491 }
1492
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001493 CHECK_GE(messages_.begin()->timestamp.time, last_message_time_)
Austin Schuh315b96b2020-12-11 21:21:12 -08001494 << DebugString() << " reading " << parts_message_reader_.filename();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001495 last_message_time_ = messages_.begin()->timestamp.time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001496 return &(*messages_.begin());
1497}
1498
1499void LogPartsSorter::PopFront() { messages_.erase(messages_.begin()); }
1500
1501std::string LogPartsSorter::DebugString() const {
1502 std::stringstream ss;
1503 ss << "messages: [\n";
Austin Schuh315b96b2020-12-11 21:21:12 -08001504 int count = 0;
1505 bool no_dots = true;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001506 for (const Message &m : messages_) {
Austin Schuh315b96b2020-12-11 21:21:12 -08001507 if (count < 15 || count > static_cast<int>(messages_.size()) - 15) {
1508 ss << m << "\n";
1509 } else if (no_dots) {
1510 ss << "...\n";
1511 no_dots = false;
1512 }
1513 ++count;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001514 }
1515 ss << "] <- " << parts_message_reader_.filename();
1516 return ss.str();
1517}
1518
Austin Schuhd2f96102020-12-01 20:27:29 -08001519NodeMerger::NodeMerger(std::vector<LogParts> parts) {
1520 CHECK_GE(parts.size(), 1u);
Austin Schuh715adc12021-06-29 22:07:39 -07001521 // Enforce that we are sorting things only from a single node from a single
1522 // boot.
1523 const std::string_view part0_node = parts[0].node;
1524 const std::string_view part0_source_boot_uuid = parts[0].source_boot_uuid;
Austin Schuhd2f96102020-12-01 20:27:29 -08001525 for (size_t i = 1; i < parts.size(); ++i) {
1526 CHECK_EQ(part0_node, parts[i].node) << ": Can't merge different nodes.";
Austin Schuh715adc12021-06-29 22:07:39 -07001527 CHECK_EQ(part0_source_boot_uuid, parts[i].source_boot_uuid)
1528 << ": Can't merge different boots.";
Austin Schuhd2f96102020-12-01 20:27:29 -08001529 }
Austin Schuh715adc12021-06-29 22:07:39 -07001530
1531 node_ = configuration::GetNodeIndex(parts[0].config.get(), part0_node);
1532
Austin Schuhd2f96102020-12-01 20:27:29 -08001533 for (LogParts &part : parts) {
1534 parts_sorters_.emplace_back(std::move(part));
1535 }
1536
Austin Schuhd2f96102020-12-01 20:27:29 -08001537 monotonic_start_time_ = monotonic_clock::max_time;
Austin Schuh9dc42612021-09-20 20:41:29 -07001538 realtime_start_time_ = realtime_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001539 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001540 // We want to capture the earliest meaningful start time here. The start
1541 // time defaults to min_time when there's no meaningful value to report, so
1542 // let's ignore those.
Austin Schuh9dc42612021-09-20 20:41:29 -07001543 if (parts_sorter.monotonic_start_time() != monotonic_clock::min_time) {
1544 bool accept = false;
1545 // We want to prioritize start times from the logger node. Really, we
1546 // want to prioritize start times with a valid realtime_clock time. So,
1547 // if we have a start time without a RT clock, prefer a start time with a
1548 // RT clock, even it if is later.
1549 if (parts_sorter.realtime_start_time() != realtime_clock::min_time) {
1550 // We've got a good one. See if the current start time has a good RT
1551 // clock, or if we should use this one instead.
1552 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
1553 accept = true;
1554 } else if (realtime_start_time_ == realtime_clock::min_time) {
1555 // The previous start time doesn't have a good RT time, so it is very
1556 // likely the start time from a remote part file. We just found a
1557 // better start time with a real RT time, so switch to that instead.
1558 accept = true;
1559 }
1560 } else if (realtime_start_time_ == realtime_clock::min_time) {
1561 // We don't have a RT time, so take the oldest.
1562 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
1563 accept = true;
1564 }
1565 }
1566
1567 if (accept) {
1568 monotonic_start_time_ = parts_sorter.monotonic_start_time();
1569 realtime_start_time_ = parts_sorter.realtime_start_time();
1570 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001571 }
1572 }
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001573
1574 // If there was no meaningful start time reported, just use min_time.
1575 if (monotonic_start_time_ == monotonic_clock::max_time) {
1576 monotonic_start_time_ = monotonic_clock::min_time;
1577 realtime_start_time_ = realtime_clock::min_time;
1578 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001579}
Austin Schuh8f52ed52020-11-30 23:12:39 -08001580
Austin Schuh0ca51f32020-12-25 21:51:45 -08001581std::vector<const LogParts *> NodeMerger::Parts() const {
1582 std::vector<const LogParts *> p;
1583 p.reserve(parts_sorters_.size());
1584 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
1585 p.emplace_back(&parts_sorter.parts());
1586 }
1587 return p;
1588}
1589
Austin Schuh8f52ed52020-11-30 23:12:39 -08001590Message *NodeMerger::Front() {
1591 // Return the current Front if we have one, otherwise go compute one.
1592 if (current_ != nullptr) {
Austin Schuhb000de62020-12-03 22:00:40 -08001593 Message *result = current_->Front();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001594 CHECK_GE(result->timestamp.time, last_message_time_);
Austin Schuhb000de62020-12-03 22:00:40 -08001595 return result;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001596 }
1597
1598 // Otherwise, do a simple search for the oldest message, deduplicating any
1599 // duplicates.
1600 Message *oldest = nullptr;
1601 sorted_until_ = monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001602 for (LogPartsSorter &parts_sorter : parts_sorters_) {
1603 Message *m = parts_sorter.Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -08001604 if (!m) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001605 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001606 continue;
1607 }
1608 if (oldest == nullptr || *m < *oldest) {
1609 oldest = m;
Austin Schuhd2f96102020-12-01 20:27:29 -08001610 current_ = &parts_sorter;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001611 } else if (*m == *oldest) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001612 // Found a duplicate. If there is a choice, we want the one which has
1613 // the timestamp time.
1614 if (!m->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001615 parts_sorter.PopFront();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001616 } else if (!oldest->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001617 current_->PopFront();
1618 current_ = &parts_sorter;
1619 oldest = m;
1620 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001621 CHECK_EQ(m->data->monotonic_timestamp_time,
1622 oldest->data->monotonic_timestamp_time);
Austin Schuh8bf1e632021-01-02 22:41:04 -08001623 parts_sorter.PopFront();
1624 }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001625 }
1626
1627 // PopFront may change this, so compute it down here.
Austin Schuhd2f96102020-12-01 20:27:29 -08001628 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001629 }
1630
Austin Schuhb000de62020-12-03 22:00:40 -08001631 if (oldest) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001632 CHECK_GE(oldest->timestamp.time, last_message_time_);
1633 last_message_time_ = oldest->timestamp.time;
Austin Schuh5dd22842021-11-17 16:09:39 -08001634 monotonic_oldest_time_ =
1635 std::min(monotonic_oldest_time_, oldest->timestamp.time);
Austin Schuhb000de62020-12-03 22:00:40 -08001636 } else {
1637 last_message_time_ = monotonic_clock::max_time;
1638 }
1639
Austin Schuh8f52ed52020-11-30 23:12:39 -08001640 // Return the oldest message found. This will be nullptr if nothing was
1641 // found, indicating there is nothing left.
1642 return oldest;
1643}
1644
1645void NodeMerger::PopFront() {
1646 CHECK(current_ != nullptr) << "Popping before calling Front()";
1647 current_->PopFront();
1648 current_ = nullptr;
1649}
1650
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001651BootMerger::BootMerger(std::vector<LogParts> files) {
1652 std::vector<std::vector<LogParts>> boots;
1653
1654 // Now, we need to split things out by boot.
1655 for (size_t i = 0; i < files.size(); ++i) {
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001656 const size_t boot_count = files[i].boot_count;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001657 if (boot_count + 1 > boots.size()) {
1658 boots.resize(boot_count + 1);
1659 }
1660 boots[boot_count].emplace_back(std::move(files[i]));
1661 }
1662
1663 node_mergers_.reserve(boots.size());
1664 for (size_t i = 0; i < boots.size(); ++i) {
Austin Schuh48507722021-07-17 17:29:24 -07001665 VLOG(2) << "Boot " << i;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001666 for (auto &p : boots[i]) {
Austin Schuh48507722021-07-17 17:29:24 -07001667 VLOG(2) << "Part " << p;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001668 }
1669 node_mergers_.emplace_back(
1670 std::make_unique<NodeMerger>(std::move(boots[i])));
1671 }
1672}
1673
1674Message *BootMerger::Front() {
1675 Message *result = node_mergers_[index_]->Front();
1676
1677 if (result != nullptr) {
1678 return result;
1679 }
1680
1681 if (index_ + 1u == node_mergers_.size()) {
1682 // At the end of the last node merger, just return.
1683 return nullptr;
1684 } else {
1685 ++index_;
1686 return Front();
1687 }
1688}
1689
1690void BootMerger::PopFront() { node_mergers_[index_]->PopFront(); }
1691
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001692std::vector<const LogParts *> BootMerger::Parts() const {
1693 std::vector<const LogParts *> results;
1694 for (const std::unique_ptr<NodeMerger> &node_merger : node_mergers_) {
1695 std::vector<const LogParts *> node_parts = node_merger->Parts();
1696
1697 results.insert(results.end(), std::make_move_iterator(node_parts.begin()),
1698 std::make_move_iterator(node_parts.end()));
1699 }
1700
1701 return results;
1702}
1703
Austin Schuhd2f96102020-12-01 20:27:29 -08001704TimestampMapper::TimestampMapper(std::vector<LogParts> parts)
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001705 : boot_merger_(std::move(parts)),
Austin Schuh79b30942021-01-24 22:32:21 -08001706 timestamp_callback_([](TimestampedMessage *) {}) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001707 for (const LogParts *part : boot_merger_.Parts()) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001708 if (!configuration_) {
1709 configuration_ = part->config;
1710 } else {
1711 CHECK_EQ(configuration_.get(), part->config.get());
1712 }
1713 }
1714 const Configuration *config = configuration_.get();
Austin Schuhd2f96102020-12-01 20:27:29 -08001715 // Only fill out nodes_data_ if there are nodes. Otherwise everything gets
1716 // pretty simple.
1717 if (configuration::MultiNode(config)) {
1718 nodes_data_.resize(config->nodes()->size());
1719 const Node *my_node = config->nodes()->Get(node());
1720 for (size_t node_index = 0; node_index < nodes_data_.size(); ++node_index) {
1721 const Node *node = config->nodes()->Get(node_index);
1722 NodeData *node_data = &nodes_data_[node_index];
1723 node_data->channels.resize(config->channels()->size());
1724 // We should save the channel if it is delivered to the node represented
1725 // by the NodeData, but not sent by that node. That combo means it is
1726 // forwarded.
1727 size_t channel_index = 0;
1728 node_data->any_delivered = false;
1729 for (const Channel *channel : *config->channels()) {
1730 node_data->channels[channel_index].delivered =
1731 configuration::ChannelIsReadableOnNode(channel, node) &&
Austin Schuhb3dbb6d2021-01-02 17:29:35 -08001732 configuration::ChannelIsSendableOnNode(channel, my_node) &&
1733 (my_node != node);
Austin Schuhd2f96102020-12-01 20:27:29 -08001734 node_data->any_delivered = node_data->any_delivered ||
1735 node_data->channels[channel_index].delivered;
Austin Schuh6a7358f2021-11-18 22:40:40 -08001736 if (node_data->channels[channel_index].delivered) {
1737 const Connection *connection =
1738 configuration::ConnectionToNode(channel, node);
1739 node_data->channels[channel_index].time_to_live =
1740 chrono::nanoseconds(connection->time_to_live());
1741 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001742 ++channel_index;
1743 }
1744 }
1745
1746 for (const Channel *channel : *config->channels()) {
1747 source_node_.emplace_back(configuration::GetNodeIndex(
1748 config, channel->source_node()->string_view()));
1749 }
1750 }
1751}
1752
1753void TimestampMapper::AddPeer(TimestampMapper *timestamp_mapper) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001754 CHECK(configuration::MultiNode(configuration()));
Austin Schuhd2f96102020-12-01 20:27:29 -08001755 CHECK_NE(timestamp_mapper->node(), node());
1756 CHECK_LT(timestamp_mapper->node(), nodes_data_.size());
1757
1758 NodeData *node_data = &nodes_data_[timestamp_mapper->node()];
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001759 // Only set it if this node delivers to the peer timestamp_mapper. Otherwise
Austin Schuhd2f96102020-12-01 20:27:29 -08001760 // we could needlessly save data.
1761 if (node_data->any_delivered) {
Austin Schuh87dd3832021-01-01 23:07:31 -08001762 VLOG(1) << "Registering on node " << node() << " for peer node "
1763 << timestamp_mapper->node();
Austin Schuhd2f96102020-12-01 20:27:29 -08001764 CHECK(timestamp_mapper->nodes_data_[node()].peer == nullptr);
1765
1766 timestamp_mapper->nodes_data_[node()].peer = this;
Austin Schuh36c00932021-07-19 18:13:21 -07001767
1768 node_data->save_for_peer = true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001769 }
1770}
1771
Austin Schuh79b30942021-01-24 22:32:21 -08001772void TimestampMapper::QueueMessage(Message *m) {
Austin Schuh60e77942022-05-16 17:48:24 -07001773 matched_messages_.emplace_back(
1774 TimestampedMessage{.channel_index = m->channel_index,
1775 .queue_index = m->queue_index,
1776 .monotonic_event_time = m->timestamp,
1777 .realtime_event_time = m->data->realtime_sent_time,
1778 .remote_queue_index = BootQueueIndex::Invalid(),
1779 .monotonic_remote_time = BootTimestamp::min_time(),
1780 .realtime_remote_time = realtime_clock::min_time,
1781 .monotonic_timestamp_time = BootTimestamp::min_time(),
1782 .data = std::move(m->data)});
Austin Schuhd2f96102020-12-01 20:27:29 -08001783}
1784
1785TimestampedMessage *TimestampMapper::Front() {
1786 // No need to fetch anything new. A previous message still exists.
1787 switch (first_message_) {
1788 case FirstMessage::kNeedsUpdate:
1789 break;
1790 case FirstMessage::kInMessage:
Austin Schuh79b30942021-01-24 22:32:21 -08001791 return &matched_messages_.front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001792 case FirstMessage::kNullptr:
1793 return nullptr;
1794 }
1795
Austin Schuh79b30942021-01-24 22:32:21 -08001796 if (matched_messages_.empty()) {
1797 if (!QueueMatched()) {
1798 first_message_ = FirstMessage::kNullptr;
1799 return nullptr;
1800 }
1801 }
1802 first_message_ = FirstMessage::kInMessage;
1803 return &matched_messages_.front();
1804}
1805
1806bool TimestampMapper::QueueMatched() {
Austin Schuhd2f96102020-12-01 20:27:29 -08001807 if (nodes_data_.empty()) {
1808 // Simple path. We are single node, so there are no timestamps to match!
1809 CHECK_EQ(messages_.size(), 0u);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001810 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001811 if (!m) {
Austin Schuh79b30942021-01-24 22:32:21 -08001812 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -08001813 }
Austin Schuh79b30942021-01-24 22:32:21 -08001814 // Enqueue this message into matched_messages_ so we have a place to
1815 // associate remote timestamps, and return it.
1816 QueueMessage(m);
Austin Schuhd2f96102020-12-01 20:27:29 -08001817
Austin Schuh79b30942021-01-24 22:32:21 -08001818 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1819 last_message_time_ = matched_messages_.back().monotonic_event_time;
1820
1821 // We are thin wrapper around node_merger. Call it directly.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001822 boot_merger_.PopFront();
Austin Schuh79b30942021-01-24 22:32:21 -08001823 timestamp_callback_(&matched_messages_.back());
1824 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001825 }
1826
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001827 // We need to only add messages to the list so they get processed for
1828 // messages which are delivered. Reuse the flow below which uses messages_
1829 // by just adding the new message to messages_ and continuing.
Austin Schuhd2f96102020-12-01 20:27:29 -08001830 if (messages_.empty()) {
1831 if (!Queue()) {
1832 // Found nothing to add, we are out of data!
Austin Schuh79b30942021-01-24 22:32:21 -08001833 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -08001834 }
1835
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001836 // Now that it has been added (and cannibalized), forget about it
1837 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001838 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08001839 }
1840
1841 Message *m = &(messages_.front());
1842
1843 if (source_node_[m->channel_index] == node()) {
1844 // From us, just forward it on, filling the remote data in as invalid.
Austin Schuh79b30942021-01-24 22:32:21 -08001845 QueueMessage(m);
1846 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1847 last_message_time_ = matched_messages_.back().monotonic_event_time;
1848 messages_.pop_front();
1849 timestamp_callback_(&matched_messages_.back());
1850 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001851 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001852 // Got a timestamp, find the matching remote data, match it, and return
1853 // it.
Austin Schuhd2f96102020-12-01 20:27:29 -08001854 Message data = MatchingMessageFor(*m);
1855
1856 // Return the data from the remote. The local message only has timestamp
1857 // info which isn't relevant anymore once extracted.
Austin Schuh79b30942021-01-24 22:32:21 -08001858 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -08001859 .channel_index = m->channel_index,
1860 .queue_index = m->queue_index,
1861 .monotonic_event_time = m->timestamp,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001862 .realtime_event_time = m->data->realtime_sent_time,
Austin Schuh58646e22021-08-23 23:51:46 -07001863 .remote_queue_index =
1864 BootQueueIndex{.boot = m->monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001865 .index = m->data->remote_queue_index.value()},
1866 .monotonic_remote_time = {m->monotonic_remote_boot,
Austin Schuh826e6ce2021-11-18 20:33:10 -08001867 m->data->monotonic_remote_time.value()},
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001868 .realtime_remote_time = m->data->realtime_remote_time.value(),
1869 .monotonic_timestamp_time = {m->monotonic_timestamp_boot,
1870 m->data->monotonic_timestamp_time},
Austin Schuh79b30942021-01-24 22:32:21 -08001871 .data = std::move(data.data)});
1872 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1873 last_message_time_ = matched_messages_.back().monotonic_event_time;
1874 // Since messages_ holds the data, drop it.
1875 messages_.pop_front();
1876 timestamp_callback_(&matched_messages_.back());
1877 return true;
1878 }
1879}
1880
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001881void TimestampMapper::QueueUntil(BootTimestamp queue_time) {
Austin Schuh79b30942021-01-24 22:32:21 -08001882 while (last_message_time_ <= queue_time) {
1883 if (!QueueMatched()) {
1884 return;
1885 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001886 }
1887}
1888
Austin Schuhe639ea12021-01-25 13:00:22 -08001889void TimestampMapper::QueueFor(chrono::nanoseconds time_estimation_buffer) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001890 // Note: queueing for time doesn't really work well across boots. So we
1891 // just assume that if you are using this, you only care about the current
1892 // boot.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001893 //
1894 // TODO(austin): Is that the right concept?
1895 //
Austin Schuhe639ea12021-01-25 13:00:22 -08001896 // Make sure we have something queued first. This makes the end time
1897 // calculation simpler, and is typically what folks want regardless.
1898 if (matched_messages_.empty()) {
1899 if (!QueueMatched()) {
1900 return;
1901 }
1902 }
1903
1904 const aos::monotonic_clock::time_point end_queue_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001905 std::max(monotonic_start_time(
1906 matched_messages_.front().monotonic_event_time.boot),
1907 matched_messages_.front().monotonic_event_time.time) +
Austin Schuhe639ea12021-01-25 13:00:22 -08001908 time_estimation_buffer;
1909
1910 // Place sorted messages on the list until we have
1911 // --time_estimation_buffer_seconds seconds queued up (but queue at least
1912 // until the log starts).
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001913 while (end_queue_time >= last_message_time_.time) {
Austin Schuhe639ea12021-01-25 13:00:22 -08001914 if (!QueueMatched()) {
1915 return;
1916 }
1917 }
1918}
1919
Austin Schuhd2f96102020-12-01 20:27:29 -08001920void TimestampMapper::PopFront() {
1921 CHECK(first_message_ != FirstMessage::kNeedsUpdate);
Austin Schuh6a7358f2021-11-18 22:40:40 -08001922 last_popped_message_time_ = Front()->monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001923 first_message_ = FirstMessage::kNeedsUpdate;
1924
Austin Schuh79b30942021-01-24 22:32:21 -08001925 matched_messages_.pop_front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001926}
1927
1928Message TimestampMapper::MatchingMessageFor(const Message &message) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001929 // Figure out what queue index we are looking for.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001930 CHECK_NOTNULL(message.data);
1931 CHECK(message.data->remote_queue_index.has_value());
Austin Schuh58646e22021-08-23 23:51:46 -07001932 const BootQueueIndex remote_queue_index =
1933 BootQueueIndex{.boot = message.monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001934 .index = *message.data->remote_queue_index};
Austin Schuhd2f96102020-12-01 20:27:29 -08001935
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001936 CHECK(message.data->monotonic_remote_time.has_value());
1937 CHECK(message.data->realtime_remote_time.has_value());
Austin Schuhd2f96102020-12-01 20:27:29 -08001938
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001939 const BootTimestamp monotonic_remote_time{
Austin Schuh48507722021-07-17 17:29:24 -07001940 .boot = message.monotonic_remote_boot,
Austin Schuh826e6ce2021-11-18 20:33:10 -08001941 .time = message.data->monotonic_remote_time.value()};
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001942 const realtime_clock::time_point realtime_remote_time =
1943 *message.data->realtime_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001944
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001945 TimestampMapper *peer =
1946 nodes_data_[source_node_[message.data->channel_index]].peer;
Austin Schuhfecf1d82020-12-19 16:57:28 -08001947
1948 // We only register the peers which we have data for. So, if we are being
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001949 // asked to pull a timestamp from a peer which doesn't exist, return an
1950 // empty message.
Austin Schuhfecf1d82020-12-19 16:57:28 -08001951 if (peer == nullptr) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001952 // TODO(austin): Make sure the tests hit all these paths with a boot count
1953 // of 1...
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001954 return Message{.channel_index = message.channel_index,
1955 .queue_index = remote_queue_index,
1956 .timestamp = monotonic_remote_time,
1957 .monotonic_remote_boot = 0xffffff,
1958 .monotonic_timestamp_boot = 0xffffff,
1959 .data = nullptr};
Austin Schuhfecf1d82020-12-19 16:57:28 -08001960 }
1961
1962 // The queue which will have the matching data, if available.
1963 std::deque<Message> *data_queue =
1964 &peer->nodes_data_[node()].channels[message.channel_index].messages;
1965
Austin Schuh79b30942021-01-24 22:32:21 -08001966 peer->QueueUnmatchedUntil(monotonic_remote_time);
Austin Schuhd2f96102020-12-01 20:27:29 -08001967
1968 if (data_queue->empty()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001969 return Message{.channel_index = message.channel_index,
1970 .queue_index = remote_queue_index,
1971 .timestamp = monotonic_remote_time,
1972 .monotonic_remote_boot = 0xffffff,
1973 .monotonic_timestamp_boot = 0xffffff,
1974 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08001975 }
1976
Austin Schuhd2f96102020-12-01 20:27:29 -08001977 if (remote_queue_index < data_queue->front().queue_index ||
1978 remote_queue_index > data_queue->back().queue_index) {
Austin Schuh60e77942022-05-16 17:48:24 -07001979 return Message{.channel_index = message.channel_index,
1980 .queue_index = remote_queue_index,
1981 .timestamp = monotonic_remote_time,
1982 .monotonic_remote_boot = 0xffffff,
1983 .monotonic_timestamp_boot = 0xffffff,
1984 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08001985 }
1986
Austin Schuh993ccb52020-12-12 15:59:32 -08001987 // The algorithm below is constant time with some assumptions. We need there
1988 // to be no missing messages in the data stream. This also assumes a queue
1989 // hasn't wrapped. That is conservative, but should let us get started.
Austin Schuh58646e22021-08-23 23:51:46 -07001990 if (data_queue->back().queue_index.boot ==
1991 data_queue->front().queue_index.boot &&
1992 (data_queue->back().queue_index.index -
1993 data_queue->front().queue_index.index + 1u ==
1994 data_queue->size())) {
1995 CHECK_EQ(remote_queue_index.boot, data_queue->front().queue_index.boot);
Austin Schuh993ccb52020-12-12 15:59:32 -08001996 // Pull the data out and confirm that the timestamps match as expected.
Austin Schuh58646e22021-08-23 23:51:46 -07001997 //
1998 // TODO(austin): Move if not reliable.
1999 Message result = (*data_queue)[remote_queue_index.index -
2000 data_queue->front().queue_index.index];
Austin Schuh993ccb52020-12-12 15:59:32 -08002001
2002 CHECK_EQ(result.timestamp, monotonic_remote_time)
2003 << ": Queue index matches, but timestamp doesn't. Please investigate!";
Austin Schuh6a7358f2021-11-18 22:40:40 -08002004 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
Austin Schuh993ccb52020-12-12 15:59:32 -08002005 << ": Queue index matches, but timestamp doesn't. Please investigate!";
2006 // Now drop the data off the front. We have deduplicated timestamps, so we
2007 // are done. And all the data is in order.
Austin Schuh58646e22021-08-23 23:51:46 -07002008 data_queue->erase(
2009 data_queue->begin(),
2010 data_queue->begin() +
2011 (remote_queue_index.index - data_queue->front().queue_index.index));
Austin Schuh993ccb52020-12-12 15:59:32 -08002012 return result;
2013 } else {
Austin Schuh58646e22021-08-23 23:51:46 -07002014 // TODO(austin): Binary search.
2015 auto it = std::find_if(
2016 data_queue->begin(), data_queue->end(),
2017 [remote_queue_index,
2018 remote_boot = monotonic_remote_time.boot](const Message &m) {
2019 return m.queue_index == remote_queue_index &&
2020 m.timestamp.boot == remote_boot;
2021 });
Austin Schuh993ccb52020-12-12 15:59:32 -08002022 if (it == data_queue->end()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002023 return Message{.channel_index = message.channel_index,
2024 .queue_index = remote_queue_index,
2025 .timestamp = monotonic_remote_time,
2026 .monotonic_remote_boot = 0xffffff,
2027 .monotonic_timestamp_boot = 0xffffff,
2028 .data = nullptr};
Austin Schuh993ccb52020-12-12 15:59:32 -08002029 }
2030
2031 Message result = std::move(*it);
2032
2033 CHECK_EQ(result.timestamp, monotonic_remote_time)
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002034 << ": Queue index matches, but timestamp doesn't. Please "
2035 "investigate!";
2036 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
2037 << ": Queue index matches, but timestamp doesn't. Please "
2038 "investigate!";
Austin Schuh993ccb52020-12-12 15:59:32 -08002039
Austin Schuhd6b1f4c2021-11-18 20:29:00 -08002040 // Erase everything up to this message. We want to keep 1 message in the
2041 // queue so we can handle reliable messages forwarded across boots.
2042 data_queue->erase(data_queue->begin(), it);
Austin Schuh993ccb52020-12-12 15:59:32 -08002043
2044 return result;
2045 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002046}
2047
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002048void TimestampMapper::QueueUnmatchedUntil(BootTimestamp t) {
Austin Schuhd2f96102020-12-01 20:27:29 -08002049 if (queued_until_ > t) {
2050 return;
2051 }
2052 while (true) {
2053 if (!messages_.empty() && messages_.back().timestamp > t) {
2054 queued_until_ = std::max(queued_until_, messages_.back().timestamp);
2055 return;
2056 }
2057
2058 if (!Queue()) {
2059 // Found nothing to add, we are out of data!
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002060 queued_until_ = BootTimestamp::max_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08002061 return;
2062 }
2063
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002064 // Now that it has been added (and cannibalized), forget about it
2065 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002066 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08002067 }
2068}
2069
2070bool TimestampMapper::Queue() {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002071 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002072 if (m == nullptr) {
2073 return false;
2074 }
2075 for (NodeData &node_data : nodes_data_) {
2076 if (!node_data.any_delivered) continue;
Austin Schuh36c00932021-07-19 18:13:21 -07002077 if (!node_data.save_for_peer) continue;
Austin Schuhd2f96102020-12-01 20:27:29 -08002078 if (node_data.channels[m->channel_index].delivered) {
Austin Schuh6a7358f2021-11-18 22:40:40 -08002079 // If we have data but no timestamps (logs where the timestamps didn't get
2080 // logged are classic), we can grow this indefinitely. We don't need to
2081 // keep anything that is older than the last message returned.
2082
2083 // We have the time on the source node.
2084 // We care to wait until we have the time on the destination node.
2085 std::deque<Message> &messages =
2086 node_data.channels[m->channel_index].messages;
2087 // Max delay over the network is the TTL, so let's take the queue time and
2088 // add TTL to it. Don't forget any messages which are reliable until
2089 // someone can come up with a good reason to forget those too.
2090 if (node_data.channels[m->channel_index].time_to_live >
2091 chrono::nanoseconds(0)) {
2092 // We need to make *some* assumptions about network delay for this to
2093 // work. We want to only look at the RX side. This means we need to
2094 // track the last time a message was popped from any channel from the
2095 // node sending this message, and compare that to the max time we expect
2096 // that a message will take to be delivered across the network. This
2097 // assumes that messages are popped in time order as a proxy for
2098 // measuring the distributed time at this layer.
2099 //
2100 // Leave at least 1 message in here so we can handle reboots and
2101 // messages getting sent twice.
2102 while (messages.size() > 1u &&
2103 messages.begin()->timestamp +
2104 node_data.channels[m->channel_index].time_to_live +
2105 chrono::duration_cast<chrono::nanoseconds>(
2106 chrono::duration<double>(FLAGS_max_network_delay)) <
2107 last_popped_message_time_) {
2108 messages.pop_front();
2109 }
2110 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002111 node_data.channels[m->channel_index].messages.emplace_back(*m);
2112 }
2113 }
2114
2115 messages_.emplace_back(std::move(*m));
2116 return true;
2117}
2118
2119std::string TimestampMapper::DebugString() const {
2120 std::stringstream ss;
Austin Schuh6e014b82021-09-14 17:46:33 -07002121 ss << "node " << node() << " (" << node_name() << ") [\n";
Austin Schuhd2f96102020-12-01 20:27:29 -08002122 for (const Message &message : messages_) {
2123 ss << " " << message << "\n";
2124 }
2125 ss << "] queued_until " << queued_until_;
2126 for (const NodeData &ns : nodes_data_) {
2127 if (ns.peer == nullptr) continue;
2128 ss << "\nnode " << ns.peer->node() << " remote_data [\n";
2129 size_t channel_index = 0;
2130 for (const NodeData::ChannelData &channel_data :
2131 ns.peer->nodes_data_[node()].channels) {
2132 if (channel_data.messages.empty()) {
2133 continue;
2134 }
Austin Schuhb000de62020-12-03 22:00:40 -08002135
Austin Schuhd2f96102020-12-01 20:27:29 -08002136 ss << " channel " << channel_index << " [\n";
2137 for (const Message &m : channel_data.messages) {
2138 ss << " " << m << "\n";
2139 }
2140 ss << " ]\n";
2141 ++channel_index;
2142 }
2143 ss << "] queued_until " << ns.peer->queued_until_;
2144 }
2145 return ss.str();
2146}
2147
Austin Schuhee711052020-08-24 16:06:09 -07002148std::string MaybeNodeName(const Node *node) {
2149 if (node != nullptr) {
2150 return node->name()->str() + " ";
2151 }
2152 return "";
2153}
2154
Brian Silvermanf51499a2020-09-21 12:49:08 -07002155} // namespace aos::logger