blob: d1fbeb26b17265a32e3abb7c46d5c0725b66050d [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"
Austin Schuha36c8902019-12-30 18:07:15 -080018#include "aos/events/event_loop.h"
19#include "aos/events/logging/logger_generated.h"
20#include "flatbuffers/flatbuffers.h"
21
22namespace aos {
23namespace logger {
24
25enum class LogType : uint8_t {
26 // The message originated on this node and should be logged here.
27 kLogMessage,
28 // The message originated on another node, but only the delivery times are
29 // logged here.
30 kLogDeliveryTimeOnly,
31 // The message originated on another node. Log it and the delivery times
32 // together. The message_gateway is responsible for logging any messages
33 // which didn't get delivered.
Austin Schuh6f3babe2020-01-26 20:34:50 -080034 kLogMessageAndDeliveryTime,
35 // The message originated on the other node and should be logged on this node.
36 kLogRemoteMessage
Austin Schuha36c8902019-12-30 18:07:15 -080037};
38
Austin Schuha36c8902019-12-30 18:07:15 -080039// This class manages efficiently writing a sequence of detached buffers to a
40// file. It queues them up and batches the write operation.
41class DetachedBufferWriter {
42 public:
43 DetachedBufferWriter(std::string_view filename);
Austin Schuh2f8fd752020-09-01 22:38:28 -070044 DetachedBufferWriter(DetachedBufferWriter &&other);
45 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
46
Austin Schuha36c8902019-12-30 18:07:15 -080047 ~DetachedBufferWriter();
48
Austin Schuh2f8fd752020-09-01 22:38:28 -070049 DetachedBufferWriter &operator=(DetachedBufferWriter &&other);
Brian Silverman98360e22020-04-28 16:51:20 -070050 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
51
Austin Schuh6f3babe2020-01-26 20:34:50 -080052 std::string_view filename() const { return filename_; }
53
Austin Schuh2f8fd752020-09-01 22:38:28 -070054 // Rewrites a location in a file (relative to the start) to have new data in
55 // it. The main use case is updating start times after a log file starts.
56 void RewriteLocation(off64_t offset, absl::Span<const uint8_t> data);
57
Austin Schuha36c8902019-12-30 18:07:15 -080058 // TODO(austin): Snappy compress the log file if it ends with .snappy!
59
60 // Queues up a finished FlatBufferBuilder to be written. Steals the detached
61 // buffer from it.
62 void QueueSizedFlatbuffer(flatbuffers::FlatBufferBuilder *fbb);
63 // Queues up a detached buffer directly.
64 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer);
Austin Schuhde031b72020-01-10 19:34:41 -080065 // Writes a Span. This is not terribly optimized right now.
66 void WriteSizedFlatbuffer(absl::Span<const uint8_t> span);
Austin Schuha36c8902019-12-30 18:07:15 -080067
68 // Triggers data to be provided to the kernel and written.
69 void Flush();
70
Brian Silverman98360e22020-04-28 16:51:20 -070071 // Returns the number of bytes written.
72 size_t written_size() const { return written_size_; }
73
74 // Returns the number of bytes written or currently queued.
75 size_t total_size() const { return written_size_ + queued_size_; }
76
Austin Schuha36c8902019-12-30 18:07:15 -080077 private:
Austin Schuh2f8fd752020-09-01 22:38:28 -070078 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -080079
Austin Schuha36c8902019-12-30 18:07:15 -080080 int fd_ = -1;
81
82 // Size of all the data in the queue.
83 size_t queued_size_ = 0;
Brian Silverman98360e22020-04-28 16:51:20 -070084 size_t written_size_ = 0;
Austin Schuha36c8902019-12-30 18:07:15 -080085
86 // List of buffers to flush.
87 std::vector<flatbuffers::DetachedBuffer> queue_;
88 // List of iovecs to use with writev. This is a member variable to avoid
89 // churn.
90 std::vector<struct iovec> iovec_;
91};
92
93// Packes a message pointed to by the context into a MessageHeader.
94flatbuffers::Offset<MessageHeader> PackMessage(
95 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
96 int channel_index, LogType log_type);
97
Austin Schuh6f3babe2020-01-26 20:34:50 -080098FlatbufferVector<LogFileHeader> ReadHeader(std::string_view filename);
99
Austin Schuh05b70472020-01-01 17:11:17 -0800100// Class to read chunks out of a log file.
101class SpanReader {
102 public:
103 SpanReader(std::string_view filename);
Austin Schuha36c8902019-12-30 18:07:15 -0800104
Austin Schuh05b70472020-01-01 17:11:17 -0800105 ~SpanReader() { close(fd_); }
106
Austin Schuh6f3babe2020-01-26 20:34:50 -0800107 std::string_view filename() const { return filename_; }
108
Austin Schuh05b70472020-01-01 17:11:17 -0800109 // Returns a span with the data for a message from the log file, excluding
110 // the size.
111 absl::Span<const uint8_t> ReadMessage();
112
113 // Returns true if there is a full message available in the buffer, or if we
114 // will have to read more data from disk.
115 bool MessageAvailable();
116
117 private:
118 // TODO(austin): Optimization:
119 // Allocate the 256k blocks like we do today. But, refcount them with
120 // shared_ptr pointed to by the messageheader that is returned. This avoids
121 // the copy. Need to do more benchmarking.
122
123 // Reads a chunk of data into data_. Returns false if no data was read.
124 bool ReadBlock();
125
Austin Schuh6f3babe2020-01-26 20:34:50 -0800126 const std::string filename_;
127
Austin Schuh05b70472020-01-01 17:11:17 -0800128 // File descriptor for the log file.
129 int fd_ = -1;
130
131 // Allocator which doesn't zero initialize memory.
132 template <typename T>
133 struct DefaultInitAllocator {
134 typedef T value_type;
135
136 template <typename U>
137 void construct(U *p) {
138 ::new (static_cast<void *>(p)) U;
139 }
140
141 template <typename U, typename... Args>
142 void construct(U *p, Args &&... args) {
143 ::new (static_cast<void *>(p)) U(std::forward<Args>(args)...);
144 }
145
146 T *allocate(std::size_t n) {
147 return reinterpret_cast<T *>(::operator new(sizeof(T) * n));
148 }
149
150 template <typename U>
151 void deallocate(U *p, std::size_t /*n*/) {
152 ::operator delete(static_cast<void *>(p));
153 }
154 };
155
156 // Vector to read into. This uses an allocator which doesn't zero
157 // initialize the memory.
158 std::vector<uint8_t, DefaultInitAllocator<uint8_t>> data_;
159
160 // Amount of data consumed already in data_.
161 size_t consumed_data_ = 0;
162
163 // Cached bit for if we have reached the end of the file. Otherwise we will
164 // hammer on the kernel asking for more data each time we send.
165 bool end_of_file_ = false;
166};
167
168// Class which handles reading the header and messages from the log file. This
169// handles any per-file state left before merging below.
170class MessageReader {
171 public:
172 MessageReader(std::string_view filename);
173
Austin Schuh6f3babe2020-01-26 20:34:50 -0800174 std::string_view filename() const { return span_reader_.filename(); }
175
Austin Schuh05b70472020-01-01 17:11:17 -0800176 // Returns the header from the log file.
177 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700178 return &raw_log_file_header_.message();
179 }
180
181 // Returns the raw data of the header from the log file.
182 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
183 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800184 }
185
186 // Returns the minimum maount of data needed to queue up for sorting before
187 // ware guarenteed to not see data out of order.
188 std::chrono::nanoseconds max_out_of_order_duration() const {
189 return max_out_of_order_duration_;
190 }
191
Austin Schuhcde938c2020-02-02 17:30:07 -0800192 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800193 monotonic_clock::time_point newest_timestamp() const {
194 return newest_timestamp_;
195 }
196
197 // Returns the next message if there is one.
198 std::optional<FlatbufferVector<MessageHeader>> ReadMessage();
199
200 // The time at which we need to read another chunk from the logfile.
201 monotonic_clock::time_point queue_data_time() const {
202 return newest_timestamp() - max_out_of_order_duration();
203 }
204
205 private:
206 // Log chunk reader.
207 SpanReader span_reader_;
208
Austin Schuh97789fc2020-08-01 14:42:45 -0700209 // Vector holding the raw data for the log file header.
210 FlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800211
212 // Minimum amount of data to queue up for sorting before we are guarenteed
213 // to not see data out of order.
214 std::chrono::nanoseconds max_out_of_order_duration_;
215
216 // Timestamp of the newest message in a channel queue.
217 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
218};
219
Austin Schuh6f3babe2020-01-26 20:34:50 -0800220class TimestampMerger;
Austin Schuh05b70472020-01-01 17:11:17 -0800221
Austin Schuh6f3babe2020-01-26 20:34:50 -0800222// A design requirement is that the relevant data for a channel is not more than
223// max_out_of_order_duration out of order. We approach sorting in layers.
224//
225// 1) Split each (maybe chunked) log file into one queue per channel. Read this
226// log file looking for data pertaining to a specific node.
227// (SplitMessageReader)
228// 2) Merge all the data per channel from the different log files into a sorted
229// list of timestamps and messages. (TimestampMerger)
230// 3) Combine the timestamps and messages. (TimestampMerger)
231// 4) Merge all the channels to produce the next message on a node.
232// (ChannelMerger)
233// 5) Duplicate this entire stack per node.
234
235// This class splits messages and timestamps up into a queue per channel, and
236// handles reading data from multiple chunks.
237class SplitMessageReader {
238 public:
239 SplitMessageReader(const std::vector<std::string> &filenames);
240
241 // Sets the TimestampMerger that gets notified for each channel. The node
242 // that the TimestampMerger is merging as needs to be passed in.
243 void SetTimestampMerger(TimestampMerger *timestamp_merger, int channel,
244 const Node *target_node);
245
Austin Schuh2f8fd752020-09-01 22:38:28 -0700246 // Returns the (timestamp, queue_index, message_header) for the oldest message
247 // in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800248 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
249 oldest_message(int channel) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800250 return channels_[channel].data.front_timestamp();
251 }
252
Austin Schuh2f8fd752020-09-01 22:38:28 -0700253 // Returns the (timestamp, queue_index, message_header) for the oldest
254 // delivery time in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800255 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
256 oldest_message(int channel, int destination_node) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800257 return channels_[channel].timestamps[destination_node].front_timestamp();
258 }
259
260 // Returns the timestamp, queue_index, and message for the oldest data on a
261 // channel. Requeues data as needed.
262 std::tuple<monotonic_clock::time_point, uint32_t,
263 FlatbufferVector<MessageHeader>>
264 PopOldest(int channel_index);
265
266 // Returns the timestamp, queue_index, and message for the oldest timestamp on
267 // a channel delivered to a node. Requeues data as needed.
268 std::tuple<monotonic_clock::time_point, uint32_t,
269 FlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -0700270 PopOldestTimestamp(int channel, int node_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800271
272 // Returns the header for the log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800273 const LogFileHeader *log_file_header() const {
Austin Schuhfa895892020-01-07 20:07:41 -0800274 return &log_file_header_.message();
Austin Schuh05b70472020-01-01 17:11:17 -0800275 }
276
Austin Schuh97789fc2020-08-01 14:42:45 -0700277 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
278 return log_file_header_;
279 }
280
Austin Schuh6f3babe2020-01-26 20:34:50 -0800281 // Returns the starting time for this set of log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800282 monotonic_clock::time_point monotonic_start_time() {
283 return monotonic_clock::time_point(
284 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
285 }
286 realtime_clock::time_point realtime_start_time() {
287 return realtime_clock::time_point(
288 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
289 }
290
Austin Schuh6f3babe2020-01-26 20:34:50 -0800291 // Returns the configuration from the log file header.
292 const Configuration *configuration() const {
293 return log_file_header()->configuration();
294 }
295
Austin Schuh05b70472020-01-01 17:11:17 -0800296 // Returns the node who's point of view this log file is from. Make sure this
297 // is a pointer in the configuration() nodes list so it can be consumed
298 // elsewhere.
299 const Node *node() const {
300 if (configuration()->has_nodes()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800301 return configuration::GetNodeOrDie(configuration(),
302 log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800303 } else {
304 CHECK(!log_file_header()->has_node());
305 return nullptr;
306 }
307 }
308
Austin Schuh6f3babe2020-01-26 20:34:50 -0800309 // Returns the timestamp of the newest message read from the log file, and the
310 // timestamp that we need to re-queue data.
311 monotonic_clock::time_point newest_timestamp() const {
Austin Schuhcde938c2020-02-02 17:30:07 -0800312 return newest_timestamp_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800313 }
314
Austin Schuhcde938c2020-02-02 17:30:07 -0800315 // Returns the next time to trigger a requeue.
316 monotonic_clock::time_point time_to_queue() const { return time_to_queue_; }
317
318 // Returns the minimum amount of data needed to queue up for sorting before
319 // ware guarenteed to not see data out of order.
320 std::chrono::nanoseconds max_out_of_order_duration() const {
321 return message_reader_->max_out_of_order_duration();
322 }
323
324 std::string_view filename() const { return message_reader_->filename(); }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800325
326 // Adds more messages to the sorted list. This reads enough data such that
327 // oldest_message_time can be replayed safely. Returns false if the log file
328 // has all been read.
329 bool QueueMessages(monotonic_clock::time_point oldest_message_time);
Austin Schuh05b70472020-01-01 17:11:17 -0800330
Austin Schuhcde938c2020-02-02 17:30:07 -0800331 // Returns debug strings for a channel, and timestamps for a node.
332 std::string DebugString(int channel) const;
333 std::string DebugString(int channel, int node_index) const;
334
Austin Schuh8bd96322020-02-13 21:18:22 -0800335 // Returns true if all the messages have been queued from the last log file in
336 // the list of log files chunks.
337 bool at_end() const { return at_end_; }
338
Austin Schuh05b70472020-01-01 17:11:17 -0800339 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800340 // TODO(austin): Need to copy or refcount the message instead of running
341 // multiple copies of the reader. Or maybe have a "as_node" index and hide it
342 // inside.
343
Austin Schuhfa895892020-01-07 20:07:41 -0800344 // Moves to the next log file in the list.
345 bool NextLogFile();
346
Austin Schuh6f3babe2020-01-26 20:34:50 -0800347 // Filenames of the log files.
348 std::vector<std::string> filenames_;
349 // And the index of the next file to open.
350 size_t next_filename_index_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800351
Austin Schuhee711052020-08-24 16:06:09 -0700352 // Node we are reading as.
353 const Node *target_node_ = nullptr;
354
Austin Schuh6f3babe2020-01-26 20:34:50 -0800355 // Log file header to report. This is a copy.
Austin Schuh97789fc2020-08-01 14:42:45 -0700356 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800357 // Current log file being read.
358 std::unique_ptr<MessageReader> message_reader_;
Austin Schuh05b70472020-01-01 17:11:17 -0800359
360 // Datastructure to hold the list of messages, cached timestamp for the
361 // oldest message, and sender to send with.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800362 struct MessageHeaderQueue {
363 // If true, this is a timestamp queue.
364 bool timestamps = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800365
Austin Schuh6f3babe2020-01-26 20:34:50 -0800366 // Returns a reference to the the oldest message.
367 FlatbufferVector<MessageHeader> &front() {
368 CHECK_GT(data_.size(), 0u);
369 return data_.front();
Austin Schuh05b70472020-01-01 17:11:17 -0800370 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800371
Austin Schuhcde938c2020-02-02 17:30:07 -0800372 // Adds a message to the back of the queue. Returns true if it was actually
373 // emplaced.
374 bool emplace_back(FlatbufferVector<MessageHeader> &&msg);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800375
376 // Drops the front message. Invalidates the front() reference.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700377 void PopFront();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800378
379 // The size of the queue.
380 size_t size() { return data_.size(); }
381
Austin Schuhcde938c2020-02-02 17:30:07 -0800382 // Returns a debug string with info about each message in the queue.
383 std::string DebugString() const;
384
Austin Schuh2f8fd752020-09-01 22:38:28 -0700385 // Returns the (timestamp, queue_index, message_header) for the oldest
386 // message.
Austin Schuhcde938c2020-02-02 17:30:07 -0800387 const std::tuple<monotonic_clock::time_point, uint32_t,
388 const MessageHeader *>
389 front_timestamp() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700390 const MessageHeader &message = front().message();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800391 return std::make_tuple(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700392 monotonic_clock::time_point(
393 std::chrono::nanoseconds(message.monotonic_sent_time())),
394 message.queue_index(), &message);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800395 }
396
397 // Pointer to the timestamp merger for this queue if available.
398 TimestampMerger *timestamp_merger = nullptr;
399 // Pointer to the reader which feeds this queue.
400 SplitMessageReader *split_reader = nullptr;
401
402 private:
403 // The data.
404 std::deque<FlatbufferVector<MessageHeader>> data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800405 };
406
Austin Schuh6f3babe2020-01-26 20:34:50 -0800407 // All the queues needed for a channel. There isn't going to be data in all
408 // of these.
409 struct ChannelData {
410 // The data queue for the channel.
411 MessageHeaderQueue data;
412 // Queues for timestamps for each node.
413 std::vector<MessageHeaderQueue> timestamps;
414 };
Austin Schuhfa895892020-01-07 20:07:41 -0800415
Austin Schuh6f3babe2020-01-26 20:34:50 -0800416 // Data for all the channels.
Austin Schuh05b70472020-01-01 17:11:17 -0800417 std::vector<ChannelData> channels_;
418
Austin Schuh6f3babe2020-01-26 20:34:50 -0800419 // Once we know the node that this SplitMessageReader will be writing as,
420 // there will be only one MessageHeaderQueue that a specific channel matches.
421 // Precompute this here for efficiency.
422 std::vector<MessageHeaderQueue *> channels_to_write_;
423
Austin Schuhcde938c2020-02-02 17:30:07 -0800424 monotonic_clock::time_point time_to_queue_ = monotonic_clock::min_time;
425
426 // Latches true when we hit the end of the last log file and there is no sense
427 // poking it further.
428 bool at_end_ = false;
429
430 // Timestamp of the newest message that was read and actually queued. We want
431 // to track this independently from the log file because we need the
432 // timestamps here to be timestamps of messages that are queued.
433 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800434};
435
436class ChannelMerger;
437
438// Sorts channels (and timestamps) from multiple log files for a single channel.
439class TimestampMerger {
440 public:
441 TimestampMerger(const Configuration *configuration,
442 std::vector<SplitMessageReader *> split_message_readers,
443 int channel_index, const Node *target_node,
444 ChannelMerger *channel_merger);
445
446 // Metadata used to schedule the message.
447 struct DeliveryTimestamp {
448 monotonic_clock::time_point monotonic_event_time =
449 monotonic_clock::min_time;
450 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
451
452 monotonic_clock::time_point monotonic_remote_time =
453 monotonic_clock::min_time;
454 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
455 uint32_t remote_queue_index = 0xffffffff;
456 };
457
458 // Pushes SplitMessageReader onto the timestamp heap. This should only be
459 // called when timestamps are placed in the channel this class is merging for
460 // the reader.
461 void UpdateTimestamp(
462 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800463 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
464 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800465 PushTimestampHeap(oldest_message_time, split_message_reader);
466 }
467 // Pushes SplitMessageReader onto the message heap. This should only be
468 // called when data is placed in the channel this class is merging for the
469 // reader.
470 void Update(
471 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800472 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
473 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800474 PushMessageHeap(oldest_message_time, split_message_reader);
475 }
476
Austin Schuhcde938c2020-02-02 17:30:07 -0800477 // Returns the oldest combined timestamp and data for this channel. If there
478 // isn't a matching piece of data, returns only the timestamp with no data.
479 // The caller can determine what the appropriate action is to recover.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800480 std::tuple<DeliveryTimestamp, FlatbufferVector<MessageHeader>> PopOldest();
481
482 // Tracks if the channel merger has pushed this onto it's heap or not.
483 bool pushed() { return pushed_; }
484 // Sets if this has been pushed to the channel merger heap. Should only be
485 // called by the channel merger.
486 void set_pushed(bool pushed) { pushed_ = pushed; }
487
Austin Schuhcde938c2020-02-02 17:30:07 -0800488 // Returns a debug string with the heaps printed out.
489 std::string DebugString() const;
490
Austin Schuh8bd96322020-02-13 21:18:22 -0800491 // Returns true if we have timestamps.
492 bool has_timestamps() const { return has_timestamps_; }
493
494 // Records that one of the log files ran out of data. This should only be
495 // called by a SplitMessageReader.
496 void NoticeAtEnd();
497
Austin Schuh2f8fd752020-09-01 22:38:28 -0700498 aos::monotonic_clock::time_point channel_merger_time() {
499 if (has_timestamps_) {
500 return std::get<0>(timestamp_heap_[0]);
501 } else {
502 return std::get<0>(message_heap_[0]);
503 }
504 }
505
Austin Schuh6f3babe2020-01-26 20:34:50 -0800506 private:
507 // Pushes messages and timestamps to the corresponding heaps.
508 void PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800509 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
510 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800511 SplitMessageReader *split_message_reader);
512 void PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800513 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
514 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800515 SplitMessageReader *split_message_reader);
516
517 // Pops a message from the message heap. This automatically triggers the
518 // split message reader to re-fetch any new data.
519 std::tuple<monotonic_clock::time_point, uint32_t,
520 FlatbufferVector<MessageHeader>>
521 PopMessageHeap();
Austin Schuhcde938c2020-02-02 17:30:07 -0800522
523 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
524 oldest_message() const;
525 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
526 oldest_timestamp() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800527 // Pops a message from the timestamp heap. This automatically triggers the
528 // split message reader to re-fetch any new data.
529 std::tuple<monotonic_clock::time_point, uint32_t,
530 FlatbufferVector<MessageHeader>>
531 PopTimestampHeap();
532
533 const Configuration *configuration_;
534
535 // If true, this is a forwarded channel and timestamps should be matched.
536 bool has_timestamps_ = false;
537
538 // Tracks if the ChannelMerger has pushed this onto it's queue.
539 bool pushed_ = false;
540
541 // The split message readers used for source data.
542 std::vector<SplitMessageReader *> split_message_readers_;
543
544 // The channel to merge.
545 int channel_index_;
546
547 // Our node.
548 int node_index_;
549
550 // Heaps for messages and timestamps.
551 std::vector<
552 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
553 message_heap_;
554 std::vector<
555 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
556 timestamp_heap_;
557
558 // Parent channel merger.
559 ChannelMerger *channel_merger_;
560};
561
562// This class handles constructing all the split message readers, channel
563// mergers, and combining the results.
564class ChannelMerger {
565 public:
566 // Builds a ChannelMerger around a set of log files. These are of the format:
567 // {
568 // {log1_part0, log1_part1, ...},
569 // {log2}
570 // }
571 // The inner vector is a list of log file chunks which form up a log file.
572 // The outer vector is a list of log files with subsets of the messages, or
573 // messages from different nodes.
574 ChannelMerger(const std::vector<std::vector<std::string>> &filenames);
575
576 // Returns the nodes that we know how to merge.
577 const std::vector<const Node *> nodes() const;
578 // Sets the node that we will return messages as. Returns true if the node
579 // has log files and will produce data. This can only be called once, and
580 // will likely corrupt state if called a second time.
581 bool SetNode(const Node *target_node);
582
583 // Everything else needs the node set before it works.
584
585 // Returns a timestamp for the oldest message in this group of logfiles.
Austin Schuh858c9f32020-08-31 16:56:12 -0700586 monotonic_clock::time_point OldestMessageTime() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800587 // Pops the oldest message.
588 std::tuple<TimestampMerger::DeliveryTimestamp, int,
589 FlatbufferVector<MessageHeader>>
590 PopOldest();
591
592 // Returns the config for this set of log files.
593 const Configuration *configuration() const {
594 return log_file_header()->configuration();
595 }
596
597 const LogFileHeader *log_file_header() const {
598 return &log_file_header_.message();
599 }
600
601 // Returns the start times for the configured node's log files.
Austin Schuhcde938c2020-02-02 17:30:07 -0800602 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800603 return monotonic_clock::time_point(
604 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
605 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800606 realtime_clock::time_point realtime_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800607 return realtime_clock::time_point(
608 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
609 }
610
611 // Returns the node set by SetNode above.
612 const Node *node() const { return node_; }
613
614 // Called by the TimestampMerger when new data is available with the provided
615 // timestamp and channel_index.
616 void Update(monotonic_clock::time_point timestamp, int channel_index) {
617 PushChannelHeap(timestamp, channel_index);
618 }
619
Austin Schuhcde938c2020-02-02 17:30:07 -0800620 // Returns a debug string with all the heaps in it. Generally only useful for
621 // debugging what went wrong.
622 std::string DebugString() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800623
Austin Schuh8bd96322020-02-13 21:18:22 -0800624 // Returns true if one of the log files has finished reading everything. When
625 // log file chunks are involved, this means that the last chunk in a log file
626 // has been read. It is acceptable to be missing data at this point in time.
627 bool at_end() const { return at_end_; }
628
629 // Marks that one of the log files is at the end. This should only be called
630 // by timestamp mergers.
631 void NoticeAtEnd() { at_end_ = true; }
632
Austin Schuhcde938c2020-02-02 17:30:07 -0800633 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800634 // Pushes the timestamp for new data on the provided channel.
635 void PushChannelHeap(monotonic_clock::time_point timestamp,
636 int channel_index);
637
Austin Schuh2f8fd752020-09-01 22:38:28 -0700638 // CHECKs that channel_heap_ and timestamp_heap_ are valid heaps.
639 void VerifyHeaps();
640
Austin Schuh6f3babe2020-01-26 20:34:50 -0800641 // All the message readers.
642 std::vector<std::unique_ptr<SplitMessageReader>> split_message_readers_;
643
644 // The log header we are claiming to be.
Austin Schuh97789fc2020-08-01 14:42:45 -0700645 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800646
647 // The timestamp mergers which combine data from the split message readers.
648 std::vector<TimestampMerger> timestamp_mergers_;
649
650 // A heap of the channel readers and timestamps for the oldest data in each.
Austin Schuh05b70472020-01-01 17:11:17 -0800651 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800652 // A heap of just the timestamp channel readers and timestamps for the oldest
653 // data in each.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700654 // TODO(austin): I think this is no longer used and can be removed (!)
Austin Schuh8bd96322020-02-13 21:18:22 -0800655 std::vector<std::pair<monotonic_clock::time_point, int>> timestamp_heap_;
Austin Schuh05b70472020-01-01 17:11:17 -0800656
Austin Schuh6f3babe2020-01-26 20:34:50 -0800657 // Configured node.
658 const Node *node_;
659
Austin Schuh8bd96322020-02-13 21:18:22 -0800660 bool at_end_ = false;
661
Austin Schuh6f3babe2020-01-26 20:34:50 -0800662 // Cached copy of the list of nodes.
663 std::vector<const Node *> nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700664
665 // Last time popped. Used to detect events being returned out of order.
666 monotonic_clock::time_point last_popped_time_ = monotonic_clock::min_time;
Austin Schuh05b70472020-01-01 17:11:17 -0800667};
Austin Schuha36c8902019-12-30 18:07:15 -0800668
Austin Schuhee711052020-08-24 16:06:09 -0700669// Returns the node name with a trailing space, or an empty string if we are on
670// a single node.
671std::string MaybeNodeName(const Node *);
672
Austin Schuha36c8902019-12-30 18:07:15 -0800673} // namespace logger
674} // namespace aos
675
676#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_