blob: d781a20c378a6d7ad5a1cda4a360b9a865badc30 [file] [log] [blame]
Austin Schuha36c8902019-12-30 18:07:15 -08001#ifndef AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_
2#define AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_
3
4#include <sys/uio.h>
5
Austin Schuh97789fc2020-08-01 14:42:45 -07006#include <chrono>
Austin Schuh05b70472020-01-01 17:11:17 -08007#include <deque>
Austin Schuh97789fc2020-08-01 14:42:45 -07008#include <limits>
9#include <memory>
Austin Schuh05b70472020-01-01 17:11:17 -080010#include <optional>
Austin Schuhfa895892020-01-07 20:07:41 -080011#include <string>
Austin Schuha36c8902019-12-30 18:07:15 -080012#include <string_view>
Brian Silverman98360e22020-04-28 16:51:20 -070013#include <tuple>
Austin Schuh97789fc2020-08-01 14:42:45 -070014#include <utility>
Austin Schuha36c8902019-12-30 18:07:15 -080015#include <vector>
16
Austin Schuh4b5c22a2020-11-30 22:58:43 -080017#include "absl/container/btree_set.h"
Austin Schuh05b70472020-01-01 17:11:17 -080018#include "absl/types/span.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070019#include "flatbuffers/flatbuffers.h"
20
Austin Schuh63097262023-08-16 17:04:29 -070021#include "aos/configuration.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070022#include "aos/containers/resizeable_buffer.h"
Austin Schuha36c8902019-12-30 18:07:15 -080023#include "aos/events/event_loop.h"
Austin Schuh2dc8c7d2021-07-01 17:41:28 -070024#include "aos/events/logging/boot_timestamp.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070025#include "aos/events/logging/buffer_encoder.h"
Alexei Strots01395492023-03-20 13:59:56 -070026#include "aos/events/logging/log_backend.h"
Austin Schuhc41603c2020-10-11 16:17:37 -070027#include "aos/events/logging/logfile_sorting.h"
Austin Schuha36c8902019-12-30 18:07:15 -080028#include "aos/events/logging/logger_generated.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070029#include "aos/flatbuffers.h"
Austin Schuhf2d0e682022-10-16 14:20:58 -070030#include "aos/network/remote_message_generated.h"
Austin Schuha36c8902019-12-30 18:07:15 -080031
Brian Silvermanf51499a2020-09-21 12:49:08 -070032namespace aos::logger {
Austin Schuha36c8902019-12-30 18:07:15 -080033
34enum class LogType : uint8_t {
35 // The message originated on this node and should be logged here.
36 kLogMessage,
37 // The message originated on another node, but only the delivery times are
38 // logged here.
39 kLogDeliveryTimeOnly,
Austin Schuh6f3babe2020-01-26 20:34:50 -080040 // The message originated on the other node and should be logged on this node.
41 kLogRemoteMessage
Austin Schuha36c8902019-12-30 18:07:15 -080042};
43
Austin Schuha36c8902019-12-30 18:07:15 -080044// This class manages efficiently writing a sequence of detached buffers to a
Brian Silvermanf51499a2020-09-21 12:49:08 -070045// file. It encodes them, queues them up, and batches the write operation.
Alexei Strots01395492023-03-20 13:59:56 -070046
Austin Schuha36c8902019-12-30 18:07:15 -080047class DetachedBufferWriter {
48 public:
Brian Silvermana9f2ec92020-10-06 18:00:53 -070049 // Marker struct for one of our constructor overloads.
50 struct already_out_of_space_t {};
51
Alexei Strotsbc082d82023-05-03 08:43:42 -070052 DetachedBufferWriter(std::unique_ptr<LogSink> log_sink,
Austin Schuh48d10d62022-10-16 22:19:23 -070053 std::unique_ptr<DataEncoder> encoder);
Brian Silvermana9f2ec92020-10-06 18:00:53 -070054 // Creates a dummy instance which won't even open a file. It will act as if
55 // opening the file ran out of space immediately.
Philipp Schrader10397952023-06-15 11:43:07 -070056 DetachedBufferWriter(already_out_of_space_t);
Austin Schuh2f8fd752020-09-01 22:38:28 -070057 DetachedBufferWriter(DetachedBufferWriter &&other);
58 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
59
Philipp Schrader10397952023-06-15 11:43:07 -070060 virtual ~DetachedBufferWriter();
Austin Schuha36c8902019-12-30 18:07:15 -080061
Austin Schuh2f8fd752020-09-01 22:38:28 -070062 DetachedBufferWriter &operator=(DetachedBufferWriter &&other);
Brian Silverman98360e22020-04-28 16:51:20 -070063 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
64
Alexei Strotsbc082d82023-05-03 08:43:42 -070065 std::string_view name() const { return log_sink_->name(); }
Austin Schuh6f3babe2020-01-26 20:34:50 -080066
Brian Silvermana9f2ec92020-10-06 18:00:53 -070067 // This will be true until Close() is called, unless the file couldn't be
68 // created due to running out of space.
Alexei Strotsbc082d82023-05-03 08:43:42 -070069 bool is_open() const { return log_sink_->is_open(); }
Brian Silvermana9f2ec92020-10-06 18:00:53 -070070
Brian Silvermanf51499a2020-09-21 12:49:08 -070071 // Queues up a finished FlatBufferBuilder to be encoded and written.
72 //
73 // Triggers a flush if there's enough data queued up.
74 //
75 // Steals the detached buffer from it.
Austin Schuh48d10d62022-10-16 22:19:23 -070076 void CopyMessage(DataEncoder::Copier *coppier,
77 aos::monotonic_clock::time_point now);
Austin Schuha36c8902019-12-30 18:07:15 -080078
Brian Silverman0465fcf2020-09-24 00:29:18 -070079 // Indicates we got ENOSPC when trying to write. After this returns true, no
80 // further data is written.
81 bool ran_out_of_space() const { return ran_out_of_space_; }
82
83 // To avoid silently failing to write logfiles, you must call this before
84 // destruction if ran_out_of_space() is true and the situation has been
85 // handled.
86 void acknowledge_out_of_space() {
87 CHECK(ran_out_of_space_);
88 acknowledge_ran_out_of_space_ = true;
89 }
90
91 // Fully flushes and closes the underlying file now. No additional data may be
92 // enqueued after calling this.
93 //
94 // This will be performed in the destructor automatically.
95 //
96 // Note that this may set ran_out_of_space().
97 void Close();
98
Brian Silvermanf51499a2020-09-21 12:49:08 -070099 // Returns the total number of bytes written and currently queued.
Austin Schuha426f1f2021-03-31 22:27:41 -0700100 size_t total_bytes() const {
101 if (!encoder_) {
102 return 0;
103 }
104 return encoder_->total_bytes();
105 }
Austin Schuha36c8902019-12-30 18:07:15 -0800106
Alexei Strotsbc082d82023-05-03 08:43:42 -0700107 WriteStats *WriteStatistics() const { return log_sink_->WriteStatistics(); }
Brian Silverman98360e22020-04-28 16:51:20 -0700108
Austin Schuha36c8902019-12-30 18:07:15 -0800109 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700110 // Performs a single writev call with as much of the data we have queued up as
Austin Schuh8bdfc492023-02-11 12:53:13 -0800111 // possible. now is the time we flushed at, to be recorded in
112 // last_flush_time_.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700113 //
114 // This will normally take all of the data we have queued up, unless an
115 // encoder has spit out a big enough chunk all at once that we can't manage
116 // all of it.
Austin Schuh8bdfc492023-02-11 12:53:13 -0800117 void Flush(aos::monotonic_clock::time_point now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700118
Brian Silvermanf51499a2020-09-21 12:49:08 -0700119 // Flushes data if we've reached the threshold to do that as part of normal
Austin Schuhbd06ae42021-03-31 22:48:21 -0700120 // operation either due to the outstanding queued data, or because we have
121 // passed our flush period. now is the current time to save some CPU grabbing
122 // the current time. It just needs to be close.
123 void FlushAtThreshold(aos::monotonic_clock::time_point now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700124
Alexei Strotsbc082d82023-05-03 08:43:42 -0700125 std::unique_ptr<LogSink> log_sink_;
Austin Schuh48d10d62022-10-16 22:19:23 -0700126 std::unique_ptr<DataEncoder> encoder_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800127
Brian Silverman0465fcf2020-09-24 00:29:18 -0700128 bool ran_out_of_space_ = false;
129 bool acknowledge_ran_out_of_space_ = false;
Austin Schuha36c8902019-12-30 18:07:15 -0800130
Austin Schuhbd06ae42021-03-31 22:48:21 -0700131 aos::monotonic_clock::time_point last_flush_time_ =
132 aos::monotonic_clock::min_time;
Austin Schuha36c8902019-12-30 18:07:15 -0800133};
134
Austin Schuhf2d0e682022-10-16 14:20:58 -0700135// Repacks the provided RemoteMessage into fbb.
136flatbuffers::Offset<MessageHeader> PackRemoteMessage(
137 flatbuffers::FlatBufferBuilder *fbb,
138 const message_bridge::RemoteMessage *msg, int channel_index,
139 const aos::monotonic_clock::time_point monotonic_timestamp_time);
140
141constexpr flatbuffers::uoffset_t PackRemoteMessageSize() { return 96u; }
142size_t PackRemoteMessageInline(
143 uint8_t *data, const message_bridge::RemoteMessage *msg, int channel_index,
Austin Schuh71a40d42023-02-04 21:22:22 -0800144 const aos::monotonic_clock::time_point monotonic_timestamp_time,
145 size_t start_byte, size_t end_byte);
Austin Schuhf2d0e682022-10-16 14:20:58 -0700146
Austin Schuha36c8902019-12-30 18:07:15 -0800147// Packes a message pointed to by the context into a MessageHeader.
148flatbuffers::Offset<MessageHeader> PackMessage(
149 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
150 int channel_index, LogType log_type);
151
Austin Schuhfa30c352022-10-16 11:12:02 -0700152// Returns the size that the packed message from PackMessage or
153// PackMessageInline will be.
Austin Schuh48d10d62022-10-16 22:19:23 -0700154flatbuffers::uoffset_t PackMessageSize(LogType log_type, size_t data_size);
Austin Schuhfa30c352022-10-16 11:12:02 -0700155
156// Packs the provided message pointed to by context into the provided buffer.
157// This is equivalent to PackMessage, but doesn't require allocating a
158// FlatBufferBuilder underneath.
159size_t PackMessageInline(uint8_t *data, const Context &contex,
Austin Schuh71a40d42023-02-04 21:22:22 -0800160 int channel_index, LogType log_type, size_t start_byte,
161 size_t end_byte);
Austin Schuhfa30c352022-10-16 11:12:02 -0700162
Austin Schuh05b70472020-01-01 17:11:17 -0800163// Class to read chunks out of a log file.
164class SpanReader {
165 public:
Alexei Strotscee7b372023-04-21 11:57:54 -0700166 // It creates a reader and makes proper decoder based on information encoded
167 // in the filename.
Austin Schuhcd368422021-11-22 21:23:29 -0800168 SpanReader(std::string_view filename, bool quiet = false);
Austin Schuha36c8902019-12-30 18:07:15 -0800169
Alexei Strotscee7b372023-04-21 11:57:54 -0700170 // Opens new reader from provided decoder.
171 SpanReader(std::string_view filename, std::unique_ptr<DataDecoder> decoder);
172
Austin Schuh6f3babe2020-01-26 20:34:50 -0800173 std::string_view filename() const { return filename_; }
174
Brian Smarttea913d42021-12-10 15:02:38 -0800175 size_t TotalRead() const { return total_read_; }
176 size_t TotalConsumed() const { return total_consumed_; }
Austin Schuh60e77942022-05-16 17:48:24 -0700177 bool IsIncomplete() const {
178 return is_finished_ && total_consumed_ < total_read_;
179 }
Brian Smarttea913d42021-12-10 15:02:38 -0800180
Austin Schuhcf5f6442021-07-06 10:43:28 -0700181 // Returns a span with the data for the next message from the log file,
182 // including the size. The result is only guarenteed to be valid until
183 // ReadMessage() or PeekMessage() is called again.
Austin Schuh05b70472020-01-01 17:11:17 -0800184 absl::Span<const uint8_t> ReadMessage();
185
Austin Schuhcf5f6442021-07-06 10:43:28 -0700186 // Returns a span with the data for the next message without consuming it.
187 // Multiple calls to PeekMessage return the same data. ReadMessage or
188 // ConsumeMessage must be called to get the next message.
189 absl::Span<const uint8_t> PeekMessage();
190 // Consumes the message so the next call to ReadMessage or PeekMessage returns
191 // new data. This does not invalidate the data.
192 void ConsumeMessage();
193
Austin Schuh05b70472020-01-01 17:11:17 -0800194 private:
195 // TODO(austin): Optimization:
196 // Allocate the 256k blocks like we do today. But, refcount them with
197 // shared_ptr pointed to by the messageheader that is returned. This avoids
198 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700199 // And (Brian): Consider just mmapping the file and handing out refcounted
200 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800201
202 // Reads a chunk of data into data_. Returns false if no data was read.
203 bool ReadBlock();
204
Austin Schuhc41603c2020-10-11 16:17:37 -0700205 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800206
Brian Silvermanf51499a2020-09-21 12:49:08 -0700207 // File reader and data decoder.
208 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800209
Brian Silvermanf51499a2020-09-21 12:49:08 -0700210 // Vector to read into.
211 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800212
213 // Amount of data consumed already in data_.
214 size_t consumed_data_ = 0;
Brian Smarttea913d42021-12-10 15:02:38 -0800215
216 // Accumulates the total volume of bytes read from filename_
217 size_t total_read_ = 0;
218
219 // Accumulates the total volume of read bytes that were 'consumed' into
220 // messages. May be less than total_read_, if the last message (span) is
221 // either truncated or somehow corrupt.
222 size_t total_consumed_ = 0;
223
224 // Reached the end, no more readable messages.
225 bool is_finished_ = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800226};
227
Alexei Strotsa3194712023-04-21 23:30:50 -0700228// Class to borrow log readers from pool based on their ids. This is used as a
229// factory and helps with performance when construction or descrution of
230// decoders are not free. For instance,, S3 fetchers are slow to destroy.
231class ReadersPool {
232 public:
233 virtual ~ReadersPool() = default;
234
235 // Borrow reader from pool based on the id.
236 virtual SpanReader *BorrowReader(std::string_view id) = 0;
237};
238
239class LogReadersPool : public ReadersPool {
240 public:
241 explicit LogReadersPool(const LogSource *log_source = nullptr,
242 size_t pool_size = 50);
243
244 SpanReader *BorrowReader(std::string_view id) override;
245
246 private:
247 const LogSource *log_source_;
248 std::vector<SpanReader> part_readers_;
249 const size_t pool_size_;
250};
251
Brian Silvermanfee16972021-09-14 12:06:38 -0700252// Reads the last header from a log file. This handles any duplicate headers
253// that were written.
254std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
255 SpanReader *span_reader);
256std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
257 std::string_view filename);
258// Reads the Nth message from a log file, excluding the header. Note: this
259// doesn't handle duplicate headers.
260std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
261 std::string_view filename, size_t n);
262
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700263class UnpackedMessageHeader;
264
Austin Schuh05b70472020-01-01 17:11:17 -0800265// Class which handles reading the header and messages from the log file. This
266// handles any per-file state left before merging below.
267class MessageReader {
268 public:
Alexei Strots58017402023-05-03 22:05:06 -0700269 // TODO (Alexei): it's deprecated and needs to be removed.
270 explicit MessageReader(std::string_view filename)
271 : MessageReader(SpanReader(filename)) {}
272
273 explicit MessageReader(SpanReader span_reader);
Austin Schuh05b70472020-01-01 17:11:17 -0800274
Austin Schuh6f3babe2020-01-26 20:34:50 -0800275 std::string_view filename() const { return span_reader_.filename(); }
276
Austin Schuh05b70472020-01-01 17:11:17 -0800277 // Returns the header from the log file.
278 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700279 return &raw_log_file_header_.message();
280 }
281
282 // Returns the raw data of the header from the log file.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800283 const SizePrefixedFlatbufferVector<LogFileHeader> &raw_log_file_header()
284 const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700285 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800286 }
287
Mithun Bharadwaja5cb8e02023-08-02 16:10:40 -0700288 // Returns the minimum amount of data needed to queue up for sorting before
289 // we're guarenteed to not see data out of order.
Austin Schuh05b70472020-01-01 17:11:17 -0800290 std::chrono::nanoseconds max_out_of_order_duration() const {
291 return max_out_of_order_duration_;
292 }
293
Austin Schuhcde938c2020-02-02 17:30:07 -0800294 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800295 monotonic_clock::time_point newest_timestamp() const {
296 return newest_timestamp_;
297 }
298
299 // Returns the next message if there is one.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700300 std::shared_ptr<UnpackedMessageHeader> ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800301
302 // The time at which we need to read another chunk from the logfile.
303 monotonic_clock::time_point queue_data_time() const {
304 return newest_timestamp() - max_out_of_order_duration();
305 }
306
Brian Smarttea913d42021-12-10 15:02:38 -0800307 // Flag value setters for testing
308 void set_crash_on_corrupt_message_flag(bool b) {
309 crash_on_corrupt_message_flag_ = b;
310 }
311 void set_ignore_corrupt_messages_flag(bool b) {
312 ignore_corrupt_messages_flag_ = b;
313 }
314
Austin Schuh05b70472020-01-01 17:11:17 -0800315 private:
316 // Log chunk reader.
317 SpanReader span_reader_;
318
Austin Schuh97789fc2020-08-01 14:42:45 -0700319 // Vector holding the raw data for the log file header.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800320 SizePrefixedFlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800321
322 // Minimum amount of data to queue up for sorting before we are guarenteed
323 // to not see data out of order.
324 std::chrono::nanoseconds max_out_of_order_duration_;
325
326 // Timestamp of the newest message in a channel queue.
327 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Brian Smarttea913d42021-12-10 15:02:38 -0800328
329 // Total volume of verifiable messages from the beginning of the file.
330 // TODO - are message counts also useful?
331 size_t total_verified_before_ = 0;
332
333 // Total volume of messages with corrupted flatbuffer formatting, if any.
334 // Excludes corrupted message content.
335 // TODO - if the layout included something as simple as a CRC (relatively
336 // fast and robust enough) for each span, then corrupted content could be
337 // included in this check.
338 size_t total_corrupted_ = 0;
339
340 // Total volume of verifiable messages intermixed with corrupted messages,
341 // if any. Will be == 0 if total_corrupted_ == 0.
342 size_t total_verified_during_ = 0;
343
344 // Total volume of verifiable messages found after the last corrupted one,
345 // if any. Will be == 0 if total_corrupted_ == 0.
346 size_t total_verified_after_ = 0;
347
348 bool is_corrupted() const { return total_corrupted_ > 0; }
349
350 bool crash_on_corrupt_message_flag_ = true;
351 bool ignore_corrupt_messages_flag_ = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800352};
353
Austin Schuhc41603c2020-10-11 16:17:37 -0700354// A class to seamlessly read messages from a list of part files.
355class PartsMessageReader {
356 public:
Alexei Strots58017402023-05-03 22:05:06 -0700357 // TODO (Alexei): it's deprecated, need to removed.
358 explicit PartsMessageReader(LogParts log_parts)
359 : PartsMessageReader(LogPartsAccess(std::nullopt, std::move(log_parts))) {
360 }
361
362 explicit PartsMessageReader(LogPartsAccess log_parts_access);
Austin Schuhc41603c2020-10-11 16:17:37 -0700363
364 std::string_view filename() const { return message_reader_.filename(); }
365
Austin Schuhd2f96102020-12-01 20:27:29 -0800366 // Returns the LogParts that holds the filenames we are reading.
Alexei Strots58017402023-05-03 22:05:06 -0700367 const LogParts &parts() const { return log_parts_access_.parts(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800368
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800369 const LogFileHeader *log_file_header() const {
370 return message_reader_.log_file_header();
371 }
372
Austin Schuhc41603c2020-10-11 16:17:37 -0700373 // Returns the minimum amount of data needed to queue up for sorting before
374 // we are guarenteed to not see data out of order.
375 std::chrono::nanoseconds max_out_of_order_duration() const {
Mithun Bharadwaja5cb8e02023-08-02 16:10:40 -0700376 return max_out_of_order_duration_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700377 }
378
379 // Returns the newest timestamp read out of the log file.
380 monotonic_clock::time_point newest_timestamp() const {
381 return newest_timestamp_;
382 }
383
384 // Returns the next message if there is one, or nullopt if we have reached the
385 // end of all the files.
386 // Note: reading the next message may change the max_out_of_order_duration().
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700387 std::shared_ptr<UnpackedMessageHeader> ReadMessage();
Austin Schuhc41603c2020-10-11 16:17:37 -0700388
Austin Schuh48507722021-07-17 17:29:24 -0700389 // Returns the boot count for the requested node, or std::nullopt if we don't
390 // know.
391 std::optional<size_t> boot_count(size_t node_index) const {
392 CHECK_GE(node_index, 0u);
393 CHECK_LT(node_index, boot_counts_.size());
394 return boot_counts_[node_index];
395 }
396
Austin Schuhc41603c2020-10-11 16:17:37 -0700397 private:
Alexei Strots58017402023-05-03 22:05:06 -0700398 static SpanReader MakeSpanReader(const LogPartsAccess &log_parts_access,
399 size_t part_number);
400
Austin Schuhc41603c2020-10-11 16:17:37 -0700401 // Opens the next log and updates message_reader_. Sets done_ if there is
402 // nothing more to do.
403 void NextLog();
Austin Schuh48507722021-07-17 17:29:24 -0700404 void ComputeBootCounts();
Austin Schuhc41603c2020-10-11 16:17:37 -0700405
Alexei Strots58017402023-05-03 22:05:06 -0700406 const LogPartsAccess log_parts_access_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700407 size_t next_part_index_ = 1u;
408 bool done_ = false;
Alexei Strots036d84e2023-05-03 16:05:12 -0700409
Austin Schuhc41603c2020-10-11 16:17:37 -0700410 MessageReader message_reader_;
Brian Silvermanfee16972021-09-14 12:06:38 -0700411 // We instantiate the next one early, to allow implementations to prefetch.
412 // TODO(Brian): To get optimal performance when downloading, this needs more
413 // communication with the implementation to prioritize the next part and add
414 // more parallelism when it helps. Maybe some kind of a queue of parts in
415 // order, and the implementation gets to pull however many make sense off the
416 // front?
417 std::optional<MessageReader> next_message_reader_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700418
Austin Schuh315b96b2020-12-11 21:21:12 -0800419 // True after we have seen a message after the start of the log. The
420 // guarentees on logging essentially are that all data from before the
421 // starting time of the log may be arbitrarily out of order, but once we get
422 // max_out_of_order_duration past the start, everything will remain within
423 // max_out_of_order_duration. We shouldn't see anything before the start
424 // after we've seen a message that is at least max_out_of_order_duration after
425 // the start.
426 bool after_start_ = false;
427
Austin Schuhc41603c2020-10-11 16:17:37 -0700428 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh48507722021-07-17 17:29:24 -0700429
430 // Per node boot counts.
431 std::vector<std::optional<size_t>> boot_counts_;
Mithun Bharadwaja5cb8e02023-08-02 16:10:40 -0700432
433 const std::chrono::nanoseconds max_out_of_order_duration_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700434};
435
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700436// Stores MessageHeader as a flat header and inline, aligned block of data.
437class UnpackedMessageHeader {
438 public:
James Kuszmaul9776b392023-01-14 14:08:08 -0800439 UnpackedMessageHeader(
440 uint32_t channel_index, monotonic_clock::time_point monotonic_sent_time,
441 realtime_clock::time_point realtime_sent_time, uint32_t queue_index,
442 std::optional<monotonic_clock::time_point> monotonic_remote_time,
443 std::optional<realtime_clock::time_point> realtime_remote_time,
Austin Schuhb5224ec2024-03-27 15:20:09 -0700444 monotonic_clock::time_point monotonic_remote_transmit_time,
James Kuszmaul9776b392023-01-14 14:08:08 -0800445 std::optional<uint32_t> remote_queue_index,
446 monotonic_clock::time_point monotonic_timestamp_time,
447 bool has_monotonic_timestamp_time, absl::Span<const uint8_t> span)
448 : channel_index(channel_index),
449 monotonic_sent_time(monotonic_sent_time),
450 realtime_sent_time(realtime_sent_time),
451 queue_index(queue_index),
452 monotonic_remote_time(monotonic_remote_time),
453 realtime_remote_time(realtime_remote_time),
Austin Schuhb5224ec2024-03-27 15:20:09 -0700454 monotonic_remote_transmit_time(monotonic_remote_transmit_time),
James Kuszmaul9776b392023-01-14 14:08:08 -0800455 remote_queue_index(remote_queue_index),
456 monotonic_timestamp_time(monotonic_timestamp_time),
457 has_monotonic_timestamp_time(has_monotonic_timestamp_time),
458 span(span) {}
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700459 UnpackedMessageHeader(const UnpackedMessageHeader &) = delete;
460 UnpackedMessageHeader &operator=(const UnpackedMessageHeader &) = delete;
461
462 // The channel.
463 uint32_t channel_index = 0xffffffff;
464
465 monotonic_clock::time_point monotonic_sent_time;
466 realtime_clock::time_point realtime_sent_time;
467
468 // The local queue index.
469 uint32_t queue_index = 0xffffffff;
470
Austin Schuh826e6ce2021-11-18 20:33:10 -0800471 std::optional<aos::monotonic_clock::time_point> monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700472
473 std::optional<realtime_clock::time_point> realtime_remote_time;
Austin Schuhb5224ec2024-03-27 15:20:09 -0700474 aos::monotonic_clock::time_point monotonic_remote_transmit_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700475 std::optional<uint32_t> remote_queue_index;
476
477 // This field is defaulted in the flatbuffer, so we need to store both the
478 // possibly defaulted value and whether it is defaulted.
479 monotonic_clock::time_point monotonic_timestamp_time;
480 bool has_monotonic_timestamp_time;
481
482 static std::shared_ptr<UnpackedMessageHeader> MakeMessage(
483 const MessageHeader &message);
484
485 // Note: we are storing a span here because we need something to put in the
486 // SharedSpan pointer that RawSender takes. We are using the aliasing
487 // constructor of shared_ptr to avoid the allocation, and it needs a nice
488 // pointer to track.
489 absl::Span<const uint8_t> span;
490
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600491 // Used to be able to mutate the data in the span. This is only used for
492 // mutating the message inside of LogReader for the Before Send Callback. It
493 // is safe in this case since there is only one caller to Send, and the data
494 // is not mutated after Send is called.
495 uint8_t *mutable_data() { return const_cast<uint8_t *>(span.data()); }
496
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700497 char actual_data[];
498
499 private:
500 ~UnpackedMessageHeader() {}
501
502 static void DestroyAndFree(UnpackedMessageHeader *p) {
503 p->~UnpackedMessageHeader();
504 free(p);
505 }
506};
507
508std::ostream &operator<<(std::ostream &os,
509 const UnpackedMessageHeader &message);
510
Austin Schuh1be0ce42020-11-29 22:43:26 -0800511// Struct to hold a message as it gets sorted on a single node.
512struct Message {
513 // The channel.
514 uint32_t channel_index = 0xffffffff;
515 // The local queue index.
Austin Schuh58646e22021-08-23 23:51:46 -0700516 // TODO(austin): Technically the boot inside queue_index is redundant with
517 // timestamp. In practice, it is less error-prone to duplicate it. Maybe a
518 // function to return the combined struct?
519 BootQueueIndex queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700520 // The local timestamp.
521 BootTimestamp timestamp;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700522
Austin Schuh48507722021-07-17 17:29:24 -0700523 // Remote boot when this is a timestamp.
524 size_t monotonic_remote_boot = 0xffffff;
525
526 size_t monotonic_timestamp_boot = 0xffffff;
527
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700528 std::shared_ptr<UnpackedMessageHeader> data;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800529
530 bool operator<(const Message &m2) const;
Austin Schuh63097262023-08-16 17:04:29 -0700531 bool operator<=(const Message &m2) const;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800532 bool operator>=(const Message &m2) const;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800533 bool operator==(const Message &m2) const;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800534};
535
536std::ostream &operator<<(std::ostream &os, const Message &m);
537
Austin Schuhd2f96102020-12-01 20:27:29 -0800538// Structure to hold a full message and all the timestamps, which may or may not
539// have been sent from a remote node. The remote_queue_index will be invalid if
540// this message is from the point of view of the node which sent it.
541struct TimestampedMessage {
542 uint32_t channel_index = 0xffffffff;
543
Austin Schuh58646e22021-08-23 23:51:46 -0700544 BootQueueIndex queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700545 BootTimestamp monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800546 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
547
Austin Schuh58646e22021-08-23 23:51:46 -0700548 BootQueueIndex remote_queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700549 BootTimestamp monotonic_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800550 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
551
Austin Schuhb5224ec2024-03-27 15:20:09 -0700552 BootTimestamp monotonic_remote_transmit_time;
553
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700554 BootTimestamp monotonic_timestamp_time;
Austin Schuh8bf1e632021-01-02 22:41:04 -0800555
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700556 std::shared_ptr<UnpackedMessageHeader> data;
Austin Schuhd2f96102020-12-01 20:27:29 -0800557};
558
559std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m);
560
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800561// Class to sort the resulting messages from a PartsMessageReader.
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700562class MessageSorter {
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800563 public:
Alexei Strots58017402023-05-03 22:05:06 -0700564 // TODO (Alexei): it's deperecated and need to be removed.
565 explicit MessageSorter(LogParts log_parts)
566 : MessageSorter(LogPartsAccess(std::nullopt, std::move(log_parts))) {}
567
568 explicit MessageSorter(const LogPartsAccess log_parts_access);
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800569
Austin Schuh0ca51f32020-12-25 21:51:45 -0800570 // Returns the parts that this is sorting messages from.
571 const LogParts &parts() const { return parts_message_reader_.parts(); }
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800572
Austin Schuhd2f96102020-12-01 20:27:29 -0800573 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800574 return parts().monotonic_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800575 }
576 realtime_clock::time_point realtime_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800577 return parts().realtime_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800578 }
579
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800580 // The time this data is sorted until.
581 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
582
Adam Snaider13d48d92023-08-03 12:20:15 -0700583 // Returns the next sorted message from the log file.
584 const Message *Front();
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800585 // Pops the front message. This should only be called after a call to
586 // Front().
587 void PopFront();
588
589 // Returns a debug string representing the contents of this sorter.
590 std::string DebugString() const;
591
592 private:
593 // Log parts reader we are wrapping.
594 PartsMessageReader parts_message_reader_;
595 // Cache of the time we are sorted until.
596 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
597
Austin Schuhb000de62020-12-03 22:00:40 -0800598 // Timestamp of the last message returned. Used to make sure nothing goes
599 // backwards.
600 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
601
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800602 // Set used for efficient sorting of messages. We can benchmark and evaluate
603 // other data structures if this proves to be the bottleneck.
604 absl::btree_set<Message> messages_;
Austin Schuh48507722021-07-17 17:29:24 -0700605
606 // Mapping from channel to source node.
607 // TODO(austin): Should we put this in Boots so it can be cached for everyone?
608 std::vector<size_t> source_node_index_;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800609};
610
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700611// Class to run merge sort on the messages associated with specific node and
612// boot.
613class PartsMerger {
Austin Schuh8f52ed52020-11-30 23:12:39 -0800614 public:
Austin Schuh63097262023-08-16 17:04:29 -0700615 PartsMerger(SelectedLogParts &&selected_parts);
Austin Schuhd2f96102020-12-01 20:27:29 -0800616
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700617 // Copying and moving will mess up the internal raw pointers. Just don't do
618 // it.
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700619 PartsMerger(PartsMerger const &) = delete;
620 PartsMerger(PartsMerger &&) = delete;
621 void operator=(PartsMerger const &) = delete;
622 void operator=(PartsMerger &&) = delete;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700623
Austin Schuhd2f96102020-12-01 20:27:29 -0800624 // Node index in the configuration of this node.
625 int node() const { return node_; }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800626
Austin Schuh63097262023-08-16 17:04:29 -0700627 std::string_view node_name() const {
628 return configuration::NodeName(configuration().get(), node());
629 }
630
Austin Schuh0ca51f32020-12-25 21:51:45 -0800631 // List of parts being sorted together.
632 std::vector<const LogParts *> Parts() const;
633
Austin Schuh63097262023-08-16 17:04:29 -0700634 const std::shared_ptr<const Configuration> configuration() const {
635 return message_sorters_[0].parts().config;
Austin Schuhd2f96102020-12-01 20:27:29 -0800636 }
637
638 monotonic_clock::time_point monotonic_start_time() const {
639 return monotonic_start_time_;
640 }
641 realtime_clock::time_point realtime_start_time() const {
642 return realtime_start_time_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800643 }
Austin Schuh63097262023-08-16 17:04:29 -0700644
645 // Returns the oldest message observed in this set of parts. This could be
646 // before the start time if we fetched it at the start of logging from long
647 // ago.
648 monotonic_clock::time_point monotonic_oldest_time() {
649 if (monotonic_oldest_time_ == monotonic_clock::max_time) {
650 VLOG(1) << "No oldest message time, fetching " << node_name();
651 (void)Front();
652 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800653 return monotonic_oldest_time_;
654 }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800655
656 // The time this data is sorted until.
657 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
658
Adam Snaider13d48d92023-08-03 12:20:15 -0700659 // Returns the next sorted message from the set of log files.
660 const Message *Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -0800661 // Pops the front message. This should only be called after a call to
662 // Front().
663 void PopFront();
664
665 private:
666 // Unsorted list of all parts sorters.
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700667 std::vector<MessageSorter> message_sorters_;
Alexei Strots58017402023-05-03 22:05:06 -0700668
Austin Schuh8f52ed52020-11-30 23:12:39 -0800669 // Pointer to the parts sorter holding the current Front message if one
670 // exists, or nullptr if a new one needs to be found.
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700671 MessageSorter *current_ = nullptr;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800672 // Cached sorted_until value.
673 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800674
675 // Cached node.
676 int node_;
677
Austin Schuhb000de62020-12-03 22:00:40 -0800678 // Timestamp of the last message returned. Used to make sure nothing goes
679 // backwards.
680 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
681
Austin Schuhd2f96102020-12-01 20:27:29 -0800682 realtime_clock::time_point realtime_start_time_ = realtime_clock::max_time;
683 monotonic_clock::time_point monotonic_start_time_ = monotonic_clock::max_time;
Austin Schuh60e77942022-05-16 17:48:24 -0700684 monotonic_clock::time_point monotonic_oldest_time_ =
685 monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800686};
687
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700688// Class to concatenate multiple boots worth of logs into a single per-node
689// stream.
690class BootMerger {
691 public:
Austin Schuh63097262023-08-16 17:04:29 -0700692 BootMerger(std::string_view node_name, const LogFilesContainer &log_files,
693 const std::vector<StoredDataType> &types);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700694
695 // Copying and moving will mess up the internal raw pointers. Just don't do
696 // it.
697 BootMerger(BootMerger const &) = delete;
698 BootMerger(BootMerger &&) = delete;
699 void operator=(BootMerger const &) = delete;
700 void operator=(BootMerger &&) = delete;
701
702 // Node index in the configuration of this node.
Austin Schuh63097262023-08-16 17:04:29 -0700703 int node() const { return node_; }
704 std::string_view node_name() const;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700705
706 // List of parts being sorted together.
707 std::vector<const LogParts *> Parts() const;
708
Austin Schuh63097262023-08-16 17:04:29 -0700709 const std::shared_ptr<const Configuration> configuration() const {
710 return configuration_;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700711 }
712
Austin Schuh63097262023-08-16 17:04:29 -0700713 monotonic_clock::time_point monotonic_start_time(size_t boot) const;
714 realtime_clock::time_point realtime_start_time(size_t boot) const;
715 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700716
Austin Schuh63097262023-08-16 17:04:29 -0700717 bool started() const;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700718
Adam Snaider13d48d92023-08-03 12:20:15 -0700719 // Returns the next sorted message from the set of log files.
720 const Message *Front();
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700721 // Pops the front message. This should only be called after a call to
722 // Front().
723 void PopFront();
724
725 private:
726 int index_ = 0;
727
728 // TODO(austin): Sanjay points out this is pretty inefficient. Don't keep so
729 // many things open.
Austin Schuh63097262023-08-16 17:04:29 -0700730 // A list of all the parts mergers. Only the boots with something to sort are
731 // instantiated.
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700732 std::vector<std::unique_ptr<PartsMerger>> parts_mergers_;
Austin Schuh63097262023-08-16 17:04:29 -0700733
734 std::shared_ptr<const Configuration> configuration_;
735 int node_;
736};
737
738enum class TimestampQueueStrategy {
739 // Read the timestamps at the same time as all the other data.
740 kQueueTogether,
741 // Read the timestamps first.
742 kQueueTimestampsAtStartup,
743};
744
745// Class to manage queueing up timestamps from BootMerger and notifying
746// TimestampMapper of them.
747class SplitTimestampBootMerger {
748 public:
749 SplitTimestampBootMerger(std::string_view node_name,
750 const LogFilesContainer &log_files,
751 TimestampQueueStrategy timestamp_queue_strategy);
752
753 // Copying and moving will mess up the internal raw pointers. Just don't do
754 // it.
755 SplitTimestampBootMerger(SplitTimestampBootMerger const &) = delete;
756 SplitTimestampBootMerger(SplitTimestampBootMerger &&) = delete;
757 void operator=(SplitTimestampBootMerger const &) = delete;
758 void operator=(SplitTimestampBootMerger &&) = delete;
759
760 // Reads all timestamps into a member variable queue, and calls the function
761 // on each timestamp. This only saves timestamps, which are defined as
762 // messages sent on this node, but not originally from this node. To make
763 // that distinction, source_node is provided which has a list of which node
764 // index is the source node for each channel, where the channel index is the
765 // array index.
766 void QueueTimestamps(std::function<void(TimestampedMessage *)> fn,
767 const std::vector<size_t> &source_node);
768
769 // Node index in the configuration of this node.
770 int node() const { return boot_merger_.node(); }
771 // Returns the name of the node this class is sorting for.
772 std::string_view node_name() const;
773
774 std::shared_ptr<const Configuration> configuration() const {
775 return boot_merger_.configuration();
776 }
777
778 monotonic_clock::time_point monotonic_start_time(size_t boot) const;
779 realtime_clock::time_point realtime_start_time(size_t boot) const;
780 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const;
781
782 // Returns true if the log has been started.
783 bool started() const {
784 // Timestamps don't count, so only track boot_merger_.
785 return boot_merger_.started();
786 }
787
Adam Snaider13d48d92023-08-03 12:20:15 -0700788 // Returns the next sorted message from the set of log files.
789 const Message *Front();
Austin Schuh63097262023-08-16 17:04:29 -0700790
791 // Pops the front message. This should only be called after a call to
792 // Front().
793 void PopFront();
794
795 private:
796 enum class MessageSource {
797 kTimestampMessage,
798 kBootMerger,
799 };
800
801 MessageSource message_source_ = MessageSource::kBootMerger;
802
803 // Boot merger for data and potentially timestamps.
804 BootMerger boot_merger_;
805
806 // Boot merger for just timestamps. Any data read from here is to be ignored.
807 std::unique_ptr<BootMerger> timestamp_boot_merger_;
808
809 // The callback requires us to convert each message to a TimestampedMessage.
810 std::deque<TimestampedMessage> timestamp_messages_;
811
812 // Storage for the next timestamp message to return. This is separate so we
813 // can convert them back to a Message.
814 //
815 // TODO(austin): It would be nice to not have to convert...
816 std::optional<Message> next_timestamp_;
817
818 // Start times for each boot.
819 std::vector<monotonic_clock::time_point> monotonic_start_time_;
820 std::vector<realtime_clock::time_point> realtime_start_time_;
821
822 // Tracks if QueueTimestamps loaded any timestamps.
823 bool queue_timestamps_ran_ = false;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700824};
825
Austin Schuhd2f96102020-12-01 20:27:29 -0800826// Class to match timestamps with the corresponding data from other nodes.
Austin Schuh79b30942021-01-24 22:32:21 -0800827//
828// This class also buffers data for the node it represents, and supports
829// notifying when new data is queued as well as queueing until a point in time.
Austin Schuhd2f96102020-12-01 20:27:29 -0800830class TimestampMapper {
831 public:
Alexei Strots1f51ac72023-05-15 10:14:54 -0700832 TimestampMapper(std::string_view node_name,
Austin Schuh63097262023-08-16 17:04:29 -0700833 const LogFilesContainer &log_files,
834 TimestampQueueStrategy timestamp_queue_strategy);
Austin Schuhd2f96102020-12-01 20:27:29 -0800835
836 // Copying and moving will mess up the internal raw pointers. Just don't do
837 // it.
838 TimestampMapper(TimestampMapper const &) = delete;
839 TimestampMapper(TimestampMapper &&) = delete;
840 void operator=(TimestampMapper const &) = delete;
841 void operator=(TimestampMapper &&) = delete;
842
843 // TODO(austin): It would be super helpful to provide a way to queue up to
844 // time X without matching timestamps, and to then be able to pull the
845 // timestamps out of this queue. This lets us bootstrap time estimation
846 // without exploding memory usage worst case.
847
Austin Schuh0ca51f32020-12-25 21:51:45 -0800848 const Configuration *configuration() const { return configuration_.get(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800849
850 // Returns which node this is sorting for.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700851 size_t node() const { return boot_merger_.node(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800852
853 // The start time of this log.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700854 monotonic_clock::time_point monotonic_start_time(size_t boot) const {
855 return boot_merger_.monotonic_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800856 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700857 realtime_clock::time_point realtime_start_time(size_t boot) const {
858 return boot_merger_.realtime_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800859 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800860 // Returns the oldest timestamp on a message on this boot.
861 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const {
862 return boot_merger_.monotonic_oldest_time(boot);
863 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800864
865 // Uses timestamp_mapper as the peer for its node. Only one mapper may be set
866 // for each node. Peers are used to look up the data for timestamps on this
867 // node.
868 void AddPeer(TimestampMapper *timestamp_mapper);
869
Austin Schuh24bf4972021-06-29 22:09:08 -0700870 // Returns true if anything has been queued up.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700871 bool started() const { return boot_merger_.started(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800872
873 // Returns the next message for this node.
874 TimestampedMessage *Front();
875 // Pops the next message. Front must be called first.
876 void PopFront();
877
878 // Returns debug information about this node.
879 std::string DebugString() const;
880
Austin Schuh63097262023-08-16 17:04:29 -0700881 // Queues just the timestamps so that the timestamp callback gets called.
882 // Note, the timestamp callback will get called when they get returned too, so
883 // make sure to unset it if you don't want to be called twice.
884 void QueueTimestamps();
885
Austin Schuh79b30942021-01-24 22:32:21 -0800886 // Queues data the provided time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700887 void QueueUntil(BootTimestamp queue_time);
Austin Schuhe639ea12021-01-25 13:00:22 -0800888 // Queues until we have time_estimation_buffer of data in the queue.
889 void QueueFor(std::chrono::nanoseconds time_estimation_buffer);
Austin Schuh79b30942021-01-24 22:32:21 -0800890
Austin Schuh06601222021-01-26 17:02:50 -0800891 // Queues until the condition is met.
892 template <typename T>
893 void QueueUntilCondition(T fn) {
894 while (true) {
895 if (fn()) {
896 break;
897 }
898 if (!QueueMatched()) {
899 break;
900 }
901 }
902 }
903
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700904 // Sets the callback that can be used to skip messages.
905 void set_replay_channels_callback(
906 std::function<bool(const TimestampedMessage &)> fn) {
907 replay_channels_callback_ = fn;
908 }
909
Austin Schuh79b30942021-01-24 22:32:21 -0800910 // Sets a callback to be called whenever a full message is queued.
911 void set_timestamp_callback(std::function<void(TimestampedMessage *)> fn) {
912 timestamp_callback_ = fn;
913 }
914
Austin Schuhd2f96102020-12-01 20:27:29 -0800915 private:
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700916 // Result of MaybeQueueMatched
917 enum class MatchResult : uint8_t {
918 kEndOfFile, // End of the log file being read
919 kQueued, // Message was queued
920 kSkipped // Message was skipped over
921 };
922
Austin Schuhd2f96102020-12-01 20:27:29 -0800923 // The state for a remote node. This holds the data that needs to be matched
924 // with the remote node's timestamps.
925 struct NodeData {
926 // True if we should save data here. This should be true if any of the
927 // bools in delivered below are true.
928 bool any_delivered = false;
929
Austin Schuh36c00932021-07-19 18:13:21 -0700930 // True if we have a peer and therefore should be saving data for it.
931 bool save_for_peer = false;
932
Austin Schuhd2f96102020-12-01 20:27:29 -0800933 // Peer pointer. This node is only to be considered if a peer is set.
934 TimestampMapper *peer = nullptr;
935
936 struct ChannelData {
937 // Deque per channel. This contains the data from the outside
938 // TimestampMapper node which is relevant for the node this NodeData
939 // points to.
940 std::deque<Message> messages;
941 // Bool tracking per channel if a message is delivered to the node this
942 // NodeData represents.
943 bool delivered = false;
Austin Schuh6a7358f2021-11-18 22:40:40 -0800944 // The TTL for delivery.
945 std::chrono::nanoseconds time_to_live = std::chrono::nanoseconds(0);
Austin Schuhd2f96102020-12-01 20:27:29 -0800946 };
947
948 // Vector with per channel data.
949 std::vector<ChannelData> channels;
950 };
951
952 // Returns (and forgets about) the data for the provided timestamp message
953 // showing when it was delivered to this node.
954 Message MatchingMessageFor(const Message &message);
955
956 // Queues up a single message into our message queue, and any nodes that this
957 // message is delivered to. Returns true if one was available, false
958 // otherwise.
959 bool Queue();
960
Austin Schuh79b30942021-01-24 22:32:21 -0800961 // Queues up a single matched message into our matched message queue. Returns
962 // true if one was queued, and false otherwise.
963 bool QueueMatched();
964
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700965 // Queues a message if the replay_channels_callback is passed and the end of
966 // the log file has not been reached.
967 MatchResult MaybeQueueMatched();
968
Austin Schuhd2f96102020-12-01 20:27:29 -0800969 // Queues up data until we have at least one message >= to time t.
970 // Useful for triggering a remote node to read enough data to have the
971 // timestamp you care about available.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700972 void QueueUnmatchedUntil(BootTimestamp t);
Austin Schuhd2f96102020-12-01 20:27:29 -0800973
Austin Schuh79b30942021-01-24 22:32:21 -0800974 // Queues m into matched_messages_.
Adam Snaider13d48d92023-08-03 12:20:15 -0700975 void QueueMessage(const Message *m);
Austin Schuhd2f96102020-12-01 20:27:29 -0800976
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700977 // If a replay_channels_callback was set and the callback returns false, a
978 // matched message is popped and true is returned. Otherwise false is
979 // returned.
980 bool CheckReplayChannelsAndMaybePop(const TimestampedMessage &message);
981
Austin Schuh58646e22021-08-23 23:51:46 -0700982 // Returns the name of the node this class is sorting for.
983 std::string_view node_name() const {
Austin Schuh63097262023-08-16 17:04:29 -0700984 return configuration::NodeName(configuration(), node());
Austin Schuh58646e22021-08-23 23:51:46 -0700985 }
986
Austin Schuhd2f96102020-12-01 20:27:29 -0800987 // The node merger to source messages from.
Austin Schuh63097262023-08-16 17:04:29 -0700988 SplitTimestampBootMerger boot_merger_;
Austin Schuh0ca51f32020-12-25 21:51:45 -0800989
990 std::shared_ptr<const Configuration> configuration_;
991
Austin Schuhd2f96102020-12-01 20:27:29 -0800992 // The buffer of messages for this node. These are not matched with any
993 // remote data.
994 std::deque<Message> messages_;
995 // The node index for the source node for each channel.
996 std::vector<size_t> source_node_;
997
998 // Vector per node. Not all nodes will have anything.
999 std::vector<NodeData> nodes_data_;
1000
1001 // Latest message to return.
Austin Schuh79b30942021-01-24 22:32:21 -08001002 std::deque<TimestampedMessage> matched_messages_;
Austin Schuhd2f96102020-12-01 20:27:29 -08001003
Austin Schuh79b30942021-01-24 22:32:21 -08001004 // Tracks the state of the first message in matched_messages_. Do we need to
1005 // update it, is it valid, or should we return nullptr?
Austin Schuhd2f96102020-12-01 20:27:29 -08001006 enum class FirstMessage {
1007 kNeedsUpdate,
1008 kInMessage,
1009 kNullptr,
1010 };
1011 FirstMessage first_message_ = FirstMessage::kNeedsUpdate;
1012
1013 // Timestamp of the last message returned. Used to make sure nothing goes
1014 // backwards.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001015 BootTimestamp last_message_time_ = BootTimestamp::min_time();
Austin Schuh6a7358f2021-11-18 22:40:40 -08001016 BootTimestamp last_popped_message_time_ = BootTimestamp::min_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08001017 // Time this node is queued up until. Used for caching.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001018 BootTimestamp queued_until_ = BootTimestamp::min_time();
Austin Schuh79b30942021-01-24 22:32:21 -08001019
1020 std::function<void(TimestampedMessage *)> timestamp_callback_;
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001021 std::function<bool(TimestampedMessage &)> replay_channels_callback_;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001022};
1023
Alexei Strots036d84e2023-05-03 16:05:12 -07001024// Returns the node name, or an empty string if we are a single node.
1025inline std::string_view MaybeNodeName(const Node *node) {
1026 if (node != nullptr) {
1027 return node->name()->string_view();
1028 }
1029 return "";
1030}
Austin Schuhee711052020-08-24 16:06:09 -07001031
Austin Schuh71a40d42023-02-04 21:22:22 -08001032// Class to copy a RemoteMessage into the provided buffer.
1033class RemoteMessageCopier : public DataEncoder::Copier {
1034 public:
1035 RemoteMessageCopier(const message_bridge::RemoteMessage *message,
1036 int channel_index,
1037 aos::monotonic_clock::time_point monotonic_timestamp_time,
1038 EventLoop *event_loop)
1039 : DataEncoder::Copier(PackRemoteMessageSize()),
1040 message_(message),
1041 channel_index_(channel_index),
1042 monotonic_timestamp_time_(monotonic_timestamp_time),
1043 event_loop_(event_loop) {}
1044
1045 monotonic_clock::time_point end_time() const { return end_time_; }
1046
1047 size_t Copy(uint8_t *data, size_t start_byte, size_t end_byte) final {
1048 size_t result = PackRemoteMessageInline(data, message_, channel_index_,
1049 monotonic_timestamp_time_,
1050 start_byte, end_byte);
1051 end_time_ = event_loop_->monotonic_now();
1052 return result;
1053 }
1054
1055 private:
1056 const message_bridge::RemoteMessage *message_;
1057 int channel_index_;
1058 aos::monotonic_clock::time_point monotonic_timestamp_time_;
1059 EventLoop *event_loop_;
1060 monotonic_clock::time_point end_time_;
1061};
1062
1063// Class to copy a context into the provided buffer.
1064class ContextDataCopier : public DataEncoder::Copier {
1065 public:
1066 ContextDataCopier(const Context &context, int channel_index, LogType log_type,
1067 EventLoop *event_loop)
1068 : DataEncoder::Copier(PackMessageSize(log_type, context.size)),
1069 context_(context),
1070 channel_index_(channel_index),
1071 log_type_(log_type),
1072 event_loop_(event_loop) {}
1073
1074 monotonic_clock::time_point end_time() const { return end_time_; }
1075
1076 size_t Copy(uint8_t *data, size_t start_byte, size_t end_byte) final {
1077 size_t result = PackMessageInline(data, context_, channel_index_, log_type_,
1078 start_byte, end_byte);
1079 end_time_ = event_loop_->monotonic_now();
1080 return result;
1081 }
1082
1083 private:
1084 const Context &context_;
1085 const int channel_index_;
1086 const LogType log_type_;
1087 EventLoop *event_loop_;
1088 monotonic_clock::time_point end_time_;
1089};
1090
Brian Silvermanf51499a2020-09-21 12:49:08 -07001091} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -08001092
1093#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_