blob: 8381a9a76ad15c843febac2c68f5bca16a686f60 [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 Schuh3bd4c402020-11-06 18:19:06 -0800184std::optional<FlatbufferVector<LogFileHeader>> ReadHeader(
185 std::string_view filename);
186std::optional<FlatbufferVector<MessageHeader>> ReadNthMessage(
187 std::string_view filename, size_t n);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800188
Austin Schuh05b70472020-01-01 17:11:17 -0800189// Class to read chunks out of a log file.
190class SpanReader {
191 public:
192 SpanReader(std::string_view filename);
Austin Schuha36c8902019-12-30 18:07:15 -0800193
Austin Schuh6f3babe2020-01-26 20:34:50 -0800194 std::string_view filename() const { return filename_; }
195
Austin Schuh05b70472020-01-01 17:11:17 -0800196 // Returns a span with the data for a message from the log file, excluding
197 // the size.
198 absl::Span<const uint8_t> ReadMessage();
199
Austin Schuh05b70472020-01-01 17:11:17 -0800200 private:
201 // TODO(austin): Optimization:
202 // Allocate the 256k blocks like we do today. But, refcount them with
203 // shared_ptr pointed to by the messageheader that is returned. This avoids
204 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700205 // And (Brian): Consider just mmapping the file and handing out refcounted
206 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800207
208 // Reads a chunk of data into data_. Returns false if no data was read.
209 bool ReadBlock();
210
Austin Schuhc41603c2020-10-11 16:17:37 -0700211 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800212
Brian Silvermanf51499a2020-09-21 12:49:08 -0700213 // File reader and data decoder.
214 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800215
Brian Silvermanf51499a2020-09-21 12:49:08 -0700216 // Vector to read into.
217 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800218
219 // Amount of data consumed already in data_.
220 size_t consumed_data_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800221};
222
223// Class which handles reading the header and messages from the log file. This
224// handles any per-file state left before merging below.
225class MessageReader {
226 public:
227 MessageReader(std::string_view filename);
228
Austin Schuh6f3babe2020-01-26 20:34:50 -0800229 std::string_view filename() const { return span_reader_.filename(); }
230
Austin Schuh05b70472020-01-01 17:11:17 -0800231 // Returns the header from the log file.
232 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700233 return &raw_log_file_header_.message();
234 }
235
236 // Returns the raw data of the header from the log file.
237 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
238 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800239 }
240
241 // Returns the minimum maount of data needed to queue up for sorting before
242 // ware guarenteed to not see data out of order.
243 std::chrono::nanoseconds max_out_of_order_duration() const {
244 return max_out_of_order_duration_;
245 }
246
Austin Schuhcde938c2020-02-02 17:30:07 -0800247 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800248 monotonic_clock::time_point newest_timestamp() const {
249 return newest_timestamp_;
250 }
251
252 // Returns the next message if there is one.
253 std::optional<FlatbufferVector<MessageHeader>> ReadMessage();
254
255 // The time at which we need to read another chunk from the logfile.
256 monotonic_clock::time_point queue_data_time() const {
257 return newest_timestamp() - max_out_of_order_duration();
258 }
259
260 private:
261 // Log chunk reader.
262 SpanReader span_reader_;
263
Austin Schuh97789fc2020-08-01 14:42:45 -0700264 // Vector holding the raw data for the log file header.
265 FlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800266
267 // Minimum amount of data to queue up for sorting before we are guarenteed
268 // to not see data out of order.
269 std::chrono::nanoseconds max_out_of_order_duration_;
270
271 // Timestamp of the newest message in a channel queue.
272 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
273};
274
Austin Schuhc41603c2020-10-11 16:17:37 -0700275// A class to seamlessly read messages from a list of part files.
276class PartsMessageReader {
277 public:
278 PartsMessageReader(LogParts log_parts);
279
280 std::string_view filename() const { return message_reader_.filename(); }
281
282 // Returns the minimum amount of data needed to queue up for sorting before
283 // we are guarenteed to not see data out of order.
284 std::chrono::nanoseconds max_out_of_order_duration() const {
285 return message_reader_.max_out_of_order_duration();
286 }
287
288 // Returns the newest timestamp read out of the log file.
289 monotonic_clock::time_point newest_timestamp() const {
290 return newest_timestamp_;
291 }
292
293 // Returns the next message if there is one, or nullopt if we have reached the
294 // end of all the files.
295 // Note: reading the next message may change the max_out_of_order_duration().
296 std::optional<FlatbufferVector<MessageHeader>> ReadMessage();
297
298 private:
299 // Opens the next log and updates message_reader_. Sets done_ if there is
300 // nothing more to do.
301 void NextLog();
302
303 const LogParts parts_;
304 size_t next_part_index_ = 1u;
305 bool done_ = false;
306 MessageReader message_reader_;
307
308 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
309};
310
Austin Schuh6f3babe2020-01-26 20:34:50 -0800311class TimestampMerger;
Austin Schuh05b70472020-01-01 17:11:17 -0800312
Austin Schuh6f3babe2020-01-26 20:34:50 -0800313// A design requirement is that the relevant data for a channel is not more than
314// max_out_of_order_duration out of order. We approach sorting in layers.
315//
316// 1) Split each (maybe chunked) log file into one queue per channel. Read this
317// log file looking for data pertaining to a specific node.
318// (SplitMessageReader)
319// 2) Merge all the data per channel from the different log files into a sorted
320// list of timestamps and messages. (TimestampMerger)
321// 3) Combine the timestamps and messages. (TimestampMerger)
322// 4) Merge all the channels to produce the next message on a node.
323// (ChannelMerger)
324// 5) Duplicate this entire stack per node.
325
326// This class splits messages and timestamps up into a queue per channel, and
327// handles reading data from multiple chunks.
328class SplitMessageReader {
329 public:
330 SplitMessageReader(const std::vector<std::string> &filenames);
331
332 // Sets the TimestampMerger that gets notified for each channel. The node
333 // that the TimestampMerger is merging as needs to be passed in.
334 void SetTimestampMerger(TimestampMerger *timestamp_merger, int channel,
335 const Node *target_node);
336
Austin Schuh2f8fd752020-09-01 22:38:28 -0700337 // Returns the (timestamp, queue_index, message_header) for the oldest message
338 // in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800339 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
340 oldest_message(int channel) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800341 return channels_[channel].data.front_timestamp();
342 }
343
Austin Schuh2f8fd752020-09-01 22:38:28 -0700344 // Returns the (timestamp, queue_index, message_header) for the oldest
345 // delivery time in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800346 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
347 oldest_message(int channel, int destination_node) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800348 return channels_[channel].timestamps[destination_node].front_timestamp();
349 }
350
351 // Returns the timestamp, queue_index, and message for the oldest data on a
352 // channel. Requeues data as needed.
353 std::tuple<monotonic_clock::time_point, uint32_t,
354 FlatbufferVector<MessageHeader>>
355 PopOldest(int channel_index);
356
357 // Returns the timestamp, queue_index, and message for the oldest timestamp on
358 // a channel delivered to a node. Requeues data as needed.
359 std::tuple<monotonic_clock::time_point, uint32_t,
360 FlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -0700361 PopOldestTimestamp(int channel, int node_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800362
363 // Returns the header for the log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800364 const LogFileHeader *log_file_header() const {
Austin Schuhfa895892020-01-07 20:07:41 -0800365 return &log_file_header_.message();
Austin Schuh05b70472020-01-01 17:11:17 -0800366 }
367
Austin Schuh97789fc2020-08-01 14:42:45 -0700368 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
369 return log_file_header_;
370 }
371
Austin Schuh6f3babe2020-01-26 20:34:50 -0800372 // Returns the starting time for this set of log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800373 monotonic_clock::time_point monotonic_start_time() {
374 return monotonic_clock::time_point(
375 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
376 }
377 realtime_clock::time_point realtime_start_time() {
378 return realtime_clock::time_point(
379 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
380 }
381
Austin Schuh6f3babe2020-01-26 20:34:50 -0800382 // Returns the configuration from the log file header.
383 const Configuration *configuration() const {
384 return log_file_header()->configuration();
385 }
386
Austin Schuh05b70472020-01-01 17:11:17 -0800387 // Returns the node who's point of view this log file is from. Make sure this
388 // is a pointer in the configuration() nodes list so it can be consumed
389 // elsewhere.
390 const Node *node() const {
391 if (configuration()->has_nodes()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800392 return configuration::GetNodeOrDie(configuration(),
393 log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800394 } else {
395 CHECK(!log_file_header()->has_node());
396 return nullptr;
397 }
398 }
399
Austin Schuh6f3babe2020-01-26 20:34:50 -0800400 // Returns the timestamp of the newest message read from the log file, and the
401 // timestamp that we need to re-queue data.
402 monotonic_clock::time_point newest_timestamp() const {
Austin Schuhcde938c2020-02-02 17:30:07 -0800403 return newest_timestamp_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800404 }
405
Austin Schuhcde938c2020-02-02 17:30:07 -0800406 // Returns the next time to trigger a requeue.
407 monotonic_clock::time_point time_to_queue() const { return time_to_queue_; }
408
409 // Returns the minimum amount of data needed to queue up for sorting before
Austin Schuhc41603c2020-10-11 16:17:37 -0700410 // we are guarenteed to not see data out of order.
Austin Schuhcde938c2020-02-02 17:30:07 -0800411 std::chrono::nanoseconds max_out_of_order_duration() const {
412 return message_reader_->max_out_of_order_duration();
413 }
414
415 std::string_view filename() const { return message_reader_->filename(); }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800416
417 // Adds more messages to the sorted list. This reads enough data such that
418 // oldest_message_time can be replayed safely. Returns false if the log file
419 // has all been read.
420 bool QueueMessages(monotonic_clock::time_point oldest_message_time);
Austin Schuh05b70472020-01-01 17:11:17 -0800421
Austin Schuhcde938c2020-02-02 17:30:07 -0800422 // Returns debug strings for a channel, and timestamps for a node.
423 std::string DebugString(int channel) const;
424 std::string DebugString(int channel, int node_index) const;
425
Austin Schuh8bd96322020-02-13 21:18:22 -0800426 // Returns true if all the messages have been queued from the last log file in
427 // the list of log files chunks.
428 bool at_end() const { return at_end_; }
429
Austin Schuh05b70472020-01-01 17:11:17 -0800430 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800431 // TODO(austin): Need to copy or refcount the message instead of running
432 // multiple copies of the reader. Or maybe have a "as_node" index and hide it
433 // inside.
434
Austin Schuhfa895892020-01-07 20:07:41 -0800435 // Moves to the next log file in the list.
436 bool NextLogFile();
437
Austin Schuh6f3babe2020-01-26 20:34:50 -0800438 // Filenames of the log files.
439 std::vector<std::string> filenames_;
440 // And the index of the next file to open.
441 size_t next_filename_index_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800442
Austin Schuhee711052020-08-24 16:06:09 -0700443 // Node we are reading as.
444 const Node *target_node_ = nullptr;
445
Austin Schuh6f3babe2020-01-26 20:34:50 -0800446 // Log file header to report. This is a copy.
Austin Schuh97789fc2020-08-01 14:42:45 -0700447 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800448 // Current log file being read.
449 std::unique_ptr<MessageReader> message_reader_;
Austin Schuh05b70472020-01-01 17:11:17 -0800450
451 // Datastructure to hold the list of messages, cached timestamp for the
452 // oldest message, and sender to send with.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800453 struct MessageHeaderQueue {
454 // If true, this is a timestamp queue.
455 bool timestamps = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800456
Austin Schuh6f3babe2020-01-26 20:34:50 -0800457 // Returns a reference to the the oldest message.
458 FlatbufferVector<MessageHeader> &front() {
459 CHECK_GT(data_.size(), 0u);
460 return data_.front();
Austin Schuh05b70472020-01-01 17:11:17 -0800461 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800462
Austin Schuhcde938c2020-02-02 17:30:07 -0800463 // Adds a message to the back of the queue. Returns true if it was actually
464 // emplaced.
465 bool emplace_back(FlatbufferVector<MessageHeader> &&msg);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800466
467 // Drops the front message. Invalidates the front() reference.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700468 void PopFront();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800469
470 // The size of the queue.
471 size_t size() { return data_.size(); }
472
Austin Schuhcde938c2020-02-02 17:30:07 -0800473 // Returns a debug string with info about each message in the queue.
474 std::string DebugString() const;
475
Austin Schuh2f8fd752020-09-01 22:38:28 -0700476 // Returns the (timestamp, queue_index, message_header) for the oldest
477 // message.
Austin Schuhcde938c2020-02-02 17:30:07 -0800478 const std::tuple<monotonic_clock::time_point, uint32_t,
479 const MessageHeader *>
480 front_timestamp() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700481 const MessageHeader &message = front().message();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800482 return std::make_tuple(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700483 monotonic_clock::time_point(
484 std::chrono::nanoseconds(message.monotonic_sent_time())),
485 message.queue_index(), &message);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800486 }
487
488 // Pointer to the timestamp merger for this queue if available.
489 TimestampMerger *timestamp_merger = nullptr;
490 // Pointer to the reader which feeds this queue.
491 SplitMessageReader *split_reader = nullptr;
492
493 private:
494 // The data.
495 std::deque<FlatbufferVector<MessageHeader>> data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800496 };
497
Austin Schuh6f3babe2020-01-26 20:34:50 -0800498 // All the queues needed for a channel. There isn't going to be data in all
499 // of these.
500 struct ChannelData {
501 // The data queue for the channel.
502 MessageHeaderQueue data;
503 // Queues for timestamps for each node.
504 std::vector<MessageHeaderQueue> timestamps;
505 };
Austin Schuhfa895892020-01-07 20:07:41 -0800506
Austin Schuh6f3babe2020-01-26 20:34:50 -0800507 // Data for all the channels.
Austin Schuh05b70472020-01-01 17:11:17 -0800508 std::vector<ChannelData> channels_;
509
Austin Schuh6f3babe2020-01-26 20:34:50 -0800510 // Once we know the node that this SplitMessageReader will be writing as,
511 // there will be only one MessageHeaderQueue that a specific channel matches.
512 // Precompute this here for efficiency.
513 std::vector<MessageHeaderQueue *> channels_to_write_;
514
Austin Schuhcde938c2020-02-02 17:30:07 -0800515 monotonic_clock::time_point time_to_queue_ = monotonic_clock::min_time;
516
517 // Latches true when we hit the end of the last log file and there is no sense
518 // poking it further.
519 bool at_end_ = false;
520
521 // Timestamp of the newest message that was read and actually queued. We want
522 // to track this independently from the log file because we need the
523 // timestamps here to be timestamps of messages that are queued.
524 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800525};
526
527class ChannelMerger;
528
529// Sorts channels (and timestamps) from multiple log files for a single channel.
530class TimestampMerger {
531 public:
532 TimestampMerger(const Configuration *configuration,
533 std::vector<SplitMessageReader *> split_message_readers,
534 int channel_index, const Node *target_node,
535 ChannelMerger *channel_merger);
536
537 // Metadata used to schedule the message.
538 struct DeliveryTimestamp {
539 monotonic_clock::time_point monotonic_event_time =
540 monotonic_clock::min_time;
541 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700542 uint32_t queue_index = 0xffffffff;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800543
544 monotonic_clock::time_point monotonic_remote_time =
545 monotonic_clock::min_time;
546 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
547 uint32_t remote_queue_index = 0xffffffff;
548 };
549
550 // Pushes SplitMessageReader onto the timestamp heap. This should only be
551 // called when timestamps are placed in the channel this class is merging for
552 // the reader.
553 void UpdateTimestamp(
554 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800555 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
556 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800557 PushTimestampHeap(oldest_message_time, split_message_reader);
558 }
559 // Pushes SplitMessageReader onto the message heap. This should only be
560 // called when data is placed in the channel this class is merging for the
561 // reader.
562 void Update(
563 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800564 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
565 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800566 PushMessageHeap(oldest_message_time, split_message_reader);
567 }
568
Austin Schuhcde938c2020-02-02 17:30:07 -0800569 // Returns the oldest combined timestamp and data for this channel. If there
570 // isn't a matching piece of data, returns only the timestamp with no data.
571 // The caller can determine what the appropriate action is to recover.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800572 std::tuple<DeliveryTimestamp, FlatbufferVector<MessageHeader>> PopOldest();
573
574 // Tracks if the channel merger has pushed this onto it's heap or not.
575 bool pushed() { return pushed_; }
576 // Sets if this has been pushed to the channel merger heap. Should only be
577 // called by the channel merger.
578 void set_pushed(bool pushed) { pushed_ = pushed; }
579
Austin Schuhcde938c2020-02-02 17:30:07 -0800580 // Returns a debug string with the heaps printed out.
581 std::string DebugString() const;
582
Austin Schuh8bd96322020-02-13 21:18:22 -0800583 // Returns true if we have timestamps.
584 bool has_timestamps() const { return has_timestamps_; }
585
586 // Records that one of the log files ran out of data. This should only be
587 // called by a SplitMessageReader.
588 void NoticeAtEnd();
589
Austin Schuh2f8fd752020-09-01 22:38:28 -0700590 aos::monotonic_clock::time_point channel_merger_time() {
591 if (has_timestamps_) {
592 return std::get<0>(timestamp_heap_[0]);
593 } else {
594 return std::get<0>(message_heap_[0]);
595 }
596 }
597
Austin Schuh6f3babe2020-01-26 20:34:50 -0800598 private:
599 // Pushes messages and timestamps to the corresponding heaps.
600 void PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800601 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
602 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800603 SplitMessageReader *split_message_reader);
604 void PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800605 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
606 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800607 SplitMessageReader *split_message_reader);
608
609 // Pops a message from the message heap. This automatically triggers the
610 // split message reader to re-fetch any new data.
611 std::tuple<monotonic_clock::time_point, uint32_t,
612 FlatbufferVector<MessageHeader>>
613 PopMessageHeap();
Austin Schuhcde938c2020-02-02 17:30:07 -0800614
615 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
616 oldest_message() const;
617 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
618 oldest_timestamp() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800619 // Pops a message from the timestamp heap. This automatically triggers the
620 // split message reader to re-fetch any new data.
621 std::tuple<monotonic_clock::time_point, uint32_t,
622 FlatbufferVector<MessageHeader>>
623 PopTimestampHeap();
624
625 const Configuration *configuration_;
626
627 // If true, this is a forwarded channel and timestamps should be matched.
628 bool has_timestamps_ = false;
629
630 // Tracks if the ChannelMerger has pushed this onto it's queue.
631 bool pushed_ = false;
632
633 // The split message readers used for source data.
634 std::vector<SplitMessageReader *> split_message_readers_;
635
636 // The channel to merge.
637 int channel_index_;
638
639 // Our node.
640 int node_index_;
641
642 // Heaps for messages and timestamps.
643 std::vector<
644 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
645 message_heap_;
646 std::vector<
647 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
648 timestamp_heap_;
649
650 // Parent channel merger.
651 ChannelMerger *channel_merger_;
652};
653
654// This class handles constructing all the split message readers, channel
655// mergers, and combining the results.
656class ChannelMerger {
657 public:
658 // Builds a ChannelMerger around a set of log files. These are of the format:
659 // {
660 // {log1_part0, log1_part1, ...},
661 // {log2}
662 // }
663 // The inner vector is a list of log file chunks which form up a log file.
664 // The outer vector is a list of log files with subsets of the messages, or
665 // messages from different nodes.
666 ChannelMerger(const std::vector<std::vector<std::string>> &filenames);
667
668 // Returns the nodes that we know how to merge.
669 const std::vector<const Node *> nodes() const;
670 // Sets the node that we will return messages as. Returns true if the node
671 // has log files and will produce data. This can only be called once, and
672 // will likely corrupt state if called a second time.
673 bool SetNode(const Node *target_node);
674
675 // Everything else needs the node set before it works.
676
677 // Returns a timestamp for the oldest message in this group of logfiles.
Austin Schuh858c9f32020-08-31 16:56:12 -0700678 monotonic_clock::time_point OldestMessageTime() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800679 // Pops the oldest message.
680 std::tuple<TimestampMerger::DeliveryTimestamp, int,
681 FlatbufferVector<MessageHeader>>
682 PopOldest();
683
684 // Returns the config for this set of log files.
685 const Configuration *configuration() const {
686 return log_file_header()->configuration();
687 }
688
689 const LogFileHeader *log_file_header() const {
690 return &log_file_header_.message();
691 }
692
693 // Returns the start times for the configured node's log files.
Austin Schuhcde938c2020-02-02 17:30:07 -0800694 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800695 return monotonic_clock::time_point(
696 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
697 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800698 realtime_clock::time_point realtime_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800699 return realtime_clock::time_point(
700 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
701 }
702
703 // Returns the node set by SetNode above.
704 const Node *node() const { return node_; }
705
706 // Called by the TimestampMerger when new data is available with the provided
707 // timestamp and channel_index.
708 void Update(monotonic_clock::time_point timestamp, int channel_index) {
709 PushChannelHeap(timestamp, channel_index);
710 }
711
Austin Schuhcde938c2020-02-02 17:30:07 -0800712 // Returns a debug string with all the heaps in it. Generally only useful for
713 // debugging what went wrong.
714 std::string DebugString() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800715
Austin Schuh8bd96322020-02-13 21:18:22 -0800716 // Returns true if one of the log files has finished reading everything. When
717 // log file chunks are involved, this means that the last chunk in a log file
718 // has been read. It is acceptable to be missing data at this point in time.
719 bool at_end() const { return at_end_; }
720
721 // Marks that one of the log files is at the end. This should only be called
722 // by timestamp mergers.
723 void NoticeAtEnd() { at_end_ = true; }
724
Austin Schuhcde938c2020-02-02 17:30:07 -0800725 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800726 // Pushes the timestamp for new data on the provided channel.
727 void PushChannelHeap(monotonic_clock::time_point timestamp,
728 int channel_index);
729
Austin Schuh2f8fd752020-09-01 22:38:28 -0700730 // CHECKs that channel_heap_ and timestamp_heap_ are valid heaps.
731 void VerifyHeaps();
732
Austin Schuh6f3babe2020-01-26 20:34:50 -0800733 // All the message readers.
734 std::vector<std::unique_ptr<SplitMessageReader>> split_message_readers_;
735
736 // The log header we are claiming to be.
Austin Schuh97789fc2020-08-01 14:42:45 -0700737 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800738
739 // The timestamp mergers which combine data from the split message readers.
740 std::vector<TimestampMerger> timestamp_mergers_;
741
742 // A heap of the channel readers and timestamps for the oldest data in each.
Austin Schuh05b70472020-01-01 17:11:17 -0800743 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap_;
744
Austin Schuh6f3babe2020-01-26 20:34:50 -0800745 // Configured node.
746 const Node *node_;
747
Austin Schuh8bd96322020-02-13 21:18:22 -0800748 bool at_end_ = false;
749
Austin Schuh6f3babe2020-01-26 20:34:50 -0800750 // Cached copy of the list of nodes.
751 std::vector<const Node *> nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700752
753 // Last time popped. Used to detect events being returned out of order.
754 monotonic_clock::time_point last_popped_time_ = monotonic_clock::min_time;
Austin Schuh05b70472020-01-01 17:11:17 -0800755};
Austin Schuha36c8902019-12-30 18:07:15 -0800756
Austin Schuhee711052020-08-24 16:06:09 -0700757// Returns the node name with a trailing space, or an empty string if we are on
758// a single node.
759std::string MaybeNodeName(const Node *);
760
Brian Silvermanf51499a2020-09-21 12:49:08 -0700761} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -0800762
763#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_