blob: 16f367516dff2725924719797a4342fe7b82ddfc [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 Schuha36c8902019-12-30 18:07:15 -080047class DetachedBufferWriter {
48 public:
Brian Silvermana9f2ec92020-10-06 18:00:53 -070049 // Marker struct for one of our constructor overloads.
50 struct already_out_of_space_t {};
51
Brian Silvermanf51499a2020-09-21 12:49:08 -070052 DetachedBufferWriter(std::string_view filename,
53 std::unique_ptr<DetachedBufferEncoder> encoder);
Brian Silvermana9f2ec92020-10-06 18:00:53 -070054 // Creates a dummy instance which won't even open a file. It will act as if
55 // opening the file ran out of space immediately.
56 DetachedBufferWriter(already_out_of_space_t) : ran_out_of_space_(true) {}
Austin Schuh2f8fd752020-09-01 22:38:28 -070057 DetachedBufferWriter(DetachedBufferWriter &&other);
58 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
59
Austin Schuha36c8902019-12-30 18:07:15 -080060 ~DetachedBufferWriter();
61
Austin Schuh2f8fd752020-09-01 22:38:28 -070062 DetachedBufferWriter &operator=(DetachedBufferWriter &&other);
Brian Silverman98360e22020-04-28 16:51:20 -070063 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
64
Austin Schuh6f3babe2020-01-26 20:34:50 -080065 std::string_view filename() const { return filename_; }
66
Brian Silvermana9f2ec92020-10-06 18:00:53 -070067 // This will be true until Close() is called, unless the file couldn't be
68 // created due to running out of space.
69 bool is_open() const { return fd_ != -1; }
70
Brian Silvermanf51499a2020-09-21 12:49:08 -070071 // Queues up a finished FlatBufferBuilder to be encoded and written.
72 //
73 // Triggers a flush if there's enough data queued up.
74 //
75 // Steals the detached buffer from it.
Austin Schuhbd06ae42021-03-31 22:48:21 -070076 void QueueSizedFlatbuffer(flatbuffers::FlatBufferBuilder *fbb,
77 aos::monotonic_clock::time_point now) {
78 QueueSizedFlatbuffer(fbb->Release(), now);
Brian Silvermanf51499a2020-09-21 12:49:08 -070079 }
80 // May steal the backing storage of buffer, or may leave it alone.
Austin Schuhbd06ae42021-03-31 22:48:21 -070081 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer,
82 aos::monotonic_clock::time_point now) {
83 QueueSizedFlatbuffer(std::move(buffer));
84 FlushAtThreshold(now);
85 }
86 // Unconditionally queues the buffer.
Brian Silvermanf51499a2020-09-21 12:49:08 -070087 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070088 if (ran_out_of_space_) {
89 return;
90 }
Brian Silvermanf51499a2020-09-21 12:49:08 -070091 encoder_->Encode(std::move(buffer));
Brian Silvermanf51499a2020-09-21 12:49:08 -070092 }
Austin Schuha36c8902019-12-30 18:07:15 -080093
Brian Silvermanf51499a2020-09-21 12:49:08 -070094 // Queues up data in span. May copy or may write it to disk immediately.
95 void QueueSpan(absl::Span<const uint8_t> span);
Austin Schuha36c8902019-12-30 18:07:15 -080096
Brian Silverman0465fcf2020-09-24 00:29:18 -070097 // Indicates we got ENOSPC when trying to write. After this returns true, no
98 // further data is written.
99 bool ran_out_of_space() const { return ran_out_of_space_; }
100
101 // To avoid silently failing to write logfiles, you must call this before
102 // destruction if ran_out_of_space() is true and the situation has been
103 // handled.
104 void acknowledge_out_of_space() {
105 CHECK(ran_out_of_space_);
106 acknowledge_ran_out_of_space_ = true;
107 }
108
109 // Fully flushes and closes the underlying file now. No additional data may be
110 // enqueued after calling this.
111 //
112 // This will be performed in the destructor automatically.
113 //
114 // Note that this may set ran_out_of_space().
115 void Close();
116
Brian Silvermanf51499a2020-09-21 12:49:08 -0700117 // Returns the total number of bytes written and currently queued.
Austin Schuha426f1f2021-03-31 22:27:41 -0700118 size_t total_bytes() const {
119 if (!encoder_) {
120 return 0;
121 }
122 return encoder_->total_bytes();
123 }
Austin Schuha36c8902019-12-30 18:07:15 -0800124
Brian Silvermanf51499a2020-09-21 12:49:08 -0700125 // The maximum time for a single write call, or 0 if none have been performed.
126 std::chrono::nanoseconds max_write_time() const { return max_write_time_; }
127 // The number of bytes in the longest write call, or -1 if none have been
128 // performed.
129 int max_write_time_bytes() const { return max_write_time_bytes_; }
130 // The number of buffers in the longest write call, or -1 if none have been
131 // performed.
132 int max_write_time_messages() const { return max_write_time_messages_; }
133 // The total time spent in write calls.
134 std::chrono::nanoseconds total_write_time() const {
135 return total_write_time_;
136 }
137 // The total number of writes which have been performed.
138 int total_write_count() const { return total_write_count_; }
139 // The total number of messages which have been written.
140 int total_write_messages() const { return total_write_messages_; }
141 // The total number of bytes which have been written.
142 int total_write_bytes() const { return total_write_bytes_; }
143 void ResetStatistics() {
144 max_write_time_ = std::chrono::nanoseconds::zero();
145 max_write_time_bytes_ = -1;
146 max_write_time_messages_ = -1;
147 total_write_time_ = std::chrono::nanoseconds::zero();
148 total_write_count_ = 0;
149 total_write_messages_ = 0;
150 total_write_bytes_ = 0;
151 }
Brian Silverman98360e22020-04-28 16:51:20 -0700152
Austin Schuha36c8902019-12-30 18:07:15 -0800153 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700154 // Performs a single writev call with as much of the data we have queued up as
155 // possible.
156 //
157 // This will normally take all of the data we have queued up, unless an
158 // encoder has spit out a big enough chunk all at once that we can't manage
159 // all of it.
160 void Flush();
161
Brian Silverman0465fcf2020-09-24 00:29:18 -0700162 // write_return is what write(2) or writev(2) returned. write_size is the
163 // number of bytes we expected it to write.
164 void HandleWriteReturn(ssize_t write_return, size_t write_size);
165
Brian Silvermanf51499a2020-09-21 12:49:08 -0700166 void UpdateStatsForWrite(aos::monotonic_clock::duration duration,
167 ssize_t written, int iovec_size);
168
169 // Flushes data if we've reached the threshold to do that as part of normal
Austin Schuhbd06ae42021-03-31 22:48:21 -0700170 // operation either due to the outstanding queued data, or because we have
171 // passed our flush period. now is the current time to save some CPU grabbing
172 // the current time. It just needs to be close.
173 void FlushAtThreshold(aos::monotonic_clock::time_point now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700174
Austin Schuh2f8fd752020-09-01 22:38:28 -0700175 std::string filename_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700176 std::unique_ptr<DetachedBufferEncoder> encoder_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800177
Austin Schuha36c8902019-12-30 18:07:15 -0800178 int fd_ = -1;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700179 bool ran_out_of_space_ = false;
180 bool acknowledge_ran_out_of_space_ = false;
Austin Schuha36c8902019-12-30 18:07:15 -0800181
Austin Schuha36c8902019-12-30 18:07:15 -0800182 // List of iovecs to use with writev. This is a member variable to avoid
183 // churn.
184 std::vector<struct iovec> iovec_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700185
186 std::chrono::nanoseconds max_write_time_ = std::chrono::nanoseconds::zero();
187 int max_write_time_bytes_ = -1;
188 int max_write_time_messages_ = -1;
189 std::chrono::nanoseconds total_write_time_ = std::chrono::nanoseconds::zero();
190 int total_write_count_ = 0;
191 int total_write_messages_ = 0;
192 int total_write_bytes_ = 0;
Austin Schuhbd06ae42021-03-31 22:48:21 -0700193
194 aos::monotonic_clock::time_point last_flush_time_ =
195 aos::monotonic_clock::min_time;
Austin Schuha36c8902019-12-30 18:07:15 -0800196};
197
Austin Schuhf2d0e682022-10-16 14:20:58 -0700198// Repacks the provided RemoteMessage into fbb.
199flatbuffers::Offset<MessageHeader> PackRemoteMessage(
200 flatbuffers::FlatBufferBuilder *fbb,
201 const message_bridge::RemoteMessage *msg, int channel_index,
202 const aos::monotonic_clock::time_point monotonic_timestamp_time);
203
204constexpr flatbuffers::uoffset_t PackRemoteMessageSize() { return 96u; }
205size_t PackRemoteMessageInline(
206 uint8_t *data, const message_bridge::RemoteMessage *msg, int channel_index,
207 const aos::monotonic_clock::time_point monotonic_timestamp_time);
208
Austin Schuha36c8902019-12-30 18:07:15 -0800209// Packes a message pointed to by the context into a MessageHeader.
210flatbuffers::Offset<MessageHeader> PackMessage(
211 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
212 int channel_index, LogType log_type);
213
Austin Schuhfa30c352022-10-16 11:12:02 -0700214// Returns the size that the packed message from PackMessage or
215// PackMessageInline will be.
216flatbuffers::uoffset_t PackMessageSize(LogType log_type,
217 const Context &context);
218
219// Packs the provided message pointed to by context into the provided buffer.
220// This is equivalent to PackMessage, but doesn't require allocating a
221// FlatBufferBuilder underneath.
222size_t PackMessageInline(uint8_t *data, const Context &contex,
223 int channel_index, LogType log_type);
224
Austin Schuh05b70472020-01-01 17:11:17 -0800225// Class to read chunks out of a log file.
226class SpanReader {
227 public:
Austin Schuhcd368422021-11-22 21:23:29 -0800228 SpanReader(std::string_view filename, bool quiet = false);
Austin Schuha36c8902019-12-30 18:07:15 -0800229
Austin Schuh6f3babe2020-01-26 20:34:50 -0800230 std::string_view filename() const { return filename_; }
231
Brian Smarttea913d42021-12-10 15:02:38 -0800232 size_t TotalRead() const { return total_read_; }
233 size_t TotalConsumed() const { return total_consumed_; }
Austin Schuh60e77942022-05-16 17:48:24 -0700234 bool IsIncomplete() const {
235 return is_finished_ && total_consumed_ < total_read_;
236 }
Brian Smarttea913d42021-12-10 15:02:38 -0800237
Austin Schuhcf5f6442021-07-06 10:43:28 -0700238 // Returns a span with the data for the next message from the log file,
239 // including the size. The result is only guarenteed to be valid until
240 // ReadMessage() or PeekMessage() is called again.
Austin Schuh05b70472020-01-01 17:11:17 -0800241 absl::Span<const uint8_t> ReadMessage();
242
Austin Schuhcf5f6442021-07-06 10:43:28 -0700243 // Returns a span with the data for the next message without consuming it.
244 // Multiple calls to PeekMessage return the same data. ReadMessage or
245 // ConsumeMessage must be called to get the next message.
246 absl::Span<const uint8_t> PeekMessage();
247 // Consumes the message so the next call to ReadMessage or PeekMessage returns
248 // new data. This does not invalidate the data.
249 void ConsumeMessage();
250
Austin Schuh05b70472020-01-01 17:11:17 -0800251 private:
252 // TODO(austin): Optimization:
253 // Allocate the 256k blocks like we do today. But, refcount them with
254 // shared_ptr pointed to by the messageheader that is returned. This avoids
255 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700256 // And (Brian): Consider just mmapping the file and handing out refcounted
257 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800258
259 // Reads a chunk of data into data_. Returns false if no data was read.
260 bool ReadBlock();
261
Austin Schuhc41603c2020-10-11 16:17:37 -0700262 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800263
Brian Silvermanf51499a2020-09-21 12:49:08 -0700264 // File reader and data decoder.
265 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800266
Brian Silvermanf51499a2020-09-21 12:49:08 -0700267 // Vector to read into.
268 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800269
270 // Amount of data consumed already in data_.
271 size_t consumed_data_ = 0;
Brian Smarttea913d42021-12-10 15:02:38 -0800272
273 // Accumulates the total volume of bytes read from filename_
274 size_t total_read_ = 0;
275
276 // Accumulates the total volume of read bytes that were 'consumed' into
277 // messages. May be less than total_read_, if the last message (span) is
278 // either truncated or somehow corrupt.
279 size_t total_consumed_ = 0;
280
281 // Reached the end, no more readable messages.
282 bool is_finished_ = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800283};
284
Brian Silvermanfee16972021-09-14 12:06:38 -0700285// Reads the last header from a log file. This handles any duplicate headers
286// that were written.
287std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
288 SpanReader *span_reader);
289std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
290 std::string_view filename);
291// Reads the Nth message from a log file, excluding the header. Note: this
292// doesn't handle duplicate headers.
293std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
294 std::string_view filename, size_t n);
295
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700296class UnpackedMessageHeader;
297
Austin Schuh05b70472020-01-01 17:11:17 -0800298// Class which handles reading the header and messages from the log file. This
299// handles any per-file state left before merging below.
300class MessageReader {
301 public:
302 MessageReader(std::string_view filename);
303
Austin Schuh6f3babe2020-01-26 20:34:50 -0800304 std::string_view filename() const { return span_reader_.filename(); }
305
Austin Schuh05b70472020-01-01 17:11:17 -0800306 // Returns the header from the log file.
307 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700308 return &raw_log_file_header_.message();
309 }
310
311 // Returns the raw data of the header from the log file.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800312 const SizePrefixedFlatbufferVector<LogFileHeader> &raw_log_file_header()
313 const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700314 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800315 }
316
317 // Returns the minimum maount of data needed to queue up for sorting before
318 // ware guarenteed to not see data out of order.
319 std::chrono::nanoseconds max_out_of_order_duration() const {
320 return max_out_of_order_duration_;
321 }
322
Austin Schuhcde938c2020-02-02 17:30:07 -0800323 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800324 monotonic_clock::time_point newest_timestamp() const {
325 return newest_timestamp_;
326 }
327
328 // Returns the next message if there is one.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700329 std::shared_ptr<UnpackedMessageHeader> ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800330
331 // The time at which we need to read another chunk from the logfile.
332 monotonic_clock::time_point queue_data_time() const {
333 return newest_timestamp() - max_out_of_order_duration();
334 }
335
Brian Smarttea913d42021-12-10 15:02:38 -0800336 // Flag value setters for testing
337 void set_crash_on_corrupt_message_flag(bool b) {
338 crash_on_corrupt_message_flag_ = b;
339 }
340 void set_ignore_corrupt_messages_flag(bool b) {
341 ignore_corrupt_messages_flag_ = b;
342 }
343
Austin Schuh05b70472020-01-01 17:11:17 -0800344 private:
345 // Log chunk reader.
346 SpanReader span_reader_;
347
Austin Schuh97789fc2020-08-01 14:42:45 -0700348 // Vector holding the raw data for the log file header.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800349 SizePrefixedFlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800350
351 // Minimum amount of data to queue up for sorting before we are guarenteed
352 // to not see data out of order.
353 std::chrono::nanoseconds max_out_of_order_duration_;
354
355 // Timestamp of the newest message in a channel queue.
356 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Brian Smarttea913d42021-12-10 15:02:38 -0800357
358 // Total volume of verifiable messages from the beginning of the file.
359 // TODO - are message counts also useful?
360 size_t total_verified_before_ = 0;
361
362 // Total volume of messages with corrupted flatbuffer formatting, if any.
363 // Excludes corrupted message content.
364 // TODO - if the layout included something as simple as a CRC (relatively
365 // fast and robust enough) for each span, then corrupted content could be
366 // included in this check.
367 size_t total_corrupted_ = 0;
368
369 // Total volume of verifiable messages intermixed with corrupted messages,
370 // if any. Will be == 0 if total_corrupted_ == 0.
371 size_t total_verified_during_ = 0;
372
373 // Total volume of verifiable messages found after the last corrupted one,
374 // if any. Will be == 0 if total_corrupted_ == 0.
375 size_t total_verified_after_ = 0;
376
377 bool is_corrupted() const { return total_corrupted_ > 0; }
378
379 bool crash_on_corrupt_message_flag_ = true;
380 bool ignore_corrupt_messages_flag_ = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800381};
382
Austin Schuhc41603c2020-10-11 16:17:37 -0700383// A class to seamlessly read messages from a list of part files.
384class PartsMessageReader {
385 public:
386 PartsMessageReader(LogParts log_parts);
387
388 std::string_view filename() const { return message_reader_.filename(); }
389
Austin Schuhd2f96102020-12-01 20:27:29 -0800390 // Returns the LogParts that holds the filenames we are reading.
391 const LogParts &parts() const { return parts_; }
392
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800393 const LogFileHeader *log_file_header() const {
394 return message_reader_.log_file_header();
395 }
396
Austin Schuhc41603c2020-10-11 16:17:37 -0700397 // Returns the minimum amount of data needed to queue up for sorting before
398 // we are guarenteed to not see data out of order.
399 std::chrono::nanoseconds max_out_of_order_duration() const {
400 return message_reader_.max_out_of_order_duration();
401 }
402
403 // Returns the newest timestamp read out of the log file.
404 monotonic_clock::time_point newest_timestamp() const {
405 return newest_timestamp_;
406 }
407
408 // Returns the next message if there is one, or nullopt if we have reached the
409 // end of all the files.
410 // Note: reading the next message may change the max_out_of_order_duration().
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700411 std::shared_ptr<UnpackedMessageHeader> ReadMessage();
Austin Schuhc41603c2020-10-11 16:17:37 -0700412
Austin Schuh48507722021-07-17 17:29:24 -0700413 // Returns the boot count for the requested node, or std::nullopt if we don't
414 // know.
415 std::optional<size_t> boot_count(size_t node_index) const {
416 CHECK_GE(node_index, 0u);
417 CHECK_LT(node_index, boot_counts_.size());
418 return boot_counts_[node_index];
419 }
420
Austin Schuhc41603c2020-10-11 16:17:37 -0700421 private:
422 // Opens the next log and updates message_reader_. Sets done_ if there is
423 // nothing more to do.
424 void NextLog();
Austin Schuh48507722021-07-17 17:29:24 -0700425 void ComputeBootCounts();
Austin Schuhc41603c2020-10-11 16:17:37 -0700426
427 const LogParts parts_;
428 size_t next_part_index_ = 1u;
429 bool done_ = false;
430 MessageReader message_reader_;
Brian Silvermanfee16972021-09-14 12:06:38 -0700431 // We instantiate the next one early, to allow implementations to prefetch.
432 // TODO(Brian): To get optimal performance when downloading, this needs more
433 // communication with the implementation to prioritize the next part and add
434 // more parallelism when it helps. Maybe some kind of a queue of parts in
435 // order, and the implementation gets to pull however many make sense off the
436 // front?
437 std::optional<MessageReader> next_message_reader_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700438
Austin Schuh315b96b2020-12-11 21:21:12 -0800439 // True after we have seen a message after the start of the log. The
440 // guarentees on logging essentially are that all data from before the
441 // starting time of the log may be arbitrarily out of order, but once we get
442 // max_out_of_order_duration past the start, everything will remain within
443 // max_out_of_order_duration. We shouldn't see anything before the start
444 // after we've seen a message that is at least max_out_of_order_duration after
445 // the start.
446 bool after_start_ = false;
447
Austin Schuhc41603c2020-10-11 16:17:37 -0700448 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh48507722021-07-17 17:29:24 -0700449
450 // Per node boot counts.
451 std::vector<std::optional<size_t>> boot_counts_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700452};
453
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700454// Stores MessageHeader as a flat header and inline, aligned block of data.
455class UnpackedMessageHeader {
456 public:
457 UnpackedMessageHeader(const UnpackedMessageHeader &) = delete;
458 UnpackedMessageHeader &operator=(const UnpackedMessageHeader &) = delete;
459
460 // The channel.
461 uint32_t channel_index = 0xffffffff;
462
463 monotonic_clock::time_point monotonic_sent_time;
464 realtime_clock::time_point realtime_sent_time;
465
466 // The local queue index.
467 uint32_t queue_index = 0xffffffff;
468
Austin Schuh826e6ce2021-11-18 20:33:10 -0800469 std::optional<aos::monotonic_clock::time_point> monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700470
471 std::optional<realtime_clock::time_point> realtime_remote_time;
472 std::optional<uint32_t> remote_queue_index;
473
474 // This field is defaulted in the flatbuffer, so we need to store both the
475 // possibly defaulted value and whether it is defaulted.
476 monotonic_clock::time_point monotonic_timestamp_time;
477 bool has_monotonic_timestamp_time;
478
479 static std::shared_ptr<UnpackedMessageHeader> MakeMessage(
480 const MessageHeader &message);
481
482 // Note: we are storing a span here because we need something to put in the
483 // SharedSpan pointer that RawSender takes. We are using the aliasing
484 // constructor of shared_ptr to avoid the allocation, and it needs a nice
485 // pointer to track.
486 absl::Span<const uint8_t> span;
487
488 char actual_data[];
489
490 private:
491 ~UnpackedMessageHeader() {}
492
493 static void DestroyAndFree(UnpackedMessageHeader *p) {
494 p->~UnpackedMessageHeader();
495 free(p);
496 }
497};
498
499std::ostream &operator<<(std::ostream &os,
500 const UnpackedMessageHeader &message);
501
Austin Schuh1be0ce42020-11-29 22:43:26 -0800502// Struct to hold a message as it gets sorted on a single node.
503struct Message {
504 // The channel.
505 uint32_t channel_index = 0xffffffff;
506 // The local queue index.
Austin Schuh58646e22021-08-23 23:51:46 -0700507 // TODO(austin): Technically the boot inside queue_index is redundant with
508 // timestamp. In practice, it is less error-prone to duplicate it. Maybe a
509 // function to return the combined struct?
510 BootQueueIndex queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700511 // The local timestamp.
512 BootTimestamp timestamp;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700513
Austin Schuh48507722021-07-17 17:29:24 -0700514 // Remote boot when this is a timestamp.
515 size_t monotonic_remote_boot = 0xffffff;
516
517 size_t monotonic_timestamp_boot = 0xffffff;
518
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700519 std::shared_ptr<UnpackedMessageHeader> data;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800520
521 bool operator<(const Message &m2) const;
522 bool operator>=(const Message &m2) const;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800523 bool operator==(const Message &m2) const;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800524};
525
526std::ostream &operator<<(std::ostream &os, const Message &m);
527
Austin Schuhd2f96102020-12-01 20:27:29 -0800528// Structure to hold a full message and all the timestamps, which may or may not
529// have been sent from a remote node. The remote_queue_index will be invalid if
530// this message is from the point of view of the node which sent it.
531struct TimestampedMessage {
532 uint32_t channel_index = 0xffffffff;
533
Austin Schuh58646e22021-08-23 23:51:46 -0700534 BootQueueIndex queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700535 BootTimestamp monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800536 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
537
Austin Schuh58646e22021-08-23 23:51:46 -0700538 BootQueueIndex remote_queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700539 BootTimestamp monotonic_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800540 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
541
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700542 BootTimestamp monotonic_timestamp_time;
Austin Schuh8bf1e632021-01-02 22:41:04 -0800543
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700544 std::shared_ptr<UnpackedMessageHeader> data;
Austin Schuhd2f96102020-12-01 20:27:29 -0800545};
546
547std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m);
548
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800549// Class to sort the resulting messages from a PartsMessageReader.
550class LogPartsSorter {
551 public:
552 LogPartsSorter(LogParts log_parts);
553
Austin Schuh0ca51f32020-12-25 21:51:45 -0800554 // Returns the parts that this is sorting messages from.
555 const LogParts &parts() const { return parts_message_reader_.parts(); }
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800556
Austin Schuhd2f96102020-12-01 20:27:29 -0800557 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800558 return parts().monotonic_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800559 }
560 realtime_clock::time_point realtime_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800561 return parts().realtime_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800562 }
563
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800564 // The time this data is sorted until.
565 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
566
567 // Returns the next sorted message from the log file. It is safe to call
568 // std::move() on the result to move the data flatbuffer from it.
569 Message *Front();
570 // Pops the front message. This should only be called after a call to
571 // Front().
572 void PopFront();
573
574 // Returns a debug string representing the contents of this sorter.
575 std::string DebugString() const;
576
577 private:
578 // Log parts reader we are wrapping.
579 PartsMessageReader parts_message_reader_;
580 // Cache of the time we are sorted until.
581 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
582
Austin Schuhb000de62020-12-03 22:00:40 -0800583 // Timestamp of the last message returned. Used to make sure nothing goes
584 // backwards.
585 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
586
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800587 // Set used for efficient sorting of messages. We can benchmark and evaluate
588 // other data structures if this proves to be the bottleneck.
589 absl::btree_set<Message> messages_;
Austin Schuh48507722021-07-17 17:29:24 -0700590
591 // Mapping from channel to source node.
592 // TODO(austin): Should we put this in Boots so it can be cached for everyone?
593 std::vector<size_t> source_node_index_;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800594};
595
Austin Schuh8f52ed52020-11-30 23:12:39 -0800596// Class to run merge sort on the messages from multiple LogPartsSorter
597// instances.
598class NodeMerger {
599 public:
Austin Schuhd2f96102020-12-01 20:27:29 -0800600 NodeMerger(std::vector<LogParts> parts);
601
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700602 // Copying and moving will mess up the internal raw pointers. Just don't do
603 // it.
604 NodeMerger(NodeMerger const &) = delete;
605 NodeMerger(NodeMerger &&) = delete;
606 void operator=(NodeMerger const &) = delete;
607 void operator=(NodeMerger &&) = delete;
608
Austin Schuhd2f96102020-12-01 20:27:29 -0800609 // Node index in the configuration of this node.
610 int node() const { return node_; }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800611
Austin Schuh0ca51f32020-12-25 21:51:45 -0800612 // List of parts being sorted together.
613 std::vector<const LogParts *> Parts() const;
614
615 const Configuration *configuration() const {
616 return parts_sorters_[0].parts().config.get();
Austin Schuhd2f96102020-12-01 20:27:29 -0800617 }
618
619 monotonic_clock::time_point monotonic_start_time() const {
620 return monotonic_start_time_;
621 }
622 realtime_clock::time_point realtime_start_time() const {
623 return realtime_start_time_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800624 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800625 monotonic_clock::time_point monotonic_oldest_time() const {
626 return monotonic_oldest_time_;
627 }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800628
629 // The time this data is sorted until.
630 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
631
632 // Returns the next sorted message from the set of log files. It is safe to
633 // call std::move() on the result to move the data flatbuffer from it.
634 Message *Front();
635 // Pops the front message. This should only be called after a call to
636 // Front().
637 void PopFront();
638
639 private:
640 // Unsorted list of all parts sorters.
Austin Schuhd2f96102020-12-01 20:27:29 -0800641 std::vector<LogPartsSorter> parts_sorters_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800642 // Pointer to the parts sorter holding the current Front message if one
643 // exists, or nullptr if a new one needs to be found.
644 LogPartsSorter *current_ = nullptr;
645 // Cached sorted_until value.
646 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800647
648 // Cached node.
649 int node_;
650
Austin Schuhb000de62020-12-03 22:00:40 -0800651 // Timestamp of the last message returned. Used to make sure nothing goes
652 // backwards.
653 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
654
Austin Schuhd2f96102020-12-01 20:27:29 -0800655 realtime_clock::time_point realtime_start_time_ = realtime_clock::max_time;
656 monotonic_clock::time_point monotonic_start_time_ = monotonic_clock::max_time;
Austin Schuh60e77942022-05-16 17:48:24 -0700657 monotonic_clock::time_point monotonic_oldest_time_ =
658 monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800659};
660
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700661// Class to concatenate multiple boots worth of logs into a single per-node
662// stream.
663class BootMerger {
664 public:
665 BootMerger(std::vector<LogParts> file);
666
667 // Copying and moving will mess up the internal raw pointers. Just don't do
668 // it.
669 BootMerger(BootMerger const &) = delete;
670 BootMerger(BootMerger &&) = delete;
671 void operator=(BootMerger const &) = delete;
672 void operator=(BootMerger &&) = delete;
673
674 // Node index in the configuration of this node.
675 int node() const { return node_mergers_[0]->node(); }
676
677 // List of parts being sorted together.
678 std::vector<const LogParts *> Parts() const;
679
680 const Configuration *configuration() const {
681 return node_mergers_[0]->configuration();
682 }
683
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700684 monotonic_clock::time_point monotonic_start_time(size_t boot) const {
685 CHECK_LT(boot, node_mergers_.size());
686 return node_mergers_[boot]->monotonic_start_time();
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700687 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700688 realtime_clock::time_point realtime_start_time(size_t boot) const {
689 CHECK_LT(boot, node_mergers_.size());
690 return node_mergers_[boot]->realtime_start_time();
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700691 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800692 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const {
693 CHECK_LT(boot, node_mergers_.size());
694 return node_mergers_[boot]->monotonic_oldest_time();
695 }
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700696
697 bool started() const {
698 return node_mergers_[index_]->sorted_until() != monotonic_clock::min_time ||
699 index_ != 0;
700 }
701
702 // Returns the next sorted message from the set of log files. It is safe to
703 // call std::move() on the result to move the data flatbuffer from it.
704 Message *Front();
705 // Pops the front message. This should only be called after a call to
706 // Front().
707 void PopFront();
708
709 private:
710 int index_ = 0;
711
712 // TODO(austin): Sanjay points out this is pretty inefficient. Don't keep so
713 // many things open.
714 std::vector<std::unique_ptr<NodeMerger>> node_mergers_;
715};
716
Austin Schuhd2f96102020-12-01 20:27:29 -0800717// Class to match timestamps with the corresponding data from other nodes.
Austin Schuh79b30942021-01-24 22:32:21 -0800718//
719// This class also buffers data for the node it represents, and supports
720// notifying when new data is queued as well as queueing until a point in time.
Austin Schuhd2f96102020-12-01 20:27:29 -0800721class TimestampMapper {
722 public:
723 TimestampMapper(std::vector<LogParts> file);
724
725 // Copying and moving will mess up the internal raw pointers. Just don't do
726 // it.
727 TimestampMapper(TimestampMapper const &) = delete;
728 TimestampMapper(TimestampMapper &&) = delete;
729 void operator=(TimestampMapper const &) = delete;
730 void operator=(TimestampMapper &&) = delete;
731
732 // TODO(austin): It would be super helpful to provide a way to queue up to
733 // time X without matching timestamps, and to then be able to pull the
734 // timestamps out of this queue. This lets us bootstrap time estimation
735 // without exploding memory usage worst case.
736
Austin Schuh0ca51f32020-12-25 21:51:45 -0800737 const Configuration *configuration() const { return configuration_.get(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800738
739 // Returns which node this is sorting for.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700740 size_t node() const { return boot_merger_.node(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800741
742 // The start time of this log.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700743 monotonic_clock::time_point monotonic_start_time(size_t boot) const {
744 return boot_merger_.monotonic_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800745 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700746 realtime_clock::time_point realtime_start_time(size_t boot) const {
747 return boot_merger_.realtime_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800748 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800749 // Returns the oldest timestamp on a message on this boot.
750 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const {
751 return boot_merger_.monotonic_oldest_time(boot);
752 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800753
754 // Uses timestamp_mapper as the peer for its node. Only one mapper may be set
755 // for each node. Peers are used to look up the data for timestamps on this
756 // node.
757 void AddPeer(TimestampMapper *timestamp_mapper);
758
Austin Schuh24bf4972021-06-29 22:09:08 -0700759 // Returns true if anything has been queued up.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700760 bool started() const { return boot_merger_.started(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800761
762 // Returns the next message for this node.
763 TimestampedMessage *Front();
764 // Pops the next message. Front must be called first.
765 void PopFront();
766
767 // Returns debug information about this node.
768 std::string DebugString() const;
769
Austin Schuh79b30942021-01-24 22:32:21 -0800770 // Queues data the provided time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700771 void QueueUntil(BootTimestamp queue_time);
Austin Schuhe639ea12021-01-25 13:00:22 -0800772 // Queues until we have time_estimation_buffer of data in the queue.
773 void QueueFor(std::chrono::nanoseconds time_estimation_buffer);
Austin Schuh79b30942021-01-24 22:32:21 -0800774
Austin Schuh06601222021-01-26 17:02:50 -0800775 // Queues until the condition is met.
776 template <typename T>
777 void QueueUntilCondition(T fn) {
778 while (true) {
779 if (fn()) {
780 break;
781 }
782 if (!QueueMatched()) {
783 break;
784 }
785 }
786 }
787
Austin Schuh79b30942021-01-24 22:32:21 -0800788 // Sets a callback to be called whenever a full message is queued.
789 void set_timestamp_callback(std::function<void(TimestampedMessage *)> fn) {
790 timestamp_callback_ = fn;
791 }
792
Austin Schuhd2f96102020-12-01 20:27:29 -0800793 private:
794 // The state for a remote node. This holds the data that needs to be matched
795 // with the remote node's timestamps.
796 struct NodeData {
797 // True if we should save data here. This should be true if any of the
798 // bools in delivered below are true.
799 bool any_delivered = false;
800
Austin Schuh36c00932021-07-19 18:13:21 -0700801 // True if we have a peer and therefore should be saving data for it.
802 bool save_for_peer = false;
803
Austin Schuhd2f96102020-12-01 20:27:29 -0800804 // Peer pointer. This node is only to be considered if a peer is set.
805 TimestampMapper *peer = nullptr;
806
807 struct ChannelData {
808 // Deque per channel. This contains the data from the outside
809 // TimestampMapper node which is relevant for the node this NodeData
810 // points to.
811 std::deque<Message> messages;
812 // Bool tracking per channel if a message is delivered to the node this
813 // NodeData represents.
814 bool delivered = false;
Austin Schuh6a7358f2021-11-18 22:40:40 -0800815 // The TTL for delivery.
816 std::chrono::nanoseconds time_to_live = std::chrono::nanoseconds(0);
Austin Schuhd2f96102020-12-01 20:27:29 -0800817 };
818
819 // Vector with per channel data.
820 std::vector<ChannelData> channels;
821 };
822
823 // Returns (and forgets about) the data for the provided timestamp message
824 // showing when it was delivered to this node.
825 Message MatchingMessageFor(const Message &message);
826
827 // Queues up a single message into our message queue, and any nodes that this
828 // message is delivered to. Returns true if one was available, false
829 // otherwise.
830 bool Queue();
831
Austin Schuh79b30942021-01-24 22:32:21 -0800832 // Queues up a single matched message into our matched message queue. Returns
833 // true if one was queued, and false otherwise.
834 bool QueueMatched();
835
Austin Schuhd2f96102020-12-01 20:27:29 -0800836 // Queues up data until we have at least one message >= to time t.
837 // Useful for triggering a remote node to read enough data to have the
838 // timestamp you care about available.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700839 void QueueUnmatchedUntil(BootTimestamp t);
Austin Schuhd2f96102020-12-01 20:27:29 -0800840
Austin Schuh79b30942021-01-24 22:32:21 -0800841 // Queues m into matched_messages_.
842 void QueueMessage(Message *m);
Austin Schuhd2f96102020-12-01 20:27:29 -0800843
Austin Schuh58646e22021-08-23 23:51:46 -0700844 // Returns the name of the node this class is sorting for.
845 std::string_view node_name() const {
846 return configuration_->has_nodes() ? configuration_->nodes()
847 ->Get(boot_merger_.node())
848 ->name()
849 ->string_view()
850 : "(single node)";
851 }
852
Austin Schuhd2f96102020-12-01 20:27:29 -0800853 // The node merger to source messages from.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700854 BootMerger boot_merger_;
Austin Schuh0ca51f32020-12-25 21:51:45 -0800855
856 std::shared_ptr<const Configuration> configuration_;
857
Austin Schuhd2f96102020-12-01 20:27:29 -0800858 // The buffer of messages for this node. These are not matched with any
859 // remote data.
860 std::deque<Message> messages_;
861 // The node index for the source node for each channel.
862 std::vector<size_t> source_node_;
863
864 // Vector per node. Not all nodes will have anything.
865 std::vector<NodeData> nodes_data_;
866
867 // Latest message to return.
Austin Schuh79b30942021-01-24 22:32:21 -0800868 std::deque<TimestampedMessage> matched_messages_;
Austin Schuhd2f96102020-12-01 20:27:29 -0800869
Austin Schuh79b30942021-01-24 22:32:21 -0800870 // Tracks the state of the first message in matched_messages_. Do we need to
871 // update it, is it valid, or should we return nullptr?
Austin Schuhd2f96102020-12-01 20:27:29 -0800872 enum class FirstMessage {
873 kNeedsUpdate,
874 kInMessage,
875 kNullptr,
876 };
877 FirstMessage first_message_ = FirstMessage::kNeedsUpdate;
878
879 // Timestamp of the last message returned. Used to make sure nothing goes
880 // backwards.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700881 BootTimestamp last_message_time_ = BootTimestamp::min_time();
Austin Schuh6a7358f2021-11-18 22:40:40 -0800882 BootTimestamp last_popped_message_time_ = BootTimestamp::min_time();
Austin Schuhd2f96102020-12-01 20:27:29 -0800883 // Time this node is queued up until. Used for caching.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700884 BootTimestamp queued_until_ = BootTimestamp::min_time();
Austin Schuh79b30942021-01-24 22:32:21 -0800885
886 std::function<void(TimestampedMessage *)> timestamp_callback_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800887};
888
Austin Schuhee711052020-08-24 16:06:09 -0700889// Returns the node name with a trailing space, or an empty string if we are on
890// a single node.
891std::string MaybeNodeName(const Node *);
892
Brian Silvermanf51499a2020-09-21 12:49:08 -0700893} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -0800894
895#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_