blob: 5fe45a5ac31d13d5629beaab0b8251209d0ba8ee [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"
Brian Silvermanf51499a2020-09-21 12:49:08 -070021#include "aos/events/logging/buffer_encoder.h"
Austin Schuhc41603c2020-10-11 16:17:37 -070022#include "aos/events/logging/logfile_sorting.h"
Austin Schuha36c8902019-12-30 18:07:15 -080023#include "aos/events/logging/logger_generated.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070024#include "aos/flatbuffers.h"
Austin Schuha36c8902019-12-30 18:07:15 -080025#include "flatbuffers/flatbuffers.h"
26
Brian Silvermanf51499a2020-09-21 12:49:08 -070027namespace aos::logger {
Austin Schuha36c8902019-12-30 18:07:15 -080028
29enum class LogType : uint8_t {
30 // The message originated on this node and should be logged here.
31 kLogMessage,
32 // The message originated on another node, but only the delivery times are
33 // logged here.
34 kLogDeliveryTimeOnly,
35 // The message originated on another node. Log it and the delivery times
36 // together. The message_gateway is responsible for logging any messages
37 // which didn't get delivered.
Austin Schuh6f3babe2020-01-26 20:34:50 -080038 kLogMessageAndDeliveryTime,
39 // The message originated on the other node and should be logged on this node.
40 kLogRemoteMessage
Austin Schuha36c8902019-12-30 18:07:15 -080041};
42
Austin Schuha36c8902019-12-30 18:07:15 -080043// This class manages efficiently writing a sequence of detached buffers to a
Brian Silvermanf51499a2020-09-21 12:49:08 -070044// file. It encodes them, queues them up, and batches the write operation.
Austin Schuha36c8902019-12-30 18:07:15 -080045class DetachedBufferWriter {
46 public:
Brian Silvermana9f2ec92020-10-06 18:00:53 -070047 // Marker struct for one of our constructor overloads.
48 struct already_out_of_space_t {};
49
Brian Silvermanf51499a2020-09-21 12:49:08 -070050 DetachedBufferWriter(std::string_view filename,
51 std::unique_ptr<DetachedBufferEncoder> encoder);
Brian Silvermana9f2ec92020-10-06 18:00:53 -070052 // Creates a dummy instance which won't even open a file. It will act as if
53 // opening the file ran out of space immediately.
54 DetachedBufferWriter(already_out_of_space_t) : ran_out_of_space_(true) {}
Austin Schuh2f8fd752020-09-01 22:38:28 -070055 DetachedBufferWriter(DetachedBufferWriter &&other);
56 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
57
Austin Schuha36c8902019-12-30 18:07:15 -080058 ~DetachedBufferWriter();
59
Austin Schuh2f8fd752020-09-01 22:38:28 -070060 DetachedBufferWriter &operator=(DetachedBufferWriter &&other);
Brian Silverman98360e22020-04-28 16:51:20 -070061 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
62
Austin Schuh6f3babe2020-01-26 20:34:50 -080063 std::string_view filename() const { return filename_; }
64
Brian Silvermana9f2ec92020-10-06 18:00:53 -070065 // This will be true until Close() is called, unless the file couldn't be
66 // created due to running out of space.
67 bool is_open() const { return fd_ != -1; }
68
Brian Silvermanf51499a2020-09-21 12:49:08 -070069 // Queues up a finished FlatBufferBuilder to be encoded and written.
70 //
71 // Triggers a flush if there's enough data queued up.
72 //
73 // Steals the detached buffer from it.
74 void QueueSizedFlatbuffer(flatbuffers::FlatBufferBuilder *fbb) {
75 QueueSizedFlatbuffer(fbb->Release());
76 }
77 // May steal the backing storage of buffer, or may leave it alone.
78 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070079 if (ran_out_of_space_) {
80 return;
81 }
Brian Silvermanf51499a2020-09-21 12:49:08 -070082 encoder_->Encode(std::move(buffer));
83 FlushAtThreshold();
84 }
Austin Schuha36c8902019-12-30 18:07:15 -080085
Brian Silvermanf51499a2020-09-21 12:49:08 -070086 // Queues up data in span. May copy or may write it to disk immediately.
87 void QueueSpan(absl::Span<const uint8_t> span);
Austin Schuha36c8902019-12-30 18:07:15 -080088
Brian Silverman0465fcf2020-09-24 00:29:18 -070089 // Indicates we got ENOSPC when trying to write. After this returns true, no
90 // further data is written.
91 bool ran_out_of_space() const { return ran_out_of_space_; }
92
93 // To avoid silently failing to write logfiles, you must call this before
94 // destruction if ran_out_of_space() is true and the situation has been
95 // handled.
96 void acknowledge_out_of_space() {
97 CHECK(ran_out_of_space_);
98 acknowledge_ran_out_of_space_ = true;
99 }
100
101 // Fully flushes and closes the underlying file now. No additional data may be
102 // enqueued after calling this.
103 //
104 // This will be performed in the destructor automatically.
105 //
106 // Note that this may set ran_out_of_space().
107 void Close();
108
Brian Silvermanf51499a2020-09-21 12:49:08 -0700109 // Returns the total number of bytes written and currently queued.
Austin Schuha426f1f2021-03-31 22:27:41 -0700110 size_t total_bytes() const {
111 if (!encoder_) {
112 return 0;
113 }
114 return encoder_->total_bytes();
115 }
Austin Schuha36c8902019-12-30 18:07:15 -0800116
Brian Silvermanf51499a2020-09-21 12:49:08 -0700117 // The maximum time for a single write call, or 0 if none have been performed.
118 std::chrono::nanoseconds max_write_time() const { return max_write_time_; }
119 // The number of bytes in the longest write call, or -1 if none have been
120 // performed.
121 int max_write_time_bytes() const { return max_write_time_bytes_; }
122 // The number of buffers in the longest write call, or -1 if none have been
123 // performed.
124 int max_write_time_messages() const { return max_write_time_messages_; }
125 // The total time spent in write calls.
126 std::chrono::nanoseconds total_write_time() const {
127 return total_write_time_;
128 }
129 // The total number of writes which have been performed.
130 int total_write_count() const { return total_write_count_; }
131 // The total number of messages which have been written.
132 int total_write_messages() const { return total_write_messages_; }
133 // The total number of bytes which have been written.
134 int total_write_bytes() const { return total_write_bytes_; }
135 void ResetStatistics() {
136 max_write_time_ = std::chrono::nanoseconds::zero();
137 max_write_time_bytes_ = -1;
138 max_write_time_messages_ = -1;
139 total_write_time_ = std::chrono::nanoseconds::zero();
140 total_write_count_ = 0;
141 total_write_messages_ = 0;
142 total_write_bytes_ = 0;
143 }
Brian Silverman98360e22020-04-28 16:51:20 -0700144
Austin Schuha36c8902019-12-30 18:07:15 -0800145 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700146 // Performs a single writev call with as much of the data we have queued up as
147 // possible.
148 //
149 // This will normally take all of the data we have queued up, unless an
150 // encoder has spit out a big enough chunk all at once that we can't manage
151 // all of it.
152 void Flush();
153
Brian Silverman0465fcf2020-09-24 00:29:18 -0700154 // write_return is what write(2) or writev(2) returned. write_size is the
155 // number of bytes we expected it to write.
156 void HandleWriteReturn(ssize_t write_return, size_t write_size);
157
Brian Silvermanf51499a2020-09-21 12:49:08 -0700158 void UpdateStatsForWrite(aos::monotonic_clock::duration duration,
159 ssize_t written, int iovec_size);
160
161 // Flushes data if we've reached the threshold to do that as part of normal
162 // operation.
163 void FlushAtThreshold();
164
Austin Schuh2f8fd752020-09-01 22:38:28 -0700165 std::string filename_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700166 std::unique_ptr<DetachedBufferEncoder> encoder_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800167
Austin Schuha36c8902019-12-30 18:07:15 -0800168 int fd_ = -1;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700169 bool ran_out_of_space_ = false;
170 bool acknowledge_ran_out_of_space_ = false;
Austin Schuha36c8902019-12-30 18:07:15 -0800171
Austin Schuha36c8902019-12-30 18:07:15 -0800172 // List of iovecs to use with writev. This is a member variable to avoid
173 // churn.
174 std::vector<struct iovec> iovec_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700175
176 std::chrono::nanoseconds max_write_time_ = std::chrono::nanoseconds::zero();
177 int max_write_time_bytes_ = -1;
178 int max_write_time_messages_ = -1;
179 std::chrono::nanoseconds total_write_time_ = std::chrono::nanoseconds::zero();
180 int total_write_count_ = 0;
181 int total_write_messages_ = 0;
182 int total_write_bytes_ = 0;
Austin Schuha36c8902019-12-30 18:07:15 -0800183};
184
185// Packes a message pointed to by the context into a MessageHeader.
186flatbuffers::Offset<MessageHeader> PackMessage(
187 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
188 int channel_index, LogType log_type);
189
Austin Schuhadd6eb32020-11-09 21:24:26 -0800190std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800191 std::string_view filename);
Austin Schuhadd6eb32020-11-09 21:24:26 -0800192std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800193 std::string_view filename, size_t n);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800194
Austin Schuh05b70472020-01-01 17:11:17 -0800195// Class to read chunks out of a log file.
196class SpanReader {
197 public:
198 SpanReader(std::string_view filename);
Austin Schuha36c8902019-12-30 18:07:15 -0800199
Austin Schuh6f3babe2020-01-26 20:34:50 -0800200 std::string_view filename() const { return filename_; }
201
Austin Schuh05b70472020-01-01 17:11:17 -0800202 // Returns a span with the data for a message from the log file, excluding
203 // the size.
204 absl::Span<const uint8_t> ReadMessage();
205
Austin Schuh05b70472020-01-01 17:11:17 -0800206 private:
207 // TODO(austin): Optimization:
208 // Allocate the 256k blocks like we do today. But, refcount them with
209 // shared_ptr pointed to by the messageheader that is returned. This avoids
210 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700211 // And (Brian): Consider just mmapping the file and handing out refcounted
212 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800213
214 // Reads a chunk of data into data_. Returns false if no data was read.
215 bool ReadBlock();
216
Austin Schuhc41603c2020-10-11 16:17:37 -0700217 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800218
Brian Silvermanf51499a2020-09-21 12:49:08 -0700219 // File reader and data decoder.
220 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800221
Brian Silvermanf51499a2020-09-21 12:49:08 -0700222 // Vector to read into.
223 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800224
225 // Amount of data consumed already in data_.
226 size_t consumed_data_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800227};
228
229// Class which handles reading the header and messages from the log file. This
230// handles any per-file state left before merging below.
231class MessageReader {
232 public:
233 MessageReader(std::string_view filename);
234
Austin Schuh6f3babe2020-01-26 20:34:50 -0800235 std::string_view filename() const { return span_reader_.filename(); }
236
Austin Schuh05b70472020-01-01 17:11:17 -0800237 // Returns the header from the log file.
238 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700239 return &raw_log_file_header_.message();
240 }
241
242 // Returns the raw data of the header from the log file.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800243 const SizePrefixedFlatbufferVector<LogFileHeader> &raw_log_file_header()
244 const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700245 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800246 }
247
248 // Returns the minimum maount of data needed to queue up for sorting before
249 // ware guarenteed to not see data out of order.
250 std::chrono::nanoseconds max_out_of_order_duration() const {
251 return max_out_of_order_duration_;
252 }
253
Austin Schuhcde938c2020-02-02 17:30:07 -0800254 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800255 monotonic_clock::time_point newest_timestamp() const {
256 return newest_timestamp_;
257 }
258
259 // Returns the next message if there is one.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800260 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800261
262 // The time at which we need to read another chunk from the logfile.
263 monotonic_clock::time_point queue_data_time() const {
264 return newest_timestamp() - max_out_of_order_duration();
265 }
266
267 private:
268 // Log chunk reader.
269 SpanReader span_reader_;
270
Austin Schuh97789fc2020-08-01 14:42:45 -0700271 // Vector holding the raw data for the log file header.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800272 SizePrefixedFlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800273
274 // Minimum amount of data to queue up for sorting before we are guarenteed
275 // to not see data out of order.
276 std::chrono::nanoseconds max_out_of_order_duration_;
277
278 // Timestamp of the newest message in a channel queue.
279 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
280};
281
Austin Schuhc41603c2020-10-11 16:17:37 -0700282// A class to seamlessly read messages from a list of part files.
283class PartsMessageReader {
284 public:
285 PartsMessageReader(LogParts log_parts);
286
287 std::string_view filename() const { return message_reader_.filename(); }
288
Austin Schuhd2f96102020-12-01 20:27:29 -0800289 // Returns the LogParts that holds the filenames we are reading.
290 const LogParts &parts() const { return parts_; }
291
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800292 const LogFileHeader *log_file_header() const {
293 return message_reader_.log_file_header();
294 }
295
Austin Schuhc41603c2020-10-11 16:17:37 -0700296 // Returns the minimum amount of data needed to queue up for sorting before
297 // we are guarenteed to not see data out of order.
298 std::chrono::nanoseconds max_out_of_order_duration() const {
299 return message_reader_.max_out_of_order_duration();
300 }
301
302 // Returns the newest timestamp read out of the log file.
303 monotonic_clock::time_point newest_timestamp() const {
304 return newest_timestamp_;
305 }
306
307 // Returns the next message if there is one, or nullopt if we have reached the
308 // end of all the files.
309 // Note: reading the next message may change the max_out_of_order_duration().
Austin Schuhadd6eb32020-11-09 21:24:26 -0800310 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadMessage();
Austin Schuhc41603c2020-10-11 16:17:37 -0700311
312 private:
313 // Opens the next log and updates message_reader_. Sets done_ if there is
314 // nothing more to do.
315 void NextLog();
316
317 const LogParts parts_;
318 size_t next_part_index_ = 1u;
319 bool done_ = false;
320 MessageReader message_reader_;
321
Austin Schuh315b96b2020-12-11 21:21:12 -0800322 // True after we have seen a message after the start of the log. The
323 // guarentees on logging essentially are that all data from before the
324 // starting time of the log may be arbitrarily out of order, but once we get
325 // max_out_of_order_duration past the start, everything will remain within
326 // max_out_of_order_duration. We shouldn't see anything before the start
327 // after we've seen a message that is at least max_out_of_order_duration after
328 // the start.
329 bool after_start_ = false;
330
Austin Schuhc41603c2020-10-11 16:17:37 -0700331 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
332};
333
Austin Schuh1be0ce42020-11-29 22:43:26 -0800334// Struct to hold a message as it gets sorted on a single node.
335struct Message {
336 // The channel.
337 uint32_t channel_index = 0xffffffff;
338 // The local queue index.
339 uint32_t queue_index = 0xffffffff;
340 // The local timestamp on the monotonic clock.
341 monotonic_clock::time_point timestamp = monotonic_clock::min_time;
342 // The data (either a timestamp header, or a data header).
343 SizePrefixedFlatbufferVector<MessageHeader> data;
344
345 bool operator<(const Message &m2) const;
346 bool operator>=(const Message &m2) const;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800347 bool operator==(const Message &m2) const;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800348};
349
350std::ostream &operator<<(std::ostream &os, const Message &m);
351
Austin Schuhd2f96102020-12-01 20:27:29 -0800352// Structure to hold a full message and all the timestamps, which may or may not
353// have been sent from a remote node. The remote_queue_index will be invalid if
354// this message is from the point of view of the node which sent it.
355struct TimestampedMessage {
356 uint32_t channel_index = 0xffffffff;
357
358 uint32_t queue_index = 0xffffffff;
359 monotonic_clock::time_point monotonic_event_time = monotonic_clock::min_time;
360 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
361
362 uint32_t remote_queue_index = 0xffffffff;
363 monotonic_clock::time_point monotonic_remote_time = monotonic_clock::min_time;
364 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
365
Austin Schuh8bf1e632021-01-02 22:41:04 -0800366 monotonic_clock::time_point monotonic_timestamp_time =
367 monotonic_clock::min_time;
368
Austin Schuhd2f96102020-12-01 20:27:29 -0800369 SizePrefixedFlatbufferVector<MessageHeader> data;
370};
371
372std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m);
373
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800374// Class to sort the resulting messages from a PartsMessageReader.
375class LogPartsSorter {
376 public:
377 LogPartsSorter(LogParts log_parts);
378
Austin Schuh0ca51f32020-12-25 21:51:45 -0800379 // Returns the parts that this is sorting messages from.
380 const LogParts &parts() const { return parts_message_reader_.parts(); }
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800381
Austin Schuhd2f96102020-12-01 20:27:29 -0800382 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800383 return parts().monotonic_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800384 }
385 realtime_clock::time_point realtime_start_time() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800386 return parts().realtime_start_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800387 }
388
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800389 // The time this data is sorted until.
390 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
391
392 // Returns the next sorted message from the log file. It is safe to call
393 // std::move() on the result to move the data flatbuffer from it.
394 Message *Front();
395 // Pops the front message. This should only be called after a call to
396 // Front().
397 void PopFront();
398
399 // Returns a debug string representing the contents of this sorter.
400 std::string DebugString() const;
401
402 private:
403 // Log parts reader we are wrapping.
404 PartsMessageReader parts_message_reader_;
405 // Cache of the time we are sorted until.
406 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
407
Austin Schuhb000de62020-12-03 22:00:40 -0800408 // Timestamp of the last message returned. Used to make sure nothing goes
409 // backwards.
410 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
411
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800412 // Set used for efficient sorting of messages. We can benchmark and evaluate
413 // other data structures if this proves to be the bottleneck.
414 absl::btree_set<Message> messages_;
415};
416
Austin Schuh8f52ed52020-11-30 23:12:39 -0800417// Class to run merge sort on the messages from multiple LogPartsSorter
418// instances.
419class NodeMerger {
420 public:
Austin Schuhd2f96102020-12-01 20:27:29 -0800421 NodeMerger(std::vector<LogParts> parts);
422
423 // Node index in the configuration of this node.
424 int node() const { return node_; }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800425
Austin Schuh0ca51f32020-12-25 21:51:45 -0800426 // List of parts being sorted together.
427 std::vector<const LogParts *> Parts() const;
428
429 const Configuration *configuration() const {
430 return parts_sorters_[0].parts().config.get();
Austin Schuhd2f96102020-12-01 20:27:29 -0800431 }
432
433 monotonic_clock::time_point monotonic_start_time() const {
434 return monotonic_start_time_;
435 }
436 realtime_clock::time_point realtime_start_time() const {
437 return realtime_start_time_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800438 }
439
440 // The time this data is sorted until.
441 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
442
443 // Returns the next sorted message from the set of log files. It is safe to
444 // call std::move() on the result to move the data flatbuffer from it.
445 Message *Front();
446 // Pops the front message. This should only be called after a call to
447 // Front().
448 void PopFront();
449
450 private:
451 // Unsorted list of all parts sorters.
Austin Schuhd2f96102020-12-01 20:27:29 -0800452 std::vector<LogPartsSorter> parts_sorters_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800453 // Pointer to the parts sorter holding the current Front message if one
454 // exists, or nullptr if a new one needs to be found.
455 LogPartsSorter *current_ = nullptr;
456 // Cached sorted_until value.
457 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800458
459 // Cached node.
460 int node_;
461
Austin Schuhb000de62020-12-03 22:00:40 -0800462 // Timestamp of the last message returned. Used to make sure nothing goes
463 // backwards.
464 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
465
Austin Schuhd2f96102020-12-01 20:27:29 -0800466 realtime_clock::time_point realtime_start_time_ = realtime_clock::max_time;
467 monotonic_clock::time_point monotonic_start_time_ = monotonic_clock::max_time;
468};
469
470// Class to match timestamps with the corresponding data from other nodes.
Austin Schuh79b30942021-01-24 22:32:21 -0800471//
472// This class also buffers data for the node it represents, and supports
473// notifying when new data is queued as well as queueing until a point in time.
Austin Schuhd2f96102020-12-01 20:27:29 -0800474class TimestampMapper {
475 public:
476 TimestampMapper(std::vector<LogParts> file);
477
478 // Copying and moving will mess up the internal raw pointers. Just don't do
479 // it.
480 TimestampMapper(TimestampMapper const &) = delete;
481 TimestampMapper(TimestampMapper &&) = delete;
482 void operator=(TimestampMapper const &) = delete;
483 void operator=(TimestampMapper &&) = delete;
484
485 // TODO(austin): It would be super helpful to provide a way to queue up to
486 // time X without matching timestamps, and to then be able to pull the
487 // timestamps out of this queue. This lets us bootstrap time estimation
488 // without exploding memory usage worst case.
489
Austin Schuh0ca51f32020-12-25 21:51:45 -0800490 std::vector<const LogParts *> Parts() const { return node_merger_.Parts(); }
491
492 const Configuration *configuration() const { return configuration_.get(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800493
494 // Returns which node this is sorting for.
Austin Schuh287d43d2020-12-04 20:19:33 -0800495 size_t node() const { return node_merger_.node(); }
Austin Schuhd2f96102020-12-01 20:27:29 -0800496
497 // The start time of this log.
498 monotonic_clock::time_point monotonic_start_time() const {
499 return node_merger_.monotonic_start_time();
500 }
501 realtime_clock::time_point realtime_start_time() const {
502 return node_merger_.realtime_start_time();
503 }
504
505 // Uses timestamp_mapper as the peer for its node. Only one mapper may be set
506 // for each node. Peers are used to look up the data for timestamps on this
507 // node.
508 void AddPeer(TimestampMapper *timestamp_mapper);
509
510 // Time that we are sorted until internally.
511 monotonic_clock::time_point sorted_until() const {
512 return node_merger_.sorted_until();
513 }
514
515 // Returns the next message for this node.
516 TimestampedMessage *Front();
517 // Pops the next message. Front must be called first.
518 void PopFront();
519
520 // Returns debug information about this node.
521 std::string DebugString() const;
522
Austin Schuh79b30942021-01-24 22:32:21 -0800523 // Queues data the provided time.
524 void QueueUntil(monotonic_clock::time_point queue_time);
Austin Schuhe639ea12021-01-25 13:00:22 -0800525 // Queues until we have time_estimation_buffer of data in the queue.
526 void QueueFor(std::chrono::nanoseconds time_estimation_buffer);
Austin Schuh79b30942021-01-24 22:32:21 -0800527
Austin Schuh06601222021-01-26 17:02:50 -0800528 // Queues until the condition is met.
529 template <typename T>
530 void QueueUntilCondition(T fn) {
531 while (true) {
532 if (fn()) {
533 break;
534 }
535 if (!QueueMatched()) {
536 break;
537 }
538 }
539 }
540
Austin Schuh79b30942021-01-24 22:32:21 -0800541 // Sets a callback to be called whenever a full message is queued.
542 void set_timestamp_callback(std::function<void(TimestampedMessage *)> fn) {
543 timestamp_callback_ = fn;
544 }
545
Austin Schuhd2f96102020-12-01 20:27:29 -0800546 private:
547 // The state for a remote node. This holds the data that needs to be matched
548 // with the remote node's timestamps.
549 struct NodeData {
550 // True if we should save data here. This should be true if any of the
551 // bools in delivered below are true.
552 bool any_delivered = false;
553
554 // Peer pointer. This node is only to be considered if a peer is set.
555 TimestampMapper *peer = nullptr;
556
557 struct ChannelData {
558 // Deque per channel. This contains the data from the outside
559 // TimestampMapper node which is relevant for the node this NodeData
560 // points to.
561 std::deque<Message> messages;
562 // Bool tracking per channel if a message is delivered to the node this
563 // NodeData represents.
564 bool delivered = false;
565 };
566
567 // Vector with per channel data.
568 std::vector<ChannelData> channels;
569 };
570
571 // Returns (and forgets about) the data for the provided timestamp message
572 // showing when it was delivered to this node.
573 Message MatchingMessageFor(const Message &message);
574
575 // Queues up a single message into our message queue, and any nodes that this
576 // message is delivered to. Returns true if one was available, false
577 // otherwise.
578 bool Queue();
579
Austin Schuh79b30942021-01-24 22:32:21 -0800580 // Queues up a single matched message into our matched message queue. Returns
581 // true if one was queued, and false otherwise.
582 bool QueueMatched();
583
Austin Schuhd2f96102020-12-01 20:27:29 -0800584 // Queues up data until we have at least one message >= to time t.
585 // Useful for triggering a remote node to read enough data to have the
586 // timestamp you care about available.
Austin Schuh79b30942021-01-24 22:32:21 -0800587 void QueueUnmatchedUntil(monotonic_clock::time_point t);
Austin Schuhd2f96102020-12-01 20:27:29 -0800588
Austin Schuh79b30942021-01-24 22:32:21 -0800589 // Queues m into matched_messages_.
590 void QueueMessage(Message *m);
Austin Schuhd2f96102020-12-01 20:27:29 -0800591
592 // The node merger to source messages from.
593 NodeMerger node_merger_;
Austin Schuh0ca51f32020-12-25 21:51:45 -0800594
595 std::shared_ptr<const Configuration> configuration_;
596
Austin Schuhd2f96102020-12-01 20:27:29 -0800597 // The buffer of messages for this node. These are not matched with any
598 // remote data.
599 std::deque<Message> messages_;
600 // The node index for the source node for each channel.
601 std::vector<size_t> source_node_;
602
603 // Vector per node. Not all nodes will have anything.
604 std::vector<NodeData> nodes_data_;
605
606 // Latest message to return.
Austin Schuh79b30942021-01-24 22:32:21 -0800607 std::deque<TimestampedMessage> matched_messages_;
Austin Schuhd2f96102020-12-01 20:27:29 -0800608
Austin Schuh79b30942021-01-24 22:32:21 -0800609 // Tracks the state of the first message in matched_messages_. Do we need to
610 // update it, is it valid, or should we return nullptr?
Austin Schuhd2f96102020-12-01 20:27:29 -0800611 enum class FirstMessage {
612 kNeedsUpdate,
613 kInMessage,
614 kNullptr,
615 };
616 FirstMessage first_message_ = FirstMessage::kNeedsUpdate;
617
618 // Timestamp of the last message returned. Used to make sure nothing goes
619 // backwards.
620 monotonic_clock::time_point last_message_time_ = monotonic_clock::min_time;
621 // Time this node is queued up until. Used for caching.
622 monotonic_clock::time_point queued_until_ = monotonic_clock::min_time;
Austin Schuh79b30942021-01-24 22:32:21 -0800623
624 std::function<void(TimestampedMessage *)> timestamp_callback_;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800625};
626
Austin Schuhee711052020-08-24 16:06:09 -0700627// Returns the node name with a trailing space, or an empty string if we are on
628// a single node.
629std::string MaybeNodeName(const Node *);
630
Brian Silvermanf51499a2020-09-21 12:49:08 -0700631} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -0800632
633#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_