blob: e034bfec74d60e064516d9f57af10195a1baf49b [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,
Austin Schuh48d10d62022-10-16 22:19:23 -070053 std::unique_ptr<DataEncoder> encoder);
Brian Silvermana9f2ec92020-10-06 18:00:53 -070054 // Creates a dummy instance which won't even open a file. It will act as if
55 // opening the file ran out of space immediately.
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 Schuh48d10d62022-10-16 22:19:23 -070076 void CopyMessage(DataEncoder::Copier *coppier,
77 aos::monotonic_clock::time_point now);
Austin Schuha36c8902019-12-30 18:07:15 -080078
Brian Silvermanf51499a2020-09-21 12:49:08 -070079 // Queues up data in span. May copy or may write it to disk immediately.
80 void QueueSpan(absl::Span<const uint8_t> span);
Austin Schuha36c8902019-12-30 18:07:15 -080081
Brian Silverman0465fcf2020-09-24 00:29:18 -070082 // Indicates we got ENOSPC when trying to write. After this returns true, no
83 // further data is written.
84 bool ran_out_of_space() const { return ran_out_of_space_; }
85
86 // To avoid silently failing to write logfiles, you must call this before
87 // destruction if ran_out_of_space() is true and the situation has been
88 // handled.
89 void acknowledge_out_of_space() {
90 CHECK(ran_out_of_space_);
91 acknowledge_ran_out_of_space_ = true;
92 }
93
94 // Fully flushes and closes the underlying file now. No additional data may be
95 // enqueued after calling this.
96 //
97 // This will be performed in the destructor automatically.
98 //
99 // Note that this may set ran_out_of_space().
100 void Close();
101
Brian Silvermanf51499a2020-09-21 12:49:08 -0700102 // Returns the total number of bytes written and currently queued.
Austin Schuha426f1f2021-03-31 22:27:41 -0700103 size_t total_bytes() const {
104 if (!encoder_) {
105 return 0;
106 }
107 return encoder_->total_bytes();
108 }
Austin Schuha36c8902019-12-30 18:07:15 -0800109
Brian Silvermanf51499a2020-09-21 12:49:08 -0700110 // The maximum time for a single write call, or 0 if none have been performed.
111 std::chrono::nanoseconds max_write_time() const { return max_write_time_; }
112 // The number of bytes in the longest write call, or -1 if none have been
113 // performed.
114 int max_write_time_bytes() const { return max_write_time_bytes_; }
115 // The number of buffers in the longest write call, or -1 if none have been
116 // performed.
117 int max_write_time_messages() const { return max_write_time_messages_; }
118 // The total time spent in write calls.
119 std::chrono::nanoseconds total_write_time() const {
120 return total_write_time_;
121 }
122 // The total number of writes which have been performed.
123 int total_write_count() const { return total_write_count_; }
124 // The total number of messages which have been written.
125 int total_write_messages() const { return total_write_messages_; }
126 // The total number of bytes which have been written.
127 int total_write_bytes() const { return total_write_bytes_; }
128 void ResetStatistics() {
129 max_write_time_ = std::chrono::nanoseconds::zero();
130 max_write_time_bytes_ = -1;
131 max_write_time_messages_ = -1;
132 total_write_time_ = std::chrono::nanoseconds::zero();
133 total_write_count_ = 0;
134 total_write_messages_ = 0;
135 total_write_bytes_ = 0;
136 }
Brian Silverman98360e22020-04-28 16:51:20 -0700137
Austin Schuha36c8902019-12-30 18:07:15 -0800138 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700139 // Performs a single writev call with as much of the data we have queued up as
140 // possible.
141 //
142 // This will normally take all of the data we have queued up, unless an
143 // encoder has spit out a big enough chunk all at once that we can't manage
144 // all of it.
145 void Flush();
146
Brian Silverman0465fcf2020-09-24 00:29:18 -0700147 // write_return is what write(2) or writev(2) returned. write_size is the
148 // number of bytes we expected it to write.
149 void HandleWriteReturn(ssize_t write_return, size_t write_size);
150
Brian Silvermanf51499a2020-09-21 12:49:08 -0700151 void UpdateStatsForWrite(aos::monotonic_clock::duration duration,
152 ssize_t written, int iovec_size);
153
154 // Flushes data if we've reached the threshold to do that as part of normal
Austin Schuhbd06ae42021-03-31 22:48:21 -0700155 // operation either due to the outstanding queued data, or because we have
156 // passed our flush period. now is the current time to save some CPU grabbing
157 // the current time. It just needs to be close.
158 void FlushAtThreshold(aos::monotonic_clock::time_point now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700159
Austin Schuh2f8fd752020-09-01 22:38:28 -0700160 std::string filename_;
Austin Schuh48d10d62022-10-16 22:19:23 -0700161 std::unique_ptr<DataEncoder> encoder_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800162
Austin Schuha36c8902019-12-30 18:07:15 -0800163 int fd_ = -1;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700164 bool ran_out_of_space_ = false;
165 bool acknowledge_ran_out_of_space_ = false;
Austin Schuha36c8902019-12-30 18:07:15 -0800166
Austin Schuha36c8902019-12-30 18:07:15 -0800167 // List of iovecs to use with writev. This is a member variable to avoid
168 // churn.
169 std::vector<struct iovec> iovec_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700170
171 std::chrono::nanoseconds max_write_time_ = std::chrono::nanoseconds::zero();
172 int max_write_time_bytes_ = -1;
173 int max_write_time_messages_ = -1;
174 std::chrono::nanoseconds total_write_time_ = std::chrono::nanoseconds::zero();
175 int total_write_count_ = 0;
176 int total_write_messages_ = 0;
177 int total_write_bytes_ = 0;
Austin Schuhbd06ae42021-03-31 22:48:21 -0700178
179 aos::monotonic_clock::time_point last_flush_time_ =
180 aos::monotonic_clock::min_time;
Austin Schuha36c8902019-12-30 18:07:15 -0800181};
182
Austin Schuhf2d0e682022-10-16 14:20:58 -0700183// Repacks the provided RemoteMessage into fbb.
184flatbuffers::Offset<MessageHeader> PackRemoteMessage(
185 flatbuffers::FlatBufferBuilder *fbb,
186 const message_bridge::RemoteMessage *msg, int channel_index,
187 const aos::monotonic_clock::time_point monotonic_timestamp_time);
188
189constexpr flatbuffers::uoffset_t PackRemoteMessageSize() { return 96u; }
190size_t PackRemoteMessageInline(
191 uint8_t *data, const message_bridge::RemoteMessage *msg, int channel_index,
192 const aos::monotonic_clock::time_point monotonic_timestamp_time);
193
Austin Schuha36c8902019-12-30 18:07:15 -0800194// Packes a message pointed to by the context into a MessageHeader.
195flatbuffers::Offset<MessageHeader> PackMessage(
196 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
197 int channel_index, LogType log_type);
198
Austin Schuhfa30c352022-10-16 11:12:02 -0700199// Returns the size that the packed message from PackMessage or
200// PackMessageInline will be.
Austin Schuh48d10d62022-10-16 22:19:23 -0700201flatbuffers::uoffset_t PackMessageSize(LogType log_type, size_t data_size);
Austin Schuhfa30c352022-10-16 11:12:02 -0700202
203// Packs the provided message pointed to by context into the provided buffer.
204// This is equivalent to PackMessage, but doesn't require allocating a
205// FlatBufferBuilder underneath.
206size_t PackMessageInline(uint8_t *data, const Context &contex,
207 int channel_index, LogType log_type);
208
Austin Schuh05b70472020-01-01 17:11:17 -0800209// Class to read chunks out of a log file.
210class SpanReader {
211 public:
Austin Schuhcd368422021-11-22 21:23:29 -0800212 SpanReader(std::string_view filename, bool quiet = false);
Austin Schuha36c8902019-12-30 18:07:15 -0800213
Austin Schuh6f3babe2020-01-26 20:34:50 -0800214 std::string_view filename() const { return filename_; }
215
Brian Smarttea913d42021-12-10 15:02:38 -0800216 size_t TotalRead() const { return total_read_; }
217 size_t TotalConsumed() const { return total_consumed_; }
Austin Schuh60e77942022-05-16 17:48:24 -0700218 bool IsIncomplete() const {
219 return is_finished_ && total_consumed_ < total_read_;
220 }
Brian Smarttea913d42021-12-10 15:02:38 -0800221
Austin Schuhcf5f6442021-07-06 10:43:28 -0700222 // Returns a span with the data for the next message from the log file,
223 // including the size. The result is only guarenteed to be valid until
224 // ReadMessage() or PeekMessage() is called again.
Austin Schuh05b70472020-01-01 17:11:17 -0800225 absl::Span<const uint8_t> ReadMessage();
226
Austin Schuhcf5f6442021-07-06 10:43:28 -0700227 // Returns a span with the data for the next message without consuming it.
228 // Multiple calls to PeekMessage return the same data. ReadMessage or
229 // ConsumeMessage must be called to get the next message.
230 absl::Span<const uint8_t> PeekMessage();
231 // Consumes the message so the next call to ReadMessage or PeekMessage returns
232 // new data. This does not invalidate the data.
233 void ConsumeMessage();
234
Austin Schuh05b70472020-01-01 17:11:17 -0800235 private:
236 // TODO(austin): Optimization:
237 // Allocate the 256k blocks like we do today. But, refcount them with
238 // shared_ptr pointed to by the messageheader that is returned. This avoids
239 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700240 // And (Brian): Consider just mmapping the file and handing out refcounted
241 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800242
243 // Reads a chunk of data into data_. Returns false if no data was read.
244 bool ReadBlock();
245
Austin Schuhc41603c2020-10-11 16:17:37 -0700246 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800247
Brian Silvermanf51499a2020-09-21 12:49:08 -0700248 // File reader and data decoder.
249 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800250
Brian Silvermanf51499a2020-09-21 12:49:08 -0700251 // Vector to read into.
252 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800253
254 // Amount of data consumed already in data_.
255 size_t consumed_data_ = 0;
Brian Smarttea913d42021-12-10 15:02:38 -0800256
257 // Accumulates the total volume of bytes read from filename_
258 size_t total_read_ = 0;
259
260 // Accumulates the total volume of read bytes that were 'consumed' into
261 // messages. May be less than total_read_, if the last message (span) is
262 // either truncated or somehow corrupt.
263 size_t total_consumed_ = 0;
264
265 // Reached the end, no more readable messages.
266 bool is_finished_ = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800267};
268
Brian Silvermanfee16972021-09-14 12:06:38 -0700269// Reads the last header from a log file. This handles any duplicate headers
270// that were written.
271std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
272 SpanReader *span_reader);
273std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
274 std::string_view filename);
275// Reads the Nth message from a log file, excluding the header. Note: this
276// doesn't handle duplicate headers.
277std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
278 std::string_view filename, size_t n);
279
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700280class UnpackedMessageHeader;
281
Austin Schuh05b70472020-01-01 17:11:17 -0800282// Class which handles reading the header and messages from the log file. This
283// handles any per-file state left before merging below.
284class MessageReader {
285 public:
286 MessageReader(std::string_view filename);
287
Austin Schuh6f3babe2020-01-26 20:34:50 -0800288 std::string_view filename() const { return span_reader_.filename(); }
289
Austin Schuh05b70472020-01-01 17:11:17 -0800290 // Returns the header from the log file.
291 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700292 return &raw_log_file_header_.message();
293 }
294
295 // Returns the raw data of the header from the log file.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800296 const SizePrefixedFlatbufferVector<LogFileHeader> &raw_log_file_header()
297 const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700298 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800299 }
300
301 // Returns the minimum maount of data needed to queue up for sorting before
302 // ware guarenteed to not see data out of order.
303 std::chrono::nanoseconds max_out_of_order_duration() const {
304 return max_out_of_order_duration_;
305 }
306
Austin Schuhcde938c2020-02-02 17:30:07 -0800307 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800308 monotonic_clock::time_point newest_timestamp() const {
309 return newest_timestamp_;
310 }
311
312 // Returns the next message if there is one.
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700313 std::shared_ptr<UnpackedMessageHeader> ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800314
315 // The time at which we need to read another chunk from the logfile.
316 monotonic_clock::time_point queue_data_time() const {
317 return newest_timestamp() - max_out_of_order_duration();
318 }
319
Brian Smarttea913d42021-12-10 15:02:38 -0800320 // Flag value setters for testing
321 void set_crash_on_corrupt_message_flag(bool b) {
322 crash_on_corrupt_message_flag_ = b;
323 }
324 void set_ignore_corrupt_messages_flag(bool b) {
325 ignore_corrupt_messages_flag_ = b;
326 }
327
Austin Schuh05b70472020-01-01 17:11:17 -0800328 private:
329 // Log chunk reader.
330 SpanReader span_reader_;
331
Austin Schuh97789fc2020-08-01 14:42:45 -0700332 // Vector holding the raw data for the log file header.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800333 SizePrefixedFlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800334
335 // Minimum amount of data to queue up for sorting before we are guarenteed
336 // to not see data out of order.
337 std::chrono::nanoseconds max_out_of_order_duration_;
338
339 // Timestamp of the newest message in a channel queue.
340 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Brian Smarttea913d42021-12-10 15:02:38 -0800341
342 // Total volume of verifiable messages from the beginning of the file.
343 // TODO - are message counts also useful?
344 size_t total_verified_before_ = 0;
345
346 // Total volume of messages with corrupted flatbuffer formatting, if any.
347 // Excludes corrupted message content.
348 // TODO - if the layout included something as simple as a CRC (relatively
349 // fast and robust enough) for each span, then corrupted content could be
350 // included in this check.
351 size_t total_corrupted_ = 0;
352
353 // Total volume of verifiable messages intermixed with corrupted messages,
354 // if any. Will be == 0 if total_corrupted_ == 0.
355 size_t total_verified_during_ = 0;
356
357 // Total volume of verifiable messages found after the last corrupted one,
358 // if any. Will be == 0 if total_corrupted_ == 0.
359 size_t total_verified_after_ = 0;
360
361 bool is_corrupted() const { return total_corrupted_ > 0; }
362
363 bool crash_on_corrupt_message_flag_ = true;
364 bool ignore_corrupt_messages_flag_ = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800365};
366
Austin Schuhc41603c2020-10-11 16:17:37 -0700367// A class to seamlessly read messages from a list of part files.
368class PartsMessageReader {
369 public:
370 PartsMessageReader(LogParts log_parts);
371
372 std::string_view filename() const { return message_reader_.filename(); }
373
Austin Schuhd2f96102020-12-01 20:27:29 -0800374 // Returns the LogParts that holds the filenames we are reading.
375 const LogParts &parts() const { return parts_; }
376
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800377 const LogFileHeader *log_file_header() const {
378 return message_reader_.log_file_header();
379 }
380
Austin Schuhc41603c2020-10-11 16:17:37 -0700381 // Returns the minimum amount of data needed to queue up for sorting before
382 // we are guarenteed to not see data out of order.
383 std::chrono::nanoseconds max_out_of_order_duration() const {
384 return message_reader_.max_out_of_order_duration();
385 }
386
387 // Returns the newest timestamp read out of the log file.
388 monotonic_clock::time_point newest_timestamp() const {
389 return newest_timestamp_;
390 }
391
392 // Returns the next message if there is one, or nullopt if we have reached the
393 // end of all the files.
394 // Note: reading the next message may change the max_out_of_order_duration().
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700395 std::shared_ptr<UnpackedMessageHeader> ReadMessage();
Austin Schuhc41603c2020-10-11 16:17:37 -0700396
Austin Schuh48507722021-07-17 17:29:24 -0700397 // Returns the boot count for the requested node, or std::nullopt if we don't
398 // know.
399 std::optional<size_t> boot_count(size_t node_index) const {
400 CHECK_GE(node_index, 0u);
401 CHECK_LT(node_index, boot_counts_.size());
402 return boot_counts_[node_index];
403 }
404
Austin Schuhc41603c2020-10-11 16:17:37 -0700405 private:
406 // Opens the next log and updates message_reader_. Sets done_ if there is
407 // nothing more to do.
408 void NextLog();
Austin Schuh48507722021-07-17 17:29:24 -0700409 void ComputeBootCounts();
Austin Schuhc41603c2020-10-11 16:17:37 -0700410
411 const LogParts parts_;
412 size_t next_part_index_ = 1u;
413 bool done_ = false;
414 MessageReader message_reader_;
Brian Silvermanfee16972021-09-14 12:06:38 -0700415 // We instantiate the next one early, to allow implementations to prefetch.
416 // TODO(Brian): To get optimal performance when downloading, this needs more
417 // communication with the implementation to prioritize the next part and add
418 // more parallelism when it helps. Maybe some kind of a queue of parts in
419 // order, and the implementation gets to pull however many make sense off the
420 // front?
421 std::optional<MessageReader> next_message_reader_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700422
Austin Schuh315b96b2020-12-11 21:21:12 -0800423 // True after we have seen a message after the start of the log. The
424 // guarentees on logging essentially are that all data from before the
425 // starting time of the log may be arbitrarily out of order, but once we get
426 // max_out_of_order_duration past the start, everything will remain within
427 // max_out_of_order_duration. We shouldn't see anything before the start
428 // after we've seen a message that is at least max_out_of_order_duration after
429 // the start.
430 bool after_start_ = false;
431
Austin Schuhc41603c2020-10-11 16:17:37 -0700432 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh48507722021-07-17 17:29:24 -0700433
434 // Per node boot counts.
435 std::vector<std::optional<size_t>> boot_counts_;
Austin Schuhc41603c2020-10-11 16:17:37 -0700436};
437
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700438// Stores MessageHeader as a flat header and inline, aligned block of data.
439class UnpackedMessageHeader {
440 public:
441 UnpackedMessageHeader(const UnpackedMessageHeader &) = delete;
442 UnpackedMessageHeader &operator=(const UnpackedMessageHeader &) = delete;
443
444 // The channel.
445 uint32_t channel_index = 0xffffffff;
446
447 monotonic_clock::time_point monotonic_sent_time;
448 realtime_clock::time_point realtime_sent_time;
449
450 // The local queue index.
451 uint32_t queue_index = 0xffffffff;
452
Austin Schuh826e6ce2021-11-18 20:33:10 -0800453 std::optional<aos::monotonic_clock::time_point> monotonic_remote_time;
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700454
455 std::optional<realtime_clock::time_point> realtime_remote_time;
456 std::optional<uint32_t> remote_queue_index;
457
458 // This field is defaulted in the flatbuffer, so we need to store both the
459 // possibly defaulted value and whether it is defaulted.
460 monotonic_clock::time_point monotonic_timestamp_time;
461 bool has_monotonic_timestamp_time;
462
463 static std::shared_ptr<UnpackedMessageHeader> MakeMessage(
464 const MessageHeader &message);
465
466 // Note: we are storing a span here because we need something to put in the
467 // SharedSpan pointer that RawSender takes. We are using the aliasing
468 // constructor of shared_ptr to avoid the allocation, and it needs a nice
469 // pointer to track.
470 absl::Span<const uint8_t> span;
471
472 char actual_data[];
473
474 private:
475 ~UnpackedMessageHeader() {}
476
477 static void DestroyAndFree(UnpackedMessageHeader *p) {
478 p->~UnpackedMessageHeader();
479 free(p);
480 }
481};
482
483std::ostream &operator<<(std::ostream &os,
484 const UnpackedMessageHeader &message);
485
Austin Schuh1be0ce42020-11-29 22:43:26 -0800486// Struct to hold a message as it gets sorted on a single node.
487struct Message {
488 // The channel.
489 uint32_t channel_index = 0xffffffff;
490 // The local queue index.
Austin Schuh58646e22021-08-23 23:51:46 -0700491 // TODO(austin): Technically the boot inside queue_index is redundant with
492 // timestamp. In practice, it is less error-prone to duplicate it. Maybe a
493 // function to return the combined struct?
494 BootQueueIndex queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700495 // The local timestamp.
496 BootTimestamp timestamp;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700497
Austin Schuh48507722021-07-17 17:29:24 -0700498 // Remote boot when this is a timestamp.
499 size_t monotonic_remote_boot = 0xffffff;
500
501 size_t monotonic_timestamp_boot = 0xffffff;
502
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700503 std::shared_ptr<UnpackedMessageHeader> data;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800504
505 bool operator<(const Message &m2) const;
506 bool operator>=(const Message &m2) const;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800507 bool operator==(const Message &m2) const;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800508};
509
510std::ostream &operator<<(std::ostream &os, const Message &m);
511
Austin Schuhd2f96102020-12-01 20:27:29 -0800512// Structure to hold a full message and all the timestamps, which may or may not
513// have been sent from a remote node. The remote_queue_index will be invalid if
514// this message is from the point of view of the node which sent it.
515struct TimestampedMessage {
516 uint32_t channel_index = 0xffffffff;
517
Austin Schuh58646e22021-08-23 23:51:46 -0700518 BootQueueIndex queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700519 BootTimestamp monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800520 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
521
Austin Schuh58646e22021-08-23 23:51:46 -0700522 BootQueueIndex remote_queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700523 BootTimestamp monotonic_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800524 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
525
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700526 BootTimestamp monotonic_timestamp_time;
Austin Schuh8bf1e632021-01-02 22:41:04 -0800527
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700528 std::shared_ptr<UnpackedMessageHeader> data;
Austin Schuhd2f96102020-12-01 20:27:29 -0800529};
530
531std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m);
532
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800533// Class to sort the resulting messages from a PartsMessageReader.
534class LogPartsSorter {
535 public:
536 LogPartsSorter(LogParts log_parts);
537
Austin Schuh0ca51f32020-12-25 21:51:45 -0800538 // Returns the parts that this is sorting messages from.
539 const LogParts &parts() const { return parts_message_reader_.parts(); }
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800540
Austin Schuhd2f96102020-12-01 20:27:29 -0800541 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800542 return parts().monotonic_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800543 }
544 realtime_clock::time_point realtime_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800545 return parts().realtime_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800546 }
547
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800548 // The time this data is sorted until.
549 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
550
551 // Returns the next sorted message from the log file. It is safe to call
552 // std::move() on the result to move the data flatbuffer from it.
553 Message *Front();
554 // Pops the front message. This should only be called after a call to
555 // Front().
556 void PopFront();
557
558 // Returns a debug string representing the contents of this sorter.
559 std::string DebugString() const;
560
561 private:
562 // Log parts reader we are wrapping.
563 PartsMessageReader parts_message_reader_;
564 // Cache of the time we are sorted until.
565 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
566
Austin Schuhb000de62020-12-03 22:00:40 -0800567 // Timestamp of the last message returned. Used to make sure nothing goes
568 // backwards.
569 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
570
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800571 // Set used for efficient sorting of messages. We can benchmark and evaluate
572 // other data structures if this proves to be the bottleneck.
573 absl::btree_set<Message> messages_;
Austin Schuh48507722021-07-17 17:29:24 -0700574
575 // Mapping from channel to source node.
576 // TODO(austin): Should we put this in Boots so it can be cached for everyone?
577 std::vector<size_t> source_node_index_;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800578};
579
Austin Schuh8f52ed52020-11-30 23:12:39 -0800580// Class to run merge sort on the messages from multiple LogPartsSorter
581// instances.
582class NodeMerger {
583 public:
Austin Schuhd2f96102020-12-01 20:27:29 -0800584 NodeMerger(std::vector<LogParts> parts);
585
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700586 // Copying and moving will mess up the internal raw pointers. Just don't do
587 // it.
588 NodeMerger(NodeMerger const &) = delete;
589 NodeMerger(NodeMerger &&) = delete;
590 void operator=(NodeMerger const &) = delete;
591 void operator=(NodeMerger &&) = delete;
592
Austin Schuhd2f96102020-12-01 20:27:29 -0800593 // Node index in the configuration of this node.
594 int node() const { return node_; }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800595
Austin Schuh0ca51f32020-12-25 21:51:45 -0800596 // List of parts being sorted together.
597 std::vector<const LogParts *> Parts() const;
598
599 const Configuration *configuration() const {
600 return parts_sorters_[0].parts().config.get();
Austin Schuhd2f96102020-12-01 20:27:29 -0800601 }
602
603 monotonic_clock::time_point monotonic_start_time() const {
604 return monotonic_start_time_;
605 }
606 realtime_clock::time_point realtime_start_time() const {
607 return realtime_start_time_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800608 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800609 monotonic_clock::time_point monotonic_oldest_time() const {
610 return monotonic_oldest_time_;
611 }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800612
613 // The time this data is sorted until.
614 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
615
616 // Returns the next sorted message from the set of log files. It is safe to
617 // call std::move() on the result to move the data flatbuffer from it.
618 Message *Front();
619 // Pops the front message. This should only be called after a call to
620 // Front().
621 void PopFront();
622
623 private:
624 // Unsorted list of all parts sorters.
Austin Schuhd2f96102020-12-01 20:27:29 -0800625 std::vector<LogPartsSorter> parts_sorters_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800626 // Pointer to the parts sorter holding the current Front message if one
627 // exists, or nullptr if a new one needs to be found.
628 LogPartsSorter *current_ = nullptr;
629 // Cached sorted_until value.
630 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800631
632 // Cached node.
633 int node_;
634
Austin Schuhb000de62020-12-03 22:00:40 -0800635 // Timestamp of the last message returned. Used to make sure nothing goes
636 // backwards.
637 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
638
Austin Schuhd2f96102020-12-01 20:27:29 -0800639 realtime_clock::time_point realtime_start_time_ = realtime_clock::max_time;
640 monotonic_clock::time_point monotonic_start_time_ = monotonic_clock::max_time;
Austin Schuh60e77942022-05-16 17:48:24 -0700641 monotonic_clock::time_point monotonic_oldest_time_ =
642 monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800643};
644
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700645// Class to concatenate multiple boots worth of logs into a single per-node
646// stream.
647class BootMerger {
648 public:
649 BootMerger(std::vector<LogParts> file);
650
651 // Copying and moving will mess up the internal raw pointers. Just don't do
652 // it.
653 BootMerger(BootMerger const &) = delete;
654 BootMerger(BootMerger &&) = delete;
655 void operator=(BootMerger const &) = delete;
656 void operator=(BootMerger &&) = delete;
657
658 // Node index in the configuration of this node.
659 int node() const { return node_mergers_[0]->node(); }
660
661 // List of parts being sorted together.
662 std::vector<const LogParts *> Parts() const;
663
664 const Configuration *configuration() const {
665 return node_mergers_[0]->configuration();
666 }
667
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700668 monotonic_clock::time_point monotonic_start_time(size_t boot) const {
669 CHECK_LT(boot, node_mergers_.size());
670 return node_mergers_[boot]->monotonic_start_time();
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700671 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700672 realtime_clock::time_point realtime_start_time(size_t boot) const {
673 CHECK_LT(boot, node_mergers_.size());
674 return node_mergers_[boot]->realtime_start_time();
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700675 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800676 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const {
677 CHECK_LT(boot, node_mergers_.size());
678 return node_mergers_[boot]->monotonic_oldest_time();
679 }
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700680
681 bool started() const {
682 return node_mergers_[index_]->sorted_until() != monotonic_clock::min_time ||
683 index_ != 0;
684 }
685
686 // Returns the next sorted message from the set of log files. It is safe to
687 // call std::move() on the result to move the data flatbuffer from it.
688 Message *Front();
689 // Pops the front message. This should only be called after a call to
690 // Front().
691 void PopFront();
692
693 private:
694 int index_ = 0;
695
696 // TODO(austin): Sanjay points out this is pretty inefficient. Don't keep so
697 // many things open.
698 std::vector<std::unique_ptr<NodeMerger>> node_mergers_;
699};
700
Austin Schuhd2f96102020-12-01 20:27:29 -0800701// Class to match timestamps with the corresponding data from other nodes.
Austin Schuh79b30942021-01-24 22:32:21 -0800702//
703// This class also buffers data for the node it represents, and supports
704// notifying when new data is queued as well as queueing until a point in time.
Austin Schuhd2f96102020-12-01 20:27:29 -0800705class TimestampMapper {
706 public:
707 TimestampMapper(std::vector<LogParts> file);
708
709 // Copying and moving will mess up the internal raw pointers. Just don't do
710 // it.
711 TimestampMapper(TimestampMapper const &) = delete;
712 TimestampMapper(TimestampMapper &&) = delete;
713 void operator=(TimestampMapper const &) = delete;
714 void operator=(TimestampMapper &&) = delete;
715
716 // TODO(austin): It would be super helpful to provide a way to queue up to
717 // time X without matching timestamps, and to then be able to pull the
718 // timestamps out of this queue. This lets us bootstrap time estimation
719 // without exploding memory usage worst case.
720
Austin Schuh0ca51f32020-12-25 21:51:45 -0800721 const Configuration *configuration() const { return configuration_.get(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800722
723 // Returns which node this is sorting for.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700724 size_t node() const { return boot_merger_.node(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800725
726 // The start time of this log.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700727 monotonic_clock::time_point monotonic_start_time(size_t boot) const {
728 return boot_merger_.monotonic_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800729 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700730 realtime_clock::time_point realtime_start_time(size_t boot) const {
731 return boot_merger_.realtime_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800732 }
Austin Schuh5dd22842021-11-17 16:09:39 -0800733 // Returns the oldest timestamp on a message on this boot.
734 monotonic_clock::time_point monotonic_oldest_time(size_t boot) const {
735 return boot_merger_.monotonic_oldest_time(boot);
736 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800737
738 // Uses timestamp_mapper as the peer for its node. Only one mapper may be set
739 // for each node. Peers are used to look up the data for timestamps on this
740 // node.
741 void AddPeer(TimestampMapper *timestamp_mapper);
742
Austin Schuh24bf4972021-06-29 22:09:08 -0700743 // Returns true if anything has been queued up.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700744 bool started() const { return boot_merger_.started(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800745
746 // Returns the next message for this node.
747 TimestampedMessage *Front();
748 // Pops the next message. Front must be called first.
749 void PopFront();
750
751 // Returns debug information about this node.
752 std::string DebugString() const;
753
Austin Schuh79b30942021-01-24 22:32:21 -0800754 // Queues data the provided time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700755 void QueueUntil(BootTimestamp queue_time);
Austin Schuhe639ea12021-01-25 13:00:22 -0800756 // Queues until we have time_estimation_buffer of data in the queue.
757 void QueueFor(std::chrono::nanoseconds time_estimation_buffer);
Austin Schuh79b30942021-01-24 22:32:21 -0800758
Austin Schuh06601222021-01-26 17:02:50 -0800759 // Queues until the condition is met.
760 template <typename T>
761 void QueueUntilCondition(T fn) {
762 while (true) {
763 if (fn()) {
764 break;
765 }
766 if (!QueueMatched()) {
767 break;
768 }
769 }
770 }
771
Austin Schuh79b30942021-01-24 22:32:21 -0800772 // Sets a callback to be called whenever a full message is queued.
773 void set_timestamp_callback(std::function<void(TimestampedMessage *)> fn) {
774 timestamp_callback_ = fn;
775 }
776
Austin Schuhd2f96102020-12-01 20:27:29 -0800777 private:
778 // The state for a remote node. This holds the data that needs to be matched
779 // with the remote node's timestamps.
780 struct NodeData {
781 // True if we should save data here. This should be true if any of the
782 // bools in delivered below are true.
783 bool any_delivered = false;
784
Austin Schuh36c00932021-07-19 18:13:21 -0700785 // True if we have a peer and therefore should be saving data for it.
786 bool save_for_peer = false;
787
Austin Schuhd2f96102020-12-01 20:27:29 -0800788 // Peer pointer. This node is only to be considered if a peer is set.
789 TimestampMapper *peer = nullptr;
790
791 struct ChannelData {
792 // Deque per channel. This contains the data from the outside
793 // TimestampMapper node which is relevant for the node this NodeData
794 // points to.
795 std::deque<Message> messages;
796 // Bool tracking per channel if a message is delivered to the node this
797 // NodeData represents.
798 bool delivered = false;
Austin Schuh6a7358f2021-11-18 22:40:40 -0800799 // The TTL for delivery.
800 std::chrono::nanoseconds time_to_live = std::chrono::nanoseconds(0);
Austin Schuhd2f96102020-12-01 20:27:29 -0800801 };
802
803 // Vector with per channel data.
804 std::vector<ChannelData> channels;
805 };
806
807 // Returns (and forgets about) the data for the provided timestamp message
808 // showing when it was delivered to this node.
809 Message MatchingMessageFor(const Message &message);
810
811 // Queues up a single message into our message queue, and any nodes that this
812 // message is delivered to. Returns true if one was available, false
813 // otherwise.
814 bool Queue();
815
Austin Schuh79b30942021-01-24 22:32:21 -0800816 // Queues up a single matched message into our matched message queue. Returns
817 // true if one was queued, and false otherwise.
818 bool QueueMatched();
819
Austin Schuhd2f96102020-12-01 20:27:29 -0800820 // Queues up data until we have at least one message >= to time t.
821 // Useful for triggering a remote node to read enough data to have the
822 // timestamp you care about available.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700823 void QueueUnmatchedUntil(BootTimestamp t);
Austin Schuhd2f96102020-12-01 20:27:29 -0800824
Austin Schuh79b30942021-01-24 22:32:21 -0800825 // Queues m into matched_messages_.
826 void QueueMessage(Message *m);
Austin Schuhd2f96102020-12-01 20:27:29 -0800827
Austin Schuh58646e22021-08-23 23:51:46 -0700828 // Returns the name of the node this class is sorting for.
829 std::string_view node_name() const {
830 return configuration_->has_nodes() ? configuration_->nodes()
831 ->Get(boot_merger_.node())
832 ->name()
833 ->string_view()
834 : "(single node)";
835 }
836
Austin Schuhd2f96102020-12-01 20:27:29 -0800837 // The node merger to source messages from.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700838 BootMerger boot_merger_;
Austin Schuh0ca51f32020-12-25 21:51:45 -0800839
840 std::shared_ptr<const Configuration> configuration_;
841
Austin Schuhd2f96102020-12-01 20:27:29 -0800842 // The buffer of messages for this node. These are not matched with any
843 // remote data.
844 std::deque<Message> messages_;
845 // The node index for the source node for each channel.
846 std::vector<size_t> source_node_;
847
848 // Vector per node. Not all nodes will have anything.
849 std::vector<NodeData> nodes_data_;
850
851 // Latest message to return.
Austin Schuh79b30942021-01-24 22:32:21 -0800852 std::deque<TimestampedMessage> matched_messages_;
Austin Schuhd2f96102020-12-01 20:27:29 -0800853
Austin Schuh79b30942021-01-24 22:32:21 -0800854 // Tracks the state of the first message in matched_messages_. Do we need to
855 // update it, is it valid, or should we return nullptr?
Austin Schuhd2f96102020-12-01 20:27:29 -0800856 enum class FirstMessage {
857 kNeedsUpdate,
858 kInMessage,
859 kNullptr,
860 };
861 FirstMessage first_message_ = FirstMessage::kNeedsUpdate;
862
863 // Timestamp of the last message returned. Used to make sure nothing goes
864 // backwards.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700865 BootTimestamp last_message_time_ = BootTimestamp::min_time();
Austin Schuh6a7358f2021-11-18 22:40:40 -0800866 BootTimestamp last_popped_message_time_ = BootTimestamp::min_time();
Austin Schuhd2f96102020-12-01 20:27:29 -0800867 // Time this node is queued up until. Used for caching.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700868 BootTimestamp queued_until_ = BootTimestamp::min_time();
Austin Schuh79b30942021-01-24 22:32:21 -0800869
870 std::function<void(TimestampedMessage *)> timestamp_callback_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800871};
872
Austin Schuhee711052020-08-24 16:06:09 -0700873// Returns the node name with a trailing space, or an empty string if we are on
874// a single node.
875std::string MaybeNodeName(const Node *);
876
Brian Silvermanf51499a2020-09-21 12:49:08 -0700877} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -0800878
879#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_