blob: 12d7cac6cb7e55a5e34f765497ec5a541d20af8a [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 Schuh05b70472020-01-01 17:11:17 -080017#include "absl/types/span.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070018#include "aos/containers/resizeable_buffer.h"
Austin Schuha36c8902019-12-30 18:07:15 -080019#include "aos/events/event_loop.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070020#include "aos/events/logging/buffer_encoder.h"
Austin Schuhc41603c2020-10-11 16:17:37 -070021#include "aos/events/logging/logfile_sorting.h"
Austin Schuha36c8902019-12-30 18:07:15 -080022#include "aos/events/logging/logger_generated.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070023#include "aos/flatbuffers.h"
Austin Schuha36c8902019-12-30 18:07:15 -080024#include "flatbuffers/flatbuffers.h"
25
Brian Silvermanf51499a2020-09-21 12:49:08 -070026namespace aos::logger {
Austin Schuha36c8902019-12-30 18:07:15 -080027
28enum class LogType : uint8_t {
29 // The message originated on this node and should be logged here.
30 kLogMessage,
31 // The message originated on another node, but only the delivery times are
32 // logged here.
33 kLogDeliveryTimeOnly,
34 // The message originated on another node. Log it and the delivery times
35 // together. The message_gateway is responsible for logging any messages
36 // which didn't get delivered.
Austin Schuh6f3babe2020-01-26 20:34:50 -080037 kLogMessageAndDeliveryTime,
38 // The message originated on the other node and should be logged on this node.
39 kLogRemoteMessage
Austin Schuha36c8902019-12-30 18:07:15 -080040};
41
Austin Schuha36c8902019-12-30 18:07:15 -080042// This class manages efficiently writing a sequence of detached buffers to a
Brian Silvermanf51499a2020-09-21 12:49:08 -070043// file. It encodes them, queues them up, and batches the write operation.
Austin Schuha36c8902019-12-30 18:07:15 -080044class DetachedBufferWriter {
45 public:
Brian Silvermana9f2ec92020-10-06 18:00:53 -070046 // Marker struct for one of our constructor overloads.
47 struct already_out_of_space_t {};
48
Brian Silvermanf51499a2020-09-21 12:49:08 -070049 DetachedBufferWriter(std::string_view filename,
50 std::unique_ptr<DetachedBufferEncoder> encoder);
Brian Silvermana9f2ec92020-10-06 18:00:53 -070051 // Creates a dummy instance which won't even open a file. It will act as if
52 // opening the file ran out of space immediately.
53 DetachedBufferWriter(already_out_of_space_t) : ran_out_of_space_(true) {}
Austin Schuh2f8fd752020-09-01 22:38:28 -070054 DetachedBufferWriter(DetachedBufferWriter &&other);
55 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
56
Austin Schuha36c8902019-12-30 18:07:15 -080057 ~DetachedBufferWriter();
58
Austin Schuh2f8fd752020-09-01 22:38:28 -070059 DetachedBufferWriter &operator=(DetachedBufferWriter &&other);
Brian Silverman98360e22020-04-28 16:51:20 -070060 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
61
Austin Schuh6f3babe2020-01-26 20:34:50 -080062 std::string_view filename() const { return filename_; }
63
Brian Silvermana9f2ec92020-10-06 18:00:53 -070064 // This will be true until Close() is called, unless the file couldn't be
65 // created due to running out of space.
66 bool is_open() const { return fd_ != -1; }
67
Brian Silvermanf51499a2020-09-21 12:49:08 -070068 // Queues up a finished FlatBufferBuilder to be encoded and written.
69 //
70 // Triggers a flush if there's enough data queued up.
71 //
72 // Steals the detached buffer from it.
73 void QueueSizedFlatbuffer(flatbuffers::FlatBufferBuilder *fbb) {
74 QueueSizedFlatbuffer(fbb->Release());
75 }
76 // May steal the backing storage of buffer, or may leave it alone.
77 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070078 if (ran_out_of_space_) {
79 return;
80 }
Brian Silvermanf51499a2020-09-21 12:49:08 -070081 encoder_->Encode(std::move(buffer));
82 FlushAtThreshold();
83 }
Austin Schuha36c8902019-12-30 18:07:15 -080084
Brian Silvermanf51499a2020-09-21 12:49:08 -070085 // Queues up data in span. May copy or may write it to disk immediately.
86 void QueueSpan(absl::Span<const uint8_t> span);
Austin Schuha36c8902019-12-30 18:07:15 -080087
Brian Silverman0465fcf2020-09-24 00:29:18 -070088 // Indicates we got ENOSPC when trying to write. After this returns true, no
89 // further data is written.
90 bool ran_out_of_space() const { return ran_out_of_space_; }
91
92 // To avoid silently failing to write logfiles, you must call this before
93 // destruction if ran_out_of_space() is true and the situation has been
94 // handled.
95 void acknowledge_out_of_space() {
96 CHECK(ran_out_of_space_);
97 acknowledge_ran_out_of_space_ = true;
98 }
99
100 // Fully flushes and closes the underlying file now. No additional data may be
101 // enqueued after calling this.
102 //
103 // This will be performed in the destructor automatically.
104 //
105 // Note that this may set ran_out_of_space().
106 void Close();
107
Brian Silvermanf51499a2020-09-21 12:49:08 -0700108 // Returns the total number of bytes written and currently queued.
109 size_t total_bytes() const { return encoder_->total_bytes(); }
Austin Schuha36c8902019-12-30 18:07:15 -0800110
Brian Silvermanf51499a2020-09-21 12:49:08 -0700111 // The maximum time for a single write call, or 0 if none have been performed.
112 std::chrono::nanoseconds max_write_time() const { return max_write_time_; }
113 // The number of bytes in the longest write call, or -1 if none have been
114 // performed.
115 int max_write_time_bytes() const { return max_write_time_bytes_; }
116 // The number of buffers in the longest write call, or -1 if none have been
117 // performed.
118 int max_write_time_messages() const { return max_write_time_messages_; }
119 // The total time spent in write calls.
120 std::chrono::nanoseconds total_write_time() const {
121 return total_write_time_;
122 }
123 // The total number of writes which have been performed.
124 int total_write_count() const { return total_write_count_; }
125 // The total number of messages which have been written.
126 int total_write_messages() const { return total_write_messages_; }
127 // The total number of bytes which have been written.
128 int total_write_bytes() const { return total_write_bytes_; }
129 void ResetStatistics() {
130 max_write_time_ = std::chrono::nanoseconds::zero();
131 max_write_time_bytes_ = -1;
132 max_write_time_messages_ = -1;
133 total_write_time_ = std::chrono::nanoseconds::zero();
134 total_write_count_ = 0;
135 total_write_messages_ = 0;
136 total_write_bytes_ = 0;
137 }
Brian Silverman98360e22020-04-28 16:51:20 -0700138
Austin Schuha36c8902019-12-30 18:07:15 -0800139 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700140 // Performs a single writev call with as much of the data we have queued up as
141 // possible.
142 //
143 // This will normally take all of the data we have queued up, unless an
144 // encoder has spit out a big enough chunk all at once that we can't manage
145 // all of it.
146 void Flush();
147
Brian Silverman0465fcf2020-09-24 00:29:18 -0700148 // write_return is what write(2) or writev(2) returned. write_size is the
149 // number of bytes we expected it to write.
150 void HandleWriteReturn(ssize_t write_return, size_t write_size);
151
Brian Silvermanf51499a2020-09-21 12:49:08 -0700152 void UpdateStatsForWrite(aos::monotonic_clock::duration duration,
153 ssize_t written, int iovec_size);
154
155 // Flushes data if we've reached the threshold to do that as part of normal
156 // operation.
157 void FlushAtThreshold();
158
Austin Schuh2f8fd752020-09-01 22:38:28 -0700159 std::string filename_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700160 std::unique_ptr<DetachedBufferEncoder> encoder_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800161
Austin Schuha36c8902019-12-30 18:07:15 -0800162 int fd_ = -1;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700163 bool ran_out_of_space_ = false;
164 bool acknowledge_ran_out_of_space_ = false;
Austin Schuha36c8902019-12-30 18:07:15 -0800165
Austin Schuha36c8902019-12-30 18:07:15 -0800166 // List of iovecs to use with writev. This is a member variable to avoid
167 // churn.
168 std::vector<struct iovec> iovec_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700169
170 std::chrono::nanoseconds max_write_time_ = std::chrono::nanoseconds::zero();
171 int max_write_time_bytes_ = -1;
172 int max_write_time_messages_ = -1;
173 std::chrono::nanoseconds total_write_time_ = std::chrono::nanoseconds::zero();
174 int total_write_count_ = 0;
175 int total_write_messages_ = 0;
176 int total_write_bytes_ = 0;
Austin Schuha36c8902019-12-30 18:07:15 -0800177};
178
179// Packes a message pointed to by the context into a MessageHeader.
180flatbuffers::Offset<MessageHeader> PackMessage(
181 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
182 int channel_index, LogType log_type);
183
Austin Schuh6f3babe2020-01-26 20:34:50 -0800184FlatbufferVector<LogFileHeader> ReadHeader(std::string_view filename);
Austin Schuh5212cad2020-09-09 23:12:09 -0700185FlatbufferVector<MessageHeader> ReadNthMessage(std::string_view filename,
186 size_t n);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800187
Austin Schuh05b70472020-01-01 17:11:17 -0800188// Class to read chunks out of a log file.
189class SpanReader {
190 public:
191 SpanReader(std::string_view filename);
Austin Schuha36c8902019-12-30 18:07:15 -0800192
Austin Schuh6f3babe2020-01-26 20:34:50 -0800193 std::string_view filename() const { return filename_; }
194
Austin Schuh05b70472020-01-01 17:11:17 -0800195 // Returns a span with the data for a message from the log file, excluding
196 // the size.
197 absl::Span<const uint8_t> ReadMessage();
198
Austin Schuh05b70472020-01-01 17:11:17 -0800199 private:
200 // TODO(austin): Optimization:
201 // Allocate the 256k blocks like we do today. But, refcount them with
202 // shared_ptr pointed to by the messageheader that is returned. This avoids
203 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700204 // And (Brian): Consider just mmapping the file and handing out refcounted
205 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800206
207 // Reads a chunk of data into data_. Returns false if no data was read.
208 bool ReadBlock();
209
Austin Schuhc41603c2020-10-11 16:17:37 -0700210 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800211
Brian Silvermanf51499a2020-09-21 12:49:08 -0700212 // File reader and data decoder.
213 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800214
Brian Silvermanf51499a2020-09-21 12:49:08 -0700215 // Vector to read into.
216 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800217
218 // Amount of data consumed already in data_.
219 size_t consumed_data_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800220};
221
222// Class which handles reading the header and messages from the log file. This
223// handles any per-file state left before merging below.
224class MessageReader {
225 public:
226 MessageReader(std::string_view filename);
227
Austin Schuh6f3babe2020-01-26 20:34:50 -0800228 std::string_view filename() const { return span_reader_.filename(); }
229
Austin Schuh05b70472020-01-01 17:11:17 -0800230 // Returns the header from the log file.
231 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700232 return &raw_log_file_header_.message();
233 }
234
235 // Returns the raw data of the header from the log file.
236 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
237 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800238 }
239
240 // Returns the minimum maount of data needed to queue up for sorting before
241 // ware guarenteed to not see data out of order.
242 std::chrono::nanoseconds max_out_of_order_duration() const {
243 return max_out_of_order_duration_;
244 }
245
Austin Schuhcde938c2020-02-02 17:30:07 -0800246 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800247 monotonic_clock::time_point newest_timestamp() const {
248 return newest_timestamp_;
249 }
250
251 // Returns the next message if there is one.
252 std::optional<FlatbufferVector<MessageHeader>> ReadMessage();
253
254 // The time at which we need to read another chunk from the logfile.
255 monotonic_clock::time_point queue_data_time() const {
256 return newest_timestamp() - max_out_of_order_duration();
257 }
258
259 private:
260 // Log chunk reader.
261 SpanReader span_reader_;
262
Austin Schuh97789fc2020-08-01 14:42:45 -0700263 // Vector holding the raw data for the log file header.
264 FlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800265
266 // Minimum amount of data to queue up for sorting before we are guarenteed
267 // to not see data out of order.
268 std::chrono::nanoseconds max_out_of_order_duration_;
269
270 // Timestamp of the newest message in a channel queue.
271 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
272};
273
Austin Schuhc41603c2020-10-11 16:17:37 -0700274// A class to seamlessly read messages from a list of part files.
275class PartsMessageReader {
276 public:
277 PartsMessageReader(LogParts log_parts);
278
279 std::string_view filename() const { return message_reader_.filename(); }
280
281 // Returns the minimum amount of data needed to queue up for sorting before
282 // we are guarenteed to not see data out of order.
283 std::chrono::nanoseconds max_out_of_order_duration() const {
284 return message_reader_.max_out_of_order_duration();
285 }
286
287 // Returns the newest timestamp read out of the log file.
288 monotonic_clock::time_point newest_timestamp() const {
289 return newest_timestamp_;
290 }
291
292 // Returns the next message if there is one, or nullopt if we have reached the
293 // end of all the files.
294 // Note: reading the next message may change the max_out_of_order_duration().
295 std::optional<FlatbufferVector<MessageHeader>> ReadMessage();
296
297 private:
298 // Opens the next log and updates message_reader_. Sets done_ if there is
299 // nothing more to do.
300 void NextLog();
301
302 const LogParts parts_;
303 size_t next_part_index_ = 1u;
304 bool done_ = false;
305 MessageReader message_reader_;
306
307 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
308};
309
Austin Schuh6f3babe2020-01-26 20:34:50 -0800310class TimestampMerger;
Austin Schuh05b70472020-01-01 17:11:17 -0800311
Austin Schuh6f3babe2020-01-26 20:34:50 -0800312// A design requirement is that the relevant data for a channel is not more than
313// max_out_of_order_duration out of order. We approach sorting in layers.
314//
315// 1) Split each (maybe chunked) log file into one queue per channel. Read this
316// log file looking for data pertaining to a specific node.
317// (SplitMessageReader)
318// 2) Merge all the data per channel from the different log files into a sorted
319// list of timestamps and messages. (TimestampMerger)
320// 3) Combine the timestamps and messages. (TimestampMerger)
321// 4) Merge all the channels to produce the next message on a node.
322// (ChannelMerger)
323// 5) Duplicate this entire stack per node.
324
325// This class splits messages and timestamps up into a queue per channel, and
326// handles reading data from multiple chunks.
327class SplitMessageReader {
328 public:
329 SplitMessageReader(const std::vector<std::string> &filenames);
330
331 // Sets the TimestampMerger that gets notified for each channel. The node
332 // that the TimestampMerger is merging as needs to be passed in.
333 void SetTimestampMerger(TimestampMerger *timestamp_merger, int channel,
334 const Node *target_node);
335
Austin Schuh2f8fd752020-09-01 22:38:28 -0700336 // Returns the (timestamp, queue_index, message_header) for the oldest message
337 // in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800338 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
339 oldest_message(int channel) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800340 return channels_[channel].data.front_timestamp();
341 }
342
Austin Schuh2f8fd752020-09-01 22:38:28 -0700343 // Returns the (timestamp, queue_index, message_header) for the oldest
344 // delivery time in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800345 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
346 oldest_message(int channel, int destination_node) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800347 return channels_[channel].timestamps[destination_node].front_timestamp();
348 }
349
350 // Returns the timestamp, queue_index, and message for the oldest data on a
351 // channel. Requeues data as needed.
352 std::tuple<monotonic_clock::time_point, uint32_t,
353 FlatbufferVector<MessageHeader>>
354 PopOldest(int channel_index);
355
356 // Returns the timestamp, queue_index, and message for the oldest timestamp on
357 // a channel delivered to a node. Requeues data as needed.
358 std::tuple<monotonic_clock::time_point, uint32_t,
359 FlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -0700360 PopOldestTimestamp(int channel, int node_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800361
362 // Returns the header for the log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800363 const LogFileHeader *log_file_header() const {
Austin Schuhfa895892020-01-07 20:07:41 -0800364 return &log_file_header_.message();
Austin Schuh05b70472020-01-01 17:11:17 -0800365 }
366
Austin Schuh97789fc2020-08-01 14:42:45 -0700367 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
368 return log_file_header_;
369 }
370
Austin Schuh6f3babe2020-01-26 20:34:50 -0800371 // Returns the starting time for this set of log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800372 monotonic_clock::time_point monotonic_start_time() {
373 return monotonic_clock::time_point(
374 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
375 }
376 realtime_clock::time_point realtime_start_time() {
377 return realtime_clock::time_point(
378 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
379 }
380
Austin Schuh6f3babe2020-01-26 20:34:50 -0800381 // Returns the configuration from the log file header.
382 const Configuration *configuration() const {
383 return log_file_header()->configuration();
384 }
385
Austin Schuh05b70472020-01-01 17:11:17 -0800386 // Returns the node who's point of view this log file is from. Make sure this
387 // is a pointer in the configuration() nodes list so it can be consumed
388 // elsewhere.
389 const Node *node() const {
390 if (configuration()->has_nodes()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800391 return configuration::GetNodeOrDie(configuration(),
392 log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800393 } else {
394 CHECK(!log_file_header()->has_node());
395 return nullptr;
396 }
397 }
398
Austin Schuh6f3babe2020-01-26 20:34:50 -0800399 // Returns the timestamp of the newest message read from the log file, and the
400 // timestamp that we need to re-queue data.
401 monotonic_clock::time_point newest_timestamp() const {
Austin Schuhcde938c2020-02-02 17:30:07 -0800402 return newest_timestamp_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800403 }
404
Austin Schuhcde938c2020-02-02 17:30:07 -0800405 // Returns the next time to trigger a requeue.
406 monotonic_clock::time_point time_to_queue() const { return time_to_queue_; }
407
408 // Returns the minimum amount of data needed to queue up for sorting before
Austin Schuhc41603c2020-10-11 16:17:37 -0700409 // we are guarenteed to not see data out of order.
Austin Schuhcde938c2020-02-02 17:30:07 -0800410 std::chrono::nanoseconds max_out_of_order_duration() const {
411 return message_reader_->max_out_of_order_duration();
412 }
413
414 std::string_view filename() const { return message_reader_->filename(); }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800415
416 // Adds more messages to the sorted list. This reads enough data such that
417 // oldest_message_time can be replayed safely. Returns false if the log file
418 // has all been read.
419 bool QueueMessages(monotonic_clock::time_point oldest_message_time);
Austin Schuh05b70472020-01-01 17:11:17 -0800420
Austin Schuhcde938c2020-02-02 17:30:07 -0800421 // Returns debug strings for a channel, and timestamps for a node.
422 std::string DebugString(int channel) const;
423 std::string DebugString(int channel, int node_index) const;
424
Austin Schuh8bd96322020-02-13 21:18:22 -0800425 // Returns true if all the messages have been queued from the last log file in
426 // the list of log files chunks.
427 bool at_end() const { return at_end_; }
428
Austin Schuh05b70472020-01-01 17:11:17 -0800429 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800430 // TODO(austin): Need to copy or refcount the message instead of running
431 // multiple copies of the reader. Or maybe have a "as_node" index and hide it
432 // inside.
433
Austin Schuhfa895892020-01-07 20:07:41 -0800434 // Moves to the next log file in the list.
435 bool NextLogFile();
436
Austin Schuh6f3babe2020-01-26 20:34:50 -0800437 // Filenames of the log files.
438 std::vector<std::string> filenames_;
439 // And the index of the next file to open.
440 size_t next_filename_index_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800441
Austin Schuhee711052020-08-24 16:06:09 -0700442 // Node we are reading as.
443 const Node *target_node_ = nullptr;
444
Austin Schuh6f3babe2020-01-26 20:34:50 -0800445 // Log file header to report. This is a copy.
Austin Schuh97789fc2020-08-01 14:42:45 -0700446 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800447 // Current log file being read.
448 std::unique_ptr<MessageReader> message_reader_;
Austin Schuh05b70472020-01-01 17:11:17 -0800449
450 // Datastructure to hold the list of messages, cached timestamp for the
451 // oldest message, and sender to send with.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800452 struct MessageHeaderQueue {
453 // If true, this is a timestamp queue.
454 bool timestamps = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800455
Austin Schuh6f3babe2020-01-26 20:34:50 -0800456 // Returns a reference to the the oldest message.
457 FlatbufferVector<MessageHeader> &front() {
458 CHECK_GT(data_.size(), 0u);
459 return data_.front();
Austin Schuh05b70472020-01-01 17:11:17 -0800460 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800461
Austin Schuhcde938c2020-02-02 17:30:07 -0800462 // Adds a message to the back of the queue. Returns true if it was actually
463 // emplaced.
464 bool emplace_back(FlatbufferVector<MessageHeader> &&msg);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800465
466 // Drops the front message. Invalidates the front() reference.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700467 void PopFront();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800468
469 // The size of the queue.
470 size_t size() { return data_.size(); }
471
Austin Schuhcde938c2020-02-02 17:30:07 -0800472 // Returns a debug string with info about each message in the queue.
473 std::string DebugString() const;
474
Austin Schuh2f8fd752020-09-01 22:38:28 -0700475 // Returns the (timestamp, queue_index, message_header) for the oldest
476 // message.
Austin Schuhcde938c2020-02-02 17:30:07 -0800477 const std::tuple<monotonic_clock::time_point, uint32_t,
478 const MessageHeader *>
479 front_timestamp() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700480 const MessageHeader &message = front().message();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800481 return std::make_tuple(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700482 monotonic_clock::time_point(
483 std::chrono::nanoseconds(message.monotonic_sent_time())),
484 message.queue_index(), &message);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800485 }
486
487 // Pointer to the timestamp merger for this queue if available.
488 TimestampMerger *timestamp_merger = nullptr;
489 // Pointer to the reader which feeds this queue.
490 SplitMessageReader *split_reader = nullptr;
491
492 private:
493 // The data.
494 std::deque<FlatbufferVector<MessageHeader>> data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800495 };
496
Austin Schuh6f3babe2020-01-26 20:34:50 -0800497 // All the queues needed for a channel. There isn't going to be data in all
498 // of these.
499 struct ChannelData {
500 // The data queue for the channel.
501 MessageHeaderQueue data;
502 // Queues for timestamps for each node.
503 std::vector<MessageHeaderQueue> timestamps;
504 };
Austin Schuhfa895892020-01-07 20:07:41 -0800505
Austin Schuh6f3babe2020-01-26 20:34:50 -0800506 // Data for all the channels.
Austin Schuh05b70472020-01-01 17:11:17 -0800507 std::vector<ChannelData> channels_;
508
Austin Schuh6f3babe2020-01-26 20:34:50 -0800509 // Once we know the node that this SplitMessageReader will be writing as,
510 // there will be only one MessageHeaderQueue that a specific channel matches.
511 // Precompute this here for efficiency.
512 std::vector<MessageHeaderQueue *> channels_to_write_;
513
Austin Schuhcde938c2020-02-02 17:30:07 -0800514 monotonic_clock::time_point time_to_queue_ = monotonic_clock::min_time;
515
516 // Latches true when we hit the end of the last log file and there is no sense
517 // poking it further.
518 bool at_end_ = false;
519
520 // Timestamp of the newest message that was read and actually queued. We want
521 // to track this independently from the log file because we need the
522 // timestamps here to be timestamps of messages that are queued.
523 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800524};
525
526class ChannelMerger;
527
528// Sorts channels (and timestamps) from multiple log files for a single channel.
529class TimestampMerger {
530 public:
531 TimestampMerger(const Configuration *configuration,
532 std::vector<SplitMessageReader *> split_message_readers,
533 int channel_index, const Node *target_node,
534 ChannelMerger *channel_merger);
535
536 // Metadata used to schedule the message.
537 struct DeliveryTimestamp {
538 monotonic_clock::time_point monotonic_event_time =
539 monotonic_clock::min_time;
540 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700541 uint32_t queue_index = 0xffffffff;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800542
543 monotonic_clock::time_point monotonic_remote_time =
544 monotonic_clock::min_time;
545 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
546 uint32_t remote_queue_index = 0xffffffff;
547 };
548
549 // Pushes SplitMessageReader onto the timestamp heap. This should only be
550 // called when timestamps are placed in the channel this class is merging for
551 // the reader.
552 void UpdateTimestamp(
553 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800554 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
555 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800556 PushTimestampHeap(oldest_message_time, split_message_reader);
557 }
558 // Pushes SplitMessageReader onto the message heap. This should only be
559 // called when data is placed in the channel this class is merging for the
560 // reader.
561 void Update(
562 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800563 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
564 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800565 PushMessageHeap(oldest_message_time, split_message_reader);
566 }
567
Austin Schuhcde938c2020-02-02 17:30:07 -0800568 // Returns the oldest combined timestamp and data for this channel. If there
569 // isn't a matching piece of data, returns only the timestamp with no data.
570 // The caller can determine what the appropriate action is to recover.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800571 std::tuple<DeliveryTimestamp, FlatbufferVector<MessageHeader>> PopOldest();
572
573 // Tracks if the channel merger has pushed this onto it's heap or not.
574 bool pushed() { return pushed_; }
575 // Sets if this has been pushed to the channel merger heap. Should only be
576 // called by the channel merger.
577 void set_pushed(bool pushed) { pushed_ = pushed; }
578
Austin Schuhcde938c2020-02-02 17:30:07 -0800579 // Returns a debug string with the heaps printed out.
580 std::string DebugString() const;
581
Austin Schuh8bd96322020-02-13 21:18:22 -0800582 // Returns true if we have timestamps.
583 bool has_timestamps() const { return has_timestamps_; }
584
585 // Records that one of the log files ran out of data. This should only be
586 // called by a SplitMessageReader.
587 void NoticeAtEnd();
588
Austin Schuh2f8fd752020-09-01 22:38:28 -0700589 aos::monotonic_clock::time_point channel_merger_time() {
590 if (has_timestamps_) {
591 return std::get<0>(timestamp_heap_[0]);
592 } else {
593 return std::get<0>(message_heap_[0]);
594 }
595 }
596
Austin Schuh6f3babe2020-01-26 20:34:50 -0800597 private:
598 // Pushes messages and timestamps to the corresponding heaps.
599 void PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800600 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
601 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800602 SplitMessageReader *split_message_reader);
603 void PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800604 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
605 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800606 SplitMessageReader *split_message_reader);
607
608 // Pops a message from the message heap. This automatically triggers the
609 // split message reader to re-fetch any new data.
610 std::tuple<monotonic_clock::time_point, uint32_t,
611 FlatbufferVector<MessageHeader>>
612 PopMessageHeap();
Austin Schuhcde938c2020-02-02 17:30:07 -0800613
614 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
615 oldest_message() const;
616 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
617 oldest_timestamp() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800618 // Pops a message from the timestamp heap. This automatically triggers the
619 // split message reader to re-fetch any new data.
620 std::tuple<monotonic_clock::time_point, uint32_t,
621 FlatbufferVector<MessageHeader>>
622 PopTimestampHeap();
623
624 const Configuration *configuration_;
625
626 // If true, this is a forwarded channel and timestamps should be matched.
627 bool has_timestamps_ = false;
628
629 // Tracks if the ChannelMerger has pushed this onto it's queue.
630 bool pushed_ = false;
631
632 // The split message readers used for source data.
633 std::vector<SplitMessageReader *> split_message_readers_;
634
635 // The channel to merge.
636 int channel_index_;
637
638 // Our node.
639 int node_index_;
640
641 // Heaps for messages and timestamps.
642 std::vector<
643 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
644 message_heap_;
645 std::vector<
646 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
647 timestamp_heap_;
648
649 // Parent channel merger.
650 ChannelMerger *channel_merger_;
651};
652
653// This class handles constructing all the split message readers, channel
654// mergers, and combining the results.
655class ChannelMerger {
656 public:
657 // Builds a ChannelMerger around a set of log files. These are of the format:
658 // {
659 // {log1_part0, log1_part1, ...},
660 // {log2}
661 // }
662 // The inner vector is a list of log file chunks which form up a log file.
663 // The outer vector is a list of log files with subsets of the messages, or
664 // messages from different nodes.
665 ChannelMerger(const std::vector<std::vector<std::string>> &filenames);
666
667 // Returns the nodes that we know how to merge.
668 const std::vector<const Node *> nodes() const;
669 // Sets the node that we will return messages as. Returns true if the node
670 // has log files and will produce data. This can only be called once, and
671 // will likely corrupt state if called a second time.
672 bool SetNode(const Node *target_node);
673
674 // Everything else needs the node set before it works.
675
676 // Returns a timestamp for the oldest message in this group of logfiles.
Austin Schuh858c9f32020-08-31 16:56:12 -0700677 monotonic_clock::time_point OldestMessageTime() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800678 // Pops the oldest message.
679 std::tuple<TimestampMerger::DeliveryTimestamp, int,
680 FlatbufferVector<MessageHeader>>
681 PopOldest();
682
683 // Returns the config for this set of log files.
684 const Configuration *configuration() const {
685 return log_file_header()->configuration();
686 }
687
688 const LogFileHeader *log_file_header() const {
689 return &log_file_header_.message();
690 }
691
692 // Returns the start times for the configured node's log files.
Austin Schuhcde938c2020-02-02 17:30:07 -0800693 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800694 return monotonic_clock::time_point(
695 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
696 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800697 realtime_clock::time_point realtime_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800698 return realtime_clock::time_point(
699 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
700 }
701
702 // Returns the node set by SetNode above.
703 const Node *node() const { return node_; }
704
705 // Called by the TimestampMerger when new data is available with the provided
706 // timestamp and channel_index.
707 void Update(monotonic_clock::time_point timestamp, int channel_index) {
708 PushChannelHeap(timestamp, channel_index);
709 }
710
Austin Schuhcde938c2020-02-02 17:30:07 -0800711 // Returns a debug string with all the heaps in it. Generally only useful for
712 // debugging what went wrong.
713 std::string DebugString() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800714
Austin Schuh8bd96322020-02-13 21:18:22 -0800715 // Returns true if one of the log files has finished reading everything. When
716 // log file chunks are involved, this means that the last chunk in a log file
717 // has been read. It is acceptable to be missing data at this point in time.
718 bool at_end() const { return at_end_; }
719
720 // Marks that one of the log files is at the end. This should only be called
721 // by timestamp mergers.
722 void NoticeAtEnd() { at_end_ = true; }
723
Austin Schuhcde938c2020-02-02 17:30:07 -0800724 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800725 // Pushes the timestamp for new data on the provided channel.
726 void PushChannelHeap(monotonic_clock::time_point timestamp,
727 int channel_index);
728
Austin Schuh2f8fd752020-09-01 22:38:28 -0700729 // CHECKs that channel_heap_ and timestamp_heap_ are valid heaps.
730 void VerifyHeaps();
731
Austin Schuh6f3babe2020-01-26 20:34:50 -0800732 // All the message readers.
733 std::vector<std::unique_ptr<SplitMessageReader>> split_message_readers_;
734
735 // The log header we are claiming to be.
Austin Schuh97789fc2020-08-01 14:42:45 -0700736 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800737
738 // The timestamp mergers which combine data from the split message readers.
739 std::vector<TimestampMerger> timestamp_mergers_;
740
741 // A heap of the channel readers and timestamps for the oldest data in each.
Austin Schuh05b70472020-01-01 17:11:17 -0800742 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap_;
743
Austin Schuh6f3babe2020-01-26 20:34:50 -0800744 // Configured node.
745 const Node *node_;
746
Austin Schuh8bd96322020-02-13 21:18:22 -0800747 bool at_end_ = false;
748
Austin Schuh6f3babe2020-01-26 20:34:50 -0800749 // Cached copy of the list of nodes.
750 std::vector<const Node *> nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700751
752 // Last time popped. Used to detect events being returned out of order.
753 monotonic_clock::time_point last_popped_time_ = monotonic_clock::min_time;
Austin Schuh05b70472020-01-01 17:11:17 -0800754};
Austin Schuha36c8902019-12-30 18:07:15 -0800755
Austin Schuhee711052020-08-24 16:06:09 -0700756// Returns the node name with a trailing space, or an empty string if we are on
757// a single node.
758std::string MaybeNodeName(const Node *);
759
Brian Silvermanf51499a2020-09-21 12:49:08 -0700760} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -0800761
762#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_