blob: d0afdc9adf27bb877778eec111170a3f33df0f2d [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.
110 size_t total_bytes() const { return encoder_->total_bytes(); }
Austin Schuha36c8902019-12-30 18:07:15 -0800111
Brian Silvermanf51499a2020-09-21 12:49:08 -0700112 // The maximum time for a single write call, or 0 if none have been performed.
113 std::chrono::nanoseconds max_write_time() const { return max_write_time_; }
114 // The number of bytes in the longest write call, or -1 if none have been
115 // performed.
116 int max_write_time_bytes() const { return max_write_time_bytes_; }
117 // The number of buffers in the longest write call, or -1 if none have been
118 // performed.
119 int max_write_time_messages() const { return max_write_time_messages_; }
120 // The total time spent in write calls.
121 std::chrono::nanoseconds total_write_time() const {
122 return total_write_time_;
123 }
124 // The total number of writes which have been performed.
125 int total_write_count() const { return total_write_count_; }
126 // The total number of messages which have been written.
127 int total_write_messages() const { return total_write_messages_; }
128 // The total number of bytes which have been written.
129 int total_write_bytes() const { return total_write_bytes_; }
130 void ResetStatistics() {
131 max_write_time_ = std::chrono::nanoseconds::zero();
132 max_write_time_bytes_ = -1;
133 max_write_time_messages_ = -1;
134 total_write_time_ = std::chrono::nanoseconds::zero();
135 total_write_count_ = 0;
136 total_write_messages_ = 0;
137 total_write_bytes_ = 0;
138 }
Brian Silverman98360e22020-04-28 16:51:20 -0700139
Austin Schuha36c8902019-12-30 18:07:15 -0800140 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700141 // Performs a single writev call with as much of the data we have queued up as
142 // possible.
143 //
144 // This will normally take all of the data we have queued up, unless an
145 // encoder has spit out a big enough chunk all at once that we can't manage
146 // all of it.
147 void Flush();
148
Brian Silverman0465fcf2020-09-24 00:29:18 -0700149 // write_return is what write(2) or writev(2) returned. write_size is the
150 // number of bytes we expected it to write.
151 void HandleWriteReturn(ssize_t write_return, size_t write_size);
152
Brian Silvermanf51499a2020-09-21 12:49:08 -0700153 void UpdateStatsForWrite(aos::monotonic_clock::duration duration,
154 ssize_t written, int iovec_size);
155
156 // Flushes data if we've reached the threshold to do that as part of normal
157 // operation.
158 void FlushAtThreshold();
159
Austin Schuh2f8fd752020-09-01 22:38:28 -0700160 std::string filename_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700161 std::unique_ptr<DetachedBufferEncoder> 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 Schuha36c8902019-12-30 18:07:15 -0800178};
179
180// Packes a message pointed to by the context into a MessageHeader.
181flatbuffers::Offset<MessageHeader> PackMessage(
182 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
183 int channel_index, LogType log_type);
184
Austin Schuhadd6eb32020-11-09 21:24:26 -0800185std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800186 std::string_view filename);
Austin Schuhadd6eb32020-11-09 21:24:26 -0800187std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800188 std::string_view filename, size_t n);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800189
Austin Schuh05b70472020-01-01 17:11:17 -0800190// Class to read chunks out of a log file.
191class SpanReader {
192 public:
193 SpanReader(std::string_view filename);
Austin Schuha36c8902019-12-30 18:07:15 -0800194
Austin Schuh6f3babe2020-01-26 20:34:50 -0800195 std::string_view filename() const { return filename_; }
196
Austin Schuh05b70472020-01-01 17:11:17 -0800197 // Returns a span with the data for a message from the log file, excluding
198 // the size.
199 absl::Span<const uint8_t> ReadMessage();
200
Austin Schuh05b70472020-01-01 17:11:17 -0800201 private:
202 // TODO(austin): Optimization:
203 // Allocate the 256k blocks like we do today. But, refcount them with
204 // shared_ptr pointed to by the messageheader that is returned. This avoids
205 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700206 // And (Brian): Consider just mmapping the file and handing out refcounted
207 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800208
209 // Reads a chunk of data into data_. Returns false if no data was read.
210 bool ReadBlock();
211
Austin Schuhc41603c2020-10-11 16:17:37 -0700212 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800213
Brian Silvermanf51499a2020-09-21 12:49:08 -0700214 // File reader and data decoder.
215 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800216
Brian Silvermanf51499a2020-09-21 12:49:08 -0700217 // Vector to read into.
218 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800219
220 // Amount of data consumed already in data_.
221 size_t consumed_data_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800222};
223
224// Class which handles reading the header and messages from the log file. This
225// handles any per-file state left before merging below.
226class MessageReader {
227 public:
228 MessageReader(std::string_view filename);
229
Austin Schuh6f3babe2020-01-26 20:34:50 -0800230 std::string_view filename() const { return span_reader_.filename(); }
231
Austin Schuh05b70472020-01-01 17:11:17 -0800232 // Returns the header from the log file.
233 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700234 return &raw_log_file_header_.message();
235 }
236
237 // Returns the raw data of the header from the log file.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800238 const SizePrefixedFlatbufferVector<LogFileHeader> &raw_log_file_header()
239 const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700240 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800241 }
242
243 // Returns the minimum maount of data needed to queue up for sorting before
244 // ware guarenteed to not see data out of order.
245 std::chrono::nanoseconds max_out_of_order_duration() const {
246 return max_out_of_order_duration_;
247 }
248
Austin Schuhcde938c2020-02-02 17:30:07 -0800249 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800250 monotonic_clock::time_point newest_timestamp() const {
251 return newest_timestamp_;
252 }
253
254 // Returns the next message if there is one.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800255 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800256
257 // The time at which we need to read another chunk from the logfile.
258 monotonic_clock::time_point queue_data_time() const {
259 return newest_timestamp() - max_out_of_order_duration();
260 }
261
262 private:
263 // Log chunk reader.
264 SpanReader span_reader_;
265
Austin Schuh97789fc2020-08-01 14:42:45 -0700266 // Vector holding the raw data for the log file header.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800267 SizePrefixedFlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800268
269 // Minimum amount of data to queue up for sorting before we are guarenteed
270 // to not see data out of order.
271 std::chrono::nanoseconds max_out_of_order_duration_;
272
273 // Timestamp of the newest message in a channel queue.
274 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
275};
276
Austin Schuhc41603c2020-10-11 16:17:37 -0700277// A class to seamlessly read messages from a list of part files.
278class PartsMessageReader {
279 public:
280 PartsMessageReader(LogParts log_parts);
281
282 std::string_view filename() const { return message_reader_.filename(); }
283
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800284 const LogFileHeader *log_file_header() const {
285 return message_reader_.log_file_header();
286 }
287
Austin Schuhc41603c2020-10-11 16:17:37 -0700288 // Returns the minimum amount of data needed to queue up for sorting before
289 // we are guarenteed to not see data out of order.
290 std::chrono::nanoseconds max_out_of_order_duration() const {
291 return message_reader_.max_out_of_order_duration();
292 }
293
294 // Returns the newest timestamp read out of the log file.
295 monotonic_clock::time_point newest_timestamp() const {
296 return newest_timestamp_;
297 }
298
299 // Returns the next message if there is one, or nullopt if we have reached the
300 // end of all the files.
301 // Note: reading the next message may change the max_out_of_order_duration().
Austin Schuhadd6eb32020-11-09 21:24:26 -0800302 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadMessage();
Austin Schuhc41603c2020-10-11 16:17:37 -0700303
304 private:
305 // Opens the next log and updates message_reader_. Sets done_ if there is
306 // nothing more to do.
307 void NextLog();
308
309 const LogParts parts_;
310 size_t next_part_index_ = 1u;
311 bool done_ = false;
312 MessageReader message_reader_;
313
314 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
315};
316
Austin Schuh1be0ce42020-11-29 22:43:26 -0800317// Struct to hold a message as it gets sorted on a single node.
318struct Message {
319 // The channel.
320 uint32_t channel_index = 0xffffffff;
321 // The local queue index.
322 uint32_t queue_index = 0xffffffff;
323 // The local timestamp on the monotonic clock.
324 monotonic_clock::time_point timestamp = monotonic_clock::min_time;
325 // The data (either a timestamp header, or a data header).
326 SizePrefixedFlatbufferVector<MessageHeader> data;
327
328 bool operator<(const Message &m2) const;
329 bool operator>=(const Message &m2) const;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800330 bool operator==(const Message &m2) const;
Austin Schuh1be0ce42020-11-29 22:43:26 -0800331};
332
333std::ostream &operator<<(std::ostream &os, const Message &m);
334
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800335// Class to sort the resulting messages from a PartsMessageReader.
336class LogPartsSorter {
337 public:
338 LogPartsSorter(LogParts log_parts);
339
340 // Returns the current log file header.
341 // TODO(austin): Is this the header we want to report? Do we want a better
342 // start time?
343 // TODO(austin): Report a start time from the LogParts. Figure out how that
344 // all works.
345 const LogFileHeader *log_file_header() const {
346 return parts_message_reader_.log_file_header();
347 }
348
349 // The time this data is sorted until.
350 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
351
352 // Returns the next sorted message from the log file. It is safe to call
353 // std::move() on the result to move the data flatbuffer from it.
354 Message *Front();
355 // Pops the front message. This should only be called after a call to
356 // Front().
357 void PopFront();
358
359 // Returns a debug string representing the contents of this sorter.
360 std::string DebugString() const;
361
362 private:
363 // Log parts reader we are wrapping.
364 PartsMessageReader parts_message_reader_;
365 // Cache of the time we are sorted until.
366 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
367
368 // Set used for efficient sorting of messages. We can benchmark and evaluate
369 // other data structures if this proves to be the bottleneck.
370 absl::btree_set<Message> messages_;
371};
372
Austin Schuh8f52ed52020-11-30 23:12:39 -0800373// Class to run merge sort on the messages from multiple LogPartsSorter
374// instances.
375class NodeMerger {
376 public:
377 NodeMerger(std::vector<std::unique_ptr<LogPartsSorter>> parts);
378
379 // The log file header for one of the log files.
380 const LogFileHeader *log_file_header() const {
381 CHECK(!parts_sorters_.empty());
382 return parts_sorters_[0]->log_file_header();
383 }
384
385 // The time this data is sorted until.
386 monotonic_clock::time_point sorted_until() const { return sorted_until_; }
387
388 // Returns the next sorted message from the set of log files. It is safe to
389 // call std::move() on the result to move the data flatbuffer from it.
390 Message *Front();
391 // Pops the front message. This should only be called after a call to
392 // Front().
393 void PopFront();
394
395 private:
396 // Unsorted list of all parts sorters.
397 std::vector<std::unique_ptr<LogPartsSorter>> parts_sorters_;
398 // Pointer to the parts sorter holding the current Front message if one
399 // exists, or nullptr if a new one needs to be found.
400 LogPartsSorter *current_ = nullptr;
401 // Cached sorted_until value.
402 aos::monotonic_clock::time_point sorted_until_ = monotonic_clock::min_time;
403};
404
Austin Schuh6f3babe2020-01-26 20:34:50 -0800405class TimestampMerger;
Austin Schuh05b70472020-01-01 17:11:17 -0800406
Austin Schuh6f3babe2020-01-26 20:34:50 -0800407// A design requirement is that the relevant data for a channel is not more than
408// max_out_of_order_duration out of order. We approach sorting in layers.
409//
410// 1) Split each (maybe chunked) log file into one queue per channel. Read this
411// log file looking for data pertaining to a specific node.
412// (SplitMessageReader)
413// 2) Merge all the data per channel from the different log files into a sorted
414// list of timestamps and messages. (TimestampMerger)
415// 3) Combine the timestamps and messages. (TimestampMerger)
416// 4) Merge all the channels to produce the next message on a node.
417// (ChannelMerger)
418// 5) Duplicate this entire stack per node.
419
420// This class splits messages and timestamps up into a queue per channel, and
421// handles reading data from multiple chunks.
422class SplitMessageReader {
423 public:
424 SplitMessageReader(const std::vector<std::string> &filenames);
425
426 // Sets the TimestampMerger that gets notified for each channel. The node
427 // that the TimestampMerger is merging as needs to be passed in.
428 void SetTimestampMerger(TimestampMerger *timestamp_merger, int channel,
429 const Node *target_node);
430
Austin Schuh2f8fd752020-09-01 22:38:28 -0700431 // Returns the (timestamp, queue_index, message_header) for the oldest message
432 // in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800433 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
434 oldest_message(int channel) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800435 return channels_[channel].data.front_timestamp();
436 }
437
Austin Schuh2f8fd752020-09-01 22:38:28 -0700438 // Returns the (timestamp, queue_index, message_header) for the oldest
439 // delivery time in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800440 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
441 oldest_message(int channel, int destination_node) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800442 return channels_[channel].timestamps[destination_node].front_timestamp();
443 }
444
445 // Returns the timestamp, queue_index, and message for the oldest data on a
446 // channel. Requeues data as needed.
447 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800448 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -0800449 PopOldest(int channel_index);
450
451 // Returns the timestamp, queue_index, and message for the oldest timestamp on
452 // a channel delivered to a node. Requeues data as needed.
453 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800454 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -0700455 PopOldestTimestamp(int channel, int node_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800456
457 // Returns the header for the log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800458 const LogFileHeader *log_file_header() const {
Austin Schuhfa895892020-01-07 20:07:41 -0800459 return &log_file_header_.message();
Austin Schuh05b70472020-01-01 17:11:17 -0800460 }
461
Austin Schuhadd6eb32020-11-09 21:24:26 -0800462 const SizePrefixedFlatbufferVector<LogFileHeader> &raw_log_file_header()
463 const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700464 return log_file_header_;
465 }
466
Austin Schuh6f3babe2020-01-26 20:34:50 -0800467 // Returns the starting time for this set of log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800468 monotonic_clock::time_point monotonic_start_time() {
469 return monotonic_clock::time_point(
470 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
471 }
472 realtime_clock::time_point realtime_start_time() {
473 return realtime_clock::time_point(
474 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
475 }
476
Austin Schuh6f3babe2020-01-26 20:34:50 -0800477 // Returns the configuration from the log file header.
478 const Configuration *configuration() const {
479 return log_file_header()->configuration();
480 }
481
Austin Schuh05b70472020-01-01 17:11:17 -0800482 // Returns the node who's point of view this log file is from. Make sure this
483 // is a pointer in the configuration() nodes list so it can be consumed
484 // elsewhere.
485 const Node *node() const {
486 if (configuration()->has_nodes()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800487 return configuration::GetNodeOrDie(configuration(),
488 log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800489 } else {
490 CHECK(!log_file_header()->has_node());
491 return nullptr;
492 }
493 }
494
Austin Schuh6f3babe2020-01-26 20:34:50 -0800495 // Returns the timestamp of the newest message read from the log file, and the
496 // timestamp that we need to re-queue data.
497 monotonic_clock::time_point newest_timestamp() const {
Austin Schuhcde938c2020-02-02 17:30:07 -0800498 return newest_timestamp_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800499 }
500
Austin Schuhcde938c2020-02-02 17:30:07 -0800501 // Returns the next time to trigger a requeue.
502 monotonic_clock::time_point time_to_queue() const { return time_to_queue_; }
503
504 // Returns the minimum amount of data needed to queue up for sorting before
Austin Schuhc41603c2020-10-11 16:17:37 -0700505 // we are guarenteed to not see data out of order.
Austin Schuhcde938c2020-02-02 17:30:07 -0800506 std::chrono::nanoseconds max_out_of_order_duration() const {
507 return message_reader_->max_out_of_order_duration();
508 }
509
510 std::string_view filename() const { return message_reader_->filename(); }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800511
512 // Adds more messages to the sorted list. This reads enough data such that
513 // oldest_message_time can be replayed safely. Returns false if the log file
514 // has all been read.
515 bool QueueMessages(monotonic_clock::time_point oldest_message_time);
Austin Schuh05b70472020-01-01 17:11:17 -0800516
Austin Schuhcde938c2020-02-02 17:30:07 -0800517 // Returns debug strings for a channel, and timestamps for a node.
518 std::string DebugString(int channel) const;
519 std::string DebugString(int channel, int node_index) const;
520
Austin Schuh8bd96322020-02-13 21:18:22 -0800521 // Returns true if all the messages have been queued from the last log file in
522 // the list of log files chunks.
523 bool at_end() const { return at_end_; }
524
Austin Schuh05b70472020-01-01 17:11:17 -0800525 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800526 // TODO(austin): Need to copy or refcount the message instead of running
527 // multiple copies of the reader. Or maybe have a "as_node" index and hide it
528 // inside.
529
Austin Schuhfa895892020-01-07 20:07:41 -0800530 // Moves to the next log file in the list.
531 bool NextLogFile();
532
Austin Schuh6f3babe2020-01-26 20:34:50 -0800533 // Filenames of the log files.
534 std::vector<std::string> filenames_;
535 // And the index of the next file to open.
536 size_t next_filename_index_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800537
Austin Schuhee711052020-08-24 16:06:09 -0700538 // Node we are reading as.
539 const Node *target_node_ = nullptr;
540
Austin Schuh6f3babe2020-01-26 20:34:50 -0800541 // Log file header to report. This is a copy.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800542 SizePrefixedFlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800543 // Current log file being read.
544 std::unique_ptr<MessageReader> message_reader_;
Austin Schuh05b70472020-01-01 17:11:17 -0800545
546 // Datastructure to hold the list of messages, cached timestamp for the
547 // oldest message, and sender to send with.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800548 struct MessageHeaderQueue {
549 // If true, this is a timestamp queue.
550 bool timestamps = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800551
Austin Schuh6f3babe2020-01-26 20:34:50 -0800552 // Returns a reference to the the oldest message.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800553 SizePrefixedFlatbufferVector<MessageHeader> &front() {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800554 CHECK_GT(data_.size(), 0u);
555 return data_.front();
Austin Schuh05b70472020-01-01 17:11:17 -0800556 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800557
Austin Schuhcde938c2020-02-02 17:30:07 -0800558 // Adds a message to the back of the queue. Returns true if it was actually
559 // emplaced.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800560 bool emplace_back(SizePrefixedFlatbufferVector<MessageHeader> &&msg);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800561
562 // Drops the front message. Invalidates the front() reference.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700563 void PopFront();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800564
565 // The size of the queue.
566 size_t size() { return data_.size(); }
567
Austin Schuhcde938c2020-02-02 17:30:07 -0800568 // Returns a debug string with info about each message in the queue.
569 std::string DebugString() const;
570
Austin Schuh2f8fd752020-09-01 22:38:28 -0700571 // Returns the (timestamp, queue_index, message_header) for the oldest
572 // message.
Austin Schuhcde938c2020-02-02 17:30:07 -0800573 const std::tuple<monotonic_clock::time_point, uint32_t,
574 const MessageHeader *>
575 front_timestamp() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700576 const MessageHeader &message = front().message();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800577 return std::make_tuple(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700578 monotonic_clock::time_point(
579 std::chrono::nanoseconds(message.monotonic_sent_time())),
580 message.queue_index(), &message);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800581 }
582
583 // Pointer to the timestamp merger for this queue if available.
584 TimestampMerger *timestamp_merger = nullptr;
585 // Pointer to the reader which feeds this queue.
586 SplitMessageReader *split_reader = nullptr;
587
588 private:
589 // The data.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800590 std::deque<SizePrefixedFlatbufferVector<MessageHeader>> data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800591 };
592
Austin Schuh6f3babe2020-01-26 20:34:50 -0800593 // All the queues needed for a channel. There isn't going to be data in all
594 // of these.
595 struct ChannelData {
596 // The data queue for the channel.
597 MessageHeaderQueue data;
598 // Queues for timestamps for each node.
599 std::vector<MessageHeaderQueue> timestamps;
600 };
Austin Schuhfa895892020-01-07 20:07:41 -0800601
Austin Schuh6f3babe2020-01-26 20:34:50 -0800602 // Data for all the channels.
Austin Schuh05b70472020-01-01 17:11:17 -0800603 std::vector<ChannelData> channels_;
604
Austin Schuh6f3babe2020-01-26 20:34:50 -0800605 // Once we know the node that this SplitMessageReader will be writing as,
606 // there will be only one MessageHeaderQueue that a specific channel matches.
607 // Precompute this here for efficiency.
608 std::vector<MessageHeaderQueue *> channels_to_write_;
609
Austin Schuhcde938c2020-02-02 17:30:07 -0800610 monotonic_clock::time_point time_to_queue_ = monotonic_clock::min_time;
611
612 // Latches true when we hit the end of the last log file and there is no sense
613 // poking it further.
614 bool at_end_ = false;
615
616 // Timestamp of the newest message that was read and actually queued. We want
617 // to track this independently from the log file because we need the
618 // timestamps here to be timestamps of messages that are queued.
619 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800620};
621
622class ChannelMerger;
623
624// Sorts channels (and timestamps) from multiple log files for a single channel.
625class TimestampMerger {
626 public:
627 TimestampMerger(const Configuration *configuration,
628 std::vector<SplitMessageReader *> split_message_readers,
629 int channel_index, const Node *target_node,
630 ChannelMerger *channel_merger);
631
632 // Metadata used to schedule the message.
633 struct DeliveryTimestamp {
634 monotonic_clock::time_point monotonic_event_time =
635 monotonic_clock::min_time;
636 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700637 uint32_t queue_index = 0xffffffff;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800638
639 monotonic_clock::time_point monotonic_remote_time =
640 monotonic_clock::min_time;
641 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
642 uint32_t remote_queue_index = 0xffffffff;
643 };
644
645 // Pushes SplitMessageReader onto the timestamp heap. This should only be
646 // called when timestamps are placed in the channel this class is merging for
647 // the reader.
648 void UpdateTimestamp(
649 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800650 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
651 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800652 PushTimestampHeap(oldest_message_time, split_message_reader);
653 }
654 // Pushes SplitMessageReader onto the message heap. This should only be
655 // called when data is placed in the channel this class is merging for the
656 // reader.
657 void Update(
658 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800659 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
660 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800661 PushMessageHeap(oldest_message_time, split_message_reader);
662 }
663
Austin Schuhcde938c2020-02-02 17:30:07 -0800664 // Returns the oldest combined timestamp and data for this channel. If there
665 // isn't a matching piece of data, returns only the timestamp with no data.
666 // The caller can determine what the appropriate action is to recover.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800667 std::tuple<DeliveryTimestamp, SizePrefixedFlatbufferVector<MessageHeader>>
668 PopOldest();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800669
670 // Tracks if the channel merger has pushed this onto it's heap or not.
671 bool pushed() { return pushed_; }
672 // Sets if this has been pushed to the channel merger heap. Should only be
673 // called by the channel merger.
674 void set_pushed(bool pushed) { pushed_ = pushed; }
675
Austin Schuhcde938c2020-02-02 17:30:07 -0800676 // Returns a debug string with the heaps printed out.
677 std::string DebugString() const;
678
Austin Schuh8bd96322020-02-13 21:18:22 -0800679 // Returns true if we have timestamps.
680 bool has_timestamps() const { return has_timestamps_; }
681
682 // Records that one of the log files ran out of data. This should only be
683 // called by a SplitMessageReader.
684 void NoticeAtEnd();
685
Austin Schuh2f8fd752020-09-01 22:38:28 -0700686 aos::monotonic_clock::time_point channel_merger_time() {
687 if (has_timestamps_) {
688 return std::get<0>(timestamp_heap_[0]);
689 } else {
690 return std::get<0>(message_heap_[0]);
691 }
692 }
693
Austin Schuh6f3babe2020-01-26 20:34:50 -0800694 private:
695 // Pushes messages and timestamps to the corresponding heaps.
696 void PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800697 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
698 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800699 SplitMessageReader *split_message_reader);
700 void PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800701 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
702 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800703 SplitMessageReader *split_message_reader);
704
705 // Pops a message from the message heap. This automatically triggers the
706 // split message reader to re-fetch any new data.
707 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800708 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -0800709 PopMessageHeap();
Austin Schuhcde938c2020-02-02 17:30:07 -0800710
711 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
712 oldest_message() const;
713 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
714 oldest_timestamp() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800715 // Pops a message from the timestamp heap. This automatically triggers the
716 // split message reader to re-fetch any new data.
717 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800718 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -0800719 PopTimestampHeap();
720
721 const Configuration *configuration_;
722
723 // If true, this is a forwarded channel and timestamps should be matched.
724 bool has_timestamps_ = false;
725
726 // Tracks if the ChannelMerger has pushed this onto it's queue.
727 bool pushed_ = false;
728
729 // The split message readers used for source data.
730 std::vector<SplitMessageReader *> split_message_readers_;
731
732 // The channel to merge.
733 int channel_index_;
734
735 // Our node.
736 int node_index_;
737
738 // Heaps for messages and timestamps.
739 std::vector<
740 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
741 message_heap_;
742 std::vector<
743 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
744 timestamp_heap_;
745
746 // Parent channel merger.
747 ChannelMerger *channel_merger_;
748};
749
750// This class handles constructing all the split message readers, channel
751// mergers, and combining the results.
752class ChannelMerger {
753 public:
754 // Builds a ChannelMerger around a set of log files. These are of the format:
755 // {
756 // {log1_part0, log1_part1, ...},
757 // {log2}
758 // }
759 // The inner vector is a list of log file chunks which form up a log file.
760 // The outer vector is a list of log files with subsets of the messages, or
761 // messages from different nodes.
762 ChannelMerger(const std::vector<std::vector<std::string>> &filenames);
763
764 // Returns the nodes that we know how to merge.
765 const std::vector<const Node *> nodes() const;
766 // Sets the node that we will return messages as. Returns true if the node
767 // has log files and will produce data. This can only be called once, and
768 // will likely corrupt state if called a second time.
769 bool SetNode(const Node *target_node);
770
771 // Everything else needs the node set before it works.
772
773 // Returns a timestamp for the oldest message in this group of logfiles.
Austin Schuh858c9f32020-08-31 16:56:12 -0700774 monotonic_clock::time_point OldestMessageTime() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800775 // Pops the oldest message.
776 std::tuple<TimestampMerger::DeliveryTimestamp, int,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800777 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -0800778 PopOldest();
779
780 // Returns the config for this set of log files.
781 const Configuration *configuration() const {
782 return log_file_header()->configuration();
783 }
784
785 const LogFileHeader *log_file_header() const {
786 return &log_file_header_.message();
787 }
788
789 // Returns the start times for the configured node's log files.
Austin Schuhcde938c2020-02-02 17:30:07 -0800790 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800791 return monotonic_clock::time_point(
792 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
793 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800794 realtime_clock::time_point realtime_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800795 return realtime_clock::time_point(
796 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
797 }
798
799 // Returns the node set by SetNode above.
800 const Node *node() const { return node_; }
801
802 // Called by the TimestampMerger when new data is available with the provided
803 // timestamp and channel_index.
804 void Update(monotonic_clock::time_point timestamp, int channel_index) {
805 PushChannelHeap(timestamp, channel_index);
806 }
807
Austin Schuhcde938c2020-02-02 17:30:07 -0800808 // Returns a debug string with all the heaps in it. Generally only useful for
809 // debugging what went wrong.
810 std::string DebugString() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800811
Austin Schuh8bd96322020-02-13 21:18:22 -0800812 // Returns true if one of the log files has finished reading everything. When
813 // log file chunks are involved, this means that the last chunk in a log file
814 // has been read. It is acceptable to be missing data at this point in time.
815 bool at_end() const { return at_end_; }
816
817 // Marks that one of the log files is at the end. This should only be called
818 // by timestamp mergers.
819 void NoticeAtEnd() { at_end_ = true; }
820
Austin Schuhcde938c2020-02-02 17:30:07 -0800821 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800822 // Pushes the timestamp for new data on the provided channel.
823 void PushChannelHeap(monotonic_clock::time_point timestamp,
824 int channel_index);
825
Austin Schuh2f8fd752020-09-01 22:38:28 -0700826 // CHECKs that channel_heap_ and timestamp_heap_ are valid heaps.
827 void VerifyHeaps();
828
Austin Schuh6f3babe2020-01-26 20:34:50 -0800829 // All the message readers.
830 std::vector<std::unique_ptr<SplitMessageReader>> split_message_readers_;
831
832 // The log header we are claiming to be.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800833 SizePrefixedFlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800834
835 // The timestamp mergers which combine data from the split message readers.
836 std::vector<TimestampMerger> timestamp_mergers_;
837
838 // A heap of the channel readers and timestamps for the oldest data in each.
Austin Schuh05b70472020-01-01 17:11:17 -0800839 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap_;
840
Austin Schuh6f3babe2020-01-26 20:34:50 -0800841 // Configured node.
842 const Node *node_;
843
Austin Schuh8bd96322020-02-13 21:18:22 -0800844 bool at_end_ = false;
845
Austin Schuh6f3babe2020-01-26 20:34:50 -0800846 // Cached copy of the list of nodes.
847 std::vector<const Node *> nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700848
849 // Last time popped. Used to detect events being returned out of order.
850 monotonic_clock::time_point last_popped_time_ = monotonic_clock::min_time;
Austin Schuh05b70472020-01-01 17:11:17 -0800851};
Austin Schuha36c8902019-12-30 18:07:15 -0800852
Austin Schuhee711052020-08-24 16:06:09 -0700853// Returns the node name with a trailing space, or an empty string if we are on
854// a single node.
855std::string MaybeNodeName(const Node *);
856
Brian Silvermanf51499a2020-09-21 12:49:08 -0700857} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -0800858
859#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_