blob: 60bd39c1ca55c9d819eb6a22f2076de08479178d [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 Schuha36c8902019-12-30 18:07:15 -080021#include "aos/events/logging/logger_generated.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070022#include "aos/flatbuffers.h"
Austin Schuha36c8902019-12-30 18:07:15 -080023#include "flatbuffers/flatbuffers.h"
24
Brian Silvermanf51499a2020-09-21 12:49:08 -070025namespace aos::logger {
Austin Schuha36c8902019-12-30 18:07:15 -080026
27enum class LogType : uint8_t {
28 // The message originated on this node and should be logged here.
29 kLogMessage,
30 // The message originated on another node, but only the delivery times are
31 // logged here.
32 kLogDeliveryTimeOnly,
33 // The message originated on another node. Log it and the delivery times
34 // together. The message_gateway is responsible for logging any messages
35 // which didn't get delivered.
Austin Schuh6f3babe2020-01-26 20:34:50 -080036 kLogMessageAndDeliveryTime,
37 // The message originated on the other node and should be logged on this node.
38 kLogRemoteMessage
Austin Schuha36c8902019-12-30 18:07:15 -080039};
40
Austin Schuha36c8902019-12-30 18:07:15 -080041// This class manages efficiently writing a sequence of detached buffers to a
Brian Silvermanf51499a2020-09-21 12:49:08 -070042// file. It encodes them, queues them up, and batches the write operation.
Austin Schuha36c8902019-12-30 18:07:15 -080043class DetachedBufferWriter {
44 public:
Brian Silvermana9f2ec92020-10-06 18:00:53 -070045 // Marker struct for one of our constructor overloads.
46 struct already_out_of_space_t {};
47
Brian Silvermanf51499a2020-09-21 12:49:08 -070048 DetachedBufferWriter(std::string_view filename,
49 std::unique_ptr<DetachedBufferEncoder> encoder);
Brian Silvermana9f2ec92020-10-06 18:00:53 -070050 // Creates a dummy instance which won't even open a file. It will act as if
51 // opening the file ran out of space immediately.
52 DetachedBufferWriter(already_out_of_space_t) : ran_out_of_space_(true) {}
Austin Schuh2f8fd752020-09-01 22:38:28 -070053 DetachedBufferWriter(DetachedBufferWriter &&other);
54 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
55
Austin Schuha36c8902019-12-30 18:07:15 -080056 ~DetachedBufferWriter();
57
Austin Schuh2f8fd752020-09-01 22:38:28 -070058 DetachedBufferWriter &operator=(DetachedBufferWriter &&other);
Brian Silverman98360e22020-04-28 16:51:20 -070059 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
60
Austin Schuh6f3babe2020-01-26 20:34:50 -080061 std::string_view filename() const { return filename_; }
62
Brian Silvermana9f2ec92020-10-06 18:00:53 -070063 // This will be true until Close() is called, unless the file couldn't be
64 // created due to running out of space.
65 bool is_open() const { return fd_ != -1; }
66
Brian Silvermanf51499a2020-09-21 12:49:08 -070067 // Queues up a finished FlatBufferBuilder to be encoded and written.
68 //
69 // Triggers a flush if there's enough data queued up.
70 //
71 // Steals the detached buffer from it.
72 void QueueSizedFlatbuffer(flatbuffers::FlatBufferBuilder *fbb) {
73 QueueSizedFlatbuffer(fbb->Release());
74 }
75 // May steal the backing storage of buffer, or may leave it alone.
76 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070077 if (ran_out_of_space_) {
78 return;
79 }
Brian Silvermanf51499a2020-09-21 12:49:08 -070080 encoder_->Encode(std::move(buffer));
81 FlushAtThreshold();
82 }
Austin Schuha36c8902019-12-30 18:07:15 -080083
Brian Silvermanf51499a2020-09-21 12:49:08 -070084 // Queues up data in span. May copy or may write it to disk immediately.
85 void QueueSpan(absl::Span<const uint8_t> span);
Austin Schuha36c8902019-12-30 18:07:15 -080086
Brian Silverman0465fcf2020-09-24 00:29:18 -070087 // Indicates we got ENOSPC when trying to write. After this returns true, no
88 // further data is written.
89 bool ran_out_of_space() const { return ran_out_of_space_; }
90
91 // To avoid silently failing to write logfiles, you must call this before
92 // destruction if ran_out_of_space() is true and the situation has been
93 // handled.
94 void acknowledge_out_of_space() {
95 CHECK(ran_out_of_space_);
96 acknowledge_ran_out_of_space_ = true;
97 }
98
99 // Fully flushes and closes the underlying file now. No additional data may be
100 // enqueued after calling this.
101 //
102 // This will be performed in the destructor automatically.
103 //
104 // Note that this may set ran_out_of_space().
105 void Close();
106
Brian Silvermanf51499a2020-09-21 12:49:08 -0700107 // Returns the total number of bytes written and currently queued.
108 size_t total_bytes() const { return encoder_->total_bytes(); }
Austin Schuha36c8902019-12-30 18:07:15 -0800109
Brian Silvermanf51499a2020-09-21 12:49:08 -0700110 // The maximum time for a single write call, or 0 if none have been performed.
111 std::chrono::nanoseconds max_write_time() const { return max_write_time_; }
112 // The number of bytes in the longest write call, or -1 if none have been
113 // performed.
114 int max_write_time_bytes() const { return max_write_time_bytes_; }
115 // The number of buffers in the longest write call, or -1 if none have been
116 // performed.
117 int max_write_time_messages() const { return max_write_time_messages_; }
118 // The total time spent in write calls.
119 std::chrono::nanoseconds total_write_time() const {
120 return total_write_time_;
121 }
122 // The total number of writes which have been performed.
123 int total_write_count() const { return total_write_count_; }
124 // The total number of messages which have been written.
125 int total_write_messages() const { return total_write_messages_; }
126 // The total number of bytes which have been written.
127 int total_write_bytes() const { return total_write_bytes_; }
128 void ResetStatistics() {
129 max_write_time_ = std::chrono::nanoseconds::zero();
130 max_write_time_bytes_ = -1;
131 max_write_time_messages_ = -1;
132 total_write_time_ = std::chrono::nanoseconds::zero();
133 total_write_count_ = 0;
134 total_write_messages_ = 0;
135 total_write_bytes_ = 0;
136 }
Brian Silverman98360e22020-04-28 16:51:20 -0700137
Austin Schuha36c8902019-12-30 18:07:15 -0800138 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700139 // Performs a single writev call with as much of the data we have queued up as
140 // possible.
141 //
142 // This will normally take all of the data we have queued up, unless an
143 // encoder has spit out a big enough chunk all at once that we can't manage
144 // all of it.
145 void Flush();
146
Brian Silverman0465fcf2020-09-24 00:29:18 -0700147 // write_return is what write(2) or writev(2) returned. write_size is the
148 // number of bytes we expected it to write.
149 void HandleWriteReturn(ssize_t write_return, size_t write_size);
150
Brian Silvermanf51499a2020-09-21 12:49:08 -0700151 void UpdateStatsForWrite(aos::monotonic_clock::duration duration,
152 ssize_t written, int iovec_size);
153
154 // Flushes data if we've reached the threshold to do that as part of normal
155 // operation.
156 void FlushAtThreshold();
157
Austin Schuh2f8fd752020-09-01 22:38:28 -0700158 std::string filename_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700159 std::unique_ptr<DetachedBufferEncoder> encoder_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800160
Austin Schuha36c8902019-12-30 18:07:15 -0800161 int fd_ = -1;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700162 bool ran_out_of_space_ = false;
163 bool acknowledge_ran_out_of_space_ = false;
Austin Schuha36c8902019-12-30 18:07:15 -0800164
Austin Schuha36c8902019-12-30 18:07:15 -0800165 // List of iovecs to use with writev. This is a member variable to avoid
166 // churn.
167 std::vector<struct iovec> iovec_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700168
169 std::chrono::nanoseconds max_write_time_ = std::chrono::nanoseconds::zero();
170 int max_write_time_bytes_ = -1;
171 int max_write_time_messages_ = -1;
172 std::chrono::nanoseconds total_write_time_ = std::chrono::nanoseconds::zero();
173 int total_write_count_ = 0;
174 int total_write_messages_ = 0;
175 int total_write_bytes_ = 0;
Austin Schuha36c8902019-12-30 18:07:15 -0800176};
177
178// Packes a message pointed to by the context into a MessageHeader.
179flatbuffers::Offset<MessageHeader> PackMessage(
180 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
181 int channel_index, LogType log_type);
182
Austin Schuh6f3babe2020-01-26 20:34:50 -0800183FlatbufferVector<LogFileHeader> ReadHeader(std::string_view filename);
Austin Schuh5212cad2020-09-09 23:12:09 -0700184FlatbufferVector<MessageHeader> ReadNthMessage(std::string_view filename,
185 size_t n);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800186
Austin Schuh05b70472020-01-01 17:11:17 -0800187// Class to read chunks out of a log file.
188class SpanReader {
189 public:
190 SpanReader(std::string_view filename);
Austin Schuha36c8902019-12-30 18:07:15 -0800191
Austin Schuh6f3babe2020-01-26 20:34:50 -0800192 std::string_view filename() const { return filename_; }
193
Austin Schuh05b70472020-01-01 17:11:17 -0800194 // Returns a span with the data for a message from the log file, excluding
195 // the size.
196 absl::Span<const uint8_t> ReadMessage();
197
Austin Schuh05b70472020-01-01 17:11:17 -0800198 private:
199 // TODO(austin): Optimization:
200 // Allocate the 256k blocks like we do today. But, refcount them with
201 // shared_ptr pointed to by the messageheader that is returned. This avoids
202 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700203 // And (Brian): Consider just mmapping the file and handing out refcounted
204 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800205
206 // Reads a chunk of data into data_. Returns false if no data was read.
207 bool ReadBlock();
208
Austin Schuh6f3babe2020-01-26 20:34:50 -0800209 const std::string filename_;
210
Brian Silvermanf51499a2020-09-21 12:49:08 -0700211 // File reader and data decoder.
212 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800213
Brian Silvermanf51499a2020-09-21 12:49:08 -0700214 // Vector to read into.
215 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800216
217 // Amount of data consumed already in data_.
218 size_t consumed_data_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800219};
220
221// Class which handles reading the header and messages from the log file. This
222// handles any per-file state left before merging below.
223class MessageReader {
224 public:
225 MessageReader(std::string_view filename);
226
Austin Schuh6f3babe2020-01-26 20:34:50 -0800227 std::string_view filename() const { return span_reader_.filename(); }
228
Austin Schuh05b70472020-01-01 17:11:17 -0800229 // Returns the header from the log file.
230 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700231 return &raw_log_file_header_.message();
232 }
233
234 // Returns the raw data of the header from the log file.
235 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
236 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800237 }
238
239 // Returns the minimum maount of data needed to queue up for sorting before
240 // ware guarenteed to not see data out of order.
241 std::chrono::nanoseconds max_out_of_order_duration() const {
242 return max_out_of_order_duration_;
243 }
244
Austin Schuhcde938c2020-02-02 17:30:07 -0800245 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800246 monotonic_clock::time_point newest_timestamp() const {
247 return newest_timestamp_;
248 }
249
250 // Returns the next message if there is one.
251 std::optional<FlatbufferVector<MessageHeader>> ReadMessage();
252
253 // The time at which we need to read another chunk from the logfile.
254 monotonic_clock::time_point queue_data_time() const {
255 return newest_timestamp() - max_out_of_order_duration();
256 }
257
258 private:
259 // Log chunk reader.
260 SpanReader span_reader_;
261
Austin Schuh97789fc2020-08-01 14:42:45 -0700262 // Vector holding the raw data for the log file header.
263 FlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800264
265 // Minimum amount of data to queue up for sorting before we are guarenteed
266 // to not see data out of order.
267 std::chrono::nanoseconds max_out_of_order_duration_;
268
269 // Timestamp of the newest message in a channel queue.
270 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
271};
272
Austin Schuh6f3babe2020-01-26 20:34:50 -0800273class TimestampMerger;
Austin Schuh05b70472020-01-01 17:11:17 -0800274
Austin Schuh6f3babe2020-01-26 20:34:50 -0800275// A design requirement is that the relevant data for a channel is not more than
276// max_out_of_order_duration out of order. We approach sorting in layers.
277//
278// 1) Split each (maybe chunked) log file into one queue per channel. Read this
279// log file looking for data pertaining to a specific node.
280// (SplitMessageReader)
281// 2) Merge all the data per channel from the different log files into a sorted
282// list of timestamps and messages. (TimestampMerger)
283// 3) Combine the timestamps and messages. (TimestampMerger)
284// 4) Merge all the channels to produce the next message on a node.
285// (ChannelMerger)
286// 5) Duplicate this entire stack per node.
287
288// This class splits messages and timestamps up into a queue per channel, and
289// handles reading data from multiple chunks.
290class SplitMessageReader {
291 public:
292 SplitMessageReader(const std::vector<std::string> &filenames);
293
294 // Sets the TimestampMerger that gets notified for each channel. The node
295 // that the TimestampMerger is merging as needs to be passed in.
296 void SetTimestampMerger(TimestampMerger *timestamp_merger, int channel,
297 const Node *target_node);
298
Austin Schuh2f8fd752020-09-01 22:38:28 -0700299 // Returns the (timestamp, queue_index, message_header) for the oldest message
300 // in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800301 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
302 oldest_message(int channel) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800303 return channels_[channel].data.front_timestamp();
304 }
305
Austin Schuh2f8fd752020-09-01 22:38:28 -0700306 // Returns the (timestamp, queue_index, message_header) for the oldest
307 // delivery time in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800308 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
309 oldest_message(int channel, int destination_node) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800310 return channels_[channel].timestamps[destination_node].front_timestamp();
311 }
312
313 // Returns the timestamp, queue_index, and message for the oldest data on a
314 // channel. Requeues data as needed.
315 std::tuple<monotonic_clock::time_point, uint32_t,
316 FlatbufferVector<MessageHeader>>
317 PopOldest(int channel_index);
318
319 // Returns the timestamp, queue_index, and message for the oldest timestamp on
320 // a channel delivered to a node. Requeues data as needed.
321 std::tuple<monotonic_clock::time_point, uint32_t,
322 FlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -0700323 PopOldestTimestamp(int channel, int node_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800324
325 // Returns the header for the log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800326 const LogFileHeader *log_file_header() const {
Austin Schuhfa895892020-01-07 20:07:41 -0800327 return &log_file_header_.message();
Austin Schuh05b70472020-01-01 17:11:17 -0800328 }
329
Austin Schuh97789fc2020-08-01 14:42:45 -0700330 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
331 return log_file_header_;
332 }
333
Austin Schuh6f3babe2020-01-26 20:34:50 -0800334 // Returns the starting time for this set of log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800335 monotonic_clock::time_point monotonic_start_time() {
336 return monotonic_clock::time_point(
337 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
338 }
339 realtime_clock::time_point realtime_start_time() {
340 return realtime_clock::time_point(
341 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
342 }
343
Austin Schuh6f3babe2020-01-26 20:34:50 -0800344 // Returns the configuration from the log file header.
345 const Configuration *configuration() const {
346 return log_file_header()->configuration();
347 }
348
Austin Schuh05b70472020-01-01 17:11:17 -0800349 // Returns the node who's point of view this log file is from. Make sure this
350 // is a pointer in the configuration() nodes list so it can be consumed
351 // elsewhere.
352 const Node *node() const {
353 if (configuration()->has_nodes()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800354 return configuration::GetNodeOrDie(configuration(),
355 log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800356 } else {
357 CHECK(!log_file_header()->has_node());
358 return nullptr;
359 }
360 }
361
Austin Schuh6f3babe2020-01-26 20:34:50 -0800362 // Returns the timestamp of the newest message read from the log file, and the
363 // timestamp that we need to re-queue data.
364 monotonic_clock::time_point newest_timestamp() const {
Austin Schuhcde938c2020-02-02 17:30:07 -0800365 return newest_timestamp_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800366 }
367
Austin Schuhcde938c2020-02-02 17:30:07 -0800368 // Returns the next time to trigger a requeue.
369 monotonic_clock::time_point time_to_queue() const { return time_to_queue_; }
370
371 // Returns the minimum amount of data needed to queue up for sorting before
372 // ware guarenteed to not see data out of order.
373 std::chrono::nanoseconds max_out_of_order_duration() const {
374 return message_reader_->max_out_of_order_duration();
375 }
376
377 std::string_view filename() const { return message_reader_->filename(); }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800378
379 // Adds more messages to the sorted list. This reads enough data such that
380 // oldest_message_time can be replayed safely. Returns false if the log file
381 // has all been read.
382 bool QueueMessages(monotonic_clock::time_point oldest_message_time);
Austin Schuh05b70472020-01-01 17:11:17 -0800383
Austin Schuhcde938c2020-02-02 17:30:07 -0800384 // Returns debug strings for a channel, and timestamps for a node.
385 std::string DebugString(int channel) const;
386 std::string DebugString(int channel, int node_index) const;
387
Austin Schuh8bd96322020-02-13 21:18:22 -0800388 // Returns true if all the messages have been queued from the last log file in
389 // the list of log files chunks.
390 bool at_end() const { return at_end_; }
391
Austin Schuh05b70472020-01-01 17:11:17 -0800392 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800393 // TODO(austin): Need to copy or refcount the message instead of running
394 // multiple copies of the reader. Or maybe have a "as_node" index and hide it
395 // inside.
396
Austin Schuhfa895892020-01-07 20:07:41 -0800397 // Moves to the next log file in the list.
398 bool NextLogFile();
399
Austin Schuh6f3babe2020-01-26 20:34:50 -0800400 // Filenames of the log files.
401 std::vector<std::string> filenames_;
402 // And the index of the next file to open.
403 size_t next_filename_index_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800404
Austin Schuhee711052020-08-24 16:06:09 -0700405 // Node we are reading as.
406 const Node *target_node_ = nullptr;
407
Austin Schuh6f3babe2020-01-26 20:34:50 -0800408 // Log file header to report. This is a copy.
Austin Schuh97789fc2020-08-01 14:42:45 -0700409 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800410 // Current log file being read.
411 std::unique_ptr<MessageReader> message_reader_;
Austin Schuh05b70472020-01-01 17:11:17 -0800412
413 // Datastructure to hold the list of messages, cached timestamp for the
414 // oldest message, and sender to send with.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800415 struct MessageHeaderQueue {
416 // If true, this is a timestamp queue.
417 bool timestamps = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800418
Austin Schuh6f3babe2020-01-26 20:34:50 -0800419 // Returns a reference to the the oldest message.
420 FlatbufferVector<MessageHeader> &front() {
421 CHECK_GT(data_.size(), 0u);
422 return data_.front();
Austin Schuh05b70472020-01-01 17:11:17 -0800423 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800424
Austin Schuhcde938c2020-02-02 17:30:07 -0800425 // Adds a message to the back of the queue. Returns true if it was actually
426 // emplaced.
427 bool emplace_back(FlatbufferVector<MessageHeader> &&msg);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800428
429 // Drops the front message. Invalidates the front() reference.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700430 void PopFront();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800431
432 // The size of the queue.
433 size_t size() { return data_.size(); }
434
Austin Schuhcde938c2020-02-02 17:30:07 -0800435 // Returns a debug string with info about each message in the queue.
436 std::string DebugString() const;
437
Austin Schuh2f8fd752020-09-01 22:38:28 -0700438 // Returns the (timestamp, queue_index, message_header) for the oldest
439 // message.
Austin Schuhcde938c2020-02-02 17:30:07 -0800440 const std::tuple<monotonic_clock::time_point, uint32_t,
441 const MessageHeader *>
442 front_timestamp() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700443 const MessageHeader &message = front().message();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800444 return std::make_tuple(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700445 monotonic_clock::time_point(
446 std::chrono::nanoseconds(message.monotonic_sent_time())),
447 message.queue_index(), &message);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800448 }
449
450 // Pointer to the timestamp merger for this queue if available.
451 TimestampMerger *timestamp_merger = nullptr;
452 // Pointer to the reader which feeds this queue.
453 SplitMessageReader *split_reader = nullptr;
454
455 private:
456 // The data.
457 std::deque<FlatbufferVector<MessageHeader>> data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800458 };
459
Austin Schuh6f3babe2020-01-26 20:34:50 -0800460 // All the queues needed for a channel. There isn't going to be data in all
461 // of these.
462 struct ChannelData {
463 // The data queue for the channel.
464 MessageHeaderQueue data;
465 // Queues for timestamps for each node.
466 std::vector<MessageHeaderQueue> timestamps;
467 };
Austin Schuhfa895892020-01-07 20:07:41 -0800468
Austin Schuh6f3babe2020-01-26 20:34:50 -0800469 // Data for all the channels.
Austin Schuh05b70472020-01-01 17:11:17 -0800470 std::vector<ChannelData> channels_;
471
Austin Schuh6f3babe2020-01-26 20:34:50 -0800472 // Once we know the node that this SplitMessageReader will be writing as,
473 // there will be only one MessageHeaderQueue that a specific channel matches.
474 // Precompute this here for efficiency.
475 std::vector<MessageHeaderQueue *> channels_to_write_;
476
Austin Schuhcde938c2020-02-02 17:30:07 -0800477 monotonic_clock::time_point time_to_queue_ = monotonic_clock::min_time;
478
479 // Latches true when we hit the end of the last log file and there is no sense
480 // poking it further.
481 bool at_end_ = false;
482
483 // Timestamp of the newest message that was read and actually queued. We want
484 // to track this independently from the log file because we need the
485 // timestamps here to be timestamps of messages that are queued.
486 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800487};
488
489class ChannelMerger;
490
491// Sorts channels (and timestamps) from multiple log files for a single channel.
492class TimestampMerger {
493 public:
494 TimestampMerger(const Configuration *configuration,
495 std::vector<SplitMessageReader *> split_message_readers,
496 int channel_index, const Node *target_node,
497 ChannelMerger *channel_merger);
498
499 // Metadata used to schedule the message.
500 struct DeliveryTimestamp {
501 monotonic_clock::time_point monotonic_event_time =
502 monotonic_clock::min_time;
503 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700504 uint32_t queue_index = 0xffffffff;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800505
506 monotonic_clock::time_point monotonic_remote_time =
507 monotonic_clock::min_time;
508 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
509 uint32_t remote_queue_index = 0xffffffff;
510 };
511
512 // Pushes SplitMessageReader onto the timestamp heap. This should only be
513 // called when timestamps are placed in the channel this class is merging for
514 // the reader.
515 void UpdateTimestamp(
516 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800517 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
518 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800519 PushTimestampHeap(oldest_message_time, split_message_reader);
520 }
521 // Pushes SplitMessageReader onto the message heap. This should only be
522 // called when data is placed in the channel this class is merging for the
523 // reader.
524 void Update(
525 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800526 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
527 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800528 PushMessageHeap(oldest_message_time, split_message_reader);
529 }
530
Austin Schuhcde938c2020-02-02 17:30:07 -0800531 // Returns the oldest combined timestamp and data for this channel. If there
532 // isn't a matching piece of data, returns only the timestamp with no data.
533 // The caller can determine what the appropriate action is to recover.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800534 std::tuple<DeliveryTimestamp, FlatbufferVector<MessageHeader>> PopOldest();
535
536 // Tracks if the channel merger has pushed this onto it's heap or not.
537 bool pushed() { return pushed_; }
538 // Sets if this has been pushed to the channel merger heap. Should only be
539 // called by the channel merger.
540 void set_pushed(bool pushed) { pushed_ = pushed; }
541
Austin Schuhcde938c2020-02-02 17:30:07 -0800542 // Returns a debug string with the heaps printed out.
543 std::string DebugString() const;
544
Austin Schuh8bd96322020-02-13 21:18:22 -0800545 // Returns true if we have timestamps.
546 bool has_timestamps() const { return has_timestamps_; }
547
548 // Records that one of the log files ran out of data. This should only be
549 // called by a SplitMessageReader.
550 void NoticeAtEnd();
551
Austin Schuh2f8fd752020-09-01 22:38:28 -0700552 aos::monotonic_clock::time_point channel_merger_time() {
553 if (has_timestamps_) {
554 return std::get<0>(timestamp_heap_[0]);
555 } else {
556 return std::get<0>(message_heap_[0]);
557 }
558 }
559
Austin Schuh6f3babe2020-01-26 20:34:50 -0800560 private:
561 // Pushes messages and timestamps to the corresponding heaps.
562 void PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800563 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
564 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800565 SplitMessageReader *split_message_reader);
566 void PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800567 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
568 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800569 SplitMessageReader *split_message_reader);
570
571 // Pops a message from the message heap. This automatically triggers the
572 // split message reader to re-fetch any new data.
573 std::tuple<monotonic_clock::time_point, uint32_t,
574 FlatbufferVector<MessageHeader>>
575 PopMessageHeap();
Austin Schuhcde938c2020-02-02 17:30:07 -0800576
577 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
578 oldest_message() const;
579 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
580 oldest_timestamp() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800581 // Pops a message from the timestamp heap. This automatically triggers the
582 // split message reader to re-fetch any new data.
583 std::tuple<monotonic_clock::time_point, uint32_t,
584 FlatbufferVector<MessageHeader>>
585 PopTimestampHeap();
586
587 const Configuration *configuration_;
588
589 // If true, this is a forwarded channel and timestamps should be matched.
590 bool has_timestamps_ = false;
591
592 // Tracks if the ChannelMerger has pushed this onto it's queue.
593 bool pushed_ = false;
594
595 // The split message readers used for source data.
596 std::vector<SplitMessageReader *> split_message_readers_;
597
598 // The channel to merge.
599 int channel_index_;
600
601 // Our node.
602 int node_index_;
603
604 // Heaps for messages and timestamps.
605 std::vector<
606 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
607 message_heap_;
608 std::vector<
609 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
610 timestamp_heap_;
611
612 // Parent channel merger.
613 ChannelMerger *channel_merger_;
614};
615
616// This class handles constructing all the split message readers, channel
617// mergers, and combining the results.
618class ChannelMerger {
619 public:
620 // Builds a ChannelMerger around a set of log files. These are of the format:
621 // {
622 // {log1_part0, log1_part1, ...},
623 // {log2}
624 // }
625 // The inner vector is a list of log file chunks which form up a log file.
626 // The outer vector is a list of log files with subsets of the messages, or
627 // messages from different nodes.
628 ChannelMerger(const std::vector<std::vector<std::string>> &filenames);
629
630 // Returns the nodes that we know how to merge.
631 const std::vector<const Node *> nodes() const;
632 // Sets the node that we will return messages as. Returns true if the node
633 // has log files and will produce data. This can only be called once, and
634 // will likely corrupt state if called a second time.
635 bool SetNode(const Node *target_node);
636
637 // Everything else needs the node set before it works.
638
639 // Returns a timestamp for the oldest message in this group of logfiles.
Austin Schuh858c9f32020-08-31 16:56:12 -0700640 monotonic_clock::time_point OldestMessageTime() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800641 // Pops the oldest message.
642 std::tuple<TimestampMerger::DeliveryTimestamp, int,
643 FlatbufferVector<MessageHeader>>
644 PopOldest();
645
646 // Returns the config for this set of log files.
647 const Configuration *configuration() const {
648 return log_file_header()->configuration();
649 }
650
651 const LogFileHeader *log_file_header() const {
652 return &log_file_header_.message();
653 }
654
655 // Returns the start times for the configured node's log files.
Austin Schuhcde938c2020-02-02 17:30:07 -0800656 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800657 return monotonic_clock::time_point(
658 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
659 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800660 realtime_clock::time_point realtime_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800661 return realtime_clock::time_point(
662 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
663 }
664
665 // Returns the node set by SetNode above.
666 const Node *node() const { return node_; }
667
668 // Called by the TimestampMerger when new data is available with the provided
669 // timestamp and channel_index.
670 void Update(monotonic_clock::time_point timestamp, int channel_index) {
671 PushChannelHeap(timestamp, channel_index);
672 }
673
Austin Schuhcde938c2020-02-02 17:30:07 -0800674 // Returns a debug string with all the heaps in it. Generally only useful for
675 // debugging what went wrong.
676 std::string DebugString() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800677
Austin Schuh8bd96322020-02-13 21:18:22 -0800678 // Returns true if one of the log files has finished reading everything. When
679 // log file chunks are involved, this means that the last chunk in a log file
680 // has been read. It is acceptable to be missing data at this point in time.
681 bool at_end() const { return at_end_; }
682
683 // Marks that one of the log files is at the end. This should only be called
684 // by timestamp mergers.
685 void NoticeAtEnd() { at_end_ = true; }
686
Austin Schuhcde938c2020-02-02 17:30:07 -0800687 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800688 // Pushes the timestamp for new data on the provided channel.
689 void PushChannelHeap(monotonic_clock::time_point timestamp,
690 int channel_index);
691
Austin Schuh2f8fd752020-09-01 22:38:28 -0700692 // CHECKs that channel_heap_ and timestamp_heap_ are valid heaps.
693 void VerifyHeaps();
694
Austin Schuh6f3babe2020-01-26 20:34:50 -0800695 // All the message readers.
696 std::vector<std::unique_ptr<SplitMessageReader>> split_message_readers_;
697
698 // The log header we are claiming to be.
Austin Schuh97789fc2020-08-01 14:42:45 -0700699 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800700
701 // The timestamp mergers which combine data from the split message readers.
702 std::vector<TimestampMerger> timestamp_mergers_;
703
704 // A heap of the channel readers and timestamps for the oldest data in each.
Austin Schuh05b70472020-01-01 17:11:17 -0800705 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap_;
706
Austin Schuh6f3babe2020-01-26 20:34:50 -0800707 // Configured node.
708 const Node *node_;
709
Austin Schuh8bd96322020-02-13 21:18:22 -0800710 bool at_end_ = false;
711
Austin Schuh6f3babe2020-01-26 20:34:50 -0800712 // Cached copy of the list of nodes.
713 std::vector<const Node *> nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700714
715 // Last time popped. Used to detect events being returned out of order.
716 monotonic_clock::time_point last_popped_time_ = monotonic_clock::min_time;
Austin Schuh05b70472020-01-01 17:11:17 -0800717};
Austin Schuha36c8902019-12-30 18:07:15 -0800718
Austin Schuhee711052020-08-24 16:06:09 -0700719// Returns the node name with a trailing space, or an empty string if we are on
720// a single node.
721std::string MaybeNodeName(const Node *);
722
Brian Silvermanf51499a2020-09-21 12:49:08 -0700723} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -0800724
725#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_