blob: b1a2d67f67e1530f2d123a49b9b60a85382138c2 [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);
44 ~DetachedBufferWriter();
45
Brian Silverman98360e22020-04-28 16:51:20 -070046 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
47 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
48
Austin Schuh6f3babe2020-01-26 20:34:50 -080049 std::string_view filename() const { return filename_; }
50
Austin Schuha36c8902019-12-30 18:07:15 -080051 // TODO(austin): Snappy compress the log file if it ends with .snappy!
52
53 // Queues up a finished FlatBufferBuilder to be written. Steals the detached
54 // buffer from it.
55 void QueueSizedFlatbuffer(flatbuffers::FlatBufferBuilder *fbb);
56 // Queues up a detached buffer directly.
57 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer);
Austin Schuhde031b72020-01-10 19:34:41 -080058 // Writes a Span. This is not terribly optimized right now.
59 void WriteSizedFlatbuffer(absl::Span<const uint8_t> span);
Austin Schuha36c8902019-12-30 18:07:15 -080060
61 // Triggers data to be provided to the kernel and written.
62 void Flush();
63
Brian Silverman98360e22020-04-28 16:51:20 -070064 // Returns the number of bytes written.
65 size_t written_size() const { return written_size_; }
66
67 // Returns the number of bytes written or currently queued.
68 size_t total_size() const { return written_size_ + queued_size_; }
69
Austin Schuha36c8902019-12-30 18:07:15 -080070 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -080071 const std::string filename_;
72
Austin Schuha36c8902019-12-30 18:07:15 -080073 int fd_ = -1;
74
75 // Size of all the data in the queue.
76 size_t queued_size_ = 0;
Brian Silverman98360e22020-04-28 16:51:20 -070077 size_t written_size_ = 0;
Austin Schuha36c8902019-12-30 18:07:15 -080078
79 // List of buffers to flush.
80 std::vector<flatbuffers::DetachedBuffer> queue_;
81 // List of iovecs to use with writev. This is a member variable to avoid
82 // churn.
83 std::vector<struct iovec> iovec_;
84};
85
86// Packes a message pointed to by the context into a MessageHeader.
87flatbuffers::Offset<MessageHeader> PackMessage(
88 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
89 int channel_index, LogType log_type);
90
Austin Schuh6f3babe2020-01-26 20:34:50 -080091FlatbufferVector<LogFileHeader> ReadHeader(std::string_view filename);
92
Austin Schuh05b70472020-01-01 17:11:17 -080093// Class to read chunks out of a log file.
94class SpanReader {
95 public:
96 SpanReader(std::string_view filename);
Austin Schuha36c8902019-12-30 18:07:15 -080097
Austin Schuh05b70472020-01-01 17:11:17 -080098 ~SpanReader() { close(fd_); }
99
Austin Schuh6f3babe2020-01-26 20:34:50 -0800100 std::string_view filename() const { return filename_; }
101
Austin Schuh05b70472020-01-01 17:11:17 -0800102 // Returns a span with the data for a message from the log file, excluding
103 // the size.
104 absl::Span<const uint8_t> ReadMessage();
105
106 // Returns true if there is a full message available in the buffer, or if we
107 // will have to read more data from disk.
108 bool MessageAvailable();
109
110 private:
111 // TODO(austin): Optimization:
112 // Allocate the 256k blocks like we do today. But, refcount them with
113 // shared_ptr pointed to by the messageheader that is returned. This avoids
114 // the copy. Need to do more benchmarking.
115
116 // Reads a chunk of data into data_. Returns false if no data was read.
117 bool ReadBlock();
118
Austin Schuh6f3babe2020-01-26 20:34:50 -0800119 const std::string filename_;
120
Austin Schuh05b70472020-01-01 17:11:17 -0800121 // File descriptor for the log file.
122 int fd_ = -1;
123
124 // Allocator which doesn't zero initialize memory.
125 template <typename T>
126 struct DefaultInitAllocator {
127 typedef T value_type;
128
129 template <typename U>
130 void construct(U *p) {
131 ::new (static_cast<void *>(p)) U;
132 }
133
134 template <typename U, typename... Args>
135 void construct(U *p, Args &&... args) {
136 ::new (static_cast<void *>(p)) U(std::forward<Args>(args)...);
137 }
138
139 T *allocate(std::size_t n) {
140 return reinterpret_cast<T *>(::operator new(sizeof(T) * n));
141 }
142
143 template <typename U>
144 void deallocate(U *p, std::size_t /*n*/) {
145 ::operator delete(static_cast<void *>(p));
146 }
147 };
148
149 // Vector to read into. This uses an allocator which doesn't zero
150 // initialize the memory.
151 std::vector<uint8_t, DefaultInitAllocator<uint8_t>> data_;
152
153 // Amount of data consumed already in data_.
154 size_t consumed_data_ = 0;
155
156 // Cached bit for if we have reached the end of the file. Otherwise we will
157 // hammer on the kernel asking for more data each time we send.
158 bool end_of_file_ = false;
159};
160
161// Class which handles reading the header and messages from the log file. This
162// handles any per-file state left before merging below.
163class MessageReader {
164 public:
165 MessageReader(std::string_view filename);
166
Austin Schuh6f3babe2020-01-26 20:34:50 -0800167 std::string_view filename() const { return span_reader_.filename(); }
168
Austin Schuh05b70472020-01-01 17:11:17 -0800169 // Returns the header from the log file.
170 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700171 return &raw_log_file_header_.message();
172 }
173
174 // Returns the raw data of the header from the log file.
175 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
176 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800177 }
178
179 // Returns the minimum maount of data needed to queue up for sorting before
180 // ware guarenteed to not see data out of order.
181 std::chrono::nanoseconds max_out_of_order_duration() const {
182 return max_out_of_order_duration_;
183 }
184
Austin Schuhcde938c2020-02-02 17:30:07 -0800185 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800186 monotonic_clock::time_point newest_timestamp() const {
187 return newest_timestamp_;
188 }
189
190 // Returns the next message if there is one.
191 std::optional<FlatbufferVector<MessageHeader>> ReadMessage();
192
193 // The time at which we need to read another chunk from the logfile.
194 monotonic_clock::time_point queue_data_time() const {
195 return newest_timestamp() - max_out_of_order_duration();
196 }
197
198 private:
199 // Log chunk reader.
200 SpanReader span_reader_;
201
Austin Schuh97789fc2020-08-01 14:42:45 -0700202 // Vector holding the raw data for the log file header.
203 FlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800204
205 // Minimum amount of data to queue up for sorting before we are guarenteed
206 // to not see data out of order.
207 std::chrono::nanoseconds max_out_of_order_duration_;
208
209 // Timestamp of the newest message in a channel queue.
210 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
211};
212
Austin Schuh6f3babe2020-01-26 20:34:50 -0800213class TimestampMerger;
Austin Schuh05b70472020-01-01 17:11:17 -0800214
Austin Schuh6f3babe2020-01-26 20:34:50 -0800215// A design requirement is that the relevant data for a channel is not more than
216// max_out_of_order_duration out of order. We approach sorting in layers.
217//
218// 1) Split each (maybe chunked) log file into one queue per channel. Read this
219// log file looking for data pertaining to a specific node.
220// (SplitMessageReader)
221// 2) Merge all the data per channel from the different log files into a sorted
222// list of timestamps and messages. (TimestampMerger)
223// 3) Combine the timestamps and messages. (TimestampMerger)
224// 4) Merge all the channels to produce the next message on a node.
225// (ChannelMerger)
226// 5) Duplicate this entire stack per node.
227
228// This class splits messages and timestamps up into a queue per channel, and
229// handles reading data from multiple chunks.
230class SplitMessageReader {
231 public:
232 SplitMessageReader(const std::vector<std::string> &filenames);
233
234 // Sets the TimestampMerger that gets notified for each channel. The node
235 // that the TimestampMerger is merging as needs to be passed in.
236 void SetTimestampMerger(TimestampMerger *timestamp_merger, int channel,
237 const Node *target_node);
238
239 // Returns the (timestamp, queue_idex) for the oldest message in a channel, or
240 // max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800241 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
242 oldest_message(int channel) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800243 return channels_[channel].data.front_timestamp();
244 }
245
246 // Returns the (timestamp, queue_index) for the oldest delivery time in a
247 // 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, int destination_node) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800250 return channels_[channel].timestamps[destination_node].front_timestamp();
251 }
252
253 // Returns the timestamp, queue_index, and message for the oldest data on a
254 // channel. Requeues data as needed.
255 std::tuple<monotonic_clock::time_point, uint32_t,
256 FlatbufferVector<MessageHeader>>
257 PopOldest(int channel_index);
258
259 // Returns the timestamp, queue_index, and message for the oldest timestamp on
260 // a channel delivered to a node. Requeues data as needed.
261 std::tuple<monotonic_clock::time_point, uint32_t,
262 FlatbufferVector<MessageHeader>>
263 PopOldest(int channel, int node_index);
264
265 // Returns the header for the log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800266 const LogFileHeader *log_file_header() const {
Austin Schuhfa895892020-01-07 20:07:41 -0800267 return &log_file_header_.message();
Austin Schuh05b70472020-01-01 17:11:17 -0800268 }
269
Austin Schuh97789fc2020-08-01 14:42:45 -0700270 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
271 return log_file_header_;
272 }
273
Austin Schuh6f3babe2020-01-26 20:34:50 -0800274 // Returns the starting time for this set of log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800275 monotonic_clock::time_point monotonic_start_time() {
276 return monotonic_clock::time_point(
277 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
278 }
279 realtime_clock::time_point realtime_start_time() {
280 return realtime_clock::time_point(
281 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
282 }
283
Austin Schuh6f3babe2020-01-26 20:34:50 -0800284 // Returns the configuration from the log file header.
285 const Configuration *configuration() const {
286 return log_file_header()->configuration();
287 }
288
Austin Schuh05b70472020-01-01 17:11:17 -0800289 // Returns the node who's point of view this log file is from. Make sure this
290 // is a pointer in the configuration() nodes list so it can be consumed
291 // elsewhere.
292 const Node *node() const {
293 if (configuration()->has_nodes()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800294 return configuration::GetNodeOrDie(configuration(),
295 log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800296 } else {
297 CHECK(!log_file_header()->has_node());
298 return nullptr;
299 }
300 }
301
Austin Schuh6f3babe2020-01-26 20:34:50 -0800302 // Returns the timestamp of the newest message read from the log file, and the
303 // timestamp that we need to re-queue data.
304 monotonic_clock::time_point newest_timestamp() const {
Austin Schuhcde938c2020-02-02 17:30:07 -0800305 return newest_timestamp_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800306 }
307
Austin Schuhcde938c2020-02-02 17:30:07 -0800308 // Returns the next time to trigger a requeue.
309 monotonic_clock::time_point time_to_queue() const { return time_to_queue_; }
310
311 // Returns the minimum amount of data needed to queue up for sorting before
312 // ware guarenteed to not see data out of order.
313 std::chrono::nanoseconds max_out_of_order_duration() const {
314 return message_reader_->max_out_of_order_duration();
315 }
316
317 std::string_view filename() const { return message_reader_->filename(); }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800318
319 // Adds more messages to the sorted list. This reads enough data such that
320 // oldest_message_time can be replayed safely. Returns false if the log file
321 // has all been read.
322 bool QueueMessages(monotonic_clock::time_point oldest_message_time);
Austin Schuh05b70472020-01-01 17:11:17 -0800323
Austin Schuhcde938c2020-02-02 17:30:07 -0800324 // Returns debug strings for a channel, and timestamps for a node.
325 std::string DebugString(int channel) const;
326 std::string DebugString(int channel, int node_index) const;
327
Austin Schuh8bd96322020-02-13 21:18:22 -0800328 // Returns true if all the messages have been queued from the last log file in
329 // the list of log files chunks.
330 bool at_end() const { return at_end_; }
331
Austin Schuh05b70472020-01-01 17:11:17 -0800332 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800333 // TODO(austin): Need to copy or refcount the message instead of running
334 // multiple copies of the reader. Or maybe have a "as_node" index and hide it
335 // inside.
336
Austin Schuhfa895892020-01-07 20:07:41 -0800337 // Moves to the next log file in the list.
338 bool NextLogFile();
339
Austin Schuh6f3babe2020-01-26 20:34:50 -0800340 // Filenames of the log files.
341 std::vector<std::string> filenames_;
342 // And the index of the next file to open.
343 size_t next_filename_index_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800344
Austin Schuh6f3babe2020-01-26 20:34:50 -0800345 // Log file header to report. This is a copy.
Austin Schuh97789fc2020-08-01 14:42:45 -0700346 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800347 // Current log file being read.
348 std::unique_ptr<MessageReader> message_reader_;
Austin Schuh05b70472020-01-01 17:11:17 -0800349
350 // Datastructure to hold the list of messages, cached timestamp for the
351 // oldest message, and sender to send with.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800352 struct MessageHeaderQueue {
353 // If true, this is a timestamp queue.
354 bool timestamps = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800355
Austin Schuh6f3babe2020-01-26 20:34:50 -0800356 // Returns a reference to the the oldest message.
357 FlatbufferVector<MessageHeader> &front() {
358 CHECK_GT(data_.size(), 0u);
359 return data_.front();
Austin Schuh05b70472020-01-01 17:11:17 -0800360 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800361
Austin Schuhcde938c2020-02-02 17:30:07 -0800362 // Adds a message to the back of the queue. Returns true if it was actually
363 // emplaced.
364 bool emplace_back(FlatbufferVector<MessageHeader> &&msg);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800365
366 // Drops the front message. Invalidates the front() reference.
367 void pop_front();
368
369 // The size of the queue.
370 size_t size() { return data_.size(); }
371
Austin Schuhcde938c2020-02-02 17:30:07 -0800372 // Returns a debug string with info about each message in the queue.
373 std::string DebugString() const;
374
Austin Schuh6f3babe2020-01-26 20:34:50 -0800375 // Returns the (timestamp, queue_index) for the oldest message.
Austin Schuhcde938c2020-02-02 17:30:07 -0800376 const std::tuple<monotonic_clock::time_point, uint32_t,
377 const MessageHeader *>
378 front_timestamp() {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800379 CHECK_GT(data_.size(), 0u);
380 return std::make_tuple(
381 monotonic_clock::time_point(std::chrono::nanoseconds(
382 front().message().monotonic_sent_time())),
Austin Schuhcde938c2020-02-02 17:30:07 -0800383 front().message().queue_index(), &front().message());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800384 }
385
386 // Pointer to the timestamp merger for this queue if available.
387 TimestampMerger *timestamp_merger = nullptr;
388 // Pointer to the reader which feeds this queue.
389 SplitMessageReader *split_reader = nullptr;
390
391 private:
392 // The data.
393 std::deque<FlatbufferVector<MessageHeader>> data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800394 };
395
Austin Schuh6f3babe2020-01-26 20:34:50 -0800396 // All the queues needed for a channel. There isn't going to be data in all
397 // of these.
398 struct ChannelData {
399 // The data queue for the channel.
400 MessageHeaderQueue data;
401 // Queues for timestamps for each node.
402 std::vector<MessageHeaderQueue> timestamps;
403 };
Austin Schuhfa895892020-01-07 20:07:41 -0800404
Austin Schuh6f3babe2020-01-26 20:34:50 -0800405 // Data for all the channels.
Austin Schuh05b70472020-01-01 17:11:17 -0800406 std::vector<ChannelData> channels_;
407
Austin Schuh6f3babe2020-01-26 20:34:50 -0800408 // Once we know the node that this SplitMessageReader will be writing as,
409 // there will be only one MessageHeaderQueue that a specific channel matches.
410 // Precompute this here for efficiency.
411 std::vector<MessageHeaderQueue *> channels_to_write_;
412
Austin Schuhcde938c2020-02-02 17:30:07 -0800413 monotonic_clock::time_point time_to_queue_ = monotonic_clock::min_time;
414
415 // Latches true when we hit the end of the last log file and there is no sense
416 // poking it further.
417 bool at_end_ = false;
418
419 // Timestamp of the newest message that was read and actually queued. We want
420 // to track this independently from the log file because we need the
421 // timestamps here to be timestamps of messages that are queued.
422 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800423};
424
425class ChannelMerger;
426
427// Sorts channels (and timestamps) from multiple log files for a single channel.
428class TimestampMerger {
429 public:
430 TimestampMerger(const Configuration *configuration,
431 std::vector<SplitMessageReader *> split_message_readers,
432 int channel_index, const Node *target_node,
433 ChannelMerger *channel_merger);
434
435 // Metadata used to schedule the message.
436 struct DeliveryTimestamp {
437 monotonic_clock::time_point monotonic_event_time =
438 monotonic_clock::min_time;
439 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
440
441 monotonic_clock::time_point monotonic_remote_time =
442 monotonic_clock::min_time;
443 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
444 uint32_t remote_queue_index = 0xffffffff;
445 };
446
447 // Pushes SplitMessageReader onto the timestamp heap. This should only be
448 // called when timestamps are placed in the channel this class is merging for
449 // the reader.
450 void UpdateTimestamp(
451 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800452 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
453 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800454 PushTimestampHeap(oldest_message_time, split_message_reader);
455 }
456 // Pushes SplitMessageReader onto the message heap. This should only be
457 // called when data is placed in the channel this class is merging for the
458 // reader.
459 void Update(
460 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800461 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
462 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800463 PushMessageHeap(oldest_message_time, split_message_reader);
464 }
465
Austin Schuhcde938c2020-02-02 17:30:07 -0800466 // Returns the oldest combined timestamp and data for this channel. If there
467 // isn't a matching piece of data, returns only the timestamp with no data.
468 // The caller can determine what the appropriate action is to recover.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800469 std::tuple<DeliveryTimestamp, FlatbufferVector<MessageHeader>> PopOldest();
470
Austin Schuh8bd96322020-02-13 21:18:22 -0800471 // Returns the oldest forwarding timestamp.
472 DeliveryTimestamp OldestTimestamp() const;
473
Austin Schuh6f3babe2020-01-26 20:34:50 -0800474 // Tracks if the channel merger has pushed this onto it's heap or not.
475 bool pushed() { return pushed_; }
476 // Sets if this has been pushed to the channel merger heap. Should only be
477 // called by the channel merger.
478 void set_pushed(bool pushed) { pushed_ = pushed; }
479
Austin Schuhcde938c2020-02-02 17:30:07 -0800480 // Returns a debug string with the heaps printed out.
481 std::string DebugString() const;
482
Austin Schuh8bd96322020-02-13 21:18:22 -0800483 // Returns true if we have timestamps.
484 bool has_timestamps() const { return has_timestamps_; }
485
486 // Records that one of the log files ran out of data. This should only be
487 // called by a SplitMessageReader.
488 void NoticeAtEnd();
489
Austin Schuh6f3babe2020-01-26 20:34:50 -0800490 private:
491 // Pushes messages and timestamps to the corresponding heaps.
492 void PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800493 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
494 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800495 SplitMessageReader *split_message_reader);
496 void PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800497 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
498 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800499 SplitMessageReader *split_message_reader);
500
501 // Pops a message from the message heap. This automatically triggers the
502 // split message reader to re-fetch any new data.
503 std::tuple<monotonic_clock::time_point, uint32_t,
504 FlatbufferVector<MessageHeader>>
505 PopMessageHeap();
Austin Schuhcde938c2020-02-02 17:30:07 -0800506
507 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
508 oldest_message() const;
509 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
510 oldest_timestamp() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800511 // Pops a message from the timestamp heap. This automatically triggers the
512 // split message reader to re-fetch any new data.
513 std::tuple<monotonic_clock::time_point, uint32_t,
514 FlatbufferVector<MessageHeader>>
515 PopTimestampHeap();
516
517 const Configuration *configuration_;
518
519 // If true, this is a forwarded channel and timestamps should be matched.
520 bool has_timestamps_ = false;
521
522 // Tracks if the ChannelMerger has pushed this onto it's queue.
523 bool pushed_ = false;
524
525 // The split message readers used for source data.
526 std::vector<SplitMessageReader *> split_message_readers_;
527
528 // The channel to merge.
529 int channel_index_;
530
531 // Our node.
532 int node_index_;
533
534 // Heaps for messages and timestamps.
535 std::vector<
536 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
537 message_heap_;
538 std::vector<
539 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
540 timestamp_heap_;
541
542 // Parent channel merger.
543 ChannelMerger *channel_merger_;
544};
545
546// This class handles constructing all the split message readers, channel
547// mergers, and combining the results.
548class ChannelMerger {
549 public:
550 // Builds a ChannelMerger around a set of log files. These are of the format:
551 // {
552 // {log1_part0, log1_part1, ...},
553 // {log2}
554 // }
555 // The inner vector is a list of log file chunks which form up a log file.
556 // The outer vector is a list of log files with subsets of the messages, or
557 // messages from different nodes.
558 ChannelMerger(const std::vector<std::vector<std::string>> &filenames);
559
560 // Returns the nodes that we know how to merge.
561 const std::vector<const Node *> nodes() const;
562 // Sets the node that we will return messages as. Returns true if the node
563 // has log files and will produce data. This can only be called once, and
564 // will likely corrupt state if called a second time.
565 bool SetNode(const Node *target_node);
566
567 // Everything else needs the node set before it works.
568
569 // Returns a timestamp for the oldest message in this group of logfiles.
570 monotonic_clock::time_point OldestMessage() const;
571 // Pops the oldest message.
572 std::tuple<TimestampMerger::DeliveryTimestamp, int,
573 FlatbufferVector<MessageHeader>>
574 PopOldest();
575
Austin Schuh8bd96322020-02-13 21:18:22 -0800576 // Returns the oldest timestamp in the timestamp heap.
577 TimestampMerger::DeliveryTimestamp OldestTimestamp() const;
578 // Returns the oldest timestamp in the timestamp heap for a specific channel.
579 TimestampMerger::DeliveryTimestamp OldestTimestampForChannel(
580 int channel) const;
581
Austin Schuh6f3babe2020-01-26 20:34:50 -0800582 // Returns the config for this set of log files.
583 const Configuration *configuration() const {
584 return log_file_header()->configuration();
585 }
586
587 const LogFileHeader *log_file_header() const {
588 return &log_file_header_.message();
589 }
590
591 // Returns the start times for the configured node's log files.
Austin Schuhcde938c2020-02-02 17:30:07 -0800592 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800593 return monotonic_clock::time_point(
594 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
595 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800596 realtime_clock::time_point realtime_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800597 return realtime_clock::time_point(
598 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
599 }
600
601 // Returns the node set by SetNode above.
602 const Node *node() const { return node_; }
603
604 // Called by the TimestampMerger when new data is available with the provided
605 // timestamp and channel_index.
606 void Update(monotonic_clock::time_point timestamp, int channel_index) {
607 PushChannelHeap(timestamp, channel_index);
608 }
609
Austin Schuhcde938c2020-02-02 17:30:07 -0800610 // Returns a debug string with all the heaps in it. Generally only useful for
611 // debugging what went wrong.
612 std::string DebugString() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800613
Austin Schuh8bd96322020-02-13 21:18:22 -0800614 // Returns true if one of the log files has finished reading everything. When
615 // log file chunks are involved, this means that the last chunk in a log file
616 // has been read. It is acceptable to be missing data at this point in time.
617 bool at_end() const { return at_end_; }
618
619 // Marks that one of the log files is at the end. This should only be called
620 // by timestamp mergers.
621 void NoticeAtEnd() { at_end_ = true; }
622
Austin Schuhcde938c2020-02-02 17:30:07 -0800623 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800624 // Pushes the timestamp for new data on the provided channel.
625 void PushChannelHeap(monotonic_clock::time_point timestamp,
626 int channel_index);
627
628 // All the message readers.
629 std::vector<std::unique_ptr<SplitMessageReader>> split_message_readers_;
630
631 // The log header we are claiming to be.
Austin Schuh97789fc2020-08-01 14:42:45 -0700632 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800633
634 // The timestamp mergers which combine data from the split message readers.
635 std::vector<TimestampMerger> timestamp_mergers_;
636
637 // A heap of the channel readers and timestamps for the oldest data in each.
Austin Schuh05b70472020-01-01 17:11:17 -0800638 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800639 // A heap of just the timestamp channel readers and timestamps for the oldest
640 // data in each.
641 std::vector<std::pair<monotonic_clock::time_point, int>> timestamp_heap_;
Austin Schuh05b70472020-01-01 17:11:17 -0800642
Austin Schuh6f3babe2020-01-26 20:34:50 -0800643 // Configured node.
644 const Node *node_;
645
Austin Schuh8bd96322020-02-13 21:18:22 -0800646 bool at_end_ = false;
647
Austin Schuh6f3babe2020-01-26 20:34:50 -0800648 // Cached copy of the list of nodes.
649 std::vector<const Node *> nodes_;
Austin Schuh05b70472020-01-01 17:11:17 -0800650};
Austin Schuha36c8902019-12-30 18:07:15 -0800651
652} // namespace logger
653} // namespace aos
654
655#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_