blob: 0918545fce08a062717b37ebd1b67e9821700aa7 [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
Austin Schuh7ef11a42023-02-04 17:15:12 -0800132void DetachedBufferWriter::CopyMessage(DataEncoder::Copier *coppier,
133 aos::monotonic_clock::time_point now) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -0700134 if (ran_out_of_space_) {
135 // We don't want any later data to be written after space becomes
136 // available, so refuse to write anything more once we've dropped data
137 // because we ran out of space.
Austin Schuh48d10d62022-10-16 22:19:23 -0700138 return;
Austin Schuha36c8902019-12-30 18:07:15 -0800139 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700140
Austin Schuh48d10d62022-10-16 22:19:23 -0700141 if (!encoder_->HasSpace(coppier->size())) {
142 Flush();
143 CHECK(encoder_->HasSpace(coppier->size()));
144 }
145
146 encoder_->Encode(coppier);
Austin Schuhbd06ae42021-03-31 22:48:21 -0700147 FlushAtThreshold(now);
Austin Schuha36c8902019-12-30 18:07:15 -0800148}
149
Brian Silverman0465fcf2020-09-24 00:29:18 -0700150void DetachedBufferWriter::Close() {
151 if (fd_ == -1) {
152 return;
153 }
154 encoder_->Finish();
155 while (encoder_->queue_size() > 0) {
156 Flush();
157 }
158 if (close(fd_) == -1) {
159 if (errno == ENOSPC) {
160 ran_out_of_space_ = true;
161 } else {
162 PLOG(ERROR) << "Closing log file failed";
163 }
164 }
165 fd_ = -1;
Austin Schuh58646e22021-08-23 23:51:46 -0700166 VLOG(1) << "Closed " << filename();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700167}
168
Austin Schuha36c8902019-12-30 18:07:15 -0800169void DetachedBufferWriter::Flush() {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700170 if (ran_out_of_space_) {
171 // We don't want any later data to be written after space becomes available,
172 // so refuse to write anything more once we've dropped data because we ran
173 // out of space.
Austin Schuha426f1f2021-03-31 22:27:41 -0700174 if (encoder_) {
175 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
176 encoder_->Clear(encoder_->queue().size());
177 } else {
178 VLOG(1) << "No queue to ignore";
179 }
180 return;
181 }
182
183 const auto queue = encoder_->queue();
184 if (queue.empty()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700185 return;
186 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700187
Austin Schuha36c8902019-12-30 18:07:15 -0800188 iovec_.clear();
Brian Silvermanf51499a2020-09-21 12:49:08 -0700189 const size_t iovec_size = std::min<size_t>(queue.size(), IOV_MAX);
190 iovec_.resize(iovec_size);
Austin Schuha36c8902019-12-30 18:07:15 -0800191 size_t counted_size = 0;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700192 for (size_t i = 0; i < iovec_size; ++i) {
193 iovec_[i].iov_base = const_cast<uint8_t *>(queue[i].data());
194 iovec_[i].iov_len = queue[i].size();
195 counted_size += iovec_[i].iov_len;
Austin Schuha36c8902019-12-30 18:07:15 -0800196 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700197
198 const auto start = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800199 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700200 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700201 HandleWriteReturn(written, counted_size);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700202
203 encoder_->Clear(iovec_size);
204
205 UpdateStatsForWrite(end - start, written, iovec_size);
206}
207
Brian Silverman0465fcf2020-09-24 00:29:18 -0700208void DetachedBufferWriter::HandleWriteReturn(ssize_t write_return,
209 size_t write_size) {
210 if (write_return == -1 && errno == ENOSPC) {
211 ran_out_of_space_ = true;
212 return;
213 }
214 PCHECK(write_return >= 0) << ": write failed";
215 if (write_return < static_cast<ssize_t>(write_size)) {
216 // Sometimes this happens instead of ENOSPC. On a real filesystem, this
217 // never seems to happen in any other case. If we ever want to log to a
218 // socket, this will happen more often. However, until we get there, we'll
219 // just assume it means we ran out of space.
220 ran_out_of_space_ = true;
221 return;
222 }
223}
224
Brian Silvermanf51499a2020-09-21 12:49:08 -0700225void DetachedBufferWriter::UpdateStatsForWrite(
226 aos::monotonic_clock::duration duration, ssize_t written, int iovec_size) {
227 if (duration > max_write_time_) {
228 max_write_time_ = duration;
229 max_write_time_bytes_ = written;
230 max_write_time_messages_ = iovec_size;
231 }
232 total_write_time_ += duration;
233 ++total_write_count_;
234 total_write_messages_ += iovec_size;
235 total_write_bytes_ += written;
236}
237
Austin Schuhbd06ae42021-03-31 22:48:21 -0700238void DetachedBufferWriter::FlushAtThreshold(
239 aos::monotonic_clock::time_point now) {
Austin Schuha426f1f2021-03-31 22:27:41 -0700240 if (ran_out_of_space_) {
241 // We don't want any later data to be written after space becomes available,
242 // so refuse to write anything more once we've dropped data because we ran
243 // out of space.
244 if (encoder_) {
245 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
246 encoder_->Clear(encoder_->queue().size());
247 } else {
248 VLOG(1) << "No queue to ignore";
249 }
250 return;
251 }
252
Austin Schuhbd06ae42021-03-31 22:48:21 -0700253 // We don't want to flush the first time through. Otherwise we will flush as
254 // the log file header might be compressing, defeating any parallelism and
255 // queueing there.
256 if (last_flush_time_ == aos::monotonic_clock::min_time) {
257 last_flush_time_ = now;
258 }
259
Brian Silvermanf51499a2020-09-21 12:49:08 -0700260 // Flush if we are at the max number of iovs per writev, because there's no
261 // point queueing up any more data in memory. Also flush once we have enough
Austin Schuhbd06ae42021-03-31 22:48:21 -0700262 // data queued up or if it has been long enough.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700263 while (encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
Austin Schuhbd06ae42021-03-31 22:48:21 -0700264 encoder_->queue_size() >= IOV_MAX ||
265 now > last_flush_time_ +
266 chrono::duration_cast<chrono::nanoseconds>(
267 chrono::duration<double>(FLAGS_flush_period))) {
268 last_flush_time_ = now;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700269 Flush();
270 }
Austin Schuha36c8902019-12-30 18:07:15 -0800271}
272
Austin Schuhf2d0e682022-10-16 14:20:58 -0700273// Do the magic dance to convert the endianness of the data and append it to the
274// buffer.
275namespace {
276
277// TODO(austin): Look at the generated code to see if building the header is
278// efficient or not.
279template <typename T>
280uint8_t *Push(uint8_t *buffer, const T data) {
281 const T endian_data = flatbuffers::EndianScalar<T>(data);
282 std::memcpy(buffer, &endian_data, sizeof(T));
283 return buffer + sizeof(T);
284}
285
286uint8_t *PushBytes(uint8_t *buffer, const void *data, size_t size) {
287 std::memcpy(buffer, data, size);
288 return buffer + size;
289}
290
291uint8_t *Pad(uint8_t *buffer, size_t padding) {
292 std::memset(buffer, 0, padding);
293 return buffer + padding;
294}
295} // namespace
296
297flatbuffers::Offset<MessageHeader> PackRemoteMessage(
298 flatbuffers::FlatBufferBuilder *fbb,
299 const message_bridge::RemoteMessage *msg, int channel_index,
300 const aos::monotonic_clock::time_point monotonic_timestamp_time) {
301 logger::MessageHeader::Builder message_header_builder(*fbb);
302 // Note: this must match the same order as MessageBridgeServer and
303 // PackMessage. We want identical headers to have identical
304 // on-the-wire formats to make comparing them easier.
305
306 message_header_builder.add_channel_index(channel_index);
307
308 message_header_builder.add_queue_index(msg->queue_index());
309 message_header_builder.add_monotonic_sent_time(msg->monotonic_sent_time());
310 message_header_builder.add_realtime_sent_time(msg->realtime_sent_time());
311
312 message_header_builder.add_monotonic_remote_time(
313 msg->monotonic_remote_time());
314 message_header_builder.add_realtime_remote_time(msg->realtime_remote_time());
315 message_header_builder.add_remote_queue_index(msg->remote_queue_index());
316
317 message_header_builder.add_monotonic_timestamp_time(
318 monotonic_timestamp_time.time_since_epoch().count());
319
320 return message_header_builder.Finish();
321}
322
323size_t PackRemoteMessageInline(
324 uint8_t *buffer, const message_bridge::RemoteMessage *msg,
325 int channel_index,
Austin Schuh71a40d42023-02-04 21:22:22 -0800326 const aos::monotonic_clock::time_point monotonic_timestamp_time,
327 size_t start_byte, size_t end_byte) {
Austin Schuhf2d0e682022-10-16 14:20:58 -0700328 const flatbuffers::uoffset_t message_size = PackRemoteMessageSize();
Austin Schuh71a40d42023-02-04 21:22:22 -0800329 DCHECK_EQ((start_byte % 8u), 0u);
330 DCHECK_EQ((end_byte % 8u), 0u);
331 DCHECK_LE(start_byte, end_byte);
332 DCHECK_LE(end_byte, message_size);
Austin Schuhf2d0e682022-10-16 14:20:58 -0700333
Austin Schuh71a40d42023-02-04 21:22:22 -0800334 switch (start_byte) {
335 case 0x00u:
336 if ((end_byte) == 0x00u) {
337 break;
338 }
339 // clang-format off
340 // header:
341 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
342 buffer = Push<flatbuffers::uoffset_t>(
343 buffer, message_size - sizeof(flatbuffers::uoffset_t));
344 // +0x04 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: +0x24 | offset to root table `aos.logger.MessageHeader`
345 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x20);
346 [[fallthrough]];
347 case 0x08u:
348 if ((end_byte) == 0x08u) {
349 break;
350 }
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 [[fallthrough]];
360 case 0x10u:
361 if ((end_byte) == 0x10u) {
362 break;
363 }
364 // +0x10 | 3C 00 | uint16_t | 0x003C (60) | size of referring table
365 buffer = Push<flatbuffers::voffset_t>(buffer, 0x3c);
366 // +0x12 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `channel_index` (id: 0)
367 buffer = Push<flatbuffers::voffset_t>(buffer, 0x38);
368 // +0x14 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `monotonic_sent_time` (id: 1)
369 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
370 // +0x16 | 24 00 | VOffset16 | 0x0024 (36) | offset to field `realtime_sent_time` (id: 2)
371 buffer = Push<flatbuffers::voffset_t>(buffer, 0x24);
372 [[fallthrough]];
373 case 0x18u:
374 if ((end_byte) == 0x18u) {
375 break;
376 }
377 // +0x18 | 34 00 | VOffset16 | 0x0034 (52) | offset to field `queue_index` (id: 3)
378 buffer = Push<flatbuffers::voffset_t>(buffer, 0x34);
379 // +0x1A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `data` (id: 4) <null> (Vector)
380 buffer = Push<flatbuffers::voffset_t>(buffer, 0x00);
381 // +0x1C | 1C 00 | VOffset16 | 0x001C (28) | offset to field `monotonic_remote_time` (id: 5)
382 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
383 // +0x1E | 14 00 | VOffset16 | 0x0014 (20) | offset to field `realtime_remote_time` (id: 6)
384 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
385 [[fallthrough]];
386 case 0x20u:
387 if ((end_byte) == 0x20u) {
388 break;
389 }
390 // +0x20 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `remote_queue_index` (id: 7)
391 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
392 // +0x22 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `monotonic_timestamp_time` (id: 8)
393 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
394 //
395 // root_table (aos.logger.MessageHeader):
396 // +0x24 | 16 00 00 00 | SOffset32 | 0x00000016 (22) Loc: +0x0E | offset to vtable
397 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x16);
398 [[fallthrough]];
399 case 0x28u:
400 if ((end_byte) == 0x28u) {
401 break;
402 }
403 // +0x28 | F6 0B D8 11 A4 A8 B1 71 | int64_t | 0x71B1A8A411D80BF6 (8192514619791117302) | table field `monotonic_timestamp_time` (Long)
404 buffer = Push<int64_t>(buffer,
405 monotonic_timestamp_time.time_since_epoch().count());
406 [[fallthrough]];
407 case 0x30u:
408 if ((end_byte) == 0x30u) {
409 break;
410 }
411 // +0x30 | 00 00 00 00 | uint8_t[4] | .... | padding
412 // TODO(austin): Can we re-arrange the order to ditch the padding?
413 // (Answer is yes, but what is the impact elsewhere? It will change the
414 // binary format)
415 buffer = Pad(buffer, 4);
416 // +0x34 | 75 00 00 00 | uint32_t | 0x00000075 (117) | table field `remote_queue_index` (UInt)
417 buffer = Push<uint32_t>(buffer, msg->remote_queue_index());
418 [[fallthrough]];
419 case 0x38u:
420 if ((end_byte) == 0x38u) {
421 break;
422 }
423 // +0x38 | AA B0 43 0A 35 BE FA D2 | int64_t | 0xD2FABE350A43B0AA (-3244071446552268630) | table field `realtime_remote_time` (Long)
424 buffer = Push<int64_t>(buffer, msg->realtime_remote_time());
425 [[fallthrough]];
426 case 0x40u:
427 if ((end_byte) == 0x40u) {
428 break;
429 }
430 // +0x40 | D5 40 30 F3 C1 A7 26 1D | int64_t | 0x1D26A7C1F33040D5 (2100550727665467605) | table field `monotonic_remote_time` (Long)
431 buffer = Push<int64_t>(buffer, msg->monotonic_remote_time());
432 [[fallthrough]];
433 case 0x48u:
434 if ((end_byte) == 0x48u) {
435 break;
436 }
437 // +0x48 | 5B 25 32 A1 4A E8 46 CA | int64_t | 0xCA46E84AA132255B (-3871151422448720549) | table field `realtime_sent_time` (Long)
438 buffer = Push<int64_t>(buffer, msg->realtime_sent_time());
439 [[fallthrough]];
440 case 0x50u:
441 if ((end_byte) == 0x50u) {
442 break;
443 }
444 // +0x50 | 49 7D 45 1F 8C 36 6B A3 | int64_t | 0xA36B368C1F457D49 (-6671178447571288759) | table field `monotonic_sent_time` (Long)
445 buffer = Push<int64_t>(buffer, msg->monotonic_sent_time());
446 [[fallthrough]];
447 case 0x58u:
448 if ((end_byte) == 0x58u) {
449 break;
450 }
451 // +0x58 | 33 00 00 00 | uint32_t | 0x00000033 (51) | table field `queue_index` (UInt)
452 buffer = Push<uint32_t>(buffer, msg->queue_index());
453 // +0x5C | 76 00 00 00 | uint32_t | 0x00000076 (118) | table field `channel_index` (UInt)
454 buffer = Push<uint32_t>(buffer, channel_index);
455 // clang-format on
456 [[fallthrough]];
457 case 0x60u:
458 if ((end_byte) == 0x60u) {
459 break;
460 }
461 }
Austin Schuhf2d0e682022-10-16 14:20:58 -0700462
Austin Schuh71a40d42023-02-04 21:22:22 -0800463 return end_byte - start_byte;
Austin Schuhf2d0e682022-10-16 14:20:58 -0700464}
465
Austin Schuha36c8902019-12-30 18:07:15 -0800466flatbuffers::Offset<MessageHeader> PackMessage(
467 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
468 int channel_index, LogType log_type) {
469 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
470
471 switch (log_type) {
472 case LogType::kLogMessage:
473 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800474 case LogType::kLogRemoteMessage:
Austin Schuhfa30c352022-10-16 11:12:02 -0700475 // Since the timestamps are 8 byte aligned, we are going to end up adding
476 // padding in the middle of the message to pad everything out to 8 byte
477 // alignment. That's rather wasteful. To make things efficient to mmap
478 // while reading uncompressed logs, we'd actually rather the message be
479 // aligned. So, force 8 byte alignment (enough to preserve alignment
480 // inside the nested message so that we can read it without moving it)
481 // here.
482 fbb->ForceVectorAlignment(context.size, sizeof(uint8_t), 8);
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700483 data_offset = fbb->CreateVector(
484 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800485 break;
486
487 case LogType::kLogDeliveryTimeOnly:
488 break;
489 }
490
491 MessageHeader::Builder message_header_builder(*fbb);
492 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800493
Austin Schuhfa30c352022-10-16 11:12:02 -0700494 // These are split out into very explicit serialization calls because the
495 // order here changes the order things are written out on the wire, and we
496 // want to control and understand it here. Changing the order can increase
497 // the amount of padding bytes in the middle.
498 //
James Kuszmaul9776b392023-01-14 14:08:08 -0800499 // It is also easier to follow... And doesn't actually make things much
500 // bigger.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800501 switch (log_type) {
502 case LogType::kLogRemoteMessage:
503 message_header_builder.add_queue_index(context.remote_queue_index);
Austin Schuhfa30c352022-10-16 11:12:02 -0700504 message_header_builder.add_data(data_offset);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800505 message_header_builder.add_monotonic_sent_time(
506 context.monotonic_remote_time.time_since_epoch().count());
507 message_header_builder.add_realtime_sent_time(
508 context.realtime_remote_time.time_since_epoch().count());
509 break;
510
Austin Schuh6f3babe2020-01-26 20:34:50 -0800511 case LogType::kLogDeliveryTimeOnly:
512 message_header_builder.add_queue_index(context.queue_index);
513 message_header_builder.add_monotonic_sent_time(
514 context.monotonic_event_time.time_since_epoch().count());
515 message_header_builder.add_realtime_sent_time(
516 context.realtime_event_time.time_since_epoch().count());
Austin Schuha36c8902019-12-30 18:07:15 -0800517 message_header_builder.add_monotonic_remote_time(
518 context.monotonic_remote_time.time_since_epoch().count());
519 message_header_builder.add_realtime_remote_time(
520 context.realtime_remote_time.time_since_epoch().count());
521 message_header_builder.add_remote_queue_index(context.remote_queue_index);
522 break;
Austin Schuhfa30c352022-10-16 11:12:02 -0700523
524 case LogType::kLogMessage:
525 message_header_builder.add_queue_index(context.queue_index);
526 message_header_builder.add_data(data_offset);
527 message_header_builder.add_monotonic_sent_time(
528 context.monotonic_event_time.time_since_epoch().count());
529 message_header_builder.add_realtime_sent_time(
530 context.realtime_event_time.time_since_epoch().count());
531 break;
532
533 case LogType::kLogMessageAndDeliveryTime:
534 message_header_builder.add_queue_index(context.queue_index);
535 message_header_builder.add_remote_queue_index(context.remote_queue_index);
536 message_header_builder.add_monotonic_sent_time(
537 context.monotonic_event_time.time_since_epoch().count());
538 message_header_builder.add_realtime_sent_time(
539 context.realtime_event_time.time_since_epoch().count());
540 message_header_builder.add_monotonic_remote_time(
541 context.monotonic_remote_time.time_since_epoch().count());
542 message_header_builder.add_realtime_remote_time(
543 context.realtime_remote_time.time_since_epoch().count());
544 message_header_builder.add_data(data_offset);
545 break;
Austin Schuha36c8902019-12-30 18:07:15 -0800546 }
547
548 return message_header_builder.Finish();
549}
550
Austin Schuhfa30c352022-10-16 11:12:02 -0700551flatbuffers::uoffset_t PackMessageHeaderSize(LogType log_type) {
552 switch (log_type) {
553 case LogType::kLogMessage:
554 return
555 // Root table size + offset.
556 sizeof(flatbuffers::uoffset_t) * 2 +
557 // 6 padding bytes to pad the header out properly.
558 6 +
559 // vtable header (size + size of table)
560 sizeof(flatbuffers::voffset_t) * 2 +
561 // offsets to all the fields.
562 sizeof(flatbuffers::voffset_t) * 5 +
563 // pointer to vtable
564 sizeof(flatbuffers::soffset_t) +
565 // pointer to data
566 sizeof(flatbuffers::uoffset_t) +
567 // realtime_sent_time, monotonic_sent_time
568 sizeof(int64_t) * 2 +
569 // queue_index, channel_index
570 sizeof(uint32_t) * 2;
571
572 case LogType::kLogDeliveryTimeOnly:
573 return
574 // Root table size + offset.
575 sizeof(flatbuffers::uoffset_t) * 2 +
576 // 6 padding bytes to pad the header out properly.
577 4 +
578 // vtable header (size + size of table)
579 sizeof(flatbuffers::voffset_t) * 2 +
580 // offsets to all the fields.
581 sizeof(flatbuffers::voffset_t) * 8 +
582 // pointer to vtable
583 sizeof(flatbuffers::soffset_t) +
584 // remote_queue_index
585 sizeof(uint32_t) +
586 // realtime_remote_time, monotonic_remote_time, realtime_sent_time,
587 // monotonic_sent_time
588 sizeof(int64_t) * 4 +
589 // queue_index, channel_index
590 sizeof(uint32_t) * 2;
591
592 case LogType::kLogMessageAndDeliveryTime:
593 return
594 // Root table size + offset.
595 sizeof(flatbuffers::uoffset_t) * 2 +
596 // 4 padding bytes to pad the header out properly.
597 4 +
598 // vtable header (size + size of table)
599 sizeof(flatbuffers::voffset_t) * 2 +
600 // offsets to all the fields.
601 sizeof(flatbuffers::voffset_t) * 8 +
602 // pointer to vtable
603 sizeof(flatbuffers::soffset_t) +
604 // pointer to data
605 sizeof(flatbuffers::uoffset_t) +
606 // realtime_remote_time, monotonic_remote_time, realtime_sent_time,
607 // monotonic_sent_time
608 sizeof(int64_t) * 4 +
609 // remote_queue_index, queue_index, channel_index
610 sizeof(uint32_t) * 3;
611
612 case LogType::kLogRemoteMessage:
613 return
614 // Root table size + offset.
615 sizeof(flatbuffers::uoffset_t) * 2 +
616 // 6 padding bytes to pad the header out properly.
617 6 +
618 // vtable header (size + size of table)
619 sizeof(flatbuffers::voffset_t) * 2 +
620 // offsets to all the fields.
621 sizeof(flatbuffers::voffset_t) * 5 +
622 // pointer to vtable
623 sizeof(flatbuffers::soffset_t) +
624 // realtime_sent_time, monotonic_sent_time
625 sizeof(int64_t) * 2 +
626 // pointer to data
627 sizeof(flatbuffers::uoffset_t) +
628 // queue_index, channel_index
629 sizeof(uint32_t) * 2;
630 }
631 LOG(FATAL);
632}
633
James Kuszmaul9776b392023-01-14 14:08:08 -0800634flatbuffers::uoffset_t PackMessageSize(LogType log_type, size_t data_size) {
Austin Schuhfa30c352022-10-16 11:12:02 -0700635 static_assert(sizeof(flatbuffers::uoffset_t) == 4u,
636 "Update size logic please.");
637 const flatbuffers::uoffset_t aligned_data_length =
Austin Schuh48d10d62022-10-16 22:19:23 -0700638 ((data_size + 7) & 0xfffffff8u);
Austin Schuhfa30c352022-10-16 11:12:02 -0700639 switch (log_type) {
640 case LogType::kLogDeliveryTimeOnly:
641 return PackMessageHeaderSize(log_type);
642
643 case LogType::kLogMessage:
644 case LogType::kLogMessageAndDeliveryTime:
645 case LogType::kLogRemoteMessage:
646 return PackMessageHeaderSize(log_type) +
647 // Vector...
648 sizeof(flatbuffers::uoffset_t) + aligned_data_length;
649 }
650 LOG(FATAL);
651}
652
Austin Schuhfa30c352022-10-16 11:12:02 -0700653size_t PackMessageInline(uint8_t *buffer, const Context &context,
Austin Schuh71a40d42023-02-04 21:22:22 -0800654 int channel_index, LogType log_type, size_t start_byte,
655 size_t end_byte) {
Austin Schuh48d10d62022-10-16 22:19:23 -0700656 // TODO(austin): Figure out how to copy directly from shared memory instead of
657 // first into the fetcher's memory and then into here. That would save a lot
658 // of memory.
Austin Schuhfa30c352022-10-16 11:12:02 -0700659 const flatbuffers::uoffset_t message_size =
Austin Schuh48d10d62022-10-16 22:19:23 -0700660 PackMessageSize(log_type, context.size);
Austin Schuh71a40d42023-02-04 21:22:22 -0800661 DCHECK_EQ((message_size % 8), 0u) << ": Non 8 byte length...";
662 DCHECK_EQ((start_byte % 8u), 0u);
663 DCHECK_EQ((end_byte % 8u), 0u);
664 DCHECK_LE(start_byte, end_byte);
665 DCHECK_LE(end_byte, message_size);
Austin Schuhfa30c352022-10-16 11:12:02 -0700666
667 // Pack all the data in. This is brittle but easy to change. Use the
668 // InlinePackMessage.Equivilent unit test to verify everything matches.
669 switch (log_type) {
670 case LogType::kLogMessage:
Austin Schuh71a40d42023-02-04 21:22:22 -0800671 switch (start_byte) {
672 case 0x00u:
673 if ((end_byte) == 0x00u) {
674 break;
675 }
676 // clang-format off
677 // header:
678 // +0x00 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: +0x4C | size prefix
679 buffer = Push<flatbuffers::uoffset_t>(
680 buffer, message_size - sizeof(flatbuffers::uoffset_t));
681
682 // +0x04 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: +0x1C | offset to root table `aos.logger.MessageHeader`
683 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x18);
684 [[fallthrough]];
685 case 0x08u:
686 if ((end_byte) == 0x08u) {
687 break;
688 }
689 //
690 // padding:
691 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
692 buffer = Pad(buffer, 6);
693 //
694 // vtable (aos.logger.MessageHeader):
695 // +0x0E | 0E 00 | uint16_t | 0x000E (14) | size of this vtable
696 buffer = Push<flatbuffers::voffset_t>(buffer, 0xe);
697 [[fallthrough]];
698 case 0x10u:
699 if ((end_byte) == 0x10u) {
700 break;
701 }
702 // +0x10 | 20 00 | uint16_t | 0x0020 (32) | size of referring table
703 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
704 // +0x12 | 1C 00 | VOffset16 | 0x001C (28) | offset to field `channel_index` (id: 0)
705 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
706 // +0x14 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `monotonic_sent_time` (id: 1)
707 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0c);
708 // +0x16 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `realtime_sent_time` (id: 2)
709 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
710 [[fallthrough]];
711 case 0x18u:
712 if ((end_byte) == 0x18u) {
713 break;
714 }
715 // +0x18 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `queue_index` (id: 3)
716 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
717 // +0x1A | 14 00 | VOffset16 | 0x0014 (20) | offset to field `data` (id: 4)
718 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
719 //
720 // root_table (aos.logger.MessageHeader):
721 // +0x1C | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: +0x0E | offset to vtable
722 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0e);
723 [[fallthrough]];
724 case 0x20u:
725 if ((end_byte) == 0x20u) {
726 break;
727 }
728 // +0x20 | B2 E4 EF 89 19 7D 7F 6F | int64_t | 0x6F7F7D1989EFE4B2 (8034277808894108850) | table field `realtime_sent_time` (Long)
729 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
730 [[fallthrough]];
731 case 0x28u:
732 if ((end_byte) == 0x28u) {
733 break;
734 }
735 // +0x28 | 86 8D 92 65 FC 79 74 2B | int64_t | 0x2B7479FC65928D86 (3131261765872160134) | table field `monotonic_sent_time` (Long)
736 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
737 [[fallthrough]];
738 case 0x30u:
739 if ((end_byte) == 0x30u) {
740 break;
741 }
742 // +0x30 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: +0x3C | offset to field `data` (vector)
743 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0c);
744 // +0x34 | 86 00 00 00 | uint32_t | 0x00000086 (134) | table field `queue_index` (UInt)
745 buffer = Push<uint32_t>(buffer, context.queue_index);
746 [[fallthrough]];
747 case 0x38u:
748 if ((end_byte) == 0x38u) {
749 break;
750 }
751 // +0x38 | 71 00 00 00 | uint32_t | 0x00000071 (113) | table field `channel_index` (UInt)
752 buffer = Push<uint32_t>(buffer, channel_index);
753 //
754 // vector (aos.logger.MessageHeader.data):
755 // +0x3C | 0E 00 00 00 | uint32_t | 0x0000000E (14) | length of vector (# items)
756 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
757 [[fallthrough]];
758 case 0x40u:
759 if ((end_byte) == 0x40u) {
760 break;
761 }
762 [[fallthrough]];
763 default:
764 // +0x40 | FF | uint8_t | 0xFF (255) | value[0]
765 // +0x41 | B8 | uint8_t | 0xB8 (184) | value[1]
766 // +0x42 | EE | uint8_t | 0xEE (238) | value[2]
767 // +0x43 | 00 | uint8_t | 0x00 (0) | value[3]
768 // +0x44 | 20 | uint8_t | 0x20 (32) | value[4]
769 // +0x45 | 4D | uint8_t | 0x4D (77) | value[5]
770 // +0x46 | FF | uint8_t | 0xFF (255) | value[6]
771 // +0x47 | 25 | uint8_t | 0x25 (37) | value[7]
772 // +0x48 | 3C | uint8_t | 0x3C (60) | value[8]
773 // +0x49 | 17 | uint8_t | 0x17 (23) | value[9]
774 // +0x4A | 65 | uint8_t | 0x65 (101) | value[10]
775 // +0x4B | 2F | uint8_t | 0x2F (47) | value[11]
776 // +0x4C | 63 | uint8_t | 0x63 (99) | value[12]
777 // +0x4D | 58 | uint8_t | 0x58 (88) | value[13]
778 //
779 // padding:
780 // +0x4E | 00 00 | uint8_t[2] | .. | padding
781 // clang-format on
782 if (start_byte <= 0x40 && end_byte == message_size) {
783 // The easy one, slap it all down.
784 buffer = PushBytes(buffer, context.data, context.size);
785 buffer =
786 Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
787 } else {
788 const size_t data_start_byte =
789 start_byte < 0x40 ? 0x0u : (start_byte - 0x40);
790 const size_t data_end_byte = end_byte - 0x40;
791 const size_t padded_size = ((context.size + 7) & 0xfffffff8u);
792 if (data_start_byte < padded_size) {
793 buffer = PushBytes(
794 buffer,
795 reinterpret_cast<const uint8_t *>(context.data) +
796 data_start_byte,
797 std::min(context.size, data_end_byte) - data_start_byte);
798 if (data_end_byte == padded_size) {
799 // We can only pad the last 7 bytes, so this only gets written
800 // if we write the last byte.
801 buffer = Pad(buffer,
802 ((context.size + 7) & 0xfffffff8u) - context.size);
803 }
804 }
805 }
806 break;
807 }
Austin Schuhfa30c352022-10-16 11:12:02 -0700808 break;
809
810 case LogType::kLogDeliveryTimeOnly:
Austin Schuh71a40d42023-02-04 21:22:22 -0800811 switch (start_byte) {
812 case 0x00u:
813 if ((end_byte) == 0x00u) {
814 break;
815 }
816 // clang-format off
817 // header:
818 // +0x00 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: +0x4C | size prefix
819 buffer = Push<flatbuffers::uoffset_t>(
820 buffer, message_size - sizeof(flatbuffers::uoffset_t));
821 // +0x04 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: +0x20 | offset to root table `aos.logger.MessageHeader`
822 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x1c);
Austin Schuhfa30c352022-10-16 11:12:02 -0700823
Austin Schuh71a40d42023-02-04 21:22:22 -0800824 [[fallthrough]];
825 case 0x08u:
826 if ((end_byte) == 0x08u) {
827 break;
828 }
829 //
830 // padding:
831 // +0x08 | 00 00 00 00 | uint8_t[4] | .... | padding
832 buffer = Pad(buffer, 4);
833 //
834 // vtable (aos.logger.MessageHeader):
835 // +0x0C | 14 00 | uint16_t | 0x0014 (20) | size of this vtable
836 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
837 // +0x0E | 30 00 | uint16_t | 0x0030 (48) | size of referring table
838 buffer = Push<flatbuffers::voffset_t>(buffer, 0x30);
839 [[fallthrough]];
840 case 0x10u:
841 if ((end_byte) == 0x10u) {
842 break;
843 }
844 // +0x10 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `channel_index` (id: 0)
845 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
846 // +0x12 | 20 00 | VOffset16 | 0x0020 (32) | offset to field `monotonic_sent_time` (id: 1)
847 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
848 // +0x14 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `realtime_sent_time` (id: 2)
849 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
850 // +0x16 | 28 00 | VOffset16 | 0x0028 (40) | offset to field `queue_index` (id: 3)
851 buffer = Push<flatbuffers::voffset_t>(buffer, 0x28);
852 [[fallthrough]];
853 case 0x18u:
854 if ((end_byte) == 0x18u) {
855 break;
856 }
857 // +0x18 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `data` (id: 4) <null> (Vector)
858 buffer = Push<flatbuffers::voffset_t>(buffer, 0x00);
859 // +0x1A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `monotonic_remote_time` (id: 5)
860 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
861 // +0x1C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `realtime_remote_time` (id: 6)
862 buffer = Push<flatbuffers::voffset_t>(buffer, 0x08);
863 // +0x1E | 04 00 | VOffset16 | 0x0004 (4) | offset to field `remote_queue_index` (id: 7)
864 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
865 [[fallthrough]];
866 case 0x20u:
867 if ((end_byte) == 0x20u) {
868 break;
869 }
870 //
871 // root_table (aos.logger.MessageHeader):
872 // +0x20 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: +0x0C | offset to vtable
873 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x14);
874 // +0x24 | 69 00 00 00 | uint32_t | 0x00000069 (105) | table field `remote_queue_index` (UInt)
875 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
876 [[fallthrough]];
877 case 0x28u:
878 if ((end_byte) == 0x28u) {
879 break;
880 }
881 // +0x28 | C6 85 F1 AB 83 B5 CD EB | int64_t | 0xEBCDB583ABF185C6 (-1455307527440726586) | table field `realtime_remote_time` (Long)
882 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
883 [[fallthrough]];
884 case 0x30u:
885 if ((end_byte) == 0x30u) {
886 break;
887 }
888 // +0x30 | 47 24 D3 97 1E 42 2D 99 | int64_t | 0x992D421E97D32447 (-7409193112790948793) | table field `monotonic_remote_time` (Long)
889 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
890 [[fallthrough]];
891 case 0x38u:
892 if ((end_byte) == 0x38u) {
893 break;
894 }
895 // +0x38 | C8 B9 A7 AB 79 F2 CD 60 | int64_t | 0x60CDF279ABA7B9C8 (6975498002251626952) | table field `realtime_sent_time` (Long)
896 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
897 [[fallthrough]];
898 case 0x40u:
899 if ((end_byte) == 0x40u) {
900 break;
901 }
902 // +0x40 | EA 8F 2A 0F AF 01 7A AB | int64_t | 0xAB7A01AF0F2A8FEA (-6090553694679822358) | table field `monotonic_sent_time` (Long)
903 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
904 [[fallthrough]];
905 case 0x48u:
906 if ((end_byte) == 0x48u) {
907 break;
908 }
909 // +0x48 | F5 00 00 00 | uint32_t | 0x000000F5 (245) | table field `queue_index` (UInt)
910 buffer = Push<uint32_t>(buffer, context.queue_index);
911 // +0x4C | 88 00 00 00 | uint32_t | 0x00000088 (136) | table field `channel_index` (UInt)
912 buffer = Push<uint32_t>(buffer, channel_index);
913
914 // clang-format on
915 }
Austin Schuhfa30c352022-10-16 11:12:02 -0700916 break;
917
918 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh71a40d42023-02-04 21:22:22 -0800919 switch (start_byte) {
920 case 0x00u:
921 if ((end_byte) == 0x00u) {
922 break;
923 }
924 // clang-format off
925 // header:
926 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
927 buffer = Push<flatbuffers::uoffset_t>(
928 buffer, message_size - sizeof(flatbuffers::uoffset_t));
929 // +0x04 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: +0x20 | offset to root table `aos.logger.MessageHeader`
930 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x1c);
931 [[fallthrough]];
932 case 0x08u:
933 if ((end_byte) == 0x08u) {
934 break;
935 }
936 //
937 // padding:
938 // +0x08 | 00 00 00 00 | uint8_t[4] | .... | padding
939 buffer = Pad(buffer, 4);
940 //
941 // vtable (aos.logger.MessageHeader):
942 // +0x0C | 14 00 | uint16_t | 0x0014 (20) | size of this vtable
943 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
944 // +0x0E | 34 00 | uint16_t | 0x0034 (52) | size of referring table
945 buffer = Push<flatbuffers::voffset_t>(buffer, 0x34);
946 [[fallthrough]];
947 case 0x10u:
948 if ((end_byte) == 0x10u) {
949 break;
950 }
951 // +0x10 | 30 00 | VOffset16 | 0x0030 (48) | offset to field `channel_index` (id: 0)
952 buffer = Push<flatbuffers::voffset_t>(buffer, 0x30);
953 // +0x12 | 20 00 | VOffset16 | 0x0020 (32) | offset to field `monotonic_sent_time` (id: 1)
954 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
955 // +0x14 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `realtime_sent_time` (id: 2)
956 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
957 // +0x16 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `queue_index` (id: 3)
958 buffer = Push<flatbuffers::voffset_t>(buffer, 0x2c);
959 [[fallthrough]];
960 case 0x18u:
961 if ((end_byte) == 0x18u) {
962 break;
963 }
964 // +0x18 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `data` (id: 4)
965 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
966 // +0x1A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `monotonic_remote_time` (id: 5)
967 buffer = Push<flatbuffers::voffset_t>(buffer, 0x10);
968 // +0x1C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `realtime_remote_time` (id: 6)
969 buffer = Push<flatbuffers::voffset_t>(buffer, 0x08);
970 // +0x1E | 28 00 | VOffset16 | 0x0028 (40) | offset to field `remote_queue_index` (id: 7)
971 buffer = Push<flatbuffers::voffset_t>(buffer, 0x28);
972 [[fallthrough]];
973 case 0x20u:
974 if ((end_byte) == 0x20u) {
975 break;
976 }
977 //
978 // root_table (aos.logger.MessageHeader):
979 // +0x20 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: +0x0C | offset to vtable
980 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x14);
981 // +0x24 | 30 00 00 00 | UOffset32 | 0x00000030 (48) Loc: +0x54 | offset to field `data` (vector)
982 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x30);
983 [[fallthrough]];
984 case 0x28u:
985 if ((end_byte) == 0x28u) {
986 break;
987 }
988 // +0x28 | C4 C8 87 BF 40 6C 1F 29 | int64_t | 0x291F6C40BF87C8C4 (2963206105180129476) | table field `realtime_remote_time` (Long)
989 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
990 [[fallthrough]];
991 case 0x30u:
992 if ((end_byte) == 0x30u) {
993 break;
994 }
995 // +0x30 | 0F 00 26 FD D2 6D C0 1F | int64_t | 0x1FC06DD2FD26000F (2287949363661897743) | table field `monotonic_remote_time` (Long)
996 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
997 [[fallthrough]];
998 case 0x38u:
999 if ((end_byte) == 0x38u) {
1000 break;
1001 }
1002 // +0x38 | 29 75 09 C0 73 73 BF 88 | int64_t | 0x88BF7373C0097529 (-8593022623019338455) | table field `realtime_sent_time` (Long)
1003 buffer = Push<int64_t>(buffer, context.realtime_event_time.time_since_epoch().count());
1004 [[fallthrough]];
1005 case 0x40u:
1006 if ((end_byte) == 0x40u) {
1007 break;
1008 }
1009 // +0x40 | 6D 8A AE 04 50 25 9C E9 | int64_t | 0xE99C255004AE8A6D (-1613373540899321235) | table field `monotonic_sent_time` (Long)
1010 buffer = Push<int64_t>(buffer, context.monotonic_event_time.time_since_epoch().count());
1011 [[fallthrough]];
1012 case 0x48u:
1013 if ((end_byte) == 0x48u) {
1014 break;
1015 }
1016 // +0x48 | 47 00 00 00 | uint32_t | 0x00000047 (71) | table field `remote_queue_index` (UInt)
1017 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
1018 // +0x4C | 4C 00 00 00 | uint32_t | 0x0000004C (76) | table field `queue_index` (UInt)
1019 buffer = Push<uint32_t>(buffer, context.queue_index);
1020 [[fallthrough]];
1021 case 0x50u:
1022 if ((end_byte) == 0x50u) {
1023 break;
1024 }
1025 // +0x50 | 72 00 00 00 | uint32_t | 0x00000072 (114) | table field `channel_index` (UInt)
1026 buffer = Push<uint32_t>(buffer, channel_index);
1027 //
1028 // vector (aos.logger.MessageHeader.data):
1029 // +0x54 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of vector (# items)
1030 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
1031 [[fallthrough]];
1032 case 0x58u:
1033 if ((end_byte) == 0x58u) {
1034 break;
1035 }
1036 [[fallthrough]];
1037 default:
1038 // +0x58 | B1 | uint8_t | 0xB1 (177) | value[0]
1039 // +0x59 | 4A | uint8_t | 0x4A (74) | value[1]
1040 // +0x5A | 50 | uint8_t | 0x50 (80) | value[2]
1041 // +0x5B | 24 | uint8_t | 0x24 (36) | value[3]
1042 // +0x5C | AF | uint8_t | 0xAF (175) | value[4]
1043 // +0x5D | C8 | uint8_t | 0xC8 (200) | value[5]
1044 // +0x5E | D5 | uint8_t | 0xD5 (213) | value[6]
1045 //
1046 // padding:
1047 // +0x5F | 00 | uint8_t[1] | . | padding
1048 // clang-format on
1049
1050 if (start_byte <= 0x58 && end_byte == message_size) {
1051 // The easy one, slap it all down.
1052 buffer = PushBytes(buffer, context.data, context.size);
1053 buffer =
1054 Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
1055 } else {
1056 const size_t data_start_byte =
1057 start_byte < 0x58 ? 0x0u : (start_byte - 0x58);
1058 const size_t data_end_byte = end_byte - 0x58;
1059 const size_t padded_size = ((context.size + 7) & 0xfffffff8u);
1060 if (data_start_byte < padded_size) {
1061 buffer = PushBytes(
1062 buffer,
1063 reinterpret_cast<const uint8_t *>(context.data) +
1064 data_start_byte,
1065 std::min(context.size, data_end_byte) - data_start_byte);
1066 if (data_end_byte == padded_size) {
1067 // We can only pad the last 7 bytes, so this only gets written
1068 // if we write the last byte.
1069 buffer = Pad(buffer,
1070 ((context.size + 7) & 0xfffffff8u) - context.size);
1071 }
1072 }
1073 }
1074
1075 break;
1076 }
Austin Schuhfa30c352022-10-16 11:12:02 -07001077
1078 break;
1079
1080 case LogType::kLogRemoteMessage:
Austin Schuh71a40d42023-02-04 21:22:22 -08001081 switch (start_byte) {
1082 case 0x00u:
1083 if ((end_byte) == 0x00u) {
1084 break;
1085 }
1086 // This is the message we need to recreate.
1087 //
1088 // clang-format off
1089 // header:
1090 // +0x00 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: +0x5C | size prefix
1091 buffer = Push<flatbuffers::uoffset_t>(
1092 buffer, message_size - sizeof(flatbuffers::uoffset_t));
1093 // +0x04 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: +0x1C | offset to root table `aos.logger.MessageHeader`
1094 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x18);
1095 [[fallthrough]];
1096 case 0x08u:
1097 if ((end_byte) == 0x08u) {
1098 break;
1099 }
1100 //
1101 // padding:
1102 // +0x08 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
1103 buffer = Pad(buffer, 6);
1104 //
1105 // vtable (aos.logger.MessageHeader):
1106 // +0x0E | 0E 00 | uint16_t | 0x000E (14) | size of this vtable
1107 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0e);
1108 [[fallthrough]];
1109 case 0x10u:
1110 if ((end_byte) == 0x10u) {
1111 break;
1112 }
1113 // +0x10 | 20 00 | uint16_t | 0x0020 (32) | size of referring table
1114 buffer = Push<flatbuffers::voffset_t>(buffer, 0x20);
1115 // +0x12 | 1C 00 | VOffset16 | 0x001C (28) | offset to field `channel_index` (id: 0)
1116 buffer = Push<flatbuffers::voffset_t>(buffer, 0x1c);
1117 // +0x14 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `monotonic_sent_time` (id: 1)
1118 buffer = Push<flatbuffers::voffset_t>(buffer, 0x0c);
1119 // +0x16 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `realtime_sent_time` (id: 2)
1120 buffer = Push<flatbuffers::voffset_t>(buffer, 0x04);
1121 [[fallthrough]];
1122 case 0x18u:
1123 if ((end_byte) == 0x18u) {
1124 break;
1125 }
1126 // +0x18 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `queue_index` (id: 3)
1127 buffer = Push<flatbuffers::voffset_t>(buffer, 0x18);
1128 // +0x1A | 14 00 | VOffset16 | 0x0014 (20) | offset to field `data` (id: 4)
1129 buffer = Push<flatbuffers::voffset_t>(buffer, 0x14);
1130 //
1131 // root_table (aos.logger.MessageHeader):
1132 // +0x1C | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: +0x0E | offset to vtable
1133 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0E);
1134 [[fallthrough]];
1135 case 0x20u:
1136 if ((end_byte) == 0x20u) {
1137 break;
1138 }
1139 // +0x20 | D8 96 32 1A A0 D3 23 BB | int64_t | 0xBB23D3A01A3296D8 (-4961889679844403496) | table field `realtime_sent_time` (Long)
1140 buffer = Push<int64_t>(buffer, context.realtime_remote_time.time_since_epoch().count());
1141 [[fallthrough]];
1142 case 0x28u:
1143 if ((end_byte) == 0x28u) {
1144 break;
1145 }
1146 // +0x28 | 2E 5D 23 B3 BE 84 CF C2 | int64_t | 0xC2CF84BEB3235D2E (-4409159555588334290) | table field `monotonic_sent_time` (Long)
1147 buffer = Push<int64_t>(buffer, context.monotonic_remote_time.time_since_epoch().count());
1148 [[fallthrough]];
1149 case 0x30u:
1150 if ((end_byte) == 0x30u) {
1151 break;
1152 }
1153 // +0x30 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: +0x3C | offset to field `data` (vector)
1154 buffer = Push<flatbuffers::uoffset_t>(buffer, 0x0C);
1155 // +0x34 | 69 00 00 00 | uint32_t | 0x00000069 (105) | table field `queue_index` (UInt)
1156 buffer = Push<uint32_t>(buffer, context.remote_queue_index);
1157 [[fallthrough]];
1158 case 0x38u:
1159 if ((end_byte) == 0x38u) {
1160 break;
1161 }
1162 // +0x38 | F3 00 00 00 | uint32_t | 0x000000F3 (243) | table field `channel_index` (UInt)
1163 buffer = Push<uint32_t>(buffer, channel_index);
1164 //
1165 // vector (aos.logger.MessageHeader.data):
1166 // +0x3C | 1A 00 00 00 | uint32_t | 0x0000001A (26) | length of vector (# items)
1167 buffer = Push<flatbuffers::uoffset_t>(buffer, context.size);
1168 [[fallthrough]];
1169 case 0x40u:
1170 if ((end_byte) == 0x40u) {
1171 break;
1172 }
1173 [[fallthrough]];
1174 default:
1175 // +0x40 | 38 | uint8_t | 0x38 (56) | value[0]
1176 // +0x41 | 1A | uint8_t | 0x1A (26) | value[1]
1177 // ...
1178 // +0x58 | 90 | uint8_t | 0x90 (144) | value[24]
1179 // +0x59 | 92 | uint8_t | 0x92 (146) | value[25]
1180 //
1181 // padding:
1182 // +0x5A | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding
1183 // clang-format on
1184 if (start_byte <= 0x40 && end_byte == message_size) {
1185 // The easy one, slap it all down.
1186 buffer = PushBytes(buffer, context.data, context.size);
1187 buffer =
1188 Pad(buffer, ((context.size + 7) & 0xfffffff8u) - context.size);
1189 } else {
1190 const size_t data_start_byte =
1191 start_byte < 0x40 ? 0x0u : (start_byte - 0x40);
1192 const size_t data_end_byte = end_byte - 0x40;
1193 const size_t padded_size = ((context.size + 7) & 0xfffffff8u);
1194 if (data_start_byte < padded_size) {
1195 buffer = PushBytes(
1196 buffer,
1197 reinterpret_cast<const uint8_t *>(context.data) +
1198 data_start_byte,
1199 std::min(context.size, data_end_byte) - data_start_byte);
1200 if (data_end_byte == padded_size) {
1201 // We can only pad the last 7 bytes, so this only gets written
1202 // if we write the last byte.
1203 buffer = Pad(buffer,
1204 ((context.size + 7) & 0xfffffff8u) - context.size);
1205 }
1206 }
1207 }
1208 break;
1209 }
Austin Schuhfa30c352022-10-16 11:12:02 -07001210 }
1211
Austin Schuh71a40d42023-02-04 21:22:22 -08001212 return end_byte - start_byte;
Austin Schuhfa30c352022-10-16 11:12:02 -07001213}
1214
Austin Schuhcd368422021-11-22 21:23:29 -08001215SpanReader::SpanReader(std::string_view filename, bool quiet)
1216 : filename_(filename) {
Austin Schuh86110712022-09-16 15:40:54 -07001217 static constexpr std::string_view kS3 = "s3:";
1218 if (filename.substr(0, kS3.size()) == kS3) {
1219#if ENABLE_S3
1220 decoder_ = std::make_unique<S3Fetcher>(filename);
1221#else
1222 LOG(FATAL) << "Reading files from S3 not supported on this platform";
1223#endif
1224 } else {
1225 decoder_ = std::make_unique<DummyDecoder>(filename);
1226 }
Tyler Chatow2015bc62021-08-04 21:15:09 -07001227
1228 static constexpr std::string_view kXz = ".xz";
James Kuszmauldd0a5042021-10-28 23:38:04 -07001229 static constexpr std::string_view kSnappy = SnappyDecoder::kExtension;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -07001230 if (filename.substr(filename.size() - kXz.size()) == kXz) {
1231#if ENABLE_LZMA
Austin Schuhcd368422021-11-22 21:23:29 -08001232 decoder_ =
1233 std::make_unique<ThreadedLzmaDecoder>(std::move(decoder_), quiet);
Brian Silvermanf59fe3f2020-09-22 21:04:09 -07001234#else
Austin Schuhcd368422021-11-22 21:23:29 -08001235 (void)quiet;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -07001236 LOG(FATAL) << "Reading xz-compressed files not supported on this platform";
1237#endif
James Kuszmauldd0a5042021-10-28 23:38:04 -07001238 } else if (filename.substr(filename.size() - kSnappy.size()) == kSnappy) {
1239 decoder_ = std::make_unique<SnappyDecoder>(std::move(decoder_));
Brian Silvermanf59fe3f2020-09-22 21:04:09 -07001240 }
Austin Schuh05b70472020-01-01 17:11:17 -08001241}
1242
Austin Schuhcf5f6442021-07-06 10:43:28 -07001243absl::Span<const uint8_t> SpanReader::PeekMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -08001244 // Make sure we have enough for the size.
1245 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
1246 if (!ReadBlock()) {
1247 return absl::Span<const uint8_t>();
1248 }
1249 }
1250
1251 // Now make sure we have enough for the message.
1252 const size_t data_size =
1253 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
1254 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -08001255 if (data_size == sizeof(flatbuffers::uoffset_t)) {
1256 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
1257 LOG(ERROR) << " Rest of log file is "
1258 << absl::BytesToHexString(std::string_view(
1259 reinterpret_cast<const char *>(data_.data() +
1260 consumed_data_),
1261 data_.size() - consumed_data_));
1262 return absl::Span<const uint8_t>();
1263 }
Austin Schuh05b70472020-01-01 17:11:17 -08001264 while (data_.size() < consumed_data_ + data_size) {
1265 if (!ReadBlock()) {
1266 return absl::Span<const uint8_t>();
1267 }
1268 }
1269
1270 // And return it, consuming the data.
1271 const uint8_t *data_ptr = data_.data() + consumed_data_;
1272
Austin Schuh05b70472020-01-01 17:11:17 -08001273 return absl::Span<const uint8_t>(data_ptr, data_size);
1274}
1275
Austin Schuhcf5f6442021-07-06 10:43:28 -07001276void SpanReader::ConsumeMessage() {
Brian Smarttea913d42021-12-10 15:02:38 -08001277 size_t consumed_size =
Austin Schuhcf5f6442021-07-06 10:43:28 -07001278 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
1279 sizeof(flatbuffers::uoffset_t);
Brian Smarttea913d42021-12-10 15:02:38 -08001280 consumed_data_ += consumed_size;
1281 total_consumed_ += consumed_size;
Austin Schuhcf5f6442021-07-06 10:43:28 -07001282}
1283
1284absl::Span<const uint8_t> SpanReader::ReadMessage() {
1285 absl::Span<const uint8_t> result = PeekMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001286 if (!result.empty()) {
Austin Schuhcf5f6442021-07-06 10:43:28 -07001287 ConsumeMessage();
Brian Smarttea913d42021-12-10 15:02:38 -08001288 } else {
1289 is_finished_ = true;
Austin Schuhcf5f6442021-07-06 10:43:28 -07001290 }
1291 return result;
1292}
1293
Austin Schuh05b70472020-01-01 17:11:17 -08001294bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -07001295 // This is the amount of data we grab at a time. Doing larger chunks minimizes
1296 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -08001297 constexpr size_t kReadSize = 256 * 1024;
1298
1299 // Strip off any unused data at the front.
1300 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -07001301 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -08001302 consumed_data_ = 0;
1303 }
1304
1305 const size_t starting_size = data_.size();
1306
1307 // This should automatically grow the backing store. It won't shrink if we
1308 // get a small chunk later. This reduces allocations when we want to append
1309 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -07001310 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -08001311
Brian Silvermanf51499a2020-09-21 12:49:08 -07001312 const size_t count =
1313 decoder_->Read(data_.begin() + starting_size, data_.end());
1314 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -08001315 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -08001316 return false;
1317 }
Austin Schuh05b70472020-01-01 17:11:17 -08001318
Brian Smarttea913d42021-12-10 15:02:38 -08001319 total_read_ += count;
1320
Austin Schuh05b70472020-01-01 17:11:17 -08001321 return true;
1322}
1323
Austin Schuhadd6eb32020-11-09 21:24:26 -08001324std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh0e8db662021-07-06 10:43:47 -07001325 SpanReader *span_reader) {
1326 absl::Span<const uint8_t> config_data = span_reader->ReadMessage();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001327
1328 // Make sure something was read.
James Kuszmaul9776b392023-01-14 14:08:08 -08001329 if (config_data.empty()) {
Austin Schuh3bd4c402020-11-06 18:19:06 -08001330 return std::nullopt;
1331 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001332
Austin Schuh5212cad2020-09-09 23:12:09 -07001333 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -07001334 SizePrefixedFlatbufferVector<LogFileHeader> result(config_data);
Austin Schuhe09beb12020-12-11 20:04:27 -08001335 if (!result.Verify()) {
1336 return std::nullopt;
1337 }
Austin Schuh0e8db662021-07-06 10:43:47 -07001338
Austin Schuhcc2c9a52022-12-12 15:55:13 -08001339 // We only know of busted headers in the versions of the log file header
1340 // *before* the logger_sha1 field was added. At some point before that point,
1341 // the logic to track when a header has been written was rewritten in such a
1342 // way that it can't happen anymore. We've seen some logs where the body
1343 // parses as a header recently, so the simple solution of always looking is
1344 // failing us.
1345 if (FLAGS_workaround_double_headers && !result.message().has_logger_sha1()) {
Austin Schuh0e8db662021-07-06 10:43:47 -07001346 while (true) {
1347 absl::Span<const uint8_t> maybe_header_data = span_reader->PeekMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001348 if (maybe_header_data.empty()) {
Austin Schuh0e8db662021-07-06 10:43:47 -07001349 break;
1350 }
1351
1352 aos::SizePrefixedFlatbufferSpan<aos::logger::LogFileHeader> maybe_header(
1353 maybe_header_data);
1354 if (maybe_header.Verify()) {
1355 LOG(WARNING) << "Found duplicate LogFileHeader in "
1356 << span_reader->filename();
1357 ResizeableBuffer header_data_copy;
1358 header_data_copy.resize(maybe_header_data.size());
1359 memcpy(header_data_copy.data(), maybe_header_data.begin(),
1360 header_data_copy.size());
1361 result = SizePrefixedFlatbufferVector<LogFileHeader>(
1362 std::move(header_data_copy));
1363
1364 span_reader->ConsumeMessage();
1365 } else {
1366 break;
1367 }
1368 }
1369 }
Austin Schuhe09beb12020-12-11 20:04:27 -08001370 return result;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001371}
1372
Austin Schuh0e8db662021-07-06 10:43:47 -07001373std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
1374 std::string_view filename) {
1375 SpanReader span_reader(filename);
1376 return ReadHeader(&span_reader);
1377}
1378
Austin Schuhadd6eb32020-11-09 21:24:26 -08001379std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -08001380 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -07001381 SpanReader span_reader(filename);
1382 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
1383 for (size_t i = 0; i < n + 1; ++i) {
1384 data_span = span_reader.ReadMessage();
1385
1386 // Make sure something was read.
James Kuszmaul9776b392023-01-14 14:08:08 -08001387 if (data_span.empty()) {
Austin Schuh3bd4c402020-11-06 18:19:06 -08001388 return std::nullopt;
1389 }
Austin Schuh5212cad2020-09-09 23:12:09 -07001390 }
1391
Brian Silverman354697a2020-09-22 21:06:32 -07001392 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -07001393 SizePrefixedFlatbufferVector<MessageHeader> result(data_span);
Austin Schuhe09beb12020-12-11 20:04:27 -08001394 if (!result.Verify()) {
1395 return std::nullopt;
1396 }
1397 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -07001398}
1399
Austin Schuh05b70472020-01-01 17:11:17 -08001400MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -07001401 : span_reader_(filename),
Austin Schuhadd6eb32020-11-09 21:24:26 -08001402 raw_log_file_header_(
1403 SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001404 set_crash_on_corrupt_message_flag(FLAGS_crash_on_corrupt_message);
1405 set_ignore_corrupt_messages_flag(FLAGS_ignore_corrupt_messages);
1406
Austin Schuh0e8db662021-07-06 10:43:47 -07001407 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>>
1408 raw_log_file_header = ReadHeader(&span_reader_);
Austin Schuh05b70472020-01-01 17:11:17 -08001409
1410 // Make sure something was read.
Austin Schuh0e8db662021-07-06 10:43:47 -07001411 CHECK(raw_log_file_header) << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -08001412
Austin Schuh0e8db662021-07-06 10:43:47 -07001413 raw_log_file_header_ = std::move(*raw_log_file_header);
Austin Schuh05b70472020-01-01 17:11:17 -08001414
Austin Schuh5b728b72021-06-16 14:57:15 -07001415 CHECK(raw_log_file_header_.Verify()) << "Log file header is corrupted";
1416
Brian Smarttea913d42021-12-10 15:02:38 -08001417 total_verified_before_ = span_reader_.TotalConsumed();
1418
Austin Schuhcde938c2020-02-02 17:30:07 -08001419 max_out_of_order_duration_ =
Austin Schuha040c3f2021-02-13 16:09:07 -08001420 FLAGS_max_out_of_order > 0
1421 ? chrono::duration_cast<chrono::nanoseconds>(
1422 chrono::duration<double>(FLAGS_max_out_of_order))
1423 : chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -08001424
1425 VLOG(1) << "Opened " << filename << " as node "
1426 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -08001427}
1428
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001429std::shared_ptr<UnpackedMessageHeader> MessageReader::ReadMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -08001430 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
James Kuszmaul9776b392023-01-14 14:08:08 -08001431 if (msg_data.empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001432 if (is_corrupted()) {
1433 LOG(ERROR) << "Total corrupted volumes: before = "
1434 << total_verified_before_
1435 << " | corrupted = " << total_corrupted_
1436 << " | during = " << total_verified_during_
1437 << " | after = " << total_verified_after_ << std::endl;
1438 }
1439
1440 if (span_reader_.IsIncomplete()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001441 LOG(ERROR) << "Unable to access some messages in " << filename() << " : "
1442 << span_reader_.TotalRead() << " bytes read, "
Brian Smarttea913d42021-12-10 15:02:38 -08001443 << span_reader_.TotalConsumed() << " bytes usable."
1444 << std::endl;
1445 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001446 return nullptr;
Austin Schuh05b70472020-01-01 17:11:17 -08001447 }
1448
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001449 SizePrefixedFlatbufferSpan<MessageHeader> msg(msg_data);
Brian Smarttea913d42021-12-10 15:02:38 -08001450
1451 if (crash_on_corrupt_message_flag_) {
1452 CHECK(msg.Verify()) << "Corrupted message at offset "
Austin Schuh60e77942022-05-16 17:48:24 -07001453 << total_verified_before_ << " found within "
1454 << filename()
Brian Smarttea913d42021-12-10 15:02:38 -08001455 << "; set --nocrash_on_corrupt_message to see summary;"
1456 << " also set --ignore_corrupt_messages to process"
1457 << " anyway";
1458
1459 } else if (!msg.Verify()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001460 LOG(ERROR) << "Corrupted message at offset " << total_verified_before_
Brian Smarttea913d42021-12-10 15:02:38 -08001461 << " from " << filename() << std::endl;
1462
1463 total_corrupted_ += msg_data.size();
1464
1465 while (true) {
1466 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
1467
James Kuszmaul9776b392023-01-14 14:08:08 -08001468 if (msg_data.empty()) {
Brian Smarttea913d42021-12-10 15:02:38 -08001469 if (!ignore_corrupt_messages_flag_) {
1470 LOG(ERROR) << "Total corrupted volumes: before = "
1471 << total_verified_before_
1472 << " | corrupted = " << total_corrupted_
1473 << " | during = " << total_verified_during_
1474 << " | after = " << total_verified_after_ << std::endl;
1475
1476 if (span_reader_.IsIncomplete()) {
1477 LOG(ERROR) << "Unable to access some messages in " << filename()
1478 << " : " << span_reader_.TotalRead() << " bytes read, "
1479 << span_reader_.TotalConsumed() << " bytes usable."
1480 << std::endl;
1481 }
1482 return nullptr;
1483 }
1484 break;
1485 }
1486
1487 SizePrefixedFlatbufferSpan<MessageHeader> next_msg(msg_data);
1488
1489 if (!next_msg.Verify()) {
1490 total_corrupted_ += msg_data.size();
1491 total_verified_during_ += total_verified_after_;
1492 total_verified_after_ = 0;
1493
1494 } else {
1495 total_verified_after_ += msg_data.size();
1496 if (ignore_corrupt_messages_flag_) {
1497 msg = next_msg;
1498 break;
1499 }
1500 }
1501 }
1502 }
1503
1504 if (is_corrupted()) {
1505 total_verified_after_ += msg_data.size();
1506 } else {
1507 total_verified_before_ += msg_data.size();
1508 }
Austin Schuh05b70472020-01-01 17:11:17 -08001509
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001510 auto result = UnpackedMessageHeader::MakeMessage(msg.message());
Austin Schuh0e8db662021-07-06 10:43:47 -07001511
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001512 const monotonic_clock::time_point timestamp = result->monotonic_sent_time;
Austin Schuh05b70472020-01-01 17:11:17 -08001513
1514 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuhd1873292021-11-18 15:35:30 -08001515
1516 if (VLOG_IS_ON(3)) {
1517 VLOG(3) << "Read from " << filename() << " data " << FlatbufferToJson(msg);
1518 } else if (VLOG_IS_ON(2)) {
1519 SizePrefixedFlatbufferVector<MessageHeader> msg_copy = msg;
1520 msg_copy.mutable_message()->clear_data();
1521 VLOG(2) << "Read from " << filename() << " data "
1522 << FlatbufferToJson(msg_copy);
1523 }
1524
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001525 return result;
1526}
1527
1528std::shared_ptr<UnpackedMessageHeader> UnpackedMessageHeader::MakeMessage(
1529 const MessageHeader &message) {
1530 const size_t data_size = message.has_data() ? message.data()->size() : 0;
1531
1532 UnpackedMessageHeader *const unpacked_message =
1533 reinterpret_cast<UnpackedMessageHeader *>(
1534 malloc(sizeof(UnpackedMessageHeader) + data_size +
1535 kChannelDataAlignment - 1));
1536
1537 CHECK(message.has_channel_index());
1538 CHECK(message.has_monotonic_sent_time());
1539
1540 absl::Span<uint8_t> span;
1541 if (data_size > 0) {
1542 span =
1543 absl::Span<uint8_t>(reinterpret_cast<uint8_t *>(RoundChannelData(
1544 &unpacked_message->actual_data[0], data_size)),
1545 data_size);
1546 }
1547
Austin Schuh826e6ce2021-11-18 20:33:10 -08001548 std::optional<aos::monotonic_clock::time_point> monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001549 if (message.has_monotonic_remote_time()) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001550 monotonic_remote_time = aos::monotonic_clock::time_point(
1551 std::chrono::nanoseconds(message.monotonic_remote_time()));
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001552 }
1553 std::optional<realtime_clock::time_point> realtime_remote_time;
1554 if (message.has_realtime_remote_time()) {
1555 realtime_remote_time = realtime_clock::time_point(
1556 chrono::nanoseconds(message.realtime_remote_time()));
1557 }
1558
1559 std::optional<uint32_t> remote_queue_index;
1560 if (message.has_remote_queue_index()) {
1561 remote_queue_index = message.remote_queue_index();
1562 }
1563
James Kuszmaul9776b392023-01-14 14:08:08 -08001564 new (unpacked_message) UnpackedMessageHeader(
1565 message.channel_index(),
1566 monotonic_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001567 chrono::nanoseconds(message.monotonic_sent_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001568 realtime_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001569 chrono::nanoseconds(message.realtime_sent_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001570 message.queue_index(), monotonic_remote_time, realtime_remote_time,
1571 remote_queue_index,
1572 monotonic_clock::time_point(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001573 std::chrono::nanoseconds(message.monotonic_timestamp_time())),
James Kuszmaul9776b392023-01-14 14:08:08 -08001574 message.has_monotonic_timestamp_time(), span);
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001575
1576 if (data_size > 0) {
1577 memcpy(span.data(), message.data()->data(), data_size);
1578 }
1579
1580 return std::shared_ptr<UnpackedMessageHeader>(unpacked_message,
1581 &DestroyAndFree);
Austin Schuh05b70472020-01-01 17:11:17 -08001582}
1583
Austin Schuhc41603c2020-10-11 16:17:37 -07001584PartsMessageReader::PartsMessageReader(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -07001585 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {
Brian Silvermanfee16972021-09-14 12:06:38 -07001586 if (parts_.parts.size() >= 2) {
1587 next_message_reader_.emplace(parts_.parts[1]);
1588 }
Austin Schuh48507722021-07-17 17:29:24 -07001589 ComputeBootCounts();
1590}
1591
1592void PartsMessageReader::ComputeBootCounts() {
1593 boot_counts_.assign(configuration::NodesCount(parts_.config.get()),
1594 std::nullopt);
1595
1596 // We have 3 vintages of log files with different amounts of information.
1597 if (log_file_header()->has_boot_uuids()) {
1598 // The new hotness with the boots explicitly listed out. We can use the log
1599 // file header to compute the boot count of all relevant nodes.
1600 CHECK_EQ(log_file_header()->boot_uuids()->size(), boot_counts_.size());
1601 size_t node_index = 0;
1602 for (const flatbuffers::String *boot_uuid :
1603 *log_file_header()->boot_uuids()) {
1604 CHECK(parts_.boots);
1605 if (boot_uuid->size() != 0) {
1606 auto it = parts_.boots->boot_count_map.find(boot_uuid->str());
1607 if (it != parts_.boots->boot_count_map.end()) {
1608 boot_counts_[node_index] = it->second;
1609 }
1610 } else if (parts().boots->boots[node_index].size() == 1u) {
1611 boot_counts_[node_index] = 0;
1612 }
1613 ++node_index;
1614 }
1615 } else {
1616 // Older multi-node logs which are guarenteed to have UUIDs logged, or
1617 // single node log files with boot UUIDs in the header. We only know how to
1618 // order certain boots in certain circumstances.
1619 if (configuration::MultiNode(parts_.config.get()) || parts_.boots) {
1620 for (size_t node_index = 0; node_index < boot_counts_.size();
1621 ++node_index) {
1622 CHECK(parts_.boots);
1623 if (parts().boots->boots[node_index].size() == 1u) {
1624 boot_counts_[node_index] = 0;
1625 }
1626 }
1627 } else {
1628 // Really old single node logs without any UUIDs. They can't reboot.
1629 CHECK_EQ(boot_counts_.size(), 1u);
1630 boot_counts_[0] = 0u;
1631 }
1632 }
1633}
Austin Schuhc41603c2020-10-11 16:17:37 -07001634
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001635std::shared_ptr<UnpackedMessageHeader> PartsMessageReader::ReadMessage() {
Austin Schuhc41603c2020-10-11 16:17:37 -07001636 while (!done_) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001637 std::shared_ptr<UnpackedMessageHeader> message =
Austin Schuhc41603c2020-10-11 16:17:37 -07001638 message_reader_.ReadMessage();
1639 if (message) {
1640 newest_timestamp_ = message_reader_.newest_timestamp();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001641 const monotonic_clock::time_point monotonic_sent_time =
1642 message->monotonic_sent_time;
1643
1644 // TODO(austin): Does this work with startup? Might need to use the
1645 // start time.
1646 // TODO(austin): Does this work with startup when we don't know the
1647 // remote start time too? Look at one of those logs to compare.
Austin Schuh315b96b2020-12-11 21:21:12 -08001648 if (monotonic_sent_time >
1649 parts_.monotonic_start_time + max_out_of_order_duration()) {
1650 after_start_ = true;
1651 }
1652 if (after_start_) {
Austin Schuhb000de62020-12-03 22:00:40 -08001653 CHECK_GE(monotonic_sent_time,
1654 newest_timestamp_ - max_out_of_order_duration())
Austin Schuha040c3f2021-02-13 16:09:07 -08001655 << ": Max out of order of " << max_out_of_order_duration().count()
1656 << "ns exceeded. " << parts_ << ", start time is "
Austin Schuh315b96b2020-12-11 21:21:12 -08001657 << parts_.monotonic_start_time << " currently reading "
1658 << filename();
Austin Schuhb000de62020-12-03 22:00:40 -08001659 }
Austin Schuhc41603c2020-10-11 16:17:37 -07001660 return message;
1661 }
1662 NextLog();
1663 }
Austin Schuh32f68492020-11-08 21:45:51 -08001664 newest_timestamp_ = monotonic_clock::max_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001665 return nullptr;
Austin Schuhc41603c2020-10-11 16:17:37 -07001666}
1667
1668void PartsMessageReader::NextLog() {
1669 if (next_part_index_ == parts_.parts.size()) {
Brian Silvermanfee16972021-09-14 12:06:38 -07001670 CHECK(!next_message_reader_);
Austin Schuhc41603c2020-10-11 16:17:37 -07001671 done_ = true;
1672 return;
1673 }
Brian Silvermanfee16972021-09-14 12:06:38 -07001674 CHECK(next_message_reader_);
1675 message_reader_ = std::move(*next_message_reader_);
Austin Schuh48507722021-07-17 17:29:24 -07001676 ComputeBootCounts();
Brian Silvermanfee16972021-09-14 12:06:38 -07001677 if (next_part_index_ + 1 < parts_.parts.size()) {
1678 next_message_reader_.emplace(parts_.parts[next_part_index_ + 1]);
1679 } else {
1680 next_message_reader_.reset();
1681 }
Austin Schuhc41603c2020-10-11 16:17:37 -07001682 ++next_part_index_;
1683}
1684
Austin Schuh1be0ce42020-11-29 22:43:26 -08001685bool Message::operator<(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001686 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001687
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001688 if (this->timestamp.time < m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -08001689 return true;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001690 } else if (this->timestamp.time > m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -08001691 return false;
1692 }
1693
1694 if (this->channel_index < m2.channel_index) {
1695 return true;
1696 } else if (this->channel_index > m2.channel_index) {
1697 return false;
1698 }
1699
1700 return this->queue_index < m2.queue_index;
1701}
1702
1703bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001704bool Message::operator==(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001705 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -07001706
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001707 return timestamp.time == m2.timestamp.time &&
1708 channel_index == m2.channel_index && queue_index == m2.queue_index;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001709}
Austin Schuh1be0ce42020-11-29 22:43:26 -08001710
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001711std::ostream &operator<<(std::ostream &os, const UnpackedMessageHeader &m) {
1712 os << "{.channel_index=" << m.channel_index
1713 << ", .monotonic_sent_time=" << m.monotonic_sent_time
1714 << ", .realtime_sent_time=" << m.realtime_sent_time
1715 << ", .queue_index=" << m.queue_index;
1716 if (m.monotonic_remote_time) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001717 os << ", .monotonic_remote_time=" << *m.monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001718 }
1719 os << ", .realtime_remote_time=";
1720 PrintOptionalOrNull(&os, m.realtime_remote_time);
1721 os << ", .remote_queue_index=";
1722 PrintOptionalOrNull(&os, m.remote_queue_index);
1723 if (m.has_monotonic_timestamp_time) {
1724 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
1725 }
Austin Schuh22cf7862022-09-19 19:09:42 -07001726 os << "}";
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001727 return os;
1728}
1729
Austin Schuh1be0ce42020-11-29 22:43:26 -08001730std::ostream &operator<<(std::ostream &os, const Message &m) {
1731 os << "{.channel_index=" << m.channel_index
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001732 << ", .queue_index=" << m.queue_index << ", .timestamp=" << m.timestamp;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001733 if (m.data != nullptr) {
Austin Schuh826e6ce2021-11-18 20:33:10 -08001734 if (m.data->remote_queue_index.has_value()) {
1735 os << ", .remote_queue_index=" << *m.data->remote_queue_index;
1736 }
1737 if (m.data->monotonic_remote_time.has_value()) {
1738 os << ", .monotonic_remote_time=" << *m.data->monotonic_remote_time;
1739 }
Austin Schuhfb1b3292021-11-16 21:20:15 -08001740 os << ", .data=" << m.data;
Austin Schuhd2f96102020-12-01 20:27:29 -08001741 }
1742 os << "}";
1743 return os;
1744}
1745
1746std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m) {
1747 os << "{.channel_index=" << m.channel_index
1748 << ", .queue_index=" << m.queue_index
1749 << ", .monotonic_event_time=" << m.monotonic_event_time
1750 << ", .realtime_event_time=" << m.realtime_event_time;
Austin Schuh58646e22021-08-23 23:51:46 -07001751 if (m.remote_queue_index != BootQueueIndex::Invalid()) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001752 os << ", .remote_queue_index=" << m.remote_queue_index;
1753 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001754 if (m.monotonic_remote_time != BootTimestamp::min_time()) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001755 os << ", .monotonic_remote_time=" << m.monotonic_remote_time;
1756 }
1757 if (m.realtime_remote_time != realtime_clock::min_time) {
1758 os << ", .realtime_remote_time=" << m.realtime_remote_time;
1759 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001760 if (m.monotonic_timestamp_time != BootTimestamp::min_time()) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001761 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
1762 }
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001763 if (m.data != nullptr) {
1764 os << ", .data=" << *m.data;
Austin Schuh22cf7862022-09-19 19:09:42 -07001765 } else {
1766 os << ", .data=nullptr";
Austin Schuhd2f96102020-12-01 20:27:29 -08001767 }
1768 os << "}";
Austin Schuh1be0ce42020-11-29 22:43:26 -08001769 return os;
1770}
1771
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001772LogPartsSorter::LogPartsSorter(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -07001773 : parts_message_reader_(log_parts),
1774 source_node_index_(configuration::SourceNodeIndex(parts().config.get())) {
1775}
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001776
1777Message *LogPartsSorter::Front() {
1778 // Queue up data until enough data has been queued that the front message is
1779 // sorted enough to be safe to pop. This may do nothing, so we should make
1780 // sure the nothing path is checked quickly.
1781 if (sorted_until() != monotonic_clock::max_time) {
1782 while (true) {
Austin Schuh48507722021-07-17 17:29:24 -07001783 if (!messages_.empty() &&
1784 messages_.begin()->timestamp.time < sorted_until() &&
Austin Schuhb000de62020-12-03 22:00:40 -08001785 sorted_until() >= monotonic_start_time()) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001786 break;
1787 }
1788
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001789 std::shared_ptr<UnpackedMessageHeader> m =
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001790 parts_message_reader_.ReadMessage();
1791 // No data left, sorted forever, work through what is left.
1792 if (!m) {
1793 sorted_until_ = monotonic_clock::max_time;
1794 break;
1795 }
1796
Austin Schuh48507722021-07-17 17:29:24 -07001797 size_t monotonic_timestamp_boot = 0;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001798 if (m->has_monotonic_timestamp_time) {
Austin Schuh48507722021-07-17 17:29:24 -07001799 monotonic_timestamp_boot = parts().logger_boot_count;
1800 }
1801 size_t monotonic_remote_boot = 0xffffff;
1802
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001803 if (m->monotonic_remote_time.has_value()) {
Austin Schuh60e77942022-05-16 17:48:24 -07001804 const Node *node =
1805 parts().config->nodes()->Get(source_node_index_[m->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -07001806
Austin Schuh48507722021-07-17 17:29:24 -07001807 std::optional<size_t> boot = parts_message_reader_.boot_count(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001808 source_node_index_[m->channel_index]);
milind-ua50344f2021-08-25 18:22:20 -07001809 CHECK(boot) << ": Failed to find boot for node " << MaybeNodeName(node)
Austin Schuh60e77942022-05-16 17:48:24 -07001810 << ", with index " << source_node_index_[m->channel_index];
Austin Schuh48507722021-07-17 17:29:24 -07001811 monotonic_remote_boot = *boot;
1812 }
1813
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001814 messages_.insert(
1815 Message{.channel_index = m->channel_index,
1816 .queue_index = BootQueueIndex{.boot = parts().boot_count,
1817 .index = m->queue_index},
1818 .timestamp = BootTimestamp{.boot = parts().boot_count,
1819 .time = m->monotonic_sent_time},
1820 .monotonic_remote_boot = monotonic_remote_boot,
1821 .monotonic_timestamp_boot = monotonic_timestamp_boot,
1822 .data = std::move(m)});
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001823
1824 // Now, update sorted_until_ to match the new message.
1825 if (parts_message_reader_.newest_timestamp() >
1826 monotonic_clock::min_time +
1827 parts_message_reader_.max_out_of_order_duration()) {
1828 sorted_until_ = parts_message_reader_.newest_timestamp() -
1829 parts_message_reader_.max_out_of_order_duration();
1830 } else {
1831 sorted_until_ = monotonic_clock::min_time;
1832 }
1833 }
1834 }
1835
1836 // Now that we have enough data queued, return a pointer to the oldest piece
1837 // of data if it exists.
1838 if (messages_.empty()) {
Austin Schuhb000de62020-12-03 22:00:40 -08001839 last_message_time_ = monotonic_clock::max_time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001840 return nullptr;
1841 }
1842
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001843 CHECK_GE(messages_.begin()->timestamp.time, last_message_time_)
Austin Schuh315b96b2020-12-11 21:21:12 -08001844 << DebugString() << " reading " << parts_message_reader_.filename();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001845 last_message_time_ = messages_.begin()->timestamp.time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001846 return &(*messages_.begin());
1847}
1848
1849void LogPartsSorter::PopFront() { messages_.erase(messages_.begin()); }
1850
1851std::string LogPartsSorter::DebugString() const {
1852 std::stringstream ss;
1853 ss << "messages: [\n";
Austin Schuh315b96b2020-12-11 21:21:12 -08001854 int count = 0;
1855 bool no_dots = true;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001856 for (const Message &m : messages_) {
Austin Schuh315b96b2020-12-11 21:21:12 -08001857 if (count < 15 || count > static_cast<int>(messages_.size()) - 15) {
1858 ss << m << "\n";
1859 } else if (no_dots) {
1860 ss << "...\n";
1861 no_dots = false;
1862 }
1863 ++count;
Austin Schuh4b5c22a2020-11-30 22:58:43 -08001864 }
1865 ss << "] <- " << parts_message_reader_.filename();
1866 return ss.str();
1867}
1868
Austin Schuhd2f96102020-12-01 20:27:29 -08001869NodeMerger::NodeMerger(std::vector<LogParts> parts) {
1870 CHECK_GE(parts.size(), 1u);
Austin Schuh715adc12021-06-29 22:07:39 -07001871 // Enforce that we are sorting things only from a single node from a single
1872 // boot.
1873 const std::string_view part0_node = parts[0].node;
1874 const std::string_view part0_source_boot_uuid = parts[0].source_boot_uuid;
Austin Schuhd2f96102020-12-01 20:27:29 -08001875 for (size_t i = 1; i < parts.size(); ++i) {
1876 CHECK_EQ(part0_node, parts[i].node) << ": Can't merge different nodes.";
Austin Schuh715adc12021-06-29 22:07:39 -07001877 CHECK_EQ(part0_source_boot_uuid, parts[i].source_boot_uuid)
1878 << ": Can't merge different boots.";
Austin Schuhd2f96102020-12-01 20:27:29 -08001879 }
Austin Schuh715adc12021-06-29 22:07:39 -07001880
1881 node_ = configuration::GetNodeIndex(parts[0].config.get(), part0_node);
1882
Austin Schuhd2f96102020-12-01 20:27:29 -08001883 for (LogParts &part : parts) {
1884 parts_sorters_.emplace_back(std::move(part));
1885 }
1886
Austin Schuhd2f96102020-12-01 20:27:29 -08001887 monotonic_start_time_ = monotonic_clock::max_time;
Austin Schuh9dc42612021-09-20 20:41:29 -07001888 realtime_start_time_ = realtime_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001889 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001890 // We want to capture the earliest meaningful start time here. The start
1891 // time defaults to min_time when there's no meaningful value to report, so
1892 // let's ignore those.
Austin Schuh9dc42612021-09-20 20:41:29 -07001893 if (parts_sorter.monotonic_start_time() != monotonic_clock::min_time) {
1894 bool accept = false;
1895 // We want to prioritize start times from the logger node. Really, we
1896 // want to prioritize start times with a valid realtime_clock time. So,
1897 // if we have a start time without a RT clock, prefer a start time with a
1898 // RT clock, even it if is later.
1899 if (parts_sorter.realtime_start_time() != realtime_clock::min_time) {
1900 // We've got a good one. See if the current start time has a good RT
1901 // clock, or if we should use this one instead.
1902 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
1903 accept = true;
1904 } else if (realtime_start_time_ == realtime_clock::min_time) {
1905 // The previous start time doesn't have a good RT time, so it is very
1906 // likely the start time from a remote part file. We just found a
1907 // better start time with a real RT time, so switch to that instead.
1908 accept = true;
1909 }
1910 } else if (realtime_start_time_ == realtime_clock::min_time) {
1911 // We don't have a RT time, so take the oldest.
1912 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
1913 accept = true;
1914 }
1915 }
1916
1917 if (accept) {
1918 monotonic_start_time_ = parts_sorter.monotonic_start_time();
1919 realtime_start_time_ = parts_sorter.realtime_start_time();
1920 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001921 }
1922 }
Sanjay Narayanan9896c752021-09-01 16:16:48 -07001923
1924 // If there was no meaningful start time reported, just use min_time.
1925 if (monotonic_start_time_ == monotonic_clock::max_time) {
1926 monotonic_start_time_ = monotonic_clock::min_time;
1927 realtime_start_time_ = realtime_clock::min_time;
1928 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001929}
Austin Schuh8f52ed52020-11-30 23:12:39 -08001930
Austin Schuh0ca51f32020-12-25 21:51:45 -08001931std::vector<const LogParts *> NodeMerger::Parts() const {
1932 std::vector<const LogParts *> p;
1933 p.reserve(parts_sorters_.size());
1934 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
1935 p.emplace_back(&parts_sorter.parts());
1936 }
1937 return p;
1938}
1939
Austin Schuh8f52ed52020-11-30 23:12:39 -08001940Message *NodeMerger::Front() {
1941 // Return the current Front if we have one, otherwise go compute one.
1942 if (current_ != nullptr) {
Austin Schuhb000de62020-12-03 22:00:40 -08001943 Message *result = current_->Front();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001944 CHECK_GE(result->timestamp.time, last_message_time_);
Austin Schuhb000de62020-12-03 22:00:40 -08001945 return result;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001946 }
1947
1948 // Otherwise, do a simple search for the oldest message, deduplicating any
1949 // duplicates.
1950 Message *oldest = nullptr;
1951 sorted_until_ = monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08001952 for (LogPartsSorter &parts_sorter : parts_sorters_) {
1953 Message *m = parts_sorter.Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -08001954 if (!m) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001955 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001956 continue;
1957 }
1958 if (oldest == nullptr || *m < *oldest) {
1959 oldest = m;
Austin Schuhd2f96102020-12-01 20:27:29 -08001960 current_ = &parts_sorter;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001961 } else if (*m == *oldest) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001962 // Found a duplicate. If there is a choice, we want the one which has
1963 // the timestamp time.
1964 if (!m->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001965 parts_sorter.PopFront();
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001966 } else if (!oldest->data->has_monotonic_timestamp_time) {
Austin Schuh8bf1e632021-01-02 22:41:04 -08001967 current_->PopFront();
1968 current_ = &parts_sorter;
1969 oldest = m;
1970 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001971 CHECK_EQ(m->data->monotonic_timestamp_time,
1972 oldest->data->monotonic_timestamp_time);
Austin Schuh8bf1e632021-01-02 22:41:04 -08001973 parts_sorter.PopFront();
1974 }
Austin Schuh8f52ed52020-11-30 23:12:39 -08001975 }
1976
1977 // PopFront may change this, so compute it down here.
Austin Schuhd2f96102020-12-01 20:27:29 -08001978 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -08001979 }
1980
Austin Schuhb000de62020-12-03 22:00:40 -08001981 if (oldest) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001982 CHECK_GE(oldest->timestamp.time, last_message_time_);
1983 last_message_time_ = oldest->timestamp.time;
Austin Schuh5dd22842021-11-17 16:09:39 -08001984 monotonic_oldest_time_ =
1985 std::min(monotonic_oldest_time_, oldest->timestamp.time);
Austin Schuhb000de62020-12-03 22:00:40 -08001986 } else {
1987 last_message_time_ = monotonic_clock::max_time;
1988 }
1989
Austin Schuh8f52ed52020-11-30 23:12:39 -08001990 // Return the oldest message found. This will be nullptr if nothing was
1991 // found, indicating there is nothing left.
1992 return oldest;
1993}
1994
1995void NodeMerger::PopFront() {
1996 CHECK(current_ != nullptr) << "Popping before calling Front()";
1997 current_->PopFront();
1998 current_ = nullptr;
1999}
2000
Austin Schuhf16ef6a2021-06-30 21:48:17 -07002001BootMerger::BootMerger(std::vector<LogParts> files) {
2002 std::vector<std::vector<LogParts>> boots;
2003
2004 // Now, we need to split things out by boot.
2005 for (size_t i = 0; i < files.size(); ++i) {
Austin Schuhf16ef6a2021-06-30 21:48:17 -07002006 const size_t boot_count = files[i].boot_count;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07002007 if (boot_count + 1 > boots.size()) {
2008 boots.resize(boot_count + 1);
2009 }
2010 boots[boot_count].emplace_back(std::move(files[i]));
2011 }
2012
2013 node_mergers_.reserve(boots.size());
2014 for (size_t i = 0; i < boots.size(); ++i) {
Austin Schuh48507722021-07-17 17:29:24 -07002015 VLOG(2) << "Boot " << i;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07002016 for (auto &p : boots[i]) {
Austin Schuh48507722021-07-17 17:29:24 -07002017 VLOG(2) << "Part " << p;
Austin Schuhf16ef6a2021-06-30 21:48:17 -07002018 }
2019 node_mergers_.emplace_back(
2020 std::make_unique<NodeMerger>(std::move(boots[i])));
2021 }
2022}
2023
2024Message *BootMerger::Front() {
2025 Message *result = node_mergers_[index_]->Front();
2026
2027 if (result != nullptr) {
2028 return result;
2029 }
2030
2031 if (index_ + 1u == node_mergers_.size()) {
2032 // At the end of the last node merger, just return.
2033 return nullptr;
2034 } else {
2035 ++index_;
2036 return Front();
2037 }
2038}
2039
2040void BootMerger::PopFront() { node_mergers_[index_]->PopFront(); }
2041
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002042std::vector<const LogParts *> BootMerger::Parts() const {
2043 std::vector<const LogParts *> results;
2044 for (const std::unique_ptr<NodeMerger> &node_merger : node_mergers_) {
2045 std::vector<const LogParts *> node_parts = node_merger->Parts();
2046
2047 results.insert(results.end(), std::make_move_iterator(node_parts.begin()),
2048 std::make_move_iterator(node_parts.end()));
2049 }
2050
2051 return results;
2052}
2053
Austin Schuhd2f96102020-12-01 20:27:29 -08002054TimestampMapper::TimestampMapper(std::vector<LogParts> parts)
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002055 : boot_merger_(std::move(parts)),
Austin Schuh79b30942021-01-24 22:32:21 -08002056 timestamp_callback_([](TimestampedMessage *) {}) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002057 for (const LogParts *part : boot_merger_.Parts()) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08002058 if (!configuration_) {
2059 configuration_ = part->config;
2060 } else {
2061 CHECK_EQ(configuration_.get(), part->config.get());
2062 }
2063 }
2064 const Configuration *config = configuration_.get();
Austin Schuhd2f96102020-12-01 20:27:29 -08002065 // Only fill out nodes_data_ if there are nodes. Otherwise everything gets
2066 // pretty simple.
2067 if (configuration::MultiNode(config)) {
2068 nodes_data_.resize(config->nodes()->size());
2069 const Node *my_node = config->nodes()->Get(node());
2070 for (size_t node_index = 0; node_index < nodes_data_.size(); ++node_index) {
2071 const Node *node = config->nodes()->Get(node_index);
2072 NodeData *node_data = &nodes_data_[node_index];
2073 node_data->channels.resize(config->channels()->size());
2074 // We should save the channel if it is delivered to the node represented
2075 // by the NodeData, but not sent by that node. That combo means it is
2076 // forwarded.
2077 size_t channel_index = 0;
2078 node_data->any_delivered = false;
2079 for (const Channel *channel : *config->channels()) {
2080 node_data->channels[channel_index].delivered =
2081 configuration::ChannelIsReadableOnNode(channel, node) &&
Austin Schuhb3dbb6d2021-01-02 17:29:35 -08002082 configuration::ChannelIsSendableOnNode(channel, my_node) &&
2083 (my_node != node);
Austin Schuhd2f96102020-12-01 20:27:29 -08002084 node_data->any_delivered = node_data->any_delivered ||
2085 node_data->channels[channel_index].delivered;
Austin Schuh6a7358f2021-11-18 22:40:40 -08002086 if (node_data->channels[channel_index].delivered) {
2087 const Connection *connection =
2088 configuration::ConnectionToNode(channel, node);
2089 node_data->channels[channel_index].time_to_live =
2090 chrono::nanoseconds(connection->time_to_live());
2091 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002092 ++channel_index;
2093 }
2094 }
2095
2096 for (const Channel *channel : *config->channels()) {
2097 source_node_.emplace_back(configuration::GetNodeIndex(
2098 config, channel->source_node()->string_view()));
2099 }
2100 }
2101}
2102
2103void TimestampMapper::AddPeer(TimestampMapper *timestamp_mapper) {
Austin Schuh0ca51f32020-12-25 21:51:45 -08002104 CHECK(configuration::MultiNode(configuration()));
Austin Schuhd2f96102020-12-01 20:27:29 -08002105 CHECK_NE(timestamp_mapper->node(), node());
2106 CHECK_LT(timestamp_mapper->node(), nodes_data_.size());
2107
2108 NodeData *node_data = &nodes_data_[timestamp_mapper->node()];
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002109 // Only set it if this node delivers to the peer timestamp_mapper. Otherwise
Austin Schuhd2f96102020-12-01 20:27:29 -08002110 // we could needlessly save data.
2111 if (node_data->any_delivered) {
Austin Schuh87dd3832021-01-01 23:07:31 -08002112 VLOG(1) << "Registering on node " << node() << " for peer node "
2113 << timestamp_mapper->node();
Austin Schuhd2f96102020-12-01 20:27:29 -08002114 CHECK(timestamp_mapper->nodes_data_[node()].peer == nullptr);
2115
2116 timestamp_mapper->nodes_data_[node()].peer = this;
Austin Schuh36c00932021-07-19 18:13:21 -07002117
2118 node_data->save_for_peer = true;
Austin Schuhd2f96102020-12-01 20:27:29 -08002119 }
2120}
2121
Austin Schuh79b30942021-01-24 22:32:21 -08002122void TimestampMapper::QueueMessage(Message *m) {
Austin Schuh60e77942022-05-16 17:48:24 -07002123 matched_messages_.emplace_back(
2124 TimestampedMessage{.channel_index = m->channel_index,
2125 .queue_index = m->queue_index,
2126 .monotonic_event_time = m->timestamp,
2127 .realtime_event_time = m->data->realtime_sent_time,
2128 .remote_queue_index = BootQueueIndex::Invalid(),
2129 .monotonic_remote_time = BootTimestamp::min_time(),
2130 .realtime_remote_time = realtime_clock::min_time,
2131 .monotonic_timestamp_time = BootTimestamp::min_time(),
2132 .data = std::move(m->data)});
Austin Schuhd2f96102020-12-01 20:27:29 -08002133}
2134
2135TimestampedMessage *TimestampMapper::Front() {
2136 // No need to fetch anything new. A previous message still exists.
2137 switch (first_message_) {
2138 case FirstMessage::kNeedsUpdate:
2139 break;
2140 case FirstMessage::kInMessage:
Austin Schuh79b30942021-01-24 22:32:21 -08002141 return &matched_messages_.front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002142 case FirstMessage::kNullptr:
2143 return nullptr;
2144 }
2145
Austin Schuh79b30942021-01-24 22:32:21 -08002146 if (matched_messages_.empty()) {
2147 if (!QueueMatched()) {
2148 first_message_ = FirstMessage::kNullptr;
2149 return nullptr;
2150 }
2151 }
2152 first_message_ = FirstMessage::kInMessage;
2153 return &matched_messages_.front();
2154}
2155
2156bool TimestampMapper::QueueMatched() {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002157 MatchResult result = MatchResult::kEndOfFile;
2158 do {
2159 result = MaybeQueueMatched();
2160 } while (result == MatchResult::kSkipped);
2161 return result == MatchResult::kQueued;
2162}
2163
2164bool TimestampMapper::CheckReplayChannelsAndMaybePop(
2165 const TimestampedMessage & /*message*/) {
2166 if (replay_channels_callback_ &&
2167 !replay_channels_callback_(matched_messages_.back())) {
2168 matched_messages_.pop_back();
2169 return true;
2170 }
2171 return false;
2172}
2173
2174TimestampMapper::MatchResult TimestampMapper::MaybeQueueMatched() {
Austin Schuhd2f96102020-12-01 20:27:29 -08002175 if (nodes_data_.empty()) {
2176 // Simple path. We are single node, so there are no timestamps to match!
2177 CHECK_EQ(messages_.size(), 0u);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002178 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002179 if (!m) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002180 return MatchResult::kEndOfFile;
Austin Schuhd2f96102020-12-01 20:27:29 -08002181 }
Austin Schuh79b30942021-01-24 22:32:21 -08002182 // Enqueue this message into matched_messages_ so we have a place to
2183 // associate remote timestamps, and return it.
2184 QueueMessage(m);
Austin Schuhd2f96102020-12-01 20:27:29 -08002185
Austin Schuh79b30942021-01-24 22:32:21 -08002186 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
2187 last_message_time_ = matched_messages_.back().monotonic_event_time;
2188
2189 // We are thin wrapper around node_merger. Call it directly.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002190 boot_merger_.PopFront();
Austin Schuh79b30942021-01-24 22:32:21 -08002191 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002192 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2193 return MatchResult::kSkipped;
2194 }
2195 return MatchResult::kQueued;
Austin Schuhd2f96102020-12-01 20:27:29 -08002196 }
2197
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002198 // We need to only add messages to the list so they get processed for
2199 // messages which are delivered. Reuse the flow below which uses messages_
2200 // by just adding the new message to messages_ and continuing.
Austin Schuhd2f96102020-12-01 20:27:29 -08002201 if (messages_.empty()) {
2202 if (!Queue()) {
2203 // Found nothing to add, we are out of data!
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002204 return MatchResult::kEndOfFile;
Austin Schuhd2f96102020-12-01 20:27:29 -08002205 }
2206
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002207 // Now that it has been added (and cannibalized), forget about it
2208 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002209 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08002210 }
2211
2212 Message *m = &(messages_.front());
2213
2214 if (source_node_[m->channel_index] == node()) {
2215 // From us, just forward it on, filling the remote data in as invalid.
Austin Schuh79b30942021-01-24 22:32:21 -08002216 QueueMessage(m);
2217 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
2218 last_message_time_ = matched_messages_.back().monotonic_event_time;
2219 messages_.pop_front();
2220 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002221 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2222 return MatchResult::kSkipped;
2223 }
2224 return MatchResult::kQueued;
Austin Schuhd2f96102020-12-01 20:27:29 -08002225 } else {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002226 // Got a timestamp, find the matching remote data, match it, and return
2227 // it.
Austin Schuhd2f96102020-12-01 20:27:29 -08002228 Message data = MatchingMessageFor(*m);
2229
2230 // Return the data from the remote. The local message only has timestamp
2231 // info which isn't relevant anymore once extracted.
Austin Schuh79b30942021-01-24 22:32:21 -08002232 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -08002233 .channel_index = m->channel_index,
2234 .queue_index = m->queue_index,
2235 .monotonic_event_time = m->timestamp,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002236 .realtime_event_time = m->data->realtime_sent_time,
Austin Schuh58646e22021-08-23 23:51:46 -07002237 .remote_queue_index =
2238 BootQueueIndex{.boot = m->monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002239 .index = m->data->remote_queue_index.value()},
2240 .monotonic_remote_time = {m->monotonic_remote_boot,
Austin Schuh826e6ce2021-11-18 20:33:10 -08002241 m->data->monotonic_remote_time.value()},
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002242 .realtime_remote_time = m->data->realtime_remote_time.value(),
2243 .monotonic_timestamp_time = {m->monotonic_timestamp_boot,
2244 m->data->monotonic_timestamp_time},
Austin Schuh79b30942021-01-24 22:32:21 -08002245 .data = std::move(data.data)});
2246 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
2247 last_message_time_ = matched_messages_.back().monotonic_event_time;
2248 // Since messages_ holds the data, drop it.
2249 messages_.pop_front();
2250 timestamp_callback_(&matched_messages_.back());
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002251 if (CheckReplayChannelsAndMaybePop(matched_messages_.back())) {
2252 return MatchResult::kSkipped;
2253 }
2254 return MatchResult::kQueued;
Austin Schuh79b30942021-01-24 22:32:21 -08002255 }
2256}
2257
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002258void TimestampMapper::QueueUntil(BootTimestamp queue_time) {
Austin Schuh79b30942021-01-24 22:32:21 -08002259 while (last_message_time_ <= queue_time) {
2260 if (!QueueMatched()) {
2261 return;
2262 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002263 }
2264}
2265
Austin Schuhe639ea12021-01-25 13:00:22 -08002266void TimestampMapper::QueueFor(chrono::nanoseconds time_estimation_buffer) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002267 // Note: queueing for time doesn't really work well across boots. So we
2268 // just assume that if you are using this, you only care about the current
2269 // boot.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002270 //
2271 // TODO(austin): Is that the right concept?
2272 //
Austin Schuhe639ea12021-01-25 13:00:22 -08002273 // Make sure we have something queued first. This makes the end time
2274 // calculation simpler, and is typically what folks want regardless.
2275 if (matched_messages_.empty()) {
2276 if (!QueueMatched()) {
2277 return;
2278 }
2279 }
2280
2281 const aos::monotonic_clock::time_point end_queue_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002282 std::max(monotonic_start_time(
2283 matched_messages_.front().monotonic_event_time.boot),
2284 matched_messages_.front().monotonic_event_time.time) +
Austin Schuhe639ea12021-01-25 13:00:22 -08002285 time_estimation_buffer;
2286
2287 // Place sorted messages on the list until we have
2288 // --time_estimation_buffer_seconds seconds queued up (but queue at least
2289 // until the log starts).
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002290 while (end_queue_time >= last_message_time_.time) {
Austin Schuhe639ea12021-01-25 13:00:22 -08002291 if (!QueueMatched()) {
2292 return;
2293 }
2294 }
2295}
2296
Austin Schuhd2f96102020-12-01 20:27:29 -08002297void TimestampMapper::PopFront() {
2298 CHECK(first_message_ != FirstMessage::kNeedsUpdate);
Austin Schuh6a7358f2021-11-18 22:40:40 -08002299 last_popped_message_time_ = Front()->monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08002300 first_message_ = FirstMessage::kNeedsUpdate;
2301
Austin Schuh79b30942021-01-24 22:32:21 -08002302 matched_messages_.pop_front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002303}
2304
2305Message TimestampMapper::MatchingMessageFor(const Message &message) {
Austin Schuhd2f96102020-12-01 20:27:29 -08002306 // Figure out what queue index we are looking for.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002307 CHECK_NOTNULL(message.data);
2308 CHECK(message.data->remote_queue_index.has_value());
Austin Schuh58646e22021-08-23 23:51:46 -07002309 const BootQueueIndex remote_queue_index =
2310 BootQueueIndex{.boot = message.monotonic_remote_boot,
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002311 .index = *message.data->remote_queue_index};
Austin Schuhd2f96102020-12-01 20:27:29 -08002312
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002313 CHECK(message.data->monotonic_remote_time.has_value());
2314 CHECK(message.data->realtime_remote_time.has_value());
Austin Schuhd2f96102020-12-01 20:27:29 -08002315
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002316 const BootTimestamp monotonic_remote_time{
Austin Schuh48507722021-07-17 17:29:24 -07002317 .boot = message.monotonic_remote_boot,
Austin Schuh826e6ce2021-11-18 20:33:10 -08002318 .time = message.data->monotonic_remote_time.value()};
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002319 const realtime_clock::time_point realtime_remote_time =
2320 *message.data->realtime_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -08002321
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002322 TimestampMapper *peer =
2323 nodes_data_[source_node_[message.data->channel_index]].peer;
Austin Schuhfecf1d82020-12-19 16:57:28 -08002324
2325 // We only register the peers which we have data for. So, if we are being
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002326 // asked to pull a timestamp from a peer which doesn't exist, return an
2327 // empty message.
Austin Schuhfecf1d82020-12-19 16:57:28 -08002328 if (peer == nullptr) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002329 // TODO(austin): Make sure the tests hit all these paths with a boot count
2330 // of 1...
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002331 return Message{.channel_index = message.channel_index,
2332 .queue_index = remote_queue_index,
2333 .timestamp = monotonic_remote_time,
2334 .monotonic_remote_boot = 0xffffff,
2335 .monotonic_timestamp_boot = 0xffffff,
2336 .data = nullptr};
Austin Schuhfecf1d82020-12-19 16:57:28 -08002337 }
2338
2339 // The queue which will have the matching data, if available.
2340 std::deque<Message> *data_queue =
2341 &peer->nodes_data_[node()].channels[message.channel_index].messages;
2342
Austin Schuh79b30942021-01-24 22:32:21 -08002343 peer->QueueUnmatchedUntil(monotonic_remote_time);
Austin Schuhd2f96102020-12-01 20:27:29 -08002344
2345 if (data_queue->empty()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002346 return Message{.channel_index = message.channel_index,
2347 .queue_index = remote_queue_index,
2348 .timestamp = monotonic_remote_time,
2349 .monotonic_remote_boot = 0xffffff,
2350 .monotonic_timestamp_boot = 0xffffff,
2351 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08002352 }
2353
Austin Schuhd2f96102020-12-01 20:27:29 -08002354 if (remote_queue_index < data_queue->front().queue_index ||
2355 remote_queue_index > data_queue->back().queue_index) {
Austin Schuh60e77942022-05-16 17:48:24 -07002356 return Message{.channel_index = message.channel_index,
2357 .queue_index = remote_queue_index,
2358 .timestamp = monotonic_remote_time,
2359 .monotonic_remote_boot = 0xffffff,
2360 .monotonic_timestamp_boot = 0xffffff,
2361 .data = nullptr};
Austin Schuhd2f96102020-12-01 20:27:29 -08002362 }
2363
Austin Schuh993ccb52020-12-12 15:59:32 -08002364 // The algorithm below is constant time with some assumptions. We need there
2365 // to be no missing messages in the data stream. This also assumes a queue
2366 // hasn't wrapped. That is conservative, but should let us get started.
Austin Schuh58646e22021-08-23 23:51:46 -07002367 if (data_queue->back().queue_index.boot ==
2368 data_queue->front().queue_index.boot &&
2369 (data_queue->back().queue_index.index -
2370 data_queue->front().queue_index.index + 1u ==
2371 data_queue->size())) {
2372 CHECK_EQ(remote_queue_index.boot, data_queue->front().queue_index.boot);
Austin Schuh993ccb52020-12-12 15:59:32 -08002373 // Pull the data out and confirm that the timestamps match as expected.
Austin Schuh58646e22021-08-23 23:51:46 -07002374 //
2375 // TODO(austin): Move if not reliable.
2376 Message result = (*data_queue)[remote_queue_index.index -
2377 data_queue->front().queue_index.index];
Austin Schuh993ccb52020-12-12 15:59:32 -08002378
2379 CHECK_EQ(result.timestamp, monotonic_remote_time)
2380 << ": Queue index matches, but timestamp doesn't. Please investigate!";
Austin Schuh6a7358f2021-11-18 22:40:40 -08002381 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
Austin Schuh993ccb52020-12-12 15:59:32 -08002382 << ": Queue index matches, but timestamp doesn't. Please investigate!";
2383 // Now drop the data off the front. We have deduplicated timestamps, so we
2384 // are done. And all the data is in order.
Austin Schuh58646e22021-08-23 23:51:46 -07002385 data_queue->erase(
2386 data_queue->begin(),
2387 data_queue->begin() +
2388 (remote_queue_index.index - data_queue->front().queue_index.index));
Austin Schuh993ccb52020-12-12 15:59:32 -08002389 return result;
2390 } else {
Austin Schuh58646e22021-08-23 23:51:46 -07002391 // TODO(austin): Binary search.
2392 auto it = std::find_if(
2393 data_queue->begin(), data_queue->end(),
2394 [remote_queue_index,
2395 remote_boot = monotonic_remote_time.boot](const Message &m) {
2396 return m.queue_index == remote_queue_index &&
2397 m.timestamp.boot == remote_boot;
2398 });
Austin Schuh993ccb52020-12-12 15:59:32 -08002399 if (it == data_queue->end()) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002400 return Message{.channel_index = message.channel_index,
2401 .queue_index = remote_queue_index,
2402 .timestamp = monotonic_remote_time,
2403 .monotonic_remote_boot = 0xffffff,
2404 .monotonic_timestamp_boot = 0xffffff,
2405 .data = nullptr};
Austin Schuh993ccb52020-12-12 15:59:32 -08002406 }
2407
2408 Message result = std::move(*it);
2409
2410 CHECK_EQ(result.timestamp, monotonic_remote_time)
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002411 << ": Queue index matches, but timestamp doesn't. Please "
2412 "investigate!";
2413 CHECK_EQ(result.data->realtime_sent_time, realtime_remote_time)
2414 << ": Queue index matches, but timestamp doesn't. Please "
2415 "investigate!";
Austin Schuh993ccb52020-12-12 15:59:32 -08002416
Austin Schuhd6b1f4c2021-11-18 20:29:00 -08002417 // Erase everything up to this message. We want to keep 1 message in the
2418 // queue so we can handle reliable messages forwarded across boots.
2419 data_queue->erase(data_queue->begin(), it);
Austin Schuh993ccb52020-12-12 15:59:32 -08002420
2421 return result;
2422 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002423}
2424
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002425void TimestampMapper::QueueUnmatchedUntil(BootTimestamp t) {
Austin Schuhd2f96102020-12-01 20:27:29 -08002426 if (queued_until_ > t) {
2427 return;
2428 }
2429 while (true) {
2430 if (!messages_.empty() && messages_.back().timestamp > t) {
2431 queued_until_ = std::max(queued_until_, messages_.back().timestamp);
2432 return;
2433 }
2434
2435 if (!Queue()) {
2436 // Found nothing to add, we are out of data!
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002437 queued_until_ = BootTimestamp::max_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08002438 return;
2439 }
2440
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07002441 // Now that it has been added (and cannibalized), forget about it
2442 // upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002443 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08002444 }
2445}
2446
2447bool TimestampMapper::Queue() {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002448 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08002449 if (m == nullptr) {
2450 return false;
2451 }
2452 for (NodeData &node_data : nodes_data_) {
2453 if (!node_data.any_delivered) continue;
Austin Schuh36c00932021-07-19 18:13:21 -07002454 if (!node_data.save_for_peer) continue;
Austin Schuhd2f96102020-12-01 20:27:29 -08002455 if (node_data.channels[m->channel_index].delivered) {
Austin Schuh6a7358f2021-11-18 22:40:40 -08002456 // If we have data but no timestamps (logs where the timestamps didn't get
2457 // logged are classic), we can grow this indefinitely. We don't need to
2458 // keep anything that is older than the last message returned.
2459
2460 // We have the time on the source node.
2461 // We care to wait until we have the time on the destination node.
2462 std::deque<Message> &messages =
2463 node_data.channels[m->channel_index].messages;
2464 // Max delay over the network is the TTL, so let's take the queue time and
2465 // add TTL to it. Don't forget any messages which are reliable until
2466 // someone can come up with a good reason to forget those too.
2467 if (node_data.channels[m->channel_index].time_to_live >
2468 chrono::nanoseconds(0)) {
2469 // We need to make *some* assumptions about network delay for this to
2470 // work. We want to only look at the RX side. This means we need to
2471 // track the last time a message was popped from any channel from the
2472 // node sending this message, and compare that to the max time we expect
2473 // that a message will take to be delivered across the network. This
2474 // assumes that messages are popped in time order as a proxy for
2475 // measuring the distributed time at this layer.
2476 //
2477 // Leave at least 1 message in here so we can handle reboots and
2478 // messages getting sent twice.
2479 while (messages.size() > 1u &&
2480 messages.begin()->timestamp +
2481 node_data.channels[m->channel_index].time_to_live +
2482 chrono::duration_cast<chrono::nanoseconds>(
2483 chrono::duration<double>(FLAGS_max_network_delay)) <
2484 last_popped_message_time_) {
2485 messages.pop_front();
2486 }
2487 }
Austin Schuhd2f96102020-12-01 20:27:29 -08002488 node_data.channels[m->channel_index].messages.emplace_back(*m);
2489 }
2490 }
2491
2492 messages_.emplace_back(std::move(*m));
2493 return true;
2494}
2495
2496std::string TimestampMapper::DebugString() const {
2497 std::stringstream ss;
Austin Schuh6e014b82021-09-14 17:46:33 -07002498 ss << "node " << node() << " (" << node_name() << ") [\n";
Austin Schuhd2f96102020-12-01 20:27:29 -08002499 for (const Message &message : messages_) {
2500 ss << " " << message << "\n";
2501 }
2502 ss << "] queued_until " << queued_until_;
2503 for (const NodeData &ns : nodes_data_) {
2504 if (ns.peer == nullptr) continue;
2505 ss << "\nnode " << ns.peer->node() << " remote_data [\n";
2506 size_t channel_index = 0;
2507 for (const NodeData::ChannelData &channel_data :
2508 ns.peer->nodes_data_[node()].channels) {
2509 if (channel_data.messages.empty()) {
2510 continue;
2511 }
Austin Schuhb000de62020-12-03 22:00:40 -08002512
Austin Schuhd2f96102020-12-01 20:27:29 -08002513 ss << " channel " << channel_index << " [\n";
2514 for (const Message &m : channel_data.messages) {
2515 ss << " " << m << "\n";
2516 }
2517 ss << " ]\n";
2518 ++channel_index;
2519 }
2520 ss << "] queued_until " << ns.peer->queued_until_;
2521 }
2522 return ss.str();
2523}
2524
Austin Schuhee711052020-08-24 16:06:09 -07002525std::string MaybeNodeName(const Node *node) {
2526 if (node != nullptr) {
2527 return node->name()->str() + " ";
2528 }
2529 return "";
2530}
2531
Brian Silvermanf51499a2020-09-21 12:49:08 -07002532} // namespace aos::logger