blob: 50f6b40738e5ead0d4760090bb77a28dc1a70707 [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"
Brian Silvermanf51499a2020-09-21 12:49:08 -070019#include "aos/containers/resizeable_buffer.h"
Austin Schuha36c8902019-12-30 18:07:15 -080020#include "aos/events/event_loop.h"
Austin Schuh2dc8c7d2021-07-01 17:41:28 -070021#include "aos/events/logging/boot_timestamp.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070022#include "aos/events/logging/buffer_encoder.h"
Austin Schuhc41603c2020-10-11 16:17:37 -070023#include "aos/events/logging/logfile_sorting.h"
Austin Schuha36c8902019-12-30 18:07:15 -080024#include "aos/events/logging/logger_generated.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070025#include "aos/flatbuffers.h"
Austin Schuhf2d0e682022-10-16 14:20:58 -070026#include "aos/network/remote_message_generated.h"
Austin Schuha36c8902019-12-30 18:07:15 -080027#include "flatbuffers/flatbuffers.h"
28
Brian Silvermanf51499a2020-09-21 12:49:08 -070029namespace aos::logger {
Austin Schuha36c8902019-12-30 18:07:15 -080030
31enum class LogType : uint8_t {
32 // The message originated on this node and should be logged here.
33 kLogMessage,
34 // The message originated on another node, but only the delivery times are
35 // logged here.
36 kLogDeliveryTimeOnly,
37 // The message originated on another node. Log it and the delivery times
38 // together. The message_gateway is responsible for logging any messages
39 // which didn't get delivered.
Austin Schuh6f3babe2020-01-26 20:34:50 -080040 kLogMessageAndDeliveryTime,
41 // The message originated on the other node and should be logged on this node.
42 kLogRemoteMessage
Austin Schuha36c8902019-12-30 18:07:15 -080043};
44
Austin Schuha36c8902019-12-30 18:07:15 -080045// This class manages efficiently writing a sequence of detached buffers to a
Brian Silvermanf51499a2020-09-21 12:49:08 -070046// file. It encodes them, queues them up, and batches the write operation.
Austin Schuh4c3cdb72023-02-11 15:05:26 -080047//
48// There are a couple over-arching constraints on writing to keep track of.
49// 1) The kernel is both faster and more efficient at writing large, aligned
50// chunks with O_DIRECT set on the file. The alignment needed is specified
51// by kSector and is file system dependent.
52// 2) Not all encoders support generating round multiples of kSector of data.
53// Rather than burden the API for detecting when that is the case, we want
54// DetachedBufferWriter to be as efficient as it can at writing what given.
55// 3) Some files are small and not updated frequently. They need to be
56// flushed or we will lose data on power off. It is most efficient to write
57// as much as we can aligned by kSector and then fall back to the non direct
58// method when it has been flushed.
59// 4) Not all filesystems support O_DIRECT, and different sizes may be optimal
60// for different machines. The defaults should work decently anywhere and
61// be tuneable for faster systems.
Austin Schuha36c8902019-12-30 18:07:15 -080062class DetachedBufferWriter {
63 public:
Brian Silvermana9f2ec92020-10-06 18:00:53 -070064 // Marker struct for one of our constructor overloads.
65 struct already_out_of_space_t {};
66
Austin Schuh4c3cdb72023-02-11 15:05:26 -080067 // Size of an aligned sector used to detect when the data is aligned enough to
68 // use O_DIRECT instead.
69 static constexpr size_t kSector = 512u;
70
Brian Silvermanf51499a2020-09-21 12:49:08 -070071 DetachedBufferWriter(std::string_view filename,
Austin Schuh48d10d62022-10-16 22:19:23 -070072 std::unique_ptr<DataEncoder> encoder);
Brian Silvermana9f2ec92020-10-06 18:00:53 -070073 // Creates a dummy instance which won't even open a file. It will act as if
74 // opening the file ran out of space immediately.
75 DetachedBufferWriter(already_out_of_space_t) : ran_out_of_space_(true) {}
Austin Schuh2f8fd752020-09-01 22:38:28 -070076 DetachedBufferWriter(DetachedBufferWriter &&other);
77 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
78
Austin Schuha36c8902019-12-30 18:07:15 -080079 ~DetachedBufferWriter();
80
Austin Schuh2f8fd752020-09-01 22:38:28 -070081 DetachedBufferWriter &operator=(DetachedBufferWriter &&other);
Brian Silverman98360e22020-04-28 16:51:20 -070082 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
83
Austin Schuh6f3babe2020-01-26 20:34:50 -080084 std::string_view filename() const { return filename_; }
85
Brian Silvermana9f2ec92020-10-06 18:00:53 -070086 // This will be true until Close() is called, unless the file couldn't be
87 // created due to running out of space.
88 bool is_open() const { return fd_ != -1; }
89
Brian Silvermanf51499a2020-09-21 12:49:08 -070090 // Queues up a finished FlatBufferBuilder to be encoded and written.
91 //
92 // Triggers a flush if there's enough data queued up.
93 //
94 // Steals the detached buffer from it.
Austin Schuh48d10d62022-10-16 22:19:23 -070095 void CopyMessage(DataEncoder::Copier *coppier,
96 aos::monotonic_clock::time_point now);
Austin Schuha36c8902019-12-30 18:07:15 -080097
Brian Silverman0465fcf2020-09-24 00:29:18 -070098 // Indicates we got ENOSPC when trying to write. After this returns true, no
99 // further data is written.
100 bool ran_out_of_space() const { return ran_out_of_space_; }
101
102 // To avoid silently failing to write logfiles, you must call this before
103 // destruction if ran_out_of_space() is true and the situation has been
104 // handled.
105 void acknowledge_out_of_space() {
106 CHECK(ran_out_of_space_);
107 acknowledge_ran_out_of_space_ = true;
108 }
109
110 // Fully flushes and closes the underlying file now. No additional data may be
111 // enqueued after calling this.
112 //
113 // This will be performed in the destructor automatically.
114 //
115 // Note that this may set ran_out_of_space().
116 void Close();
117
Brian Silvermanf51499a2020-09-21 12:49:08 -0700118 // Returns the total number of bytes written and currently queued.
Austin Schuha426f1f2021-03-31 22:27:41 -0700119 size_t total_bytes() const {
120 if (!encoder_) {
121 return 0;
122 }
123 return encoder_->total_bytes();
124 }
Austin Schuha36c8902019-12-30 18:07:15 -0800125
Brian Silvermanf51499a2020-09-21 12:49:08 -0700126 // The maximum time for a single write call, or 0 if none have been performed.
127 std::chrono::nanoseconds max_write_time() const { return max_write_time_; }
128 // The number of bytes in the longest write call, or -1 if none have been
129 // performed.
130 int max_write_time_bytes() const { return max_write_time_bytes_; }
131 // The number of buffers in the longest write call, or -1 if none have been
132 // performed.
133 int max_write_time_messages() const { return max_write_time_messages_; }
134 // The total time spent in write calls.
135 std::chrono::nanoseconds total_write_time() const {
136 return total_write_time_;
137 }
138 // The total number of writes which have been performed.
139 int total_write_count() const { return total_write_count_; }
140 // The total number of messages which have been written.
141 int total_write_messages() const { return total_write_messages_; }
142 // The total number of bytes which have been written.
143 int total_write_bytes() const { return total_write_bytes_; }
144 void ResetStatistics() {
145 max_write_time_ = std::chrono::nanoseconds::zero();
146 max_write_time_bytes_ = -1;
147 max_write_time_messages_ = -1;
148 total_write_time_ = std::chrono::nanoseconds::zero();
149 total_write_count_ = 0;
150 total_write_messages_ = 0;
151 total_write_bytes_ = 0;
152 }
Brian Silverman98360e22020-04-28 16:51:20 -0700153
Austin Schuha36c8902019-12-30 18:07:15 -0800154 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700155 // Performs a single writev call with as much of the data we have queued up as
Austin Schuh8bdfc492023-02-11 12:53:13 -0800156 // possible. now is the time we flushed at, to be recorded in
157 // last_flush_time_.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700158 //
159 // This will normally take all of the data we have queued up, unless an
160 // encoder has spit out a big enough chunk all at once that we can't manage
161 // all of it.
Austin Schuh8bdfc492023-02-11 12:53:13 -0800162 void Flush(aos::monotonic_clock::time_point now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700163
Brian Silverman0465fcf2020-09-24 00:29:18 -0700164 // write_return is what write(2) or writev(2) returned. write_size is the
165 // number of bytes we expected it to write.
166 void HandleWriteReturn(ssize_t write_return, size_t write_size);
167
Brian Silvermanf51499a2020-09-21 12:49:08 -0700168 void UpdateStatsForWrite(aos::monotonic_clock::duration duration,
169 ssize_t written, int iovec_size);
170
171 // Flushes data if we've reached the threshold to do that as part of normal
Austin Schuhbd06ae42021-03-31 22:48:21 -0700172 // operation either due to the outstanding queued data, or because we have
173 // passed our flush period. now is the current time to save some CPU grabbing
174 // the current time. It just needs to be close.
175 void FlushAtThreshold(aos::monotonic_clock::time_point now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700176
Austin Schuh4c3cdb72023-02-11 15:05:26 -0800177 // Enables O_DIRECT on the open file if it is supported. Cheap to call if it
178 // is already enabled.
179 void EnableDirect();
180 // Disables O_DIRECT on the open file if it is supported. Cheap to call if it
181 // is already disabld.
182 void DisableDirect();
183
184 // Writes a chunk of iovecs. aligned is true if all the data is kSector byte
185 // aligned and multiples of it in length, and counted_size is the sum of the
186 // sizes of all the chunks of data. Returns the size of data written.
187 size_t WriteV(struct iovec *iovec_data, size_t iovec_size, bool aligned,
188 size_t counted_size);
189
190 bool ODirectEnabled() { return !!(flags_ & O_DIRECT); }
191
Austin Schuh2f8fd752020-09-01 22:38:28 -0700192 std::string filename_;
Austin Schuh48d10d62022-10-16 22:19:23 -0700193 std::unique_ptr<DataEncoder> encoder_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800194
Austin Schuha36c8902019-12-30 18:07:15 -0800195 int fd_ = -1;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700196 bool ran_out_of_space_ = false;
197 bool acknowledge_ran_out_of_space_ = false;
Austin Schuha36c8902019-12-30 18:07:15 -0800198
Austin Schuha36c8902019-12-30 18:07:15 -0800199 // List of iovecs to use with writev. This is a member variable to avoid
200 // churn.
201 std::vector<struct iovec> iovec_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700202
203 std::chrono::nanoseconds max_write_time_ = std::chrono::nanoseconds::zero();
204 int max_write_time_bytes_ = -1;
205 int max_write_time_messages_ = -1;
206 std::chrono::nanoseconds total_write_time_ = std::chrono::nanoseconds::zero();
207 int total_write_count_ = 0;
208 int total_write_messages_ = 0;
209 int total_write_bytes_ = 0;
Austin Schuh4c3cdb72023-02-11 15:05:26 -0800210 int last_synced_bytes_ = 0;
211
212 bool supports_odirect_ = true;
213 int flags_ = 0;
Austin Schuhbd06ae42021-03-31 22:48:21 -0700214
215 aos::monotonic_clock::time_point last_flush_time_ =
216 aos::monotonic_clock::min_time;
Austin Schuha36c8902019-12-30 18:07:15 -0800217};
218
Austin Schuhf2d0e682022-10-16 14:20:58 -0700219// Repacks the provided RemoteMessage into fbb.
220flatbuffers::Offset<MessageHeader> PackRemoteMessage(
221 flatbuffers::FlatBufferBuilder *fbb,
222 const message_bridge::RemoteMessage *msg, int channel_index,
223 const aos::monotonic_clock::time_point monotonic_timestamp_time);
224
225constexpr flatbuffers::uoffset_t PackRemoteMessageSize() { return 96u; }
226size_t PackRemoteMessageInline(
227 uint8_t *data, const message_bridge::RemoteMessage *msg, int channel_index,
Austin Schuh71a40d42023-02-04 21:22:22 -0800228 const aos::monotonic_clock::time_point monotonic_timestamp_time,
229 size_t start_byte, size_t end_byte);
Austin Schuhf2d0e682022-10-16 14:20:58 -0700230
Austin Schuha36c8902019-12-30 18:07:15 -0800231// Packes a message pointed to by the context into a MessageHeader.
232flatbuffers::Offset<MessageHeader> PackMessage(
233 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
234 int channel_index, LogType log_type);
235
Austin Schuhfa30c352022-10-16 11:12:02 -0700236// Returns the size that the packed message from PackMessage or
237// PackMessageInline will be.
Austin Schuh48d10d62022-10-16 22:19:23 -0700238flatbuffers::uoffset_t PackMessageSize(LogType log_type, size_t data_size);
Austin Schuhfa30c352022-10-16 11:12:02 -0700239
240// Packs the provided message pointed to by context into the provided buffer.
241// This is equivalent to PackMessage, but doesn't require allocating a
242// FlatBufferBuilder underneath.
243size_t PackMessageInline(uint8_t *data, const Context &contex,
Austin Schuh71a40d42023-02-04 21:22:22 -0800244 int channel_index, LogType log_type, size_t start_byte,
245 size_t end_byte);
Austin Schuhfa30c352022-10-16 11:12:02 -0700246
Austin Schuh05b70472020-01-01 17:11:17 -0800247// Class to read chunks out of a log file.
248class SpanReader {
249 public:
Austin Schuhcd368422021-11-22 21:23:29 -0800250 SpanReader(std::string_view filename, bool quiet = false);
Austin Schuha36c8902019-12-30 18:07:15 -0800251
Austin Schuh6f3babe2020-01-26 20:34:50 -0800252 std::string_view filename() const { return filename_; }
253
Brian Smarttea913d42021-12-10 15:02:38 -0800254 size_t TotalRead() const { return total_read_; }
255 size_t TotalConsumed() const { return total_consumed_; }
Austin Schuh60e77942022-05-16 17:48:24 -0700256 bool IsIncomplete() const {
257 return is_finished_ && total_consumed_ < total_read_;
258 }
Brian Smarttea913d42021-12-10 15:02:38 -0800259
Austin Schuhcf5f6442021-07-06 10:43:28 -0700260 // Returns a span with the data for the next message from the log file,
261 // including the size. The result is only guarenteed to be valid until
262 // ReadMessage() or PeekMessage() is called again.
Austin Schuh05b70472020-01-01 17:11:17 -0800263 absl::Span<const uint8_t> ReadMessage();
264
Austin Schuhcf5f6442021-07-06 10:43:28 -0700265 // Returns a span with the data for the next message without consuming it.
266 // Multiple calls to PeekMessage return the same data. ReadMessage or
267 // ConsumeMessage must be called to get the next message.
268 absl::Span<const uint8_t> PeekMessage();
269 // Consumes the message so the next call to ReadMessage or PeekMessage returns
270 // new data. This does not invalidate the data.
271 void ConsumeMessage();
272
Austin Schuh05b70472020-01-01 17:11:17 -0800273 private:
274 // TODO(austin): Optimization:
275 // Allocate the 256k blocks like we do today. But, refcount them with
276 // shared_ptr pointed to by the messageheader that is returned. This avoids
277 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700278 // And (Brian): Consider just mmapping the file and handing out refcounted
279 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800280
281 // Reads a chunk of data into data_. Returns false if no data was read.
282 bool ReadBlock();
283
Austin Schuhc41603c2020-10-11 16:17:37 -0700284 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800285
Brian Silvermanf51499a2020-09-21 12:49:08 -0700286 // File reader and data decoder.
287 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800288
Brian Silvermanf51499a2020-09-21 12:49:08 -0700289 // Vector to read into.
290 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800291
292 // Amount of data consumed already in data_.
293 size_t consumed_data_ = 0;
Brian Smarttea913d42021-12-10 15:02:38 -0800294
295 // Accumulates the total volume of bytes read from filename_
296 size_t total_read_ = 0;
297
298 // Accumulates the total volume of read bytes that were 'consumed' into
299 // messages. May be less than total_read_, if the last message (span) is
300 // either truncated or somehow corrupt.
301 size_t total_consumed_ = 0;
302
303 // Reached the end, no more readable messages.
304 bool is_finished_ = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800305};
306
Brian Silvermanfee16972021-09-14 12:06:38 -0700307// Reads the last header from a log file. This handles any duplicate headers
308// that were written.
309std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
310 SpanReader *span_reader);
311std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
312 std::string_view filename);
313// Reads the Nth message from a log file, excluding the header. Note: this
314// doesn't handle duplicate headers.
315std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
316 std::string_view filename, size_t n);
317
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700318class UnpackedMessageHeader;
319
Austin Schuh05b70472020-01-01 17:11:17 -0800320// Class which handles reading the header and messages from the log file. This
321// handles any per-file state left before merging below.
322class MessageReader {
323 public:
324 MessageReader(std::string_view filename);
325
Austin Schuh6f3babe2020-01-26 20:34:50 -0800326 std::string_view filename() const { return span_reader_.filename(); }
327
Austin Schuh05b70472020-01-01 17:11:17 -0800328 // Returns the header from the log file.
329 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700330 return &raw_log_file_header_.message();
331 }
332
333 // Returns the raw data of the header from the log file.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800334 const SizePrefixedFlatbufferVector<LogFileHeader> &raw_log_file_header()
335 const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700336 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800337 }
338
339 // Returns the minimum maount of data needed to queue up for sorting before
340 // ware guarenteed to not see data out of order.
341 std::chrono::nanoseconds max_out_of_order_duration() const {
342 return max_out_of_order_duration_;
343 }
344
Austin Schuhcde938c2020-02-02 17:30:07 -0800345 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800346 monotonic_clock::time_point newest_timestamp() const {
347 return newest_timestamp_;
348 }
349
350 // Returns the next message if there is one.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700351 std::shared_ptr<UnpackedMessageHeader> ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800352
353 // The time at which we need to read another chunk from the logfile.
354 monotonic_clock::time_point queue_data_time() const {
355 return newest_timestamp() - max_out_of_order_duration();
356 }
357
Brian Smarttea913d42021-12-10 15:02:38 -0800358 // Flag value setters for testing
359 void set_crash_on_corrupt_message_flag(bool b) {
360 crash_on_corrupt_message_flag_ = b;
361 }
362 void set_ignore_corrupt_messages_flag(bool b) {
363 ignore_corrupt_messages_flag_ = b;
364 }
365
Austin Schuh05b70472020-01-01 17:11:17 -0800366 private:
367 // Log chunk reader.
368 SpanReader span_reader_;
369
Austin Schuh97789fc2020-08-01 14:42:45 -0700370 // Vector holding the raw data for the log file header.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800371 SizePrefixedFlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800372
373 // Minimum amount of data to queue up for sorting before we are guarenteed
374 // to not see data out of order.
375 std::chrono::nanoseconds max_out_of_order_duration_;
376
377 // Timestamp of the newest message in a channel queue.
378 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Brian Smarttea913d42021-12-10 15:02:38 -0800379
380 // Total volume of verifiable messages from the beginning of the file.
381 // TODO - are message counts also useful?
382 size_t total_verified_before_ = 0;
383
384 // Total volume of messages with corrupted flatbuffer formatting, if any.
385 // Excludes corrupted message content.
386 // TODO - if the layout included something as simple as a CRC (relatively
387 // fast and robust enough) for each span, then corrupted content could be
388 // included in this check.
389 size_t total_corrupted_ = 0;
390
391 // Total volume of verifiable messages intermixed with corrupted messages,
392 // if any. Will be == 0 if total_corrupted_ == 0.
393 size_t total_verified_during_ = 0;
394
395 // Total volume of verifiable messages found after the last corrupted one,
396 // if any. Will be == 0 if total_corrupted_ == 0.
397 size_t total_verified_after_ = 0;
398
399 bool is_corrupted() const { return total_corrupted_ > 0; }
400
401 bool crash_on_corrupt_message_flag_ = true;
402 bool ignore_corrupt_messages_flag_ = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800403};
404
Austin Schuhc41603c2020-10-11 16:17:37 -0700405// A class to seamlessly read messages from a list of part files.
406class PartsMessageReader {
407 public:
408 PartsMessageReader(LogParts log_parts);
409
410 std::string_view filename() const { return message_reader_.filename(); }
411
Austin Schuhd2f96102020-12-01 20:27:29 -0800412 // Returns the LogParts that holds the filenames we are reading.
413 const LogParts &parts() const { return parts_; }
414
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800415 const LogFileHeader *log_file_header() const {
416 return message_reader_.log_file_header();
417 }
418
Austin Schuhc41603c2020-10-11 16:17:37 -0700419 // Returns the minimum amount of data needed to queue up for sorting before
420 // we are guarenteed to not see data out of order.
421 std::chrono::nanoseconds max_out_of_order_duration() const {
422 return message_reader_.max_out_of_order_duration();
423 }
424
425 // Returns the newest timestamp read out of the log file.
426 monotonic_clock::time_point newest_timestamp() const {
427 return newest_timestamp_;
428 }
429
430 // Returns the next message if there is one, or nullopt if we have reached the
431 // end of all the files.
432 // Note: reading the next message may change the max_out_of_order_duration().
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700433 std::shared_ptr<UnpackedMessageHeader> ReadMessage();
Austin Schuhc41603c2020-10-11 16:17:37 -0700434
Austin Schuh48507722021-07-17 17:29:24 -0700435 // Returns the boot count for the requested node, or std::nullopt if we don't
436 // know.
437 std::optional<size_t> boot_count(size_t node_index) const {
438 CHECK_GE(node_index, 0u);
439 CHECK_LT(node_index, boot_counts_.size());
440 return boot_counts_[node_index];
441 }
442
Austin Schuhc41603c2020-10-11 16:17:37 -0700443 private:
444 // Opens the next log and updates message_reader_. Sets done_ if there is
445 // nothing more to do.
446 void NextLog();
Austin Schuh48507722021-07-17 17:29:24 -0700447 void ComputeBootCounts();
Austin Schuhc41603c2020-10-11 16:17:37 -0700448
449 const LogParts parts_;
450 size_t next_part_index_ = 1u;
451 bool done_ = false;
452 MessageReader message_reader_;
Brian Silvermanfee16972021-09-14 12:06:38 -0700453 // We instantiate the next one early, to allow implementations to prefetch.
454 // TODO(Brian): To get optimal performance when downloading, this needs more
455 // communication with the implementation to prioritize the next part and add
456 // more parallelism when it helps. Maybe some kind of a queue of parts in
457 // order, and the implementation gets to pull however many make sense off the
458 // front?
459 std::optional<MessageReader> next_message_reader_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700460
Austin Schuh315b96b2020-12-11 21:21:12 -0800461 // True after we have seen a message after the start of the log. The
462 // guarentees on logging essentially are that all data from before the
463 // starting time of the log may be arbitrarily out of order, but once we get
464 // max_out_of_order_duration past the start, everything will remain within
465 // max_out_of_order_duration. We shouldn't see anything before the start
466 // after we've seen a message that is at least max_out_of_order_duration after
467 // the start.
468 bool after_start_ = false;
469
Austin Schuhc41603c2020-10-11 16:17:37 -0700470 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh48507722021-07-17 17:29:24 -0700471
472 // Per node boot counts.
473 std::vector<std::optional<size_t>> boot_counts_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700474};
475
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700476// Stores MessageHeader as a flat header and inline, aligned block of data.
477class UnpackedMessageHeader {
478 public:
James Kuszmaul9776b392023-01-14 14:08:08 -0800479 UnpackedMessageHeader(
480 uint32_t channel_index, monotonic_clock::time_point monotonic_sent_time,
481 realtime_clock::time_point realtime_sent_time, uint32_t queue_index,
482 std::optional<monotonic_clock::time_point> monotonic_remote_time,
483 std::optional<realtime_clock::time_point> realtime_remote_time,
484 std::optional<uint32_t> remote_queue_index,
485 monotonic_clock::time_point monotonic_timestamp_time,
486 bool has_monotonic_timestamp_time, absl::Span<const uint8_t> span)
487 : channel_index(channel_index),
488 monotonic_sent_time(monotonic_sent_time),
489 realtime_sent_time(realtime_sent_time),
490 queue_index(queue_index),
491 monotonic_remote_time(monotonic_remote_time),
492 realtime_remote_time(realtime_remote_time),
493 remote_queue_index(remote_queue_index),
494 monotonic_timestamp_time(monotonic_timestamp_time),
495 has_monotonic_timestamp_time(has_monotonic_timestamp_time),
496 span(span) {}
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700497 UnpackedMessageHeader(const UnpackedMessageHeader &) = delete;
498 UnpackedMessageHeader &operator=(const UnpackedMessageHeader &) = delete;
499
500 // The channel.
501 uint32_t channel_index = 0xffffffff;
502
503 monotonic_clock::time_point monotonic_sent_time;
504 realtime_clock::time_point realtime_sent_time;
505
506 // The local queue index.
507 uint32_t queue_index = 0xffffffff;
508
Austin Schuh826e6ce2021-11-18 20:33:10 -0800509 std::optional<aos::monotonic_clock::time_point> monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700510
511 std::optional<realtime_clock::time_point> realtime_remote_time;
512 std::optional<uint32_t> remote_queue_index;
513
514 // This field is defaulted in the flatbuffer, so we need to store both the
515 // possibly defaulted value and whether it is defaulted.
516 monotonic_clock::time_point monotonic_timestamp_time;
517 bool has_monotonic_timestamp_time;
518
519 static std::shared_ptr<UnpackedMessageHeader> MakeMessage(
520 const MessageHeader &message);
521
522 // Note: we are storing a span here because we need something to put in the
523 // SharedSpan pointer that RawSender takes. We are using the aliasing
524 // constructor of shared_ptr to avoid the allocation, and it needs a nice
525 // pointer to track.
526 absl::Span<const uint8_t> span;
527
528 char actual_data[];
529
530 private:
531 ~UnpackedMessageHeader() {}
532
533 static void DestroyAndFree(UnpackedMessageHeader *p) {
534 p->~UnpackedMessageHeader();
535 free(p);
536 }
537};
538
539std::ostream &operator<<(std::ostream &os,
540 const UnpackedMessageHeader &message);
541
Austin Schuh1be0ce42020-11-29 22:43:26 -0800542// Struct to hold a message as it gets sorted on a single node.
543struct Message {
544 // The channel.
545 uint32_t channel_index = 0xffffffff;
546 // The local queue index.
Austin Schuh58646e22021-08-23 23:51:46 -0700547 // TODO(austin): Technically the boot inside queue_index is redundant with
548 // timestamp. In practice, it is less error-prone to duplicate it. Maybe a
549 // function to return the combined struct?
550 BootQueueIndex queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700551 // The local timestamp.
552 BootTimestamp timestamp;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700553
Austin Schuh48507722021-07-17 17:29:24 -0700554 // Remote boot when this is a timestamp.
555 size_t monotonic_remote_boot = 0xffffff;
556
557 size_t monotonic_timestamp_boot = 0xffffff;
558
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700559 std::shared_ptr<UnpackedMessageHeader> data;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800560
561 bool operator<(const Message &m2) const;
562 bool operator>=(const Message &m2) const;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800563 bool operator==(const Message &m2) const;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800564};
565
566std::ostream &operator<<(std::ostream &os, const Message &m);
567
Austin Schuhd2f96102020-12-01 20:27:29 -0800568// Structure to hold a full message and all the timestamps, which may or may not
569// have been sent from a remote node. The remote_queue_index will be invalid if
570// this message is from the point of view of the node which sent it.
571struct TimestampedMessage {
572 uint32_t channel_index = 0xffffffff;
573
Austin Schuh58646e22021-08-23 23:51:46 -0700574 BootQueueIndex queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700575 BootTimestamp monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800576 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
577
Austin Schuh58646e22021-08-23 23:51:46 -0700578 BootQueueIndex remote_queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700579 BootTimestamp monotonic_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800580 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
581
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700582 BootTimestamp monotonic_timestamp_time;
Austin Schuh8bf1e632021-01-02 22:41:04 -0800583
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700584 std::shared_ptr<UnpackedMessageHeader> data;
Austin Schuhd2f96102020-12-01 20:27:29 -0800585};
586
587std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m);
588
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800589// Class to sort the resulting messages from a PartsMessageReader.
590class LogPartsSorter {
591 public:
592 LogPartsSorter(LogParts log_parts);
593
Austin Schuh0ca51f32020-12-25 21:51:45 -0800594 // Returns the parts that this is sorting messages from.
595 const LogParts &parts() const { return parts_message_reader_.parts(); }
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800596
Austin Schuhd2f96102020-12-01 20:27:29 -0800597 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800598 return parts().monotonic_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800599 }
600 realtime_clock::time_point realtime_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800601 return parts().realtime_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800602 }
603
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800604 // The time this data is sorted until.
605 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
606
607 // Returns the next sorted message from the log file. It is safe to call
608 // std::move() on the result to move the data flatbuffer from it.
609 Message *Front();
610 // Pops the front message. This should only be called after a call to
611 // Front().
612 void PopFront();
613
614 // Returns a debug string representing the contents of this sorter.
615 std::string DebugString() const;
616
617 private:
618 // Log parts reader we are wrapping.
619 PartsMessageReader parts_message_reader_;
620 // Cache of the time we are sorted until.
621 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
622
Austin Schuhb000de62020-12-03 22:00:40 -0800623 // Timestamp of the last message returned. Used to make sure nothing goes
624 // backwards.
625 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
626
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800627 // Set used for efficient sorting of messages. We can benchmark and evaluate
628 // other data structures if this proves to be the bottleneck.
629 absl::btree_set<Message> messages_;
Austin Schuh48507722021-07-17 17:29:24 -0700630
631 // Mapping from channel to source node.
632 // TODO(austin): Should we put this in Boots so it can be cached for everyone?
633 std::vector<size_t> source_node_index_;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800634};
635
Austin Schuh8f52ed52020-11-30 23:12:39 -0800636// Class to run merge sort on the messages from multiple LogPartsSorter
637// instances.
638class NodeMerger {
639 public:
Austin Schuhd2f96102020-12-01 20:27:29 -0800640 NodeMerger(std::vector<LogParts> parts);
641
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700642 // Copying and moving will mess up the internal raw pointers. Just don't do
643 // it.
644 NodeMerger(NodeMerger const &) = delete;
645 NodeMerger(NodeMerger &&) = delete;
646 void operator=(NodeMerger const &) = delete;
647 void operator=(NodeMerger &&) = delete;
648
Austin Schuhd2f96102020-12-01 20:27:29 -0800649 // Node index in the configuration of this node.
650 int node() const { return node_; }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800651
Austin Schuh0ca51f32020-12-25 21:51:45 -0800652 // List of parts being sorted together.
653 std::vector<const LogParts *> Parts() const;
654
655 const Configuration *configuration() const {
656 return parts_sorters_[0].parts().config.get();
Austin Schuhd2f96102020-12-01 20:27:29 -0800657 }
658
659 monotonic_clock::time_point monotonic_start_time() const {
660 return monotonic_start_time_;
661 }
662 realtime_clock::time_point realtime_start_time() const {
663 return realtime_start_time_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800664 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800665 monotonic_clock::time_point monotonic_oldest_time() const {
666 return monotonic_oldest_time_;
667 }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800668
669 // The time this data is sorted until.
670 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
671
672 // Returns the next sorted message from the set of log files. It is safe to
673 // call std::move() on the result to move the data flatbuffer from it.
674 Message *Front();
675 // Pops the front message. This should only be called after a call to
676 // Front().
677 void PopFront();
678
679 private:
680 // Unsorted list of all parts sorters.
Austin Schuhd2f96102020-12-01 20:27:29 -0800681 std::vector<LogPartsSorter> parts_sorters_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800682 // Pointer to the parts sorter holding the current Front message if one
683 // exists, or nullptr if a new one needs to be found.
684 LogPartsSorter *current_ = nullptr;
685 // Cached sorted_until value.
686 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800687
688 // Cached node.
689 int node_;
690
Austin Schuhb000de62020-12-03 22:00:40 -0800691 // Timestamp of the last message returned. Used to make sure nothing goes
692 // backwards.
693 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
694
Austin Schuhd2f96102020-12-01 20:27:29 -0800695 realtime_clock::time_point realtime_start_time_ = realtime_clock::max_time;
696 monotonic_clock::time_point monotonic_start_time_ = monotonic_clock::max_time;
Austin Schuh60e77942022-05-16 17:48:24 -0700697 monotonic_clock::time_point monotonic_oldest_time_ =
698 monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800699};
700
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700701// Class to concatenate multiple boots worth of logs into a single per-node
702// stream.
703class BootMerger {
704 public:
705 BootMerger(std::vector<LogParts> file);
706
707 // Copying and moving will mess up the internal raw pointers. Just don't do
708 // it.
709 BootMerger(BootMerger const &) = delete;
710 BootMerger(BootMerger &&) = delete;
711 void operator=(BootMerger const &) = delete;
712 void operator=(BootMerger &&) = delete;
713
714 // Node index in the configuration of this node.
715 int node() const { return node_mergers_[0]->node(); }
716
717 // List of parts being sorted together.
718 std::vector<const LogParts *> Parts() const;
719
720 const Configuration *configuration() const {
721 return node_mergers_[0]->configuration();
722 }
723
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700724 monotonic_clock::time_point monotonic_start_time(size_t boot) const {
725 CHECK_LT(boot, node_mergers_.size());
726 return node_mergers_[boot]->monotonic_start_time();
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700727 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700728 realtime_clock::time_point realtime_start_time(size_t boot) const {
729 CHECK_LT(boot, node_mergers_.size());
730 return node_mergers_[boot]->realtime_start_time();
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700731 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800732 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const {
733 CHECK_LT(boot, node_mergers_.size());
734 return node_mergers_[boot]->monotonic_oldest_time();
735 }
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700736
737 bool started() const {
738 return node_mergers_[index_]->sorted_until() != monotonic_clock::min_time ||
739 index_ != 0;
740 }
741
742 // Returns the next sorted message from the set of log files. It is safe to
743 // call std::move() on the result to move the data flatbuffer from it.
744 Message *Front();
745 // Pops the front message. This should only be called after a call to
746 // Front().
747 void PopFront();
748
749 private:
750 int index_ = 0;
751
752 // TODO(austin): Sanjay points out this is pretty inefficient. Don't keep so
753 // many things open.
754 std::vector<std::unique_ptr<NodeMerger>> node_mergers_;
755};
756
Austin Schuhd2f96102020-12-01 20:27:29 -0800757// Class to match timestamps with the corresponding data from other nodes.
Austin Schuh79b30942021-01-24 22:32:21 -0800758//
759// This class also buffers data for the node it represents, and supports
760// notifying when new data is queued as well as queueing until a point in time.
Austin Schuhd2f96102020-12-01 20:27:29 -0800761class TimestampMapper {
762 public:
763 TimestampMapper(std::vector<LogParts> file);
764
765 // Copying and moving will mess up the internal raw pointers. Just don't do
766 // it.
767 TimestampMapper(TimestampMapper const &) = delete;
768 TimestampMapper(TimestampMapper &&) = delete;
769 void operator=(TimestampMapper const &) = delete;
770 void operator=(TimestampMapper &&) = delete;
771
772 // TODO(austin): It would be super helpful to provide a way to queue up to
773 // time X without matching timestamps, and to then be able to pull the
774 // timestamps out of this queue. This lets us bootstrap time estimation
775 // without exploding memory usage worst case.
776
Austin Schuh0ca51f32020-12-25 21:51:45 -0800777 const Configuration *configuration() const { return configuration_.get(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800778
779 // Returns which node this is sorting for.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700780 size_t node() const { return boot_merger_.node(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800781
782 // The start time of this log.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700783 monotonic_clock::time_point monotonic_start_time(size_t boot) const {
784 return boot_merger_.monotonic_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800785 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700786 realtime_clock::time_point realtime_start_time(size_t boot) const {
787 return boot_merger_.realtime_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800788 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800789 // Returns the oldest timestamp on a message on this boot.
790 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const {
791 return boot_merger_.monotonic_oldest_time(boot);
792 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800793
794 // Uses timestamp_mapper as the peer for its node. Only one mapper may be set
795 // for each node. Peers are used to look up the data for timestamps on this
796 // node.
797 void AddPeer(TimestampMapper *timestamp_mapper);
798
Austin Schuh24bf4972021-06-29 22:09:08 -0700799 // Returns true if anything has been queued up.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700800 bool started() const { return boot_merger_.started(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800801
802 // Returns the next message for this node.
803 TimestampedMessage *Front();
804 // Pops the next message. Front must be called first.
805 void PopFront();
806
807 // Returns debug information about this node.
808 std::string DebugString() const;
809
Austin Schuh79b30942021-01-24 22:32:21 -0800810 // Queues data the provided time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700811 void QueueUntil(BootTimestamp queue_time);
Austin Schuhe639ea12021-01-25 13:00:22 -0800812 // Queues until we have time_estimation_buffer of data in the queue.
813 void QueueFor(std::chrono::nanoseconds time_estimation_buffer);
Austin Schuh79b30942021-01-24 22:32:21 -0800814
Austin Schuh06601222021-01-26 17:02:50 -0800815 // Queues until the condition is met.
816 template <typename T>
817 void QueueUntilCondition(T fn) {
818 while (true) {
819 if (fn()) {
820 break;
821 }
822 if (!QueueMatched()) {
823 break;
824 }
825 }
826 }
827
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700828 // Sets the callback that can be used to skip messages.
829 void set_replay_channels_callback(
830 std::function<bool(const TimestampedMessage &)> fn) {
831 replay_channels_callback_ = fn;
832 }
833
Austin Schuh79b30942021-01-24 22:32:21 -0800834 // Sets a callback to be called whenever a full message is queued.
835 void set_timestamp_callback(std::function<void(TimestampedMessage *)> fn) {
836 timestamp_callback_ = fn;
837 }
838
Austin Schuhd2f96102020-12-01 20:27:29 -0800839 private:
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700840 // Result of MaybeQueueMatched
841 enum class MatchResult : uint8_t {
842 kEndOfFile, // End of the log file being read
843 kQueued, // Message was queued
844 kSkipped // Message was skipped over
845 };
846
Austin Schuhd2f96102020-12-01 20:27:29 -0800847 // The state for a remote node. This holds the data that needs to be matched
848 // with the remote node's timestamps.
849 struct NodeData {
850 // True if we should save data here. This should be true if any of the
851 // bools in delivered below are true.
852 bool any_delivered = false;
853
Austin Schuh36c00932021-07-19 18:13:21 -0700854 // True if we have a peer and therefore should be saving data for it.
855 bool save_for_peer = false;
856
Austin Schuhd2f96102020-12-01 20:27:29 -0800857 // Peer pointer. This node is only to be considered if a peer is set.
858 TimestampMapper *peer = nullptr;
859
860 struct ChannelData {
861 // Deque per channel. This contains the data from the outside
862 // TimestampMapper node which is relevant for the node this NodeData
863 // points to.
864 std::deque<Message> messages;
865 // Bool tracking per channel if a message is delivered to the node this
866 // NodeData represents.
867 bool delivered = false;
Austin Schuh6a7358f2021-11-18 22:40:40 -0800868 // The TTL for delivery.
869 std::chrono::nanoseconds time_to_live = std::chrono::nanoseconds(0);
Austin Schuhd2f96102020-12-01 20:27:29 -0800870 };
871
872 // Vector with per channel data.
873 std::vector<ChannelData> channels;
874 };
875
876 // Returns (and forgets about) the data for the provided timestamp message
877 // showing when it was delivered to this node.
878 Message MatchingMessageFor(const Message &message);
879
880 // Queues up a single message into our message queue, and any nodes that this
881 // message is delivered to. Returns true if one was available, false
882 // otherwise.
883 bool Queue();
884
Austin Schuh79b30942021-01-24 22:32:21 -0800885 // Queues up a single matched message into our matched message queue. Returns
886 // true if one was queued, and false otherwise.
887 bool QueueMatched();
888
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700889 // Queues a message if the replay_channels_callback is passed and the end of
890 // the log file has not been reached.
891 MatchResult MaybeQueueMatched();
892
Austin Schuhd2f96102020-12-01 20:27:29 -0800893 // Queues up data until we have at least one message >= to time t.
894 // Useful for triggering a remote node to read enough data to have the
895 // timestamp you care about available.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700896 void QueueUnmatchedUntil(BootTimestamp t);
Austin Schuhd2f96102020-12-01 20:27:29 -0800897
Austin Schuh79b30942021-01-24 22:32:21 -0800898 // Queues m into matched_messages_.
899 void QueueMessage(Message *m);
Austin Schuhd2f96102020-12-01 20:27:29 -0800900
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700901 // If a replay_channels_callback was set and the callback returns false, a
902 // matched message is popped and true is returned. Otherwise false is
903 // returned.
904 bool CheckReplayChannelsAndMaybePop(const TimestampedMessage &message);
905
Austin Schuh58646e22021-08-23 23:51:46 -0700906 // Returns the name of the node this class is sorting for.
907 std::string_view node_name() const {
908 return configuration_->has_nodes() ? configuration_->nodes()
909 ->Get(boot_merger_.node())
910 ->name()
911 ->string_view()
912 : "(single node)";
913 }
914
Austin Schuhd2f96102020-12-01 20:27:29 -0800915 // The node merger to source messages from.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700916 BootMerger boot_merger_;
Austin Schuh0ca51f32020-12-25 21:51:45 -0800917
918 std::shared_ptr<const Configuration> configuration_;
919
Austin Schuhd2f96102020-12-01 20:27:29 -0800920 // The buffer of messages for this node. These are not matched with any
921 // remote data.
922 std::deque<Message> messages_;
923 // The node index for the source node for each channel.
924 std::vector<size_t> source_node_;
925
926 // Vector per node. Not all nodes will have anything.
927 std::vector<NodeData> nodes_data_;
928
929 // Latest message to return.
Austin Schuh79b30942021-01-24 22:32:21 -0800930 std::deque<TimestampedMessage> matched_messages_;
Austin Schuhd2f96102020-12-01 20:27:29 -0800931
Austin Schuh79b30942021-01-24 22:32:21 -0800932 // Tracks the state of the first message in matched_messages_. Do we need to
933 // update it, is it valid, or should we return nullptr?
Austin Schuhd2f96102020-12-01 20:27:29 -0800934 enum class FirstMessage {
935 kNeedsUpdate,
936 kInMessage,
937 kNullptr,
938 };
939 FirstMessage first_message_ = FirstMessage::kNeedsUpdate;
940
941 // Timestamp of the last message returned. Used to make sure nothing goes
942 // backwards.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700943 BootTimestamp last_message_time_ = BootTimestamp::min_time();
Austin Schuh6a7358f2021-11-18 22:40:40 -0800944 BootTimestamp last_popped_message_time_ = BootTimestamp::min_time();
Austin Schuhd2f96102020-12-01 20:27:29 -0800945 // Time this node is queued up until. Used for caching.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700946 BootTimestamp queued_until_ = BootTimestamp::min_time();
Austin Schuh79b30942021-01-24 22:32:21 -0800947
948 std::function<void(TimestampedMessage *)> timestamp_callback_;
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700949 std::function<bool(TimestampedMessage &)> replay_channels_callback_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800950};
951
Austin Schuhee711052020-08-24 16:06:09 -0700952// Returns the node name with a trailing space, or an empty string if we are on
953// a single node.
954std::string MaybeNodeName(const Node *);
955
Austin Schuh71a40d42023-02-04 21:22:22 -0800956// Class to copy a RemoteMessage into the provided buffer.
957class RemoteMessageCopier : public DataEncoder::Copier {
958 public:
959 RemoteMessageCopier(const message_bridge::RemoteMessage *message,
960 int channel_index,
961 aos::monotonic_clock::time_point monotonic_timestamp_time,
962 EventLoop *event_loop)
963 : DataEncoder::Copier(PackRemoteMessageSize()),
964 message_(message),
965 channel_index_(channel_index),
966 monotonic_timestamp_time_(monotonic_timestamp_time),
967 event_loop_(event_loop) {}
968
969 monotonic_clock::time_point end_time() const { return end_time_; }
970
971 size_t Copy(uint8_t *data, size_t start_byte, size_t end_byte) final {
972 size_t result = PackRemoteMessageInline(data, message_, channel_index_,
973 monotonic_timestamp_time_,
974 start_byte, end_byte);
975 end_time_ = event_loop_->monotonic_now();
976 return result;
977 }
978
979 private:
980 const message_bridge::RemoteMessage *message_;
981 int channel_index_;
982 aos::monotonic_clock::time_point monotonic_timestamp_time_;
983 EventLoop *event_loop_;
984 monotonic_clock::time_point end_time_;
985};
986
987// Class to copy a context into the provided buffer.
988class ContextDataCopier : public DataEncoder::Copier {
989 public:
990 ContextDataCopier(const Context &context, int channel_index, LogType log_type,
991 EventLoop *event_loop)
992 : DataEncoder::Copier(PackMessageSize(log_type, context.size)),
993 context_(context),
994 channel_index_(channel_index),
995 log_type_(log_type),
996 event_loop_(event_loop) {}
997
998 monotonic_clock::time_point end_time() const { return end_time_; }
999
1000 size_t Copy(uint8_t *data, size_t start_byte, size_t end_byte) final {
1001 size_t result = PackMessageInline(data, context_, channel_index_, log_type_,
1002 start_byte, end_byte);
1003 end_time_ = event_loop_->monotonic_now();
1004 return result;
1005 }
1006
1007 private:
1008 const Context &context_;
1009 const int channel_index_;
1010 const LogType log_type_;
1011 EventLoop *event_loop_;
1012 monotonic_clock::time_point end_time_;
1013};
1014
Brian Silvermanf51499a2020-09-21 12:49:08 -07001015} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -08001016
1017#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_