blob: 8a569ba50f5fb760607d3482139174fa86f42fd0 [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,
40 // The message originated on another node. Log it and the delivery times
41 // together. The message_gateway is responsible for logging any messages
42 // which didn't get delivered.
Austin Schuh6f3babe2020-01-26 20:34:50 -080043 kLogMessageAndDeliveryTime,
44 // The message originated on the other node and should be logged on this node.
45 kLogRemoteMessage
Austin Schuha36c8902019-12-30 18:07:15 -080046};
47
Austin Schuha36c8902019-12-30 18:07:15 -080048// This class manages efficiently writing a sequence of detached buffers to a
Brian Silvermanf51499a2020-09-21 12:49:08 -070049// file. It encodes them, queues them up, and batches the write operation.
Alexei Strots01395492023-03-20 13:59:56 -070050
Austin Schuha36c8902019-12-30 18:07:15 -080051class DetachedBufferWriter {
52 public:
Brian Silvermana9f2ec92020-10-06 18:00:53 -070053 // Marker struct for one of our constructor overloads.
54 struct already_out_of_space_t {};
55
Alexei Strotsbc082d82023-05-03 08:43:42 -070056 DetachedBufferWriter(std::unique_ptr<LogSink> log_sink,
Austin Schuh48d10d62022-10-16 22:19:23 -070057 std::unique_ptr<DataEncoder> encoder);
Brian Silvermana9f2ec92020-10-06 18:00:53 -070058 // Creates a dummy instance which won't even open a file. It will act as if
59 // opening the file ran out of space immediately.
Philipp Schrader10397952023-06-15 11:43:07 -070060 DetachedBufferWriter(already_out_of_space_t);
Austin Schuh2f8fd752020-09-01 22:38:28 -070061 DetachedBufferWriter(DetachedBufferWriter &&other);
62 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
63
Philipp Schrader10397952023-06-15 11:43:07 -070064 virtual ~DetachedBufferWriter();
Austin Schuha36c8902019-12-30 18:07:15 -080065
Austin Schuh2f8fd752020-09-01 22:38:28 -070066 DetachedBufferWriter &operator=(DetachedBufferWriter &&other);
Brian Silverman98360e22020-04-28 16:51:20 -070067 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
68
Alexei Strotsbc082d82023-05-03 08:43:42 -070069 std::string_view name() const { return log_sink_->name(); }
Austin Schuh6f3babe2020-01-26 20:34:50 -080070
Brian Silvermana9f2ec92020-10-06 18:00:53 -070071 // This will be true until Close() is called, unless the file couldn't be
72 // created due to running out of space.
Alexei Strotsbc082d82023-05-03 08:43:42 -070073 bool is_open() const { return log_sink_->is_open(); }
Brian Silvermana9f2ec92020-10-06 18:00:53 -070074
Brian Silvermanf51499a2020-09-21 12:49:08 -070075 // Queues up a finished FlatBufferBuilder to be encoded and written.
76 //
77 // Triggers a flush if there's enough data queued up.
78 //
79 // Steals the detached buffer from it.
Austin Schuh48d10d62022-10-16 22:19:23 -070080 void CopyMessage(DataEncoder::Copier *coppier,
81 aos::monotonic_clock::time_point now);
Austin Schuha36c8902019-12-30 18:07:15 -080082
Brian Silverman0465fcf2020-09-24 00:29:18 -070083 // Indicates we got ENOSPC when trying to write. After this returns true, no
84 // further data is written.
85 bool ran_out_of_space() const { return ran_out_of_space_; }
86
87 // To avoid silently failing to write logfiles, you must call this before
88 // destruction if ran_out_of_space() is true and the situation has been
89 // handled.
90 void acknowledge_out_of_space() {
91 CHECK(ran_out_of_space_);
92 acknowledge_ran_out_of_space_ = true;
93 }
94
95 // Fully flushes and closes the underlying file now. No additional data may be
96 // enqueued after calling this.
97 //
98 // This will be performed in the destructor automatically.
99 //
100 // Note that this may set ran_out_of_space().
101 void Close();
102
Brian Silvermanf51499a2020-09-21 12:49:08 -0700103 // Returns the total number of bytes written and currently queued.
Austin Schuha426f1f2021-03-31 22:27:41 -0700104 size_t total_bytes() const {
105 if (!encoder_) {
106 return 0;
107 }
108 return encoder_->total_bytes();
109 }
Austin Schuha36c8902019-12-30 18:07:15 -0800110
Alexei Strotsbc082d82023-05-03 08:43:42 -0700111 WriteStats *WriteStatistics() const { return log_sink_->WriteStatistics(); }
Brian Silverman98360e22020-04-28 16:51:20 -0700112
Austin Schuha36c8902019-12-30 18:07:15 -0800113 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700114 // Performs a single writev call with as much of the data we have queued up as
Austin Schuh8bdfc492023-02-11 12:53:13 -0800115 // possible. now is the time we flushed at, to be recorded in
116 // last_flush_time_.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700117 //
118 // This will normally take all of the data we have queued up, unless an
119 // encoder has spit out a big enough chunk all at once that we can't manage
120 // all of it.
Austin Schuh8bdfc492023-02-11 12:53:13 -0800121 void Flush(aos::monotonic_clock::time_point now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700122
Brian Silvermanf51499a2020-09-21 12:49:08 -0700123 // Flushes data if we've reached the threshold to do that as part of normal
Austin Schuhbd06ae42021-03-31 22:48:21 -0700124 // operation either due to the outstanding queued data, or because we have
125 // passed our flush period. now is the current time to save some CPU grabbing
126 // the current time. It just needs to be close.
127 void FlushAtThreshold(aos::monotonic_clock::time_point now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700128
Alexei Strotsbc082d82023-05-03 08:43:42 -0700129 std::unique_ptr<LogSink> log_sink_;
Austin Schuh48d10d62022-10-16 22:19:23 -0700130 std::unique_ptr<DataEncoder> encoder_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800131
Brian Silverman0465fcf2020-09-24 00:29:18 -0700132 bool ran_out_of_space_ = false;
133 bool acknowledge_ran_out_of_space_ = false;
Austin Schuha36c8902019-12-30 18:07:15 -0800134
Austin Schuhbd06ae42021-03-31 22:48:21 -0700135 aos::monotonic_clock::time_point last_flush_time_ =
136 aos::monotonic_clock::min_time;
Austin Schuha36c8902019-12-30 18:07:15 -0800137};
138
Austin Schuhf2d0e682022-10-16 14:20:58 -0700139// Repacks the provided RemoteMessage into fbb.
140flatbuffers::Offset<MessageHeader> PackRemoteMessage(
141 flatbuffers::FlatBufferBuilder *fbb,
142 const message_bridge::RemoteMessage *msg, int channel_index,
143 const aos::monotonic_clock::time_point monotonic_timestamp_time);
144
145constexpr flatbuffers::uoffset_t PackRemoteMessageSize() { return 96u; }
146size_t PackRemoteMessageInline(
147 uint8_t *data, const message_bridge::RemoteMessage *msg, int channel_index,
Austin Schuh71a40d42023-02-04 21:22:22 -0800148 const aos::monotonic_clock::time_point monotonic_timestamp_time,
149 size_t start_byte, size_t end_byte);
Austin Schuhf2d0e682022-10-16 14:20:58 -0700150
Austin Schuha36c8902019-12-30 18:07:15 -0800151// Packes a message pointed to by the context into a MessageHeader.
152flatbuffers::Offset<MessageHeader> PackMessage(
153 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
154 int channel_index, LogType log_type);
155
Austin Schuhfa30c352022-10-16 11:12:02 -0700156// Returns the size that the packed message from PackMessage or
157// PackMessageInline will be.
Austin Schuh48d10d62022-10-16 22:19:23 -0700158flatbuffers::uoffset_t PackMessageSize(LogType log_type, size_t data_size);
Austin Schuhfa30c352022-10-16 11:12:02 -0700159
160// Packs the provided message pointed to by context into the provided buffer.
161// This is equivalent to PackMessage, but doesn't require allocating a
162// FlatBufferBuilder underneath.
163size_t PackMessageInline(uint8_t *data, const Context &contex,
Austin Schuh71a40d42023-02-04 21:22:22 -0800164 int channel_index, LogType log_type, size_t start_byte,
165 size_t end_byte);
Austin Schuhfa30c352022-10-16 11:12:02 -0700166
Austin Schuh05b70472020-01-01 17:11:17 -0800167// Class to read chunks out of a log file.
168class SpanReader {
169 public:
Alexei Strotscee7b372023-04-21 11:57:54 -0700170 // It creates a reader and makes proper decoder based on information encoded
171 // in the filename.
Austin Schuhcd368422021-11-22 21:23:29 -0800172 SpanReader(std::string_view filename, bool quiet = false);
Austin Schuha36c8902019-12-30 18:07:15 -0800173
Alexei Strotscee7b372023-04-21 11:57:54 -0700174 // Opens new reader from provided decoder.
175 SpanReader(std::string_view filename, std::unique_ptr<DataDecoder> decoder);
176
Austin Schuh6f3babe2020-01-26 20:34:50 -0800177 std::string_view filename() const { return filename_; }
178
Brian Smarttea913d42021-12-10 15:02:38 -0800179 size_t TotalRead() const { return total_read_; }
180 size_t TotalConsumed() const { return total_consumed_; }
Austin Schuh60e77942022-05-16 17:48:24 -0700181 bool IsIncomplete() const {
182 return is_finished_ && total_consumed_ < total_read_;
183 }
Brian Smarttea913d42021-12-10 15:02:38 -0800184
Austin Schuhcf5f6442021-07-06 10:43:28 -0700185 // Returns a span with the data for the next message from the log file,
186 // including the size. The result is only guarenteed to be valid until
187 // ReadMessage() or PeekMessage() is called again.
Austin Schuh05b70472020-01-01 17:11:17 -0800188 absl::Span<const uint8_t> ReadMessage();
189
Austin Schuhcf5f6442021-07-06 10:43:28 -0700190 // Returns a span with the data for the next message without consuming it.
191 // Multiple calls to PeekMessage return the same data. ReadMessage or
192 // ConsumeMessage must be called to get the next message.
193 absl::Span<const uint8_t> PeekMessage();
194 // Consumes the message so the next call to ReadMessage or PeekMessage returns
195 // new data. This does not invalidate the data.
196 void ConsumeMessage();
197
Austin Schuh05b70472020-01-01 17:11:17 -0800198 private:
199 // TODO(austin): Optimization:
200 // Allocate the 256k blocks like we do today. But, refcount them with
201 // shared_ptr pointed to by the messageheader that is returned. This avoids
202 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700203 // And (Brian): Consider just mmapping the file and handing out refcounted
204 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800205
206 // Reads a chunk of data into data_. Returns false if no data was read.
207 bool ReadBlock();
208
Austin Schuhc41603c2020-10-11 16:17:37 -0700209 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800210
Brian Silvermanf51499a2020-09-21 12:49:08 -0700211 // File reader and data decoder.
212 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800213
Brian Silvermanf51499a2020-09-21 12:49:08 -0700214 // Vector to read into.
215 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800216
217 // Amount of data consumed already in data_.
218 size_t consumed_data_ = 0;
Brian Smarttea913d42021-12-10 15:02:38 -0800219
220 // Accumulates the total volume of bytes read from filename_
221 size_t total_read_ = 0;
222
223 // Accumulates the total volume of read bytes that were 'consumed' into
224 // messages. May be less than total_read_, if the last message (span) is
225 // either truncated or somehow corrupt.
226 size_t total_consumed_ = 0;
227
228 // Reached the end, no more readable messages.
229 bool is_finished_ = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800230};
231
Alexei Strotsa3194712023-04-21 23:30:50 -0700232// Class to borrow log readers from pool based on their ids. This is used as a
233// factory and helps with performance when construction or descrution of
234// decoders are not free. For instance,, S3 fetchers are slow to destroy.
235class ReadersPool {
236 public:
237 virtual ~ReadersPool() = default;
238
239 // Borrow reader from pool based on the id.
240 virtual SpanReader *BorrowReader(std::string_view id) = 0;
241};
242
243class LogReadersPool : public ReadersPool {
244 public:
245 explicit LogReadersPool(const LogSource *log_source = nullptr,
246 size_t pool_size = 50);
247
248 SpanReader *BorrowReader(std::string_view id) override;
249
250 private:
251 const LogSource *log_source_;
252 std::vector<SpanReader> part_readers_;
253 const size_t pool_size_;
254};
255
Brian Silvermanfee16972021-09-14 12:06:38 -0700256// Reads the last header from a log file. This handles any duplicate headers
257// that were written.
258std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
259 SpanReader *span_reader);
260std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
261 std::string_view filename);
262// Reads the Nth message from a log file, excluding the header. Note: this
263// doesn't handle duplicate headers.
264std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
265 std::string_view filename, size_t n);
266
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700267class UnpackedMessageHeader;
268
Austin Schuh05b70472020-01-01 17:11:17 -0800269// Class which handles reading the header and messages from the log file. This
270// handles any per-file state left before merging below.
271class MessageReader {
272 public:
Alexei Strots58017402023-05-03 22:05:06 -0700273 // TODO (Alexei): it's deprecated and needs to be removed.
274 explicit MessageReader(std::string_view filename)
275 : MessageReader(SpanReader(filename)) {}
276
277 explicit MessageReader(SpanReader span_reader);
Austin Schuh05b70472020-01-01 17:11:17 -0800278
Austin Schuh6f3babe2020-01-26 20:34:50 -0800279 std::string_view filename() const { return span_reader_.filename(); }
280
Austin Schuh05b70472020-01-01 17:11:17 -0800281 // Returns the header from the log file.
282 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700283 return &raw_log_file_header_.message();
284 }
285
286 // Returns the raw data of the header from the log file.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800287 const SizePrefixedFlatbufferVector<LogFileHeader> &raw_log_file_header()
288 const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700289 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800290 }
291
Mithun Bharadwaja5cb8e02023-08-02 16:10:40 -0700292 // Returns the minimum amount of data needed to queue up for sorting before
293 // we're guarenteed to not see data out of order.
Austin Schuh05b70472020-01-01 17:11:17 -0800294 std::chrono::nanoseconds max_out_of_order_duration() const {
295 return max_out_of_order_duration_;
296 }
297
Austin Schuhcde938c2020-02-02 17:30:07 -0800298 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800299 monotonic_clock::time_point newest_timestamp() const {
300 return newest_timestamp_;
301 }
302
303 // Returns the next message if there is one.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700304 std::shared_ptr<UnpackedMessageHeader> ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800305
306 // The time at which we need to read another chunk from the logfile.
307 monotonic_clock::time_point queue_data_time() const {
308 return newest_timestamp() - max_out_of_order_duration();
309 }
310
Brian Smarttea913d42021-12-10 15:02:38 -0800311 // Flag value setters for testing
312 void set_crash_on_corrupt_message_flag(bool b) {
313 crash_on_corrupt_message_flag_ = b;
314 }
315 void set_ignore_corrupt_messages_flag(bool b) {
316 ignore_corrupt_messages_flag_ = b;
317 }
318
Austin Schuh05b70472020-01-01 17:11:17 -0800319 private:
320 // Log chunk reader.
321 SpanReader span_reader_;
322
Austin Schuh97789fc2020-08-01 14:42:45 -0700323 // Vector holding the raw data for the log file header.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800324 SizePrefixedFlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800325
326 // Minimum amount of data to queue up for sorting before we are guarenteed
327 // to not see data out of order.
328 std::chrono::nanoseconds max_out_of_order_duration_;
329
330 // Timestamp of the newest message in a channel queue.
331 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Brian Smarttea913d42021-12-10 15:02:38 -0800332
333 // Total volume of verifiable messages from the beginning of the file.
334 // TODO - are message counts also useful?
335 size_t total_verified_before_ = 0;
336
337 // Total volume of messages with corrupted flatbuffer formatting, if any.
338 // Excludes corrupted message content.
339 // TODO - if the layout included something as simple as a CRC (relatively
340 // fast and robust enough) for each span, then corrupted content could be
341 // included in this check.
342 size_t total_corrupted_ = 0;
343
344 // Total volume of verifiable messages intermixed with corrupted messages,
345 // if any. Will be == 0 if total_corrupted_ == 0.
346 size_t total_verified_during_ = 0;
347
348 // Total volume of verifiable messages found after the last corrupted one,
349 // if any. Will be == 0 if total_corrupted_ == 0.
350 size_t total_verified_after_ = 0;
351
352 bool is_corrupted() const { return total_corrupted_ > 0; }
353
354 bool crash_on_corrupt_message_flag_ = true;
355 bool ignore_corrupt_messages_flag_ = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800356};
357
Austin Schuhc41603c2020-10-11 16:17:37 -0700358// A class to seamlessly read messages from a list of part files.
359class PartsMessageReader {
360 public:
Alexei Strots58017402023-05-03 22:05:06 -0700361 // TODO (Alexei): it's deprecated, need to removed.
362 explicit PartsMessageReader(LogParts log_parts)
363 : PartsMessageReader(LogPartsAccess(std::nullopt, std::move(log_parts))) {
364 }
365
366 explicit PartsMessageReader(LogPartsAccess log_parts_access);
Austin Schuhc41603c2020-10-11 16:17:37 -0700367
368 std::string_view filename() const { return message_reader_.filename(); }
369
Austin Schuhd2f96102020-12-01 20:27:29 -0800370 // Returns the LogParts that holds the filenames we are reading.
Alexei Strots58017402023-05-03 22:05:06 -0700371 const LogParts &parts() const { return log_parts_access_.parts(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800372
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800373 const LogFileHeader *log_file_header() const {
374 return message_reader_.log_file_header();
375 }
376
Austin Schuhc41603c2020-10-11 16:17:37 -0700377 // Returns the minimum amount of data needed to queue up for sorting before
378 // we are guarenteed to not see data out of order.
379 std::chrono::nanoseconds max_out_of_order_duration() const {
Mithun Bharadwaja5cb8e02023-08-02 16:10:40 -0700380 return max_out_of_order_duration_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700381 }
382
383 // Returns the newest timestamp read out of the log file.
384 monotonic_clock::time_point newest_timestamp() const {
385 return newest_timestamp_;
386 }
387
388 // Returns the next message if there is one, or nullopt if we have reached the
389 // end of all the files.
390 // Note: reading the next message may change the max_out_of_order_duration().
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700391 std::shared_ptr<UnpackedMessageHeader> ReadMessage();
Austin Schuhc41603c2020-10-11 16:17:37 -0700392
Austin Schuh48507722021-07-17 17:29:24 -0700393 // Returns the boot count for the requested node, or std::nullopt if we don't
394 // know.
395 std::optional<size_t> boot_count(size_t node_index) const {
396 CHECK_GE(node_index, 0u);
397 CHECK_LT(node_index, boot_counts_.size());
398 return boot_counts_[node_index];
399 }
400
Austin Schuhc41603c2020-10-11 16:17:37 -0700401 private:
Alexei Strots58017402023-05-03 22:05:06 -0700402 static SpanReader MakeSpanReader(const LogPartsAccess &log_parts_access,
403 size_t part_number);
404
Austin Schuhc41603c2020-10-11 16:17:37 -0700405 // Opens the next log and updates message_reader_. Sets done_ if there is
406 // nothing more to do.
407 void NextLog();
Austin Schuh48507722021-07-17 17:29:24 -0700408 void ComputeBootCounts();
Austin Schuhc41603c2020-10-11 16:17:37 -0700409
Alexei Strots58017402023-05-03 22:05:06 -0700410 const LogPartsAccess log_parts_access_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700411 size_t next_part_index_ = 1u;
412 bool done_ = false;
Alexei Strots036d84e2023-05-03 16:05:12 -0700413
Austin Schuhc41603c2020-10-11 16:17:37 -0700414 MessageReader message_reader_;
Brian Silvermanfee16972021-09-14 12:06:38 -0700415 // We instantiate the next one early, to allow implementations to prefetch.
416 // TODO(Brian): To get optimal performance when downloading, this needs more
417 // communication with the implementation to prioritize the next part and add
418 // more parallelism when it helps. Maybe some kind of a queue of parts in
419 // order, and the implementation gets to pull however many make sense off the
420 // front?
421 std::optional<MessageReader> next_message_reader_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700422
Austin Schuh315b96b2020-12-11 21:21:12 -0800423 // True after we have seen a message after the start of the log. The
424 // guarentees on logging essentially are that all data from before the
425 // starting time of the log may be arbitrarily out of order, but once we get
426 // max_out_of_order_duration past the start, everything will remain within
427 // max_out_of_order_duration. We shouldn't see anything before the start
428 // after we've seen a message that is at least max_out_of_order_duration after
429 // the start.
430 bool after_start_ = false;
431
Austin Schuhc41603c2020-10-11 16:17:37 -0700432 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh48507722021-07-17 17:29:24 -0700433
434 // Per node boot counts.
435 std::vector<std::optional<size_t>> boot_counts_;
Mithun Bharadwaja5cb8e02023-08-02 16:10:40 -0700436
437 const std::chrono::nanoseconds max_out_of_order_duration_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700438};
439
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700440// Stores MessageHeader as a flat header and inline, aligned block of data.
441class UnpackedMessageHeader {
442 public:
James Kuszmaul9776b392023-01-14 14:08:08 -0800443 UnpackedMessageHeader(
444 uint32_t channel_index, monotonic_clock::time_point monotonic_sent_time,
445 realtime_clock::time_point realtime_sent_time, uint32_t queue_index,
446 std::optional<monotonic_clock::time_point> monotonic_remote_time,
447 std::optional<realtime_clock::time_point> realtime_remote_time,
448 std::optional<uint32_t> remote_queue_index,
449 monotonic_clock::time_point monotonic_timestamp_time,
450 bool has_monotonic_timestamp_time, absl::Span<const uint8_t> span)
451 : channel_index(channel_index),
452 monotonic_sent_time(monotonic_sent_time),
453 realtime_sent_time(realtime_sent_time),
454 queue_index(queue_index),
455 monotonic_remote_time(monotonic_remote_time),
456 realtime_remote_time(realtime_remote_time),
457 remote_queue_index(remote_queue_index),
458 monotonic_timestamp_time(monotonic_timestamp_time),
459 has_monotonic_timestamp_time(has_monotonic_timestamp_time),
460 span(span) {}
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700461 UnpackedMessageHeader(const UnpackedMessageHeader &) = delete;
462 UnpackedMessageHeader &operator=(const UnpackedMessageHeader &) = delete;
463
464 // The channel.
465 uint32_t channel_index = 0xffffffff;
466
467 monotonic_clock::time_point monotonic_sent_time;
468 realtime_clock::time_point realtime_sent_time;
469
470 // The local queue index.
471 uint32_t queue_index = 0xffffffff;
472
Austin Schuh826e6ce2021-11-18 20:33:10 -0800473 std::optional<aos::monotonic_clock::time_point> monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700474
475 std::optional<realtime_clock::time_point> realtime_remote_time;
476 std::optional<uint32_t> remote_queue_index;
477
478 // This field is defaulted in the flatbuffer, so we need to store both the
479 // possibly defaulted value and whether it is defaulted.
480 monotonic_clock::time_point monotonic_timestamp_time;
481 bool has_monotonic_timestamp_time;
482
483 static std::shared_ptr<UnpackedMessageHeader> MakeMessage(
484 const MessageHeader &message);
485
486 // Note: we are storing a span here because we need something to put in the
487 // SharedSpan pointer that RawSender takes. We are using the aliasing
488 // constructor of shared_ptr to avoid the allocation, and it needs a nice
489 // pointer to track.
490 absl::Span<const uint8_t> span;
491
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600492 // Used to be able to mutate the data in the span. This is only used for
493 // mutating the message inside of LogReader for the Before Send Callback. It
494 // is safe in this case since there is only one caller to Send, and the data
495 // is not mutated after Send is called.
496 uint8_t *mutable_data() { return const_cast<uint8_t *>(span.data()); }
497
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700498 char actual_data[];
499
500 private:
501 ~UnpackedMessageHeader() {}
502
503 static void DestroyAndFree(UnpackedMessageHeader *p) {
504 p->~UnpackedMessageHeader();
505 free(p);
506 }
507};
508
509std::ostream &operator<<(std::ostream &os,
510 const UnpackedMessageHeader &message);
511
Austin Schuh1be0ce42020-11-29 22:43:26 -0800512// Struct to hold a message as it gets sorted on a single node.
513struct Message {
514 // The channel.
515 uint32_t channel_index = 0xffffffff;
516 // The local queue index.
Austin Schuh58646e22021-08-23 23:51:46 -0700517 // TODO(austin): Technically the boot inside queue_index is redundant with
518 // timestamp. In practice, it is less error-prone to duplicate it. Maybe a
519 // function to return the combined struct?
520 BootQueueIndex queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700521 // The local timestamp.
522 BootTimestamp timestamp;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700523
Austin Schuh48507722021-07-17 17:29:24 -0700524 // Remote boot when this is a timestamp.
525 size_t monotonic_remote_boot = 0xffffff;
526
527 size_t monotonic_timestamp_boot = 0xffffff;
528
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700529 std::shared_ptr<UnpackedMessageHeader> data;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800530
531 bool operator<(const Message &m2) const;
Austin Schuh63097262023-08-16 17:04:29 -0700532 bool operator<=(const Message &m2) const;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800533 bool operator>=(const Message &m2) const;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800534 bool operator==(const Message &m2) const;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800535};
536
537std::ostream &operator<<(std::ostream &os, const Message &m);
538
Austin Schuhd2f96102020-12-01 20:27:29 -0800539// Structure to hold a full message and all the timestamps, which may or may not
540// have been sent from a remote node. The remote_queue_index will be invalid if
541// this message is from the point of view of the node which sent it.
542struct TimestampedMessage {
543 uint32_t channel_index = 0xffffffff;
544
Austin Schuh58646e22021-08-23 23:51:46 -0700545 BootQueueIndex queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700546 BootTimestamp monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800547 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
548
Austin Schuh58646e22021-08-23 23:51:46 -0700549 BootQueueIndex remote_queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700550 BootTimestamp monotonic_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800551 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
552
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700553 BootTimestamp monotonic_timestamp_time;
Austin Schuh8bf1e632021-01-02 22:41:04 -0800554
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700555 std::shared_ptr<UnpackedMessageHeader> data;
Austin Schuhd2f96102020-12-01 20:27:29 -0800556};
557
558std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m);
559
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800560// Class to sort the resulting messages from a PartsMessageReader.
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700561class MessageSorter {
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800562 public:
Alexei Strots58017402023-05-03 22:05:06 -0700563 // TODO (Alexei): it's deperecated and need to be removed.
564 explicit MessageSorter(LogParts log_parts)
565 : MessageSorter(LogPartsAccess(std::nullopt, std::move(log_parts))) {}
566
567 explicit MessageSorter(const LogPartsAccess log_parts_access);
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800568
Austin Schuh0ca51f32020-12-25 21:51:45 -0800569 // Returns the parts that this is sorting messages from.
570 const LogParts &parts() const { return parts_message_reader_.parts(); }
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800571
Austin Schuhd2f96102020-12-01 20:27:29 -0800572 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800573 return parts().monotonic_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800574 }
575 realtime_clock::time_point realtime_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800576 return parts().realtime_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800577 }
578
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800579 // The time this data is sorted until.
580 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
581
Adam Snaider13d48d92023-08-03 12:20:15 -0700582 // Returns the next sorted message from the log file.
583 const Message *Front();
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800584 // Pops the front message. This should only be called after a call to
585 // Front().
586 void PopFront();
587
588 // Returns a debug string representing the contents of this sorter.
589 std::string DebugString() const;
590
591 private:
592 // Log parts reader we are wrapping.
593 PartsMessageReader parts_message_reader_;
594 // Cache of the time we are sorted until.
595 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
596
Austin Schuhb000de62020-12-03 22:00:40 -0800597 // Timestamp of the last message returned. Used to make sure nothing goes
598 // backwards.
599 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
600
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800601 // Set used for efficient sorting of messages. We can benchmark and evaluate
602 // other data structures if this proves to be the bottleneck.
603 absl::btree_set<Message> messages_;
Austin Schuh48507722021-07-17 17:29:24 -0700604
605 // Mapping from channel to source node.
606 // TODO(austin): Should we put this in Boots so it can be cached for everyone?
607 std::vector<size_t> source_node_index_;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800608};
609
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700610// Class to run merge sort on the messages associated with specific node and
611// boot.
612class PartsMerger {
Austin Schuh8f52ed52020-11-30 23:12:39 -0800613 public:
Austin Schuh63097262023-08-16 17:04:29 -0700614 PartsMerger(SelectedLogParts &&selected_parts);
Austin Schuhd2f96102020-12-01 20:27:29 -0800615
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700616 // Copying and moving will mess up the internal raw pointers. Just don't do
617 // it.
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700618 PartsMerger(PartsMerger const &) = delete;
619 PartsMerger(PartsMerger &&) = delete;
620 void operator=(PartsMerger const &) = delete;
621 void operator=(PartsMerger &&) = delete;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700622
Austin Schuhd2f96102020-12-01 20:27:29 -0800623 // Node index in the configuration of this node.
624 int node() const { return node_; }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800625
Austin Schuh63097262023-08-16 17:04:29 -0700626 std::string_view node_name() const {
627 return configuration::NodeName(configuration().get(), node());
628 }
629
Austin Schuh0ca51f32020-12-25 21:51:45 -0800630 // List of parts being sorted together.
631 std::vector<const LogParts *> Parts() const;
632
Austin Schuh63097262023-08-16 17:04:29 -0700633 const std::shared_ptr<const Configuration> configuration() const {
634 return message_sorters_[0].parts().config;
Austin Schuhd2f96102020-12-01 20:27:29 -0800635 }
636
637 monotonic_clock::time_point monotonic_start_time() const {
638 return monotonic_start_time_;
639 }
640 realtime_clock::time_point realtime_start_time() const {
641 return realtime_start_time_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800642 }
Austin Schuh63097262023-08-16 17:04:29 -0700643
644 // Returns the oldest message observed in this set of parts. This could be
645 // before the start time if we fetched it at the start of logging from long
646 // ago.
647 monotonic_clock::time_point monotonic_oldest_time() {
648 if (monotonic_oldest_time_ == monotonic_clock::max_time) {
649 VLOG(1) << "No oldest message time, fetching " << node_name();
650 (void)Front();
651 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800652 return monotonic_oldest_time_;
653 }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800654
655 // The time this data is sorted until.
656 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
657
Adam Snaider13d48d92023-08-03 12:20:15 -0700658 // Returns the next sorted message from the set of log files.
659 const Message *Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -0800660 // Pops the front message. This should only be called after a call to
661 // Front().
662 void PopFront();
663
664 private:
665 // Unsorted list of all parts sorters.
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700666 std::vector<MessageSorter> message_sorters_;
Alexei Strots58017402023-05-03 22:05:06 -0700667
Austin Schuh8f52ed52020-11-30 23:12:39 -0800668 // Pointer to the parts sorter holding the current Front message if one
669 // exists, or nullptr if a new one needs to be found.
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700670 MessageSorter *current_ = nullptr;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800671 // Cached sorted_until value.
672 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800673
674 // Cached node.
675 int node_;
676
Austin Schuhb000de62020-12-03 22:00:40 -0800677 // Timestamp of the last message returned. Used to make sure nothing goes
678 // backwards.
679 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
680
Austin Schuhd2f96102020-12-01 20:27:29 -0800681 realtime_clock::time_point realtime_start_time_ = realtime_clock::max_time;
682 monotonic_clock::time_point monotonic_start_time_ = monotonic_clock::max_time;
Austin Schuh60e77942022-05-16 17:48:24 -0700683 monotonic_clock::time_point monotonic_oldest_time_ =
684 monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800685};
686
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700687// Class to concatenate multiple boots worth of logs into a single per-node
688// stream.
689class BootMerger {
690 public:
Austin Schuh63097262023-08-16 17:04:29 -0700691 BootMerger(std::string_view node_name, const LogFilesContainer &log_files,
692 const std::vector<StoredDataType> &types);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700693
694 // Copying and moving will mess up the internal raw pointers. Just don't do
695 // it.
696 BootMerger(BootMerger const &) = delete;
697 BootMerger(BootMerger &&) = delete;
698 void operator=(BootMerger const &) = delete;
699 void operator=(BootMerger &&) = delete;
700
701 // Node index in the configuration of this node.
Austin Schuh63097262023-08-16 17:04:29 -0700702 int node() const { return node_; }
703 std::string_view node_name() const;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700704
705 // List of parts being sorted together.
706 std::vector<const LogParts *> Parts() const;
707
Austin Schuh63097262023-08-16 17:04:29 -0700708 const std::shared_ptr<const Configuration> configuration() const {
709 return configuration_;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700710 }
711
Austin Schuh63097262023-08-16 17:04:29 -0700712 monotonic_clock::time_point monotonic_start_time(size_t boot) const;
713 realtime_clock::time_point realtime_start_time(size_t boot) const;
714 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700715
Austin Schuh63097262023-08-16 17:04:29 -0700716 bool started() const;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700717
Adam Snaider13d48d92023-08-03 12:20:15 -0700718 // Returns the next sorted message from the set of log files.
719 const Message *Front();
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700720 // Pops the front message. This should only be called after a call to
721 // Front().
722 void PopFront();
723
724 private:
725 int index_ = 0;
726
727 // TODO(austin): Sanjay points out this is pretty inefficient. Don't keep so
728 // many things open.
Austin Schuh63097262023-08-16 17:04:29 -0700729 // A list of all the parts mergers. Only the boots with something to sort are
730 // instantiated.
Alexei Strotsa8dadd12023-04-28 15:19:23 -0700731 std::vector<std::unique_ptr<PartsMerger>> parts_mergers_;
Austin Schuh63097262023-08-16 17:04:29 -0700732
733 std::shared_ptr<const Configuration> configuration_;
734 int node_;
735};
736
737enum class TimestampQueueStrategy {
738 // Read the timestamps at the same time as all the other data.
739 kQueueTogether,
740 // Read the timestamps first.
741 kQueueTimestampsAtStartup,
742};
743
744// Class to manage queueing up timestamps from BootMerger and notifying
745// TimestampMapper of them.
746class SplitTimestampBootMerger {
747 public:
748 SplitTimestampBootMerger(std::string_view node_name,
749 const LogFilesContainer &log_files,
750 TimestampQueueStrategy timestamp_queue_strategy);
751
752 // Copying and moving will mess up the internal raw pointers. Just don't do
753 // it.
754 SplitTimestampBootMerger(SplitTimestampBootMerger const &) = delete;
755 SplitTimestampBootMerger(SplitTimestampBootMerger &&) = delete;
756 void operator=(SplitTimestampBootMerger const &) = delete;
757 void operator=(SplitTimestampBootMerger &&) = delete;
758
759 // Reads all timestamps into a member variable queue, and calls the function
760 // on each timestamp. This only saves timestamps, which are defined as
761 // messages sent on this node, but not originally from this node. To make
762 // that distinction, source_node is provided which has a list of which node
763 // index is the source node for each channel, where the channel index is the
764 // array index.
765 void QueueTimestamps(std::function<void(TimestampedMessage *)> fn,
766 const std::vector<size_t> &source_node);
767
768 // Node index in the configuration of this node.
769 int node() const { return boot_merger_.node(); }
770 // Returns the name of the node this class is sorting for.
771 std::string_view node_name() const;
772
773 std::shared_ptr<const Configuration> configuration() const {
774 return boot_merger_.configuration();
775 }
776
777 monotonic_clock::time_point monotonic_start_time(size_t boot) const;
778 realtime_clock::time_point realtime_start_time(size_t boot) const;
779 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const;
780
781 // Returns true if the log has been started.
782 bool started() const {
783 // Timestamps don't count, so only track boot_merger_.
784 return boot_merger_.started();
785 }
786
Adam Snaider13d48d92023-08-03 12:20:15 -0700787 // Returns the next sorted message from the set of log files.
788 const Message *Front();
Austin Schuh63097262023-08-16 17:04:29 -0700789
790 // Pops the front message. This should only be called after a call to
791 // Front().
792 void PopFront();
793
794 private:
795 enum class MessageSource {
796 kTimestampMessage,
797 kBootMerger,
798 };
799
800 MessageSource message_source_ = MessageSource::kBootMerger;
801
802 // Boot merger for data and potentially timestamps.
803 BootMerger boot_merger_;
804
805 // Boot merger for just timestamps. Any data read from here is to be ignored.
806 std::unique_ptr<BootMerger> timestamp_boot_merger_;
807
808 // The callback requires us to convert each message to a TimestampedMessage.
809 std::deque<TimestampedMessage> timestamp_messages_;
810
811 // Storage for the next timestamp message to return. This is separate so we
812 // can convert them back to a Message.
813 //
814 // TODO(austin): It would be nice to not have to convert...
815 std::optional<Message> next_timestamp_;
816
817 // Start times for each boot.
818 std::vector<monotonic_clock::time_point> monotonic_start_time_;
819 std::vector<realtime_clock::time_point> realtime_start_time_;
820
821 // Tracks if QueueTimestamps loaded any timestamps.
822 bool queue_timestamps_ran_ = false;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700823};
824
Austin Schuhd2f96102020-12-01 20:27:29 -0800825// Class to match timestamps with the corresponding data from other nodes.
Austin Schuh79b30942021-01-24 22:32:21 -0800826//
827// This class also buffers data for the node it represents, and supports
828// notifying when new data is queued as well as queueing until a point in time.
Austin Schuhd2f96102020-12-01 20:27:29 -0800829class TimestampMapper {
830 public:
Alexei Strots1f51ac72023-05-15 10:14:54 -0700831 TimestampMapper(std::string_view node_name,
Austin Schuh63097262023-08-16 17:04:29 -0700832 const LogFilesContainer &log_files,
833 TimestampQueueStrategy timestamp_queue_strategy);
Austin Schuhd2f96102020-12-01 20:27:29 -0800834
835 // Copying and moving will mess up the internal raw pointers. Just don't do
836 // it.
837 TimestampMapper(TimestampMapper const &) = delete;
838 TimestampMapper(TimestampMapper &&) = delete;
839 void operator=(TimestampMapper const &) = delete;
840 void operator=(TimestampMapper &&) = delete;
841
842 // TODO(austin): It would be super helpful to provide a way to queue up to
843 // time X without matching timestamps, and to then be able to pull the
844 // timestamps out of this queue. This lets us bootstrap time estimation
845 // without exploding memory usage worst case.
846
Austin Schuh0ca51f32020-12-25 21:51:45 -0800847 const Configuration *configuration() const { return configuration_.get(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800848
849 // Returns which node this is sorting for.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700850 size_t node() const { return boot_merger_.node(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800851
852 // The start time of this log.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700853 monotonic_clock::time_point monotonic_start_time(size_t boot) const {
854 return boot_merger_.monotonic_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800855 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700856 realtime_clock::time_point realtime_start_time(size_t boot) const {
857 return boot_merger_.realtime_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800858 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800859 // Returns the oldest timestamp on a message on this boot.
860 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const {
861 return boot_merger_.monotonic_oldest_time(boot);
862 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800863
864 // Uses timestamp_mapper as the peer for its node. Only one mapper may be set
865 // for each node. Peers are used to look up the data for timestamps on this
866 // node.
867 void AddPeer(TimestampMapper *timestamp_mapper);
868
Austin Schuh24bf4972021-06-29 22:09:08 -0700869 // Returns true if anything has been queued up.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700870 bool started() const { return boot_merger_.started(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800871
872 // Returns the next message for this node.
873 TimestampedMessage *Front();
874 // Pops the next message. Front must be called first.
875 void PopFront();
876
877 // Returns debug information about this node.
878 std::string DebugString() const;
879
Austin Schuh63097262023-08-16 17:04:29 -0700880 // Queues just the timestamps so that the timestamp callback gets called.
881 // Note, the timestamp callback will get called when they get returned too, so
882 // make sure to unset it if you don't want to be called twice.
883 void QueueTimestamps();
884
Austin Schuh79b30942021-01-24 22:32:21 -0800885 // Queues data the provided time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700886 void QueueUntil(BootTimestamp queue_time);
Austin Schuhe639ea12021-01-25 13:00:22 -0800887 // Queues until we have time_estimation_buffer of data in the queue.
888 void QueueFor(std::chrono::nanoseconds time_estimation_buffer);
Austin Schuh79b30942021-01-24 22:32:21 -0800889
Austin Schuh06601222021-01-26 17:02:50 -0800890 // Queues until the condition is met.
891 template <typename T>
892 void QueueUntilCondition(T fn) {
893 while (true) {
894 if (fn()) {
895 break;
896 }
897 if (!QueueMatched()) {
898 break;
899 }
900 }
901 }
902
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700903 // Sets the callback that can be used to skip messages.
904 void set_replay_channels_callback(
905 std::function<bool(const TimestampedMessage &)> fn) {
906 replay_channels_callback_ = fn;
907 }
908
Austin Schuh79b30942021-01-24 22:32:21 -0800909 // Sets a callback to be called whenever a full message is queued.
910 void set_timestamp_callback(std::function<void(TimestampedMessage *)> fn) {
911 timestamp_callback_ = fn;
912 }
913
Austin Schuhd2f96102020-12-01 20:27:29 -0800914 private:
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700915 // Result of MaybeQueueMatched
916 enum class MatchResult : uint8_t {
917 kEndOfFile, // End of the log file being read
918 kQueued, // Message was queued
919 kSkipped // Message was skipped over
920 };
921
Austin Schuhd2f96102020-12-01 20:27:29 -0800922 // The state for a remote node. This holds the data that needs to be matched
923 // with the remote node's timestamps.
924 struct NodeData {
925 // True if we should save data here. This should be true if any of the
926 // bools in delivered below are true.
927 bool any_delivered = false;
928
Austin Schuh36c00932021-07-19 18:13:21 -0700929 // True if we have a peer and therefore should be saving data for it.
930 bool save_for_peer = false;
931
Austin Schuhd2f96102020-12-01 20:27:29 -0800932 // Peer pointer. This node is only to be considered if a peer is set.
933 TimestampMapper *peer = nullptr;
934
935 struct ChannelData {
936 // Deque per channel. This contains the data from the outside
937 // TimestampMapper node which is relevant for the node this NodeData
938 // points to.
939 std::deque<Message> messages;
940 // Bool tracking per channel if a message is delivered to the node this
941 // NodeData represents.
942 bool delivered = false;
Austin Schuh6a7358f2021-11-18 22:40:40 -0800943 // The TTL for delivery.
944 std::chrono::nanoseconds time_to_live = std::chrono::nanoseconds(0);
Austin Schuhd2f96102020-12-01 20:27:29 -0800945 };
946
947 // Vector with per channel data.
948 std::vector<ChannelData> channels;
949 };
950
951 // Returns (and forgets about) the data for the provided timestamp message
952 // showing when it was delivered to this node.
953 Message MatchingMessageFor(const Message &message);
954
955 // Queues up a single message into our message queue, and any nodes that this
956 // message is delivered to. Returns true if one was available, false
957 // otherwise.
958 bool Queue();
959
Austin Schuh79b30942021-01-24 22:32:21 -0800960 // Queues up a single matched message into our matched message queue. Returns
961 // true if one was queued, and false otherwise.
962 bool QueueMatched();
963
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700964 // Queues a message if the replay_channels_callback is passed and the end of
965 // the log file has not been reached.
966 MatchResult MaybeQueueMatched();
967
Austin Schuhd2f96102020-12-01 20:27:29 -0800968 // Queues up data until we have at least one message >= to time t.
969 // Useful for triggering a remote node to read enough data to have the
970 // timestamp you care about available.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700971 void QueueUnmatchedUntil(BootTimestamp t);
Austin Schuhd2f96102020-12-01 20:27:29 -0800972
Austin Schuh79b30942021-01-24 22:32:21 -0800973 // Queues m into matched_messages_.
Adam Snaider13d48d92023-08-03 12:20:15 -0700974 void QueueMessage(const Message *m);
Austin Schuhd2f96102020-12-01 20:27:29 -0800975
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700976 // If a replay_channels_callback was set and the callback returns false, a
977 // matched message is popped and true is returned. Otherwise false is
978 // returned.
979 bool CheckReplayChannelsAndMaybePop(const TimestampedMessage &message);
980
Austin Schuh58646e22021-08-23 23:51:46 -0700981 // Returns the name of the node this class is sorting for.
982 std::string_view node_name() const {
Austin Schuh63097262023-08-16 17:04:29 -0700983 return configuration::NodeName(configuration(), node());
Austin Schuh58646e22021-08-23 23:51:46 -0700984 }
985
Austin Schuhd2f96102020-12-01 20:27:29 -0800986 // The node merger to source messages from.
Austin Schuh63097262023-08-16 17:04:29 -0700987 SplitTimestampBootMerger boot_merger_;
Austin Schuh0ca51f32020-12-25 21:51:45 -0800988
989 std::shared_ptr<const Configuration> configuration_;
990
Austin Schuhd2f96102020-12-01 20:27:29 -0800991 // The buffer of messages for this node. These are not matched with any
992 // remote data.
993 std::deque<Message> messages_;
994 // The node index for the source node for each channel.
995 std::vector<size_t> source_node_;
996
997 // Vector per node. Not all nodes will have anything.
998 std::vector<NodeData> nodes_data_;
999
1000 // Latest message to return.
Austin Schuh79b30942021-01-24 22:32:21 -08001001 std::deque<TimestampedMessage> matched_messages_;
Austin Schuhd2f96102020-12-01 20:27:29 -08001002
Austin Schuh79b30942021-01-24 22:32:21 -08001003 // Tracks the state of the first message in matched_messages_. Do we need to
1004 // update it, is it valid, or should we return nullptr?
Austin Schuhd2f96102020-12-01 20:27:29 -08001005 enum class FirstMessage {
1006 kNeedsUpdate,
1007 kInMessage,
1008 kNullptr,
1009 };
1010 FirstMessage first_message_ = FirstMessage::kNeedsUpdate;
1011
1012 // Timestamp of the last message returned. Used to make sure nothing goes
1013 // backwards.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001014 BootTimestamp last_message_time_ = BootTimestamp::min_time();
Austin Schuh6a7358f2021-11-18 22:40:40 -08001015 BootTimestamp last_popped_message_time_ = BootTimestamp::min_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08001016 // Time this node is queued up until. Used for caching.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001017 BootTimestamp queued_until_ = BootTimestamp::min_time();
Austin Schuh79b30942021-01-24 22:32:21 -08001018
1019 std::function<void(TimestampedMessage *)> timestamp_callback_;
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001020 std::function<bool(TimestampedMessage &)> replay_channels_callback_;
Austin Schuh8f52ed52020-11-30 23:12:39 -08001021};
1022
Alexei Strots036d84e2023-05-03 16:05:12 -07001023// Returns the node name, or an empty string if we are a single node.
1024inline std::string_view MaybeNodeName(const Node *node) {
1025 if (node != nullptr) {
1026 return node->name()->string_view();
1027 }
1028 return "";
1029}
Austin Schuhee711052020-08-24 16:06:09 -07001030
Austin Schuh71a40d42023-02-04 21:22:22 -08001031// Class to copy a RemoteMessage into the provided buffer.
1032class RemoteMessageCopier : public DataEncoder::Copier {
1033 public:
1034 RemoteMessageCopier(const message_bridge::RemoteMessage *message,
1035 int channel_index,
1036 aos::monotonic_clock::time_point monotonic_timestamp_time,
1037 EventLoop *event_loop)
1038 : DataEncoder::Copier(PackRemoteMessageSize()),
1039 message_(message),
1040 channel_index_(channel_index),
1041 monotonic_timestamp_time_(monotonic_timestamp_time),
1042 event_loop_(event_loop) {}
1043
1044 monotonic_clock::time_point end_time() const { return end_time_; }
1045
1046 size_t Copy(uint8_t *data, size_t start_byte, size_t end_byte) final {
1047 size_t result = PackRemoteMessageInline(data, message_, channel_index_,
1048 monotonic_timestamp_time_,
1049 start_byte, end_byte);
1050 end_time_ = event_loop_->monotonic_now();
1051 return result;
1052 }
1053
1054 private:
1055 const message_bridge::RemoteMessage *message_;
1056 int channel_index_;
1057 aos::monotonic_clock::time_point monotonic_timestamp_time_;
1058 EventLoop *event_loop_;
1059 monotonic_clock::time_point end_time_;
1060};
1061
1062// Class to copy a context into the provided buffer.
1063class ContextDataCopier : public DataEncoder::Copier {
1064 public:
1065 ContextDataCopier(const Context &context, int channel_index, LogType log_type,
1066 EventLoop *event_loop)
1067 : DataEncoder::Copier(PackMessageSize(log_type, context.size)),
1068 context_(context),
1069 channel_index_(channel_index),
1070 log_type_(log_type),
1071 event_loop_(event_loop) {}
1072
1073 monotonic_clock::time_point end_time() const { return end_time_; }
1074
1075 size_t Copy(uint8_t *data, size_t start_byte, size_t end_byte) final {
1076 size_t result = PackMessageInline(data, context_, channel_index_, log_type_,
1077 start_byte, end_byte);
1078 end_time_ = event_loop_->monotonic_now();
1079 return result;
1080 }
1081
1082 private:
1083 const Context &context_;
1084 const int channel_index_;
1085 const LogType log_type_;
1086 EventLoop *event_loop_;
1087 monotonic_clock::time_point end_time_;
1088};
1089
Brian Silvermanf51499a2020-09-21 12:49:08 -07001090} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -08001091
1092#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_