blob: f876d2595271944808acaccaf5f6966e9d6244d8 [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 Schuha36c8902019-12-30 18:07:15 -080026#include "flatbuffers/flatbuffers.h"
27
Brian Silvermanf51499a2020-09-21 12:49:08 -070028namespace aos::logger {
Austin Schuha36c8902019-12-30 18:07:15 -080029
30enum class LogType : uint8_t {
31 // The message originated on this node and should be logged here.
32 kLogMessage,
33 // The message originated on another node, but only the delivery times are
34 // logged here.
35 kLogDeliveryTimeOnly,
36 // The message originated on another node. Log it and the delivery times
37 // together. The message_gateway is responsible for logging any messages
38 // which didn't get delivered.
Austin Schuh6f3babe2020-01-26 20:34:50 -080039 kLogMessageAndDeliveryTime,
40 // The message originated on the other node and should be logged on this node.
41 kLogRemoteMessage
Austin Schuha36c8902019-12-30 18:07:15 -080042};
43
Austin Schuha36c8902019-12-30 18:07:15 -080044// This class manages efficiently writing a sequence of detached buffers to a
Brian Silvermanf51499a2020-09-21 12:49:08 -070045// file. It encodes them, queues them up, and batches the write operation.
Austin Schuha36c8902019-12-30 18:07:15 -080046class DetachedBufferWriter {
47 public:
Brian Silvermana9f2ec92020-10-06 18:00:53 -070048 // Marker struct for one of our constructor overloads.
49 struct already_out_of_space_t {};
50
Brian Silvermanf51499a2020-09-21 12:49:08 -070051 DetachedBufferWriter(std::string_view filename,
52 std::unique_ptr<DetachedBufferEncoder> encoder);
Brian Silvermana9f2ec92020-10-06 18:00:53 -070053 // Creates a dummy instance which won't even open a file. It will act as if
54 // opening the file ran out of space immediately.
55 DetachedBufferWriter(already_out_of_space_t) : ran_out_of_space_(true) {}
Austin Schuh2f8fd752020-09-01 22:38:28 -070056 DetachedBufferWriter(DetachedBufferWriter &&other);
57 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
58
Austin Schuha36c8902019-12-30 18:07:15 -080059 ~DetachedBufferWriter();
60
Austin Schuh2f8fd752020-09-01 22:38:28 -070061 DetachedBufferWriter &operator=(DetachedBufferWriter &&other);
Brian Silverman98360e22020-04-28 16:51:20 -070062 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
63
Austin Schuh6f3babe2020-01-26 20:34:50 -080064 std::string_view filename() const { return filename_; }
65
Brian Silvermana9f2ec92020-10-06 18:00:53 -070066 // This will be true until Close() is called, unless the file couldn't be
67 // created due to running out of space.
68 bool is_open() const { return fd_ != -1; }
69
Brian Silvermanf51499a2020-09-21 12:49:08 -070070 // Queues up a finished FlatBufferBuilder to be encoded and written.
71 //
72 // Triggers a flush if there's enough data queued up.
73 //
74 // Steals the detached buffer from it.
Austin Schuhbd06ae42021-03-31 22:48:21 -070075 void QueueSizedFlatbuffer(flatbuffers::FlatBufferBuilder *fbb,
76 aos::monotonic_clock::time_point now) {
77 QueueSizedFlatbuffer(fbb->Release(), now);
Brian Silvermanf51499a2020-09-21 12:49:08 -070078 }
79 // May steal the backing storage of buffer, or may leave it alone.
Austin Schuhbd06ae42021-03-31 22:48:21 -070080 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer,
81 aos::monotonic_clock::time_point now) {
82 QueueSizedFlatbuffer(std::move(buffer));
83 FlushAtThreshold(now);
84 }
85 // Unconditionally queues the buffer.
Brian Silvermanf51499a2020-09-21 12:49:08 -070086 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070087 if (ran_out_of_space_) {
88 return;
89 }
Brian Silvermanf51499a2020-09-21 12:49:08 -070090 encoder_->Encode(std::move(buffer));
Brian Silvermanf51499a2020-09-21 12:49:08 -070091 }
Austin Schuha36c8902019-12-30 18:07:15 -080092
Brian Silvermanf51499a2020-09-21 12:49:08 -070093 // Queues up data in span. May copy or may write it to disk immediately.
94 void QueueSpan(absl::Span<const uint8_t> span);
Austin Schuha36c8902019-12-30 18:07:15 -080095
Brian Silverman0465fcf2020-09-24 00:29:18 -070096 // Indicates we got ENOSPC when trying to write. After this returns true, no
97 // further data is written.
98 bool ran_out_of_space() const { return ran_out_of_space_; }
99
100 // To avoid silently failing to write logfiles, you must call this before
101 // destruction if ran_out_of_space() is true and the situation has been
102 // handled.
103 void acknowledge_out_of_space() {
104 CHECK(ran_out_of_space_);
105 acknowledge_ran_out_of_space_ = true;
106 }
107
108 // Fully flushes and closes the underlying file now. No additional data may be
109 // enqueued after calling this.
110 //
111 // This will be performed in the destructor automatically.
112 //
113 // Note that this may set ran_out_of_space().
114 void Close();
115
Brian Silvermanf51499a2020-09-21 12:49:08 -0700116 // Returns the total number of bytes written and currently queued.
Austin Schuha426f1f2021-03-31 22:27:41 -0700117 size_t total_bytes() const {
118 if (!encoder_) {
119 return 0;
120 }
121 return encoder_->total_bytes();
122 }
Austin Schuha36c8902019-12-30 18:07:15 -0800123
Brian Silvermanf51499a2020-09-21 12:49:08 -0700124 // The maximum time for a single write call, or 0 if none have been performed.
125 std::chrono::nanoseconds max_write_time() const { return max_write_time_; }
126 // The number of bytes in the longest write call, or -1 if none have been
127 // performed.
128 int max_write_time_bytes() const { return max_write_time_bytes_; }
129 // The number of buffers in the longest write call, or -1 if none have been
130 // performed.
131 int max_write_time_messages() const { return max_write_time_messages_; }
132 // The total time spent in write calls.
133 std::chrono::nanoseconds total_write_time() const {
134 return total_write_time_;
135 }
136 // The total number of writes which have been performed.
137 int total_write_count() const { return total_write_count_; }
138 // The total number of messages which have been written.
139 int total_write_messages() const { return total_write_messages_; }
140 // The total number of bytes which have been written.
141 int total_write_bytes() const { return total_write_bytes_; }
142 void ResetStatistics() {
143 max_write_time_ = std::chrono::nanoseconds::zero();
144 max_write_time_bytes_ = -1;
145 max_write_time_messages_ = -1;
146 total_write_time_ = std::chrono::nanoseconds::zero();
147 total_write_count_ = 0;
148 total_write_messages_ = 0;
149 total_write_bytes_ = 0;
150 }
Brian Silverman98360e22020-04-28 16:51:20 -0700151
Austin Schuha36c8902019-12-30 18:07:15 -0800152 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700153 // Performs a single writev call with as much of the data we have queued up as
154 // possible.
155 //
156 // This will normally take all of the data we have queued up, unless an
157 // encoder has spit out a big enough chunk all at once that we can't manage
158 // all of it.
159 void Flush();
160
Brian Silverman0465fcf2020-09-24 00:29:18 -0700161 // write_return is what write(2) or writev(2) returned. write_size is the
162 // number of bytes we expected it to write.
163 void HandleWriteReturn(ssize_t write_return, size_t write_size);
164
Brian Silvermanf51499a2020-09-21 12:49:08 -0700165 void UpdateStatsForWrite(aos::monotonic_clock::duration duration,
166 ssize_t written, int iovec_size);
167
168 // Flushes data if we've reached the threshold to do that as part of normal
Austin Schuhbd06ae42021-03-31 22:48:21 -0700169 // operation either due to the outstanding queued data, or because we have
170 // passed our flush period. now is the current time to save some CPU grabbing
171 // the current time. It just needs to be close.
172 void FlushAtThreshold(aos::monotonic_clock::time_point now);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700173
Austin Schuh2f8fd752020-09-01 22:38:28 -0700174 std::string filename_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700175 std::unique_ptr<DetachedBufferEncoder> encoder_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800176
Austin Schuha36c8902019-12-30 18:07:15 -0800177 int fd_ = -1;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700178 bool ran_out_of_space_ = false;
179 bool acknowledge_ran_out_of_space_ = false;
Austin Schuha36c8902019-12-30 18:07:15 -0800180
Austin Schuha36c8902019-12-30 18:07:15 -0800181 // List of iovecs to use with writev. This is a member variable to avoid
182 // churn.
183 std::vector<struct iovec> iovec_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700184
185 std::chrono::nanoseconds max_write_time_ = std::chrono::nanoseconds::zero();
186 int max_write_time_bytes_ = -1;
187 int max_write_time_messages_ = -1;
188 std::chrono::nanoseconds total_write_time_ = std::chrono::nanoseconds::zero();
189 int total_write_count_ = 0;
190 int total_write_messages_ = 0;
191 int total_write_bytes_ = 0;
Austin Schuhbd06ae42021-03-31 22:48:21 -0700192
193 aos::monotonic_clock::time_point last_flush_time_ =
194 aos::monotonic_clock::min_time;
Austin Schuha36c8902019-12-30 18:07:15 -0800195};
196
197// Packes a message pointed to by the context into a MessageHeader.
198flatbuffers::Offset<MessageHeader> PackMessage(
199 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
200 int channel_index, LogType log_type);
201
Austin Schuh0e8db662021-07-06 10:43:47 -0700202// Reads the last header from a log file. This handles any duplicate headers
203// that were written.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800204std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800205 std::string_view filename);
Austin Schuh0e8db662021-07-06 10:43:47 -0700206// Reads the Nth message from a log file, excluding the header. Note: this
207// doesn't handle duplicate headers.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800208std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800209 std::string_view filename, size_t n);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800210
Austin Schuh05b70472020-01-01 17:11:17 -0800211// Class to read chunks out of a log file.
212class SpanReader {
213 public:
214 SpanReader(std::string_view filename);
Austin Schuha36c8902019-12-30 18:07:15 -0800215
Austin Schuh6f3babe2020-01-26 20:34:50 -0800216 std::string_view filename() const { return filename_; }
217
Austin Schuhcf5f6442021-07-06 10:43:28 -0700218 // Returns a span with the data for the next message from the log file,
219 // including the size. The result is only guarenteed to be valid until
220 // ReadMessage() or PeekMessage() is called again.
Austin Schuh05b70472020-01-01 17:11:17 -0800221 absl::Span<const uint8_t> ReadMessage();
222
Austin Schuhcf5f6442021-07-06 10:43:28 -0700223 // Returns a span with the data for the next message without consuming it.
224 // Multiple calls to PeekMessage return the same data. ReadMessage or
225 // ConsumeMessage must be called to get the next message.
226 absl::Span<const uint8_t> PeekMessage();
227 // Consumes the message so the next call to ReadMessage or PeekMessage returns
228 // new data. This does not invalidate the data.
229 void ConsumeMessage();
230
Austin Schuh05b70472020-01-01 17:11:17 -0800231 private:
232 // TODO(austin): Optimization:
233 // Allocate the 256k blocks like we do today. But, refcount them with
234 // shared_ptr pointed to by the messageheader that is returned. This avoids
235 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700236 // And (Brian): Consider just mmapping the file and handing out refcounted
237 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800238
239 // Reads a chunk of data into data_. Returns false if no data was read.
240 bool ReadBlock();
241
Austin Schuhc41603c2020-10-11 16:17:37 -0700242 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800243
Brian Silvermanf51499a2020-09-21 12:49:08 -0700244 // File reader and data decoder.
245 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800246
Brian Silvermanf51499a2020-09-21 12:49:08 -0700247 // Vector to read into.
248 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800249
250 // Amount of data consumed already in data_.
251 size_t consumed_data_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800252};
253
254// Class which handles reading the header and messages from the log file. This
255// handles any per-file state left before merging below.
256class MessageReader {
257 public:
258 MessageReader(std::string_view filename);
259
Austin Schuh6f3babe2020-01-26 20:34:50 -0800260 std::string_view filename() const { return span_reader_.filename(); }
261
Austin Schuh05b70472020-01-01 17:11:17 -0800262 // Returns the header from the log file.
263 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700264 return &raw_log_file_header_.message();
265 }
266
267 // Returns the raw data of the header from the log file.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800268 const SizePrefixedFlatbufferVector<LogFileHeader> &raw_log_file_header()
269 const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700270 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800271 }
272
273 // Returns the minimum maount of data needed to queue up for sorting before
274 // ware guarenteed to not see data out of order.
275 std::chrono::nanoseconds max_out_of_order_duration() const {
276 return max_out_of_order_duration_;
277 }
278
Austin Schuhcde938c2020-02-02 17:30:07 -0800279 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800280 monotonic_clock::time_point newest_timestamp() const {
281 return newest_timestamp_;
282 }
283
284 // Returns the next message if there is one.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800285 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800286
287 // The time at which we need to read another chunk from the logfile.
288 monotonic_clock::time_point queue_data_time() const {
289 return newest_timestamp() - max_out_of_order_duration();
290 }
291
292 private:
293 // Log chunk reader.
294 SpanReader span_reader_;
295
Austin Schuh97789fc2020-08-01 14:42:45 -0700296 // Vector holding the raw data for the log file header.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800297 SizePrefixedFlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800298
299 // Minimum amount of data to queue up for sorting before we are guarenteed
300 // to not see data out of order.
301 std::chrono::nanoseconds max_out_of_order_duration_;
302
303 // Timestamp of the newest message in a channel queue.
304 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
305};
306
Austin Schuhc41603c2020-10-11 16:17:37 -0700307// A class to seamlessly read messages from a list of part files.
308class PartsMessageReader {
309 public:
310 PartsMessageReader(LogParts log_parts);
311
312 std::string_view filename() const { return message_reader_.filename(); }
313
Austin Schuhd2f96102020-12-01 20:27:29 -0800314 // Returns the LogParts that holds the filenames we are reading.
315 const LogParts &parts() const { return parts_; }
316
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800317 const LogFileHeader *log_file_header() const {
318 return message_reader_.log_file_header();
319 }
320
Austin Schuhc41603c2020-10-11 16:17:37 -0700321 // Returns the minimum amount of data needed to queue up for sorting before
322 // we are guarenteed to not see data out of order.
323 std::chrono::nanoseconds max_out_of_order_duration() const {
324 return message_reader_.max_out_of_order_duration();
325 }
326
327 // Returns the newest timestamp read out of the log file.
328 monotonic_clock::time_point newest_timestamp() const {
329 return newest_timestamp_;
330 }
331
332 // Returns the next message if there is one, or nullopt if we have reached the
333 // end of all the files.
334 // Note: reading the next message may change the max_out_of_order_duration().
Austin Schuhadd6eb32020-11-09 21:24:26 -0800335 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadMessage();
Austin Schuhc41603c2020-10-11 16:17:37 -0700336
337 private:
338 // Opens the next log and updates message_reader_. Sets done_ if there is
339 // nothing more to do.
340 void NextLog();
341
342 const LogParts parts_;
343 size_t next_part_index_ = 1u;
344 bool done_ = false;
345 MessageReader message_reader_;
346
Austin Schuh315b96b2020-12-11 21:21:12 -0800347 // True after we have seen a message after the start of the log. The
348 // guarentees on logging essentially are that all data from before the
349 // starting time of the log may be arbitrarily out of order, but once we get
350 // max_out_of_order_duration past the start, everything will remain within
351 // max_out_of_order_duration. We shouldn't see anything before the start
352 // after we've seen a message that is at least max_out_of_order_duration after
353 // the start.
354 bool after_start_ = false;
355
Austin Schuhc41603c2020-10-11 16:17:37 -0700356 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
357};
358
Austin Schuh1be0ce42020-11-29 22:43:26 -0800359// Struct to hold a message as it gets sorted on a single node.
360struct Message {
361 // The channel.
362 uint32_t channel_index = 0xffffffff;
363 // The local queue index.
364 uint32_t queue_index = 0xffffffff;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700365 // The local timestamp.
366 BootTimestamp timestamp;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700367
Austin Schuh1be0ce42020-11-29 22:43:26 -0800368 // The data (either a timestamp header, or a data header).
369 SizePrefixedFlatbufferVector<MessageHeader> data;
370
371 bool operator<(const Message &m2) const;
372 bool operator>=(const Message &m2) const;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800373 bool operator==(const Message &m2) const;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800374};
375
376std::ostream &operator<<(std::ostream &os, const Message &m);
377
Austin Schuhd2f96102020-12-01 20:27:29 -0800378// Structure to hold a full message and all the timestamps, which may or may not
379// have been sent from a remote node. The remote_queue_index will be invalid if
380// this message is from the point of view of the node which sent it.
381struct TimestampedMessage {
382 uint32_t channel_index = 0xffffffff;
383
384 uint32_t queue_index = 0xffffffff;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700385 BootTimestamp monotonic_event_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800386 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
387
388 uint32_t remote_queue_index = 0xffffffff;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700389 BootTimestamp monotonic_remote_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800390 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
391
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700392 BootTimestamp monotonic_timestamp_time;
Austin Schuh8bf1e632021-01-02 22:41:04 -0800393
Austin Schuhd2f96102020-12-01 20:27:29 -0800394 SizePrefixedFlatbufferVector<MessageHeader> data;
395};
396
397std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m);
398
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800399// Class to sort the resulting messages from a PartsMessageReader.
400class LogPartsSorter {
401 public:
402 LogPartsSorter(LogParts log_parts);
403
Austin Schuh0ca51f32020-12-25 21:51:45 -0800404 // Returns the parts that this is sorting messages from.
405 const LogParts &parts() const { return parts_message_reader_.parts(); }
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800406
Austin Schuhd2f96102020-12-01 20:27:29 -0800407 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800408 return parts().monotonic_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800409 }
410 realtime_clock::time_point realtime_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800411 return parts().realtime_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800412 }
413
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800414 // The time this data is sorted until.
415 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
416
417 // Returns the next sorted message from the log file. It is safe to call
418 // std::move() on the result to move the data flatbuffer from it.
419 Message *Front();
420 // Pops the front message. This should only be called after a call to
421 // Front().
422 void PopFront();
423
424 // Returns a debug string representing the contents of this sorter.
425 std::string DebugString() const;
426
427 private:
428 // Log parts reader we are wrapping.
429 PartsMessageReader parts_message_reader_;
430 // Cache of the time we are sorted until.
431 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
432
Austin Schuhb000de62020-12-03 22:00:40 -0800433 // Timestamp of the last message returned. Used to make sure nothing goes
434 // backwards.
435 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
436
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800437 // Set used for efficient sorting of messages. We can benchmark and evaluate
438 // other data structures if this proves to be the bottleneck.
439 absl::btree_set<Message> messages_;
440};
441
Austin Schuh8f52ed52020-11-30 23:12:39 -0800442// Class to run merge sort on the messages from multiple LogPartsSorter
443// instances.
444class NodeMerger {
445 public:
Austin Schuhd2f96102020-12-01 20:27:29 -0800446 NodeMerger(std::vector<LogParts> parts);
447
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700448 // Copying and moving will mess up the internal raw pointers. Just don't do
449 // it.
450 NodeMerger(NodeMerger const &) = delete;
451 NodeMerger(NodeMerger &&) = delete;
452 void operator=(NodeMerger const &) = delete;
453 void operator=(NodeMerger &&) = delete;
454
Austin Schuhd2f96102020-12-01 20:27:29 -0800455 // Node index in the configuration of this node.
456 int node() const { return node_; }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800457
Austin Schuh0ca51f32020-12-25 21:51:45 -0800458 // List of parts being sorted together.
459 std::vector<const LogParts *> Parts() const;
460
461 const Configuration *configuration() const {
462 return parts_sorters_[0].parts().config.get();
Austin Schuhd2f96102020-12-01 20:27:29 -0800463 }
464
465 monotonic_clock::time_point monotonic_start_time() const {
466 return monotonic_start_time_;
467 }
468 realtime_clock::time_point realtime_start_time() const {
469 return realtime_start_time_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800470 }
471
472 // The time this data is sorted until.
473 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
474
475 // Returns the next sorted message from the set of log files. It is safe to
476 // call std::move() on the result to move the data flatbuffer from it.
477 Message *Front();
478 // Pops the front message. This should only be called after a call to
479 // Front().
480 void PopFront();
481
482 private:
483 // Unsorted list of all parts sorters.
Austin Schuhd2f96102020-12-01 20:27:29 -0800484 std::vector<LogPartsSorter> parts_sorters_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800485 // Pointer to the parts sorter holding the current Front message if one
486 // exists, or nullptr if a new one needs to be found.
487 LogPartsSorter *current_ = nullptr;
488 // Cached sorted_until value.
489 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800490
491 // Cached node.
492 int node_;
493
Austin Schuhb000de62020-12-03 22:00:40 -0800494 // Timestamp of the last message returned. Used to make sure nothing goes
495 // backwards.
496 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
497
Austin Schuhd2f96102020-12-01 20:27:29 -0800498 realtime_clock::time_point realtime_start_time_ = realtime_clock::max_time;
499 monotonic_clock::time_point monotonic_start_time_ = monotonic_clock::max_time;
500};
501
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700502// Class to concatenate multiple boots worth of logs into a single per-node
503// stream.
504class BootMerger {
505 public:
506 BootMerger(std::vector<LogParts> file);
507
508 // Copying and moving will mess up the internal raw pointers. Just don't do
509 // it.
510 BootMerger(BootMerger const &) = delete;
511 BootMerger(BootMerger &&) = delete;
512 void operator=(BootMerger const &) = delete;
513 void operator=(BootMerger &&) = delete;
514
515 // Node index in the configuration of this node.
516 int node() const { return node_mergers_[0]->node(); }
517
518 // List of parts being sorted together.
519 std::vector<const LogParts *> Parts() const;
520
521 const Configuration *configuration() const {
522 return node_mergers_[0]->configuration();
523 }
524
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700525 monotonic_clock::time_point monotonic_start_time(size_t boot) const {
526 CHECK_LT(boot, node_mergers_.size());
527 return node_mergers_[boot]->monotonic_start_time();
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700528 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700529 realtime_clock::time_point realtime_start_time(size_t boot) const {
530 CHECK_LT(boot, node_mergers_.size());
531 return node_mergers_[boot]->realtime_start_time();
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700532 }
533
534 bool started() const {
535 return node_mergers_[index_]->sorted_until() != monotonic_clock::min_time ||
536 index_ != 0;
537 }
538
539 // Returns the next sorted message from the set of log files. It is safe to
540 // call std::move() on the result to move the data flatbuffer from it.
541 Message *Front();
542 // Pops the front message. This should only be called after a call to
543 // Front().
544 void PopFront();
545
546 private:
547 int index_ = 0;
548
549 // TODO(austin): Sanjay points out this is pretty inefficient. Don't keep so
550 // many things open.
551 std::vector<std::unique_ptr<NodeMerger>> node_mergers_;
552};
553
Austin Schuhd2f96102020-12-01 20:27:29 -0800554// Class to match timestamps with the corresponding data from other nodes.
Austin Schuh79b30942021-01-24 22:32:21 -0800555//
556// This class also buffers data for the node it represents, and supports
557// notifying when new data is queued as well as queueing until a point in time.
Austin Schuhd2f96102020-12-01 20:27:29 -0800558class TimestampMapper {
559 public:
560 TimestampMapper(std::vector<LogParts> file);
561
562 // Copying and moving will mess up the internal raw pointers. Just don't do
563 // it.
564 TimestampMapper(TimestampMapper const &) = delete;
565 TimestampMapper(TimestampMapper &&) = delete;
566 void operator=(TimestampMapper const &) = delete;
567 void operator=(TimestampMapper &&) = delete;
568
569 // TODO(austin): It would be super helpful to provide a way to queue up to
570 // time X without matching timestamps, and to then be able to pull the
571 // timestamps out of this queue. This lets us bootstrap time estimation
572 // without exploding memory usage worst case.
573
Austin Schuh0ca51f32020-12-25 21:51:45 -0800574 const Configuration *configuration() const { return configuration_.get(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800575
576 // Returns which node this is sorting for.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700577 size_t node() const { return boot_merger_.node(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800578
579 // The start time of this log.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700580 // TODO(austin): This concept is probably wrong... We have start times per
581 // boot, and an order of them.
582 monotonic_clock::time_point monotonic_start_time(size_t boot) const {
583 return boot_merger_.monotonic_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800584 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700585 realtime_clock::time_point realtime_start_time(size_t boot) const {
586 return boot_merger_.realtime_start_time(boot);
Austin Schuhd2f96102020-12-01 20:27:29 -0800587 }
588
589 // Uses timestamp_mapper as the peer for its node. Only one mapper may be set
590 // for each node. Peers are used to look up the data for timestamps on this
591 // node.
592 void AddPeer(TimestampMapper *timestamp_mapper);
593
Austin Schuh24bf4972021-06-29 22:09:08 -0700594 // Returns true if anything has been queued up.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700595 bool started() const { return boot_merger_.started(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800596
597 // Returns the next message for this node.
598 TimestampedMessage *Front();
599 // Pops the next message. Front must be called first.
600 void PopFront();
601
602 // Returns debug information about this node.
603 std::string DebugString() const;
604
Austin Schuh79b30942021-01-24 22:32:21 -0800605 // Queues data the provided time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700606 void QueueUntil(BootTimestamp queue_time);
Austin Schuhe639ea12021-01-25 13:00:22 -0800607 // Queues until we have time_estimation_buffer of data in the queue.
608 void QueueFor(std::chrono::nanoseconds time_estimation_buffer);
Austin Schuh79b30942021-01-24 22:32:21 -0800609
Austin Schuh06601222021-01-26 17:02:50 -0800610 // Queues until the condition is met.
611 template <typename T>
612 void QueueUntilCondition(T fn) {
613 while (true) {
614 if (fn()) {
615 break;
616 }
617 if (!QueueMatched()) {
618 break;
619 }
620 }
621 }
622
Austin Schuh79b30942021-01-24 22:32:21 -0800623 // Sets a callback to be called whenever a full message is queued.
624 void set_timestamp_callback(std::function<void(TimestampedMessage *)> fn) {
625 timestamp_callback_ = fn;
626 }
627
Austin Schuhd2f96102020-12-01 20:27:29 -0800628 private:
629 // The state for a remote node. This holds the data that needs to be matched
630 // with the remote node's timestamps.
631 struct NodeData {
632 // True if we should save data here. This should be true if any of the
633 // bools in delivered below are true.
634 bool any_delivered = false;
635
636 // Peer pointer. This node is only to be considered if a peer is set.
637 TimestampMapper *peer = nullptr;
638
639 struct ChannelData {
640 // Deque per channel. This contains the data from the outside
641 // TimestampMapper node which is relevant for the node this NodeData
642 // points to.
643 std::deque<Message> messages;
644 // Bool tracking per channel if a message is delivered to the node this
645 // NodeData represents.
646 bool delivered = false;
647 };
648
649 // Vector with per channel data.
650 std::vector<ChannelData> channels;
651 };
652
653 // Returns (and forgets about) the data for the provided timestamp message
654 // showing when it was delivered to this node.
655 Message MatchingMessageFor(const Message &message);
656
657 // Queues up a single message into our message queue, and any nodes that this
658 // message is delivered to. Returns true if one was available, false
659 // otherwise.
660 bool Queue();
661
Austin Schuh79b30942021-01-24 22:32:21 -0800662 // Queues up a single matched message into our matched message queue. Returns
663 // true if one was queued, and false otherwise.
664 bool QueueMatched();
665
Austin Schuhd2f96102020-12-01 20:27:29 -0800666 // Queues up data until we have at least one message >= to time t.
667 // Useful for triggering a remote node to read enough data to have the
668 // timestamp you care about available.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700669 void QueueUnmatchedUntil(BootTimestamp t);
Austin Schuhd2f96102020-12-01 20:27:29 -0800670
Austin Schuh79b30942021-01-24 22:32:21 -0800671 // Queues m into matched_messages_.
672 void QueueMessage(Message *m);
Austin Schuhd2f96102020-12-01 20:27:29 -0800673
674 // The node merger to source messages from.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700675 BootMerger boot_merger_;
Austin Schuh0ca51f32020-12-25 21:51:45 -0800676
677 std::shared_ptr<const Configuration> configuration_;
678
Austin Schuhd2f96102020-12-01 20:27:29 -0800679 // The buffer of messages for this node. These are not matched with any
680 // remote data.
681 std::deque<Message> messages_;
682 // The node index for the source node for each channel.
683 std::vector<size_t> source_node_;
684
685 // Vector per node. Not all nodes will have anything.
686 std::vector<NodeData> nodes_data_;
687
688 // Latest message to return.
Austin Schuh79b30942021-01-24 22:32:21 -0800689 std::deque<TimestampedMessage> matched_messages_;
Austin Schuhd2f96102020-12-01 20:27:29 -0800690
Austin Schuh79b30942021-01-24 22:32:21 -0800691 // Tracks the state of the first message in matched_messages_. Do we need to
692 // update it, is it valid, or should we return nullptr?
Austin Schuhd2f96102020-12-01 20:27:29 -0800693 enum class FirstMessage {
694 kNeedsUpdate,
695 kInMessage,
696 kNullptr,
697 };
698 FirstMessage first_message_ = FirstMessage::kNeedsUpdate;
699
700 // Timestamp of the last message returned. Used to make sure nothing goes
701 // backwards.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700702 BootTimestamp last_message_time_ = BootTimestamp::min_time();
Austin Schuhd2f96102020-12-01 20:27:29 -0800703 // Time this node is queued up until. Used for caching.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700704 BootTimestamp queued_until_ = BootTimestamp::min_time();
Austin Schuh79b30942021-01-24 22:32:21 -0800705
706 std::function<void(TimestampedMessage *)> timestamp_callback_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800707};
708
Austin Schuhee711052020-08-24 16:06:09 -0700709// Returns the node name with a trailing space, or an empty string if we are on
710// a single node.
711std::string MaybeNodeName(const Node *);
712
Brian Silvermanf51499a2020-09-21 12:49:08 -0700713} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -0800714
715#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_